xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision 6e0414acac7fe81ff262fb9d3d83c0700fe9b695)
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/sunddi.h>
42 #include <sys/cmn_err.h>
43 #include <sys/debug.h>
44 #include <sys/kobj.h>
45 #include <sys/modctl.h>
46 #include <sys/atomic.h>
47 #include <sys/policy.h>
48 #include <sys/priv.h>
49 #include <sys/taskq.h>
50 
51 #include <sys/systm.h>
52 #include <sys/param.h>
53 #include <sys/kmem.h>
54 #include <sys/sdt.h>
55 #include <sys/socket.h>
56 #include <sys/vtrace.h>
57 #include <sys/isa_defs.h>
58 #include <sys/mac.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/optcom.h>
73 #include <inet/kstatcom.h>
74 
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip6.h>
77 #include <netinet/icmp6.h>
78 #include <netinet/sctp.h>
79 
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip6_asp.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/ip_multi.h>
87 #include <inet/ip_if.h>
88 #include <inet/ip_ire.h>
89 #include <inet/ip_ftable.h>
90 #include <inet/ip_rts.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <inet/rawip_impl.h>
122 #include <inet/rts_impl.h>
123 #include <sys/sunddi.h>
124 
125 #include <sys/tsol/label.h>
126 #include <sys/tsol/tnet.h>
127 
128 #include <rpc/pmap_prot.h>
129 #include <sys/squeue_impl.h>
130 
131 /*
132  * Values for squeue switch:
133  * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
134  * IP_SQUEUE_ENTER: SQ_PROCESS
135  * IP_SQUEUE_FILL: SQ_FILL
136  */
137 int ip_squeue_enter = 2;	/* Setable in /etc/system */
138 
139 int ip_squeue_flag;
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 /*
143  * Setable in /etc/system
144  */
145 int ip_poll_normal_ms = 100;
146 int ip_poll_normal_ticks = 0;
147 int ip_modclose_ackwait_ms = 3000;
148 
149 /*
150  * It would be nice to have these present only in DEBUG systems, but the
151  * current design of the global symbol checking logic requires them to be
152  * unconditionally present.
153  */
154 uint_t ip_thread_data;			/* TSD key for debug support */
155 krwlock_t ip_thread_rwlock;
156 list_t	ip_thread_list;
157 
158 /*
159  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
160  */
161 
162 struct listptr_s {
163 	mblk_t	*lp_head;	/* pointer to the head of the list */
164 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
165 };
166 
167 typedef struct listptr_s listptr_t;
168 
169 /*
170  * This is used by ip_snmp_get_mib2_ip_route_media and
171  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
172  */
173 typedef struct iproutedata_s {
174 	uint_t		ird_idx;
175 	listptr_t	ird_route;	/* ipRouteEntryTable */
176 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
177 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
178 } iproutedata_t;
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
199     uint8_t *laddrp, uint8_t *faddrp) = NULL;
200 
201 /*
202  * Hook function to generate cluster wide SPI.
203  */
204 void (*cl_inet_getspi)(uint8_t, uint8_t *, size_t) = NULL;
205 
206 /*
207  * Hook function to verify if the SPI is already utlized.
208  */
209 
210 int (*cl_inet_checkspi)(uint8_t, uint32_t) = NULL;
211 
212 /*
213  * Hook function to delete the SPI from the cluster wide repository.
214  */
215 
216 void (*cl_inet_deletespi)(uint8_t, uint32_t) = NULL;
217 
218 /*
219  * Hook function to inform the cluster when packet received on an IDLE SA
220  */
221 
222 void (*cl_inet_idlesa)(uint8_t, uint32_t, sa_family_t, in6_addr_t,
223     in6_addr_t) = 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 /* RFC1122 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_insert_ire(mblk_t *, ire_t *, iulp_t *,
662 		    ip_stack_t *);
663 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
664 char		*ip_dot_addr(ipaddr_t, char *);
665 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
666 int		ip_close(queue_t *, int);
667 static char	*ip_dot_saddr(uchar_t *, char *);
668 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
669 		    boolean_t, boolean_t, ill_t *, zoneid_t);
670 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
671 		    boolean_t, boolean_t, zoneid_t);
672 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
673 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
674 static void	ip_lrput(queue_t *, mblk_t *);
675 ipaddr_t	ip_net_mask(ipaddr_t);
676 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
677 		    ip_stack_t *);
678 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
679 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
680 char		*ip_nv_lookup(nv_t *, int);
681 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
682 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
683 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
684 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
685     ipndp_t *, size_t);
686 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
687 void	ip_rput(queue_t *, mblk_t *);
688 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
689 		    void *dummy_arg);
690 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
691 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
692     ip_stack_t *);
693 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
694 			    ire_t *, ip_stack_t *);
695 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
696 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
697 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
698     ip_stack_t *);
699 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
700 		    uint16_t *);
701 int		ip_snmp_get(queue_t *, mblk_t *, int);
702 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
703 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
704 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
705 		    ip_stack_t *);
706 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
707 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
708 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
709 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
710 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
711 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
712 		    ip_stack_t *ipst);
713 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
714 		    ip_stack_t *ipst);
715 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
716 		    ip_stack_t *ipst);
717 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
718 		    ip_stack_t *ipst);
719 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
720 		    ip_stack_t *ipst);
721 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
722 		    ip_stack_t *ipst);
723 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
724 		    ip_stack_t *ipst);
725 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
726 		    ip_stack_t *ipst);
727 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
728 		    ip_stack_t *ipst);
729 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
730 		    ip_stack_t *ipst);
731 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
732 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
733 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
734 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
735 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
736 static boolean_t	ip_source_route_included(ipha_t *);
737 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
738 
739 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
740 		    zoneid_t, ip_stack_t *, conn_t *);
741 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
742 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
743 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
744 		    zoneid_t, ip_stack_t *);
745 
746 static void	conn_drain_init(ip_stack_t *);
747 static void	conn_drain_fini(ip_stack_t *);
748 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
749 
750 static void	conn_walk_drain(ip_stack_t *);
751 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
752     zoneid_t);
753 
754 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
755 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
756 static void	ip_stack_fini(netstackid_t stackid, void *arg);
757 
758 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
759     zoneid_t);
760 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
761     void *dummy_arg);
762 
763 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
764 
765 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
766     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
767     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
768 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
769 
770 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
771 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
772     caddr_t, cred_t *);
773 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
774     caddr_t cp, cred_t *cr);
775 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
776     cred_t *);
777 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
778     cred_t *);
779 static int	ip_squeue_switch(int);
780 
781 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
782 static void	ip_kstat_fini(netstackid_t, kstat_t *);
783 static int	ip_kstat_update(kstat_t *kp, int rw);
784 static void	*icmp_kstat_init(netstackid_t);
785 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
786 static int	icmp_kstat_update(kstat_t *kp, int rw);
787 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
788 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
789 
790 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
791 
792 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
793     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
794 
795 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
796     ipha_t *, ill_t *, boolean_t, boolean_t);
797 
798 static void ipobs_init(ip_stack_t *);
799 static void ipobs_fini(ip_stack_t *);
800 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
801 
802 /* How long, in seconds, we allow frags to hang around. */
803 #define	IP_FRAG_TIMEOUT	15
804 
805 /*
806  * Threshold which determines whether MDT should be used when
807  * generating IP fragments; payload size must be greater than
808  * this threshold for MDT to take place.
809  */
810 #define	IP_WPUT_FRAG_MDT_MIN	32768
811 
812 /* Setable in /etc/system only */
813 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
814 
815 static long ip_rput_pullups;
816 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
817 
818 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
819 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
820 
821 int	ip_debug;
822 
823 #ifdef DEBUG
824 uint32_t ipsechw_debug = 0;
825 #endif
826 
827 /*
828  * Multirouting/CGTP stuff
829  */
830 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
831 
832 /*
833  * XXX following really should only be in a header. Would need more
834  * header and .c clean up first.
835  */
836 extern optdb_obj_t	ip_opt_obj;
837 
838 ulong_t ip_squeue_enter_unbound = 0;
839 
840 /*
841  * Named Dispatch Parameter Table.
842  * All of these are alterable, within the min/max values given, at run time.
843  */
844 static ipparam_t	lcl_param_arr[] = {
845 	/* min	max	value	name */
846 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
847 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
848 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
849 	{  0,	1,	0,	"ip_respond_to_timestamp"},
850 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
851 	{  0,	1,	1,	"ip_send_redirects"},
852 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
853 	{  0,	10,	0,	"ip_mrtdebug"},
854 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
855 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
856 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
857 	{  1,	255,	255,	"ip_def_ttl" },
858 	{  0,	1,	0,	"ip_forward_src_routed"},
859 	{  0,	256,	32,	"ip_wroff_extra" },
860 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
861 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
862 	{  0,	1,	1,	"ip_path_mtu_discovery" },
863 	{  0,	240,	30,	"ip_ignore_delete_time" },
864 	{  0,	1,	0,	"ip_ignore_redirect" },
865 	{  0,	1,	1,	"ip_output_queue" },
866 	{  1,	254,	1,	"ip_broadcast_ttl" },
867 	{  0,	99999,	100,	"ip_icmp_err_interval" },
868 	{  1,	99999,	10,	"ip_icmp_err_burst" },
869 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
870 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
871 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
872 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
873 	{  0,	1,	1,	"icmp_accept_clear_messages" },
874 	{  0,	1,	1,	"igmp_accept_clear_messages" },
875 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
876 				"ip_ndp_delay_first_probe_time"},
877 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
878 				"ip_ndp_max_unicast_solicit"},
879 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
880 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
881 	{  0,	1,	0,	"ip6_forward_src_routed"},
882 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
883 	{  0,	1,	1,	"ip6_send_redirects"},
884 	{  0,	1,	0,	"ip6_ignore_redirect" },
885 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
886 
887 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
888 
889 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
890 
891 	{  0,	1,	1,	"pim_accept_clear_messages" },
892 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
893 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
894 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
895 	{  0,	15,	0,	"ip_policy_mask" },
896 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
897 	{  0,	255,	1,	"ip_multirt_ttl" },
898 	{  0,	1,	1,	"ip_multidata_outbound" },
899 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
900 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
901 	{  0,	1000,	1,	"ip_max_temp_defend" },
902 	{  0,	1000,	3,	"ip_max_defend" },
903 	{  0,	999999,	30,	"ip_defend_interval" },
904 	{  0,	3600000, 300000, "ip_dup_recovery" },
905 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
906 	{  0,	1,	1,	"ip_lso_outbound" },
907 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
908 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
909 	{ 68,	65535,	576,	"ip_pmtu_min" },
910 #ifdef DEBUG
911 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
912 #else
913 	{  0,	0,	0,	"" },
914 #endif
915 };
916 
917 /*
918  * Extended NDP table
919  * The addresses for the first two are filled in to be ips_ip_g_forward
920  * and ips_ipv6_forward at init time.
921  */
922 static ipndp_t	lcl_ndp_arr[] = {
923 	/* getf			setf		data			name */
924 #define	IPNDP_IP_FORWARDING_OFFSET	0
925 	{  ip_param_generic_get,	ip_forward_set,	NULL,
926 	    "ip_forwarding" },
927 #define	IPNDP_IP6_FORWARDING_OFFSET	1
928 	{  ip_param_generic_get,	ip_forward_set,	NULL,
929 	    "ip6_forwarding" },
930 	{  ip_ill_report,	NULL,		NULL,
931 	    "ip_ill_status" },
932 	{  ip_ipif_report,	NULL,		NULL,
933 	    "ip_ipif_status" },
934 	{  ip_conn_report,	NULL,		NULL,
935 	    "ip_conn_status" },
936 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
937 	    "ip_rput_pullups" },
938 	{  ip_srcid_report,	NULL,		NULL,
939 	    "ip_srcid_status" },
940 	{ ip_param_generic_get, ip_input_proc_set,
941 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
942 	{ ip_param_generic_get, ip_int_set,
943 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
944 #define	IPNDP_CGTP_FILTER_OFFSET	9
945 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
946 	    "ip_cgtp_filter" },
947 #define	IPNDP_IPMP_HOOK_OFFSET		10
948 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
949 	    "ipmp_hook_emulation" },
950 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
951 	    "ip_debug" },
952 };
953 
954 /*
955  * Table of IP ioctls encoding the various properties of the ioctl and
956  * indexed based on the last byte of the ioctl command. Occasionally there
957  * is a clash, and there is more than 1 ioctl with the same last byte.
958  * In such a case 1 ioctl is encoded in the ndx table and the remaining
959  * ioctls are encoded in the misc table. An entry in the ndx table is
960  * retrieved by indexing on the last byte of the ioctl command and comparing
961  * the ioctl command with the value in the ndx table. In the event of a
962  * mismatch the misc table is then searched sequentially for the desired
963  * ioctl command.
964  *
965  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
966  */
967 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
968 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
969 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
970 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
971 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
972 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
973 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
974 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
975 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
976 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
977 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
978 
979 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
980 			MISC_CMD, ip_siocaddrt, NULL },
981 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
982 			MISC_CMD, ip_siocdelrt, NULL },
983 
984 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
985 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
986 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
987 			IF_CMD, ip_sioctl_get_addr, NULL },
988 
989 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
990 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
991 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
992 			IPI_GET_CMD | IPI_REPL,
993 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
994 
995 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
996 			IPI_PRIV | IPI_WR | IPI_REPL,
997 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
998 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
999 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1000 			IF_CMD, ip_sioctl_get_flags, NULL },
1001 
1002 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1003 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1004 
1005 	/* copyin size cannot be coded for SIOCGIFCONF */
1006 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1007 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1008 
1009 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1010 			IF_CMD, ip_sioctl_mtu, NULL },
1011 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1012 			IF_CMD, ip_sioctl_get_mtu, NULL },
1013 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1014 			IPI_GET_CMD | IPI_REPL,
1015 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1016 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1017 			IF_CMD, ip_sioctl_brdaddr, NULL },
1018 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1019 			IPI_GET_CMD | IPI_REPL,
1020 			IF_CMD, ip_sioctl_get_netmask, NULL },
1021 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1022 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1023 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1024 			IPI_GET_CMD | IPI_REPL,
1025 			IF_CMD, ip_sioctl_get_metric, NULL },
1026 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1027 			IF_CMD, ip_sioctl_metric, NULL },
1028 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 
1030 	/* See 166-168 below for extended SIOC*XARP ioctls */
1031 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1032 			ARP_CMD, ip_sioctl_arp, NULL },
1033 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1034 			ARP_CMD, ip_sioctl_arp, NULL },
1035 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1036 			ARP_CMD, ip_sioctl_arp, NULL },
1037 
1038 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 
1060 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1061 			MISC_CMD, if_unitsel, if_unitsel_restart },
1062 
1063 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 
1082 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1083 			IPI_PRIV | IPI_WR | IPI_MODOK,
1084 			IF_CMD, ip_sioctl_sifname, NULL },
1085 
1086 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1087 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1088 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1089 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1090 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 
1100 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1101 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1102 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1103 			IF_CMD, ip_sioctl_get_muxid, NULL },
1104 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1105 			IPI_PRIV | IPI_WR | IPI_REPL,
1106 			IF_CMD, ip_sioctl_muxid, NULL },
1107 
1108 	/* Both if and lif variants share same func */
1109 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1110 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1111 	/* Both if and lif variants share same func */
1112 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1113 			IPI_PRIV | IPI_WR | IPI_REPL,
1114 			IF_CMD, ip_sioctl_slifindex, NULL },
1115 
1116 	/* copyin size cannot be coded for SIOCGIFCONF */
1117 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1118 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1119 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 
1137 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1138 			IPI_PRIV | IPI_WR | IPI_REPL,
1139 			LIF_CMD, ip_sioctl_removeif,
1140 			ip_sioctl_removeif_restart },
1141 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1142 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1143 			LIF_CMD, ip_sioctl_addif, NULL },
1144 #define	SIOCLIFADDR_NDX 112
1145 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1146 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1147 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1148 			IPI_GET_CMD | IPI_REPL,
1149 			LIF_CMD, ip_sioctl_get_addr, NULL },
1150 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1151 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1152 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1153 			IPI_GET_CMD | IPI_REPL,
1154 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1155 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1156 			IPI_PRIV | IPI_WR | IPI_REPL,
1157 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1158 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_flags, NULL },
1161 
1162 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1163 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1164 
1165 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1166 			ip_sioctl_get_lifconf, NULL },
1167 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1168 			LIF_CMD, ip_sioctl_mtu, NULL },
1169 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1170 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1171 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1172 			IPI_GET_CMD | IPI_REPL,
1173 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1174 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1175 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1176 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1177 			IPI_GET_CMD | IPI_REPL,
1178 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1179 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1180 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1181 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1182 			IPI_GET_CMD | IPI_REPL,
1183 			LIF_CMD, ip_sioctl_get_metric, NULL },
1184 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1185 			LIF_CMD, ip_sioctl_metric, NULL },
1186 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1187 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_slifname,
1189 			ip_sioctl_slifname_restart },
1190 
1191 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1192 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1193 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1194 			IPI_GET_CMD | IPI_REPL,
1195 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1196 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1197 			IPI_PRIV | IPI_WR | IPI_REPL,
1198 			LIF_CMD, ip_sioctl_muxid, NULL },
1199 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1200 			IPI_GET_CMD | IPI_REPL,
1201 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1202 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1203 			IPI_PRIV | IPI_WR | IPI_REPL,
1204 			LIF_CMD, ip_sioctl_slifindex, 0 },
1205 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1206 			LIF_CMD, ip_sioctl_token, NULL },
1207 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1208 			IPI_GET_CMD | IPI_REPL,
1209 			LIF_CMD, ip_sioctl_get_token, NULL },
1210 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1211 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1212 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1213 			IPI_GET_CMD | IPI_REPL,
1214 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1215 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1216 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1217 
1218 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1219 			IPI_GET_CMD | IPI_REPL,
1220 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1221 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1222 			LIF_CMD, ip_siocdelndp_v6, NULL },
1223 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1224 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1225 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1226 			LIF_CMD, ip_siocsetndp_v6, NULL },
1227 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1228 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1229 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1230 			MISC_CMD, ip_sioctl_tonlink, NULL },
1231 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1232 			MISC_CMD, ip_sioctl_tmysite, NULL },
1233 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1234 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1235 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1236 		    IPI_PRIV | IPI_WR,
1237 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1238 
1239 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1240 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1241 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1242 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1243 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1244 
1245 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1246 			IPI_PRIV | IPI_WR | IPI_REPL,
1247 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1248 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1249 			IPI_PRIV | IPI_WR | IPI_REPL,
1250 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1251 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1252 			IPI_PRIV | IPI_WR | IPI_REPL,
1253 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1254 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1255 			IPI_GET_CMD | IPI_REPL,
1256 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1257 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1258 			IPI_GET_CMD | IPI_REPL,
1259 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1260 
1261 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1262 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1263 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1264 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1265 
1266 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1267 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1268 
1269 	/* These are handled in ip_sioctl_copyin_setup itself */
1270 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1271 			MISC_CMD, NULL, NULL },
1272 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1273 			MISC_CMD, NULL, NULL },
1274 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1275 
1276 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1277 			ip_sioctl_get_lifconf, NULL },
1278 
1279 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1280 			XARP_CMD, ip_sioctl_arp, NULL },
1281 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1282 			XARP_CMD, ip_sioctl_arp, NULL },
1283 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1284 			XARP_CMD, ip_sioctl_arp, NULL },
1285 
1286 	/* SIOCPOPSOCKFS is not handled by IP */
1287 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1288 
1289 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1290 			IPI_GET_CMD | IPI_REPL,
1291 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1292 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1293 			IPI_PRIV | IPI_WR | IPI_REPL,
1294 			LIF_CMD, ip_sioctl_slifzone,
1295 			ip_sioctl_slifzone_restart },
1296 	/* 172-174 are SCTP ioctls and not handled by IP */
1297 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1298 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1299 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1300 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1301 			IPI_GET_CMD, LIF_CMD,
1302 			ip_sioctl_get_lifusesrc, 0 },
1303 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1304 			IPI_PRIV | IPI_WR,
1305 			LIF_CMD, ip_sioctl_slifusesrc,
1306 			NULL },
1307 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1308 			ip_sioctl_get_lifsrcof, NULL },
1309 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1310 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1311 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1312 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1313 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1314 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1315 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1316 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1317 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1318 			ip_sioctl_set_ipmpfailback, NULL },
1319 	/* SIOCSENABLESDP is handled by SDP */
1320 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1321 };
1322 
1323 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1324 
1325 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1326 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1327 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1328 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1329 		TUN_CMD, ip_sioctl_tunparam, NULL },
1330 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1331 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1332 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1333 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1334 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1335 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1336 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1337 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1338 		MISC_CMD, mrt_ioctl},
1339 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1340 		MISC_CMD, mrt_ioctl},
1341 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1342 		MISC_CMD, mrt_ioctl}
1343 };
1344 
1345 int ip_misc_ioctl_count =
1346     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1347 
1348 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1349 					/* Settable in /etc/system */
1350 /* Defined in ip_ire.c */
1351 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1352 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1353 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1354 
1355 static nv_t	ire_nv_arr[] = {
1356 	{ IRE_BROADCAST, "BROADCAST" },
1357 	{ IRE_LOCAL, "LOCAL" },
1358 	{ IRE_LOOPBACK, "LOOPBACK" },
1359 	{ IRE_CACHE, "CACHE" },
1360 	{ IRE_DEFAULT, "DEFAULT" },
1361 	{ IRE_PREFIX, "PREFIX" },
1362 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1363 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1364 	{ IRE_HOST, "HOST" },
1365 	{ 0 }
1366 };
1367 
1368 nv_t	*ire_nv_tbl = ire_nv_arr;
1369 
1370 /* Simple ICMP IP Header Template */
1371 static ipha_t icmp_ipha = {
1372 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1373 };
1374 
1375 struct module_info ip_mod_info = {
1376 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1377 };
1378 
1379 /*
1380  * Duplicate static symbols within a module confuses mdb; so we avoid the
1381  * problem by making the symbols here distinct from those in udp.c.
1382  */
1383 
1384 /*
1385  * Entry points for IP as a device and as a module.
1386  * FIXME: down the road we might want a separate module and driver qinit.
1387  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1388  */
1389 static struct qinit iprinitv4 = {
1390 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1391 	&ip_mod_info
1392 };
1393 
1394 struct qinit iprinitv6 = {
1395 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1396 	&ip_mod_info
1397 };
1398 
1399 static struct qinit ipwinitv4 = {
1400 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1401 	&ip_mod_info
1402 };
1403 
1404 struct qinit ipwinitv6 = {
1405 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1406 	&ip_mod_info
1407 };
1408 
1409 static struct qinit iplrinit = {
1410 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1411 	&ip_mod_info
1412 };
1413 
1414 static struct qinit iplwinit = {
1415 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1416 	&ip_mod_info
1417 };
1418 
1419 /* For AF_INET aka /dev/ip */
1420 struct streamtab ipinfov4 = {
1421 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1422 };
1423 
1424 /* For AF_INET6 aka /dev/ip6 */
1425 struct streamtab ipinfov6 = {
1426 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1427 };
1428 
1429 #ifdef	DEBUG
1430 static boolean_t skip_sctp_cksum = B_FALSE;
1431 #endif
1432 
1433 /*
1434  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1435  * ip_rput_v6(), ip_output(), etc.  If the message
1436  * block already has a M_CTL at the front of it, then simply set the zoneid
1437  * appropriately.
1438  */
1439 mblk_t *
1440 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1441 {
1442 	mblk_t		*first_mp;
1443 	ipsec_out_t	*io;
1444 
1445 	ASSERT(zoneid != ALL_ZONES);
1446 	if (mp->b_datap->db_type == M_CTL) {
1447 		io = (ipsec_out_t *)mp->b_rptr;
1448 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1449 		io->ipsec_out_zoneid = zoneid;
1450 		return (mp);
1451 	}
1452 
1453 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1454 	if (first_mp == NULL)
1455 		return (NULL);
1456 	io = (ipsec_out_t *)first_mp->b_rptr;
1457 	/* This is not a secure packet */
1458 	io->ipsec_out_secure = B_FALSE;
1459 	io->ipsec_out_zoneid = zoneid;
1460 	first_mp->b_cont = mp;
1461 	return (first_mp);
1462 }
1463 
1464 /*
1465  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1466  */
1467 mblk_t *
1468 ip_copymsg(mblk_t *mp)
1469 {
1470 	mblk_t *nmp;
1471 	ipsec_info_t *in;
1472 
1473 	if (mp->b_datap->db_type != M_CTL)
1474 		return (copymsg(mp));
1475 
1476 	in = (ipsec_info_t *)mp->b_rptr;
1477 
1478 	/*
1479 	 * Note that M_CTL is also used for delivering ICMP error messages
1480 	 * upstream to transport layers.
1481 	 */
1482 	if (in->ipsec_info_type != IPSEC_OUT &&
1483 	    in->ipsec_info_type != IPSEC_IN)
1484 		return (copymsg(mp));
1485 
1486 	nmp = copymsg(mp->b_cont);
1487 
1488 	if (in->ipsec_info_type == IPSEC_OUT) {
1489 		return (ipsec_out_tag(mp, nmp,
1490 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1491 	} else {
1492 		return (ipsec_in_tag(mp, nmp,
1493 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1494 	}
1495 }
1496 
1497 /* Generate an ICMP fragmentation needed message. */
1498 static void
1499 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1500     ip_stack_t *ipst)
1501 {
1502 	icmph_t	icmph;
1503 	mblk_t *first_mp;
1504 	boolean_t mctl_present;
1505 
1506 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1507 
1508 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1509 		if (mctl_present)
1510 			freeb(first_mp);
1511 		return;
1512 	}
1513 
1514 	bzero(&icmph, sizeof (icmph_t));
1515 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1516 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1517 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1518 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1519 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1520 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1521 	    ipst);
1522 }
1523 
1524 /*
1525  * icmp_inbound deals with ICMP messages in the following ways.
1526  *
1527  * 1) It needs to send a reply back and possibly delivering it
1528  *    to the "interested" upper clients.
1529  * 2) It needs to send it to the upper clients only.
1530  * 3) It needs to change some values in IP only.
1531  * 4) It needs to change some values in IP and upper layers e.g TCP.
1532  *
1533  * We need to accomodate icmp messages coming in clear until we get
1534  * everything secure from the wire. If icmp_accept_clear_messages
1535  * is zero we check with the global policy and act accordingly. If
1536  * it is non-zero, we accept the message without any checks. But
1537  * *this does not mean* that this will be delivered to the upper
1538  * clients. By accepting we might send replies back, change our MTU
1539  * value etc. but delivery to the ULP/clients depends on their policy
1540  * dispositions.
1541  *
1542  * We handle the above 4 cases in the context of IPsec in the
1543  * following way :
1544  *
1545  * 1) Send the reply back in the same way as the request came in.
1546  *    If it came in encrypted, it goes out encrypted. If it came in
1547  *    clear, it goes out in clear. Thus, this will prevent chosen
1548  *    plain text attack.
1549  * 2) The client may or may not expect things to come in secure.
1550  *    If it comes in secure, the policy constraints are checked
1551  *    before delivering it to the upper layers. If it comes in
1552  *    clear, ipsec_inbound_accept_clear will decide whether to
1553  *    accept this in clear or not. In both the cases, if the returned
1554  *    message (IP header + 8 bytes) that caused the icmp message has
1555  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1556  *    sending up. If there are only 8 bytes of returned message, then
1557  *    upper client will not be notified.
1558  * 3) Check with global policy to see whether it matches the constaints.
1559  *    But this will be done only if icmp_accept_messages_in_clear is
1560  *    zero.
1561  * 4) If we need to change both in IP and ULP, then the decision taken
1562  *    while affecting the values in IP and while delivering up to TCP
1563  *    should be the same.
1564  *
1565  * 	There are two cases.
1566  *
1567  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1568  *	   failed), we will not deliver it to the ULP, even though they
1569  *	   are *willing* to accept in *clear*. This is fine as our global
1570  *	   disposition to icmp messages asks us reject the datagram.
1571  *
1572  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1573  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1574  *	   to deliver it to ULP (policy failed), it can lead to
1575  *	   consistency problems. The cases known at this time are
1576  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1577  *	   values :
1578  *
1579  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1580  *	     and Upper layer rejects. Then the communication will
1581  *	     come to a stop. This is solved by making similar decisions
1582  *	     at both levels. Currently, when we are unable to deliver
1583  *	     to the Upper Layer (due to policy failures) while IP has
1584  *	     adjusted ire_max_frag, the next outbound datagram would
1585  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1586  *	     will be with the right level of protection. Thus the right
1587  *	     value will be communicated even if we are not able to
1588  *	     communicate when we get from the wire initially. But this
1589  *	     assumes there would be at least one outbound datagram after
1590  *	     IP has adjusted its ire_max_frag value. To make things
1591  *	     simpler, we accept in clear after the validation of
1592  *	     AH/ESP headers.
1593  *
1594  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1595  *	     upper layer depending on the level of protection the upper
1596  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1597  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1598  *	     should be accepted in clear when the Upper layer expects secure.
1599  *	     Thus the communication may get aborted by some bad ICMP
1600  *	     packets.
1601  *
1602  * IPQoS Notes:
1603  * The only instance when a packet is sent for processing is when there
1604  * isn't an ICMP client and if we are interested in it.
1605  * If there is a client, IPPF processing will take place in the
1606  * ip_fanout_proto routine.
1607  *
1608  * Zones notes:
1609  * The packet is only processed in the context of the specified zone: typically
1610  * only this zone will reply to an echo request, and only interested clients in
1611  * this zone will receive a copy of the packet. This means that the caller must
1612  * call icmp_inbound() for each relevant zone.
1613  */
1614 static void
1615 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1616     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1617     ill_t *recv_ill, zoneid_t zoneid)
1618 {
1619 	icmph_t	*icmph;
1620 	ipha_t	*ipha;
1621 	int	iph_hdr_length;
1622 	int	hdr_length;
1623 	boolean_t	interested;
1624 	uint32_t	ts;
1625 	uchar_t	*wptr;
1626 	ipif_t	*ipif;
1627 	mblk_t *first_mp;
1628 	ipsec_in_t *ii;
1629 	ire_t *src_ire;
1630 	boolean_t onlink;
1631 	timestruc_t now;
1632 	uint32_t ill_index;
1633 	ip_stack_t *ipst;
1634 
1635 	ASSERT(ill != NULL);
1636 	ipst = ill->ill_ipst;
1637 
1638 	first_mp = mp;
1639 	if (mctl_present) {
1640 		mp = first_mp->b_cont;
1641 		ASSERT(mp != NULL);
1642 	}
1643 
1644 	ipha = (ipha_t *)mp->b_rptr;
1645 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1646 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1647 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1648 		if (first_mp == NULL)
1649 			return;
1650 	}
1651 
1652 	/*
1653 	 * On a labeled system, we have to check whether the zone itself is
1654 	 * permitted to receive raw traffic.
1655 	 */
1656 	if (is_system_labeled()) {
1657 		if (zoneid == ALL_ZONES)
1658 			zoneid = tsol_packet_to_zoneid(mp);
1659 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1660 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1661 			    zoneid));
1662 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1663 			freemsg(first_mp);
1664 			return;
1665 		}
1666 	}
1667 
1668 	/*
1669 	 * We have accepted the ICMP message. It means that we will
1670 	 * respond to the packet if needed. It may not be delivered
1671 	 * to the upper client depending on the policy constraints
1672 	 * and the disposition in ipsec_inbound_accept_clear.
1673 	 */
1674 
1675 	ASSERT(ill != NULL);
1676 
1677 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1678 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1679 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1680 		/* Last chance to get real. */
1681 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1682 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1683 			freemsg(first_mp);
1684 			return;
1685 		}
1686 		/* Refresh iph following the pullup. */
1687 		ipha = (ipha_t *)mp->b_rptr;
1688 	}
1689 	/* ICMP header checksum, including checksum field, should be zero. */
1690 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1691 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1692 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1693 		freemsg(first_mp);
1694 		return;
1695 	}
1696 	/* The IP header will always be a multiple of four bytes */
1697 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1698 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1699 	    icmph->icmph_code));
1700 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1701 	/* We will set "interested" to "true" if we want a copy */
1702 	interested = B_FALSE;
1703 	switch (icmph->icmph_type) {
1704 	case ICMP_ECHO_REPLY:
1705 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1706 		break;
1707 	case ICMP_DEST_UNREACHABLE:
1708 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1709 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1710 		interested = B_TRUE;	/* Pass up to transport */
1711 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1712 		break;
1713 	case ICMP_SOURCE_QUENCH:
1714 		interested = B_TRUE;	/* Pass up to transport */
1715 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1716 		break;
1717 	case ICMP_REDIRECT:
1718 		if (!ipst->ips_ip_ignore_redirect)
1719 			interested = B_TRUE;
1720 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1721 		break;
1722 	case ICMP_ECHO_REQUEST:
1723 		/*
1724 		 * Whether to respond to echo requests that come in as IP
1725 		 * broadcasts or as IP multicast is subject to debate
1726 		 * (what isn't?).  We aim to please, you pick it.
1727 		 * Default is do it.
1728 		 */
1729 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1730 			/* unicast: always respond */
1731 			interested = B_TRUE;
1732 		} else if (CLASSD(ipha->ipha_dst)) {
1733 			/* multicast: respond based on tunable */
1734 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1735 		} else if (broadcast) {
1736 			/* broadcast: respond based on tunable */
1737 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1738 		}
1739 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1740 		break;
1741 	case ICMP_ROUTER_ADVERTISEMENT:
1742 	case ICMP_ROUTER_SOLICITATION:
1743 		break;
1744 	case ICMP_TIME_EXCEEDED:
1745 		interested = B_TRUE;	/* Pass up to transport */
1746 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1747 		break;
1748 	case ICMP_PARAM_PROBLEM:
1749 		interested = B_TRUE;	/* Pass up to transport */
1750 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1751 		break;
1752 	case ICMP_TIME_STAMP_REQUEST:
1753 		/* Response to Time Stamp Requests is local policy. */
1754 		if (ipst->ips_ip_g_resp_to_timestamp &&
1755 		    /* So is whether to respond if it was an IP broadcast. */
1756 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1757 			int tstamp_len = 3 * sizeof (uint32_t);
1758 
1759 			if (wptr +  tstamp_len > mp->b_wptr) {
1760 				if (!pullupmsg(mp, wptr + tstamp_len -
1761 				    mp->b_rptr)) {
1762 					BUMP_MIB(ill->ill_ip_mib,
1763 					    ipIfStatsInDiscards);
1764 					freemsg(first_mp);
1765 					return;
1766 				}
1767 				/* Refresh ipha following the pullup. */
1768 				ipha = (ipha_t *)mp->b_rptr;
1769 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1770 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1771 			}
1772 			interested = B_TRUE;
1773 		}
1774 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1775 		break;
1776 	case ICMP_TIME_STAMP_REPLY:
1777 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1778 		break;
1779 	case ICMP_INFO_REQUEST:
1780 		/* Per RFC 1122 3.2.2.7, ignore this. */
1781 	case ICMP_INFO_REPLY:
1782 		break;
1783 	case ICMP_ADDRESS_MASK_REQUEST:
1784 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1785 		    !broadcast) &&
1786 		    /* TODO m_pullup of complete header? */
1787 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1788 			interested = B_TRUE;
1789 		}
1790 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1791 		break;
1792 	case ICMP_ADDRESS_MASK_REPLY:
1793 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1794 		break;
1795 	default:
1796 		interested = B_TRUE;	/* Pass up to transport */
1797 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1798 		break;
1799 	}
1800 	/* See if there is an ICMP client. */
1801 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1802 		/* If there is an ICMP client and we want one too, copy it. */
1803 		mblk_t *first_mp1;
1804 
1805 		if (!interested) {
1806 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1807 			    ip_policy, recv_ill, zoneid);
1808 			return;
1809 		}
1810 		first_mp1 = ip_copymsg(first_mp);
1811 		if (first_mp1 != NULL) {
1812 			ip_fanout_proto(q, first_mp1, ill, ipha,
1813 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1814 		}
1815 	} else if (!interested) {
1816 		freemsg(first_mp);
1817 		return;
1818 	} else {
1819 		/*
1820 		 * Initiate policy processing for this packet if ip_policy
1821 		 * is true.
1822 		 */
1823 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1824 			ill_index = ill->ill_phyint->phyint_ifindex;
1825 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1826 			if (mp == NULL) {
1827 				if (mctl_present) {
1828 					freeb(first_mp);
1829 				}
1830 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1831 				return;
1832 			}
1833 		}
1834 	}
1835 	/* We want to do something with it. */
1836 	/* Check db_ref to make sure we can modify the packet. */
1837 	if (mp->b_datap->db_ref > 1) {
1838 		mblk_t	*first_mp1;
1839 
1840 		first_mp1 = ip_copymsg(first_mp);
1841 		freemsg(first_mp);
1842 		if (!first_mp1) {
1843 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1844 			return;
1845 		}
1846 		first_mp = first_mp1;
1847 		if (mctl_present) {
1848 			mp = first_mp->b_cont;
1849 			ASSERT(mp != NULL);
1850 		} else {
1851 			mp = first_mp;
1852 		}
1853 		ipha = (ipha_t *)mp->b_rptr;
1854 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1855 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1856 	}
1857 	switch (icmph->icmph_type) {
1858 	case ICMP_ADDRESS_MASK_REQUEST:
1859 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1860 		if (ipif == NULL) {
1861 			freemsg(first_mp);
1862 			return;
1863 		}
1864 		/*
1865 		 * outging interface must be IPv4
1866 		 */
1867 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1868 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1869 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1870 		ipif_refrele(ipif);
1871 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1872 		break;
1873 	case ICMP_ECHO_REQUEST:
1874 		icmph->icmph_type = ICMP_ECHO_REPLY;
1875 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1876 		break;
1877 	case ICMP_TIME_STAMP_REQUEST: {
1878 		uint32_t *tsp;
1879 
1880 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1881 		tsp = (uint32_t *)wptr;
1882 		tsp++;		/* Skip past 'originate time' */
1883 		/* Compute # of milliseconds since midnight */
1884 		gethrestime(&now);
1885 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1886 		    now.tv_nsec / (NANOSEC / MILLISEC);
1887 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1888 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1889 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1890 		break;
1891 	}
1892 	default:
1893 		ipha = (ipha_t *)&icmph[1];
1894 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1895 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1896 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1897 				freemsg(first_mp);
1898 				return;
1899 			}
1900 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1901 			ipha = (ipha_t *)&icmph[1];
1902 		}
1903 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1904 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1905 			freemsg(first_mp);
1906 			return;
1907 		}
1908 		hdr_length = IPH_HDR_LENGTH(ipha);
1909 		if (hdr_length < sizeof (ipha_t)) {
1910 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1911 			freemsg(first_mp);
1912 			return;
1913 		}
1914 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1915 			if (!pullupmsg(mp,
1916 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1917 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1918 				freemsg(first_mp);
1919 				return;
1920 			}
1921 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1922 			ipha = (ipha_t *)&icmph[1];
1923 		}
1924 		switch (icmph->icmph_type) {
1925 		case ICMP_REDIRECT:
1926 			/*
1927 			 * As there is no upper client to deliver, we don't
1928 			 * need the first_mp any more.
1929 			 */
1930 			if (mctl_present) {
1931 				freeb(first_mp);
1932 			}
1933 			icmp_redirect(ill, mp);
1934 			return;
1935 		case ICMP_DEST_UNREACHABLE:
1936 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1937 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1938 				    zoneid, mp, iph_hdr_length, ipst)) {
1939 					freemsg(first_mp);
1940 					return;
1941 				}
1942 				/*
1943 				 * icmp_inbound_too_big() may alter mp.
1944 				 * Resynch ipha and icmph accordingly.
1945 				 */
1946 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1947 				ipha = (ipha_t *)&icmph[1];
1948 			}
1949 			/* FALLTHRU */
1950 		default :
1951 			/*
1952 			 * IPQoS notes: Since we have already done IPQoS
1953 			 * processing we don't want to do it again in
1954 			 * the fanout routines called by
1955 			 * icmp_inbound_error_fanout, hence the last
1956 			 * argument, ip_policy, is B_FALSE.
1957 			 */
1958 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1959 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1960 			    B_FALSE, recv_ill, zoneid);
1961 		}
1962 		return;
1963 	}
1964 	/* Send out an ICMP packet */
1965 	icmph->icmph_checksum = 0;
1966 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1967 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1968 		ipif_t	*ipif_chosen;
1969 		/*
1970 		 * Make it look like it was directed to us, so we don't look
1971 		 * like a fool with a broadcast or multicast source address.
1972 		 */
1973 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1974 		/*
1975 		 * Make sure that we haven't grabbed an interface that's DOWN.
1976 		 */
1977 		if (ipif != NULL) {
1978 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1979 			    ipha->ipha_src, zoneid);
1980 			if (ipif_chosen != NULL) {
1981 				ipif_refrele(ipif);
1982 				ipif = ipif_chosen;
1983 			}
1984 		}
1985 		if (ipif == NULL) {
1986 			ip0dbg(("icmp_inbound: "
1987 			    "No source for broadcast/multicast:\n"
1988 			    "\tsrc 0x%x dst 0x%x ill %p "
1989 			    "ipif_lcl_addr 0x%x\n",
1990 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1991 			    (void *)ill,
1992 			    ill->ill_ipif->ipif_lcl_addr));
1993 			freemsg(first_mp);
1994 			return;
1995 		}
1996 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1997 		ipha->ipha_dst = ipif->ipif_src_addr;
1998 		ipif_refrele(ipif);
1999 	}
2000 	/* Reset time to live. */
2001 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2002 	{
2003 		/* Swap source and destination addresses */
2004 		ipaddr_t tmp;
2005 
2006 		tmp = ipha->ipha_src;
2007 		ipha->ipha_src = ipha->ipha_dst;
2008 		ipha->ipha_dst = tmp;
2009 	}
2010 	ipha->ipha_ident = 0;
2011 	if (!IS_SIMPLE_IPH(ipha))
2012 		icmp_options_update(ipha);
2013 
2014 	/*
2015 	 * ICMP echo replies should go out on the same interface
2016 	 * the request came on as probes used by in.mpathd for detecting
2017 	 * NIC failures are ECHO packets. We turn-off load spreading
2018 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2019 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2020 	 * function. This is in turn handled by ip_wput and ip_newroute
2021 	 * to make sure that the packet goes out on the interface it came
2022 	 * in on. If we don't turnoff load spreading, the packets might get
2023 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2024 	 * to go out and in.mpathd would wrongly detect a failure or
2025 	 * mis-detect a NIC failure for link failure. As load spreading
2026 	 * can happen only if ill_group is not NULL, we do only for
2027 	 * that case and this does not affect the normal case.
2028 	 *
2029 	 * We turn off load spreading only on echo packets that came from
2030 	 * on-link hosts. If the interface route has been deleted, this will
2031 	 * not be enforced as we can't do much. For off-link hosts, as the
2032 	 * default routes in IPv4 does not typically have an ire_ipif
2033 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2034 	 * Moreover, expecting a default route through this interface may
2035 	 * not be correct. We use ipha_dst because of the swap above.
2036 	 */
2037 	onlink = B_FALSE;
2038 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2039 		/*
2040 		 * First, we need to make sure that it is not one of our
2041 		 * local addresses. If we set onlink when it is one of
2042 		 * our local addresses, we will end up creating IRE_CACHES
2043 		 * for one of our local addresses. Then, we will never
2044 		 * accept packets for them afterwards.
2045 		 */
2046 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2047 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2048 		if (src_ire == NULL) {
2049 			ipif = ipif_get_next_ipif(NULL, ill);
2050 			if (ipif == NULL) {
2051 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2052 				freemsg(mp);
2053 				return;
2054 			}
2055 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2056 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2057 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2058 			ipif_refrele(ipif);
2059 			if (src_ire != NULL) {
2060 				onlink = B_TRUE;
2061 				ire_refrele(src_ire);
2062 			}
2063 		} else {
2064 			ire_refrele(src_ire);
2065 		}
2066 	}
2067 	if (!mctl_present) {
2068 		/*
2069 		 * This packet should go out the same way as it
2070 		 * came in i.e in clear. To make sure that global
2071 		 * policy will not be applied to this in ip_wput_ire,
2072 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2073 		 */
2074 		ASSERT(first_mp == mp);
2075 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2076 		if (first_mp == NULL) {
2077 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2078 			freemsg(mp);
2079 			return;
2080 		}
2081 		ii = (ipsec_in_t *)first_mp->b_rptr;
2082 
2083 		/* This is not a secure packet */
2084 		ii->ipsec_in_secure = B_FALSE;
2085 		if (onlink) {
2086 			ii->ipsec_in_attach_if = B_TRUE;
2087 			ii->ipsec_in_ill_index =
2088 			    ill->ill_phyint->phyint_ifindex;
2089 			ii->ipsec_in_rill_index =
2090 			    recv_ill->ill_phyint->phyint_ifindex;
2091 		}
2092 		first_mp->b_cont = mp;
2093 	} else if (onlink) {
2094 		ii = (ipsec_in_t *)first_mp->b_rptr;
2095 		ii->ipsec_in_attach_if = B_TRUE;
2096 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2097 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2098 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2099 	} else {
2100 		ii = (ipsec_in_t *)first_mp->b_rptr;
2101 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2102 	}
2103 	ii->ipsec_in_zoneid = zoneid;
2104 	ASSERT(zoneid != ALL_ZONES);
2105 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2106 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2107 		return;
2108 	}
2109 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2110 	put(WR(q), first_mp);
2111 }
2112 
2113 static ipaddr_t
2114 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2115 {
2116 	conn_t *connp;
2117 	connf_t *connfp;
2118 	ipaddr_t nexthop_addr = INADDR_ANY;
2119 	int hdr_length = IPH_HDR_LENGTH(ipha);
2120 	uint16_t *up;
2121 	uint32_t ports;
2122 	ip_stack_t *ipst = ill->ill_ipst;
2123 
2124 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2125 	switch (ipha->ipha_protocol) {
2126 		case IPPROTO_TCP:
2127 		{
2128 			tcph_t *tcph;
2129 
2130 			/* do a reverse lookup */
2131 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2132 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2133 			    TCPS_LISTEN, ipst);
2134 			break;
2135 		}
2136 		case IPPROTO_UDP:
2137 		{
2138 			uint32_t dstport, srcport;
2139 
2140 			((uint16_t *)&ports)[0] = up[1];
2141 			((uint16_t *)&ports)[1] = up[0];
2142 
2143 			/* Extract ports in net byte order */
2144 			dstport = htons(ntohl(ports) & 0xFFFF);
2145 			srcport = htons(ntohl(ports) >> 16);
2146 
2147 			connfp = &ipst->ips_ipcl_udp_fanout[
2148 			    IPCL_UDP_HASH(dstport, ipst)];
2149 			mutex_enter(&connfp->connf_lock);
2150 			connp = connfp->connf_head;
2151 
2152 			/* do a reverse lookup */
2153 			while ((connp != NULL) &&
2154 			    (!IPCL_UDP_MATCH(connp, dstport,
2155 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2156 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2157 				connp = connp->conn_next;
2158 			}
2159 			if (connp != NULL)
2160 				CONN_INC_REF(connp);
2161 			mutex_exit(&connfp->connf_lock);
2162 			break;
2163 		}
2164 		case IPPROTO_SCTP:
2165 		{
2166 			in6_addr_t map_src, map_dst;
2167 
2168 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2169 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2170 			((uint16_t *)&ports)[0] = up[1];
2171 			((uint16_t *)&ports)[1] = up[0];
2172 
2173 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2174 			    zoneid, ipst->ips_netstack->netstack_sctp);
2175 			if (connp == NULL) {
2176 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2177 				    zoneid, ports, ipha, ipst);
2178 			} else {
2179 				CONN_INC_REF(connp);
2180 				SCTP_REFRELE(CONN2SCTP(connp));
2181 			}
2182 			break;
2183 		}
2184 		default:
2185 		{
2186 			ipha_t ripha;
2187 
2188 			ripha.ipha_src = ipha->ipha_dst;
2189 			ripha.ipha_dst = ipha->ipha_src;
2190 			ripha.ipha_protocol = ipha->ipha_protocol;
2191 
2192 			connfp = &ipst->ips_ipcl_proto_fanout[
2193 			    ipha->ipha_protocol];
2194 			mutex_enter(&connfp->connf_lock);
2195 			connp = connfp->connf_head;
2196 			for (connp = connfp->connf_head; connp != NULL;
2197 			    connp = connp->conn_next) {
2198 				if (IPCL_PROTO_MATCH(connp,
2199 				    ipha->ipha_protocol, &ripha, ill,
2200 				    0, zoneid)) {
2201 					CONN_INC_REF(connp);
2202 					break;
2203 				}
2204 			}
2205 			mutex_exit(&connfp->connf_lock);
2206 		}
2207 	}
2208 	if (connp != NULL) {
2209 		if (connp->conn_nexthop_set)
2210 			nexthop_addr = connp->conn_nexthop_v4;
2211 		CONN_DEC_REF(connp);
2212 	}
2213 	return (nexthop_addr);
2214 }
2215 
2216 /* Table from RFC 1191 */
2217 static int icmp_frag_size_table[] =
2218 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2219 
2220 /*
2221  * Process received ICMP Packet too big.
2222  * After updating any IRE it does the fanout to any matching transport streams.
2223  * Assumes the message has been pulled up till the IP header that caused
2224  * the error.
2225  *
2226  * Returns B_FALSE on failure and B_TRUE on success.
2227  */
2228 static boolean_t
2229 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2230     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2231     ip_stack_t *ipst)
2232 {
2233 	ire_t	*ire, *first_ire;
2234 	int	mtu, orig_mtu;
2235 	int	hdr_length;
2236 	ipaddr_t nexthop_addr;
2237 	boolean_t disable_pmtud;
2238 
2239 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2240 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2241 	ASSERT(ill != NULL);
2242 
2243 	hdr_length = IPH_HDR_LENGTH(ipha);
2244 
2245 	/* Drop if the original packet contained a source route */
2246 	if (ip_source_route_included(ipha)) {
2247 		return (B_FALSE);
2248 	}
2249 	/*
2250 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2251 	 * header.
2252 	 */
2253 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2254 	    mp->b_wptr) {
2255 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2256 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2257 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2258 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2259 			return (B_FALSE);
2260 		}
2261 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2262 		ipha = (ipha_t *)&icmph[1];
2263 	}
2264 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2265 	if (nexthop_addr != INADDR_ANY) {
2266 		/* nexthop set */
2267 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2268 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2269 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2270 	} else {
2271 		/* nexthop not set */
2272 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2273 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2274 	}
2275 
2276 	if (!first_ire) {
2277 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2278 		    ntohl(ipha->ipha_dst)));
2279 		return (B_FALSE);
2280 	}
2281 
2282 	/* Check for MTU discovery advice as described in RFC 1191 */
2283 	mtu = ntohs(icmph->icmph_du_mtu);
2284 	orig_mtu = mtu;
2285 	disable_pmtud = B_FALSE;
2286 
2287 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2288 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2289 	    ire = ire->ire_next) {
2290 		/*
2291 		 * Look for the connection to which this ICMP message is
2292 		 * directed. If it has the IP_NEXTHOP option set, then the
2293 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2294 		 * option. Else the search is limited to regular IREs.
2295 		 */
2296 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2297 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2298 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2299 		    (nexthop_addr != INADDR_ANY)))
2300 			continue;
2301 
2302 		mutex_enter(&ire->ire_lock);
2303 		if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
2304 			uint32_t length;
2305 			int	i;
2306 
2307 			/*
2308 			 * Use the table from RFC 1191 to figure out
2309 			 * the next "plateau" based on the length in
2310 			 * the original IP packet.
2311 			 */
2312 			length = ntohs(ipha->ipha_length);
2313 			DTRACE_PROBE2(ip4__pmtu__guess, ire_t *, ire,
2314 			    uint32_t, length);
2315 			if (ire->ire_max_frag <= length &&
2316 			    ire->ire_max_frag >= length - hdr_length) {
2317 				/*
2318 				 * Handle broken BSD 4.2 systems that
2319 				 * return the wrong iph_length in ICMP
2320 				 * errors.
2321 				 */
2322 				length -= hdr_length;
2323 			}
2324 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2325 				if (length > icmp_frag_size_table[i])
2326 					break;
2327 			}
2328 			if (i == A_CNT(icmp_frag_size_table)) {
2329 				/* Smaller than 68! */
2330 				disable_pmtud = B_TRUE;
2331 				mtu = ipst->ips_ip_pmtu_min;
2332 			} else {
2333 				mtu = icmp_frag_size_table[i];
2334 				if (mtu < ipst->ips_ip_pmtu_min) {
2335 					mtu = ipst->ips_ip_pmtu_min;
2336 					disable_pmtud = B_TRUE;
2337 				}
2338 			}
2339 			/* Fool the ULP into believing our guessed PMTU. */
2340 			icmph->icmph_du_zero = 0;
2341 			icmph->icmph_du_mtu = htons(mtu);
2342 		}
2343 		if (disable_pmtud)
2344 			ire->ire_frag_flag = 0;
2345 		/* Reduce the IRE max frag value as advised. */
2346 		ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2347 		mutex_exit(&ire->ire_lock);
2348 		DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, ire_t *,
2349 		    ire, int, orig_mtu, int, mtu);
2350 	}
2351 	rw_exit(&first_ire->ire_bucket->irb_lock);
2352 	ire_refrele(first_ire);
2353 	return (B_TRUE);
2354 }
2355 
2356 /*
2357  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2358  * calls this function.
2359  */
2360 static mblk_t *
2361 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2362 {
2363 	ipha_t *ipha;
2364 	icmph_t *icmph;
2365 	ipha_t *in_ipha;
2366 	int length;
2367 
2368 	ASSERT(mp->b_datap->db_type == M_DATA);
2369 
2370 	/*
2371 	 * For Self-encapsulated packets, we added an extra IP header
2372 	 * without the options. Inner IP header is the one from which
2373 	 * the outer IP header was formed. Thus, we need to remove the
2374 	 * outer IP header. To do this, we pullup the whole message
2375 	 * and overlay whatever follows the outer IP header over the
2376 	 * outer IP header.
2377 	 */
2378 
2379 	if (!pullupmsg(mp, -1))
2380 		return (NULL);
2381 
2382 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2383 	ipha = (ipha_t *)&icmph[1];
2384 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2385 
2386 	/*
2387 	 * The length that we want to overlay is following the inner
2388 	 * IP header. Subtracting the IP header + icmp header + outer
2389 	 * IP header's length should give us the length that we want to
2390 	 * overlay.
2391 	 */
2392 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2393 	    hdr_length;
2394 	/*
2395 	 * Overlay whatever follows the inner header over the
2396 	 * outer header.
2397 	 */
2398 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2399 
2400 	/* Set the wptr to account for the outer header */
2401 	mp->b_wptr -= hdr_length;
2402 	return (mp);
2403 }
2404 
2405 /*
2406  * Try to pass the ICMP message upstream in case the ULP cares.
2407  *
2408  * If the packet that caused the ICMP error is secure, we send
2409  * it to AH/ESP to make sure that the attached packet has a
2410  * valid association. ipha in the code below points to the
2411  * IP header of the packet that caused the error.
2412  *
2413  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2414  * in the context of IPsec. Normally we tell the upper layer
2415  * whenever we send the ire (including ip_bind), the IPsec header
2416  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2417  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2418  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2419  * same thing. As TCP has the IPsec options size that needs to be
2420  * adjusted, we just pass the MTU unchanged.
2421  *
2422  * IFN could have been generated locally or by some router.
2423  *
2424  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2425  *	    This happens because IP adjusted its value of MTU on an
2426  *	    earlier IFN message and could not tell the upper layer,
2427  *	    the new adjusted value of MTU e.g. Packet was encrypted
2428  *	    or there was not enough information to fanout to upper
2429  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2430  *	    generates the IFN, where IPsec processing has *not* been
2431  *	    done.
2432  *
2433  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2434  *	    could have generated this. This happens because ire_max_frag
2435  *	    value in IP was set to a new value, while the IPsec processing
2436  *	    was being done and after we made the fragmentation check in
2437  *	    ip_wput_ire. Thus on return from IPsec processing,
2438  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2439  *	    and generates the IFN. As IPsec processing is over, we fanout
2440  *	    to AH/ESP to remove the header.
2441  *
2442  *	    In both these cases, ipsec_in_loopback will be set indicating
2443  *	    that IFN was generated locally.
2444  *
2445  * ROUTER : IFN could be secure or non-secure.
2446  *
2447  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2448  *	      packet in error has AH/ESP headers to validate the AH/ESP
2449  *	      headers. AH/ESP will verify whether there is a valid SA or
2450  *	      not and send it back. We will fanout again if we have more
2451  *	      data in the packet.
2452  *
2453  *	      If the packet in error does not have AH/ESP, we handle it
2454  *	      like any other case.
2455  *
2456  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2457  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2458  *	      for validation. AH/ESP will verify whether there is a
2459  *	      valid SA or not and send it back. We will fanout again if
2460  *	      we have more data in the packet.
2461  *
2462  *	      If the packet in error does not have AH/ESP, we handle it
2463  *	      like any other case.
2464  */
2465 static void
2466 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2467     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2468     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2469     zoneid_t zoneid)
2470 {
2471 	uint16_t *up;	/* Pointer to ports in ULP header */
2472 	uint32_t ports;	/* reversed ports for fanout */
2473 	ipha_t ripha;	/* With reversed addresses */
2474 	mblk_t *first_mp;
2475 	ipsec_in_t *ii;
2476 	tcph_t	*tcph;
2477 	conn_t	*connp;
2478 	ip_stack_t *ipst;
2479 
2480 	ASSERT(ill != NULL);
2481 
2482 	ASSERT(recv_ill != NULL);
2483 	ipst = recv_ill->ill_ipst;
2484 
2485 	first_mp = mp;
2486 	if (mctl_present) {
2487 		mp = first_mp->b_cont;
2488 		ASSERT(mp != NULL);
2489 
2490 		ii = (ipsec_in_t *)first_mp->b_rptr;
2491 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2492 	} else {
2493 		ii = NULL;
2494 	}
2495 
2496 	switch (ipha->ipha_protocol) {
2497 	case IPPROTO_UDP:
2498 		/*
2499 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2500 		 * transport header.
2501 		 */
2502 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2503 		    mp->b_wptr) {
2504 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2505 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2506 				goto discard_pkt;
2507 			}
2508 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2509 			ipha = (ipha_t *)&icmph[1];
2510 		}
2511 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2512 
2513 		/*
2514 		 * Attempt to find a client stream based on port.
2515 		 * Note that we do a reverse lookup since the header is
2516 		 * in the form we sent it out.
2517 		 * The ripha header is only used for the IP_UDP_MATCH and we
2518 		 * only set the src and dst addresses and protocol.
2519 		 */
2520 		ripha.ipha_src = ipha->ipha_dst;
2521 		ripha.ipha_dst = ipha->ipha_src;
2522 		ripha.ipha_protocol = ipha->ipha_protocol;
2523 		((uint16_t *)&ports)[0] = up[1];
2524 		((uint16_t *)&ports)[1] = up[0];
2525 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2526 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2527 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2528 		    icmph->icmph_type, icmph->icmph_code));
2529 
2530 		/* Have to change db_type after any pullupmsg */
2531 		DB_TYPE(mp) = M_CTL;
2532 
2533 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2534 		    mctl_present, ip_policy, recv_ill, zoneid);
2535 		return;
2536 
2537 	case IPPROTO_TCP:
2538 		/*
2539 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2540 		 * transport header.
2541 		 */
2542 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2543 		    mp->b_wptr) {
2544 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2545 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2546 				goto discard_pkt;
2547 			}
2548 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2549 			ipha = (ipha_t *)&icmph[1];
2550 		}
2551 		/*
2552 		 * Find a TCP client stream for this packet.
2553 		 * Note that we do a reverse lookup since the header is
2554 		 * in the form we sent it out.
2555 		 */
2556 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2557 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2558 		    ipst);
2559 		if (connp == NULL)
2560 			goto discard_pkt;
2561 
2562 		/* Have to change db_type after any pullupmsg */
2563 		DB_TYPE(mp) = M_CTL;
2564 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, tcp_input, connp,
2565 		    SQ_FILL, SQTAG_TCP_INPUT_ICMP_ERR);
2566 		return;
2567 
2568 	case IPPROTO_SCTP:
2569 		/*
2570 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2571 		 * transport header.
2572 		 */
2573 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2574 		    mp->b_wptr) {
2575 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2576 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2577 				goto discard_pkt;
2578 			}
2579 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2580 			ipha = (ipha_t *)&icmph[1];
2581 		}
2582 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2583 		/*
2584 		 * Find a SCTP client stream for this packet.
2585 		 * Note that we do a reverse lookup since the header is
2586 		 * in the form we sent it out.
2587 		 * The ripha header is only used for the matching and we
2588 		 * only set the src and dst addresses, protocol, and version.
2589 		 */
2590 		ripha.ipha_src = ipha->ipha_dst;
2591 		ripha.ipha_dst = ipha->ipha_src;
2592 		ripha.ipha_protocol = ipha->ipha_protocol;
2593 		ripha.ipha_version_and_hdr_length =
2594 		    ipha->ipha_version_and_hdr_length;
2595 		((uint16_t *)&ports)[0] = up[1];
2596 		((uint16_t *)&ports)[1] = up[0];
2597 
2598 		/* Have to change db_type after any pullupmsg */
2599 		DB_TYPE(mp) = M_CTL;
2600 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2601 		    mctl_present, ip_policy, zoneid);
2602 		return;
2603 
2604 	case IPPROTO_ESP:
2605 	case IPPROTO_AH: {
2606 		int ipsec_rc;
2607 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2608 
2609 		/*
2610 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2611 		 * We will re-use the IPSEC_IN if it is already present as
2612 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2613 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2614 		 * one and attach it in the front.
2615 		 */
2616 		if (ii != NULL) {
2617 			/*
2618 			 * ip_fanout_proto_again converts the ICMP errors
2619 			 * that come back from AH/ESP to M_DATA so that
2620 			 * if it is non-AH/ESP and we do a pullupmsg in
2621 			 * this function, it would work. Convert it back
2622 			 * to M_CTL before we send up as this is a ICMP
2623 			 * error. This could have been generated locally or
2624 			 * by some router. Validate the inner IPsec
2625 			 * headers.
2626 			 *
2627 			 * NOTE : ill_index is used by ip_fanout_proto_again
2628 			 * to locate the ill.
2629 			 */
2630 			ASSERT(ill != NULL);
2631 			ii->ipsec_in_ill_index =
2632 			    ill->ill_phyint->phyint_ifindex;
2633 			ii->ipsec_in_rill_index =
2634 			    recv_ill->ill_phyint->phyint_ifindex;
2635 			DB_TYPE(first_mp->b_cont) = M_CTL;
2636 		} else {
2637 			/*
2638 			 * IPSEC_IN is not present. We attach a ipsec_in
2639 			 * message and send up to IPsec for validating
2640 			 * and removing the IPsec headers. Clear
2641 			 * ipsec_in_secure so that when we return
2642 			 * from IPsec, we don't mistakenly think that this
2643 			 * is a secure packet came from the network.
2644 			 *
2645 			 * NOTE : ill_index is used by ip_fanout_proto_again
2646 			 * to locate the ill.
2647 			 */
2648 			ASSERT(first_mp == mp);
2649 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2650 			if (first_mp == NULL) {
2651 				freemsg(mp);
2652 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2653 				return;
2654 			}
2655 			ii = (ipsec_in_t *)first_mp->b_rptr;
2656 
2657 			/* This is not a secure packet */
2658 			ii->ipsec_in_secure = B_FALSE;
2659 			first_mp->b_cont = mp;
2660 			DB_TYPE(mp) = M_CTL;
2661 			ASSERT(ill != NULL);
2662 			ii->ipsec_in_ill_index =
2663 			    ill->ill_phyint->phyint_ifindex;
2664 			ii->ipsec_in_rill_index =
2665 			    recv_ill->ill_phyint->phyint_ifindex;
2666 		}
2667 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2668 
2669 		if (!ipsec_loaded(ipss)) {
2670 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2671 			return;
2672 		}
2673 
2674 		if (ipha->ipha_protocol == IPPROTO_ESP)
2675 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2676 		else
2677 			ipsec_rc = ipsecah_icmp_error(first_mp);
2678 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2679 			return;
2680 
2681 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2682 		return;
2683 	}
2684 	default:
2685 		/*
2686 		 * The ripha header is only used for the lookup and we
2687 		 * only set the src and dst addresses and protocol.
2688 		 */
2689 		ripha.ipha_src = ipha->ipha_dst;
2690 		ripha.ipha_dst = ipha->ipha_src;
2691 		ripha.ipha_protocol = ipha->ipha_protocol;
2692 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2693 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2694 		    ntohl(ipha->ipha_dst),
2695 		    icmph->icmph_type, icmph->icmph_code));
2696 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2697 			ipha_t *in_ipha;
2698 
2699 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2700 			    mp->b_wptr) {
2701 				if (!pullupmsg(mp, (uchar_t *)ipha +
2702 				    hdr_length + sizeof (ipha_t) -
2703 				    mp->b_rptr)) {
2704 					goto discard_pkt;
2705 				}
2706 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2707 				ipha = (ipha_t *)&icmph[1];
2708 			}
2709 			/*
2710 			 * Caller has verified that length has to be
2711 			 * at least the size of IP header.
2712 			 */
2713 			ASSERT(hdr_length >= sizeof (ipha_t));
2714 			/*
2715 			 * Check the sanity of the inner IP header like
2716 			 * we did for the outer header.
2717 			 */
2718 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2719 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2720 				goto discard_pkt;
2721 			}
2722 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2723 				goto discard_pkt;
2724 			}
2725 			/* Check for Self-encapsulated tunnels */
2726 			if (in_ipha->ipha_src == ipha->ipha_src &&
2727 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2728 
2729 				mp = icmp_inbound_self_encap_error(mp,
2730 				    iph_hdr_length, hdr_length);
2731 				if (mp == NULL)
2732 					goto discard_pkt;
2733 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2734 				ipha = (ipha_t *)&icmph[1];
2735 				hdr_length = IPH_HDR_LENGTH(ipha);
2736 				/*
2737 				 * The packet in error is self-encapsualted.
2738 				 * And we are finding it further encapsulated
2739 				 * which we could not have possibly generated.
2740 				 */
2741 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2742 					goto discard_pkt;
2743 				}
2744 				icmp_inbound_error_fanout(q, ill, first_mp,
2745 				    icmph, ipha, iph_hdr_length, hdr_length,
2746 				    mctl_present, ip_policy, recv_ill, zoneid);
2747 				return;
2748 			}
2749 		}
2750 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2751 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2752 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2753 		    ii != NULL &&
2754 		    ii->ipsec_in_loopback &&
2755 		    ii->ipsec_in_secure) {
2756 			/*
2757 			 * For IP tunnels that get a looped-back
2758 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2759 			 * reported new MTU to take into account the IPsec
2760 			 * headers protecting this configured tunnel.
2761 			 *
2762 			 * This allows the tunnel module (tun.c) to blindly
2763 			 * accept the MTU reported in an ICMP "too big"
2764 			 * message.
2765 			 *
2766 			 * Non-looped back ICMP messages will just be
2767 			 * handled by the security protocols (if needed),
2768 			 * and the first subsequent packet will hit this
2769 			 * path.
2770 			 */
2771 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2772 			    ipsec_in_extra_length(first_mp));
2773 		}
2774 		/* Have to change db_type after any pullupmsg */
2775 		DB_TYPE(mp) = M_CTL;
2776 
2777 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2778 		    ip_policy, recv_ill, zoneid);
2779 		return;
2780 	}
2781 	/* NOTREACHED */
2782 discard_pkt:
2783 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2784 drop_pkt:;
2785 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2786 	freemsg(first_mp);
2787 }
2788 
2789 /*
2790  * Common IP options parser.
2791  *
2792  * Setup routine: fill in *optp with options-parsing state, then
2793  * tail-call ipoptp_next to return the first option.
2794  */
2795 uint8_t
2796 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2797 {
2798 	uint32_t totallen; /* total length of all options */
2799 
2800 	totallen = ipha->ipha_version_and_hdr_length -
2801 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2802 	totallen <<= 2;
2803 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2804 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2805 	optp->ipoptp_flags = 0;
2806 	return (ipoptp_next(optp));
2807 }
2808 
2809 /*
2810  * Common IP options parser: extract next option.
2811  */
2812 uint8_t
2813 ipoptp_next(ipoptp_t *optp)
2814 {
2815 	uint8_t *end = optp->ipoptp_end;
2816 	uint8_t *cur = optp->ipoptp_next;
2817 	uint8_t opt, len, pointer;
2818 
2819 	/*
2820 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2821 	 * has been corrupted.
2822 	 */
2823 	ASSERT(cur <= end);
2824 
2825 	if (cur == end)
2826 		return (IPOPT_EOL);
2827 
2828 	opt = cur[IPOPT_OPTVAL];
2829 
2830 	/*
2831 	 * Skip any NOP options.
2832 	 */
2833 	while (opt == IPOPT_NOP) {
2834 		cur++;
2835 		if (cur == end)
2836 			return (IPOPT_EOL);
2837 		opt = cur[IPOPT_OPTVAL];
2838 	}
2839 
2840 	if (opt == IPOPT_EOL)
2841 		return (IPOPT_EOL);
2842 
2843 	/*
2844 	 * Option requiring a length.
2845 	 */
2846 	if ((cur + 1) >= end) {
2847 		optp->ipoptp_flags |= IPOPTP_ERROR;
2848 		return (IPOPT_EOL);
2849 	}
2850 	len = cur[IPOPT_OLEN];
2851 	if (len < 2) {
2852 		optp->ipoptp_flags |= IPOPTP_ERROR;
2853 		return (IPOPT_EOL);
2854 	}
2855 	optp->ipoptp_cur = cur;
2856 	optp->ipoptp_len = len;
2857 	optp->ipoptp_next = cur + len;
2858 	if (cur + len > end) {
2859 		optp->ipoptp_flags |= IPOPTP_ERROR;
2860 		return (IPOPT_EOL);
2861 	}
2862 
2863 	/*
2864 	 * For the options which require a pointer field, make sure
2865 	 * its there, and make sure it points to either something
2866 	 * inside this option, or the end of the option.
2867 	 */
2868 	switch (opt) {
2869 	case IPOPT_RR:
2870 	case IPOPT_TS:
2871 	case IPOPT_LSRR:
2872 	case IPOPT_SSRR:
2873 		if (len <= IPOPT_OFFSET) {
2874 			optp->ipoptp_flags |= IPOPTP_ERROR;
2875 			return (opt);
2876 		}
2877 		pointer = cur[IPOPT_OFFSET];
2878 		if (pointer - 1 > len) {
2879 			optp->ipoptp_flags |= IPOPTP_ERROR;
2880 			return (opt);
2881 		}
2882 		break;
2883 	}
2884 
2885 	/*
2886 	 * Sanity check the pointer field based on the type of the
2887 	 * option.
2888 	 */
2889 	switch (opt) {
2890 	case IPOPT_RR:
2891 	case IPOPT_SSRR:
2892 	case IPOPT_LSRR:
2893 		if (pointer < IPOPT_MINOFF_SR)
2894 			optp->ipoptp_flags |= IPOPTP_ERROR;
2895 		break;
2896 	case IPOPT_TS:
2897 		if (pointer < IPOPT_MINOFF_IT)
2898 			optp->ipoptp_flags |= IPOPTP_ERROR;
2899 		/*
2900 		 * Note that the Internet Timestamp option also
2901 		 * contains two four bit fields (the Overflow field,
2902 		 * and the Flag field), which follow the pointer
2903 		 * field.  We don't need to check that these fields
2904 		 * fall within the length of the option because this
2905 		 * was implicitely done above.  We've checked that the
2906 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2907 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2908 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2909 		 */
2910 		ASSERT(len > IPOPT_POS_OV_FLG);
2911 		break;
2912 	}
2913 
2914 	return (opt);
2915 }
2916 
2917 /*
2918  * Use the outgoing IP header to create an IP_OPTIONS option the way
2919  * it was passed down from the application.
2920  */
2921 int
2922 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2923 {
2924 	ipoptp_t	opts;
2925 	const uchar_t	*opt;
2926 	uint8_t		optval;
2927 	uint8_t		optlen;
2928 	uint32_t	len = 0;
2929 	uchar_t	*buf1 = buf;
2930 
2931 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2932 	len += IP_ADDR_LEN;
2933 	bzero(buf1, IP_ADDR_LEN);
2934 
2935 	/*
2936 	 * OK to cast away const here, as we don't store through the returned
2937 	 * opts.ipoptp_cur pointer.
2938 	 */
2939 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2940 	    optval != IPOPT_EOL;
2941 	    optval = ipoptp_next(&opts)) {
2942 		int	off;
2943 
2944 		opt = opts.ipoptp_cur;
2945 		optlen = opts.ipoptp_len;
2946 		switch (optval) {
2947 		case IPOPT_SSRR:
2948 		case IPOPT_LSRR:
2949 
2950 			/*
2951 			 * Insert ipha_dst as the first entry in the source
2952 			 * route and move down the entries on step.
2953 			 * The last entry gets placed at buf1.
2954 			 */
2955 			buf[IPOPT_OPTVAL] = optval;
2956 			buf[IPOPT_OLEN] = optlen;
2957 			buf[IPOPT_OFFSET] = optlen;
2958 
2959 			off = optlen - IP_ADDR_LEN;
2960 			if (off < 0) {
2961 				/* No entries in source route */
2962 				break;
2963 			}
2964 			/* Last entry in source route */
2965 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2966 			off -= IP_ADDR_LEN;
2967 
2968 			while (off > 0) {
2969 				bcopy(opt + off,
2970 				    buf + off + IP_ADDR_LEN,
2971 				    IP_ADDR_LEN);
2972 				off -= IP_ADDR_LEN;
2973 			}
2974 			/* ipha_dst into first slot */
2975 			bcopy(&ipha->ipha_dst,
2976 			    buf + off + IP_ADDR_LEN,
2977 			    IP_ADDR_LEN);
2978 			buf += optlen;
2979 			len += optlen;
2980 			break;
2981 
2982 		case IPOPT_COMSEC:
2983 		case IPOPT_SECURITY:
2984 			/* if passing up a label is not ok, then remove */
2985 			if (is_system_labeled())
2986 				break;
2987 			/* FALLTHROUGH */
2988 		default:
2989 			bcopy(opt, buf, optlen);
2990 			buf += optlen;
2991 			len += optlen;
2992 			break;
2993 		}
2994 	}
2995 done:
2996 	/* Pad the resulting options */
2997 	while (len & 0x3) {
2998 		*buf++ = IPOPT_EOL;
2999 		len++;
3000 	}
3001 	return (len);
3002 }
3003 
3004 /*
3005  * Update any record route or timestamp options to include this host.
3006  * Reverse any source route option.
3007  * This routine assumes that the options are well formed i.e. that they
3008  * have already been checked.
3009  */
3010 static void
3011 icmp_options_update(ipha_t *ipha)
3012 {
3013 	ipoptp_t	opts;
3014 	uchar_t		*opt;
3015 	uint8_t		optval;
3016 	ipaddr_t	src;		/* Our local address */
3017 	ipaddr_t	dst;
3018 
3019 	ip2dbg(("icmp_options_update\n"));
3020 	src = ipha->ipha_src;
3021 	dst = ipha->ipha_dst;
3022 
3023 	for (optval = ipoptp_first(&opts, ipha);
3024 	    optval != IPOPT_EOL;
3025 	    optval = ipoptp_next(&opts)) {
3026 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3027 		opt = opts.ipoptp_cur;
3028 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3029 		    optval, opts.ipoptp_len));
3030 		switch (optval) {
3031 			int off1, off2;
3032 		case IPOPT_SSRR:
3033 		case IPOPT_LSRR:
3034 			/*
3035 			 * Reverse the source route.  The first entry
3036 			 * should be the next to last one in the current
3037 			 * source route (the last entry is our address).
3038 			 * The last entry should be the final destination.
3039 			 */
3040 			off1 = IPOPT_MINOFF_SR - 1;
3041 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3042 			if (off2 < 0) {
3043 				/* No entries in source route */
3044 				ip1dbg((
3045 				    "icmp_options_update: bad src route\n"));
3046 				break;
3047 			}
3048 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3049 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3050 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3051 			off2 -= IP_ADDR_LEN;
3052 
3053 			while (off1 < off2) {
3054 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3055 				bcopy((char *)opt + off2, (char *)opt + off1,
3056 				    IP_ADDR_LEN);
3057 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3058 				off1 += IP_ADDR_LEN;
3059 				off2 -= IP_ADDR_LEN;
3060 			}
3061 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3062 			break;
3063 		}
3064 	}
3065 }
3066 
3067 /*
3068  * Process received ICMP Redirect messages.
3069  */
3070 static void
3071 icmp_redirect(ill_t *ill, mblk_t *mp)
3072 {
3073 	ipha_t	*ipha;
3074 	int	iph_hdr_length;
3075 	icmph_t	*icmph;
3076 	ipha_t	*ipha_err;
3077 	ire_t	*ire;
3078 	ire_t	*prev_ire;
3079 	ire_t	*save_ire;
3080 	ipaddr_t  src, dst, gateway;
3081 	iulp_t	ulp_info = { 0 };
3082 	int	error;
3083 	ip_stack_t *ipst;
3084 
3085 	ASSERT(ill != NULL);
3086 	ipst = ill->ill_ipst;
3087 
3088 	ipha = (ipha_t *)mp->b_rptr;
3089 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3090 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3091 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3092 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3093 		freemsg(mp);
3094 		return;
3095 	}
3096 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3097 	ipha_err = (ipha_t *)&icmph[1];
3098 	src = ipha->ipha_src;
3099 	dst = ipha_err->ipha_dst;
3100 	gateway = icmph->icmph_rd_gateway;
3101 	/* Make sure the new gateway is reachable somehow. */
3102 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3103 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3104 	/*
3105 	 * Make sure we had a route for the dest in question and that
3106 	 * that route was pointing to the old gateway (the source of the
3107 	 * redirect packet.)
3108 	 */
3109 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3110 	    NULL, MATCH_IRE_GW, ipst);
3111 	/*
3112 	 * Check that
3113 	 *	the redirect was not from ourselves
3114 	 *	the new gateway and the old gateway are directly reachable
3115 	 */
3116 	if (!prev_ire ||
3117 	    !ire ||
3118 	    ire->ire_type == IRE_LOCAL) {
3119 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3120 		freemsg(mp);
3121 		if (ire != NULL)
3122 			ire_refrele(ire);
3123 		if (prev_ire != NULL)
3124 			ire_refrele(prev_ire);
3125 		return;
3126 	}
3127 
3128 	/*
3129 	 * Should we use the old ULP info to create the new gateway?  From
3130 	 * a user's perspective, we should inherit the info so that it
3131 	 * is a "smooth" transition.  If we do not do that, then new
3132 	 * connections going thru the new gateway will have no route metrics,
3133 	 * which is counter-intuitive to user.  From a network point of
3134 	 * view, this may or may not make sense even though the new gateway
3135 	 * is still directly connected to us so the route metrics should not
3136 	 * change much.
3137 	 *
3138 	 * But if the old ire_uinfo is not initialized, we do another
3139 	 * recursive lookup on the dest using the new gateway.  There may
3140 	 * be a route to that.  If so, use it to initialize the redirect
3141 	 * route.
3142 	 */
3143 	if (prev_ire->ire_uinfo.iulp_set) {
3144 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3145 	} else {
3146 		ire_t *tmp_ire;
3147 		ire_t *sire;
3148 
3149 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3150 		    ALL_ZONES, 0, NULL,
3151 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3152 		    ipst);
3153 		if (sire != NULL) {
3154 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3155 			/*
3156 			 * If sire != NULL, ire_ftable_lookup() should not
3157 			 * return a NULL value.
3158 			 */
3159 			ASSERT(tmp_ire != NULL);
3160 			ire_refrele(tmp_ire);
3161 			ire_refrele(sire);
3162 		} else if (tmp_ire != NULL) {
3163 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3164 			    sizeof (iulp_t));
3165 			ire_refrele(tmp_ire);
3166 		}
3167 	}
3168 	if (prev_ire->ire_type == IRE_CACHE)
3169 		ire_delete(prev_ire);
3170 	ire_refrele(prev_ire);
3171 	/*
3172 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3173 	 * require TOS routing
3174 	 */
3175 	switch (icmph->icmph_code) {
3176 	case 0:
3177 	case 1:
3178 		/* TODO: TOS specificity for cases 2 and 3 */
3179 	case 2:
3180 	case 3:
3181 		break;
3182 	default:
3183 		freemsg(mp);
3184 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3185 		ire_refrele(ire);
3186 		return;
3187 	}
3188 	/*
3189 	 * Create a Route Association.  This will allow us to remember that
3190 	 * someone we believe told us to use the particular gateway.
3191 	 */
3192 	save_ire = ire;
3193 	ire = ire_create(
3194 	    (uchar_t *)&dst,			/* dest addr */
3195 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3196 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3197 	    (uchar_t *)&gateway,		/* gateway addr */
3198 	    &save_ire->ire_max_frag,		/* max frag */
3199 	    NULL,				/* no src nce */
3200 	    NULL,				/* no rfq */
3201 	    NULL,				/* no stq */
3202 	    IRE_HOST,
3203 	    NULL,				/* ipif */
3204 	    0,					/* cmask */
3205 	    0,					/* phandle */
3206 	    0,					/* ihandle */
3207 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3208 	    &ulp_info,
3209 	    NULL,				/* tsol_gc_t */
3210 	    NULL,				/* gcgrp */
3211 	    ipst);
3212 
3213 	if (ire == NULL) {
3214 		freemsg(mp);
3215 		ire_refrele(save_ire);
3216 		return;
3217 	}
3218 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3219 	ire_refrele(save_ire);
3220 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3221 
3222 	if (error == 0) {
3223 		ire_refrele(ire);		/* Held in ire_add_v4 */
3224 		/* tell routing sockets that we received a redirect */
3225 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3226 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3227 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3228 	}
3229 
3230 	/*
3231 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3232 	 * This together with the added IRE has the effect of
3233 	 * modifying an existing redirect.
3234 	 */
3235 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3236 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3237 	if (prev_ire != NULL) {
3238 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3239 			ire_delete(prev_ire);
3240 		ire_refrele(prev_ire);
3241 	}
3242 
3243 	freemsg(mp);
3244 }
3245 
3246 /*
3247  * Generate an ICMP parameter problem message.
3248  */
3249 static void
3250 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3251 	ip_stack_t *ipst)
3252 {
3253 	icmph_t	icmph;
3254 	boolean_t mctl_present;
3255 	mblk_t *first_mp;
3256 
3257 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3258 
3259 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3260 		if (mctl_present)
3261 			freeb(first_mp);
3262 		return;
3263 	}
3264 
3265 	bzero(&icmph, sizeof (icmph_t));
3266 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3267 	icmph.icmph_pp_ptr = ptr;
3268 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3269 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3270 	    ipst);
3271 }
3272 
3273 /*
3274  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3275  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3276  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3277  * an icmp error packet can be sent.
3278  * Assigns an appropriate source address to the packet. If ipha_dst is
3279  * one of our addresses use it for source. Otherwise pick a source based
3280  * on a route lookup back to ipha_src.
3281  * Note that ipha_src must be set here since the
3282  * packet is likely to arrive on an ill queue in ip_wput() which will
3283  * not set a source address.
3284  */
3285 static void
3286 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3287     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3288 {
3289 	ipaddr_t dst;
3290 	icmph_t	*icmph;
3291 	ipha_t	*ipha;
3292 	uint_t	len_needed;
3293 	size_t	msg_len;
3294 	mblk_t	*mp1;
3295 	ipaddr_t src;
3296 	ire_t	*ire;
3297 	mblk_t *ipsec_mp;
3298 	ipsec_out_t	*io = NULL;
3299 
3300 	if (mctl_present) {
3301 		/*
3302 		 * If it is :
3303 		 *
3304 		 * 1) a IPSEC_OUT, then this is caused by outbound
3305 		 *    datagram originating on this host. IPsec processing
3306 		 *    may or may not have been done. Refer to comments above
3307 		 *    icmp_inbound_error_fanout for details.
3308 		 *
3309 		 * 2) a IPSEC_IN if we are generating a icmp_message
3310 		 *    for an incoming datagram destined for us i.e called
3311 		 *    from ip_fanout_send_icmp.
3312 		 */
3313 		ipsec_info_t *in;
3314 		ipsec_mp = mp;
3315 		mp = ipsec_mp->b_cont;
3316 
3317 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3318 		ipha = (ipha_t *)mp->b_rptr;
3319 
3320 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3321 		    in->ipsec_info_type == IPSEC_IN);
3322 
3323 		if (in->ipsec_info_type == IPSEC_IN) {
3324 			/*
3325 			 * Convert the IPSEC_IN to IPSEC_OUT.
3326 			 */
3327 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3328 				BUMP_MIB(&ipst->ips_ip_mib,
3329 				    ipIfStatsOutDiscards);
3330 				return;
3331 			}
3332 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3333 		} else {
3334 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3335 			io = (ipsec_out_t *)in;
3336 			/*
3337 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3338 			 * ire lookup.
3339 			 */
3340 			io->ipsec_out_proc_begin = B_FALSE;
3341 		}
3342 		ASSERT(zoneid == io->ipsec_out_zoneid);
3343 		ASSERT(zoneid != ALL_ZONES);
3344 	} else {
3345 		/*
3346 		 * This is in clear. The icmp message we are building
3347 		 * here should go out in clear.
3348 		 *
3349 		 * Pardon the convolution of it all, but it's easier to
3350 		 * allocate a "use cleartext" IPSEC_IN message and convert
3351 		 * it than it is to allocate a new one.
3352 		 */
3353 		ipsec_in_t *ii;
3354 		ASSERT(DB_TYPE(mp) == M_DATA);
3355 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3356 		if (ipsec_mp == NULL) {
3357 			freemsg(mp);
3358 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3359 			return;
3360 		}
3361 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3362 
3363 		/* This is not a secure packet */
3364 		ii->ipsec_in_secure = B_FALSE;
3365 		/*
3366 		 * For trusted extensions using a shared IP address we can
3367 		 * send using any zoneid.
3368 		 */
3369 		if (zoneid == ALL_ZONES)
3370 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3371 		else
3372 			ii->ipsec_in_zoneid = zoneid;
3373 		ipsec_mp->b_cont = mp;
3374 		ipha = (ipha_t *)mp->b_rptr;
3375 		/*
3376 		 * Convert the IPSEC_IN to IPSEC_OUT.
3377 		 */
3378 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3379 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3380 			return;
3381 		}
3382 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3383 	}
3384 
3385 	/* Remember our eventual destination */
3386 	dst = ipha->ipha_src;
3387 
3388 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3389 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3390 	if (ire != NULL &&
3391 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3392 		src = ipha->ipha_dst;
3393 	} else {
3394 		if (ire != NULL)
3395 			ire_refrele(ire);
3396 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3397 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3398 		    ipst);
3399 		if (ire == NULL) {
3400 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3401 			freemsg(ipsec_mp);
3402 			return;
3403 		}
3404 		src = ire->ire_src_addr;
3405 	}
3406 
3407 	if (ire != NULL)
3408 		ire_refrele(ire);
3409 
3410 	/*
3411 	 * Check if we can send back more then 8 bytes in addition to
3412 	 * the IP header.  We try to send 64 bytes of data and the internal
3413 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3414 	 */
3415 	len_needed = IPH_HDR_LENGTH(ipha);
3416 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3417 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3418 
3419 		if (!pullupmsg(mp, -1)) {
3420 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3421 			freemsg(ipsec_mp);
3422 			return;
3423 		}
3424 		ipha = (ipha_t *)mp->b_rptr;
3425 
3426 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3427 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3428 			    len_needed));
3429 		} else {
3430 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3431 
3432 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3433 			len_needed += ip_hdr_length_v6(mp, ip6h);
3434 		}
3435 	}
3436 	len_needed += ipst->ips_ip_icmp_return;
3437 	msg_len = msgdsize(mp);
3438 	if (msg_len > len_needed) {
3439 		(void) adjmsg(mp, len_needed - msg_len);
3440 		msg_len = len_needed;
3441 	}
3442 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3443 	if (mp1 == NULL) {
3444 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3445 		freemsg(ipsec_mp);
3446 		return;
3447 	}
3448 	mp1->b_cont = mp;
3449 	mp = mp1;
3450 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3451 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3452 	    io->ipsec_out_type == IPSEC_OUT);
3453 	ipsec_mp->b_cont = mp;
3454 
3455 	/*
3456 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3457 	 * node generates be accepted in peace by all on-host destinations.
3458 	 * If we do NOT assume that all on-host destinations trust
3459 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3460 	 * (Look for ipsec_out_icmp_loopback).
3461 	 */
3462 	io->ipsec_out_icmp_loopback = B_TRUE;
3463 
3464 	ipha = (ipha_t *)mp->b_rptr;
3465 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3466 	*ipha = icmp_ipha;
3467 	ipha->ipha_src = src;
3468 	ipha->ipha_dst = dst;
3469 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3470 	msg_len += sizeof (icmp_ipha) + len;
3471 	if (msg_len > IP_MAXPACKET) {
3472 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3473 		msg_len = IP_MAXPACKET;
3474 	}
3475 	ipha->ipha_length = htons((uint16_t)msg_len);
3476 	icmph = (icmph_t *)&ipha[1];
3477 	bcopy(stuff, icmph, len);
3478 	icmph->icmph_checksum = 0;
3479 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3480 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3481 	put(q, ipsec_mp);
3482 }
3483 
3484 /*
3485  * Determine if an ICMP error packet can be sent given the rate limit.
3486  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3487  * in milliseconds) and a burst size. Burst size number of packets can
3488  * be sent arbitrarely closely spaced.
3489  * The state is tracked using two variables to implement an approximate
3490  * token bucket filter:
3491  *	icmp_pkt_err_last - lbolt value when the last burst started
3492  *	icmp_pkt_err_sent - number of packets sent in current burst
3493  */
3494 boolean_t
3495 icmp_err_rate_limit(ip_stack_t *ipst)
3496 {
3497 	clock_t now = TICK_TO_MSEC(lbolt);
3498 	uint_t refilled; /* Number of packets refilled in tbf since last */
3499 	/* Guard against changes by loading into local variable */
3500 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3501 
3502 	if (err_interval == 0)
3503 		return (B_FALSE);
3504 
3505 	if (ipst->ips_icmp_pkt_err_last > now) {
3506 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3507 		ipst->ips_icmp_pkt_err_last = 0;
3508 		ipst->ips_icmp_pkt_err_sent = 0;
3509 	}
3510 	/*
3511 	 * If we are in a burst update the token bucket filter.
3512 	 * Update the "last" time to be close to "now" but make sure
3513 	 * we don't loose precision.
3514 	 */
3515 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3516 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3517 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3518 			ipst->ips_icmp_pkt_err_sent = 0;
3519 		} else {
3520 			ipst->ips_icmp_pkt_err_sent -= refilled;
3521 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3522 		}
3523 	}
3524 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3525 		/* Start of new burst */
3526 		ipst->ips_icmp_pkt_err_last = now;
3527 	}
3528 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3529 		ipst->ips_icmp_pkt_err_sent++;
3530 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3531 		    ipst->ips_icmp_pkt_err_sent));
3532 		return (B_FALSE);
3533 	}
3534 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3535 	return (B_TRUE);
3536 }
3537 
3538 /*
3539  * Check if it is ok to send an IPv4 ICMP error packet in
3540  * response to the IPv4 packet in mp.
3541  * Free the message and return null if no
3542  * ICMP error packet should be sent.
3543  */
3544 static mblk_t *
3545 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3546 {
3547 	icmph_t	*icmph;
3548 	ipha_t	*ipha;
3549 	uint_t	len_needed;
3550 	ire_t	*src_ire;
3551 	ire_t	*dst_ire;
3552 
3553 	if (!mp)
3554 		return (NULL);
3555 	ipha = (ipha_t *)mp->b_rptr;
3556 	if (ip_csum_hdr(ipha)) {
3557 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3558 		freemsg(mp);
3559 		return (NULL);
3560 	}
3561 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3562 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3563 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3564 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3565 	if (src_ire != NULL || dst_ire != NULL ||
3566 	    CLASSD(ipha->ipha_dst) ||
3567 	    CLASSD(ipha->ipha_src) ||
3568 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3569 		/* Note: only errors to the fragment with offset 0 */
3570 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3571 		freemsg(mp);
3572 		if (src_ire != NULL)
3573 			ire_refrele(src_ire);
3574 		if (dst_ire != NULL)
3575 			ire_refrele(dst_ire);
3576 		return (NULL);
3577 	}
3578 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3579 		/*
3580 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3581 		 * errors in response to any ICMP errors.
3582 		 */
3583 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3584 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3585 			if (!pullupmsg(mp, len_needed)) {
3586 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3587 				freemsg(mp);
3588 				return (NULL);
3589 			}
3590 			ipha = (ipha_t *)mp->b_rptr;
3591 		}
3592 		icmph = (icmph_t *)
3593 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3594 		switch (icmph->icmph_type) {
3595 		case ICMP_DEST_UNREACHABLE:
3596 		case ICMP_SOURCE_QUENCH:
3597 		case ICMP_TIME_EXCEEDED:
3598 		case ICMP_PARAM_PROBLEM:
3599 		case ICMP_REDIRECT:
3600 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3601 			freemsg(mp);
3602 			return (NULL);
3603 		default:
3604 			break;
3605 		}
3606 	}
3607 	/*
3608 	 * If this is a labeled system, then check to see if we're allowed to
3609 	 * send a response to this particular sender.  If not, then just drop.
3610 	 */
3611 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3612 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3613 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3614 		freemsg(mp);
3615 		return (NULL);
3616 	}
3617 	if (icmp_err_rate_limit(ipst)) {
3618 		/*
3619 		 * Only send ICMP error packets every so often.
3620 		 * This should be done on a per port/source basis,
3621 		 * but for now this will suffice.
3622 		 */
3623 		freemsg(mp);
3624 		return (NULL);
3625 	}
3626 	return (mp);
3627 }
3628 
3629 /*
3630  * Generate an ICMP redirect message.
3631  */
3632 static void
3633 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3634 {
3635 	icmph_t	icmph;
3636 
3637 	/*
3638 	 * We are called from ip_rput where we could
3639 	 * not have attached an IPSEC_IN.
3640 	 */
3641 	ASSERT(mp->b_datap->db_type == M_DATA);
3642 
3643 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3644 		return;
3645 	}
3646 
3647 	bzero(&icmph, sizeof (icmph_t));
3648 	icmph.icmph_type = ICMP_REDIRECT;
3649 	icmph.icmph_code = 1;
3650 	icmph.icmph_rd_gateway = gateway;
3651 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3652 	/* Redirects sent by router, and router is global zone */
3653 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3654 }
3655 
3656 /*
3657  * Generate an ICMP time exceeded message.
3658  */
3659 void
3660 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3661     ip_stack_t *ipst)
3662 {
3663 	icmph_t	icmph;
3664 	boolean_t mctl_present;
3665 	mblk_t *first_mp;
3666 
3667 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3668 
3669 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3670 		if (mctl_present)
3671 			freeb(first_mp);
3672 		return;
3673 	}
3674 
3675 	bzero(&icmph, sizeof (icmph_t));
3676 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3677 	icmph.icmph_code = code;
3678 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3679 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3680 	    ipst);
3681 }
3682 
3683 /*
3684  * Generate an ICMP unreachable message.
3685  */
3686 void
3687 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3688     ip_stack_t *ipst)
3689 {
3690 	icmph_t	icmph;
3691 	mblk_t *first_mp;
3692 	boolean_t mctl_present;
3693 
3694 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3695 
3696 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3697 		if (mctl_present)
3698 			freeb(first_mp);
3699 		return;
3700 	}
3701 
3702 	bzero(&icmph, sizeof (icmph_t));
3703 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3704 	icmph.icmph_code = code;
3705 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3706 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3707 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3708 	    zoneid, ipst);
3709 }
3710 
3711 /*
3712  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3713  * duplicate.  As long as someone else holds the address, the interface will
3714  * stay down.  When that conflict goes away, the interface is brought back up.
3715  * This is done so that accidental shutdowns of addresses aren't made
3716  * permanent.  Your server will recover from a failure.
3717  *
3718  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3719  * user space process (dhcpagent).
3720  *
3721  * Recovery completes if ARP reports that the address is now ours (via
3722  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3723  *
3724  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3725  */
3726 static void
3727 ipif_dup_recovery(void *arg)
3728 {
3729 	ipif_t *ipif = arg;
3730 	ill_t *ill = ipif->ipif_ill;
3731 	mblk_t *arp_add_mp;
3732 	mblk_t *arp_del_mp;
3733 	area_t *area;
3734 	ip_stack_t *ipst = ill->ill_ipst;
3735 
3736 	ipif->ipif_recovery_id = 0;
3737 
3738 	/*
3739 	 * No lock needed for moving or condemned check, as this is just an
3740 	 * optimization.
3741 	 */
3742 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3743 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3744 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3745 		/* No reason to try to bring this address back. */
3746 		return;
3747 	}
3748 
3749 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3750 		goto alloc_fail;
3751 
3752 	if (ipif->ipif_arp_del_mp == NULL) {
3753 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3754 			goto alloc_fail;
3755 		ipif->ipif_arp_del_mp = arp_del_mp;
3756 	}
3757 
3758 	/* Setting the 'unverified' flag restarts DAD */
3759 	area = (area_t *)arp_add_mp->b_rptr;
3760 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3761 	    ACE_F_UNVERIFIED;
3762 	putnext(ill->ill_rq, arp_add_mp);
3763 	return;
3764 
3765 alloc_fail:
3766 	/*
3767 	 * On allocation failure, just restart the timer.  Note that the ipif
3768 	 * is down here, so no other thread could be trying to start a recovery
3769 	 * timer.  The ill_lock protects the condemned flag and the recovery
3770 	 * timer ID.
3771 	 */
3772 	freemsg(arp_add_mp);
3773 	mutex_enter(&ill->ill_lock);
3774 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3775 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3776 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3777 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3778 	}
3779 	mutex_exit(&ill->ill_lock);
3780 }
3781 
3782 /*
3783  * This is for exclusive changes due to ARP.  Either tear down an interface due
3784  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3785  */
3786 /* ARGSUSED */
3787 static void
3788 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3789 {
3790 	ill_t	*ill = rq->q_ptr;
3791 	arh_t *arh;
3792 	ipaddr_t src;
3793 	ipif_t	*ipif;
3794 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3795 	char hbuf[MAC_STR_LEN];
3796 	char sbuf[INET_ADDRSTRLEN];
3797 	const char *failtype;
3798 	boolean_t bring_up;
3799 	ip_stack_t *ipst = ill->ill_ipst;
3800 
3801 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3802 	case AR_CN_READY:
3803 		failtype = NULL;
3804 		bring_up = B_TRUE;
3805 		break;
3806 	case AR_CN_FAILED:
3807 		failtype = "in use";
3808 		bring_up = B_FALSE;
3809 		break;
3810 	default:
3811 		failtype = "claimed";
3812 		bring_up = B_FALSE;
3813 		break;
3814 	}
3815 
3816 	arh = (arh_t *)mp->b_cont->b_rptr;
3817 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3818 
3819 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3820 	    sizeof (hbuf));
3821 	(void) ip_dot_addr(src, sbuf);
3822 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3823 
3824 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3825 		    ipif->ipif_lcl_addr != src) {
3826 			continue;
3827 		}
3828 
3829 		/*
3830 		 * If we failed on a recovery probe, then restart the timer to
3831 		 * try again later.
3832 		 */
3833 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3834 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3835 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3836 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3837 		    ipst->ips_ip_dup_recovery > 0 &&
3838 		    ipif->ipif_recovery_id == 0) {
3839 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3840 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3841 			continue;
3842 		}
3843 
3844 		/*
3845 		 * If what we're trying to do has already been done, then do
3846 		 * nothing.
3847 		 */
3848 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3849 			continue;
3850 
3851 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3852 
3853 		if (failtype == NULL) {
3854 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3855 			    ibuf);
3856 		} else {
3857 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3858 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3859 		}
3860 
3861 		if (bring_up) {
3862 			ASSERT(ill->ill_dl_up);
3863 			/*
3864 			 * Free up the ARP delete message so we can allocate
3865 			 * a fresh one through the normal path.
3866 			 */
3867 			freemsg(ipif->ipif_arp_del_mp);
3868 			ipif->ipif_arp_del_mp = NULL;
3869 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3870 			    EINPROGRESS) {
3871 				ipif->ipif_addr_ready = 1;
3872 				(void) ipif_up_done(ipif);
3873 			}
3874 			continue;
3875 		}
3876 
3877 		mutex_enter(&ill->ill_lock);
3878 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3879 		ipif->ipif_flags |= IPIF_DUPLICATE;
3880 		ill->ill_ipif_dup_count++;
3881 		mutex_exit(&ill->ill_lock);
3882 		/*
3883 		 * Already exclusive on the ill; no need to handle deferred
3884 		 * processing here.
3885 		 */
3886 		(void) ipif_down(ipif, NULL, NULL);
3887 		ipif_down_tail(ipif);
3888 		mutex_enter(&ill->ill_lock);
3889 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3890 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3891 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3892 		    ipst->ips_ip_dup_recovery > 0) {
3893 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3894 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3895 		}
3896 		mutex_exit(&ill->ill_lock);
3897 	}
3898 	freemsg(mp);
3899 }
3900 
3901 /* ARGSUSED */
3902 static void
3903 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3904 {
3905 	ill_t	*ill = rq->q_ptr;
3906 	arh_t *arh;
3907 	ipaddr_t src;
3908 	ipif_t	*ipif;
3909 
3910 	arh = (arh_t *)mp->b_cont->b_rptr;
3911 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3912 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3913 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3914 			(void) ipif_resolver_up(ipif, Res_act_defend);
3915 	}
3916 	freemsg(mp);
3917 }
3918 
3919 /*
3920  * News from ARP.  ARP sends notification of interesting events down
3921  * to its clients using M_CTL messages with the interesting ARP packet
3922  * attached via b_cont.
3923  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3924  * queue as opposed to ARP sending the message to all the clients, i.e. all
3925  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3926  * table if a cache IRE is found to delete all the entries for the address in
3927  * the packet.
3928  */
3929 static void
3930 ip_arp_news(queue_t *q, mblk_t *mp)
3931 {
3932 	arcn_t		*arcn;
3933 	arh_t		*arh;
3934 	ire_t		*ire = NULL;
3935 	char		hbuf[MAC_STR_LEN];
3936 	char		sbuf[INET_ADDRSTRLEN];
3937 	ipaddr_t	src;
3938 	in6_addr_t	v6src;
3939 	boolean_t	isv6 = B_FALSE;
3940 	ipif_t		*ipif;
3941 	ill_t		*ill;
3942 	ip_stack_t	*ipst;
3943 
3944 	if (CONN_Q(q)) {
3945 		conn_t *connp = Q_TO_CONN(q);
3946 
3947 		ipst = connp->conn_netstack->netstack_ip;
3948 	} else {
3949 		ill_t *ill = (ill_t *)q->q_ptr;
3950 
3951 		ipst = ill->ill_ipst;
3952 	}
3953 
3954 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3955 		if (q->q_next) {
3956 			putnext(q, mp);
3957 		} else
3958 			freemsg(mp);
3959 		return;
3960 	}
3961 	arh = (arh_t *)mp->b_cont->b_rptr;
3962 	/* Is it one we are interested in? */
3963 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3964 		isv6 = B_TRUE;
3965 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3966 		    IPV6_ADDR_LEN);
3967 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3968 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3969 		    IP_ADDR_LEN);
3970 	} else {
3971 		freemsg(mp);
3972 		return;
3973 	}
3974 
3975 	ill = q->q_ptr;
3976 
3977 	arcn = (arcn_t *)mp->b_rptr;
3978 	switch (arcn->arcn_code) {
3979 	case AR_CN_BOGON:
3980 		/*
3981 		 * Someone is sending ARP packets with a source protocol
3982 		 * address that we have published and for which we believe our
3983 		 * entry is authoritative and (when ill_arp_extend is set)
3984 		 * verified to be unique on the network.
3985 		 *
3986 		 * The ARP module internally handles the cases where the sender
3987 		 * is just probing (for DAD) and where the hardware address of
3988 		 * a non-authoritative entry has changed.  Thus, these are the
3989 		 * real conflicts, and we have to do resolution.
3990 		 *
3991 		 * We back away quickly from the address if it's from DHCP or
3992 		 * otherwise temporary and hasn't been used recently (or at
3993 		 * all).  We'd like to include "deprecated" addresses here as
3994 		 * well (as there's no real reason to defend something we're
3995 		 * discarding), but IPMP "reuses" this flag to mean something
3996 		 * other than the standard meaning.
3997 		 *
3998 		 * If the ARP module above is not extended (meaning that it
3999 		 * doesn't know how to defend the address), then we just log
4000 		 * the problem as we always did and continue on.  It's not
4001 		 * right, but there's little else we can do, and those old ATM
4002 		 * users are going away anyway.
4003 		 */
4004 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4005 		    hbuf, sizeof (hbuf));
4006 		(void) ip_dot_addr(src, sbuf);
4007 		if (isv6) {
4008 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4009 			    ipst);
4010 		} else {
4011 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4012 		}
4013 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4014 			uint32_t now;
4015 			uint32_t maxage;
4016 			clock_t lused;
4017 			uint_t maxdefense;
4018 			uint_t defs;
4019 
4020 			/*
4021 			 * First, figure out if this address hasn't been used
4022 			 * in a while.  If it hasn't, then it's a better
4023 			 * candidate for abandoning.
4024 			 */
4025 			ipif = ire->ire_ipif;
4026 			ASSERT(ipif != NULL);
4027 			now = gethrestime_sec();
4028 			maxage = now - ire->ire_create_time;
4029 			if (maxage > ipst->ips_ip_max_temp_idle)
4030 				maxage = ipst->ips_ip_max_temp_idle;
4031 			lused = drv_hztousec(ddi_get_lbolt() -
4032 			    ire->ire_last_used_time) / MICROSEC + 1;
4033 			if (lused >= maxage && (ipif->ipif_flags &
4034 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4035 				maxdefense = ipst->ips_ip_max_temp_defend;
4036 			else
4037 				maxdefense = ipst->ips_ip_max_defend;
4038 
4039 			/*
4040 			 * Now figure out how many times we've defended
4041 			 * ourselves.  Ignore defenses that happened long in
4042 			 * the past.
4043 			 */
4044 			mutex_enter(&ire->ire_lock);
4045 			if ((defs = ire->ire_defense_count) > 0 &&
4046 			    now - ire->ire_defense_time >
4047 			    ipst->ips_ip_defend_interval) {
4048 				ire->ire_defense_count = defs = 0;
4049 			}
4050 			ire->ire_defense_count++;
4051 			ire->ire_defense_time = now;
4052 			mutex_exit(&ire->ire_lock);
4053 			ill_refhold(ill);
4054 			ire_refrele(ire);
4055 
4056 			/*
4057 			 * If we've defended ourselves too many times already,
4058 			 * then give up and tear down the interface(s) using
4059 			 * this address.  Otherwise, defend by sending out a
4060 			 * gratuitous ARP.
4061 			 */
4062 			if (defs >= maxdefense && ill->ill_arp_extend) {
4063 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4064 				    B_FALSE);
4065 			} else {
4066 				cmn_err(CE_WARN,
4067 				    "node %s is using our IP address %s on %s",
4068 				    hbuf, sbuf, ill->ill_name);
4069 				/*
4070 				 * If this is an old (ATM) ARP module, then
4071 				 * don't try to defend the address.  Remain
4072 				 * compatible with the old behavior.  Defend
4073 				 * only with new ARP.
4074 				 */
4075 				if (ill->ill_arp_extend) {
4076 					qwriter_ip(ill, q, mp, ip_arp_defend,
4077 					    NEW_OP, B_FALSE);
4078 				} else {
4079 					ill_refrele(ill);
4080 				}
4081 			}
4082 			return;
4083 		}
4084 		cmn_err(CE_WARN,
4085 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4086 		    hbuf, sbuf, ill->ill_name);
4087 		if (ire != NULL)
4088 			ire_refrele(ire);
4089 		break;
4090 	case AR_CN_ANNOUNCE:
4091 		if (isv6) {
4092 			/*
4093 			 * For XRESOLV interfaces.
4094 			 * Delete the IRE cache entry and NCE for this
4095 			 * v6 address
4096 			 */
4097 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4098 			/*
4099 			 * If v6src is a non-zero, it's a router address
4100 			 * as below. Do the same sort of thing to clean
4101 			 * out off-net IRE_CACHE entries that go through
4102 			 * the router.
4103 			 */
4104 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4105 				ire_walk_v6(ire_delete_cache_gw_v6,
4106 				    (char *)&v6src, ALL_ZONES, ipst);
4107 			}
4108 		} else {
4109 			nce_hw_map_t hwm;
4110 
4111 			/*
4112 			 * ARP gives us a copy of any packet where it thinks
4113 			 * the address has changed, so that we can update our
4114 			 * caches.  We're responsible for caching known answers
4115 			 * in the current design.  We check whether the
4116 			 * hardware address really has changed in all of our
4117 			 * entries that have cached this mapping, and if so, we
4118 			 * blow them away.  This way we will immediately pick
4119 			 * up the rare case of a host changing hardware
4120 			 * address.
4121 			 */
4122 			if (src == 0)
4123 				break;
4124 			hwm.hwm_addr = src;
4125 			hwm.hwm_hwlen = arh->arh_hlen;
4126 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4127 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4128 			ndp_walk_common(ipst->ips_ndp4, NULL,
4129 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4130 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4131 		}
4132 		break;
4133 	case AR_CN_READY:
4134 		/* No external v6 resolver has a contract to use this */
4135 		if (isv6)
4136 			break;
4137 		/* If the link is down, we'll retry this later */
4138 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4139 			break;
4140 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4141 		    NULL, NULL, ipst);
4142 		if (ipif != NULL) {
4143 			/*
4144 			 * If this is a duplicate recovery, then we now need to
4145 			 * go exclusive to bring this thing back up.
4146 			 */
4147 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4148 			    IPIF_DUPLICATE) {
4149 				ipif_refrele(ipif);
4150 				ill_refhold(ill);
4151 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4152 				    B_FALSE);
4153 				return;
4154 			}
4155 			/*
4156 			 * If this is the first notice that this address is
4157 			 * ready, then let the user know now.
4158 			 */
4159 			if ((ipif->ipif_flags & IPIF_UP) &&
4160 			    !ipif->ipif_addr_ready) {
4161 				ipif_mask_reply(ipif);
4162 				ipif_up_notify(ipif);
4163 			}
4164 			ipif->ipif_addr_ready = 1;
4165 			ipif_refrele(ipif);
4166 		}
4167 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4168 		if (ire != NULL) {
4169 			ire->ire_defense_count = 0;
4170 			ire_refrele(ire);
4171 		}
4172 		break;
4173 	case AR_CN_FAILED:
4174 		/* No external v6 resolver has a contract to use this */
4175 		if (isv6)
4176 			break;
4177 		ill_refhold(ill);
4178 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4179 		return;
4180 	}
4181 	freemsg(mp);
4182 }
4183 
4184 /*
4185  * Create a mblk suitable for carrying the interface index and/or source link
4186  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4187  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4188  * application.
4189  */
4190 mblk_t *
4191 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4192     ip_stack_t *ipst)
4193 {
4194 	mblk_t		*mp;
4195 	ip_pktinfo_t	*pinfo;
4196 	ipha_t *ipha;
4197 	struct ether_header *pether;
4198 
4199 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4200 	if (mp == NULL) {
4201 		ip1dbg(("ip_add_info: allocation failure.\n"));
4202 		return (data_mp);
4203 	}
4204 
4205 	ipha	= (ipha_t *)data_mp->b_rptr;
4206 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4207 	bzero(pinfo, sizeof (ip_pktinfo_t));
4208 	pinfo->ip_pkt_flags = (uchar_t)flags;
4209 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4210 
4211 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4212 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4213 	if (flags & IPF_RECVADDR) {
4214 		ipif_t	*ipif;
4215 		ire_t	*ire;
4216 
4217 		/*
4218 		 * Only valid for V4
4219 		 */
4220 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4221 		    (IPV4_VERSION << 4));
4222 
4223 		ipif = ipif_get_next_ipif(NULL, ill);
4224 		if (ipif != NULL) {
4225 			/*
4226 			 * Since a decision has already been made to deliver the
4227 			 * packet, there is no need to test for SECATTR and
4228 			 * ZONEONLY.
4229 			 * When a multicast packet is transmitted
4230 			 * a cache entry is created for the multicast address.
4231 			 * When delivering a copy of the packet or when new
4232 			 * packets are received we do not want to match on the
4233 			 * cached entry so explicitly match on
4234 			 * IRE_LOCAL and IRE_LOOPBACK
4235 			 */
4236 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4237 			    IRE_LOCAL | IRE_LOOPBACK,
4238 			    ipif, zoneid, NULL,
4239 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4240 			if (ire == NULL) {
4241 				/*
4242 				 * packet must have come on a different
4243 				 * interface.
4244 				 * Since a decision has already been made to
4245 				 * deliver the packet, there is no need to test
4246 				 * for SECATTR and ZONEONLY.
4247 				 * Only match on local and broadcast ire's.
4248 				 * See detailed comment above.
4249 				 */
4250 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4251 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4252 				    NULL, MATCH_IRE_TYPE, ipst);
4253 			}
4254 
4255 			if (ire == NULL) {
4256 				/*
4257 				 * This is either a multicast packet or
4258 				 * the address has been removed since
4259 				 * the packet was received.
4260 				 * Return INADDR_ANY so that normal source
4261 				 * selection occurs for the response.
4262 				 */
4263 
4264 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4265 			} else {
4266 				pinfo->ip_pkt_match_addr.s_addr =
4267 				    ire->ire_src_addr;
4268 				ire_refrele(ire);
4269 			}
4270 			ipif_refrele(ipif);
4271 		} else {
4272 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4273 		}
4274 	}
4275 
4276 	pether = (struct ether_header *)((char *)ipha
4277 	    - sizeof (struct ether_header));
4278 	/*
4279 	 * Make sure the interface is an ethernet type, since this option
4280 	 * is currently supported only on this type of interface. Also make
4281 	 * sure we are pointing correctly above db_base.
4282 	 */
4283 
4284 	if ((flags & IPF_RECVSLLA) &&
4285 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4286 	    (ill->ill_type == IFT_ETHER) &&
4287 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4288 
4289 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4290 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4291 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4292 	} else {
4293 		/*
4294 		 * Clear the bit. Indicate to upper layer that IP is not
4295 		 * sending this ancillary info.
4296 		 */
4297 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4298 	}
4299 
4300 	mp->b_datap->db_type = M_CTL;
4301 	mp->b_wptr += sizeof (ip_pktinfo_t);
4302 	mp->b_cont = data_mp;
4303 
4304 	return (mp);
4305 }
4306 
4307 /*
4308  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4309  * part of the bind request.
4310  */
4311 
4312 boolean_t
4313 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4314 {
4315 	ipsec_in_t *ii;
4316 
4317 	ASSERT(policy_mp != NULL);
4318 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4319 
4320 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4321 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4322 
4323 	connp->conn_policy = ii->ipsec_in_policy;
4324 	ii->ipsec_in_policy = NULL;
4325 
4326 	if (ii->ipsec_in_action != NULL) {
4327 		if (connp->conn_latch == NULL) {
4328 			connp->conn_latch = iplatch_create();
4329 			if (connp->conn_latch == NULL)
4330 				return (B_FALSE);
4331 		}
4332 		ipsec_latch_inbound(connp->conn_latch, ii);
4333 	}
4334 	return (B_TRUE);
4335 }
4336 
4337 /*
4338  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4339  * and to arrange for power-fanout assist.  The ULP is identified by
4340  * adding a single byte at the end of the original bind message.
4341  * A ULP other than UDP or TCP that wishes to be recognized passes
4342  * down a bind with a zero length address.
4343  *
4344  * The binding works as follows:
4345  * - A zero byte address means just bind to the protocol.
4346  * - A four byte address is treated as a request to validate
4347  *   that the address is a valid local address, appropriate for
4348  *   an application to bind to. This does not affect any fanout
4349  *   information in IP.
4350  * - A sizeof sin_t byte address is used to bind to only the local address
4351  *   and port.
4352  * - A sizeof ipa_conn_t byte address contains complete fanout information
4353  *   consisting of local and remote addresses and ports.  In
4354  *   this case, the addresses are both validated as appropriate
4355  *   for this operation, and, if so, the information is retained
4356  *   for use in the inbound fanout.
4357  *
4358  * The ULP (except in the zero-length bind) can append an
4359  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4360  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4361  * a copy of the source or destination IRE (source for local bind;
4362  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4363  * policy information contained should be copied on to the conn.
4364  *
4365  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4366  */
4367 mblk_t *
4368 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4369 {
4370 	ssize_t		len;
4371 	struct T_bind_req	*tbr;
4372 	sin_t		*sin;
4373 	ipa_conn_t	*ac;
4374 	uchar_t		*ucp;
4375 	mblk_t		*mp1;
4376 	boolean_t	ire_requested;
4377 	boolean_t	ipsec_policy_set = B_FALSE;
4378 	int		error = 0;
4379 	int		protocol;
4380 	ipa_conn_x_t	*acx;
4381 
4382 	ASSERT(!connp->conn_af_isv6);
4383 	connp->conn_pkt_isv6 = B_FALSE;
4384 
4385 	len = MBLKL(mp);
4386 	if (len < (sizeof (*tbr) + 1)) {
4387 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4388 		    "ip_bind: bogus msg, len %ld", len);
4389 		/* XXX: Need to return something better */
4390 		goto bad_addr;
4391 	}
4392 	/* Back up and extract the protocol identifier. */
4393 	mp->b_wptr--;
4394 	protocol = *mp->b_wptr & 0xFF;
4395 	tbr = (struct T_bind_req *)mp->b_rptr;
4396 	/* Reset the message type in preparation for shipping it back. */
4397 	DB_TYPE(mp) = M_PCPROTO;
4398 
4399 	connp->conn_ulp = (uint8_t)protocol;
4400 
4401 	/*
4402 	 * Check for a zero length address.  This is from a protocol that
4403 	 * wants to register to receive all packets of its type.
4404 	 */
4405 	if (tbr->ADDR_length == 0) {
4406 		/*
4407 		 * These protocols are now intercepted in ip_bind_v6().
4408 		 * Reject protocol-level binds here for now.
4409 		 *
4410 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4411 		 * so that the protocol type cannot be SCTP.
4412 		 */
4413 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4414 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4415 			goto bad_addr;
4416 		}
4417 
4418 		/*
4419 		 *
4420 		 * The udp module never sends down a zero-length address,
4421 		 * and allowing this on a labeled system will break MLP
4422 		 * functionality.
4423 		 */
4424 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4425 			goto bad_addr;
4426 
4427 		if (connp->conn_mac_exempt)
4428 			goto bad_addr;
4429 
4430 		/* No hash here really.  The table is big enough. */
4431 		connp->conn_srcv6 = ipv6_all_zeros;
4432 
4433 		ipcl_proto_insert(connp, protocol);
4434 
4435 		tbr->PRIM_type = T_BIND_ACK;
4436 		return (mp);
4437 	}
4438 
4439 	/* Extract the address pointer from the message. */
4440 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4441 	    tbr->ADDR_length);
4442 	if (ucp == NULL) {
4443 		ip1dbg(("ip_bind: no address\n"));
4444 		goto bad_addr;
4445 	}
4446 	if (!OK_32PTR(ucp)) {
4447 		ip1dbg(("ip_bind: unaligned address\n"));
4448 		goto bad_addr;
4449 	}
4450 	/*
4451 	 * Check for trailing mps.
4452 	 */
4453 
4454 	mp1 = mp->b_cont;
4455 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4456 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4457 
4458 	switch (tbr->ADDR_length) {
4459 	default:
4460 		ip1dbg(("ip_bind: bad address length %d\n",
4461 		    (int)tbr->ADDR_length));
4462 		goto bad_addr;
4463 
4464 	case IP_ADDR_LEN:
4465 		/* Verification of local address only */
4466 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4467 		    ire_requested, ipsec_policy_set, B_FALSE);
4468 		break;
4469 
4470 	case sizeof (sin_t):
4471 		sin = (sin_t *)ucp;
4472 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4473 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4474 		break;
4475 
4476 	case sizeof (ipa_conn_t):
4477 		ac = (ipa_conn_t *)ucp;
4478 		/* For raw socket, the local port is not set. */
4479 		if (ac->ac_lport == 0)
4480 			ac->ac_lport = connp->conn_lport;
4481 		/* Always verify destination reachability. */
4482 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4483 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4484 		    ipsec_policy_set, B_TRUE, B_TRUE);
4485 		break;
4486 
4487 	case sizeof (ipa_conn_x_t):
4488 		acx = (ipa_conn_x_t *)ucp;
4489 		/*
4490 		 * Whether or not to verify destination reachability depends
4491 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4492 		 */
4493 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4494 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4495 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4496 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4497 		break;
4498 	}
4499 	if (error == EINPROGRESS)
4500 		return (NULL);
4501 	else if (error != 0)
4502 		goto bad_addr;
4503 	/*
4504 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4505 	 * We can't do this in ip_bind_insert_ire because the policy
4506 	 * may not have been inherited at that point in time and hence
4507 	 * conn_out_enforce_policy may not be set.
4508 	 */
4509 	mp1 = mp->b_cont;
4510 	if (ire_requested && connp->conn_out_enforce_policy &&
4511 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4512 		ire_t *ire = (ire_t *)mp1->b_rptr;
4513 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4514 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4515 	}
4516 
4517 	/* Send it home. */
4518 	mp->b_datap->db_type = M_PCPROTO;
4519 	tbr->PRIM_type = T_BIND_ACK;
4520 	return (mp);
4521 
4522 bad_addr:
4523 	/*
4524 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4525 	 * a unix errno.
4526 	 */
4527 	if (error > 0)
4528 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4529 	else
4530 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4531 	return (mp);
4532 }
4533 
4534 /*
4535  * Here address is verified to be a valid local address.
4536  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4537  * address is also considered a valid local address.
4538  * In the case of a broadcast/multicast address, however, the
4539  * upper protocol is expected to reset the src address
4540  * to 0 if it sees a IRE_BROADCAST type returned so that
4541  * no packets are emitted with broadcast/multicast address as
4542  * source address (that violates hosts requirements RFC1122)
4543  * The addresses valid for bind are:
4544  *	(1) - INADDR_ANY (0)
4545  *	(2) - IP address of an UP interface
4546  *	(3) - IP address of a DOWN interface
4547  *	(4) - valid local IP broadcast addresses. In this case
4548  *	the conn will only receive packets destined to
4549  *	the specified broadcast address.
4550  *	(5) - a multicast address. In this case
4551  *	the conn will only receive packets destined to
4552  *	the specified multicast address. Note: the
4553  *	application still has to issue an
4554  *	IP_ADD_MEMBERSHIP socket option.
4555  *
4556  * On error, return -1 for TBADADDR otherwise pass the
4557  * errno with TSYSERR reply.
4558  *
4559  * In all the above cases, the bound address must be valid in the current zone.
4560  * When the address is loopback, multicast or broadcast, there might be many
4561  * matching IREs so bind has to look up based on the zone.
4562  *
4563  * Note: lport is in network byte order.
4564  */
4565 int
4566 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4567     boolean_t ire_requested, boolean_t ipsec_policy_set,
4568     boolean_t fanout_insert)
4569 {
4570 	int		error = 0;
4571 	ire_t		*src_ire;
4572 	mblk_t		*policy_mp;
4573 	ipif_t		*ipif;
4574 	zoneid_t	zoneid;
4575 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4576 
4577 	if (ipsec_policy_set) {
4578 		policy_mp = mp->b_cont;
4579 	}
4580 
4581 	/*
4582 	 * If it was previously connected, conn_fully_bound would have
4583 	 * been set.
4584 	 */
4585 	connp->conn_fully_bound = B_FALSE;
4586 
4587 	src_ire = NULL;
4588 	ipif = NULL;
4589 
4590 	zoneid = IPCL_ZONEID(connp);
4591 
4592 	if (src_addr) {
4593 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4594 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4595 		/*
4596 		 * If an address other than 0.0.0.0 is requested,
4597 		 * we verify that it is a valid address for bind
4598 		 * Note: Following code is in if-else-if form for
4599 		 * readability compared to a condition check.
4600 		 */
4601 		/* LINTED - statement has no consequent */
4602 		if (IRE_IS_LOCAL(src_ire)) {
4603 			/*
4604 			 * (2) Bind to address of local UP interface
4605 			 */
4606 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4607 			/*
4608 			 * (4) Bind to broadcast address
4609 			 * Note: permitted only from transports that
4610 			 * request IRE
4611 			 */
4612 			if (!ire_requested)
4613 				error = EADDRNOTAVAIL;
4614 		} else {
4615 			/*
4616 			 * (3) Bind to address of local DOWN interface
4617 			 * (ipif_lookup_addr() looks up all interfaces
4618 			 * but we do not get here for UP interfaces
4619 			 * - case (2) above)
4620 			 * We put the protocol byte back into the mblk
4621 			 * since we may come back via ip_wput_nondata()
4622 			 * later with this mblk if ipif_lookup_addr chooses
4623 			 * to defer processing.
4624 			 */
4625 			*mp->b_wptr++ = (char)connp->conn_ulp;
4626 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4627 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4628 			    &error, ipst)) != NULL) {
4629 				ipif_refrele(ipif);
4630 			} else if (error == EINPROGRESS) {
4631 				if (src_ire != NULL)
4632 					ire_refrele(src_ire);
4633 				return (EINPROGRESS);
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 			 * Just to keep it consistent with the processing in
4658 			 * ip_bind_v4()
4659 			 */
4660 			mp->b_wptr--;
4661 		}
4662 		if (error) {
4663 			/* Red Alert!  Attempting to be a bogon! */
4664 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4665 			    ntohl(src_addr)));
4666 			goto bad_addr;
4667 		}
4668 	}
4669 
4670 	/*
4671 	 * Allow setting new policies. For example, disconnects come
4672 	 * down as ipa_t bind. As we would have set conn_policy_cached
4673 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4674 	 * can change after the disconnect.
4675 	 */
4676 	connp->conn_policy_cached = B_FALSE;
4677 
4678 	/*
4679 	 * If not fanout_insert this was just an address verification
4680 	 */
4681 	if (fanout_insert) {
4682 		/*
4683 		 * The addresses have been verified. Time to insert in
4684 		 * the correct fanout list.
4685 		 */
4686 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4687 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4688 		connp->conn_lport = lport;
4689 		connp->conn_fport = 0;
4690 		/*
4691 		 * Do we need to add a check to reject Multicast packets
4692 		 */
4693 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4694 	}
4695 
4696 	if (error == 0) {
4697 		if (ire_requested) {
4698 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4699 				error = -1;
4700 				/* Falls through to bad_addr */
4701 			}
4702 		} else if (ipsec_policy_set) {
4703 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4704 				error = -1;
4705 				/* Falls through to bad_addr */
4706 			}
4707 		}
4708 	}
4709 bad_addr:
4710 	if (error != 0) {
4711 		if (connp->conn_anon_port) {
4712 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4713 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4714 			    B_FALSE);
4715 		}
4716 		connp->conn_mlp_type = mlptSingle;
4717 	}
4718 	if (src_ire != NULL)
4719 		IRE_REFRELE(src_ire);
4720 	if (ipsec_policy_set) {
4721 		ASSERT(policy_mp == mp->b_cont);
4722 		ASSERT(policy_mp != NULL);
4723 		freeb(policy_mp);
4724 		/*
4725 		 * As of now assume that nothing else accompanies
4726 		 * IPSEC_POLICY_SET.
4727 		 */
4728 		mp->b_cont = NULL;
4729 	}
4730 	return (error);
4731 }
4732 
4733 /*
4734  * Verify that both the source and destination addresses
4735  * are valid.  If verify_dst is false, then the destination address may be
4736  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4737  * destination reachability, while tunnels do not.
4738  * Note that we allow connect to broadcast and multicast
4739  * addresses when ire_requested is set. Thus the ULP
4740  * has to check for IRE_BROADCAST and multicast.
4741  *
4742  * Returns zero if ok.
4743  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4744  * (for use with TSYSERR reply).
4745  *
4746  * Note: lport and fport are in network byte order.
4747  */
4748 int
4749 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4750     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4751     boolean_t ire_requested, boolean_t ipsec_policy_set,
4752     boolean_t fanout_insert, boolean_t verify_dst)
4753 {
4754 	ire_t		*src_ire;
4755 	ire_t		*dst_ire;
4756 	int		error = 0;
4757 	int 		protocol;
4758 	mblk_t		*policy_mp;
4759 	ire_t		*sire = NULL;
4760 	ire_t		*md_dst_ire = NULL;
4761 	ire_t		*lso_dst_ire = NULL;
4762 	ill_t		*ill = NULL;
4763 	zoneid_t	zoneid;
4764 	ipaddr_t	src_addr = *src_addrp;
4765 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4766 
4767 	src_ire = dst_ire = NULL;
4768 	protocol = *mp->b_wptr & 0xFF;
4769 
4770 	/*
4771 	 * If we never got a disconnect before, clear it now.
4772 	 */
4773 	connp->conn_fully_bound = B_FALSE;
4774 
4775 	if (ipsec_policy_set) {
4776 		policy_mp = mp->b_cont;
4777 	}
4778 
4779 	zoneid = IPCL_ZONEID(connp);
4780 
4781 	if (CLASSD(dst_addr)) {
4782 		/* Pick up an IRE_BROADCAST */
4783 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4784 		    NULL, zoneid, MBLK_GETLABEL(mp),
4785 		    (MATCH_IRE_RECURSIVE |
4786 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4787 		    MATCH_IRE_SECATTR), ipst);
4788 	} else {
4789 		/*
4790 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4791 		 * and onlink ipif is not found set ENETUNREACH error.
4792 		 */
4793 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4794 			ipif_t *ipif;
4795 
4796 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4797 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4798 			if (ipif == NULL) {
4799 				error = ENETUNREACH;
4800 				goto bad_addr;
4801 			}
4802 			ipif_refrele(ipif);
4803 		}
4804 
4805 		if (connp->conn_nexthop_set) {
4806 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4807 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4808 			    MATCH_IRE_SECATTR, ipst);
4809 		} else {
4810 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4811 			    &sire, zoneid, MBLK_GETLABEL(mp),
4812 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4813 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4814 			    MATCH_IRE_SECATTR), ipst);
4815 		}
4816 	}
4817 	/*
4818 	 * dst_ire can't be a broadcast when not ire_requested.
4819 	 * We also prevent ire's with src address INADDR_ANY to
4820 	 * be used, which are created temporarily for
4821 	 * sending out packets from endpoints that have
4822 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4823 	 * reachable.  If verify_dst is false, the destination needn't be
4824 	 * reachable.
4825 	 *
4826 	 * If we match on a reject or black hole, then we've got a
4827 	 * local failure.  May as well fail out the connect() attempt,
4828 	 * since it's never going to succeed.
4829 	 */
4830 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4831 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4832 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4833 		/*
4834 		 * If we're verifying destination reachability, we always want
4835 		 * to complain here.
4836 		 *
4837 		 * If we're not verifying destination reachability but the
4838 		 * destination has a route, we still want to fail on the
4839 		 * temporary address and broadcast address tests.
4840 		 */
4841 		if (verify_dst || (dst_ire != NULL)) {
4842 			if (ip_debug > 2) {
4843 				pr_addr_dbg("ip_bind_connected: bad connected "
4844 				    "dst %s\n", AF_INET, &dst_addr);
4845 			}
4846 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4847 				error = ENETUNREACH;
4848 			else
4849 				error = EHOSTUNREACH;
4850 			goto bad_addr;
4851 		}
4852 	}
4853 
4854 	/*
4855 	 * We now know that routing will allow us to reach the destination.
4856 	 * Check whether Trusted Solaris policy allows communication with this
4857 	 * host, and pretend that the destination is unreachable if not.
4858 	 *
4859 	 * This is never a problem for TCP, since that transport is known to
4860 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4861 	 * handling.  If the remote is unreachable, it will be detected at that
4862 	 * point, so there's no reason to check it here.
4863 	 *
4864 	 * Note that for sendto (and other datagram-oriented friends), this
4865 	 * check is done as part of the data path label computation instead.
4866 	 * The check here is just to make non-TCP connect() report the right
4867 	 * error.
4868 	 */
4869 	if (dst_ire != NULL && is_system_labeled() &&
4870 	    !IPCL_IS_TCP(connp) &&
4871 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4872 	    connp->conn_mac_exempt, ipst) != 0) {
4873 		error = EHOSTUNREACH;
4874 		if (ip_debug > 2) {
4875 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4876 			    AF_INET, &dst_addr);
4877 		}
4878 		goto bad_addr;
4879 	}
4880 
4881 	/*
4882 	 * If the app does a connect(), it means that it will most likely
4883 	 * send more than 1 packet to the destination.  It makes sense
4884 	 * to clear the temporary flag.
4885 	 */
4886 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4887 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4888 		irb_t *irb = dst_ire->ire_bucket;
4889 
4890 		rw_enter(&irb->irb_lock, RW_WRITER);
4891 		/*
4892 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4893 		 * the lock to guarantee irb_tmp_ire_cnt.
4894 		 */
4895 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4896 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4897 			irb->irb_tmp_ire_cnt--;
4898 		}
4899 		rw_exit(&irb->irb_lock);
4900 	}
4901 
4902 	/*
4903 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4904 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4905 	 * eligibility tests for passive connects are handled separately
4906 	 * through tcp_adapt_ire().  We do this before the source address
4907 	 * selection, because dst_ire may change after a call to
4908 	 * ipif_select_source().  This is a best-effort check, as the
4909 	 * packet for this connection may not actually go through
4910 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4911 	 * calling ip_newroute().  This is why we further check on the
4912 	 * IRE during LSO/Multidata packet transmission in
4913 	 * tcp_lsosend()/tcp_multisend().
4914 	 */
4915 	if (!ipsec_policy_set && dst_ire != NULL &&
4916 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4917 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4918 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4919 			lso_dst_ire = dst_ire;
4920 			IRE_REFHOLD(lso_dst_ire);
4921 		} else if (ipst->ips_ip_multidata_outbound &&
4922 		    ILL_MDT_CAPABLE(ill)) {
4923 			md_dst_ire = dst_ire;
4924 			IRE_REFHOLD(md_dst_ire);
4925 		}
4926 	}
4927 
4928 	if (dst_ire != NULL &&
4929 	    dst_ire->ire_type == IRE_LOCAL &&
4930 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4931 		/*
4932 		 * If the IRE belongs to a different zone, look for a matching
4933 		 * route in the forwarding table and use the source address from
4934 		 * that route.
4935 		 */
4936 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4937 		    zoneid, 0, NULL,
4938 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4939 		    MATCH_IRE_RJ_BHOLE, ipst);
4940 		if (src_ire == NULL) {
4941 			error = EHOSTUNREACH;
4942 			goto bad_addr;
4943 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4944 			if (!(src_ire->ire_type & IRE_HOST))
4945 				error = ENETUNREACH;
4946 			else
4947 				error = EHOSTUNREACH;
4948 			goto bad_addr;
4949 		}
4950 		if (src_addr == INADDR_ANY)
4951 			src_addr = src_ire->ire_src_addr;
4952 		ire_refrele(src_ire);
4953 		src_ire = NULL;
4954 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4955 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4956 			src_addr = sire->ire_src_addr;
4957 			ire_refrele(dst_ire);
4958 			dst_ire = sire;
4959 			sire = NULL;
4960 		} else {
4961 			/*
4962 			 * Pick a source address so that a proper inbound
4963 			 * load spreading would happen.
4964 			 */
4965 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4966 			ipif_t *src_ipif = NULL;
4967 			ire_t *ipif_ire;
4968 
4969 			/*
4970 			 * Supply a local source address such that inbound
4971 			 * load spreading happens.
4972 			 *
4973 			 * Determine the best source address on this ill for
4974 			 * the destination.
4975 			 *
4976 			 * 1) For broadcast, we should return a broadcast ire
4977 			 *    found above so that upper layers know that the
4978 			 *    destination address is a broadcast address.
4979 			 *
4980 			 * 2) If this is part of a group, select a better
4981 			 *    source address so that better inbound load
4982 			 *    balancing happens. Do the same if the ipif
4983 			 *    is DEPRECATED.
4984 			 *
4985 			 * 3) If the outgoing interface is part of a usesrc
4986 			 *    group, then try selecting a source address from
4987 			 *    the usesrc ILL.
4988 			 */
4989 			if ((dst_ire->ire_zoneid != zoneid &&
4990 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4991 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4992 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4993 			    ((dst_ill->ill_group != NULL) ||
4994 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4995 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4996 				/*
4997 				 * If the destination is reachable via a
4998 				 * given gateway, the selected source address
4999 				 * should be in the same subnet as the gateway.
5000 				 * Otherwise, the destination is not reachable.
5001 				 *
5002 				 * If there are no interfaces on the same subnet
5003 				 * as the destination, ipif_select_source gives
5004 				 * first non-deprecated interface which might be
5005 				 * on a different subnet than the gateway.
5006 				 * This is not desirable. Hence pass the dst_ire
5007 				 * source address to ipif_select_source.
5008 				 * It is sure that the destination is reachable
5009 				 * with the dst_ire source address subnet.
5010 				 * So passing dst_ire source address to
5011 				 * ipif_select_source will make sure that the
5012 				 * selected source will be on the same subnet
5013 				 * as dst_ire source address.
5014 				 */
5015 				ipaddr_t saddr =
5016 				    dst_ire->ire_ipif->ipif_src_addr;
5017 				src_ipif = ipif_select_source(dst_ill,
5018 				    saddr, zoneid);
5019 				if (src_ipif != NULL) {
5020 					if (IS_VNI(src_ipif->ipif_ill)) {
5021 						/*
5022 						 * For VNI there is no
5023 						 * interface route
5024 						 */
5025 						src_addr =
5026 						    src_ipif->ipif_src_addr;
5027 					} else {
5028 						ipif_ire =
5029 						    ipif_to_ire(src_ipif);
5030 						if (ipif_ire != NULL) {
5031 							IRE_REFRELE(dst_ire);
5032 							dst_ire = ipif_ire;
5033 						}
5034 						src_addr =
5035 						    dst_ire->ire_src_addr;
5036 					}
5037 					ipif_refrele(src_ipif);
5038 				} else {
5039 					src_addr = dst_ire->ire_src_addr;
5040 				}
5041 			} else {
5042 				src_addr = dst_ire->ire_src_addr;
5043 			}
5044 		}
5045 	}
5046 
5047 	/*
5048 	 * We do ire_route_lookup() here (and not
5049 	 * interface lookup as we assert that
5050 	 * src_addr should only come from an
5051 	 * UP interface for hard binding.
5052 	 */
5053 	ASSERT(src_ire == NULL);
5054 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5055 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5056 	/* src_ire must be a local|loopback */
5057 	if (!IRE_IS_LOCAL(src_ire)) {
5058 		if (ip_debug > 2) {
5059 			pr_addr_dbg("ip_bind_connected: bad connected "
5060 			    "src %s\n", AF_INET, &src_addr);
5061 		}
5062 		error = EADDRNOTAVAIL;
5063 		goto bad_addr;
5064 	}
5065 
5066 	/*
5067 	 * If the source address is a loopback address, the
5068 	 * destination had best be local or multicast.
5069 	 * The transports that can't handle multicast will reject
5070 	 * those addresses.
5071 	 */
5072 	if (src_ire->ire_type == IRE_LOOPBACK &&
5073 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5074 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5075 		error = -1;
5076 		goto bad_addr;
5077 	}
5078 
5079 	/*
5080 	 * Allow setting new policies. For example, disconnects come
5081 	 * down as ipa_t bind. As we would have set conn_policy_cached
5082 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5083 	 * can change after the disconnect.
5084 	 */
5085 	connp->conn_policy_cached = B_FALSE;
5086 
5087 	/*
5088 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5089 	 * can handle their passed-in conn's.
5090 	 */
5091 
5092 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5093 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5094 	connp->conn_lport = lport;
5095 	connp->conn_fport = fport;
5096 	*src_addrp = src_addr;
5097 
5098 	ASSERT(!(ipsec_policy_set && ire_requested));
5099 	if (ire_requested) {
5100 		iulp_t *ulp_info = NULL;
5101 
5102 		/*
5103 		 * Note that sire will not be NULL if this is an off-link
5104 		 * connection and there is not cache for that dest yet.
5105 		 *
5106 		 * XXX Because of an existing bug, if there are multiple
5107 		 * default routes, the IRE returned now may not be the actual
5108 		 * default route used (default routes are chosen in a
5109 		 * round robin fashion).  So if the metrics for different
5110 		 * default routes are different, we may return the wrong
5111 		 * metrics.  This will not be a problem if the existing
5112 		 * bug is fixed.
5113 		 */
5114 		if (sire != NULL) {
5115 			ulp_info = &(sire->ire_uinfo);
5116 		}
5117 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5118 			error = -1;
5119 			goto bad_addr;
5120 		}
5121 	} else if (ipsec_policy_set) {
5122 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5123 			error = -1;
5124 			goto bad_addr;
5125 		}
5126 	}
5127 
5128 	/*
5129 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5130 	 * we'll cache that.  If we don't, we'll inherit global policy.
5131 	 *
5132 	 * We can't insert until the conn reflects the policy. Note that
5133 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5134 	 * connections where we don't have a policy. This is to prevent
5135 	 * global policy lookups in the inbound path.
5136 	 *
5137 	 * If we insert before we set conn_policy_cached,
5138 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5139 	 * because global policy cound be non-empty. We normally call
5140 	 * ipsec_check_policy() for conn_policy_cached connections only if
5141 	 * ipc_in_enforce_policy is set. But in this case,
5142 	 * conn_policy_cached can get set anytime since we made the
5143 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5144 	 * called, which will make the above assumption false.  Thus, we
5145 	 * need to insert after we set conn_policy_cached.
5146 	 */
5147 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5148 		goto bad_addr;
5149 
5150 	if (fanout_insert) {
5151 		/*
5152 		 * The addresses have been verified. Time to insert in
5153 		 * the correct fanout list.
5154 		 */
5155 		error = ipcl_conn_insert(connp, protocol, src_addr,
5156 		    dst_addr, connp->conn_ports);
5157 	}
5158 
5159 	if (error == 0) {
5160 		connp->conn_fully_bound = B_TRUE;
5161 		/*
5162 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5163 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5164 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5165 		 * ip_xxinfo_return(), which performs further checks
5166 		 * against them and upon success, returns the LSO/MDT info
5167 		 * mblk which we will attach to the bind acknowledgment.
5168 		 */
5169 		if (lso_dst_ire != NULL) {
5170 			mblk_t *lsoinfo_mp;
5171 
5172 			ASSERT(ill->ill_lso_capab != NULL);
5173 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5174 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5175 				linkb(mp, lsoinfo_mp);
5176 		} else if (md_dst_ire != NULL) {
5177 			mblk_t *mdinfo_mp;
5178 
5179 			ASSERT(ill->ill_mdt_capab != NULL);
5180 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5181 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5182 				linkb(mp, mdinfo_mp);
5183 		}
5184 	}
5185 bad_addr:
5186 	if (ipsec_policy_set) {
5187 		ASSERT(policy_mp == mp->b_cont);
5188 		ASSERT(policy_mp != NULL);
5189 		freeb(policy_mp);
5190 		/*
5191 		 * As of now assume that nothing else accompanies
5192 		 * IPSEC_POLICY_SET.
5193 		 */
5194 		mp->b_cont = NULL;
5195 	}
5196 	if (src_ire != NULL)
5197 		IRE_REFRELE(src_ire);
5198 	if (dst_ire != NULL)
5199 		IRE_REFRELE(dst_ire);
5200 	if (sire != NULL)
5201 		IRE_REFRELE(sire);
5202 	if (md_dst_ire != NULL)
5203 		IRE_REFRELE(md_dst_ire);
5204 	if (lso_dst_ire != NULL)
5205 		IRE_REFRELE(lso_dst_ire);
5206 	return (error);
5207 }
5208 
5209 /*
5210  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5211  * Prefers dst_ire over src_ire.
5212  */
5213 static boolean_t
5214 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5215 {
5216 	mblk_t	*mp1;
5217 	ire_t *ret_ire = NULL;
5218 
5219 	mp1 = mp->b_cont;
5220 	ASSERT(mp1 != NULL);
5221 
5222 	if (ire != NULL) {
5223 		/*
5224 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5225 		 * appended mblk. Its <upper protocol>'s
5226 		 * job to make sure there is room.
5227 		 */
5228 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5229 			return (0);
5230 
5231 		mp1->b_datap->db_type = IRE_DB_TYPE;
5232 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5233 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5234 		ret_ire = (ire_t *)mp1->b_rptr;
5235 		/*
5236 		 * Pass the latest setting of the ip_path_mtu_discovery and
5237 		 * copy the ulp info if any.
5238 		 */
5239 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5240 		    IPH_DF : 0;
5241 		if (ulp_info != NULL) {
5242 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5243 			    sizeof (iulp_t));
5244 		}
5245 		ret_ire->ire_mp = mp1;
5246 	} else {
5247 		/*
5248 		 * No IRE was found. Remove IRE mblk.
5249 		 */
5250 		mp->b_cont = mp1->b_cont;
5251 		freeb(mp1);
5252 	}
5253 
5254 	return (1);
5255 }
5256 
5257 /*
5258  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5259  * the final piece where we don't.  Return a pointer to the first mblk in the
5260  * result, and update the pointer to the next mblk to chew on.  If anything
5261  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5262  * NULL pointer.
5263  */
5264 mblk_t *
5265 ip_carve_mp(mblk_t **mpp, ssize_t len)
5266 {
5267 	mblk_t	*mp0;
5268 	mblk_t	*mp1;
5269 	mblk_t	*mp2;
5270 
5271 	if (!len || !mpp || !(mp0 = *mpp))
5272 		return (NULL);
5273 	/* If we aren't going to consume the first mblk, we need a dup. */
5274 	if (mp0->b_wptr - mp0->b_rptr > len) {
5275 		mp1 = dupb(mp0);
5276 		if (mp1) {
5277 			/* Partition the data between the two mblks. */
5278 			mp1->b_wptr = mp1->b_rptr + len;
5279 			mp0->b_rptr = mp1->b_wptr;
5280 			/*
5281 			 * after adjustments if mblk not consumed is now
5282 			 * unaligned, try to align it. If this fails free
5283 			 * all messages and let upper layer recover.
5284 			 */
5285 			if (!OK_32PTR(mp0->b_rptr)) {
5286 				if (!pullupmsg(mp0, -1)) {
5287 					freemsg(mp0);
5288 					freemsg(mp1);
5289 					*mpp = NULL;
5290 					return (NULL);
5291 				}
5292 			}
5293 		}
5294 		return (mp1);
5295 	}
5296 	/* Eat through as many mblks as we need to get len bytes. */
5297 	len -= mp0->b_wptr - mp0->b_rptr;
5298 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5299 		if (mp2->b_wptr - mp2->b_rptr > len) {
5300 			/*
5301 			 * We won't consume the entire last mblk.  Like
5302 			 * above, dup and partition it.
5303 			 */
5304 			mp1->b_cont = dupb(mp2);
5305 			mp1 = mp1->b_cont;
5306 			if (!mp1) {
5307 				/*
5308 				 * Trouble.  Rather than go to a lot of
5309 				 * trouble to clean up, we free the messages.
5310 				 * This won't be any worse than losing it on
5311 				 * the wire.
5312 				 */
5313 				freemsg(mp0);
5314 				freemsg(mp2);
5315 				*mpp = NULL;
5316 				return (NULL);
5317 			}
5318 			mp1->b_wptr = mp1->b_rptr + len;
5319 			mp2->b_rptr = mp1->b_wptr;
5320 			/*
5321 			 * after adjustments if mblk not consumed is now
5322 			 * unaligned, try to align it. If this fails free
5323 			 * all messages and let upper layer recover.
5324 			 */
5325 			if (!OK_32PTR(mp2->b_rptr)) {
5326 				if (!pullupmsg(mp2, -1)) {
5327 					freemsg(mp0);
5328 					freemsg(mp2);
5329 					*mpp = NULL;
5330 					return (NULL);
5331 				}
5332 			}
5333 			*mpp = mp2;
5334 			return (mp0);
5335 		}
5336 		/* Decrement len by the amount we just got. */
5337 		len -= mp2->b_wptr - mp2->b_rptr;
5338 	}
5339 	/*
5340 	 * len should be reduced to zero now.  If not our caller has
5341 	 * screwed up.
5342 	 */
5343 	if (len) {
5344 		/* Shouldn't happen! */
5345 		freemsg(mp0);
5346 		*mpp = NULL;
5347 		return (NULL);
5348 	}
5349 	/*
5350 	 * We consumed up to exactly the end of an mblk.  Detach the part
5351 	 * we are returning from the rest of the chain.
5352 	 */
5353 	mp1->b_cont = NULL;
5354 	*mpp = mp2;
5355 	return (mp0);
5356 }
5357 
5358 /* The ill stream is being unplumbed. Called from ip_close */
5359 int
5360 ip_modclose(ill_t *ill)
5361 {
5362 	boolean_t success;
5363 	ipsq_t	*ipsq;
5364 	ipif_t	*ipif;
5365 	queue_t	*q = ill->ill_rq;
5366 	ip_stack_t	*ipst = ill->ill_ipst;
5367 
5368 	/*
5369 	 * The punlink prior to this may have initiated a capability
5370 	 * negotiation. But ipsq_enter will block until that finishes or
5371 	 * times out.
5372 	 */
5373 	success = ipsq_enter(ill, B_FALSE, NEW_OP);
5374 
5375 	/*
5376 	 * Open/close/push/pop is guaranteed to be single threaded
5377 	 * per stream by STREAMS. FS guarantees that all references
5378 	 * from top are gone before close is called. So there can't
5379 	 * be another close thread that has set CONDEMNED on this ill.
5380 	 * and cause ipsq_enter to return failure.
5381 	 */
5382 	ASSERT(success);
5383 	ipsq = ill->ill_phyint->phyint_ipsq;
5384 
5385 	/*
5386 	 * Mark it condemned. No new reference will be made to this ill.
5387 	 * Lookup functions will return an error. Threads that try to
5388 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5389 	 * that the refcnt will drop down to zero.
5390 	 */
5391 	mutex_enter(&ill->ill_lock);
5392 	ill->ill_state_flags |= ILL_CONDEMNED;
5393 	for (ipif = ill->ill_ipif; ipif != NULL;
5394 	    ipif = ipif->ipif_next) {
5395 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5396 	}
5397 	/*
5398 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5399 	 * returns  error if ILL_CONDEMNED is set
5400 	 */
5401 	cv_broadcast(&ill->ill_cv);
5402 	mutex_exit(&ill->ill_lock);
5403 
5404 	/*
5405 	 * Send all the deferred DLPI messages downstream which came in
5406 	 * during the small window right before ipsq_enter(). We do this
5407 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5408 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5409 	 */
5410 	ill_dlpi_send_deferred(ill);
5411 
5412 	/*
5413 	 * Shut down fragmentation reassembly.
5414 	 * ill_frag_timer won't start a timer again.
5415 	 * Now cancel any existing timer
5416 	 */
5417 	(void) untimeout(ill->ill_frag_timer_id);
5418 	(void) ill_frag_timeout(ill, 0);
5419 
5420 	/*
5421 	 * If MOVE was in progress, clear the
5422 	 * move_in_progress fields also.
5423 	 */
5424 	if (ill->ill_move_in_progress) {
5425 		ILL_CLEAR_MOVE(ill);
5426 	}
5427 
5428 	/*
5429 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5430 	 * this ill. Then wait for the refcnts to drop to zero.
5431 	 * ill_is_freeable checks whether the ill is really quiescent.
5432 	 * Then make sure that threads that are waiting to enter the
5433 	 * ipsq have seen the error returned by ipsq_enter and have
5434 	 * gone away. Then we call ill_delete_tail which does the
5435 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5436 	 */
5437 	ill_delete(ill);
5438 	mutex_enter(&ill->ill_lock);
5439 	while (!ill_is_freeable(ill))
5440 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5441 	while (ill->ill_waiters)
5442 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5443 
5444 	mutex_exit(&ill->ill_lock);
5445 
5446 	/*
5447 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5448 	 * it held until the end of the function since the cleanup
5449 	 * below needs to be able to use the ip_stack_t.
5450 	 */
5451 	netstack_hold(ipst->ips_netstack);
5452 
5453 	/* qprocsoff is called in ill_delete_tail */
5454 	ill_delete_tail(ill);
5455 	ASSERT(ill->ill_ipst == NULL);
5456 
5457 	/*
5458 	 * Walk through all upper (conn) streams and qenable
5459 	 * those that have queued data.
5460 	 * close synchronization needs this to
5461 	 * be done to ensure that all upper layers blocked
5462 	 * due to flow control to the closing device
5463 	 * get unblocked.
5464 	 */
5465 	ip1dbg(("ip_wsrv: walking\n"));
5466 	conn_walk_drain(ipst);
5467 
5468 	mutex_enter(&ipst->ips_ip_mi_lock);
5469 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5470 	mutex_exit(&ipst->ips_ip_mi_lock);
5471 
5472 	/*
5473 	 * credp could be null if the open didn't succeed and ip_modopen
5474 	 * itself calls ip_close.
5475 	 */
5476 	if (ill->ill_credp != NULL)
5477 		crfree(ill->ill_credp);
5478 
5479 	/*
5480 	 * Now we are done with the module close pieces that
5481 	 * need the netstack_t.
5482 	 */
5483 	netstack_rele(ipst->ips_netstack);
5484 
5485 	mi_close_free((IDP)ill);
5486 	q->q_ptr = WR(q)->q_ptr = NULL;
5487 
5488 	ipsq_exit(ipsq);
5489 
5490 	return (0);
5491 }
5492 
5493 /*
5494  * This is called as part of close() for IP, UDP, ICMP, and RTS
5495  * in order to quiesce the conn.
5496  */
5497 void
5498 ip_quiesce_conn(conn_t *connp)
5499 {
5500 	boolean_t	drain_cleanup_reqd = B_FALSE;
5501 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5502 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5503 	ip_stack_t	*ipst;
5504 
5505 	ASSERT(!IPCL_IS_TCP(connp));
5506 	ipst = connp->conn_netstack->netstack_ip;
5507 
5508 	/*
5509 	 * Mark the conn as closing, and this conn must not be
5510 	 * inserted in future into any list. Eg. conn_drain_insert(),
5511 	 * won't insert this conn into the conn_drain_list.
5512 	 * Similarly ill_pending_mp_add() will not add any mp to
5513 	 * the pending mp list, after this conn has started closing.
5514 	 *
5515 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5516 	 * cannot get set henceforth.
5517 	 */
5518 	mutex_enter(&connp->conn_lock);
5519 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5520 	connp->conn_state_flags |= CONN_CLOSING;
5521 	if (connp->conn_idl != NULL)
5522 		drain_cleanup_reqd = B_TRUE;
5523 	if (connp->conn_oper_pending_ill != NULL)
5524 		conn_ioctl_cleanup_reqd = B_TRUE;
5525 	if (connp->conn_dhcpinit_ill != NULL) {
5526 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5527 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5528 		connp->conn_dhcpinit_ill = NULL;
5529 	}
5530 	if (connp->conn_ilg_inuse != 0)
5531 		ilg_cleanup_reqd = B_TRUE;
5532 	mutex_exit(&connp->conn_lock);
5533 
5534 	if (conn_ioctl_cleanup_reqd)
5535 		conn_ioctl_cleanup(connp);
5536 
5537 	if (is_system_labeled() && connp->conn_anon_port) {
5538 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5539 		    connp->conn_mlp_type, connp->conn_ulp,
5540 		    ntohs(connp->conn_lport), B_FALSE);
5541 		connp->conn_anon_port = 0;
5542 	}
5543 	connp->conn_mlp_type = mlptSingle;
5544 
5545 	/*
5546 	 * Remove this conn from any fanout list it is on.
5547 	 * and then wait for any threads currently operating
5548 	 * on this endpoint to finish
5549 	 */
5550 	ipcl_hash_remove(connp);
5551 
5552 	/*
5553 	 * Remove this conn from the drain list, and do
5554 	 * any other cleanup that may be required.
5555 	 * (Only non-tcp streams may have a non-null conn_idl.
5556 	 * TCP streams are never flow controlled, and
5557 	 * conn_idl will be null)
5558 	 */
5559 	if (drain_cleanup_reqd)
5560 		conn_drain_tail(connp, B_TRUE);
5561 
5562 	if (connp == ipst->ips_ip_g_mrouter)
5563 		(void) ip_mrouter_done(NULL, ipst);
5564 
5565 	if (ilg_cleanup_reqd)
5566 		ilg_delete_all(connp);
5567 
5568 	conn_delete_ire(connp, NULL);
5569 
5570 	/*
5571 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5572 	 * callers from write side can't be there now because close
5573 	 * is in progress. The only other caller is ipcl_walk
5574 	 * which checks for the condemned flag.
5575 	 */
5576 	mutex_enter(&connp->conn_lock);
5577 	connp->conn_state_flags |= CONN_CONDEMNED;
5578 	while (connp->conn_ref != 1)
5579 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5580 	connp->conn_state_flags |= CONN_QUIESCED;
5581 	mutex_exit(&connp->conn_lock);
5582 }
5583 
5584 /* ARGSUSED */
5585 int
5586 ip_close(queue_t *q, int flags)
5587 {
5588 	conn_t		*connp;
5589 
5590 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5591 
5592 	/*
5593 	 * Call the appropriate delete routine depending on whether this is
5594 	 * a module or device.
5595 	 */
5596 	if (WR(q)->q_next != NULL) {
5597 		/* This is a module close */
5598 		return (ip_modclose((ill_t *)q->q_ptr));
5599 	}
5600 
5601 	connp = q->q_ptr;
5602 	ip_quiesce_conn(connp);
5603 
5604 	qprocsoff(q);
5605 
5606 	/*
5607 	 * Now we are truly single threaded on this stream, and can
5608 	 * delete the things hanging off the connp, and finally the connp.
5609 	 * We removed this connp from the fanout list, it cannot be
5610 	 * accessed thru the fanouts, and we already waited for the
5611 	 * conn_ref to drop to 0. We are already in close, so
5612 	 * there cannot be any other thread from the top. qprocsoff
5613 	 * has completed, and service has completed or won't run in
5614 	 * future.
5615 	 */
5616 	ASSERT(connp->conn_ref == 1);
5617 
5618 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5619 
5620 	connp->conn_ref--;
5621 	ipcl_conn_destroy(connp);
5622 
5623 	q->q_ptr = WR(q)->q_ptr = NULL;
5624 	return (0);
5625 }
5626 
5627 /*
5628  * Wapper around putnext() so that ip_rts_request can merely use
5629  * conn_recv.
5630  */
5631 /*ARGSUSED2*/
5632 static void
5633 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5634 {
5635 	conn_t *connp = (conn_t *)arg1;
5636 
5637 	putnext(connp->conn_rq, mp);
5638 }
5639 
5640 /*
5641  * Called when the module is about to be unloaded
5642  */
5643 void
5644 ip_ddi_destroy(void)
5645 {
5646 	tnet_fini();
5647 
5648 	icmp_ddi_destroy();
5649 	rts_ddi_destroy();
5650 	udp_ddi_destroy();
5651 	sctp_ddi_g_destroy();
5652 	tcp_ddi_g_destroy();
5653 	ipsec_policy_g_destroy();
5654 	ipcl_g_destroy();
5655 	ip_net_g_destroy();
5656 	ip_ire_g_fini();
5657 	inet_minor_destroy(ip_minor_arena_sa);
5658 #if defined(_LP64)
5659 	inet_minor_destroy(ip_minor_arena_la);
5660 #endif
5661 
5662 #ifdef DEBUG
5663 	list_destroy(&ip_thread_list);
5664 	rw_destroy(&ip_thread_rwlock);
5665 	tsd_destroy(&ip_thread_data);
5666 #endif
5667 
5668 	netstack_unregister(NS_IP);
5669 }
5670 
5671 /*
5672  * First step in cleanup.
5673  */
5674 /* ARGSUSED */
5675 static void
5676 ip_stack_shutdown(netstackid_t stackid, void *arg)
5677 {
5678 	ip_stack_t *ipst = (ip_stack_t *)arg;
5679 
5680 #ifdef NS_DEBUG
5681 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5682 #endif
5683 
5684 	/* Get rid of loopback interfaces and their IREs */
5685 	ip_loopback_cleanup(ipst);
5686 
5687 	/*
5688 	 * The *_hook_shutdown()s start the process of notifying any
5689 	 * consumers that things are going away.... nothing is destroyed.
5690 	 */
5691 	ipv4_hook_shutdown(ipst);
5692 	ipv6_hook_shutdown(ipst);
5693 
5694 	mutex_enter(&ipst->ips_capab_taskq_lock);
5695 	ipst->ips_capab_taskq_quit = B_TRUE;
5696 	cv_signal(&ipst->ips_capab_taskq_cv);
5697 	mutex_exit(&ipst->ips_capab_taskq_lock);
5698 }
5699 
5700 /*
5701  * Free the IP stack instance.
5702  */
5703 static void
5704 ip_stack_fini(netstackid_t stackid, void *arg)
5705 {
5706 	ip_stack_t *ipst = (ip_stack_t *)arg;
5707 	int ret;
5708 
5709 	/*
5710 	 * At this point, all of the notifications that the events and
5711 	 * protocols are going away have been run, meaning that we can
5712 	 * now set about starting to clean things up.
5713 	 */
5714 	ipv4_hook_destroy(ipst);
5715 	ipv6_hook_destroy(ipst);
5716 	ip_net_destroy(ipst);
5717 
5718 	mutex_destroy(&ipst->ips_capab_taskq_lock);
5719 	cv_destroy(&ipst->ips_capab_taskq_cv);
5720 	list_destroy(&ipst->ips_capab_taskq_list);
5721 
5722 #ifdef NS_DEBUG
5723 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5724 #endif
5725 	rw_destroy(&ipst->ips_srcid_lock);
5726 
5727 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5728 	ipst->ips_ip_mibkp = NULL;
5729 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5730 	ipst->ips_icmp_mibkp = NULL;
5731 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5732 	ipst->ips_ip_kstat = NULL;
5733 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5734 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5735 	ipst->ips_ip6_kstat = NULL;
5736 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5737 
5738 	nd_free(&ipst->ips_ip_g_nd);
5739 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5740 	ipst->ips_param_arr = NULL;
5741 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5742 	ipst->ips_ndp_arr = NULL;
5743 
5744 	ip_mrouter_stack_destroy(ipst);
5745 
5746 	mutex_destroy(&ipst->ips_ip_mi_lock);
5747 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5748 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5749 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5750 
5751 	ret = untimeout(ipst->ips_igmp_timeout_id);
5752 	if (ret == -1) {
5753 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5754 	} else {
5755 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5756 		ipst->ips_igmp_timeout_id = 0;
5757 	}
5758 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5759 	if (ret == -1) {
5760 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5761 	} else {
5762 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5763 		ipst->ips_igmp_slowtimeout_id = 0;
5764 	}
5765 	ret = untimeout(ipst->ips_mld_timeout_id);
5766 	if (ret == -1) {
5767 		ASSERT(ipst->ips_mld_timeout_id == 0);
5768 	} else {
5769 		ASSERT(ipst->ips_mld_timeout_id != 0);
5770 		ipst->ips_mld_timeout_id = 0;
5771 	}
5772 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5773 	if (ret == -1) {
5774 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5775 	} else {
5776 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5777 		ipst->ips_mld_slowtimeout_id = 0;
5778 	}
5779 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5780 	if (ret == -1) {
5781 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5782 	} else {
5783 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5784 		ipst->ips_ip_ire_expire_id = 0;
5785 	}
5786 
5787 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5788 	mutex_destroy(&ipst->ips_mld_timer_lock);
5789 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5790 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5791 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5792 	rw_destroy(&ipst->ips_ill_g_lock);
5793 
5794 	ipobs_fini(ipst);
5795 	ip_ire_fini(ipst);
5796 	ip6_asp_free(ipst);
5797 	conn_drain_fini(ipst);
5798 	ipcl_destroy(ipst);
5799 
5800 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5801 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5802 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5803 	ipst->ips_ndp4 = NULL;
5804 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5805 	ipst->ips_ndp6 = NULL;
5806 
5807 	if (ipst->ips_loopback_ksp != NULL) {
5808 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5809 		ipst->ips_loopback_ksp = NULL;
5810 	}
5811 
5812 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5813 	ipst->ips_phyint_g_list = NULL;
5814 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5815 	ipst->ips_ill_g_heads = NULL;
5816 
5817 	kmem_free(ipst, sizeof (*ipst));
5818 }
5819 
5820 /*
5821  * This function is called from the TSD destructor, and is used to debug
5822  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5823  * details.
5824  */
5825 static void
5826 ip_thread_exit(void *phash)
5827 {
5828 	th_hash_t *thh = phash;
5829 
5830 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5831 	list_remove(&ip_thread_list, thh);
5832 	rw_exit(&ip_thread_rwlock);
5833 	mod_hash_destroy_hash(thh->thh_hash);
5834 	kmem_free(thh, sizeof (*thh));
5835 }
5836 
5837 /*
5838  * Called when the IP kernel module is loaded into the kernel
5839  */
5840 void
5841 ip_ddi_init(void)
5842 {
5843 	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);
5844 
5845 	/*
5846 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5847 	 * initial devices: ip, ip6, tcp, tcp6.
5848 	 */
5849 	/*
5850 	 * If this is a 64-bit kernel, then create two separate arenas -
5851 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5852 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5853 	 */
5854 	ip_minor_arena_la = NULL;
5855 	ip_minor_arena_sa = NULL;
5856 #if defined(_LP64)
5857 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5858 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5859 		cmn_err(CE_PANIC,
5860 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5861 	}
5862 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5863 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5864 		cmn_err(CE_PANIC,
5865 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5866 	}
5867 #else
5868 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5869 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5870 		cmn_err(CE_PANIC,
5871 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5872 	}
5873 #endif
5874 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5875 
5876 	ipcl_g_init();
5877 	ip_ire_g_init();
5878 	ip_net_g_init();
5879 
5880 #ifdef DEBUG
5881 	tsd_create(&ip_thread_data, ip_thread_exit);
5882 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5883 	list_create(&ip_thread_list, sizeof (th_hash_t),
5884 	    offsetof(th_hash_t, thh_link));
5885 #endif
5886 
5887 	/*
5888 	 * We want to be informed each time a stack is created or
5889 	 * destroyed in the kernel, so we can maintain the
5890 	 * set of udp_stack_t's.
5891 	 */
5892 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5893 	    ip_stack_fini);
5894 
5895 	ipsec_policy_g_init();
5896 	tcp_ddi_g_init();
5897 	sctp_ddi_g_init();
5898 
5899 	tnet_init();
5900 
5901 	udp_ddi_init();
5902 	rts_ddi_init();
5903 	icmp_ddi_init();
5904 }
5905 
5906 /*
5907  * Initialize the IP stack instance.
5908  */
5909 static void *
5910 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5911 {
5912 	ip_stack_t	*ipst;
5913 	ipparam_t	*pa;
5914 	ipndp_t		*na;
5915 
5916 #ifdef NS_DEBUG
5917 	printf("ip_stack_init(stack %d)\n", stackid);
5918 #endif
5919 
5920 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5921 	ipst->ips_netstack = ns;
5922 
5923 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5924 	    KM_SLEEP);
5925 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5926 	    KM_SLEEP);
5927 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5928 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5929 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5930 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5931 
5932 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5933 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5934 	ipst->ips_igmp_deferred_next = INFINITY;
5935 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5936 	ipst->ips_mld_deferred_next = INFINITY;
5937 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5938 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5939 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5940 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5941 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5942 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5943 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5944 
5945 	ipcl_init(ipst);
5946 	ip_ire_init(ipst);
5947 	ip6_asp_init(ipst);
5948 	ipif_init(ipst);
5949 	conn_drain_init(ipst);
5950 	ip_mrouter_stack_init(ipst);
5951 
5952 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5953 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5954 
5955 	ipst->ips_ip_multirt_log_interval = 1000;
5956 
5957 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5958 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5959 	ipst->ips_ill_index = 1;
5960 
5961 	ipst->ips_saved_ip_g_forward = -1;
5962 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5963 
5964 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5965 	ipst->ips_param_arr = pa;
5966 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5967 
5968 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5969 	ipst->ips_ndp_arr = na;
5970 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5971 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5972 	    (caddr_t)&ipst->ips_ip_g_forward;
5973 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5974 	    (caddr_t)&ipst->ips_ipv6_forward;
5975 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5976 	    "ip_cgtp_filter") == 0);
5977 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5978 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5979 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5980 	    "ipmp_hook_emulation") == 0);
5981 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5982 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5983 
5984 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5985 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5986 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5987 
5988 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5989 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5990 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5991 	ipst->ips_ip6_kstat =
5992 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
5993 
5994 	ipst->ips_ipmp_enable_failback = B_TRUE;
5995 
5996 	ipst->ips_ip_src_id = 1;
5997 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
5998 
5999 	ipobs_init(ipst);
6000 	ip_net_init(ipst, ns);
6001 	ipv4_hook_init(ipst);
6002 	ipv6_hook_init(ipst);
6003 
6004 	/*
6005 	 * Create the taskq dispatcher thread and initialize related stuff.
6006 	 */
6007 	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
6008 	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);
6009 	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
6010 	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
6011 	list_create(&ipst->ips_capab_taskq_list, sizeof (mblk_t),
6012 	    offsetof(mblk_t, b_next));
6013 
6014 	return (ipst);
6015 }
6016 
6017 /*
6018  * Allocate and initialize a DLPI template of the specified length.  (May be
6019  * called as writer.)
6020  */
6021 mblk_t *
6022 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6023 {
6024 	mblk_t	*mp;
6025 
6026 	mp = allocb(len, BPRI_MED);
6027 	if (!mp)
6028 		return (NULL);
6029 
6030 	/*
6031 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6032 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6033 	 * that other DLPI are M_PROTO.
6034 	 */
6035 	if (prim == DL_INFO_REQ) {
6036 		mp->b_datap->db_type = M_PCPROTO;
6037 	} else {
6038 		mp->b_datap->db_type = M_PROTO;
6039 	}
6040 
6041 	mp->b_wptr = mp->b_rptr + len;
6042 	bzero(mp->b_rptr, len);
6043 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6044 	return (mp);
6045 }
6046 
6047 /*
6048  * Debug formatting routine.  Returns a character string representation of the
6049  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6050  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6051  *
6052  * Once the ndd table-printing interfaces are removed, this can be changed to
6053  * standard dotted-decimal form.
6054  */
6055 char *
6056 ip_dot_addr(ipaddr_t addr, char *buf)
6057 {
6058 	uint8_t *ap = (uint8_t *)&addr;
6059 
6060 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6061 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6062 	return (buf);
6063 }
6064 
6065 /*
6066  * Write the given MAC address as a printable string in the usual colon-
6067  * separated format.
6068  */
6069 const char *
6070 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6071 {
6072 	char *bp;
6073 
6074 	if (alen == 0 || buflen < 4)
6075 		return ("?");
6076 	bp = buf;
6077 	for (;;) {
6078 		/*
6079 		 * If there are more MAC address bytes available, but we won't
6080 		 * have any room to print them, then add "..." to the string
6081 		 * instead.  See below for the 'magic number' explanation.
6082 		 */
6083 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6084 			(void) strcpy(bp, "...");
6085 			break;
6086 		}
6087 		(void) sprintf(bp, "%02x", *addr++);
6088 		bp += 2;
6089 		if (--alen == 0)
6090 			break;
6091 		*bp++ = ':';
6092 		buflen -= 3;
6093 		/*
6094 		 * At this point, based on the first 'if' statement above,
6095 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6096 		 * buflen >= 4.  The first case leaves room for the final "xx"
6097 		 * number and trailing NUL byte.  The second leaves room for at
6098 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6099 		 * that statement.
6100 		 */
6101 	}
6102 	return (buf);
6103 }
6104 
6105 /*
6106  * Send an ICMP error after patching up the packet appropriately.  Returns
6107  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6108  */
6109 static boolean_t
6110 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6111     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6112     zoneid_t zoneid, ip_stack_t *ipst)
6113 {
6114 	ipha_t *ipha;
6115 	mblk_t *first_mp;
6116 	boolean_t secure;
6117 	unsigned char db_type;
6118 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6119 
6120 	first_mp = mp;
6121 	if (mctl_present) {
6122 		mp = mp->b_cont;
6123 		secure = ipsec_in_is_secure(first_mp);
6124 		ASSERT(mp != NULL);
6125 	} else {
6126 		/*
6127 		 * If this is an ICMP error being reported - which goes
6128 		 * up as M_CTLs, we need to convert them to M_DATA till
6129 		 * we finish checking with global policy because
6130 		 * ipsec_check_global_policy() assumes M_DATA as clear
6131 		 * and M_CTL as secure.
6132 		 */
6133 		db_type = DB_TYPE(mp);
6134 		DB_TYPE(mp) = M_DATA;
6135 		secure = B_FALSE;
6136 	}
6137 	/*
6138 	 * We are generating an icmp error for some inbound packet.
6139 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6140 	 * Before we generate an error, check with global policy
6141 	 * to see whether this is allowed to enter the system. As
6142 	 * there is no "conn", we are checking with global policy.
6143 	 */
6144 	ipha = (ipha_t *)mp->b_rptr;
6145 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6146 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6147 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6148 		if (first_mp == NULL)
6149 			return (B_FALSE);
6150 	}
6151 
6152 	if (!mctl_present)
6153 		DB_TYPE(mp) = db_type;
6154 
6155 	if (flags & IP_FF_SEND_ICMP) {
6156 		if (flags & IP_FF_HDR_COMPLETE) {
6157 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6158 				freemsg(first_mp);
6159 				return (B_TRUE);
6160 			}
6161 		}
6162 		if (flags & IP_FF_CKSUM) {
6163 			/*
6164 			 * Have to correct checksum since
6165 			 * the packet might have been
6166 			 * fragmented and the reassembly code in ip_rput
6167 			 * does not restore the IP checksum.
6168 			 */
6169 			ipha->ipha_hdr_checksum = 0;
6170 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6171 		}
6172 		switch (icmp_type) {
6173 		case ICMP_DEST_UNREACHABLE:
6174 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6175 			    ipst);
6176 			break;
6177 		default:
6178 			freemsg(first_mp);
6179 			break;
6180 		}
6181 	} else {
6182 		freemsg(first_mp);
6183 		return (B_FALSE);
6184 	}
6185 
6186 	return (B_TRUE);
6187 }
6188 
6189 /*
6190  * Used to send an ICMP error message when a packet is received for
6191  * a protocol that is not supported. The mblk passed as argument
6192  * is consumed by this function.
6193  */
6194 void
6195 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6196     ip_stack_t *ipst)
6197 {
6198 	mblk_t *mp;
6199 	ipha_t *ipha;
6200 	ill_t *ill;
6201 	ipsec_in_t *ii;
6202 
6203 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6204 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6205 
6206 	mp = ipsec_mp->b_cont;
6207 	ipsec_mp->b_cont = NULL;
6208 	ipha = (ipha_t *)mp->b_rptr;
6209 	/* Get ill from index in ipsec_in_t. */
6210 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6211 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6212 	    ipst);
6213 	if (ill != NULL) {
6214 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6215 			if (ip_fanout_send_icmp(q, mp, flags,
6216 			    ICMP_DEST_UNREACHABLE,
6217 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6218 				BUMP_MIB(ill->ill_ip_mib,
6219 				    ipIfStatsInUnknownProtos);
6220 			}
6221 		} else {
6222 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6223 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6224 			    0, B_FALSE, zoneid, ipst)) {
6225 				BUMP_MIB(ill->ill_ip_mib,
6226 				    ipIfStatsInUnknownProtos);
6227 			}
6228 		}
6229 		ill_refrele(ill);
6230 	} else { /* re-link for the freemsg() below. */
6231 		ipsec_mp->b_cont = mp;
6232 	}
6233 
6234 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6235 	freemsg(ipsec_mp);
6236 }
6237 
6238 /*
6239  * See if the inbound datagram has had IPsec processing applied to it.
6240  */
6241 boolean_t
6242 ipsec_in_is_secure(mblk_t *ipsec_mp)
6243 {
6244 	ipsec_in_t *ii;
6245 
6246 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6247 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6248 
6249 	if (ii->ipsec_in_loopback) {
6250 		return (ii->ipsec_in_secure);
6251 	} else {
6252 		return (ii->ipsec_in_ah_sa != NULL ||
6253 		    ii->ipsec_in_esp_sa != NULL ||
6254 		    ii->ipsec_in_decaps);
6255 	}
6256 }
6257 
6258 /*
6259  * Handle protocols with which IP is less intimate.  There
6260  * can be more than one stream bound to a particular
6261  * protocol.  When this is the case, normally each one gets a copy
6262  * of any incoming packets.
6263  *
6264  * IPsec NOTE :
6265  *
6266  * Don't allow a secure packet going up a non-secure connection.
6267  * We don't allow this because
6268  *
6269  * 1) Reply might go out in clear which will be dropped at
6270  *    the sending side.
6271  * 2) If the reply goes out in clear it will give the
6272  *    adversary enough information for getting the key in
6273  *    most of the cases.
6274  *
6275  * Moreover getting a secure packet when we expect clear
6276  * implies that SA's were added without checking for
6277  * policy on both ends. This should not happen once ISAKMP
6278  * is used to negotiate SAs as SAs will be added only after
6279  * verifying the policy.
6280  *
6281  * NOTE : If the packet was tunneled and not multicast we only send
6282  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6283  * back to delivering packets to AF_INET6 raw sockets.
6284  *
6285  * IPQoS Notes:
6286  * Once we have determined the client, invoke IPPF processing.
6287  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6288  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6289  * ip_policy will be false.
6290  *
6291  * Zones notes:
6292  * Currently only applications in the global zone can create raw sockets for
6293  * protocols other than ICMP. So unlike the broadcast / multicast case of
6294  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6295  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6296  */
6297 static void
6298 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6299     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6300     zoneid_t zoneid)
6301 {
6302 	queue_t	*rq;
6303 	mblk_t	*mp1, *first_mp1;
6304 	uint_t	protocol = ipha->ipha_protocol;
6305 	ipaddr_t dst;
6306 	boolean_t one_only;
6307 	mblk_t *first_mp = mp;
6308 	boolean_t secure;
6309 	uint32_t ill_index;
6310 	conn_t	*connp, *first_connp, *next_connp;
6311 	connf_t	*connfp;
6312 	boolean_t shared_addr;
6313 	mib2_ipIfStatsEntry_t *mibptr;
6314 	ip_stack_t *ipst = recv_ill->ill_ipst;
6315 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6316 
6317 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6318 	if (mctl_present) {
6319 		mp = first_mp->b_cont;
6320 		secure = ipsec_in_is_secure(first_mp);
6321 		ASSERT(mp != NULL);
6322 	} else {
6323 		secure = B_FALSE;
6324 	}
6325 	dst = ipha->ipha_dst;
6326 	/*
6327 	 * If the packet was tunneled and not multicast we only send to it
6328 	 * the first match.
6329 	 */
6330 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6331 	    !CLASSD(dst));
6332 
6333 	shared_addr = (zoneid == ALL_ZONES);
6334 	if (shared_addr) {
6335 		/*
6336 		 * We don't allow multilevel ports for raw IP, so no need to
6337 		 * check for that here.
6338 		 */
6339 		zoneid = tsol_packet_to_zoneid(mp);
6340 	}
6341 
6342 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6343 	mutex_enter(&connfp->connf_lock);
6344 	connp = connfp->connf_head;
6345 	for (connp = connfp->connf_head; connp != NULL;
6346 	    connp = connp->conn_next) {
6347 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6348 		    zoneid) &&
6349 		    (!is_system_labeled() ||
6350 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6351 		    connp))) {
6352 			break;
6353 		}
6354 	}
6355 
6356 	if (connp == NULL || connp->conn_upq == NULL) {
6357 		/*
6358 		 * No one bound to these addresses.  Is
6359 		 * there a client that wants all
6360 		 * unclaimed datagrams?
6361 		 */
6362 		mutex_exit(&connfp->connf_lock);
6363 		/*
6364 		 * Check for IPPROTO_ENCAP...
6365 		 */
6366 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6367 			/*
6368 			 * If an IPsec mblk is here on a multicast
6369 			 * tunnel (using ip_mroute stuff), check policy here,
6370 			 * THEN ship off to ip_mroute_decap().
6371 			 *
6372 			 * BTW,  If I match a configured IP-in-IP
6373 			 * tunnel, this path will not be reached, and
6374 			 * ip_mroute_decap will never be called.
6375 			 */
6376 			first_mp = ipsec_check_global_policy(first_mp, connp,
6377 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6378 			if (first_mp != NULL) {
6379 				if (mctl_present)
6380 					freeb(first_mp);
6381 				ip_mroute_decap(q, mp, ill);
6382 			} /* Else we already freed everything! */
6383 		} else {
6384 			/*
6385 			 * Otherwise send an ICMP protocol unreachable.
6386 			 */
6387 			if (ip_fanout_send_icmp(q, first_mp, flags,
6388 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6389 			    mctl_present, zoneid, ipst)) {
6390 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6391 			}
6392 		}
6393 		return;
6394 	}
6395 	CONN_INC_REF(connp);
6396 	first_connp = connp;
6397 
6398 	/*
6399 	 * Only send message to one tunnel driver by immediately
6400 	 * terminating the loop.
6401 	 */
6402 	connp = one_only ? NULL : connp->conn_next;
6403 
6404 	for (;;) {
6405 		while (connp != NULL) {
6406 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6407 			    flags, zoneid) &&
6408 			    (!is_system_labeled() ||
6409 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6410 			    shared_addr, connp)))
6411 				break;
6412 			connp = connp->conn_next;
6413 		}
6414 
6415 		/*
6416 		 * Copy the packet.
6417 		 */
6418 		if (connp == NULL || connp->conn_upq == NULL ||
6419 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6420 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6421 			/*
6422 			 * No more interested clients or memory
6423 			 * allocation failed
6424 			 */
6425 			connp = first_connp;
6426 			break;
6427 		}
6428 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6429 		CONN_INC_REF(connp);
6430 		mutex_exit(&connfp->connf_lock);
6431 		rq = connp->conn_rq;
6432 		if (!canputnext(rq)) {
6433 			if (flags & IP_FF_RAWIP) {
6434 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6435 			} else {
6436 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6437 			}
6438 
6439 			freemsg(first_mp1);
6440 		} else {
6441 			/*
6442 			 * Don't enforce here if we're an actual tunnel -
6443 			 * let "tun" do it instead.
6444 			 */
6445 			if (!IPCL_IS_IPTUN(connp) &&
6446 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6447 			    secure)) {
6448 				first_mp1 = ipsec_check_inbound_policy
6449 				    (first_mp1, connp, ipha, NULL,
6450 				    mctl_present);
6451 			}
6452 			if (first_mp1 != NULL) {
6453 				int in_flags = 0;
6454 				/*
6455 				 * ip_fanout_proto also gets called from
6456 				 * icmp_inbound_error_fanout, in which case
6457 				 * the msg type is M_CTL.  Don't add info
6458 				 * in this case for the time being. In future
6459 				 * when there is a need for knowing the
6460 				 * inbound iface index for ICMP error msgs,
6461 				 * then this can be changed.
6462 				 */
6463 				if (connp->conn_recvif)
6464 					in_flags = IPF_RECVIF;
6465 				/*
6466 				 * The ULP may support IP_RECVPKTINFO for both
6467 				 * IP v4 and v6 so pass the appropriate argument
6468 				 * based on conn IP version.
6469 				 */
6470 				if (connp->conn_ip_recvpktinfo) {
6471 					if (connp->conn_af_isv6) {
6472 						/*
6473 						 * V6 only needs index
6474 						 */
6475 						in_flags |= IPF_RECVIF;
6476 					} else {
6477 						/*
6478 						 * V4 needs index +
6479 						 * matching address.
6480 						 */
6481 						in_flags |= IPF_RECVADDR;
6482 					}
6483 				}
6484 				if ((in_flags != 0) &&
6485 				    (mp->b_datap->db_type != M_CTL)) {
6486 					/*
6487 					 * the actual data will be
6488 					 * contained in b_cont upon
6489 					 * successful return of the
6490 					 * following call else
6491 					 * original mblk is returned
6492 					 */
6493 					ASSERT(recv_ill != NULL);
6494 					mp1 = ip_add_info(mp1, recv_ill,
6495 					    in_flags, IPCL_ZONEID(connp), ipst);
6496 				}
6497 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6498 				if (mctl_present)
6499 					freeb(first_mp1);
6500 				(connp->conn_recv)(connp, mp1, NULL);
6501 			}
6502 		}
6503 		mutex_enter(&connfp->connf_lock);
6504 		/* Follow the next pointer before releasing the conn. */
6505 		next_connp = connp->conn_next;
6506 		CONN_DEC_REF(connp);
6507 		connp = next_connp;
6508 	}
6509 
6510 	/* Last one.  Send it upstream. */
6511 	mutex_exit(&connfp->connf_lock);
6512 
6513 	/*
6514 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6515 	 * will be set to false.
6516 	 */
6517 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6518 		ill_index = ill->ill_phyint->phyint_ifindex;
6519 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6520 		if (mp == NULL) {
6521 			CONN_DEC_REF(connp);
6522 			if (mctl_present) {
6523 				freeb(first_mp);
6524 			}
6525 			return;
6526 		}
6527 	}
6528 
6529 	rq = connp->conn_rq;
6530 	if (!canputnext(rq)) {
6531 		if (flags & IP_FF_RAWIP) {
6532 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6533 		} else {
6534 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6535 		}
6536 
6537 		freemsg(first_mp);
6538 	} else {
6539 		if (IPCL_IS_IPTUN(connp)) {
6540 			/*
6541 			 * Tunneled packet.  We enforce policy in the tunnel
6542 			 * module itself.
6543 			 *
6544 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6545 			 * a policy check.
6546 			 * FIXME to use conn_recv for tun later.
6547 			 */
6548 			putnext(rq, first_mp);
6549 			CONN_DEC_REF(connp);
6550 			return;
6551 		}
6552 
6553 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6554 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6555 			    ipha, NULL, mctl_present);
6556 		}
6557 
6558 		if (first_mp != NULL) {
6559 			int in_flags = 0;
6560 
6561 			/*
6562 			 * ip_fanout_proto also gets called
6563 			 * from icmp_inbound_error_fanout, in
6564 			 * which case the msg type is M_CTL.
6565 			 * Don't add info in this case for time
6566 			 * being. In future when there is a
6567 			 * need for knowing the inbound iface
6568 			 * index for ICMP error msgs, then this
6569 			 * can be changed
6570 			 */
6571 			if (connp->conn_recvif)
6572 				in_flags = IPF_RECVIF;
6573 			if (connp->conn_ip_recvpktinfo) {
6574 				if (connp->conn_af_isv6) {
6575 					/*
6576 					 * V6 only needs index
6577 					 */
6578 					in_flags |= IPF_RECVIF;
6579 				} else {
6580 					/*
6581 					 * V4 needs index +
6582 					 * matching address.
6583 					 */
6584 					in_flags |= IPF_RECVADDR;
6585 				}
6586 			}
6587 			if ((in_flags != 0) &&
6588 			    (mp->b_datap->db_type != M_CTL)) {
6589 
6590 				/*
6591 				 * the actual data will be contained in
6592 				 * b_cont upon successful return
6593 				 * of the following call else original
6594 				 * mblk is returned
6595 				 */
6596 				ASSERT(recv_ill != NULL);
6597 				mp = ip_add_info(mp, recv_ill,
6598 				    in_flags, IPCL_ZONEID(connp), ipst);
6599 			}
6600 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6601 			(connp->conn_recv)(connp, mp, NULL);
6602 			if (mctl_present)
6603 				freeb(first_mp);
6604 		}
6605 	}
6606 	CONN_DEC_REF(connp);
6607 }
6608 
6609 /*
6610  * Fanout for TCP packets
6611  * The caller puts <fport, lport> in the ports parameter.
6612  *
6613  * IPQoS Notes
6614  * Before sending it to the client, invoke IPPF processing.
6615  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6616  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6617  * ip_policy is false.
6618  */
6619 static void
6620 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6621     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6622 {
6623 	mblk_t  *first_mp;
6624 	boolean_t secure;
6625 	uint32_t ill_index;
6626 	int	ip_hdr_len;
6627 	tcph_t	*tcph;
6628 	boolean_t syn_present = B_FALSE;
6629 	conn_t	*connp;
6630 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6631 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6632 
6633 	ASSERT(recv_ill != NULL);
6634 
6635 	first_mp = mp;
6636 	if (mctl_present) {
6637 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6638 		mp = first_mp->b_cont;
6639 		secure = ipsec_in_is_secure(first_mp);
6640 		ASSERT(mp != NULL);
6641 	} else {
6642 		secure = B_FALSE;
6643 	}
6644 
6645 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6646 
6647 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6648 	    zoneid, ipst)) == NULL) {
6649 		/*
6650 		 * No connected connection or listener. Send a
6651 		 * TH_RST via tcp_xmit_listeners_reset.
6652 		 */
6653 
6654 		/* Initiate IPPf processing, if needed. */
6655 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6656 			uint32_t ill_index;
6657 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6658 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6659 			if (first_mp == NULL)
6660 				return;
6661 		}
6662 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6663 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6664 		    zoneid));
6665 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6666 		    ipst->ips_netstack->netstack_tcp, NULL);
6667 		return;
6668 	}
6669 
6670 	/*
6671 	 * Allocate the SYN for the TCP connection here itself
6672 	 */
6673 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6674 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6675 		if (IPCL_IS_TCP(connp)) {
6676 			squeue_t *sqp;
6677 
6678 			/*
6679 			 * For fused tcp loopback, assign the eager's
6680 			 * squeue to be that of the active connect's.
6681 			 * Note that we don't check for IP_FF_LOOPBACK
6682 			 * here since this routine gets called only
6683 			 * for loopback (unlike the IPv6 counterpart).
6684 			 */
6685 			ASSERT(Q_TO_CONN(q) != NULL);
6686 			if (do_tcp_fusion &&
6687 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6688 			    !secure &&
6689 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6690 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6691 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6692 				sqp = Q_TO_CONN(q)->conn_sqp;
6693 			} else {
6694 				sqp = IP_SQUEUE_GET(lbolt);
6695 			}
6696 
6697 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6698 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6699 			syn_present = B_TRUE;
6700 		}
6701 	}
6702 
6703 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6704 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6705 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6706 		if ((flags & TH_RST) || (flags & TH_URG)) {
6707 			CONN_DEC_REF(connp);
6708 			freemsg(first_mp);
6709 			return;
6710 		}
6711 		if (flags & TH_ACK) {
6712 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6713 			    ipst->ips_netstack->netstack_tcp, connp);
6714 			CONN_DEC_REF(connp);
6715 			return;
6716 		}
6717 
6718 		CONN_DEC_REF(connp);
6719 		freemsg(first_mp);
6720 		return;
6721 	}
6722 
6723 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6724 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6725 		    NULL, mctl_present);
6726 		if (first_mp == NULL) {
6727 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6728 			CONN_DEC_REF(connp);
6729 			return;
6730 		}
6731 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6732 			ASSERT(syn_present);
6733 			if (mctl_present) {
6734 				ASSERT(first_mp != mp);
6735 				first_mp->b_datap->db_struioflag |=
6736 				    STRUIO_POLICY;
6737 			} else {
6738 				ASSERT(first_mp == mp);
6739 				mp->b_datap->db_struioflag &=
6740 				    ~STRUIO_EAGER;
6741 				mp->b_datap->db_struioflag |=
6742 				    STRUIO_POLICY;
6743 			}
6744 		} else {
6745 			/*
6746 			 * Discard first_mp early since we're dealing with a
6747 			 * fully-connected conn_t and tcp doesn't do policy in
6748 			 * this case.
6749 			 */
6750 			if (mctl_present) {
6751 				freeb(first_mp);
6752 				mctl_present = B_FALSE;
6753 			}
6754 			first_mp = mp;
6755 		}
6756 	}
6757 
6758 	/*
6759 	 * Initiate policy processing here if needed. If we get here from
6760 	 * icmp_inbound_error_fanout, ip_policy is false.
6761 	 */
6762 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6763 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6764 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6765 		if (mp == NULL) {
6766 			CONN_DEC_REF(connp);
6767 			if (mctl_present)
6768 				freeb(first_mp);
6769 			return;
6770 		} else if (mctl_present) {
6771 			ASSERT(first_mp != mp);
6772 			first_mp->b_cont = mp;
6773 		} else {
6774 			first_mp = mp;
6775 		}
6776 	}
6777 
6778 
6779 
6780 	/* Handle socket options. */
6781 	if (!syn_present &&
6782 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6783 		/* Add header */
6784 		ASSERT(recv_ill != NULL);
6785 		/*
6786 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6787 		 * IPF_RECVIF.
6788 		 */
6789 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6790 		    ipst);
6791 		if (mp == NULL) {
6792 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6793 			CONN_DEC_REF(connp);
6794 			if (mctl_present)
6795 				freeb(first_mp);
6796 			return;
6797 		} else if (mctl_present) {
6798 			/*
6799 			 * ip_add_info might return a new mp.
6800 			 */
6801 			ASSERT(first_mp != mp);
6802 			first_mp->b_cont = mp;
6803 		} else {
6804 			first_mp = mp;
6805 		}
6806 	}
6807 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6808 	if (IPCL_IS_TCP(connp)) {
6809 		/* do not drain, certain use cases can blow the stack */
6810 		SQUEUE_ENTER_ONE(connp->conn_sqp, first_mp, connp->conn_recv,
6811 		    connp, ip_squeue_flag, SQTAG_IP_FANOUT_TCP);
6812 	} else {
6813 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6814 		(connp->conn_recv)(connp, first_mp, NULL);
6815 		CONN_DEC_REF(connp);
6816 	}
6817 }
6818 
6819 /*
6820  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6821  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6822  * is not consumed.
6823  *
6824  * One of four things can happen, all of which affect the passed-in mblk:
6825  *
6826  * 1.) ICMP messages that go through here just get returned TRUE.
6827  *
6828  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6829  *
6830  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6831  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6832  *
6833  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6834  */
6835 static boolean_t
6836 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6837     ipsec_stack_t *ipss)
6838 {
6839 	int shift, plen, iph_len;
6840 	ipha_t *ipha;
6841 	udpha_t *udpha;
6842 	uint32_t *spi;
6843 	uint32_t esp_ports;
6844 	uint8_t *orptr;
6845 	boolean_t free_ire;
6846 
6847 	if (DB_TYPE(mp) == M_CTL) {
6848 		/*
6849 		 * ICMP message with UDP inside.  Don't bother stripping, just
6850 		 * send it up.
6851 		 *
6852 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6853 		 * to ignore errors set by ICMP anyway ('cause they might be
6854 		 * forged), but that's the app's decision, not ours.
6855 		 */
6856 
6857 		/* Bunch of reality checks for DEBUG kernels... */
6858 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6859 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6860 
6861 		return (B_TRUE);
6862 	}
6863 
6864 	ipha = (ipha_t *)mp->b_rptr;
6865 	iph_len = IPH_HDR_LENGTH(ipha);
6866 	plen = ntohs(ipha->ipha_length);
6867 
6868 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6869 		/*
6870 		 * Most likely a keepalive for the benefit of an intervening
6871 		 * NAT.  These aren't for us, per se, so drop it.
6872 		 *
6873 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6874 		 * byte packets (keepalives are 1-byte), but we'll drop them
6875 		 * also.
6876 		 */
6877 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6878 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6879 		return (B_FALSE);
6880 	}
6881 
6882 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6883 		/* might as well pull it all up - it might be ESP. */
6884 		if (!pullupmsg(mp, -1)) {
6885 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6886 			    DROPPER(ipss, ipds_esp_nomem),
6887 			    &ipss->ipsec_dropper);
6888 			return (B_FALSE);
6889 		}
6890 
6891 		ipha = (ipha_t *)mp->b_rptr;
6892 	}
6893 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6894 	if (*spi == 0) {
6895 		/* UDP packet - remove 0-spi. */
6896 		shift = sizeof (uint32_t);
6897 	} else {
6898 		/* ESP-in-UDP packet - reduce to ESP. */
6899 		ipha->ipha_protocol = IPPROTO_ESP;
6900 		shift = sizeof (udpha_t);
6901 	}
6902 
6903 	/* Fix IP header */
6904 	ipha->ipha_length = htons(plen - shift);
6905 	ipha->ipha_hdr_checksum = 0;
6906 
6907 	orptr = mp->b_rptr;
6908 	mp->b_rptr += shift;
6909 
6910 	udpha = (udpha_t *)(orptr + iph_len);
6911 	if (*spi == 0) {
6912 		ASSERT((uint8_t *)ipha == orptr);
6913 		udpha->uha_length = htons(plen - shift - iph_len);
6914 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6915 		esp_ports = 0;
6916 	} else {
6917 		esp_ports = *((uint32_t *)udpha);
6918 		ASSERT(esp_ports != 0);
6919 	}
6920 	ovbcopy(orptr, orptr + shift, iph_len);
6921 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6922 		ipha = (ipha_t *)(orptr + shift);
6923 
6924 		free_ire = (ire == NULL);
6925 		if (free_ire) {
6926 			/* Re-acquire ire. */
6927 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6928 			    ipss->ipsec_netstack->netstack_ip);
6929 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6930 				if (ire != NULL)
6931 					ire_refrele(ire);
6932 				/*
6933 				 * Do a regular freemsg(), as this is an IP
6934 				 * error (no local route) not an IPsec one.
6935 				 */
6936 				freemsg(mp);
6937 			}
6938 		}
6939 
6940 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
6941 		if (free_ire)
6942 			ire_refrele(ire);
6943 	}
6944 
6945 	return (esp_ports == 0);
6946 }
6947 
6948 /*
6949  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6950  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6951  * Caller is responsible for dropping references to the conn, and freeing
6952  * first_mp.
6953  *
6954  * IPQoS Notes
6955  * Before sending it to the client, invoke IPPF processing. Policy processing
6956  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6957  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6958  * ip_wput_local, ip_policy is false.
6959  */
6960 static void
6961 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6962     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6963     boolean_t ip_policy)
6964 {
6965 	boolean_t	mctl_present = (first_mp != NULL);
6966 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6967 	uint32_t	ill_index;
6968 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6969 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6970 
6971 	ASSERT(ill != NULL);
6972 
6973 	if (mctl_present)
6974 		first_mp->b_cont = mp;
6975 	else
6976 		first_mp = mp;
6977 
6978 	if (CONN_UDP_FLOWCTLD(connp)) {
6979 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6980 		freemsg(first_mp);
6981 		return;
6982 	}
6983 
6984 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6985 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6986 		    NULL, mctl_present);
6987 		/* Freed by ipsec_check_inbound_policy(). */
6988 		if (first_mp == NULL) {
6989 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6990 			return;
6991 		}
6992 	}
6993 	if (mctl_present)
6994 		freeb(first_mp);
6995 
6996 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
6997 	if (connp->conn_udp->udp_nat_t_endpoint) {
6998 		if (mctl_present) {
6999 			/* mctl_present *shouldn't* happen. */
7000 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7001 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7002 			    &ipss->ipsec_dropper);
7003 			return;
7004 		}
7005 
7006 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7007 			return;
7008 	}
7009 
7010 	/* Handle options. */
7011 	if (connp->conn_recvif)
7012 		in_flags = IPF_RECVIF;
7013 	/*
7014 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7015 	 * passed to ip_add_info is based on IP version of connp.
7016 	 */
7017 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7018 		if (connp->conn_af_isv6) {
7019 			/*
7020 			 * V6 only needs index
7021 			 */
7022 			in_flags |= IPF_RECVIF;
7023 		} else {
7024 			/*
7025 			 * V4 needs index + matching address.
7026 			 */
7027 			in_flags |= IPF_RECVADDR;
7028 		}
7029 	}
7030 
7031 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7032 		in_flags |= IPF_RECVSLLA;
7033 
7034 	/*
7035 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7036 	 * freed if the packet is dropped. The caller will do so.
7037 	 */
7038 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7039 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7040 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7041 		if (mp == NULL) {
7042 			return;
7043 		}
7044 	}
7045 	if ((in_flags != 0) &&
7046 	    (mp->b_datap->db_type != M_CTL)) {
7047 		/*
7048 		 * The actual data will be contained in b_cont
7049 		 * upon successful return of the following call
7050 		 * else original mblk is returned
7051 		 */
7052 		ASSERT(recv_ill != NULL);
7053 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7054 		    ipst);
7055 	}
7056 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7057 	/* Send it upstream */
7058 	(connp->conn_recv)(connp, mp, NULL);
7059 }
7060 
7061 /*
7062  * Fanout for UDP packets.
7063  * The caller puts <fport, lport> in the ports parameter.
7064  *
7065  * If SO_REUSEADDR is set all multicast and broadcast packets
7066  * will be delivered to all streams bound to the same port.
7067  *
7068  * Zones notes:
7069  * Multicast and broadcast packets will be distributed to streams in all zones.
7070  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7071  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7072  * packets. To maintain this behavior with multiple zones, the conns are grouped
7073  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7074  * each zone. If unset, all the following conns in the same zone are skipped.
7075  */
7076 static void
7077 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7078     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7079     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7080 {
7081 	uint32_t	dstport, srcport;
7082 	ipaddr_t	dst;
7083 	mblk_t		*first_mp;
7084 	boolean_t	secure;
7085 	in6_addr_t	v6src;
7086 	conn_t		*connp;
7087 	connf_t		*connfp;
7088 	conn_t		*first_connp;
7089 	conn_t		*next_connp;
7090 	mblk_t		*mp1, *first_mp1;
7091 	ipaddr_t	src;
7092 	zoneid_t	last_zoneid;
7093 	boolean_t	reuseaddr;
7094 	boolean_t	shared_addr;
7095 	boolean_t	unlabeled;
7096 	ip_stack_t	*ipst;
7097 
7098 	ASSERT(recv_ill != NULL);
7099 	ipst = recv_ill->ill_ipst;
7100 
7101 	first_mp = mp;
7102 	if (mctl_present) {
7103 		mp = first_mp->b_cont;
7104 		first_mp->b_cont = NULL;
7105 		secure = ipsec_in_is_secure(first_mp);
7106 		ASSERT(mp != NULL);
7107 	} else {
7108 		first_mp = NULL;
7109 		secure = B_FALSE;
7110 	}
7111 
7112 	/* Extract ports in net byte order */
7113 	dstport = htons(ntohl(ports) & 0xFFFF);
7114 	srcport = htons(ntohl(ports) >> 16);
7115 	dst = ipha->ipha_dst;
7116 	src = ipha->ipha_src;
7117 
7118 	unlabeled = B_FALSE;
7119 	if (is_system_labeled())
7120 		/* Cred cannot be null on IPv4 */
7121 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7122 		    TSLF_UNLABELED) != 0;
7123 	shared_addr = (zoneid == ALL_ZONES);
7124 	if (shared_addr) {
7125 		/*
7126 		 * No need to handle exclusive-stack zones since ALL_ZONES
7127 		 * only applies to the shared stack.
7128 		 */
7129 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7130 		/*
7131 		 * If no shared MLP is found, tsol_mlp_findzone returns
7132 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7133 		 * search for the zone based on the packet label.
7134 		 *
7135 		 * If there is such a zone, we prefer to find a
7136 		 * connection in it.  Otherwise, we look for a
7137 		 * MAC-exempt connection in any zone whose label
7138 		 * dominates the default label on the packet.
7139 		 */
7140 		if (zoneid == ALL_ZONES)
7141 			zoneid = tsol_packet_to_zoneid(mp);
7142 		else
7143 			unlabeled = B_FALSE;
7144 	}
7145 
7146 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7147 	mutex_enter(&connfp->connf_lock);
7148 	connp = connfp->connf_head;
7149 	if (!broadcast && !CLASSD(dst)) {
7150 		/*
7151 		 * Not broadcast or multicast. Send to the one (first)
7152 		 * client we find. No need to check conn_wantpacket()
7153 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7154 		 * IPv4 unicast packets.
7155 		 */
7156 		while ((connp != NULL) &&
7157 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7158 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7159 		    !(unlabeled && connp->conn_mac_exempt)))) {
7160 			/*
7161 			 * We keep searching since the conn did not match,
7162 			 * or its zone did not match and it is not either
7163 			 * an allzones conn or a mac exempt conn (if the
7164 			 * sender is unlabeled.)
7165 			 */
7166 			connp = connp->conn_next;
7167 		}
7168 
7169 		if (connp == NULL || connp->conn_upq == NULL)
7170 			goto notfound;
7171 
7172 		if (is_system_labeled() &&
7173 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7174 		    connp))
7175 			goto notfound;
7176 
7177 		CONN_INC_REF(connp);
7178 		mutex_exit(&connfp->connf_lock);
7179 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7180 		    flags, recv_ill, ip_policy);
7181 		IP_STAT(ipst, ip_udp_fannorm);
7182 		CONN_DEC_REF(connp);
7183 		return;
7184 	}
7185 
7186 	/*
7187 	 * Broadcast and multicast case
7188 	 *
7189 	 * Need to check conn_wantpacket().
7190 	 * If SO_REUSEADDR has been set on the first we send the
7191 	 * packet to all clients that have joined the group and
7192 	 * match the port.
7193 	 */
7194 
7195 	while (connp != NULL) {
7196 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7197 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7198 		    (!is_system_labeled() ||
7199 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7200 		    connp)))
7201 			break;
7202 		connp = connp->conn_next;
7203 	}
7204 
7205 	if (connp == NULL || connp->conn_upq == NULL)
7206 		goto notfound;
7207 
7208 	first_connp = connp;
7209 	/*
7210 	 * When SO_REUSEADDR is not set, send the packet only to the first
7211 	 * matching connection in its zone by keeping track of the zoneid.
7212 	 */
7213 	reuseaddr = first_connp->conn_reuseaddr;
7214 	last_zoneid = first_connp->conn_zoneid;
7215 
7216 	CONN_INC_REF(connp);
7217 	connp = connp->conn_next;
7218 	for (;;) {
7219 		while (connp != NULL) {
7220 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7221 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7222 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7223 			    (!is_system_labeled() ||
7224 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7225 			    shared_addr, connp)))
7226 				break;
7227 			connp = connp->conn_next;
7228 		}
7229 		/*
7230 		 * Just copy the data part alone. The mctl part is
7231 		 * needed just for verifying policy and it is never
7232 		 * sent up.
7233 		 */
7234 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7235 		    ((mp1 = copymsg(mp)) == NULL))) {
7236 			/*
7237 			 * No more interested clients or memory
7238 			 * allocation failed
7239 			 */
7240 			connp = first_connp;
7241 			break;
7242 		}
7243 		if (connp->conn_zoneid != last_zoneid) {
7244 			/*
7245 			 * Update the zoneid so that the packet isn't sent to
7246 			 * any more conns in the same zone unless SO_REUSEADDR
7247 			 * is set.
7248 			 */
7249 			reuseaddr = connp->conn_reuseaddr;
7250 			last_zoneid = connp->conn_zoneid;
7251 		}
7252 		if (first_mp != NULL) {
7253 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7254 			    ipsec_info_type == IPSEC_IN);
7255 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7256 			    ipst->ips_netstack);
7257 			if (first_mp1 == NULL) {
7258 				freemsg(mp1);
7259 				connp = first_connp;
7260 				break;
7261 			}
7262 		} else {
7263 			first_mp1 = NULL;
7264 		}
7265 		CONN_INC_REF(connp);
7266 		mutex_exit(&connfp->connf_lock);
7267 		/*
7268 		 * IPQoS notes: We don't send the packet for policy
7269 		 * processing here, will do it for the last one (below).
7270 		 * i.e. we do it per-packet now, but if we do policy
7271 		 * processing per-conn, then we would need to do it
7272 		 * here too.
7273 		 */
7274 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7275 		    ipha, flags, recv_ill, B_FALSE);
7276 		mutex_enter(&connfp->connf_lock);
7277 		/* Follow the next pointer before releasing the conn. */
7278 		next_connp = connp->conn_next;
7279 		IP_STAT(ipst, ip_udp_fanmb);
7280 		CONN_DEC_REF(connp);
7281 		connp = next_connp;
7282 	}
7283 
7284 	/* Last one.  Send it upstream. */
7285 	mutex_exit(&connfp->connf_lock);
7286 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7287 	    recv_ill, ip_policy);
7288 	IP_STAT(ipst, ip_udp_fanmb);
7289 	CONN_DEC_REF(connp);
7290 	return;
7291 
7292 notfound:
7293 
7294 	mutex_exit(&connfp->connf_lock);
7295 	IP_STAT(ipst, ip_udp_fanothers);
7296 	/*
7297 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7298 	 * have already been matched above, since they live in the IPv4
7299 	 * fanout tables. This implies we only need to
7300 	 * check for IPv6 in6addr_any endpoints here.
7301 	 * Thus we compare using ipv6_all_zeros instead of the destination
7302 	 * address, except for the multicast group membership lookup which
7303 	 * uses the IPv4 destination.
7304 	 */
7305 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7306 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7307 	mutex_enter(&connfp->connf_lock);
7308 	connp = connfp->connf_head;
7309 	if (!broadcast && !CLASSD(dst)) {
7310 		while (connp != NULL) {
7311 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7312 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7313 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7314 			    !connp->conn_ipv6_v6only)
7315 				break;
7316 			connp = connp->conn_next;
7317 		}
7318 
7319 		if (connp != NULL && is_system_labeled() &&
7320 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7321 		    connp))
7322 			connp = NULL;
7323 
7324 		if (connp == NULL || connp->conn_upq == NULL) {
7325 			/*
7326 			 * No one bound to this port.  Is
7327 			 * there a client that wants all
7328 			 * unclaimed datagrams?
7329 			 */
7330 			mutex_exit(&connfp->connf_lock);
7331 
7332 			if (mctl_present)
7333 				first_mp->b_cont = mp;
7334 			else
7335 				first_mp = mp;
7336 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7337 			    connf_head != NULL) {
7338 				ip_fanout_proto(q, first_mp, ill, ipha,
7339 				    flags | IP_FF_RAWIP, mctl_present,
7340 				    ip_policy, recv_ill, zoneid);
7341 			} else {
7342 				if (ip_fanout_send_icmp(q, first_mp, flags,
7343 				    ICMP_DEST_UNREACHABLE,
7344 				    ICMP_PORT_UNREACHABLE,
7345 				    mctl_present, zoneid, ipst)) {
7346 					BUMP_MIB(ill->ill_ip_mib,
7347 					    udpIfStatsNoPorts);
7348 				}
7349 			}
7350 			return;
7351 		}
7352 
7353 		CONN_INC_REF(connp);
7354 		mutex_exit(&connfp->connf_lock);
7355 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7356 		    flags, recv_ill, ip_policy);
7357 		CONN_DEC_REF(connp);
7358 		return;
7359 	}
7360 	/*
7361 	 * IPv4 multicast packet being delivered to an AF_INET6
7362 	 * in6addr_any endpoint.
7363 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7364 	 * and not conn_wantpacket_v6() since any multicast membership is
7365 	 * for an IPv4-mapped multicast address.
7366 	 * The packet is sent to all clients in all zones that have joined the
7367 	 * group and match the port.
7368 	 */
7369 	while (connp != NULL) {
7370 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7371 		    srcport, v6src) &&
7372 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7373 		    (!is_system_labeled() ||
7374 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7375 		    connp)))
7376 			break;
7377 		connp = connp->conn_next;
7378 	}
7379 
7380 	if (connp == NULL || connp->conn_upq == NULL) {
7381 		/*
7382 		 * No one bound to this port.  Is
7383 		 * there a client that wants all
7384 		 * unclaimed datagrams?
7385 		 */
7386 		mutex_exit(&connfp->connf_lock);
7387 
7388 		if (mctl_present)
7389 			first_mp->b_cont = mp;
7390 		else
7391 			first_mp = mp;
7392 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7393 		    NULL) {
7394 			ip_fanout_proto(q, first_mp, ill, ipha,
7395 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7396 			    recv_ill, zoneid);
7397 		} else {
7398 			/*
7399 			 * We used to attempt to send an icmp error here, but
7400 			 * since this is known to be a multicast packet
7401 			 * and we don't send icmp errors in response to
7402 			 * multicast, just drop the packet and give up sooner.
7403 			 */
7404 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7405 			freemsg(first_mp);
7406 		}
7407 		return;
7408 	}
7409 
7410 	first_connp = connp;
7411 
7412 	CONN_INC_REF(connp);
7413 	connp = connp->conn_next;
7414 	for (;;) {
7415 		while (connp != NULL) {
7416 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7417 			    ipv6_all_zeros, srcport, v6src) &&
7418 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7419 			    (!is_system_labeled() ||
7420 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7421 			    shared_addr, connp)))
7422 				break;
7423 			connp = connp->conn_next;
7424 		}
7425 		/*
7426 		 * Just copy the data part alone. The mctl part is
7427 		 * needed just for verifying policy and it is never
7428 		 * sent up.
7429 		 */
7430 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7431 		    ((mp1 = copymsg(mp)) == NULL))) {
7432 			/*
7433 			 * No more intested clients or memory
7434 			 * allocation failed
7435 			 */
7436 			connp = first_connp;
7437 			break;
7438 		}
7439 		if (first_mp != NULL) {
7440 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7441 			    ipsec_info_type == IPSEC_IN);
7442 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7443 			    ipst->ips_netstack);
7444 			if (first_mp1 == NULL) {
7445 				freemsg(mp1);
7446 				connp = first_connp;
7447 				break;
7448 			}
7449 		} else {
7450 			first_mp1 = NULL;
7451 		}
7452 		CONN_INC_REF(connp);
7453 		mutex_exit(&connfp->connf_lock);
7454 		/*
7455 		 * IPQoS notes: We don't send the packet for policy
7456 		 * processing here, will do it for the last one (below).
7457 		 * i.e. we do it per-packet now, but if we do policy
7458 		 * processing per-conn, then we would need to do it
7459 		 * here too.
7460 		 */
7461 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7462 		    ipha, flags, recv_ill, B_FALSE);
7463 		mutex_enter(&connfp->connf_lock);
7464 		/* Follow the next pointer before releasing the conn. */
7465 		next_connp = connp->conn_next;
7466 		CONN_DEC_REF(connp);
7467 		connp = next_connp;
7468 	}
7469 
7470 	/* Last one.  Send it upstream. */
7471 	mutex_exit(&connfp->connf_lock);
7472 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7473 	    recv_ill, ip_policy);
7474 	CONN_DEC_REF(connp);
7475 }
7476 
7477 /*
7478  * Complete the ip_wput header so that it
7479  * is possible to generate ICMP
7480  * errors.
7481  */
7482 int
7483 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7484 {
7485 	ire_t *ire;
7486 
7487 	if (ipha->ipha_src == INADDR_ANY) {
7488 		ire = ire_lookup_local(zoneid, ipst);
7489 		if (ire == NULL) {
7490 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7491 			return (1);
7492 		}
7493 		ipha->ipha_src = ire->ire_addr;
7494 		ire_refrele(ire);
7495 	}
7496 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7497 	ipha->ipha_hdr_checksum = 0;
7498 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7499 	return (0);
7500 }
7501 
7502 /*
7503  * Nobody should be sending
7504  * packets up this stream
7505  */
7506 static void
7507 ip_lrput(queue_t *q, mblk_t *mp)
7508 {
7509 	mblk_t *mp1;
7510 
7511 	switch (mp->b_datap->db_type) {
7512 	case M_FLUSH:
7513 		/* Turn around */
7514 		if (*mp->b_rptr & FLUSHW) {
7515 			*mp->b_rptr &= ~FLUSHR;
7516 			qreply(q, mp);
7517 			return;
7518 		}
7519 		break;
7520 	}
7521 	/* Could receive messages that passed through ar_rput */
7522 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7523 		mp1->b_prev = mp1->b_next = NULL;
7524 	freemsg(mp);
7525 }
7526 
7527 /* Nobody should be sending packets down this stream */
7528 /* ARGSUSED */
7529 void
7530 ip_lwput(queue_t *q, mblk_t *mp)
7531 {
7532 	freemsg(mp);
7533 }
7534 
7535 /*
7536  * Move the first hop in any source route to ipha_dst and remove that part of
7537  * the source route.  Called by other protocols.  Errors in option formatting
7538  * are ignored - will be handled by ip_wput_options Return the final
7539  * destination (either ipha_dst or the last entry in a source route.)
7540  */
7541 ipaddr_t
7542 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7543 {
7544 	ipoptp_t	opts;
7545 	uchar_t		*opt;
7546 	uint8_t		optval;
7547 	uint8_t		optlen;
7548 	ipaddr_t	dst;
7549 	int		i;
7550 	ire_t		*ire;
7551 	ip_stack_t	*ipst = ns->netstack_ip;
7552 
7553 	ip2dbg(("ip_massage_options\n"));
7554 	dst = ipha->ipha_dst;
7555 	for (optval = ipoptp_first(&opts, ipha);
7556 	    optval != IPOPT_EOL;
7557 	    optval = ipoptp_next(&opts)) {
7558 		opt = opts.ipoptp_cur;
7559 		switch (optval) {
7560 			uint8_t off;
7561 		case IPOPT_SSRR:
7562 		case IPOPT_LSRR:
7563 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7564 				ip1dbg(("ip_massage_options: bad src route\n"));
7565 				break;
7566 			}
7567 			optlen = opts.ipoptp_len;
7568 			off = opt[IPOPT_OFFSET];
7569 			off--;
7570 		redo_srr:
7571 			if (optlen < IP_ADDR_LEN ||
7572 			    off > optlen - IP_ADDR_LEN) {
7573 				/* End of source route */
7574 				ip1dbg(("ip_massage_options: end of SR\n"));
7575 				break;
7576 			}
7577 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7578 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7579 			    ntohl(dst)));
7580 			/*
7581 			 * Check if our address is present more than
7582 			 * once as consecutive hops in source route.
7583 			 * XXX verify per-interface ip_forwarding
7584 			 * for source route?
7585 			 */
7586 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7587 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7588 			if (ire != NULL) {
7589 				ire_refrele(ire);
7590 				off += IP_ADDR_LEN;
7591 				goto redo_srr;
7592 			}
7593 			if (dst == htonl(INADDR_LOOPBACK)) {
7594 				ip1dbg(("ip_massage_options: loopback addr in "
7595 				    "source route!\n"));
7596 				break;
7597 			}
7598 			/*
7599 			 * Update ipha_dst to be the first hop and remove the
7600 			 * first hop from the source route (by overwriting
7601 			 * part of the option with NOP options).
7602 			 */
7603 			ipha->ipha_dst = dst;
7604 			/* Put the last entry in dst */
7605 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7606 			    3;
7607 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7608 
7609 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7610 			    ntohl(dst)));
7611 			/* Move down and overwrite */
7612 			opt[IP_ADDR_LEN] = opt[0];
7613 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7614 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7615 			for (i = 0; i < IP_ADDR_LEN; i++)
7616 				opt[i] = IPOPT_NOP;
7617 			break;
7618 		}
7619 	}
7620 	return (dst);
7621 }
7622 
7623 /*
7624  * Return the network mask
7625  * associated with the specified address.
7626  */
7627 ipaddr_t
7628 ip_net_mask(ipaddr_t addr)
7629 {
7630 	uchar_t	*up = (uchar_t *)&addr;
7631 	ipaddr_t mask = 0;
7632 	uchar_t	*maskp = (uchar_t *)&mask;
7633 
7634 #if defined(__i386) || defined(__amd64)
7635 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7636 #endif
7637 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7638 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7639 #endif
7640 	if (CLASSD(addr)) {
7641 		maskp[0] = 0xF0;
7642 		return (mask);
7643 	}
7644 
7645 	/* We assume Class E default netmask to be 32 */
7646 	if (CLASSE(addr))
7647 		return (0xffffffffU);
7648 
7649 	if (addr == 0)
7650 		return (0);
7651 	maskp[0] = 0xFF;
7652 	if ((up[0] & 0x80) == 0)
7653 		return (mask);
7654 
7655 	maskp[1] = 0xFF;
7656 	if ((up[0] & 0xC0) == 0x80)
7657 		return (mask);
7658 
7659 	maskp[2] = 0xFF;
7660 	if ((up[0] & 0xE0) == 0xC0)
7661 		return (mask);
7662 
7663 	/* Otherwise return no mask */
7664 	return ((ipaddr_t)0);
7665 }
7666 
7667 /*
7668  * Select an ill for the packet by considering load spreading across
7669  * a different ill in the group if dst_ill is part of some group.
7670  */
7671 ill_t *
7672 ip_newroute_get_dst_ill(ill_t *dst_ill)
7673 {
7674 	ill_t *ill;
7675 
7676 	/*
7677 	 * We schedule irrespective of whether the source address is
7678 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7679 	 */
7680 	ill = illgrp_scheduler(dst_ill);
7681 	if (ill == NULL)
7682 		return (NULL);
7683 
7684 	/*
7685 	 * For groups with names ip_sioctl_groupname ensures that all
7686 	 * ills are of same type. For groups without names, ifgrp_insert
7687 	 * ensures this.
7688 	 */
7689 	ASSERT(dst_ill->ill_type == ill->ill_type);
7690 
7691 	return (ill);
7692 }
7693 
7694 /*
7695  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7696  */
7697 ill_t *
7698 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7699     ip_stack_t *ipst)
7700 {
7701 	ill_t *ret_ill;
7702 
7703 	ASSERT(ifindex != 0);
7704 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7705 	    ipst);
7706 	if (ret_ill == NULL ||
7707 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7708 		if (isv6) {
7709 			if (ill != NULL) {
7710 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7711 			} else {
7712 				BUMP_MIB(&ipst->ips_ip6_mib,
7713 				    ipIfStatsOutDiscards);
7714 			}
7715 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7716 			    "bad ifindex %d.\n", ifindex));
7717 		} else {
7718 			if (ill != NULL) {
7719 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7720 			} else {
7721 				BUMP_MIB(&ipst->ips_ip_mib,
7722 				    ipIfStatsOutDiscards);
7723 			}
7724 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7725 			    "bad ifindex %d.\n", ifindex));
7726 		}
7727 		if (ret_ill != NULL)
7728 			ill_refrele(ret_ill);
7729 		freemsg(first_mp);
7730 		return (NULL);
7731 	}
7732 
7733 	return (ret_ill);
7734 }
7735 
7736 /*
7737  * IPv4 -
7738  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7739  * out a packet to a destination address for which we do not have specific
7740  * (or sufficient) routing information.
7741  *
7742  * NOTE : These are the scopes of some of the variables that point at IRE,
7743  *	  which needs to be followed while making any future modifications
7744  *	  to avoid memory leaks.
7745  *
7746  *	- ire and sire are the entries looked up initially by
7747  *	  ire_ftable_lookup.
7748  *	- ipif_ire is used to hold the interface ire associated with
7749  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7750  *	  it before branching out to error paths.
7751  *	- save_ire is initialized before ire_create, so that ire returned
7752  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7753  *	  before breaking out of the switch.
7754  *
7755  *	Thus on failures, we have to REFRELE only ire and sire, if they
7756  *	are not NULL.
7757  */
7758 void
7759 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7760     zoneid_t zoneid, ip_stack_t *ipst)
7761 {
7762 	areq_t	*areq;
7763 	ipaddr_t gw = 0;
7764 	ire_t	*ire = NULL;
7765 	mblk_t	*res_mp;
7766 	ipaddr_t *addrp;
7767 	ipaddr_t nexthop_addr;
7768 	ipif_t  *src_ipif = NULL;
7769 	ill_t	*dst_ill = NULL;
7770 	ipha_t  *ipha;
7771 	ire_t	*sire = NULL;
7772 	mblk_t	*first_mp;
7773 	ire_t	*save_ire;
7774 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7775 	ushort_t ire_marks = 0;
7776 	boolean_t mctl_present;
7777 	ipsec_out_t *io;
7778 	mblk_t	*saved_mp;
7779 	ire_t	*first_sire = NULL;
7780 	mblk_t	*copy_mp = NULL;
7781 	mblk_t	*xmit_mp = NULL;
7782 	ipaddr_t save_dst;
7783 	uint32_t multirt_flags =
7784 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7785 	boolean_t multirt_is_resolvable;
7786 	boolean_t multirt_resolve_next;
7787 	boolean_t unspec_src;
7788 	boolean_t do_attach_ill = B_FALSE;
7789 	boolean_t ip_nexthop = B_FALSE;
7790 	tsol_ire_gw_secattr_t *attrp = NULL;
7791 	tsol_gcgrp_t *gcgrp = NULL;
7792 	tsol_gcgrp_addr_t ga;
7793 
7794 	if (ip_debug > 2) {
7795 		/* ip1dbg */
7796 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7797 	}
7798 
7799 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7800 	if (mctl_present) {
7801 		io = (ipsec_out_t *)first_mp->b_rptr;
7802 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7803 		ASSERT(zoneid == io->ipsec_out_zoneid);
7804 		ASSERT(zoneid != ALL_ZONES);
7805 	}
7806 
7807 	ipha = (ipha_t *)mp->b_rptr;
7808 
7809 	/* All multicast lookups come through ip_newroute_ipif() */
7810 	if (CLASSD(dst)) {
7811 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7812 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7813 		freemsg(first_mp);
7814 		return;
7815 	}
7816 
7817 	if (mctl_present && io->ipsec_out_attach_if) {
7818 		/* ip_grab_attach_ill returns a held ill */
7819 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7820 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7821 
7822 		/* Failure case frees things for us. */
7823 		if (attach_ill == NULL)
7824 			return;
7825 
7826 		/*
7827 		 * Check if we need an ire that will not be
7828 		 * looked up by anybody else i.e. HIDDEN.
7829 		 */
7830 		if (ill_is_probeonly(attach_ill))
7831 			ire_marks = IRE_MARK_HIDDEN;
7832 	}
7833 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7834 		ip_nexthop = B_TRUE;
7835 		nexthop_addr = io->ipsec_out_nexthop_addr;
7836 	}
7837 	/*
7838 	 * If this IRE is created for forwarding or it is not for
7839 	 * traffic for congestion controlled protocols, mark it as temporary.
7840 	 */
7841 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7842 		ire_marks |= IRE_MARK_TEMPORARY;
7843 
7844 	/*
7845 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7846 	 * chain until it gets the most specific information available.
7847 	 * For example, we know that there is no IRE_CACHE for this dest,
7848 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7849 	 * ire_ftable_lookup will look up the gateway, etc.
7850 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7851 	 * to the destination, of equal netmask length in the forward table,
7852 	 * will be recursively explored. If no information is available
7853 	 * for the final gateway of that route, we force the returned ire
7854 	 * to be equal to sire using MATCH_IRE_PARENT.
7855 	 * At least, in this case we have a starting point (in the buckets)
7856 	 * to look for other routes to the destination in the forward table.
7857 	 * This is actually used only for multirouting, where a list
7858 	 * of routes has to be processed in sequence.
7859 	 *
7860 	 * In the process of coming up with the most specific information,
7861 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7862 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7863 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7864 	 * Two caveats when handling incomplete ire's in ip_newroute:
7865 	 * - we should be careful when accessing its ire_nce (specifically
7866 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7867 	 * - not all legacy code path callers are prepared to handle
7868 	 *   incomplete ire's, so we should not create/add incomplete
7869 	 *   ire_cache entries here. (See discussion about temporary solution
7870 	 *   further below).
7871 	 *
7872 	 * In order to minimize packet dropping, and to preserve existing
7873 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7874 	 * gateway, and instead use the IF_RESOLVER ire to send out
7875 	 * another request to ARP (this is achieved by passing the
7876 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7877 	 * arp response comes back in ip_wput_nondata, we will create
7878 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7879 	 *
7880 	 * Note that this is a temporary solution; the correct solution is
7881 	 * to create an incomplete  per-dst ire_cache entry, and send the
7882 	 * packet out when the gw's nce is resolved. In order to achieve this,
7883 	 * all packet processing must have been completed prior to calling
7884 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7885 	 * to be modified to accomodate this solution.
7886 	 */
7887 	if (ip_nexthop) {
7888 		/*
7889 		 * The first time we come here, we look for an IRE_INTERFACE
7890 		 * entry for the specified nexthop, set the dst to be the
7891 		 * nexthop address and create an IRE_CACHE entry for the
7892 		 * nexthop. The next time around, we are able to find an
7893 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7894 		 * nexthop address and create an IRE_CACHE entry for the
7895 		 * destination address via the specified nexthop.
7896 		 */
7897 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7898 		    MBLK_GETLABEL(mp), ipst);
7899 		if (ire != NULL) {
7900 			gw = nexthop_addr;
7901 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7902 		} else {
7903 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7904 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7905 			    MBLK_GETLABEL(mp),
7906 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7907 			    ipst);
7908 			if (ire != NULL) {
7909 				dst = nexthop_addr;
7910 			}
7911 		}
7912 	} else if (attach_ill == NULL) {
7913 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7914 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7915 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7916 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7917 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7918 		    ipst);
7919 	} else {
7920 		/*
7921 		 * attach_ill is set only for communicating with
7922 		 * on-link hosts. So, don't look for DEFAULT.
7923 		 */
7924 		ipif_t	*attach_ipif;
7925 
7926 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7927 		if (attach_ipif == NULL) {
7928 			ill_refrele(attach_ill);
7929 			goto icmp_err_ret;
7930 		}
7931 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7932 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7933 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7934 		    MATCH_IRE_SECATTR, ipst);
7935 		ipif_refrele(attach_ipif);
7936 	}
7937 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7938 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7939 
7940 	/*
7941 	 * This loop is run only once in most cases.
7942 	 * We loop to resolve further routes only when the destination
7943 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7944 	 */
7945 	do {
7946 		/* Clear the previous iteration's values */
7947 		if (src_ipif != NULL) {
7948 			ipif_refrele(src_ipif);
7949 			src_ipif = NULL;
7950 		}
7951 		if (dst_ill != NULL) {
7952 			ill_refrele(dst_ill);
7953 			dst_ill = NULL;
7954 		}
7955 
7956 		multirt_resolve_next = B_FALSE;
7957 		/*
7958 		 * We check if packets have to be multirouted.
7959 		 * In this case, given the current <ire, sire> couple,
7960 		 * we look for the next suitable <ire, sire>.
7961 		 * This check is done in ire_multirt_lookup(),
7962 		 * which applies various criteria to find the next route
7963 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7964 		 * unchanged if it detects it has not been tried yet.
7965 		 */
7966 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7967 			ip3dbg(("ip_newroute: starting next_resolution "
7968 			    "with first_mp %p, tag %d\n",
7969 			    (void *)first_mp,
7970 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7971 
7972 			ASSERT(sire != NULL);
7973 			multirt_is_resolvable =
7974 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7975 			    MBLK_GETLABEL(mp), ipst);
7976 
7977 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7978 			    "ire %p, sire %p\n",
7979 			    multirt_is_resolvable,
7980 			    (void *)ire, (void *)sire));
7981 
7982 			if (!multirt_is_resolvable) {
7983 				/*
7984 				 * No more multirt route to resolve; give up
7985 				 * (all routes resolved or no more
7986 				 * resolvable routes).
7987 				 */
7988 				if (ire != NULL) {
7989 					ire_refrele(ire);
7990 					ire = NULL;
7991 				}
7992 			} else {
7993 				ASSERT(sire != NULL);
7994 				ASSERT(ire != NULL);
7995 				/*
7996 				 * We simply use first_sire as a flag that
7997 				 * indicates if a resolvable multirt route
7998 				 * has already been found.
7999 				 * If it is not the case, we may have to send
8000 				 * an ICMP error to report that the
8001 				 * destination is unreachable.
8002 				 * We do not IRE_REFHOLD first_sire.
8003 				 */
8004 				if (first_sire == NULL) {
8005 					first_sire = sire;
8006 				}
8007 			}
8008 		}
8009 		if (ire == NULL) {
8010 			if (ip_debug > 3) {
8011 				/* ip2dbg */
8012 				pr_addr_dbg("ip_newroute: "
8013 				    "can't resolve %s\n", AF_INET, &dst);
8014 			}
8015 			ip3dbg(("ip_newroute: "
8016 			    "ire %p, sire %p, first_sire %p\n",
8017 			    (void *)ire, (void *)sire, (void *)first_sire));
8018 
8019 			if (sire != NULL) {
8020 				ire_refrele(sire);
8021 				sire = NULL;
8022 			}
8023 
8024 			if (first_sire != NULL) {
8025 				/*
8026 				 * At least one multirt route has been found
8027 				 * in the same call to ip_newroute();
8028 				 * there is no need to report an ICMP error.
8029 				 * first_sire was not IRE_REFHOLDed.
8030 				 */
8031 				MULTIRT_DEBUG_UNTAG(first_mp);
8032 				freemsg(first_mp);
8033 				return;
8034 			}
8035 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8036 			    RTA_DST, ipst);
8037 			if (attach_ill != NULL)
8038 				ill_refrele(attach_ill);
8039 			goto icmp_err_ret;
8040 		}
8041 
8042 		/*
8043 		 * Verify that the returned IRE does not have either
8044 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8045 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8046 		 */
8047 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8048 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8049 			if (attach_ill != NULL)
8050 				ill_refrele(attach_ill);
8051 			goto icmp_err_ret;
8052 		}
8053 		/*
8054 		 * Increment the ire_ob_pkt_count field for ire if it is an
8055 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8056 		 * increment the same for the parent IRE, sire, if it is some
8057 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8058 		 */
8059 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8060 			UPDATE_OB_PKT_COUNT(ire);
8061 			ire->ire_last_used_time = lbolt;
8062 		}
8063 
8064 		if (sire != NULL) {
8065 			gw = sire->ire_gateway_addr;
8066 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8067 			    IRE_INTERFACE)) == 0);
8068 			UPDATE_OB_PKT_COUNT(sire);
8069 			sire->ire_last_used_time = lbolt;
8070 		}
8071 		/*
8072 		 * We have a route to reach the destination.
8073 		 *
8074 		 * 1) If the interface is part of ill group, try to get a new
8075 		 *    ill taking load spreading into account.
8076 		 *
8077 		 * 2) After selecting the ill, get a source address that
8078 		 *    might create good inbound load spreading.
8079 		 *    ipif_select_source does this for us.
8080 		 *
8081 		 * If the application specified the ill (ifindex), we still
8082 		 * load spread. Only if the packets needs to go out
8083 		 * specifically on a given ill e.g. binding to
8084 		 * IPIF_NOFAILOVER address, then we don't try to use a
8085 		 * different ill for load spreading.
8086 		 */
8087 		if (attach_ill == NULL) {
8088 			/*
8089 			 * Don't perform outbound load spreading in the
8090 			 * case of an RTF_MULTIRT route, as we actually
8091 			 * typically want to replicate outgoing packets
8092 			 * through particular interfaces.
8093 			 */
8094 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8095 				dst_ill = ire->ire_ipif->ipif_ill;
8096 				/* for uniformity */
8097 				ill_refhold(dst_ill);
8098 			} else {
8099 				/*
8100 				 * If we are here trying to create an IRE_CACHE
8101 				 * for an offlink destination and have the
8102 				 * IRE_CACHE for the next hop and the latter is
8103 				 * using virtual IP source address selection i.e
8104 				 * it's ire->ire_ipif is pointing to a virtual
8105 				 * network interface (vni) then
8106 				 * ip_newroute_get_dst_ll() will return the vni
8107 				 * interface as the dst_ill. Since the vni is
8108 				 * virtual i.e not associated with any physical
8109 				 * interface, it cannot be the dst_ill, hence
8110 				 * in such a case call ip_newroute_get_dst_ll()
8111 				 * with the stq_ill instead of the ire_ipif ILL.
8112 				 * The function returns a refheld ill.
8113 				 */
8114 				if ((ire->ire_type == IRE_CACHE) &&
8115 				    IS_VNI(ire->ire_ipif->ipif_ill))
8116 					dst_ill = ip_newroute_get_dst_ill(
8117 					    ire->ire_stq->q_ptr);
8118 				else
8119 					dst_ill = ip_newroute_get_dst_ill(
8120 					    ire->ire_ipif->ipif_ill);
8121 			}
8122 			if (dst_ill == NULL) {
8123 				if (ip_debug > 2) {
8124 					pr_addr_dbg("ip_newroute: "
8125 					    "no dst ill for dst"
8126 					    " %s\n", AF_INET, &dst);
8127 				}
8128 				goto icmp_err_ret;
8129 			}
8130 		} else {
8131 			dst_ill = ire->ire_ipif->ipif_ill;
8132 			/* for uniformity */
8133 			ill_refhold(dst_ill);
8134 			/*
8135 			 * We should have found a route matching ill as we
8136 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8137 			 * Rather than asserting, when there is a mismatch,
8138 			 * we just drop the packet.
8139 			 */
8140 			if (dst_ill != attach_ill) {
8141 				ip0dbg(("ip_newroute: Packet dropped as "
8142 				    "IPIF_NOFAILOVER ill is %s, "
8143 				    "ire->ire_ipif->ipif_ill is %s\n",
8144 				    attach_ill->ill_name,
8145 				    dst_ill->ill_name));
8146 				ill_refrele(attach_ill);
8147 				goto icmp_err_ret;
8148 			}
8149 		}
8150 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8151 		if (attach_ill != NULL) {
8152 			ill_refrele(attach_ill);
8153 			attach_ill = NULL;
8154 			do_attach_ill = B_TRUE;
8155 		}
8156 		ASSERT(dst_ill != NULL);
8157 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8158 
8159 		/*
8160 		 * Pick the best source address from dst_ill.
8161 		 *
8162 		 * 1) If it is part of a multipathing group, we would
8163 		 *    like to spread the inbound packets across different
8164 		 *    interfaces. ipif_select_source picks a random source
8165 		 *    across the different ills in the group.
8166 		 *
8167 		 * 2) If it is not part of a multipathing group, we try
8168 		 *    to pick the source address from the destination
8169 		 *    route. Clustering assumes that when we have multiple
8170 		 *    prefixes hosted on an interface, the prefix of the
8171 		 *    source address matches the prefix of the destination
8172 		 *    route. We do this only if the address is not
8173 		 *    DEPRECATED.
8174 		 *
8175 		 * 3) If the conn is in a different zone than the ire, we
8176 		 *    need to pick a source address from the right zone.
8177 		 *
8178 		 * NOTE : If we hit case (1) above, the prefix of the source
8179 		 *	  address picked may not match the prefix of the
8180 		 *	  destination routes prefix as ipif_select_source
8181 		 *	  does not look at "dst" while picking a source
8182 		 *	  address.
8183 		 *	  If we want the same behavior as (2), we will need
8184 		 *	  to change the behavior of ipif_select_source.
8185 		 */
8186 		ASSERT(src_ipif == NULL);
8187 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8188 			/*
8189 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8190 			 * Check that the ipif matching the requested source
8191 			 * address still exists.
8192 			 */
8193 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8194 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8195 		}
8196 
8197 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8198 
8199 		if (src_ipif == NULL &&
8200 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8201 			ire_marks |= IRE_MARK_USESRC_CHECK;
8202 			if ((dst_ill->ill_group != NULL) ||
8203 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8204 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8205 			    ire->ire_zoneid != ALL_ZONES) ||
8206 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8207 				/*
8208 				 * If the destination is reachable via a
8209 				 * given gateway, the selected source address
8210 				 * should be in the same subnet as the gateway.
8211 				 * Otherwise, the destination is not reachable.
8212 				 *
8213 				 * If there are no interfaces on the same subnet
8214 				 * as the destination, ipif_select_source gives
8215 				 * first non-deprecated interface which might be
8216 				 * on a different subnet than the gateway.
8217 				 * This is not desirable. Hence pass the dst_ire
8218 				 * source address to ipif_select_source.
8219 				 * It is sure that the destination is reachable
8220 				 * with the dst_ire source address subnet.
8221 				 * So passing dst_ire source address to
8222 				 * ipif_select_source will make sure that the
8223 				 * selected source will be on the same subnet
8224 				 * as dst_ire source address.
8225 				 */
8226 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8227 				src_ipif = ipif_select_source(dst_ill, saddr,
8228 				    zoneid);
8229 				if (src_ipif == NULL) {
8230 					if (ip_debug > 2) {
8231 						pr_addr_dbg("ip_newroute: "
8232 						    "no src for dst %s ",
8233 						    AF_INET, &dst);
8234 						printf("through interface %s\n",
8235 						    dst_ill->ill_name);
8236 					}
8237 					goto icmp_err_ret;
8238 				}
8239 			} else {
8240 				src_ipif = ire->ire_ipif;
8241 				ASSERT(src_ipif != NULL);
8242 				/* hold src_ipif for uniformity */
8243 				ipif_refhold(src_ipif);
8244 			}
8245 		}
8246 
8247 		/*
8248 		 * Assign a source address while we have the conn.
8249 		 * We can't have ip_wput_ire pick a source address when the
8250 		 * packet returns from arp since we need to look at
8251 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8252 		 * going through arp.
8253 		 *
8254 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8255 		 *	  it uses ip6i to store this information.
8256 		 */
8257 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8258 			ipha->ipha_src = src_ipif->ipif_src_addr;
8259 
8260 		if (ip_debug > 3) {
8261 			/* ip2dbg */
8262 			pr_addr_dbg("ip_newroute: first hop %s\n",
8263 			    AF_INET, &gw);
8264 		}
8265 		ip2dbg(("\tire type %s (%d)\n",
8266 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8267 
8268 		/*
8269 		 * The TTL of multirouted packets is bounded by the
8270 		 * ip_multirt_ttl ndd variable.
8271 		 */
8272 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8273 			/* Force TTL of multirouted packets */
8274 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8275 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8276 				ip2dbg(("ip_newroute: forcing multirt TTL "
8277 				    "to %d (was %d), dst 0x%08x\n",
8278 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8279 				    ntohl(sire->ire_addr)));
8280 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8281 			}
8282 		}
8283 		/*
8284 		 * At this point in ip_newroute(), ire is either the
8285 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8286 		 * destination or an IRE_INTERFACE type that should be used
8287 		 * to resolve an on-subnet destination or an on-subnet
8288 		 * next-hop gateway.
8289 		 *
8290 		 * In the IRE_CACHE case, we have the following :
8291 		 *
8292 		 * 1) src_ipif - used for getting a source address.
8293 		 *
8294 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8295 		 *    means packets using this IRE_CACHE will go out on
8296 		 *    dst_ill.
8297 		 *
8298 		 * 3) The IRE sire will point to the prefix that is the
8299 		 *    longest  matching route for the destination. These
8300 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8301 		 *
8302 		 *    The newly created IRE_CACHE entry for the off-subnet
8303 		 *    destination is tied to both the prefix route and the
8304 		 *    interface route used to resolve the next-hop gateway
8305 		 *    via the ire_phandle and ire_ihandle fields,
8306 		 *    respectively.
8307 		 *
8308 		 * In the IRE_INTERFACE case, we have the following :
8309 		 *
8310 		 * 1) src_ipif - used for getting a source address.
8311 		 *
8312 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8313 		 *    means packets using the IRE_CACHE that we will build
8314 		 *    here will go out on dst_ill.
8315 		 *
8316 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8317 		 *    to be created will only be tied to the IRE_INTERFACE
8318 		 *    that was derived from the ire_ihandle field.
8319 		 *
8320 		 *    If sire is non-NULL, it means the destination is
8321 		 *    off-link and we will first create the IRE_CACHE for the
8322 		 *    gateway. Next time through ip_newroute, we will create
8323 		 *    the IRE_CACHE for the final destination as described
8324 		 *    above.
8325 		 *
8326 		 * In both cases, after the current resolution has been
8327 		 * completed (or possibly initialised, in the IRE_INTERFACE
8328 		 * case), the loop may be re-entered to attempt the resolution
8329 		 * of another RTF_MULTIRT route.
8330 		 *
8331 		 * When an IRE_CACHE entry for the off-subnet destination is
8332 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8333 		 * for further processing in emission loops.
8334 		 */
8335 		save_ire = ire;
8336 		switch (ire->ire_type) {
8337 		case IRE_CACHE: {
8338 			ire_t	*ipif_ire;
8339 
8340 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8341 			if (gw == 0)
8342 				gw = ire->ire_gateway_addr;
8343 			/*
8344 			 * We need 3 ire's to create a new cache ire for an
8345 			 * off-link destination from the cache ire of the
8346 			 * gateway.
8347 			 *
8348 			 *	1. The prefix ire 'sire' (Note that this does
8349 			 *	   not apply to the conn_nexthop_set case)
8350 			 *	2. The cache ire of the gateway 'ire'
8351 			 *	3. The interface ire 'ipif_ire'
8352 			 *
8353 			 * We have (1) and (2). We lookup (3) below.
8354 			 *
8355 			 * If there is no interface route to the gateway,
8356 			 * it is a race condition, where we found the cache
8357 			 * but the interface route has been deleted.
8358 			 */
8359 			if (ip_nexthop) {
8360 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8361 			} else {
8362 				ipif_ire =
8363 				    ire_ihandle_lookup_offlink(ire, sire);
8364 			}
8365 			if (ipif_ire == NULL) {
8366 				ip1dbg(("ip_newroute: "
8367 				    "ire_ihandle_lookup_offlink failed\n"));
8368 				goto icmp_err_ret;
8369 			}
8370 
8371 			/*
8372 			 * Check cached gateway IRE for any security
8373 			 * attributes; if found, associate the gateway
8374 			 * credentials group to the destination IRE.
8375 			 */
8376 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8377 				mutex_enter(&attrp->igsa_lock);
8378 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8379 					GCGRP_REFHOLD(gcgrp);
8380 				mutex_exit(&attrp->igsa_lock);
8381 			}
8382 
8383 			/*
8384 			 * XXX For the source of the resolver mp,
8385 			 * we are using the same DL_UNITDATA_REQ
8386 			 * (from save_ire->ire_nce->nce_res_mp)
8387 			 * though the save_ire is not pointing at the same ill.
8388 			 * This is incorrect. We need to send it up to the
8389 			 * resolver to get the right res_mp. For ethernets
8390 			 * this may be okay (ill_type == DL_ETHER).
8391 			 */
8392 
8393 			ire = ire_create(
8394 			    (uchar_t *)&dst,		/* dest address */
8395 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8396 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8397 			    (uchar_t *)&gw,		/* gateway address */
8398 			    &save_ire->ire_max_frag,
8399 			    save_ire->ire_nce,		/* src nce */
8400 			    dst_ill->ill_rq,		/* recv-from queue */
8401 			    dst_ill->ill_wq,		/* send-to queue */
8402 			    IRE_CACHE,			/* IRE type */
8403 			    src_ipif,
8404 			    (sire != NULL) ?
8405 			    sire->ire_mask : 0, 	/* Parent mask */
8406 			    (sire != NULL) ?
8407 			    sire->ire_phandle : 0,	/* Parent handle */
8408 			    ipif_ire->ire_ihandle,	/* Interface handle */
8409 			    (sire != NULL) ? (sire->ire_flags &
8410 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8411 			    (sire != NULL) ?
8412 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8413 			    NULL,
8414 			    gcgrp,
8415 			    ipst);
8416 
8417 			if (ire == NULL) {
8418 				if (gcgrp != NULL) {
8419 					GCGRP_REFRELE(gcgrp);
8420 					gcgrp = NULL;
8421 				}
8422 				ire_refrele(ipif_ire);
8423 				ire_refrele(save_ire);
8424 				break;
8425 			}
8426 
8427 			/* reference now held by IRE */
8428 			gcgrp = NULL;
8429 
8430 			ire->ire_marks |= ire_marks;
8431 
8432 			/*
8433 			 * Prevent sire and ipif_ire from getting deleted.
8434 			 * The newly created ire is tied to both of them via
8435 			 * the phandle and ihandle respectively.
8436 			 */
8437 			if (sire != NULL) {
8438 				IRB_REFHOLD(sire->ire_bucket);
8439 				/* Has it been removed already ? */
8440 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8441 					IRB_REFRELE(sire->ire_bucket);
8442 					ire_refrele(ipif_ire);
8443 					ire_refrele(save_ire);
8444 					break;
8445 				}
8446 			}
8447 
8448 			IRB_REFHOLD(ipif_ire->ire_bucket);
8449 			/* Has it been removed already ? */
8450 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8451 				IRB_REFRELE(ipif_ire->ire_bucket);
8452 				if (sire != NULL)
8453 					IRB_REFRELE(sire->ire_bucket);
8454 				ire_refrele(ipif_ire);
8455 				ire_refrele(save_ire);
8456 				break;
8457 			}
8458 
8459 			xmit_mp = first_mp;
8460 			/*
8461 			 * In the case of multirouting, a copy
8462 			 * of the packet is done before its sending.
8463 			 * The copy is used to attempt another
8464 			 * route resolution, in a next loop.
8465 			 */
8466 			if (ire->ire_flags & RTF_MULTIRT) {
8467 				copy_mp = copymsg(first_mp);
8468 				if (copy_mp != NULL) {
8469 					xmit_mp = copy_mp;
8470 					MULTIRT_DEBUG_TAG(first_mp);
8471 				}
8472 			}
8473 			ire_add_then_send(q, ire, xmit_mp);
8474 			ire_refrele(save_ire);
8475 
8476 			/* Assert that sire is not deleted yet. */
8477 			if (sire != NULL) {
8478 				ASSERT(sire->ire_ptpn != NULL);
8479 				IRB_REFRELE(sire->ire_bucket);
8480 			}
8481 
8482 			/* Assert that ipif_ire is not deleted yet. */
8483 			ASSERT(ipif_ire->ire_ptpn != NULL);
8484 			IRB_REFRELE(ipif_ire->ire_bucket);
8485 			ire_refrele(ipif_ire);
8486 
8487 			/*
8488 			 * If copy_mp is not NULL, multirouting was
8489 			 * requested. We loop to initiate a next
8490 			 * route resolution attempt, starting from sire.
8491 			 */
8492 			if (copy_mp != NULL) {
8493 				/*
8494 				 * Search for the next unresolved
8495 				 * multirt route.
8496 				 */
8497 				copy_mp = NULL;
8498 				ipif_ire = NULL;
8499 				ire = NULL;
8500 				multirt_resolve_next = B_TRUE;
8501 				continue;
8502 			}
8503 			if (sire != NULL)
8504 				ire_refrele(sire);
8505 			ipif_refrele(src_ipif);
8506 			ill_refrele(dst_ill);
8507 			return;
8508 		}
8509 		case IRE_IF_NORESOLVER: {
8510 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8511 			    dst_ill->ill_resolver_mp == NULL) {
8512 				ip1dbg(("ip_newroute: dst_ill %p "
8513 				    "for IRE_IF_NORESOLVER ire %p has "
8514 				    "no ill_resolver_mp\n",
8515 				    (void *)dst_ill, (void *)ire));
8516 				break;
8517 			}
8518 
8519 			/*
8520 			 * TSol note: We are creating the ire cache for the
8521 			 * destination 'dst'. If 'dst' is offlink, going
8522 			 * through the first hop 'gw', the security attributes
8523 			 * of 'dst' must be set to point to the gateway
8524 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8525 			 * is possible that 'dst' is a potential gateway that is
8526 			 * referenced by some route that has some security
8527 			 * attributes. Thus in the former case, we need to do a
8528 			 * gcgrp_lookup of 'gw' while in the latter case we
8529 			 * need to do gcgrp_lookup of 'dst' itself.
8530 			 */
8531 			ga.ga_af = AF_INET;
8532 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8533 			    &ga.ga_addr);
8534 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8535 
8536 			ire = ire_create(
8537 			    (uchar_t *)&dst,		/* dest address */
8538 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8539 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8540 			    (uchar_t *)&gw,		/* gateway address */
8541 			    &save_ire->ire_max_frag,
8542 			    NULL,			/* no src nce */
8543 			    dst_ill->ill_rq,		/* recv-from queue */
8544 			    dst_ill->ill_wq,		/* send-to queue */
8545 			    IRE_CACHE,
8546 			    src_ipif,
8547 			    save_ire->ire_mask,		/* Parent mask */
8548 			    (sire != NULL) ?		/* Parent handle */
8549 			    sire->ire_phandle : 0,
8550 			    save_ire->ire_ihandle,	/* Interface handle */
8551 			    (sire != NULL) ? sire->ire_flags &
8552 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8553 			    &(save_ire->ire_uinfo),
8554 			    NULL,
8555 			    gcgrp,
8556 			    ipst);
8557 
8558 			if (ire == NULL) {
8559 				if (gcgrp != NULL) {
8560 					GCGRP_REFRELE(gcgrp);
8561 					gcgrp = NULL;
8562 				}
8563 				ire_refrele(save_ire);
8564 				break;
8565 			}
8566 
8567 			/* reference now held by IRE */
8568 			gcgrp = NULL;
8569 
8570 			ire->ire_marks |= ire_marks;
8571 
8572 			/* Prevent save_ire from getting deleted */
8573 			IRB_REFHOLD(save_ire->ire_bucket);
8574 			/* Has it been removed already ? */
8575 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8576 				IRB_REFRELE(save_ire->ire_bucket);
8577 				ire_refrele(save_ire);
8578 				break;
8579 			}
8580 
8581 			/*
8582 			 * In the case of multirouting, a copy
8583 			 * of the packet is made before it is sent.
8584 			 * The copy is used in the next
8585 			 * loop to attempt another resolution.
8586 			 */
8587 			xmit_mp = first_mp;
8588 			if ((sire != NULL) &&
8589 			    (sire->ire_flags & RTF_MULTIRT)) {
8590 				copy_mp = copymsg(first_mp);
8591 				if (copy_mp != NULL) {
8592 					xmit_mp = copy_mp;
8593 					MULTIRT_DEBUG_TAG(first_mp);
8594 				}
8595 			}
8596 			ire_add_then_send(q, ire, xmit_mp);
8597 
8598 			/* Assert that it is not deleted yet. */
8599 			ASSERT(save_ire->ire_ptpn != NULL);
8600 			IRB_REFRELE(save_ire->ire_bucket);
8601 			ire_refrele(save_ire);
8602 
8603 			if (copy_mp != NULL) {
8604 				/*
8605 				 * If we found a (no)resolver, we ignore any
8606 				 * trailing top priority IRE_CACHE in further
8607 				 * loops. This ensures that we do not omit any
8608 				 * (no)resolver.
8609 				 * This IRE_CACHE, if any, will be processed
8610 				 * by another thread entering ip_newroute().
8611 				 * IRE_CACHE entries, if any, will be processed
8612 				 * by another thread entering ip_newroute(),
8613 				 * (upon resolver response, for instance).
8614 				 * This aims to force parallel multirt
8615 				 * resolutions as soon as a packet must be sent.
8616 				 * In the best case, after the tx of only one
8617 				 * packet, all reachable routes are resolved.
8618 				 * Otherwise, the resolution of all RTF_MULTIRT
8619 				 * routes would require several emissions.
8620 				 */
8621 				multirt_flags &= ~MULTIRT_CACHEGW;
8622 
8623 				/*
8624 				 * Search for the next unresolved multirt
8625 				 * route.
8626 				 */
8627 				copy_mp = NULL;
8628 				save_ire = NULL;
8629 				ire = NULL;
8630 				multirt_resolve_next = B_TRUE;
8631 				continue;
8632 			}
8633 
8634 			/*
8635 			 * Don't need sire anymore
8636 			 */
8637 			if (sire != NULL)
8638 				ire_refrele(sire);
8639 
8640 			ipif_refrele(src_ipif);
8641 			ill_refrele(dst_ill);
8642 			return;
8643 		}
8644 		case IRE_IF_RESOLVER:
8645 			/*
8646 			 * We can't build an IRE_CACHE yet, but at least we
8647 			 * found a resolver that can help.
8648 			 */
8649 			res_mp = dst_ill->ill_resolver_mp;
8650 			if (!OK_RESOLVER_MP(res_mp))
8651 				break;
8652 
8653 			/*
8654 			 * To be at this point in the code with a non-zero gw
8655 			 * means that dst is reachable through a gateway that
8656 			 * we have never resolved.  By changing dst to the gw
8657 			 * addr we resolve the gateway first.
8658 			 * When ire_add_then_send() tries to put the IP dg
8659 			 * to dst, it will reenter ip_newroute() at which
8660 			 * time we will find the IRE_CACHE for the gw and
8661 			 * create another IRE_CACHE in case IRE_CACHE above.
8662 			 */
8663 			if (gw != INADDR_ANY) {
8664 				/*
8665 				 * The source ipif that was determined above was
8666 				 * relative to the destination address, not the
8667 				 * gateway's. If src_ipif was not taken out of
8668 				 * the IRE_IF_RESOLVER entry, we'll need to call
8669 				 * ipif_select_source() again.
8670 				 */
8671 				if (src_ipif != ire->ire_ipif) {
8672 					ipif_refrele(src_ipif);
8673 					src_ipif = ipif_select_source(dst_ill,
8674 					    gw, zoneid);
8675 					if (src_ipif == NULL) {
8676 						if (ip_debug > 2) {
8677 							pr_addr_dbg(
8678 							    "ip_newroute: no "
8679 							    "src for gw %s ",
8680 							    AF_INET, &gw);
8681 							printf("through "
8682 							    "interface %s\n",
8683 							    dst_ill->ill_name);
8684 						}
8685 						goto icmp_err_ret;
8686 					}
8687 				}
8688 				save_dst = dst;
8689 				dst = gw;
8690 				gw = INADDR_ANY;
8691 			}
8692 
8693 			/*
8694 			 * We obtain a partial IRE_CACHE which we will pass
8695 			 * along with the resolver query.  When the response
8696 			 * comes back it will be there ready for us to add.
8697 			 * The ire_max_frag is atomically set under the
8698 			 * irebucket lock in ire_add_v[46].
8699 			 */
8700 
8701 			ire = ire_create_mp(
8702 			    (uchar_t *)&dst,		/* dest address */
8703 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8704 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8705 			    (uchar_t *)&gw,		/* gateway address */
8706 			    NULL,			/* ire_max_frag */
8707 			    NULL,			/* no src nce */
8708 			    dst_ill->ill_rq,		/* recv-from queue */
8709 			    dst_ill->ill_wq,		/* send-to queue */
8710 			    IRE_CACHE,
8711 			    src_ipif,			/* Interface ipif */
8712 			    save_ire->ire_mask,		/* Parent mask */
8713 			    0,
8714 			    save_ire->ire_ihandle,	/* Interface handle */
8715 			    0,				/* flags if any */
8716 			    &(save_ire->ire_uinfo),
8717 			    NULL,
8718 			    NULL,
8719 			    ipst);
8720 
8721 			if (ire == NULL) {
8722 				ire_refrele(save_ire);
8723 				break;
8724 			}
8725 
8726 			if ((sire != NULL) &&
8727 			    (sire->ire_flags & RTF_MULTIRT)) {
8728 				copy_mp = copymsg(first_mp);
8729 				if (copy_mp != NULL)
8730 					MULTIRT_DEBUG_TAG(copy_mp);
8731 			}
8732 
8733 			ire->ire_marks |= ire_marks;
8734 
8735 			/*
8736 			 * Construct message chain for the resolver
8737 			 * of the form:
8738 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8739 			 * Packet could contain a IPSEC_OUT mp.
8740 			 *
8741 			 * NOTE : ire will be added later when the response
8742 			 * comes back from ARP. If the response does not
8743 			 * come back, ARP frees the packet. For this reason,
8744 			 * we can't REFHOLD the bucket of save_ire to prevent
8745 			 * deletions. We may not be able to REFRELE the bucket
8746 			 * if the response never comes back. Thus, before
8747 			 * adding the ire, ire_add_v4 will make sure that the
8748 			 * interface route does not get deleted. This is the
8749 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8750 			 * where we can always prevent deletions because of
8751 			 * the synchronous nature of adding IRES i.e
8752 			 * ire_add_then_send is called after creating the IRE.
8753 			 */
8754 			ASSERT(ire->ire_mp != NULL);
8755 			ire->ire_mp->b_cont = first_mp;
8756 			/* Have saved_mp handy, for cleanup if canput fails */
8757 			saved_mp = mp;
8758 			mp = copyb(res_mp);
8759 			if (mp == NULL) {
8760 				/* Prepare for cleanup */
8761 				mp = saved_mp; /* pkt */
8762 				ire_delete(ire); /* ire_mp */
8763 				ire = NULL;
8764 				ire_refrele(save_ire);
8765 				if (copy_mp != NULL) {
8766 					MULTIRT_DEBUG_UNTAG(copy_mp);
8767 					freemsg(copy_mp);
8768 					copy_mp = NULL;
8769 				}
8770 				break;
8771 			}
8772 			linkb(mp, ire->ire_mp);
8773 
8774 			/*
8775 			 * Fill in the source and dest addrs for the resolver.
8776 			 * NOTE: this depends on memory layouts imposed by
8777 			 * ill_init().
8778 			 */
8779 			areq = (areq_t *)mp->b_rptr;
8780 			addrp = (ipaddr_t *)((char *)areq +
8781 			    areq->areq_sender_addr_offset);
8782 			if (do_attach_ill) {
8783 				/*
8784 				 * This is bind to no failover case.
8785 				 * arp packet also must go out on attach_ill.
8786 				 */
8787 				ASSERT(ipha->ipha_src != NULL);
8788 				*addrp = ipha->ipha_src;
8789 			} else {
8790 				*addrp = save_ire->ire_src_addr;
8791 			}
8792 
8793 			ire_refrele(save_ire);
8794 			addrp = (ipaddr_t *)((char *)areq +
8795 			    areq->areq_target_addr_offset);
8796 			*addrp = dst;
8797 			/* Up to the resolver. */
8798 			if (canputnext(dst_ill->ill_rq) &&
8799 			    !(dst_ill->ill_arp_closing)) {
8800 				putnext(dst_ill->ill_rq, mp);
8801 				ire = NULL;
8802 				if (copy_mp != NULL) {
8803 					/*
8804 					 * If we found a resolver, we ignore
8805 					 * any trailing top priority IRE_CACHE
8806 					 * in the further loops. This ensures
8807 					 * that we do not omit any resolver.
8808 					 * IRE_CACHE entries, if any, will be
8809 					 * processed next time we enter
8810 					 * ip_newroute().
8811 					 */
8812 					multirt_flags &= ~MULTIRT_CACHEGW;
8813 					/*
8814 					 * Search for the next unresolved
8815 					 * multirt route.
8816 					 */
8817 					first_mp = copy_mp;
8818 					copy_mp = NULL;
8819 					/* Prepare the next resolution loop. */
8820 					mp = first_mp;
8821 					EXTRACT_PKT_MP(mp, first_mp,
8822 					    mctl_present);
8823 					if (mctl_present)
8824 						io = (ipsec_out_t *)
8825 						    first_mp->b_rptr;
8826 					ipha = (ipha_t *)mp->b_rptr;
8827 
8828 					ASSERT(sire != NULL);
8829 
8830 					dst = save_dst;
8831 					multirt_resolve_next = B_TRUE;
8832 					continue;
8833 				}
8834 
8835 				if (sire != NULL)
8836 					ire_refrele(sire);
8837 
8838 				/*
8839 				 * The response will come back in ip_wput
8840 				 * with db_type IRE_DB_TYPE.
8841 				 */
8842 				ipif_refrele(src_ipif);
8843 				ill_refrele(dst_ill);
8844 				return;
8845 			} else {
8846 				/* Prepare for cleanup */
8847 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8848 				    mp);
8849 				mp->b_cont = NULL;
8850 				freeb(mp); /* areq */
8851 				/*
8852 				 * this is an ire that is not added to the
8853 				 * cache. ire_freemblk will handle the release
8854 				 * of any resources associated with the ire.
8855 				 */
8856 				ire_delete(ire); /* ire_mp */
8857 				mp = saved_mp; /* pkt */
8858 				ire = NULL;
8859 				if (copy_mp != NULL) {
8860 					MULTIRT_DEBUG_UNTAG(copy_mp);
8861 					freemsg(copy_mp);
8862 					copy_mp = NULL;
8863 				}
8864 				break;
8865 			}
8866 		default:
8867 			break;
8868 		}
8869 	} while (multirt_resolve_next);
8870 
8871 	ip1dbg(("ip_newroute: dropped\n"));
8872 	/* Did this packet originate externally? */
8873 	if (mp->b_prev) {
8874 		mp->b_next = NULL;
8875 		mp->b_prev = NULL;
8876 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8877 	} else {
8878 		if (dst_ill != NULL) {
8879 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8880 		} else {
8881 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8882 		}
8883 	}
8884 	ASSERT(copy_mp == NULL);
8885 	MULTIRT_DEBUG_UNTAG(first_mp);
8886 	freemsg(first_mp);
8887 	if (ire != NULL)
8888 		ire_refrele(ire);
8889 	if (sire != NULL)
8890 		ire_refrele(sire);
8891 	if (src_ipif != NULL)
8892 		ipif_refrele(src_ipif);
8893 	if (dst_ill != NULL)
8894 		ill_refrele(dst_ill);
8895 	return;
8896 
8897 icmp_err_ret:
8898 	ip1dbg(("ip_newroute: no route\n"));
8899 	if (src_ipif != NULL)
8900 		ipif_refrele(src_ipif);
8901 	if (dst_ill != NULL)
8902 		ill_refrele(dst_ill);
8903 	if (sire != NULL)
8904 		ire_refrele(sire);
8905 	/* Did this packet originate externally? */
8906 	if (mp->b_prev) {
8907 		mp->b_next = NULL;
8908 		mp->b_prev = NULL;
8909 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8910 		q = WR(q);
8911 	} else {
8912 		/*
8913 		 * There is no outgoing ill, so just increment the
8914 		 * system MIB.
8915 		 */
8916 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8917 		/*
8918 		 * Since ip_wput() isn't close to finished, we fill
8919 		 * in enough of the header for credible error reporting.
8920 		 */
8921 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8922 			/* Failed */
8923 			MULTIRT_DEBUG_UNTAG(first_mp);
8924 			freemsg(first_mp);
8925 			if (ire != NULL)
8926 				ire_refrele(ire);
8927 			return;
8928 		}
8929 	}
8930 
8931 	/*
8932 	 * At this point we will have ire only if RTF_BLACKHOLE
8933 	 * or RTF_REJECT flags are set on the IRE. It will not
8934 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8935 	 */
8936 	if (ire != NULL) {
8937 		if (ire->ire_flags & RTF_BLACKHOLE) {
8938 			ire_refrele(ire);
8939 			MULTIRT_DEBUG_UNTAG(first_mp);
8940 			freemsg(first_mp);
8941 			return;
8942 		}
8943 		ire_refrele(ire);
8944 	}
8945 	if (ip_source_routed(ipha, ipst)) {
8946 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8947 		    zoneid, ipst);
8948 		return;
8949 	}
8950 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8951 }
8952 
8953 ip_opt_info_t zero_info;
8954 
8955 /*
8956  * IPv4 -
8957  * ip_newroute_ipif is called by ip_wput_multicast and
8958  * ip_rput_forward_multicast whenever we need to send
8959  * out a packet to a destination address for which we do not have specific
8960  * routing information. It is used when the packet will be sent out
8961  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8962  * socket option is set or icmp error message wants to go out on a particular
8963  * interface for a unicast packet.
8964  *
8965  * In most cases, the destination address is resolved thanks to the ipif
8966  * intrinsic resolver. However, there are some cases where the call to
8967  * ip_newroute_ipif must take into account the potential presence of
8968  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8969  * that uses the interface. This is specified through flags,
8970  * which can be a combination of:
8971  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8972  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8973  *   and flags. Additionally, the packet source address has to be set to
8974  *   the specified address. The caller is thus expected to set this flag
8975  *   if the packet has no specific source address yet.
8976  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8977  *   flag, the resulting ire will inherit the flag. All unresolved routes
8978  *   to the destination must be explored in the same call to
8979  *   ip_newroute_ipif().
8980  */
8981 static void
8982 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8983     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8984 {
8985 	areq_t	*areq;
8986 	ire_t	*ire = NULL;
8987 	mblk_t	*res_mp;
8988 	ipaddr_t *addrp;
8989 	mblk_t *first_mp;
8990 	ire_t	*save_ire = NULL;
8991 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8992 	ipif_t	*src_ipif = NULL;
8993 	ushort_t ire_marks = 0;
8994 	ill_t	*dst_ill = NULL;
8995 	boolean_t mctl_present;
8996 	ipsec_out_t *io;
8997 	ipha_t *ipha;
8998 	int	ihandle = 0;
8999 	mblk_t	*saved_mp;
9000 	ire_t   *fire = NULL;
9001 	mblk_t  *copy_mp = NULL;
9002 	boolean_t multirt_resolve_next;
9003 	boolean_t unspec_src;
9004 	ipaddr_t ipha_dst;
9005 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9006 
9007 	/*
9008 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9009 	 * here for uniformity
9010 	 */
9011 	ipif_refhold(ipif);
9012 
9013 	/*
9014 	 * This loop is run only once in most cases.
9015 	 * We loop to resolve further routes only when the destination
9016 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9017 	 */
9018 	do {
9019 		if (dst_ill != NULL) {
9020 			ill_refrele(dst_ill);
9021 			dst_ill = NULL;
9022 		}
9023 		if (src_ipif != NULL) {
9024 			ipif_refrele(src_ipif);
9025 			src_ipif = NULL;
9026 		}
9027 		multirt_resolve_next = B_FALSE;
9028 
9029 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9030 		    ipif->ipif_ill->ill_name));
9031 
9032 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9033 		if (mctl_present)
9034 			io = (ipsec_out_t *)first_mp->b_rptr;
9035 
9036 		ipha = (ipha_t *)mp->b_rptr;
9037 
9038 		/*
9039 		 * Save the packet destination address, we may need it after
9040 		 * the packet has been consumed.
9041 		 */
9042 		ipha_dst = ipha->ipha_dst;
9043 
9044 		/*
9045 		 * If the interface is a pt-pt interface we look for an
9046 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9047 		 * local_address and the pt-pt destination address. Otherwise
9048 		 * we just match the local address.
9049 		 * NOTE: dst could be different than ipha->ipha_dst in case
9050 		 * of sending igmp multicast packets over a point-to-point
9051 		 * connection.
9052 		 * Thus we must be careful enough to check ipha_dst to be a
9053 		 * multicast address, otherwise it will take xmit_if path for
9054 		 * multicast packets resulting into kernel stack overflow by
9055 		 * repeated calls to ip_newroute_ipif from ire_send().
9056 		 */
9057 		if (CLASSD(ipha_dst) &&
9058 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9059 			goto err_ret;
9060 		}
9061 
9062 		/*
9063 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9064 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9065 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9066 		 * propagate its flags to the new ire.
9067 		 */
9068 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9069 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9070 			ip2dbg(("ip_newroute_ipif: "
9071 			    "ipif_lookup_multi_ire("
9072 			    "ipif %p, dst %08x) = fire %p\n",
9073 			    (void *)ipif, ntohl(dst), (void *)fire));
9074 		}
9075 
9076 		if (mctl_present && io->ipsec_out_attach_if) {
9077 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9078 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9079 
9080 			/* Failure case frees things for us. */
9081 			if (attach_ill == NULL) {
9082 				ipif_refrele(ipif);
9083 				if (fire != NULL)
9084 					ire_refrele(fire);
9085 				return;
9086 			}
9087 
9088 			/*
9089 			 * Check if we need an ire that will not be
9090 			 * looked up by anybody else i.e. HIDDEN.
9091 			 */
9092 			if (ill_is_probeonly(attach_ill)) {
9093 				ire_marks = IRE_MARK_HIDDEN;
9094 			}
9095 			/*
9096 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9097 			 * case.
9098 			 */
9099 			dst_ill = ipif->ipif_ill;
9100 			/* attach_ill has been refheld by ip_grab_attach_ill */
9101 			ASSERT(dst_ill == attach_ill);
9102 		} else {
9103 			/*
9104 			 * If the interface belongs to an interface group,
9105 			 * make sure the next possible interface in the group
9106 			 * is used.  This encourages load spreading among
9107 			 * peers in an interface group.
9108 			 * Note: load spreading is disabled for RTF_MULTIRT
9109 			 * routes.
9110 			 */
9111 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9112 			    (fire->ire_flags & RTF_MULTIRT)) {
9113 				/*
9114 				 * Don't perform outbound load spreading
9115 				 * in the case of an RTF_MULTIRT issued route,
9116 				 * we actually typically want to replicate
9117 				 * outgoing packets through particular
9118 				 * interfaces.
9119 				 */
9120 				dst_ill = ipif->ipif_ill;
9121 				ill_refhold(dst_ill);
9122 			} else {
9123 				dst_ill = ip_newroute_get_dst_ill(
9124 				    ipif->ipif_ill);
9125 			}
9126 			if (dst_ill == NULL) {
9127 				if (ip_debug > 2) {
9128 					pr_addr_dbg("ip_newroute_ipif: "
9129 					    "no dst ill for dst %s\n",
9130 					    AF_INET, &dst);
9131 				}
9132 				goto err_ret;
9133 			}
9134 		}
9135 
9136 		/*
9137 		 * Pick a source address preferring non-deprecated ones.
9138 		 * Unlike ip_newroute, we don't do any source address
9139 		 * selection here since for multicast it really does not help
9140 		 * in inbound load spreading as in the unicast case.
9141 		 */
9142 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9143 		    (fire->ire_flags & RTF_SETSRC)) {
9144 			/*
9145 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9146 			 * on that interface. This ire has RTF_SETSRC flag, so
9147 			 * the source address of the packet must be changed.
9148 			 * Check that the ipif matching the requested source
9149 			 * address still exists.
9150 			 */
9151 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9152 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9153 		}
9154 
9155 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9156 
9157 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9158 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9159 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9160 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9161 		    (src_ipif == NULL) &&
9162 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9163 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9164 			if (src_ipif == NULL) {
9165 				if (ip_debug > 2) {
9166 					/* ip1dbg */
9167 					pr_addr_dbg("ip_newroute_ipif: "
9168 					    "no src for dst %s",
9169 					    AF_INET, &dst);
9170 				}
9171 				ip1dbg((" through interface %s\n",
9172 				    dst_ill->ill_name));
9173 				goto err_ret;
9174 			}
9175 			ipif_refrele(ipif);
9176 			ipif = src_ipif;
9177 			ipif_refhold(ipif);
9178 		}
9179 		if (src_ipif == NULL) {
9180 			src_ipif = ipif;
9181 			ipif_refhold(src_ipif);
9182 		}
9183 
9184 		/*
9185 		 * Assign a source address while we have the conn.
9186 		 * We can't have ip_wput_ire pick a source address when the
9187 		 * packet returns from arp since conn_unspec_src might be set
9188 		 * and we lose the conn when going through arp.
9189 		 */
9190 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9191 			ipha->ipha_src = src_ipif->ipif_src_addr;
9192 
9193 		/*
9194 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9195 		 * that the outgoing interface does not have an interface ire.
9196 		 */
9197 		if (CLASSD(ipha_dst) && (connp == NULL ||
9198 		    connp->conn_outgoing_ill == NULL) &&
9199 		    infop->ip_opt_ill_index == 0) {
9200 			/* ipif_to_ire returns an held ire */
9201 			ire = ipif_to_ire(ipif);
9202 			if (ire == NULL)
9203 				goto err_ret;
9204 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9205 				goto err_ret;
9206 			/*
9207 			 * ihandle is needed when the ire is added to
9208 			 * cache table.
9209 			 */
9210 			save_ire = ire;
9211 			ihandle = save_ire->ire_ihandle;
9212 
9213 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9214 			    "flags %04x\n",
9215 			    (void *)ire, (void *)ipif, flags));
9216 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9217 			    (fire->ire_flags & RTF_MULTIRT)) {
9218 				/*
9219 				 * As requested by flags, an IRE_OFFSUBNET was
9220 				 * looked up on that interface. This ire has
9221 				 * RTF_MULTIRT flag, so the resolution loop will
9222 				 * be re-entered to resolve additional routes on
9223 				 * other interfaces. For that purpose, a copy of
9224 				 * the packet is performed at this point.
9225 				 */
9226 				fire->ire_last_used_time = lbolt;
9227 				copy_mp = copymsg(first_mp);
9228 				if (copy_mp) {
9229 					MULTIRT_DEBUG_TAG(copy_mp);
9230 				}
9231 			}
9232 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9233 			    (fire->ire_flags & RTF_SETSRC)) {
9234 				/*
9235 				 * As requested by flags, an IRE_OFFSUBET was
9236 				 * looked up on that interface. This ire has
9237 				 * RTF_SETSRC flag, so the source address of the
9238 				 * packet must be changed.
9239 				 */
9240 				ipha->ipha_src = fire->ire_src_addr;
9241 			}
9242 		} else {
9243 			ASSERT((connp == NULL) ||
9244 			    (connp->conn_outgoing_ill != NULL) ||
9245 			    (connp->conn_dontroute) ||
9246 			    infop->ip_opt_ill_index != 0);
9247 			/*
9248 			 * The only ways we can come here are:
9249 			 * 1) IP_BOUND_IF socket option is set
9250 			 * 2) SO_DONTROUTE socket option is set
9251 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9252 			 * In all cases, the new ire will not be added
9253 			 * into cache table.
9254 			 */
9255 			ire_marks |= IRE_MARK_NOADD;
9256 		}
9257 
9258 		switch (ipif->ipif_net_type) {
9259 		case IRE_IF_NORESOLVER: {
9260 			/* We have what we need to build an IRE_CACHE. */
9261 
9262 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9263 			    (dst_ill->ill_resolver_mp == NULL)) {
9264 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9265 				    "for IRE_IF_NORESOLVER ire %p has "
9266 				    "no ill_resolver_mp\n",
9267 				    (void *)dst_ill, (void *)ire));
9268 				break;
9269 			}
9270 
9271 			/*
9272 			 * The new ire inherits the IRE_OFFSUBNET flags
9273 			 * and source address, if this was requested.
9274 			 */
9275 			ire = ire_create(
9276 			    (uchar_t *)&dst,		/* dest address */
9277 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9278 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9279 			    NULL,			/* gateway address */
9280 			    &ipif->ipif_mtu,
9281 			    NULL,			/* no src nce */
9282 			    dst_ill->ill_rq,		/* recv-from queue */
9283 			    dst_ill->ill_wq,		/* send-to queue */
9284 			    IRE_CACHE,
9285 			    src_ipif,
9286 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9287 			    (fire != NULL) ?		/* Parent handle */
9288 			    fire->ire_phandle : 0,
9289 			    ihandle,			/* Interface handle */
9290 			    (fire != NULL) ?
9291 			    (fire->ire_flags &
9292 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9293 			    (save_ire == NULL ? &ire_uinfo_null :
9294 			    &save_ire->ire_uinfo),
9295 			    NULL,
9296 			    NULL,
9297 			    ipst);
9298 
9299 			if (ire == NULL) {
9300 				if (save_ire != NULL)
9301 					ire_refrele(save_ire);
9302 				break;
9303 			}
9304 
9305 			ire->ire_marks |= ire_marks;
9306 
9307 			/*
9308 			 * If IRE_MARK_NOADD is set then we need to convert
9309 			 * the max_fragp to a useable value now. This is
9310 			 * normally done in ire_add_v[46]. We also need to
9311 			 * associate the ire with an nce (normally would be
9312 			 * done in ip_wput_nondata()).
9313 			 *
9314 			 * Note that IRE_MARK_NOADD packets created here
9315 			 * do not have a non-null ire_mp pointer. The null
9316 			 * value of ire_bucket indicates that they were
9317 			 * never added.
9318 			 */
9319 			if (ire->ire_marks & IRE_MARK_NOADD) {
9320 				uint_t  max_frag;
9321 
9322 				max_frag = *ire->ire_max_fragp;
9323 				ire->ire_max_fragp = NULL;
9324 				ire->ire_max_frag = max_frag;
9325 
9326 				if ((ire->ire_nce = ndp_lookup_v4(
9327 				    ire_to_ill(ire),
9328 				    (ire->ire_gateway_addr != INADDR_ANY ?
9329 				    &ire->ire_gateway_addr : &ire->ire_addr),
9330 				    B_FALSE)) == NULL) {
9331 					if (save_ire != NULL)
9332 						ire_refrele(save_ire);
9333 					break;
9334 				}
9335 				ASSERT(ire->ire_nce->nce_state ==
9336 				    ND_REACHABLE);
9337 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9338 			}
9339 
9340 			/* Prevent save_ire from getting deleted */
9341 			if (save_ire != NULL) {
9342 				IRB_REFHOLD(save_ire->ire_bucket);
9343 				/* Has it been removed already ? */
9344 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9345 					IRB_REFRELE(save_ire->ire_bucket);
9346 					ire_refrele(save_ire);
9347 					break;
9348 				}
9349 			}
9350 
9351 			ire_add_then_send(q, ire, first_mp);
9352 
9353 			/* Assert that save_ire is not deleted yet. */
9354 			if (save_ire != NULL) {
9355 				ASSERT(save_ire->ire_ptpn != NULL);
9356 				IRB_REFRELE(save_ire->ire_bucket);
9357 				ire_refrele(save_ire);
9358 				save_ire = NULL;
9359 			}
9360 			if (fire != NULL) {
9361 				ire_refrele(fire);
9362 				fire = NULL;
9363 			}
9364 
9365 			/*
9366 			 * the resolution loop is re-entered if this
9367 			 * was requested through flags and if we
9368 			 * actually are in a multirouting case.
9369 			 */
9370 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9371 				boolean_t need_resolve =
9372 				    ire_multirt_need_resolve(ipha_dst,
9373 				    MBLK_GETLABEL(copy_mp), ipst);
9374 				if (!need_resolve) {
9375 					MULTIRT_DEBUG_UNTAG(copy_mp);
9376 					freemsg(copy_mp);
9377 					copy_mp = NULL;
9378 				} else {
9379 					/*
9380 					 * ipif_lookup_group() calls
9381 					 * ire_lookup_multi() that uses
9382 					 * ire_ftable_lookup() to find
9383 					 * an IRE_INTERFACE for the group.
9384 					 * In the multirt case,
9385 					 * ire_lookup_multi() then invokes
9386 					 * ire_multirt_lookup() to find
9387 					 * the next resolvable ire.
9388 					 * As a result, we obtain an new
9389 					 * interface, derived from the
9390 					 * next ire.
9391 					 */
9392 					ipif_refrele(ipif);
9393 					ipif = ipif_lookup_group(ipha_dst,
9394 					    zoneid, ipst);
9395 					ip2dbg(("ip_newroute_ipif: "
9396 					    "multirt dst %08x, ipif %p\n",
9397 					    htonl(dst), (void *)ipif));
9398 					if (ipif != NULL) {
9399 						mp = copy_mp;
9400 						copy_mp = NULL;
9401 						multirt_resolve_next = B_TRUE;
9402 						continue;
9403 					} else {
9404 						freemsg(copy_mp);
9405 					}
9406 				}
9407 			}
9408 			if (ipif != NULL)
9409 				ipif_refrele(ipif);
9410 			ill_refrele(dst_ill);
9411 			ipif_refrele(src_ipif);
9412 			return;
9413 		}
9414 		case IRE_IF_RESOLVER:
9415 			/*
9416 			 * We can't build an IRE_CACHE yet, but at least
9417 			 * we found a resolver that can help.
9418 			 */
9419 			res_mp = dst_ill->ill_resolver_mp;
9420 			if (!OK_RESOLVER_MP(res_mp))
9421 				break;
9422 
9423 			/*
9424 			 * We obtain a partial IRE_CACHE which we will pass
9425 			 * along with the resolver query.  When the response
9426 			 * comes back it will be there ready for us to add.
9427 			 * The new ire inherits the IRE_OFFSUBNET flags
9428 			 * and source address, if this was requested.
9429 			 * The ire_max_frag is atomically set under the
9430 			 * irebucket lock in ire_add_v[46]. Only in the
9431 			 * case of IRE_MARK_NOADD, we set it here itself.
9432 			 */
9433 			ire = ire_create_mp(
9434 			    (uchar_t *)&dst,		/* dest address */
9435 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9436 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9437 			    NULL,			/* gateway address */
9438 			    (ire_marks & IRE_MARK_NOADD) ?
9439 			    ipif->ipif_mtu : 0,		/* max_frag */
9440 			    NULL,			/* no src nce */
9441 			    dst_ill->ill_rq,		/* recv-from queue */
9442 			    dst_ill->ill_wq,		/* send-to queue */
9443 			    IRE_CACHE,
9444 			    src_ipif,
9445 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9446 			    (fire != NULL) ?		/* Parent handle */
9447 			    fire->ire_phandle : 0,
9448 			    ihandle,			/* Interface handle */
9449 			    (fire != NULL) ?		/* flags if any */
9450 			    (fire->ire_flags &
9451 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9452 			    (save_ire == NULL ? &ire_uinfo_null :
9453 			    &save_ire->ire_uinfo),
9454 			    NULL,
9455 			    NULL,
9456 			    ipst);
9457 
9458 			if (save_ire != NULL) {
9459 				ire_refrele(save_ire);
9460 				save_ire = NULL;
9461 			}
9462 			if (ire == NULL)
9463 				break;
9464 
9465 			ire->ire_marks |= ire_marks;
9466 			/*
9467 			 * Construct message chain for the resolver of the
9468 			 * form:
9469 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9470 			 *
9471 			 * NOTE : ire will be added later when the response
9472 			 * comes back from ARP. If the response does not
9473 			 * come back, ARP frees the packet. For this reason,
9474 			 * we can't REFHOLD the bucket of save_ire to prevent
9475 			 * deletions. We may not be able to REFRELE the
9476 			 * bucket if the response never comes back.
9477 			 * Thus, before adding the ire, ire_add_v4 will make
9478 			 * sure that the interface route does not get deleted.
9479 			 * This is the only case unlike ip_newroute_v6,
9480 			 * ip_newroute_ipif_v6 where we can always prevent
9481 			 * deletions because ire_add_then_send is called after
9482 			 * creating the IRE.
9483 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9484 			 * does not add this IRE into the IRE CACHE.
9485 			 */
9486 			ASSERT(ire->ire_mp != NULL);
9487 			ire->ire_mp->b_cont = first_mp;
9488 			/* Have saved_mp handy, for cleanup if canput fails */
9489 			saved_mp = mp;
9490 			mp = copyb(res_mp);
9491 			if (mp == NULL) {
9492 				/* Prepare for cleanup */
9493 				mp = saved_mp; /* pkt */
9494 				ire_delete(ire); /* ire_mp */
9495 				ire = NULL;
9496 				if (copy_mp != NULL) {
9497 					MULTIRT_DEBUG_UNTAG(copy_mp);
9498 					freemsg(copy_mp);
9499 					copy_mp = NULL;
9500 				}
9501 				break;
9502 			}
9503 			linkb(mp, ire->ire_mp);
9504 
9505 			/*
9506 			 * Fill in the source and dest addrs for the resolver.
9507 			 * NOTE: this depends on memory layouts imposed by
9508 			 * ill_init().
9509 			 */
9510 			areq = (areq_t *)mp->b_rptr;
9511 			addrp = (ipaddr_t *)((char *)areq +
9512 			    areq->areq_sender_addr_offset);
9513 			*addrp = ire->ire_src_addr;
9514 			addrp = (ipaddr_t *)((char *)areq +
9515 			    areq->areq_target_addr_offset);
9516 			*addrp = dst;
9517 			/* Up to the resolver. */
9518 			if (canputnext(dst_ill->ill_rq) &&
9519 			    !(dst_ill->ill_arp_closing)) {
9520 				putnext(dst_ill->ill_rq, mp);
9521 				/*
9522 				 * The response will come back in ip_wput
9523 				 * with db_type IRE_DB_TYPE.
9524 				 */
9525 			} else {
9526 				mp->b_cont = NULL;
9527 				freeb(mp); /* areq */
9528 				ire_delete(ire); /* ire_mp */
9529 				saved_mp->b_next = NULL;
9530 				saved_mp->b_prev = NULL;
9531 				freemsg(first_mp); /* pkt */
9532 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9533 			}
9534 
9535 			if (fire != NULL) {
9536 				ire_refrele(fire);
9537 				fire = NULL;
9538 			}
9539 
9540 
9541 			/*
9542 			 * The resolution loop is re-entered if this was
9543 			 * requested through flags and we actually are
9544 			 * in a multirouting case.
9545 			 */
9546 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9547 				boolean_t need_resolve =
9548 				    ire_multirt_need_resolve(ipha_dst,
9549 				    MBLK_GETLABEL(copy_mp), ipst);
9550 				if (!need_resolve) {
9551 					MULTIRT_DEBUG_UNTAG(copy_mp);
9552 					freemsg(copy_mp);
9553 					copy_mp = NULL;
9554 				} else {
9555 					/*
9556 					 * ipif_lookup_group() calls
9557 					 * ire_lookup_multi() that uses
9558 					 * ire_ftable_lookup() to find
9559 					 * an IRE_INTERFACE for the group.
9560 					 * In the multirt case,
9561 					 * ire_lookup_multi() then invokes
9562 					 * ire_multirt_lookup() to find
9563 					 * the next resolvable ire.
9564 					 * As a result, we obtain an new
9565 					 * interface, derived from the
9566 					 * next ire.
9567 					 */
9568 					ipif_refrele(ipif);
9569 					ipif = ipif_lookup_group(ipha_dst,
9570 					    zoneid, ipst);
9571 					if (ipif != NULL) {
9572 						mp = copy_mp;
9573 						copy_mp = NULL;
9574 						multirt_resolve_next = B_TRUE;
9575 						continue;
9576 					} else {
9577 						freemsg(copy_mp);
9578 					}
9579 				}
9580 			}
9581 			if (ipif != NULL)
9582 				ipif_refrele(ipif);
9583 			ill_refrele(dst_ill);
9584 			ipif_refrele(src_ipif);
9585 			return;
9586 		default:
9587 			break;
9588 		}
9589 	} while (multirt_resolve_next);
9590 
9591 err_ret:
9592 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9593 	if (fire != NULL)
9594 		ire_refrele(fire);
9595 	ipif_refrele(ipif);
9596 	/* Did this packet originate externally? */
9597 	if (dst_ill != NULL)
9598 		ill_refrele(dst_ill);
9599 	if (src_ipif != NULL)
9600 		ipif_refrele(src_ipif);
9601 	if (mp->b_prev || mp->b_next) {
9602 		mp->b_next = NULL;
9603 		mp->b_prev = NULL;
9604 	} else {
9605 		/*
9606 		 * Since ip_wput() isn't close to finished, we fill
9607 		 * in enough of the header for credible error reporting.
9608 		 */
9609 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9610 			/* Failed */
9611 			freemsg(first_mp);
9612 			if (ire != NULL)
9613 				ire_refrele(ire);
9614 			return;
9615 		}
9616 	}
9617 	/*
9618 	 * At this point we will have ire only if RTF_BLACKHOLE
9619 	 * or RTF_REJECT flags are set on the IRE. It will not
9620 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9621 	 */
9622 	if (ire != NULL) {
9623 		if (ire->ire_flags & RTF_BLACKHOLE) {
9624 			ire_refrele(ire);
9625 			freemsg(first_mp);
9626 			return;
9627 		}
9628 		ire_refrele(ire);
9629 	}
9630 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9631 }
9632 
9633 /* Name/Value Table Lookup Routine */
9634 char *
9635 ip_nv_lookup(nv_t *nv, int value)
9636 {
9637 	if (!nv)
9638 		return (NULL);
9639 	for (; nv->nv_name; nv++) {
9640 		if (nv->nv_value == value)
9641 			return (nv->nv_name);
9642 	}
9643 	return ("unknown");
9644 }
9645 
9646 /*
9647  * This is a module open, i.e. this is a control stream for access
9648  * to a DLPI device.  We allocate an ill_t as the instance data in
9649  * this case.
9650  */
9651 int
9652 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9653 {
9654 	ill_t	*ill;
9655 	int	err;
9656 	zoneid_t zoneid;
9657 	netstack_t *ns;
9658 	ip_stack_t *ipst;
9659 
9660 	/*
9661 	 * Prevent unprivileged processes from pushing IP so that
9662 	 * they can't send raw IP.
9663 	 */
9664 	if (secpolicy_net_rawaccess(credp) != 0)
9665 		return (EPERM);
9666 
9667 	ns = netstack_find_by_cred(credp);
9668 	ASSERT(ns != NULL);
9669 	ipst = ns->netstack_ip;
9670 	ASSERT(ipst != NULL);
9671 
9672 	/*
9673 	 * For exclusive stacks we set the zoneid to zero
9674 	 * to make IP operate as if in the global zone.
9675 	 */
9676 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9677 		zoneid = GLOBAL_ZONEID;
9678 	else
9679 		zoneid = crgetzoneid(credp);
9680 
9681 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9682 	q->q_ptr = WR(q)->q_ptr = ill;
9683 	ill->ill_ipst = ipst;
9684 	ill->ill_zoneid = zoneid;
9685 
9686 	/*
9687 	 * ill_init initializes the ill fields and then sends down
9688 	 * down a DL_INFO_REQ after calling qprocson.
9689 	 */
9690 	err = ill_init(q, ill);
9691 	if (err != 0) {
9692 		mi_free(ill);
9693 		netstack_rele(ipst->ips_netstack);
9694 		q->q_ptr = NULL;
9695 		WR(q)->q_ptr = NULL;
9696 		return (err);
9697 	}
9698 
9699 	/* ill_init initializes the ipsq marking this thread as writer */
9700 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9701 	/* Wait for the DL_INFO_ACK */
9702 	mutex_enter(&ill->ill_lock);
9703 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9704 		/*
9705 		 * Return value of 0 indicates a pending signal.
9706 		 */
9707 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9708 		if (err == 0) {
9709 			mutex_exit(&ill->ill_lock);
9710 			(void) ip_close(q, 0);
9711 			return (EINTR);
9712 		}
9713 	}
9714 	mutex_exit(&ill->ill_lock);
9715 
9716 	/*
9717 	 * ip_rput_other could have set an error  in ill_error on
9718 	 * receipt of M_ERROR.
9719 	 */
9720 
9721 	err = ill->ill_error;
9722 	if (err != 0) {
9723 		(void) ip_close(q, 0);
9724 		return (err);
9725 	}
9726 
9727 	ill->ill_credp = credp;
9728 	crhold(credp);
9729 
9730 	mutex_enter(&ipst->ips_ip_mi_lock);
9731 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9732 	    credp);
9733 	mutex_exit(&ipst->ips_ip_mi_lock);
9734 	if (err) {
9735 		(void) ip_close(q, 0);
9736 		return (err);
9737 	}
9738 	return (0);
9739 }
9740 
9741 /* For /dev/ip aka AF_INET open */
9742 int
9743 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9744 {
9745 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9746 }
9747 
9748 /* For /dev/ip6 aka AF_INET6 open */
9749 int
9750 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9751 {
9752 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9753 }
9754 
9755 /* IP open routine. */
9756 int
9757 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9758     boolean_t isv6)
9759 {
9760 	conn_t 		*connp;
9761 	major_t		maj;
9762 	zoneid_t	zoneid;
9763 	netstack_t	*ns;
9764 	ip_stack_t	*ipst;
9765 
9766 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9767 
9768 	/* Allow reopen. */
9769 	if (q->q_ptr != NULL)
9770 		return (0);
9771 
9772 	if (sflag & MODOPEN) {
9773 		/* This is a module open */
9774 		return (ip_modopen(q, devp, flag, sflag, credp));
9775 	}
9776 
9777 	ns = netstack_find_by_cred(credp);
9778 	ASSERT(ns != NULL);
9779 	ipst = ns->netstack_ip;
9780 	ASSERT(ipst != NULL);
9781 
9782 	/*
9783 	 * For exclusive stacks we set the zoneid to zero
9784 	 * to make IP operate as if in the global zone.
9785 	 */
9786 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9787 		zoneid = GLOBAL_ZONEID;
9788 	else
9789 		zoneid = crgetzoneid(credp);
9790 
9791 	/*
9792 	 * We are opening as a device. This is an IP client stream, and we
9793 	 * allocate an conn_t as the instance data.
9794 	 */
9795 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9796 
9797 	/*
9798 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9799 	 * done by netstack_find_by_cred()
9800 	 */
9801 	netstack_rele(ipst->ips_netstack);
9802 
9803 	connp->conn_zoneid = zoneid;
9804 	connp->conn_sqp = NULL;
9805 	connp->conn_initial_sqp = NULL;
9806 	connp->conn_final_sqp = NULL;
9807 
9808 	connp->conn_upq = q;
9809 	q->q_ptr = WR(q)->q_ptr = connp;
9810 
9811 	if (flag & SO_SOCKSTR)
9812 		connp->conn_flags |= IPCL_SOCKET;
9813 
9814 	/* Minor tells us which /dev entry was opened */
9815 	if (isv6) {
9816 		connp->conn_flags |= IPCL_ISV6;
9817 		connp->conn_af_isv6 = B_TRUE;
9818 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9819 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9820 	} else {
9821 		connp->conn_af_isv6 = B_FALSE;
9822 		connp->conn_pkt_isv6 = B_FALSE;
9823 	}
9824 
9825 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9826 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9827 		connp->conn_minor_arena = ip_minor_arena_la;
9828 	} else {
9829 		/*
9830 		 * Either minor numbers in the large arena were exhausted
9831 		 * or a non socket application is doing the open.
9832 		 * Try to allocate from the small arena.
9833 		 */
9834 		if ((connp->conn_dev =
9835 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9836 			/* CONN_DEC_REF takes care of netstack_rele() */
9837 			q->q_ptr = WR(q)->q_ptr = NULL;
9838 			CONN_DEC_REF(connp);
9839 			return (EBUSY);
9840 		}
9841 		connp->conn_minor_arena = ip_minor_arena_sa;
9842 	}
9843 
9844 	maj = getemajor(*devp);
9845 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9846 
9847 	/*
9848 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9849 	 */
9850 	connp->conn_cred = credp;
9851 
9852 	/*
9853 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9854 	 */
9855 	connp->conn_recv = ip_conn_input;
9856 
9857 	crhold(connp->conn_cred);
9858 
9859 	/*
9860 	 * If the caller has the process-wide flag set, then default to MAC
9861 	 * exempt mode.  This allows read-down to unlabeled hosts.
9862 	 */
9863 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9864 		connp->conn_mac_exempt = B_TRUE;
9865 
9866 	connp->conn_rq = q;
9867 	connp->conn_wq = WR(q);
9868 
9869 	/* Non-zero default values */
9870 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9871 
9872 	/*
9873 	 * Make the conn globally visible to walkers
9874 	 */
9875 	ASSERT(connp->conn_ref == 1);
9876 	mutex_enter(&connp->conn_lock);
9877 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9878 	mutex_exit(&connp->conn_lock);
9879 
9880 	qprocson(q);
9881 
9882 	return (0);
9883 }
9884 
9885 /*
9886  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9887  * Note that there is no race since either ip_output function works - it
9888  * is just an optimization to enter the best ip_output routine directly.
9889  */
9890 void
9891 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9892     ip_stack_t *ipst)
9893 {
9894 	if (isv6)  {
9895 		if (bump_mib) {
9896 			BUMP_MIB(&ipst->ips_ip6_mib,
9897 			    ipIfStatsOutSwitchIPVersion);
9898 		}
9899 		connp->conn_send = ip_output_v6;
9900 		connp->conn_pkt_isv6 = B_TRUE;
9901 	} else {
9902 		if (bump_mib) {
9903 			BUMP_MIB(&ipst->ips_ip_mib,
9904 			    ipIfStatsOutSwitchIPVersion);
9905 		}
9906 		connp->conn_send = ip_output;
9907 		connp->conn_pkt_isv6 = B_FALSE;
9908 	}
9909 
9910 }
9911 
9912 /*
9913  * See if IPsec needs loading because of the options in mp.
9914  */
9915 static boolean_t
9916 ipsec_opt_present(mblk_t *mp)
9917 {
9918 	uint8_t *optcp, *next_optcp, *opt_endcp;
9919 	struct opthdr *opt;
9920 	struct T_opthdr *topt;
9921 	int opthdr_len;
9922 	t_uscalar_t optname, optlevel;
9923 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9924 	ipsec_req_t *ipsr;
9925 
9926 	/*
9927 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9928 	 * return TRUE.
9929 	 */
9930 
9931 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9932 	opt_endcp = optcp + tor->OPT_length;
9933 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9934 		opthdr_len = sizeof (struct T_opthdr);
9935 	} else {		/* O_OPTMGMT_REQ */
9936 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9937 		opthdr_len = sizeof (struct opthdr);
9938 	}
9939 	for (; optcp < opt_endcp; optcp = next_optcp) {
9940 		if (optcp + opthdr_len > opt_endcp)
9941 			return (B_FALSE);	/* Not enough option header. */
9942 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9943 			topt = (struct T_opthdr *)optcp;
9944 			optlevel = topt->level;
9945 			optname = topt->name;
9946 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9947 		} else {
9948 			opt = (struct opthdr *)optcp;
9949 			optlevel = opt->level;
9950 			optname = opt->name;
9951 			next_optcp = optcp + opthdr_len +
9952 			    _TPI_ALIGN_OPT(opt->len);
9953 		}
9954 		if ((next_optcp < optcp) || /* wraparound pointer space */
9955 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9956 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9957 			return (B_FALSE); /* bad option buffer */
9958 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9959 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9960 			/*
9961 			 * Check to see if it's an all-bypass or all-zeroes
9962 			 * IPsec request.  Don't bother loading IPsec if
9963 			 * the socket doesn't want to use it.  (A good example
9964 			 * is a bypass request.)
9965 			 *
9966 			 * Basically, if any of the non-NEVER bits are set,
9967 			 * load IPsec.
9968 			 */
9969 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9970 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9971 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9972 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9973 			    != 0)
9974 				return (B_TRUE);
9975 		}
9976 	}
9977 	return (B_FALSE);
9978 }
9979 
9980 /*
9981  * If conn is is waiting for ipsec to finish loading, kick it.
9982  */
9983 /* ARGSUSED */
9984 static void
9985 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9986 {
9987 	t_scalar_t	optreq_prim;
9988 	mblk_t		*mp;
9989 	cred_t		*cr;
9990 	int		err = 0;
9991 
9992 	/*
9993 	 * This function is called, after ipsec loading is complete.
9994 	 * Since IP checks exclusively and atomically (i.e it prevents
9995 	 * ipsec load from completing until ip_optcom_req completes)
9996 	 * whether ipsec load is complete, there cannot be a race with IP
9997 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9998 	 */
9999 	mutex_enter(&connp->conn_lock);
10000 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10001 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10002 		mp = connp->conn_ipsec_opt_mp;
10003 		connp->conn_ipsec_opt_mp = NULL;
10004 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10005 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10006 		mutex_exit(&connp->conn_lock);
10007 
10008 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10009 
10010 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10011 		if (optreq_prim == T_OPTMGMT_REQ) {
10012 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10013 			    &ip_opt_obj, B_FALSE);
10014 		} else {
10015 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10016 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10017 			    &ip_opt_obj, B_FALSE);
10018 		}
10019 		if (err != EINPROGRESS)
10020 			CONN_OPER_PENDING_DONE(connp);
10021 		return;
10022 	}
10023 	mutex_exit(&connp->conn_lock);
10024 }
10025 
10026 /*
10027  * Called from the ipsec_loader thread, outside any perimeter, to tell
10028  * ip qenable any of the queues waiting for the ipsec loader to
10029  * complete.
10030  */
10031 void
10032 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10033 {
10034 	netstack_t *ns = ipss->ipsec_netstack;
10035 
10036 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10037 }
10038 
10039 /*
10040  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10041  * determines the grp on which it has to become exclusive, queues the mp
10042  * and sq draining restarts the optmgmt
10043  */
10044 static boolean_t
10045 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10046 {
10047 	conn_t *connp = Q_TO_CONN(q);
10048 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10049 
10050 	/*
10051 	 * Take IPsec requests and treat them special.
10052 	 */
10053 	if (ipsec_opt_present(mp)) {
10054 		/* First check if IPsec is loaded. */
10055 		mutex_enter(&ipss->ipsec_loader_lock);
10056 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10057 			mutex_exit(&ipss->ipsec_loader_lock);
10058 			return (B_FALSE);
10059 		}
10060 		mutex_enter(&connp->conn_lock);
10061 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10062 
10063 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10064 		connp->conn_ipsec_opt_mp = mp;
10065 		mutex_exit(&connp->conn_lock);
10066 		mutex_exit(&ipss->ipsec_loader_lock);
10067 
10068 		ipsec_loader_loadnow(ipss);
10069 		return (B_TRUE);
10070 	}
10071 	return (B_FALSE);
10072 }
10073 
10074 /*
10075  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10076  * all of them are copied to the conn_t. If the req is "zero", the policy is
10077  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10078  * fields.
10079  * We keep only the latest setting of the policy and thus policy setting
10080  * is not incremental/cumulative.
10081  *
10082  * Requests to set policies with multiple alternative actions will
10083  * go through a different API.
10084  */
10085 int
10086 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10087 {
10088 	uint_t ah_req = 0;
10089 	uint_t esp_req = 0;
10090 	uint_t se_req = 0;
10091 	ipsec_selkey_t sel;
10092 	ipsec_act_t *actp = NULL;
10093 	uint_t nact;
10094 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10095 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10096 	ipsec_policy_root_t *pr;
10097 	ipsec_policy_head_t *ph;
10098 	int fam;
10099 	boolean_t is_pol_reset;
10100 	int error = 0;
10101 	netstack_t	*ns = connp->conn_netstack;
10102 	ip_stack_t	*ipst = ns->netstack_ip;
10103 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10104 
10105 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10106 
10107 	/*
10108 	 * The IP_SEC_OPT option does not allow variable length parameters,
10109 	 * hence a request cannot be NULL.
10110 	 */
10111 	if (req == NULL)
10112 		return (EINVAL);
10113 
10114 	ah_req = req->ipsr_ah_req;
10115 	esp_req = req->ipsr_esp_req;
10116 	se_req = req->ipsr_self_encap_req;
10117 
10118 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10119 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10120 		return (EINVAL);
10121 
10122 	/*
10123 	 * Are we dealing with a request to reset the policy (i.e.
10124 	 * zero requests).
10125 	 */
10126 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10127 	    (esp_req & REQ_MASK) == 0 &&
10128 	    (se_req & REQ_MASK) == 0);
10129 
10130 	if (!is_pol_reset) {
10131 		/*
10132 		 * If we couldn't load IPsec, fail with "protocol
10133 		 * not supported".
10134 		 * IPsec may not have been loaded for a request with zero
10135 		 * policies, so we don't fail in this case.
10136 		 */
10137 		mutex_enter(&ipss->ipsec_loader_lock);
10138 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10139 			mutex_exit(&ipss->ipsec_loader_lock);
10140 			return (EPROTONOSUPPORT);
10141 		}
10142 		mutex_exit(&ipss->ipsec_loader_lock);
10143 
10144 		/*
10145 		 * Test for valid requests. Invalid algorithms
10146 		 * need to be tested by IPsec code because new
10147 		 * algorithms can be added dynamically.
10148 		 */
10149 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10150 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10151 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10152 			return (EINVAL);
10153 		}
10154 
10155 		/*
10156 		 * Only privileged users can issue these
10157 		 * requests.
10158 		 */
10159 		if (((ah_req & IPSEC_PREF_NEVER) ||
10160 		    (esp_req & IPSEC_PREF_NEVER) ||
10161 		    (se_req & IPSEC_PREF_NEVER)) &&
10162 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10163 			return (EPERM);
10164 		}
10165 
10166 		/*
10167 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10168 		 * are mutually exclusive.
10169 		 */
10170 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10171 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10172 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10173 			/* Both of them are set */
10174 			return (EINVAL);
10175 		}
10176 	}
10177 
10178 	mutex_enter(&connp->conn_lock);
10179 
10180 	/*
10181 	 * If we have already cached policies in ip_bind_connected*(), don't
10182 	 * let them change now. We cache policies for connections
10183 	 * whose src,dst [addr, port] is known.
10184 	 */
10185 	if (connp->conn_policy_cached) {
10186 		mutex_exit(&connp->conn_lock);
10187 		return (EINVAL);
10188 	}
10189 
10190 	/*
10191 	 * We have a zero policies, reset the connection policy if already
10192 	 * set. This will cause the connection to inherit the
10193 	 * global policy, if any.
10194 	 */
10195 	if (is_pol_reset) {
10196 		if (connp->conn_policy != NULL) {
10197 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10198 			connp->conn_policy = NULL;
10199 		}
10200 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10201 		connp->conn_in_enforce_policy = B_FALSE;
10202 		connp->conn_out_enforce_policy = B_FALSE;
10203 		mutex_exit(&connp->conn_lock);
10204 		return (0);
10205 	}
10206 
10207 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10208 	    ipst->ips_netstack);
10209 	if (ph == NULL)
10210 		goto enomem;
10211 
10212 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10213 	if (actp == NULL)
10214 		goto enomem;
10215 
10216 	/*
10217 	 * Always allocate IPv4 policy entries, since they can also
10218 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10219 	 */
10220 	bzero(&sel, sizeof (sel));
10221 	sel.ipsl_valid = IPSL_IPV4;
10222 
10223 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10224 	    ipst->ips_netstack);
10225 	if (pin4 == NULL)
10226 		goto enomem;
10227 
10228 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10229 	    ipst->ips_netstack);
10230 	if (pout4 == NULL)
10231 		goto enomem;
10232 
10233 	if (connp->conn_af_isv6) {
10234 		/*
10235 		 * We're looking at a v6 socket, also allocate the
10236 		 * v6-specific entries...
10237 		 */
10238 		sel.ipsl_valid = IPSL_IPV6;
10239 		pin6 = ipsec_policy_create(&sel, actp, nact,
10240 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10241 		if (pin6 == NULL)
10242 			goto enomem;
10243 
10244 		pout6 = ipsec_policy_create(&sel, actp, nact,
10245 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10246 		if (pout6 == NULL)
10247 			goto enomem;
10248 
10249 		/*
10250 		 * .. and file them away in the right place.
10251 		 */
10252 		fam = IPSEC_AF_V6;
10253 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10254 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10255 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10256 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10257 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10258 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10259 	}
10260 
10261 	ipsec_actvec_free(actp, nact);
10262 
10263 	/*
10264 	 * File the v4 policies.
10265 	 */
10266 	fam = IPSEC_AF_V4;
10267 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10268 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10269 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10270 
10271 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10272 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10273 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10274 
10275 	/*
10276 	 * If the requests need security, set enforce_policy.
10277 	 * If the requests are IPSEC_PREF_NEVER, one should
10278 	 * still set conn_out_enforce_policy so that an ipsec_out
10279 	 * gets attached in ip_wput. This is needed so that
10280 	 * for connections that we don't cache policy in ip_bind,
10281 	 * if global policy matches in ip_wput_attach_policy, we
10282 	 * don't wrongly inherit global policy. Similarly, we need
10283 	 * to set conn_in_enforce_policy also so that we don't verify
10284 	 * policy wrongly.
10285 	 */
10286 	if ((ah_req & REQ_MASK) != 0 ||
10287 	    (esp_req & REQ_MASK) != 0 ||
10288 	    (se_req & REQ_MASK) != 0) {
10289 		connp->conn_in_enforce_policy = B_TRUE;
10290 		connp->conn_out_enforce_policy = B_TRUE;
10291 		connp->conn_flags |= IPCL_CHECK_POLICY;
10292 	}
10293 
10294 	mutex_exit(&connp->conn_lock);
10295 	return (error);
10296 #undef REQ_MASK
10297 
10298 	/*
10299 	 * Common memory-allocation-failure exit path.
10300 	 */
10301 enomem:
10302 	mutex_exit(&connp->conn_lock);
10303 	if (actp != NULL)
10304 		ipsec_actvec_free(actp, nact);
10305 	if (pin4 != NULL)
10306 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10307 	if (pout4 != NULL)
10308 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10309 	if (pin6 != NULL)
10310 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10311 	if (pout6 != NULL)
10312 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10313 	return (ENOMEM);
10314 }
10315 
10316 /*
10317  * Only for options that pass in an IP addr. Currently only V4 options
10318  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10319  * So this function assumes level is IPPROTO_IP
10320  */
10321 int
10322 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10323     mblk_t *first_mp)
10324 {
10325 	ipif_t *ipif = NULL;
10326 	int error;
10327 	ill_t *ill;
10328 	int zoneid;
10329 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10330 
10331 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10332 
10333 	if (addr != INADDR_ANY || checkonly) {
10334 		ASSERT(connp != NULL);
10335 		zoneid = IPCL_ZONEID(connp);
10336 		if (option == IP_NEXTHOP) {
10337 			ipif = ipif_lookup_onlink_addr(addr,
10338 			    connp->conn_zoneid, ipst);
10339 		} else {
10340 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10341 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10342 			    &error, ipst);
10343 		}
10344 		if (ipif == NULL) {
10345 			if (error == EINPROGRESS)
10346 				return (error);
10347 			else if ((option == IP_MULTICAST_IF) ||
10348 			    (option == IP_NEXTHOP))
10349 				return (EHOSTUNREACH);
10350 			else
10351 				return (EINVAL);
10352 		} else if (checkonly) {
10353 			if (option == IP_MULTICAST_IF) {
10354 				ill = ipif->ipif_ill;
10355 				/* not supported by the virtual network iface */
10356 				if (IS_VNI(ill)) {
10357 					ipif_refrele(ipif);
10358 					return (EINVAL);
10359 				}
10360 			}
10361 			ipif_refrele(ipif);
10362 			return (0);
10363 		}
10364 		ill = ipif->ipif_ill;
10365 		mutex_enter(&connp->conn_lock);
10366 		mutex_enter(&ill->ill_lock);
10367 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10368 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10369 			mutex_exit(&ill->ill_lock);
10370 			mutex_exit(&connp->conn_lock);
10371 			ipif_refrele(ipif);
10372 			return (option == IP_MULTICAST_IF ?
10373 			    EHOSTUNREACH : EINVAL);
10374 		}
10375 	} else {
10376 		mutex_enter(&connp->conn_lock);
10377 	}
10378 
10379 	/* None of the options below are supported on the VNI */
10380 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10381 		mutex_exit(&ill->ill_lock);
10382 		mutex_exit(&connp->conn_lock);
10383 		ipif_refrele(ipif);
10384 		return (EINVAL);
10385 	}
10386 
10387 	switch (option) {
10388 	case IP_DONTFAILOVER_IF:
10389 		/*
10390 		 * This option is used by in.mpathd to ensure
10391 		 * that IPMP probe packets only go out on the
10392 		 * test interfaces. in.mpathd sets this option
10393 		 * on the non-failover interfaces.
10394 		 * For backward compatibility, this option
10395 		 * implicitly sets IP_MULTICAST_IF, as used
10396 		 * be done in bind(), so that ip_wput gets
10397 		 * this ipif to send mcast packets.
10398 		 */
10399 		if (ipif != NULL) {
10400 			ASSERT(addr != INADDR_ANY);
10401 			connp->conn_nofailover_ill = ipif->ipif_ill;
10402 			connp->conn_multicast_ipif = ipif;
10403 		} else {
10404 			ASSERT(addr == INADDR_ANY);
10405 			connp->conn_nofailover_ill = NULL;
10406 			connp->conn_multicast_ipif = NULL;
10407 		}
10408 		break;
10409 
10410 	case IP_MULTICAST_IF:
10411 		connp->conn_multicast_ipif = ipif;
10412 		break;
10413 	case IP_NEXTHOP:
10414 		connp->conn_nexthop_v4 = addr;
10415 		connp->conn_nexthop_set = B_TRUE;
10416 		break;
10417 	}
10418 
10419 	if (ipif != NULL) {
10420 		mutex_exit(&ill->ill_lock);
10421 		mutex_exit(&connp->conn_lock);
10422 		ipif_refrele(ipif);
10423 		return (0);
10424 	}
10425 	mutex_exit(&connp->conn_lock);
10426 	/* We succeded in cleared the option */
10427 	return (0);
10428 }
10429 
10430 /*
10431  * For options that pass in an ifindex specifying the ill. V6 options always
10432  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10433  */
10434 int
10435 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10436     int level, int option, mblk_t *first_mp)
10437 {
10438 	ill_t *ill = NULL;
10439 	int error = 0;
10440 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10441 
10442 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10443 	if (ifindex != 0) {
10444 		ASSERT(connp != NULL);
10445 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10446 		    first_mp, ip_restart_optmgmt, &error, ipst);
10447 		if (ill != NULL) {
10448 			if (checkonly) {
10449 				/* not supported by the virtual network iface */
10450 				if (IS_VNI(ill)) {
10451 					ill_refrele(ill);
10452 					return (EINVAL);
10453 				}
10454 				ill_refrele(ill);
10455 				return (0);
10456 			}
10457 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10458 			    0, NULL)) {
10459 				ill_refrele(ill);
10460 				ill = NULL;
10461 				mutex_enter(&connp->conn_lock);
10462 				goto setit;
10463 			}
10464 			mutex_enter(&connp->conn_lock);
10465 			mutex_enter(&ill->ill_lock);
10466 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10467 				mutex_exit(&ill->ill_lock);
10468 				mutex_exit(&connp->conn_lock);
10469 				ill_refrele(ill);
10470 				ill = NULL;
10471 				mutex_enter(&connp->conn_lock);
10472 			}
10473 			goto setit;
10474 		} else if (error == EINPROGRESS) {
10475 			return (error);
10476 		} else {
10477 			error = 0;
10478 		}
10479 	}
10480 	mutex_enter(&connp->conn_lock);
10481 setit:
10482 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10483 
10484 	/*
10485 	 * The options below assume that the ILL (if any) transmits and/or
10486 	 * receives traffic. Neither of which is true for the virtual network
10487 	 * interface, so fail setting these on a VNI.
10488 	 */
10489 	if (IS_VNI(ill)) {
10490 		ASSERT(ill != NULL);
10491 		mutex_exit(&ill->ill_lock);
10492 		mutex_exit(&connp->conn_lock);
10493 		ill_refrele(ill);
10494 		return (EINVAL);
10495 	}
10496 
10497 	if (level == IPPROTO_IP) {
10498 		switch (option) {
10499 		case IP_BOUND_IF:
10500 			connp->conn_incoming_ill = ill;
10501 			connp->conn_outgoing_ill = ill;
10502 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10503 			    0 : ifindex;
10504 			break;
10505 
10506 		case IP_MULTICAST_IF:
10507 			/*
10508 			 * This option is an internal special. The socket
10509 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10510 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10511 			 * specifies an ifindex and we try first on V6 ill's.
10512 			 * If we don't find one, we they try using on v4 ill's
10513 			 * intenally and we come here.
10514 			 */
10515 			if (!checkonly && ill != NULL) {
10516 				ipif_t	*ipif;
10517 				ipif = ill->ill_ipif;
10518 
10519 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10520 					mutex_exit(&ill->ill_lock);
10521 					mutex_exit(&connp->conn_lock);
10522 					ill_refrele(ill);
10523 					ill = NULL;
10524 					mutex_enter(&connp->conn_lock);
10525 				} else {
10526 					connp->conn_multicast_ipif = ipif;
10527 				}
10528 			}
10529 			break;
10530 
10531 		case IP_DHCPINIT_IF:
10532 			if (connp->conn_dhcpinit_ill != NULL) {
10533 				/*
10534 				 * We've locked the conn so conn_cleanup_ill()
10535 				 * cannot clear conn_dhcpinit_ill -- so it's
10536 				 * safe to access the ill.
10537 				 */
10538 				ill_t *oill = connp->conn_dhcpinit_ill;
10539 
10540 				ASSERT(oill->ill_dhcpinit != 0);
10541 				atomic_dec_32(&oill->ill_dhcpinit);
10542 				connp->conn_dhcpinit_ill = NULL;
10543 			}
10544 
10545 			if (ill != NULL) {
10546 				connp->conn_dhcpinit_ill = ill;
10547 				atomic_inc_32(&ill->ill_dhcpinit);
10548 			}
10549 			break;
10550 		}
10551 	} else {
10552 		switch (option) {
10553 		case IPV6_BOUND_IF:
10554 			connp->conn_incoming_ill = ill;
10555 			connp->conn_outgoing_ill = ill;
10556 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10557 			    0 : ifindex;
10558 			break;
10559 
10560 		case IPV6_BOUND_PIF:
10561 			/*
10562 			 * Limit all transmit to this ill.
10563 			 * Unlike IPV6_BOUND_IF, using this option
10564 			 * prevents load spreading and failover from
10565 			 * happening when the interface is part of the
10566 			 * group. That's why we don't need to remember
10567 			 * the ifindex in orig_bound_ifindex as in
10568 			 * IPV6_BOUND_IF.
10569 			 */
10570 			connp->conn_outgoing_pill = ill;
10571 			break;
10572 
10573 		case IPV6_DONTFAILOVER_IF:
10574 			/*
10575 			 * This option is used by in.mpathd to ensure
10576 			 * that IPMP probe packets only go out on the
10577 			 * test interfaces. in.mpathd sets this option
10578 			 * on the non-failover interfaces.
10579 			 */
10580 			connp->conn_nofailover_ill = ill;
10581 			/*
10582 			 * For backward compatibility, this option
10583 			 * implicitly sets ip_multicast_ill as used in
10584 			 * IPV6_MULTICAST_IF so that ip_wput gets
10585 			 * this ill to send mcast packets.
10586 			 */
10587 			connp->conn_multicast_ill = ill;
10588 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10589 			    0 : ifindex;
10590 			break;
10591 
10592 		case IPV6_MULTICAST_IF:
10593 			/*
10594 			 * Set conn_multicast_ill to be the IPv6 ill.
10595 			 * Set conn_multicast_ipif to be an IPv4 ipif
10596 			 * for ifindex to make IPv4 mapped addresses
10597 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10598 			 * Even if no IPv6 ill exists for the ifindex
10599 			 * we need to check for an IPv4 ifindex in order
10600 			 * for this to work with mapped addresses. In that
10601 			 * case only set conn_multicast_ipif.
10602 			 */
10603 			if (!checkonly) {
10604 				if (ifindex == 0) {
10605 					connp->conn_multicast_ill = NULL;
10606 					connp->conn_orig_multicast_ifindex = 0;
10607 					connp->conn_multicast_ipif = NULL;
10608 				} else if (ill != NULL) {
10609 					connp->conn_multicast_ill = ill;
10610 					connp->conn_orig_multicast_ifindex =
10611 					    ifindex;
10612 				}
10613 			}
10614 			break;
10615 		}
10616 	}
10617 
10618 	if (ill != NULL) {
10619 		mutex_exit(&ill->ill_lock);
10620 		mutex_exit(&connp->conn_lock);
10621 		ill_refrele(ill);
10622 		return (0);
10623 	}
10624 	mutex_exit(&connp->conn_lock);
10625 	/*
10626 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10627 	 * locate the ill and could not set the option (ifindex != 0)
10628 	 */
10629 	return (ifindex == 0 ? 0 : EINVAL);
10630 }
10631 
10632 /* This routine sets socket options. */
10633 /* ARGSUSED */
10634 int
10635 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10636     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10637     void *dummy, cred_t *cr, mblk_t *first_mp)
10638 {
10639 	int		*i1 = (int *)invalp;
10640 	conn_t		*connp = Q_TO_CONN(q);
10641 	int		error = 0;
10642 	boolean_t	checkonly;
10643 	ire_t		*ire;
10644 	boolean_t	found;
10645 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10646 
10647 	switch (optset_context) {
10648 
10649 	case SETFN_OPTCOM_CHECKONLY:
10650 		checkonly = B_TRUE;
10651 		/*
10652 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10653 		 * inlen != 0 implies value supplied and
10654 		 * 	we have to "pretend" to set it.
10655 		 * inlen == 0 implies that there is no
10656 		 * 	value part in T_CHECK request and just validation
10657 		 * done elsewhere should be enough, we just return here.
10658 		 */
10659 		if (inlen == 0) {
10660 			*outlenp = 0;
10661 			return (0);
10662 		}
10663 		break;
10664 	case SETFN_OPTCOM_NEGOTIATE:
10665 	case SETFN_UD_NEGOTIATE:
10666 	case SETFN_CONN_NEGOTIATE:
10667 		checkonly = B_FALSE;
10668 		break;
10669 	default:
10670 		/*
10671 		 * We should never get here
10672 		 */
10673 		*outlenp = 0;
10674 		return (EINVAL);
10675 	}
10676 
10677 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10678 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10679 
10680 	/*
10681 	 * For fixed length options, no sanity check
10682 	 * of passed in length is done. It is assumed *_optcom_req()
10683 	 * routines do the right thing.
10684 	 */
10685 
10686 	switch (level) {
10687 	case SOL_SOCKET:
10688 		/*
10689 		 * conn_lock protects the bitfields, and is used to
10690 		 * set the fields atomically.
10691 		 */
10692 		switch (name) {
10693 		case SO_BROADCAST:
10694 			if (!checkonly) {
10695 				/* TODO: use value someplace? */
10696 				mutex_enter(&connp->conn_lock);
10697 				connp->conn_broadcast = *i1 ? 1 : 0;
10698 				mutex_exit(&connp->conn_lock);
10699 			}
10700 			break;	/* goto sizeof (int) option return */
10701 		case SO_USELOOPBACK:
10702 			if (!checkonly) {
10703 				/* TODO: use value someplace? */
10704 				mutex_enter(&connp->conn_lock);
10705 				connp->conn_loopback = *i1 ? 1 : 0;
10706 				mutex_exit(&connp->conn_lock);
10707 			}
10708 			break;	/* goto sizeof (int) option return */
10709 		case SO_DONTROUTE:
10710 			if (!checkonly) {
10711 				mutex_enter(&connp->conn_lock);
10712 				connp->conn_dontroute = *i1 ? 1 : 0;
10713 				mutex_exit(&connp->conn_lock);
10714 			}
10715 			break;	/* goto sizeof (int) option return */
10716 		case SO_REUSEADDR:
10717 			if (!checkonly) {
10718 				mutex_enter(&connp->conn_lock);
10719 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10720 				mutex_exit(&connp->conn_lock);
10721 			}
10722 			break;	/* goto sizeof (int) option return */
10723 		case SO_PROTOTYPE:
10724 			if (!checkonly) {
10725 				mutex_enter(&connp->conn_lock);
10726 				connp->conn_proto = *i1;
10727 				mutex_exit(&connp->conn_lock);
10728 			}
10729 			break;	/* goto sizeof (int) option return */
10730 		case SO_ALLZONES:
10731 			if (!checkonly) {
10732 				mutex_enter(&connp->conn_lock);
10733 				if (IPCL_IS_BOUND(connp)) {
10734 					mutex_exit(&connp->conn_lock);
10735 					return (EINVAL);
10736 				}
10737 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10738 				mutex_exit(&connp->conn_lock);
10739 			}
10740 			break;	/* goto sizeof (int) option return */
10741 		case SO_ANON_MLP:
10742 			if (!checkonly) {
10743 				mutex_enter(&connp->conn_lock);
10744 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10745 				mutex_exit(&connp->conn_lock);
10746 			}
10747 			break;	/* goto sizeof (int) option return */
10748 		case SO_MAC_EXEMPT:
10749 			if (secpolicy_net_mac_aware(cr) != 0 ||
10750 			    IPCL_IS_BOUND(connp))
10751 				return (EACCES);
10752 			if (!checkonly) {
10753 				mutex_enter(&connp->conn_lock);
10754 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10755 				mutex_exit(&connp->conn_lock);
10756 			}
10757 			break;	/* goto sizeof (int) option return */
10758 		default:
10759 			/*
10760 			 * "soft" error (negative)
10761 			 * option not handled at this level
10762 			 * Note: Do not modify *outlenp
10763 			 */
10764 			return (-EINVAL);
10765 		}
10766 		break;
10767 	case IPPROTO_IP:
10768 		switch (name) {
10769 		case IP_NEXTHOP:
10770 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10771 				return (EPERM);
10772 			/* FALLTHRU */
10773 		case IP_MULTICAST_IF:
10774 		case IP_DONTFAILOVER_IF: {
10775 			ipaddr_t addr = *i1;
10776 
10777 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10778 			    first_mp);
10779 			if (error != 0)
10780 				return (error);
10781 			break;	/* goto sizeof (int) option return */
10782 		}
10783 
10784 		case IP_MULTICAST_TTL:
10785 			/* Recorded in transport above IP */
10786 			*outvalp = *invalp;
10787 			*outlenp = sizeof (uchar_t);
10788 			return (0);
10789 		case IP_MULTICAST_LOOP:
10790 			if (!checkonly) {
10791 				mutex_enter(&connp->conn_lock);
10792 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10793 				mutex_exit(&connp->conn_lock);
10794 			}
10795 			*outvalp = *invalp;
10796 			*outlenp = sizeof (uchar_t);
10797 			return (0);
10798 		case IP_ADD_MEMBERSHIP:
10799 		case MCAST_JOIN_GROUP:
10800 		case IP_DROP_MEMBERSHIP:
10801 		case MCAST_LEAVE_GROUP: {
10802 			struct ip_mreq *mreqp;
10803 			struct group_req *greqp;
10804 			ire_t *ire;
10805 			boolean_t done = B_FALSE;
10806 			ipaddr_t group, ifaddr;
10807 			struct sockaddr_in *sin;
10808 			uint32_t *ifindexp;
10809 			boolean_t mcast_opt = B_TRUE;
10810 			mcast_record_t fmode;
10811 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10812 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10813 
10814 			switch (name) {
10815 			case IP_ADD_MEMBERSHIP:
10816 				mcast_opt = B_FALSE;
10817 				/* FALLTHRU */
10818 			case MCAST_JOIN_GROUP:
10819 				fmode = MODE_IS_EXCLUDE;
10820 				optfn = ip_opt_add_group;
10821 				break;
10822 
10823 			case IP_DROP_MEMBERSHIP:
10824 				mcast_opt = B_FALSE;
10825 				/* FALLTHRU */
10826 			case MCAST_LEAVE_GROUP:
10827 				fmode = MODE_IS_INCLUDE;
10828 				optfn = ip_opt_delete_group;
10829 				break;
10830 			}
10831 
10832 			if (mcast_opt) {
10833 				greqp = (struct group_req *)i1;
10834 				sin = (struct sockaddr_in *)&greqp->gr_group;
10835 				if (sin->sin_family != AF_INET) {
10836 					*outlenp = 0;
10837 					return (ENOPROTOOPT);
10838 				}
10839 				group = (ipaddr_t)sin->sin_addr.s_addr;
10840 				ifaddr = INADDR_ANY;
10841 				ifindexp = &greqp->gr_interface;
10842 			} else {
10843 				mreqp = (struct ip_mreq *)i1;
10844 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10845 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10846 				ifindexp = NULL;
10847 			}
10848 
10849 			/*
10850 			 * In the multirouting case, we need to replicate
10851 			 * the request on all interfaces that will take part
10852 			 * in replication.  We do so because multirouting is
10853 			 * reflective, thus we will probably receive multi-
10854 			 * casts on those interfaces.
10855 			 * The ip_multirt_apply_membership() succeeds if the
10856 			 * operation succeeds on at least one interface.
10857 			 */
10858 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10859 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10860 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10861 			if (ire != NULL) {
10862 				if (ire->ire_flags & RTF_MULTIRT) {
10863 					error = ip_multirt_apply_membership(
10864 					    optfn, ire, connp, checkonly, group,
10865 					    fmode, INADDR_ANY, first_mp);
10866 					done = B_TRUE;
10867 				}
10868 				ire_refrele(ire);
10869 			}
10870 			if (!done) {
10871 				error = optfn(connp, checkonly, group, ifaddr,
10872 				    ifindexp, fmode, INADDR_ANY, first_mp);
10873 			}
10874 			if (error) {
10875 				/*
10876 				 * EINPROGRESS is a soft error, needs retry
10877 				 * so don't make *outlenp zero.
10878 				 */
10879 				if (error != EINPROGRESS)
10880 					*outlenp = 0;
10881 				return (error);
10882 			}
10883 			/* OK return - copy input buffer into output buffer */
10884 			if (invalp != outvalp) {
10885 				/* don't trust bcopy for identical src/dst */
10886 				bcopy(invalp, outvalp, inlen);
10887 			}
10888 			*outlenp = inlen;
10889 			return (0);
10890 		}
10891 		case IP_BLOCK_SOURCE:
10892 		case IP_UNBLOCK_SOURCE:
10893 		case IP_ADD_SOURCE_MEMBERSHIP:
10894 		case IP_DROP_SOURCE_MEMBERSHIP:
10895 		case MCAST_BLOCK_SOURCE:
10896 		case MCAST_UNBLOCK_SOURCE:
10897 		case MCAST_JOIN_SOURCE_GROUP:
10898 		case MCAST_LEAVE_SOURCE_GROUP: {
10899 			struct ip_mreq_source *imreqp;
10900 			struct group_source_req *gsreqp;
10901 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10902 			uint32_t ifindex = 0;
10903 			mcast_record_t fmode;
10904 			struct sockaddr_in *sin;
10905 			ire_t *ire;
10906 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10907 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10908 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10909 
10910 			switch (name) {
10911 			case IP_BLOCK_SOURCE:
10912 				mcast_opt = B_FALSE;
10913 				/* FALLTHRU */
10914 			case MCAST_BLOCK_SOURCE:
10915 				fmode = MODE_IS_EXCLUDE;
10916 				optfn = ip_opt_add_group;
10917 				break;
10918 
10919 			case IP_UNBLOCK_SOURCE:
10920 				mcast_opt = B_FALSE;
10921 				/* FALLTHRU */
10922 			case MCAST_UNBLOCK_SOURCE:
10923 				fmode = MODE_IS_EXCLUDE;
10924 				optfn = ip_opt_delete_group;
10925 				break;
10926 
10927 			case IP_ADD_SOURCE_MEMBERSHIP:
10928 				mcast_opt = B_FALSE;
10929 				/* FALLTHRU */
10930 			case MCAST_JOIN_SOURCE_GROUP:
10931 				fmode = MODE_IS_INCLUDE;
10932 				optfn = ip_opt_add_group;
10933 				break;
10934 
10935 			case IP_DROP_SOURCE_MEMBERSHIP:
10936 				mcast_opt = B_FALSE;
10937 				/* FALLTHRU */
10938 			case MCAST_LEAVE_SOURCE_GROUP:
10939 				fmode = MODE_IS_INCLUDE;
10940 				optfn = ip_opt_delete_group;
10941 				break;
10942 			}
10943 
10944 			if (mcast_opt) {
10945 				gsreqp = (struct group_source_req *)i1;
10946 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10947 					*outlenp = 0;
10948 					return (ENOPROTOOPT);
10949 				}
10950 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10951 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10952 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10953 				src = (ipaddr_t)sin->sin_addr.s_addr;
10954 				ifindex = gsreqp->gsr_interface;
10955 			} else {
10956 				imreqp = (struct ip_mreq_source *)i1;
10957 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10958 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10959 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10960 			}
10961 
10962 			/*
10963 			 * In the multirouting case, we need to replicate
10964 			 * the request as noted in the mcast cases above.
10965 			 */
10966 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10967 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10968 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10969 			if (ire != NULL) {
10970 				if (ire->ire_flags & RTF_MULTIRT) {
10971 					error = ip_multirt_apply_membership(
10972 					    optfn, ire, connp, checkonly, grp,
10973 					    fmode, src, first_mp);
10974 					done = B_TRUE;
10975 				}
10976 				ire_refrele(ire);
10977 			}
10978 			if (!done) {
10979 				error = optfn(connp, checkonly, grp, ifaddr,
10980 				    &ifindex, fmode, src, first_mp);
10981 			}
10982 			if (error != 0) {
10983 				/*
10984 				 * EINPROGRESS is a soft error, needs retry
10985 				 * so don't make *outlenp zero.
10986 				 */
10987 				if (error != EINPROGRESS)
10988 					*outlenp = 0;
10989 				return (error);
10990 			}
10991 			/* OK return - copy input buffer into output buffer */
10992 			if (invalp != outvalp) {
10993 				bcopy(invalp, outvalp, inlen);
10994 			}
10995 			*outlenp = inlen;
10996 			return (0);
10997 		}
10998 		case IP_SEC_OPT:
10999 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11000 			if (error != 0) {
11001 				*outlenp = 0;
11002 				return (error);
11003 			}
11004 			break;
11005 		case IP_HDRINCL:
11006 		case IP_OPTIONS:
11007 		case T_IP_OPTIONS:
11008 		case IP_TOS:
11009 		case T_IP_TOS:
11010 		case IP_TTL:
11011 		case IP_RECVDSTADDR:
11012 		case IP_RECVOPTS:
11013 			/* OK return - copy input buffer into output buffer */
11014 			if (invalp != outvalp) {
11015 				/* don't trust bcopy for identical src/dst */
11016 				bcopy(invalp, outvalp, inlen);
11017 			}
11018 			*outlenp = inlen;
11019 			return (0);
11020 		case IP_RECVIF:
11021 			/* Retrieve the inbound interface index */
11022 			if (!checkonly) {
11023 				mutex_enter(&connp->conn_lock);
11024 				connp->conn_recvif = *i1 ? 1 : 0;
11025 				mutex_exit(&connp->conn_lock);
11026 			}
11027 			break;	/* goto sizeof (int) option return */
11028 		case IP_RECVPKTINFO:
11029 			if (!checkonly) {
11030 				mutex_enter(&connp->conn_lock);
11031 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11032 				mutex_exit(&connp->conn_lock);
11033 			}
11034 			break;	/* goto sizeof (int) option return */
11035 		case IP_RECVSLLA:
11036 			/* Retrieve the source link layer address */
11037 			if (!checkonly) {
11038 				mutex_enter(&connp->conn_lock);
11039 				connp->conn_recvslla = *i1 ? 1 : 0;
11040 				mutex_exit(&connp->conn_lock);
11041 			}
11042 			break;	/* goto sizeof (int) option return */
11043 		case MRT_INIT:
11044 		case MRT_DONE:
11045 		case MRT_ADD_VIF:
11046 		case MRT_DEL_VIF:
11047 		case MRT_ADD_MFC:
11048 		case MRT_DEL_MFC:
11049 		case MRT_ASSERT:
11050 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11051 				*outlenp = 0;
11052 				return (error);
11053 			}
11054 			error = ip_mrouter_set((int)name, q, checkonly,
11055 			    (uchar_t *)invalp, inlen, first_mp);
11056 			if (error) {
11057 				*outlenp = 0;
11058 				return (error);
11059 			}
11060 			/* OK return - copy input buffer into output buffer */
11061 			if (invalp != outvalp) {
11062 				/* don't trust bcopy for identical src/dst */
11063 				bcopy(invalp, outvalp, inlen);
11064 			}
11065 			*outlenp = inlen;
11066 			return (0);
11067 		case IP_BOUND_IF:
11068 		case IP_DHCPINIT_IF:
11069 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11070 			    level, name, first_mp);
11071 			if (error != 0)
11072 				return (error);
11073 			break; 		/* goto sizeof (int) option return */
11074 
11075 		case IP_UNSPEC_SRC:
11076 			/* Allow sending with a zero source address */
11077 			if (!checkonly) {
11078 				mutex_enter(&connp->conn_lock);
11079 				connp->conn_unspec_src = *i1 ? 1 : 0;
11080 				mutex_exit(&connp->conn_lock);
11081 			}
11082 			break;	/* goto sizeof (int) option return */
11083 		default:
11084 			/*
11085 			 * "soft" error (negative)
11086 			 * option not handled at this level
11087 			 * Note: Do not modify *outlenp
11088 			 */
11089 			return (-EINVAL);
11090 		}
11091 		break;
11092 	case IPPROTO_IPV6:
11093 		switch (name) {
11094 		case IPV6_BOUND_IF:
11095 		case IPV6_BOUND_PIF:
11096 		case IPV6_DONTFAILOVER_IF:
11097 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11098 			    level, name, first_mp);
11099 			if (error != 0)
11100 				return (error);
11101 			break; 		/* goto sizeof (int) option return */
11102 
11103 		case IPV6_MULTICAST_IF:
11104 			/*
11105 			 * The only possible errors are EINPROGRESS and
11106 			 * EINVAL. EINPROGRESS will be restarted and is not
11107 			 * a hard error. We call this option on both V4 and V6
11108 			 * If both return EINVAL, then this call returns
11109 			 * EINVAL. If at least one of them succeeds we
11110 			 * return success.
11111 			 */
11112 			found = B_FALSE;
11113 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11114 			    level, name, first_mp);
11115 			if (error == EINPROGRESS)
11116 				return (error);
11117 			if (error == 0)
11118 				found = B_TRUE;
11119 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11120 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11121 			if (error == 0)
11122 				found = B_TRUE;
11123 			if (!found)
11124 				return (error);
11125 			break; 		/* goto sizeof (int) option return */
11126 
11127 		case IPV6_MULTICAST_HOPS:
11128 			/* Recorded in transport above IP */
11129 			break;	/* goto sizeof (int) option return */
11130 		case IPV6_MULTICAST_LOOP:
11131 			if (!checkonly) {
11132 				mutex_enter(&connp->conn_lock);
11133 				connp->conn_multicast_loop = *i1;
11134 				mutex_exit(&connp->conn_lock);
11135 			}
11136 			break;	/* goto sizeof (int) option return */
11137 		case IPV6_JOIN_GROUP:
11138 		case MCAST_JOIN_GROUP:
11139 		case IPV6_LEAVE_GROUP:
11140 		case MCAST_LEAVE_GROUP: {
11141 			struct ipv6_mreq *ip_mreqp;
11142 			struct group_req *greqp;
11143 			ire_t *ire;
11144 			boolean_t done = B_FALSE;
11145 			in6_addr_t groupv6;
11146 			uint32_t ifindex;
11147 			boolean_t mcast_opt = B_TRUE;
11148 			mcast_record_t fmode;
11149 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11150 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11151 
11152 			switch (name) {
11153 			case IPV6_JOIN_GROUP:
11154 				mcast_opt = B_FALSE;
11155 				/* FALLTHRU */
11156 			case MCAST_JOIN_GROUP:
11157 				fmode = MODE_IS_EXCLUDE;
11158 				optfn = ip_opt_add_group_v6;
11159 				break;
11160 
11161 			case IPV6_LEAVE_GROUP:
11162 				mcast_opt = B_FALSE;
11163 				/* FALLTHRU */
11164 			case MCAST_LEAVE_GROUP:
11165 				fmode = MODE_IS_INCLUDE;
11166 				optfn = ip_opt_delete_group_v6;
11167 				break;
11168 			}
11169 
11170 			if (mcast_opt) {
11171 				struct sockaddr_in *sin;
11172 				struct sockaddr_in6 *sin6;
11173 				greqp = (struct group_req *)i1;
11174 				if (greqp->gr_group.ss_family == AF_INET) {
11175 					sin = (struct sockaddr_in *)
11176 					    &(greqp->gr_group);
11177 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11178 					    &groupv6);
11179 				} else {
11180 					sin6 = (struct sockaddr_in6 *)
11181 					    &(greqp->gr_group);
11182 					groupv6 = sin6->sin6_addr;
11183 				}
11184 				ifindex = greqp->gr_interface;
11185 			} else {
11186 				ip_mreqp = (struct ipv6_mreq *)i1;
11187 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11188 				ifindex = ip_mreqp->ipv6mr_interface;
11189 			}
11190 			/*
11191 			 * In the multirouting case, we need to replicate
11192 			 * the request on all interfaces that will take part
11193 			 * in replication.  We do so because multirouting is
11194 			 * reflective, thus we will probably receive multi-
11195 			 * casts on those interfaces.
11196 			 * The ip_multirt_apply_membership_v6() succeeds if
11197 			 * the operation succeeds on at least one interface.
11198 			 */
11199 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11200 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11201 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11202 			if (ire != NULL) {
11203 				if (ire->ire_flags & RTF_MULTIRT) {
11204 					error = ip_multirt_apply_membership_v6(
11205 					    optfn, ire, connp, checkonly,
11206 					    &groupv6, fmode, &ipv6_all_zeros,
11207 					    first_mp);
11208 					done = B_TRUE;
11209 				}
11210 				ire_refrele(ire);
11211 			}
11212 			if (!done) {
11213 				error = optfn(connp, checkonly, &groupv6,
11214 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11215 			}
11216 			if (error) {
11217 				/*
11218 				 * EINPROGRESS is a soft error, needs retry
11219 				 * so don't make *outlenp zero.
11220 				 */
11221 				if (error != EINPROGRESS)
11222 					*outlenp = 0;
11223 				return (error);
11224 			}
11225 			/* OK return - copy input buffer into output buffer */
11226 			if (invalp != outvalp) {
11227 				/* don't trust bcopy for identical src/dst */
11228 				bcopy(invalp, outvalp, inlen);
11229 			}
11230 			*outlenp = inlen;
11231 			return (0);
11232 		}
11233 		case MCAST_BLOCK_SOURCE:
11234 		case MCAST_UNBLOCK_SOURCE:
11235 		case MCAST_JOIN_SOURCE_GROUP:
11236 		case MCAST_LEAVE_SOURCE_GROUP: {
11237 			struct group_source_req *gsreqp;
11238 			in6_addr_t v6grp, v6src;
11239 			uint32_t ifindex;
11240 			mcast_record_t fmode;
11241 			ire_t *ire;
11242 			boolean_t done = B_FALSE;
11243 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11244 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11245 
11246 			switch (name) {
11247 			case MCAST_BLOCK_SOURCE:
11248 				fmode = MODE_IS_EXCLUDE;
11249 				optfn = ip_opt_add_group_v6;
11250 				break;
11251 			case MCAST_UNBLOCK_SOURCE:
11252 				fmode = MODE_IS_EXCLUDE;
11253 				optfn = ip_opt_delete_group_v6;
11254 				break;
11255 			case MCAST_JOIN_SOURCE_GROUP:
11256 				fmode = MODE_IS_INCLUDE;
11257 				optfn = ip_opt_add_group_v6;
11258 				break;
11259 			case MCAST_LEAVE_SOURCE_GROUP:
11260 				fmode = MODE_IS_INCLUDE;
11261 				optfn = ip_opt_delete_group_v6;
11262 				break;
11263 			}
11264 
11265 			gsreqp = (struct group_source_req *)i1;
11266 			ifindex = gsreqp->gsr_interface;
11267 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11268 				struct sockaddr_in *s;
11269 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11270 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11271 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11272 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11273 			} else {
11274 				struct sockaddr_in6 *s6;
11275 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11276 				v6grp = s6->sin6_addr;
11277 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11278 				v6src = s6->sin6_addr;
11279 			}
11280 
11281 			/*
11282 			 * In the multirouting case, we need to replicate
11283 			 * the request as noted in the mcast cases above.
11284 			 */
11285 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11286 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11287 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11288 			if (ire != NULL) {
11289 				if (ire->ire_flags & RTF_MULTIRT) {
11290 					error = ip_multirt_apply_membership_v6(
11291 					    optfn, ire, connp, checkonly,
11292 					    &v6grp, fmode, &v6src, first_mp);
11293 					done = B_TRUE;
11294 				}
11295 				ire_refrele(ire);
11296 			}
11297 			if (!done) {
11298 				error = optfn(connp, checkonly, &v6grp,
11299 				    ifindex, fmode, &v6src, first_mp);
11300 			}
11301 			if (error != 0) {
11302 				/*
11303 				 * EINPROGRESS is a soft error, needs retry
11304 				 * so don't make *outlenp zero.
11305 				 */
11306 				if (error != EINPROGRESS)
11307 					*outlenp = 0;
11308 				return (error);
11309 			}
11310 			/* OK return - copy input buffer into output buffer */
11311 			if (invalp != outvalp) {
11312 				bcopy(invalp, outvalp, inlen);
11313 			}
11314 			*outlenp = inlen;
11315 			return (0);
11316 		}
11317 		case IPV6_UNICAST_HOPS:
11318 			/* Recorded in transport above IP */
11319 			break;	/* goto sizeof (int) option return */
11320 		case IPV6_UNSPEC_SRC:
11321 			/* Allow sending with a zero source address */
11322 			if (!checkonly) {
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_unspec_src = *i1 ? 1 : 0;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;	/* goto sizeof (int) option return */
11328 		case IPV6_RECVPKTINFO:
11329 			if (!checkonly) {
11330 				mutex_enter(&connp->conn_lock);
11331 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11332 				mutex_exit(&connp->conn_lock);
11333 			}
11334 			break;	/* goto sizeof (int) option return */
11335 		case IPV6_RECVTCLASS:
11336 			if (!checkonly) {
11337 				if (*i1 < 0 || *i1 > 1) {
11338 					return (EINVAL);
11339 				}
11340 				mutex_enter(&connp->conn_lock);
11341 				connp->conn_ipv6_recvtclass = *i1;
11342 				mutex_exit(&connp->conn_lock);
11343 			}
11344 			break;
11345 		case IPV6_RECVPATHMTU:
11346 			if (!checkonly) {
11347 				if (*i1 < 0 || *i1 > 1) {
11348 					return (EINVAL);
11349 				}
11350 				mutex_enter(&connp->conn_lock);
11351 				connp->conn_ipv6_recvpathmtu = *i1;
11352 				mutex_exit(&connp->conn_lock);
11353 			}
11354 			break;
11355 		case IPV6_RECVHOPLIMIT:
11356 			if (!checkonly) {
11357 				mutex_enter(&connp->conn_lock);
11358 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11359 				mutex_exit(&connp->conn_lock);
11360 			}
11361 			break;	/* goto sizeof (int) option return */
11362 		case IPV6_RECVHOPOPTS:
11363 			if (!checkonly) {
11364 				mutex_enter(&connp->conn_lock);
11365 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11366 				mutex_exit(&connp->conn_lock);
11367 			}
11368 			break;	/* goto sizeof (int) option return */
11369 		case IPV6_RECVDSTOPTS:
11370 			if (!checkonly) {
11371 				mutex_enter(&connp->conn_lock);
11372 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11373 				mutex_exit(&connp->conn_lock);
11374 			}
11375 			break;	/* goto sizeof (int) option return */
11376 		case IPV6_RECVRTHDR:
11377 			if (!checkonly) {
11378 				mutex_enter(&connp->conn_lock);
11379 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11380 				mutex_exit(&connp->conn_lock);
11381 			}
11382 			break;	/* goto sizeof (int) option return */
11383 		case IPV6_RECVRTHDRDSTOPTS:
11384 			if (!checkonly) {
11385 				mutex_enter(&connp->conn_lock);
11386 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11387 				mutex_exit(&connp->conn_lock);
11388 			}
11389 			break;	/* goto sizeof (int) option return */
11390 		case IPV6_PKTINFO:
11391 			if (inlen == 0)
11392 				return (-EINVAL);	/* clearing option */
11393 			error = ip6_set_pktinfo(cr, connp,
11394 			    (struct in6_pktinfo *)invalp, first_mp);
11395 			if (error != 0)
11396 				*outlenp = 0;
11397 			else
11398 				*outlenp = inlen;
11399 			return (error);
11400 		case IPV6_NEXTHOP: {
11401 			struct sockaddr_in6 *sin6;
11402 
11403 			/* Verify that the nexthop is reachable */
11404 			if (inlen == 0)
11405 				return (-EINVAL);	/* clearing option */
11406 
11407 			sin6 = (struct sockaddr_in6 *)invalp;
11408 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11409 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11410 			    NULL, MATCH_IRE_DEFAULT, ipst);
11411 
11412 			if (ire == NULL) {
11413 				*outlenp = 0;
11414 				return (EHOSTUNREACH);
11415 			}
11416 			ire_refrele(ire);
11417 			return (-EINVAL);
11418 		}
11419 		case IPV6_SEC_OPT:
11420 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11421 			if (error != 0) {
11422 				*outlenp = 0;
11423 				return (error);
11424 			}
11425 			break;
11426 		case IPV6_SRC_PREFERENCES: {
11427 			/*
11428 			 * This is implemented strictly in the ip module
11429 			 * (here and in tcp_opt_*() to accomodate tcp
11430 			 * sockets).  Modules above ip pass this option
11431 			 * down here since ip is the only one that needs to
11432 			 * be aware of source address preferences.
11433 			 *
11434 			 * This socket option only affects connected
11435 			 * sockets that haven't already bound to a specific
11436 			 * IPv6 address.  In other words, sockets that
11437 			 * don't call bind() with an address other than the
11438 			 * unspecified address and that call connect().
11439 			 * ip_bind_connected_v6() passes these preferences
11440 			 * to the ipif_select_source_v6() function.
11441 			 */
11442 			if (inlen != sizeof (uint32_t))
11443 				return (EINVAL);
11444 			error = ip6_set_src_preferences(connp,
11445 			    *(uint32_t *)invalp);
11446 			if (error != 0) {
11447 				*outlenp = 0;
11448 				return (error);
11449 			} else {
11450 				*outlenp = sizeof (uint32_t);
11451 			}
11452 			break;
11453 		}
11454 		case IPV6_V6ONLY:
11455 			if (*i1 < 0 || *i1 > 1) {
11456 				return (EINVAL);
11457 			}
11458 			mutex_enter(&connp->conn_lock);
11459 			connp->conn_ipv6_v6only = *i1;
11460 			mutex_exit(&connp->conn_lock);
11461 			break;
11462 		default:
11463 			return (-EINVAL);
11464 		}
11465 		break;
11466 	default:
11467 		/*
11468 		 * "soft" error (negative)
11469 		 * option not handled at this level
11470 		 * Note: Do not modify *outlenp
11471 		 */
11472 		return (-EINVAL);
11473 	}
11474 	/*
11475 	 * Common case of return from an option that is sizeof (int)
11476 	 */
11477 	*(int *)outvalp = *i1;
11478 	*outlenp = sizeof (int);
11479 	return (0);
11480 }
11481 
11482 /*
11483  * This routine gets default values of certain options whose default
11484  * values are maintained by protocol specific code
11485  */
11486 /* ARGSUSED */
11487 int
11488 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11489 {
11490 	int *i1 = (int *)ptr;
11491 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11492 
11493 	switch (level) {
11494 	case IPPROTO_IP:
11495 		switch (name) {
11496 		case IP_MULTICAST_TTL:
11497 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11498 			return (sizeof (uchar_t));
11499 		case IP_MULTICAST_LOOP:
11500 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11501 			return (sizeof (uchar_t));
11502 		default:
11503 			return (-1);
11504 		}
11505 	case IPPROTO_IPV6:
11506 		switch (name) {
11507 		case IPV6_UNICAST_HOPS:
11508 			*i1 = ipst->ips_ipv6_def_hops;
11509 			return (sizeof (int));
11510 		case IPV6_MULTICAST_HOPS:
11511 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11512 			return (sizeof (int));
11513 		case IPV6_MULTICAST_LOOP:
11514 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11515 			return (sizeof (int));
11516 		case IPV6_V6ONLY:
11517 			*i1 = 1;
11518 			return (sizeof (int));
11519 		default:
11520 			return (-1);
11521 		}
11522 	default:
11523 		return (-1);
11524 	}
11525 	/* NOTREACHED */
11526 }
11527 
11528 /*
11529  * Given a destination address and a pointer to where to put the information
11530  * this routine fills in the mtuinfo.
11531  */
11532 int
11533 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11534     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11535 {
11536 	ire_t *ire;
11537 	ip_stack_t	*ipst = ns->netstack_ip;
11538 
11539 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11540 		return (-1);
11541 
11542 	bzero(mtuinfo, sizeof (*mtuinfo));
11543 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11544 	mtuinfo->ip6m_addr.sin6_port = port;
11545 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11546 
11547 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11548 	if (ire != NULL) {
11549 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11550 		ire_refrele(ire);
11551 	} else {
11552 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11553 	}
11554 	return (sizeof (struct ip6_mtuinfo));
11555 }
11556 
11557 /*
11558  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11559  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11560  * isn't.  This doesn't matter as the error checking is done properly for the
11561  * other MRT options coming in through ip_opt_set.
11562  */
11563 int
11564 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11565 {
11566 	conn_t		*connp = Q_TO_CONN(q);
11567 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11568 
11569 	switch (level) {
11570 	case IPPROTO_IP:
11571 		switch (name) {
11572 		case MRT_VERSION:
11573 		case MRT_ASSERT:
11574 			(void) ip_mrouter_get(name, q, ptr);
11575 			return (sizeof (int));
11576 		case IP_SEC_OPT:
11577 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11578 		case IP_NEXTHOP:
11579 			if (connp->conn_nexthop_set) {
11580 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11581 				return (sizeof (ipaddr_t));
11582 			} else
11583 				return (0);
11584 		case IP_RECVPKTINFO:
11585 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11586 			return (sizeof (int));
11587 		default:
11588 			break;
11589 		}
11590 		break;
11591 	case IPPROTO_IPV6:
11592 		switch (name) {
11593 		case IPV6_SEC_OPT:
11594 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11595 		case IPV6_SRC_PREFERENCES: {
11596 			return (ip6_get_src_preferences(connp,
11597 			    (uint32_t *)ptr));
11598 		}
11599 		case IPV6_V6ONLY:
11600 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11601 			return (sizeof (int));
11602 		case IPV6_PATHMTU:
11603 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11604 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11605 		default:
11606 			break;
11607 		}
11608 		break;
11609 	default:
11610 		break;
11611 	}
11612 	return (-1);
11613 }
11614 
11615 /* Named Dispatch routine to get a current value out of our parameter table. */
11616 /* ARGSUSED */
11617 static int
11618 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11619 {
11620 	ipparam_t *ippa = (ipparam_t *)cp;
11621 
11622 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11623 	return (0);
11624 }
11625 
11626 /* ARGSUSED */
11627 static int
11628 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11629 {
11630 
11631 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11632 	return (0);
11633 }
11634 
11635 /*
11636  * Set ip{,6}_forwarding values.  This means walking through all of the
11637  * ill's and toggling their forwarding values.
11638  */
11639 /* ARGSUSED */
11640 static int
11641 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11642 {
11643 	long new_value;
11644 	int *forwarding_value = (int *)cp;
11645 	ill_t *ill;
11646 	boolean_t isv6;
11647 	ill_walk_context_t ctx;
11648 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11649 
11650 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11651 
11652 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11653 	    new_value < 0 || new_value > 1) {
11654 		return (EINVAL);
11655 	}
11656 
11657 	*forwarding_value = new_value;
11658 
11659 	/*
11660 	 * Regardless of the current value of ip_forwarding, set all per-ill
11661 	 * values of ip_forwarding to the value being set.
11662 	 *
11663 	 * Bring all the ill's up to date with the new global value.
11664 	 */
11665 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11666 
11667 	if (isv6)
11668 		ill = ILL_START_WALK_V6(&ctx, ipst);
11669 	else
11670 		ill = ILL_START_WALK_V4(&ctx, ipst);
11671 
11672 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11673 		(void) ill_forward_set(ill, new_value != 0);
11674 
11675 	rw_exit(&ipst->ips_ill_g_lock);
11676 	return (0);
11677 }
11678 
11679 /*
11680  * Walk through the param array specified registering each element with the
11681  * Named Dispatch handler. This is called only during init. So it is ok
11682  * not to acquire any locks
11683  */
11684 static boolean_t
11685 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11686     ipndp_t *ipnd, size_t ipnd_cnt)
11687 {
11688 	for (; ippa_cnt-- > 0; ippa++) {
11689 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11690 			if (!nd_load(ndp, ippa->ip_param_name,
11691 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11692 				nd_free(ndp);
11693 				return (B_FALSE);
11694 			}
11695 		}
11696 	}
11697 
11698 	for (; ipnd_cnt-- > 0; ipnd++) {
11699 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11700 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11701 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11702 			    ipnd->ip_ndp_data)) {
11703 				nd_free(ndp);
11704 				return (B_FALSE);
11705 			}
11706 		}
11707 	}
11708 
11709 	return (B_TRUE);
11710 }
11711 
11712 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11713 /* ARGSUSED */
11714 static int
11715 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11716 {
11717 	long		new_value;
11718 	ipparam_t	*ippa = (ipparam_t *)cp;
11719 
11720 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11721 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11722 		return (EINVAL);
11723 	}
11724 	ippa->ip_param_value = new_value;
11725 	return (0);
11726 }
11727 
11728 /*
11729  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11730  * When an ipf is passed here for the first time, if
11731  * we already have in-order fragments on the queue, we convert from the fast-
11732  * path reassembly scheme to the hard-case scheme.  From then on, additional
11733  * fragments are reassembled here.  We keep track of the start and end offsets
11734  * of each piece, and the number of holes in the chain.  When the hole count
11735  * goes to zero, we are done!
11736  *
11737  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11738  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11739  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11740  * after the call to ip_reassemble().
11741  */
11742 int
11743 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11744     size_t msg_len)
11745 {
11746 	uint_t	end;
11747 	mblk_t	*next_mp;
11748 	mblk_t	*mp1;
11749 	uint_t	offset;
11750 	boolean_t incr_dups = B_TRUE;
11751 	boolean_t offset_zero_seen = B_FALSE;
11752 	boolean_t pkt_boundary_checked = B_FALSE;
11753 
11754 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11755 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11756 
11757 	/* Add in byte count */
11758 	ipf->ipf_count += msg_len;
11759 	if (ipf->ipf_end) {
11760 		/*
11761 		 * We were part way through in-order reassembly, but now there
11762 		 * is a hole.  We walk through messages already queued, and
11763 		 * mark them for hard case reassembly.  We know that up till
11764 		 * now they were in order starting from offset zero.
11765 		 */
11766 		offset = 0;
11767 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11768 			IP_REASS_SET_START(mp1, offset);
11769 			if (offset == 0) {
11770 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11771 				offset = -ipf->ipf_nf_hdr_len;
11772 			}
11773 			offset += mp1->b_wptr - mp1->b_rptr;
11774 			IP_REASS_SET_END(mp1, offset);
11775 		}
11776 		/* One hole at the end. */
11777 		ipf->ipf_hole_cnt = 1;
11778 		/* Brand it as a hard case, forever. */
11779 		ipf->ipf_end = 0;
11780 	}
11781 	/* Walk through all the new pieces. */
11782 	do {
11783 		end = start + (mp->b_wptr - mp->b_rptr);
11784 		/*
11785 		 * If start is 0, decrease 'end' only for the first mblk of
11786 		 * the fragment. Otherwise 'end' can get wrong value in the
11787 		 * second pass of the loop if first mblk is exactly the
11788 		 * size of ipf_nf_hdr_len.
11789 		 */
11790 		if (start == 0 && !offset_zero_seen) {
11791 			/* First segment */
11792 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11793 			end -= ipf->ipf_nf_hdr_len;
11794 			offset_zero_seen = B_TRUE;
11795 		}
11796 		next_mp = mp->b_cont;
11797 		/*
11798 		 * We are checking to see if there is any interesing data
11799 		 * to process.  If there isn't and the mblk isn't the
11800 		 * one which carries the unfragmentable header then we
11801 		 * drop it.  It's possible to have just the unfragmentable
11802 		 * header come through without any data.  That needs to be
11803 		 * saved.
11804 		 *
11805 		 * If the assert at the top of this function holds then the
11806 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11807 		 * is infrequently traveled enough that the test is left in
11808 		 * to protect against future code changes which break that
11809 		 * invariant.
11810 		 */
11811 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11812 			/* Empty.  Blast it. */
11813 			IP_REASS_SET_START(mp, 0);
11814 			IP_REASS_SET_END(mp, 0);
11815 			/*
11816 			 * If the ipf points to the mblk we are about to free,
11817 			 * update ipf to point to the next mblk (or NULL
11818 			 * if none).
11819 			 */
11820 			if (ipf->ipf_mp->b_cont == mp)
11821 				ipf->ipf_mp->b_cont = next_mp;
11822 			freeb(mp);
11823 			continue;
11824 		}
11825 		mp->b_cont = NULL;
11826 		IP_REASS_SET_START(mp, start);
11827 		IP_REASS_SET_END(mp, end);
11828 		if (!ipf->ipf_tail_mp) {
11829 			ipf->ipf_tail_mp = mp;
11830 			ipf->ipf_mp->b_cont = mp;
11831 			if (start == 0 || !more) {
11832 				ipf->ipf_hole_cnt = 1;
11833 				/*
11834 				 * if the first fragment comes in more than one
11835 				 * mblk, this loop will be executed for each
11836 				 * mblk. Need to adjust hole count so exiting
11837 				 * this routine will leave hole count at 1.
11838 				 */
11839 				if (next_mp)
11840 					ipf->ipf_hole_cnt++;
11841 			} else
11842 				ipf->ipf_hole_cnt = 2;
11843 			continue;
11844 		} else if (ipf->ipf_last_frag_seen && !more &&
11845 		    !pkt_boundary_checked) {
11846 			/*
11847 			 * We check datagram boundary only if this fragment
11848 			 * claims to be the last fragment and we have seen a
11849 			 * last fragment in the past too. We do this only
11850 			 * once for a given fragment.
11851 			 *
11852 			 * start cannot be 0 here as fragments with start=0
11853 			 * and MF=0 gets handled as a complete packet. These
11854 			 * fragments should not reach here.
11855 			 */
11856 
11857 			if (start + msgdsize(mp) !=
11858 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11859 				/*
11860 				 * We have two fragments both of which claim
11861 				 * to be the last fragment but gives conflicting
11862 				 * information about the whole datagram size.
11863 				 * Something fishy is going on. Drop the
11864 				 * fragment and free up the reassembly list.
11865 				 */
11866 				return (IP_REASS_FAILED);
11867 			}
11868 
11869 			/*
11870 			 * We shouldn't come to this code block again for this
11871 			 * particular fragment.
11872 			 */
11873 			pkt_boundary_checked = B_TRUE;
11874 		}
11875 
11876 		/* New stuff at or beyond tail? */
11877 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11878 		if (start >= offset) {
11879 			if (ipf->ipf_last_frag_seen) {
11880 				/* current fragment is beyond last fragment */
11881 				return (IP_REASS_FAILED);
11882 			}
11883 			/* Link it on end. */
11884 			ipf->ipf_tail_mp->b_cont = mp;
11885 			ipf->ipf_tail_mp = mp;
11886 			if (more) {
11887 				if (start != offset)
11888 					ipf->ipf_hole_cnt++;
11889 			} else if (start == offset && next_mp == NULL)
11890 					ipf->ipf_hole_cnt--;
11891 			continue;
11892 		}
11893 		mp1 = ipf->ipf_mp->b_cont;
11894 		offset = IP_REASS_START(mp1);
11895 		/* New stuff at the front? */
11896 		if (start < offset) {
11897 			if (start == 0) {
11898 				if (end >= offset) {
11899 					/* Nailed the hole at the begining. */
11900 					ipf->ipf_hole_cnt--;
11901 				}
11902 			} else if (end < offset) {
11903 				/*
11904 				 * A hole, stuff, and a hole where there used
11905 				 * to be just a hole.
11906 				 */
11907 				ipf->ipf_hole_cnt++;
11908 			}
11909 			mp->b_cont = mp1;
11910 			/* Check for overlap. */
11911 			while (end > offset) {
11912 				if (end < IP_REASS_END(mp1)) {
11913 					mp->b_wptr -= end - offset;
11914 					IP_REASS_SET_END(mp, offset);
11915 					BUMP_MIB(ill->ill_ip_mib,
11916 					    ipIfStatsReasmPartDups);
11917 					break;
11918 				}
11919 				/* Did we cover another hole? */
11920 				if ((mp1->b_cont &&
11921 				    IP_REASS_END(mp1) !=
11922 				    IP_REASS_START(mp1->b_cont) &&
11923 				    end >= IP_REASS_START(mp1->b_cont)) ||
11924 				    (!ipf->ipf_last_frag_seen && !more)) {
11925 					ipf->ipf_hole_cnt--;
11926 				}
11927 				/* Clip out mp1. */
11928 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11929 					/*
11930 					 * After clipping out mp1, this guy
11931 					 * is now hanging off the end.
11932 					 */
11933 					ipf->ipf_tail_mp = mp;
11934 				}
11935 				IP_REASS_SET_START(mp1, 0);
11936 				IP_REASS_SET_END(mp1, 0);
11937 				/* Subtract byte count */
11938 				ipf->ipf_count -= mp1->b_datap->db_lim -
11939 				    mp1->b_datap->db_base;
11940 				freeb(mp1);
11941 				BUMP_MIB(ill->ill_ip_mib,
11942 				    ipIfStatsReasmPartDups);
11943 				mp1 = mp->b_cont;
11944 				if (!mp1)
11945 					break;
11946 				offset = IP_REASS_START(mp1);
11947 			}
11948 			ipf->ipf_mp->b_cont = mp;
11949 			continue;
11950 		}
11951 		/*
11952 		 * The new piece starts somewhere between the start of the head
11953 		 * and before the end of the tail.
11954 		 */
11955 		for (; mp1; mp1 = mp1->b_cont) {
11956 			offset = IP_REASS_END(mp1);
11957 			if (start < offset) {
11958 				if (end <= offset) {
11959 					/* Nothing new. */
11960 					IP_REASS_SET_START(mp, 0);
11961 					IP_REASS_SET_END(mp, 0);
11962 					/* Subtract byte count */
11963 					ipf->ipf_count -= mp->b_datap->db_lim -
11964 					    mp->b_datap->db_base;
11965 					if (incr_dups) {
11966 						ipf->ipf_num_dups++;
11967 						incr_dups = B_FALSE;
11968 					}
11969 					freeb(mp);
11970 					BUMP_MIB(ill->ill_ip_mib,
11971 					    ipIfStatsReasmDuplicates);
11972 					break;
11973 				}
11974 				/*
11975 				 * Trim redundant stuff off beginning of new
11976 				 * piece.
11977 				 */
11978 				IP_REASS_SET_START(mp, offset);
11979 				mp->b_rptr += offset - start;
11980 				BUMP_MIB(ill->ill_ip_mib,
11981 				    ipIfStatsReasmPartDups);
11982 				start = offset;
11983 				if (!mp1->b_cont) {
11984 					/*
11985 					 * After trimming, this guy is now
11986 					 * hanging off the end.
11987 					 */
11988 					mp1->b_cont = mp;
11989 					ipf->ipf_tail_mp = mp;
11990 					if (!more) {
11991 						ipf->ipf_hole_cnt--;
11992 					}
11993 					break;
11994 				}
11995 			}
11996 			if (start >= IP_REASS_START(mp1->b_cont))
11997 				continue;
11998 			/* Fill a hole */
11999 			if (start > offset)
12000 				ipf->ipf_hole_cnt++;
12001 			mp->b_cont = mp1->b_cont;
12002 			mp1->b_cont = mp;
12003 			mp1 = mp->b_cont;
12004 			offset = IP_REASS_START(mp1);
12005 			if (end >= offset) {
12006 				ipf->ipf_hole_cnt--;
12007 				/* Check for overlap. */
12008 				while (end > offset) {
12009 					if (end < IP_REASS_END(mp1)) {
12010 						mp->b_wptr -= end - offset;
12011 						IP_REASS_SET_END(mp, offset);
12012 						/*
12013 						 * TODO we might bump
12014 						 * this up twice if there is
12015 						 * overlap at both ends.
12016 						 */
12017 						BUMP_MIB(ill->ill_ip_mib,
12018 						    ipIfStatsReasmPartDups);
12019 						break;
12020 					}
12021 					/* Did we cover another hole? */
12022 					if ((mp1->b_cont &&
12023 					    IP_REASS_END(mp1)
12024 					    != IP_REASS_START(mp1->b_cont) &&
12025 					    end >=
12026 					    IP_REASS_START(mp1->b_cont)) ||
12027 					    (!ipf->ipf_last_frag_seen &&
12028 					    !more)) {
12029 						ipf->ipf_hole_cnt--;
12030 					}
12031 					/* Clip out mp1. */
12032 					if ((mp->b_cont = mp1->b_cont) ==
12033 					    NULL) {
12034 						/*
12035 						 * After clipping out mp1,
12036 						 * this guy is now hanging
12037 						 * off the end.
12038 						 */
12039 						ipf->ipf_tail_mp = mp;
12040 					}
12041 					IP_REASS_SET_START(mp1, 0);
12042 					IP_REASS_SET_END(mp1, 0);
12043 					/* Subtract byte count */
12044 					ipf->ipf_count -=
12045 					    mp1->b_datap->db_lim -
12046 					    mp1->b_datap->db_base;
12047 					freeb(mp1);
12048 					BUMP_MIB(ill->ill_ip_mib,
12049 					    ipIfStatsReasmPartDups);
12050 					mp1 = mp->b_cont;
12051 					if (!mp1)
12052 						break;
12053 					offset = IP_REASS_START(mp1);
12054 				}
12055 			}
12056 			break;
12057 		}
12058 	} while (start = end, mp = next_mp);
12059 
12060 	/* Fragment just processed could be the last one. Remember this fact */
12061 	if (!more)
12062 		ipf->ipf_last_frag_seen = B_TRUE;
12063 
12064 	/* Still got holes? */
12065 	if (ipf->ipf_hole_cnt)
12066 		return (IP_REASS_PARTIAL);
12067 	/* Clean up overloaded fields to avoid upstream disasters. */
12068 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12069 		IP_REASS_SET_START(mp1, 0);
12070 		IP_REASS_SET_END(mp1, 0);
12071 	}
12072 	return (IP_REASS_COMPLETE);
12073 }
12074 
12075 /*
12076  * ipsec processing for the fast path, used for input UDP Packets
12077  * Returns true if ready for passup to UDP.
12078  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12079  * was an ESP-in-UDP packet, etc.).
12080  */
12081 static boolean_t
12082 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12083     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12084 {
12085 	uint32_t	ill_index;
12086 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12087 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12088 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12089 	udp_t		*udp = connp->conn_udp;
12090 
12091 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12092 	/* The ill_index of the incoming ILL */
12093 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12094 
12095 	/* pass packet up to the transport */
12096 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12097 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12098 		    NULL, mctl_present);
12099 		if (*first_mpp == NULL) {
12100 			return (B_FALSE);
12101 		}
12102 	}
12103 
12104 	/* Initiate IPPF processing for fastpath UDP */
12105 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12106 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12107 		if (*mpp == NULL) {
12108 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12109 			    "deferred/dropped during IPPF processing\n"));
12110 			return (B_FALSE);
12111 		}
12112 	}
12113 	/*
12114 	 * Remove 0-spi if it's 0, or move everything behind
12115 	 * the UDP header over it and forward to ESP via
12116 	 * ip_proto_input().
12117 	 */
12118 	if (udp->udp_nat_t_endpoint) {
12119 		if (mctl_present) {
12120 			/* mctl_present *shouldn't* happen. */
12121 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12122 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12123 			    &ipss->ipsec_dropper);
12124 			*first_mpp = NULL;
12125 			return (B_FALSE);
12126 		}
12127 
12128 		/* "ill" is "recv_ill" in actuality. */
12129 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12130 			return (B_FALSE);
12131 
12132 		/* Else continue like a normal UDP packet. */
12133 	}
12134 
12135 	/*
12136 	 * We make the checks as below since we are in the fast path
12137 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12138 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12139 	 */
12140 	if (connp->conn_recvif || connp->conn_recvslla ||
12141 	    connp->conn_ip_recvpktinfo) {
12142 		if (connp->conn_recvif) {
12143 			in_flags = IPF_RECVIF;
12144 		}
12145 		/*
12146 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12147 		 * so the flag passed to ip_add_info is based on IP version
12148 		 * of connp.
12149 		 */
12150 		if (connp->conn_ip_recvpktinfo) {
12151 			if (connp->conn_af_isv6) {
12152 				/*
12153 				 * V6 only needs index
12154 				 */
12155 				in_flags |= IPF_RECVIF;
12156 			} else {
12157 				/*
12158 				 * V4 needs index + matching address.
12159 				 */
12160 				in_flags |= IPF_RECVADDR;
12161 			}
12162 		}
12163 		if (connp->conn_recvslla) {
12164 			in_flags |= IPF_RECVSLLA;
12165 		}
12166 		/*
12167 		 * since in_flags are being set ill will be
12168 		 * referenced in ip_add_info, so it better not
12169 		 * be NULL.
12170 		 */
12171 		/*
12172 		 * the actual data will be contained in b_cont
12173 		 * upon successful return of the following call.
12174 		 * If the call fails then the original mblk is
12175 		 * returned.
12176 		 */
12177 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12178 		    ipst);
12179 	}
12180 
12181 	return (B_TRUE);
12182 }
12183 
12184 /*
12185  * Fragmentation reassembly.  Each ILL has a hash table for
12186  * queuing packets undergoing reassembly for all IPIFs
12187  * associated with the ILL.  The hash is based on the packet
12188  * IP ident field.  The ILL frag hash table was allocated
12189  * as a timer block at the time the ILL was created.  Whenever
12190  * there is anything on the reassembly queue, the timer will
12191  * be running.  Returns B_TRUE if successful else B_FALSE;
12192  * frees mp on failure.
12193  */
12194 static boolean_t
12195 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12196     uint32_t *cksum_val, uint16_t *cksum_flags)
12197 {
12198 	uint32_t	frag_offset_flags;
12199 	ill_t		*ill = (ill_t *)q->q_ptr;
12200 	mblk_t		*mp = *mpp;
12201 	mblk_t		*t_mp;
12202 	ipaddr_t	dst;
12203 	uint8_t		proto = ipha->ipha_protocol;
12204 	uint32_t	sum_val;
12205 	uint16_t	sum_flags;
12206 	ipf_t		*ipf;
12207 	ipf_t		**ipfp;
12208 	ipfb_t		*ipfb;
12209 	uint16_t	ident;
12210 	uint32_t	offset;
12211 	ipaddr_t	src;
12212 	uint_t		hdr_length;
12213 	uint32_t	end;
12214 	mblk_t		*mp1;
12215 	mblk_t		*tail_mp;
12216 	size_t		count;
12217 	size_t		msg_len;
12218 	uint8_t		ecn_info = 0;
12219 	uint32_t	packet_size;
12220 	boolean_t	pruned = B_FALSE;
12221 	ip_stack_t *ipst = ill->ill_ipst;
12222 
12223 	if (cksum_val != NULL)
12224 		*cksum_val = 0;
12225 	if (cksum_flags != NULL)
12226 		*cksum_flags = 0;
12227 
12228 	/*
12229 	 * Drop the fragmented as early as possible, if
12230 	 * we don't have resource(s) to re-assemble.
12231 	 */
12232 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12233 		freemsg(mp);
12234 		return (B_FALSE);
12235 	}
12236 
12237 	/* Check for fragmentation offset; return if there's none */
12238 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12239 	    (IPH_MF | IPH_OFFSET)) == 0)
12240 		return (B_TRUE);
12241 
12242 	/*
12243 	 * We utilize hardware computed checksum info only for UDP since
12244 	 * IP fragmentation is a normal occurence for the protocol.  In
12245 	 * addition, checksum offload support for IP fragments carrying
12246 	 * UDP payload is commonly implemented across network adapters.
12247 	 */
12248 	ASSERT(ill != NULL);
12249 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12250 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12251 		mblk_t *mp1 = mp->b_cont;
12252 		int32_t len;
12253 
12254 		/* Record checksum information from the packet */
12255 		sum_val = (uint32_t)DB_CKSUM16(mp);
12256 		sum_flags = DB_CKSUMFLAGS(mp);
12257 
12258 		/* IP payload offset from beginning of mblk */
12259 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12260 
12261 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12262 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12263 		    offset >= DB_CKSUMSTART(mp) &&
12264 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12265 			uint32_t adj;
12266 			/*
12267 			 * Partial checksum has been calculated by hardware
12268 			 * and attached to the packet; in addition, any
12269 			 * prepended extraneous data is even byte aligned.
12270 			 * If any such data exists, we adjust the checksum;
12271 			 * this would also handle any postpended data.
12272 			 */
12273 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12274 			    mp, mp1, len, adj);
12275 
12276 			/* One's complement subtract extraneous checksum */
12277 			if (adj >= sum_val)
12278 				sum_val = ~(adj - sum_val) & 0xFFFF;
12279 			else
12280 				sum_val -= adj;
12281 		}
12282 	} else {
12283 		sum_val = 0;
12284 		sum_flags = 0;
12285 	}
12286 
12287 	/* Clear hardware checksumming flag */
12288 	DB_CKSUMFLAGS(mp) = 0;
12289 
12290 	ident = ipha->ipha_ident;
12291 	offset = (frag_offset_flags << 3) & 0xFFFF;
12292 	src = ipha->ipha_src;
12293 	dst = ipha->ipha_dst;
12294 	hdr_length = IPH_HDR_LENGTH(ipha);
12295 	end = ntohs(ipha->ipha_length) - hdr_length;
12296 
12297 	/* If end == 0 then we have a packet with no data, so just free it */
12298 	if (end == 0) {
12299 		freemsg(mp);
12300 		return (B_FALSE);
12301 	}
12302 
12303 	/* Record the ECN field info. */
12304 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12305 	if (offset != 0) {
12306 		/*
12307 		 * If this isn't the first piece, strip the header, and
12308 		 * add the offset to the end value.
12309 		 */
12310 		mp->b_rptr += hdr_length;
12311 		end += offset;
12312 	}
12313 
12314 	msg_len = MBLKSIZE(mp);
12315 	tail_mp = mp;
12316 	while (tail_mp->b_cont != NULL) {
12317 		tail_mp = tail_mp->b_cont;
12318 		msg_len += MBLKSIZE(tail_mp);
12319 	}
12320 
12321 	/* If the reassembly list for this ILL will get too big, prune it */
12322 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12323 	    ipst->ips_ip_reass_queue_bytes) {
12324 		ill_frag_prune(ill,
12325 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12326 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12327 		pruned = B_TRUE;
12328 	}
12329 
12330 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12331 	mutex_enter(&ipfb->ipfb_lock);
12332 
12333 	ipfp = &ipfb->ipfb_ipf;
12334 	/* Try to find an existing fragment queue for this packet. */
12335 	for (;;) {
12336 		ipf = ipfp[0];
12337 		if (ipf != NULL) {
12338 			/*
12339 			 * It has to match on ident and src/dst address.
12340 			 */
12341 			if (ipf->ipf_ident == ident &&
12342 			    ipf->ipf_src == src &&
12343 			    ipf->ipf_dst == dst &&
12344 			    ipf->ipf_protocol == proto) {
12345 				/*
12346 				 * If we have received too many
12347 				 * duplicate fragments for this packet
12348 				 * free it.
12349 				 */
12350 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12351 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12352 					freemsg(mp);
12353 					mutex_exit(&ipfb->ipfb_lock);
12354 					return (B_FALSE);
12355 				}
12356 				/* Found it. */
12357 				break;
12358 			}
12359 			ipfp = &ipf->ipf_hash_next;
12360 			continue;
12361 		}
12362 
12363 		/*
12364 		 * If we pruned the list, do we want to store this new
12365 		 * fragment?. We apply an optimization here based on the
12366 		 * fact that most fragments will be received in order.
12367 		 * So if the offset of this incoming fragment is zero,
12368 		 * it is the first fragment of a new packet. We will
12369 		 * keep it.  Otherwise drop the fragment, as we have
12370 		 * probably pruned the packet already (since the
12371 		 * packet cannot be found).
12372 		 */
12373 		if (pruned && offset != 0) {
12374 			mutex_exit(&ipfb->ipfb_lock);
12375 			freemsg(mp);
12376 			return (B_FALSE);
12377 		}
12378 
12379 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12380 			/*
12381 			 * Too many fragmented packets in this hash
12382 			 * bucket. Free the oldest.
12383 			 */
12384 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12385 		}
12386 
12387 		/* New guy.  Allocate a frag message. */
12388 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12389 		if (mp1 == NULL) {
12390 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12391 			freemsg(mp);
12392 reass_done:
12393 			mutex_exit(&ipfb->ipfb_lock);
12394 			return (B_FALSE);
12395 		}
12396 
12397 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12398 		mp1->b_cont = mp;
12399 
12400 		/* Initialize the fragment header. */
12401 		ipf = (ipf_t *)mp1->b_rptr;
12402 		ipf->ipf_mp = mp1;
12403 		ipf->ipf_ptphn = ipfp;
12404 		ipfp[0] = ipf;
12405 		ipf->ipf_hash_next = NULL;
12406 		ipf->ipf_ident = ident;
12407 		ipf->ipf_protocol = proto;
12408 		ipf->ipf_src = src;
12409 		ipf->ipf_dst = dst;
12410 		ipf->ipf_nf_hdr_len = 0;
12411 		/* Record reassembly start time. */
12412 		ipf->ipf_timestamp = gethrestime_sec();
12413 		/* Record ipf generation and account for frag header */
12414 		ipf->ipf_gen = ill->ill_ipf_gen++;
12415 		ipf->ipf_count = MBLKSIZE(mp1);
12416 		ipf->ipf_last_frag_seen = B_FALSE;
12417 		ipf->ipf_ecn = ecn_info;
12418 		ipf->ipf_num_dups = 0;
12419 		ipfb->ipfb_frag_pkts++;
12420 		ipf->ipf_checksum = 0;
12421 		ipf->ipf_checksum_flags = 0;
12422 
12423 		/* Store checksum value in fragment header */
12424 		if (sum_flags != 0) {
12425 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12426 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12427 			ipf->ipf_checksum = sum_val;
12428 			ipf->ipf_checksum_flags = sum_flags;
12429 		}
12430 
12431 		/*
12432 		 * We handle reassembly two ways.  In the easy case,
12433 		 * where all the fragments show up in order, we do
12434 		 * minimal bookkeeping, and just clip new pieces on
12435 		 * the end.  If we ever see a hole, then we go off
12436 		 * to ip_reassemble which has to mark the pieces and
12437 		 * keep track of the number of holes, etc.  Obviously,
12438 		 * the point of having both mechanisms is so we can
12439 		 * handle the easy case as efficiently as possible.
12440 		 */
12441 		if (offset == 0) {
12442 			/* Easy case, in-order reassembly so far. */
12443 			ipf->ipf_count += msg_len;
12444 			ipf->ipf_tail_mp = tail_mp;
12445 			/*
12446 			 * Keep track of next expected offset in
12447 			 * ipf_end.
12448 			 */
12449 			ipf->ipf_end = end;
12450 			ipf->ipf_nf_hdr_len = hdr_length;
12451 		} else {
12452 			/* Hard case, hole at the beginning. */
12453 			ipf->ipf_tail_mp = NULL;
12454 			/*
12455 			 * ipf_end == 0 means that we have given up
12456 			 * on easy reassembly.
12457 			 */
12458 			ipf->ipf_end = 0;
12459 
12460 			/* Forget checksum offload from now on */
12461 			ipf->ipf_checksum_flags = 0;
12462 
12463 			/*
12464 			 * ipf_hole_cnt is set by ip_reassemble.
12465 			 * ipf_count is updated by ip_reassemble.
12466 			 * No need to check for return value here
12467 			 * as we don't expect reassembly to complete
12468 			 * or fail for the first fragment itself.
12469 			 */
12470 			(void) ip_reassemble(mp, ipf,
12471 			    (frag_offset_flags & IPH_OFFSET) << 3,
12472 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12473 		}
12474 		/* Update per ipfb and ill byte counts */
12475 		ipfb->ipfb_count += ipf->ipf_count;
12476 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12477 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12478 		/* If the frag timer wasn't already going, start it. */
12479 		mutex_enter(&ill->ill_lock);
12480 		ill_frag_timer_start(ill);
12481 		mutex_exit(&ill->ill_lock);
12482 		goto reass_done;
12483 	}
12484 
12485 	/*
12486 	 * If the packet's flag has changed (it could be coming up
12487 	 * from an interface different than the previous, therefore
12488 	 * possibly different checksum capability), then forget about
12489 	 * any stored checksum states.  Otherwise add the value to
12490 	 * the existing one stored in the fragment header.
12491 	 */
12492 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12493 		sum_val += ipf->ipf_checksum;
12494 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12495 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12496 		ipf->ipf_checksum = sum_val;
12497 	} else if (ipf->ipf_checksum_flags != 0) {
12498 		/* Forget checksum offload from now on */
12499 		ipf->ipf_checksum_flags = 0;
12500 	}
12501 
12502 	/*
12503 	 * We have a new piece of a datagram which is already being
12504 	 * reassembled.  Update the ECN info if all IP fragments
12505 	 * are ECN capable.  If there is one which is not, clear
12506 	 * all the info.  If there is at least one which has CE
12507 	 * code point, IP needs to report that up to transport.
12508 	 */
12509 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12510 		if (ecn_info == IPH_ECN_CE)
12511 			ipf->ipf_ecn = IPH_ECN_CE;
12512 	} else {
12513 		ipf->ipf_ecn = IPH_ECN_NECT;
12514 	}
12515 	if (offset && ipf->ipf_end == offset) {
12516 		/* The new fragment fits at the end */
12517 		ipf->ipf_tail_mp->b_cont = mp;
12518 		/* Update the byte count */
12519 		ipf->ipf_count += msg_len;
12520 		/* Update per ipfb and ill byte counts */
12521 		ipfb->ipfb_count += msg_len;
12522 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12523 		atomic_add_32(&ill->ill_frag_count, msg_len);
12524 		if (frag_offset_flags & IPH_MF) {
12525 			/* More to come. */
12526 			ipf->ipf_end = end;
12527 			ipf->ipf_tail_mp = tail_mp;
12528 			goto reass_done;
12529 		}
12530 	} else {
12531 		/* Go do the hard cases. */
12532 		int ret;
12533 
12534 		if (offset == 0)
12535 			ipf->ipf_nf_hdr_len = hdr_length;
12536 
12537 		/* Save current byte count */
12538 		count = ipf->ipf_count;
12539 		ret = ip_reassemble(mp, ipf,
12540 		    (frag_offset_flags & IPH_OFFSET) << 3,
12541 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12542 		/* Count of bytes added and subtracted (freeb()ed) */
12543 		count = ipf->ipf_count - count;
12544 		if (count) {
12545 			/* Update per ipfb and ill byte counts */
12546 			ipfb->ipfb_count += count;
12547 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12548 			atomic_add_32(&ill->ill_frag_count, count);
12549 		}
12550 		if (ret == IP_REASS_PARTIAL) {
12551 			goto reass_done;
12552 		} else if (ret == IP_REASS_FAILED) {
12553 			/* Reassembly failed. Free up all resources */
12554 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12555 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12556 				IP_REASS_SET_START(t_mp, 0);
12557 				IP_REASS_SET_END(t_mp, 0);
12558 			}
12559 			freemsg(mp);
12560 			goto reass_done;
12561 		}
12562 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12563 	}
12564 	/*
12565 	 * We have completed reassembly.  Unhook the frag header from
12566 	 * the reassembly list.
12567 	 *
12568 	 * Before we free the frag header, record the ECN info
12569 	 * to report back to the transport.
12570 	 */
12571 	ecn_info = ipf->ipf_ecn;
12572 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12573 	ipfp = ipf->ipf_ptphn;
12574 
12575 	/* We need to supply these to caller */
12576 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12577 		sum_val = ipf->ipf_checksum;
12578 	else
12579 		sum_val = 0;
12580 
12581 	mp1 = ipf->ipf_mp;
12582 	count = ipf->ipf_count;
12583 	ipf = ipf->ipf_hash_next;
12584 	if (ipf != NULL)
12585 		ipf->ipf_ptphn = ipfp;
12586 	ipfp[0] = ipf;
12587 	atomic_add_32(&ill->ill_frag_count, -count);
12588 	ASSERT(ipfb->ipfb_count >= count);
12589 	ipfb->ipfb_count -= count;
12590 	ipfb->ipfb_frag_pkts--;
12591 	mutex_exit(&ipfb->ipfb_lock);
12592 	/* Ditch the frag header. */
12593 	mp = mp1->b_cont;
12594 
12595 	freeb(mp1);
12596 
12597 	/* Restore original IP length in header. */
12598 	packet_size = (uint32_t)msgdsize(mp);
12599 	if (packet_size > IP_MAXPACKET) {
12600 		freemsg(mp);
12601 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12602 		return (B_FALSE);
12603 	}
12604 
12605 	if (DB_REF(mp) > 1) {
12606 		mblk_t *mp2 = copymsg(mp);
12607 
12608 		freemsg(mp);
12609 		if (mp2 == NULL) {
12610 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12611 			return (B_FALSE);
12612 		}
12613 		mp = mp2;
12614 	}
12615 	ipha = (ipha_t *)mp->b_rptr;
12616 
12617 	ipha->ipha_length = htons((uint16_t)packet_size);
12618 	/* We're now complete, zip the frag state */
12619 	ipha->ipha_fragment_offset_and_flags = 0;
12620 	/* Record the ECN info. */
12621 	ipha->ipha_type_of_service &= 0xFC;
12622 	ipha->ipha_type_of_service |= ecn_info;
12623 	*mpp = mp;
12624 
12625 	/* Reassembly is successful; return checksum information if needed */
12626 	if (cksum_val != NULL)
12627 		*cksum_val = sum_val;
12628 	if (cksum_flags != NULL)
12629 		*cksum_flags = sum_flags;
12630 
12631 	return (B_TRUE);
12632 }
12633 
12634 /*
12635  * Perform ip header check sum update local options.
12636  * return B_TRUE if all is well, else return B_FALSE and release
12637  * the mp. caller is responsible for decrementing ire ref cnt.
12638  */
12639 static boolean_t
12640 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12641     ip_stack_t *ipst)
12642 {
12643 	mblk_t		*first_mp;
12644 	boolean_t	mctl_present;
12645 	uint16_t	sum;
12646 
12647 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12648 	/*
12649 	 * Don't do the checksum if it has gone through AH/ESP
12650 	 * processing.
12651 	 */
12652 	if (!mctl_present) {
12653 		sum = ip_csum_hdr(ipha);
12654 		if (sum != 0) {
12655 			if (ill != NULL) {
12656 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12657 			} else {
12658 				BUMP_MIB(&ipst->ips_ip_mib,
12659 				    ipIfStatsInCksumErrs);
12660 			}
12661 			freemsg(first_mp);
12662 			return (B_FALSE);
12663 		}
12664 	}
12665 
12666 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12667 		if (mctl_present)
12668 			freeb(first_mp);
12669 		return (B_FALSE);
12670 	}
12671 
12672 	return (B_TRUE);
12673 }
12674 
12675 /*
12676  * All udp packet are delivered to the local host via this routine.
12677  */
12678 void
12679 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12680     ill_t *recv_ill)
12681 {
12682 	uint32_t	sum;
12683 	uint32_t	u1;
12684 	boolean_t	mctl_present;
12685 	conn_t		*connp;
12686 	mblk_t		*first_mp;
12687 	uint16_t	*up;
12688 	ill_t		*ill = (ill_t *)q->q_ptr;
12689 	uint16_t	reass_hck_flags = 0;
12690 	ip_stack_t	*ipst;
12691 
12692 	ASSERT(recv_ill != NULL);
12693 	ipst = recv_ill->ill_ipst;
12694 
12695 #define	rptr    ((uchar_t *)ipha)
12696 
12697 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12698 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12699 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12700 	ASSERT(ill != NULL);
12701 
12702 	/*
12703 	 * FAST PATH for udp packets
12704 	 */
12705 
12706 	/* u1 is # words of IP options */
12707 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12708 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12709 
12710 	/* IP options present */
12711 	if (u1 != 0)
12712 		goto ipoptions;
12713 
12714 	/* Check the IP header checksum.  */
12715 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12716 		/* Clear the IP header h/w cksum flag */
12717 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12718 	} else if (!mctl_present) {
12719 		/*
12720 		 * Don't verify header checksum if this packet is coming
12721 		 * back from AH/ESP as we already did it.
12722 		 */
12723 #define	uph	((uint16_t *)ipha)
12724 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12725 		    uph[6] + uph[7] + uph[8] + uph[9];
12726 #undef	uph
12727 		/* finish doing IP checksum */
12728 		sum = (sum & 0xFFFF) + (sum >> 16);
12729 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12730 		if (sum != 0 && sum != 0xFFFF) {
12731 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12732 			freemsg(first_mp);
12733 			return;
12734 		}
12735 	}
12736 
12737 	/*
12738 	 * Count for SNMP of inbound packets for ire.
12739 	 * if mctl is present this might be a secure packet and
12740 	 * has already been counted for in ip_proto_input().
12741 	 */
12742 	if (!mctl_present) {
12743 		UPDATE_IB_PKT_COUNT(ire);
12744 		ire->ire_last_used_time = lbolt;
12745 	}
12746 
12747 	/* packet part of fragmented IP packet? */
12748 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12749 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12750 		goto fragmented;
12751 	}
12752 
12753 	/* u1 = IP header length (20 bytes) */
12754 	u1 = IP_SIMPLE_HDR_LENGTH;
12755 
12756 	/* packet does not contain complete IP & UDP headers */
12757 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12758 		goto udppullup;
12759 
12760 	/* up points to UDP header */
12761 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12762 #define	iphs    ((uint16_t *)ipha)
12763 
12764 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12765 	if (up[3] != 0) {
12766 		mblk_t *mp1 = mp->b_cont;
12767 		boolean_t cksum_err;
12768 		uint16_t hck_flags = 0;
12769 
12770 		/* Pseudo-header checksum */
12771 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12772 		    iphs[9] + up[2];
12773 
12774 		/*
12775 		 * Revert to software checksum calculation if the interface
12776 		 * isn't capable of checksum offload or if IPsec is present.
12777 		 */
12778 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12779 			hck_flags = DB_CKSUMFLAGS(mp);
12780 
12781 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12782 			IP_STAT(ipst, ip_in_sw_cksum);
12783 
12784 		IP_CKSUM_RECV(hck_flags, u1,
12785 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12786 		    (int32_t)((uchar_t *)up - rptr),
12787 		    mp, mp1, cksum_err);
12788 
12789 		if (cksum_err) {
12790 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12791 			if (hck_flags & HCK_FULLCKSUM)
12792 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12793 			else if (hck_flags & HCK_PARTIALCKSUM)
12794 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12795 			else
12796 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12797 
12798 			freemsg(first_mp);
12799 			return;
12800 		}
12801 	}
12802 
12803 	/* Non-fragmented broadcast or multicast packet? */
12804 	if (ire->ire_type == IRE_BROADCAST)
12805 		goto udpslowpath;
12806 
12807 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12808 	    ire->ire_zoneid, ipst)) != NULL) {
12809 		ASSERT(connp->conn_upq != NULL);
12810 		IP_STAT(ipst, ip_udp_fast_path);
12811 
12812 		if (CONN_UDP_FLOWCTLD(connp)) {
12813 			freemsg(mp);
12814 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12815 		} else {
12816 			if (!mctl_present) {
12817 				BUMP_MIB(ill->ill_ip_mib,
12818 				    ipIfStatsHCInDelivers);
12819 			}
12820 			/*
12821 			 * mp and first_mp can change.
12822 			 */
12823 			if (ip_udp_check(q, connp, recv_ill,
12824 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12825 				/* Send it upstream */
12826 				(connp->conn_recv)(connp, mp, NULL);
12827 			}
12828 		}
12829 		/*
12830 		 * freeb() cannot deal with null mblk being passed
12831 		 * in and first_mp can be set to null in the call
12832 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12833 		 */
12834 		if (mctl_present && first_mp != NULL) {
12835 			freeb(first_mp);
12836 		}
12837 		CONN_DEC_REF(connp);
12838 		return;
12839 	}
12840 
12841 	/*
12842 	 * if we got here we know the packet is not fragmented and
12843 	 * has no options. The classifier could not find a conn_t and
12844 	 * most likely its an icmp packet so send it through slow path.
12845 	 */
12846 
12847 	goto udpslowpath;
12848 
12849 ipoptions:
12850 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12851 		goto slow_done;
12852 	}
12853 
12854 	UPDATE_IB_PKT_COUNT(ire);
12855 	ire->ire_last_used_time = lbolt;
12856 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12857 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12858 fragmented:
12859 		/*
12860 		 * "sum" and "reass_hck_flags" are non-zero if the
12861 		 * reassembled packet has a valid hardware computed
12862 		 * checksum information associated with it.
12863 		 */
12864 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12865 			goto slow_done;
12866 		/*
12867 		 * Make sure that first_mp points back to mp as
12868 		 * the mp we came in with could have changed in
12869 		 * ip_rput_fragment().
12870 		 */
12871 		ASSERT(!mctl_present);
12872 		ipha = (ipha_t *)mp->b_rptr;
12873 		first_mp = mp;
12874 	}
12875 
12876 	/* Now we have a complete datagram, destined for this machine. */
12877 	u1 = IPH_HDR_LENGTH(ipha);
12878 	/* Pull up the UDP header, if necessary. */
12879 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12880 udppullup:
12881 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12882 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12883 			freemsg(first_mp);
12884 			goto slow_done;
12885 		}
12886 		ipha = (ipha_t *)mp->b_rptr;
12887 	}
12888 
12889 	/*
12890 	 * Validate the checksum for the reassembled packet; for the
12891 	 * pullup case we calculate the payload checksum in software.
12892 	 */
12893 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12894 	if (up[3] != 0) {
12895 		boolean_t cksum_err;
12896 
12897 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12898 			IP_STAT(ipst, ip_in_sw_cksum);
12899 
12900 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12901 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12902 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12903 		    iphs[9] + up[2], sum, cksum_err);
12904 
12905 		if (cksum_err) {
12906 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12907 
12908 			if (reass_hck_flags & HCK_FULLCKSUM)
12909 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12910 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12911 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12912 			else
12913 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12914 
12915 			freemsg(first_mp);
12916 			goto slow_done;
12917 		}
12918 	}
12919 udpslowpath:
12920 
12921 	/* Clear hardware checksum flag to be safe */
12922 	DB_CKSUMFLAGS(mp) = 0;
12923 
12924 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12925 	    (ire->ire_type == IRE_BROADCAST),
12926 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12927 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12928 
12929 slow_done:
12930 	IP_STAT(ipst, ip_udp_slow_path);
12931 	return;
12932 
12933 #undef  iphs
12934 #undef  rptr
12935 }
12936 
12937 /* ARGSUSED */
12938 static mblk_t *
12939 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12940     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12941     ill_rx_ring_t *ill_ring)
12942 {
12943 	conn_t		*connp;
12944 	uint32_t	sum;
12945 	uint32_t	u1;
12946 	uint16_t	*up;
12947 	int		offset;
12948 	ssize_t		len;
12949 	mblk_t		*mp1;
12950 	boolean_t	syn_present = B_FALSE;
12951 	tcph_t		*tcph;
12952 	uint_t		tcph_flags;
12953 	uint_t		ip_hdr_len;
12954 	ill_t		*ill = (ill_t *)q->q_ptr;
12955 	zoneid_t	zoneid = ire->ire_zoneid;
12956 	boolean_t	cksum_err;
12957 	uint16_t	hck_flags = 0;
12958 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12959 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12960 
12961 #define	rptr	((uchar_t *)ipha)
12962 
12963 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12964 	ASSERT(ill != NULL);
12965 
12966 	/*
12967 	 * FAST PATH for tcp packets
12968 	 */
12969 
12970 	/* u1 is # words of IP options */
12971 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12972 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12973 
12974 	/* IP options present */
12975 	if (u1) {
12976 		goto ipoptions;
12977 	} else if (!mctl_present) {
12978 		/* Check the IP header checksum.  */
12979 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12980 			/* Clear the IP header h/w cksum flag */
12981 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12982 		} else if (!mctl_present) {
12983 			/*
12984 			 * Don't verify header checksum if this packet
12985 			 * is coming back from AH/ESP as we already did it.
12986 			 */
12987 #define	uph	((uint16_t *)ipha)
12988 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12989 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12990 #undef	uph
12991 			/* finish doing IP checksum */
12992 			sum = (sum & 0xFFFF) + (sum >> 16);
12993 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12994 			if (sum != 0 && sum != 0xFFFF) {
12995 				BUMP_MIB(ill->ill_ip_mib,
12996 				    ipIfStatsInCksumErrs);
12997 				goto error;
12998 			}
12999 		}
13000 	}
13001 
13002 	if (!mctl_present) {
13003 		UPDATE_IB_PKT_COUNT(ire);
13004 		ire->ire_last_used_time = lbolt;
13005 	}
13006 
13007 	/* packet part of fragmented IP packet? */
13008 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13009 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13010 		goto fragmented;
13011 	}
13012 
13013 	/* u1 = IP header length (20 bytes) */
13014 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13015 
13016 	/* does packet contain IP+TCP headers? */
13017 	len = mp->b_wptr - rptr;
13018 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13019 		IP_STAT(ipst, ip_tcppullup);
13020 		goto tcppullup;
13021 	}
13022 
13023 	/* TCP options present? */
13024 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13025 
13026 	/*
13027 	 * If options need to be pulled up, then goto tcpoptions.
13028 	 * otherwise we are still in the fast path
13029 	 */
13030 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13031 		IP_STAT(ipst, ip_tcpoptions);
13032 		goto tcpoptions;
13033 	}
13034 
13035 	/* multiple mblks of tcp data? */
13036 	if ((mp1 = mp->b_cont) != NULL) {
13037 		/* more then two? */
13038 		if (mp1->b_cont != NULL) {
13039 			IP_STAT(ipst, ip_multipkttcp);
13040 			goto multipkttcp;
13041 		}
13042 		len += mp1->b_wptr - mp1->b_rptr;
13043 	}
13044 
13045 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13046 
13047 	/* part of pseudo checksum */
13048 
13049 	/* TCP datagram length */
13050 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13051 
13052 #define	iphs    ((uint16_t *)ipha)
13053 
13054 #ifdef	_BIG_ENDIAN
13055 	u1 += IPPROTO_TCP;
13056 #else
13057 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13058 #endif
13059 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13060 
13061 	/*
13062 	 * Revert to software checksum calculation if the interface
13063 	 * isn't capable of checksum offload or if IPsec is present.
13064 	 */
13065 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13066 		hck_flags = DB_CKSUMFLAGS(mp);
13067 
13068 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13069 		IP_STAT(ipst, ip_in_sw_cksum);
13070 
13071 	IP_CKSUM_RECV(hck_flags, u1,
13072 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13073 	    (int32_t)((uchar_t *)up - rptr),
13074 	    mp, mp1, cksum_err);
13075 
13076 	if (cksum_err) {
13077 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13078 
13079 		if (hck_flags & HCK_FULLCKSUM)
13080 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13081 		else if (hck_flags & HCK_PARTIALCKSUM)
13082 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13083 		else
13084 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13085 
13086 		goto error;
13087 	}
13088 
13089 try_again:
13090 
13091 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13092 	    zoneid, ipst)) == NULL) {
13093 		/* Send the TH_RST */
13094 		goto no_conn;
13095 	}
13096 
13097 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13098 	tcph_flags = tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG);
13099 
13100 	/*
13101 	 * TCP FAST PATH for AF_INET socket.
13102 	 *
13103 	 * TCP fast path to avoid extra work. An AF_INET socket type
13104 	 * does not have facility to receive extra information via
13105 	 * ip_process or ip_add_info. Also, when the connection was
13106 	 * established, we made a check if this connection is impacted
13107 	 * by any global IPsec policy or per connection policy (a
13108 	 * policy that comes in effect later will not apply to this
13109 	 * connection). Since all this can be determined at the
13110 	 * connection establishment time, a quick check of flags
13111 	 * can avoid extra work.
13112 	 */
13113 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13114 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13115 		ASSERT(first_mp == mp);
13116 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13117 		if (tcph_flags != (TH_SYN | TH_ACK)) {
13118 			SET_SQUEUE(mp, tcp_rput_data, connp);
13119 			return (mp);
13120 		}
13121 		mp->b_datap->db_struioflag |= STRUIO_CONNECT;
13122 		DB_CKSUMSTART(mp) = (intptr_t)ip_squeue_get(ill_ring);
13123 		SET_SQUEUE(mp, tcp_input, connp);
13124 		return (mp);
13125 	}
13126 
13127 	if (tcph_flags == TH_SYN) {
13128 		if (IPCL_IS_TCP(connp)) {
13129 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13130 			DB_CKSUMSTART(mp) =
13131 			    (intptr_t)ip_squeue_get(ill_ring);
13132 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13133 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13134 				BUMP_MIB(ill->ill_ip_mib,
13135 				    ipIfStatsHCInDelivers);
13136 				SET_SQUEUE(mp, connp->conn_recv, connp);
13137 				return (mp);
13138 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13139 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13140 				BUMP_MIB(ill->ill_ip_mib,
13141 				    ipIfStatsHCInDelivers);
13142 				ip_squeue_enter_unbound++;
13143 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13144 				    connp);
13145 				return (mp);
13146 			}
13147 			syn_present = B_TRUE;
13148 		}
13149 	}
13150 
13151 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13152 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13153 
13154 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13155 		/* No need to send this packet to TCP */
13156 		if ((flags & TH_RST) || (flags & TH_URG)) {
13157 			CONN_DEC_REF(connp);
13158 			freemsg(first_mp);
13159 			return (NULL);
13160 		}
13161 		if (flags & TH_ACK) {
13162 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13163 			    ipst->ips_netstack->netstack_tcp, connp);
13164 			CONN_DEC_REF(connp);
13165 			return (NULL);
13166 		}
13167 
13168 		CONN_DEC_REF(connp);
13169 		freemsg(first_mp);
13170 		return (NULL);
13171 	}
13172 
13173 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13174 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13175 		    ipha, NULL, mctl_present);
13176 		if (first_mp == NULL) {
13177 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13178 			CONN_DEC_REF(connp);
13179 			return (NULL);
13180 		}
13181 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13182 			ASSERT(syn_present);
13183 			if (mctl_present) {
13184 				ASSERT(first_mp != mp);
13185 				first_mp->b_datap->db_struioflag |=
13186 				    STRUIO_POLICY;
13187 			} else {
13188 				ASSERT(first_mp == mp);
13189 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13190 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13191 			}
13192 		} else {
13193 			/*
13194 			 * Discard first_mp early since we're dealing with a
13195 			 * fully-connected conn_t and tcp doesn't do policy in
13196 			 * this case.
13197 			 */
13198 			if (mctl_present) {
13199 				freeb(first_mp);
13200 				mctl_present = B_FALSE;
13201 			}
13202 			first_mp = mp;
13203 		}
13204 	}
13205 
13206 	/* Initiate IPPF processing for fastpath */
13207 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13208 		uint32_t	ill_index;
13209 
13210 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13211 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13212 		if (mp == NULL) {
13213 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13214 			    "deferred/dropped during IPPF processing\n"));
13215 			CONN_DEC_REF(connp);
13216 			if (mctl_present)
13217 				freeb(first_mp);
13218 			return (NULL);
13219 		} else if (mctl_present) {
13220 			/*
13221 			 * ip_process might return a new mp.
13222 			 */
13223 			ASSERT(first_mp != mp);
13224 			first_mp->b_cont = mp;
13225 		} else {
13226 			first_mp = mp;
13227 		}
13228 
13229 	}
13230 
13231 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13232 		/*
13233 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13234 		 * make sure IPF_RECVIF is passed to ip_add_info.
13235 		 */
13236 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13237 		    IPCL_ZONEID(connp), ipst);
13238 		if (mp == NULL) {
13239 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13240 			CONN_DEC_REF(connp);
13241 			if (mctl_present)
13242 				freeb(first_mp);
13243 			return (NULL);
13244 		} else if (mctl_present) {
13245 			/*
13246 			 * ip_add_info might return a new mp.
13247 			 */
13248 			ASSERT(first_mp != mp);
13249 			first_mp->b_cont = mp;
13250 		} else {
13251 			first_mp = mp;
13252 		}
13253 	}
13254 
13255 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13256 	if (IPCL_IS_TCP(connp)) {
13257 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13258 		return (first_mp);
13259 	} else {
13260 		/* SOCK_RAW, IPPROTO_TCP case */
13261 		(connp->conn_recv)(connp, first_mp, NULL);
13262 		CONN_DEC_REF(connp);
13263 		return (NULL);
13264 	}
13265 
13266 no_conn:
13267 	/* Initiate IPPf processing, if needed. */
13268 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13269 		uint32_t ill_index;
13270 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13271 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13272 		if (first_mp == NULL) {
13273 			return (NULL);
13274 		}
13275 	}
13276 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13277 
13278 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13279 	    ipst->ips_netstack->netstack_tcp, NULL);
13280 	return (NULL);
13281 ipoptions:
13282 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13283 		goto slow_done;
13284 	}
13285 
13286 	UPDATE_IB_PKT_COUNT(ire);
13287 	ire->ire_last_used_time = lbolt;
13288 
13289 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13290 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13291 fragmented:
13292 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13293 			if (mctl_present)
13294 				freeb(first_mp);
13295 			goto slow_done;
13296 		}
13297 		/*
13298 		 * Make sure that first_mp points back to mp as
13299 		 * the mp we came in with could have changed in
13300 		 * ip_rput_fragment().
13301 		 */
13302 		ASSERT(!mctl_present);
13303 		ipha = (ipha_t *)mp->b_rptr;
13304 		first_mp = mp;
13305 	}
13306 
13307 	/* Now we have a complete datagram, destined for this machine. */
13308 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13309 
13310 	len = mp->b_wptr - mp->b_rptr;
13311 	/* Pull up a minimal TCP header, if necessary. */
13312 	if (len < (u1 + 20)) {
13313 tcppullup:
13314 		if (!pullupmsg(mp, u1 + 20)) {
13315 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13316 			goto error;
13317 		}
13318 		ipha = (ipha_t *)mp->b_rptr;
13319 		len = mp->b_wptr - mp->b_rptr;
13320 	}
13321 
13322 	/*
13323 	 * Extract the offset field from the TCP header.  As usual, we
13324 	 * try to help the compiler more than the reader.
13325 	 */
13326 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13327 	if (offset != 5) {
13328 tcpoptions:
13329 		if (offset < 5) {
13330 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13331 			goto error;
13332 		}
13333 		/*
13334 		 * There must be TCP options.
13335 		 * Make sure we can grab them.
13336 		 */
13337 		offset <<= 2;
13338 		offset += u1;
13339 		if (len < offset) {
13340 			if (!pullupmsg(mp, offset)) {
13341 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13342 				goto error;
13343 			}
13344 			ipha = (ipha_t *)mp->b_rptr;
13345 			len = mp->b_wptr - rptr;
13346 		}
13347 	}
13348 
13349 	/* Get the total packet length in len, including headers. */
13350 	if (mp->b_cont) {
13351 multipkttcp:
13352 		len = msgdsize(mp);
13353 	}
13354 
13355 	/*
13356 	 * Check the TCP checksum by pulling together the pseudo-
13357 	 * header checksum, and passing it to ip_csum to be added in
13358 	 * with the TCP datagram.
13359 	 *
13360 	 * Since we are not using the hwcksum if available we must
13361 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13362 	 * If either of these fails along the way the mblk is freed.
13363 	 * If this logic ever changes and mblk is reused to say send
13364 	 * ICMP's back, then this flag may need to be cleared in
13365 	 * other places as well.
13366 	 */
13367 	DB_CKSUMFLAGS(mp) = 0;
13368 
13369 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13370 
13371 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13372 #ifdef	_BIG_ENDIAN
13373 	u1 += IPPROTO_TCP;
13374 #else
13375 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13376 #endif
13377 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13378 	/*
13379 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13380 	 */
13381 	IP_STAT(ipst, ip_in_sw_cksum);
13382 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13383 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13384 		goto error;
13385 	}
13386 
13387 	IP_STAT(ipst, ip_tcp_slow_path);
13388 	goto try_again;
13389 #undef  iphs
13390 #undef  rptr
13391 
13392 error:
13393 	freemsg(first_mp);
13394 slow_done:
13395 	return (NULL);
13396 }
13397 
13398 /* ARGSUSED */
13399 static void
13400 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13401     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13402 {
13403 	conn_t		*connp;
13404 	uint32_t	sum;
13405 	uint32_t	u1;
13406 	ssize_t		len;
13407 	sctp_hdr_t	*sctph;
13408 	zoneid_t	zoneid = ire->ire_zoneid;
13409 	uint32_t	pktsum;
13410 	uint32_t	calcsum;
13411 	uint32_t	ports;
13412 	in6_addr_t	map_src, map_dst;
13413 	ill_t		*ill = (ill_t *)q->q_ptr;
13414 	ip_stack_t	*ipst;
13415 	sctp_stack_t	*sctps;
13416 	boolean_t	sctp_csum_err = B_FALSE;
13417 
13418 	ASSERT(recv_ill != NULL);
13419 	ipst = recv_ill->ill_ipst;
13420 	sctps = ipst->ips_netstack->netstack_sctp;
13421 
13422 #define	rptr	((uchar_t *)ipha)
13423 
13424 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13425 	ASSERT(ill != NULL);
13426 
13427 	/* u1 is # words of IP options */
13428 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13429 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13430 
13431 	/* IP options present */
13432 	if (u1 > 0) {
13433 		goto ipoptions;
13434 	} else {
13435 		/* Check the IP header checksum.  */
13436 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13437 		    !mctl_present) {
13438 #define	uph	((uint16_t *)ipha)
13439 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13440 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13441 #undef	uph
13442 			/* finish doing IP checksum */
13443 			sum = (sum & 0xFFFF) + (sum >> 16);
13444 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13445 			/*
13446 			 * Don't verify header checksum if this packet
13447 			 * is coming back from AH/ESP as we already did it.
13448 			 */
13449 			if (sum != 0 && sum != 0xFFFF) {
13450 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13451 				goto error;
13452 			}
13453 		}
13454 		/*
13455 		 * Since there is no SCTP h/w cksum support yet, just
13456 		 * clear the flag.
13457 		 */
13458 		DB_CKSUMFLAGS(mp) = 0;
13459 	}
13460 
13461 	/*
13462 	 * Don't verify header checksum if this packet is coming
13463 	 * back from AH/ESP as we already did it.
13464 	 */
13465 	if (!mctl_present) {
13466 		UPDATE_IB_PKT_COUNT(ire);
13467 		ire->ire_last_used_time = lbolt;
13468 	}
13469 
13470 	/* packet part of fragmented IP packet? */
13471 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13472 	if (u1 & (IPH_MF | IPH_OFFSET))
13473 		goto fragmented;
13474 
13475 	/* u1 = IP header length (20 bytes) */
13476 	u1 = IP_SIMPLE_HDR_LENGTH;
13477 
13478 find_sctp_client:
13479 	/* Pullup if we don't have the sctp common header. */
13480 	len = MBLKL(mp);
13481 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13482 		if (mp->b_cont == NULL ||
13483 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13484 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13485 			goto error;
13486 		}
13487 		ipha = (ipha_t *)mp->b_rptr;
13488 		len = MBLKL(mp);
13489 	}
13490 
13491 	sctph = (sctp_hdr_t *)(rptr + u1);
13492 #ifdef	DEBUG
13493 	if (!skip_sctp_cksum) {
13494 #endif
13495 		pktsum = sctph->sh_chksum;
13496 		sctph->sh_chksum = 0;
13497 		calcsum = sctp_cksum(mp, u1);
13498 		sctph->sh_chksum = pktsum;
13499 		if (calcsum != pktsum)
13500 			sctp_csum_err = B_TRUE;
13501 #ifdef	DEBUG	/* skip_sctp_cksum */
13502 	}
13503 #endif
13504 	/* get the ports */
13505 	ports = *(uint32_t *)&sctph->sh_sport;
13506 
13507 	IRE_REFRELE(ire);
13508 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13509 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13510 	if (sctp_csum_err) {
13511 		/*
13512 		 * No potential sctp checksum errors go to the Sun
13513 		 * sctp stack however they might be Adler-32 summed
13514 		 * packets a userland stack bound to a raw IP socket
13515 		 * could reasonably use. Note though that Adler-32 is
13516 		 * a long deprecated algorithm and customer sctp
13517 		 * networks should eventually migrate to CRC-32 at
13518 		 * which time this facility should be removed.
13519 		 */
13520 		flags |= IP_FF_SCTP_CSUM_ERR;
13521 		goto no_conn;
13522 	}
13523 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13524 	    sctps)) == NULL) {
13525 		/* Check for raw socket or OOTB handling */
13526 		goto no_conn;
13527 	}
13528 
13529 	/* Found a client; up it goes */
13530 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13531 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13532 	return;
13533 
13534 no_conn:
13535 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13536 	    ports, mctl_present, flags, B_TRUE, zoneid);
13537 	return;
13538 
13539 ipoptions:
13540 	DB_CKSUMFLAGS(mp) = 0;
13541 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13542 		goto slow_done;
13543 
13544 	UPDATE_IB_PKT_COUNT(ire);
13545 	ire->ire_last_used_time = lbolt;
13546 
13547 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13548 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13549 fragmented:
13550 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13551 			goto slow_done;
13552 		/*
13553 		 * Make sure that first_mp points back to mp as
13554 		 * the mp we came in with could have changed in
13555 		 * ip_rput_fragment().
13556 		 */
13557 		ASSERT(!mctl_present);
13558 		ipha = (ipha_t *)mp->b_rptr;
13559 		first_mp = mp;
13560 	}
13561 
13562 	/* Now we have a complete datagram, destined for this machine. */
13563 	u1 = IPH_HDR_LENGTH(ipha);
13564 	goto find_sctp_client;
13565 #undef  iphs
13566 #undef  rptr
13567 
13568 error:
13569 	freemsg(first_mp);
13570 slow_done:
13571 	IRE_REFRELE(ire);
13572 }
13573 
13574 #define	VER_BITS	0xF0
13575 #define	VERSION_6	0x60
13576 
13577 static boolean_t
13578 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13579     ipaddr_t *dstp, ip_stack_t *ipst)
13580 {
13581 	uint_t	opt_len;
13582 	ipha_t *ipha;
13583 	ssize_t len;
13584 	uint_t	pkt_len;
13585 
13586 	ASSERT(ill != NULL);
13587 	IP_STAT(ipst, ip_ipoptions);
13588 	ipha = *iphapp;
13589 
13590 #define	rptr    ((uchar_t *)ipha)
13591 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13592 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13593 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13594 		freemsg(mp);
13595 		return (B_FALSE);
13596 	}
13597 
13598 	/* multiple mblk or too short */
13599 	pkt_len = ntohs(ipha->ipha_length);
13600 
13601 	/* Get the number of words of IP options in the IP header. */
13602 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13603 	if (opt_len) {
13604 		/* IP Options present!  Validate and process. */
13605 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13606 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13607 			goto done;
13608 		}
13609 		/*
13610 		 * Recompute complete header length and make sure we
13611 		 * have access to all of it.
13612 		 */
13613 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13614 		if (len > (mp->b_wptr - rptr)) {
13615 			if (len > pkt_len) {
13616 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13617 				goto done;
13618 			}
13619 			if (!pullupmsg(mp, len)) {
13620 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13621 				goto done;
13622 			}
13623 			ipha = (ipha_t *)mp->b_rptr;
13624 		}
13625 		/*
13626 		 * Go off to ip_rput_options which returns the next hop
13627 		 * destination address, which may have been affected
13628 		 * by source routing.
13629 		 */
13630 		IP_STAT(ipst, ip_opt);
13631 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13632 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13633 			return (B_FALSE);
13634 		}
13635 	}
13636 	*iphapp = ipha;
13637 	return (B_TRUE);
13638 done:
13639 	/* clear b_prev - used by ip_mroute_decap */
13640 	mp->b_prev = NULL;
13641 	freemsg(mp);
13642 	return (B_FALSE);
13643 #undef  rptr
13644 }
13645 
13646 /*
13647  * Deal with the fact that there is no ire for the destination.
13648  */
13649 static ire_t *
13650 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13651 {
13652 	ipha_t	*ipha;
13653 	ill_t	*ill;
13654 	ire_t	*ire;
13655 	ip_stack_t *ipst;
13656 	enum	ire_forward_action ret_action;
13657 
13658 	ipha = (ipha_t *)mp->b_rptr;
13659 	ill = (ill_t *)q->q_ptr;
13660 
13661 	ASSERT(ill != NULL);
13662 	ipst = ill->ill_ipst;
13663 
13664 	/*
13665 	 * No IRE for this destination, so it can't be for us.
13666 	 * Unless we are forwarding, drop the packet.
13667 	 * We have to let source routed packets through
13668 	 * since we don't yet know if they are 'ping -l'
13669 	 * packets i.e. if they will go out over the
13670 	 * same interface as they came in on.
13671 	 */
13672 	if (ll_multicast) {
13673 		freemsg(mp);
13674 		return (NULL);
13675 	}
13676 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13677 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13678 		freemsg(mp);
13679 		return (NULL);
13680 	}
13681 
13682 	/*
13683 	 * Mark this packet as having originated externally.
13684 	 *
13685 	 * For non-forwarding code path, ire_send later double
13686 	 * checks this interface to see if it is still exists
13687 	 * post-ARP resolution.
13688 	 *
13689 	 * Also, IPQOS uses this to differentiate between
13690 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13691 	 * QOS packet processing in ip_wput_attach_llhdr().
13692 	 * The QoS module can mark the b_band for a fastpath message
13693 	 * or the dl_priority field in a unitdata_req header for
13694 	 * CoS marking. This info can only be found in
13695 	 * ip_wput_attach_llhdr().
13696 	 */
13697 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13698 	/*
13699 	 * Clear the indication that this may have a hardware checksum
13700 	 * as we are not using it
13701 	 */
13702 	DB_CKSUMFLAGS(mp) = 0;
13703 
13704 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13705 	    MBLK_GETLABEL(mp), ipst);
13706 
13707 	if (ire == NULL && ret_action == Forward_check_multirt) {
13708 		/* Let ip_newroute handle CGTP  */
13709 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13710 		return (NULL);
13711 	}
13712 
13713 	if (ire != NULL)
13714 		return (ire);
13715 
13716 	mp->b_prev = mp->b_next = 0;
13717 
13718 	if (ret_action == Forward_blackhole) {
13719 		freemsg(mp);
13720 		return (NULL);
13721 	}
13722 	/* send icmp unreachable */
13723 	q = WR(q);
13724 	/* Sent by forwarding path, and router is global zone */
13725 	if (ip_source_routed(ipha, ipst)) {
13726 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13727 		    GLOBAL_ZONEID, ipst);
13728 	} else {
13729 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13730 		    ipst);
13731 	}
13732 
13733 	return (NULL);
13734 
13735 }
13736 
13737 /*
13738  * check ip header length and align it.
13739  */
13740 static boolean_t
13741 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13742 {
13743 	ssize_t len;
13744 	ill_t *ill;
13745 	ipha_t	*ipha;
13746 
13747 	len = MBLKL(mp);
13748 
13749 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13750 		ill = (ill_t *)q->q_ptr;
13751 
13752 		if (!OK_32PTR(mp->b_rptr))
13753 			IP_STAT(ipst, ip_notaligned1);
13754 		else
13755 			IP_STAT(ipst, ip_notaligned2);
13756 		/* Guard against bogus device drivers */
13757 		if (len < 0) {
13758 			/* clear b_prev - used by ip_mroute_decap */
13759 			mp->b_prev = NULL;
13760 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13761 			freemsg(mp);
13762 			return (B_FALSE);
13763 		}
13764 
13765 		if (ip_rput_pullups++ == 0) {
13766 			ipha = (ipha_t *)mp->b_rptr;
13767 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13768 			    "ip_check_and_align_header: %s forced us to "
13769 			    " pullup pkt, hdr len %ld, hdr addr %p",
13770 			    ill->ill_name, len, (void *)ipha);
13771 		}
13772 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13773 			/* clear b_prev - used by ip_mroute_decap */
13774 			mp->b_prev = NULL;
13775 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13776 			freemsg(mp);
13777 			return (B_FALSE);
13778 		}
13779 	}
13780 	return (B_TRUE);
13781 }
13782 
13783 ire_t *
13784 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13785 {
13786 	ire_t		*new_ire;
13787 	ill_t		*ire_ill;
13788 	uint_t		ifindex;
13789 	ip_stack_t	*ipst = ill->ill_ipst;
13790 	boolean_t	strict_check = B_FALSE;
13791 
13792 	/*
13793 	 * This packet came in on an interface other than the one associated
13794 	 * with the first ire we found for the destination address. We do
13795 	 * another ire lookup here, using the ingress ill, to see if the
13796 	 * interface is in an interface group.
13797 	 * As long as the ills belong to the same group, we don't consider
13798 	 * them to be arriving on the wrong interface. Thus, if the switch
13799 	 * is doing inbound load spreading, we won't drop packets when the
13800 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13801 	 * for 'usesrc groups' where the destination address may belong to
13802 	 * another interface to allow multipathing to happen.
13803 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13804 	 * where the local address may not be unique. In this case we were
13805 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13806 	 * actually returned. The new lookup, which is more specific, should
13807 	 * only find the IRE_LOCAL associated with the ingress ill if one
13808 	 * exists.
13809 	 */
13810 
13811 	if (ire->ire_ipversion == IPV4_VERSION) {
13812 		if (ipst->ips_ip_strict_dst_multihoming)
13813 			strict_check = B_TRUE;
13814 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13815 		    ill->ill_ipif, ALL_ZONES, NULL,
13816 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13817 	} else {
13818 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13819 		if (ipst->ips_ipv6_strict_dst_multihoming)
13820 			strict_check = B_TRUE;
13821 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13822 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13823 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13824 	}
13825 	/*
13826 	 * If the same ire that was returned in ip_input() is found then this
13827 	 * is an indication that interface groups are in use. The packet
13828 	 * arrived on a different ill in the group than the one associated with
13829 	 * the destination address.  If a different ire was found then the same
13830 	 * IP address must be hosted on multiple ills. This is possible with
13831 	 * unnumbered point2point interfaces. We switch to use this new ire in
13832 	 * order to have accurate interface statistics.
13833 	 */
13834 	if (new_ire != NULL) {
13835 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13836 			ire_refrele(ire);
13837 			ire = new_ire;
13838 		} else {
13839 			ire_refrele(new_ire);
13840 		}
13841 		return (ire);
13842 	} else if ((ire->ire_rfq == NULL) &&
13843 	    (ire->ire_ipversion == IPV4_VERSION)) {
13844 		/*
13845 		 * The best match could have been the original ire which
13846 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13847 		 * the strict multihoming checks are irrelevant as we consider
13848 		 * local addresses hosted on lo0 to be interface agnostic. We
13849 		 * only expect a null ire_rfq on IREs which are associated with
13850 		 * lo0 hence we can return now.
13851 		 */
13852 		return (ire);
13853 	}
13854 
13855 	/*
13856 	 * Chase pointers once and store locally.
13857 	 */
13858 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13859 	    (ill_t *)(ire->ire_rfq->q_ptr);
13860 	ifindex = ill->ill_usesrc_ifindex;
13861 
13862 	/*
13863 	 * Check if it's a legal address on the 'usesrc' interface.
13864 	 */
13865 	if ((ifindex != 0) && (ire_ill != NULL) &&
13866 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13867 		return (ire);
13868 	}
13869 
13870 	/*
13871 	 * If the ip*_strict_dst_multihoming switch is on then we can
13872 	 * only accept this packet if the interface is marked as routing.
13873 	 */
13874 	if (!(strict_check))
13875 		return (ire);
13876 
13877 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13878 	    ILLF_ROUTER) != 0) {
13879 		return (ire);
13880 	}
13881 
13882 	ire_refrele(ire);
13883 	return (NULL);
13884 }
13885 
13886 /*
13887  *
13888  * This is the fast forward path. If we are here, we dont need to
13889  * worry about RSVP, CGTP, or TSol. Furthermore the ftable lookup
13890  * needed to find the nexthop in this case is much simpler
13891  */
13892 ire_t *
13893 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13894 {
13895 	ipha_t	*ipha;
13896 	ire_t	*src_ire;
13897 	ill_t	*stq_ill;
13898 	uint_t	hlen;
13899 	uint_t	pkt_len;
13900 	uint32_t sum;
13901 	queue_t	*dev_q;
13902 	ip_stack_t *ipst = ill->ill_ipst;
13903 	mblk_t *fpmp;
13904 	enum	ire_forward_action ret_action;
13905 
13906 	ipha = (ipha_t *)mp->b_rptr;
13907 
13908 	if (ire != NULL &&
13909 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13910 	    ire->ire_zoneid != ALL_ZONES) {
13911 		/*
13912 		 * Should only use IREs that are visible to the global
13913 		 * zone for forwarding.
13914 		 */
13915 		ire_refrele(ire);
13916 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13917 		/*
13918 		 * ire_cache_lookup() can return ire of IRE_LOCAL in
13919 		 * transient cases. In such case, just drop the packet
13920 		 */
13921 		if (ire->ire_type != IRE_CACHE)
13922 			goto drop;
13923 	}
13924 
13925 	/*
13926 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13927 	 * The loopback address check for both src and dst has already
13928 	 * been checked in ip_input
13929 	 */
13930 
13931 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13932 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13933 		goto drop;
13934 	}
13935 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13936 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13937 
13938 	if (src_ire != NULL) {
13939 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13940 		ire_refrele(src_ire);
13941 		goto drop;
13942 	}
13943 
13944 	/* No ire cache of nexthop. So first create one  */
13945 	if (ire == NULL) {
13946 
13947 		ire = ire_forward_simple(dst, &ret_action, ipst);
13948 
13949 		/*
13950 		 * We only come to ip_fast_forward if ip_cgtp_filter
13951 		 * is not set. So ire_forward() should not return with
13952 		 * Forward_check_multirt as the next action.
13953 		 */
13954 		ASSERT(ret_action != Forward_check_multirt);
13955 		if (ire == NULL) {
13956 			/* An attempt was made to forward the packet */
13957 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13958 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13959 			mp->b_prev = mp->b_next = 0;
13960 			/* send icmp unreachable */
13961 			/* Sent by forwarding path, and router is global zone */
13962 			if (ret_action == Forward_ret_icmp_err) {
13963 				if (ip_source_routed(ipha, ipst)) {
13964 					icmp_unreachable(ill->ill_wq, mp,
13965 					    ICMP_SOURCE_ROUTE_FAILED,
13966 					    GLOBAL_ZONEID, ipst);
13967 				} else {
13968 					icmp_unreachable(ill->ill_wq, mp,
13969 					    ICMP_HOST_UNREACHABLE,
13970 					    GLOBAL_ZONEID, ipst);
13971 				}
13972 			} else {
13973 				freemsg(mp);
13974 			}
13975 			return (NULL);
13976 		}
13977 	}
13978 
13979 	/*
13980 	 * Forwarding fastpath exception case:
13981 	 * If either of the follwoing case is true, we take
13982 	 * the slowpath
13983 	 *	o forwarding is not enabled
13984 	 *	o incoming and outgoing interface are the same, or the same
13985 	 *	  IPMP group
13986 	 *	o corresponding ire is in incomplete state
13987 	 *	o packet needs fragmentation
13988 	 *	o ARP cache is not resolved
13989 	 *
13990 	 * The codeflow from here on is thus:
13991 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13992 	 */
13993 	pkt_len = ntohs(ipha->ipha_length);
13994 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13995 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13996 	    (ill == stq_ill) ||
13997 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13998 	    (ire->ire_nce == NULL) ||
13999 	    (pkt_len > ire->ire_max_frag) ||
14000 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14001 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14002 	    ipha->ipha_ttl <= 1) {
14003 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14004 		    ipha, ill, B_FALSE, B_TRUE);
14005 		return (ire);
14006 	}
14007 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14008 
14009 	DTRACE_PROBE4(ip4__forwarding__start,
14010 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14011 
14012 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14013 	    ipst->ips_ipv4firewall_forwarding,
14014 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14015 
14016 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14017 
14018 	if (mp == NULL)
14019 		goto drop;
14020 
14021 	mp->b_datap->db_struioun.cksum.flags = 0;
14022 	/* Adjust the checksum to reflect the ttl decrement. */
14023 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14024 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14025 	ipha->ipha_ttl--;
14026 
14027 	/*
14028 	 * Write the link layer header.  We can do this safely here,
14029 	 * because we have already tested to make sure that the IP
14030 	 * policy is not set, and that we have a fast path destination
14031 	 * header.
14032 	 */
14033 	mp->b_rptr -= hlen;
14034 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14035 
14036 	UPDATE_IB_PKT_COUNT(ire);
14037 	ire->ire_last_used_time = lbolt;
14038 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14039 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14040 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14041 
14042 	if (!ILL_DIRECT_CAPABLE(stq_ill) || DB_TYPE(mp) != M_DATA) {
14043 		dev_q = ire->ire_stq->q_next;
14044 		if (DEV_Q_FLOW_BLOCKED(dev_q))
14045 			goto indiscard;
14046 	}
14047 
14048 	DTRACE_PROBE4(ip4__physical__out__start,
14049 	    ill_t *, NULL, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14050 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
14051 	    ipst->ips_ipv4firewall_physical_out,
14052 	    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14053 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14054 	DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14055 	    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14056 	    ip6_t *, NULL, int, 0);
14057 
14058 	if (mp != NULL) {
14059 		if (ipst->ips_ipobs_enabled) {
14060 			zoneid_t szone;
14061 
14062 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp,
14063 			    ipst, ALL_ZONES);
14064 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone,
14065 			    ALL_ZONES, ill, IPV4_VERSION, hlen, ipst);
14066 		}
14067 
14068 		ILL_SEND_TX(stq_ill, ire, dst, mp, IP_DROP_ON_NO_DESC);
14069 	}
14070 	return (ire);
14071 
14072 indiscard:
14073 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14074 drop:
14075 	if (mp != NULL)
14076 		freemsg(mp);
14077 	return (ire);
14078 
14079 }
14080 
14081 /*
14082  * This function is called in the forwarding slowpath, when
14083  * either the ire lacks the link-layer address, or the packet needs
14084  * further processing(eg. fragmentation), before transmission.
14085  */
14086 
14087 static void
14088 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14089     ill_t *ill, boolean_t ll_multicast, boolean_t from_ip_fast_forward)
14090 {
14091 	ill_group_t	*ill_group;
14092 	ill_group_t	*ire_group;
14093 	queue_t		*dev_q;
14094 	ire_t		*src_ire;
14095 	ip_stack_t	*ipst = ill->ill_ipst;
14096 
14097 	ASSERT(ire->ire_stq != NULL);
14098 
14099 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14100 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14101 
14102 	/*
14103 	 * If the caller of this function is ip_fast_forward() skip the
14104 	 * next three checks as it does not apply.
14105 	 */
14106 	if (from_ip_fast_forward) {
14107 		ill_group = ill->ill_group;
14108 		ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14109 		goto skip;
14110 	}
14111 
14112 	if (ll_multicast != 0) {
14113 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14114 		goto drop_pkt;
14115 	}
14116 
14117 	/*
14118 	 * check if ipha_src is a broadcast address. Note that this
14119 	 * check is redundant when we get here from ip_fast_forward()
14120 	 * which has already done this check. However, since we can
14121 	 * also get here from ip_rput_process_broadcast() or, for
14122 	 * for the slow path through ip_fast_forward(), we perform
14123 	 * the check again for code-reusability
14124 	 */
14125 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14126 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14127 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14128 		if (src_ire != NULL)
14129 			ire_refrele(src_ire);
14130 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14131 		ip2dbg(("ip_rput_process_forward: Received packet with"
14132 		    " bad src/dst address on %s\n", ill->ill_name));
14133 		goto drop_pkt;
14134 	}
14135 
14136 	ill_group = ill->ill_group;
14137 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14138 	/*
14139 	 * Check if we want to forward this one at this time.
14140 	 * We allow source routed packets on a host provided that
14141 	 * they go out the same interface or same interface group
14142 	 * as they came in on.
14143 	 *
14144 	 * XXX To be quicker, we may wish to not chase pointers to
14145 	 * get the ILLF_ROUTER flag and instead store the
14146 	 * forwarding policy in the ire.  An unfortunate
14147 	 * side-effect of that would be requiring an ire flush
14148 	 * whenever the ILLF_ROUTER flag changes.
14149 	 */
14150 skip:
14151 	if (((ill->ill_flags &
14152 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14153 	    ILLF_ROUTER) == 0) &&
14154 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14155 	    (ill_group != NULL && ill_group == ire_group)))) {
14156 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14157 		if (ip_source_routed(ipha, ipst)) {
14158 			q = WR(q);
14159 			/*
14160 			 * Clear the indication that this may have
14161 			 * hardware checksum as we are not using it.
14162 			 */
14163 			DB_CKSUMFLAGS(mp) = 0;
14164 			/* Sent by forwarding path, and router is global zone */
14165 			icmp_unreachable(q, mp,
14166 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14167 			return;
14168 		}
14169 		goto drop_pkt;
14170 	}
14171 
14172 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14173 
14174 	/* Packet is being forwarded. Turning off hwcksum flag. */
14175 	DB_CKSUMFLAGS(mp) = 0;
14176 	if (ipst->ips_ip_g_send_redirects) {
14177 		/*
14178 		 * Check whether the incoming interface and outgoing
14179 		 * interface is part of the same group. If so,
14180 		 * send redirects.
14181 		 *
14182 		 * Check the source address to see if it originated
14183 		 * on the same logical subnet it is going back out on.
14184 		 * If so, we should be able to send it a redirect.
14185 		 * Avoid sending a redirect if the destination
14186 		 * is directly connected (i.e., ipha_dst is the same
14187 		 * as ire_gateway_addr or the ire_addr of the
14188 		 * nexthop IRE_CACHE ), or if the packet was source
14189 		 * routed out this interface.
14190 		 */
14191 		ipaddr_t src, nhop;
14192 		mblk_t	*mp1;
14193 		ire_t	*nhop_ire = NULL;
14194 
14195 		/*
14196 		 * Check whether ire_rfq and q are from the same ill
14197 		 * or if they are not same, they at least belong
14198 		 * to the same group. If so, send redirects.
14199 		 */
14200 		if ((ire->ire_rfq == q ||
14201 		    (ill_group != NULL && ill_group == ire_group)) &&
14202 		    !ip_source_routed(ipha, ipst)) {
14203 
14204 			nhop = (ire->ire_gateway_addr != 0 ?
14205 			    ire->ire_gateway_addr : ire->ire_addr);
14206 
14207 			if (ipha->ipha_dst == nhop) {
14208 				/*
14209 				 * We avoid sending a redirect if the
14210 				 * destination is directly connected
14211 				 * because it is possible that multiple
14212 				 * IP subnets may have been configured on
14213 				 * the link, and the source may not
14214 				 * be on the same subnet as ip destination,
14215 				 * even though they are on the same
14216 				 * physical link.
14217 				 */
14218 				goto sendit;
14219 			}
14220 
14221 			src = ipha->ipha_src;
14222 
14223 			/*
14224 			 * We look up the interface ire for the nexthop,
14225 			 * to see if ipha_src is in the same subnet
14226 			 * as the nexthop.
14227 			 *
14228 			 * Note that, if, in the future, IRE_CACHE entries
14229 			 * are obsoleted,  this lookup will not be needed,
14230 			 * as the ire passed to this function will be the
14231 			 * same as the nhop_ire computed below.
14232 			 */
14233 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14234 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14235 			    0, NULL, MATCH_IRE_TYPE, ipst);
14236 
14237 			if (nhop_ire != NULL) {
14238 				if ((src & nhop_ire->ire_mask) ==
14239 				    (nhop & nhop_ire->ire_mask)) {
14240 					/*
14241 					 * The source is directly connected.
14242 					 * Just copy the ip header (which is
14243 					 * in the first mblk)
14244 					 */
14245 					mp1 = copyb(mp);
14246 					if (mp1 != NULL) {
14247 						icmp_send_redirect(WR(q), mp1,
14248 						    nhop, ipst);
14249 					}
14250 				}
14251 				ire_refrele(nhop_ire);
14252 			}
14253 		}
14254 	}
14255 sendit:
14256 	dev_q = ire->ire_stq->q_next;
14257 	if (DEV_Q_FLOW_BLOCKED(dev_q)) {
14258 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14259 		freemsg(mp);
14260 		return;
14261 	}
14262 
14263 	ip_rput_forward(ire, ipha, mp, ill);
14264 	return;
14265 
14266 drop_pkt:
14267 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14268 	freemsg(mp);
14269 }
14270 
14271 ire_t *
14272 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14273     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14274 {
14275 	queue_t		*q;
14276 	uint16_t	hcksumflags;
14277 	ip_stack_t	*ipst = ill->ill_ipst;
14278 
14279 	q = *qp;
14280 
14281 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14282 
14283 	/*
14284 	 * Clear the indication that this may have hardware
14285 	 * checksum as we are not using it for forwarding.
14286 	 */
14287 	hcksumflags = DB_CKSUMFLAGS(mp);
14288 	DB_CKSUMFLAGS(mp) = 0;
14289 
14290 	/*
14291 	 * Directed broadcast forwarding: if the packet came in over a
14292 	 * different interface then it is routed out over we can forward it.
14293 	 */
14294 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14295 		ire_refrele(ire);
14296 		freemsg(mp);
14297 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14298 		return (NULL);
14299 	}
14300 	/*
14301 	 * For multicast we have set dst to be INADDR_BROADCAST
14302 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14303 	 * only for broadcast packets.
14304 	 */
14305 	if (!CLASSD(ipha->ipha_dst)) {
14306 		ire_t *new_ire;
14307 		ipif_t *ipif;
14308 		/*
14309 		 * For ill groups, as the switch duplicates broadcasts
14310 		 * across all the ports, we need to filter out and
14311 		 * send up only one copy. There is one copy for every
14312 		 * broadcast address on each ill. Thus, we look for a
14313 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14314 		 * later to see whether this ill is eligible to receive
14315 		 * them or not. ill_nominate_bcast_rcv() nominates only
14316 		 * one set of IREs for receiving.
14317 		 */
14318 
14319 		ipif = ipif_get_next_ipif(NULL, ill);
14320 		if (ipif == NULL) {
14321 			ire_refrele(ire);
14322 			freemsg(mp);
14323 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14324 			return (NULL);
14325 		}
14326 		new_ire = ire_ctable_lookup(dst, 0, 0,
14327 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14328 		ipif_refrele(ipif);
14329 
14330 		if (new_ire != NULL) {
14331 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14332 				ire_refrele(ire);
14333 				ire_refrele(new_ire);
14334 				freemsg(mp);
14335 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14336 				return (NULL);
14337 			}
14338 			/*
14339 			 * In the special case of multirouted broadcast
14340 			 * packets, we unconditionally need to "gateway"
14341 			 * them to the appropriate interface here.
14342 			 * In the normal case, this cannot happen, because
14343 			 * there is no broadcast IRE tagged with the
14344 			 * RTF_MULTIRT flag.
14345 			 */
14346 			if (new_ire->ire_flags & RTF_MULTIRT) {
14347 				ire_refrele(new_ire);
14348 				if (ire->ire_rfq != NULL) {
14349 					q = ire->ire_rfq;
14350 					*qp = q;
14351 				}
14352 			} else {
14353 				ire_refrele(ire);
14354 				ire = new_ire;
14355 			}
14356 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14357 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14358 				/*
14359 				 * Free the message if
14360 				 * ip_g_forward_directed_bcast is turned
14361 				 * off for non-local broadcast.
14362 				 */
14363 				ire_refrele(ire);
14364 				freemsg(mp);
14365 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14366 				return (NULL);
14367 			}
14368 		} else {
14369 			/*
14370 			 * This CGTP packet successfully passed the
14371 			 * CGTP filter, but the related CGTP
14372 			 * broadcast IRE has not been found,
14373 			 * meaning that the redundant ipif is
14374 			 * probably down. However, if we discarded
14375 			 * this packet, its duplicate would be
14376 			 * filtered out by the CGTP filter so none
14377 			 * of them would get through. So we keep
14378 			 * going with this one.
14379 			 */
14380 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14381 			if (ire->ire_rfq != NULL) {
14382 				q = ire->ire_rfq;
14383 				*qp = q;
14384 			}
14385 		}
14386 	}
14387 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14388 		/*
14389 		 * Verify that there are not more then one
14390 		 * IRE_BROADCAST with this broadcast address which
14391 		 * has ire_stq set.
14392 		 * TODO: simplify, loop over all IRE's
14393 		 */
14394 		ire_t	*ire1;
14395 		int	num_stq = 0;
14396 		mblk_t	*mp1;
14397 
14398 		/* Find the first one with ire_stq set */
14399 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14400 		for (ire1 = ire; ire1 &&
14401 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14402 		    ire1 = ire1->ire_next)
14403 			;
14404 		if (ire1) {
14405 			ire_refrele(ire);
14406 			ire = ire1;
14407 			IRE_REFHOLD(ire);
14408 		}
14409 
14410 		/* Check if there are additional ones with stq set */
14411 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14412 			if (ire->ire_addr != ire1->ire_addr)
14413 				break;
14414 			if (ire1->ire_stq) {
14415 				num_stq++;
14416 				break;
14417 			}
14418 		}
14419 		rw_exit(&ire->ire_bucket->irb_lock);
14420 		if (num_stq == 1 && ire->ire_stq != NULL) {
14421 			ip1dbg(("ip_rput_process_broadcast: directed "
14422 			    "broadcast to 0x%x\n",
14423 			    ntohl(ire->ire_addr)));
14424 			mp1 = copymsg(mp);
14425 			if (mp1) {
14426 				switch (ipha->ipha_protocol) {
14427 				case IPPROTO_UDP:
14428 					ip_udp_input(q, mp1, ipha, ire, ill);
14429 					break;
14430 				default:
14431 					ip_proto_input(q, mp1, ipha, ire, ill,
14432 					    0);
14433 					break;
14434 				}
14435 			}
14436 			/*
14437 			 * Adjust ttl to 2 (1+1 - the forward engine
14438 			 * will decrement it by one.
14439 			 */
14440 			if (ip_csum_hdr(ipha)) {
14441 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14442 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14443 				freemsg(mp);
14444 				ire_refrele(ire);
14445 				return (NULL);
14446 			}
14447 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14448 			ipha->ipha_hdr_checksum = 0;
14449 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14450 			ip_rput_process_forward(q, mp, ire, ipha,
14451 			    ill, ll_multicast, B_FALSE);
14452 			ire_refrele(ire);
14453 			return (NULL);
14454 		}
14455 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14456 		    ntohl(ire->ire_addr)));
14457 	}
14458 
14459 
14460 	/* Restore any hardware checksum flags */
14461 	DB_CKSUMFLAGS(mp) = hcksumflags;
14462 	return (ire);
14463 }
14464 
14465 /* ARGSUSED */
14466 static boolean_t
14467 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14468     int *ll_multicast, ipaddr_t *dstp)
14469 {
14470 	ip_stack_t	*ipst = ill->ill_ipst;
14471 
14472 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14473 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14474 	    ntohs(ipha->ipha_length));
14475 
14476 	/*
14477 	 * Forward packets only if we have joined the allmulti
14478 	 * group on this interface.
14479 	 */
14480 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14481 		int retval;
14482 
14483 		/*
14484 		 * Clear the indication that this may have hardware
14485 		 * checksum as we are not using it.
14486 		 */
14487 		DB_CKSUMFLAGS(mp) = 0;
14488 		retval = ip_mforward(ill, ipha, mp);
14489 		/* ip_mforward updates mib variables if needed */
14490 		/* clear b_prev - used by ip_mroute_decap */
14491 		mp->b_prev = NULL;
14492 
14493 		switch (retval) {
14494 		case 0:
14495 			/*
14496 			 * pkt is okay and arrived on phyint.
14497 			 *
14498 			 * If we are running as a multicast router
14499 			 * we need to see all IGMP and/or PIM packets.
14500 			 */
14501 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14502 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14503 				goto done;
14504 			}
14505 			break;
14506 		case -1:
14507 			/* pkt is mal-formed, toss it */
14508 			goto drop_pkt;
14509 		case 1:
14510 			/* pkt is okay and arrived on a tunnel */
14511 			/*
14512 			 * If we are running a multicast router
14513 			 *  we need to see all igmp packets.
14514 			 */
14515 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14516 				*dstp = INADDR_BROADCAST;
14517 				*ll_multicast = 1;
14518 				return (B_FALSE);
14519 			}
14520 
14521 			goto drop_pkt;
14522 		}
14523 	}
14524 
14525 	ILM_WALKER_HOLD(ill);
14526 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14527 		/*
14528 		 * This might just be caused by the fact that
14529 		 * multiple IP Multicast addresses map to the same
14530 		 * link layer multicast - no need to increment counter!
14531 		 */
14532 		ILM_WALKER_RELE(ill);
14533 		freemsg(mp);
14534 		return (B_TRUE);
14535 	}
14536 	ILM_WALKER_RELE(ill);
14537 done:
14538 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14539 	/*
14540 	 * This assumes the we deliver to all streams for multicast
14541 	 * and broadcast packets.
14542 	 */
14543 	*dstp = INADDR_BROADCAST;
14544 	*ll_multicast = 1;
14545 	return (B_FALSE);
14546 drop_pkt:
14547 	ip2dbg(("ip_rput: drop pkt\n"));
14548 	freemsg(mp);
14549 	return (B_TRUE);
14550 }
14551 
14552 /*
14553  * This function is used to both return an indication of whether or not
14554  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14555  * and in doing so, determine whether or not it is broadcast vs multicast.
14556  * For it to be a broadcast packet, we must have the appropriate mblk_t
14557  * hanging off the ill_t.  If this is either not present or doesn't match
14558  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14559  * to be multicast.  Thus NICs that have no broadcast address (or no
14560  * capability for one, such as point to point links) cannot return as
14561  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14562  * the return values simplifies the current use of the return value of this
14563  * function, which is to pass through the multicast/broadcast characteristic
14564  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14565  * changing the return value to some other symbol demands the appropriate
14566  * "translation" when hpe_flags is set prior to calling hook_run() for
14567  * packet events.
14568  */
14569 int
14570 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14571 {
14572 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14573 	mblk_t *bmp;
14574 
14575 	if (ind->dl_group_address) {
14576 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14577 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14578 		    MBLKL(mb) &&
14579 		    (bmp = ill->ill_bcast_mp) != NULL) {
14580 			dl_unitdata_req_t *dlur;
14581 			uint8_t *bphys_addr;
14582 
14583 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14584 			if (ill->ill_sap_length < 0)
14585 				bphys_addr = (uchar_t *)dlur +
14586 				    dlur->dl_dest_addr_offset;
14587 			else
14588 				bphys_addr = (uchar_t *)dlur +
14589 				    dlur->dl_dest_addr_offset +
14590 				    ill->ill_sap_length;
14591 
14592 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14593 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14594 				return (HPE_BROADCAST);
14595 			}
14596 			return (HPE_MULTICAST);
14597 		}
14598 		return (HPE_MULTICAST);
14599 	}
14600 	return (0);
14601 }
14602 
14603 static boolean_t
14604 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14605     int *ll_multicast, mblk_t **mpp)
14606 {
14607 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14608 	boolean_t must_copy = B_FALSE;
14609 	struct iocblk   *iocp;
14610 	ipha_t		*ipha;
14611 	ip_stack_t	*ipst = ill->ill_ipst;
14612 
14613 #define	rptr    ((uchar_t *)ipha)
14614 
14615 	first_mp = *first_mpp;
14616 	mp = *mpp;
14617 
14618 	ASSERT(first_mp == mp);
14619 
14620 	/*
14621 	 * if db_ref > 1 then copymsg and free original. Packet may be
14622 	 * changed and do not want other entity who has a reference to this
14623 	 * message to trip over the changes. This is a blind change because
14624 	 * trying to catch all places that might change packet is too
14625 	 * difficult (since it may be a module above this one)
14626 	 *
14627 	 * This corresponds to the non-fast path case. We walk down the full
14628 	 * chain in this case, and check the db_ref count of all the dblks,
14629 	 * and do a copymsg if required. It is possible that the db_ref counts
14630 	 * of the data blocks in the mblk chain can be different.
14631 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14632 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14633 	 * 'snoop' is running.
14634 	 */
14635 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14636 		if (mp1->b_datap->db_ref > 1) {
14637 			must_copy = B_TRUE;
14638 			break;
14639 		}
14640 	}
14641 
14642 	if (must_copy) {
14643 		mp1 = copymsg(mp);
14644 		if (mp1 == NULL) {
14645 			for (mp1 = mp; mp1 != NULL;
14646 			    mp1 = mp1->b_cont) {
14647 				mp1->b_next = NULL;
14648 				mp1->b_prev = NULL;
14649 			}
14650 			freemsg(mp);
14651 			if (ill != NULL) {
14652 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14653 			} else {
14654 				BUMP_MIB(&ipst->ips_ip_mib,
14655 				    ipIfStatsInDiscards);
14656 			}
14657 			return (B_TRUE);
14658 		}
14659 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14660 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14661 			/* Copy b_prev - used by ip_mroute_decap */
14662 			to_mp->b_prev = from_mp->b_prev;
14663 			from_mp->b_prev = NULL;
14664 		}
14665 		*first_mpp = first_mp = mp1;
14666 		freemsg(mp);
14667 		mp = mp1;
14668 		*mpp = mp1;
14669 	}
14670 
14671 	ipha = (ipha_t *)mp->b_rptr;
14672 
14673 	/*
14674 	 * previous code has a case for M_DATA.
14675 	 * We want to check how that happens.
14676 	 */
14677 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14678 	switch (first_mp->b_datap->db_type) {
14679 	case M_PROTO:
14680 	case M_PCPROTO:
14681 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14682 		    DL_UNITDATA_IND) {
14683 			/* Go handle anything other than data elsewhere. */
14684 			ip_rput_dlpi(q, mp);
14685 			return (B_TRUE);
14686 		}
14687 
14688 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14689 		/* Ditch the DLPI header. */
14690 		mp1 = mp->b_cont;
14691 		ASSERT(first_mp == mp);
14692 		*first_mpp = mp1;
14693 		freeb(mp);
14694 		*mpp = mp1;
14695 		return (B_FALSE);
14696 	case M_IOCACK:
14697 		ip1dbg(("got iocack "));
14698 		iocp = (struct iocblk *)mp->b_rptr;
14699 		switch (iocp->ioc_cmd) {
14700 		case DL_IOC_HDR_INFO:
14701 			ill = (ill_t *)q->q_ptr;
14702 			ill_fastpath_ack(ill, mp);
14703 			return (B_TRUE);
14704 		case SIOCSTUNPARAM:
14705 		case OSIOCSTUNPARAM:
14706 			/* Go through qwriter_ip */
14707 			break;
14708 		case SIOCGTUNPARAM:
14709 		case OSIOCGTUNPARAM:
14710 			ip_rput_other(NULL, q, mp, NULL);
14711 			return (B_TRUE);
14712 		default:
14713 			putnext(q, mp);
14714 			return (B_TRUE);
14715 		}
14716 		/* FALLTHRU */
14717 	case M_ERROR:
14718 	case M_HANGUP:
14719 		/*
14720 		 * Since this is on the ill stream we unconditionally
14721 		 * bump up the refcount
14722 		 */
14723 		ill_refhold(ill);
14724 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14725 		return (B_TRUE);
14726 	case M_CTL:
14727 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14728 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14729 		    IPHADA_M_CTL)) {
14730 			/*
14731 			 * It's an IPsec accelerated packet.
14732 			 * Make sure that the ill from which we received the
14733 			 * packet has enabled IPsec hardware acceleration.
14734 			 */
14735 			if (!(ill->ill_capabilities &
14736 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14737 				/* IPsec kstats: bean counter */
14738 				freemsg(mp);
14739 				return (B_TRUE);
14740 			}
14741 
14742 			/*
14743 			 * Make mp point to the mblk following the M_CTL,
14744 			 * then process according to type of mp.
14745 			 * After this processing, first_mp will point to
14746 			 * the data-attributes and mp to the pkt following
14747 			 * the M_CTL.
14748 			 */
14749 			mp = first_mp->b_cont;
14750 			if (mp == NULL) {
14751 				freemsg(first_mp);
14752 				return (B_TRUE);
14753 			}
14754 			/*
14755 			 * A Hardware Accelerated packet can only be M_DATA
14756 			 * ESP or AH packet.
14757 			 */
14758 			if (mp->b_datap->db_type != M_DATA) {
14759 				/* non-M_DATA IPsec accelerated packet */
14760 				IPSECHW_DEBUG(IPSECHW_PKT,
14761 				    ("non-M_DATA IPsec accelerated pkt\n"));
14762 				freemsg(first_mp);
14763 				return (B_TRUE);
14764 			}
14765 			ipha = (ipha_t *)mp->b_rptr;
14766 			if (ipha->ipha_protocol != IPPROTO_AH &&
14767 			    ipha->ipha_protocol != IPPROTO_ESP) {
14768 				IPSECHW_DEBUG(IPSECHW_PKT,
14769 				    ("non-M_DATA IPsec accelerated pkt\n"));
14770 				freemsg(first_mp);
14771 				return (B_TRUE);
14772 			}
14773 			*mpp = mp;
14774 			return (B_FALSE);
14775 		}
14776 		putnext(q, mp);
14777 		return (B_TRUE);
14778 	case M_IOCNAK:
14779 		ip1dbg(("got iocnak "));
14780 		iocp = (struct iocblk *)mp->b_rptr;
14781 		switch (iocp->ioc_cmd) {
14782 		case SIOCSTUNPARAM:
14783 		case OSIOCSTUNPARAM:
14784 			/*
14785 			 * Since this is on the ill stream we unconditionally
14786 			 * bump up the refcount
14787 			 */
14788 			ill_refhold(ill);
14789 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14790 			return (B_TRUE);
14791 		case DL_IOC_HDR_INFO:
14792 		case SIOCGTUNPARAM:
14793 		case OSIOCGTUNPARAM:
14794 			ip_rput_other(NULL, q, mp, NULL);
14795 			return (B_TRUE);
14796 		default:
14797 			break;
14798 		}
14799 		/* FALLTHRU */
14800 	default:
14801 		putnext(q, mp);
14802 		return (B_TRUE);
14803 	}
14804 }
14805 
14806 /* Read side put procedure.  Packets coming from the wire arrive here. */
14807 void
14808 ip_rput(queue_t *q, mblk_t *mp)
14809 {
14810 	ill_t	*ill;
14811 	union DL_primitives *dl;
14812 
14813 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14814 
14815 	ill = (ill_t *)q->q_ptr;
14816 
14817 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14818 		/*
14819 		 * If things are opening or closing, only accept high-priority
14820 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14821 		 * created; on close, things hanging off the ill may have been
14822 		 * freed already.)
14823 		 */
14824 		dl = (union DL_primitives *)mp->b_rptr;
14825 		if (DB_TYPE(mp) != M_PCPROTO ||
14826 		    dl->dl_primitive == DL_UNITDATA_IND) {
14827 			/*
14828 			 * SIOC[GS]TUNPARAM ioctls can come here.
14829 			 */
14830 			inet_freemsg(mp);
14831 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14832 			    "ip_rput_end: q %p (%S)", q, "uninit");
14833 			return;
14834 		}
14835 	}
14836 
14837 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14838 	    "ip_rput_end: q %p (%S)", q, "end");
14839 
14840 	ip_input(ill, NULL, mp, NULL);
14841 }
14842 
14843 static mblk_t *
14844 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14845 {
14846 	mblk_t *mp1;
14847 	boolean_t adjusted = B_FALSE;
14848 	ip_stack_t *ipst = ill->ill_ipst;
14849 
14850 	IP_STAT(ipst, ip_db_ref);
14851 	/*
14852 	 * The IP_RECVSLLA option depends on having the
14853 	 * link layer header. First check that:
14854 	 * a> the underlying device is of type ether,
14855 	 * since this option is currently supported only
14856 	 * over ethernet.
14857 	 * b> there is enough room to copy over the link
14858 	 * layer header.
14859 	 *
14860 	 * Once the checks are done, adjust rptr so that
14861 	 * the link layer header will be copied via
14862 	 * copymsg. Note that, IFT_ETHER may be returned
14863 	 * by some non-ethernet drivers but in this case
14864 	 * the second check will fail.
14865 	 */
14866 	if (ill->ill_type == IFT_ETHER &&
14867 	    (mp->b_rptr - mp->b_datap->db_base) >=
14868 	    sizeof (struct ether_header)) {
14869 		mp->b_rptr -= sizeof (struct ether_header);
14870 		adjusted = B_TRUE;
14871 	}
14872 	mp1 = copymsg(mp);
14873 
14874 	if (mp1 == NULL) {
14875 		mp->b_next = NULL;
14876 		/* clear b_prev - used by ip_mroute_decap */
14877 		mp->b_prev = NULL;
14878 		freemsg(mp);
14879 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14880 		return (NULL);
14881 	}
14882 
14883 	if (adjusted) {
14884 		/*
14885 		 * Copy is done. Restore the pointer in
14886 		 * the _new_ mblk
14887 		 */
14888 		mp1->b_rptr += sizeof (struct ether_header);
14889 	}
14890 
14891 	/* Copy b_prev - used by ip_mroute_decap */
14892 	mp1->b_prev = mp->b_prev;
14893 	mp->b_prev = NULL;
14894 
14895 	/* preserve the hardware checksum flags and data, if present */
14896 	if (DB_CKSUMFLAGS(mp) != 0) {
14897 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14898 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14899 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14900 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14901 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14902 	}
14903 
14904 	freemsg(mp);
14905 	return (mp1);
14906 }
14907 
14908 #define	ADD_TO_CHAIN(head, tail, cnt, mp) {    			\
14909 	if (tail != NULL)					\
14910 		tail->b_next = mp;				\
14911 	else							\
14912 		head = mp;					\
14913 	tail = mp;						\
14914 	cnt++;							\
14915 }
14916 
14917 /*
14918  * Direct read side procedure capable of dealing with chains. GLDv3 based
14919  * drivers call this function directly with mblk chains while STREAMS
14920  * read side procedure ip_rput() calls this for single packet with ip_ring
14921  * set to NULL to process one packet at a time.
14922  *
14923  * The ill will always be valid if this function is called directly from
14924  * the driver.
14925  *
14926  * If ip_input() is called from GLDv3:
14927  *
14928  *   - This must be a non-VLAN IP stream.
14929  *   - 'mp' is either an untagged or a special priority-tagged packet.
14930  *   - Any VLAN tag that was in the MAC header has been stripped.
14931  *
14932  * If the IP header in packet is not 32-bit aligned, every message in the
14933  * chain will be aligned before further operations. This is required on SPARC
14934  * platform.
14935  */
14936 /* ARGSUSED */
14937 void
14938 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14939     struct mac_header_info_s *mhip)
14940 {
14941 	ipaddr_t		dst = NULL;
14942 	ipaddr_t		prev_dst;
14943 	ire_t			*ire = NULL;
14944 	ipha_t			*ipha;
14945 	uint_t			pkt_len;
14946 	ssize_t			len;
14947 	uint_t			opt_len;
14948 	int			ll_multicast;
14949 	int			cgtp_flt_pkt;
14950 	queue_t			*q = ill->ill_rq;
14951 	squeue_t		*curr_sqp = NULL;
14952 	mblk_t 			*head = NULL;
14953 	mblk_t			*tail = NULL;
14954 	mblk_t			*first_mp;
14955 	int			cnt = 0;
14956 	ip_stack_t		*ipst = ill->ill_ipst;
14957 	mblk_t			*mp;
14958 	mblk_t			*dmp;
14959 	uint8_t			tag;
14960 
14961 	ASSERT(mp_chain != NULL);
14962 	ASSERT(ill != NULL);
14963 
14964 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14965 
14966 	tag = (ip_ring != NULL) ? SQTAG_IP_INPUT_RX_RING : SQTAG_IP_INPUT;
14967 
14968 #define	rptr	((uchar_t *)ipha)
14969 
14970 	while (mp_chain != NULL) {
14971 		mp = mp_chain;
14972 		mp_chain = mp_chain->b_next;
14973 		mp->b_next = NULL;
14974 		ll_multicast = 0;
14975 
14976 		/*
14977 		 * We do ire caching from one iteration to
14978 		 * another. In the event the packet chain contains
14979 		 * all packets from the same dst, this caching saves
14980 		 * an ire_cache_lookup for each of the succeeding
14981 		 * packets in a packet chain.
14982 		 */
14983 		prev_dst = dst;
14984 
14985 		/*
14986 		 * if db_ref > 1 then copymsg and free original. Packet
14987 		 * may be changed and we do not want the other entity
14988 		 * who has a reference to this message to trip over the
14989 		 * changes. This is a blind change because trying to
14990 		 * catch all places that might change the packet is too
14991 		 * difficult.
14992 		 *
14993 		 * This corresponds to the fast path case, where we have
14994 		 * a chain of M_DATA mblks.  We check the db_ref count
14995 		 * of only the 1st data block in the mblk chain. There
14996 		 * doesn't seem to be a reason why a device driver would
14997 		 * send up data with varying db_ref counts in the mblk
14998 		 * chain. In any case the Fast path is a private
14999 		 * interface, and our drivers don't do such a thing.
15000 		 * Given the above assumption, there is no need to walk
15001 		 * down the entire mblk chain (which could have a
15002 		 * potential performance problem)
15003 		 *
15004 		 * The "(DB_REF(mp) > 1)" check was moved from ip_rput()
15005 		 * to here because of exclusive ip stacks and vnics.
15006 		 * Packets transmitted from exclusive stack over vnic
15007 		 * can have db_ref > 1 and when it gets looped back to
15008 		 * another vnic in a different zone, you have ip_input()
15009 		 * getting dblks with db_ref > 1. So if someone
15010 		 * complains of TCP performance under this scenario,
15011 		 * take a serious look here on the impact of copymsg().
15012 		 */
15013 
15014 		if (DB_REF(mp) > 1) {
15015 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
15016 				continue;
15017 		}
15018 
15019 		/*
15020 		 * Check and align the IP header.
15021 		 */
15022 		first_mp = mp;
15023 		if (DB_TYPE(mp) == M_DATA) {
15024 			dmp = mp;
15025 		} else if (DB_TYPE(mp) == M_PROTO &&
15026 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15027 			dmp = mp->b_cont;
15028 		} else {
15029 			dmp = NULL;
15030 		}
15031 		if (dmp != NULL) {
15032 			/*
15033 			 * IP header ptr not aligned?
15034 			 * OR IP header not complete in first mblk
15035 			 */
15036 			if (!OK_32PTR(dmp->b_rptr) ||
15037 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15038 				if (!ip_check_and_align_header(q, dmp, ipst))
15039 					continue;
15040 			}
15041 		}
15042 
15043 		/*
15044 		 * ip_input fast path
15045 		 */
15046 
15047 		/* mblk type is not M_DATA */
15048 		if (DB_TYPE(mp) != M_DATA) {
15049 			if (ip_rput_process_notdata(q, &first_mp, ill,
15050 			    &ll_multicast, &mp))
15051 				continue;
15052 
15053 			/*
15054 			 * The only way we can get here is if we had a
15055 			 * packet that was either a DL_UNITDATA_IND or
15056 			 * an M_CTL for an IPsec accelerated packet.
15057 			 *
15058 			 * In either case, the first_mp will point to
15059 			 * the leading M_PROTO or M_CTL.
15060 			 */
15061 			ASSERT(first_mp != NULL);
15062 		} else if (mhip != NULL) {
15063 			/*
15064 			 * ll_multicast is set here so that it is ready
15065 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15066 			 * manipulates ll_multicast in the same fashion when
15067 			 * called from ip_rput_process_notdata.
15068 			 */
15069 			switch (mhip->mhi_dsttype) {
15070 			case MAC_ADDRTYPE_MULTICAST :
15071 				ll_multicast = HPE_MULTICAST;
15072 				break;
15073 			case MAC_ADDRTYPE_BROADCAST :
15074 				ll_multicast = HPE_BROADCAST;
15075 				break;
15076 			default :
15077 				break;
15078 			}
15079 		}
15080 
15081 		/* Only M_DATA can come here and it is always aligned */
15082 		ASSERT(DB_TYPE(mp) == M_DATA);
15083 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15084 
15085 		ipha = (ipha_t *)mp->b_rptr;
15086 		len = mp->b_wptr - rptr;
15087 		pkt_len = ntohs(ipha->ipha_length);
15088 
15089 		/*
15090 		 * We must count all incoming packets, even if they end
15091 		 * up being dropped later on.
15092 		 */
15093 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15094 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15095 
15096 		/* multiple mblk or too short */
15097 		len -= pkt_len;
15098 		if (len != 0) {
15099 			/*
15100 			 * Make sure we have data length consistent
15101 			 * with the IP header.
15102 			 */
15103 			if (mp->b_cont == NULL) {
15104 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15105 					BUMP_MIB(ill->ill_ip_mib,
15106 					    ipIfStatsInHdrErrors);
15107 					ip2dbg(("ip_input: drop pkt\n"));
15108 					freemsg(mp);
15109 					continue;
15110 				}
15111 				mp->b_wptr = rptr + pkt_len;
15112 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15113 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15114 					BUMP_MIB(ill->ill_ip_mib,
15115 					    ipIfStatsInHdrErrors);
15116 					ip2dbg(("ip_input: drop pkt\n"));
15117 					freemsg(mp);
15118 					continue;
15119 				}
15120 				(void) adjmsg(mp, -len);
15121 				IP_STAT(ipst, ip_multimblk3);
15122 			}
15123 		}
15124 
15125 		/* Obtain the dst of the current packet */
15126 		dst = ipha->ipha_dst;
15127 
15128 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15129 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15130 		    ipha, ip6_t *, NULL, int, 0);
15131 
15132 		/*
15133 		 * The following test for loopback is faster than
15134 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15135 		 * operations.
15136 		 * Note that these addresses are always in network byte order
15137 		 */
15138 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15139 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15140 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15141 			freemsg(mp);
15142 			continue;
15143 		}
15144 
15145 		/*
15146 		 * The event for packets being received from a 'physical'
15147 		 * interface is placed after validation of the source and/or
15148 		 * destination address as being local so that packets can be
15149 		 * redirected to loopback addresses using ipnat.
15150 		 */
15151 		DTRACE_PROBE4(ip4__physical__in__start,
15152 		    ill_t *, ill, ill_t *, NULL,
15153 		    ipha_t *, ipha, mblk_t *, first_mp);
15154 
15155 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15156 		    ipst->ips_ipv4firewall_physical_in,
15157 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15158 
15159 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15160 
15161 		if (first_mp == NULL) {
15162 			continue;
15163 		}
15164 		dst = ipha->ipha_dst;
15165 		/*
15166 		 * Attach any necessary label information to
15167 		 * this packet
15168 		 */
15169 		if (is_system_labeled() &&
15170 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15171 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15172 			freemsg(mp);
15173 			continue;
15174 		}
15175 
15176 		if (ipst->ips_ipobs_enabled) {
15177 			zoneid_t dzone;
15178 
15179 			/*
15180 			 * On the inbound path the src zone will be unknown as
15181 			 * this packet has come from the wire.
15182 			 */
15183 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15184 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15185 			    ill, IPV4_VERSION, 0, ipst);
15186 		}
15187 
15188 		/*
15189 		 * Reuse the cached ire only if the ipha_dst of the previous
15190 		 * packet is the same as the current packet AND it is not
15191 		 * INADDR_ANY.
15192 		 */
15193 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15194 		    (ire != NULL)) {
15195 			ire_refrele(ire);
15196 			ire = NULL;
15197 		}
15198 
15199 		opt_len = ipha->ipha_version_and_hdr_length -
15200 		    IP_SIMPLE_HDR_VERSION;
15201 
15202 		/*
15203 		 * Check to see if we can take the fastpath.
15204 		 * That is possible if the following conditions are met
15205 		 *	o Tsol disabled
15206 		 *	o CGTP disabled
15207 		 *	o ipp_action_count is 0
15208 		 *	o no options in the packet
15209 		 *	o not a RSVP packet
15210 		 * 	o not a multicast packet
15211 		 *	o ill not in IP_DHCPINIT_IF mode
15212 		 */
15213 		if (!is_system_labeled() &&
15214 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15215 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15216 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15217 			if (ire == NULL)
15218 				ire = ire_cache_lookup_simple(dst, ipst);
15219 			/*
15220 			 * Unless forwarding is enabled, dont call
15221 			 * ip_fast_forward(). Incoming packet is for forwarding
15222 			 */
15223 			if ((ill->ill_flags & ILLF_ROUTER) &&
15224 			    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15225 				ire = ip_fast_forward(ire, dst, ill, mp);
15226 				continue;
15227 			}
15228 			/* incoming packet is for local consumption */
15229 			if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15230 				goto local;
15231 		}
15232 
15233 		/*
15234 		 * Disable ire caching for anything more complex
15235 		 * than the simple fast path case we checked for above.
15236 		 */
15237 		if (ire != NULL) {
15238 			ire_refrele(ire);
15239 			ire = NULL;
15240 		}
15241 
15242 		/*
15243 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15244 		 * server to unicast DHCP packets to a DHCP client using the
15245 		 * IP address it is offering to the client.  This can be
15246 		 * disabled through the "broadcast bit", but not all DHCP
15247 		 * servers honor that bit.  Therefore, to interoperate with as
15248 		 * many DHCP servers as possible, the DHCP client allows the
15249 		 * server to unicast, but we treat those packets as broadcast
15250 		 * here.  Note that we don't rewrite the packet itself since
15251 		 * (a) that would mess up the checksums and (b) the DHCP
15252 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15253 		 * hand it the packet regardless.
15254 		 */
15255 		if (ill->ill_dhcpinit != 0 &&
15256 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15257 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15258 			udpha_t *udpha;
15259 
15260 			/*
15261 			 * Reload ipha since pullupmsg() can change b_rptr.
15262 			 */
15263 			ipha = (ipha_t *)mp->b_rptr;
15264 			udpha = (udpha_t *)&ipha[1];
15265 
15266 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15267 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15268 				    mblk_t *, mp);
15269 				dst = INADDR_BROADCAST;
15270 			}
15271 		}
15272 
15273 		/* Full-blown slow path */
15274 		if (opt_len != 0) {
15275 			if (len != 0)
15276 				IP_STAT(ipst, ip_multimblk4);
15277 			else
15278 				IP_STAT(ipst, ip_ipoptions);
15279 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15280 			    &dst, ipst))
15281 				continue;
15282 		}
15283 
15284 		/*
15285 		 * Invoke the CGTP (multirouting) filtering module to process
15286 		 * the incoming packet. Packets identified as duplicates
15287 		 * must be discarded. Filtering is active only if the
15288 		 * the ip_cgtp_filter ndd variable is non-zero.
15289 		 */
15290 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15291 		if (ipst->ips_ip_cgtp_filter &&
15292 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15293 			netstackid_t stackid;
15294 
15295 			stackid = ipst->ips_netstack->netstack_stackid;
15296 			cgtp_flt_pkt =
15297 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15298 			    ill->ill_phyint->phyint_ifindex, mp);
15299 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15300 				freemsg(first_mp);
15301 				continue;
15302 			}
15303 		}
15304 
15305 		/*
15306 		 * If rsvpd is running, let RSVP daemon handle its processing
15307 		 * and forwarding of RSVP multicast/unicast packets.
15308 		 * If rsvpd is not running but mrouted is running, RSVP
15309 		 * multicast packets are forwarded as multicast traffic
15310 		 * and RSVP unicast packets are forwarded by unicast router.
15311 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15312 		 * packets are not forwarded, but the unicast packets are
15313 		 * forwarded like unicast traffic.
15314 		 */
15315 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15316 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15317 		    NULL) {
15318 			/* RSVP packet and rsvpd running. Treat as ours */
15319 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15320 			/*
15321 			 * This assumes that we deliver to all streams for
15322 			 * multicast and broadcast packets.
15323 			 * We have to force ll_multicast to 1 to handle the
15324 			 * M_DATA messages passed in from ip_mroute_decap.
15325 			 */
15326 			dst = INADDR_BROADCAST;
15327 			ll_multicast = 1;
15328 		} else if (CLASSD(dst)) {
15329 			/* packet is multicast */
15330 			mp->b_next = NULL;
15331 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15332 			    &ll_multicast, &dst))
15333 				continue;
15334 		}
15335 
15336 		if (ire == NULL) {
15337 			ire = ire_cache_lookup(dst, ALL_ZONES,
15338 			    MBLK_GETLABEL(mp), ipst);
15339 		}
15340 
15341 		if (ire != NULL && ire->ire_stq != NULL &&
15342 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15343 		    ire->ire_zoneid != ALL_ZONES) {
15344 			/*
15345 			 * Should only use IREs that are visible from the
15346 			 * global zone for forwarding.
15347 			 */
15348 			ire_refrele(ire);
15349 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15350 			    MBLK_GETLABEL(mp), ipst);
15351 		}
15352 
15353 		if (ire == NULL) {
15354 			/*
15355 			 * No IRE for this destination, so it can't be for us.
15356 			 * Unless we are forwarding, drop the packet.
15357 			 * We have to let source routed packets through
15358 			 * since we don't yet know if they are 'ping -l'
15359 			 * packets i.e. if they will go out over the
15360 			 * same interface as they came in on.
15361 			 */
15362 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15363 			if (ire == NULL)
15364 				continue;
15365 		}
15366 
15367 		/*
15368 		 * Broadcast IRE may indicate either broadcast or
15369 		 * multicast packet
15370 		 */
15371 		if (ire->ire_type == IRE_BROADCAST) {
15372 			/*
15373 			 * Skip broadcast checks if packet is UDP multicast;
15374 			 * we'd rather not enter ip_rput_process_broadcast()
15375 			 * unless the packet is broadcast for real, since
15376 			 * that routine is a no-op for multicast.
15377 			 */
15378 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15379 			    !CLASSD(ipha->ipha_dst)) {
15380 				ire = ip_rput_process_broadcast(&q, mp,
15381 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15382 				    ll_multicast);
15383 				if (ire == NULL)
15384 					continue;
15385 			}
15386 		} else if (ire->ire_stq != NULL) {
15387 			/* fowarding? */
15388 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15389 			    ll_multicast, B_FALSE);
15390 			/* ip_rput_process_forward consumed the packet */
15391 			continue;
15392 		}
15393 
15394 local:
15395 		/*
15396 		 * If the queue in the ire is different to the ingress queue
15397 		 * then we need to check to see if we can accept the packet.
15398 		 * Note that for multicast packets and broadcast packets sent
15399 		 * to a broadcast address which is shared between multiple
15400 		 * interfaces we should not do this since we just got a random
15401 		 * broadcast ire.
15402 		 */
15403 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15404 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15405 			    ill)) == NULL) {
15406 				/* Drop packet */
15407 				BUMP_MIB(ill->ill_ip_mib,
15408 				    ipIfStatsForwProhibits);
15409 				freemsg(mp);
15410 				continue;
15411 			}
15412 			if (ire->ire_rfq != NULL)
15413 				q = ire->ire_rfq;
15414 		}
15415 
15416 		switch (ipha->ipha_protocol) {
15417 		case IPPROTO_TCP:
15418 			ASSERT(first_mp == mp);
15419 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15420 			    mp, 0, q, ip_ring)) != NULL) {
15421 				if (curr_sqp == NULL) {
15422 					curr_sqp = GET_SQUEUE(mp);
15423 					ASSERT(cnt == 0);
15424 					cnt++;
15425 					head = tail = mp;
15426 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15427 					ASSERT(tail != NULL);
15428 					cnt++;
15429 					tail->b_next = mp;
15430 					tail = mp;
15431 				} else {
15432 					/*
15433 					 * A different squeue. Send the
15434 					 * chain for the previous squeue on
15435 					 * its way. This shouldn't happen
15436 					 * often unless interrupt binding
15437 					 * changes.
15438 					 */
15439 					IP_STAT(ipst, ip_input_multi_squeue);
15440 					SQUEUE_ENTER(curr_sqp, head,
15441 					    tail, cnt, SQ_PROCESS, tag);
15442 					curr_sqp = GET_SQUEUE(mp);
15443 					head = mp;
15444 					tail = mp;
15445 					cnt = 1;
15446 				}
15447 			}
15448 			continue;
15449 		case IPPROTO_UDP:
15450 			ASSERT(first_mp == mp);
15451 			ip_udp_input(q, mp, ipha, ire, ill);
15452 			continue;
15453 		case IPPROTO_SCTP:
15454 			ASSERT(first_mp == mp);
15455 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15456 			    q, dst);
15457 			/* ire has been released by ip_sctp_input */
15458 			ire = NULL;
15459 			continue;
15460 		default:
15461 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15462 			continue;
15463 		}
15464 	}
15465 
15466 	if (ire != NULL)
15467 		ire_refrele(ire);
15468 
15469 	if (head != NULL)
15470 		SQUEUE_ENTER(curr_sqp, head, tail, cnt, SQ_PROCESS, tag);
15471 
15472 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15473 	    "ip_input_end: q %p (%S)", q, "end");
15474 #undef  rptr
15475 }
15476 
15477 /*
15478  * ip_accept_tcp() - This function is called by the squeue when it retrieves
15479  * a chain of packets in the poll mode. The packets have gone through the
15480  * data link processing but not IP processing. For performance and latency
15481  * reasons, the squeue wants to process the chain in line instead of feeding
15482  * it back via ip_input path.
15483  *
15484  * So this is a light weight function which checks to see if the packets
15485  * retrived are indeed TCP packets (TCP squeue always polls TCP soft ring
15486  * but we still do the paranoid check) meant for local machine and we don't
15487  * have labels etc enabled. Packets that meet the criterion are returned to
15488  * the squeue and processed inline while the rest go via ip_input path.
15489  */
15490 /*ARGSUSED*/
15491 mblk_t *
15492 ip_accept_tcp(ill_t *ill, ill_rx_ring_t *ip_ring, squeue_t *target_sqp,
15493     mblk_t *mp_chain, mblk_t **last, uint_t *cnt)
15494 {
15495 	mblk_t 		*mp;
15496 	ipaddr_t	dst = NULL;
15497 	ipaddr_t	prev_dst;
15498 	ire_t		*ire = NULL;
15499 	ipha_t		*ipha;
15500 	uint_t		pkt_len;
15501 	ssize_t		len;
15502 	uint_t		opt_len;
15503 	queue_t		*q = ill->ill_rq;
15504 	squeue_t	*curr_sqp;
15505 	mblk_t 		*ahead = NULL;	/* Accepted head */
15506 	mblk_t		*atail = NULL;	/* Accepted tail */
15507 	uint_t		acnt = 0;	/* Accepted count */
15508 	mblk_t		*utail = NULL;	/* Unaccepted head */
15509 	mblk_t		*uhead = NULL;	/* Unaccepted tail */
15510 	uint_t		ucnt = 0;	/* Unaccepted cnt */
15511 	ip_stack_t	*ipst = ill->ill_ipst;
15512 
15513 	*cnt = 0;
15514 
15515 	ASSERT(ill != NULL);
15516 	ASSERT(ip_ring != NULL);
15517 
15518 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_accept_tcp: q %p", q);
15519 
15520 #define	rptr	((uchar_t *)ipha)
15521 
15522 	while (mp_chain != NULL) {
15523 		mp = mp_chain;
15524 		mp_chain = mp_chain->b_next;
15525 		mp->b_next = NULL;
15526 
15527 		/*
15528 		 * We do ire caching from one iteration to
15529 		 * another. In the event the packet chain contains
15530 		 * all packets from the same dst, this caching saves
15531 		 * an ire_cache_lookup for each of the succeeding
15532 		 * packets in a packet chain.
15533 		 */
15534 		prev_dst = dst;
15535 
15536 		ipha = (ipha_t *)mp->b_rptr;
15537 		len = mp->b_wptr - rptr;
15538 
15539 		ASSERT(!MBLK_RX_FANOUT_SLOWPATH(mp, ipha));
15540 
15541 		/*
15542 		 * If it is a non TCP packet, or doesn't have H/W cksum,
15543 		 * or doesn't have min len, reject.
15544 		 */
15545 		if ((ipha->ipha_protocol != IPPROTO_TCP) || (len <
15546 		    (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH))) {
15547 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15548 			continue;
15549 		}
15550 
15551 		pkt_len = ntohs(ipha->ipha_length);
15552 		if (len != pkt_len) {
15553 			if (len > pkt_len) {
15554 				mp->b_wptr = rptr + pkt_len;
15555 			} else {
15556 				ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15557 				continue;
15558 			}
15559 		}
15560 
15561 		opt_len = ipha->ipha_version_and_hdr_length -
15562 		    IP_SIMPLE_HDR_VERSION;
15563 		dst = ipha->ipha_dst;
15564 
15565 		/* IP version bad or there are IP options */
15566 		if (opt_len && (!ip_rput_multimblk_ipoptions(q, ill,
15567 		    mp, &ipha, &dst, ipst)))
15568 			continue;
15569 
15570 		if (is_system_labeled() || (ill->ill_dhcpinit != 0) ||
15571 		    (ipst->ips_ip_cgtp_filter &&
15572 		    ipst->ips_ip_cgtp_filter_ops != NULL)) {
15573 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15574 			continue;
15575 		}
15576 
15577 		/*
15578 		 * Reuse the cached ire only if the ipha_dst of the previous
15579 		 * packet is the same as the current packet AND it is not
15580 		 * INADDR_ANY.
15581 		 */
15582 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15583 		    (ire != NULL)) {
15584 			ire_refrele(ire);
15585 			ire = NULL;
15586 		}
15587 
15588 		if (ire == NULL)
15589 			ire = ire_cache_lookup_simple(dst, ipst);
15590 
15591 		/*
15592 		 * Unless forwarding is enabled, dont call
15593 		 * ip_fast_forward(). Incoming packet is for forwarding
15594 		 */
15595 		if ((ill->ill_flags & ILLF_ROUTER) &&
15596 		    (ire == NULL || (ire->ire_type & IRE_CACHE))) {
15597 
15598 			DTRACE_PROBE4(ip4__physical__in__start,
15599 			    ill_t *, ill, ill_t *, NULL,
15600 			    ipha_t *, ipha, mblk_t *, mp);
15601 
15602 			FW_HOOKS(ipst->ips_ip4_physical_in_event,
15603 			    ipst->ips_ipv4firewall_physical_in,
15604 			    ill, NULL, ipha, mp, mp, 0, ipst);
15605 
15606 			DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15607 
15608 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15609 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets,
15610 			    pkt_len);
15611 
15612 			ire = ip_fast_forward(ire, dst, ill, mp);
15613 			continue;
15614 		}
15615 
15616 		/* incoming packet is for local consumption */
15617 		if ((ire != NULL) && (ire->ire_type & IRE_LOCAL))
15618 			goto local_accept;
15619 
15620 		/*
15621 		 * Disable ire caching for anything more complex
15622 		 * than the simple fast path case we checked for above.
15623 		 */
15624 		if (ire != NULL) {
15625 			ire_refrele(ire);
15626 			ire = NULL;
15627 		}
15628 
15629 		ire = ire_cache_lookup(dst, ALL_ZONES, MBLK_GETLABEL(mp),
15630 		    ipst);
15631 		if (ire == NULL || ire->ire_type == IRE_BROADCAST ||
15632 		    ire->ire_stq != NULL) {
15633 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15634 			if (ire != NULL) {
15635 				ire_refrele(ire);
15636 				ire = NULL;
15637 			}
15638 			continue;
15639 		}
15640 
15641 local_accept:
15642 
15643 		if (ire->ire_rfq != q) {
15644 			ADD_TO_CHAIN(uhead, utail, ucnt, mp);
15645 			if (ire != NULL) {
15646 				ire_refrele(ire);
15647 				ire = NULL;
15648 			}
15649 			continue;
15650 		}
15651 
15652 		/*
15653 		 * The event for packets being received from a 'physical'
15654 		 * interface is placed after validation of the source and/or
15655 		 * destination address as being local so that packets can be
15656 		 * redirected to loopback addresses using ipnat.
15657 		 */
15658 		DTRACE_PROBE4(ip4__physical__in__start,
15659 		    ill_t *, ill, ill_t *, NULL,
15660 		    ipha_t *, ipha, mblk_t *, mp);
15661 
15662 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15663 		    ipst->ips_ipv4firewall_physical_in,
15664 		    ill, NULL, ipha, mp, mp, 0, ipst);
15665 
15666 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, mp);
15667 
15668 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15669 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15670 
15671 		if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire, mp,
15672 		    0, q, ip_ring)) != NULL) {
15673 			if ((curr_sqp = GET_SQUEUE(mp)) == target_sqp) {
15674 				ADD_TO_CHAIN(ahead, atail, acnt, mp);
15675 			} else {
15676 				SQUEUE_ENTER(curr_sqp, mp, mp, 1,
15677 				    SQ_FILL, SQTAG_IP_INPUT);
15678 			}
15679 		}
15680 	}
15681 
15682 	if (ire != NULL)
15683 		ire_refrele(ire);
15684 
15685 	if (uhead != NULL)
15686 		ip_input(ill, ip_ring, uhead, NULL);
15687 
15688 	if (ahead != NULL) {
15689 		*last = atail;
15690 		*cnt = acnt;
15691 		return (ahead);
15692 	}
15693 
15694 	return (NULL);
15695 #undef  rptr
15696 }
15697 
15698 static void
15699 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15700     t_uscalar_t err)
15701 {
15702 	if (dl_err == DL_SYSERR) {
15703 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15704 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15705 		    ill->ill_name, dl_primstr(prim), err);
15706 		return;
15707 	}
15708 
15709 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15710 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15711 	    dl_errstr(dl_err));
15712 }
15713 
15714 /*
15715  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15716  * than DL_UNITDATA_IND messages. If we need to process this message
15717  * exclusively, we call qwriter_ip, in which case we also need to call
15718  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15719  */
15720 void
15721 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15722 {
15723 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15724 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15725 	ill_t		*ill = q->q_ptr;
15726 	t_uscalar_t	prim = dloa->dl_primitive;
15727 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15728 
15729 	ip1dbg(("ip_rput_dlpi"));
15730 
15731 	/*
15732 	 * If we received an ACK but didn't send a request for it, then it
15733 	 * can't be part of any pending operation; discard up-front.
15734 	 */
15735 	switch (prim) {
15736 	case DL_ERROR_ACK:
15737 		reqprim = dlea->dl_error_primitive;
15738 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15739 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15740 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15741 		    dlea->dl_unix_errno));
15742 		break;
15743 	case DL_OK_ACK:
15744 		reqprim = dloa->dl_correct_primitive;
15745 		break;
15746 	case DL_INFO_ACK:
15747 		reqprim = DL_INFO_REQ;
15748 		break;
15749 	case DL_BIND_ACK:
15750 		reqprim = DL_BIND_REQ;
15751 		break;
15752 	case DL_PHYS_ADDR_ACK:
15753 		reqprim = DL_PHYS_ADDR_REQ;
15754 		break;
15755 	case DL_NOTIFY_ACK:
15756 		reqprim = DL_NOTIFY_REQ;
15757 		break;
15758 	case DL_CONTROL_ACK:
15759 		reqprim = DL_CONTROL_REQ;
15760 		break;
15761 	case DL_CAPABILITY_ACK:
15762 		reqprim = DL_CAPABILITY_REQ;
15763 		break;
15764 	}
15765 
15766 	if (prim != DL_NOTIFY_IND) {
15767 		if (reqprim == DL_PRIM_INVAL ||
15768 		    !ill_dlpi_pending(ill, reqprim)) {
15769 			/* Not a DLPI message we support or expected */
15770 			freemsg(mp);
15771 			return;
15772 		}
15773 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15774 		    dl_primstr(reqprim)));
15775 	}
15776 
15777 	switch (reqprim) {
15778 	case DL_UNBIND_REQ:
15779 		/*
15780 		 * NOTE: we mark the unbind as complete even if we got a
15781 		 * DL_ERROR_ACK, since there's not much else we can do.
15782 		 */
15783 		mutex_enter(&ill->ill_lock);
15784 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15785 		cv_signal(&ill->ill_cv);
15786 		mutex_exit(&ill->ill_lock);
15787 		break;
15788 
15789 	case DL_ENABMULTI_REQ:
15790 		if (prim == DL_OK_ACK) {
15791 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15792 				ill->ill_dlpi_multicast_state = IDS_OK;
15793 		}
15794 		break;
15795 	}
15796 
15797 	/*
15798 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15799 	 * need to become writer to continue to process it.  Because an
15800 	 * exclusive operation doesn't complete until replies to all queued
15801 	 * DLPI messages have been received, we know we're in the middle of an
15802 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15803 	 *
15804 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15805 	 * Since this is on the ill stream we unconditionally bump up the
15806 	 * refcount without doing ILL_CAN_LOOKUP().
15807 	 */
15808 	ill_refhold(ill);
15809 	if (prim == DL_NOTIFY_IND)
15810 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15811 	else
15812 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15813 }
15814 
15815 /*
15816  * Handling of DLPI messages that require exclusive access to the ipsq.
15817  *
15818  * Need to do ill_pending_mp_release on ioctl completion, which could
15819  * happen here. (along with mi_copy_done)
15820  */
15821 /* ARGSUSED */
15822 static void
15823 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15824 {
15825 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15826 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15827 	int		err = 0;
15828 	ill_t		*ill;
15829 	ipif_t		*ipif = NULL;
15830 	mblk_t		*mp1 = NULL;
15831 	conn_t		*connp = NULL;
15832 	t_uscalar_t	paddrreq;
15833 	mblk_t		*mp_hw;
15834 	boolean_t	success;
15835 	boolean_t	ioctl_aborted = B_FALSE;
15836 	boolean_t	log = B_TRUE;
15837 	ip_stack_t		*ipst;
15838 
15839 	ip1dbg(("ip_rput_dlpi_writer .."));
15840 	ill = (ill_t *)q->q_ptr;
15841 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15842 
15843 	ASSERT(IAM_WRITER_ILL(ill));
15844 
15845 	ipst = ill->ill_ipst;
15846 
15847 	/*
15848 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15849 	 * both are null or non-null. However we can assert that only
15850 	 * after grabbing the ipsq_lock. So we don't make any assertion
15851 	 * here and in other places in the code.
15852 	 */
15853 	ipif = ipsq->ipsq_pending_ipif;
15854 	/*
15855 	 * The current ioctl could have been aborted by the user and a new
15856 	 * ioctl to bring up another ill could have started. We could still
15857 	 * get a response from the driver later.
15858 	 */
15859 	if (ipif != NULL && ipif->ipif_ill != ill)
15860 		ioctl_aborted = B_TRUE;
15861 
15862 	switch (dloa->dl_primitive) {
15863 	case DL_ERROR_ACK:
15864 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15865 		    dl_primstr(dlea->dl_error_primitive)));
15866 
15867 		switch (dlea->dl_error_primitive) {
15868 		case DL_DISABMULTI_REQ:
15869 			if (!ill->ill_isv6)
15870 				ipsq_current_finish(ipsq);
15871 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15872 			break;
15873 		case DL_PROMISCON_REQ:
15874 		case DL_PROMISCOFF_REQ:
15875 		case DL_UNBIND_REQ:
15876 		case DL_ATTACH_REQ:
15877 		case DL_INFO_REQ:
15878 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15879 			break;
15880 		case DL_NOTIFY_REQ:
15881 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15882 			log = B_FALSE;
15883 			break;
15884 		case DL_PHYS_ADDR_REQ:
15885 			/*
15886 			 * For IPv6 only, there are two additional
15887 			 * phys_addr_req's sent to the driver to get the
15888 			 * IPv6 token and lla. This allows IP to acquire
15889 			 * the hardware address format for a given interface
15890 			 * without having built in knowledge of the hardware
15891 			 * address. ill_phys_addr_pend keeps track of the last
15892 			 * DL_PAR sent so we know which response we are
15893 			 * dealing with. ill_dlpi_done will update
15894 			 * ill_phys_addr_pend when it sends the next req.
15895 			 * We don't complete the IOCTL until all three DL_PARs
15896 			 * have been attempted, so set *_len to 0 and break.
15897 			 */
15898 			paddrreq = ill->ill_phys_addr_pend;
15899 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15900 			if (paddrreq == DL_IPV6_TOKEN) {
15901 				ill->ill_token_length = 0;
15902 				log = B_FALSE;
15903 				break;
15904 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15905 				ill->ill_nd_lla_len = 0;
15906 				log = B_FALSE;
15907 				break;
15908 			}
15909 			/*
15910 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15911 			 * We presumably have an IOCTL hanging out waiting
15912 			 * for completion. Find it and complete the IOCTL
15913 			 * with the error noted.
15914 			 * However, ill_dl_phys was called on an ill queue
15915 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15916 			 * set. But the ioctl is known to be pending on ill_wq.
15917 			 */
15918 			if (!ill->ill_ifname_pending)
15919 				break;
15920 			ill->ill_ifname_pending = 0;
15921 			if (!ioctl_aborted)
15922 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15923 			if (mp1 != NULL) {
15924 				/*
15925 				 * This operation (SIOCSLIFNAME) must have
15926 				 * happened on the ill. Assert there is no conn
15927 				 */
15928 				ASSERT(connp == NULL);
15929 				q = ill->ill_wq;
15930 			}
15931 			break;
15932 		case DL_BIND_REQ:
15933 			ill_dlpi_done(ill, DL_BIND_REQ);
15934 			if (ill->ill_ifname_pending)
15935 				break;
15936 			/*
15937 			 * Something went wrong with the bind.  We presumably
15938 			 * have an IOCTL hanging out waiting for completion.
15939 			 * Find it, take down the interface that was coming
15940 			 * up, and complete the IOCTL with the error noted.
15941 			 */
15942 			if (!ioctl_aborted)
15943 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15944 			if (mp1 != NULL) {
15945 				/*
15946 				 * This operation (SIOCSLIFFLAGS) must have
15947 				 * happened from a conn.
15948 				 */
15949 				ASSERT(connp != NULL);
15950 				q = CONNP_TO_WQ(connp);
15951 				if (ill->ill_move_in_progress) {
15952 					ILL_CLEAR_MOVE(ill);
15953 				}
15954 				(void) ipif_down(ipif, NULL, NULL);
15955 				/* error is set below the switch */
15956 			}
15957 			break;
15958 		case DL_ENABMULTI_REQ:
15959 			if (!ill->ill_isv6)
15960 				ipsq_current_finish(ipsq);
15961 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15962 
15963 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15964 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15965 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15966 				ipif_t *ipif;
15967 
15968 				printf("ip: joining multicasts failed (%d)"
15969 				    " on %s - will use link layer "
15970 				    "broadcasts for multicast\n",
15971 				    dlea->dl_errno, ill->ill_name);
15972 
15973 				/*
15974 				 * Set up the multicast mapping alone.
15975 				 * writer, so ok to access ill->ill_ipif
15976 				 * without any lock.
15977 				 */
15978 				ipif = ill->ill_ipif;
15979 				mutex_enter(&ill->ill_phyint->phyint_lock);
15980 				ill->ill_phyint->phyint_flags |=
15981 				    PHYI_MULTI_BCAST;
15982 				mutex_exit(&ill->ill_phyint->phyint_lock);
15983 
15984 				if (!ill->ill_isv6) {
15985 					(void) ipif_arp_setup_multicast(ipif,
15986 					    NULL);
15987 				} else {
15988 					(void) ipif_ndp_setup_multicast(ipif,
15989 					    NULL);
15990 				}
15991 			}
15992 			freemsg(mp);	/* Don't want to pass this up */
15993 			return;
15994 		case DL_CONTROL_REQ:
15995 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15996 			    "DL_CONTROL_REQ\n"));
15997 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15998 			freemsg(mp);
15999 			return;
16000 		case DL_CAPABILITY_REQ:
16001 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
16002 			    "DL_CAPABILITY REQ\n"));
16003 			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
16004 				ill->ill_dlpi_capab_state = IDCS_FAILED;
16005 			ill_capability_done(ill);
16006 			freemsg(mp);
16007 			return;
16008 		}
16009 		/*
16010 		 * Note the error for IOCTL completion (mp1 is set when
16011 		 * ready to complete ioctl). If ill_ifname_pending_err is
16012 		 * set, an error occured during plumbing (ill_ifname_pending),
16013 		 * so we want to report that error.
16014 		 *
16015 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
16016 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
16017 		 * expected to get errack'd if the driver doesn't support
16018 		 * these flags (e.g. ethernet). log will be set to B_FALSE
16019 		 * if these error conditions are encountered.
16020 		 */
16021 		if (mp1 != NULL) {
16022 			if (ill->ill_ifname_pending_err != 0)  {
16023 				err = ill->ill_ifname_pending_err;
16024 				ill->ill_ifname_pending_err = 0;
16025 			} else {
16026 				err = dlea->dl_unix_errno ?
16027 				    dlea->dl_unix_errno : ENXIO;
16028 			}
16029 		/*
16030 		 * If we're plumbing an interface and an error hasn't already
16031 		 * been saved, set ill_ifname_pending_err to the error passed
16032 		 * up. Ignore the error if log is B_FALSE (see comment above).
16033 		 */
16034 		} else if (log && ill->ill_ifname_pending &&
16035 		    ill->ill_ifname_pending_err == 0) {
16036 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
16037 			    dlea->dl_unix_errno : ENXIO;
16038 		}
16039 
16040 		if (log)
16041 			ip_dlpi_error(ill, dlea->dl_error_primitive,
16042 			    dlea->dl_errno, dlea->dl_unix_errno);
16043 		break;
16044 	case DL_CAPABILITY_ACK:
16045 		ill_capability_ack(ill, mp);
16046 		/*
16047 		 * The message has been handed off to ill_capability_ack
16048 		 * and must not be freed below
16049 		 */
16050 		mp = NULL;
16051 		break;
16052 
16053 	case DL_CONTROL_ACK:
16054 		/* We treat all of these as "fire and forget" */
16055 		ill_dlpi_done(ill, DL_CONTROL_REQ);
16056 		break;
16057 	case DL_INFO_ACK:
16058 		/* Call a routine to handle this one. */
16059 		ill_dlpi_done(ill, DL_INFO_REQ);
16060 		ip_ll_subnet_defaults(ill, mp);
16061 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
16062 		return;
16063 	case DL_BIND_ACK:
16064 		/*
16065 		 * We should have an IOCTL waiting on this unless
16066 		 * sent by ill_dl_phys, in which case just return
16067 		 */
16068 		ill_dlpi_done(ill, DL_BIND_REQ);
16069 		if (ill->ill_ifname_pending)
16070 			break;
16071 
16072 		if (!ioctl_aborted)
16073 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16074 		if (mp1 == NULL)
16075 			break;
16076 		/*
16077 		 * Because mp1 was added by ill_dl_up(), and it always
16078 		 * passes a valid connp, connp must be valid here.
16079 		 */
16080 		ASSERT(connp != NULL);
16081 		q = CONNP_TO_WQ(connp);
16082 
16083 		/*
16084 		 * We are exclusive. So nothing can change even after
16085 		 * we get the pending mp. If need be we can put it back
16086 		 * and restart, as in calling ipif_arp_up()  below.
16087 		 */
16088 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
16089 
16090 		mutex_enter(&ill->ill_lock);
16091 		ill->ill_dl_up = 1;
16092 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
16093 		mutex_exit(&ill->ill_lock);
16094 
16095 		/*
16096 		 * Now bring up the resolver; when that is complete, we'll
16097 		 * create IREs.  Note that we intentionally mirror what
16098 		 * ipif_up() would have done, because we got here by way of
16099 		 * ill_dl_up(), which stopped ipif_up()'s processing.
16100 		 */
16101 		if (ill->ill_isv6) {
16102 			/*
16103 			 * v6 interfaces.
16104 			 * Unlike ARP which has to do another bind
16105 			 * and attach, once we get here we are
16106 			 * done with NDP. Except in the case of
16107 			 * ILLF_XRESOLV, in which case we send an
16108 			 * AR_INTERFACE_UP to the external resolver.
16109 			 * If all goes well, the ioctl will complete
16110 			 * in ip_rput(). If there's an error, we
16111 			 * complete it here.
16112 			 */
16113 			if ((err = ipif_ndp_up(ipif)) == 0) {
16114 				if (ill->ill_flags & ILLF_XRESOLV) {
16115 					mutex_enter(&connp->conn_lock);
16116 					mutex_enter(&ill->ill_lock);
16117 					success = ipsq_pending_mp_add(
16118 					    connp, ipif, q, mp1, 0);
16119 					mutex_exit(&ill->ill_lock);
16120 					mutex_exit(&connp->conn_lock);
16121 					if (success) {
16122 						err = ipif_resolver_up(ipif,
16123 						    Res_act_initial);
16124 						if (err == EINPROGRESS) {
16125 							freemsg(mp);
16126 							return;
16127 						}
16128 						ASSERT(err != 0);
16129 						mp1 = ipsq_pending_mp_get(ipsq,
16130 						    &connp);
16131 						ASSERT(mp1 != NULL);
16132 					} else {
16133 						/* conn has started closing */
16134 						err = EINTR;
16135 					}
16136 				} else { /* Non XRESOLV interface */
16137 					(void) ipif_resolver_up(ipif,
16138 					    Res_act_initial);
16139 					err = ipif_up_done_v6(ipif);
16140 				}
16141 			}
16142 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16143 			/*
16144 			 * ARP and other v4 external resolvers.
16145 			 * Leave the pending mblk intact so that
16146 			 * the ioctl completes in ip_rput().
16147 			 */
16148 			mutex_enter(&connp->conn_lock);
16149 			mutex_enter(&ill->ill_lock);
16150 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16151 			mutex_exit(&ill->ill_lock);
16152 			mutex_exit(&connp->conn_lock);
16153 			if (success) {
16154 				err = ipif_resolver_up(ipif, Res_act_initial);
16155 				if (err == EINPROGRESS) {
16156 					freemsg(mp);
16157 					return;
16158 				}
16159 				ASSERT(err != 0);
16160 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16161 			} else {
16162 				/* The conn has started closing */
16163 				err = EINTR;
16164 			}
16165 		} else {
16166 			/*
16167 			 * This one is complete. Reply to pending ioctl.
16168 			 */
16169 			(void) ipif_resolver_up(ipif, Res_act_initial);
16170 			err = ipif_up_done(ipif);
16171 		}
16172 
16173 		if ((err == 0) && (ill->ill_up_ipifs)) {
16174 			err = ill_up_ipifs(ill, q, mp1);
16175 			if (err == EINPROGRESS) {
16176 				freemsg(mp);
16177 				return;
16178 			}
16179 		}
16180 
16181 		if (ill->ill_up_ipifs) {
16182 			ill_group_cleanup(ill);
16183 		}
16184 
16185 		break;
16186 	case DL_NOTIFY_IND: {
16187 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16188 		ire_t *ire;
16189 		boolean_t need_ire_walk_v4 = B_FALSE;
16190 		boolean_t need_ire_walk_v6 = B_FALSE;
16191 
16192 		switch (notify->dl_notification) {
16193 		case DL_NOTE_PHYS_ADDR:
16194 			err = ill_set_phys_addr(ill, mp);
16195 			break;
16196 
16197 		case DL_NOTE_FASTPATH_FLUSH:
16198 			ill_fastpath_flush(ill);
16199 			break;
16200 
16201 		case DL_NOTE_SDU_SIZE:
16202 			/*
16203 			 * Change the MTU size of the interface, of all
16204 			 * attached ipif's, and of all relevant ire's.  The
16205 			 * new value's a uint32_t at notify->dl_data.
16206 			 * Mtu change Vs. new ire creation - protocol below.
16207 			 *
16208 			 * a Mark the ipif as IPIF_CHANGING.
16209 			 * b Set the new mtu in the ipif.
16210 			 * c Change the ire_max_frag on all affected ires
16211 			 * d Unmark the IPIF_CHANGING
16212 			 *
16213 			 * To see how the protocol works, assume an interface
16214 			 * route is also being added simultaneously by
16215 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16216 			 * the ire. If the ire is created before step a,
16217 			 * it will be cleaned up by step c. If the ire is
16218 			 * created after step d, it will see the new value of
16219 			 * ipif_mtu. Any attempt to create the ire between
16220 			 * steps a to d will fail because of the IPIF_CHANGING
16221 			 * flag. Note that ire_create() is passed a pointer to
16222 			 * the ipif_mtu, and not the value. During ire_add
16223 			 * under the bucket lock, the ire_max_frag of the
16224 			 * new ire being created is set from the ipif/ire from
16225 			 * which it is being derived.
16226 			 */
16227 			mutex_enter(&ill->ill_lock);
16228 			ill->ill_max_frag = (uint_t)notify->dl_data;
16229 
16230 			/*
16231 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16232 			 * leave it alone
16233 			 */
16234 			if (ill->ill_mtu_userspecified) {
16235 				mutex_exit(&ill->ill_lock);
16236 				break;
16237 			}
16238 			ill->ill_max_mtu = ill->ill_max_frag;
16239 			if (ill->ill_isv6) {
16240 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16241 					ill->ill_max_mtu = IPV6_MIN_MTU;
16242 			} else {
16243 				if (ill->ill_max_mtu < IP_MIN_MTU)
16244 					ill->ill_max_mtu = IP_MIN_MTU;
16245 			}
16246 			for (ipif = ill->ill_ipif; ipif != NULL;
16247 			    ipif = ipif->ipif_next) {
16248 				/*
16249 				 * Don't override the mtu if the user
16250 				 * has explicitly set it.
16251 				 */
16252 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16253 					continue;
16254 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16255 				if (ipif->ipif_isv6)
16256 					ire = ipif_to_ire_v6(ipif);
16257 				else
16258 					ire = ipif_to_ire(ipif);
16259 				if (ire != NULL) {
16260 					ire->ire_max_frag = ipif->ipif_mtu;
16261 					ire_refrele(ire);
16262 				}
16263 				if (ipif->ipif_flags & IPIF_UP) {
16264 					if (ill->ill_isv6)
16265 						need_ire_walk_v6 = B_TRUE;
16266 					else
16267 						need_ire_walk_v4 = B_TRUE;
16268 				}
16269 			}
16270 			mutex_exit(&ill->ill_lock);
16271 			if (need_ire_walk_v4)
16272 				ire_walk_v4(ill_mtu_change, (char *)ill,
16273 				    ALL_ZONES, ipst);
16274 			if (need_ire_walk_v6)
16275 				ire_walk_v6(ill_mtu_change, (char *)ill,
16276 				    ALL_ZONES, ipst);
16277 			break;
16278 		case DL_NOTE_LINK_UP:
16279 		case DL_NOTE_LINK_DOWN: {
16280 			/*
16281 			 * We are writer. ill / phyint / ipsq assocs stable.
16282 			 * The RUNNING flag reflects the state of the link.
16283 			 */
16284 			phyint_t *phyint = ill->ill_phyint;
16285 			uint64_t new_phyint_flags;
16286 			boolean_t changed = B_FALSE;
16287 			boolean_t went_up;
16288 
16289 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16290 			mutex_enter(&phyint->phyint_lock);
16291 			new_phyint_flags = went_up ?
16292 			    phyint->phyint_flags | PHYI_RUNNING :
16293 			    phyint->phyint_flags & ~PHYI_RUNNING;
16294 			if (new_phyint_flags != phyint->phyint_flags) {
16295 				phyint->phyint_flags = new_phyint_flags;
16296 				changed = B_TRUE;
16297 			}
16298 			mutex_exit(&phyint->phyint_lock);
16299 			/*
16300 			 * ill_restart_dad handles the DAD restart and routing
16301 			 * socket notification logic.
16302 			 */
16303 			if (changed) {
16304 				ill_restart_dad(phyint->phyint_illv4, went_up);
16305 				ill_restart_dad(phyint->phyint_illv6, went_up);
16306 			}
16307 			break;
16308 		}
16309 		case DL_NOTE_PROMISC_ON_PHYS:
16310 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16311 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16312 			mutex_enter(&ill->ill_lock);
16313 			ill->ill_promisc_on_phys = B_TRUE;
16314 			mutex_exit(&ill->ill_lock);
16315 			break;
16316 		case DL_NOTE_PROMISC_OFF_PHYS:
16317 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16318 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16319 			mutex_enter(&ill->ill_lock);
16320 			ill->ill_promisc_on_phys = B_FALSE;
16321 			mutex_exit(&ill->ill_lock);
16322 			break;
16323 		case DL_NOTE_CAPAB_RENEG:
16324 			/*
16325 			 * Something changed on the driver side.
16326 			 * It wants us to renegotiate the capabilities
16327 			 * on this ill. One possible cause is the aggregation
16328 			 * interface under us where a port got added or
16329 			 * went away.
16330 			 *
16331 			 * If the capability negotiation is already done
16332 			 * or is in progress, reset the capabilities and
16333 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16334 			 * so that when the ack comes back, we can start
16335 			 * the renegotiation process.
16336 			 *
16337 			 * Note that if ill_capab_reneg is already B_TRUE
16338 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16339 			 * the capability resetting request has been sent
16340 			 * and the renegotiation has not been started yet;
16341 			 * nothing needs to be done in this case.
16342 			 */
16343 			ipsq_current_start(ipsq, ill->ill_ipif, 0);
16344 			ill_capability_reset(ill, B_TRUE);
16345 			ipsq_current_finish(ipsq);
16346 			break;
16347 		default:
16348 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16349 			    "type 0x%x for DL_NOTIFY_IND\n",
16350 			    notify->dl_notification));
16351 			break;
16352 		}
16353 
16354 		/*
16355 		 * As this is an asynchronous operation, we
16356 		 * should not call ill_dlpi_done
16357 		 */
16358 		break;
16359 	}
16360 	case DL_NOTIFY_ACK: {
16361 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16362 
16363 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16364 			ill->ill_note_link = 1;
16365 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16366 		break;
16367 	}
16368 	case DL_PHYS_ADDR_ACK: {
16369 		/*
16370 		 * As part of plumbing the interface via SIOCSLIFNAME,
16371 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16372 		 * whose answers we receive here.  As each answer is received,
16373 		 * we call ill_dlpi_done() to dispatch the next request as
16374 		 * we're processing the current one.  Once all answers have
16375 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16376 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16377 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16378 		 * available, but we know the ioctl is pending on ill_wq.)
16379 		 */
16380 		uint_t paddrlen, paddroff;
16381 
16382 		paddrreq = ill->ill_phys_addr_pend;
16383 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16384 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16385 
16386 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16387 		if (paddrreq == DL_IPV6_TOKEN) {
16388 			/*
16389 			 * bcopy to low-order bits of ill_token
16390 			 *
16391 			 * XXX Temporary hack - currently, all known tokens
16392 			 * are 64 bits, so I'll cheat for the moment.
16393 			 */
16394 			bcopy(mp->b_rptr + paddroff,
16395 			    &ill->ill_token.s6_addr32[2], paddrlen);
16396 			ill->ill_token_length = paddrlen;
16397 			break;
16398 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16399 			ASSERT(ill->ill_nd_lla_mp == NULL);
16400 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16401 			mp = NULL;
16402 			break;
16403 		}
16404 
16405 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16406 		ASSERT(ill->ill_phys_addr_mp == NULL);
16407 		if (!ill->ill_ifname_pending)
16408 			break;
16409 		ill->ill_ifname_pending = 0;
16410 		if (!ioctl_aborted)
16411 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16412 		if (mp1 != NULL) {
16413 			ASSERT(connp == NULL);
16414 			q = ill->ill_wq;
16415 		}
16416 		/*
16417 		 * If any error acks received during the plumbing sequence,
16418 		 * ill_ifname_pending_err will be set. Break out and send up
16419 		 * the error to the pending ioctl.
16420 		 */
16421 		if (ill->ill_ifname_pending_err != 0) {
16422 			err = ill->ill_ifname_pending_err;
16423 			ill->ill_ifname_pending_err = 0;
16424 			break;
16425 		}
16426 
16427 		ill->ill_phys_addr_mp = mp;
16428 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16429 		mp = NULL;
16430 
16431 		/*
16432 		 * If paddrlen is zero, the DLPI provider doesn't support
16433 		 * physical addresses.  The other two tests were historical
16434 		 * workarounds for bugs in our former PPP implementation, but
16435 		 * now other things have grown dependencies on them -- e.g.,
16436 		 * the tun module specifies a dl_addr_length of zero in its
16437 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16438 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16439 		 * but only after careful testing ensures that all dependent
16440 		 * broken DLPI providers have been fixed.
16441 		 */
16442 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16443 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16444 			ill->ill_phys_addr = NULL;
16445 		} else if (paddrlen != ill->ill_phys_addr_length) {
16446 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16447 			    paddrlen, ill->ill_phys_addr_length));
16448 			err = EINVAL;
16449 			break;
16450 		}
16451 
16452 		if (ill->ill_nd_lla_mp == NULL) {
16453 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16454 				err = ENOMEM;
16455 				break;
16456 			}
16457 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16458 		}
16459 
16460 		/*
16461 		 * Set the interface token.  If the zeroth interface address
16462 		 * is unspecified, then set it to the link local address.
16463 		 */
16464 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16465 			(void) ill_setdefaulttoken(ill);
16466 
16467 		ASSERT(ill->ill_ipif->ipif_id == 0);
16468 		if (ipif != NULL &&
16469 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16470 			(void) ipif_setlinklocal(ipif);
16471 		}
16472 		break;
16473 	}
16474 	case DL_OK_ACK:
16475 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16476 		    dl_primstr((int)dloa->dl_correct_primitive),
16477 		    dloa->dl_correct_primitive));
16478 		switch (dloa->dl_correct_primitive) {
16479 		case DL_ENABMULTI_REQ:
16480 		case DL_DISABMULTI_REQ:
16481 			if (!ill->ill_isv6)
16482 				ipsq_current_finish(ipsq);
16483 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16484 			break;
16485 		case DL_PROMISCON_REQ:
16486 		case DL_PROMISCOFF_REQ:
16487 		case DL_UNBIND_REQ:
16488 		case DL_ATTACH_REQ:
16489 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16490 			break;
16491 		}
16492 		break;
16493 	default:
16494 		break;
16495 	}
16496 
16497 	freemsg(mp);
16498 	if (mp1 != NULL) {
16499 		/*
16500 		 * The operation must complete without EINPROGRESS
16501 		 * since ipsq_pending_mp_get() has removed the mblk
16502 		 * from ipsq_pending_mp.  Otherwise, the operation
16503 		 * will be stuck forever in the ipsq.
16504 		 */
16505 		ASSERT(err != EINPROGRESS);
16506 
16507 		switch (ipsq->ipsq_current_ioctl) {
16508 		case 0:
16509 			ipsq_current_finish(ipsq);
16510 			break;
16511 
16512 		case SIOCLIFADDIF:
16513 		case SIOCSLIFNAME:
16514 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16515 			break;
16516 
16517 		default:
16518 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16519 			break;
16520 		}
16521 	}
16522 }
16523 
16524 /*
16525  * ip_rput_other is called by ip_rput to handle messages modifying the global
16526  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16527  */
16528 /* ARGSUSED */
16529 void
16530 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16531 {
16532 	ill_t		*ill;
16533 	struct iocblk	*iocp;
16534 	mblk_t		*mp1;
16535 	conn_t		*connp = NULL;
16536 
16537 	ip1dbg(("ip_rput_other "));
16538 	ill = (ill_t *)q->q_ptr;
16539 	/*
16540 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16541 	 * in which case ipsq is NULL.
16542 	 */
16543 	if (ipsq != NULL) {
16544 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16545 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16546 	}
16547 
16548 	switch (mp->b_datap->db_type) {
16549 	case M_ERROR:
16550 	case M_HANGUP:
16551 		/*
16552 		 * The device has a problem.  We force the ILL down.  It can
16553 		 * be brought up again manually using SIOCSIFFLAGS (via
16554 		 * ifconfig or equivalent).
16555 		 */
16556 		ASSERT(ipsq != NULL);
16557 		if (mp->b_rptr < mp->b_wptr)
16558 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16559 		if (ill->ill_error == 0)
16560 			ill->ill_error = ENXIO;
16561 		if (!ill_down_start(q, mp))
16562 			return;
16563 		ipif_all_down_tail(ipsq, q, mp, NULL);
16564 		break;
16565 	case M_IOCACK:
16566 		iocp = (struct iocblk *)mp->b_rptr;
16567 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16568 		switch (iocp->ioc_cmd) {
16569 		case SIOCSTUNPARAM:
16570 		case OSIOCSTUNPARAM:
16571 			ASSERT(ipsq != NULL);
16572 			/*
16573 			 * Finish socket ioctl passed through to tun.
16574 			 * We should have an IOCTL waiting on this.
16575 			 */
16576 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16577 			if (ill->ill_isv6) {
16578 				struct iftun_req *ta;
16579 
16580 				/*
16581 				 * if a source or destination is
16582 				 * being set, try and set the link
16583 				 * local address for the tunnel
16584 				 */
16585 				ta = (struct iftun_req *)mp->b_cont->
16586 				    b_cont->b_rptr;
16587 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16588 					ipif_set_tun_llink(ill, ta);
16589 				}
16590 
16591 			}
16592 			if (mp1 != NULL) {
16593 				/*
16594 				 * Now copy back the b_next/b_prev used by
16595 				 * mi code for the mi_copy* functions.
16596 				 * See ip_sioctl_tunparam() for the reason.
16597 				 * Also protect against missing b_cont.
16598 				 */
16599 				if (mp->b_cont != NULL) {
16600 					mp->b_cont->b_next =
16601 					    mp1->b_cont->b_next;
16602 					mp->b_cont->b_prev =
16603 					    mp1->b_cont->b_prev;
16604 				}
16605 				inet_freemsg(mp1);
16606 				ASSERT(connp != NULL);
16607 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16608 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16609 			} else {
16610 				ASSERT(connp == NULL);
16611 				putnext(q, mp);
16612 			}
16613 			break;
16614 		case SIOCGTUNPARAM:
16615 		case OSIOCGTUNPARAM:
16616 			/*
16617 			 * This is really M_IOCDATA from the tunnel driver.
16618 			 * convert back and complete the ioctl.
16619 			 * We should have an IOCTL waiting on this.
16620 			 */
16621 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16622 			if (mp1) {
16623 				/*
16624 				 * Now copy back the b_next/b_prev used by
16625 				 * mi code for the mi_copy* functions.
16626 				 * See ip_sioctl_tunparam() for the reason.
16627 				 * Also protect against missing b_cont.
16628 				 */
16629 				if (mp->b_cont != NULL) {
16630 					mp->b_cont->b_next =
16631 					    mp1->b_cont->b_next;
16632 					mp->b_cont->b_prev =
16633 					    mp1->b_cont->b_prev;
16634 				}
16635 				inet_freemsg(mp1);
16636 				if (iocp->ioc_error == 0)
16637 					mp->b_datap->db_type = M_IOCDATA;
16638 				ASSERT(connp != NULL);
16639 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16640 				    iocp->ioc_error, COPYOUT, NULL);
16641 			} else {
16642 				ASSERT(connp == NULL);
16643 				putnext(q, mp);
16644 			}
16645 			break;
16646 		default:
16647 			break;
16648 		}
16649 		break;
16650 	case M_IOCNAK:
16651 		iocp = (struct iocblk *)mp->b_rptr;
16652 
16653 		switch (iocp->ioc_cmd) {
16654 			int mode;
16655 
16656 		case DL_IOC_HDR_INFO:
16657 			/*
16658 			 * If this was the first attempt turn of the
16659 			 * fastpath probing.
16660 			 */
16661 			mutex_enter(&ill->ill_lock);
16662 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16663 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16664 				mutex_exit(&ill->ill_lock);
16665 				ill_fastpath_nack(ill);
16666 				ip1dbg(("ip_rput: DLPI fastpath off on "
16667 				    "interface %s\n",
16668 				    ill->ill_name));
16669 			} else {
16670 				mutex_exit(&ill->ill_lock);
16671 			}
16672 			freemsg(mp);
16673 			break;
16674 		case SIOCSTUNPARAM:
16675 		case OSIOCSTUNPARAM:
16676 			ASSERT(ipsq != NULL);
16677 			/*
16678 			 * Finish socket ioctl passed through to tun
16679 			 * We should have an IOCTL waiting on this.
16680 			 */
16681 			/* FALLTHRU */
16682 		case SIOCGTUNPARAM:
16683 		case OSIOCGTUNPARAM:
16684 			/*
16685 			 * This is really M_IOCDATA from the tunnel driver.
16686 			 * convert back and complete the ioctl.
16687 			 * We should have an IOCTL waiting on this.
16688 			 */
16689 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16690 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16691 				mp1 = ill_pending_mp_get(ill, &connp,
16692 				    iocp->ioc_id);
16693 				mode = COPYOUT;
16694 				ipsq = NULL;
16695 			} else {
16696 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16697 				mode = NO_COPYOUT;
16698 			}
16699 			if (mp1 != NULL) {
16700 				/*
16701 				 * Now copy back the b_next/b_prev used by
16702 				 * mi code for the mi_copy* functions.
16703 				 * See ip_sioctl_tunparam() for the reason.
16704 				 * Also protect against missing b_cont.
16705 				 */
16706 				if (mp->b_cont != NULL) {
16707 					mp->b_cont->b_next =
16708 					    mp1->b_cont->b_next;
16709 					mp->b_cont->b_prev =
16710 					    mp1->b_cont->b_prev;
16711 				}
16712 				inet_freemsg(mp1);
16713 				if (iocp->ioc_error == 0)
16714 					iocp->ioc_error = EINVAL;
16715 				ASSERT(connp != NULL);
16716 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16717 				    iocp->ioc_error, mode, ipsq);
16718 			} else {
16719 				ASSERT(connp == NULL);
16720 				putnext(q, mp);
16721 			}
16722 			break;
16723 		default:
16724 			break;
16725 		}
16726 	default:
16727 		break;
16728 	}
16729 }
16730 
16731 /*
16732  * NOTE : This function does not ire_refrele the ire argument passed in.
16733  *
16734  * IPQoS notes
16735  * IP policy is invoked twice for a forwarded packet, once on the read side
16736  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16737  * enabled. An additional parameter, in_ill, has been added for this purpose.
16738  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16739  * because ip_mroute drops this information.
16740  *
16741  */
16742 void
16743 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16744 {
16745 	uint32_t	old_pkt_len;
16746 	uint32_t	pkt_len;
16747 	queue_t	*q;
16748 	uint32_t	sum;
16749 #define	rptr	((uchar_t *)ipha)
16750 	uint32_t	max_frag;
16751 	uint32_t	ill_index;
16752 	ill_t		*out_ill;
16753 	mib2_ipIfStatsEntry_t *mibptr;
16754 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16755 
16756 	/* Get the ill_index of the incoming ILL */
16757 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16758 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16759 
16760 	/* Initiate Read side IPPF processing */
16761 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16762 		ip_process(IPP_FWD_IN, &mp, ill_index);
16763 		if (mp == NULL) {
16764 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16765 			    "during IPPF processing\n"));
16766 			return;
16767 		}
16768 	}
16769 
16770 	/* Adjust the checksum to reflect the ttl decrement. */
16771 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16772 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16773 
16774 	if (ipha->ipha_ttl-- <= 1) {
16775 		if (ip_csum_hdr(ipha)) {
16776 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16777 			goto drop_pkt;
16778 		}
16779 		/*
16780 		 * Note: ire_stq this will be NULL for multicast
16781 		 * datagrams using the long path through arp (the IRE
16782 		 * is not an IRE_CACHE). This should not cause
16783 		 * problems since we don't generate ICMP errors for
16784 		 * multicast packets.
16785 		 */
16786 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16787 		q = ire->ire_stq;
16788 		if (q != NULL) {
16789 			/* Sent by forwarding path, and router is global zone */
16790 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16791 			    GLOBAL_ZONEID, ipst);
16792 		} else
16793 			freemsg(mp);
16794 		return;
16795 	}
16796 
16797 	/*
16798 	 * Don't forward if the interface is down
16799 	 */
16800 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16801 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16802 		ip2dbg(("ip_rput_forward:interface is down\n"));
16803 		goto drop_pkt;
16804 	}
16805 
16806 	/* Get the ill_index of the outgoing ILL */
16807 	out_ill = ire_to_ill(ire);
16808 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16809 
16810 	DTRACE_PROBE4(ip4__forwarding__start,
16811 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16812 
16813 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16814 	    ipst->ips_ipv4firewall_forwarding,
16815 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16816 
16817 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16818 
16819 	if (mp == NULL)
16820 		return;
16821 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16822 
16823 	if (is_system_labeled()) {
16824 		mblk_t *mp1;
16825 
16826 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16827 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16828 			goto drop_pkt;
16829 		}
16830 		/* Size may have changed */
16831 		mp = mp1;
16832 		ipha = (ipha_t *)mp->b_rptr;
16833 		pkt_len = ntohs(ipha->ipha_length);
16834 	}
16835 
16836 	/* Check if there are options to update */
16837 	if (!IS_SIMPLE_IPH(ipha)) {
16838 		if (ip_csum_hdr(ipha)) {
16839 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16840 			goto drop_pkt;
16841 		}
16842 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16843 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16844 			return;
16845 		}
16846 
16847 		ipha->ipha_hdr_checksum = 0;
16848 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16849 	}
16850 	max_frag = ire->ire_max_frag;
16851 	if (pkt_len > max_frag) {
16852 		/*
16853 		 * It needs fragging on its way out.  We haven't
16854 		 * verified the header checksum yet.  Since we
16855 		 * are going to put a surely good checksum in the
16856 		 * outgoing header, we have to make sure that it
16857 		 * was good coming in.
16858 		 */
16859 		if (ip_csum_hdr(ipha)) {
16860 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16861 			goto drop_pkt;
16862 		}
16863 		/* Initiate Write side IPPF processing */
16864 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16865 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16866 			if (mp == NULL) {
16867 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16868 				    " during IPPF processing\n"));
16869 				return;
16870 			}
16871 		}
16872 		/*
16873 		 * Handle labeled packet resizing.
16874 		 *
16875 		 * If we have added a label, inform ip_wput_frag() of its
16876 		 * effect on the MTU for ICMP messages.
16877 		 */
16878 		if (pkt_len > old_pkt_len) {
16879 			uint32_t secopt_size;
16880 
16881 			secopt_size = pkt_len - old_pkt_len;
16882 			if (secopt_size < max_frag)
16883 				max_frag -= secopt_size;
16884 		}
16885 
16886 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0,
16887 		    GLOBAL_ZONEID, ipst, NULL);
16888 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16889 		return;
16890 	}
16891 
16892 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16893 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16894 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16895 	    ipst->ips_ipv4firewall_physical_out,
16896 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16897 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16898 	if (mp == NULL)
16899 		return;
16900 
16901 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16902 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16903 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE, NULL);
16904 	/* ip_xmit_v4 always consumes the packet */
16905 	return;
16906 
16907 drop_pkt:;
16908 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16909 	freemsg(mp);
16910 #undef	rptr
16911 }
16912 
16913 void
16914 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16915 {
16916 	ire_t	*ire;
16917 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16918 
16919 	ASSERT(!ipif->ipif_isv6);
16920 	/*
16921 	 * Find an IRE which matches the destination and the outgoing
16922 	 * queue in the cache table. All we need is an IRE_CACHE which
16923 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16924 	 * then it is enough to have some IRE_CACHE in the group.
16925 	 */
16926 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16927 		dst = ipif->ipif_pp_dst_addr;
16928 
16929 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16930 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16931 	if (ire == NULL) {
16932 		/*
16933 		 * Mark this packet to make it be delivered to
16934 		 * ip_rput_forward after the new ire has been
16935 		 * created.
16936 		 */
16937 		mp->b_prev = NULL;
16938 		mp->b_next = mp;
16939 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16940 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16941 	} else {
16942 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16943 		IRE_REFRELE(ire);
16944 	}
16945 }
16946 
16947 /* Update any source route, record route or timestamp options */
16948 static int
16949 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16950 {
16951 	ipoptp_t	opts;
16952 	uchar_t		*opt;
16953 	uint8_t		optval;
16954 	uint8_t		optlen;
16955 	ipaddr_t	dst;
16956 	uint32_t	ts;
16957 	ire_t		*dst_ire = NULL;
16958 	ire_t		*tmp_ire = NULL;
16959 	timestruc_t	now;
16960 
16961 	ip2dbg(("ip_rput_forward_options\n"));
16962 	dst = ipha->ipha_dst;
16963 	for (optval = ipoptp_first(&opts, ipha);
16964 	    optval != IPOPT_EOL;
16965 	    optval = ipoptp_next(&opts)) {
16966 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16967 		opt = opts.ipoptp_cur;
16968 		optlen = opts.ipoptp_len;
16969 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16970 		    optval, opts.ipoptp_len));
16971 		switch (optval) {
16972 			uint32_t off;
16973 		case IPOPT_SSRR:
16974 		case IPOPT_LSRR:
16975 			/* Check if adminstratively disabled */
16976 			if (!ipst->ips_ip_forward_src_routed) {
16977 				if (ire->ire_stq != NULL) {
16978 					/*
16979 					 * Sent by forwarding path, and router
16980 					 * is global zone
16981 					 */
16982 					icmp_unreachable(ire->ire_stq, mp,
16983 					    ICMP_SOURCE_ROUTE_FAILED,
16984 					    GLOBAL_ZONEID, ipst);
16985 				} else {
16986 					ip0dbg(("ip_rput_forward_options: "
16987 					    "unable to send unreach\n"));
16988 					freemsg(mp);
16989 				}
16990 				return (-1);
16991 			}
16992 
16993 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16994 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16995 			if (dst_ire == NULL) {
16996 				/*
16997 				 * Must be partial since ip_rput_options
16998 				 * checked for strict.
16999 				 */
17000 				break;
17001 			}
17002 			off = opt[IPOPT_OFFSET];
17003 			off--;
17004 		redo_srr:
17005 			if (optlen < IP_ADDR_LEN ||
17006 			    off > optlen - IP_ADDR_LEN) {
17007 				/* End of source route */
17008 				ip1dbg((
17009 				    "ip_rput_forward_options: end of SR\n"));
17010 				ire_refrele(dst_ire);
17011 				break;
17012 			}
17013 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17014 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17015 			    IP_ADDR_LEN);
17016 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
17017 			    ntohl(dst)));
17018 
17019 			/*
17020 			 * Check if our address is present more than
17021 			 * once as consecutive hops in source route.
17022 			 */
17023 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17024 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17025 			if (tmp_ire != NULL) {
17026 				ire_refrele(tmp_ire);
17027 				off += IP_ADDR_LEN;
17028 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17029 				goto redo_srr;
17030 			}
17031 			ipha->ipha_dst = dst;
17032 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17033 			ire_refrele(dst_ire);
17034 			break;
17035 		case IPOPT_RR:
17036 			off = opt[IPOPT_OFFSET];
17037 			off--;
17038 			if (optlen < IP_ADDR_LEN ||
17039 			    off > optlen - IP_ADDR_LEN) {
17040 				/* No more room - ignore */
17041 				ip1dbg((
17042 				    "ip_rput_forward_options: end of RR\n"));
17043 				break;
17044 			}
17045 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17046 			    IP_ADDR_LEN);
17047 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17048 			break;
17049 		case IPOPT_TS:
17050 			/* Insert timestamp if there is room */
17051 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17052 			case IPOPT_TS_TSONLY:
17053 				off = IPOPT_TS_TIMELEN;
17054 				break;
17055 			case IPOPT_TS_PRESPEC:
17056 			case IPOPT_TS_PRESPEC_RFC791:
17057 				/* Verify that the address matched */
17058 				off = opt[IPOPT_OFFSET] - 1;
17059 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17060 				dst_ire = ire_ctable_lookup(dst, 0,
17061 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
17062 				    MATCH_IRE_TYPE, ipst);
17063 				if (dst_ire == NULL) {
17064 					/* Not for us */
17065 					break;
17066 				}
17067 				ire_refrele(dst_ire);
17068 				/* FALLTHRU */
17069 			case IPOPT_TS_TSANDADDR:
17070 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17071 				break;
17072 			default:
17073 				/*
17074 				 * ip_*put_options should have already
17075 				 * dropped this packet.
17076 				 */
17077 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
17078 				    "unknown IT - bug in ip_rput_options?\n");
17079 				return (0);	/* Keep "lint" happy */
17080 			}
17081 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17082 				/* Increase overflow counter */
17083 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17084 				opt[IPOPT_POS_OV_FLG] =
17085 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17086 				    (off << 4));
17087 				break;
17088 			}
17089 			off = opt[IPOPT_OFFSET] - 1;
17090 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17091 			case IPOPT_TS_PRESPEC:
17092 			case IPOPT_TS_PRESPEC_RFC791:
17093 			case IPOPT_TS_TSANDADDR:
17094 				bcopy(&ire->ire_src_addr,
17095 				    (char *)opt + off, IP_ADDR_LEN);
17096 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17097 				/* FALLTHRU */
17098 			case IPOPT_TS_TSONLY:
17099 				off = opt[IPOPT_OFFSET] - 1;
17100 				/* Compute # of milliseconds since midnight */
17101 				gethrestime(&now);
17102 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17103 				    now.tv_nsec / (NANOSEC / MILLISEC);
17104 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17105 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17106 				break;
17107 			}
17108 			break;
17109 		}
17110 	}
17111 	return (0);
17112 }
17113 
17114 /*
17115  * This is called after processing at least one of AH/ESP headers.
17116  *
17117  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
17118  * the actual, physical interface on which the packet was received,
17119  * but, when ip_strict_dst_multihoming is set to 1, could be the
17120  * interface which had the ipha_dst configured when the packet went
17121  * through ip_rput. The ill_index corresponding to the recv_ill
17122  * is saved in ipsec_in_rill_index
17123  *
17124  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
17125  * cannot assume "ire" points to valid data for any IPv6 cases.
17126  */
17127 void
17128 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17129 {
17130 	mblk_t *mp;
17131 	ipaddr_t dst;
17132 	in6_addr_t *v6dstp;
17133 	ipha_t *ipha;
17134 	ip6_t *ip6h;
17135 	ipsec_in_t *ii;
17136 	boolean_t ill_need_rele = B_FALSE;
17137 	boolean_t rill_need_rele = B_FALSE;
17138 	boolean_t ire_need_rele = B_FALSE;
17139 	netstack_t	*ns;
17140 	ip_stack_t	*ipst;
17141 
17142 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17143 	ASSERT(ii->ipsec_in_ill_index != 0);
17144 	ns = ii->ipsec_in_ns;
17145 	ASSERT(ii->ipsec_in_ns != NULL);
17146 	ipst = ns->netstack_ip;
17147 
17148 	mp = ipsec_mp->b_cont;
17149 	ASSERT(mp != NULL);
17150 
17151 
17152 	if (ill == NULL) {
17153 		ASSERT(recv_ill == NULL);
17154 		/*
17155 		 * We need to get the original queue on which ip_rput_local
17156 		 * or ip_rput_data_v6 was called.
17157 		 */
17158 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17159 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17160 		ill_need_rele = B_TRUE;
17161 
17162 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17163 			recv_ill = ill_lookup_on_ifindex(
17164 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17165 			    NULL, NULL, NULL, NULL, ipst);
17166 			rill_need_rele = B_TRUE;
17167 		} else {
17168 			recv_ill = ill;
17169 		}
17170 
17171 		if ((ill == NULL) || (recv_ill == NULL)) {
17172 			ip0dbg(("ip_fanout_proto_again: interface "
17173 			    "disappeared\n"));
17174 			if (ill != NULL)
17175 				ill_refrele(ill);
17176 			if (recv_ill != NULL)
17177 				ill_refrele(recv_ill);
17178 			freemsg(ipsec_mp);
17179 			return;
17180 		}
17181 	}
17182 
17183 	ASSERT(ill != NULL && recv_ill != NULL);
17184 
17185 	if (mp->b_datap->db_type == M_CTL) {
17186 		/*
17187 		 * AH/ESP is returning the ICMP message after
17188 		 * removing their headers. Fanout again till
17189 		 * it gets to the right protocol.
17190 		 */
17191 		if (ii->ipsec_in_v4) {
17192 			icmph_t *icmph;
17193 			int iph_hdr_length;
17194 			int hdr_length;
17195 
17196 			ipha = (ipha_t *)mp->b_rptr;
17197 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17198 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17199 			ipha = (ipha_t *)&icmph[1];
17200 			hdr_length = IPH_HDR_LENGTH(ipha);
17201 			/*
17202 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17203 			 * Reset the type to M_DATA.
17204 			 */
17205 			mp->b_datap->db_type = M_DATA;
17206 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17207 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17208 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17209 		} else {
17210 			icmp6_t *icmp6;
17211 			int hdr_length;
17212 
17213 			ip6h = (ip6_t *)mp->b_rptr;
17214 			/* Don't call hdr_length_v6() unless you have to. */
17215 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17216 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17217 			else
17218 				hdr_length = IPV6_HDR_LEN;
17219 
17220 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17221 			/*
17222 			 * icmp_inbound_error_fanout_v6 may need to do
17223 			 * pullupmsg.  Reset the type to M_DATA.
17224 			 */
17225 			mp->b_datap->db_type = M_DATA;
17226 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17227 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17228 		}
17229 		if (ill_need_rele)
17230 			ill_refrele(ill);
17231 		if (rill_need_rele)
17232 			ill_refrele(recv_ill);
17233 		return;
17234 	}
17235 
17236 	if (ii->ipsec_in_v4) {
17237 		ipha = (ipha_t *)mp->b_rptr;
17238 		dst = ipha->ipha_dst;
17239 		if (CLASSD(dst)) {
17240 			/*
17241 			 * Multicast has to be delivered to all streams.
17242 			 */
17243 			dst = INADDR_BROADCAST;
17244 		}
17245 
17246 		if (ire == NULL) {
17247 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17248 			    MBLK_GETLABEL(mp), ipst);
17249 			if (ire == NULL) {
17250 				if (ill_need_rele)
17251 					ill_refrele(ill);
17252 				if (rill_need_rele)
17253 					ill_refrele(recv_ill);
17254 				ip1dbg(("ip_fanout_proto_again: "
17255 				    "IRE not found"));
17256 				freemsg(ipsec_mp);
17257 				return;
17258 			}
17259 			ire_need_rele = B_TRUE;
17260 		}
17261 
17262 		switch (ipha->ipha_protocol) {
17263 			case IPPROTO_UDP:
17264 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17265 				    recv_ill);
17266 				if (ire_need_rele)
17267 					ire_refrele(ire);
17268 				break;
17269 			case IPPROTO_TCP:
17270 				if (!ire_need_rele)
17271 					IRE_REFHOLD(ire);
17272 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17273 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17274 				IRE_REFRELE(ire);
17275 				if (mp != NULL) {
17276 
17277 					SQUEUE_ENTER(GET_SQUEUE(mp), mp,
17278 					    mp, 1, SQ_PROCESS,
17279 					    SQTAG_IP_PROTO_AGAIN);
17280 				}
17281 				break;
17282 			case IPPROTO_SCTP:
17283 				if (!ire_need_rele)
17284 					IRE_REFHOLD(ire);
17285 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17286 				    ipsec_mp, 0, ill->ill_rq, dst);
17287 				break;
17288 			default:
17289 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17290 				    recv_ill, 0);
17291 				if (ire_need_rele)
17292 					ire_refrele(ire);
17293 				break;
17294 		}
17295 	} else {
17296 		uint32_t rput_flags = 0;
17297 
17298 		ip6h = (ip6_t *)mp->b_rptr;
17299 		v6dstp = &ip6h->ip6_dst;
17300 		/*
17301 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17302 		 * address.
17303 		 *
17304 		 * Currently, we don't store that state in the IPSEC_IN
17305 		 * message, and we may need to.
17306 		 */
17307 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17308 		    IP6_IN_LLMCAST : 0);
17309 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17310 		    NULL, NULL);
17311 	}
17312 	if (ill_need_rele)
17313 		ill_refrele(ill);
17314 	if (rill_need_rele)
17315 		ill_refrele(recv_ill);
17316 }
17317 
17318 /*
17319  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17320  * returns 'true' if there are still fragments left on the queue, in
17321  * which case we restart the timer.
17322  */
17323 void
17324 ill_frag_timer(void *arg)
17325 {
17326 	ill_t	*ill = (ill_t *)arg;
17327 	boolean_t frag_pending;
17328 	ip_stack_t	*ipst = ill->ill_ipst;
17329 
17330 	mutex_enter(&ill->ill_lock);
17331 	ASSERT(!ill->ill_fragtimer_executing);
17332 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17333 		ill->ill_frag_timer_id = 0;
17334 		mutex_exit(&ill->ill_lock);
17335 		return;
17336 	}
17337 	ill->ill_fragtimer_executing = 1;
17338 	mutex_exit(&ill->ill_lock);
17339 
17340 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17341 
17342 	/*
17343 	 * Restart the timer, if we have fragments pending or if someone
17344 	 * wanted us to be scheduled again.
17345 	 */
17346 	mutex_enter(&ill->ill_lock);
17347 	ill->ill_fragtimer_executing = 0;
17348 	ill->ill_frag_timer_id = 0;
17349 	if (frag_pending || ill->ill_fragtimer_needrestart)
17350 		ill_frag_timer_start(ill);
17351 	mutex_exit(&ill->ill_lock);
17352 }
17353 
17354 void
17355 ill_frag_timer_start(ill_t *ill)
17356 {
17357 	ip_stack_t	*ipst = ill->ill_ipst;
17358 
17359 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17360 
17361 	/* If the ill is closing or opening don't proceed */
17362 	if (ill->ill_state_flags & ILL_CONDEMNED)
17363 		return;
17364 
17365 	if (ill->ill_fragtimer_executing) {
17366 		/*
17367 		 * ill_frag_timer is currently executing. Just record the
17368 		 * the fact that we want the timer to be restarted.
17369 		 * ill_frag_timer will post a timeout before it returns,
17370 		 * ensuring it will be called again.
17371 		 */
17372 		ill->ill_fragtimer_needrestart = 1;
17373 		return;
17374 	}
17375 
17376 	if (ill->ill_frag_timer_id == 0) {
17377 		/*
17378 		 * The timer is neither running nor is the timeout handler
17379 		 * executing. Post a timeout so that ill_frag_timer will be
17380 		 * called
17381 		 */
17382 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17383 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17384 		ill->ill_fragtimer_needrestart = 0;
17385 	}
17386 }
17387 
17388 /*
17389  * This routine is needed for loopback when forwarding multicasts.
17390  *
17391  * IPQoS Notes:
17392  * IPPF processing is done in fanout routines.
17393  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17394  * processing for IPsec packets is done when it comes back in clear.
17395  * NOTE : The callers of this function need to do the ire_refrele for the
17396  *	  ire that is being passed in.
17397  */
17398 void
17399 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17400     ill_t *recv_ill, uint32_t esp_udp_ports)
17401 {
17402 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17403 	ill_t	*ill = (ill_t *)q->q_ptr;
17404 	uint32_t	sum;
17405 	uint32_t	u1;
17406 	uint32_t	u2;
17407 	int		hdr_length;
17408 	boolean_t	mctl_present;
17409 	mblk_t		*first_mp = mp;
17410 	mblk_t		*hada_mp = NULL;
17411 	ipha_t		*inner_ipha;
17412 	ip_stack_t	*ipst;
17413 
17414 	ASSERT(recv_ill != NULL);
17415 	ipst = recv_ill->ill_ipst;
17416 
17417 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17418 	    "ip_rput_locl_start: q %p", q);
17419 
17420 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17421 	ASSERT(ill != NULL);
17422 
17423 
17424 #define	rptr	((uchar_t *)ipha)
17425 #define	iphs	((uint16_t *)ipha)
17426 
17427 	/*
17428 	 * no UDP or TCP packet should come here anymore.
17429 	 */
17430 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17431 	    ipha->ipha_protocol != IPPROTO_UDP);
17432 
17433 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17434 	if (mctl_present &&
17435 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17436 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17437 
17438 		/*
17439 		 * It's an IPsec accelerated packet.
17440 		 * Keep a pointer to the data attributes around until
17441 		 * we allocate the ipsec_info_t.
17442 		 */
17443 		IPSECHW_DEBUG(IPSECHW_PKT,
17444 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17445 		hada_mp = first_mp;
17446 		hada_mp->b_cont = NULL;
17447 		/*
17448 		 * Since it is accelerated, it comes directly from
17449 		 * the ill and the data attributes is followed by
17450 		 * the packet data.
17451 		 */
17452 		ASSERT(mp->b_datap->db_type != M_CTL);
17453 		first_mp = mp;
17454 		mctl_present = B_FALSE;
17455 	}
17456 
17457 	/*
17458 	 * IF M_CTL is not present, then ipsec_in_is_secure
17459 	 * should return B_TRUE. There is a case where loopback
17460 	 * packets has an M_CTL in the front with all the
17461 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17462 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17463 	 * packets never comes here, it is safe to ASSERT the
17464 	 * following.
17465 	 */
17466 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17467 
17468 	/*
17469 	 * Also, we should never have an mctl_present if this is an
17470 	 * ESP-in-UDP packet.
17471 	 */
17472 	ASSERT(!mctl_present || !esp_in_udp_packet);
17473 
17474 
17475 	/* u1 is # words of IP options */
17476 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17477 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17478 
17479 	/*
17480 	 * Don't verify header checksum if we just removed UDP header or
17481 	 * packet is coming back from AH/ESP.
17482 	 */
17483 	if (!esp_in_udp_packet && !mctl_present) {
17484 		if (u1) {
17485 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17486 				if (hada_mp != NULL)
17487 					freemsg(hada_mp);
17488 				return;
17489 			}
17490 		} else {
17491 			/* Check the IP header checksum.  */
17492 #define	uph	((uint16_t *)ipha)
17493 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17494 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17495 #undef  uph
17496 			/* finish doing IP checksum */
17497 			sum = (sum & 0xFFFF) + (sum >> 16);
17498 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17499 			if (sum && sum != 0xFFFF) {
17500 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17501 				goto drop_pkt;
17502 			}
17503 		}
17504 	}
17505 
17506 	/*
17507 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17508 	 * might be called more than once for secure packets, count only
17509 	 * the first time.
17510 	 */
17511 	if (!mctl_present) {
17512 		UPDATE_IB_PKT_COUNT(ire);
17513 		ire->ire_last_used_time = lbolt;
17514 	}
17515 
17516 	/* Check for fragmentation offset. */
17517 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17518 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17519 	if (u1) {
17520 		/*
17521 		 * We re-assemble fragments before we do the AH/ESP
17522 		 * processing. Thus, M_CTL should not be present
17523 		 * while we are re-assembling.
17524 		 */
17525 		ASSERT(!mctl_present);
17526 		ASSERT(first_mp == mp);
17527 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17528 			return;
17529 		}
17530 		/*
17531 		 * Make sure that first_mp points back to mp as
17532 		 * the mp we came in with could have changed in
17533 		 * ip_rput_fragment().
17534 		 */
17535 		ipha = (ipha_t *)mp->b_rptr;
17536 		first_mp = mp;
17537 	}
17538 
17539 	/*
17540 	 * Clear hardware checksumming flag as it is currently only
17541 	 * used by TCP and UDP.
17542 	 */
17543 	DB_CKSUMFLAGS(mp) = 0;
17544 
17545 	/* Now we have a complete datagram, destined for this machine. */
17546 	u1 = IPH_HDR_LENGTH(ipha);
17547 	switch (ipha->ipha_protocol) {
17548 	case IPPROTO_ICMP: {
17549 		ire_t		*ire_zone;
17550 		ilm_t		*ilm;
17551 		mblk_t		*mp1;
17552 		zoneid_t	last_zoneid;
17553 
17554 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17555 			ASSERT(ire->ire_type == IRE_BROADCAST);
17556 			/*
17557 			 * Inactive/Failed interfaces are not supposed to
17558 			 * respond to the multicast packets.
17559 			 */
17560 			if (ill_is_probeonly(ill)) {
17561 				freemsg(first_mp);
17562 				return;
17563 			}
17564 
17565 			/*
17566 			 * In the multicast case, applications may have joined
17567 			 * the group from different zones, so we need to deliver
17568 			 * the packet to each of them. Loop through the
17569 			 * multicast memberships structures (ilm) on the receive
17570 			 * ill and send a copy of the packet up each matching
17571 			 * one. However, we don't do this for multicasts sent on
17572 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17573 			 * they must stay in the sender's zone.
17574 			 *
17575 			 * ilm_add_v6() ensures that ilms in the same zone are
17576 			 * contiguous in the ill_ilm list. We use this property
17577 			 * to avoid sending duplicates needed when two
17578 			 * applications in the same zone join the same group on
17579 			 * different logical interfaces: we ignore the ilm if
17580 			 * its zoneid is the same as the last matching one.
17581 			 * In addition, the sending of the packet for
17582 			 * ire_zoneid is delayed until all of the other ilms
17583 			 * have been exhausted.
17584 			 */
17585 			last_zoneid = -1;
17586 			ILM_WALKER_HOLD(recv_ill);
17587 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17588 			    ilm = ilm->ilm_next) {
17589 				if ((ilm->ilm_flags & ILM_DELETED) ||
17590 				    ipha->ipha_dst != ilm->ilm_addr ||
17591 				    ilm->ilm_zoneid == last_zoneid ||
17592 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17593 				    ilm->ilm_zoneid == ALL_ZONES ||
17594 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17595 					continue;
17596 				mp1 = ip_copymsg(first_mp);
17597 				if (mp1 == NULL)
17598 					continue;
17599 				icmp_inbound(q, mp1, B_TRUE, ill,
17600 				    0, sum, mctl_present, B_TRUE,
17601 				    recv_ill, ilm->ilm_zoneid);
17602 				last_zoneid = ilm->ilm_zoneid;
17603 			}
17604 			ILM_WALKER_RELE(recv_ill);
17605 		} else if (ire->ire_type == IRE_BROADCAST) {
17606 			/*
17607 			 * In the broadcast case, there may be many zones
17608 			 * which need a copy of the packet delivered to them.
17609 			 * There is one IRE_BROADCAST per broadcast address
17610 			 * and per zone; we walk those using a helper function.
17611 			 * In addition, the sending of the packet for ire is
17612 			 * delayed until all of the other ires have been
17613 			 * processed.
17614 			 */
17615 			IRB_REFHOLD(ire->ire_bucket);
17616 			ire_zone = NULL;
17617 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17618 			    ire)) != NULL) {
17619 				mp1 = ip_copymsg(first_mp);
17620 				if (mp1 == NULL)
17621 					continue;
17622 
17623 				UPDATE_IB_PKT_COUNT(ire_zone);
17624 				ire_zone->ire_last_used_time = lbolt;
17625 				icmp_inbound(q, mp1, B_TRUE, ill,
17626 				    0, sum, mctl_present, B_TRUE,
17627 				    recv_ill, ire_zone->ire_zoneid);
17628 			}
17629 			IRB_REFRELE(ire->ire_bucket);
17630 		}
17631 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17632 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17633 		    ire->ire_zoneid);
17634 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17635 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17636 		return;
17637 	}
17638 	case IPPROTO_IGMP:
17639 		/*
17640 		 * If we are not willing to accept IGMP packets in clear,
17641 		 * then check with global policy.
17642 		 */
17643 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17644 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17645 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17646 			if (first_mp == NULL)
17647 				return;
17648 		}
17649 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17650 			freemsg(first_mp);
17651 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17652 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17653 			return;
17654 		}
17655 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17656 			/* Bad packet - discarded by igmp_input */
17657 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17658 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17659 			if (mctl_present)
17660 				freeb(first_mp);
17661 			return;
17662 		}
17663 		/*
17664 		 * igmp_input() may have returned the pulled up message.
17665 		 * So first_mp and ipha need to be reinitialized.
17666 		 */
17667 		ipha = (ipha_t *)mp->b_rptr;
17668 		if (mctl_present)
17669 			first_mp->b_cont = mp;
17670 		else
17671 			first_mp = mp;
17672 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17673 		    connf_head != NULL) {
17674 			/* No user-level listener for IGMP packets */
17675 			goto drop_pkt;
17676 		}
17677 		/* deliver to local raw users */
17678 		break;
17679 	case IPPROTO_PIM:
17680 		/*
17681 		 * If we are not willing to accept PIM packets in clear,
17682 		 * then check with global policy.
17683 		 */
17684 		if (ipst->ips_pim_accept_clear_messages == 0) {
17685 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17686 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17687 			if (first_mp == NULL)
17688 				return;
17689 		}
17690 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17691 			freemsg(first_mp);
17692 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17693 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17694 			return;
17695 		}
17696 		if (pim_input(q, mp, ill) != 0) {
17697 			/* Bad packet - discarded by pim_input */
17698 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17699 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17700 			if (mctl_present)
17701 				freeb(first_mp);
17702 			return;
17703 		}
17704 
17705 		/*
17706 		 * pim_input() may have pulled up the message so ipha needs to
17707 		 * be reinitialized.
17708 		 */
17709 		ipha = (ipha_t *)mp->b_rptr;
17710 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17711 		    connf_head != NULL) {
17712 			/* No user-level listener for PIM packets */
17713 			goto drop_pkt;
17714 		}
17715 		/* deliver to local raw users */
17716 		break;
17717 	case IPPROTO_ENCAP:
17718 		/*
17719 		 * Handle self-encapsulated packets (IP-in-IP where
17720 		 * the inner addresses == the outer addresses).
17721 		 */
17722 		hdr_length = IPH_HDR_LENGTH(ipha);
17723 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17724 		    mp->b_wptr) {
17725 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17726 			    sizeof (ipha_t) - mp->b_rptr)) {
17727 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17728 				freemsg(first_mp);
17729 				return;
17730 			}
17731 			ipha = (ipha_t *)mp->b_rptr;
17732 		}
17733 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17734 		/*
17735 		 * Check the sanity of the inner IP header.
17736 		 */
17737 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17738 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17739 			freemsg(first_mp);
17740 			return;
17741 		}
17742 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17743 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17744 			freemsg(first_mp);
17745 			return;
17746 		}
17747 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17748 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17749 			ipsec_in_t *ii;
17750 
17751 			/*
17752 			 * Self-encapsulated tunnel packet. Remove
17753 			 * the outer IP header and fanout again.
17754 			 * We also need to make sure that the inner
17755 			 * header is pulled up until options.
17756 			 */
17757 			mp->b_rptr = (uchar_t *)inner_ipha;
17758 			ipha = inner_ipha;
17759 			hdr_length = IPH_HDR_LENGTH(ipha);
17760 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17761 				if (!pullupmsg(mp, (uchar_t *)ipha +
17762 				    + hdr_length - mp->b_rptr)) {
17763 					freemsg(first_mp);
17764 					return;
17765 				}
17766 				ipha = (ipha_t *)mp->b_rptr;
17767 			}
17768 			if (hdr_length > sizeof (ipha_t)) {
17769 				/* We got options on the inner packet. */
17770 				ipaddr_t dst = ipha->ipha_dst;
17771 
17772 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17773 				    -1) {
17774 					/* Bad options! */
17775 					return;
17776 				}
17777 				if (dst != ipha->ipha_dst) {
17778 					/*
17779 					 * Someone put a source-route in
17780 					 * the inside header of a self-
17781 					 * encapsulated packet.  Drop it
17782 					 * with extreme prejudice and let
17783 					 * the sender know.
17784 					 */
17785 					icmp_unreachable(q, first_mp,
17786 					    ICMP_SOURCE_ROUTE_FAILED,
17787 					    recv_ill->ill_zoneid, ipst);
17788 					return;
17789 				}
17790 			}
17791 			if (!mctl_present) {
17792 				ASSERT(first_mp == mp);
17793 				/*
17794 				 * This means that somebody is sending
17795 				 * Self-encapsualted packets without AH/ESP.
17796 				 * If AH/ESP was present, we would have already
17797 				 * allocated the first_mp.
17798 				 *
17799 				 * Send this packet to find a tunnel endpoint.
17800 				 * if I can't find one, an ICMP
17801 				 * PROTOCOL_UNREACHABLE will get sent.
17802 				 */
17803 				goto fanout;
17804 			}
17805 			/*
17806 			 * We generally store the ill_index if we need to
17807 			 * do IPsec processing as we lose the ill queue when
17808 			 * we come back. But in this case, we never should
17809 			 * have to store the ill_index here as it should have
17810 			 * been stored previously when we processed the
17811 			 * AH/ESP header in this routine or for non-ipsec
17812 			 * cases, we still have the queue. But for some bad
17813 			 * packets from the wire, we can get to IPsec after
17814 			 * this and we better store the index for that case.
17815 			 */
17816 			ill = (ill_t *)q->q_ptr;
17817 			ii = (ipsec_in_t *)first_mp->b_rptr;
17818 			ii->ipsec_in_ill_index =
17819 			    ill->ill_phyint->phyint_ifindex;
17820 			ii->ipsec_in_rill_index =
17821 			    recv_ill->ill_phyint->phyint_ifindex;
17822 			if (ii->ipsec_in_decaps) {
17823 				/*
17824 				 * This packet is self-encapsulated multiple
17825 				 * times. We don't want to recurse infinitely.
17826 				 * To keep it simple, drop the packet.
17827 				 */
17828 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17829 				freemsg(first_mp);
17830 				return;
17831 			}
17832 			ii->ipsec_in_decaps = B_TRUE;
17833 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17834 			    ire);
17835 			return;
17836 		}
17837 		break;
17838 	case IPPROTO_AH:
17839 	case IPPROTO_ESP: {
17840 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17841 
17842 		/*
17843 		 * Fast path for AH/ESP. If this is the first time
17844 		 * we are sending a datagram to AH/ESP, allocate
17845 		 * a IPSEC_IN message and prepend it. Otherwise,
17846 		 * just fanout.
17847 		 */
17848 
17849 		int ipsec_rc;
17850 		ipsec_in_t *ii;
17851 		netstack_t *ns = ipst->ips_netstack;
17852 
17853 		IP_STAT(ipst, ipsec_proto_ahesp);
17854 		if (!mctl_present) {
17855 			ASSERT(first_mp == mp);
17856 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17857 			if (first_mp == NULL) {
17858 				ip1dbg(("ip_proto_input: IPSEC_IN "
17859 				    "allocation failure.\n"));
17860 				freemsg(hada_mp); /* okay ifnull */
17861 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17862 				freemsg(mp);
17863 				return;
17864 			}
17865 			/*
17866 			 * Store the ill_index so that when we come back
17867 			 * from IPsec we ride on the same queue.
17868 			 */
17869 			ill = (ill_t *)q->q_ptr;
17870 			ii = (ipsec_in_t *)first_mp->b_rptr;
17871 			ii->ipsec_in_ill_index =
17872 			    ill->ill_phyint->phyint_ifindex;
17873 			ii->ipsec_in_rill_index =
17874 			    recv_ill->ill_phyint->phyint_ifindex;
17875 			first_mp->b_cont = mp;
17876 			/*
17877 			 * Cache hardware acceleration info.
17878 			 */
17879 			if (hada_mp != NULL) {
17880 				IPSECHW_DEBUG(IPSECHW_PKT,
17881 				    ("ip_rput_local: caching data attr.\n"));
17882 				ii->ipsec_in_accelerated = B_TRUE;
17883 				ii->ipsec_in_da = hada_mp;
17884 				hada_mp = NULL;
17885 			}
17886 		} else {
17887 			ii = (ipsec_in_t *)first_mp->b_rptr;
17888 		}
17889 
17890 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17891 
17892 		if (!ipsec_loaded(ipss)) {
17893 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17894 			    ire->ire_zoneid, ipst);
17895 			return;
17896 		}
17897 
17898 		ns = ipst->ips_netstack;
17899 		/* select inbound SA and have IPsec process the pkt */
17900 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17901 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17902 			boolean_t esp_in_udp_sa;
17903 			if (esph == NULL)
17904 				return;
17905 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17906 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17907 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17908 			    IPSA_F_NATT) != 0);
17909 			/*
17910 			 * The following is a fancy, but quick, way of saying:
17911 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17912 			 *    OR
17913 			 * ESP SA and ESP-in-UDP packet --> drop
17914 			 */
17915 			if (esp_in_udp_sa != esp_in_udp_packet) {
17916 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17917 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17918 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17919 				    &ns->netstack_ipsec->ipsec_dropper);
17920 				return;
17921 			}
17922 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17923 			    first_mp, esph);
17924 		} else {
17925 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17926 			if (ah == NULL)
17927 				return;
17928 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17929 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17930 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17931 			    first_mp, ah);
17932 		}
17933 
17934 		switch (ipsec_rc) {
17935 		case IPSEC_STATUS_SUCCESS:
17936 			break;
17937 		case IPSEC_STATUS_FAILED:
17938 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17939 			/* FALLTHRU */
17940 		case IPSEC_STATUS_PENDING:
17941 			return;
17942 		}
17943 		/* we're done with IPsec processing, send it up */
17944 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17945 		return;
17946 	}
17947 	default:
17948 		break;
17949 	}
17950 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17951 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17952 		    ire->ire_zoneid));
17953 		goto drop_pkt;
17954 	}
17955 	/*
17956 	 * Handle protocols with which IP is less intimate.  There
17957 	 * can be more than one stream bound to a particular
17958 	 * protocol.  When this is the case, each one gets a copy
17959 	 * of any incoming packets.
17960 	 */
17961 fanout:
17962 	ip_fanout_proto(q, first_mp, ill, ipha,
17963 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17964 	    B_TRUE, recv_ill, ire->ire_zoneid);
17965 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17966 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17967 	return;
17968 
17969 drop_pkt:
17970 	freemsg(first_mp);
17971 	if (hada_mp != NULL)
17972 		freeb(hada_mp);
17973 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17974 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17975 #undef	rptr
17976 #undef  iphs
17977 
17978 }
17979 
17980 /*
17981  * Update any source route, record route or timestamp options.
17982  * Check that we are at end of strict source route.
17983  * The options have already been checked for sanity in ip_rput_options().
17984  */
17985 static boolean_t
17986 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17987     ip_stack_t *ipst)
17988 {
17989 	ipoptp_t	opts;
17990 	uchar_t		*opt;
17991 	uint8_t		optval;
17992 	uint8_t		optlen;
17993 	ipaddr_t	dst;
17994 	uint32_t	ts;
17995 	ire_t		*dst_ire;
17996 	timestruc_t	now;
17997 	zoneid_t	zoneid;
17998 	ill_t		*ill;
17999 
18000 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18001 
18002 	ip2dbg(("ip_rput_local_options\n"));
18003 
18004 	for (optval = ipoptp_first(&opts, ipha);
18005 	    optval != IPOPT_EOL;
18006 	    optval = ipoptp_next(&opts)) {
18007 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
18008 		opt = opts.ipoptp_cur;
18009 		optlen = opts.ipoptp_len;
18010 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
18011 		    optval, optlen));
18012 		switch (optval) {
18013 			uint32_t off;
18014 		case IPOPT_SSRR:
18015 		case IPOPT_LSRR:
18016 			off = opt[IPOPT_OFFSET];
18017 			off--;
18018 			if (optlen < IP_ADDR_LEN ||
18019 			    off > optlen - IP_ADDR_LEN) {
18020 				/* End of source route */
18021 				ip1dbg(("ip_rput_local_options: end of SR\n"));
18022 				break;
18023 			}
18024 			/*
18025 			 * This will only happen if two consecutive entries
18026 			 * in the source route contains our address or if
18027 			 * it is a packet with a loose source route which
18028 			 * reaches us before consuming the whole source route
18029 			 */
18030 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
18031 			if (optval == IPOPT_SSRR) {
18032 				goto bad_src_route;
18033 			}
18034 			/*
18035 			 * Hack: instead of dropping the packet truncate the
18036 			 * source route to what has been used by filling the
18037 			 * rest with IPOPT_NOP.
18038 			 */
18039 			opt[IPOPT_OLEN] = (uint8_t)off;
18040 			while (off < optlen) {
18041 				opt[off++] = IPOPT_NOP;
18042 			}
18043 			break;
18044 		case IPOPT_RR:
18045 			off = opt[IPOPT_OFFSET];
18046 			off--;
18047 			if (optlen < IP_ADDR_LEN ||
18048 			    off > optlen - IP_ADDR_LEN) {
18049 				/* No more room - ignore */
18050 				ip1dbg((
18051 				    "ip_rput_local_options: end of RR\n"));
18052 				break;
18053 			}
18054 			bcopy(&ire->ire_src_addr, (char *)opt + off,
18055 			    IP_ADDR_LEN);
18056 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18057 			break;
18058 		case IPOPT_TS:
18059 			/* Insert timestamp if there is romm */
18060 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18061 			case IPOPT_TS_TSONLY:
18062 				off = IPOPT_TS_TIMELEN;
18063 				break;
18064 			case IPOPT_TS_PRESPEC:
18065 			case IPOPT_TS_PRESPEC_RFC791:
18066 				/* Verify that the address matched */
18067 				off = opt[IPOPT_OFFSET] - 1;
18068 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18069 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
18070 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
18071 				    ipst);
18072 				if (dst_ire == NULL) {
18073 					/* Not for us */
18074 					break;
18075 				}
18076 				ire_refrele(dst_ire);
18077 				/* FALLTHRU */
18078 			case IPOPT_TS_TSANDADDR:
18079 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18080 				break;
18081 			default:
18082 				/*
18083 				 * ip_*put_options should have already
18084 				 * dropped this packet.
18085 				 */
18086 				cmn_err(CE_PANIC, "ip_rput_local_options: "
18087 				    "unknown IT - bug in ip_rput_options?\n");
18088 				return (B_TRUE);	/* Keep "lint" happy */
18089 			}
18090 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
18091 				/* Increase overflow counter */
18092 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
18093 				opt[IPOPT_POS_OV_FLG] =
18094 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
18095 				    (off << 4));
18096 				break;
18097 			}
18098 			off = opt[IPOPT_OFFSET] - 1;
18099 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18100 			case IPOPT_TS_PRESPEC:
18101 			case IPOPT_TS_PRESPEC_RFC791:
18102 			case IPOPT_TS_TSANDADDR:
18103 				bcopy(&ire->ire_src_addr, (char *)opt + off,
18104 				    IP_ADDR_LEN);
18105 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
18106 				/* FALLTHRU */
18107 			case IPOPT_TS_TSONLY:
18108 				off = opt[IPOPT_OFFSET] - 1;
18109 				/* Compute # of milliseconds since midnight */
18110 				gethrestime(&now);
18111 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
18112 				    now.tv_nsec / (NANOSEC / MILLISEC);
18113 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
18114 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
18115 				break;
18116 			}
18117 			break;
18118 		}
18119 	}
18120 	return (B_TRUE);
18121 
18122 bad_src_route:
18123 	q = WR(q);
18124 	if (q->q_next != NULL)
18125 		ill = q->q_ptr;
18126 	else
18127 		ill = NULL;
18128 
18129 	/* make sure we clear any indication of a hardware checksum */
18130 	DB_CKSUMFLAGS(mp) = 0;
18131 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
18132 	if (zoneid == ALL_ZONES)
18133 		freemsg(mp);
18134 	else
18135 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18136 	return (B_FALSE);
18137 
18138 }
18139 
18140 /*
18141  * Process IP options in an inbound packet.  If an option affects the
18142  * effective destination address, return the next hop address via dstp.
18143  * Returns -1 if something fails in which case an ICMP error has been sent
18144  * and mp freed.
18145  */
18146 static int
18147 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
18148     ip_stack_t *ipst)
18149 {
18150 	ipoptp_t	opts;
18151 	uchar_t		*opt;
18152 	uint8_t		optval;
18153 	uint8_t		optlen;
18154 	ipaddr_t	dst;
18155 	intptr_t	code = 0;
18156 	ire_t		*ire = NULL;
18157 	zoneid_t	zoneid;
18158 	ill_t		*ill;
18159 
18160 	ip2dbg(("ip_rput_options\n"));
18161 	dst = ipha->ipha_dst;
18162 	for (optval = ipoptp_first(&opts, ipha);
18163 	    optval != IPOPT_EOL;
18164 	    optval = ipoptp_next(&opts)) {
18165 		opt = opts.ipoptp_cur;
18166 		optlen = opts.ipoptp_len;
18167 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
18168 		    optval, optlen));
18169 		/*
18170 		 * Note: we need to verify the checksum before we
18171 		 * modify anything thus this routine only extracts the next
18172 		 * hop dst from any source route.
18173 		 */
18174 		switch (optval) {
18175 			uint32_t off;
18176 		case IPOPT_SSRR:
18177 		case IPOPT_LSRR:
18178 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18179 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18180 			if (ire == NULL) {
18181 				if (optval == IPOPT_SSRR) {
18182 					ip1dbg(("ip_rput_options: not next"
18183 					    " strict source route 0x%x\n",
18184 					    ntohl(dst)));
18185 					code = (char *)&ipha->ipha_dst -
18186 					    (char *)ipha;
18187 					goto param_prob; /* RouterReq's */
18188 				}
18189 				ip2dbg(("ip_rput_options: "
18190 				    "not next source route 0x%x\n",
18191 				    ntohl(dst)));
18192 				break;
18193 			}
18194 			ire_refrele(ire);
18195 
18196 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18197 				ip1dbg((
18198 				    "ip_rput_options: bad option offset\n"));
18199 				code = (char *)&opt[IPOPT_OLEN] -
18200 				    (char *)ipha;
18201 				goto param_prob;
18202 			}
18203 			off = opt[IPOPT_OFFSET];
18204 			off--;
18205 		redo_srr:
18206 			if (optlen < IP_ADDR_LEN ||
18207 			    off > optlen - IP_ADDR_LEN) {
18208 				/* End of source route */
18209 				ip1dbg(("ip_rput_options: end of SR\n"));
18210 				break;
18211 			}
18212 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18213 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18214 			    ntohl(dst)));
18215 
18216 			/*
18217 			 * Check if our address is present more than
18218 			 * once as consecutive hops in source route.
18219 			 * XXX verify per-interface ip_forwarding
18220 			 * for source route?
18221 			 */
18222 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18223 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18224 
18225 			if (ire != NULL) {
18226 				ire_refrele(ire);
18227 				off += IP_ADDR_LEN;
18228 				goto redo_srr;
18229 			}
18230 
18231 			if (dst == htonl(INADDR_LOOPBACK)) {
18232 				ip1dbg(("ip_rput_options: loopback addr in "
18233 				    "source route!\n"));
18234 				goto bad_src_route;
18235 			}
18236 			/*
18237 			 * For strict: verify that dst is directly
18238 			 * reachable.
18239 			 */
18240 			if (optval == IPOPT_SSRR) {
18241 				ire = ire_ftable_lookup(dst, 0, 0,
18242 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18243 				    MBLK_GETLABEL(mp),
18244 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18245 				if (ire == NULL) {
18246 					ip1dbg(("ip_rput_options: SSRR not "
18247 					    "directly reachable: 0x%x\n",
18248 					    ntohl(dst)));
18249 					goto bad_src_route;
18250 				}
18251 				ire_refrele(ire);
18252 			}
18253 			/*
18254 			 * Defer update of the offset and the record route
18255 			 * until the packet is forwarded.
18256 			 */
18257 			break;
18258 		case IPOPT_RR:
18259 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18260 				ip1dbg((
18261 				    "ip_rput_options: bad option offset\n"));
18262 				code = (char *)&opt[IPOPT_OLEN] -
18263 				    (char *)ipha;
18264 				goto param_prob;
18265 			}
18266 			break;
18267 		case IPOPT_TS:
18268 			/*
18269 			 * Verify that length >= 5 and that there is either
18270 			 * room for another timestamp or that the overflow
18271 			 * counter is not maxed out.
18272 			 */
18273 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18274 			if (optlen < IPOPT_MINLEN_IT) {
18275 				goto param_prob;
18276 			}
18277 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18278 				ip1dbg((
18279 				    "ip_rput_options: bad option offset\n"));
18280 				code = (char *)&opt[IPOPT_OFFSET] -
18281 				    (char *)ipha;
18282 				goto param_prob;
18283 			}
18284 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18285 			case IPOPT_TS_TSONLY:
18286 				off = IPOPT_TS_TIMELEN;
18287 				break;
18288 			case IPOPT_TS_TSANDADDR:
18289 			case IPOPT_TS_PRESPEC:
18290 			case IPOPT_TS_PRESPEC_RFC791:
18291 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18292 				break;
18293 			default:
18294 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18295 				    (char *)ipha;
18296 				goto param_prob;
18297 			}
18298 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18299 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18300 				/*
18301 				 * No room and the overflow counter is 15
18302 				 * already.
18303 				 */
18304 				goto param_prob;
18305 			}
18306 			break;
18307 		}
18308 	}
18309 
18310 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18311 		*dstp = dst;
18312 		return (0);
18313 	}
18314 
18315 	ip1dbg(("ip_rput_options: error processing IP options."));
18316 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18317 
18318 param_prob:
18319 	q = WR(q);
18320 	if (q->q_next != NULL)
18321 		ill = q->q_ptr;
18322 	else
18323 		ill = NULL;
18324 
18325 	/* make sure we clear any indication of a hardware checksum */
18326 	DB_CKSUMFLAGS(mp) = 0;
18327 	/* Don't know whether this is for non-global or global/forwarding */
18328 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18329 	if (zoneid == ALL_ZONES)
18330 		freemsg(mp);
18331 	else
18332 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18333 	return (-1);
18334 
18335 bad_src_route:
18336 	q = WR(q);
18337 	if (q->q_next != NULL)
18338 		ill = q->q_ptr;
18339 	else
18340 		ill = NULL;
18341 
18342 	/* make sure we clear any indication of a hardware checksum */
18343 	DB_CKSUMFLAGS(mp) = 0;
18344 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18345 	if (zoneid == ALL_ZONES)
18346 		freemsg(mp);
18347 	else
18348 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18349 	return (-1);
18350 }
18351 
18352 /*
18353  * IP & ICMP info in >=14 msg's ...
18354  *  - ip fixed part (mib2_ip_t)
18355  *  - icmp fixed part (mib2_icmp_t)
18356  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18357  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18358  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18359  *  - ipRouteAttributeTable (ip 102)	labeled routes
18360  *  - ip multicast membership (ip_member_t)
18361  *  - ip multicast source filtering (ip_grpsrc_t)
18362  *  - igmp fixed part (struct igmpstat)
18363  *  - multicast routing stats (struct mrtstat)
18364  *  - multicast routing vifs (array of struct vifctl)
18365  *  - multicast routing routes (array of struct mfcctl)
18366  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18367  *					One per ill plus one generic
18368  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18369  *					One per ill plus one generic
18370  *  - ipv6RouteEntry			all IPv6 IREs
18371  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18372  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18373  *  - ipv6AddrEntry			all IPv6 ipifs
18374  *  - ipv6 multicast membership (ipv6_member_t)
18375  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18376  *
18377  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18378  *
18379  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18380  * already filled in by the caller.
18381  * Return value of 0 indicates that no messages were sent and caller
18382  * should free mpctl.
18383  */
18384 int
18385 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18386 {
18387 	ip_stack_t *ipst;
18388 	sctp_stack_t *sctps;
18389 
18390 	if (q->q_next != NULL) {
18391 		ipst = ILLQ_TO_IPST(q);
18392 	} else {
18393 		ipst = CONNQ_TO_IPST(q);
18394 	}
18395 	ASSERT(ipst != NULL);
18396 	sctps = ipst->ips_netstack->netstack_sctp;
18397 
18398 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18399 		return (0);
18400 	}
18401 
18402 	/*
18403 	 * For the purposes of the (broken) packet shell use
18404 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18405 	 * to make TCP and UDP appear first in the list of mib items.
18406 	 * TBD: We could expand this and use it in netstat so that
18407 	 * the kernel doesn't have to produce large tables (connections,
18408 	 * routes, etc) when netstat only wants the statistics or a particular
18409 	 * table.
18410 	 */
18411 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18412 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18413 			return (1);
18414 		}
18415 	}
18416 
18417 	if (level != MIB2_TCP) {
18418 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18419 			return (1);
18420 		}
18421 	}
18422 
18423 	if (level != MIB2_UDP) {
18424 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18425 			return (1);
18426 		}
18427 	}
18428 
18429 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18430 	    ipst)) == NULL) {
18431 		return (1);
18432 	}
18433 
18434 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18435 		return (1);
18436 	}
18437 
18438 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18439 		return (1);
18440 	}
18441 
18442 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18443 		return (1);
18444 	}
18445 
18446 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18447 		return (1);
18448 	}
18449 
18450 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18451 		return (1);
18452 	}
18453 
18454 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18455 		return (1);
18456 	}
18457 
18458 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18459 		return (1);
18460 	}
18461 
18462 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18463 		return (1);
18464 	}
18465 
18466 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18467 		return (1);
18468 	}
18469 
18470 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18471 		return (1);
18472 	}
18473 
18474 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18475 		return (1);
18476 	}
18477 
18478 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18479 		return (1);
18480 	}
18481 
18482 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18483 		return (1);
18484 	}
18485 
18486 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18487 		return (1);
18488 	}
18489 
18490 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18491 	if (mpctl == NULL) {
18492 		return (1);
18493 	}
18494 
18495 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18496 		return (1);
18497 	}
18498 	freemsg(mpctl);
18499 	return (1);
18500 }
18501 
18502 
18503 /* Get global (legacy) IPv4 statistics */
18504 static mblk_t *
18505 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18506     ip_stack_t *ipst)
18507 {
18508 	mib2_ip_t		old_ip_mib;
18509 	struct opthdr		*optp;
18510 	mblk_t			*mp2ctl;
18511 
18512 	/*
18513 	 * make a copy of the original message
18514 	 */
18515 	mp2ctl = copymsg(mpctl);
18516 
18517 	/* fixed length IP structure... */
18518 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18519 	optp->level = MIB2_IP;
18520 	optp->name = 0;
18521 	SET_MIB(old_ip_mib.ipForwarding,
18522 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18523 	SET_MIB(old_ip_mib.ipDefaultTTL,
18524 	    (uint32_t)ipst->ips_ip_def_ttl);
18525 	SET_MIB(old_ip_mib.ipReasmTimeout,
18526 	    ipst->ips_ip_g_frag_timeout);
18527 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18528 	    sizeof (mib2_ipAddrEntry_t));
18529 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18530 	    sizeof (mib2_ipRouteEntry_t));
18531 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18532 	    sizeof (mib2_ipNetToMediaEntry_t));
18533 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18534 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18535 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18536 	    sizeof (mib2_ipAttributeEntry_t));
18537 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18538 
18539 	/*
18540 	 * Grab the statistics from the new IP MIB
18541 	 */
18542 	SET_MIB(old_ip_mib.ipInReceives,
18543 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18544 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18545 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18546 	SET_MIB(old_ip_mib.ipForwDatagrams,
18547 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18548 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18549 	    ipmib->ipIfStatsInUnknownProtos);
18550 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18551 	SET_MIB(old_ip_mib.ipInDelivers,
18552 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18553 	SET_MIB(old_ip_mib.ipOutRequests,
18554 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18555 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18556 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18557 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18558 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18559 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18560 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18561 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18562 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18563 
18564 	/* ipRoutingDiscards is not being used */
18565 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18566 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18567 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18568 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18569 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18570 	    ipmib->ipIfStatsReasmDuplicates);
18571 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18572 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18573 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18574 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18575 	SET_MIB(old_ip_mib.rawipInOverflows,
18576 	    ipmib->rawipIfStatsInOverflows);
18577 
18578 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18579 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18580 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18581 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18582 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18583 	    ipmib->ipIfStatsOutSwitchIPVersion);
18584 
18585 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18586 	    (int)sizeof (old_ip_mib))) {
18587 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18588 		    (uint_t)sizeof (old_ip_mib)));
18589 	}
18590 
18591 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18592 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18593 	    (int)optp->level, (int)optp->name, (int)optp->len));
18594 	qreply(q, mpctl);
18595 	return (mp2ctl);
18596 }
18597 
18598 /* Per interface IPv4 statistics */
18599 static mblk_t *
18600 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18601 {
18602 	struct opthdr		*optp;
18603 	mblk_t			*mp2ctl;
18604 	ill_t			*ill;
18605 	ill_walk_context_t	ctx;
18606 	mblk_t			*mp_tail = NULL;
18607 	mib2_ipIfStatsEntry_t	global_ip_mib;
18608 
18609 	/*
18610 	 * Make a copy of the original message
18611 	 */
18612 	mp2ctl = copymsg(mpctl);
18613 
18614 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18615 	optp->level = MIB2_IP;
18616 	optp->name = MIB2_IP_TRAFFIC_STATS;
18617 	/* Include "unknown interface" ip_mib */
18618 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18619 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18620 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18621 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18622 	    (ipst->ips_ip_g_forward ? 1 : 2));
18623 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18624 	    (uint32_t)ipst->ips_ip_def_ttl);
18625 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18626 	    sizeof (mib2_ipIfStatsEntry_t));
18627 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18628 	    sizeof (mib2_ipAddrEntry_t));
18629 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18630 	    sizeof (mib2_ipRouteEntry_t));
18631 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18632 	    sizeof (mib2_ipNetToMediaEntry_t));
18633 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18634 	    sizeof (ip_member_t));
18635 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18636 	    sizeof (ip_grpsrc_t));
18637 
18638 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18639 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18640 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18641 		    "failed to allocate %u bytes\n",
18642 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18643 	}
18644 
18645 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18646 
18647 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18648 	ill = ILL_START_WALK_V4(&ctx, ipst);
18649 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18650 		ill->ill_ip_mib->ipIfStatsIfIndex =
18651 		    ill->ill_phyint->phyint_ifindex;
18652 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18653 		    (ipst->ips_ip_g_forward ? 1 : 2));
18654 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18655 		    (uint32_t)ipst->ips_ip_def_ttl);
18656 
18657 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18658 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18659 		    (char *)ill->ill_ip_mib,
18660 		    (int)sizeof (*ill->ill_ip_mib))) {
18661 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18662 			    "failed to allocate %u bytes\n",
18663 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18664 		}
18665 	}
18666 	rw_exit(&ipst->ips_ill_g_lock);
18667 
18668 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18669 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18670 	    "level %d, name %d, len %d\n",
18671 	    (int)optp->level, (int)optp->name, (int)optp->len));
18672 	qreply(q, mpctl);
18673 
18674 	if (mp2ctl == NULL)
18675 		return (NULL);
18676 
18677 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18678 }
18679 
18680 /* Global IPv4 ICMP statistics */
18681 static mblk_t *
18682 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18683 {
18684 	struct opthdr		*optp;
18685 	mblk_t			*mp2ctl;
18686 
18687 	/*
18688 	 * Make a copy of the original message
18689 	 */
18690 	mp2ctl = copymsg(mpctl);
18691 
18692 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18693 	optp->level = MIB2_ICMP;
18694 	optp->name = 0;
18695 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18696 	    (int)sizeof (ipst->ips_icmp_mib))) {
18697 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18698 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18699 	}
18700 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18701 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18702 	    (int)optp->level, (int)optp->name, (int)optp->len));
18703 	qreply(q, mpctl);
18704 	return (mp2ctl);
18705 }
18706 
18707 /* Global IPv4 IGMP statistics */
18708 static mblk_t *
18709 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18710 {
18711 	struct opthdr		*optp;
18712 	mblk_t			*mp2ctl;
18713 
18714 	/*
18715 	 * make a copy of the original message
18716 	 */
18717 	mp2ctl = copymsg(mpctl);
18718 
18719 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18720 	optp->level = EXPER_IGMP;
18721 	optp->name = 0;
18722 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18723 	    (int)sizeof (ipst->ips_igmpstat))) {
18724 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18725 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18726 	}
18727 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18728 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18729 	    (int)optp->level, (int)optp->name, (int)optp->len));
18730 	qreply(q, mpctl);
18731 	return (mp2ctl);
18732 }
18733 
18734 /* Global IPv4 Multicast Routing statistics */
18735 static mblk_t *
18736 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18737 {
18738 	struct opthdr		*optp;
18739 	mblk_t			*mp2ctl;
18740 
18741 	/*
18742 	 * make a copy of the original message
18743 	 */
18744 	mp2ctl = copymsg(mpctl);
18745 
18746 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18747 	optp->level = EXPER_DVMRP;
18748 	optp->name = 0;
18749 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18750 		ip0dbg(("ip_mroute_stats: failed\n"));
18751 	}
18752 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18753 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18754 	    (int)optp->level, (int)optp->name, (int)optp->len));
18755 	qreply(q, mpctl);
18756 	return (mp2ctl);
18757 }
18758 
18759 /* IPv4 address information */
18760 static mblk_t *
18761 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18762 {
18763 	struct opthdr		*optp;
18764 	mblk_t			*mp2ctl;
18765 	mblk_t			*mp_tail = NULL;
18766 	ill_t			*ill;
18767 	ipif_t			*ipif;
18768 	uint_t			bitval;
18769 	mib2_ipAddrEntry_t	mae;
18770 	zoneid_t		zoneid;
18771 	ill_walk_context_t ctx;
18772 
18773 	/*
18774 	 * make a copy of the original message
18775 	 */
18776 	mp2ctl = copymsg(mpctl);
18777 
18778 	/* ipAddrEntryTable */
18779 
18780 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18781 	optp->level = MIB2_IP;
18782 	optp->name = MIB2_IP_ADDR;
18783 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18784 
18785 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18786 	ill = ILL_START_WALK_V4(&ctx, ipst);
18787 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18788 		for (ipif = ill->ill_ipif; ipif != NULL;
18789 		    ipif = ipif->ipif_next) {
18790 			if (ipif->ipif_zoneid != zoneid &&
18791 			    ipif->ipif_zoneid != ALL_ZONES)
18792 				continue;
18793 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18794 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18795 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18796 
18797 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18798 			    OCTET_LENGTH);
18799 			mae.ipAdEntIfIndex.o_length =
18800 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18801 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18802 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18803 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18804 			mae.ipAdEntInfo.ae_subnet_len =
18805 			    ip_mask_to_plen(ipif->ipif_net_mask);
18806 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18807 			for (bitval = 1;
18808 			    bitval &&
18809 			    !(bitval & ipif->ipif_brd_addr);
18810 			    bitval <<= 1)
18811 				noop;
18812 			mae.ipAdEntBcastAddr = bitval;
18813 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18814 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18815 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18816 			mae.ipAdEntInfo.ae_broadcast_addr =
18817 			    ipif->ipif_brd_addr;
18818 			mae.ipAdEntInfo.ae_pp_dst_addr =
18819 			    ipif->ipif_pp_dst_addr;
18820 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18821 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18822 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18823 
18824 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18825 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18826 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18827 				    "allocate %u bytes\n",
18828 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18829 			}
18830 		}
18831 	}
18832 	rw_exit(&ipst->ips_ill_g_lock);
18833 
18834 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18835 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18836 	    (int)optp->level, (int)optp->name, (int)optp->len));
18837 	qreply(q, mpctl);
18838 	return (mp2ctl);
18839 }
18840 
18841 /* IPv6 address information */
18842 static mblk_t *
18843 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18844 {
18845 	struct opthdr		*optp;
18846 	mblk_t			*mp2ctl;
18847 	mblk_t			*mp_tail = NULL;
18848 	ill_t			*ill;
18849 	ipif_t			*ipif;
18850 	mib2_ipv6AddrEntry_t	mae6;
18851 	zoneid_t		zoneid;
18852 	ill_walk_context_t	ctx;
18853 
18854 	/*
18855 	 * make a copy of the original message
18856 	 */
18857 	mp2ctl = copymsg(mpctl);
18858 
18859 	/* ipv6AddrEntryTable */
18860 
18861 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18862 	optp->level = MIB2_IP6;
18863 	optp->name = MIB2_IP6_ADDR;
18864 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18865 
18866 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18867 	ill = ILL_START_WALK_V6(&ctx, ipst);
18868 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18869 		for (ipif = ill->ill_ipif; ipif != NULL;
18870 		    ipif = ipif->ipif_next) {
18871 			if (ipif->ipif_zoneid != zoneid &&
18872 			    ipif->ipif_zoneid != ALL_ZONES)
18873 				continue;
18874 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18875 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18876 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18877 
18878 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18879 			    OCTET_LENGTH);
18880 			mae6.ipv6AddrIfIndex.o_length =
18881 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18882 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18883 			mae6.ipv6AddrPfxLength =
18884 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18885 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18886 			mae6.ipv6AddrInfo.ae_subnet_len =
18887 			    mae6.ipv6AddrPfxLength;
18888 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18889 
18890 			/* Type: stateless(1), stateful(2), unknown(3) */
18891 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18892 				mae6.ipv6AddrType = 1;
18893 			else
18894 				mae6.ipv6AddrType = 2;
18895 			/* Anycast: true(1), false(2) */
18896 			if (ipif->ipif_flags & IPIF_ANYCAST)
18897 				mae6.ipv6AddrAnycastFlag = 1;
18898 			else
18899 				mae6.ipv6AddrAnycastFlag = 2;
18900 
18901 			/*
18902 			 * Address status: preferred(1), deprecated(2),
18903 			 * invalid(3), inaccessible(4), unknown(5)
18904 			 */
18905 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18906 				mae6.ipv6AddrStatus = 3;
18907 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18908 				mae6.ipv6AddrStatus = 2;
18909 			else
18910 				mae6.ipv6AddrStatus = 1;
18911 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18912 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18913 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18914 			    ipif->ipif_v6pp_dst_addr;
18915 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18916 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18917 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18918 			mae6.ipv6AddrIdentifier = ill->ill_token;
18919 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18920 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18921 			mae6.ipv6AddrRetransmitTime =
18922 			    ill->ill_reachable_retrans_time;
18923 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18924 			    (char *)&mae6,
18925 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18926 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18927 				    "allocate %u bytes\n",
18928 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18929 			}
18930 		}
18931 	}
18932 	rw_exit(&ipst->ips_ill_g_lock);
18933 
18934 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18935 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18936 	    (int)optp->level, (int)optp->name, (int)optp->len));
18937 	qreply(q, mpctl);
18938 	return (mp2ctl);
18939 }
18940 
18941 /* IPv4 multicast group membership. */
18942 static mblk_t *
18943 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18944 {
18945 	struct opthdr		*optp;
18946 	mblk_t			*mp2ctl;
18947 	ill_t			*ill;
18948 	ipif_t			*ipif;
18949 	ilm_t			*ilm;
18950 	ip_member_t		ipm;
18951 	mblk_t			*mp_tail = NULL;
18952 	ill_walk_context_t	ctx;
18953 	zoneid_t		zoneid;
18954 
18955 	/*
18956 	 * make a copy of the original message
18957 	 */
18958 	mp2ctl = copymsg(mpctl);
18959 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18960 
18961 	/* ipGroupMember table */
18962 	optp = (struct opthdr *)&mpctl->b_rptr[
18963 	    sizeof (struct T_optmgmt_ack)];
18964 	optp->level = MIB2_IP;
18965 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18966 
18967 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18968 	ill = ILL_START_WALK_V4(&ctx, ipst);
18969 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18970 		ILM_WALKER_HOLD(ill);
18971 		for (ipif = ill->ill_ipif; ipif != NULL;
18972 		    ipif = ipif->ipif_next) {
18973 			if (ipif->ipif_zoneid != zoneid &&
18974 			    ipif->ipif_zoneid != ALL_ZONES)
18975 				continue;	/* not this zone */
18976 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18977 			    OCTET_LENGTH);
18978 			ipm.ipGroupMemberIfIndex.o_length =
18979 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18980 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18981 				ASSERT(ilm->ilm_ipif != NULL);
18982 				ASSERT(ilm->ilm_ill == NULL);
18983 				if (ilm->ilm_ipif != ipif)
18984 					continue;
18985 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18986 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18987 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18988 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18989 				    (char *)&ipm, (int)sizeof (ipm))) {
18990 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18991 					    "failed to allocate %u bytes\n",
18992 					    (uint_t)sizeof (ipm)));
18993 				}
18994 			}
18995 		}
18996 		ILM_WALKER_RELE(ill);
18997 	}
18998 	rw_exit(&ipst->ips_ill_g_lock);
18999 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19000 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19001 	    (int)optp->level, (int)optp->name, (int)optp->len));
19002 	qreply(q, mpctl);
19003 	return (mp2ctl);
19004 }
19005 
19006 /* IPv6 multicast group membership. */
19007 static mblk_t *
19008 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19009 {
19010 	struct opthdr		*optp;
19011 	mblk_t			*mp2ctl;
19012 	ill_t			*ill;
19013 	ilm_t			*ilm;
19014 	ipv6_member_t		ipm6;
19015 	mblk_t			*mp_tail = NULL;
19016 	ill_walk_context_t	ctx;
19017 	zoneid_t		zoneid;
19018 
19019 	/*
19020 	 * make a copy of the original message
19021 	 */
19022 	mp2ctl = copymsg(mpctl);
19023 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19024 
19025 	/* ip6GroupMember table */
19026 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19027 	optp->level = MIB2_IP6;
19028 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
19029 
19030 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19031 	ill = ILL_START_WALK_V6(&ctx, ipst);
19032 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19033 		ILM_WALKER_HOLD(ill);
19034 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
19035 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19036 			ASSERT(ilm->ilm_ipif == NULL);
19037 			ASSERT(ilm->ilm_ill != NULL);
19038 			if (ilm->ilm_zoneid != zoneid)
19039 				continue;	/* not this zone */
19040 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
19041 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
19042 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
19043 			if (!snmp_append_data2(mpctl->b_cont,
19044 			    &mp_tail,
19045 			    (char *)&ipm6, (int)sizeof (ipm6))) {
19046 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
19047 				    "failed to allocate %u bytes\n",
19048 				    (uint_t)sizeof (ipm6)));
19049 			}
19050 		}
19051 		ILM_WALKER_RELE(ill);
19052 	}
19053 	rw_exit(&ipst->ips_ill_g_lock);
19054 
19055 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19056 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19057 	    (int)optp->level, (int)optp->name, (int)optp->len));
19058 	qreply(q, mpctl);
19059 	return (mp2ctl);
19060 }
19061 
19062 /* IP multicast filtered sources */
19063 static mblk_t *
19064 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19065 {
19066 	struct opthdr		*optp;
19067 	mblk_t			*mp2ctl;
19068 	ill_t			*ill;
19069 	ipif_t			*ipif;
19070 	ilm_t			*ilm;
19071 	ip_grpsrc_t		ips;
19072 	mblk_t			*mp_tail = NULL;
19073 	ill_walk_context_t	ctx;
19074 	zoneid_t		zoneid;
19075 	int			i;
19076 	slist_t			*sl;
19077 
19078 	/*
19079 	 * make a copy of the original message
19080 	 */
19081 	mp2ctl = copymsg(mpctl);
19082 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19083 
19084 	/* ipGroupSource table */
19085 	optp = (struct opthdr *)&mpctl->b_rptr[
19086 	    sizeof (struct T_optmgmt_ack)];
19087 	optp->level = MIB2_IP;
19088 	optp->name = EXPER_IP_GROUP_SOURCES;
19089 
19090 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19091 	ill = ILL_START_WALK_V4(&ctx, ipst);
19092 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19093 		ILM_WALKER_HOLD(ill);
19094 		for (ipif = ill->ill_ipif; ipif != NULL;
19095 		    ipif = ipif->ipif_next) {
19096 			if (ipif->ipif_zoneid != zoneid)
19097 				continue;	/* not this zone */
19098 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
19099 			    OCTET_LENGTH);
19100 			ips.ipGroupSourceIfIndex.o_length =
19101 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
19102 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19103 				ASSERT(ilm->ilm_ipif != NULL);
19104 				ASSERT(ilm->ilm_ill == NULL);
19105 				sl = ilm->ilm_filter;
19106 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
19107 					continue;
19108 				ips.ipGroupSourceGroup = ilm->ilm_addr;
19109 				for (i = 0; i < sl->sl_numsrc; i++) {
19110 					if (!IN6_IS_ADDR_V4MAPPED(
19111 					    &sl->sl_addr[i]))
19112 						continue;
19113 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
19114 					    ips.ipGroupSourceAddress);
19115 					if (snmp_append_data2(mpctl->b_cont,
19116 					    &mp_tail, (char *)&ips,
19117 					    (int)sizeof (ips)) == 0) {
19118 						ip1dbg(("ip_snmp_get_mib2_"
19119 						    "ip_group_src: failed to "
19120 						    "allocate %u bytes\n",
19121 						    (uint_t)sizeof (ips)));
19122 					}
19123 				}
19124 			}
19125 		}
19126 		ILM_WALKER_RELE(ill);
19127 	}
19128 	rw_exit(&ipst->ips_ill_g_lock);
19129 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19130 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19131 	    (int)optp->level, (int)optp->name, (int)optp->len));
19132 	qreply(q, mpctl);
19133 	return (mp2ctl);
19134 }
19135 
19136 /* IPv6 multicast filtered sources. */
19137 static mblk_t *
19138 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19139 {
19140 	struct opthdr		*optp;
19141 	mblk_t			*mp2ctl;
19142 	ill_t			*ill;
19143 	ilm_t			*ilm;
19144 	ipv6_grpsrc_t		ips6;
19145 	mblk_t			*mp_tail = NULL;
19146 	ill_walk_context_t	ctx;
19147 	zoneid_t		zoneid;
19148 	int			i;
19149 	slist_t			*sl;
19150 
19151 	/*
19152 	 * make a copy of the original message
19153 	 */
19154 	mp2ctl = copymsg(mpctl);
19155 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19156 
19157 	/* ip6GroupMember table */
19158 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19159 	optp->level = MIB2_IP6;
19160 	optp->name = EXPER_IP6_GROUP_SOURCES;
19161 
19162 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19163 	ill = ILL_START_WALK_V6(&ctx, ipst);
19164 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19165 		ILM_WALKER_HOLD(ill);
19166 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
19167 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
19168 			ASSERT(ilm->ilm_ipif == NULL);
19169 			ASSERT(ilm->ilm_ill != NULL);
19170 			sl = ilm->ilm_filter;
19171 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
19172 				continue;
19173 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
19174 			for (i = 0; i < sl->sl_numsrc; i++) {
19175 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
19176 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19177 				    (char *)&ips6, (int)sizeof (ips6))) {
19178 					ip1dbg(("ip_snmp_get_mib2_ip6_"
19179 					    "group_src: failed to allocate "
19180 					    "%u bytes\n",
19181 					    (uint_t)sizeof (ips6)));
19182 				}
19183 			}
19184 		}
19185 		ILM_WALKER_RELE(ill);
19186 	}
19187 	rw_exit(&ipst->ips_ill_g_lock);
19188 
19189 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19190 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
19191 	    (int)optp->level, (int)optp->name, (int)optp->len));
19192 	qreply(q, mpctl);
19193 	return (mp2ctl);
19194 }
19195 
19196 /* Multicast routing virtual interface table. */
19197 static mblk_t *
19198 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19199 {
19200 	struct opthdr		*optp;
19201 	mblk_t			*mp2ctl;
19202 
19203 	/*
19204 	 * make a copy of the original message
19205 	 */
19206 	mp2ctl = copymsg(mpctl);
19207 
19208 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19209 	optp->level = EXPER_DVMRP;
19210 	optp->name = EXPER_DVMRP_VIF;
19211 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19212 		ip0dbg(("ip_mroute_vif: failed\n"));
19213 	}
19214 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19215 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19216 	    (int)optp->level, (int)optp->name, (int)optp->len));
19217 	qreply(q, mpctl);
19218 	return (mp2ctl);
19219 }
19220 
19221 /* Multicast routing table. */
19222 static mblk_t *
19223 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19224 {
19225 	struct opthdr		*optp;
19226 	mblk_t			*mp2ctl;
19227 
19228 	/*
19229 	 * make a copy of the original message
19230 	 */
19231 	mp2ctl = copymsg(mpctl);
19232 
19233 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19234 	optp->level = EXPER_DVMRP;
19235 	optp->name = EXPER_DVMRP_MRT;
19236 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19237 		ip0dbg(("ip_mroute_mrt: failed\n"));
19238 	}
19239 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19240 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19241 	    (int)optp->level, (int)optp->name, (int)optp->len));
19242 	qreply(q, mpctl);
19243 	return (mp2ctl);
19244 }
19245 
19246 /*
19247  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19248  * in one IRE walk.
19249  */
19250 static mblk_t *
19251 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19252 {
19253 	struct opthdr	*optp;
19254 	mblk_t		*mp2ctl;	/* Returned */
19255 	mblk_t		*mp3ctl;	/* nettomedia */
19256 	mblk_t		*mp4ctl;	/* routeattrs */
19257 	iproutedata_t	ird;
19258 	zoneid_t	zoneid;
19259 
19260 	/*
19261 	 * make copies of the original message
19262 	 *	- mp2ctl is returned unchanged to the caller for his use
19263 	 *	- mpctl is sent upstream as ipRouteEntryTable
19264 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19265 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19266 	 */
19267 	mp2ctl = copymsg(mpctl);
19268 	mp3ctl = copymsg(mpctl);
19269 	mp4ctl = copymsg(mpctl);
19270 	if (mp3ctl == NULL || mp4ctl == NULL) {
19271 		freemsg(mp4ctl);
19272 		freemsg(mp3ctl);
19273 		freemsg(mp2ctl);
19274 		freemsg(mpctl);
19275 		return (NULL);
19276 	}
19277 
19278 	bzero(&ird, sizeof (ird));
19279 
19280 	ird.ird_route.lp_head = mpctl->b_cont;
19281 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19282 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19283 
19284 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19285 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19286 
19287 	/* ipRouteEntryTable in mpctl */
19288 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19289 	optp->level = MIB2_IP;
19290 	optp->name = MIB2_IP_ROUTE;
19291 	optp->len = msgdsize(ird.ird_route.lp_head);
19292 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19293 	    (int)optp->level, (int)optp->name, (int)optp->len));
19294 	qreply(q, mpctl);
19295 
19296 	/* ipNetToMediaEntryTable in mp3ctl */
19297 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19298 	optp->level = MIB2_IP;
19299 	optp->name = MIB2_IP_MEDIA;
19300 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19301 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19302 	    (int)optp->level, (int)optp->name, (int)optp->len));
19303 	qreply(q, mp3ctl);
19304 
19305 	/* ipRouteAttributeTable in mp4ctl */
19306 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19307 	optp->level = MIB2_IP;
19308 	optp->name = EXPER_IP_RTATTR;
19309 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19310 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19311 	    (int)optp->level, (int)optp->name, (int)optp->len));
19312 	if (optp->len == 0)
19313 		freemsg(mp4ctl);
19314 	else
19315 		qreply(q, mp4ctl);
19316 
19317 	return (mp2ctl);
19318 }
19319 
19320 /*
19321  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19322  * ipv6NetToMediaEntryTable in an NDP walk.
19323  */
19324 static mblk_t *
19325 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19326 {
19327 	struct opthdr	*optp;
19328 	mblk_t		*mp2ctl;	/* Returned */
19329 	mblk_t		*mp3ctl;	/* nettomedia */
19330 	mblk_t		*mp4ctl;	/* routeattrs */
19331 	iproutedata_t	ird;
19332 	zoneid_t	zoneid;
19333 
19334 	/*
19335 	 * make copies of the original message
19336 	 *	- mp2ctl is returned unchanged to the caller for his use
19337 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19338 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19339 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19340 	 */
19341 	mp2ctl = copymsg(mpctl);
19342 	mp3ctl = copymsg(mpctl);
19343 	mp4ctl = copymsg(mpctl);
19344 	if (mp3ctl == NULL || mp4ctl == NULL) {
19345 		freemsg(mp4ctl);
19346 		freemsg(mp3ctl);
19347 		freemsg(mp2ctl);
19348 		freemsg(mpctl);
19349 		return (NULL);
19350 	}
19351 
19352 	bzero(&ird, sizeof (ird));
19353 
19354 	ird.ird_route.lp_head = mpctl->b_cont;
19355 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19356 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19357 
19358 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19359 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19360 
19361 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19362 	optp->level = MIB2_IP6;
19363 	optp->name = MIB2_IP6_ROUTE;
19364 	optp->len = msgdsize(ird.ird_route.lp_head);
19365 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19366 	    (int)optp->level, (int)optp->name, (int)optp->len));
19367 	qreply(q, mpctl);
19368 
19369 	/* ipv6NetToMediaEntryTable in mp3ctl */
19370 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19371 
19372 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19373 	optp->level = MIB2_IP6;
19374 	optp->name = MIB2_IP6_MEDIA;
19375 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19376 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19377 	    (int)optp->level, (int)optp->name, (int)optp->len));
19378 	qreply(q, mp3ctl);
19379 
19380 	/* ipv6RouteAttributeTable in mp4ctl */
19381 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19382 	optp->level = MIB2_IP6;
19383 	optp->name = EXPER_IP_RTATTR;
19384 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19385 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19386 	    (int)optp->level, (int)optp->name, (int)optp->len));
19387 	if (optp->len == 0)
19388 		freemsg(mp4ctl);
19389 	else
19390 		qreply(q, mp4ctl);
19391 
19392 	return (mp2ctl);
19393 }
19394 
19395 /*
19396  * IPv6 mib: One per ill
19397  */
19398 static mblk_t *
19399 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19400 {
19401 	struct opthdr		*optp;
19402 	mblk_t			*mp2ctl;
19403 	ill_t			*ill;
19404 	ill_walk_context_t	ctx;
19405 	mblk_t			*mp_tail = NULL;
19406 
19407 	/*
19408 	 * Make a copy of the original message
19409 	 */
19410 	mp2ctl = copymsg(mpctl);
19411 
19412 	/* fixed length IPv6 structure ... */
19413 
19414 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19415 	optp->level = MIB2_IP6;
19416 	optp->name = 0;
19417 	/* Include "unknown interface" ip6_mib */
19418 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19419 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19420 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19421 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19422 	    ipst->ips_ipv6_forward ? 1 : 2);
19423 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19424 	    ipst->ips_ipv6_def_hops);
19425 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19426 	    sizeof (mib2_ipIfStatsEntry_t));
19427 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19428 	    sizeof (mib2_ipv6AddrEntry_t));
19429 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19430 	    sizeof (mib2_ipv6RouteEntry_t));
19431 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19432 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19433 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19434 	    sizeof (ipv6_member_t));
19435 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19436 	    sizeof (ipv6_grpsrc_t));
19437 
19438 	/*
19439 	 * Synchronize 64- and 32-bit counters
19440 	 */
19441 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19442 	    ipIfStatsHCInReceives);
19443 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19444 	    ipIfStatsHCInDelivers);
19445 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19446 	    ipIfStatsHCOutRequests);
19447 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19448 	    ipIfStatsHCOutForwDatagrams);
19449 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19450 	    ipIfStatsHCOutMcastPkts);
19451 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19452 	    ipIfStatsHCInMcastPkts);
19453 
19454 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19455 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19456 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19457 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19458 	}
19459 
19460 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19461 	ill = ILL_START_WALK_V6(&ctx, ipst);
19462 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19463 		ill->ill_ip_mib->ipIfStatsIfIndex =
19464 		    ill->ill_phyint->phyint_ifindex;
19465 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19466 		    ipst->ips_ipv6_forward ? 1 : 2);
19467 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19468 		    ill->ill_max_hops);
19469 
19470 		/*
19471 		 * Synchronize 64- and 32-bit counters
19472 		 */
19473 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19474 		    ipIfStatsHCInReceives);
19475 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19476 		    ipIfStatsHCInDelivers);
19477 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19478 		    ipIfStatsHCOutRequests);
19479 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19480 		    ipIfStatsHCOutForwDatagrams);
19481 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19482 		    ipIfStatsHCOutMcastPkts);
19483 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19484 		    ipIfStatsHCInMcastPkts);
19485 
19486 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19487 		    (char *)ill->ill_ip_mib,
19488 		    (int)sizeof (*ill->ill_ip_mib))) {
19489 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19490 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19491 		}
19492 	}
19493 	rw_exit(&ipst->ips_ill_g_lock);
19494 
19495 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19496 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19497 	    (int)optp->level, (int)optp->name, (int)optp->len));
19498 	qreply(q, mpctl);
19499 	return (mp2ctl);
19500 }
19501 
19502 /*
19503  * ICMPv6 mib: One per ill
19504  */
19505 static mblk_t *
19506 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19507 {
19508 	struct opthdr		*optp;
19509 	mblk_t			*mp2ctl;
19510 	ill_t			*ill;
19511 	ill_walk_context_t	ctx;
19512 	mblk_t			*mp_tail = NULL;
19513 	/*
19514 	 * Make a copy of the original message
19515 	 */
19516 	mp2ctl = copymsg(mpctl);
19517 
19518 	/* fixed length ICMPv6 structure ... */
19519 
19520 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19521 	optp->level = MIB2_ICMP6;
19522 	optp->name = 0;
19523 	/* Include "unknown interface" icmp6_mib */
19524 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19525 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19526 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19527 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19528 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19529 	    (char *)&ipst->ips_icmp6_mib,
19530 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19531 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19532 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19533 	}
19534 
19535 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19536 	ill = ILL_START_WALK_V6(&ctx, ipst);
19537 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19538 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19539 		    ill->ill_phyint->phyint_ifindex;
19540 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19541 		    (char *)ill->ill_icmp6_mib,
19542 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19543 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19544 			    "%u bytes\n",
19545 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19546 		}
19547 	}
19548 	rw_exit(&ipst->ips_ill_g_lock);
19549 
19550 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19551 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19552 	    (int)optp->level, (int)optp->name, (int)optp->len));
19553 	qreply(q, mpctl);
19554 	return (mp2ctl);
19555 }
19556 
19557 /*
19558  * ire_walk routine to create both ipRouteEntryTable and
19559  * ipRouteAttributeTable in one IRE walk
19560  */
19561 static void
19562 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19563 {
19564 	ill_t				*ill;
19565 	ipif_t				*ipif;
19566 	mib2_ipRouteEntry_t		*re;
19567 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19568 	ipaddr_t			gw_addr;
19569 	tsol_ire_gw_secattr_t		*attrp;
19570 	tsol_gc_t			*gc = NULL;
19571 	tsol_gcgrp_t			*gcgrp = NULL;
19572 	uint_t				sacnt = 0;
19573 	int				i;
19574 
19575 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19576 
19577 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19578 		return;
19579 
19580 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19581 		mutex_enter(&attrp->igsa_lock);
19582 		if ((gc = attrp->igsa_gc) != NULL) {
19583 			gcgrp = gc->gc_grp;
19584 			ASSERT(gcgrp != NULL);
19585 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19586 			sacnt = 1;
19587 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19588 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19589 			gc = gcgrp->gcgrp_head;
19590 			sacnt = gcgrp->gcgrp_count;
19591 		}
19592 		mutex_exit(&attrp->igsa_lock);
19593 
19594 		/* do nothing if there's no gc to report */
19595 		if (gc == NULL) {
19596 			ASSERT(sacnt == 0);
19597 			if (gcgrp != NULL) {
19598 				/* we might as well drop the lock now */
19599 				rw_exit(&gcgrp->gcgrp_rwlock);
19600 				gcgrp = NULL;
19601 			}
19602 			attrp = NULL;
19603 		}
19604 
19605 		ASSERT(gc == NULL || (gcgrp != NULL &&
19606 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19607 	}
19608 	ASSERT(sacnt == 0 || gc != NULL);
19609 
19610 	if (sacnt != 0 &&
19611 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19612 		kmem_free(re, sizeof (*re));
19613 		rw_exit(&gcgrp->gcgrp_rwlock);
19614 		return;
19615 	}
19616 
19617 	/*
19618 	 * Return all IRE types for route table... let caller pick and choose
19619 	 */
19620 	re->ipRouteDest = ire->ire_addr;
19621 	ipif = ire->ire_ipif;
19622 	re->ipRouteIfIndex.o_length = 0;
19623 	if (ire->ire_type == IRE_CACHE) {
19624 		ill = (ill_t *)ire->ire_stq->q_ptr;
19625 		re->ipRouteIfIndex.o_length =
19626 		    ill->ill_name_length == 0 ? 0 :
19627 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19628 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19629 		    re->ipRouteIfIndex.o_length);
19630 	} else if (ipif != NULL) {
19631 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19632 		re->ipRouteIfIndex.o_length =
19633 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19634 	}
19635 	re->ipRouteMetric1 = -1;
19636 	re->ipRouteMetric2 = -1;
19637 	re->ipRouteMetric3 = -1;
19638 	re->ipRouteMetric4 = -1;
19639 
19640 	gw_addr = ire->ire_gateway_addr;
19641 
19642 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19643 		re->ipRouteNextHop = ire->ire_src_addr;
19644 	else
19645 		re->ipRouteNextHop = gw_addr;
19646 	/* indirect(4), direct(3), or invalid(2) */
19647 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19648 		re->ipRouteType = 2;
19649 	else
19650 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19651 	re->ipRouteProto = -1;
19652 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19653 	re->ipRouteMask = ire->ire_mask;
19654 	re->ipRouteMetric5 = -1;
19655 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19656 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19657 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19658 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19659 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19660 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19661 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19662 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19663 
19664 	if (ire->ire_flags & RTF_DYNAMIC) {
19665 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19666 	} else {
19667 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19668 	}
19669 
19670 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19671 	    (char *)re, (int)sizeof (*re))) {
19672 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19673 		    (uint_t)sizeof (*re)));
19674 	}
19675 
19676 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19677 		iaeptr->iae_routeidx = ird->ird_idx;
19678 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19679 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19680 	}
19681 
19682 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19683 	    (char *)iae, sacnt * sizeof (*iae))) {
19684 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19685 		    (unsigned)(sacnt * sizeof (*iae))));
19686 	}
19687 
19688 	/* bump route index for next pass */
19689 	ird->ird_idx++;
19690 
19691 	kmem_free(re, sizeof (*re));
19692 	if (sacnt != 0)
19693 		kmem_free(iae, sacnt * sizeof (*iae));
19694 
19695 	if (gcgrp != NULL)
19696 		rw_exit(&gcgrp->gcgrp_rwlock);
19697 }
19698 
19699 /*
19700  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19701  */
19702 static void
19703 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19704 {
19705 	ill_t				*ill;
19706 	ipif_t				*ipif;
19707 	mib2_ipv6RouteEntry_t		*re;
19708 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19709 	in6_addr_t			gw_addr_v6;
19710 	tsol_ire_gw_secattr_t		*attrp;
19711 	tsol_gc_t			*gc = NULL;
19712 	tsol_gcgrp_t			*gcgrp = NULL;
19713 	uint_t				sacnt = 0;
19714 	int				i;
19715 
19716 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19717 
19718 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19719 		return;
19720 
19721 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19722 		mutex_enter(&attrp->igsa_lock);
19723 		if ((gc = attrp->igsa_gc) != NULL) {
19724 			gcgrp = gc->gc_grp;
19725 			ASSERT(gcgrp != NULL);
19726 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19727 			sacnt = 1;
19728 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19729 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19730 			gc = gcgrp->gcgrp_head;
19731 			sacnt = gcgrp->gcgrp_count;
19732 		}
19733 		mutex_exit(&attrp->igsa_lock);
19734 
19735 		/* do nothing if there's no gc to report */
19736 		if (gc == NULL) {
19737 			ASSERT(sacnt == 0);
19738 			if (gcgrp != NULL) {
19739 				/* we might as well drop the lock now */
19740 				rw_exit(&gcgrp->gcgrp_rwlock);
19741 				gcgrp = NULL;
19742 			}
19743 			attrp = NULL;
19744 		}
19745 
19746 		ASSERT(gc == NULL || (gcgrp != NULL &&
19747 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19748 	}
19749 	ASSERT(sacnt == 0 || gc != NULL);
19750 
19751 	if (sacnt != 0 &&
19752 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19753 		kmem_free(re, sizeof (*re));
19754 		rw_exit(&gcgrp->gcgrp_rwlock);
19755 		return;
19756 	}
19757 
19758 	/*
19759 	 * Return all IRE types for route table... let caller pick and choose
19760 	 */
19761 	re->ipv6RouteDest = ire->ire_addr_v6;
19762 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19763 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19764 	re->ipv6RouteIfIndex.o_length = 0;
19765 	ipif = ire->ire_ipif;
19766 	if (ire->ire_type == IRE_CACHE) {
19767 		ill = (ill_t *)ire->ire_stq->q_ptr;
19768 		re->ipv6RouteIfIndex.o_length =
19769 		    ill->ill_name_length == 0 ? 0 :
19770 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19771 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19772 		    re->ipv6RouteIfIndex.o_length);
19773 	} else if (ipif != NULL) {
19774 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19775 		re->ipv6RouteIfIndex.o_length =
19776 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19777 	}
19778 
19779 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19780 
19781 	mutex_enter(&ire->ire_lock);
19782 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19783 	mutex_exit(&ire->ire_lock);
19784 
19785 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19786 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19787 	else
19788 		re->ipv6RouteNextHop = gw_addr_v6;
19789 
19790 	/* remote(4), local(3), or discard(2) */
19791 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19792 		re->ipv6RouteType = 2;
19793 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19794 		re->ipv6RouteType = 3;
19795 	else
19796 		re->ipv6RouteType = 4;
19797 
19798 	re->ipv6RouteProtocol	= -1;
19799 	re->ipv6RoutePolicy	= 0;
19800 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19801 	re->ipv6RouteNextHopRDI	= 0;
19802 	re->ipv6RouteWeight	= 0;
19803 	re->ipv6RouteMetric	= 0;
19804 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19805 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19806 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19807 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19808 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19809 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19810 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19811 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19812 
19813 	if (ire->ire_flags & RTF_DYNAMIC) {
19814 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19815 	} else {
19816 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19817 	}
19818 
19819 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19820 	    (char *)re, (int)sizeof (*re))) {
19821 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19822 		    (uint_t)sizeof (*re)));
19823 	}
19824 
19825 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19826 		iaeptr->iae_routeidx = ird->ird_idx;
19827 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19828 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19829 	}
19830 
19831 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19832 	    (char *)iae, sacnt * sizeof (*iae))) {
19833 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19834 		    (unsigned)(sacnt * sizeof (*iae))));
19835 	}
19836 
19837 	/* bump route index for next pass */
19838 	ird->ird_idx++;
19839 
19840 	kmem_free(re, sizeof (*re));
19841 	if (sacnt != 0)
19842 		kmem_free(iae, sacnt * sizeof (*iae));
19843 
19844 	if (gcgrp != NULL)
19845 		rw_exit(&gcgrp->gcgrp_rwlock);
19846 }
19847 
19848 /*
19849  * ndp_walk routine to create ipv6NetToMediaEntryTable
19850  */
19851 static int
19852 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19853 {
19854 	ill_t				*ill;
19855 	mib2_ipv6NetToMediaEntry_t	ntme;
19856 	dl_unitdata_req_t		*dl;
19857 
19858 	ill = nce->nce_ill;
19859 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19860 		return (0);
19861 
19862 	/*
19863 	 * Neighbor cache entry attached to IRE with on-link
19864 	 * destination.
19865 	 */
19866 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19867 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19868 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19869 	    (nce->nce_res_mp != NULL)) {
19870 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19871 		ntme.ipv6NetToMediaPhysAddress.o_length =
19872 		    dl->dl_dest_addr_length;
19873 	} else {
19874 		ntme.ipv6NetToMediaPhysAddress.o_length =
19875 		    ill->ill_phys_addr_length;
19876 	}
19877 	if (nce->nce_res_mp != NULL) {
19878 		bcopy((char *)nce->nce_res_mp->b_rptr +
19879 		    NCE_LL_ADDR_OFFSET(ill),
19880 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19881 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19882 	} else {
19883 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19884 		    ill->ill_phys_addr_length);
19885 	}
19886 	/*
19887 	 * Note: Returns ND_* states. Should be:
19888 	 * reachable(1), stale(2), delay(3), probe(4),
19889 	 * invalid(5), unknown(6)
19890 	 */
19891 	ntme.ipv6NetToMediaState = nce->nce_state;
19892 	ntme.ipv6NetToMediaLastUpdated = 0;
19893 
19894 	/* other(1), dynamic(2), static(3), local(4) */
19895 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19896 		ntme.ipv6NetToMediaType = 4;
19897 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19898 		ntme.ipv6NetToMediaType = 1;
19899 	} else {
19900 		ntme.ipv6NetToMediaType = 2;
19901 	}
19902 
19903 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19904 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19905 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19906 		    (uint_t)sizeof (ntme)));
19907 	}
19908 	return (0);
19909 }
19910 
19911 /*
19912  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19913  */
19914 /* ARGSUSED */
19915 int
19916 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19917 {
19918 	switch (level) {
19919 	case MIB2_IP:
19920 	case MIB2_ICMP:
19921 		switch (name) {
19922 		default:
19923 			break;
19924 		}
19925 		return (1);
19926 	default:
19927 		return (1);
19928 	}
19929 }
19930 
19931 /*
19932  * When there exists both a 64- and 32-bit counter of a particular type
19933  * (i.e., InReceives), only the 64-bit counters are added.
19934  */
19935 void
19936 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19937 {
19938 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19939 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19940 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19941 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19942 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19943 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19944 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19945 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19946 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19947 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19948 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19949 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19950 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19951 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19952 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19953 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19954 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19955 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19956 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19957 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19958 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19959 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19960 	    o2->ipIfStatsInWrongIPVersion);
19961 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19962 	    o2->ipIfStatsInWrongIPVersion);
19963 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19964 	    o2->ipIfStatsOutSwitchIPVersion);
19965 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19966 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19967 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19968 	    o2->ipIfStatsHCInForwDatagrams);
19969 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19970 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19971 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19972 	    o2->ipIfStatsHCOutForwDatagrams);
19973 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19974 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19975 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19976 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19977 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19978 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19979 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19980 	    o2->ipIfStatsHCOutMcastOctets);
19981 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19982 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19983 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19984 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19985 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19986 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19987 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19988 }
19989 
19990 void
19991 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19992 {
19993 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19994 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19995 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19996 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19997 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19998 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19999 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
20000 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
20001 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
20002 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
20003 	    o2->ipv6IfIcmpInRouterSolicits);
20004 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
20005 	    o2->ipv6IfIcmpInRouterAdvertisements);
20006 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
20007 	    o2->ipv6IfIcmpInNeighborSolicits);
20008 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
20009 	    o2->ipv6IfIcmpInNeighborAdvertisements);
20010 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
20011 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
20012 	    o2->ipv6IfIcmpInGroupMembQueries);
20013 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
20014 	    o2->ipv6IfIcmpInGroupMembResponses);
20015 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
20016 	    o2->ipv6IfIcmpInGroupMembReductions);
20017 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
20018 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
20019 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
20020 	    o2->ipv6IfIcmpOutDestUnreachs);
20021 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
20022 	    o2->ipv6IfIcmpOutAdminProhibs);
20023 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
20024 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
20025 	    o2->ipv6IfIcmpOutParmProblems);
20026 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
20027 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
20028 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
20029 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
20030 	    o2->ipv6IfIcmpOutRouterSolicits);
20031 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
20032 	    o2->ipv6IfIcmpOutRouterAdvertisements);
20033 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
20034 	    o2->ipv6IfIcmpOutNeighborSolicits);
20035 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
20036 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
20037 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
20038 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
20039 	    o2->ipv6IfIcmpOutGroupMembQueries);
20040 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
20041 	    o2->ipv6IfIcmpOutGroupMembResponses);
20042 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
20043 	    o2->ipv6IfIcmpOutGroupMembReductions);
20044 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
20045 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
20046 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
20047 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
20048 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
20049 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
20050 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
20051 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
20052 	    o2->ipv6IfIcmpInGroupMembTotal);
20053 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
20054 	    o2->ipv6IfIcmpInGroupMembBadQueries);
20055 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
20056 	    o2->ipv6IfIcmpInGroupMembBadReports);
20057 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
20058 	    o2->ipv6IfIcmpInGroupMembOurReports);
20059 }
20060 
20061 /*
20062  * Called before the options are updated to check if this packet will
20063  * be source routed from here.
20064  * This routine assumes that the options are well formed i.e. that they
20065  * have already been checked.
20066  */
20067 static boolean_t
20068 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
20069 {
20070 	ipoptp_t	opts;
20071 	uchar_t		*opt;
20072 	uint8_t		optval;
20073 	uint8_t		optlen;
20074 	ipaddr_t	dst;
20075 	ire_t		*ire;
20076 
20077 	if (IS_SIMPLE_IPH(ipha)) {
20078 		ip2dbg(("not source routed\n"));
20079 		return (B_FALSE);
20080 	}
20081 	dst = ipha->ipha_dst;
20082 	for (optval = ipoptp_first(&opts, ipha);
20083 	    optval != IPOPT_EOL;
20084 	    optval = ipoptp_next(&opts)) {
20085 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
20086 		opt = opts.ipoptp_cur;
20087 		optlen = opts.ipoptp_len;
20088 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
20089 		    optval, optlen));
20090 		switch (optval) {
20091 			uint32_t off;
20092 		case IPOPT_SSRR:
20093 		case IPOPT_LSRR:
20094 			/*
20095 			 * If dst is one of our addresses and there are some
20096 			 * entries left in the source route return (true).
20097 			 */
20098 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
20099 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
20100 			if (ire == NULL) {
20101 				ip2dbg(("ip_source_routed: not next"
20102 				    " source route 0x%x\n",
20103 				    ntohl(dst)));
20104 				return (B_FALSE);
20105 			}
20106 			ire_refrele(ire);
20107 			off = opt[IPOPT_OFFSET];
20108 			off--;
20109 			if (optlen < IP_ADDR_LEN ||
20110 			    off > optlen - IP_ADDR_LEN) {
20111 				/* End of source route */
20112 				ip1dbg(("ip_source_routed: end of SR\n"));
20113 				return (B_FALSE);
20114 			}
20115 			return (B_TRUE);
20116 		}
20117 	}
20118 	ip2dbg(("not source routed\n"));
20119 	return (B_FALSE);
20120 }
20121 
20122 /*
20123  * Check if the packet contains any source route.
20124  */
20125 static boolean_t
20126 ip_source_route_included(ipha_t *ipha)
20127 {
20128 	ipoptp_t	opts;
20129 	uint8_t		optval;
20130 
20131 	if (IS_SIMPLE_IPH(ipha))
20132 		return (B_FALSE);
20133 	for (optval = ipoptp_first(&opts, ipha);
20134 	    optval != IPOPT_EOL;
20135 	    optval = ipoptp_next(&opts)) {
20136 		switch (optval) {
20137 		case IPOPT_SSRR:
20138 		case IPOPT_LSRR:
20139 			return (B_TRUE);
20140 		}
20141 	}
20142 	return (B_FALSE);
20143 }
20144 
20145 /*
20146  * Called when the IRE expiration timer fires.
20147  */
20148 void
20149 ip_trash_timer_expire(void *args)
20150 {
20151 	int			flush_flag = 0;
20152 	ire_expire_arg_t	iea;
20153 	ip_stack_t		*ipst = (ip_stack_t *)args;
20154 
20155 	iea.iea_ipst = ipst;	/* No netstack_hold */
20156 
20157 	/*
20158 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
20159 	 * This lock makes sure that a new invocation of this function
20160 	 * that occurs due to an almost immediate timer firing will not
20161 	 * progress beyond this point until the current invocation is done
20162 	 */
20163 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20164 	ipst->ips_ip_ire_expire_id = 0;
20165 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20166 
20167 	/* Periodic timer */
20168 	if (ipst->ips_ip_ire_arp_time_elapsed >=
20169 	    ipst->ips_ip_ire_arp_interval) {
20170 		/*
20171 		 * Remove all IRE_CACHE entries since they might
20172 		 * contain arp information.
20173 		 */
20174 		flush_flag |= FLUSH_ARP_TIME;
20175 		ipst->ips_ip_ire_arp_time_elapsed = 0;
20176 		IP_STAT(ipst, ip_ire_arp_timer_expired);
20177 	}
20178 	if (ipst->ips_ip_ire_rd_time_elapsed >=
20179 	    ipst->ips_ip_ire_redir_interval) {
20180 		/* Remove all redirects */
20181 		flush_flag |= FLUSH_REDIRECT_TIME;
20182 		ipst->ips_ip_ire_rd_time_elapsed = 0;
20183 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
20184 	}
20185 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20186 	    ipst->ips_ip_ire_pathmtu_interval) {
20187 		/* Increase path mtu */
20188 		flush_flag |= FLUSH_MTU_TIME;
20189 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20190 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20191 	}
20192 
20193 	/*
20194 	 * Optimize for the case when there are no redirects in the
20195 	 * ftable, that is, no need to walk the ftable in that case.
20196 	 */
20197 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20198 		iea.iea_flush_flag = flush_flag;
20199 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20200 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20201 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20202 		    NULL, ALL_ZONES, ipst);
20203 	}
20204 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20205 	    ipst->ips_ip_redirect_cnt > 0) {
20206 		iea.iea_flush_flag = flush_flag;
20207 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20208 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20209 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20210 	}
20211 	if (flush_flag & FLUSH_MTU_TIME) {
20212 		/*
20213 		 * Walk all IPv6 IRE's and update them
20214 		 * Note that ARP and redirect timers are not
20215 		 * needed since NUD handles stale entries.
20216 		 */
20217 		flush_flag = FLUSH_MTU_TIME;
20218 		iea.iea_flush_flag = flush_flag;
20219 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20220 		    ALL_ZONES, ipst);
20221 	}
20222 
20223 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20224 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20225 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20226 
20227 	/*
20228 	 * Hold the lock to serialize timeout calls and prevent
20229 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20230 	 * for the timer to fire and a new invocation of this function
20231 	 * to start before the return value of timeout has been stored
20232 	 * in ip_ire_expire_id by the current invocation.
20233 	 */
20234 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20235 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20236 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20237 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20238 }
20239 
20240 /*
20241  * Called by the memory allocator subsystem directly, when the system
20242  * is running low on memory.
20243  */
20244 /* ARGSUSED */
20245 void
20246 ip_trash_ire_reclaim(void *args)
20247 {
20248 	netstack_handle_t nh;
20249 	netstack_t *ns;
20250 
20251 	netstack_next_init(&nh);
20252 	while ((ns = netstack_next(&nh)) != NULL) {
20253 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20254 		netstack_rele(ns);
20255 	}
20256 	netstack_next_fini(&nh);
20257 }
20258 
20259 static void
20260 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20261 {
20262 	ire_cache_count_t icc;
20263 	ire_cache_reclaim_t icr;
20264 	ncc_cache_count_t ncc;
20265 	nce_cache_reclaim_t ncr;
20266 	uint_t delete_cnt;
20267 	/*
20268 	 * Memory reclaim call back.
20269 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20270 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20271 	 * entries, determine what fraction to free for
20272 	 * each category of IRE_CACHE entries giving absolute priority
20273 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20274 	 * entry will be freed unless all offlink entries are freed).
20275 	 */
20276 	icc.icc_total = 0;
20277 	icc.icc_unused = 0;
20278 	icc.icc_offlink = 0;
20279 	icc.icc_pmtu = 0;
20280 	icc.icc_onlink = 0;
20281 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20282 
20283 	/*
20284 	 * Free NCEs for IPv6 like the onlink ires.
20285 	 */
20286 	ncc.ncc_total = 0;
20287 	ncc.ncc_host = 0;
20288 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20289 
20290 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20291 	    icc.icc_pmtu + icc.icc_onlink);
20292 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20293 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20294 	if (delete_cnt == 0)
20295 		return;
20296 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20297 	/* Always delete all unused offlink entries */
20298 	icr.icr_ipst = ipst;
20299 	icr.icr_unused = 1;
20300 	if (delete_cnt <= icc.icc_unused) {
20301 		/*
20302 		 * Only need to free unused entries.  In other words,
20303 		 * there are enough unused entries to free to meet our
20304 		 * target number of freed ire cache entries.
20305 		 */
20306 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20307 		ncr.ncr_host = 0;
20308 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20309 		/*
20310 		 * Only need to free unused entries, plus a fraction of offlink
20311 		 * entries.  It follows from the first if statement that
20312 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20313 		 */
20314 		delete_cnt -= icc.icc_unused;
20315 		/* Round up # deleted by truncating fraction */
20316 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20317 		icr.icr_pmtu = icr.icr_onlink = 0;
20318 		ncr.ncr_host = 0;
20319 	} else if (delete_cnt <=
20320 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20321 		/*
20322 		 * Free all unused and offlink entries, plus a fraction of
20323 		 * pmtu entries.  It follows from the previous if statement
20324 		 * that icc_pmtu is non-zero, and that
20325 		 * delete_cnt != icc_unused + icc_offlink.
20326 		 */
20327 		icr.icr_offlink = 1;
20328 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20329 		/* Round up # deleted by truncating fraction */
20330 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20331 		icr.icr_onlink = 0;
20332 		ncr.ncr_host = 0;
20333 	} else {
20334 		/*
20335 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20336 		 * of onlink entries.  If we're here, then we know that
20337 		 * icc_onlink is non-zero, and that
20338 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20339 		 */
20340 		icr.icr_offlink = icr.icr_pmtu = 1;
20341 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20342 		    icc.icc_pmtu;
20343 		/* Round up # deleted by truncating fraction */
20344 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20345 		/* Using the same delete fraction as for onlink IREs */
20346 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20347 	}
20348 #ifdef DEBUG
20349 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20350 	    "fractions %d/%d/%d/%d\n",
20351 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20352 	    icc.icc_unused, icc.icc_offlink,
20353 	    icc.icc_pmtu, icc.icc_onlink,
20354 	    icr.icr_unused, icr.icr_offlink,
20355 	    icr.icr_pmtu, icr.icr_onlink));
20356 #endif
20357 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20358 	if (ncr.ncr_host != 0)
20359 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20360 		    (uchar_t *)&ncr, ipst);
20361 #ifdef DEBUG
20362 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20363 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20364 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20365 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20366 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20367 	    icc.icc_pmtu, icc.icc_onlink));
20368 #endif
20369 }
20370 
20371 /*
20372  * ip_unbind is called when a copy of an unbind request is received from the
20373  * upper level protocol.  We remove this conn from any fanout hash list it is
20374  * on, and zero out the bind information.  No reply is expected up above.
20375  */
20376 mblk_t *
20377 ip_unbind(queue_t *q, mblk_t *mp)
20378 {
20379 	conn_t  *connp = Q_TO_CONN(q);
20380 
20381 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20382 
20383 	if (is_system_labeled() && connp->conn_anon_port) {
20384 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20385 		    connp->conn_mlp_type, connp->conn_ulp,
20386 		    ntohs(connp->conn_lport), B_FALSE);
20387 		connp->conn_anon_port = 0;
20388 	}
20389 	connp->conn_mlp_type = mlptSingle;
20390 
20391 	ipcl_hash_remove(connp);
20392 
20393 	ASSERT(mp->b_cont == NULL);
20394 	/*
20395 	 * Convert mp into a T_OK_ACK
20396 	 */
20397 	mp = mi_tpi_ok_ack_alloc(mp);
20398 
20399 	/*
20400 	 * should not happen in practice... T_OK_ACK is smaller than the
20401 	 * original message.
20402 	 */
20403 	if (mp == NULL)
20404 		return (NULL);
20405 
20406 	return (mp);
20407 }
20408 
20409 /*
20410  * Write side put procedure.  Outbound data, IOCTLs, responses from
20411  * resolvers, etc, come down through here.
20412  *
20413  * arg2 is always a queue_t *.
20414  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20415  * the zoneid.
20416  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20417  */
20418 void
20419 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20420 {
20421 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20422 }
20423 
20424 void
20425 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20426     ip_opt_info_t *infop)
20427 {
20428 	conn_t		*connp = NULL;
20429 	queue_t		*q = (queue_t *)arg2;
20430 	ipha_t		*ipha;
20431 #define	rptr	((uchar_t *)ipha)
20432 	ire_t		*ire = NULL;
20433 	ire_t		*sctp_ire = NULL;
20434 	uint32_t	v_hlen_tos_len;
20435 	ipaddr_t	dst;
20436 	mblk_t		*first_mp = NULL;
20437 	boolean_t	mctl_present;
20438 	ipsec_out_t	*io;
20439 	int		match_flags;
20440 	ill_t		*attach_ill = NULL;
20441 					/* Bind to IPIF_NOFAILOVER ill etc. */
20442 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20443 	ipif_t		*dst_ipif;
20444 	boolean_t	multirt_need_resolve = B_FALSE;
20445 	mblk_t		*copy_mp = NULL;
20446 	int		err;
20447 	zoneid_t	zoneid;
20448 	boolean_t	need_decref = B_FALSE;
20449 	boolean_t	ignore_dontroute = B_FALSE;
20450 	boolean_t	ignore_nexthop = B_FALSE;
20451 	boolean_t	ip_nexthop = B_FALSE;
20452 	ipaddr_t	nexthop_addr;
20453 	ip_stack_t	*ipst;
20454 
20455 #ifdef	_BIG_ENDIAN
20456 #define	V_HLEN	(v_hlen_tos_len >> 24)
20457 #else
20458 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20459 #endif
20460 
20461 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20462 	    "ip_wput_start: q %p", q);
20463 
20464 	/*
20465 	 * ip_wput fast path
20466 	 */
20467 
20468 	/* is packet from ARP ? */
20469 	if (q->q_next != NULL) {
20470 		zoneid = (zoneid_t)(uintptr_t)arg;
20471 		goto qnext;
20472 	}
20473 
20474 	connp = (conn_t *)arg;
20475 	ASSERT(connp != NULL);
20476 	zoneid = connp->conn_zoneid;
20477 	ipst = connp->conn_netstack->netstack_ip;
20478 
20479 	/* is queue flow controlled? */
20480 	if ((q->q_first != NULL || connp->conn_draining) &&
20481 	    (caller == IP_WPUT)) {
20482 		ASSERT(!need_decref);
20483 		(void) putq(q, mp);
20484 		return;
20485 	}
20486 
20487 	/* Multidata transmit? */
20488 	if (DB_TYPE(mp) == M_MULTIDATA) {
20489 		/*
20490 		 * We should never get here, since all Multidata messages
20491 		 * originating from tcp should have been directed over to
20492 		 * tcp_multisend() in the first place.
20493 		 */
20494 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20495 		freemsg(mp);
20496 		return;
20497 	} else if (DB_TYPE(mp) != M_DATA)
20498 		goto notdata;
20499 
20500 	if (mp->b_flag & MSGHASREF) {
20501 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20502 		mp->b_flag &= ~MSGHASREF;
20503 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20504 		need_decref = B_TRUE;
20505 	}
20506 	ipha = (ipha_t *)mp->b_rptr;
20507 
20508 	/* is IP header non-aligned or mblk smaller than basic IP header */
20509 #ifndef SAFETY_BEFORE_SPEED
20510 	if (!OK_32PTR(rptr) ||
20511 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20512 		goto hdrtoosmall;
20513 #endif
20514 
20515 	ASSERT(OK_32PTR(ipha));
20516 
20517 	/*
20518 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20519 	 * wrong version, we'll catch it again in ip_output_v6.
20520 	 *
20521 	 * Note that this is *only* locally-generated output here, and never
20522 	 * forwarded data, and that we need to deal only with transports that
20523 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20524 	 * label.)
20525 	 */
20526 	if (is_system_labeled() &&
20527 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20528 	    !connp->conn_ulp_labeled) {
20529 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20530 		    connp->conn_mac_exempt, ipst);
20531 		ipha = (ipha_t *)mp->b_rptr;
20532 		if (err != 0) {
20533 			first_mp = mp;
20534 			if (err == EINVAL)
20535 				goto icmp_parameter_problem;
20536 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20537 			goto discard_pkt;
20538 		}
20539 	}
20540 
20541 	ASSERT(infop != NULL);
20542 
20543 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20544 		/*
20545 		 * IP_PKTINFO ancillary option is present.
20546 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20547 		 * allows using address of any zone as the source address.
20548 		 */
20549 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20550 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20551 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20552 		if (ire == NULL)
20553 			goto drop_pkt;
20554 		ire_refrele(ire);
20555 		ire = NULL;
20556 	}
20557 
20558 	/*
20559 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20560 	 * passed in IP_PKTINFO.
20561 	 */
20562 	if (infop->ip_opt_ill_index != 0 &&
20563 	    connp->conn_outgoing_ill == NULL &&
20564 	    connp->conn_nofailover_ill == NULL) {
20565 
20566 		xmit_ill = ill_lookup_on_ifindex(
20567 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20568 		    ipst);
20569 
20570 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20571 			goto drop_pkt;
20572 		/*
20573 		 * check that there is an ipif belonging
20574 		 * to our zone. IPCL_ZONEID is not used because
20575 		 * IP_ALLZONES option is valid only when the ill is
20576 		 * accessible from all zones i.e has a valid ipif in
20577 		 * all zones.
20578 		 */
20579 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20580 			goto drop_pkt;
20581 		}
20582 	}
20583 
20584 	/*
20585 	 * If there is a policy, try to attach an ipsec_out in
20586 	 * the front. At the end, first_mp either points to a
20587 	 * M_DATA message or IPSEC_OUT message linked to a
20588 	 * M_DATA message. We have to do it now as we might
20589 	 * lose the "conn" if we go through ip_newroute.
20590 	 */
20591 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20592 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20593 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20594 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20595 			if (need_decref)
20596 				CONN_DEC_REF(connp);
20597 			return;
20598 		} else {
20599 			ASSERT(mp->b_datap->db_type == M_CTL);
20600 			first_mp = mp;
20601 			mp = mp->b_cont;
20602 			mctl_present = B_TRUE;
20603 		}
20604 	} else {
20605 		first_mp = mp;
20606 		mctl_present = B_FALSE;
20607 	}
20608 
20609 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20610 
20611 	/* is wrong version or IP options present */
20612 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20613 		goto version_hdrlen_check;
20614 	dst = ipha->ipha_dst;
20615 
20616 	if (connp->conn_nofailover_ill != NULL) {
20617 		attach_ill = conn_get_held_ill(connp,
20618 		    &connp->conn_nofailover_ill, &err);
20619 		if (err == ILL_LOOKUP_FAILED) {
20620 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20621 			if (need_decref)
20622 				CONN_DEC_REF(connp);
20623 			freemsg(first_mp);
20624 			return;
20625 		}
20626 	}
20627 
20628 	/* If IP_BOUND_IF has been set, use that ill. */
20629 	if (connp->conn_outgoing_ill != NULL) {
20630 		xmit_ill = conn_get_held_ill(connp,
20631 		    &connp->conn_outgoing_ill, &err);
20632 		if (err == ILL_LOOKUP_FAILED)
20633 			goto drop_pkt;
20634 
20635 		goto send_from_ill;
20636 	}
20637 
20638 	/* is packet multicast? */
20639 	if (CLASSD(dst))
20640 		goto multicast;
20641 
20642 	/*
20643 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20644 	 * takes precedence over conn_dontroute and conn_nexthop_set
20645 	 */
20646 	if (xmit_ill != NULL)
20647 		goto send_from_ill;
20648 
20649 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20650 		/*
20651 		 * If the destination is a broadcast, local, or loopback
20652 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20653 		 * standard path.
20654 		 */
20655 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20656 		if ((ire == NULL) || (ire->ire_type &
20657 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20658 			if (ire != NULL) {
20659 				ire_refrele(ire);
20660 				/* No more access to ire */
20661 				ire = NULL;
20662 			}
20663 			/*
20664 			 * bypass routing checks and go directly to interface.
20665 			 */
20666 			if (connp->conn_dontroute)
20667 				goto dontroute;
20668 
20669 			ASSERT(connp->conn_nexthop_set);
20670 			ip_nexthop = B_TRUE;
20671 			nexthop_addr = connp->conn_nexthop_v4;
20672 			goto send_from_ill;
20673 		}
20674 
20675 		/* Must be a broadcast, a loopback or a local ire */
20676 		ire_refrele(ire);
20677 		/* No more access to ire */
20678 		ire = NULL;
20679 	}
20680 
20681 	if (attach_ill != NULL)
20682 		goto send_from_ill;
20683 
20684 	/*
20685 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20686 	 * this for the tcp global queue and listen end point
20687 	 * as it does not really have a real destination to
20688 	 * talk to.  This is also true for SCTP.
20689 	 */
20690 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20691 	    !connp->conn_fully_bound) {
20692 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20693 		if (ire == NULL)
20694 			goto noirefound;
20695 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20696 		    "ip_wput_end: q %p (%S)", q, "end");
20697 
20698 		/*
20699 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20700 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20701 		 */
20702 		if (ire->ire_flags & RTF_MULTIRT) {
20703 
20704 			/*
20705 			 * Force the TTL of multirouted packets if required.
20706 			 * The TTL of such packets is bounded by the
20707 			 * ip_multirt_ttl ndd variable.
20708 			 */
20709 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20710 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20711 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20712 				    "(was %d), dst 0x%08x\n",
20713 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20714 				    ntohl(ire->ire_addr)));
20715 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20716 			}
20717 			/*
20718 			 * We look at this point if there are pending
20719 			 * unresolved routes. ire_multirt_resolvable()
20720 			 * checks in O(n) that all IRE_OFFSUBNET ire
20721 			 * entries for the packet's destination and
20722 			 * flagged RTF_MULTIRT are currently resolved.
20723 			 * If some remain unresolved, we make a copy
20724 			 * of the current message. It will be used
20725 			 * to initiate additional route resolutions.
20726 			 */
20727 			multirt_need_resolve =
20728 			    ire_multirt_need_resolve(ire->ire_addr,
20729 			    MBLK_GETLABEL(first_mp), ipst);
20730 			ip2dbg(("ip_wput[TCP]: ire %p, "
20731 			    "multirt_need_resolve %d, first_mp %p\n",
20732 			    (void *)ire, multirt_need_resolve,
20733 			    (void *)first_mp));
20734 			if (multirt_need_resolve) {
20735 				copy_mp = copymsg(first_mp);
20736 				if (copy_mp != NULL) {
20737 					MULTIRT_DEBUG_TAG(copy_mp);
20738 				}
20739 			}
20740 		}
20741 
20742 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20743 
20744 		/*
20745 		 * Try to resolve another multiroute if
20746 		 * ire_multirt_need_resolve() deemed it necessary.
20747 		 */
20748 		if (copy_mp != NULL)
20749 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20750 		if (need_decref)
20751 			CONN_DEC_REF(connp);
20752 		return;
20753 	}
20754 
20755 	/*
20756 	 * Access to conn_ire_cache. (protected by conn_lock)
20757 	 *
20758 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20759 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20760 	 * send a packet or two with the IRE_CACHE that is going away.
20761 	 * Access to the ire requires an ire refhold on the ire prior to
20762 	 * its use since an interface unplumb thread may delete the cached
20763 	 * ire and release the refhold at any time.
20764 	 *
20765 	 * Caching an ire in the conn_ire_cache
20766 	 *
20767 	 * o Caching an ire pointer in the conn requires a strict check for
20768 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20769 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20770 	 * in the conn is done after making sure under the bucket lock that the
20771 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20772 	 * caching an ire after the unplumb thread has cleaned up the conn.
20773 	 * If the conn does not send a packet subsequently the unplumb thread
20774 	 * will be hanging waiting for the ire count to drop to zero.
20775 	 *
20776 	 * o We also need to atomically test for a null conn_ire_cache and
20777 	 * set the conn_ire_cache under the the protection of the conn_lock
20778 	 * to avoid races among concurrent threads trying to simultaneously
20779 	 * cache an ire in the conn_ire_cache.
20780 	 */
20781 	mutex_enter(&connp->conn_lock);
20782 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20783 
20784 	if (ire != NULL && ire->ire_addr == dst &&
20785 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20786 
20787 		IRE_REFHOLD(ire);
20788 		mutex_exit(&connp->conn_lock);
20789 
20790 	} else {
20791 		boolean_t cached = B_FALSE;
20792 		connp->conn_ire_cache = NULL;
20793 		mutex_exit(&connp->conn_lock);
20794 		/* Release the old ire */
20795 		if (ire != NULL && sctp_ire == NULL)
20796 			IRE_REFRELE_NOTR(ire);
20797 
20798 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20799 		if (ire == NULL)
20800 			goto noirefound;
20801 		IRE_REFHOLD_NOTR(ire);
20802 
20803 		mutex_enter(&connp->conn_lock);
20804 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20805 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20806 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20807 				if (connp->conn_ulp == IPPROTO_TCP)
20808 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20809 				connp->conn_ire_cache = ire;
20810 				cached = B_TRUE;
20811 			}
20812 			rw_exit(&ire->ire_bucket->irb_lock);
20813 		}
20814 		mutex_exit(&connp->conn_lock);
20815 
20816 		/*
20817 		 * We can continue to use the ire but since it was
20818 		 * not cached, we should drop the extra reference.
20819 		 */
20820 		if (!cached)
20821 			IRE_REFRELE_NOTR(ire);
20822 	}
20823 
20824 
20825 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20826 	    "ip_wput_end: q %p (%S)", q, "end");
20827 
20828 	/*
20829 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20830 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20831 	 */
20832 	if (ire->ire_flags & RTF_MULTIRT) {
20833 
20834 		/*
20835 		 * Force the TTL of multirouted packets if required.
20836 		 * The TTL of such packets is bounded by the
20837 		 * ip_multirt_ttl ndd variable.
20838 		 */
20839 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20840 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20841 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20842 			    "(was %d), dst 0x%08x\n",
20843 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20844 			    ntohl(ire->ire_addr)));
20845 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20846 		}
20847 
20848 		/*
20849 		 * At this point, we check to see if there are any pending
20850 		 * unresolved routes. ire_multirt_resolvable()
20851 		 * checks in O(n) that all IRE_OFFSUBNET ire
20852 		 * entries for the packet's destination and
20853 		 * flagged RTF_MULTIRT are currently resolved.
20854 		 * If some remain unresolved, we make a copy
20855 		 * of the current message. It will be used
20856 		 * to initiate additional route resolutions.
20857 		 */
20858 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20859 		    MBLK_GETLABEL(first_mp), ipst);
20860 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20861 		    "multirt_need_resolve %d, first_mp %p\n",
20862 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20863 		if (multirt_need_resolve) {
20864 			copy_mp = copymsg(first_mp);
20865 			if (copy_mp != NULL) {
20866 				MULTIRT_DEBUG_TAG(copy_mp);
20867 			}
20868 		}
20869 	}
20870 
20871 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20872 
20873 	/*
20874 	 * Try to resolve another multiroute if
20875 	 * ire_multirt_resolvable() deemed it necessary
20876 	 */
20877 	if (copy_mp != NULL)
20878 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20879 	if (need_decref)
20880 		CONN_DEC_REF(connp);
20881 	return;
20882 
20883 qnext:
20884 	/*
20885 	 * Upper Level Protocols pass down complete IP datagrams
20886 	 * as M_DATA messages.	Everything else is a sideshow.
20887 	 *
20888 	 * 1) We could be re-entering ip_wput because of ip_neworute
20889 	 *    in which case we could have a IPSEC_OUT message. We
20890 	 *    need to pass through ip_wput like other datagrams and
20891 	 *    hence cannot branch to ip_wput_nondata.
20892 	 *
20893 	 * 2) ARP, AH, ESP, and other clients who are on the module
20894 	 *    instance of IP stream, give us something to deal with.
20895 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20896 	 *
20897 	 * 3) ICMP replies also could come here.
20898 	 */
20899 	ipst = ILLQ_TO_IPST(q);
20900 
20901 	if (DB_TYPE(mp) != M_DATA) {
20902 notdata:
20903 		if (DB_TYPE(mp) == M_CTL) {
20904 			/*
20905 			 * M_CTL messages are used by ARP, AH and ESP to
20906 			 * communicate with IP. We deal with IPSEC_IN and
20907 			 * IPSEC_OUT here. ip_wput_nondata handles other
20908 			 * cases.
20909 			 */
20910 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20911 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20912 				first_mp = mp->b_cont;
20913 				first_mp->b_flag &= ~MSGHASREF;
20914 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20915 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20916 				CONN_DEC_REF(connp);
20917 				connp = NULL;
20918 			}
20919 			if (ii->ipsec_info_type == IPSEC_IN) {
20920 				/*
20921 				 * Either this message goes back to
20922 				 * IPsec for further processing or to
20923 				 * ULP after policy checks.
20924 				 */
20925 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20926 				return;
20927 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20928 				io = (ipsec_out_t *)ii;
20929 				if (io->ipsec_out_proc_begin) {
20930 					/*
20931 					 * IPsec processing has already started.
20932 					 * Complete it.
20933 					 * IPQoS notes: We don't care what is
20934 					 * in ipsec_out_ill_index since this
20935 					 * won't be processed for IPQoS policies
20936 					 * in ipsec_out_process.
20937 					 */
20938 					ipsec_out_process(q, mp, NULL,
20939 					    io->ipsec_out_ill_index);
20940 					return;
20941 				} else {
20942 					connp = (q->q_next != NULL) ?
20943 					    NULL : Q_TO_CONN(q);
20944 					first_mp = mp;
20945 					mp = mp->b_cont;
20946 					mctl_present = B_TRUE;
20947 				}
20948 				zoneid = io->ipsec_out_zoneid;
20949 				ASSERT(zoneid != ALL_ZONES);
20950 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20951 				/*
20952 				 * It's an IPsec control message requesting
20953 				 * an SADB update to be sent to the IPsec
20954 				 * hardware acceleration capable ills.
20955 				 */
20956 				ipsec_ctl_t *ipsec_ctl =
20957 				    (ipsec_ctl_t *)mp->b_rptr;
20958 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20959 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20960 				mblk_t *cmp = mp->b_cont;
20961 
20962 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20963 				ASSERT(cmp != NULL);
20964 
20965 				freeb(mp);
20966 				ill_ipsec_capab_send_all(satype, cmp, sa,
20967 				    ipst->ips_netstack);
20968 				return;
20969 			} else {
20970 				/*
20971 				 * This must be ARP or special TSOL signaling.
20972 				 */
20973 				ip_wput_nondata(NULL, q, mp, NULL);
20974 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20975 				    "ip_wput_end: q %p (%S)", q, "nondata");
20976 				return;
20977 			}
20978 		} else {
20979 			/*
20980 			 * This must be non-(ARP/AH/ESP) messages.
20981 			 */
20982 			ASSERT(!need_decref);
20983 			ip_wput_nondata(NULL, q, mp, NULL);
20984 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20985 			    "ip_wput_end: q %p (%S)", q, "nondata");
20986 			return;
20987 		}
20988 	} else {
20989 		first_mp = mp;
20990 		mctl_present = B_FALSE;
20991 	}
20992 
20993 	ASSERT(first_mp != NULL);
20994 	/*
20995 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20996 	 * to make sure that this packet goes out on the same interface it
20997 	 * came in. We handle that here.
20998 	 */
20999 	if (mctl_present) {
21000 		uint_t ifindex;
21001 
21002 		io = (ipsec_out_t *)first_mp->b_rptr;
21003 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
21004 			/*
21005 			 * We may have lost the conn context if we are
21006 			 * coming here from ip_newroute(). Copy the
21007 			 * nexthop information.
21008 			 */
21009 			if (io->ipsec_out_ip_nexthop) {
21010 				ip_nexthop = B_TRUE;
21011 				nexthop_addr = io->ipsec_out_nexthop_addr;
21012 
21013 				ipha = (ipha_t *)mp->b_rptr;
21014 				dst = ipha->ipha_dst;
21015 				goto send_from_ill;
21016 			} else {
21017 				ASSERT(io->ipsec_out_ill_index != 0);
21018 				ifindex = io->ipsec_out_ill_index;
21019 				attach_ill = ill_lookup_on_ifindex(ifindex,
21020 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
21021 				if (attach_ill == NULL) {
21022 					ASSERT(xmit_ill == NULL);
21023 					ip1dbg(("ip_output: bad ifindex for "
21024 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
21025 					    ifindex));
21026 					freemsg(first_mp);
21027 					BUMP_MIB(&ipst->ips_ip_mib,
21028 					    ipIfStatsOutDiscards);
21029 					ASSERT(!need_decref);
21030 					return;
21031 				}
21032 			}
21033 		}
21034 	}
21035 
21036 	ASSERT(xmit_ill == NULL);
21037 
21038 	/* We have a complete IP datagram heading outbound. */
21039 	ipha = (ipha_t *)mp->b_rptr;
21040 
21041 #ifndef SPEED_BEFORE_SAFETY
21042 	/*
21043 	 * Make sure we have a full-word aligned message and that at least
21044 	 * a simple IP header is accessible in the first message.  If not,
21045 	 * try a pullup.  For labeled systems we need to always take this
21046 	 * path as M_CTLs are "notdata" but have trailing data to process.
21047 	 */
21048 	if (!OK_32PTR(rptr) ||
21049 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
21050 hdrtoosmall:
21051 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
21052 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21053 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
21054 			if (first_mp == NULL)
21055 				first_mp = mp;
21056 			goto discard_pkt;
21057 		}
21058 
21059 		/* This function assumes that mp points to an IPv4 packet. */
21060 		if (is_system_labeled() && q->q_next == NULL &&
21061 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
21062 		    !connp->conn_ulp_labeled) {
21063 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
21064 			    connp->conn_mac_exempt, ipst);
21065 			ipha = (ipha_t *)mp->b_rptr;
21066 			if (first_mp != NULL)
21067 				first_mp->b_cont = mp;
21068 			if (err != 0) {
21069 				if (first_mp == NULL)
21070 					first_mp = mp;
21071 				if (err == EINVAL)
21072 					goto icmp_parameter_problem;
21073 				ip2dbg(("ip_wput: label check failed (%d)\n",
21074 				    err));
21075 				goto discard_pkt;
21076 			}
21077 		}
21078 
21079 		ipha = (ipha_t *)mp->b_rptr;
21080 		if (first_mp == NULL) {
21081 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
21082 			/*
21083 			 * If we got here because of "goto hdrtoosmall"
21084 			 * We need to attach a IPSEC_OUT.
21085 			 */
21086 			if (connp->conn_out_enforce_policy) {
21087 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
21088 				    NULL, ipha->ipha_protocol,
21089 				    ipst->ips_netstack)) == NULL)) {
21090 					BUMP_MIB(&ipst->ips_ip_mib,
21091 					    ipIfStatsOutDiscards);
21092 					if (need_decref)
21093 						CONN_DEC_REF(connp);
21094 					return;
21095 				} else {
21096 					ASSERT(mp->b_datap->db_type == M_CTL);
21097 					first_mp = mp;
21098 					mp = mp->b_cont;
21099 					mctl_present = B_TRUE;
21100 				}
21101 			} else {
21102 				first_mp = mp;
21103 				mctl_present = B_FALSE;
21104 			}
21105 		}
21106 	}
21107 #endif
21108 
21109 	/* Most of the code below is written for speed, not readability */
21110 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21111 
21112 	/*
21113 	 * If ip_newroute() fails, we're going to need a full
21114 	 * header for the icmp wraparound.
21115 	 */
21116 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21117 		uint_t	v_hlen;
21118 version_hdrlen_check:
21119 		ASSERT(first_mp != NULL);
21120 		v_hlen = V_HLEN;
21121 		/*
21122 		 * siphon off IPv6 packets coming down from transport
21123 		 * layer modules here.
21124 		 * Note: high-order bit carries NUD reachability confirmation
21125 		 */
21126 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21127 			/*
21128 			 * FIXME: assume that callers of ip_output* call
21129 			 * the right version?
21130 			 */
21131 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21132 			ASSERT(xmit_ill == NULL);
21133 			if (attach_ill != NULL)
21134 				ill_refrele(attach_ill);
21135 			if (need_decref)
21136 				mp->b_flag |= MSGHASREF;
21137 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21138 			return;
21139 		}
21140 
21141 		if ((v_hlen >> 4) != IP_VERSION) {
21142 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21143 			    "ip_wput_end: q %p (%S)", q, "badvers");
21144 			goto discard_pkt;
21145 		}
21146 		/*
21147 		 * Is the header length at least 20 bytes?
21148 		 *
21149 		 * Are there enough bytes accessible in the header?  If
21150 		 * not, try a pullup.
21151 		 */
21152 		v_hlen &= 0xF;
21153 		v_hlen <<= 2;
21154 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21155 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21156 			    "ip_wput_end: q %p (%S)", q, "badlen");
21157 			goto discard_pkt;
21158 		}
21159 		if (v_hlen > (mp->b_wptr - rptr)) {
21160 			if (!pullupmsg(mp, v_hlen)) {
21161 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21162 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21163 				goto discard_pkt;
21164 			}
21165 			ipha = (ipha_t *)mp->b_rptr;
21166 		}
21167 		/*
21168 		 * Move first entry from any source route into ipha_dst and
21169 		 * verify the options
21170 		 */
21171 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21172 		    zoneid, ipst)) {
21173 			ASSERT(xmit_ill == NULL);
21174 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21175 			if (attach_ill != NULL)
21176 				ill_refrele(attach_ill);
21177 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21178 			    "ip_wput_end: q %p (%S)", q, "badopts");
21179 			if (need_decref)
21180 				CONN_DEC_REF(connp);
21181 			return;
21182 		}
21183 	}
21184 	dst = ipha->ipha_dst;
21185 
21186 	/*
21187 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21188 	 * we have to run the packet through ip_newroute which will take
21189 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21190 	 * a resolver, or assigning a default gateway, etc.
21191 	 */
21192 	if (CLASSD(dst)) {
21193 		ipif_t	*ipif;
21194 		uint32_t setsrc = 0;
21195 
21196 multicast:
21197 		ASSERT(first_mp != NULL);
21198 		ip2dbg(("ip_wput: CLASSD\n"));
21199 		if (connp == NULL) {
21200 			/*
21201 			 * Use the first good ipif on the ill.
21202 			 * XXX Should this ever happen? (Appears
21203 			 * to show up with just ppp and no ethernet due
21204 			 * to in.rdisc.)
21205 			 * However, ire_send should be able to
21206 			 * call ip_wput_ire directly.
21207 			 *
21208 			 * XXX Also, this can happen for ICMP and other packets
21209 			 * with multicast source addresses.  Perhaps we should
21210 			 * fix things so that we drop the packet in question,
21211 			 * but for now, just run with it.
21212 			 */
21213 			ill_t *ill = (ill_t *)q->q_ptr;
21214 
21215 			/*
21216 			 * Don't honor attach_if for this case. If ill
21217 			 * is part of the group, ipif could belong to
21218 			 * any ill and we cannot maintain attach_ill
21219 			 * and ipif_ill same anymore and the assert
21220 			 * below would fail.
21221 			 */
21222 			if (mctl_present && io->ipsec_out_attach_if) {
21223 				io->ipsec_out_ill_index = 0;
21224 				io->ipsec_out_attach_if = B_FALSE;
21225 				ASSERT(attach_ill != NULL);
21226 				ill_refrele(attach_ill);
21227 				attach_ill = NULL;
21228 			}
21229 
21230 			ASSERT(attach_ill == NULL);
21231 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21232 			if (ipif == NULL) {
21233 				if (need_decref)
21234 					CONN_DEC_REF(connp);
21235 				freemsg(first_mp);
21236 				return;
21237 			}
21238 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21239 			    ntohl(dst), ill->ill_name));
21240 		} else {
21241 			/*
21242 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21243 			 * and IP_MULTICAST_IF.  The block comment above this
21244 			 * function explains the locking mechanism used here.
21245 			 */
21246 			if (xmit_ill == NULL) {
21247 				xmit_ill = conn_get_held_ill(connp,
21248 				    &connp->conn_outgoing_ill, &err);
21249 				if (err == ILL_LOOKUP_FAILED) {
21250 					ip1dbg(("ip_wput: No ill for "
21251 					    "IP_BOUND_IF\n"));
21252 					BUMP_MIB(&ipst->ips_ip_mib,
21253 					    ipIfStatsOutNoRoutes);
21254 					goto drop_pkt;
21255 				}
21256 			}
21257 
21258 			if (xmit_ill == NULL) {
21259 				ipif = conn_get_held_ipif(connp,
21260 				    &connp->conn_multicast_ipif, &err);
21261 				if (err == IPIF_LOOKUP_FAILED) {
21262 					ip1dbg(("ip_wput: No ipif for "
21263 					    "multicast\n"));
21264 					BUMP_MIB(&ipst->ips_ip_mib,
21265 					    ipIfStatsOutNoRoutes);
21266 					goto drop_pkt;
21267 				}
21268 			}
21269 			if (xmit_ill != NULL) {
21270 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21271 				if (ipif == NULL) {
21272 					ip1dbg(("ip_wput: No ipif for "
21273 					    "xmit_ill\n"));
21274 					BUMP_MIB(&ipst->ips_ip_mib,
21275 					    ipIfStatsOutNoRoutes);
21276 					goto drop_pkt;
21277 				}
21278 			} else if (ipif == NULL || ipif->ipif_isv6) {
21279 				/*
21280 				 * We must do this ipif determination here
21281 				 * else we could pass through ip_newroute
21282 				 * and come back here without the conn context.
21283 				 *
21284 				 * Note: we do late binding i.e. we bind to
21285 				 * the interface when the first packet is sent.
21286 				 * For performance reasons we do not rebind on
21287 				 * each packet but keep the binding until the
21288 				 * next IP_MULTICAST_IF option.
21289 				 *
21290 				 * conn_multicast_{ipif,ill} are shared between
21291 				 * IPv4 and IPv6 and AF_INET6 sockets can
21292 				 * send both IPv4 and IPv6 packets. Hence
21293 				 * we have to check that "isv6" matches above.
21294 				 */
21295 				if (ipif != NULL)
21296 					ipif_refrele(ipif);
21297 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21298 				if (ipif == NULL) {
21299 					ip1dbg(("ip_wput: No ipif for "
21300 					    "multicast\n"));
21301 					BUMP_MIB(&ipst->ips_ip_mib,
21302 					    ipIfStatsOutNoRoutes);
21303 					goto drop_pkt;
21304 				}
21305 				err = conn_set_held_ipif(connp,
21306 				    &connp->conn_multicast_ipif, ipif);
21307 				if (err == IPIF_LOOKUP_FAILED) {
21308 					ipif_refrele(ipif);
21309 					ip1dbg(("ip_wput: No ipif for "
21310 					    "multicast\n"));
21311 					BUMP_MIB(&ipst->ips_ip_mib,
21312 					    ipIfStatsOutNoRoutes);
21313 					goto drop_pkt;
21314 				}
21315 			}
21316 		}
21317 		ASSERT(!ipif->ipif_isv6);
21318 		/*
21319 		 * As we may lose the conn by the time we reach ip_wput_ire,
21320 		 * we copy conn_multicast_loop and conn_dontroute on to an
21321 		 * ipsec_out. In case if this datagram goes out secure,
21322 		 * we need the ill_index also. Copy that also into the
21323 		 * ipsec_out.
21324 		 */
21325 		if (mctl_present) {
21326 			io = (ipsec_out_t *)first_mp->b_rptr;
21327 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21328 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21329 		} else {
21330 			ASSERT(mp == first_mp);
21331 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21332 			    BPRI_HI)) == NULL) {
21333 				ipif_refrele(ipif);
21334 				first_mp = mp;
21335 				goto discard_pkt;
21336 			}
21337 			first_mp->b_datap->db_type = M_CTL;
21338 			first_mp->b_wptr += sizeof (ipsec_info_t);
21339 			/* ipsec_out_secure is B_FALSE now */
21340 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21341 			io = (ipsec_out_t *)first_mp->b_rptr;
21342 			io->ipsec_out_type = IPSEC_OUT;
21343 			io->ipsec_out_len = sizeof (ipsec_out_t);
21344 			io->ipsec_out_use_global_policy = B_TRUE;
21345 			io->ipsec_out_ns = ipst->ips_netstack;
21346 			first_mp->b_cont = mp;
21347 			mctl_present = B_TRUE;
21348 		}
21349 		if (attach_ill != NULL) {
21350 			ASSERT(attach_ill == ipif->ipif_ill);
21351 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21352 
21353 			/*
21354 			 * Check if we need an ire that will not be
21355 			 * looked up by anybody else i.e. HIDDEN.
21356 			 */
21357 			if (ill_is_probeonly(attach_ill)) {
21358 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21359 			}
21360 			io->ipsec_out_ill_index =
21361 			    attach_ill->ill_phyint->phyint_ifindex;
21362 			io->ipsec_out_attach_if = B_TRUE;
21363 		} else {
21364 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21365 			io->ipsec_out_ill_index =
21366 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21367 		}
21368 		if (connp != NULL) {
21369 			io->ipsec_out_multicast_loop =
21370 			    connp->conn_multicast_loop;
21371 			io->ipsec_out_dontroute = connp->conn_dontroute;
21372 			io->ipsec_out_zoneid = connp->conn_zoneid;
21373 		}
21374 		/*
21375 		 * If the application uses IP_MULTICAST_IF with
21376 		 * different logical addresses of the same ILL, we
21377 		 * need to make sure that the soruce address of
21378 		 * the packet matches the logical IP address used
21379 		 * in the option. We do it by initializing ipha_src
21380 		 * here. This should keep IPsec also happy as
21381 		 * when we return from IPsec processing, we don't
21382 		 * have to worry about getting the right address on
21383 		 * the packet. Thus it is sufficient to look for
21384 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21385 		 * MATCH_IRE_IPIF.
21386 		 *
21387 		 * NOTE : We need to do it for non-secure case also as
21388 		 * this might go out secure if there is a global policy
21389 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21390 		 * address, the source should be initialized already and
21391 		 * hence we won't be initializing here.
21392 		 *
21393 		 * As we do not have the ire yet, it is possible that
21394 		 * we set the source address here and then later discover
21395 		 * that the ire implies the source address to be assigned
21396 		 * through the RTF_SETSRC flag.
21397 		 * In that case, the setsrc variable will remind us
21398 		 * that overwritting the source address by the one
21399 		 * of the RTF_SETSRC-flagged ire is allowed.
21400 		 */
21401 		if (ipha->ipha_src == INADDR_ANY &&
21402 		    (connp == NULL || !connp->conn_unspec_src)) {
21403 			ipha->ipha_src = ipif->ipif_src_addr;
21404 			setsrc = RTF_SETSRC;
21405 		}
21406 		/*
21407 		 * Find an IRE which matches the destination and the outgoing
21408 		 * queue (i.e. the outgoing interface.)
21409 		 * For loopback use a unicast IP address for
21410 		 * the ire lookup.
21411 		 */
21412 		if (IS_LOOPBACK(ipif->ipif_ill))
21413 			dst = ipif->ipif_lcl_addr;
21414 
21415 		/*
21416 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21417 		 * We don't need to lookup ire in ctable as the packet
21418 		 * needs to be sent to the destination through the specified
21419 		 * ill irrespective of ires in the cache table.
21420 		 */
21421 		ire = NULL;
21422 		if (xmit_ill == NULL) {
21423 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21424 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21425 		}
21426 
21427 		/*
21428 		 * refrele attach_ill as its not needed anymore.
21429 		 */
21430 		if (attach_ill != NULL) {
21431 			ill_refrele(attach_ill);
21432 			attach_ill = NULL;
21433 		}
21434 
21435 		if (ire == NULL) {
21436 			/*
21437 			 * Multicast loopback and multicast forwarding is
21438 			 * done in ip_wput_ire.
21439 			 *
21440 			 * Mark this packet to make it be delivered to
21441 			 * ip_wput_ire after the new ire has been
21442 			 * created.
21443 			 *
21444 			 * The call to ip_newroute_ipif takes into account
21445 			 * the setsrc reminder. In any case, we take care
21446 			 * of the RTF_MULTIRT flag.
21447 			 */
21448 			mp->b_prev = mp->b_next = NULL;
21449 			if (xmit_ill == NULL ||
21450 			    xmit_ill->ill_ipif_up_count > 0) {
21451 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21452 				    setsrc | RTF_MULTIRT, zoneid, infop);
21453 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21454 				    "ip_wput_end: q %p (%S)", q, "noire");
21455 			} else {
21456 				freemsg(first_mp);
21457 			}
21458 			ipif_refrele(ipif);
21459 			if (xmit_ill != NULL)
21460 				ill_refrele(xmit_ill);
21461 			if (need_decref)
21462 				CONN_DEC_REF(connp);
21463 			return;
21464 		}
21465 
21466 		ipif_refrele(ipif);
21467 		ipif = NULL;
21468 		ASSERT(xmit_ill == NULL);
21469 
21470 		/*
21471 		 * Honor the RTF_SETSRC flag for multicast packets,
21472 		 * if allowed by the setsrc reminder.
21473 		 */
21474 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21475 			ipha->ipha_src = ire->ire_src_addr;
21476 		}
21477 
21478 		/*
21479 		 * Unconditionally force the TTL to 1 for
21480 		 * multirouted multicast packets:
21481 		 * multirouted multicast should not cross
21482 		 * multicast routers.
21483 		 */
21484 		if (ire->ire_flags & RTF_MULTIRT) {
21485 			if (ipha->ipha_ttl > 1) {
21486 				ip2dbg(("ip_wput: forcing multicast "
21487 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21488 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21489 				ipha->ipha_ttl = 1;
21490 			}
21491 		}
21492 	} else {
21493 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21494 		if ((ire != NULL) && (ire->ire_type &
21495 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21496 			ignore_dontroute = B_TRUE;
21497 			ignore_nexthop = B_TRUE;
21498 		}
21499 		if (ire != NULL) {
21500 			ire_refrele(ire);
21501 			ire = NULL;
21502 		}
21503 		/*
21504 		 * Guard against coming in from arp in which case conn is NULL.
21505 		 * Also guard against non M_DATA with dontroute set but
21506 		 * destined to local, loopback or broadcast addresses.
21507 		 */
21508 		if (connp != NULL && connp->conn_dontroute &&
21509 		    !ignore_dontroute) {
21510 dontroute:
21511 			/*
21512 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21513 			 * routing protocols from seeing false direct
21514 			 * connectivity.
21515 			 */
21516 			ipha->ipha_ttl = 1;
21517 
21518 			/* If suitable ipif not found, drop packet */
21519 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21520 			if (dst_ipif == NULL) {
21521 noroute:
21522 				ip1dbg(("ip_wput: no route for dst using"
21523 				    " SO_DONTROUTE\n"));
21524 				BUMP_MIB(&ipst->ips_ip_mib,
21525 				    ipIfStatsOutNoRoutes);
21526 				mp->b_prev = mp->b_next = NULL;
21527 				if (first_mp == NULL)
21528 					first_mp = mp;
21529 				goto drop_pkt;
21530 			} else {
21531 				/*
21532 				 * If suitable ipif has been found, set
21533 				 * xmit_ill to the corresponding
21534 				 * ipif_ill because we'll be using the
21535 				 * send_from_ill logic below.
21536 				 */
21537 				ASSERT(xmit_ill == NULL);
21538 				xmit_ill = dst_ipif->ipif_ill;
21539 				mutex_enter(&xmit_ill->ill_lock);
21540 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21541 					mutex_exit(&xmit_ill->ill_lock);
21542 					xmit_ill = NULL;
21543 					ipif_refrele(dst_ipif);
21544 					goto noroute;
21545 				}
21546 				ill_refhold_locked(xmit_ill);
21547 				mutex_exit(&xmit_ill->ill_lock);
21548 				ipif_refrele(dst_ipif);
21549 			}
21550 		}
21551 		/*
21552 		 * If we are bound to IPIF_NOFAILOVER address, look for
21553 		 * an IRE_CACHE matching the ill.
21554 		 */
21555 send_from_ill:
21556 		if (attach_ill != NULL) {
21557 			ipif_t	*attach_ipif;
21558 
21559 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21560 
21561 			/*
21562 			 * Check if we need an ire that will not be
21563 			 * looked up by anybody else i.e. HIDDEN.
21564 			 */
21565 			if (ill_is_probeonly(attach_ill)) {
21566 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21567 			}
21568 
21569 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21570 			if (attach_ipif == NULL) {
21571 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21572 				goto discard_pkt;
21573 			}
21574 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21575 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21576 			ipif_refrele(attach_ipif);
21577 		} else if (xmit_ill != NULL) {
21578 			ipif_t *ipif;
21579 
21580 			/*
21581 			 * Mark this packet as originated locally
21582 			 */
21583 			mp->b_prev = mp->b_next = NULL;
21584 
21585 			/*
21586 			 * Could be SO_DONTROUTE case also.
21587 			 * Verify that at least one ipif is up on the ill.
21588 			 */
21589 			if (xmit_ill->ill_ipif_up_count == 0) {
21590 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21591 				    xmit_ill->ill_name));
21592 				goto drop_pkt;
21593 			}
21594 
21595 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21596 			if (ipif == NULL) {
21597 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21598 				    xmit_ill->ill_name));
21599 				goto drop_pkt;
21600 			}
21601 
21602 			/*
21603 			 * Look for a ire that is part of the group,
21604 			 * if found use it else call ip_newroute_ipif.
21605 			 * IPCL_ZONEID is not used for matching because
21606 			 * IP_ALLZONES option is valid only when the
21607 			 * ill is accessible from all zones i.e has a
21608 			 * valid ipif in all zones.
21609 			 */
21610 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21611 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21612 			    MBLK_GETLABEL(mp), match_flags, ipst);
21613 			/*
21614 			 * If an ire exists use it or else create
21615 			 * an ire but don't add it to the cache.
21616 			 * Adding an ire may cause issues with
21617 			 * asymmetric routing.
21618 			 * In case of multiroute always act as if
21619 			 * ire does not exist.
21620 			 */
21621 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21622 				if (ire != NULL)
21623 					ire_refrele(ire);
21624 				ip_newroute_ipif(q, first_mp, ipif,
21625 				    dst, connp, 0, zoneid, infop);
21626 				ipif_refrele(ipif);
21627 				ip1dbg(("ip_output: xmit_ill via %s\n",
21628 				    xmit_ill->ill_name));
21629 				ill_refrele(xmit_ill);
21630 				if (need_decref)
21631 					CONN_DEC_REF(connp);
21632 				return;
21633 			}
21634 			ipif_refrele(ipif);
21635 		} else if (ip_nexthop || (connp != NULL &&
21636 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21637 			if (!ip_nexthop) {
21638 				ip_nexthop = B_TRUE;
21639 				nexthop_addr = connp->conn_nexthop_v4;
21640 			}
21641 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21642 			    MATCH_IRE_GW;
21643 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21644 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21645 		} else {
21646 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21647 			    ipst);
21648 		}
21649 		if (!ire) {
21650 			/*
21651 			 * Make sure we don't load spread if this
21652 			 * is IPIF_NOFAILOVER case.
21653 			 */
21654 			if ((attach_ill != NULL) ||
21655 			    (ip_nexthop && !ignore_nexthop)) {
21656 				if (mctl_present) {
21657 					io = (ipsec_out_t *)first_mp->b_rptr;
21658 					ASSERT(first_mp->b_datap->db_type ==
21659 					    M_CTL);
21660 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21661 				} else {
21662 					ASSERT(mp == first_mp);
21663 					first_mp = allocb(
21664 					    sizeof (ipsec_info_t), BPRI_HI);
21665 					if (first_mp == NULL) {
21666 						first_mp = mp;
21667 						goto discard_pkt;
21668 					}
21669 					first_mp->b_datap->db_type = M_CTL;
21670 					first_mp->b_wptr +=
21671 					    sizeof (ipsec_info_t);
21672 					/* ipsec_out_secure is B_FALSE now */
21673 					bzero(first_mp->b_rptr,
21674 					    sizeof (ipsec_info_t));
21675 					io = (ipsec_out_t *)first_mp->b_rptr;
21676 					io->ipsec_out_type = IPSEC_OUT;
21677 					io->ipsec_out_len =
21678 					    sizeof (ipsec_out_t);
21679 					io->ipsec_out_use_global_policy =
21680 					    B_TRUE;
21681 					io->ipsec_out_ns = ipst->ips_netstack;
21682 					first_mp->b_cont = mp;
21683 					mctl_present = B_TRUE;
21684 				}
21685 				if (attach_ill != NULL) {
21686 					io->ipsec_out_ill_index = attach_ill->
21687 					    ill_phyint->phyint_ifindex;
21688 					io->ipsec_out_attach_if = B_TRUE;
21689 				} else {
21690 					io->ipsec_out_ip_nexthop = ip_nexthop;
21691 					io->ipsec_out_nexthop_addr =
21692 					    nexthop_addr;
21693 				}
21694 			}
21695 noirefound:
21696 			/*
21697 			 * Mark this packet as having originated on
21698 			 * this machine.  This will be noted in
21699 			 * ire_add_then_send, which needs to know
21700 			 * whether to run it back through ip_wput or
21701 			 * ip_rput following successful resolution.
21702 			 */
21703 			mp->b_prev = NULL;
21704 			mp->b_next = NULL;
21705 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21706 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21707 			    "ip_wput_end: q %p (%S)", q, "newroute");
21708 			if (attach_ill != NULL)
21709 				ill_refrele(attach_ill);
21710 			if (xmit_ill != NULL)
21711 				ill_refrele(xmit_ill);
21712 			if (need_decref)
21713 				CONN_DEC_REF(connp);
21714 			return;
21715 		}
21716 	}
21717 
21718 	/* We now know where we are going with it. */
21719 
21720 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21721 	    "ip_wput_end: q %p (%S)", q, "end");
21722 
21723 	/*
21724 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21725 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21726 	 */
21727 	if (ire->ire_flags & RTF_MULTIRT) {
21728 		/*
21729 		 * Force the TTL of multirouted packets if required.
21730 		 * The TTL of such packets is bounded by the
21731 		 * ip_multirt_ttl ndd variable.
21732 		 */
21733 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21734 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21735 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21736 			    "(was %d), dst 0x%08x\n",
21737 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21738 			    ntohl(ire->ire_addr)));
21739 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21740 		}
21741 		/*
21742 		 * At this point, we check to see if there are any pending
21743 		 * unresolved routes. ire_multirt_resolvable()
21744 		 * checks in O(n) that all IRE_OFFSUBNET ire
21745 		 * entries for the packet's destination and
21746 		 * flagged RTF_MULTIRT are currently resolved.
21747 		 * If some remain unresolved, we make a copy
21748 		 * of the current message. It will be used
21749 		 * to initiate additional route resolutions.
21750 		 */
21751 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21752 		    MBLK_GETLABEL(first_mp), ipst);
21753 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21754 		    "multirt_need_resolve %d, first_mp %p\n",
21755 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21756 		if (multirt_need_resolve) {
21757 			copy_mp = copymsg(first_mp);
21758 			if (copy_mp != NULL) {
21759 				MULTIRT_DEBUG_TAG(copy_mp);
21760 			}
21761 		}
21762 	}
21763 
21764 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21765 	/*
21766 	 * Try to resolve another multiroute if
21767 	 * ire_multirt_resolvable() deemed it necessary.
21768 	 * At this point, we need to distinguish
21769 	 * multicasts from other packets. For multicasts,
21770 	 * we call ip_newroute_ipif() and request that both
21771 	 * multirouting and setsrc flags are checked.
21772 	 */
21773 	if (copy_mp != NULL) {
21774 		if (CLASSD(dst)) {
21775 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21776 			if (ipif) {
21777 				ASSERT(infop->ip_opt_ill_index == 0);
21778 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21779 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21780 				ipif_refrele(ipif);
21781 			} else {
21782 				MULTIRT_DEBUG_UNTAG(copy_mp);
21783 				freemsg(copy_mp);
21784 				copy_mp = NULL;
21785 			}
21786 		} else {
21787 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21788 		}
21789 	}
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 icmp_parameter_problem:
21799 	/* could not have originated externally */
21800 	ASSERT(mp->b_prev == NULL);
21801 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21802 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21803 		/* it's the IP header length that's in trouble */
21804 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21805 		first_mp = NULL;
21806 	}
21807 
21808 discard_pkt:
21809 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21810 drop_pkt:
21811 	ip1dbg(("ip_wput: dropped packet\n"));
21812 	if (ire != NULL)
21813 		ire_refrele(ire);
21814 	if (need_decref)
21815 		CONN_DEC_REF(connp);
21816 	freemsg(first_mp);
21817 	if (attach_ill != NULL)
21818 		ill_refrele(attach_ill);
21819 	if (xmit_ill != NULL)
21820 		ill_refrele(xmit_ill);
21821 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21822 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21823 }
21824 
21825 /*
21826  * If this is a conn_t queue, then we pass in the conn. This includes the
21827  * zoneid.
21828  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21829  * in which case we use the global zoneid since those are all part of
21830  * the global zone.
21831  */
21832 void
21833 ip_wput(queue_t *q, mblk_t *mp)
21834 {
21835 	if (CONN_Q(q))
21836 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21837 	else
21838 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21839 }
21840 
21841 /*
21842  *
21843  * The following rules must be observed when accessing any ipif or ill
21844  * that has been cached in the conn. Typically conn_nofailover_ill,
21845  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21846  *
21847  * Access: The ipif or ill pointed to from the conn can be accessed under
21848  * the protection of the conn_lock or after it has been refheld under the
21849  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21850  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21851  * The reason for this is that a concurrent unplumb could actually be
21852  * cleaning up these cached pointers by walking the conns and might have
21853  * finished cleaning up the conn in question. The macros check that an
21854  * unplumb has not yet started on the ipif or ill.
21855  *
21856  * Caching: An ipif or ill pointer may be cached in the conn only after
21857  * making sure that an unplumb has not started. So the caching is done
21858  * while holding both the conn_lock and the ill_lock and after using the
21859  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21860  * flag before starting the cleanup of conns.
21861  *
21862  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21863  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21864  * or a reference to the ipif or a reference to an ire that references the
21865  * ipif. An ipif does not change its ill except for failover/failback. Since
21866  * failover/failback happens only after bringing down the ipif and making sure
21867  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21868  * the above holds.
21869  */
21870 ipif_t *
21871 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21872 {
21873 	ipif_t	*ipif;
21874 	ill_t	*ill;
21875 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21876 
21877 	*err = 0;
21878 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21879 	mutex_enter(&connp->conn_lock);
21880 	ipif = *ipifp;
21881 	if (ipif != NULL) {
21882 		ill = ipif->ipif_ill;
21883 		mutex_enter(&ill->ill_lock);
21884 		if (IPIF_CAN_LOOKUP(ipif)) {
21885 			ipif_refhold_locked(ipif);
21886 			mutex_exit(&ill->ill_lock);
21887 			mutex_exit(&connp->conn_lock);
21888 			rw_exit(&ipst->ips_ill_g_lock);
21889 			return (ipif);
21890 		} else {
21891 			*err = IPIF_LOOKUP_FAILED;
21892 		}
21893 		mutex_exit(&ill->ill_lock);
21894 	}
21895 	mutex_exit(&connp->conn_lock);
21896 	rw_exit(&ipst->ips_ill_g_lock);
21897 	return (NULL);
21898 }
21899 
21900 ill_t *
21901 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21902 {
21903 	ill_t	*ill;
21904 
21905 	*err = 0;
21906 	mutex_enter(&connp->conn_lock);
21907 	ill = *illp;
21908 	if (ill != NULL) {
21909 		mutex_enter(&ill->ill_lock);
21910 		if (ILL_CAN_LOOKUP(ill)) {
21911 			ill_refhold_locked(ill);
21912 			mutex_exit(&ill->ill_lock);
21913 			mutex_exit(&connp->conn_lock);
21914 			return (ill);
21915 		} else {
21916 			*err = ILL_LOOKUP_FAILED;
21917 		}
21918 		mutex_exit(&ill->ill_lock);
21919 	}
21920 	mutex_exit(&connp->conn_lock);
21921 	return (NULL);
21922 }
21923 
21924 static int
21925 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21926 {
21927 	ill_t	*ill;
21928 
21929 	ill = ipif->ipif_ill;
21930 	mutex_enter(&connp->conn_lock);
21931 	mutex_enter(&ill->ill_lock);
21932 	if (IPIF_CAN_LOOKUP(ipif)) {
21933 		*ipifp = ipif;
21934 		mutex_exit(&ill->ill_lock);
21935 		mutex_exit(&connp->conn_lock);
21936 		return (0);
21937 	}
21938 	mutex_exit(&ill->ill_lock);
21939 	mutex_exit(&connp->conn_lock);
21940 	return (IPIF_LOOKUP_FAILED);
21941 }
21942 
21943 /*
21944  * This is called if the outbound datagram needs fragmentation.
21945  *
21946  * NOTE : This function does not ire_refrele the ire argument passed in.
21947  */
21948 static void
21949 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21950     ip_stack_t *ipst, conn_t *connp)
21951 {
21952 	ipha_t		*ipha;
21953 	mblk_t		*mp;
21954 	uint32_t	v_hlen_tos_len;
21955 	uint32_t	max_frag;
21956 	uint32_t	frag_flag;
21957 	boolean_t	dont_use;
21958 
21959 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21960 		mp = ipsec_mp->b_cont;
21961 	} else {
21962 		mp = ipsec_mp;
21963 	}
21964 
21965 	ipha = (ipha_t *)mp->b_rptr;
21966 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21967 
21968 #ifdef	_BIG_ENDIAN
21969 #define	V_HLEN	(v_hlen_tos_len >> 24)
21970 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21971 #else
21972 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21973 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21974 #endif
21975 
21976 #ifndef SPEED_BEFORE_SAFETY
21977 	/*
21978 	 * Check that ipha_length is consistent with
21979 	 * the mblk length
21980 	 */
21981 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21982 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21983 		    LENGTH, msgdsize(mp)));
21984 		freemsg(ipsec_mp);
21985 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21986 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21987 		    "packet length mismatch");
21988 		return;
21989 	}
21990 #endif
21991 	/*
21992 	 * Don't use frag_flag if pre-built packet or source
21993 	 * routed or if multicast (since multicast packets do not solicit
21994 	 * ICMP "packet too big" messages). Get the values of
21995 	 * max_frag and frag_flag atomically by acquiring the
21996 	 * ire_lock.
21997 	 */
21998 	mutex_enter(&ire->ire_lock);
21999 	max_frag = ire->ire_max_frag;
22000 	frag_flag = ire->ire_frag_flag;
22001 	mutex_exit(&ire->ire_lock);
22002 
22003 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
22004 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
22005 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
22006 
22007 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
22008 	    (dont_use ? 0 : frag_flag), zoneid, ipst, connp);
22009 }
22010 
22011 /*
22012  * Used for deciding the MSS size for the upper layer. Thus
22013  * we need to check the outbound policy values in the conn.
22014  */
22015 int
22016 conn_ipsec_length(conn_t *connp)
22017 {
22018 	ipsec_latch_t *ipl;
22019 
22020 	ipl = connp->conn_latch;
22021 	if (ipl == NULL)
22022 		return (0);
22023 
22024 	if (ipl->ipl_out_policy == NULL)
22025 		return (0);
22026 
22027 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
22028 }
22029 
22030 /*
22031  * Returns an estimate of the IPsec headers size. This is used if
22032  * we don't want to call into IPsec to get the exact size.
22033  */
22034 int
22035 ipsec_out_extra_length(mblk_t *ipsec_mp)
22036 {
22037 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
22038 	ipsec_action_t *a;
22039 
22040 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
22041 	if (!io->ipsec_out_secure)
22042 		return (0);
22043 
22044 	a = io->ipsec_out_act;
22045 
22046 	if (a == NULL) {
22047 		ASSERT(io->ipsec_out_policy != NULL);
22048 		a = io->ipsec_out_policy->ipsp_act;
22049 	}
22050 	ASSERT(a != NULL);
22051 
22052 	return (a->ipa_ovhd);
22053 }
22054 
22055 /*
22056  * Returns an estimate of the IPsec headers size. This is used if
22057  * we don't want to call into IPsec to get the exact size.
22058  */
22059 int
22060 ipsec_in_extra_length(mblk_t *ipsec_mp)
22061 {
22062 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
22063 	ipsec_action_t *a;
22064 
22065 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22066 
22067 	a = ii->ipsec_in_action;
22068 	return (a == NULL ? 0 : a->ipa_ovhd);
22069 }
22070 
22071 /*
22072  * If there are any source route options, return the true final
22073  * destination. Otherwise, return the destination.
22074  */
22075 ipaddr_t
22076 ip_get_dst(ipha_t *ipha)
22077 {
22078 	ipoptp_t	opts;
22079 	uchar_t		*opt;
22080 	uint8_t		optval;
22081 	uint8_t		optlen;
22082 	ipaddr_t	dst;
22083 	uint32_t off;
22084 
22085 	dst = ipha->ipha_dst;
22086 
22087 	if (IS_SIMPLE_IPH(ipha))
22088 		return (dst);
22089 
22090 	for (optval = ipoptp_first(&opts, ipha);
22091 	    optval != IPOPT_EOL;
22092 	    optval = ipoptp_next(&opts)) {
22093 		opt = opts.ipoptp_cur;
22094 		optlen = opts.ipoptp_len;
22095 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22096 		switch (optval) {
22097 		case IPOPT_SSRR:
22098 		case IPOPT_LSRR:
22099 			off = opt[IPOPT_OFFSET];
22100 			/*
22101 			 * If one of the conditions is true, it means
22102 			 * end of options and dst already has the right
22103 			 * value.
22104 			 */
22105 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22106 				off = optlen - IP_ADDR_LEN;
22107 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22108 			}
22109 			return (dst);
22110 		default:
22111 			break;
22112 		}
22113 	}
22114 
22115 	return (dst);
22116 }
22117 
22118 mblk_t *
22119 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22120     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22121 {
22122 	ipsec_out_t	*io;
22123 	mblk_t		*first_mp;
22124 	boolean_t policy_present;
22125 	ip_stack_t	*ipst;
22126 	ipsec_stack_t	*ipss;
22127 
22128 	ASSERT(ire != NULL);
22129 	ipst = ire->ire_ipst;
22130 	ipss = ipst->ips_netstack->netstack_ipsec;
22131 
22132 	first_mp = mp;
22133 	if (mp->b_datap->db_type == M_CTL) {
22134 		io = (ipsec_out_t *)first_mp->b_rptr;
22135 		/*
22136 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22137 		 *
22138 		 * 1) There is per-socket policy (including cached global
22139 		 *    policy) or a policy on the IP-in-IP tunnel.
22140 		 * 2) There is no per-socket policy, but it is
22141 		 *    a multicast packet that needs to go out
22142 		 *    on a specific interface. This is the case
22143 		 *    where (ip_wput and ip_wput_multicast) attaches
22144 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22145 		 *
22146 		 * In case (2) we check with global policy to
22147 		 * see if there is a match and set the ill_index
22148 		 * appropriately so that we can lookup the ire
22149 		 * properly in ip_wput_ipsec_out.
22150 		 */
22151 
22152 		/*
22153 		 * ipsec_out_use_global_policy is set to B_FALSE
22154 		 * in ipsec_in_to_out(). Refer to that function for
22155 		 * details.
22156 		 */
22157 		if ((io->ipsec_out_latch == NULL) &&
22158 		    (io->ipsec_out_use_global_policy)) {
22159 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22160 			    ire, connp, unspec_src, zoneid));
22161 		}
22162 		if (!io->ipsec_out_secure) {
22163 			/*
22164 			 * If this is not a secure packet, drop
22165 			 * the IPSEC_OUT mp and treat it as a clear
22166 			 * packet. This happens when we are sending
22167 			 * a ICMP reply back to a clear packet. See
22168 			 * ipsec_in_to_out() for details.
22169 			 */
22170 			mp = first_mp->b_cont;
22171 			freeb(first_mp);
22172 		}
22173 		return (mp);
22174 	}
22175 	/*
22176 	 * See whether we need to attach a global policy here. We
22177 	 * don't depend on the conn (as it could be null) for deciding
22178 	 * what policy this datagram should go through because it
22179 	 * should have happened in ip_wput if there was some
22180 	 * policy. This normally happens for connections which are not
22181 	 * fully bound preventing us from caching policies in
22182 	 * ip_bind. Packets coming from the TCP listener/global queue
22183 	 * - which are non-hard_bound - could also be affected by
22184 	 * applying policy here.
22185 	 *
22186 	 * If this packet is coming from tcp global queue or listener,
22187 	 * we will be applying policy here.  This may not be *right*
22188 	 * if these packets are coming from the detached connection as
22189 	 * it could have gone in clear before. This happens only if a
22190 	 * TCP connection started when there is no policy and somebody
22191 	 * added policy before it became detached. Thus packets of the
22192 	 * detached connection could go out secure and the other end
22193 	 * would drop it because it will be expecting in clear. The
22194 	 * converse is not true i.e if somebody starts a TCP
22195 	 * connection and deletes the policy, all the packets will
22196 	 * still go out with the policy that existed before deleting
22197 	 * because ip_unbind sends up policy information which is used
22198 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22199 	 * TCP to attach a dummy IPSEC_OUT and set
22200 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22201 	 * affect performance for normal cases, we are not doing it.
22202 	 * Thus, set policy before starting any TCP connections.
22203 	 *
22204 	 * NOTE - We might apply policy even for a hard bound connection
22205 	 * - for which we cached policy in ip_bind - if somebody added
22206 	 * global policy after we inherited the policy in ip_bind.
22207 	 * This means that the packets that were going out in clear
22208 	 * previously would start going secure and hence get dropped
22209 	 * on the other side. To fix this, TCP attaches a dummy
22210 	 * ipsec_out and make sure that we don't apply global policy.
22211 	 */
22212 	if (ipha != NULL)
22213 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22214 	else
22215 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22216 	if (!policy_present)
22217 		return (mp);
22218 
22219 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22220 	    zoneid));
22221 }
22222 
22223 ire_t *
22224 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22225 {
22226 	ipaddr_t addr;
22227 	ire_t *save_ire;
22228 	irb_t *irb;
22229 	ill_group_t *illgrp;
22230 	int	err;
22231 
22232 	save_ire = ire;
22233 	addr = ire->ire_addr;
22234 
22235 	ASSERT(ire->ire_type == IRE_BROADCAST);
22236 
22237 	illgrp = connp->conn_outgoing_ill->ill_group;
22238 	if (illgrp == NULL) {
22239 		*conn_outgoing_ill = conn_get_held_ill(connp,
22240 		    &connp->conn_outgoing_ill, &err);
22241 		if (err == ILL_LOOKUP_FAILED) {
22242 			ire_refrele(save_ire);
22243 			return (NULL);
22244 		}
22245 		return (save_ire);
22246 	}
22247 	/*
22248 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22249 	 * If it is part of the group, we need to send on the ire
22250 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22251 	 * to this group. This is okay as IP_BOUND_IF really means
22252 	 * any ill in the group. We depend on the fact that the
22253 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22254 	 * if such an ire exists. This is possible only if you have
22255 	 * at least one ill in the group that has not failed.
22256 	 *
22257 	 * First get to the ire that matches the address and group.
22258 	 *
22259 	 * We don't look for an ire with a matching zoneid because a given zone
22260 	 * won't always have broadcast ires on all ills in the group.
22261 	 */
22262 	irb = ire->ire_bucket;
22263 	rw_enter(&irb->irb_lock, RW_READER);
22264 	if (ire->ire_marks & IRE_MARK_NORECV) {
22265 		/*
22266 		 * If the current zone only has an ire broadcast for this
22267 		 * address marked NORECV, the ire we want is ahead in the
22268 		 * bucket, so we look it up deliberately ignoring the zoneid.
22269 		 */
22270 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22271 			if (ire->ire_addr != addr)
22272 				continue;
22273 			/* skip over deleted ires */
22274 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22275 				continue;
22276 		}
22277 	}
22278 	while (ire != NULL) {
22279 		/*
22280 		 * If a new interface is coming up, we could end up
22281 		 * seeing the loopback ire and the non-loopback ire
22282 		 * may not have been added yet. So check for ire_stq
22283 		 */
22284 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22285 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22286 			break;
22287 		}
22288 		ire = ire->ire_next;
22289 	}
22290 	if (ire != NULL && ire->ire_addr == addr &&
22291 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22292 		IRE_REFHOLD(ire);
22293 		rw_exit(&irb->irb_lock);
22294 		ire_refrele(save_ire);
22295 		*conn_outgoing_ill = ire_to_ill(ire);
22296 		/*
22297 		 * Refhold the ill to make the conn_outgoing_ill
22298 		 * independent of the ire. ip_wput_ire goes in a loop
22299 		 * and may refrele the ire. Since we have an ire at this
22300 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22301 		 */
22302 		ill_refhold(*conn_outgoing_ill);
22303 		return (ire);
22304 	}
22305 	rw_exit(&irb->irb_lock);
22306 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22307 	/*
22308 	 * If we can't find a suitable ire, return the original ire.
22309 	 */
22310 	return (save_ire);
22311 }
22312 
22313 /*
22314  * This function does the ire_refrele of the ire passed in as the
22315  * argument. As this function looks up more ires i.e broadcast ires,
22316  * it needs to REFRELE them. Currently, for simplicity we don't
22317  * differentiate the one passed in and looked up here. We always
22318  * REFRELE.
22319  * IPQoS Notes:
22320  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22321  * IPsec packets are done in ipsec_out_process.
22322  *
22323  */
22324 void
22325 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22326     zoneid_t zoneid)
22327 {
22328 	ipha_t		*ipha;
22329 #define	rptr	((uchar_t *)ipha)
22330 	queue_t		*stq;
22331 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22332 	uint32_t	v_hlen_tos_len;
22333 	uint32_t	ttl_protocol;
22334 	ipaddr_t	src;
22335 	ipaddr_t	dst;
22336 	uint32_t	cksum;
22337 	ipaddr_t	orig_src;
22338 	ire_t		*ire1;
22339 	mblk_t		*next_mp;
22340 	uint_t		hlen;
22341 	uint16_t	*up;
22342 	uint32_t	max_frag = ire->ire_max_frag;
22343 	ill_t		*ill = ire_to_ill(ire);
22344 	int		clusterwide;
22345 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22346 	int		ipsec_len;
22347 	mblk_t		*first_mp;
22348 	ipsec_out_t	*io;
22349 	boolean_t	conn_dontroute;		/* conn value for multicast */
22350 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22351 	boolean_t	multicast_forward;	/* Should we forward ? */
22352 	boolean_t	unspec_src;
22353 	ill_t		*conn_outgoing_ill = NULL;
22354 	ill_t		*ire_ill;
22355 	ill_t		*ire1_ill;
22356 	ill_t		*out_ill;
22357 	uint32_t 	ill_index = 0;
22358 	boolean_t	multirt_send = B_FALSE;
22359 	int		err;
22360 	ipxmit_state_t	pktxmit_state;
22361 	ip_stack_t	*ipst = ire->ire_ipst;
22362 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22363 
22364 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22365 	    "ip_wput_ire_start: q %p", q);
22366 
22367 	multicast_forward = B_FALSE;
22368 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22369 
22370 	if (ire->ire_flags & RTF_MULTIRT) {
22371 		/*
22372 		 * Multirouting case. The bucket where ire is stored
22373 		 * probably holds other RTF_MULTIRT flagged ire
22374 		 * to the destination. In this call to ip_wput_ire,
22375 		 * we attempt to send the packet through all
22376 		 * those ires. Thus, we first ensure that ire is the
22377 		 * first RTF_MULTIRT ire in the bucket,
22378 		 * before walking the ire list.
22379 		 */
22380 		ire_t *first_ire;
22381 		irb_t *irb = ire->ire_bucket;
22382 		ASSERT(irb != NULL);
22383 
22384 		/* Make sure we do not omit any multiroute ire. */
22385 		IRB_REFHOLD(irb);
22386 		for (first_ire = irb->irb_ire;
22387 		    first_ire != NULL;
22388 		    first_ire = first_ire->ire_next) {
22389 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22390 			    (first_ire->ire_addr == ire->ire_addr) &&
22391 			    !(first_ire->ire_marks &
22392 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22393 				break;
22394 			}
22395 		}
22396 
22397 		if ((first_ire != NULL) && (first_ire != ire)) {
22398 			IRE_REFHOLD(first_ire);
22399 			ire_refrele(ire);
22400 			ire = first_ire;
22401 			ill = ire_to_ill(ire);
22402 		}
22403 		IRB_REFRELE(irb);
22404 	}
22405 
22406 	/*
22407 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22408 	 * for performance we don't grab the mutexs in the fastpath
22409 	 */
22410 	if ((connp != NULL) &&
22411 	    (ire->ire_type == IRE_BROADCAST) &&
22412 	    ((connp->conn_nofailover_ill != NULL) ||
22413 	    (connp->conn_outgoing_ill != NULL))) {
22414 		/*
22415 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22416 		 * option. So, see if this endpoint is bound to a
22417 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22418 		 * that if the interface is failed, we will still send
22419 		 * the packet on the same ill which is what we want.
22420 		 */
22421 		conn_outgoing_ill = conn_get_held_ill(connp,
22422 		    &connp->conn_nofailover_ill, &err);
22423 		if (err == ILL_LOOKUP_FAILED) {
22424 			ire_refrele(ire);
22425 			freemsg(mp);
22426 			return;
22427 		}
22428 		if (conn_outgoing_ill == NULL) {
22429 			/*
22430 			 * Choose a good ill in the group to send the
22431 			 * packets on.
22432 			 */
22433 			ire = conn_set_outgoing_ill(connp, ire,
22434 			    &conn_outgoing_ill);
22435 			if (ire == NULL) {
22436 				freemsg(mp);
22437 				return;
22438 			}
22439 		}
22440 	}
22441 
22442 	if (mp->b_datap->db_type != M_CTL) {
22443 		ipha = (ipha_t *)mp->b_rptr;
22444 	} else {
22445 		io = (ipsec_out_t *)mp->b_rptr;
22446 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22447 		ASSERT(zoneid == io->ipsec_out_zoneid);
22448 		ASSERT(zoneid != ALL_ZONES);
22449 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22450 		dst = ipha->ipha_dst;
22451 		/*
22452 		 * For the multicast case, ipsec_out carries conn_dontroute and
22453 		 * conn_multicast_loop as conn may not be available here. We
22454 		 * need this for multicast loopback and forwarding which is done
22455 		 * later in the code.
22456 		 */
22457 		if (CLASSD(dst)) {
22458 			conn_dontroute = io->ipsec_out_dontroute;
22459 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22460 			/*
22461 			 * If conn_dontroute is not set or conn_multicast_loop
22462 			 * is set, we need to do forwarding/loopback. For
22463 			 * datagrams from ip_wput_multicast, conn_dontroute is
22464 			 * set to B_TRUE and conn_multicast_loop is set to
22465 			 * B_FALSE so that we neither do forwarding nor
22466 			 * loopback.
22467 			 */
22468 			if (!conn_dontroute || conn_multicast_loop)
22469 				multicast_forward = B_TRUE;
22470 		}
22471 	}
22472 
22473 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22474 	    ire->ire_zoneid != ALL_ZONES) {
22475 		/*
22476 		 * When a zone sends a packet to another zone, we try to deliver
22477 		 * the packet under the same conditions as if the destination
22478 		 * was a real node on the network. To do so, we look for a
22479 		 * matching route in the forwarding table.
22480 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22481 		 * ip_newroute() does.
22482 		 * Note that IRE_LOCAL are special, since they are used
22483 		 * when the zoneid doesn't match in some cases. This means that
22484 		 * we need to handle ipha_src differently since ire_src_addr
22485 		 * belongs to the receiving zone instead of the sending zone.
22486 		 * When ip_restrict_interzone_loopback is set, then
22487 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22488 		 * for loopback between zones when the logical "Ethernet" would
22489 		 * have looped them back.
22490 		 */
22491 		ire_t *src_ire;
22492 
22493 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22494 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22495 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22496 		if (src_ire != NULL &&
22497 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22498 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22499 		    ire_local_same_ill_group(ire, src_ire))) {
22500 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22501 				ipha->ipha_src = src_ire->ire_src_addr;
22502 			ire_refrele(src_ire);
22503 		} else {
22504 			ire_refrele(ire);
22505 			if (conn_outgoing_ill != NULL)
22506 				ill_refrele(conn_outgoing_ill);
22507 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22508 			if (src_ire != NULL) {
22509 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22510 					ire_refrele(src_ire);
22511 					freemsg(mp);
22512 					return;
22513 				}
22514 				ire_refrele(src_ire);
22515 			}
22516 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22517 				/* Failed */
22518 				freemsg(mp);
22519 				return;
22520 			}
22521 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22522 			    ipst);
22523 			return;
22524 		}
22525 	}
22526 
22527 	if (mp->b_datap->db_type == M_CTL ||
22528 	    ipss->ipsec_outbound_v4_policy_present) {
22529 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22530 		    unspec_src, zoneid);
22531 		if (mp == NULL) {
22532 			ire_refrele(ire);
22533 			if (conn_outgoing_ill != NULL)
22534 				ill_refrele(conn_outgoing_ill);
22535 			return;
22536 		}
22537 		/*
22538 		 * Trusted Extensions supports all-zones interfaces, so
22539 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22540 		 * the global zone.
22541 		 */
22542 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22543 			io = (ipsec_out_t *)mp->b_rptr;
22544 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22545 			zoneid = io->ipsec_out_zoneid;
22546 		}
22547 	}
22548 
22549 	first_mp = mp;
22550 	ipsec_len = 0;
22551 
22552 	if (first_mp->b_datap->db_type == M_CTL) {
22553 		io = (ipsec_out_t *)first_mp->b_rptr;
22554 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22555 		mp = first_mp->b_cont;
22556 		ipsec_len = ipsec_out_extra_length(first_mp);
22557 		ASSERT(ipsec_len >= 0);
22558 		/* We already picked up the zoneid from the M_CTL above */
22559 		ASSERT(zoneid == io->ipsec_out_zoneid);
22560 		ASSERT(zoneid != ALL_ZONES);
22561 
22562 		/*
22563 		 * Drop M_CTL here if IPsec processing is not needed.
22564 		 * (Non-IPsec use of M_CTL extracted any information it
22565 		 * needed above).
22566 		 */
22567 		if (ipsec_len == 0) {
22568 			freeb(first_mp);
22569 			first_mp = mp;
22570 		}
22571 	}
22572 
22573 	/*
22574 	 * Fast path for ip_wput_ire
22575 	 */
22576 
22577 	ipha = (ipha_t *)mp->b_rptr;
22578 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22579 	dst = ipha->ipha_dst;
22580 
22581 	/*
22582 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22583 	 * if the socket is a SOCK_RAW type. The transport checksum should
22584 	 * be provided in the pre-built packet, so we don't need to compute it.
22585 	 * Also, other application set flags, like DF, should not be altered.
22586 	 * Other transport MUST pass down zero.
22587 	 */
22588 	ip_hdr_included = ipha->ipha_ident;
22589 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22590 
22591 	if (CLASSD(dst)) {
22592 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22593 		    ntohl(dst),
22594 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22595 		    ntohl(ire->ire_addr)));
22596 	}
22597 
22598 /* Macros to extract header fields from data already in registers */
22599 #ifdef	_BIG_ENDIAN
22600 #define	V_HLEN	(v_hlen_tos_len >> 24)
22601 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22602 #define	PROTO	(ttl_protocol & 0xFF)
22603 #else
22604 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22605 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22606 #define	PROTO	(ttl_protocol >> 8)
22607 #endif
22608 
22609 
22610 	orig_src = src = ipha->ipha_src;
22611 	/* (The loop back to "another" is explained down below.) */
22612 another:;
22613 	/*
22614 	 * Assign an ident value for this packet.  We assign idents on
22615 	 * a per destination basis out of the IRE.  There could be
22616 	 * other threads targeting the same destination, so we have to
22617 	 * arrange for a atomic increment.  Note that we use a 32-bit
22618 	 * atomic add because it has better performance than its
22619 	 * 16-bit sibling.
22620 	 *
22621 	 * If running in cluster mode and if the source address
22622 	 * belongs to a replicated service then vector through
22623 	 * cl_inet_ipident vector to allocate ip identifier
22624 	 * NOTE: This is a contract private interface with the
22625 	 * clustering group.
22626 	 */
22627 	clusterwide = 0;
22628 	if (cl_inet_ipident) {
22629 		ASSERT(cl_inet_isclusterwide);
22630 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22631 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22632 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22633 			    AF_INET, (uint8_t *)(uintptr_t)src,
22634 			    (uint8_t *)(uintptr_t)dst);
22635 			clusterwide = 1;
22636 		}
22637 	}
22638 	if (!clusterwide) {
22639 		ipha->ipha_ident =
22640 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22641 	}
22642 
22643 #ifndef _BIG_ENDIAN
22644 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22645 #endif
22646 
22647 	/*
22648 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22649 	 * This is needed to obey conn_unspec_src when packets go through
22650 	 * ip_newroute + arp.
22651 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22652 	 */
22653 	if (src == INADDR_ANY && !unspec_src) {
22654 		/*
22655 		 * Assign the appropriate source address from the IRE if none
22656 		 * was specified.
22657 		 */
22658 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22659 
22660 		/*
22661 		 * With IP multipathing, broadcast packets are sent on the ire
22662 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22663 		 * the group. However, this ire might not be in the same zone so
22664 		 * we can't always use its source address. We look for a
22665 		 * broadcast ire in the same group and in the right zone.
22666 		 */
22667 		if (ire->ire_type == IRE_BROADCAST &&
22668 		    ire->ire_zoneid != zoneid) {
22669 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22670 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22671 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22672 			if (src_ire != NULL) {
22673 				src = src_ire->ire_src_addr;
22674 				ire_refrele(src_ire);
22675 			} else {
22676 				ire_refrele(ire);
22677 				if (conn_outgoing_ill != NULL)
22678 					ill_refrele(conn_outgoing_ill);
22679 				freemsg(first_mp);
22680 				if (ill != NULL) {
22681 					BUMP_MIB(ill->ill_ip_mib,
22682 					    ipIfStatsOutDiscards);
22683 				} else {
22684 					BUMP_MIB(&ipst->ips_ip_mib,
22685 					    ipIfStatsOutDiscards);
22686 				}
22687 				return;
22688 			}
22689 		} else {
22690 			src = ire->ire_src_addr;
22691 		}
22692 
22693 		if (connp == NULL) {
22694 			ip1dbg(("ip_wput_ire: no connp and no src "
22695 			    "address for dst 0x%x, using src 0x%x\n",
22696 			    ntohl(dst),
22697 			    ntohl(src)));
22698 		}
22699 		ipha->ipha_src = src;
22700 	}
22701 	stq = ire->ire_stq;
22702 
22703 	/*
22704 	 * We only allow ire chains for broadcasts since there will
22705 	 * be multiple IRE_CACHE entries for the same multicast
22706 	 * address (one per ipif).
22707 	 */
22708 	next_mp = NULL;
22709 
22710 	/* broadcast packet */
22711 	if (ire->ire_type == IRE_BROADCAST)
22712 		goto broadcast;
22713 
22714 	/* loopback ? */
22715 	if (stq == NULL)
22716 		goto nullstq;
22717 
22718 	/* The ill_index for outbound ILL */
22719 	ill_index = Q_TO_INDEX(stq);
22720 
22721 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22722 	ttl_protocol = ((uint16_t *)ipha)[4];
22723 
22724 	/* pseudo checksum (do it in parts for IP header checksum) */
22725 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22726 
22727 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22728 		queue_t *dev_q = stq->q_next;
22729 
22730 		/* flow controlled */
22731 		if (DEV_Q_FLOW_BLOCKED(dev_q))
22732 			goto blocked;
22733 
22734 		if ((PROTO == IPPROTO_UDP) &&
22735 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22736 			hlen = (V_HLEN & 0xF) << 2;
22737 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22738 			if (*up != 0) {
22739 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22740 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22741 				/* Software checksum? */
22742 				if (DB_CKSUMFLAGS(mp) == 0) {
22743 					IP_STAT(ipst, ip_out_sw_cksum);
22744 					IP_STAT_UPDATE(ipst,
22745 					    ip_udp_out_sw_cksum_bytes,
22746 					    LENGTH - hlen);
22747 				}
22748 			}
22749 		}
22750 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22751 		hlen = (V_HLEN & 0xF) << 2;
22752 		if (PROTO == IPPROTO_TCP) {
22753 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22754 			/*
22755 			 * The packet header is processed once and for all, even
22756 			 * in the multirouting case. We disable hardware
22757 			 * checksum if the packet is multirouted, as it will be
22758 			 * replicated via several interfaces, and not all of
22759 			 * them may have this capability.
22760 			 */
22761 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22762 			    LENGTH, max_frag, ipsec_len, cksum);
22763 			/* Software checksum? */
22764 			if (DB_CKSUMFLAGS(mp) == 0) {
22765 				IP_STAT(ipst, ip_out_sw_cksum);
22766 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22767 				    LENGTH - hlen);
22768 			}
22769 		} else {
22770 			sctp_hdr_t	*sctph;
22771 
22772 			ASSERT(PROTO == IPPROTO_SCTP);
22773 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22774 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22775 			/*
22776 			 * Zero out the checksum field to ensure proper
22777 			 * checksum calculation.
22778 			 */
22779 			sctph->sh_chksum = 0;
22780 #ifdef	DEBUG
22781 			if (!skip_sctp_cksum)
22782 #endif
22783 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22784 		}
22785 	}
22786 
22787 	/*
22788 	 * If this is a multicast packet and originated from ip_wput
22789 	 * we need to do loopback and forwarding checks. If it comes
22790 	 * from ip_wput_multicast, we SHOULD not do this.
22791 	 */
22792 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22793 
22794 	/* checksum */
22795 	cksum += ttl_protocol;
22796 
22797 	/* fragment the packet */
22798 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22799 		goto fragmentit;
22800 	/*
22801 	 * Don't use frag_flag if packet is pre-built or source
22802 	 * routed or if multicast (since multicast packets do
22803 	 * not solicit ICMP "packet too big" messages).
22804 	 */
22805 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22806 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22807 	    !ip_source_route_included(ipha)) &&
22808 	    !CLASSD(ipha->ipha_dst))
22809 		ipha->ipha_fragment_offset_and_flags |=
22810 		    htons(ire->ire_frag_flag);
22811 
22812 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22813 		/* calculate IP header checksum */
22814 		cksum += ipha->ipha_ident;
22815 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22816 		cksum += ipha->ipha_fragment_offset_and_flags;
22817 
22818 		/* IP options present */
22819 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22820 		if (hlen)
22821 			goto checksumoptions;
22822 
22823 		/* calculate hdr checksum */
22824 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22825 		cksum = ~(cksum + (cksum >> 16));
22826 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22827 	}
22828 	if (ipsec_len != 0) {
22829 		/*
22830 		 * We will do the rest of the processing after
22831 		 * we come back from IPsec in ip_wput_ipsec_out().
22832 		 */
22833 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22834 
22835 		io = (ipsec_out_t *)first_mp->b_rptr;
22836 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22837 		    ill_phyint->phyint_ifindex;
22838 
22839 		ipsec_out_process(q, first_mp, ire, ill_index);
22840 		ire_refrele(ire);
22841 		if (conn_outgoing_ill != NULL)
22842 			ill_refrele(conn_outgoing_ill);
22843 		return;
22844 	}
22845 
22846 	/*
22847 	 * In most cases, the emission loop below is entered only
22848 	 * once. Only in the case where the ire holds the
22849 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22850 	 * flagged ires in the bucket, and send the packet
22851 	 * through all crossed RTF_MULTIRT routes.
22852 	 */
22853 	if (ire->ire_flags & RTF_MULTIRT) {
22854 		multirt_send = B_TRUE;
22855 	}
22856 	do {
22857 		if (multirt_send) {
22858 			irb_t *irb;
22859 			/*
22860 			 * We are in a multiple send case, need to get
22861 			 * the next ire and make a duplicate of the packet.
22862 			 * ire1 holds here the next ire to process in the
22863 			 * bucket. If multirouting is expected,
22864 			 * any non-RTF_MULTIRT ire that has the
22865 			 * right destination address is ignored.
22866 			 */
22867 			irb = ire->ire_bucket;
22868 			ASSERT(irb != NULL);
22869 
22870 			IRB_REFHOLD(irb);
22871 			for (ire1 = ire->ire_next;
22872 			    ire1 != NULL;
22873 			    ire1 = ire1->ire_next) {
22874 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22875 					continue;
22876 				if (ire1->ire_addr != ire->ire_addr)
22877 					continue;
22878 				if (ire1->ire_marks &
22879 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22880 					continue;
22881 
22882 				/* Got one */
22883 				IRE_REFHOLD(ire1);
22884 				break;
22885 			}
22886 			IRB_REFRELE(irb);
22887 
22888 			if (ire1 != NULL) {
22889 				next_mp = copyb(mp);
22890 				if ((next_mp == NULL) ||
22891 				    ((mp->b_cont != NULL) &&
22892 				    ((next_mp->b_cont =
22893 				    dupmsg(mp->b_cont)) == NULL))) {
22894 					freemsg(next_mp);
22895 					next_mp = NULL;
22896 					ire_refrele(ire1);
22897 					ire1 = NULL;
22898 				}
22899 			}
22900 
22901 			/* Last multiroute ire; don't loop anymore. */
22902 			if (ire1 == NULL) {
22903 				multirt_send = B_FALSE;
22904 			}
22905 		}
22906 
22907 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22908 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22909 		    mblk_t *, mp);
22910 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22911 		    ipst->ips_ipv4firewall_physical_out,
22912 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22913 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22914 
22915 		if (mp == NULL)
22916 			goto release_ire_and_ill;
22917 
22918 		if (ipst->ips_ipobs_enabled) {
22919 			zoneid_t szone;
22920 
22921 			/*
22922 			 * On the outbound path the destination zone will be
22923 			 * unknown as we're sending this packet out on the
22924 			 * wire.
22925 			 */
22926 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22927 			    ALL_ZONES);
22928 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22929 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22930 		}
22931 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22932 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22933 
22934 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE, connp);
22935 
22936 		if ((pktxmit_state == SEND_FAILED) ||
22937 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22938 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22939 			    "- packet dropped\n"));
22940 release_ire_and_ill:
22941 			ire_refrele(ire);
22942 			if (next_mp != NULL) {
22943 				freemsg(next_mp);
22944 				ire_refrele(ire1);
22945 			}
22946 			if (conn_outgoing_ill != NULL)
22947 				ill_refrele(conn_outgoing_ill);
22948 			return;
22949 		}
22950 
22951 		if (CLASSD(dst)) {
22952 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22953 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22954 			    LENGTH);
22955 		}
22956 
22957 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22958 		    "ip_wput_ire_end: q %p (%S)",
22959 		    q, "last copy out");
22960 		IRE_REFRELE(ire);
22961 
22962 		if (multirt_send) {
22963 			ASSERT(ire1);
22964 			/*
22965 			 * Proceed with the next RTF_MULTIRT ire,
22966 			 * Also set up the send-to queue accordingly.
22967 			 */
22968 			ire = ire1;
22969 			ire1 = NULL;
22970 			stq = ire->ire_stq;
22971 			mp = next_mp;
22972 			next_mp = NULL;
22973 			ipha = (ipha_t *)mp->b_rptr;
22974 			ill_index = Q_TO_INDEX(stq);
22975 			ill = (ill_t *)stq->q_ptr;
22976 		}
22977 	} while (multirt_send);
22978 	if (conn_outgoing_ill != NULL)
22979 		ill_refrele(conn_outgoing_ill);
22980 	return;
22981 
22982 	/*
22983 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22984 	 */
22985 broadcast:
22986 	{
22987 		/*
22988 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22989 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22990 		 * can be overridden stack-wide through the ip_broadcast_ttl
22991 		 * ndd tunable, or on a per-connection basis through the
22992 		 * IP_BROADCAST_TTL socket option.
22993 		 *
22994 		 * In the event that we are replying to incoming ICMP packets,
22995 		 * connp could be NULL.
22996 		 */
22997 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22998 		if (connp != NULL) {
22999 			if (connp->conn_dontroute)
23000 				ipha->ipha_ttl = 1;
23001 			else if (connp->conn_broadcast_ttl != 0)
23002 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
23003 		}
23004 
23005 		/*
23006 		 * Note that we are not doing a IRB_REFHOLD here.
23007 		 * Actually we don't care if the list changes i.e
23008 		 * if somebody deletes an IRE from the list while
23009 		 * we drop the lock, the next time we come around
23010 		 * ire_next will be NULL and hence we won't send
23011 		 * out multiple copies which is fine.
23012 		 */
23013 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
23014 		ire1 = ire->ire_next;
23015 		if (conn_outgoing_ill != NULL) {
23016 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
23017 				ASSERT(ire1 == ire->ire_next);
23018 				if (ire1 != NULL && ire1->ire_addr == dst) {
23019 					ire_refrele(ire);
23020 					ire = ire1;
23021 					IRE_REFHOLD(ire);
23022 					ire1 = ire->ire_next;
23023 					continue;
23024 				}
23025 				rw_exit(&ire->ire_bucket->irb_lock);
23026 				/* Did not find a matching ill */
23027 				ip1dbg(("ip_wput_ire: broadcast with no "
23028 				    "matching IP_BOUND_IF ill %s dst %x\n",
23029 				    conn_outgoing_ill->ill_name, dst));
23030 				freemsg(first_mp);
23031 				if (ire != NULL)
23032 					ire_refrele(ire);
23033 				ill_refrele(conn_outgoing_ill);
23034 				return;
23035 			}
23036 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
23037 			/*
23038 			 * If the next IRE has the same address and is not one
23039 			 * of the two copies that we need to send, try to see
23040 			 * whether this copy should be sent at all. This
23041 			 * assumes that we insert loopbacks first and then
23042 			 * non-loopbacks. This is acheived by inserting the
23043 			 * loopback always before non-loopback.
23044 			 * This is used to send a single copy of a broadcast
23045 			 * packet out all physical interfaces that have an
23046 			 * matching IRE_BROADCAST while also looping
23047 			 * back one copy (to ip_wput_local) for each
23048 			 * matching physical interface. However, we avoid
23049 			 * sending packets out different logical that match by
23050 			 * having ipif_up/ipif_down supress duplicate
23051 			 * IRE_BROADCASTS.
23052 			 *
23053 			 * This feature is currently used to get broadcasts
23054 			 * sent to multiple interfaces, when the broadcast
23055 			 * address being used applies to multiple interfaces.
23056 			 * For example, a whole net broadcast will be
23057 			 * replicated on every connected subnet of
23058 			 * the target net.
23059 			 *
23060 			 * Each zone has its own set of IRE_BROADCASTs, so that
23061 			 * we're able to distribute inbound packets to multiple
23062 			 * zones who share a broadcast address. We avoid looping
23063 			 * back outbound packets in different zones but on the
23064 			 * same ill, as the application would see duplicates.
23065 			 *
23066 			 * If the interfaces are part of the same group,
23067 			 * we would want to send only one copy out for
23068 			 * whole group.
23069 			 *
23070 			 * This logic assumes that ire_add_v4() groups the
23071 			 * IRE_BROADCAST entries so that those with the same
23072 			 * ire_addr and ill_group are kept together.
23073 			 */
23074 			ire_ill = ire->ire_ipif->ipif_ill;
23075 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
23076 				if (ire_ill->ill_group != NULL &&
23077 				    (ire->ire_marks & IRE_MARK_NORECV)) {
23078 					/*
23079 					 * If the current zone only has an ire
23080 					 * broadcast for this address marked
23081 					 * NORECV, the ire we want is ahead in
23082 					 * the bucket, so we look it up
23083 					 * deliberately ignoring the zoneid.
23084 					 */
23085 					for (ire1 = ire->ire_bucket->irb_ire;
23086 					    ire1 != NULL;
23087 					    ire1 = ire1->ire_next) {
23088 						ire1_ill =
23089 						    ire1->ire_ipif->ipif_ill;
23090 						if (ire1->ire_addr != dst)
23091 							continue;
23092 						/* skip over the current ire */
23093 						if (ire1 == ire)
23094 							continue;
23095 						/* skip over deleted ires */
23096 						if (ire1->ire_marks &
23097 						    IRE_MARK_CONDEMNED)
23098 							continue;
23099 						/*
23100 						 * non-loopback ire in our
23101 						 * group: use it for the next
23102 						 * pass in the loop
23103 						 */
23104 						if (ire1->ire_stq != NULL &&
23105 						    ire1_ill->ill_group ==
23106 						    ire_ill->ill_group)
23107 							break;
23108 					}
23109 				}
23110 			} else {
23111 				while (ire1 != NULL && ire1->ire_addr == dst) {
23112 					ire1_ill = ire1->ire_ipif->ipif_ill;
23113 					/*
23114 					 * We can have two broadcast ires on the
23115 					 * same ill in different zones; here
23116 					 * we'll send a copy of the packet on
23117 					 * each ill and the fanout code will
23118 					 * call conn_wantpacket() to check that
23119 					 * the zone has the broadcast address
23120 					 * configured on the ill. If the two
23121 					 * ires are in the same group we only
23122 					 * send one copy up.
23123 					 */
23124 					if (ire1_ill != ire_ill &&
23125 					    (ire1_ill->ill_group == NULL ||
23126 					    ire_ill->ill_group == NULL ||
23127 					    ire1_ill->ill_group !=
23128 					    ire_ill->ill_group)) {
23129 						break;
23130 					}
23131 					ire1 = ire1->ire_next;
23132 				}
23133 			}
23134 		}
23135 		ASSERT(multirt_send == B_FALSE);
23136 		if (ire1 != NULL && ire1->ire_addr == dst) {
23137 			if ((ire->ire_flags & RTF_MULTIRT) &&
23138 			    (ire1->ire_flags & RTF_MULTIRT)) {
23139 				/*
23140 				 * We are in the multirouting case.
23141 				 * The message must be sent at least
23142 				 * on both ires. These ires have been
23143 				 * inserted AFTER the standard ones
23144 				 * in ip_rt_add(). There are thus no
23145 				 * other ire entries for the destination
23146 				 * address in the rest of the bucket
23147 				 * that do not have the RTF_MULTIRT
23148 				 * flag. We don't process a copy
23149 				 * of the message here. This will be
23150 				 * done in the final sending loop.
23151 				 */
23152 				multirt_send = B_TRUE;
23153 			} else {
23154 				next_mp = ip_copymsg(first_mp);
23155 				if (next_mp != NULL)
23156 					IRE_REFHOLD(ire1);
23157 			}
23158 		}
23159 		rw_exit(&ire->ire_bucket->irb_lock);
23160 	}
23161 
23162 	if (stq) {
23163 		/*
23164 		 * A non-NULL send-to queue means this packet is going
23165 		 * out of this machine.
23166 		 */
23167 		out_ill = (ill_t *)stq->q_ptr;
23168 
23169 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23170 		ttl_protocol = ((uint16_t *)ipha)[4];
23171 		/*
23172 		 * We accumulate the pseudo header checksum in cksum.
23173 		 * This is pretty hairy code, so watch close.  One
23174 		 * thing to keep in mind is that UDP and TCP have
23175 		 * stored their respective datagram lengths in their
23176 		 * checksum fields.  This lines things up real nice.
23177 		 */
23178 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23179 		    (src >> 16) + (src & 0xFFFF);
23180 		/*
23181 		 * We assume the udp checksum field contains the
23182 		 * length, so to compute the pseudo header checksum,
23183 		 * all we need is the protocol number and src/dst.
23184 		 */
23185 		/* Provide the checksums for UDP and TCP. */
23186 		if ((PROTO == IPPROTO_TCP) &&
23187 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23188 			/* hlen gets the number of uchar_ts in the IP header */
23189 			hlen = (V_HLEN & 0xF) << 2;
23190 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23191 			IP_STAT(ipst, ip_out_sw_cksum);
23192 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23193 			    LENGTH - hlen);
23194 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23195 		} else if (PROTO == IPPROTO_SCTP &&
23196 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23197 			sctp_hdr_t	*sctph;
23198 
23199 			hlen = (V_HLEN & 0xF) << 2;
23200 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23201 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23202 			sctph->sh_chksum = 0;
23203 #ifdef	DEBUG
23204 			if (!skip_sctp_cksum)
23205 #endif
23206 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23207 		} else {
23208 			queue_t	*dev_q = stq->q_next;
23209 
23210 			if (DEV_Q_FLOW_BLOCKED(dev_q)) {
23211 blocked:
23212 				ipha->ipha_ident = ip_hdr_included;
23213 				/*
23214 				 * If we don't have a conn to apply
23215 				 * backpressure, free the message.
23216 				 * In the ire_send path, we don't know
23217 				 * the position to requeue the packet. Rather
23218 				 * than reorder packets, we just drop this
23219 				 * packet.
23220 				 */
23221 				if (ipst->ips_ip_output_queue &&
23222 				    connp != NULL &&
23223 				    caller != IRE_SEND) {
23224 					if (caller == IP_WSRV) {
23225 						connp->conn_did_putbq = 1;
23226 						(void) putbq(connp->conn_wq,
23227 						    first_mp);
23228 						conn_drain_insert(connp);
23229 						/*
23230 						 * This is the service thread,
23231 						 * and the queue is already
23232 						 * noenabled. The check for
23233 						 * canput and the putbq is not
23234 						 * atomic. So we need to check
23235 						 * again.
23236 						 */
23237 						if (canput(stq->q_next))
23238 							connp->conn_did_putbq
23239 							    = 0;
23240 						IP_STAT(ipst, ip_conn_flputbq);
23241 					} else {
23242 						/*
23243 						 * We are not the service proc.
23244 						 * ip_wsrv will be scheduled or
23245 						 * is already running.
23246 						 */
23247 						(void) putq(connp->conn_wq,
23248 						    first_mp);
23249 					}
23250 				} else {
23251 					out_ill = (ill_t *)stq->q_ptr;
23252 					BUMP_MIB(out_ill->ill_ip_mib,
23253 					    ipIfStatsOutDiscards);
23254 					freemsg(first_mp);
23255 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23256 					    "ip_wput_ire_end: q %p (%S)",
23257 					    q, "discard");
23258 				}
23259 				ire_refrele(ire);
23260 				if (next_mp) {
23261 					ire_refrele(ire1);
23262 					freemsg(next_mp);
23263 				}
23264 				if (conn_outgoing_ill != NULL)
23265 					ill_refrele(conn_outgoing_ill);
23266 				return;
23267 			}
23268 			if ((PROTO == IPPROTO_UDP) &&
23269 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23270 				/*
23271 				 * hlen gets the number of uchar_ts in the
23272 				 * IP header
23273 				 */
23274 				hlen = (V_HLEN & 0xF) << 2;
23275 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23276 				max_frag = ire->ire_max_frag;
23277 				if (*up != 0) {
23278 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23279 					    up, PROTO, hlen, LENGTH, max_frag,
23280 					    ipsec_len, cksum);
23281 					/* Software checksum? */
23282 					if (DB_CKSUMFLAGS(mp) == 0) {
23283 						IP_STAT(ipst, ip_out_sw_cksum);
23284 						IP_STAT_UPDATE(ipst,
23285 						    ip_udp_out_sw_cksum_bytes,
23286 						    LENGTH - hlen);
23287 					}
23288 				}
23289 			}
23290 		}
23291 		/*
23292 		 * Need to do this even when fragmenting. The local
23293 		 * loopback can be done without computing checksums
23294 		 * but forwarding out other interface must be done
23295 		 * after the IP checksum (and ULP checksums) have been
23296 		 * computed.
23297 		 *
23298 		 * NOTE : multicast_forward is set only if this packet
23299 		 * originated from ip_wput. For packets originating from
23300 		 * ip_wput_multicast, it is not set.
23301 		 */
23302 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23303 multi_loopback:
23304 			ip2dbg(("ip_wput: multicast, loop %d\n",
23305 			    conn_multicast_loop));
23306 
23307 			/*  Forget header checksum offload */
23308 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23309 
23310 			/*
23311 			 * Local loopback of multicasts?  Check the
23312 			 * ill.
23313 			 *
23314 			 * Note that the loopback function will not come
23315 			 * in through ip_rput - it will only do the
23316 			 * client fanout thus we need to do an mforward
23317 			 * as well.  The is different from the BSD
23318 			 * logic.
23319 			 */
23320 			if (ill != NULL) {
23321 				ilm_t	*ilm;
23322 
23323 				ILM_WALKER_HOLD(ill);
23324 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23325 				    ALL_ZONES);
23326 				ILM_WALKER_RELE(ill);
23327 				if (ilm != NULL) {
23328 					/*
23329 					 * Pass along the virtual output q.
23330 					 * ip_wput_local() will distribute the
23331 					 * packet to all the matching zones,
23332 					 * except the sending zone when
23333 					 * IP_MULTICAST_LOOP is false.
23334 					 */
23335 					ip_multicast_loopback(q, ill, first_mp,
23336 					    conn_multicast_loop ? 0 :
23337 					    IP_FF_NO_MCAST_LOOP, zoneid);
23338 				}
23339 			}
23340 			if (ipha->ipha_ttl == 0) {
23341 				/*
23342 				 * 0 => only to this host i.e. we are
23343 				 * done. We are also done if this was the
23344 				 * loopback interface since it is sufficient
23345 				 * to loopback one copy of a multicast packet.
23346 				 */
23347 				freemsg(first_mp);
23348 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23349 				    "ip_wput_ire_end: q %p (%S)",
23350 				    q, "loopback");
23351 				ire_refrele(ire);
23352 				if (conn_outgoing_ill != NULL)
23353 					ill_refrele(conn_outgoing_ill);
23354 				return;
23355 			}
23356 			/*
23357 			 * ILLF_MULTICAST is checked in ip_newroute
23358 			 * i.e. we don't need to check it here since
23359 			 * all IRE_CACHEs come from ip_newroute.
23360 			 * For multicast traffic, SO_DONTROUTE is interpreted
23361 			 * to mean only send the packet out the interface
23362 			 * (optionally specified with IP_MULTICAST_IF)
23363 			 * and do not forward it out additional interfaces.
23364 			 * RSVP and the rsvp daemon is an example of a
23365 			 * protocol and user level process that
23366 			 * handles it's own routing. Hence, it uses the
23367 			 * SO_DONTROUTE option to accomplish this.
23368 			 */
23369 
23370 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23371 			    ill != NULL) {
23372 				/* Unconditionally redo the checksum */
23373 				ipha->ipha_hdr_checksum = 0;
23374 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23375 
23376 				/*
23377 				 * If this needs to go out secure, we need
23378 				 * to wait till we finish the IPsec
23379 				 * processing.
23380 				 */
23381 				if (ipsec_len == 0 &&
23382 				    ip_mforward(ill, ipha, mp)) {
23383 					freemsg(first_mp);
23384 					ip1dbg(("ip_wput: mforward failed\n"));
23385 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23386 					    "ip_wput_ire_end: q %p (%S)",
23387 					    q, "mforward failed");
23388 					ire_refrele(ire);
23389 					if (conn_outgoing_ill != NULL)
23390 						ill_refrele(conn_outgoing_ill);
23391 					return;
23392 				}
23393 			}
23394 		}
23395 		max_frag = ire->ire_max_frag;
23396 		cksum += ttl_protocol;
23397 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23398 			/* No fragmentation required for this one. */
23399 			/*
23400 			 * Don't use frag_flag if packet is pre-built or source
23401 			 * routed or if multicast (since multicast packets do
23402 			 * not solicit ICMP "packet too big" messages).
23403 			 */
23404 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23405 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23406 			    !ip_source_route_included(ipha)) &&
23407 			    !CLASSD(ipha->ipha_dst))
23408 				ipha->ipha_fragment_offset_and_flags |=
23409 				    htons(ire->ire_frag_flag);
23410 
23411 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23412 				/* Complete the IP header checksum. */
23413 				cksum += ipha->ipha_ident;
23414 				cksum += (v_hlen_tos_len >> 16)+
23415 				    (v_hlen_tos_len & 0xFFFF);
23416 				cksum += ipha->ipha_fragment_offset_and_flags;
23417 				hlen = (V_HLEN & 0xF) -
23418 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23419 				if (hlen) {
23420 checksumoptions:
23421 					/*
23422 					 * Account for the IP Options in the IP
23423 					 * header checksum.
23424 					 */
23425 					up = (uint16_t *)(rptr+
23426 					    IP_SIMPLE_HDR_LENGTH);
23427 					do {
23428 						cksum += up[0];
23429 						cksum += up[1];
23430 						up += 2;
23431 					} while (--hlen);
23432 				}
23433 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23434 				cksum = ~(cksum + (cksum >> 16));
23435 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23436 			}
23437 			if (ipsec_len != 0) {
23438 				ipsec_out_process(q, first_mp, ire, ill_index);
23439 				if (!next_mp) {
23440 					ire_refrele(ire);
23441 					if (conn_outgoing_ill != NULL)
23442 						ill_refrele(conn_outgoing_ill);
23443 					return;
23444 				}
23445 				goto next;
23446 			}
23447 
23448 			/*
23449 			 * multirt_send has already been handled
23450 			 * for broadcast, but not yet for multicast
23451 			 * or IP options.
23452 			 */
23453 			if (next_mp == NULL) {
23454 				if (ire->ire_flags & RTF_MULTIRT) {
23455 					multirt_send = B_TRUE;
23456 				}
23457 			}
23458 
23459 			/*
23460 			 * In most cases, the emission loop below is
23461 			 * entered only once. Only in the case where
23462 			 * the ire holds the RTF_MULTIRT flag, do we loop
23463 			 * to process all RTF_MULTIRT ires in the bucket,
23464 			 * and send the packet through all crossed
23465 			 * RTF_MULTIRT routes.
23466 			 */
23467 			do {
23468 				if (multirt_send) {
23469 					irb_t *irb;
23470 
23471 					irb = ire->ire_bucket;
23472 					ASSERT(irb != NULL);
23473 					/*
23474 					 * We are in a multiple send case,
23475 					 * need to get the next IRE and make
23476 					 * a duplicate of the packet.
23477 					 */
23478 					IRB_REFHOLD(irb);
23479 					for (ire1 = ire->ire_next;
23480 					    ire1 != NULL;
23481 					    ire1 = ire1->ire_next) {
23482 						if (!(ire1->ire_flags &
23483 						    RTF_MULTIRT)) {
23484 							continue;
23485 						}
23486 						if (ire1->ire_addr !=
23487 						    ire->ire_addr) {
23488 							continue;
23489 						}
23490 						if (ire1->ire_marks &
23491 						    (IRE_MARK_CONDEMNED|
23492 						    IRE_MARK_HIDDEN)) {
23493 							continue;
23494 						}
23495 
23496 						/* Got one */
23497 						IRE_REFHOLD(ire1);
23498 						break;
23499 					}
23500 					IRB_REFRELE(irb);
23501 
23502 					if (ire1 != NULL) {
23503 						next_mp = copyb(mp);
23504 						if ((next_mp == NULL) ||
23505 						    ((mp->b_cont != NULL) &&
23506 						    ((next_mp->b_cont =
23507 						    dupmsg(mp->b_cont))
23508 						    == NULL))) {
23509 							freemsg(next_mp);
23510 							next_mp = NULL;
23511 							ire_refrele(ire1);
23512 							ire1 = NULL;
23513 						}
23514 					}
23515 
23516 					/*
23517 					 * Last multiroute ire; don't loop
23518 					 * anymore. The emission is over
23519 					 * and next_mp is NULL.
23520 					 */
23521 					if (ire1 == NULL) {
23522 						multirt_send = B_FALSE;
23523 					}
23524 				}
23525 
23526 				out_ill = ire_to_ill(ire);
23527 				DTRACE_PROBE4(ip4__physical__out__start,
23528 				    ill_t *, NULL,
23529 				    ill_t *, out_ill,
23530 				    ipha_t *, ipha, mblk_t *, mp);
23531 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23532 				    ipst->ips_ipv4firewall_physical_out,
23533 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23534 				DTRACE_PROBE1(ip4__physical__out__end,
23535 				    mblk_t *, mp);
23536 				if (mp == NULL)
23537 					goto release_ire_and_ill_2;
23538 
23539 				ASSERT(ipsec_len == 0);
23540 				mp->b_prev =
23541 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23542 				DTRACE_PROBE2(ip__xmit__2,
23543 				    mblk_t *, mp, ire_t *, ire);
23544 				pktxmit_state = ip_xmit_v4(mp, ire,
23545 				    NULL, B_TRUE, connp);
23546 				if ((pktxmit_state == SEND_FAILED) ||
23547 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23548 release_ire_and_ill_2:
23549 					if (next_mp) {
23550 						freemsg(next_mp);
23551 						ire_refrele(ire1);
23552 					}
23553 					ire_refrele(ire);
23554 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23555 					    "ip_wput_ire_end: q %p (%S)",
23556 					    q, "discard MDATA");
23557 					if (conn_outgoing_ill != NULL)
23558 						ill_refrele(conn_outgoing_ill);
23559 					return;
23560 				}
23561 
23562 				if (CLASSD(dst)) {
23563 					BUMP_MIB(out_ill->ill_ip_mib,
23564 					    ipIfStatsHCOutMcastPkts);
23565 					UPDATE_MIB(out_ill->ill_ip_mib,
23566 					    ipIfStatsHCOutMcastOctets,
23567 					    LENGTH);
23568 				} else if (ire->ire_type == IRE_BROADCAST) {
23569 					BUMP_MIB(out_ill->ill_ip_mib,
23570 					    ipIfStatsHCOutBcastPkts);
23571 				}
23572 
23573 				if (multirt_send) {
23574 					/*
23575 					 * We are in a multiple send case,
23576 					 * need to re-enter the sending loop
23577 					 * using the next ire.
23578 					 */
23579 					ire_refrele(ire);
23580 					ire = ire1;
23581 					stq = ire->ire_stq;
23582 					mp = next_mp;
23583 					next_mp = NULL;
23584 					ipha = (ipha_t *)mp->b_rptr;
23585 					ill_index = Q_TO_INDEX(stq);
23586 				}
23587 			} while (multirt_send);
23588 
23589 			if (!next_mp) {
23590 				/*
23591 				 * Last copy going out (the ultra-common
23592 				 * case).  Note that we intentionally replicate
23593 				 * the putnext rather than calling it before
23594 				 * the next_mp check in hopes of a little
23595 				 * tail-call action out of the compiler.
23596 				 */
23597 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23598 				    "ip_wput_ire_end: q %p (%S)",
23599 				    q, "last copy out(1)");
23600 				ire_refrele(ire);
23601 				if (conn_outgoing_ill != NULL)
23602 					ill_refrele(conn_outgoing_ill);
23603 				return;
23604 			}
23605 			/* More copies going out below. */
23606 		} else {
23607 			int offset;
23608 fragmentit:
23609 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23610 			/*
23611 			 * If this would generate a icmp_frag_needed message,
23612 			 * we need to handle it before we do the IPsec
23613 			 * processing. Otherwise, we need to strip the IPsec
23614 			 * headers before we send up the message to the ULPs
23615 			 * which becomes messy and difficult.
23616 			 */
23617 			if (ipsec_len != 0) {
23618 				if ((max_frag < (unsigned int)(LENGTH +
23619 				    ipsec_len)) && (offset & IPH_DF)) {
23620 					out_ill = (ill_t *)stq->q_ptr;
23621 					BUMP_MIB(out_ill->ill_ip_mib,
23622 					    ipIfStatsOutFragFails);
23623 					BUMP_MIB(out_ill->ill_ip_mib,
23624 					    ipIfStatsOutFragReqds);
23625 					ipha->ipha_hdr_checksum = 0;
23626 					ipha->ipha_hdr_checksum =
23627 					    (uint16_t)ip_csum_hdr(ipha);
23628 					icmp_frag_needed(ire->ire_stq, first_mp,
23629 					    max_frag, zoneid, ipst);
23630 					if (!next_mp) {
23631 						ire_refrele(ire);
23632 						if (conn_outgoing_ill != NULL) {
23633 							ill_refrele(
23634 							    conn_outgoing_ill);
23635 						}
23636 						return;
23637 					}
23638 				} else {
23639 					/*
23640 					 * This won't cause a icmp_frag_needed
23641 					 * message. to be generated. Send it on
23642 					 * the wire. Note that this could still
23643 					 * cause fragmentation and all we
23644 					 * do is the generation of the message
23645 					 * to the ULP if needed before IPsec.
23646 					 */
23647 					if (!next_mp) {
23648 						ipsec_out_process(q, first_mp,
23649 						    ire, ill_index);
23650 						TRACE_2(TR_FAC_IP,
23651 						    TR_IP_WPUT_IRE_END,
23652 						    "ip_wput_ire_end: q %p "
23653 						    "(%S)", q,
23654 						    "last ipsec_out_process");
23655 						ire_refrele(ire);
23656 						if (conn_outgoing_ill != NULL) {
23657 							ill_refrele(
23658 							    conn_outgoing_ill);
23659 						}
23660 						return;
23661 					}
23662 					ipsec_out_process(q, first_mp,
23663 					    ire, ill_index);
23664 				}
23665 			} else {
23666 				/*
23667 				 * Initiate IPPF processing. For
23668 				 * fragmentable packets we finish
23669 				 * all QOS packet processing before
23670 				 * calling:
23671 				 * ip_wput_ire_fragmentit->ip_wput_frag
23672 				 */
23673 
23674 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23675 					ip_process(IPP_LOCAL_OUT, &mp,
23676 					    ill_index);
23677 					if (mp == NULL) {
23678 						out_ill = (ill_t *)stq->q_ptr;
23679 						BUMP_MIB(out_ill->ill_ip_mib,
23680 						    ipIfStatsOutDiscards);
23681 						if (next_mp != NULL) {
23682 							freemsg(next_mp);
23683 							ire_refrele(ire1);
23684 						}
23685 						ire_refrele(ire);
23686 						TRACE_2(TR_FAC_IP,
23687 						    TR_IP_WPUT_IRE_END,
23688 						    "ip_wput_ire: q %p (%S)",
23689 						    q, "discard MDATA");
23690 						if (conn_outgoing_ill != NULL) {
23691 							ill_refrele(
23692 							    conn_outgoing_ill);
23693 						}
23694 						return;
23695 					}
23696 				}
23697 				if (!next_mp) {
23698 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23699 					    "ip_wput_ire_end: q %p (%S)",
23700 					    q, "last fragmentation");
23701 					ip_wput_ire_fragmentit(mp, ire,
23702 					    zoneid, ipst, connp);
23703 					ire_refrele(ire);
23704 					if (conn_outgoing_ill != NULL)
23705 						ill_refrele(conn_outgoing_ill);
23706 					return;
23707 				}
23708 				ip_wput_ire_fragmentit(mp, ire,
23709 				    zoneid, ipst, connp);
23710 			}
23711 		}
23712 	} else {
23713 nullstq:
23714 		/* A NULL stq means the destination address is local. */
23715 		UPDATE_OB_PKT_COUNT(ire);
23716 		ire->ire_last_used_time = lbolt;
23717 		ASSERT(ire->ire_ipif != NULL);
23718 		if (!next_mp) {
23719 			/*
23720 			 * Is there an "in" and "out" for traffic local
23721 			 * to a host (loopback)?  The code in Solaris doesn't
23722 			 * explicitly draw a line in its code for in vs out,
23723 			 * so we've had to draw a line in the sand: ip_wput_ire
23724 			 * is considered to be the "output" side and
23725 			 * ip_wput_local to be the "input" side.
23726 			 */
23727 			out_ill = ire_to_ill(ire);
23728 
23729 			/*
23730 			 * DTrace this as ip:::send.  A blocked packet will
23731 			 * fire the send probe, but not the receive probe.
23732 			 */
23733 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23734 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23735 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23736 
23737 			DTRACE_PROBE4(ip4__loopback__out__start,
23738 			    ill_t *, NULL, ill_t *, out_ill,
23739 			    ipha_t *, ipha, mblk_t *, first_mp);
23740 
23741 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23742 			    ipst->ips_ipv4firewall_loopback_out,
23743 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23744 
23745 			DTRACE_PROBE1(ip4__loopback__out_end,
23746 			    mblk_t *, first_mp);
23747 
23748 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23749 			    "ip_wput_ire_end: q %p (%S)",
23750 			    q, "local address");
23751 
23752 			if (first_mp != NULL)
23753 				ip_wput_local(q, out_ill, ipha,
23754 				    first_mp, ire, 0, ire->ire_zoneid);
23755 			ire_refrele(ire);
23756 			if (conn_outgoing_ill != NULL)
23757 				ill_refrele(conn_outgoing_ill);
23758 			return;
23759 		}
23760 
23761 		out_ill = ire_to_ill(ire);
23762 
23763 		/*
23764 		 * DTrace this as ip:::send.  A blocked packet will fire the
23765 		 * send probe, but not the receive probe.
23766 		 */
23767 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23768 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23769 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23770 
23771 		DTRACE_PROBE4(ip4__loopback__out__start,
23772 		    ill_t *, NULL, ill_t *, out_ill,
23773 		    ipha_t *, ipha, mblk_t *, first_mp);
23774 
23775 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23776 		    ipst->ips_ipv4firewall_loopback_out,
23777 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23778 
23779 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23780 
23781 		if (first_mp != NULL)
23782 			ip_wput_local(q, out_ill, ipha,
23783 			    first_mp, ire, 0, ire->ire_zoneid);
23784 	}
23785 next:
23786 	/*
23787 	 * More copies going out to additional interfaces.
23788 	 * ire1 has already been held. We don't need the
23789 	 * "ire" anymore.
23790 	 */
23791 	ire_refrele(ire);
23792 	ire = ire1;
23793 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23794 	mp = next_mp;
23795 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23796 	ill = ire_to_ill(ire);
23797 	first_mp = mp;
23798 	if (ipsec_len != 0) {
23799 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23800 		mp = mp->b_cont;
23801 	}
23802 	dst = ire->ire_addr;
23803 	ipha = (ipha_t *)mp->b_rptr;
23804 	/*
23805 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23806 	 * Restore ipha_ident "no checksum" flag.
23807 	 */
23808 	src = orig_src;
23809 	ipha->ipha_ident = ip_hdr_included;
23810 	goto another;
23811 
23812 #undef	rptr
23813 #undef	Q_TO_INDEX
23814 }
23815 
23816 /*
23817  * Routine to allocate a message that is used to notify the ULP about MDT.
23818  * The caller may provide a pointer to the link-layer MDT capabilities,
23819  * or NULL if MDT is to be disabled on the stream.
23820  */
23821 mblk_t *
23822 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23823 {
23824 	mblk_t *mp;
23825 	ip_mdt_info_t *mdti;
23826 	ill_mdt_capab_t *idst;
23827 
23828 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23829 		DB_TYPE(mp) = M_CTL;
23830 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23831 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23832 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23833 		idst = &(mdti->mdt_capab);
23834 
23835 		/*
23836 		 * If the caller provides us with the capability, copy
23837 		 * it over into our notification message; otherwise
23838 		 * we zero out the capability portion.
23839 		 */
23840 		if (isrc != NULL)
23841 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23842 		else
23843 			bzero((caddr_t)idst, sizeof (*idst));
23844 	}
23845 	return (mp);
23846 }
23847 
23848 /*
23849  * Routine which determines whether MDT can be enabled on the destination
23850  * IRE and IPC combination, and if so, allocates and returns the MDT
23851  * notification mblk that may be used by ULP.  We also check if we need to
23852  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23853  * MDT usage in the past have been lifted.  This gets called during IP
23854  * and ULP binding.
23855  */
23856 mblk_t *
23857 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23858     ill_mdt_capab_t *mdt_cap)
23859 {
23860 	mblk_t *mp;
23861 	boolean_t rc = B_FALSE;
23862 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23863 
23864 	ASSERT(dst_ire != NULL);
23865 	ASSERT(connp != NULL);
23866 	ASSERT(mdt_cap != NULL);
23867 
23868 	/*
23869 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23870 	 * Multidata, which is handled in tcp_multisend().  This
23871 	 * is the reason why we do all these checks here, to ensure
23872 	 * that we don't enable Multidata for the cases which we
23873 	 * can't handle at the moment.
23874 	 */
23875 	do {
23876 		/* Only do TCP at the moment */
23877 		if (connp->conn_ulp != IPPROTO_TCP)
23878 			break;
23879 
23880 		/*
23881 		 * IPsec outbound policy present?  Note that we get here
23882 		 * after calling ipsec_conn_cache_policy() where the global
23883 		 * policy checking is performed.  conn_latch will be
23884 		 * non-NULL as long as there's a policy defined,
23885 		 * i.e. conn_out_enforce_policy may be NULL in such case
23886 		 * when the connection is non-secure, and hence we check
23887 		 * further if the latch refers to an outbound policy.
23888 		 */
23889 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23890 			break;
23891 
23892 		/* CGTP (multiroute) is enabled? */
23893 		if (dst_ire->ire_flags & RTF_MULTIRT)
23894 			break;
23895 
23896 		/* Outbound IPQoS enabled? */
23897 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23898 			/*
23899 			 * In this case, we disable MDT for this and all
23900 			 * future connections going over the interface.
23901 			 */
23902 			mdt_cap->ill_mdt_on = 0;
23903 			break;
23904 		}
23905 
23906 		/* socket option(s) present? */
23907 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23908 			break;
23909 
23910 		rc = B_TRUE;
23911 	/* CONSTCOND */
23912 	} while (0);
23913 
23914 	/* Remember the result */
23915 	connp->conn_mdt_ok = rc;
23916 
23917 	if (!rc)
23918 		return (NULL);
23919 	else if (!mdt_cap->ill_mdt_on) {
23920 		/*
23921 		 * If MDT has been previously turned off in the past, and we
23922 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23923 		 * then enable it for this interface.
23924 		 */
23925 		mdt_cap->ill_mdt_on = 1;
23926 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23927 		    "interface %s\n", ill_name));
23928 	}
23929 
23930 	/* Allocate the MDT info mblk */
23931 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23932 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23933 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23934 		return (NULL);
23935 	}
23936 	return (mp);
23937 }
23938 
23939 /*
23940  * Routine to allocate a message that is used to notify the ULP about LSO.
23941  * The caller may provide a pointer to the link-layer LSO capabilities,
23942  * or NULL if LSO is to be disabled on the stream.
23943  */
23944 mblk_t *
23945 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23946 {
23947 	mblk_t *mp;
23948 	ip_lso_info_t *lsoi;
23949 	ill_lso_capab_t *idst;
23950 
23951 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23952 		DB_TYPE(mp) = M_CTL;
23953 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23954 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23955 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23956 		idst = &(lsoi->lso_capab);
23957 
23958 		/*
23959 		 * If the caller provides us with the capability, copy
23960 		 * it over into our notification message; otherwise
23961 		 * we zero out the capability portion.
23962 		 */
23963 		if (isrc != NULL)
23964 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23965 		else
23966 			bzero((caddr_t)idst, sizeof (*idst));
23967 	}
23968 	return (mp);
23969 }
23970 
23971 /*
23972  * Routine which determines whether LSO can be enabled on the destination
23973  * IRE and IPC combination, and if so, allocates and returns the LSO
23974  * notification mblk that may be used by ULP.  We also check if we need to
23975  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23976  * LSO usage in the past have been lifted.  This gets called during IP
23977  * and ULP binding.
23978  */
23979 mblk_t *
23980 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23981     ill_lso_capab_t *lso_cap)
23982 {
23983 	mblk_t *mp;
23984 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23985 
23986 	ASSERT(dst_ire != NULL);
23987 	ASSERT(connp != NULL);
23988 	ASSERT(lso_cap != NULL);
23989 
23990 	connp->conn_lso_ok = B_TRUE;
23991 
23992 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23993 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23994 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23995 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23996 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23997 		connp->conn_lso_ok = B_FALSE;
23998 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23999 			/*
24000 			 * Disable LSO for this and all future connections going
24001 			 * over the interface.
24002 			 */
24003 			lso_cap->ill_lso_on = 0;
24004 		}
24005 	}
24006 
24007 	if (!connp->conn_lso_ok)
24008 		return (NULL);
24009 	else if (!lso_cap->ill_lso_on) {
24010 		/*
24011 		 * If LSO has been previously turned off in the past, and we
24012 		 * currently can do LSO (due to IPQoS policy removal, etc.)
24013 		 * then enable it for this interface.
24014 		 */
24015 		lso_cap->ill_lso_on = 1;
24016 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
24017 		    ill_name));
24018 	}
24019 
24020 	/* Allocate the LSO info mblk */
24021 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
24022 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
24023 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
24024 
24025 	return (mp);
24026 }
24027 
24028 /*
24029  * Create destination address attribute, and fill it with the physical
24030  * destination address and SAP taken from the template DL_UNITDATA_REQ
24031  * message block.
24032  */
24033 boolean_t
24034 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
24035 {
24036 	dl_unitdata_req_t *dlurp;
24037 	pattr_t *pa;
24038 	pattrinfo_t pa_info;
24039 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
24040 	uint_t das_len, das_off;
24041 
24042 	ASSERT(dlmp != NULL);
24043 
24044 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
24045 	das_len = dlurp->dl_dest_addr_length;
24046 	das_off = dlurp->dl_dest_addr_offset;
24047 
24048 	pa_info.type = PATTR_DSTADDRSAP;
24049 	pa_info.len = sizeof (**das) + das_len - 1;
24050 
24051 	/* create and associate the attribute */
24052 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24053 	if (pa != NULL) {
24054 		ASSERT(*das != NULL);
24055 		(*das)->addr_is_group = 0;
24056 		(*das)->addr_len = (uint8_t)das_len;
24057 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
24058 	}
24059 
24060 	return (pa != NULL);
24061 }
24062 
24063 /*
24064  * Create hardware checksum attribute and fill it with the values passed.
24065  */
24066 boolean_t
24067 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
24068     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
24069 {
24070 	pattr_t *pa;
24071 	pattrinfo_t pa_info;
24072 
24073 	ASSERT(mmd != NULL);
24074 
24075 	pa_info.type = PATTR_HCKSUM;
24076 	pa_info.len = sizeof (pattr_hcksum_t);
24077 
24078 	/* create and associate the attribute */
24079 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24080 	if (pa != NULL) {
24081 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
24082 
24083 		hck->hcksum_start_offset = start_offset;
24084 		hck->hcksum_stuff_offset = stuff_offset;
24085 		hck->hcksum_end_offset = end_offset;
24086 		hck->hcksum_flags = flags;
24087 	}
24088 	return (pa != NULL);
24089 }
24090 
24091 /*
24092  * Create zerocopy attribute and fill it with the specified flags
24093  */
24094 boolean_t
24095 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
24096 {
24097 	pattr_t *pa;
24098 	pattrinfo_t pa_info;
24099 
24100 	ASSERT(mmd != NULL);
24101 	pa_info.type = PATTR_ZCOPY;
24102 	pa_info.len = sizeof (pattr_zcopy_t);
24103 
24104 	/* create and associate the attribute */
24105 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
24106 	if (pa != NULL) {
24107 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
24108 
24109 		zcopy->zcopy_flags = flags;
24110 	}
24111 	return (pa != NULL);
24112 }
24113 
24114 /*
24115  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
24116  * block chain. We could rewrite to handle arbitrary message block chains but
24117  * that would make the code complicated and slow. Right now there three
24118  * restrictions:
24119  *
24120  *   1. The first message block must contain the complete IP header and
24121  *	at least 1 byte of payload data.
24122  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24123  *	so that we can use a single Multidata message.
24124  *   3. No frag must be distributed over two or more message blocks so
24125  *	that we don't need more than two packet descriptors per frag.
24126  *
24127  * The above restrictions allow us to support userland applications (which
24128  * will send down a single message block) and NFS over UDP (which will
24129  * send down a chain of at most three message blocks).
24130  *
24131  * We also don't use MDT for payloads with less than or equal to
24132  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24133  */
24134 boolean_t
24135 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24136 {
24137 	int	blocks;
24138 	ssize_t	total, missing, size;
24139 
24140 	ASSERT(mp != NULL);
24141 	ASSERT(hdr_len > 0);
24142 
24143 	size = MBLKL(mp) - hdr_len;
24144 	if (size <= 0)
24145 		return (B_FALSE);
24146 
24147 	/* The first mblk contains the header and some payload. */
24148 	blocks = 1;
24149 	total = size;
24150 	size %= len;
24151 	missing = (size == 0) ? 0 : (len - size);
24152 	mp = mp->b_cont;
24153 
24154 	while (mp != NULL) {
24155 		/*
24156 		 * Give up if we encounter a zero length message block.
24157 		 * In practice, this should rarely happen and therefore
24158 		 * not worth the trouble of freeing and re-linking the
24159 		 * mblk from the chain to handle such case.
24160 		 */
24161 		if ((size = MBLKL(mp)) == 0)
24162 			return (B_FALSE);
24163 
24164 		/* Too many payload buffers for a single Multidata message? */
24165 		if (++blocks > MULTIDATA_MAX_PBUFS)
24166 			return (B_FALSE);
24167 
24168 		total += size;
24169 		/* Is a frag distributed over two or more message blocks? */
24170 		if (missing > size)
24171 			return (B_FALSE);
24172 		size -= missing;
24173 
24174 		size %= len;
24175 		missing = (size == 0) ? 0 : (len - size);
24176 
24177 		mp = mp->b_cont;
24178 	}
24179 
24180 	return (total > ip_wput_frag_mdt_min);
24181 }
24182 
24183 /*
24184  * Outbound IPv4 fragmentation routine using MDT.
24185  */
24186 static void
24187 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24188     uint32_t frag_flag, int offset)
24189 {
24190 	ipha_t		*ipha_orig;
24191 	int		i1, ip_data_end;
24192 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24193 	mblk_t		*hdr_mp, *md_mp = NULL;
24194 	unsigned char	*hdr_ptr, *pld_ptr;
24195 	multidata_t	*mmd;
24196 	ip_pdescinfo_t	pdi;
24197 	ill_t		*ill;
24198 	ip_stack_t	*ipst = ire->ire_ipst;
24199 
24200 	ASSERT(DB_TYPE(mp) == M_DATA);
24201 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24202 
24203 	ill = ire_to_ill(ire);
24204 	ASSERT(ill != NULL);
24205 
24206 	ipha_orig = (ipha_t *)mp->b_rptr;
24207 	mp->b_rptr += sizeof (ipha_t);
24208 
24209 	/* Calculate how many packets we will send out */
24210 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24211 	pkts = (i1 + len - 1) / len;
24212 	ASSERT(pkts > 1);
24213 
24214 	/* Allocate a message block which will hold all the IP Headers. */
24215 	wroff = ipst->ips_ip_wroff_extra;
24216 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24217 
24218 	i1 = pkts * hdr_chunk_len;
24219 	/*
24220 	 * Create the header buffer, Multidata and destination address
24221 	 * and SAP attribute that should be associated with it.
24222 	 */
24223 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24224 	    ((hdr_mp->b_wptr += i1),
24225 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24226 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24227 		freemsg(mp);
24228 		if (md_mp == NULL) {
24229 			freemsg(hdr_mp);
24230 		} else {
24231 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24232 			freemsg(md_mp);
24233 		}
24234 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24235 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24236 		return;
24237 	}
24238 	IP_STAT(ipst, ip_frag_mdt_allocd);
24239 
24240 	/*
24241 	 * Add a payload buffer to the Multidata; this operation must not
24242 	 * fail, or otherwise our logic in this routine is broken.  There
24243 	 * is no memory allocation done by the routine, so any returned
24244 	 * failure simply tells us that we've done something wrong.
24245 	 *
24246 	 * A failure tells us that either we're adding the same payload
24247 	 * buffer more than once, or we're trying to add more buffers than
24248 	 * allowed.  None of the above cases should happen, and we panic
24249 	 * because either there's horrible heap corruption, and/or
24250 	 * programming mistake.
24251 	 */
24252 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24253 		goto pbuf_panic;
24254 
24255 	hdr_ptr = hdr_mp->b_rptr;
24256 	pld_ptr = mp->b_rptr;
24257 
24258 	/* Establish the ending byte offset, based on the starting offset. */
24259 	offset <<= 3;
24260 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24261 	    IP_SIMPLE_HDR_LENGTH;
24262 
24263 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24264 
24265 	while (pld_ptr < mp->b_wptr) {
24266 		ipha_t		*ipha;
24267 		uint16_t	offset_and_flags;
24268 		uint16_t	ip_len;
24269 		int		error;
24270 
24271 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24272 		ipha = (ipha_t *)(hdr_ptr + wroff);
24273 		ASSERT(OK_32PTR(ipha));
24274 		*ipha = *ipha_orig;
24275 
24276 		if (ip_data_end - offset > len) {
24277 			offset_and_flags = IPH_MF;
24278 		} else {
24279 			/*
24280 			 * Last frag. Set len to the length of this last piece.
24281 			 */
24282 			len = ip_data_end - offset;
24283 			/* A frag of a frag might have IPH_MF non-zero */
24284 			offset_and_flags =
24285 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24286 			    IPH_MF;
24287 		}
24288 		offset_and_flags |= (uint16_t)(offset >> 3);
24289 		offset_and_flags |= (uint16_t)frag_flag;
24290 		/* Store the offset and flags in the IP header. */
24291 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24292 
24293 		/* Store the length in the IP header. */
24294 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24295 		ipha->ipha_length = htons(ip_len);
24296 
24297 		/*
24298 		 * Set the IP header checksum.  Note that mp is just
24299 		 * the header, so this is easy to pass to ip_csum.
24300 		 */
24301 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24302 
24303 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24304 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24305 		    NULL, int, 0);
24306 
24307 		/*
24308 		 * Record offset and size of header and data of the next packet
24309 		 * in the multidata message.
24310 		 */
24311 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24312 		PDESC_PLD_INIT(&pdi);
24313 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24314 		ASSERT(i1 > 0);
24315 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24316 		if (i1 == len) {
24317 			pld_ptr += len;
24318 		} else {
24319 			i1 = len - i1;
24320 			mp = mp->b_cont;
24321 			ASSERT(mp != NULL);
24322 			ASSERT(MBLKL(mp) >= i1);
24323 			/*
24324 			 * Attach the next payload message block to the
24325 			 * multidata message.
24326 			 */
24327 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24328 				goto pbuf_panic;
24329 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24330 			pld_ptr = mp->b_rptr + i1;
24331 		}
24332 
24333 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24334 		    KM_NOSLEEP)) == NULL) {
24335 			/*
24336 			 * Any failure other than ENOMEM indicates that we
24337 			 * have passed in invalid pdesc info or parameters
24338 			 * to mmd_addpdesc, which must not happen.
24339 			 *
24340 			 * EINVAL is a result of failure on boundary checks
24341 			 * against the pdesc info contents.  It should not
24342 			 * happen, and we panic because either there's
24343 			 * horrible heap corruption, and/or programming
24344 			 * mistake.
24345 			 */
24346 			if (error != ENOMEM) {
24347 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24348 				    "pdesc logic error detected for "
24349 				    "mmd %p pinfo %p (%d)\n",
24350 				    (void *)mmd, (void *)&pdi, error);
24351 				/* NOTREACHED */
24352 			}
24353 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24354 			/* Free unattached payload message blocks as well */
24355 			md_mp->b_cont = mp->b_cont;
24356 			goto free_mmd;
24357 		}
24358 
24359 		/* Advance fragment offset. */
24360 		offset += len;
24361 
24362 		/* Advance to location for next header in the buffer. */
24363 		hdr_ptr += hdr_chunk_len;
24364 
24365 		/* Did we reach the next payload message block? */
24366 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24367 			mp = mp->b_cont;
24368 			/*
24369 			 * Attach the next message block with payload
24370 			 * data to the multidata message.
24371 			 */
24372 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24373 				goto pbuf_panic;
24374 			pld_ptr = mp->b_rptr;
24375 		}
24376 	}
24377 
24378 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24379 	ASSERT(mp->b_wptr == pld_ptr);
24380 
24381 	/* Update IP statistics */
24382 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24383 
24384 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24385 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24386 
24387 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24388 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24389 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24390 
24391 	if (pkt_type == OB_PKT) {
24392 		ire->ire_ob_pkt_count += pkts;
24393 		if (ire->ire_ipif != NULL)
24394 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24395 	} else {
24396 		/* The type is IB_PKT in the forwarding path. */
24397 		ire->ire_ib_pkt_count += pkts;
24398 		ASSERT(!IRE_IS_LOCAL(ire));
24399 		if (ire->ire_type & IRE_BROADCAST) {
24400 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24401 		} else {
24402 			UPDATE_MIB(ill->ill_ip_mib,
24403 			    ipIfStatsHCOutForwDatagrams, pkts);
24404 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24405 		}
24406 	}
24407 	ire->ire_last_used_time = lbolt;
24408 	/* Send it down */
24409 	putnext(ire->ire_stq, md_mp);
24410 	return;
24411 
24412 pbuf_panic:
24413 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24414 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24415 	    pbuf_idx);
24416 	/* NOTREACHED */
24417 }
24418 
24419 /*
24420  * Outbound IP fragmentation routine.
24421  *
24422  * NOTE : This routine does not ire_refrele the ire that is passed in
24423  * as the argument.
24424  */
24425 static void
24426 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24427     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst, conn_t *connp)
24428 {
24429 	int		i1;
24430 	mblk_t		*ll_hdr_mp;
24431 	int 		ll_hdr_len;
24432 	int		hdr_len;
24433 	mblk_t		*hdr_mp;
24434 	ipha_t		*ipha;
24435 	int		ip_data_end;
24436 	int		len;
24437 	mblk_t		*mp = mp_orig, *mp1;
24438 	int		offset;
24439 	queue_t		*q;
24440 	uint32_t	v_hlen_tos_len;
24441 	mblk_t		*first_mp;
24442 	boolean_t	mctl_present;
24443 	ill_t		*ill;
24444 	ill_t		*out_ill;
24445 	mblk_t		*xmit_mp;
24446 	mblk_t		*carve_mp;
24447 	ire_t		*ire1 = NULL;
24448 	ire_t		*save_ire = NULL;
24449 	mblk_t  	*next_mp = NULL;
24450 	boolean_t	last_frag = B_FALSE;
24451 	boolean_t	multirt_send = B_FALSE;
24452 	ire_t		*first_ire = NULL;
24453 	irb_t		*irb = NULL;
24454 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24455 
24456 	ill = ire_to_ill(ire);
24457 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24458 
24459 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24460 
24461 	if (max_frag == 0) {
24462 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24463 		    " -  dropping packet\n"));
24464 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24465 		freemsg(mp);
24466 		return;
24467 	}
24468 
24469 	/*
24470 	 * IPsec does not allow hw accelerated packets to be fragmented
24471 	 * This check is made in ip_wput_ipsec_out prior to coming here
24472 	 * via ip_wput_ire_fragmentit.
24473 	 *
24474 	 * If at this point we have an ire whose ARP request has not
24475 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24476 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24477 	 * This packet and all fragmentable packets for this ire will
24478 	 * continue to get dropped while ire_nce->nce_state remains in
24479 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24480 	 * ND_REACHABLE, all subsquent large packets for this ire will
24481 	 * get fragemented and sent out by this function.
24482 	 */
24483 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24484 		/* If nce_state is ND_INITIAL, trigger ARP query */
24485 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
24486 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24487 		    " -  dropping packet\n"));
24488 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24489 		freemsg(mp);
24490 		return;
24491 	}
24492 
24493 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24494 	    "ip_wput_frag_start:");
24495 
24496 	if (mp->b_datap->db_type == M_CTL) {
24497 		first_mp = mp;
24498 		mp_orig = mp = mp->b_cont;
24499 		mctl_present = B_TRUE;
24500 	} else {
24501 		first_mp = mp;
24502 		mctl_present = B_FALSE;
24503 	}
24504 
24505 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24506 	ipha = (ipha_t *)mp->b_rptr;
24507 
24508 	/*
24509 	 * If the Don't Fragment flag is on, generate an ICMP destination
24510 	 * unreachable, fragmentation needed.
24511 	 */
24512 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24513 	if (offset & IPH_DF) {
24514 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24515 		if (is_system_labeled()) {
24516 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24517 			    ire->ire_max_frag - max_frag, AF_INET);
24518 		}
24519 		/*
24520 		 * Need to compute hdr checksum if called from ip_wput_ire.
24521 		 * Note that ip_rput_forward verifies the checksum before
24522 		 * calling this routine so in that case this is a noop.
24523 		 */
24524 		ipha->ipha_hdr_checksum = 0;
24525 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24526 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24527 		    ipst);
24528 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24529 		    "ip_wput_frag_end:(%S)",
24530 		    "don't fragment");
24531 		return;
24532 	}
24533 	/*
24534 	 * Labeled systems adjust max_frag if they add a label
24535 	 * to send the correct path mtu.  We need the real mtu since we
24536 	 * are fragmenting the packet after label adjustment.
24537 	 */
24538 	if (is_system_labeled())
24539 		max_frag = ire->ire_max_frag;
24540 	if (mctl_present)
24541 		freeb(first_mp);
24542 	/*
24543 	 * Establish the starting offset.  May not be zero if we are fragging
24544 	 * a fragment that is being forwarded.
24545 	 */
24546 	offset = offset & IPH_OFFSET;
24547 
24548 	/* TODO why is this test needed? */
24549 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24550 	if (((max_frag - LENGTH) & ~7) < 8) {
24551 		/* TODO: notify ulp somehow */
24552 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24553 		freemsg(mp);
24554 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24555 		    "ip_wput_frag_end:(%S)",
24556 		    "len < 8");
24557 		return;
24558 	}
24559 
24560 	hdr_len = (V_HLEN & 0xF) << 2;
24561 
24562 	ipha->ipha_hdr_checksum = 0;
24563 
24564 	/*
24565 	 * Establish the number of bytes maximum per frag, after putting
24566 	 * in the header.
24567 	 */
24568 	len = (max_frag - hdr_len) & ~7;
24569 
24570 	/* Check if we can use MDT to send out the frags. */
24571 	ASSERT(!IRE_IS_LOCAL(ire));
24572 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24573 	    ipst->ips_ip_multidata_outbound &&
24574 	    !(ire->ire_flags & RTF_MULTIRT) &&
24575 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24576 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24577 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24578 		ASSERT(ill->ill_mdt_capab != NULL);
24579 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24580 			/*
24581 			 * If MDT has been previously turned off in the past,
24582 			 * and we currently can do MDT (due to IPQoS policy
24583 			 * removal, etc.) then enable it for this interface.
24584 			 */
24585 			ill->ill_mdt_capab->ill_mdt_on = 1;
24586 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24587 			    ill->ill_name));
24588 		}
24589 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24590 		    offset);
24591 		return;
24592 	}
24593 
24594 	/* Get a copy of the header for the trailing frags */
24595 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24596 	if (!hdr_mp) {
24597 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24598 		freemsg(mp);
24599 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24600 		    "ip_wput_frag_end:(%S)",
24601 		    "couldn't copy hdr");
24602 		return;
24603 	}
24604 	if (DB_CRED(mp) != NULL)
24605 		mblk_setcred(hdr_mp, DB_CRED(mp));
24606 
24607 	/* Store the starting offset, with the MoreFrags flag. */
24608 	i1 = offset | IPH_MF | frag_flag;
24609 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24610 
24611 	/* Establish the ending byte offset, based on the starting offset. */
24612 	offset <<= 3;
24613 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24614 
24615 	/* Store the length of the first fragment in the IP header. */
24616 	i1 = len + hdr_len;
24617 	ASSERT(i1 <= IP_MAXPACKET);
24618 	ipha->ipha_length = htons((uint16_t)i1);
24619 
24620 	/*
24621 	 * Compute the IP header checksum for the first frag.  We have to
24622 	 * watch out that we stop at the end of the header.
24623 	 */
24624 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24625 
24626 	/*
24627 	 * Now carve off the first frag.  Note that this will include the
24628 	 * original IP header.
24629 	 */
24630 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24631 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24632 		freeb(hdr_mp);
24633 		freemsg(mp_orig);
24634 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24635 		    "ip_wput_frag_end:(%S)",
24636 		    "couldn't carve first");
24637 		return;
24638 	}
24639 
24640 	/*
24641 	 * Multirouting case. Each fragment is replicated
24642 	 * via all non-condemned RTF_MULTIRT routes
24643 	 * currently resolved.
24644 	 * We ensure that first_ire is the first RTF_MULTIRT
24645 	 * ire in the bucket.
24646 	 */
24647 	if (ire->ire_flags & RTF_MULTIRT) {
24648 		irb = ire->ire_bucket;
24649 		ASSERT(irb != NULL);
24650 
24651 		multirt_send = B_TRUE;
24652 
24653 		/* Make sure we do not omit any multiroute ire. */
24654 		IRB_REFHOLD(irb);
24655 		for (first_ire = irb->irb_ire;
24656 		    first_ire != NULL;
24657 		    first_ire = first_ire->ire_next) {
24658 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24659 			    (first_ire->ire_addr == ire->ire_addr) &&
24660 			    !(first_ire->ire_marks &
24661 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24662 				break;
24663 			}
24664 		}
24665 
24666 		if (first_ire != NULL) {
24667 			if (first_ire != ire) {
24668 				IRE_REFHOLD(first_ire);
24669 				/*
24670 				 * Do not release the ire passed in
24671 				 * as the argument.
24672 				 */
24673 				ire = first_ire;
24674 			} else {
24675 				first_ire = NULL;
24676 			}
24677 		}
24678 		IRB_REFRELE(irb);
24679 
24680 		/*
24681 		 * Save the first ire; we will need to restore it
24682 		 * for the trailing frags.
24683 		 * We REFHOLD save_ire, as each iterated ire will be
24684 		 * REFRELEd.
24685 		 */
24686 		save_ire = ire;
24687 		IRE_REFHOLD(save_ire);
24688 	}
24689 
24690 	/*
24691 	 * First fragment emission loop.
24692 	 * In most cases, the emission loop below is entered only
24693 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24694 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24695 	 * bucket, and send the fragment through all crossed
24696 	 * RTF_MULTIRT routes.
24697 	 */
24698 	do {
24699 		if (ire->ire_flags & RTF_MULTIRT) {
24700 			/*
24701 			 * We are in a multiple send case, need to get
24702 			 * the next ire and make a copy of the packet.
24703 			 * ire1 holds here the next ire to process in the
24704 			 * bucket. If multirouting is expected,
24705 			 * any non-RTF_MULTIRT ire that has the
24706 			 * right destination address is ignored.
24707 			 *
24708 			 * We have to take into account the MTU of
24709 			 * each walked ire. max_frag is set by the
24710 			 * the caller and generally refers to
24711 			 * the primary ire entry. Here we ensure that
24712 			 * no route with a lower MTU will be used, as
24713 			 * fragments are carved once for all ires,
24714 			 * then replicated.
24715 			 */
24716 			ASSERT(irb != NULL);
24717 			IRB_REFHOLD(irb);
24718 			for (ire1 = ire->ire_next;
24719 			    ire1 != NULL;
24720 			    ire1 = ire1->ire_next) {
24721 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24722 					continue;
24723 				if (ire1->ire_addr != ire->ire_addr)
24724 					continue;
24725 				if (ire1->ire_marks &
24726 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24727 					continue;
24728 				/*
24729 				 * Ensure we do not exceed the MTU
24730 				 * of the next route.
24731 				 */
24732 				if (ire1->ire_max_frag < max_frag) {
24733 					ip_multirt_bad_mtu(ire1, max_frag);
24734 					continue;
24735 				}
24736 
24737 				/* Got one. */
24738 				IRE_REFHOLD(ire1);
24739 				break;
24740 			}
24741 			IRB_REFRELE(irb);
24742 
24743 			if (ire1 != NULL) {
24744 				next_mp = copyb(mp);
24745 				if ((next_mp == NULL) ||
24746 				    ((mp->b_cont != NULL) &&
24747 				    ((next_mp->b_cont =
24748 				    dupmsg(mp->b_cont)) == NULL))) {
24749 					freemsg(next_mp);
24750 					next_mp = NULL;
24751 					ire_refrele(ire1);
24752 					ire1 = NULL;
24753 				}
24754 			}
24755 
24756 			/* Last multiroute ire; don't loop anymore. */
24757 			if (ire1 == NULL) {
24758 				multirt_send = B_FALSE;
24759 			}
24760 		}
24761 
24762 		ll_hdr_len = 0;
24763 		LOCK_IRE_FP_MP(ire);
24764 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24765 		if (ll_hdr_mp != NULL) {
24766 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24767 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24768 		} else {
24769 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24770 		}
24771 
24772 		/* If there is a transmit header, get a copy for this frag. */
24773 		/*
24774 		 * TODO: should check db_ref before calling ip_carve_mp since
24775 		 * it might give us a dup.
24776 		 */
24777 		if (!ll_hdr_mp) {
24778 			/* No xmit header. */
24779 			xmit_mp = mp;
24780 
24781 		/* We have a link-layer header that can fit in our mblk. */
24782 		} else if (mp->b_datap->db_ref == 1 &&
24783 		    ll_hdr_len != 0 &&
24784 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24785 			/* M_DATA fastpath */
24786 			mp->b_rptr -= ll_hdr_len;
24787 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24788 			xmit_mp = mp;
24789 
24790 		/* Corner case if copyb has failed */
24791 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24792 			UNLOCK_IRE_FP_MP(ire);
24793 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24794 			freeb(hdr_mp);
24795 			freemsg(mp);
24796 			freemsg(mp_orig);
24797 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24798 			    "ip_wput_frag_end:(%S)",
24799 			    "discard");
24800 
24801 			if (multirt_send) {
24802 				ASSERT(ire1);
24803 				ASSERT(next_mp);
24804 
24805 				freemsg(next_mp);
24806 				ire_refrele(ire1);
24807 			}
24808 			if (save_ire != NULL)
24809 				IRE_REFRELE(save_ire);
24810 
24811 			if (first_ire != NULL)
24812 				ire_refrele(first_ire);
24813 			return;
24814 
24815 		/*
24816 		 * Case of res_mp OR the fastpath mp can't fit
24817 		 * in the mblk
24818 		 */
24819 		} else {
24820 			xmit_mp->b_cont = mp;
24821 			if (DB_CRED(mp) != NULL)
24822 				mblk_setcred(xmit_mp, DB_CRED(mp));
24823 			/*
24824 			 * Get priority marking, if any.
24825 			 * We propagate the CoS marking from the
24826 			 * original packet that went to QoS processing
24827 			 * in ip_wput_ire to the newly carved mp.
24828 			 */
24829 			if (DB_TYPE(xmit_mp) == M_DATA)
24830 				xmit_mp->b_band = mp->b_band;
24831 		}
24832 		UNLOCK_IRE_FP_MP(ire);
24833 
24834 		q = ire->ire_stq;
24835 		out_ill = (ill_t *)q->q_ptr;
24836 
24837 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24838 
24839 		DTRACE_PROBE4(ip4__physical__out__start,
24840 		    ill_t *, NULL, ill_t *, out_ill,
24841 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24842 
24843 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24844 		    ipst->ips_ipv4firewall_physical_out,
24845 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24846 
24847 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24848 
24849 		if (xmit_mp != NULL) {
24850 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24851 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24852 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24853 
24854 			ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
24855 
24856 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24857 			UPDATE_MIB(out_ill->ill_ip_mib,
24858 			    ipIfStatsHCOutOctets, i1);
24859 
24860 			if (pkt_type != OB_PKT) {
24861 				/*
24862 				 * Update the packet count and MIB stats
24863 				 * of trailing RTF_MULTIRT ires.
24864 				 */
24865 				UPDATE_OB_PKT_COUNT(ire);
24866 				BUMP_MIB(out_ill->ill_ip_mib,
24867 				    ipIfStatsOutFragReqds);
24868 			}
24869 		}
24870 
24871 		if (multirt_send) {
24872 			/*
24873 			 * We are in a multiple send case; look for
24874 			 * the next ire and re-enter the loop.
24875 			 */
24876 			ASSERT(ire1);
24877 			ASSERT(next_mp);
24878 			/* REFRELE the current ire before looping */
24879 			ire_refrele(ire);
24880 			ire = ire1;
24881 			ire1 = NULL;
24882 			mp = next_mp;
24883 			next_mp = NULL;
24884 		}
24885 	} while (multirt_send);
24886 
24887 	ASSERT(ire1 == NULL);
24888 
24889 	/* Restore the original ire; we need it for the trailing frags */
24890 	if (save_ire != NULL) {
24891 		/* REFRELE the last iterated ire */
24892 		ire_refrele(ire);
24893 		/* save_ire has been REFHOLDed */
24894 		ire = save_ire;
24895 		save_ire = NULL;
24896 		q = ire->ire_stq;
24897 	}
24898 
24899 	if (pkt_type == OB_PKT) {
24900 		UPDATE_OB_PKT_COUNT(ire);
24901 	} else {
24902 		out_ill = (ill_t *)q->q_ptr;
24903 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24904 		UPDATE_IB_PKT_COUNT(ire);
24905 	}
24906 
24907 	/* Advance the offset to the second frag starting point. */
24908 	offset += len;
24909 	/*
24910 	 * Update hdr_len from the copied header - there might be less options
24911 	 * in the later fragments.
24912 	 */
24913 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24914 	/* Loop until done. */
24915 	for (;;) {
24916 		uint16_t	offset_and_flags;
24917 		uint16_t	ip_len;
24918 
24919 		if (ip_data_end - offset > len) {
24920 			/*
24921 			 * Carve off the appropriate amount from the original
24922 			 * datagram.
24923 			 */
24924 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24925 				mp = NULL;
24926 				break;
24927 			}
24928 			/*
24929 			 * More frags after this one.  Get another copy
24930 			 * of the header.
24931 			 */
24932 			if (carve_mp->b_datap->db_ref == 1 &&
24933 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24934 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24935 				/* Inline IP header */
24936 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24937 				    hdr_mp->b_rptr;
24938 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24939 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24940 				mp = carve_mp;
24941 			} else {
24942 				if (!(mp = copyb(hdr_mp))) {
24943 					freemsg(carve_mp);
24944 					break;
24945 				}
24946 				/* Get priority marking, if any. */
24947 				mp->b_band = carve_mp->b_band;
24948 				mp->b_cont = carve_mp;
24949 			}
24950 			ipha = (ipha_t *)mp->b_rptr;
24951 			offset_and_flags = IPH_MF;
24952 		} else {
24953 			/*
24954 			 * Last frag.  Consume the header. Set len to
24955 			 * the length of this last piece.
24956 			 */
24957 			len = ip_data_end - offset;
24958 
24959 			/*
24960 			 * Carve off the appropriate amount from the original
24961 			 * datagram.
24962 			 */
24963 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24964 				mp = NULL;
24965 				break;
24966 			}
24967 			if (carve_mp->b_datap->db_ref == 1 &&
24968 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24969 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24970 				/* Inline IP header */
24971 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24972 				    hdr_mp->b_rptr;
24973 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24974 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24975 				mp = carve_mp;
24976 				freeb(hdr_mp);
24977 				hdr_mp = mp;
24978 			} else {
24979 				mp = hdr_mp;
24980 				/* Get priority marking, if any. */
24981 				mp->b_band = carve_mp->b_band;
24982 				mp->b_cont = carve_mp;
24983 			}
24984 			ipha = (ipha_t *)mp->b_rptr;
24985 			/* A frag of a frag might have IPH_MF non-zero */
24986 			offset_and_flags =
24987 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24988 			    IPH_MF;
24989 		}
24990 		offset_and_flags |= (uint16_t)(offset >> 3);
24991 		offset_and_flags |= (uint16_t)frag_flag;
24992 		/* Store the offset and flags in the IP header. */
24993 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24994 
24995 		/* Store the length in the IP header. */
24996 		ip_len = (uint16_t)(len + hdr_len);
24997 		ipha->ipha_length = htons(ip_len);
24998 
24999 		/*
25000 		 * Set the IP header checksum.	Note that mp is just
25001 		 * the header, so this is easy to pass to ip_csum.
25002 		 */
25003 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
25004 
25005 		/* Attach a transmit header, if any, and ship it. */
25006 		if (pkt_type == OB_PKT) {
25007 			UPDATE_OB_PKT_COUNT(ire);
25008 		} else {
25009 			out_ill = (ill_t *)q->q_ptr;
25010 			BUMP_MIB(out_ill->ill_ip_mib,
25011 			    ipIfStatsHCOutForwDatagrams);
25012 			UPDATE_IB_PKT_COUNT(ire);
25013 		}
25014 
25015 		if (ire->ire_flags & RTF_MULTIRT) {
25016 			irb = ire->ire_bucket;
25017 			ASSERT(irb != NULL);
25018 
25019 			multirt_send = B_TRUE;
25020 
25021 			/*
25022 			 * Save the original ire; we will need to restore it
25023 			 * for the tailing frags.
25024 			 */
25025 			save_ire = ire;
25026 			IRE_REFHOLD(save_ire);
25027 		}
25028 		/*
25029 		 * Emission loop for this fragment, similar
25030 		 * to what is done for the first fragment.
25031 		 */
25032 		do {
25033 			if (multirt_send) {
25034 				/*
25035 				 * We are in a multiple send case, need to get
25036 				 * the next ire and make a copy of the packet.
25037 				 */
25038 				ASSERT(irb != NULL);
25039 				IRB_REFHOLD(irb);
25040 				for (ire1 = ire->ire_next;
25041 				    ire1 != NULL;
25042 				    ire1 = ire1->ire_next) {
25043 					if (!(ire1->ire_flags & RTF_MULTIRT))
25044 						continue;
25045 					if (ire1->ire_addr != ire->ire_addr)
25046 						continue;
25047 					if (ire1->ire_marks &
25048 					    (IRE_MARK_CONDEMNED|
25049 					    IRE_MARK_HIDDEN)) {
25050 						continue;
25051 					}
25052 					/*
25053 					 * Ensure we do not exceed the MTU
25054 					 * of the next route.
25055 					 */
25056 					if (ire1->ire_max_frag < max_frag) {
25057 						ip_multirt_bad_mtu(ire1,
25058 						    max_frag);
25059 						continue;
25060 					}
25061 
25062 					/* Got one. */
25063 					IRE_REFHOLD(ire1);
25064 					break;
25065 				}
25066 				IRB_REFRELE(irb);
25067 
25068 				if (ire1 != NULL) {
25069 					next_mp = copyb(mp);
25070 					if ((next_mp == NULL) ||
25071 					    ((mp->b_cont != NULL) &&
25072 					    ((next_mp->b_cont =
25073 					    dupmsg(mp->b_cont)) == NULL))) {
25074 						freemsg(next_mp);
25075 						next_mp = NULL;
25076 						ire_refrele(ire1);
25077 						ire1 = NULL;
25078 					}
25079 				}
25080 
25081 				/* Last multiroute ire; don't loop anymore. */
25082 				if (ire1 == NULL) {
25083 					multirt_send = B_FALSE;
25084 				}
25085 			}
25086 
25087 			/* Update transmit header */
25088 			ll_hdr_len = 0;
25089 			LOCK_IRE_FP_MP(ire);
25090 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
25091 			if (ll_hdr_mp != NULL) {
25092 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
25093 				ll_hdr_len = MBLKL(ll_hdr_mp);
25094 			} else {
25095 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
25096 			}
25097 
25098 			if (!ll_hdr_mp) {
25099 				xmit_mp = mp;
25100 
25101 			/*
25102 			 * We have link-layer header that can fit in
25103 			 * our mblk.
25104 			 */
25105 			} else if (mp->b_datap->db_ref == 1 &&
25106 			    ll_hdr_len != 0 &&
25107 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
25108 				/* M_DATA fastpath */
25109 				mp->b_rptr -= ll_hdr_len;
25110 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
25111 				    ll_hdr_len);
25112 				xmit_mp = mp;
25113 
25114 			/*
25115 			 * Case of res_mp OR the fastpath mp can't fit
25116 			 * in the mblk
25117 			 */
25118 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
25119 				xmit_mp->b_cont = mp;
25120 				if (DB_CRED(mp) != NULL)
25121 					mblk_setcred(xmit_mp, DB_CRED(mp));
25122 				/* Get priority marking, if any. */
25123 				if (DB_TYPE(xmit_mp) == M_DATA)
25124 					xmit_mp->b_band = mp->b_band;
25125 
25126 			/* Corner case if copyb failed */
25127 			} else {
25128 				/*
25129 				 * Exit both the replication and
25130 				 * fragmentation loops.
25131 				 */
25132 				UNLOCK_IRE_FP_MP(ire);
25133 				goto drop_pkt;
25134 			}
25135 			UNLOCK_IRE_FP_MP(ire);
25136 
25137 			mp1 = mp;
25138 			out_ill = (ill_t *)q->q_ptr;
25139 
25140 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25141 
25142 			DTRACE_PROBE4(ip4__physical__out__start,
25143 			    ill_t *, NULL, ill_t *, out_ill,
25144 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25145 
25146 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25147 			    ipst->ips_ipv4firewall_physical_out,
25148 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
25149 
25150 			DTRACE_PROBE1(ip4__physical__out__end,
25151 			    mblk_t *, xmit_mp);
25152 
25153 			if (mp != mp1 && hdr_mp == mp1)
25154 				hdr_mp = mp;
25155 			if (mp != mp1 && mp_orig == mp1)
25156 				mp_orig = mp;
25157 
25158 			if (xmit_mp != NULL) {
25159 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
25160 				    NULL, void_ip_t *, ipha,
25161 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
25162 				    ipha, ip6_t *, NULL, int, 0);
25163 
25164 				ILL_SEND_TX(out_ill, ire, connp, xmit_mp, 0);
25165 
25166 				BUMP_MIB(out_ill->ill_ip_mib,
25167 				    ipIfStatsHCOutTransmits);
25168 				UPDATE_MIB(out_ill->ill_ip_mib,
25169 				    ipIfStatsHCOutOctets, ip_len);
25170 
25171 				if (pkt_type != OB_PKT) {
25172 					/*
25173 					 * Update the packet count of trailing
25174 					 * RTF_MULTIRT ires.
25175 					 */
25176 					UPDATE_OB_PKT_COUNT(ire);
25177 				}
25178 			}
25179 
25180 			/* All done if we just consumed the hdr_mp. */
25181 			if (mp == hdr_mp) {
25182 				last_frag = B_TRUE;
25183 				BUMP_MIB(out_ill->ill_ip_mib,
25184 				    ipIfStatsOutFragOKs);
25185 			}
25186 
25187 			if (multirt_send) {
25188 				/*
25189 				 * We are in a multiple send case; look for
25190 				 * the next ire and re-enter the loop.
25191 				 */
25192 				ASSERT(ire1);
25193 				ASSERT(next_mp);
25194 				/* REFRELE the current ire before looping */
25195 				ire_refrele(ire);
25196 				ire = ire1;
25197 				ire1 = NULL;
25198 				q = ire->ire_stq;
25199 				mp = next_mp;
25200 				next_mp = NULL;
25201 			}
25202 		} while (multirt_send);
25203 		/*
25204 		 * Restore the original ire; we need it for the
25205 		 * trailing frags
25206 		 */
25207 		if (save_ire != NULL) {
25208 			ASSERT(ire1 == NULL);
25209 			/* REFRELE the last iterated ire */
25210 			ire_refrele(ire);
25211 			/* save_ire has been REFHOLDed */
25212 			ire = save_ire;
25213 			q = ire->ire_stq;
25214 			save_ire = NULL;
25215 		}
25216 
25217 		if (last_frag) {
25218 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25219 			    "ip_wput_frag_end:(%S)",
25220 			    "consumed hdr_mp");
25221 
25222 			if (first_ire != NULL)
25223 				ire_refrele(first_ire);
25224 			return;
25225 		}
25226 		/* Otherwise, advance and loop. */
25227 		offset += len;
25228 	}
25229 
25230 drop_pkt:
25231 	/* Clean up following allocation failure. */
25232 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25233 	freemsg(mp);
25234 	if (mp != hdr_mp)
25235 		freeb(hdr_mp);
25236 	if (mp != mp_orig)
25237 		freemsg(mp_orig);
25238 
25239 	if (save_ire != NULL)
25240 		IRE_REFRELE(save_ire);
25241 	if (first_ire != NULL)
25242 		ire_refrele(first_ire);
25243 
25244 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25245 	    "ip_wput_frag_end:(%S)",
25246 	    "end--alloc failure");
25247 }
25248 
25249 /*
25250  * Copy the header plus those options which have the copy bit set
25251  */
25252 static mblk_t *
25253 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25254 {
25255 	mblk_t	*mp;
25256 	uchar_t	*up;
25257 
25258 	/*
25259 	 * Quick check if we need to look for options without the copy bit
25260 	 * set
25261 	 */
25262 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25263 	if (!mp)
25264 		return (mp);
25265 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25266 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25267 		bcopy(rptr, mp->b_rptr, hdr_len);
25268 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25269 		return (mp);
25270 	}
25271 	up  = mp->b_rptr;
25272 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25273 	up += IP_SIMPLE_HDR_LENGTH;
25274 	rptr += IP_SIMPLE_HDR_LENGTH;
25275 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25276 	while (hdr_len > 0) {
25277 		uint32_t optval;
25278 		uint32_t optlen;
25279 
25280 		optval = *rptr;
25281 		if (optval == IPOPT_EOL)
25282 			break;
25283 		if (optval == IPOPT_NOP)
25284 			optlen = 1;
25285 		else
25286 			optlen = rptr[1];
25287 		if (optval & IPOPT_COPY) {
25288 			bcopy(rptr, up, optlen);
25289 			up += optlen;
25290 		}
25291 		rptr += optlen;
25292 		hdr_len -= optlen;
25293 	}
25294 	/*
25295 	 * Make sure that we drop an even number of words by filling
25296 	 * with EOL to the next word boundary.
25297 	 */
25298 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25299 	    hdr_len & 0x3; hdr_len++)
25300 		*up++ = IPOPT_EOL;
25301 	mp->b_wptr = up;
25302 	/* Update header length */
25303 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25304 	return (mp);
25305 }
25306 
25307 /*
25308  * Delivery to local recipients including fanout to multiple recipients.
25309  * Does not do checksumming of UDP/TCP.
25310  * Note: q should be the read side queue for either the ill or conn.
25311  * Note: rq should be the read side q for the lower (ill) stream.
25312  * We don't send packets to IPPF processing, thus the last argument
25313  * to all the fanout calls are B_FALSE.
25314  */
25315 void
25316 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25317     int fanout_flags, zoneid_t zoneid)
25318 {
25319 	uint32_t	protocol;
25320 	mblk_t		*first_mp;
25321 	boolean_t	mctl_present;
25322 	int		ire_type;
25323 #define	rptr	((uchar_t *)ipha)
25324 	ip_stack_t	*ipst = ill->ill_ipst;
25325 
25326 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25327 	    "ip_wput_local_start: q %p", q);
25328 
25329 	if (ire != NULL) {
25330 		ire_type = ire->ire_type;
25331 	} else {
25332 		/*
25333 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25334 		 * packet is not multicast, we can't tell the ire type.
25335 		 */
25336 		ASSERT(CLASSD(ipha->ipha_dst));
25337 		ire_type = IRE_BROADCAST;
25338 	}
25339 
25340 	first_mp = mp;
25341 	if (first_mp->b_datap->db_type == M_CTL) {
25342 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25343 		if (!io->ipsec_out_secure) {
25344 			/*
25345 			 * This ipsec_out_t was allocated in ip_wput
25346 			 * for multicast packets to store the ill_index.
25347 			 * As this is being delivered locally, we don't
25348 			 * need this anymore.
25349 			 */
25350 			mp = first_mp->b_cont;
25351 			freeb(first_mp);
25352 			first_mp = mp;
25353 			mctl_present = B_FALSE;
25354 		} else {
25355 			/*
25356 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25357 			 * security properties for the looped-back packet.
25358 			 */
25359 			mctl_present = B_TRUE;
25360 			mp = first_mp->b_cont;
25361 			ASSERT(mp != NULL);
25362 			ipsec_out_to_in(first_mp);
25363 		}
25364 	} else {
25365 		mctl_present = B_FALSE;
25366 	}
25367 
25368 	DTRACE_PROBE4(ip4__loopback__in__start,
25369 	    ill_t *, ill, ill_t *, NULL,
25370 	    ipha_t *, ipha, mblk_t *, first_mp);
25371 
25372 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25373 	    ipst->ips_ipv4firewall_loopback_in,
25374 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25375 
25376 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25377 
25378 	if (first_mp == NULL)
25379 		return;
25380 
25381 	if (ipst->ips_ipobs_enabled) {
25382 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25383 		zoneid_t stackzoneid = netstackid_to_zoneid(
25384 		    ipst->ips_netstack->netstack_stackid);
25385 
25386 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25387 		/*
25388 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25389 		 * address.  Restrict the lookup below to the destination zone.
25390 		 */
25391 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25392 			lookup_zoneid = zoneid;
25393 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25394 		    lookup_zoneid);
25395 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25396 		    IPV4_VERSION, 0, ipst);
25397 	}
25398 
25399 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25400 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25401 	    int, 1);
25402 
25403 	ipst->ips_loopback_packets++;
25404 
25405 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25406 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25407 	if (!IS_SIMPLE_IPH(ipha)) {
25408 		ip_wput_local_options(ipha, ipst);
25409 	}
25410 
25411 	protocol = ipha->ipha_protocol;
25412 	switch (protocol) {
25413 	case IPPROTO_ICMP: {
25414 		ire_t		*ire_zone;
25415 		ilm_t		*ilm;
25416 		mblk_t		*mp1;
25417 		zoneid_t	last_zoneid;
25418 
25419 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25420 			ASSERT(ire_type == IRE_BROADCAST);
25421 			/*
25422 			 * In the multicast case, applications may have joined
25423 			 * the group from different zones, so we need to deliver
25424 			 * the packet to each of them. Loop through the
25425 			 * multicast memberships structures (ilm) on the receive
25426 			 * ill and send a copy of the packet up each matching
25427 			 * one. However, we don't do this for multicasts sent on
25428 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25429 			 * they must stay in the sender's zone.
25430 			 *
25431 			 * ilm_add_v6() ensures that ilms in the same zone are
25432 			 * contiguous in the ill_ilm list. We use this property
25433 			 * to avoid sending duplicates needed when two
25434 			 * applications in the same zone join the same group on
25435 			 * different logical interfaces: we ignore the ilm if
25436 			 * it's zoneid is the same as the last matching one.
25437 			 * In addition, the sending of the packet for
25438 			 * ire_zoneid is delayed until all of the other ilms
25439 			 * have been exhausted.
25440 			 */
25441 			last_zoneid = -1;
25442 			ILM_WALKER_HOLD(ill);
25443 			for (ilm = ill->ill_ilm; ilm != NULL;
25444 			    ilm = ilm->ilm_next) {
25445 				if ((ilm->ilm_flags & ILM_DELETED) ||
25446 				    ipha->ipha_dst != ilm->ilm_addr ||
25447 				    ilm->ilm_zoneid == last_zoneid ||
25448 				    ilm->ilm_zoneid == zoneid ||
25449 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25450 					continue;
25451 				mp1 = ip_copymsg(first_mp);
25452 				if (mp1 == NULL)
25453 					continue;
25454 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25455 				    mctl_present, B_FALSE, ill,
25456 				    ilm->ilm_zoneid);
25457 				last_zoneid = ilm->ilm_zoneid;
25458 			}
25459 			ILM_WALKER_RELE(ill);
25460 			/*
25461 			 * Loopback case: the sending endpoint has
25462 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25463 			 * dispatch the multicast packet to the sending zone.
25464 			 */
25465 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25466 				freemsg(first_mp);
25467 				return;
25468 			}
25469 		} else if (ire_type == IRE_BROADCAST) {
25470 			/*
25471 			 * In the broadcast case, there may be many zones
25472 			 * which need a copy of the packet delivered to them.
25473 			 * There is one IRE_BROADCAST per broadcast address
25474 			 * and per zone; we walk those using a helper function.
25475 			 * In addition, the sending of the packet for zoneid is
25476 			 * delayed until all of the other ires have been
25477 			 * processed.
25478 			 */
25479 			IRB_REFHOLD(ire->ire_bucket);
25480 			ire_zone = NULL;
25481 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25482 			    ire)) != NULL) {
25483 				mp1 = ip_copymsg(first_mp);
25484 				if (mp1 == NULL)
25485 					continue;
25486 
25487 				UPDATE_IB_PKT_COUNT(ire_zone);
25488 				ire_zone->ire_last_used_time = lbolt;
25489 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25490 				    mctl_present, B_FALSE, ill,
25491 				    ire_zone->ire_zoneid);
25492 			}
25493 			IRB_REFRELE(ire->ire_bucket);
25494 		}
25495 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25496 		    0, mctl_present, B_FALSE, ill, zoneid);
25497 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25498 		    "ip_wput_local_end: q %p (%S)",
25499 		    q, "icmp");
25500 		return;
25501 	}
25502 	case IPPROTO_IGMP:
25503 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25504 			/* Bad packet - discarded by igmp_input */
25505 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25506 			    "ip_wput_local_end: q %p (%S)",
25507 			    q, "igmp_input--bad packet");
25508 			if (mctl_present)
25509 				freeb(first_mp);
25510 			return;
25511 		}
25512 		/*
25513 		 * igmp_input() may have returned the pulled up message.
25514 		 * So first_mp and ipha need to be reinitialized.
25515 		 */
25516 		ipha = (ipha_t *)mp->b_rptr;
25517 		if (mctl_present)
25518 			first_mp->b_cont = mp;
25519 		else
25520 			first_mp = mp;
25521 		/* deliver to local raw users */
25522 		break;
25523 	case IPPROTO_ENCAP:
25524 		/*
25525 		 * This case is covered by either ip_fanout_proto, or by
25526 		 * the above security processing for self-tunneled packets.
25527 		 */
25528 		break;
25529 	case IPPROTO_UDP: {
25530 		uint16_t	*up;
25531 		uint32_t	ports;
25532 
25533 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25534 		    UDP_PORTS_OFFSET);
25535 		/* Force a 'valid' checksum. */
25536 		up[3] = 0;
25537 
25538 		ports = *(uint32_t *)up;
25539 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25540 		    (ire_type == IRE_BROADCAST),
25541 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25542 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25543 		    ill, zoneid);
25544 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25545 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25546 		return;
25547 	}
25548 	case IPPROTO_TCP: {
25549 
25550 		/*
25551 		 * For TCP, discard broadcast packets.
25552 		 */
25553 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25554 			freemsg(first_mp);
25555 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25556 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25557 			return;
25558 		}
25559 
25560 		if (mp->b_datap->db_type == M_DATA) {
25561 			/*
25562 			 * M_DATA mblk, so init mblk (chain) for no struio().
25563 			 */
25564 			mblk_t	*mp1 = mp;
25565 
25566 			do {
25567 				mp1->b_datap->db_struioflag = 0;
25568 			} while ((mp1 = mp1->b_cont) != NULL);
25569 		}
25570 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25571 		    <= mp->b_wptr);
25572 		ip_fanout_tcp(q, first_mp, ill, ipha,
25573 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25574 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25575 		    mctl_present, B_FALSE, zoneid);
25576 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25577 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25578 		return;
25579 	}
25580 	case IPPROTO_SCTP:
25581 	{
25582 		uint32_t	ports;
25583 
25584 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25585 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25586 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25587 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25588 		return;
25589 	}
25590 
25591 	default:
25592 		break;
25593 	}
25594 	/*
25595 	 * Find a client for some other protocol.  We give
25596 	 * copies to multiple clients, if more than one is
25597 	 * bound.
25598 	 */
25599 	ip_fanout_proto(q, first_mp, ill, ipha,
25600 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25601 	    mctl_present, B_FALSE, ill, zoneid);
25602 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25603 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25604 #undef	rptr
25605 }
25606 
25607 /*
25608  * Update any source route, record route, or timestamp options.
25609  * Check that we are at end of strict source route.
25610  * The options have been sanity checked by ip_wput_options().
25611  */
25612 static void
25613 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25614 {
25615 	ipoptp_t	opts;
25616 	uchar_t		*opt;
25617 	uint8_t		optval;
25618 	uint8_t		optlen;
25619 	ipaddr_t	dst;
25620 	uint32_t	ts;
25621 	ire_t		*ire;
25622 	timestruc_t	now;
25623 
25624 	ip2dbg(("ip_wput_local_options\n"));
25625 	for (optval = ipoptp_first(&opts, ipha);
25626 	    optval != IPOPT_EOL;
25627 	    optval = ipoptp_next(&opts)) {
25628 		opt = opts.ipoptp_cur;
25629 		optlen = opts.ipoptp_len;
25630 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25631 		switch (optval) {
25632 			uint32_t off;
25633 		case IPOPT_SSRR:
25634 		case IPOPT_LSRR:
25635 			off = opt[IPOPT_OFFSET];
25636 			off--;
25637 			if (optlen < IP_ADDR_LEN ||
25638 			    off > optlen - IP_ADDR_LEN) {
25639 				/* End of source route */
25640 				break;
25641 			}
25642 			/*
25643 			 * This will only happen if two consecutive entries
25644 			 * in the source route contains our address or if
25645 			 * it is a packet with a loose source route which
25646 			 * reaches us before consuming the whole source route
25647 			 */
25648 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25649 			if (optval == IPOPT_SSRR) {
25650 				return;
25651 			}
25652 			/*
25653 			 * Hack: instead of dropping the packet truncate the
25654 			 * source route to what has been used by filling the
25655 			 * rest with IPOPT_NOP.
25656 			 */
25657 			opt[IPOPT_OLEN] = (uint8_t)off;
25658 			while (off < optlen) {
25659 				opt[off++] = IPOPT_NOP;
25660 			}
25661 			break;
25662 		case IPOPT_RR:
25663 			off = opt[IPOPT_OFFSET];
25664 			off--;
25665 			if (optlen < IP_ADDR_LEN ||
25666 			    off > optlen - IP_ADDR_LEN) {
25667 				/* No more room - ignore */
25668 				ip1dbg((
25669 				    "ip_wput_forward_options: end of RR\n"));
25670 				break;
25671 			}
25672 			dst = htonl(INADDR_LOOPBACK);
25673 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25674 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25675 			break;
25676 		case IPOPT_TS:
25677 			/* Insert timestamp if there is romm */
25678 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25679 			case IPOPT_TS_TSONLY:
25680 				off = IPOPT_TS_TIMELEN;
25681 				break;
25682 			case IPOPT_TS_PRESPEC:
25683 			case IPOPT_TS_PRESPEC_RFC791:
25684 				/* Verify that the address matched */
25685 				off = opt[IPOPT_OFFSET] - 1;
25686 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25687 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25688 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25689 				    ipst);
25690 				if (ire == NULL) {
25691 					/* Not for us */
25692 					break;
25693 				}
25694 				ire_refrele(ire);
25695 				/* FALLTHRU */
25696 			case IPOPT_TS_TSANDADDR:
25697 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25698 				break;
25699 			default:
25700 				/*
25701 				 * ip_*put_options should have already
25702 				 * dropped this packet.
25703 				 */
25704 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25705 				    "unknown IT - bug in ip_wput_options?\n");
25706 				return;	/* Keep "lint" happy */
25707 			}
25708 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25709 				/* Increase overflow counter */
25710 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25711 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25712 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25713 				    (off << 4);
25714 				break;
25715 			}
25716 			off = opt[IPOPT_OFFSET] - 1;
25717 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25718 			case IPOPT_TS_PRESPEC:
25719 			case IPOPT_TS_PRESPEC_RFC791:
25720 			case IPOPT_TS_TSANDADDR:
25721 				dst = htonl(INADDR_LOOPBACK);
25722 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25723 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25724 				/* FALLTHRU */
25725 			case IPOPT_TS_TSONLY:
25726 				off = opt[IPOPT_OFFSET] - 1;
25727 				/* Compute # of milliseconds since midnight */
25728 				gethrestime(&now);
25729 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25730 				    now.tv_nsec / (NANOSEC / MILLISEC);
25731 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25732 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25733 				break;
25734 			}
25735 			break;
25736 		}
25737 	}
25738 }
25739 
25740 /*
25741  * Send out a multicast packet on interface ipif.
25742  * The sender does not have an conn.
25743  * Caller verifies that this isn't a PHYI_LOOPBACK.
25744  */
25745 void
25746 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25747 {
25748 	ipha_t	*ipha;
25749 	ire_t	*ire;
25750 	ipaddr_t	dst;
25751 	mblk_t		*first_mp;
25752 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25753 
25754 	/* igmp_sendpkt always allocates a ipsec_out_t */
25755 	ASSERT(mp->b_datap->db_type == M_CTL);
25756 	ASSERT(!ipif->ipif_isv6);
25757 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25758 
25759 	first_mp = mp;
25760 	mp = first_mp->b_cont;
25761 	ASSERT(mp->b_datap->db_type == M_DATA);
25762 	ipha = (ipha_t *)mp->b_rptr;
25763 
25764 	/*
25765 	 * Find an IRE which matches the destination and the outgoing
25766 	 * queue (i.e. the outgoing interface.)
25767 	 */
25768 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25769 		dst = ipif->ipif_pp_dst_addr;
25770 	else
25771 		dst = ipha->ipha_dst;
25772 	/*
25773 	 * The source address has already been initialized by the
25774 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25775 	 * be sufficient rather than MATCH_IRE_IPIF.
25776 	 *
25777 	 * This function is used for sending IGMP packets. We need
25778 	 * to make sure that we send the packet out of the interface
25779 	 * (ipif->ipif_ill) where we joined the group. This is to
25780 	 * prevent from switches doing IGMP snooping to send us multicast
25781 	 * packets for a given group on the interface we have joined.
25782 	 * If we can't find an ire, igmp_sendpkt has already initialized
25783 	 * ipsec_out_attach_if so that this will not be load spread in
25784 	 * ip_newroute_ipif.
25785 	 */
25786 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25787 	    MATCH_IRE_ILL, ipst);
25788 	if (!ire) {
25789 		/*
25790 		 * Mark this packet to make it be delivered to
25791 		 * ip_wput_ire after the new ire has been
25792 		 * created.
25793 		 */
25794 		mp->b_prev = NULL;
25795 		mp->b_next = NULL;
25796 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25797 		    zoneid, &zero_info);
25798 		return;
25799 	}
25800 
25801 	/*
25802 	 * Honor the RTF_SETSRC flag; this is the only case
25803 	 * where we force this addr whatever the current src addr is,
25804 	 * because this address is set by igmp_sendpkt(), and
25805 	 * cannot be specified by any user.
25806 	 */
25807 	if (ire->ire_flags & RTF_SETSRC) {
25808 		ipha->ipha_src = ire->ire_src_addr;
25809 	}
25810 
25811 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25812 }
25813 
25814 /*
25815  * NOTE : This function does not ire_refrele the ire argument passed in.
25816  *
25817  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25818  * failure. The nce_fp_mp can vanish any time in the case of
25819  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25820  * the ire_lock to access the nce_fp_mp in this case.
25821  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25822  * prepending a fastpath message IPQoS processing must precede it, we also set
25823  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25824  * (IPQoS might have set the b_band for CoS marking).
25825  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25826  * must follow it so that IPQoS can mark the dl_priority field for CoS
25827  * marking, if needed.
25828  */
25829 static mblk_t *
25830 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25831     uint32_t ill_index, ipha_t **iphap)
25832 {
25833 	uint_t	hlen;
25834 	ipha_t *ipha;
25835 	mblk_t *mp1;
25836 	boolean_t qos_done = B_FALSE;
25837 	uchar_t	*ll_hdr;
25838 	ip_stack_t	*ipst = ire->ire_ipst;
25839 
25840 #define	rptr	((uchar_t *)ipha)
25841 
25842 	ipha = (ipha_t *)mp->b_rptr;
25843 	hlen = 0;
25844 	LOCK_IRE_FP_MP(ire);
25845 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25846 		ASSERT(DB_TYPE(mp1) == M_DATA);
25847 		/* Initiate IPPF processing */
25848 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25849 			UNLOCK_IRE_FP_MP(ire);
25850 			ip_process(proc, &mp, ill_index);
25851 			if (mp == NULL)
25852 				return (NULL);
25853 
25854 			ipha = (ipha_t *)mp->b_rptr;
25855 			LOCK_IRE_FP_MP(ire);
25856 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25857 				qos_done = B_TRUE;
25858 				goto no_fp_mp;
25859 			}
25860 			ASSERT(DB_TYPE(mp1) == M_DATA);
25861 		}
25862 		hlen = MBLKL(mp1);
25863 		/*
25864 		 * Check if we have enough room to prepend fastpath
25865 		 * header
25866 		 */
25867 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25868 			ll_hdr = rptr - hlen;
25869 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25870 			/*
25871 			 * Set the b_rptr to the start of the link layer
25872 			 * header
25873 			 */
25874 			mp->b_rptr = ll_hdr;
25875 			mp1 = mp;
25876 		} else {
25877 			mp1 = copyb(mp1);
25878 			if (mp1 == NULL)
25879 				goto unlock_err;
25880 			mp1->b_band = mp->b_band;
25881 			mp1->b_cont = mp;
25882 			/*
25883 			 * certain system generated traffic may not
25884 			 * have cred/label in ip header block. This
25885 			 * is true even for a labeled system. But for
25886 			 * labeled traffic, inherit the label in the
25887 			 * new header.
25888 			 */
25889 			if (DB_CRED(mp) != NULL)
25890 				mblk_setcred(mp1, DB_CRED(mp));
25891 			/*
25892 			 * XXX disable ICK_VALID and compute checksum
25893 			 * here; can happen if nce_fp_mp changes and
25894 			 * it can't be copied now due to insufficient
25895 			 * space. (unlikely, fp mp can change, but it
25896 			 * does not increase in length)
25897 			 */
25898 		}
25899 		UNLOCK_IRE_FP_MP(ire);
25900 	} else {
25901 no_fp_mp:
25902 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25903 		if (mp1 == NULL) {
25904 unlock_err:
25905 			UNLOCK_IRE_FP_MP(ire);
25906 			freemsg(mp);
25907 			return (NULL);
25908 		}
25909 		UNLOCK_IRE_FP_MP(ire);
25910 		mp1->b_cont = mp;
25911 		/*
25912 		 * certain system generated traffic may not
25913 		 * have cred/label in ip header block. This
25914 		 * is true even for a labeled system. But for
25915 		 * labeled traffic, inherit the label in the
25916 		 * new header.
25917 		 */
25918 		if (DB_CRED(mp) != NULL)
25919 			mblk_setcred(mp1, DB_CRED(mp));
25920 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25921 			ip_process(proc, &mp1, ill_index);
25922 			if (mp1 == NULL)
25923 				return (NULL);
25924 
25925 			if (mp1->b_cont == NULL)
25926 				ipha = NULL;
25927 			else
25928 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25929 		}
25930 	}
25931 
25932 	*iphap = ipha;
25933 	return (mp1);
25934 #undef rptr
25935 }
25936 
25937 /*
25938  * Finish the outbound IPsec processing for an IPv6 packet. This function
25939  * is called from ipsec_out_process() if the IPsec packet was processed
25940  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25941  * asynchronously.
25942  */
25943 void
25944 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25945     ire_t *ire_arg)
25946 {
25947 	in6_addr_t *v6dstp;
25948 	ire_t *ire;
25949 	mblk_t *mp;
25950 	ip6_t *ip6h1;
25951 	uint_t	ill_index;
25952 	ipsec_out_t *io;
25953 	boolean_t attach_if, hwaccel;
25954 	uint32_t flags = IP6_NO_IPPOLICY;
25955 	int match_flags;
25956 	zoneid_t zoneid;
25957 	boolean_t ill_need_rele = B_FALSE;
25958 	boolean_t ire_need_rele = B_FALSE;
25959 	ip_stack_t	*ipst;
25960 
25961 	mp = ipsec_mp->b_cont;
25962 	ip6h1 = (ip6_t *)mp->b_rptr;
25963 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25964 	ASSERT(io->ipsec_out_ns != NULL);
25965 	ipst = io->ipsec_out_ns->netstack_ip;
25966 	ill_index = io->ipsec_out_ill_index;
25967 	if (io->ipsec_out_reachable) {
25968 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25969 	}
25970 	attach_if = io->ipsec_out_attach_if;
25971 	hwaccel = io->ipsec_out_accelerated;
25972 	zoneid = io->ipsec_out_zoneid;
25973 	ASSERT(zoneid != ALL_ZONES);
25974 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25975 	/* Multicast addresses should have non-zero ill_index. */
25976 	v6dstp = &ip6h->ip6_dst;
25977 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25978 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25979 	ASSERT(!attach_if || ill_index != 0);
25980 	if (ill_index != 0) {
25981 		if (ill == NULL) {
25982 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25983 			    B_TRUE, ipst);
25984 
25985 			/* Failure case frees things for us. */
25986 			if (ill == NULL)
25987 				return;
25988 
25989 			ill_need_rele = B_TRUE;
25990 		}
25991 		/*
25992 		 * If this packet needs to go out on a particular interface
25993 		 * honor it.
25994 		 */
25995 		if (attach_if) {
25996 			match_flags = MATCH_IRE_ILL;
25997 
25998 			/*
25999 			 * Check if we need an ire that will not be
26000 			 * looked up by anybody else i.e. HIDDEN.
26001 			 */
26002 			if (ill_is_probeonly(ill)) {
26003 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26004 			}
26005 		}
26006 	}
26007 	ASSERT(mp != NULL);
26008 
26009 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
26010 		boolean_t unspec_src;
26011 		ipif_t	*ipif;
26012 
26013 		/*
26014 		 * Use the ill_index to get the right ill.
26015 		 */
26016 		unspec_src = io->ipsec_out_unspec_src;
26017 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26018 		if (ipif == NULL) {
26019 			if (ill_need_rele)
26020 				ill_refrele(ill);
26021 			freemsg(ipsec_mp);
26022 			return;
26023 		}
26024 
26025 		if (ire_arg != NULL) {
26026 			ire = ire_arg;
26027 		} else {
26028 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
26029 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26030 			ire_need_rele = B_TRUE;
26031 		}
26032 		if (ire != NULL) {
26033 			ipif_refrele(ipif);
26034 			/*
26035 			 * XXX Do the multicast forwarding now, as the IPsec
26036 			 * processing has been done.
26037 			 */
26038 			goto send;
26039 		}
26040 
26041 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
26042 		mp->b_prev = NULL;
26043 		mp->b_next = NULL;
26044 
26045 		/*
26046 		 * If the IPsec packet was processed asynchronously,
26047 		 * drop it now.
26048 		 */
26049 		if (q == NULL) {
26050 			if (ill_need_rele)
26051 				ill_refrele(ill);
26052 			freemsg(ipsec_mp);
26053 			return;
26054 		}
26055 
26056 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
26057 		    unspec_src, zoneid);
26058 		ipif_refrele(ipif);
26059 	} else {
26060 		if (attach_if) {
26061 			ipif_t	*ipif;
26062 
26063 			ipif = ipif_get_next_ipif(NULL, ill);
26064 			if (ipif == NULL) {
26065 				if (ill_need_rele)
26066 					ill_refrele(ill);
26067 				freemsg(ipsec_mp);
26068 				return;
26069 			}
26070 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
26071 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26072 			ire_need_rele = B_TRUE;
26073 			ipif_refrele(ipif);
26074 		} else {
26075 			if (ire_arg != NULL) {
26076 				ire = ire_arg;
26077 			} else {
26078 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
26079 				    ipst);
26080 				ire_need_rele = B_TRUE;
26081 			}
26082 		}
26083 		if (ire != NULL)
26084 			goto send;
26085 		/*
26086 		 * ire disappeared underneath.
26087 		 *
26088 		 * What we need to do here is the ip_newroute
26089 		 * logic to get the ire without doing the IPsec
26090 		 * processing. Follow the same old path. But this
26091 		 * time, ip_wput or ire_add_then_send will call us
26092 		 * directly as all the IPsec operations are done.
26093 		 */
26094 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
26095 		mp->b_prev = NULL;
26096 		mp->b_next = NULL;
26097 
26098 		/*
26099 		 * If the IPsec packet was processed asynchronously,
26100 		 * drop it now.
26101 		 */
26102 		if (q == NULL) {
26103 			if (ill_need_rele)
26104 				ill_refrele(ill);
26105 			freemsg(ipsec_mp);
26106 			return;
26107 		}
26108 
26109 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
26110 		    zoneid, ipst);
26111 	}
26112 	if (ill != NULL && ill_need_rele)
26113 		ill_refrele(ill);
26114 	return;
26115 send:
26116 	if (ill != NULL && ill_need_rele)
26117 		ill_refrele(ill);
26118 
26119 	/* Local delivery */
26120 	if (ire->ire_stq == NULL) {
26121 		ill_t	*out_ill;
26122 		ASSERT(q != NULL);
26123 
26124 		/* PFHooks: LOOPBACK_OUT */
26125 		out_ill = ire_to_ill(ire);
26126 
26127 		/*
26128 		 * DTrace this as ip:::send.  A blocked packet will fire the
26129 		 * send probe, but not the receive probe.
26130 		 */
26131 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26132 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
26133 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
26134 
26135 		DTRACE_PROBE4(ip6__loopback__out__start,
26136 		    ill_t *, NULL, ill_t *, out_ill,
26137 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
26138 
26139 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
26140 		    ipst->ips_ipv6firewall_loopback_out,
26141 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
26142 
26143 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
26144 
26145 		if (ipsec_mp != NULL) {
26146 			ip_wput_local_v6(RD(q), out_ill,
26147 			    ip6h, ipsec_mp, ire, 0, zoneid);
26148 		}
26149 		if (ire_need_rele)
26150 			ire_refrele(ire);
26151 		return;
26152 	}
26153 	/*
26154 	 * Everything is done. Send it out on the wire.
26155 	 * We force the insertion of a fragment header using the
26156 	 * IPH_FRAG_HDR flag in two cases:
26157 	 * - after reception of an ICMPv6 "packet too big" message
26158 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
26159 	 * - for multirouted IPv6 packets, so that the receiver can
26160 	 *   discard duplicates according to their fragment identifier
26161 	 */
26162 	/* XXX fix flow control problems. */
26163 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
26164 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
26165 		if (hwaccel) {
26166 			/*
26167 			 * hardware acceleration does not handle these
26168 			 * "slow path" cases.
26169 			 */
26170 			/* IPsec KSTATS: should bump bean counter here. */
26171 			if (ire_need_rele)
26172 				ire_refrele(ire);
26173 			freemsg(ipsec_mp);
26174 			return;
26175 		}
26176 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
26177 		    (mp->b_cont ? msgdsize(mp) :
26178 		    mp->b_wptr - (uchar_t *)ip6h)) {
26179 			/* IPsec KSTATS: should bump bean counter here. */
26180 			ip0dbg(("Packet length mismatch: %d, %ld\n",
26181 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
26182 			    msgdsize(mp)));
26183 			if (ire_need_rele)
26184 				ire_refrele(ire);
26185 			freemsg(ipsec_mp);
26186 			return;
26187 		}
26188 		ASSERT(mp->b_prev == NULL);
26189 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26190 		    ntohs(ip6h->ip6_plen) +
26191 		    IPV6_HDR_LEN, ire->ire_max_frag));
26192 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26193 		    ire->ire_max_frag);
26194 	} else {
26195 		UPDATE_OB_PKT_COUNT(ire);
26196 		ire->ire_last_used_time = lbolt;
26197 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26198 	}
26199 	if (ire_need_rele)
26200 		ire_refrele(ire);
26201 	freeb(ipsec_mp);
26202 }
26203 
26204 void
26205 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26206 {
26207 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26208 	da_ipsec_t *hada;	/* data attributes */
26209 	ill_t *ill = (ill_t *)q->q_ptr;
26210 
26211 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26212 
26213 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26214 		/* IPsec KSTATS: Bump lose counter here! */
26215 		freemsg(mp);
26216 		return;
26217 	}
26218 
26219 	/*
26220 	 * It's an IPsec packet that must be
26221 	 * accelerated by the Provider, and the
26222 	 * outbound ill is IPsec acceleration capable.
26223 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26224 	 * to the ill.
26225 	 * IPsec KSTATS: should bump packet counter here.
26226 	 */
26227 
26228 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26229 	if (hada_mp == NULL) {
26230 		/* IPsec KSTATS: should bump packet counter here. */
26231 		freemsg(mp);
26232 		return;
26233 	}
26234 
26235 	hada_mp->b_datap->db_type = M_CTL;
26236 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26237 	hada_mp->b_cont = mp;
26238 
26239 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26240 	bzero(hada, sizeof (da_ipsec_t));
26241 	hada->da_type = IPHADA_M_CTL;
26242 
26243 	putnext(q, hada_mp);
26244 }
26245 
26246 /*
26247  * Finish the outbound IPsec processing. This function is called from
26248  * ipsec_out_process() if the IPsec packet was processed
26249  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26250  * asynchronously.
26251  */
26252 void
26253 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26254     ire_t *ire_arg)
26255 {
26256 	uint32_t v_hlen_tos_len;
26257 	ipaddr_t	dst;
26258 	ipif_t	*ipif = NULL;
26259 	ire_t *ire;
26260 	ire_t *ire1 = NULL;
26261 	mblk_t *next_mp = NULL;
26262 	uint32_t max_frag;
26263 	boolean_t multirt_send = B_FALSE;
26264 	mblk_t *mp;
26265 	ipha_t *ipha1;
26266 	uint_t	ill_index;
26267 	ipsec_out_t *io;
26268 	boolean_t attach_if;
26269 	int match_flags;
26270 	irb_t *irb = NULL;
26271 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26272 	zoneid_t zoneid;
26273 	ipxmit_state_t	pktxmit_state;
26274 	ip_stack_t	*ipst;
26275 
26276 #ifdef	_BIG_ENDIAN
26277 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26278 #else
26279 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26280 #endif
26281 
26282 	mp = ipsec_mp->b_cont;
26283 	ipha1 = (ipha_t *)mp->b_rptr;
26284 	ASSERT(mp != NULL);
26285 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26286 	dst = ipha->ipha_dst;
26287 
26288 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26289 	ill_index = io->ipsec_out_ill_index;
26290 	attach_if = io->ipsec_out_attach_if;
26291 	zoneid = io->ipsec_out_zoneid;
26292 	ASSERT(zoneid != ALL_ZONES);
26293 	ipst = io->ipsec_out_ns->netstack_ip;
26294 	ASSERT(io->ipsec_out_ns != NULL);
26295 
26296 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26297 	if (ill_index != 0) {
26298 		if (ill == NULL) {
26299 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26300 			    ill_index, B_FALSE, ipst);
26301 
26302 			/* Failure case frees things for us. */
26303 			if (ill == NULL)
26304 				return;
26305 
26306 			ill_need_rele = B_TRUE;
26307 		}
26308 		/*
26309 		 * If this packet needs to go out on a particular interface
26310 		 * honor it.
26311 		 */
26312 		if (attach_if) {
26313 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26314 
26315 			/*
26316 			 * Check if we need an ire that will not be
26317 			 * looked up by anybody else i.e. HIDDEN.
26318 			 */
26319 			if (ill_is_probeonly(ill)) {
26320 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26321 			}
26322 		}
26323 	}
26324 
26325 	if (CLASSD(dst)) {
26326 		boolean_t conn_dontroute;
26327 		/*
26328 		 * Use the ill_index to get the right ipif.
26329 		 */
26330 		conn_dontroute = io->ipsec_out_dontroute;
26331 		if (ill_index == 0)
26332 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26333 		else
26334 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26335 		if (ipif == NULL) {
26336 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26337 			    " multicast\n"));
26338 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26339 			freemsg(ipsec_mp);
26340 			goto done;
26341 		}
26342 		/*
26343 		 * ipha_src has already been intialized with the
26344 		 * value of the ipif in ip_wput. All we need now is
26345 		 * an ire to send this downstream.
26346 		 */
26347 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26348 		    MBLK_GETLABEL(mp), match_flags, ipst);
26349 		if (ire != NULL) {
26350 			ill_t *ill1;
26351 			/*
26352 			 * Do the multicast forwarding now, as the IPsec
26353 			 * processing has been done.
26354 			 */
26355 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26356 			    (ill1 = ire_to_ill(ire))) {
26357 				if (ip_mforward(ill1, ipha, mp)) {
26358 					freemsg(ipsec_mp);
26359 					ip1dbg(("ip_wput_ipsec_out: mforward "
26360 					    "failed\n"));
26361 					ire_refrele(ire);
26362 					goto done;
26363 				}
26364 			}
26365 			goto send;
26366 		}
26367 
26368 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26369 		mp->b_prev = NULL;
26370 		mp->b_next = NULL;
26371 
26372 		/*
26373 		 * If the IPsec packet was processed asynchronously,
26374 		 * drop it now.
26375 		 */
26376 		if (q == NULL) {
26377 			freemsg(ipsec_mp);
26378 			goto done;
26379 		}
26380 
26381 		/*
26382 		 * We may be using a wrong ipif to create the ire.
26383 		 * But it is okay as the source address is assigned
26384 		 * for the packet already. Next outbound packet would
26385 		 * create the IRE with the right IPIF in ip_wput.
26386 		 *
26387 		 * Also handle RTF_MULTIRT routes.
26388 		 */
26389 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26390 		    zoneid, &zero_info);
26391 	} else {
26392 		if (attach_if) {
26393 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26394 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26395 		} else {
26396 			if (ire_arg != NULL) {
26397 				ire = ire_arg;
26398 				ire_need_rele = B_FALSE;
26399 			} else {
26400 				ire = ire_cache_lookup(dst, zoneid,
26401 				    MBLK_GETLABEL(mp), ipst);
26402 			}
26403 		}
26404 		if (ire != NULL) {
26405 			goto send;
26406 		}
26407 
26408 		/*
26409 		 * ire disappeared underneath.
26410 		 *
26411 		 * What we need to do here is the ip_newroute
26412 		 * logic to get the ire without doing the IPsec
26413 		 * processing. Follow the same old path. But this
26414 		 * time, ip_wput or ire_add_then_put will call us
26415 		 * directly as all the IPsec operations are done.
26416 		 */
26417 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26418 		mp->b_prev = NULL;
26419 		mp->b_next = NULL;
26420 
26421 		/*
26422 		 * If the IPsec packet was processed asynchronously,
26423 		 * drop it now.
26424 		 */
26425 		if (q == NULL) {
26426 			freemsg(ipsec_mp);
26427 			goto done;
26428 		}
26429 
26430 		/*
26431 		 * Since we're going through ip_newroute() again, we
26432 		 * need to make sure we don't:
26433 		 *
26434 		 *	1.) Trigger the ASSERT() with the ipha_ident
26435 		 *	    overloading.
26436 		 *	2.) Redo transport-layer checksumming, since we've
26437 		 *	    already done all that to get this far.
26438 		 *
26439 		 * The easiest way not do either of the above is to set
26440 		 * the ipha_ident field to IP_HDR_INCLUDED.
26441 		 */
26442 		ipha->ipha_ident = IP_HDR_INCLUDED;
26443 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26444 		    zoneid, ipst);
26445 	}
26446 	goto done;
26447 send:
26448 	if (ire->ire_stq == NULL) {
26449 		ill_t	*out_ill;
26450 		/*
26451 		 * Loopbacks go through ip_wput_local except for one case.
26452 		 * We come here if we generate a icmp_frag_needed message
26453 		 * after IPsec processing is over. When this function calls
26454 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26455 		 * icmp_frag_needed. The message generated comes back here
26456 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26457 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26458 		 * source address as it is usually set in ip_wput_ire. As
26459 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26460 		 * and we end up here. We can't enter ip_wput_ire once the
26461 		 * IPsec processing is over and hence we need to do it here.
26462 		 */
26463 		ASSERT(q != NULL);
26464 		UPDATE_OB_PKT_COUNT(ire);
26465 		ire->ire_last_used_time = lbolt;
26466 		if (ipha->ipha_src == 0)
26467 			ipha->ipha_src = ire->ire_src_addr;
26468 
26469 		/* PFHooks: LOOPBACK_OUT */
26470 		out_ill = ire_to_ill(ire);
26471 
26472 		/*
26473 		 * DTrace this as ip:::send.  A blocked packet will fire the
26474 		 * send probe, but not the receive probe.
26475 		 */
26476 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26477 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26478 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26479 
26480 		DTRACE_PROBE4(ip4__loopback__out__start,
26481 		    ill_t *, NULL, ill_t *, out_ill,
26482 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26483 
26484 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26485 		    ipst->ips_ipv4firewall_loopback_out,
26486 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26487 
26488 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26489 
26490 		if (ipsec_mp != NULL)
26491 			ip_wput_local(RD(q), out_ill,
26492 			    ipha, ipsec_mp, ire, 0, zoneid);
26493 		if (ire_need_rele)
26494 			ire_refrele(ire);
26495 		goto done;
26496 	}
26497 
26498 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26499 		/*
26500 		 * We are through with IPsec processing.
26501 		 * Fragment this and send it on the wire.
26502 		 */
26503 		if (io->ipsec_out_accelerated) {
26504 			/*
26505 			 * The packet has been accelerated but must
26506 			 * be fragmented. This should not happen
26507 			 * since AH and ESP must not accelerate
26508 			 * packets that need fragmentation, however
26509 			 * the configuration could have changed
26510 			 * since the AH or ESP processing.
26511 			 * Drop packet.
26512 			 * IPsec KSTATS: bump bean counter here.
26513 			 */
26514 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26515 			    "fragmented accelerated packet!\n"));
26516 			freemsg(ipsec_mp);
26517 		} else {
26518 			ip_wput_ire_fragmentit(ipsec_mp, ire,
26519 			    zoneid, ipst, NULL);
26520 		}
26521 		if (ire_need_rele)
26522 			ire_refrele(ire);
26523 		goto done;
26524 	}
26525 
26526 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26527 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26528 	    (void *)ire->ire_ipif, (void *)ipif));
26529 
26530 	/*
26531 	 * Multiroute the secured packet, unless IPsec really
26532 	 * requires the packet to go out only through a particular
26533 	 * interface.
26534 	 */
26535 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26536 		ire_t *first_ire;
26537 		irb = ire->ire_bucket;
26538 		ASSERT(irb != NULL);
26539 		/*
26540 		 * This ire has been looked up as the one that
26541 		 * goes through the given ipif;
26542 		 * make sure we do not omit any other multiroute ire
26543 		 * that may be present in the bucket before this one.
26544 		 */
26545 		IRB_REFHOLD(irb);
26546 		for (first_ire = irb->irb_ire;
26547 		    first_ire != NULL;
26548 		    first_ire = first_ire->ire_next) {
26549 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26550 			    (first_ire->ire_addr == ire->ire_addr) &&
26551 			    !(first_ire->ire_marks &
26552 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26553 				break;
26554 			}
26555 		}
26556 
26557 		if ((first_ire != NULL) && (first_ire != ire)) {
26558 			/*
26559 			 * Don't change the ire if the packet must
26560 			 * be fragmented if sent via this new one.
26561 			 */
26562 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26563 				IRE_REFHOLD(first_ire);
26564 				if (ire_need_rele)
26565 					ire_refrele(ire);
26566 				else
26567 					ire_need_rele = B_TRUE;
26568 				ire = first_ire;
26569 			}
26570 		}
26571 		IRB_REFRELE(irb);
26572 
26573 		multirt_send = B_TRUE;
26574 		max_frag = ire->ire_max_frag;
26575 	} else {
26576 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26577 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26578 			    "flag, attach_if %d\n", attach_if));
26579 		}
26580 	}
26581 
26582 	/*
26583 	 * In most cases, the emission loop below is entered only once.
26584 	 * Only in the case where the ire holds the RTF_MULTIRT
26585 	 * flag, we loop to process all RTF_MULTIRT ires in the
26586 	 * bucket, and send the packet through all crossed
26587 	 * RTF_MULTIRT routes.
26588 	 */
26589 	do {
26590 		if (multirt_send) {
26591 			/*
26592 			 * ire1 holds here the next ire to process in the
26593 			 * bucket. If multirouting is expected,
26594 			 * any non-RTF_MULTIRT ire that has the
26595 			 * right destination address is ignored.
26596 			 */
26597 			ASSERT(irb != NULL);
26598 			IRB_REFHOLD(irb);
26599 			for (ire1 = ire->ire_next;
26600 			    ire1 != NULL;
26601 			    ire1 = ire1->ire_next) {
26602 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26603 					continue;
26604 				if (ire1->ire_addr != ire->ire_addr)
26605 					continue;
26606 				if (ire1->ire_marks &
26607 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26608 					continue;
26609 				/* No loopback here */
26610 				if (ire1->ire_stq == NULL)
26611 					continue;
26612 				/*
26613 				 * Ensure we do not exceed the MTU
26614 				 * of the next route.
26615 				 */
26616 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26617 					ip_multirt_bad_mtu(ire1, max_frag);
26618 					continue;
26619 				}
26620 
26621 				IRE_REFHOLD(ire1);
26622 				break;
26623 			}
26624 			IRB_REFRELE(irb);
26625 			if (ire1 != NULL) {
26626 				/*
26627 				 * We are in a multiple send case, need to
26628 				 * make a copy of the packet.
26629 				 */
26630 				next_mp = copymsg(ipsec_mp);
26631 				if (next_mp == NULL) {
26632 					ire_refrele(ire1);
26633 					ire1 = NULL;
26634 				}
26635 			}
26636 		}
26637 		/*
26638 		 * Everything is done. Send it out on the wire
26639 		 *
26640 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26641 		 * either send it on the wire or, in the case of
26642 		 * HW acceleration, call ipsec_hw_putnext.
26643 		 */
26644 		if (ire->ire_nce &&
26645 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26646 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26647 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26648 			/*
26649 			 * If ire's link-layer is unresolved (this
26650 			 * would only happen if the incomplete ire
26651 			 * was added to cachetable via forwarding path)
26652 			 * don't bother going to ip_xmit_v4. Just drop the
26653 			 * packet.
26654 			 * There is a slight risk here, in that, if we
26655 			 * have the forwarding path create an incomplete
26656 			 * IRE, then until the IRE is completed, any
26657 			 * transmitted IPsec packets will be dropped
26658 			 * instead of being queued waiting for resolution.
26659 			 *
26660 			 * But the likelihood of a forwarding packet and a wput
26661 			 * packet sending to the same dst at the same time
26662 			 * and there not yet be an ARP entry for it is small.
26663 			 * Furthermore, if this actually happens, it might
26664 			 * be likely that wput would generate multiple
26665 			 * packets (and forwarding would also have a train
26666 			 * of packets) for that destination. If this is
26667 			 * the case, some of them would have been dropped
26668 			 * anyway, since ARP only queues a few packets while
26669 			 * waiting for resolution
26670 			 *
26671 			 * NOTE: We should really call ip_xmit_v4,
26672 			 * and let it queue the packet and send the
26673 			 * ARP query and have ARP come back thus:
26674 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26675 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26676 			 * hw accel work. But it's too complex to get
26677 			 * the IPsec hw  acceleration approach to fit
26678 			 * well with ip_xmit_v4 doing ARP without
26679 			 * doing IPsec simplification. For now, we just
26680 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26681 			 * that we can continue with the send on the next
26682 			 * attempt.
26683 			 *
26684 			 * XXX THis should be revisited, when
26685 			 * the IPsec/IP interaction is cleaned up
26686 			 */
26687 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26688 			    " - dropping packet\n"));
26689 			freemsg(ipsec_mp);
26690 			/*
26691 			 * Call ip_xmit_v4() to trigger ARP query
26692 			 * in case the nce_state is ND_INITIAL
26693 			 */
26694 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
26695 			goto drop_pkt;
26696 		}
26697 
26698 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26699 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26700 		    mblk_t *, ipsec_mp);
26701 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26702 		    ipst->ips_ipv4firewall_physical_out, NULL,
26703 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26704 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26705 		if (ipsec_mp == NULL)
26706 			goto drop_pkt;
26707 
26708 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26709 		pktxmit_state = ip_xmit_v4(mp, ire,
26710 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE, NULL);
26711 
26712 		if ((pktxmit_state ==  SEND_FAILED) ||
26713 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26714 
26715 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26716 drop_pkt:
26717 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26718 			    ipIfStatsOutDiscards);
26719 			if (ire_need_rele)
26720 				ire_refrele(ire);
26721 			if (ire1 != NULL) {
26722 				ire_refrele(ire1);
26723 				freemsg(next_mp);
26724 			}
26725 			goto done;
26726 		}
26727 
26728 		freeb(ipsec_mp);
26729 		if (ire_need_rele)
26730 			ire_refrele(ire);
26731 
26732 		if (ire1 != NULL) {
26733 			ire = ire1;
26734 			ire_need_rele = B_TRUE;
26735 			ASSERT(next_mp);
26736 			ipsec_mp = next_mp;
26737 			mp = ipsec_mp->b_cont;
26738 			ire1 = NULL;
26739 			next_mp = NULL;
26740 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26741 		} else {
26742 			multirt_send = B_FALSE;
26743 		}
26744 	} while (multirt_send);
26745 done:
26746 	if (ill != NULL && ill_need_rele)
26747 		ill_refrele(ill);
26748 	if (ipif != NULL)
26749 		ipif_refrele(ipif);
26750 }
26751 
26752 /*
26753  * Get the ill corresponding to the specified ire, and compare its
26754  * capabilities with the protocol and algorithms specified by the
26755  * the SA obtained from ipsec_out. If they match, annotate the
26756  * ipsec_out structure to indicate that the packet needs acceleration.
26757  *
26758  *
26759  * A packet is eligible for outbound hardware acceleration if the
26760  * following conditions are satisfied:
26761  *
26762  * 1. the packet will not be fragmented
26763  * 2. the provider supports the algorithm
26764  * 3. there is no pending control message being exchanged
26765  * 4. snoop is not attached
26766  * 5. the destination address is not a broadcast or multicast address.
26767  *
26768  * Rationale:
26769  *	- Hardware drivers do not support fragmentation with
26770  *	  the current interface.
26771  *	- snoop, multicast, and broadcast may result in exposure of
26772  *	  a cleartext datagram.
26773  * We check all five of these conditions here.
26774  *
26775  * XXX would like to nuke "ire_t *" parameter here; problem is that
26776  * IRE is only way to figure out if a v4 address is a broadcast and
26777  * thus ineligible for acceleration...
26778  */
26779 static void
26780 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26781 {
26782 	ipsec_out_t *io;
26783 	mblk_t *data_mp;
26784 	uint_t plen, overhead;
26785 	ip_stack_t	*ipst;
26786 
26787 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26788 		return;
26789 
26790 	if (ill == NULL)
26791 		return;
26792 	ipst = ill->ill_ipst;
26793 	/*
26794 	 * Destination address is a broadcast or multicast.  Punt.
26795 	 */
26796 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26797 	    IRE_LOCAL)))
26798 		return;
26799 
26800 	data_mp = ipsec_mp->b_cont;
26801 
26802 	if (ill->ill_isv6) {
26803 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26804 
26805 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26806 			return;
26807 
26808 		plen = ip6h->ip6_plen;
26809 	} else {
26810 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26811 
26812 		if (CLASSD(ipha->ipha_dst))
26813 			return;
26814 
26815 		plen = ipha->ipha_length;
26816 	}
26817 	/*
26818 	 * Is there a pending DLPI control message being exchanged
26819 	 * between IP/IPsec and the DLS Provider? If there is, it
26820 	 * could be a SADB update, and the state of the DLS Provider
26821 	 * SADB might not be in sync with the SADB maintained by
26822 	 * IPsec. To avoid dropping packets or using the wrong keying
26823 	 * material, we do not accelerate this packet.
26824 	 */
26825 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26826 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26827 		    "ill_dlpi_pending! don't accelerate packet\n"));
26828 		return;
26829 	}
26830 
26831 	/*
26832 	 * Is the Provider in promiscous mode? If it does, we don't
26833 	 * accelerate the packet since it will bounce back up to the
26834 	 * listeners in the clear.
26835 	 */
26836 	if (ill->ill_promisc_on_phys) {
26837 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26838 		    "ill in promiscous mode, don't accelerate packet\n"));
26839 		return;
26840 	}
26841 
26842 	/*
26843 	 * Will the packet require fragmentation?
26844 	 */
26845 
26846 	/*
26847 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26848 	 * as is used elsewhere.
26849 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26850 	 *	+ 2-byte trailer
26851 	 */
26852 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26853 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26854 
26855 	if ((plen + overhead) > ill->ill_max_mtu)
26856 		return;
26857 
26858 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26859 
26860 	/*
26861 	 * Can the ill accelerate this IPsec protocol and algorithm
26862 	 * specified by the SA?
26863 	 */
26864 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26865 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26866 		return;
26867 	}
26868 
26869 	/*
26870 	 * Tell AH or ESP that the outbound ill is capable of
26871 	 * accelerating this packet.
26872 	 */
26873 	io->ipsec_out_is_capab_ill = B_TRUE;
26874 }
26875 
26876 /*
26877  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26878  *
26879  * If this function returns B_TRUE, the requested SA's have been filled
26880  * into the ipsec_out_*_sa pointers.
26881  *
26882  * If the function returns B_FALSE, the packet has been "consumed", most
26883  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26884  *
26885  * The SA references created by the protocol-specific "select"
26886  * function will be released when the ipsec_mp is freed, thanks to the
26887  * ipsec_out_free destructor -- see spd.c.
26888  */
26889 static boolean_t
26890 ipsec_out_select_sa(mblk_t *ipsec_mp)
26891 {
26892 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26893 	ipsec_out_t *io;
26894 	ipsec_policy_t *pp;
26895 	ipsec_action_t *ap;
26896 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26897 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26898 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26899 
26900 	if (!io->ipsec_out_secure) {
26901 		/*
26902 		 * We came here by mistake.
26903 		 * Don't bother with ipsec processing
26904 		 * We should "discourage" this path in the future.
26905 		 */
26906 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26907 		return (B_FALSE);
26908 	}
26909 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26910 	ASSERT((io->ipsec_out_policy != NULL) ||
26911 	    (io->ipsec_out_act != NULL));
26912 
26913 	ASSERT(io->ipsec_out_failed == B_FALSE);
26914 
26915 	/*
26916 	 * IPsec processing has started.
26917 	 */
26918 	io->ipsec_out_proc_begin = B_TRUE;
26919 	ap = io->ipsec_out_act;
26920 	if (ap == NULL) {
26921 		pp = io->ipsec_out_policy;
26922 		ASSERT(pp != NULL);
26923 		ap = pp->ipsp_act;
26924 		ASSERT(ap != NULL);
26925 	}
26926 
26927 	/*
26928 	 * We have an action.  now, let's select SA's.
26929 	 * (In the future, we can cache this in the conn_t..)
26930 	 */
26931 	if (ap->ipa_want_esp) {
26932 		if (io->ipsec_out_esp_sa == NULL) {
26933 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26934 			    IPPROTO_ESP);
26935 		}
26936 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26937 	}
26938 
26939 	if (ap->ipa_want_ah) {
26940 		if (io->ipsec_out_ah_sa == NULL) {
26941 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26942 			    IPPROTO_AH);
26943 		}
26944 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26945 		/*
26946 		 * The ESP and AH processing order needs to be preserved
26947 		 * when both protocols are required (ESP should be applied
26948 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26949 		 * when both ESP and AH are required, and an AH ACQUIRE
26950 		 * is needed.
26951 		 */
26952 		if (ap->ipa_want_esp && need_ah_acquire)
26953 			need_esp_acquire = B_TRUE;
26954 	}
26955 
26956 	/*
26957 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26958 	 * Release SAs that got referenced, but will not be used until we
26959 	 * acquire _all_ of the SAs we need.
26960 	 */
26961 	if (need_ah_acquire || need_esp_acquire) {
26962 		if (io->ipsec_out_ah_sa != NULL) {
26963 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26964 			io->ipsec_out_ah_sa = NULL;
26965 		}
26966 		if (io->ipsec_out_esp_sa != NULL) {
26967 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26968 			io->ipsec_out_esp_sa = NULL;
26969 		}
26970 
26971 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26972 		return (B_FALSE);
26973 	}
26974 
26975 	return (B_TRUE);
26976 }
26977 
26978 /*
26979  * Process an IPSEC_OUT message and see what you can
26980  * do with it.
26981  * IPQoS Notes:
26982  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26983  * IPsec.
26984  * XXX would like to nuke ire_t.
26985  * XXX ill_index better be "real"
26986  */
26987 void
26988 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26989 {
26990 	ipsec_out_t *io;
26991 	ipsec_policy_t *pp;
26992 	ipsec_action_t *ap;
26993 	ipha_t *ipha;
26994 	ip6_t *ip6h;
26995 	mblk_t *mp;
26996 	ill_t *ill;
26997 	zoneid_t zoneid;
26998 	ipsec_status_t ipsec_rc;
26999 	boolean_t ill_need_rele = B_FALSE;
27000 	ip_stack_t	*ipst;
27001 	ipsec_stack_t	*ipss;
27002 
27003 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
27004 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
27005 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
27006 	ipst = io->ipsec_out_ns->netstack_ip;
27007 	mp = ipsec_mp->b_cont;
27008 
27009 	/*
27010 	 * Initiate IPPF processing. We do it here to account for packets
27011 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
27012 	 * We can check for ipsec_out_proc_begin even for such packets, as
27013 	 * they will always be false (asserted below).
27014 	 */
27015 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
27016 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
27017 		    io->ipsec_out_ill_index : ill_index);
27018 		if (mp == NULL) {
27019 			ip2dbg(("ipsec_out_process: packet dropped "\
27020 			    "during IPPF processing\n"));
27021 			freeb(ipsec_mp);
27022 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
27023 			return;
27024 		}
27025 	}
27026 
27027 	if (!io->ipsec_out_secure) {
27028 		/*
27029 		 * We came here by mistake.
27030 		 * Don't bother with ipsec processing
27031 		 * Should "discourage" this path in the future.
27032 		 */
27033 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
27034 		goto done;
27035 	}
27036 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
27037 	ASSERT((io->ipsec_out_policy != NULL) ||
27038 	    (io->ipsec_out_act != NULL));
27039 	ASSERT(io->ipsec_out_failed == B_FALSE);
27040 
27041 	ipss = ipst->ips_netstack->netstack_ipsec;
27042 	if (!ipsec_loaded(ipss)) {
27043 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
27044 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27045 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
27046 		} else {
27047 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
27048 		}
27049 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
27050 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
27051 		    &ipss->ipsec_dropper);
27052 		return;
27053 	}
27054 
27055 	/*
27056 	 * IPsec processing has started.
27057 	 */
27058 	io->ipsec_out_proc_begin = B_TRUE;
27059 	ap = io->ipsec_out_act;
27060 	if (ap == NULL) {
27061 		pp = io->ipsec_out_policy;
27062 		ASSERT(pp != NULL);
27063 		ap = pp->ipsp_act;
27064 		ASSERT(ap != NULL);
27065 	}
27066 
27067 	/*
27068 	 * Save the outbound ill index. When the packet comes back
27069 	 * from IPsec, we make sure the ill hasn't changed or disappeared
27070 	 * before sending it the accelerated packet.
27071 	 */
27072 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
27073 		int ifindex;
27074 		ill = ire_to_ill(ire);
27075 		ifindex = ill->ill_phyint->phyint_ifindex;
27076 		io->ipsec_out_capab_ill_index = ifindex;
27077 	}
27078 
27079 	/*
27080 	 * The order of processing is first insert a IP header if needed.
27081 	 * Then insert the ESP header and then the AH header.
27082 	 */
27083 	if ((io->ipsec_out_se_done == B_FALSE) &&
27084 	    (ap->ipa_want_se)) {
27085 		/*
27086 		 * First get the outer IP header before sending
27087 		 * it to ESP.
27088 		 */
27089 		ipha_t *oipha, *iipha;
27090 		mblk_t *outer_mp, *inner_mp;
27091 
27092 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
27093 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
27094 			    "ipsec_out_process: "
27095 			    "Self-Encapsulation failed: Out of memory\n");
27096 			freemsg(ipsec_mp);
27097 			if (ill != NULL) {
27098 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27099 			} else {
27100 				BUMP_MIB(&ipst->ips_ip_mib,
27101 				    ipIfStatsOutDiscards);
27102 			}
27103 			return;
27104 		}
27105 		inner_mp = ipsec_mp->b_cont;
27106 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
27107 		oipha = (ipha_t *)outer_mp->b_rptr;
27108 		iipha = (ipha_t *)inner_mp->b_rptr;
27109 		*oipha = *iipha;
27110 		outer_mp->b_wptr += sizeof (ipha_t);
27111 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
27112 		    sizeof (ipha_t));
27113 		oipha->ipha_protocol = IPPROTO_ENCAP;
27114 		oipha->ipha_version_and_hdr_length =
27115 		    IP_SIMPLE_HDR_VERSION;
27116 		oipha->ipha_hdr_checksum = 0;
27117 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
27118 		outer_mp->b_cont = inner_mp;
27119 		ipsec_mp->b_cont = outer_mp;
27120 
27121 		io->ipsec_out_se_done = B_TRUE;
27122 		io->ipsec_out_tunnel = B_TRUE;
27123 	}
27124 
27125 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
27126 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
27127 	    !ipsec_out_select_sa(ipsec_mp))
27128 		return;
27129 
27130 	/*
27131 	 * By now, we know what SA's to use.  Toss over to ESP & AH
27132 	 * to do the heavy lifting.
27133 	 */
27134 	zoneid = io->ipsec_out_zoneid;
27135 	ASSERT(zoneid != ALL_ZONES);
27136 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
27137 		ASSERT(io->ipsec_out_esp_sa != NULL);
27138 		io->ipsec_out_esp_done = B_TRUE;
27139 		/*
27140 		 * Note that since hw accel can only apply one transform,
27141 		 * not two, we skip hw accel for ESP if we also have AH
27142 		 * This is an design limitation of the interface
27143 		 * which should be revisited.
27144 		 */
27145 		ASSERT(ire != NULL);
27146 		if (io->ipsec_out_ah_sa == NULL) {
27147 			ill = (ill_t *)ire->ire_stq->q_ptr;
27148 			ipsec_out_is_accelerated(ipsec_mp,
27149 			    io->ipsec_out_esp_sa, ill, ire);
27150 		}
27151 
27152 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
27153 		switch (ipsec_rc) {
27154 		case IPSEC_STATUS_SUCCESS:
27155 			break;
27156 		case IPSEC_STATUS_FAILED:
27157 			if (ill != NULL) {
27158 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27159 			} else {
27160 				BUMP_MIB(&ipst->ips_ip_mib,
27161 				    ipIfStatsOutDiscards);
27162 			}
27163 			/* FALLTHRU */
27164 		case IPSEC_STATUS_PENDING:
27165 			return;
27166 		}
27167 	}
27168 
27169 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27170 		ASSERT(io->ipsec_out_ah_sa != NULL);
27171 		io->ipsec_out_ah_done = B_TRUE;
27172 		if (ire == NULL) {
27173 			int idx = io->ipsec_out_capab_ill_index;
27174 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27175 			    NULL, NULL, NULL, NULL, ipst);
27176 			ill_need_rele = B_TRUE;
27177 		} else {
27178 			ill = (ill_t *)ire->ire_stq->q_ptr;
27179 		}
27180 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27181 		    ire);
27182 
27183 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27184 		switch (ipsec_rc) {
27185 		case IPSEC_STATUS_SUCCESS:
27186 			break;
27187 		case IPSEC_STATUS_FAILED:
27188 			if (ill != NULL) {
27189 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27190 			} else {
27191 				BUMP_MIB(&ipst->ips_ip_mib,
27192 				    ipIfStatsOutDiscards);
27193 			}
27194 			/* FALLTHRU */
27195 		case IPSEC_STATUS_PENDING:
27196 			if (ill != NULL && ill_need_rele)
27197 				ill_refrele(ill);
27198 			return;
27199 		}
27200 	}
27201 	/*
27202 	 * We are done with IPsec processing. Send it over
27203 	 * the wire.
27204 	 */
27205 done:
27206 	mp = ipsec_mp->b_cont;
27207 	ipha = (ipha_t *)mp->b_rptr;
27208 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27209 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27210 	} else {
27211 		ip6h = (ip6_t *)ipha;
27212 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27213 	}
27214 	if (ill != NULL && ill_need_rele)
27215 		ill_refrele(ill);
27216 }
27217 
27218 /* ARGSUSED */
27219 void
27220 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27221 {
27222 	opt_restart_t	*or;
27223 	int	err;
27224 	conn_t	*connp;
27225 
27226 	ASSERT(CONN_Q(q));
27227 	connp = Q_TO_CONN(q);
27228 
27229 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27230 	or = (opt_restart_t *)first_mp->b_rptr;
27231 	/*
27232 	 * We don't need to pass any credentials here since this is just
27233 	 * a restart. The credentials are passed in when svr4_optcom_req
27234 	 * is called the first time (from ip_wput_nondata).
27235 	 */
27236 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27237 		err = svr4_optcom_req(q, first_mp, NULL,
27238 		    &ip_opt_obj, B_FALSE);
27239 	} else {
27240 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27241 		err = tpi_optcom_req(q, first_mp, NULL,
27242 		    &ip_opt_obj, B_FALSE);
27243 	}
27244 	if (err != EINPROGRESS) {
27245 		/* operation is done */
27246 		CONN_OPER_PENDING_DONE(connp);
27247 	}
27248 }
27249 
27250 /*
27251  * ioctls that go through a down/up sequence may need to wait for the down
27252  * to complete. This involves waiting for the ire and ipif refcnts to go down
27253  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27254  */
27255 /* ARGSUSED */
27256 void
27257 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27258 {
27259 	struct iocblk *iocp;
27260 	mblk_t *mp1;
27261 	ip_ioctl_cmd_t *ipip;
27262 	int err;
27263 	sin_t	*sin;
27264 	struct lifreq *lifr;
27265 	struct ifreq *ifr;
27266 
27267 	iocp = (struct iocblk *)mp->b_rptr;
27268 	ASSERT(ipsq != NULL);
27269 	/* Existence of mp1 verified in ip_wput_nondata */
27270 	mp1 = mp->b_cont->b_cont;
27271 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27272 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27273 		/*
27274 		 * Special case where ipsq_current_ipif is not set:
27275 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27276 		 * ill could also have become part of a ipmp group in the
27277 		 * process, we are here as were not able to complete the
27278 		 * operation in ipif_set_values because we could not become
27279 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27280 		 * will not be set so we need to set it.
27281 		 */
27282 		ill_t *ill = q->q_ptr;
27283 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27284 	}
27285 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27286 
27287 	if (ipip->ipi_cmd_type == IF_CMD) {
27288 		/* This a old style SIOC[GS]IF* command */
27289 		ifr = (struct ifreq *)mp1->b_rptr;
27290 		sin = (sin_t *)&ifr->ifr_addr;
27291 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27292 		/* This a new style SIOC[GS]LIF* command */
27293 		lifr = (struct lifreq *)mp1->b_rptr;
27294 		sin = (sin_t *)&lifr->lifr_addr;
27295 	} else {
27296 		sin = NULL;
27297 	}
27298 
27299 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27300 	    ipip, mp1->b_rptr);
27301 
27302 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27303 }
27304 
27305 /*
27306  * ioctl processing
27307  *
27308  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27309  * the ioctl command in the ioctl tables, determines the copyin data size
27310  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27311  *
27312  * ioctl processing then continues when the M_IOCDATA makes its way down to
27313  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27314  * associated 'conn' is refheld till the end of the ioctl and the general
27315  * ioctl processing function ip_process_ioctl() is called to extract the
27316  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27317  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27318  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27319  * is used to extract the ioctl's arguments.
27320  *
27321  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27322  * so goes thru the serialization primitive ipsq_try_enter. Then the
27323  * appropriate function to handle the ioctl is called based on the entry in
27324  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27325  * which also refreleases the 'conn' that was refheld at the start of the
27326  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27327  *
27328  * Many exclusive ioctls go thru an internal down up sequence as part of
27329  * the operation. For example an attempt to change the IP address of an
27330  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27331  * does all the cleanup such as deleting all ires that use this address.
27332  * Then we need to wait till all references to the interface go away.
27333  */
27334 void
27335 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27336 {
27337 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27338 	ip_ioctl_cmd_t *ipip = arg;
27339 	ip_extract_func_t *extract_funcp;
27340 	cmd_info_t ci;
27341 	int err;
27342 
27343 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27344 
27345 	if (ipip == NULL)
27346 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27347 
27348 	/*
27349 	 * SIOCLIFADDIF needs to go thru a special path since the
27350 	 * ill may not exist yet. This happens in the case of lo0
27351 	 * which is created using this ioctl.
27352 	 */
27353 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27354 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27355 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27356 		return;
27357 	}
27358 
27359 	ci.ci_ipif = NULL;
27360 	if (ipip->ipi_cmd_type == MISC_CMD) {
27361 		/*
27362 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27363 		 */
27364 		if (ipip->ipi_cmd == IF_UNITSEL) {
27365 			/* ioctl comes down the ill */
27366 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27367 			ipif_refhold(ci.ci_ipif);
27368 		}
27369 		err = 0;
27370 		ci.ci_sin = NULL;
27371 		ci.ci_sin6 = NULL;
27372 		ci.ci_lifr = NULL;
27373 	} else {
27374 		switch (ipip->ipi_cmd_type) {
27375 		case IF_CMD:
27376 		case LIF_CMD:
27377 			extract_funcp = ip_extract_lifreq;
27378 			break;
27379 
27380 		case ARP_CMD:
27381 		case XARP_CMD:
27382 			extract_funcp = ip_extract_arpreq;
27383 			break;
27384 
27385 		case TUN_CMD:
27386 			extract_funcp = ip_extract_tunreq;
27387 			break;
27388 
27389 		case MSFILT_CMD:
27390 			extract_funcp = ip_extract_msfilter;
27391 			break;
27392 
27393 		default:
27394 			ASSERT(0);
27395 		}
27396 
27397 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27398 		if (err != 0) {
27399 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27400 			return;
27401 		}
27402 
27403 		/*
27404 		 * All of the extraction functions return a refheld ipif.
27405 		 */
27406 		ASSERT(ci.ci_ipif != NULL);
27407 	}
27408 
27409 	if (!(ipip->ipi_flags & IPI_WR)) {
27410 		/*
27411 		 * A return value of EINPROGRESS means the ioctl is
27412 		 * either queued and waiting for some reason or has
27413 		 * already completed.
27414 		 */
27415 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27416 		    ci.ci_lifr);
27417 		if (ci.ci_ipif != NULL)
27418 			ipif_refrele(ci.ci_ipif);
27419 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27420 		return;
27421 	}
27422 
27423 	/*
27424 	 * If ipsq is non-null, we are already being called exclusively on an
27425 	 * ill but in the case of a failover in progress it is the "from" ill,
27426 	 *  rather than the "to" ill (which is the ill ptr passed in).
27427 	 * In order to ensure we are exclusive on both ILLs we rerun
27428 	 * ipsq_try_enter() here, ipsq's support recursive entry.
27429 	 */
27430 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27431 	ASSERT(ci.ci_ipif != NULL);
27432 
27433 	ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27434 	    NEW_OP, B_TRUE);
27435 
27436 	/*
27437 	 * Release the ipif so that ipif_down and friends that wait for
27438 	 * references to go away are not misled about the current ipif_refcnt
27439 	 * values. We are writer so we can access the ipif even after releasing
27440 	 * the ipif.
27441 	 */
27442 	ipif_refrele(ci.ci_ipif);
27443 	if (ipsq == NULL)
27444 		return;
27445 
27446 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27447 
27448 	/*
27449 	 * For most set ioctls that come here, this serves as a single point
27450 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27451 	 * be any new references to the ipif. This helps functions that go
27452 	 * through this path and end up trying to wait for the refcnts
27453 	 * associated with the ipif to go down to zero. Some exceptions are
27454 	 * Failover, Failback, and Groupname commands that operate on more than
27455 	 * just the ci.ci_ipif. These commands internally determine the
27456 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27457 	 * flags on that set. Another exception is the Removeif command that
27458 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27459 	 * ipif to operate on.
27460 	 */
27461 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27462 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27463 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27464 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27465 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27466 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27467 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27468 
27469 	/*
27470 	 * A return value of EINPROGRESS means the ioctl is
27471 	 * either queued and waiting for some reason or has
27472 	 * already completed.
27473 	 */
27474 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27475 
27476 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27477 
27478 	ipsq_exit(ipsq);
27479 }
27480 
27481 /*
27482  * Complete the ioctl. Typically ioctls use the mi package and need to
27483  * do mi_copyout/mi_copy_done.
27484  */
27485 void
27486 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27487 {
27488 	conn_t	*connp = NULL;
27489 
27490 	if (err == EINPROGRESS)
27491 		return;
27492 
27493 	if (CONN_Q(q)) {
27494 		connp = Q_TO_CONN(q);
27495 		ASSERT(connp->conn_ref >= 2);
27496 	}
27497 
27498 	switch (mode) {
27499 	case COPYOUT:
27500 		if (err == 0)
27501 			mi_copyout(q, mp);
27502 		else
27503 			mi_copy_done(q, mp, err);
27504 		break;
27505 
27506 	case NO_COPYOUT:
27507 		mi_copy_done(q, mp, err);
27508 		break;
27509 
27510 	default:
27511 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27512 		break;
27513 	}
27514 
27515 	/*
27516 	 * The refhold placed at the start of the ioctl is released here.
27517 	 */
27518 	if (connp != NULL)
27519 		CONN_OPER_PENDING_DONE(connp);
27520 
27521 	if (ipsq != NULL)
27522 		ipsq_current_finish(ipsq);
27523 }
27524 
27525 /*
27526  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27527  */
27528 /* ARGSUSED */
27529 void
27530 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27531 {
27532 	conn_t *connp = arg;
27533 	tcp_t	*tcp;
27534 
27535 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27536 	tcp = connp->conn_tcp;
27537 
27538 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27539 		freemsg(mp);
27540 	else
27541 		tcp_rput_other(tcp, mp);
27542 	CONN_OPER_PENDING_DONE(connp);
27543 }
27544 
27545 /* Called from ip_wput for all non data messages */
27546 /* ARGSUSED */
27547 void
27548 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27549 {
27550 	mblk_t		*mp1;
27551 	ire_t		*ire, *fake_ire;
27552 	ill_t		*ill;
27553 	struct iocblk	*iocp;
27554 	ip_ioctl_cmd_t	*ipip;
27555 	cred_t		*cr;
27556 	conn_t		*connp;
27557 	int		err;
27558 	nce_t		*nce;
27559 	ipif_t		*ipif;
27560 	ip_stack_t	*ipst;
27561 	char		*proto_str;
27562 
27563 	if (CONN_Q(q)) {
27564 		connp = Q_TO_CONN(q);
27565 		ipst = connp->conn_netstack->netstack_ip;
27566 	} else {
27567 		connp = NULL;
27568 		ipst = ILLQ_TO_IPST(q);
27569 	}
27570 
27571 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27572 
27573 	switch (DB_TYPE(mp)) {
27574 	case M_IOCTL:
27575 		/*
27576 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27577 		 * will arrange to copy in associated control structures.
27578 		 */
27579 		ip_sioctl_copyin_setup(q, mp);
27580 		return;
27581 	case M_IOCDATA:
27582 		/*
27583 		 * Ensure that this is associated with one of our trans-
27584 		 * parent ioctls.  If it's not ours, discard it if we're
27585 		 * running as a driver, or pass it on if we're a module.
27586 		 */
27587 		iocp = (struct iocblk *)mp->b_rptr;
27588 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27589 		if (ipip == NULL) {
27590 			if (q->q_next == NULL) {
27591 				goto nak;
27592 			} else {
27593 				putnext(q, mp);
27594 			}
27595 			return;
27596 		}
27597 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27598 			/*
27599 			 * the ioctl is one we recognise, but is not
27600 			 * consumed by IP as a module, pass M_IOCDATA
27601 			 * for processing downstream, but only for
27602 			 * common Streams ioctls.
27603 			 */
27604 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27605 				putnext(q, mp);
27606 				return;
27607 			} else {
27608 				goto nak;
27609 			}
27610 		}
27611 
27612 		/* IOCTL continuation following copyin or copyout. */
27613 		if (mi_copy_state(q, mp, NULL) == -1) {
27614 			/*
27615 			 * The copy operation failed.  mi_copy_state already
27616 			 * cleaned up, so we're out of here.
27617 			 */
27618 			return;
27619 		}
27620 		/*
27621 		 * If we just completed a copy in, we become writer and
27622 		 * continue processing in ip_sioctl_copyin_done.  If it
27623 		 * was a copy out, we call mi_copyout again.  If there is
27624 		 * nothing more to copy out, it will complete the IOCTL.
27625 		 */
27626 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27627 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27628 				mi_copy_done(q, mp, EPROTO);
27629 				return;
27630 			}
27631 			/*
27632 			 * Check for cases that need more copying.  A return
27633 			 * value of 0 means a second copyin has been started,
27634 			 * so we return; a return value of 1 means no more
27635 			 * copying is needed, so we continue.
27636 			 */
27637 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27638 			    MI_COPY_COUNT(mp) == 1) {
27639 				if (ip_copyin_msfilter(q, mp) == 0)
27640 					return;
27641 			}
27642 			/*
27643 			 * Refhold the conn, till the ioctl completes. This is
27644 			 * needed in case the ioctl ends up in the pending mp
27645 			 * list. Every mp in the ill_pending_mp list and
27646 			 * the ipsq_pending_mp must have a refhold on the conn
27647 			 * to resume processing. The refhold is released when
27648 			 * the ioctl completes. (normally or abnormally)
27649 			 * In all cases ip_ioctl_finish is called to finish
27650 			 * the ioctl.
27651 			 */
27652 			if (connp != NULL) {
27653 				/* This is not a reentry */
27654 				ASSERT(ipsq == NULL);
27655 				CONN_INC_REF(connp);
27656 			} else {
27657 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27658 					mi_copy_done(q, mp, EINVAL);
27659 					return;
27660 				}
27661 			}
27662 
27663 			ip_process_ioctl(ipsq, q, mp, ipip);
27664 
27665 		} else {
27666 			mi_copyout(q, mp);
27667 		}
27668 		return;
27669 nak:
27670 		iocp->ioc_error = EINVAL;
27671 		mp->b_datap->db_type = M_IOCNAK;
27672 		iocp->ioc_count = 0;
27673 		qreply(q, mp);
27674 		return;
27675 
27676 	case M_IOCNAK:
27677 		/*
27678 		 * The only way we could get here is if a resolver didn't like
27679 		 * an IOCTL we sent it.	 This shouldn't happen.
27680 		 */
27681 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27682 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27683 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27684 		freemsg(mp);
27685 		return;
27686 	case M_IOCACK:
27687 		/* /dev/ip shouldn't see this */
27688 		if (CONN_Q(q))
27689 			goto nak;
27690 
27691 		/* Finish socket ioctls passed through to ARP. */
27692 		ip_sioctl_iocack(q, mp);
27693 		return;
27694 	case M_FLUSH:
27695 		if (*mp->b_rptr & FLUSHW)
27696 			flushq(q, FLUSHALL);
27697 		if (q->q_next) {
27698 			putnext(q, mp);
27699 			return;
27700 		}
27701 		if (*mp->b_rptr & FLUSHR) {
27702 			*mp->b_rptr &= ~FLUSHW;
27703 			qreply(q, mp);
27704 			return;
27705 		}
27706 		freemsg(mp);
27707 		return;
27708 	case IRE_DB_REQ_TYPE:
27709 		if (connp == NULL) {
27710 			proto_str = "IRE_DB_REQ_TYPE";
27711 			goto protonak;
27712 		}
27713 		/* An Upper Level Protocol wants a copy of an IRE. */
27714 		ip_ire_req(q, mp);
27715 		return;
27716 	case M_CTL:
27717 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27718 			break;
27719 
27720 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27721 		    TUN_HELLO) {
27722 			ASSERT(connp != NULL);
27723 			connp->conn_flags |= IPCL_IPTUN;
27724 			freeb(mp);
27725 			return;
27726 		}
27727 
27728 		/* M_CTL messages are used by ARP to tell us things. */
27729 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27730 			break;
27731 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27732 		case AR_ENTRY_SQUERY:
27733 			ip_wput_ctl(q, mp);
27734 			return;
27735 		case AR_CLIENT_NOTIFY:
27736 			ip_arp_news(q, mp);
27737 			return;
27738 		case AR_DLPIOP_DONE:
27739 			ASSERT(q->q_next != NULL);
27740 			ill = (ill_t *)q->q_ptr;
27741 			/* qwriter_ip releases the refhold */
27742 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27743 			ill_refhold(ill);
27744 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27745 			return;
27746 		case AR_ARP_CLOSING:
27747 			/*
27748 			 * ARP (above us) is closing. If no ARP bringup is
27749 			 * currently pending, ack the message so that ARP
27750 			 * can complete its close. Also mark ill_arp_closing
27751 			 * so that new ARP bringups will fail. If any
27752 			 * ARP bringup is currently in progress, we will
27753 			 * ack this when the current ARP bringup completes.
27754 			 */
27755 			ASSERT(q->q_next != NULL);
27756 			ill = (ill_t *)q->q_ptr;
27757 			mutex_enter(&ill->ill_lock);
27758 			ill->ill_arp_closing = 1;
27759 			if (!ill->ill_arp_bringup_pending) {
27760 				mutex_exit(&ill->ill_lock);
27761 				qreply(q, mp);
27762 			} else {
27763 				mutex_exit(&ill->ill_lock);
27764 				freemsg(mp);
27765 			}
27766 			return;
27767 		case AR_ARP_EXTEND:
27768 			/*
27769 			 * The ARP module above us is capable of duplicate
27770 			 * address detection.  Old ATM drivers will not send
27771 			 * this message.
27772 			 */
27773 			ASSERT(q->q_next != NULL);
27774 			ill = (ill_t *)q->q_ptr;
27775 			ill->ill_arp_extend = B_TRUE;
27776 			freemsg(mp);
27777 			return;
27778 		default:
27779 			break;
27780 		}
27781 		break;
27782 	case M_PROTO:
27783 	case M_PCPROTO:
27784 		/*
27785 		 * The only PROTO messages we expect are ULP binds and
27786 		 * copies of option negotiation acknowledgements.
27787 		 */
27788 		switch (((union T_primitives *)mp->b_rptr)->type) {
27789 		case O_T_BIND_REQ:
27790 		case T_BIND_REQ: {
27791 			/* Request can get queued in bind */
27792 			if (connp == NULL) {
27793 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27794 				goto protonak;
27795 			}
27796 			/*
27797 			 * The transports except SCTP call ip_bind_{v4,v6}()
27798 			 * directly instead of a a putnext. SCTP doesn't
27799 			 * generate any T_BIND_REQ since it has its own
27800 			 * fanout data structures. However, ESP and AH
27801 			 * come in for regular binds; all other cases are
27802 			 * bind retries.
27803 			 */
27804 			ASSERT(!IPCL_IS_SCTP(connp));
27805 
27806 			/* Don't increment refcnt if this is a re-entry */
27807 			if (ipsq == NULL)
27808 				CONN_INC_REF(connp);
27809 
27810 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27811 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27812 			if (mp == NULL)
27813 				return;
27814 			if (IPCL_IS_TCP(connp)) {
27815 				/*
27816 				 * In the case of TCP endpoint we
27817 				 * come here only for bind retries
27818 				 */
27819 				ASSERT(ipsq != NULL);
27820 				CONN_INC_REF(connp);
27821 				SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
27822 				    ip_resume_tcp_bind, connp,
27823 				    SQ_FILL, SQTAG_BIND_RETRY);
27824 			} else if (IPCL_IS_UDP(connp)) {
27825 				/*
27826 				 * In the case of UDP endpoint we
27827 				 * come here only for bind retries
27828 				 */
27829 				ASSERT(ipsq != NULL);
27830 				udp_resume_bind(connp, mp);
27831 			} else if (IPCL_IS_RAWIP(connp)) {
27832 				/*
27833 				 * In the case of RAWIP endpoint we
27834 				 * come here only for bind retries
27835 				 */
27836 				ASSERT(ipsq != NULL);
27837 				rawip_resume_bind(connp, mp);
27838 			} else {
27839 				/* The case of AH and ESP */
27840 				qreply(q, mp);
27841 				CONN_OPER_PENDING_DONE(connp);
27842 			}
27843 			return;
27844 		}
27845 		case T_SVR4_OPTMGMT_REQ:
27846 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27847 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27848 
27849 			if (connp == NULL) {
27850 				proto_str = "T_SVR4_OPTMGMT_REQ";
27851 				goto protonak;
27852 			}
27853 
27854 			if (!snmpcom_req(q, mp, ip_snmp_set,
27855 			    ip_snmp_get, cr)) {
27856 				/*
27857 				 * Call svr4_optcom_req so that it can
27858 				 * generate the ack. We don't come here
27859 				 * if this operation is being restarted.
27860 				 * ip_restart_optmgmt will drop the conn ref.
27861 				 * In the case of ipsec option after the ipsec
27862 				 * load is complete conn_restart_ipsec_waiter
27863 				 * drops the conn ref.
27864 				 */
27865 				ASSERT(ipsq == NULL);
27866 				CONN_INC_REF(connp);
27867 				if (ip_check_for_ipsec_opt(q, mp))
27868 					return;
27869 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27870 				    B_FALSE);
27871 				if (err != EINPROGRESS) {
27872 					/* Operation is done */
27873 					CONN_OPER_PENDING_DONE(connp);
27874 				}
27875 			}
27876 			return;
27877 		case T_OPTMGMT_REQ:
27878 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27879 			/*
27880 			 * Note: No snmpcom_req support through new
27881 			 * T_OPTMGMT_REQ.
27882 			 * Call tpi_optcom_req so that it can
27883 			 * generate the ack.
27884 			 */
27885 			if (connp == NULL) {
27886 				proto_str = "T_OPTMGMT_REQ";
27887 				goto protonak;
27888 			}
27889 
27890 			ASSERT(ipsq == NULL);
27891 			/*
27892 			 * We don't come here for restart. ip_restart_optmgmt
27893 			 * will drop the conn ref. In the case of ipsec option
27894 			 * after the ipsec load is complete
27895 			 * conn_restart_ipsec_waiter drops the conn ref.
27896 			 */
27897 			CONN_INC_REF(connp);
27898 			if (ip_check_for_ipsec_opt(q, mp))
27899 				return;
27900 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27901 			if (err != EINPROGRESS) {
27902 				/* Operation is done */
27903 				CONN_OPER_PENDING_DONE(connp);
27904 			}
27905 			return;
27906 		case T_UNBIND_REQ:
27907 			if (connp == NULL) {
27908 				proto_str = "T_UNBIND_REQ";
27909 				goto protonak;
27910 			}
27911 			mp = ip_unbind(q, mp);
27912 			qreply(q, mp);
27913 			return;
27914 		default:
27915 			/*
27916 			 * Have to drop any DLPI messages coming down from
27917 			 * arp (such as an info_req which would cause ip
27918 			 * to receive an extra info_ack if it was passed
27919 			 * through.
27920 			 */
27921 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27922 			    (int)*(uint_t *)mp->b_rptr));
27923 			freemsg(mp);
27924 			return;
27925 		}
27926 		/* NOTREACHED */
27927 	case IRE_DB_TYPE: {
27928 		nce_t		*nce;
27929 		ill_t		*ill;
27930 		in6_addr_t	gw_addr_v6;
27931 
27932 
27933 		/*
27934 		 * This is a response back from a resolver.  It
27935 		 * consists of a message chain containing:
27936 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27937 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27938 		 * The LL_HDR_MBLK is the DLPI header to use to get
27939 		 * the attached packet, and subsequent ones for the
27940 		 * same destination, transmitted.
27941 		 */
27942 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27943 			break;
27944 		/*
27945 		 * First, check to make sure the resolution succeeded.
27946 		 * If it failed, the second mblk will be empty.
27947 		 * If it is, free the chain, dropping the packet.
27948 		 * (We must ire_delete the ire; that frees the ire mblk)
27949 		 * We're doing this now to support PVCs for ATM; it's
27950 		 * a partial xresolv implementation. When we fully implement
27951 		 * xresolv interfaces, instead of freeing everything here
27952 		 * we'll initiate neighbor discovery.
27953 		 *
27954 		 * For v4 (ARP and other external resolvers) the resolver
27955 		 * frees the message, so no check is needed. This check
27956 		 * is required, though, for a full xresolve implementation.
27957 		 * Including this code here now both shows how external
27958 		 * resolvers can NACK a resolution request using an
27959 		 * existing design that has no specific provisions for NACKs,
27960 		 * and also takes into account that the current non-ARP
27961 		 * external resolver has been coded to use this method of
27962 		 * NACKing for all IPv6 (xresolv) cases,
27963 		 * whether our xresolv implementation is complete or not.
27964 		 *
27965 		 */
27966 		ire = (ire_t *)mp->b_rptr;
27967 		ill = ire_to_ill(ire);
27968 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27969 		if (mp1->b_rptr == mp1->b_wptr) {
27970 			if (ire->ire_ipversion == IPV6_VERSION) {
27971 				/*
27972 				 * XRESOLV interface.
27973 				 */
27974 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27975 				mutex_enter(&ire->ire_lock);
27976 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27977 				mutex_exit(&ire->ire_lock);
27978 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27979 					nce = ndp_lookup_v6(ill,
27980 					    &ire->ire_addr_v6, B_FALSE);
27981 				} else {
27982 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27983 					    B_FALSE);
27984 				}
27985 				if (nce != NULL) {
27986 					nce_resolv_failed(nce);
27987 					ndp_delete(nce);
27988 					NCE_REFRELE(nce);
27989 				}
27990 			}
27991 			mp->b_cont = NULL;
27992 			freemsg(mp1);		/* frees the pkt as well */
27993 			ASSERT(ire->ire_nce == NULL);
27994 			ire_delete((ire_t *)mp->b_rptr);
27995 			return;
27996 		}
27997 
27998 		/*
27999 		 * Split them into IRE_MBLK and pkt and feed it into
28000 		 * ire_add_then_send. Then in ire_add_then_send
28001 		 * the IRE will be added, and then the packet will be
28002 		 * run back through ip_wput. This time it will make
28003 		 * it to the wire.
28004 		 */
28005 		mp->b_cont = NULL;
28006 		mp = mp1->b_cont;		/* now, mp points to pkt */
28007 		mp1->b_cont = NULL;
28008 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
28009 		if (ire->ire_ipversion == IPV6_VERSION) {
28010 			/*
28011 			 * XRESOLV interface. Find the nce and put a copy
28012 			 * of the dl_unitdata_req in nce_res_mp
28013 			 */
28014 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
28015 			mutex_enter(&ire->ire_lock);
28016 			gw_addr_v6 = ire->ire_gateway_addr_v6;
28017 			mutex_exit(&ire->ire_lock);
28018 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
28019 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
28020 				    B_FALSE);
28021 			} else {
28022 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
28023 			}
28024 			if (nce != NULL) {
28025 				/*
28026 				 * We have to protect nce_res_mp here
28027 				 * from being accessed by other threads
28028 				 * while we change the mblk pointer.
28029 				 * Other functions will also lock the nce when
28030 				 * accessing nce_res_mp.
28031 				 *
28032 				 * The reason we change the mblk pointer
28033 				 * here rather than copying the resolved address
28034 				 * into the template is that, unlike with
28035 				 * ethernet, we have no guarantee that the
28036 				 * resolved address length will be
28037 				 * smaller than or equal to the lla length
28038 				 * with which the template was allocated,
28039 				 * (for ethernet, they're equal)
28040 				 * so we have to use the actual resolved
28041 				 * address mblk - which holds the real
28042 				 * dl_unitdata_req with the resolved address.
28043 				 *
28044 				 * Doing this is the same behavior as was
28045 				 * previously used in the v4 ARP case.
28046 				 */
28047 				mutex_enter(&nce->nce_lock);
28048 				if (nce->nce_res_mp != NULL)
28049 					freemsg(nce->nce_res_mp);
28050 				nce->nce_res_mp = mp1;
28051 				mutex_exit(&nce->nce_lock);
28052 				/*
28053 				 * We do a fastpath probe here because
28054 				 * we have resolved the address without
28055 				 * using Neighbor Discovery.
28056 				 * In the non-XRESOLV v6 case, the fastpath
28057 				 * probe is done right after neighbor
28058 				 * discovery completes.
28059 				 */
28060 				if (nce->nce_res_mp != NULL) {
28061 					int res;
28062 					nce_fastpath_list_add(nce);
28063 					res = ill_fastpath_probe(ill,
28064 					    nce->nce_res_mp);
28065 					if (res != 0 && res != EAGAIN)
28066 						nce_fastpath_list_delete(nce);
28067 				}
28068 
28069 				ire_add_then_send(q, ire, mp);
28070 				/*
28071 				 * Now we have to clean out any packets
28072 				 * that may have been queued on the nce
28073 				 * while it was waiting for address resolution
28074 				 * to complete.
28075 				 */
28076 				mutex_enter(&nce->nce_lock);
28077 				mp1 = nce->nce_qd_mp;
28078 				nce->nce_qd_mp = NULL;
28079 				mutex_exit(&nce->nce_lock);
28080 				while (mp1 != NULL) {
28081 					mblk_t *nxt_mp;
28082 					queue_t *fwdq = NULL;
28083 					ill_t   *inbound_ill;
28084 					uint_t ifindex;
28085 
28086 					nxt_mp = mp1->b_next;
28087 					mp1->b_next = NULL;
28088 					/*
28089 					 * Retrieve ifindex stored in
28090 					 * ip_rput_data_v6()
28091 					 */
28092 					ifindex =
28093 					    (uint_t)(uintptr_t)mp1->b_prev;
28094 					inbound_ill =
28095 					    ill_lookup_on_ifindex(ifindex,
28096 					    B_TRUE, NULL, NULL, NULL,
28097 					    NULL, ipst);
28098 					mp1->b_prev = NULL;
28099 					if (inbound_ill != NULL)
28100 						fwdq = inbound_ill->ill_rq;
28101 
28102 					if (fwdq != NULL) {
28103 						put(fwdq, mp1);
28104 						ill_refrele(inbound_ill);
28105 					} else
28106 						put(WR(ill->ill_rq), mp1);
28107 					mp1 = nxt_mp;
28108 				}
28109 				NCE_REFRELE(nce);
28110 			} else {	/* nce is NULL; clean up */
28111 				ire_delete(ire);
28112 				freemsg(mp);
28113 				freemsg(mp1);
28114 				return;
28115 			}
28116 		} else {
28117 			nce_t *arpce;
28118 			/*
28119 			 * Link layer resolution succeeded. Recompute the
28120 			 * ire_nce.
28121 			 */
28122 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
28123 			if ((arpce = ndp_lookup_v4(ill,
28124 			    (ire->ire_gateway_addr != INADDR_ANY ?
28125 			    &ire->ire_gateway_addr : &ire->ire_addr),
28126 			    B_FALSE)) == NULL) {
28127 				freeb(ire->ire_mp);
28128 				freeb(mp1);
28129 				freemsg(mp);
28130 				return;
28131 			}
28132 			mutex_enter(&arpce->nce_lock);
28133 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28134 			if (arpce->nce_state == ND_REACHABLE) {
28135 				/*
28136 				 * Someone resolved this before us;
28137 				 * cleanup the res_mp. Since ire has
28138 				 * not been added yet, the call to ire_add_v4
28139 				 * from ire_add_then_send (when a dup is
28140 				 * detected) will clean up the ire.
28141 				 */
28142 				freeb(mp1);
28143 			} else {
28144 				ASSERT(arpce->nce_res_mp == NULL);
28145 				arpce->nce_res_mp = mp1;
28146 				arpce->nce_state = ND_REACHABLE;
28147 			}
28148 			mutex_exit(&arpce->nce_lock);
28149 			if (ire->ire_marks & IRE_MARK_NOADD) {
28150 				/*
28151 				 * this ire will not be added to the ire
28152 				 * cache table, so we can set the ire_nce
28153 				 * here, as there are no atomicity constraints.
28154 				 */
28155 				ire->ire_nce = arpce;
28156 				/*
28157 				 * We are associating this nce with the ire
28158 				 * so change the nce ref taken in
28159 				 * ndp_lookup_v4() from
28160 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28161 				 */
28162 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28163 			} else {
28164 				NCE_REFRELE(arpce);
28165 			}
28166 			ire_add_then_send(q, ire, mp);
28167 		}
28168 		return;	/* All is well, the packet has been sent. */
28169 	}
28170 	case IRE_ARPRESOLVE_TYPE: {
28171 
28172 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28173 			break;
28174 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28175 		mp->b_cont = NULL;
28176 		/*
28177 		 * First, check to make sure the resolution succeeded.
28178 		 * If it failed, the second mblk will be empty.
28179 		 */
28180 		if (mp1->b_rptr == mp1->b_wptr) {
28181 			/* cleanup  the incomplete ire, free queued packets */
28182 			freemsg(mp); /* fake ire */
28183 			freeb(mp1);  /* dl_unitdata response */
28184 			return;
28185 		}
28186 
28187 		/*
28188 		 * Update any incomplete nce_t found. We search the ctable
28189 		 * and find the nce from the ire->ire_nce because we need
28190 		 * to pass the ire to ip_xmit_v4 later, and can find both
28191 		 * ire and nce in one lookup.
28192 		 */
28193 		fake_ire = (ire_t *)mp->b_rptr;
28194 
28195 		/*
28196 		 * By the time we come back here from ARP the incomplete ire
28197 		 * created in ire_forward() could have been removed. We use
28198 		 * the parameters stored in the fake_ire to specify the real
28199 		 * ire as explicitly as possible. This avoids problems when
28200 		 * IPMP groups are configured as an ipif can 'float'
28201 		 * across several ill queues. We can be confident that the
28202 		 * the inability to find an ire is because it no longer exists.
28203 		 */
28204 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
28205 		    NULL, NULL, NULL, NULL, ipst);
28206 		if (ill == NULL) {
28207 			ip1dbg(("ill for incomplete ire vanished\n"));
28208 			freemsg(mp); /* fake ire */
28209 			freeb(mp1);  /* dl_unitdata response */
28210 			return;
28211 		}
28212 
28213 		/* Get the outgoing ipif */
28214 		mutex_enter(&ill->ill_lock);
28215 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28216 		if (ipif == NULL) {
28217 			mutex_exit(&ill->ill_lock);
28218 			ill_refrele(ill);
28219 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28220 			freemsg(mp); /* fake_ire */
28221 			freeb(mp1);  /* dl_unitdata response */
28222 			return;
28223 		}
28224 
28225 		ipif_refhold_locked(ipif);
28226 		mutex_exit(&ill->ill_lock);
28227 		ill_refrele(ill);
28228 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
28229 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
28230 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
28231 		ipif_refrele(ipif);
28232 		if (ire == NULL) {
28233 			/*
28234 			 * no ire was found; check if there is an nce
28235 			 * for this lookup; if it has no ire's pointing at it
28236 			 * cleanup.
28237 			 */
28238 			if ((nce = ndp_lookup_v4(q->q_ptr,
28239 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28240 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28241 			    B_FALSE)) != NULL) {
28242 				/*
28243 				 * cleanup:
28244 				 * We check for refcnt 2 (one for the nce
28245 				 * hash list + 1 for the ref taken by
28246 				 * ndp_lookup_v4) to check that there are
28247 				 * no ire's pointing at the nce.
28248 				 */
28249 				if (nce->nce_refcnt == 2)
28250 					ndp_delete(nce);
28251 				NCE_REFRELE(nce);
28252 			}
28253 			freeb(mp1);  /* dl_unitdata response */
28254 			freemsg(mp); /* fake ire */
28255 			return;
28256 		}
28257 		nce = ire->ire_nce;
28258 		DTRACE_PROBE2(ire__arpresolve__type,
28259 		    ire_t *, ire, nce_t *, nce);
28260 		ASSERT(nce->nce_state != ND_INITIAL);
28261 		mutex_enter(&nce->nce_lock);
28262 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28263 		if (nce->nce_state == ND_REACHABLE) {
28264 			/*
28265 			 * Someone resolved this before us;
28266 			 * our response is not needed any more.
28267 			 */
28268 			mutex_exit(&nce->nce_lock);
28269 			freeb(mp1);  /* dl_unitdata response */
28270 		} else {
28271 			ASSERT(nce->nce_res_mp == NULL);
28272 			nce->nce_res_mp = mp1;
28273 			nce->nce_state = ND_REACHABLE;
28274 			mutex_exit(&nce->nce_lock);
28275 			nce_fastpath(nce);
28276 		}
28277 		/*
28278 		 * The cached nce_t has been updated to be reachable;
28279 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
28280 		 */
28281 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28282 		freemsg(mp);
28283 		/*
28284 		 * send out queued packets.
28285 		 */
28286 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE, NULL);
28287 
28288 		IRE_REFRELE(ire);
28289 		return;
28290 	}
28291 	default:
28292 		break;
28293 	}
28294 	if (q->q_next) {
28295 		putnext(q, mp);
28296 	} else
28297 		freemsg(mp);
28298 	return;
28299 
28300 protonak:
28301 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28302 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28303 		qreply(q, mp);
28304 }
28305 
28306 /*
28307  * Process IP options in an outbound packet.  Modify the destination if there
28308  * is a source route option.
28309  * Returns non-zero if something fails in which case an ICMP error has been
28310  * sent and mp freed.
28311  */
28312 static int
28313 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28314     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28315 {
28316 	ipoptp_t	opts;
28317 	uchar_t		*opt;
28318 	uint8_t		optval;
28319 	uint8_t		optlen;
28320 	ipaddr_t	dst;
28321 	intptr_t	code = 0;
28322 	mblk_t		*mp;
28323 	ire_t		*ire = NULL;
28324 
28325 	ip2dbg(("ip_wput_options\n"));
28326 	mp = ipsec_mp;
28327 	if (mctl_present) {
28328 		mp = ipsec_mp->b_cont;
28329 	}
28330 
28331 	dst = ipha->ipha_dst;
28332 	for (optval = ipoptp_first(&opts, ipha);
28333 	    optval != IPOPT_EOL;
28334 	    optval = ipoptp_next(&opts)) {
28335 		opt = opts.ipoptp_cur;
28336 		optlen = opts.ipoptp_len;
28337 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28338 		    optval, optlen));
28339 		switch (optval) {
28340 			uint32_t off;
28341 		case IPOPT_SSRR:
28342 		case IPOPT_LSRR:
28343 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28344 				ip1dbg((
28345 				    "ip_wput_options: bad option offset\n"));
28346 				code = (char *)&opt[IPOPT_OLEN] -
28347 				    (char *)ipha;
28348 				goto param_prob;
28349 			}
28350 			off = opt[IPOPT_OFFSET];
28351 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28352 			    ntohl(dst)));
28353 			/*
28354 			 * For strict: verify that dst is directly
28355 			 * reachable.
28356 			 */
28357 			if (optval == IPOPT_SSRR) {
28358 				ire = ire_ftable_lookup(dst, 0, 0,
28359 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28360 				    MBLK_GETLABEL(mp),
28361 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28362 				if (ire == NULL) {
28363 					ip1dbg(("ip_wput_options: SSRR not"
28364 					    " directly reachable: 0x%x\n",
28365 					    ntohl(dst)));
28366 					goto bad_src_route;
28367 				}
28368 				ire_refrele(ire);
28369 			}
28370 			break;
28371 		case IPOPT_RR:
28372 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28373 				ip1dbg((
28374 				    "ip_wput_options: bad option offset\n"));
28375 				code = (char *)&opt[IPOPT_OLEN] -
28376 				    (char *)ipha;
28377 				goto param_prob;
28378 			}
28379 			break;
28380 		case IPOPT_TS:
28381 			/*
28382 			 * Verify that length >=5 and that there is either
28383 			 * room for another timestamp or that the overflow
28384 			 * counter is not maxed out.
28385 			 */
28386 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28387 			if (optlen < IPOPT_MINLEN_IT) {
28388 				goto param_prob;
28389 			}
28390 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28391 				ip1dbg((
28392 				    "ip_wput_options: bad option offset\n"));
28393 				code = (char *)&opt[IPOPT_OFFSET] -
28394 				    (char *)ipha;
28395 				goto param_prob;
28396 			}
28397 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28398 			case IPOPT_TS_TSONLY:
28399 				off = IPOPT_TS_TIMELEN;
28400 				break;
28401 			case IPOPT_TS_TSANDADDR:
28402 			case IPOPT_TS_PRESPEC:
28403 			case IPOPT_TS_PRESPEC_RFC791:
28404 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28405 				break;
28406 			default:
28407 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28408 				    (char *)ipha;
28409 				goto param_prob;
28410 			}
28411 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28412 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28413 				/*
28414 				 * No room and the overflow counter is 15
28415 				 * already.
28416 				 */
28417 				goto param_prob;
28418 			}
28419 			break;
28420 		}
28421 	}
28422 
28423 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28424 		return (0);
28425 
28426 	ip1dbg(("ip_wput_options: error processing IP options."));
28427 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28428 
28429 param_prob:
28430 	/*
28431 	 * Since ip_wput() isn't close to finished, we fill
28432 	 * in enough of the header for credible error reporting.
28433 	 */
28434 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28435 		/* Failed */
28436 		freemsg(ipsec_mp);
28437 		return (-1);
28438 	}
28439 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28440 	return (-1);
28441 
28442 bad_src_route:
28443 	/*
28444 	 * Since ip_wput() isn't close to finished, we fill
28445 	 * in enough of the header for credible error reporting.
28446 	 */
28447 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28448 		/* Failed */
28449 		freemsg(ipsec_mp);
28450 		return (-1);
28451 	}
28452 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28453 	return (-1);
28454 }
28455 
28456 /*
28457  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28458  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28459  * thru /etc/system.
28460  */
28461 #define	CONN_MAXDRAINCNT	64
28462 
28463 static void
28464 conn_drain_init(ip_stack_t *ipst)
28465 {
28466 	int i;
28467 
28468 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28469 
28470 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28471 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28472 		/*
28473 		 * Default value of the number of drainers is the
28474 		 * number of cpus, subject to maximum of 8 drainers.
28475 		 */
28476 		if (boot_max_ncpus != -1)
28477 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28478 		else
28479 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28480 	}
28481 
28482 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28483 	    sizeof (idl_t), KM_SLEEP);
28484 
28485 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28486 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28487 		    MUTEX_DEFAULT, NULL);
28488 	}
28489 }
28490 
28491 static void
28492 conn_drain_fini(ip_stack_t *ipst)
28493 {
28494 	int i;
28495 
28496 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28497 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28498 	kmem_free(ipst->ips_conn_drain_list,
28499 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28500 	ipst->ips_conn_drain_list = NULL;
28501 }
28502 
28503 /*
28504  * Note: For an overview of how flowcontrol is handled in IP please see the
28505  * IP Flowcontrol notes at the top of this file.
28506  *
28507  * Flow control has blocked us from proceeding. Insert the given conn in one
28508  * of the conn drain lists. These conn wq's will be qenabled later on when
28509  * STREAMS flow control does a backenable. conn_walk_drain will enable
28510  * the first conn in each of these drain lists. Each of these qenabled conns
28511  * in turn enables the next in the list, after it runs, or when it closes,
28512  * thus sustaining the drain process.
28513  *
28514  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28515  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28516  * running at any time, on a given conn, since there can be only 1 service proc
28517  * running on a queue at any time.
28518  */
28519 void
28520 conn_drain_insert(conn_t *connp)
28521 {
28522 	idl_t	*idl;
28523 	uint_t	index;
28524 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28525 
28526 	mutex_enter(&connp->conn_lock);
28527 	if (connp->conn_state_flags & CONN_CLOSING) {
28528 		/*
28529 		 * The conn is closing as a result of which CONN_CLOSING
28530 		 * is set. Return.
28531 		 */
28532 		mutex_exit(&connp->conn_lock);
28533 		return;
28534 	} else if (connp->conn_idl == NULL) {
28535 		/*
28536 		 * Assign the next drain list round robin. We dont' use
28537 		 * a lock, and thus it may not be strictly round robin.
28538 		 * Atomicity of load/stores is enough to make sure that
28539 		 * conn_drain_list_index is always within bounds.
28540 		 */
28541 		index = ipst->ips_conn_drain_list_index;
28542 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28543 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28544 		index++;
28545 		if (index == ipst->ips_conn_drain_list_cnt)
28546 			index = 0;
28547 		ipst->ips_conn_drain_list_index = index;
28548 	}
28549 	mutex_exit(&connp->conn_lock);
28550 
28551 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28552 	if ((connp->conn_drain_prev != NULL) ||
28553 	    (connp->conn_state_flags & CONN_CLOSING)) {
28554 		/*
28555 		 * The conn is already in the drain list, OR
28556 		 * the conn is closing. We need to check again for
28557 		 * the closing case again since close can happen
28558 		 * after we drop the conn_lock, and before we
28559 		 * acquire the CONN_DRAIN_LIST_LOCK.
28560 		 */
28561 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28562 		return;
28563 	} else {
28564 		idl = connp->conn_idl;
28565 	}
28566 
28567 	/*
28568 	 * The conn is not in the drain list. Insert it at the
28569 	 * tail of the drain list. The drain list is circular
28570 	 * and doubly linked. idl_conn points to the 1st element
28571 	 * in the list.
28572 	 */
28573 	if (idl->idl_conn == NULL) {
28574 		idl->idl_conn = connp;
28575 		connp->conn_drain_next = connp;
28576 		connp->conn_drain_prev = connp;
28577 	} else {
28578 		conn_t *head = idl->idl_conn;
28579 
28580 		connp->conn_drain_next = head;
28581 		connp->conn_drain_prev = head->conn_drain_prev;
28582 		head->conn_drain_prev->conn_drain_next = connp;
28583 		head->conn_drain_prev = connp;
28584 	}
28585 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28586 }
28587 
28588 /*
28589  * This conn is closing, and we are called from ip_close. OR
28590  * This conn has been serviced by ip_wsrv, and we need to do the tail
28591  * processing.
28592  * If this conn is part of the drain list, we may need to sustain the drain
28593  * process by qenabling the next conn in the drain list. We may also need to
28594  * remove this conn from the list, if it is done.
28595  */
28596 static void
28597 conn_drain_tail(conn_t *connp, boolean_t closing)
28598 {
28599 	idl_t *idl;
28600 
28601 	/*
28602 	 * connp->conn_idl is stable at this point, and no lock is needed
28603 	 * to check it. If we are called from ip_close, close has already
28604 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28605 	 * called us only because conn_idl is non-null. If we are called thru
28606 	 * service, conn_idl could be null, but it cannot change because
28607 	 * service is single-threaded per queue, and there cannot be another
28608 	 * instance of service trying to call conn_drain_insert on this conn
28609 	 * now.
28610 	 */
28611 	ASSERT(!closing || (connp->conn_idl != NULL));
28612 
28613 	/*
28614 	 * If connp->conn_idl is null, the conn has not been inserted into any
28615 	 * drain list even once since creation of the conn. Just return.
28616 	 */
28617 	if (connp->conn_idl == NULL)
28618 		return;
28619 
28620 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28621 
28622 	if (connp->conn_drain_prev == NULL) {
28623 		/* This conn is currently not in the drain list.  */
28624 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28625 		return;
28626 	}
28627 	idl = connp->conn_idl;
28628 	if (idl->idl_conn_draining == connp) {
28629 		/*
28630 		 * This conn is the current drainer. If this is the last conn
28631 		 * in the drain list, we need to do more checks, in the 'if'
28632 		 * below. Otherwwise we need to just qenable the next conn,
28633 		 * to sustain the draining, and is handled in the 'else'
28634 		 * below.
28635 		 */
28636 		if (connp->conn_drain_next == idl->idl_conn) {
28637 			/*
28638 			 * This conn is the last in this list. This round
28639 			 * of draining is complete. If idl_repeat is set,
28640 			 * it means another flow enabling has happened from
28641 			 * the driver/streams and we need to another round
28642 			 * of draining.
28643 			 * If there are more than 2 conns in the drain list,
28644 			 * do a left rotate by 1, so that all conns except the
28645 			 * conn at the head move towards the head by 1, and the
28646 			 * the conn at the head goes to the tail. This attempts
28647 			 * a more even share for all queues that are being
28648 			 * drained.
28649 			 */
28650 			if ((connp->conn_drain_next != connp) &&
28651 			    (idl->idl_conn->conn_drain_next != connp)) {
28652 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28653 			}
28654 			if (idl->idl_repeat) {
28655 				qenable(idl->idl_conn->conn_wq);
28656 				idl->idl_conn_draining = idl->idl_conn;
28657 				idl->idl_repeat = 0;
28658 			} else {
28659 				idl->idl_conn_draining = NULL;
28660 			}
28661 		} else {
28662 			/*
28663 			 * If the next queue that we are now qenable'ing,
28664 			 * is closing, it will remove itself from this list
28665 			 * and qenable the subsequent queue in ip_close().
28666 			 * Serialization is acheived thru idl_lock.
28667 			 */
28668 			qenable(connp->conn_drain_next->conn_wq);
28669 			idl->idl_conn_draining = connp->conn_drain_next;
28670 		}
28671 	}
28672 	if (!connp->conn_did_putbq || closing) {
28673 		/*
28674 		 * Remove ourself from the drain list, if we did not do
28675 		 * a putbq, or if the conn is closing.
28676 		 * Note: It is possible that q->q_first is non-null. It means
28677 		 * that these messages landed after we did a enableok() in
28678 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28679 		 * service them.
28680 		 */
28681 		if (connp->conn_drain_next == connp) {
28682 			/* Singleton in the list */
28683 			ASSERT(connp->conn_drain_prev == connp);
28684 			idl->idl_conn = NULL;
28685 			idl->idl_conn_draining = NULL;
28686 		} else {
28687 			connp->conn_drain_prev->conn_drain_next =
28688 			    connp->conn_drain_next;
28689 			connp->conn_drain_next->conn_drain_prev =
28690 			    connp->conn_drain_prev;
28691 			if (idl->idl_conn == connp)
28692 				idl->idl_conn = connp->conn_drain_next;
28693 			ASSERT(idl->idl_conn_draining != connp);
28694 
28695 		}
28696 		connp->conn_drain_next = NULL;
28697 		connp->conn_drain_prev = NULL;
28698 	}
28699 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28700 }
28701 
28702 /*
28703  * Write service routine. Shared perimeter entry point.
28704  * ip_wsrv can be called in any of the following ways.
28705  * 1. The device queue's messages has fallen below the low water mark
28706  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28707  *    the drain lists and backenable the first conn in each list.
28708  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28709  *    qenabled non-tcp upper layers. We start dequeing messages and call
28710  *    ip_wput for each message.
28711  */
28712 
28713 void
28714 ip_wsrv(queue_t *q)
28715 {
28716 	conn_t	*connp;
28717 	ill_t	*ill;
28718 	mblk_t	*mp;
28719 
28720 	if (q->q_next) {
28721 		ill = (ill_t *)q->q_ptr;
28722 		if (ill->ill_state_flags == 0) {
28723 			/*
28724 			 * The device flow control has opened up.
28725 			 * Walk through conn drain lists and qenable the
28726 			 * first conn in each list. This makes sense only
28727 			 * if the stream is fully plumbed and setup.
28728 			 * Hence the if check above.
28729 			 */
28730 			ip1dbg(("ip_wsrv: walking\n"));
28731 			conn_walk_drain(ill->ill_ipst);
28732 		}
28733 		return;
28734 	}
28735 
28736 	connp = Q_TO_CONN(q);
28737 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28738 
28739 	/*
28740 	 * 1. Set conn_draining flag to signal that service is active.
28741 	 *
28742 	 * 2. ip_output determines whether it has been called from service,
28743 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28744 	 *    has been called from service.
28745 	 *
28746 	 * 3. Message ordering is preserved by the following logic.
28747 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28748 	 *    the message at the tail, if conn_draining is set (i.e. service
28749 	 *    is running) or if q->q_first is non-null.
28750 	 *
28751 	 *    ii. If ip_output is called from service, and if ip_output cannot
28752 	 *    putnext due to flow control, it does a putbq.
28753 	 *
28754 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28755 	 *    (causing an infinite loop).
28756 	 */
28757 	ASSERT(!connp->conn_did_putbq);
28758 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28759 		connp->conn_draining = 1;
28760 		noenable(q);
28761 		while ((mp = getq(q)) != NULL) {
28762 			ASSERT(CONN_Q(q));
28763 
28764 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28765 			if (connp->conn_did_putbq) {
28766 				/* ip_wput did a putbq */
28767 				break;
28768 			}
28769 		}
28770 		/*
28771 		 * At this point, a thread coming down from top, calling
28772 		 * ip_wput, may end up queueing the message. We have not yet
28773 		 * enabled the queue, so ip_wsrv won't be called again.
28774 		 * To avoid this race, check q->q_first again (in the loop)
28775 		 * If the other thread queued the message before we call
28776 		 * enableok(), we will catch it in the q->q_first check.
28777 		 * If the other thread queues the message after we call
28778 		 * enableok(), ip_wsrv will be called again by STREAMS.
28779 		 */
28780 		connp->conn_draining = 0;
28781 		enableok(q);
28782 	}
28783 
28784 	/* Enable the next conn for draining */
28785 	conn_drain_tail(connp, B_FALSE);
28786 
28787 	connp->conn_did_putbq = 0;
28788 }
28789 
28790 /*
28791  * Callback to disable flow control in IP.
28792  *
28793  * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
28794  * is enabled.
28795  *
28796  * When MAC_TX() is not able to send any more packets, dld sets its queue
28797  * to QFULL and enable the STREAMS flow control. Later, when the underlying
28798  * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
28799  * function and wakes up corresponding mac worker threads, which in turn
28800  * calls this callback function, and disables flow control.
28801  */
28802 /* ARGSUSED */
28803 void
28804 ill_flow_enable(void *ill, ip_mac_tx_cookie_t cookie)
28805 {
28806 	qenable(((ill_t *)ill)->ill_wq);
28807 }
28808 
28809 /*
28810  * Walk the list of all conn's calling the function provided with the
28811  * specified argument for each.	 Note that this only walks conn's that
28812  * have been bound.
28813  * Applies to both IPv4 and IPv6.
28814  */
28815 static void
28816 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28817 {
28818 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28819 	    ipst->ips_ipcl_udp_fanout_size,
28820 	    func, arg, zoneid);
28821 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28822 	    ipst->ips_ipcl_conn_fanout_size,
28823 	    func, arg, zoneid);
28824 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28825 	    ipst->ips_ipcl_bind_fanout_size,
28826 	    func, arg, zoneid);
28827 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28828 	    IPPROTO_MAX, func, arg, zoneid);
28829 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28830 	    IPPROTO_MAX, func, arg, zoneid);
28831 }
28832 
28833 /*
28834  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28835  * of conns that need to be drained, check if drain is already in progress.
28836  * If so set the idl_repeat bit, indicating that the last conn in the list
28837  * needs to reinitiate the drain once again, for the list. If drain is not
28838  * in progress for the list, initiate the draining, by qenabling the 1st
28839  * conn in the list. The drain is self-sustaining, each qenabled conn will
28840  * in turn qenable the next conn, when it is done/blocked/closing.
28841  */
28842 static void
28843 conn_walk_drain(ip_stack_t *ipst)
28844 {
28845 	int i;
28846 	idl_t *idl;
28847 
28848 	IP_STAT(ipst, ip_conn_walk_drain);
28849 
28850 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28851 		idl = &ipst->ips_conn_drain_list[i];
28852 		mutex_enter(&idl->idl_lock);
28853 		if (idl->idl_conn == NULL) {
28854 			mutex_exit(&idl->idl_lock);
28855 			continue;
28856 		}
28857 		/*
28858 		 * If this list is not being drained currently by
28859 		 * an ip_wsrv thread, start the process.
28860 		 */
28861 		if (idl->idl_conn_draining == NULL) {
28862 			ASSERT(idl->idl_repeat == 0);
28863 			qenable(idl->idl_conn->conn_wq);
28864 			idl->idl_conn_draining = idl->idl_conn;
28865 		} else {
28866 			idl->idl_repeat = 1;
28867 		}
28868 		mutex_exit(&idl->idl_lock);
28869 	}
28870 }
28871 
28872 /*
28873  * Walk an conn hash table of `count' buckets, calling func for each entry.
28874  */
28875 static void
28876 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28877     zoneid_t zoneid)
28878 {
28879 	conn_t	*connp;
28880 
28881 	while (count-- > 0) {
28882 		mutex_enter(&connfp->connf_lock);
28883 		for (connp = connfp->connf_head; connp != NULL;
28884 		    connp = connp->conn_next) {
28885 			if (zoneid == GLOBAL_ZONEID ||
28886 			    zoneid == connp->conn_zoneid) {
28887 				CONN_INC_REF(connp);
28888 				mutex_exit(&connfp->connf_lock);
28889 				(*func)(connp, arg);
28890 				mutex_enter(&connfp->connf_lock);
28891 				CONN_DEC_REF(connp);
28892 			}
28893 		}
28894 		mutex_exit(&connfp->connf_lock);
28895 		connfp++;
28896 	}
28897 }
28898 
28899 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28900 static void
28901 conn_report1(conn_t *connp, void *mp)
28902 {
28903 	char	buf1[INET6_ADDRSTRLEN];
28904 	char	buf2[INET6_ADDRSTRLEN];
28905 	uint_t	print_len, buf_len;
28906 
28907 	ASSERT(connp != NULL);
28908 
28909 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28910 	if (buf_len <= 0)
28911 		return;
28912 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28913 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28914 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28915 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28916 	    "%5d %s/%05d %s/%05d\n",
28917 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28918 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28919 	    buf1, connp->conn_lport,
28920 	    buf2, connp->conn_fport);
28921 	if (print_len < buf_len) {
28922 		((mblk_t *)mp)->b_wptr += print_len;
28923 	} else {
28924 		((mblk_t *)mp)->b_wptr += buf_len;
28925 	}
28926 }
28927 
28928 /*
28929  * Named Dispatch routine to produce a formatted report on all conns
28930  * that are listed in one of the fanout tables.
28931  * This report is accessed by using the ndd utility to "get" ND variable
28932  * "ip_conn_status".
28933  */
28934 /* ARGSUSED */
28935 static int
28936 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28937 {
28938 	conn_t *connp = Q_TO_CONN(q);
28939 
28940 	(void) mi_mpprintf(mp,
28941 	    "CONN      " MI_COL_HDRPAD_STR
28942 	    "rfq      " MI_COL_HDRPAD_STR
28943 	    "stq      " MI_COL_HDRPAD_STR
28944 	    " zone local                 remote");
28945 
28946 	/*
28947 	 * Because of the ndd constraint, at most we can have 64K buffer
28948 	 * to put in all conn info.  So to be more efficient, just
28949 	 * allocate a 64K buffer here, assuming we need that large buffer.
28950 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28951 	 */
28952 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28953 		/* The following may work even if we cannot get a large buf. */
28954 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28955 		return (0);
28956 	}
28957 
28958 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28959 	    connp->conn_netstack->netstack_ip);
28960 	return (0);
28961 }
28962 
28963 /*
28964  * Determine if the ill and multicast aspects of that packets
28965  * "matches" the conn.
28966  */
28967 boolean_t
28968 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28969     zoneid_t zoneid)
28970 {
28971 	ill_t *in_ill;
28972 	boolean_t found;
28973 	ipif_t *ipif;
28974 	ire_t *ire;
28975 	ipaddr_t dst, src;
28976 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28977 
28978 	dst = ipha->ipha_dst;
28979 	src = ipha->ipha_src;
28980 
28981 	/*
28982 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28983 	 * unicast, broadcast and multicast reception to
28984 	 * conn_incoming_ill. conn_wantpacket itself is called
28985 	 * only for BROADCAST and multicast.
28986 	 *
28987 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28988 	 *    is part of a group. Hence, we should be receiving
28989 	 *    just one copy of broadcast for the whole group.
28990 	 *    Thus, if it is part of the group the packet could
28991 	 *    come on any ill of the group and hence we need a
28992 	 *    match on the group. Otherwise, match on ill should
28993 	 *    be sufficient.
28994 	 *
28995 	 * 2) ip_rput does not suppress duplicate multicast packets.
28996 	 *    If there are two interfaces in a ill group and we have
28997 	 *    2 applications (conns) joined a multicast group G on
28998 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28999 	 *    will give us two packets because we join G on both the
29000 	 *    interfaces rather than nominating just one interface
29001 	 *    for receiving multicast like broadcast above. So,
29002 	 *    we have to call ilg_lookup_ill to filter out duplicate
29003 	 *    copies, if ill is part of a group.
29004 	 */
29005 	in_ill = connp->conn_incoming_ill;
29006 	if (in_ill != NULL) {
29007 		if (in_ill->ill_group == NULL) {
29008 			if (in_ill != ill)
29009 				return (B_FALSE);
29010 		} else if (in_ill->ill_group != ill->ill_group) {
29011 			return (B_FALSE);
29012 		}
29013 	}
29014 
29015 	if (!CLASSD(dst)) {
29016 		if (IPCL_ZONE_MATCH(connp, zoneid))
29017 			return (B_TRUE);
29018 		/*
29019 		 * The conn is in a different zone; we need to check that this
29020 		 * broadcast address is configured in the application's zone and
29021 		 * on one ill in the group.
29022 		 */
29023 		ipif = ipif_get_next_ipif(NULL, ill);
29024 		if (ipif == NULL)
29025 			return (B_FALSE);
29026 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
29027 		    connp->conn_zoneid, NULL,
29028 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
29029 		ipif_refrele(ipif);
29030 		if (ire != NULL) {
29031 			ire_refrele(ire);
29032 			return (B_TRUE);
29033 		} else {
29034 			return (B_FALSE);
29035 		}
29036 	}
29037 
29038 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
29039 	    connp->conn_zoneid == zoneid) {
29040 		/*
29041 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
29042 		 * disabled, therefore we don't dispatch the multicast packet to
29043 		 * the sending zone.
29044 		 */
29045 		return (B_FALSE);
29046 	}
29047 
29048 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
29049 		/*
29050 		 * Multicast packet on the loopback interface: we only match
29051 		 * conns who joined the group in the specified zone.
29052 		 */
29053 		return (B_FALSE);
29054 	}
29055 
29056 	if (connp->conn_multi_router) {
29057 		/* multicast packet and multicast router socket: send up */
29058 		return (B_TRUE);
29059 	}
29060 
29061 	mutex_enter(&connp->conn_lock);
29062 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
29063 	mutex_exit(&connp->conn_lock);
29064 	return (found);
29065 }
29066 
29067 /*
29068  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
29069  */
29070 /* ARGSUSED */
29071 static void
29072 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
29073 {
29074 	ill_t *ill = (ill_t *)q->q_ptr;
29075 	mblk_t	*mp1, *mp2;
29076 	ipif_t  *ipif;
29077 	int err = 0;
29078 	conn_t *connp = NULL;
29079 	ipsq_t	*ipsq;
29080 	arc_t	*arc;
29081 
29082 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
29083 
29084 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
29085 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
29086 
29087 	ASSERT(IAM_WRITER_ILL(ill));
29088 	mp2 = mp->b_cont;
29089 	mp->b_cont = NULL;
29090 
29091 	/*
29092 	 * We have now received the arp bringup completion message
29093 	 * from ARP. Mark the arp bringup as done. Also if the arp
29094 	 * stream has already started closing, send up the AR_ARP_CLOSING
29095 	 * ack now since ARP is waiting in close for this ack.
29096 	 */
29097 	mutex_enter(&ill->ill_lock);
29098 	ill->ill_arp_bringup_pending = 0;
29099 	if (ill->ill_arp_closing) {
29100 		mutex_exit(&ill->ill_lock);
29101 		/* Let's reuse the mp for sending the ack */
29102 		arc = (arc_t *)mp->b_rptr;
29103 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
29104 		arc->arc_cmd = AR_ARP_CLOSING;
29105 		qreply(q, mp);
29106 	} else {
29107 		mutex_exit(&ill->ill_lock);
29108 		freeb(mp);
29109 	}
29110 
29111 	ipsq = ill->ill_phyint->phyint_ipsq;
29112 	ipif = ipsq->ipsq_pending_ipif;
29113 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
29114 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
29115 	if (mp1 == NULL) {
29116 		/* bringup was aborted by the user */
29117 		freemsg(mp2);
29118 		return;
29119 	}
29120 
29121 	/*
29122 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
29123 	 * must have an associated conn_t.  Otherwise, we're bringing this
29124 	 * interface back up as part of handling an asynchronous event (e.g.,
29125 	 * physical address change).
29126 	 */
29127 	if (ipsq->ipsq_current_ioctl != 0) {
29128 		ASSERT(connp != NULL);
29129 		q = CONNP_TO_WQ(connp);
29130 	} else {
29131 		ASSERT(connp == NULL);
29132 		q = ill->ill_rq;
29133 	}
29134 
29135 	/*
29136 	 * If the DL_BIND_REQ fails, it is noted
29137 	 * in arc_name_offset.
29138 	 */
29139 	err = *((int *)mp2->b_rptr);
29140 	if (err == 0) {
29141 		if (ipif->ipif_isv6) {
29142 			if ((err = ipif_up_done_v6(ipif)) != 0)
29143 				ip0dbg(("ip_arp_done: init failed\n"));
29144 		} else {
29145 			if ((err = ipif_up_done(ipif)) != 0)
29146 				ip0dbg(("ip_arp_done: init failed\n"));
29147 		}
29148 	} else {
29149 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29150 	}
29151 
29152 	freemsg(mp2);
29153 
29154 	if ((err == 0) && (ill->ill_up_ipifs)) {
29155 		err = ill_up_ipifs(ill, q, mp1);
29156 		if (err == EINPROGRESS)
29157 			return;
29158 	}
29159 
29160 	if (ill->ill_up_ipifs)
29161 		ill_group_cleanup(ill);
29162 
29163 	/*
29164 	 * The operation must complete without EINPROGRESS since
29165 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29166 	 * Otherwise, the operation will be stuck forever in the ipsq.
29167 	 */
29168 	ASSERT(err != EINPROGRESS);
29169 	if (ipsq->ipsq_current_ioctl != 0)
29170 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29171 	else
29172 		ipsq_current_finish(ipsq);
29173 }
29174 
29175 /* Allocate the private structure */
29176 static int
29177 ip_priv_alloc(void **bufp)
29178 {
29179 	void	*buf;
29180 
29181 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29182 		return (ENOMEM);
29183 
29184 	*bufp = buf;
29185 	return (0);
29186 }
29187 
29188 /* Function to delete the private structure */
29189 void
29190 ip_priv_free(void *buf)
29191 {
29192 	ASSERT(buf != NULL);
29193 	kmem_free(buf, sizeof (ip_priv_t));
29194 }
29195 
29196 /*
29197  * The entry point for IPPF processing.
29198  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29199  * routine just returns.
29200  *
29201  * When called, ip_process generates an ipp_packet_t structure
29202  * which holds the state information for this packet and invokes the
29203  * the classifier (via ipp_packet_process). The classification, depending on
29204  * configured filters, results in a list of actions for this packet. Invoking
29205  * an action may cause the packet to be dropped, in which case the resulting
29206  * mblk (*mpp) is NULL. proc indicates the callout position for
29207  * this packet and ill_index is the interface this packet on or will leave
29208  * on (inbound and outbound resp.).
29209  */
29210 void
29211 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29212 {
29213 	mblk_t		*mp;
29214 	ip_priv_t	*priv;
29215 	ipp_action_id_t	aid;
29216 	int		rc = 0;
29217 	ipp_packet_t	*pp;
29218 #define	IP_CLASS	"ip"
29219 
29220 	/* If the classifier is not loaded, return  */
29221 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29222 		return;
29223 	}
29224 
29225 	mp = *mpp;
29226 	ASSERT(mp != NULL);
29227 
29228 	/* Allocate the packet structure */
29229 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29230 	if (rc != 0) {
29231 		*mpp = NULL;
29232 		freemsg(mp);
29233 		return;
29234 	}
29235 
29236 	/* Allocate the private structure */
29237 	rc = ip_priv_alloc((void **)&priv);
29238 	if (rc != 0) {
29239 		*mpp = NULL;
29240 		freemsg(mp);
29241 		ipp_packet_free(pp);
29242 		return;
29243 	}
29244 	priv->proc = proc;
29245 	priv->ill_index = ill_index;
29246 	ipp_packet_set_private(pp, priv, ip_priv_free);
29247 	ipp_packet_set_data(pp, mp);
29248 
29249 	/* Invoke the classifier */
29250 	rc = ipp_packet_process(&pp);
29251 	if (pp != NULL) {
29252 		mp = ipp_packet_get_data(pp);
29253 		ipp_packet_free(pp);
29254 		if (rc != 0) {
29255 			freemsg(mp);
29256 			*mpp = NULL;
29257 		}
29258 	} else {
29259 		*mpp = NULL;
29260 	}
29261 #undef	IP_CLASS
29262 }
29263 
29264 /*
29265  * Propagate a multicast group membership operation (add/drop) on
29266  * all the interfaces crossed by the related multirt routes.
29267  * The call is considered successful if the operation succeeds
29268  * on at least one interface.
29269  */
29270 static int
29271 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29272     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29273     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29274     mblk_t *first_mp)
29275 {
29276 	ire_t		*ire_gw;
29277 	irb_t		*irb;
29278 	int		error = 0;
29279 	opt_restart_t	*or;
29280 	ip_stack_t	*ipst = ire->ire_ipst;
29281 
29282 	irb = ire->ire_bucket;
29283 	ASSERT(irb != NULL);
29284 
29285 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29286 
29287 	or = (opt_restart_t *)first_mp->b_rptr;
29288 	IRB_REFHOLD(irb);
29289 	for (; ire != NULL; ire = ire->ire_next) {
29290 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29291 			continue;
29292 		if (ire->ire_addr != group)
29293 			continue;
29294 
29295 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29296 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29297 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29298 		/* No resolver exists for the gateway; skip this ire. */
29299 		if (ire_gw == NULL)
29300 			continue;
29301 
29302 		/*
29303 		 * This function can return EINPROGRESS. If so the operation
29304 		 * will be restarted from ip_restart_optmgmt which will
29305 		 * call ip_opt_set and option processing will restart for
29306 		 * this option. So we may end up calling 'fn' more than once.
29307 		 * This requires that 'fn' is idempotent except for the
29308 		 * return value. The operation is considered a success if
29309 		 * it succeeds at least once on any one interface.
29310 		 */
29311 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29312 		    NULL, fmode, src, first_mp);
29313 		if (error == 0)
29314 			or->or_private = CGTP_MCAST_SUCCESS;
29315 
29316 		if (ip_debug > 0) {
29317 			ulong_t	off;
29318 			char	*ksym;
29319 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29320 			ip2dbg(("ip_multirt_apply_membership: "
29321 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29322 			    "error %d [success %u]\n",
29323 			    ksym ? ksym : "?",
29324 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29325 			    error, or->or_private));
29326 		}
29327 
29328 		ire_refrele(ire_gw);
29329 		if (error == EINPROGRESS) {
29330 			IRB_REFRELE(irb);
29331 			return (error);
29332 		}
29333 	}
29334 	IRB_REFRELE(irb);
29335 	/*
29336 	 * Consider the call as successful if we succeeded on at least
29337 	 * one interface. Otherwise, return the last encountered error.
29338 	 */
29339 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29340 }
29341 
29342 
29343 /*
29344  * Issue a warning regarding a route crossing an interface with an
29345  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29346  * amount of time is logged.
29347  */
29348 static void
29349 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29350 {
29351 	hrtime_t	current = gethrtime();
29352 	char		buf[INET_ADDRSTRLEN];
29353 	ip_stack_t	*ipst = ire->ire_ipst;
29354 
29355 	/* Convert interval in ms to hrtime in ns */
29356 	if (ipst->ips_multirt_bad_mtu_last_time +
29357 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29358 	    current) {
29359 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29360 		    "to %s, incorrect MTU %u (expected %u)\n",
29361 		    ip_dot_addr(ire->ire_addr, buf),
29362 		    ire->ire_max_frag, max_frag);
29363 
29364 		ipst->ips_multirt_bad_mtu_last_time = current;
29365 	}
29366 }
29367 
29368 
29369 /*
29370  * Get the CGTP (multirouting) filtering status.
29371  * If 0, the CGTP hooks are transparent.
29372  */
29373 /* ARGSUSED */
29374 static int
29375 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29376 {
29377 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29378 
29379 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29380 	return (0);
29381 }
29382 
29383 
29384 /*
29385  * Set the CGTP (multirouting) filtering status.
29386  * If the status is changed from active to transparent
29387  * or from transparent to active, forward the new status
29388  * to the filtering module (if loaded).
29389  */
29390 /* ARGSUSED */
29391 static int
29392 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29393     cred_t *ioc_cr)
29394 {
29395 	long		new_value;
29396 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29397 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29398 
29399 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29400 		return (EPERM);
29401 
29402 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29403 	    new_value < 0 || new_value > 1) {
29404 		return (EINVAL);
29405 	}
29406 
29407 	if ((!*ip_cgtp_filter_value) && new_value) {
29408 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29409 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29410 		    " (module not loaded)" : "");
29411 	}
29412 	if (*ip_cgtp_filter_value && (!new_value)) {
29413 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29414 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29415 		    " (module not loaded)" : "");
29416 	}
29417 
29418 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29419 		int	res;
29420 		netstackid_t stackid;
29421 
29422 		stackid = ipst->ips_netstack->netstack_stackid;
29423 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29424 		    new_value);
29425 		if (res)
29426 			return (res);
29427 	}
29428 
29429 	*ip_cgtp_filter_value = (boolean_t)new_value;
29430 
29431 	return (0);
29432 }
29433 
29434 
29435 /*
29436  * Return the expected CGTP hooks version number.
29437  */
29438 int
29439 ip_cgtp_filter_supported(void)
29440 {
29441 	return (ip_cgtp_filter_rev);
29442 }
29443 
29444 
29445 /*
29446  * CGTP hooks can be registered by invoking this function.
29447  * Checks that the version number matches.
29448  */
29449 int
29450 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29451 {
29452 	netstack_t *ns;
29453 	ip_stack_t *ipst;
29454 
29455 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29456 		return (ENOTSUP);
29457 
29458 	ns = netstack_find_by_stackid(stackid);
29459 	if (ns == NULL)
29460 		return (EINVAL);
29461 	ipst = ns->netstack_ip;
29462 	ASSERT(ipst != NULL);
29463 
29464 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29465 		netstack_rele(ns);
29466 		return (EALREADY);
29467 	}
29468 
29469 	ipst->ips_ip_cgtp_filter_ops = ops;
29470 	netstack_rele(ns);
29471 	return (0);
29472 }
29473 
29474 /*
29475  * CGTP hooks can be unregistered by invoking this function.
29476  * Returns ENXIO if there was no registration.
29477  * Returns EBUSY if the ndd variable has not been turned off.
29478  */
29479 int
29480 ip_cgtp_filter_unregister(netstackid_t stackid)
29481 {
29482 	netstack_t *ns;
29483 	ip_stack_t *ipst;
29484 
29485 	ns = netstack_find_by_stackid(stackid);
29486 	if (ns == NULL)
29487 		return (EINVAL);
29488 	ipst = ns->netstack_ip;
29489 	ASSERT(ipst != NULL);
29490 
29491 	if (ipst->ips_ip_cgtp_filter) {
29492 		netstack_rele(ns);
29493 		return (EBUSY);
29494 	}
29495 
29496 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29497 		netstack_rele(ns);
29498 		return (ENXIO);
29499 	}
29500 	ipst->ips_ip_cgtp_filter_ops = NULL;
29501 	netstack_rele(ns);
29502 	return (0);
29503 }
29504 
29505 /*
29506  * Check whether there is a CGTP filter registration.
29507  * Returns non-zero if there is a registration, otherwise returns zero.
29508  * Note: returns zero if bad stackid.
29509  */
29510 int
29511 ip_cgtp_filter_is_registered(netstackid_t stackid)
29512 {
29513 	netstack_t *ns;
29514 	ip_stack_t *ipst;
29515 	int ret;
29516 
29517 	ns = netstack_find_by_stackid(stackid);
29518 	if (ns == NULL)
29519 		return (0);
29520 	ipst = ns->netstack_ip;
29521 	ASSERT(ipst != NULL);
29522 
29523 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29524 		ret = 1;
29525 	else
29526 		ret = 0;
29527 
29528 	netstack_rele(ns);
29529 	return (ret);
29530 }
29531 
29532 static int
29533 ip_squeue_switch(int val)
29534 {
29535 	int rval = SQ_FILL;
29536 
29537 	switch (val) {
29538 	case IP_SQUEUE_ENTER_NODRAIN:
29539 		rval = SQ_NODRAIN;
29540 		break;
29541 	case IP_SQUEUE_ENTER:
29542 		rval = SQ_PROCESS;
29543 		break;
29544 	default:
29545 		break;
29546 	}
29547 	return (rval);
29548 }
29549 
29550 /* ARGSUSED */
29551 static int
29552 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29553     caddr_t addr, cred_t *cr)
29554 {
29555 	int *v = (int *)addr;
29556 	long new_value;
29557 
29558 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29559 		return (EPERM);
29560 
29561 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29562 		return (EINVAL);
29563 
29564 	ip_squeue_flag = ip_squeue_switch(new_value);
29565 	*v = new_value;
29566 	return (0);
29567 }
29568 
29569 /*
29570  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29571  * ip_debug.
29572  */
29573 /* ARGSUSED */
29574 static int
29575 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29576     caddr_t addr, cred_t *cr)
29577 {
29578 	int *v = (int *)addr;
29579 	long new_value;
29580 
29581 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29582 		return (EPERM);
29583 
29584 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29585 		return (EINVAL);
29586 
29587 	*v = new_value;
29588 	return (0);
29589 }
29590 
29591 /*
29592  * Handle changes to ipmp_hook_emulation ndd variable.
29593  * Need to update phyint_hook_ifindex.
29594  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29595  */
29596 static void
29597 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29598 {
29599 	phyint_t *phyi;
29600 	phyint_t *phyi_tmp;
29601 	char *groupname;
29602 	int namelen;
29603 	ill_t	*ill;
29604 	boolean_t new_group;
29605 
29606 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29607 	/*
29608 	 * Group indicies are stored in the phyint - a common structure
29609 	 * to both IPv4 and IPv6.
29610 	 */
29611 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29612 	for (; phyi != NULL;
29613 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29614 	    phyi, AVL_AFTER)) {
29615 		/* Ignore the ones that do not have a group */
29616 		if (phyi->phyint_groupname_len == 0)
29617 			continue;
29618 
29619 		/*
29620 		 * Look for other phyint in group.
29621 		 * Clear name/namelen so the lookup doesn't find ourselves.
29622 		 */
29623 		namelen = phyi->phyint_groupname_len;
29624 		groupname = phyi->phyint_groupname;
29625 		phyi->phyint_groupname_len = 0;
29626 		phyi->phyint_groupname = NULL;
29627 
29628 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29629 		/* Restore */
29630 		phyi->phyint_groupname_len = namelen;
29631 		phyi->phyint_groupname = groupname;
29632 
29633 		new_group = B_FALSE;
29634 		if (ipst->ips_ipmp_hook_emulation) {
29635 			/*
29636 			 * If the group already exists and has already
29637 			 * been assigned a group ifindex, we use the existing
29638 			 * group_ifindex, otherwise we pick a new group_ifindex
29639 			 * here.
29640 			 */
29641 			if (phyi_tmp != NULL &&
29642 			    phyi_tmp->phyint_group_ifindex != 0) {
29643 				phyi->phyint_group_ifindex =
29644 				    phyi_tmp->phyint_group_ifindex;
29645 			} else {
29646 				/* XXX We need a recovery strategy here. */
29647 				if (!ip_assign_ifindex(
29648 				    &phyi->phyint_group_ifindex, ipst))
29649 					cmn_err(CE_PANIC,
29650 					    "ip_assign_ifindex() failed");
29651 				new_group = B_TRUE;
29652 			}
29653 		} else {
29654 			phyi->phyint_group_ifindex = 0;
29655 		}
29656 		if (ipst->ips_ipmp_hook_emulation)
29657 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29658 		else
29659 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29660 
29661 		/*
29662 		 * For IP Filter to find out the relationship between
29663 		 * names and interface indicies, we need to generate
29664 		 * a NE_PLUMB event when a new group can appear.
29665 		 * We always generate events when a new interface appears
29666 		 * (even when ipmp_hook_emulation is set) so there
29667 		 * is no need to generate NE_PLUMB events when
29668 		 * ipmp_hook_emulation is turned off.
29669 		 * And since it isn't critical for IP Filter to get
29670 		 * the NE_UNPLUMB events we skip those here.
29671 		 */
29672 		if (new_group) {
29673 			/*
29674 			 * First phyint in group - generate group PLUMB event.
29675 			 * Since we are not running inside the ipsq we do
29676 			 * the dispatch immediately.
29677 			 */
29678 			if (phyi->phyint_illv4 != NULL)
29679 				ill = phyi->phyint_illv4;
29680 			else
29681 				ill = phyi->phyint_illv6;
29682 
29683 			if (ill != NULL)
29684 				ill_nic_event_plumb(ill, B_TRUE);
29685 		}
29686 	}
29687 	rw_exit(&ipst->ips_ill_g_lock);
29688 }
29689 
29690 /* ARGSUSED */
29691 static int
29692 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29693     caddr_t addr, cred_t *cr)
29694 {
29695 	int *v = (int *)addr;
29696 	long new_value;
29697 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29698 
29699 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29700 		return (EINVAL);
29701 
29702 	if (*v != new_value) {
29703 		*v = new_value;
29704 		ipmp_hook_emulation_changed(ipst);
29705 	}
29706 	return (0);
29707 }
29708 
29709 static void *
29710 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29711 {
29712 	kstat_t *ksp;
29713 
29714 	ip_stat_t template = {
29715 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29716 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29717 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29718 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29719 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29720 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29721 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29722 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29723 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29724 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29725 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29726 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29727 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29728 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29729 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29730 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29731 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29732 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29733 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29734 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29735 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29736 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29737 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29738 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29739 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29740 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29741 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29742 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29743 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29744 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29745 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29746 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29747 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29748 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29749 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29750 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29751 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29752 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29753 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29754 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29755 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29756 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29757 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29758 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29759 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29760 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29761 	};
29762 
29763 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29764 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29765 	    KSTAT_FLAG_VIRTUAL, stackid);
29766 
29767 	if (ksp == NULL)
29768 		return (NULL);
29769 
29770 	bcopy(&template, ip_statisticsp, sizeof (template));
29771 	ksp->ks_data = (void *)ip_statisticsp;
29772 	ksp->ks_private = (void *)(uintptr_t)stackid;
29773 
29774 	kstat_install(ksp);
29775 	return (ksp);
29776 }
29777 
29778 static void
29779 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29780 {
29781 	if (ksp != NULL) {
29782 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29783 		kstat_delete_netstack(ksp, stackid);
29784 	}
29785 }
29786 
29787 static void *
29788 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29789 {
29790 	kstat_t	*ksp;
29791 
29792 	ip_named_kstat_t template = {
29793 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29794 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29795 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29796 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29797 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29798 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29799 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29800 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29801 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29802 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29803 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29804 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29805 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29806 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29807 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29808 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29809 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29810 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29811 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29812 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29813 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29814 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29815 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29816 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29817 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29818 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29819 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29820 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29821 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29822 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29823 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29824 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29825 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29826 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29827 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29828 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29829 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29830 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29831 	};
29832 
29833 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29834 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29835 	if (ksp == NULL || ksp->ks_data == NULL)
29836 		return (NULL);
29837 
29838 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29839 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29840 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29841 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29842 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29843 
29844 	template.netToMediaEntrySize.value.i32 =
29845 	    sizeof (mib2_ipNetToMediaEntry_t);
29846 
29847 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29848 
29849 	bcopy(&template, ksp->ks_data, sizeof (template));
29850 	ksp->ks_update = ip_kstat_update;
29851 	ksp->ks_private = (void *)(uintptr_t)stackid;
29852 
29853 	kstat_install(ksp);
29854 	return (ksp);
29855 }
29856 
29857 static void
29858 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29859 {
29860 	if (ksp != NULL) {
29861 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29862 		kstat_delete_netstack(ksp, stackid);
29863 	}
29864 }
29865 
29866 static int
29867 ip_kstat_update(kstat_t *kp, int rw)
29868 {
29869 	ip_named_kstat_t *ipkp;
29870 	mib2_ipIfStatsEntry_t ipmib;
29871 	ill_walk_context_t ctx;
29872 	ill_t *ill;
29873 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29874 	netstack_t	*ns;
29875 	ip_stack_t	*ipst;
29876 
29877 	if (kp == NULL || kp->ks_data == NULL)
29878 		return (EIO);
29879 
29880 	if (rw == KSTAT_WRITE)
29881 		return (EACCES);
29882 
29883 	ns = netstack_find_by_stackid(stackid);
29884 	if (ns == NULL)
29885 		return (-1);
29886 	ipst = ns->netstack_ip;
29887 	if (ipst == NULL) {
29888 		netstack_rele(ns);
29889 		return (-1);
29890 	}
29891 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29892 
29893 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29894 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29895 	ill = ILL_START_WALK_V4(&ctx, ipst);
29896 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29897 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29898 	rw_exit(&ipst->ips_ill_g_lock);
29899 
29900 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29901 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29902 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29903 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29904 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29905 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29906 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29907 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29908 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29909 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29910 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29911 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29912 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29913 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29914 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29915 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29916 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29917 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29918 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29919 
29920 	ipkp->routingDiscards.value.ui32 =	0;
29921 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29922 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29923 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29924 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29925 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29926 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29927 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29928 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29929 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29930 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29931 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29932 
29933 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29934 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29935 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29936 
29937 	netstack_rele(ns);
29938 
29939 	return (0);
29940 }
29941 
29942 static void *
29943 icmp_kstat_init(netstackid_t stackid)
29944 {
29945 	kstat_t	*ksp;
29946 
29947 	icmp_named_kstat_t template = {
29948 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29949 		{ "inErrors",		KSTAT_DATA_UINT32 },
29950 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29951 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29952 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29953 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29954 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29955 		{ "inEchos",		KSTAT_DATA_UINT32 },
29956 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29957 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29958 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29959 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29960 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29961 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29962 		{ "outErrors",		KSTAT_DATA_UINT32 },
29963 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29964 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29965 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29966 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29967 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29968 		{ "outEchos",		KSTAT_DATA_UINT32 },
29969 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29970 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29971 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29972 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29973 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29974 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29975 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29976 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29977 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29978 		{ "outDrops",		KSTAT_DATA_UINT32 },
29979 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29980 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29981 	};
29982 
29983 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29984 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29985 	if (ksp == NULL || ksp->ks_data == NULL)
29986 		return (NULL);
29987 
29988 	bcopy(&template, ksp->ks_data, sizeof (template));
29989 
29990 	ksp->ks_update = icmp_kstat_update;
29991 	ksp->ks_private = (void *)(uintptr_t)stackid;
29992 
29993 	kstat_install(ksp);
29994 	return (ksp);
29995 }
29996 
29997 static void
29998 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29999 {
30000 	if (ksp != NULL) {
30001 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
30002 		kstat_delete_netstack(ksp, stackid);
30003 	}
30004 }
30005 
30006 static int
30007 icmp_kstat_update(kstat_t *kp, int rw)
30008 {
30009 	icmp_named_kstat_t *icmpkp;
30010 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
30011 	netstack_t	*ns;
30012 	ip_stack_t	*ipst;
30013 
30014 	if ((kp == NULL) || (kp->ks_data == NULL))
30015 		return (EIO);
30016 
30017 	if (rw == KSTAT_WRITE)
30018 		return (EACCES);
30019 
30020 	ns = netstack_find_by_stackid(stackid);
30021 	if (ns == NULL)
30022 		return (-1);
30023 	ipst = ns->netstack_ip;
30024 	if (ipst == NULL) {
30025 		netstack_rele(ns);
30026 		return (-1);
30027 	}
30028 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
30029 
30030 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
30031 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
30032 	icmpkp->inDestUnreachs.value.ui32 =
30033 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
30034 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
30035 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
30036 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
30037 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
30038 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
30039 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
30040 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
30041 	icmpkp->inTimestampReps.value.ui32 =
30042 	    ipst->ips_icmp_mib.icmpInTimestampReps;
30043 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
30044 	icmpkp->inAddrMaskReps.value.ui32 =
30045 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
30046 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
30047 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
30048 	icmpkp->outDestUnreachs.value.ui32 =
30049 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
30050 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
30051 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
30052 	icmpkp->outSrcQuenchs.value.ui32 =
30053 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
30054 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
30055 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
30056 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
30057 	icmpkp->outTimestamps.value.ui32 =
30058 	    ipst->ips_icmp_mib.icmpOutTimestamps;
30059 	icmpkp->outTimestampReps.value.ui32 =
30060 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
30061 	icmpkp->outAddrMasks.value.ui32 =
30062 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
30063 	icmpkp->outAddrMaskReps.value.ui32 =
30064 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
30065 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
30066 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
30067 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
30068 	icmpkp->outFragNeeded.value.ui32 =
30069 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
30070 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
30071 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
30072 	icmpkp->inBadRedirects.value.ui32 =
30073 	    ipst->ips_icmp_mib.icmpInBadRedirects;
30074 
30075 	netstack_rele(ns);
30076 	return (0);
30077 }
30078 
30079 /*
30080  * This is the fanout function for raw socket opened for SCTP.  Note
30081  * that it is called after SCTP checks that there is no socket which
30082  * wants a packet.  Then before SCTP handles this out of the blue packet,
30083  * this function is called to see if there is any raw socket for SCTP.
30084  * If there is and it is bound to the correct address, the packet will
30085  * be sent to that socket.  Note that only one raw socket can be bound to
30086  * a port.  This is assured in ipcl_sctp_hash_insert();
30087  */
30088 void
30089 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
30090     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
30091     zoneid_t zoneid)
30092 {
30093 	conn_t		*connp;
30094 	queue_t		*rq;
30095 	mblk_t		*first_mp;
30096 	boolean_t	secure;
30097 	ip6_t		*ip6h;
30098 	ip_stack_t	*ipst = recv_ill->ill_ipst;
30099 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
30100 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
30101 	boolean_t	sctp_csum_err = B_FALSE;
30102 
30103 	if (flags & IP_FF_SCTP_CSUM_ERR) {
30104 		sctp_csum_err = B_TRUE;
30105 		flags &= ~IP_FF_SCTP_CSUM_ERR;
30106 	}
30107 
30108 	first_mp = mp;
30109 	if (mctl_present) {
30110 		mp = first_mp->b_cont;
30111 		secure = ipsec_in_is_secure(first_mp);
30112 		ASSERT(mp != NULL);
30113 	} else {
30114 		secure = B_FALSE;
30115 	}
30116 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
30117 
30118 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
30119 	if (connp == NULL) {
30120 		/*
30121 		 * Although raw sctp is not summed, OOB chunks must be.
30122 		 * Drop the packet here if the sctp checksum failed.
30123 		 */
30124 		if (sctp_csum_err) {
30125 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
30126 			freemsg(first_mp);
30127 			return;
30128 		}
30129 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
30130 		return;
30131 	}
30132 	rq = connp->conn_rq;
30133 	if (!canputnext(rq)) {
30134 		CONN_DEC_REF(connp);
30135 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
30136 		freemsg(first_mp);
30137 		return;
30138 	}
30139 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
30140 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
30141 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
30142 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
30143 		if (first_mp == NULL) {
30144 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
30145 			CONN_DEC_REF(connp);
30146 			return;
30147 		}
30148 	}
30149 	/*
30150 	 * We probably should not send M_CTL message up to
30151 	 * raw socket.
30152 	 */
30153 	if (mctl_present)
30154 		freeb(first_mp);
30155 
30156 	/* Initiate IPPF processing here if needed. */
30157 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
30158 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
30159 		ip_process(IPP_LOCAL_IN, &mp,
30160 		    recv_ill->ill_phyint->phyint_ifindex);
30161 		if (mp == NULL) {
30162 			CONN_DEC_REF(connp);
30163 			return;
30164 		}
30165 	}
30166 
30167 	if (connp->conn_recvif || connp->conn_recvslla ||
30168 	    ((connp->conn_ip_recvpktinfo ||
30169 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
30170 	    (flags & IP_FF_IPINFO))) {
30171 		int in_flags = 0;
30172 
30173 		/*
30174 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
30175 		 * IPF_RECVIF.
30176 		 */
30177 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
30178 			in_flags = IPF_RECVIF;
30179 		}
30180 		if (connp->conn_recvslla) {
30181 			in_flags |= IPF_RECVSLLA;
30182 		}
30183 		if (isv4) {
30184 			mp = ip_add_info(mp, recv_ill, in_flags,
30185 			    IPCL_ZONEID(connp), ipst);
30186 		} else {
30187 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
30188 			if (mp == NULL) {
30189 				BUMP_MIB(recv_ill->ill_ip_mib,
30190 				    ipIfStatsInDiscards);
30191 				CONN_DEC_REF(connp);
30192 				return;
30193 			}
30194 		}
30195 	}
30196 
30197 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30198 	/*
30199 	 * We are sending the IPSEC_IN message also up. Refer
30200 	 * to comments above this function.
30201 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
30202 	 */
30203 	(connp->conn_recv)(connp, mp, NULL);
30204 	CONN_DEC_REF(connp);
30205 }
30206 
30207 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30208 {									\
30209 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30210 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30211 }
30212 /*
30213  * This function should be called only if all packet processing
30214  * including fragmentation is complete. Callers of this function
30215  * must set mp->b_prev to one of these values:
30216  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30217  * prior to handing over the mp as first argument to this function.
30218  *
30219  * If the ire passed by caller is incomplete, this function
30220  * queues the packet and if necessary, sends ARP request and bails.
30221  * If the ire passed is fully resolved, we simply prepend
30222  * the link-layer header to the packet, do ipsec hw acceleration
30223  * work if necessary, and send the packet out on the wire.
30224  *
30225  * NOTE: IPsec will only call this function with fully resolved
30226  * ires if hw acceleration is involved.
30227  * TODO list :
30228  * 	a Handle M_MULTIDATA so that
30229  *	  tcp_multisend->tcp_multisend_data can
30230  *	  call ip_xmit_v4 directly
30231  *	b Handle post-ARP work for fragments so that
30232  *	  ip_wput_frag can call this function.
30233  */
30234 ipxmit_state_t
30235 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io,
30236     boolean_t flow_ctl_enabled, conn_t *connp)
30237 {
30238 	nce_t		*arpce;
30239 	ipha_t		*ipha;
30240 	queue_t		*q;
30241 	int		ill_index;
30242 	mblk_t		*nxt_mp, *first_mp;
30243 	boolean_t	xmit_drop = B_FALSE;
30244 	ip_proc_t	proc;
30245 	ill_t		*out_ill;
30246 	int		pkt_len;
30247 
30248 	arpce = ire->ire_nce;
30249 	ASSERT(arpce != NULL);
30250 
30251 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30252 
30253 	mutex_enter(&arpce->nce_lock);
30254 	switch (arpce->nce_state) {
30255 	case ND_REACHABLE:
30256 		/* If there are other queued packets, queue this packet */
30257 		if (arpce->nce_qd_mp != NULL) {
30258 			if (mp != NULL)
30259 				nce_queue_mp_common(arpce, mp, B_FALSE);
30260 			mp = arpce->nce_qd_mp;
30261 		}
30262 		arpce->nce_qd_mp = NULL;
30263 		mutex_exit(&arpce->nce_lock);
30264 
30265 		/*
30266 		 * Flush the queue.  In the common case, where the
30267 		 * ARP is already resolved,  it will go through the
30268 		 * while loop only once.
30269 		 */
30270 		while (mp != NULL) {
30271 
30272 			nxt_mp = mp->b_next;
30273 			mp->b_next = NULL;
30274 			ASSERT(mp->b_datap->db_type != M_CTL);
30275 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30276 			/*
30277 			 * This info is needed for IPQOS to do COS marking
30278 			 * in ip_wput_attach_llhdr->ip_process.
30279 			 */
30280 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30281 			mp->b_prev = NULL;
30282 
30283 			/* set up ill index for outbound qos processing */
30284 			out_ill = ire_to_ill(ire);
30285 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30286 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30287 			    ill_index, &ipha);
30288 			if (first_mp == NULL) {
30289 				xmit_drop = B_TRUE;
30290 				BUMP_MIB(out_ill->ill_ip_mib,
30291 				    ipIfStatsOutDiscards);
30292 				goto next_mp;
30293 			}
30294 
30295 			/* non-ipsec hw accel case */
30296 			if (io == NULL || !io->ipsec_out_accelerated) {
30297 				/* send it */
30298 				q = ire->ire_stq;
30299 				if (proc == IPP_FWD_OUT) {
30300 					UPDATE_IB_PKT_COUNT(ire);
30301 				} else {
30302 					UPDATE_OB_PKT_COUNT(ire);
30303 				}
30304 				ire->ire_last_used_time = lbolt;
30305 
30306 				if (flow_ctl_enabled || canputnext(q)) {
30307 					if (proc == IPP_FWD_OUT) {
30308 
30309 					BUMP_MIB(out_ill->ill_ip_mib,
30310 					    ipIfStatsHCOutForwDatagrams);
30311 
30312 					}
30313 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30314 					    pkt_len);
30315 
30316 					DTRACE_IP7(send, mblk_t *, first_mp,
30317 					    conn_t *, NULL, void_ip_t *, ipha,
30318 					    __dtrace_ipsr_ill_t *, out_ill,
30319 					    ipha_t *, ipha, ip6_t *, NULL, int,
30320 					    0);
30321 
30322 					ILL_SEND_TX(out_ill,
30323 					    ire, connp, first_mp, 0);
30324 				} else {
30325 					BUMP_MIB(out_ill->ill_ip_mib,
30326 					    ipIfStatsOutDiscards);
30327 					xmit_drop = B_TRUE;
30328 					freemsg(first_mp);
30329 				}
30330 			} else {
30331 				/*
30332 				 * Safety Pup says: make sure this
30333 				 *  is going to the right interface!
30334 				 */
30335 				ill_t *ill1 =
30336 				    (ill_t *)ire->ire_stq->q_ptr;
30337 				int ifindex =
30338 				    ill1->ill_phyint->phyint_ifindex;
30339 				if (ifindex !=
30340 				    io->ipsec_out_capab_ill_index) {
30341 					xmit_drop = B_TRUE;
30342 					freemsg(mp);
30343 				} else {
30344 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30345 					    pkt_len);
30346 
30347 					DTRACE_IP7(send, mblk_t *, first_mp,
30348 					    conn_t *, NULL, void_ip_t *, ipha,
30349 					    __dtrace_ipsr_ill_t *, ill1,
30350 					    ipha_t *, ipha, ip6_t *, NULL,
30351 					    int, 0);
30352 
30353 					ipsec_hw_putnext(ire->ire_stq, mp);
30354 				}
30355 			}
30356 next_mp:
30357 			mp = nxt_mp;
30358 		} /* while (mp != NULL) */
30359 		if (xmit_drop)
30360 			return (SEND_FAILED);
30361 		else
30362 			return (SEND_PASSED);
30363 
30364 	case ND_INITIAL:
30365 	case ND_INCOMPLETE:
30366 
30367 		/*
30368 		 * While we do send off packets to dests that
30369 		 * use fully-resolved CGTP routes, we do not
30370 		 * handle unresolved CGTP routes.
30371 		 */
30372 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30373 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30374 
30375 		if (mp != NULL) {
30376 			/* queue the packet */
30377 			nce_queue_mp_common(arpce, mp, B_FALSE);
30378 		}
30379 
30380 		if (arpce->nce_state == ND_INCOMPLETE) {
30381 			mutex_exit(&arpce->nce_lock);
30382 			DTRACE_PROBE3(ip__xmit__incomplete,
30383 			    (ire_t *), ire, (mblk_t *), mp,
30384 			    (ipsec_out_t *), io);
30385 			return (LOOKUP_IN_PROGRESS);
30386 		}
30387 
30388 		arpce->nce_state = ND_INCOMPLETE;
30389 		mutex_exit(&arpce->nce_lock);
30390 		/*
30391 		 * Note that ire_add() (called from ire_forward())
30392 		 * holds a ref on the ire until ARP is completed.
30393 		 */
30394 
30395 		ire_arpresolve(ire, ire_to_ill(ire));
30396 		return (LOOKUP_IN_PROGRESS);
30397 	default:
30398 		ASSERT(0);
30399 		mutex_exit(&arpce->nce_lock);
30400 		return (LLHDR_RESLV_FAILED);
30401 	}
30402 }
30403 
30404 #undef	UPDATE_IP_MIB_OB_COUNTERS
30405 
30406 /*
30407  * Return B_TRUE if the buffers differ in length or content.
30408  * This is used for comparing extension header buffers.
30409  * Note that an extension header would be declared different
30410  * even if all that changed was the next header value in that header i.e.
30411  * what really changed is the next extension header.
30412  */
30413 boolean_t
30414 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30415     uint_t blen)
30416 {
30417 	if (!b_valid)
30418 		blen = 0;
30419 
30420 	if (alen != blen)
30421 		return (B_TRUE);
30422 	if (alen == 0)
30423 		return (B_FALSE);	/* Both zero length */
30424 	return (bcmp(abuf, bbuf, alen));
30425 }
30426 
30427 /*
30428  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30429  * Return B_FALSE if memory allocation fails - don't change any state!
30430  */
30431 boolean_t
30432 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30433     const void *src, uint_t srclen)
30434 {
30435 	void *dst;
30436 
30437 	if (!src_valid)
30438 		srclen = 0;
30439 
30440 	ASSERT(*dstlenp == 0);
30441 	if (src != NULL && srclen != 0) {
30442 		dst = mi_alloc(srclen, BPRI_MED);
30443 		if (dst == NULL)
30444 			return (B_FALSE);
30445 	} else {
30446 		dst = NULL;
30447 	}
30448 	if (*dstp != NULL)
30449 		mi_free(*dstp);
30450 	*dstp = dst;
30451 	*dstlenp = dst == NULL ? 0 : srclen;
30452 	return (B_TRUE);
30453 }
30454 
30455 /*
30456  * Replace what is in *dst, *dstlen with the source.
30457  * Assumes ip_allocbuf has already been called.
30458  */
30459 void
30460 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30461     const void *src, uint_t srclen)
30462 {
30463 	if (!src_valid)
30464 		srclen = 0;
30465 
30466 	ASSERT(*dstlenp == srclen);
30467 	if (src != NULL && srclen != 0)
30468 		bcopy(src, *dstp, srclen);
30469 }
30470 
30471 /*
30472  * Free the storage pointed to by the members of an ip6_pkt_t.
30473  */
30474 void
30475 ip6_pkt_free(ip6_pkt_t *ipp)
30476 {
30477 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30478 
30479 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30480 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30481 		ipp->ipp_hopopts = NULL;
30482 		ipp->ipp_hopoptslen = 0;
30483 	}
30484 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30485 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30486 		ipp->ipp_rtdstopts = NULL;
30487 		ipp->ipp_rtdstoptslen = 0;
30488 	}
30489 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30490 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30491 		ipp->ipp_dstopts = NULL;
30492 		ipp->ipp_dstoptslen = 0;
30493 	}
30494 	if (ipp->ipp_fields & IPPF_RTHDR) {
30495 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30496 		ipp->ipp_rthdr = NULL;
30497 		ipp->ipp_rthdrlen = 0;
30498 	}
30499 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30500 	    IPPF_RTHDR);
30501 }
30502 
30503 zoneid_t
30504 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30505     zoneid_t lookup_zoneid)
30506 {
30507 	ire_t		*ire;
30508 	int		ire_flags = MATCH_IRE_TYPE;
30509 	zoneid_t	zoneid = ALL_ZONES;
30510 
30511 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30512 		return (ALL_ZONES);
30513 
30514 	if (lookup_zoneid != ALL_ZONES)
30515 		ire_flags |= MATCH_IRE_ZONEONLY;
30516 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30517 	    lookup_zoneid, NULL, ire_flags, ipst);
30518 	if (ire != NULL) {
30519 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30520 		ire_refrele(ire);
30521 	}
30522 	return (zoneid);
30523 }
30524 
30525 zoneid_t
30526 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30527     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30528 {
30529 	ire_t		*ire;
30530 	int		ire_flags = MATCH_IRE_TYPE;
30531 	zoneid_t	zoneid = ALL_ZONES;
30532 	ipif_t		*ipif_arg = NULL;
30533 
30534 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30535 		return (ALL_ZONES);
30536 
30537 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30538 		ire_flags |= MATCH_IRE_ILL_GROUP;
30539 		ipif_arg = ill->ill_ipif;
30540 	}
30541 	if (lookup_zoneid != ALL_ZONES)
30542 		ire_flags |= MATCH_IRE_ZONEONLY;
30543 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30544 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30545 	if (ire != NULL) {
30546 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30547 		ire_refrele(ire);
30548 	}
30549 	return (zoneid);
30550 }
30551 
30552 /*
30553  * IP obserability hook support functions.
30554  */
30555 
30556 static void
30557 ipobs_init(ip_stack_t *ipst)
30558 {
30559 	ipst->ips_ipobs_enabled = B_FALSE;
30560 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30561 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30562 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30563 	ipst->ips_ipobs_cb_nwalkers = 0;
30564 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30565 }
30566 
30567 static void
30568 ipobs_fini(ip_stack_t *ipst)
30569 {
30570 	ipobs_cb_t *cb;
30571 
30572 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30573 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30574 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30575 
30576 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30577 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30578 		kmem_free(cb, sizeof (*cb));
30579 	}
30580 	list_destroy(&ipst->ips_ipobs_cb_list);
30581 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30582 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30583 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30584 }
30585 
30586 void
30587 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30588     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30589 {
30590 	ipobs_cb_t *ipobs_cb;
30591 
30592 	ASSERT(DB_TYPE(mp) == M_DATA);
30593 
30594 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30595 	ipst->ips_ipobs_cb_nwalkers++;
30596 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30597 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30598 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30599 		mblk_t  *mp2 = allocb(sizeof (ipobs_hook_data_t),
30600 		    BPRI_HI);
30601 		if (mp2 != NULL) {
30602 			ipobs_hook_data_t *ihd =
30603 			    (ipobs_hook_data_t *)mp2->b_rptr;
30604 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30605 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30606 				freemsg(mp2);
30607 				continue;
30608 			}
30609 			ihd->ihd_mp->b_rptr += hlen;
30610 			ihd->ihd_htype = htype;
30611 			ihd->ihd_ipver = ipver;
30612 			ihd->ihd_zsrc = zsrc;
30613 			ihd->ihd_zdst = zdst;
30614 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30615 			ihd->ihd_stack = ipst->ips_netstack;
30616 			mp2->b_wptr += sizeof (*ihd);
30617 			ipobs_cb->ipobs_cbfunc(mp2);
30618 		}
30619 	}
30620 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30621 	ipst->ips_ipobs_cb_nwalkers--;
30622 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30623 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30624 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30625 }
30626 
30627 void
30628 ipobs_register_hook(netstack_t *ns, pfv_t func)
30629 {
30630 	ipobs_cb_t   *cb;
30631 	ip_stack_t *ipst = ns->netstack_ip;
30632 
30633 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30634 
30635 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30636 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30637 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30638 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30639 
30640 	cb->ipobs_cbfunc = func;
30641 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30642 	ipst->ips_ipobs_enabled = B_TRUE;
30643 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30644 }
30645 
30646 void
30647 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30648 {
30649 	ipobs_cb_t	*curcb;
30650 	ip_stack_t	*ipst = ns->netstack_ip;
30651 
30652 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30653 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30654 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30655 
30656 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30657 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30658 		if (func == curcb->ipobs_cbfunc) {
30659 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30660 			kmem_free(curcb, sizeof (*curcb));
30661 			break;
30662 		}
30663 	}
30664 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30665 		ipst->ips_ipobs_enabled = B_FALSE;
30666 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30667 }
30668