xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 1b8adde7ba7d5e04395c141c5400dc2cffd7d809)
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 
50 #include <sys/systm.h>
51 #include <sys/param.h>
52 #include <sys/kmem.h>
53 #include <sys/sdt.h>
54 #include <sys/socket.h>
55 #include <sys/vtrace.h>
56 #include <sys/isa_defs.h>
57 #include <sys/mac.h>
58 #include <net/if.h>
59 #include <net/if_arp.h>
60 #include <net/route.h>
61 #include <sys/sockio.h>
62 #include <netinet/in.h>
63 #include <net/if_dl.h>
64 
65 #include <inet/common.h>
66 #include <inet/mi.h>
67 #include <inet/mib2.h>
68 #include <inet/nd.h>
69 #include <inet/arp.h>
70 #include <inet/snmpcom.h>
71 #include <inet/optcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/ip_ndp.h>
91 #include <inet/ip_listutils.h>
92 #include <netinet/igmp.h>
93 #include <netinet/ip_mroute.h>
94 #include <inet/ipp_common.h>
95 
96 #include <net/pfkeyv2.h>
97 #include <inet/ipsec_info.h>
98 #include <inet/sadb.h>
99 #include <inet/ipsec_impl.h>
100 #include <sys/iphada.h>
101 #include <inet/tun.h>
102 #include <inet/ipdrop.h>
103 #include <inet/ip_netinfo.h>
104 
105 #include <sys/ethernet.h>
106 #include <net/if_types.h>
107 #include <sys/cpuvar.h>
108 
109 #include <ipp/ipp.h>
110 #include <ipp/ipp_impl.h>
111 #include <ipp/ipgpc/ipgpc.h>
112 
113 #include <sys/multidata.h>
114 #include <sys/pattr.h>
115 
116 #include <inet/ipclassifier.h>
117 #include <inet/sctp_ip.h>
118 #include <inet/sctp/sctp_impl.h>
119 #include <inet/udp_impl.h>
120 #include <inet/rawip_impl.h>
121 #include <inet/rts_impl.h>
122 #include <sys/sunddi.h>
123 
124 #include <sys/tsol/label.h>
125 #include <sys/tsol/tnet.h>
126 
127 #include <rpc/pmap_prot.h>
128 
129 /*
130  * Values for squeue switch:
131  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
132  * IP_SQUEUE_ENTER: squeue_enter
133  * IP_SQUEUE_FILL: squeue_fill
134  */
135 int ip_squeue_enter = 2;	/* Setable in /etc/system */
136 
137 squeue_func_t ip_input_proc;
138 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
139 
140 /*
141  * Setable in /etc/system
142  */
143 int ip_poll_normal_ms = 100;
144 int ip_poll_normal_ticks = 0;
145 int ip_modclose_ackwait_ms = 3000;
146 
147 /*
148  * It would be nice to have these present only in DEBUG systems, but the
149  * current design of the global symbol checking logic requires them to be
150  * unconditionally present.
151  */
152 uint_t ip_thread_data;			/* TSD key for debug support */
153 krwlock_t ip_thread_rwlock;
154 list_t	ip_thread_list;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /*
179  * Cluster specific hooks. These should be NULL when booted as a non-cluster
180  */
181 
182 /*
183  * Hook functions to enable cluster networking
184  * On non-clustered systems these vectors must always be NULL.
185  *
186  * Hook function to Check ip specified ip address is a shared ip address
187  * in the cluster
188  *
189  */
190 int (*cl_inet_isclusterwide)(uint8_t protocol,
191     sa_family_t addr_family, uint8_t *laddrp) = NULL;
192 
193 /*
194  * Hook function to generate cluster wide ip fragment identifier
195  */
196 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
197     uint8_t *laddrp, uint8_t *faddrp) = NULL;
198 
199 /*
200  * Hook function to generate cluster wide SPI.
201  */
202 void (*cl_inet_getspi)(uint8_t, uint8_t *, size_t) = NULL;
203 
204 /*
205  * Hook function to verify if the SPI is already utlized.
206  */
207 
208 int (*cl_inet_checkspi)(uint8_t, uint32_t) = NULL;
209 
210 /*
211  * Hook function to delete the SPI from the cluster wide repository.
212  */
213 
214 void (*cl_inet_deletespi)(uint8_t, uint32_t) = NULL;
215 
216 /*
217  * Hook function to inform the cluster when packet received on an IDLE SA
218  */
219 
220 void (*cl_inet_idlesa)(uint8_t, uint32_t, sa_family_t, in6_addr_t,
221     in6_addr_t) = NULL;
222 
223 /*
224  * Synchronization notes:
225  *
226  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
227  * MT level protection given by STREAMS. IP uses a combination of its own
228  * internal serialization mechanism and standard Solaris locking techniques.
229  * The internal serialization is per phyint (no IPMP) or per IPMP group.
230  * This is used to serialize plumbing operations, IPMP operations, certain
231  * multicast operations, most set ioctls, igmp/mld timers etc.
232  *
233  * Plumbing is a long sequence of operations involving message
234  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
235  * involved in plumbing operations. A natural model is to serialize these
236  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
237  * parallel without any interference. But various set ioctls on hme0 are best
238  * serialized. However if the system uses IPMP, the operations are easier if
239  * they are serialized on a per IPMP group basis since IPMP operations
240  * happen across ill's of a group. Thus the lowest common denominator is to
241  * serialize most set ioctls, multicast join/leave operations, IPMP operations
242  * igmp/mld timer operations, and processing of DLPI control messages received
243  * from drivers on a per IPMP group basis. If the system does not employ
244  * IPMP the serialization is on a per phyint basis. This serialization is
245  * provided by the ipsq_t and primitives operating on this. Details can
246  * be found in ip_if.c above the core primitives operating on ipsq_t.
247  *
248  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
249  * Simiarly lookup of an ire by a thread also returns a refheld ire.
250  * In addition ipif's and ill's referenced by the ire are also indirectly
251  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
252  * the ipif's address or netmask change as long as an ipif is refheld
253  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
254  * address of an ipif has to go through the ipsq_t. This ensures that only
255  * 1 such exclusive operation proceeds at any time on the ipif. It then
256  * deletes all ires associated with this ipif, and waits for all refcnts
257  * associated with this ipif to come down to zero. The address is changed
258  * only after the ipif has been quiesced. Then the ipif is brought up again.
259  * More details are described above the comment in ip_sioctl_flags.
260  *
261  * Packet processing is based mostly on IREs and are fully multi-threaded
262  * using standard Solaris MT techniques.
263  *
264  * There are explicit locks in IP to handle:
265  * - The ip_g_head list maintained by mi_open_link() and friends.
266  *
267  * - The reassembly data structures (one lock per hash bucket)
268  *
269  * - conn_lock is meant to protect conn_t fields. The fields actually
270  *   protected by conn_lock are documented in the conn_t definition.
271  *
272  * - ire_lock to protect some of the fields of the ire, IRE tables
273  *   (one lock per hash bucket). Refer to ip_ire.c for details.
274  *
275  * - ndp_g_lock and nce_lock for protecting NCEs.
276  *
277  * - ill_lock protects fields of the ill and ipif. Details in ip.h
278  *
279  * - ill_g_lock: This is a global reader/writer lock. Protects the following
280  *	* The AVL tree based global multi list of all ills.
281  *	* The linked list of all ipifs of an ill
282  *	* The <ill-ipsq> mapping
283  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
284  *	* The illgroup list threaded by ill_group_next.
285  *	* <ill-phyint> association
286  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
287  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
288  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
289  *   will all have to hold the ill_g_lock as writer for the actual duration
290  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
291  *   may be found in the IPMP section.
292  *
293  * - ill_lock:  This is a per ill mutex.
294  *   It protects some members of the ill and is documented below.
295  *   It also protects the <ill-ipsq> mapping
296  *   It also protects the illgroup list threaded by ill_group_next.
297  *   It also protects the <ill-phyint> assoc.
298  *   It also protects the list of ipifs hanging off the ill.
299  *
300  * - ipsq_lock: This is a per ipsq_t mutex lock.
301  *   This protects all the other members of the ipsq struct except
302  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
303  *
304  * - illgrp_lock: This is a per ill_group mutex lock.
305  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
306  *   which dictates which is the next ill in an ill_group that is to be chosen
307  *   for sending outgoing packets, through creation of an IRE_CACHE that
308  *   references this ill.
309  *
310  * - phyint_lock: This is a per phyint mutex lock. Protects just the
311  *   phyint_flags
312  *
313  * - ip_g_nd_lock: This is a global reader/writer lock.
314  *   Any call to nd_load to load a new parameter to the ND table must hold the
315  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
316  *   as reader.
317  *
318  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
319  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
320  *   uniqueness check also done atomically.
321  *
322  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
323  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
324  *   as a writer when adding or deleting elements from these lists, and
325  *   as a reader when walking these lists to send a SADB update to the
326  *   IPsec capable ills.
327  *
328  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
329  *   group list linked by ill_usesrc_grp_next. It also protects the
330  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
331  *   group is being added or deleted.  This lock is taken as a reader when
332  *   walking the list/group(eg: to get the number of members in a usesrc group).
333  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
334  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
335  *   example, it is not necessary to take this lock in the initial portion
336  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
337  *   ip_sioctl_flags since the these operations are executed exclusively and
338  *   that ensures that the "usesrc group state" cannot change. The "usesrc
339  *   group state" change can happen only in the latter part of
340  *   ip_sioctl_slifusesrc and in ill_delete.
341  *
342  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
343  *
344  * To change the <ill-phyint> association, the ill_g_lock must be held
345  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
346  * must be held.
347  *
348  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
349  * and the ill_lock of the ill in question must be held.
350  *
351  * To change the <ill-illgroup> association the ill_g_lock must be held as
352  * writer and the ill_lock of the ill in question must be held.
353  *
354  * To add or delete an ipif from the list of ipifs hanging off the ill,
355  * ill_g_lock (writer) and ill_lock must be held and the thread must be
356  * a writer on the associated ipsq,.
357  *
358  * To add or delete an ill to the system, the ill_g_lock must be held as
359  * writer and the thread must be a writer on the associated ipsq.
360  *
361  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
362  * must be a writer on the associated ipsq.
363  *
364  * Lock hierarchy
365  *
366  * Some lock hierarchy scenarios are listed below.
367  *
368  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
369  * ill_g_lock -> illgrp_lock -> ill_lock
370  * ill_g_lock -> ill_lock(s) -> phyint_lock
371  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
372  * ill_g_lock -> ip_addr_avail_lock
373  * conn_lock -> irb_lock -> ill_lock -> ire_lock
374  * ill_g_lock -> ip_g_nd_lock
375  *
376  * When more than 1 ill lock is needed to be held, all ill lock addresses
377  * are sorted on address and locked starting from highest addressed lock
378  * downward.
379  *
380  * IPsec scenarios
381  *
382  * ipsa_lock -> ill_g_lock -> ill_lock
383  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
384  * ipsec_capab_ills_lock -> ipsa_lock
385  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
386  *
387  * Trusted Solaris scenarios
388  *
389  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
390  * igsa_lock -> gcdb_lock
391  * gcgrp_rwlock -> ire_lock
392  * gcgrp_rwlock -> gcdb_lock
393  *
394  *
395  * Routing/forwarding table locking notes:
396  *
397  * Lock acquisition order: Radix tree lock, irb_lock.
398  * Requirements:
399  * i.  Walker must not hold any locks during the walker callback.
400  * ii  Walker must not see a truncated tree during the walk because of any node
401  *     deletion.
402  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
403  *     in many places in the code to walk the irb list. Thus even if all the
404  *     ires in a bucket have been deleted, we still can't free the radix node
405  *     until the ires have actually been inactive'd (freed).
406  *
407  * Tree traversal - Need to hold the global tree lock in read mode.
408  * Before dropping the global tree lock, need to either increment the ire_refcnt
409  * to ensure that the radix node can't be deleted.
410  *
411  * Tree add - Need to hold the global tree lock in write mode to add a
412  * radix node. To prevent the node from being deleted, increment the
413  * irb_refcnt, after the node is added to the tree. The ire itself is
414  * added later while holding the irb_lock, but not the tree lock.
415  *
416  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
417  * All associated ires must be inactive (i.e. freed), and irb_refcnt
418  * must be zero.
419  *
420  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
421  * global tree lock (read mode) for traversal.
422  *
423  * IPsec notes :
424  *
425  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
426  * in front of the actual packet. For outbound datagrams, the M_CTL
427  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
428  * information used by the IPsec code for applying the right level of
429  * protection. The information initialized by IP in the ipsec_out_t
430  * is determined by the per-socket policy or global policy in the system.
431  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
432  * ipsec_info.h) which starts out with nothing in it. It gets filled
433  * with the right information if it goes through the AH/ESP code, which
434  * happens if the incoming packet is secure. The information initialized
435  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
436  * the policy requirements needed by per-socket policy or global policy
437  * is met or not.
438  *
439  * If there is both per-socket policy (set using setsockopt) and there
440  * is also global policy match for the 5 tuples of the socket,
441  * ipsec_override_policy() makes the decision of which one to use.
442  *
443  * For fully connected sockets i.e dst, src [addr, port] is known,
444  * conn_policy_cached is set indicating that policy has been cached.
445  * conn_in_enforce_policy may or may not be set depending on whether
446  * there is a global policy match or per-socket policy match.
447  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
448  * Once the right policy is set on the conn_t, policy cannot change for
449  * this socket. This makes life simpler for TCP (UDP ?) where
450  * re-transmissions go out with the same policy. For symmetry, policy
451  * is cached for fully connected UDP sockets also. Thus if policy is cached,
452  * it also implies that policy is latched i.e policy cannot change
453  * on these sockets. As we have the right policy on the conn, we don't
454  * have to lookup global policy for every outbound and inbound datagram
455  * and thus serving as an optimization. Note that a global policy change
456  * does not affect fully connected sockets if they have policy. If fully
457  * connected sockets did not have any policy associated with it, global
458  * policy change may affect them.
459  *
460  * IP Flow control notes:
461  *
462  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
463  * cannot be sent down to the driver by IP, because of a canput failure, IP
464  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
465  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
466  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
467  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
468  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
469  * the queued messages, and removes the conn from the drain list, if all
470  * messages were drained. It also qenables the next conn in the drain list to
471  * continue the drain process.
472  *
473  * In reality the drain list is not a single list, but a configurable number
474  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
475  * list. If the ip_wsrv of the next qenabled conn does not run, because the
476  * stream closes, ip_close takes responsibility to qenable the next conn in
477  * the drain list. The directly called ip_wput path always does a putq, if
478  * it cannot putnext. Thus synchronization problems are handled between
479  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
480  * functions that manipulate this drain list. Furthermore conn_drain_insert
481  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
482  * running on a queue at any time. conn_drain_tail can be simultaneously called
483  * from both ip_wsrv and ip_close.
484  *
485  * IPQOS notes:
486  *
487  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
488  * and IPQoS modules. IPPF includes hooks in IP at different control points
489  * (callout positions) which direct packets to IPQoS modules for policy
490  * processing. Policies, if present, are global.
491  *
492  * The callout positions are located in the following paths:
493  *		o local_in (packets destined for this host)
494  *		o local_out (packets orginating from this host )
495  *		o fwd_in  (packets forwarded by this m/c - inbound)
496  *		o fwd_out (packets forwarded by this m/c - outbound)
497  * Hooks at these callout points can be enabled/disabled using the ndd variable
498  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
499  * By default all the callout positions are enabled.
500  *
501  * Outbound (local_out)
502  * Hooks are placed in ip_wput_ire and ipsec_out_process.
503  *
504  * Inbound (local_in)
505  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
506  * TCP and UDP fanout routines.
507  *
508  * Forwarding (in and out)
509  * Hooks are placed in ip_rput_forward.
510  *
511  * IP Policy Framework processing (IPPF processing)
512  * Policy processing for a packet is initiated by ip_process, which ascertains
513  * that the classifier (ipgpc) is loaded and configured, failing which the
514  * packet resumes normal processing in IP. If the clasifier is present, the
515  * packet is acted upon by one or more IPQoS modules (action instances), per
516  * filters configured in ipgpc and resumes normal IP processing thereafter.
517  * An action instance can drop a packet in course of its processing.
518  *
519  * A boolean variable, ip_policy, is used in all the fanout routines that can
520  * invoke ip_process for a packet. This variable indicates if the packet should
521  * to be sent for policy processing. The variable is set to B_TRUE by default,
522  * i.e. when the routines are invoked in the normal ip procesing path for a
523  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
524  * ip_policy is set to B_FALSE for all the routines called in these two
525  * functions because, in the former case,  we don't process loopback traffic
526  * currently while in the latter, the packets have already been processed in
527  * icmp_inbound.
528  *
529  * Zones notes:
530  *
531  * The partitioning rules for networking are as follows:
532  * 1) Packets coming from a zone must have a source address belonging to that
533  * zone.
534  * 2) Packets coming from a zone can only be sent on a physical interface on
535  * which the zone has an IP address.
536  * 3) Between two zones on the same machine, packet delivery is only allowed if
537  * there's a matching route for the destination and zone in the forwarding
538  * table.
539  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
540  * different zones can bind to the same port with the wildcard address
541  * (INADDR_ANY).
542  *
543  * The granularity of interface partitioning is at the logical interface level.
544  * Therefore, every zone has its own IP addresses, and incoming packets can be
545  * attributed to a zone unambiguously. A logical interface is placed into a zone
546  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
547  * structure. Rule (1) is implemented by modifying the source address selection
548  * algorithm so that the list of eligible addresses is filtered based on the
549  * sending process zone.
550  *
551  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
552  * across all zones, depending on their type. Here is the break-up:
553  *
554  * IRE type				Shared/exclusive
555  * --------				----------------
556  * IRE_BROADCAST			Exclusive
557  * IRE_DEFAULT (default routes)		Shared (*)
558  * IRE_LOCAL				Exclusive (x)
559  * IRE_LOOPBACK				Exclusive
560  * IRE_PREFIX (net routes)		Shared (*)
561  * IRE_CACHE				Exclusive
562  * IRE_IF_NORESOLVER (interface routes)	Exclusive
563  * IRE_IF_RESOLVER (interface routes)	Exclusive
564  * IRE_HOST (host routes)		Shared (*)
565  *
566  * (*) A zone can only use a default or off-subnet route if the gateway is
567  * directly reachable from the zone, that is, if the gateway's address matches
568  * one of the zone's logical interfaces.
569  *
570  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
571  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
572  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
573  * address of the zone itself (the destination). Since IRE_LOCAL is used
574  * for communication between zones, ip_wput_ire has special logic to set
575  * the right source address when sending using an IRE_LOCAL.
576  *
577  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
578  * ire_cache_lookup restricts loopback using an IRE_LOCAL
579  * between zone to the case when L2 would have conceptually looped the packet
580  * back, i.e. the loopback which is required since neither Ethernet drivers
581  * nor Ethernet hardware loops them back. This is the case when the normal
582  * routes (ignoring IREs with different zoneids) would send out the packet on
583  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
584  * associated.
585  *
586  * Multiple zones can share a common broadcast address; typically all zones
587  * share the 255.255.255.255 address. Incoming as well as locally originated
588  * broadcast packets must be dispatched to all the zones on the broadcast
589  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
590  * since some zones may not be on the 10.16.72/24 network. To handle this, each
591  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
592  * sent to every zone that has an IRE_BROADCAST entry for the destination
593  * address on the input ill, see conn_wantpacket().
594  *
595  * Applications in different zones can join the same multicast group address.
596  * For IPv4, group memberships are per-logical interface, so they're already
597  * inherently part of a zone. For IPv6, group memberships are per-physical
598  * interface, so we distinguish IPv6 group memberships based on group address,
599  * interface and zoneid. In both cases, received multicast packets are sent to
600  * every zone for which a group membership entry exists. On IPv6 we need to
601  * check that the target zone still has an address on the receiving physical
602  * interface; it could have been removed since the application issued the
603  * IPV6_JOIN_GROUP.
604  */
605 
606 /*
607  * Squeue Fanout flags:
608  *	0: No fanout.
609  *	1: Fanout across all squeues
610  */
611 boolean_t	ip_squeue_fanout = 0;
612 
613 /*
614  * Maximum dups allowed per packet.
615  */
616 uint_t ip_max_frag_dups = 10;
617 
618 #define	IS_SIMPLE_IPH(ipha)						\
619 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
620 
621 /* RFC1122 Conformance */
622 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
623 
624 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
625 
626 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
627 
628 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
629 		    cred_t *credp, boolean_t isv6);
630 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t,
631 		    ipha_t **);
632 
633 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
634 		    ip_stack_t *);
635 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
636 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
637 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
638 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
639 		    mblk_t *, int, ip_stack_t *);
640 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
641 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
642 		    ill_t *, zoneid_t);
643 static void	icmp_options_update(ipha_t *);
644 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
645 		    ip_stack_t *);
646 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
647 		    zoneid_t zoneid, ip_stack_t *);
648 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
649 static void	icmp_redirect(ill_t *, mblk_t *);
650 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
651 		    ip_stack_t *);
652 
653 static void	ip_arp_news(queue_t *, mblk_t *);
654 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
655 		    ip_stack_t *);
656 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
657 char		*ip_dot_addr(ipaddr_t, char *);
658 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
659 int		ip_close(queue_t *, int);
660 static char	*ip_dot_saddr(uchar_t *, char *);
661 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
662 		    boolean_t, boolean_t, ill_t *, zoneid_t);
663 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
664 		    boolean_t, boolean_t, zoneid_t);
665 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
666 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
667 static void	ip_lrput(queue_t *, mblk_t *);
668 ipaddr_t	ip_net_mask(ipaddr_t);
669 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
670 		    ip_stack_t *);
671 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
672 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
673 char		*ip_nv_lookup(nv_t *, int);
674 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
675 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
676 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
677 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
678     ipndp_t *, size_t);
679 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
680 void	ip_rput(queue_t *, mblk_t *);
681 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
682 		    void *dummy_arg);
683 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
684 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
685     ip_stack_t *);
686 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
687 			    ire_t *, ip_stack_t *);
688 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
689 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
690 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
691     ip_stack_t *);
692 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
693 		    uint16_t *);
694 int		ip_snmp_get(queue_t *, mblk_t *, int);
695 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
696 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
697 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
698 		    ip_stack_t *);
699 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
700 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
701 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
703 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
704 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
705 		    ip_stack_t *ipst);
706 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
707 		    ip_stack_t *ipst);
708 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
709 		    ip_stack_t *ipst);
710 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
711 		    ip_stack_t *ipst);
712 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
713 		    ip_stack_t *ipst);
714 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
715 		    ip_stack_t *ipst);
716 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
717 		    ip_stack_t *ipst);
718 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
719 		    ip_stack_t *ipst);
720 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
721 		    ip_stack_t *ipst);
722 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
723 		    ip_stack_t *ipst);
724 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
725 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
726 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
727 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
728 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
729 static boolean_t	ip_source_route_included(ipha_t *);
730 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
731 
732 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
733 		    zoneid_t, ip_stack_t *);
734 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
735 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
736 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
737 		    zoneid_t, ip_stack_t *);
738 
739 static void	conn_drain_init(ip_stack_t *);
740 static void	conn_drain_fini(ip_stack_t *);
741 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
742 
743 static void	conn_walk_drain(ip_stack_t *);
744 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
745     zoneid_t);
746 
747 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
748 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
749 static void	ip_stack_fini(netstackid_t stackid, void *arg);
750 
751 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
752     zoneid_t);
753 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
754     void *dummy_arg);
755 
756 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
757 
758 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
759     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
760     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
761 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
762 
763 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
764 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
765     caddr_t, cred_t *);
766 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
767     caddr_t cp, cred_t *cr);
768 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
769     cred_t *);
770 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
771     caddr_t cp, cred_t *cr);
772 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
773     cred_t *);
774 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
775     cred_t *);
776 static squeue_func_t ip_squeue_switch(int);
777 
778 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
779 static void	ip_kstat_fini(netstackid_t, kstat_t *);
780 static int	ip_kstat_update(kstat_t *kp, int rw);
781 static void	*icmp_kstat_init(netstackid_t);
782 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
783 static int	icmp_kstat_update(kstat_t *kp, int rw);
784 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
785 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
786 
787 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
788 
789 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
790     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
791 
792 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
793     ipha_t *, ill_t *, boolean_t);
794 
795 static void ipobs_init(ip_stack_t *);
796 static void ipobs_fini(ip_stack_t *);
797 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
798 
799 /* How long, in seconds, we allow frags to hang around. */
800 #define	IP_FRAG_TIMEOUT	60
801 
802 /*
803  * Threshold which determines whether MDT should be used when
804  * generating IP fragments; payload size must be greater than
805  * this threshold for MDT to take place.
806  */
807 #define	IP_WPUT_FRAG_MDT_MIN	32768
808 
809 /* Setable in /etc/system only */
810 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
811 
812 static long ip_rput_pullups;
813 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
814 
815 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
816 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
817 
818 int	ip_debug;
819 
820 #ifdef DEBUG
821 uint32_t ipsechw_debug = 0;
822 #endif
823 
824 /*
825  * Multirouting/CGTP stuff
826  */
827 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
828 
829 /*
830  * XXX following really should only be in a header. Would need more
831  * header and .c clean up first.
832  */
833 extern optdb_obj_t	ip_opt_obj;
834 
835 ulong_t ip_squeue_enter_unbound = 0;
836 
837 /*
838  * Named Dispatch Parameter Table.
839  * All of these are alterable, within the min/max values given, at run time.
840  */
841 static ipparam_t	lcl_param_arr[] = {
842 	/* min	max	value	name */
843 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
844 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
845 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
846 	{  0,	1,	0,	"ip_respond_to_timestamp"},
847 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
848 	{  0,	1,	1,	"ip_send_redirects"},
849 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
850 	{  0,	10,	0,	"ip_mrtdebug"},
851 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
852 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
853 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
854 	{  1,	255,	255,	"ip_def_ttl" },
855 	{  0,	1,	0,	"ip_forward_src_routed"},
856 	{  0,	256,	32,	"ip_wroff_extra" },
857 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
858 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
859 	{  0,	1,	1,	"ip_path_mtu_discovery" },
860 	{  0,	240,	30,	"ip_ignore_delete_time" },
861 	{  0,	1,	0,	"ip_ignore_redirect" },
862 	{  0,	1,	1,	"ip_output_queue" },
863 	{  1,	254,	1,	"ip_broadcast_ttl" },
864 	{  0,	99999,	100,	"ip_icmp_err_interval" },
865 	{  1,	99999,	10,	"ip_icmp_err_burst" },
866 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
867 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
868 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
869 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
870 	{  0,	1,	1,	"icmp_accept_clear_messages" },
871 	{  0,	1,	1,	"igmp_accept_clear_messages" },
872 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
873 				"ip_ndp_delay_first_probe_time"},
874 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
875 				"ip_ndp_max_unicast_solicit"},
876 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
877 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
878 	{  0,	1,	0,	"ip6_forward_src_routed"},
879 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
880 	{  0,	1,	1,	"ip6_send_redirects"},
881 	{  0,	1,	0,	"ip6_ignore_redirect" },
882 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
883 
884 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
885 
886 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
887 
888 	{  0,	1,	1,	"pim_accept_clear_messages" },
889 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
890 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
891 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
892 	{  0,	15,	0,	"ip_policy_mask" },
893 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
894 	{  0,	255,	1,	"ip_multirt_ttl" },
895 	{  0,	1,	1,	"ip_multidata_outbound" },
896 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
897 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
898 	{  0,	1000,	1,	"ip_max_temp_defend" },
899 	{  0,	1000,	3,	"ip_max_defend" },
900 	{  0,	999999,	30,	"ip_defend_interval" },
901 	{  0,	3600000, 300000, "ip_dup_recovery" },
902 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
903 	{  0,	1,	1,	"ip_lso_outbound" },
904 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
905 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
906 #ifdef DEBUG
907 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
908 #else
909 	{  0,	0,	0,	"" },
910 #endif
911 };
912 
913 /*
914  * Extended NDP table
915  * The addresses for the first two are filled in to be ips_ip_g_forward
916  * and ips_ipv6_forward at init time.
917  */
918 static ipndp_t	lcl_ndp_arr[] = {
919 	/* getf			setf		data			name */
920 #define	IPNDP_IP_FORWARDING_OFFSET	0
921 	{  ip_param_generic_get,	ip_forward_set,	NULL,
922 	    "ip_forwarding" },
923 #define	IPNDP_IP6_FORWARDING_OFFSET	1
924 	{  ip_param_generic_get,	ip_forward_set,	NULL,
925 	    "ip6_forwarding" },
926 	{  ip_ill_report,	NULL,		NULL,
927 	    "ip_ill_status" },
928 	{  ip_ipif_report,	NULL,		NULL,
929 	    "ip_ipif_status" },
930 	{  ip_conn_report,	NULL,		NULL,
931 	    "ip_conn_status" },
932 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
933 	    "ip_rput_pullups" },
934 	{  ip_srcid_report,	NULL,		NULL,
935 	    "ip_srcid_status" },
936 	{ ip_param_generic_get, ip_squeue_profile_set,
937 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
938 	{ ip_param_generic_get, ip_squeue_bind_set,
939 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
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	11
945 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
946 	    "ip_cgtp_filter" },
947 	{ ip_param_generic_get, ip_int_set,
948 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
949 #define	IPNDP_IPMP_HOOK_OFFSET	13
950 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
951 	    "ipmp_hook_emulation" },
952 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
953 	    "ip_debug" },
954 };
955 
956 /*
957  * Table of IP ioctls encoding the various properties of the ioctl and
958  * indexed based on the last byte of the ioctl command. Occasionally there
959  * is a clash, and there is more than 1 ioctl with the same last byte.
960  * In such a case 1 ioctl is encoded in the ndx table and the remaining
961  * ioctls are encoded in the misc table. An entry in the ndx table is
962  * retrieved by indexing on the last byte of the ioctl command and comparing
963  * the ioctl command with the value in the ndx table. In the event of a
964  * mismatch the misc table is then searched sequentially for the desired
965  * ioctl command.
966  *
967  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
968  */
969 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
970 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
971 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
972 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
973 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
974 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
975 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
976 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
977 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
978 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
979 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
980 
981 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
982 			MISC_CMD, ip_siocaddrt, NULL },
983 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
984 			MISC_CMD, ip_siocdelrt, NULL },
985 
986 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
987 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
988 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
989 			IF_CMD, ip_sioctl_get_addr, NULL },
990 
991 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
992 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
993 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
994 			IPI_GET_CMD | IPI_REPL,
995 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
996 
997 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
998 			IPI_PRIV | IPI_WR | IPI_REPL,
999 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1000 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
1001 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_flags, NULL },
1003 
1004 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1005 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1006 
1007 	/* copyin size cannot be coded for SIOCGIFCONF */
1008 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
1009 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1010 
1011 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1012 			IF_CMD, ip_sioctl_mtu, NULL },
1013 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1014 			IF_CMD, ip_sioctl_get_mtu, NULL },
1015 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1016 			IPI_GET_CMD | IPI_REPL,
1017 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1018 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1019 			IF_CMD, ip_sioctl_brdaddr, NULL },
1020 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1021 			IPI_GET_CMD | IPI_REPL,
1022 			IF_CMD, ip_sioctl_get_netmask, NULL },
1023 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1024 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1025 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1026 			IPI_GET_CMD | IPI_REPL,
1027 			IF_CMD, ip_sioctl_get_metric, NULL },
1028 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1029 			IF_CMD, ip_sioctl_metric, NULL },
1030 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 
1032 	/* See 166-168 below for extended SIOC*XARP ioctls */
1033 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1034 			ARP_CMD, ip_sioctl_arp, NULL },
1035 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1036 			ARP_CMD, ip_sioctl_arp, NULL },
1037 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1038 			ARP_CMD, ip_sioctl_arp, NULL },
1039 
1040 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 
1062 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1063 			MISC_CMD, if_unitsel, if_unitsel_restart },
1064 
1065 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 
1084 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1085 			IPI_PRIV | IPI_WR | IPI_MODOK,
1086 			IF_CMD, ip_sioctl_sifname, NULL },
1087 
1088 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1089 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1090 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1091 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1092 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1093 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1094 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1095 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 
1102 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1103 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1104 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1105 			IF_CMD, ip_sioctl_get_muxid, NULL },
1106 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1107 			IPI_PRIV | IPI_WR | IPI_REPL,
1108 			IF_CMD, ip_sioctl_muxid, NULL },
1109 
1110 	/* Both if and lif variants share same func */
1111 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1112 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1113 	/* Both if and lif variants share same func */
1114 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1115 			IPI_PRIV | IPI_WR | IPI_REPL,
1116 			IF_CMD, ip_sioctl_slifindex, NULL },
1117 
1118 	/* copyin size cannot be coded for SIOCGIFCONF */
1119 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1120 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1121 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1126 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1127 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1128 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1129 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1130 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1131 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1132 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1133 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1134 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1135 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1136 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1137 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1138 
1139 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1140 			IPI_PRIV | IPI_WR | IPI_REPL,
1141 			LIF_CMD, ip_sioctl_removeif,
1142 			ip_sioctl_removeif_restart },
1143 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1144 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1145 			LIF_CMD, ip_sioctl_addif, NULL },
1146 #define	SIOCLIFADDR_NDX 112
1147 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1148 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1149 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1150 			IPI_GET_CMD | IPI_REPL,
1151 			LIF_CMD, ip_sioctl_get_addr, NULL },
1152 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1153 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1154 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1155 			IPI_GET_CMD | IPI_REPL,
1156 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1157 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1158 			IPI_PRIV | IPI_WR | IPI_REPL,
1159 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1160 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1161 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1162 			LIF_CMD, ip_sioctl_get_flags, NULL },
1163 
1164 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1165 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1166 
1167 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1168 			ip_sioctl_get_lifconf, NULL },
1169 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1170 			LIF_CMD, ip_sioctl_mtu, NULL },
1171 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1172 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1173 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1174 			IPI_GET_CMD | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1176 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1177 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1178 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1179 			IPI_GET_CMD | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1181 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1182 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1183 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1184 			IPI_GET_CMD | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_get_metric, NULL },
1186 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1187 			LIF_CMD, ip_sioctl_metric, NULL },
1188 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1189 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1190 			LIF_CMD, ip_sioctl_slifname,
1191 			ip_sioctl_slifname_restart },
1192 
1193 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1194 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1195 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1196 			IPI_GET_CMD | IPI_REPL,
1197 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1198 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1199 			IPI_PRIV | IPI_WR | IPI_REPL,
1200 			LIF_CMD, ip_sioctl_muxid, NULL },
1201 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1202 			IPI_GET_CMD | IPI_REPL,
1203 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1204 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1205 			IPI_PRIV | IPI_WR | IPI_REPL,
1206 			LIF_CMD, ip_sioctl_slifindex, 0 },
1207 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1208 			LIF_CMD, ip_sioctl_token, NULL },
1209 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1210 			IPI_GET_CMD | IPI_REPL,
1211 			LIF_CMD, ip_sioctl_get_token, NULL },
1212 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1213 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1214 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1215 			IPI_GET_CMD | IPI_REPL,
1216 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1217 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1218 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1219 
1220 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1221 			IPI_GET_CMD | IPI_REPL,
1222 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1223 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1224 			LIF_CMD, ip_siocdelndp_v6, NULL },
1225 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1226 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1227 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1228 			LIF_CMD, ip_siocsetndp_v6, NULL },
1229 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1230 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1231 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1232 			MISC_CMD, ip_sioctl_tonlink, NULL },
1233 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1234 			MISC_CMD, ip_sioctl_tmysite, NULL },
1235 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1236 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1237 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1238 		    IPI_PRIV | IPI_WR,
1239 		    TUN_CMD, ip_sioctl_tunparam, NULL },
1240 
1241 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1242 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1243 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1244 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1245 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1246 
1247 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1248 			IPI_PRIV | IPI_WR | IPI_REPL,
1249 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1250 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1251 			IPI_PRIV | IPI_WR | IPI_REPL,
1252 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1253 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1254 			IPI_PRIV | IPI_WR | IPI_REPL,
1255 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1256 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1257 			IPI_GET_CMD | IPI_REPL,
1258 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1259 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1260 			IPI_GET_CMD | IPI_REPL,
1261 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1262 
1263 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1264 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1265 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1266 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1267 
1268 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1269 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1270 
1271 	/* These are handled in ip_sioctl_copyin_setup itself */
1272 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1273 			MISC_CMD, NULL, NULL },
1274 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1275 			MISC_CMD, NULL, NULL },
1276 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1277 
1278 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1279 			ip_sioctl_get_lifconf, NULL },
1280 
1281 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1282 			XARP_CMD, ip_sioctl_arp, NULL },
1283 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1284 			XARP_CMD, ip_sioctl_arp, NULL },
1285 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1286 			XARP_CMD, ip_sioctl_arp, NULL },
1287 
1288 	/* SIOCPOPSOCKFS is not handled by IP */
1289 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1290 
1291 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1292 			IPI_GET_CMD | IPI_REPL,
1293 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1294 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1295 			IPI_PRIV | IPI_WR | IPI_REPL,
1296 			LIF_CMD, ip_sioctl_slifzone,
1297 			ip_sioctl_slifzone_restart },
1298 	/* 172-174 are SCTP ioctls and not handled by IP */
1299 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1300 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1301 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1302 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1303 			IPI_GET_CMD, LIF_CMD,
1304 			ip_sioctl_get_lifusesrc, 0 },
1305 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1306 			IPI_PRIV | IPI_WR,
1307 			LIF_CMD, ip_sioctl_slifusesrc,
1308 			NULL },
1309 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1310 			ip_sioctl_get_lifsrcof, NULL },
1311 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1312 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1313 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1314 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1315 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1316 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1317 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1318 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1319 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1320 			ip_sioctl_set_ipmpfailback, NULL },
1321 	/* SIOCSENABLESDP is handled by SDP */
1322 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1323 };
1324 
1325 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1326 
1327 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1328 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1329 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1330 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1331 		TUN_CMD, ip_sioctl_tunparam, NULL },
1332 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1333 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1334 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1335 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1336 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1337 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1338 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1339 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1340 		MISC_CMD, mrt_ioctl},
1341 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1342 		MISC_CMD, mrt_ioctl},
1343 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1344 		MISC_CMD, mrt_ioctl}
1345 };
1346 
1347 int ip_misc_ioctl_count =
1348     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1349 
1350 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1351 					/* Settable in /etc/system */
1352 /* Defined in ip_ire.c */
1353 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1354 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1355 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1356 
1357 static nv_t	ire_nv_arr[] = {
1358 	{ IRE_BROADCAST, "BROADCAST" },
1359 	{ IRE_LOCAL, "LOCAL" },
1360 	{ IRE_LOOPBACK, "LOOPBACK" },
1361 	{ IRE_CACHE, "CACHE" },
1362 	{ IRE_DEFAULT, "DEFAULT" },
1363 	{ IRE_PREFIX, "PREFIX" },
1364 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1365 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1366 	{ IRE_HOST, "HOST" },
1367 	{ 0 }
1368 };
1369 
1370 nv_t	*ire_nv_tbl = ire_nv_arr;
1371 
1372 /* Simple ICMP IP Header Template */
1373 static ipha_t icmp_ipha = {
1374 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1375 };
1376 
1377 struct module_info ip_mod_info = {
1378 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1379 };
1380 
1381 /*
1382  * Duplicate static symbols within a module confuses mdb; so we avoid the
1383  * problem by making the symbols here distinct from those in udp.c.
1384  */
1385 
1386 /*
1387  * Entry points for IP as a device and as a module.
1388  * FIXME: down the road we might want a separate module and driver qinit.
1389  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1390  */
1391 static struct qinit iprinitv4 = {
1392 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1393 	&ip_mod_info
1394 };
1395 
1396 struct qinit iprinitv6 = {
1397 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1398 	&ip_mod_info
1399 };
1400 
1401 static struct qinit ipwinitv4 = {
1402 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1403 	&ip_mod_info
1404 };
1405 
1406 struct qinit ipwinitv6 = {
1407 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1408 	&ip_mod_info
1409 };
1410 
1411 static struct qinit iplrinit = {
1412 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1413 	&ip_mod_info
1414 };
1415 
1416 static struct qinit iplwinit = {
1417 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1418 	&ip_mod_info
1419 };
1420 
1421 /* For AF_INET aka /dev/ip */
1422 struct streamtab ipinfov4 = {
1423 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1424 };
1425 
1426 /* For AF_INET6 aka /dev/ip6 */
1427 struct streamtab ipinfov6 = {
1428 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1429 };
1430 
1431 #ifdef	DEBUG
1432 static boolean_t skip_sctp_cksum = B_FALSE;
1433 #endif
1434 
1435 /*
1436  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1437  * ip_rput_v6(), ip_output(), etc.  If the message
1438  * block already has a M_CTL at the front of it, then simply set the zoneid
1439  * appropriately.
1440  */
1441 mblk_t *
1442 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1443 {
1444 	mblk_t		*first_mp;
1445 	ipsec_out_t	*io;
1446 
1447 	ASSERT(zoneid != ALL_ZONES);
1448 	if (mp->b_datap->db_type == M_CTL) {
1449 		io = (ipsec_out_t *)mp->b_rptr;
1450 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1451 		io->ipsec_out_zoneid = zoneid;
1452 		return (mp);
1453 	}
1454 
1455 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1456 	if (first_mp == NULL)
1457 		return (NULL);
1458 	io = (ipsec_out_t *)first_mp->b_rptr;
1459 	/* This is not a secure packet */
1460 	io->ipsec_out_secure = B_FALSE;
1461 	io->ipsec_out_zoneid = zoneid;
1462 	first_mp->b_cont = mp;
1463 	return (first_mp);
1464 }
1465 
1466 /*
1467  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1468  */
1469 mblk_t *
1470 ip_copymsg(mblk_t *mp)
1471 {
1472 	mblk_t *nmp;
1473 	ipsec_info_t *in;
1474 
1475 	if (mp->b_datap->db_type != M_CTL)
1476 		return (copymsg(mp));
1477 
1478 	in = (ipsec_info_t *)mp->b_rptr;
1479 
1480 	/*
1481 	 * Note that M_CTL is also used for delivering ICMP error messages
1482 	 * upstream to transport layers.
1483 	 */
1484 	if (in->ipsec_info_type != IPSEC_OUT &&
1485 	    in->ipsec_info_type != IPSEC_IN)
1486 		return (copymsg(mp));
1487 
1488 	nmp = copymsg(mp->b_cont);
1489 
1490 	if (in->ipsec_info_type == IPSEC_OUT) {
1491 		return (ipsec_out_tag(mp, nmp,
1492 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1493 	} else {
1494 		return (ipsec_in_tag(mp, nmp,
1495 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1496 	}
1497 }
1498 
1499 /* Generate an ICMP fragmentation needed message. */
1500 static void
1501 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1502     ip_stack_t *ipst)
1503 {
1504 	icmph_t	icmph;
1505 	mblk_t *first_mp;
1506 	boolean_t mctl_present;
1507 
1508 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1509 
1510 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1511 		if (mctl_present)
1512 			freeb(first_mp);
1513 		return;
1514 	}
1515 
1516 	bzero(&icmph, sizeof (icmph_t));
1517 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1518 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1519 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1520 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1521 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1522 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1523 	    ipst);
1524 }
1525 
1526 /*
1527  * icmp_inbound deals with ICMP messages in the following ways.
1528  *
1529  * 1) It needs to send a reply back and possibly delivering it
1530  *    to the "interested" upper clients.
1531  * 2) It needs to send it to the upper clients only.
1532  * 3) It needs to change some values in IP only.
1533  * 4) It needs to change some values in IP and upper layers e.g TCP.
1534  *
1535  * We need to accomodate icmp messages coming in clear until we get
1536  * everything secure from the wire. If icmp_accept_clear_messages
1537  * is zero we check with the global policy and act accordingly. If
1538  * it is non-zero, we accept the message without any checks. But
1539  * *this does not mean* that this will be delivered to the upper
1540  * clients. By accepting we might send replies back, change our MTU
1541  * value etc. but delivery to the ULP/clients depends on their policy
1542  * dispositions.
1543  *
1544  * We handle the above 4 cases in the context of IPsec in the
1545  * following way :
1546  *
1547  * 1) Send the reply back in the same way as the request came in.
1548  *    If it came in encrypted, it goes out encrypted. If it came in
1549  *    clear, it goes out in clear. Thus, this will prevent chosen
1550  *    plain text attack.
1551  * 2) The client may or may not expect things to come in secure.
1552  *    If it comes in secure, the policy constraints are checked
1553  *    before delivering it to the upper layers. If it comes in
1554  *    clear, ipsec_inbound_accept_clear will decide whether to
1555  *    accept this in clear or not. In both the cases, if the returned
1556  *    message (IP header + 8 bytes) that caused the icmp message has
1557  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1558  *    sending up. If there are only 8 bytes of returned message, then
1559  *    upper client will not be notified.
1560  * 3) Check with global policy to see whether it matches the constaints.
1561  *    But this will be done only if icmp_accept_messages_in_clear is
1562  *    zero.
1563  * 4) If we need to change both in IP and ULP, then the decision taken
1564  *    while affecting the values in IP and while delivering up to TCP
1565  *    should be the same.
1566  *
1567  * 	There are two cases.
1568  *
1569  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1570  *	   failed), we will not deliver it to the ULP, even though they
1571  *	   are *willing* to accept in *clear*. This is fine as our global
1572  *	   disposition to icmp messages asks us reject the datagram.
1573  *
1574  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1575  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1576  *	   to deliver it to ULP (policy failed), it can lead to
1577  *	   consistency problems. The cases known at this time are
1578  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1579  *	   values :
1580  *
1581  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1582  *	     and Upper layer rejects. Then the communication will
1583  *	     come to a stop. This is solved by making similar decisions
1584  *	     at both levels. Currently, when we are unable to deliver
1585  *	     to the Upper Layer (due to policy failures) while IP has
1586  *	     adjusted ire_max_frag, the next outbound datagram would
1587  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1588  *	     will be with the right level of protection. Thus the right
1589  *	     value will be communicated even if we are not able to
1590  *	     communicate when we get from the wire initially. But this
1591  *	     assumes there would be at least one outbound datagram after
1592  *	     IP has adjusted its ire_max_frag value. To make things
1593  *	     simpler, we accept in clear after the validation of
1594  *	     AH/ESP headers.
1595  *
1596  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1597  *	     upper layer depending on the level of protection the upper
1598  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1599  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1600  *	     should be accepted in clear when the Upper layer expects secure.
1601  *	     Thus the communication may get aborted by some bad ICMP
1602  *	     packets.
1603  *
1604  * IPQoS Notes:
1605  * The only instance when a packet is sent for processing is when there
1606  * isn't an ICMP client and if we are interested in it.
1607  * If there is a client, IPPF processing will take place in the
1608  * ip_fanout_proto routine.
1609  *
1610  * Zones notes:
1611  * The packet is only processed in the context of the specified zone: typically
1612  * only this zone will reply to an echo request, and only interested clients in
1613  * this zone will receive a copy of the packet. This means that the caller must
1614  * call icmp_inbound() for each relevant zone.
1615  */
1616 static void
1617 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1618     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1619     ill_t *recv_ill, zoneid_t zoneid)
1620 {
1621 	icmph_t	*icmph;
1622 	ipha_t	*ipha;
1623 	int	iph_hdr_length;
1624 	int	hdr_length;
1625 	boolean_t	interested;
1626 	uint32_t	ts;
1627 	uchar_t	*wptr;
1628 	ipif_t	*ipif;
1629 	mblk_t *first_mp;
1630 	ipsec_in_t *ii;
1631 	ire_t *src_ire;
1632 	boolean_t onlink;
1633 	timestruc_t now;
1634 	uint32_t ill_index;
1635 	ip_stack_t *ipst;
1636 
1637 	ASSERT(ill != NULL);
1638 	ipst = ill->ill_ipst;
1639 
1640 	first_mp = mp;
1641 	if (mctl_present) {
1642 		mp = first_mp->b_cont;
1643 		ASSERT(mp != NULL);
1644 	}
1645 
1646 	ipha = (ipha_t *)mp->b_rptr;
1647 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1648 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1649 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1650 		if (first_mp == NULL)
1651 			return;
1652 	}
1653 
1654 	/*
1655 	 * On a labeled system, we have to check whether the zone itself is
1656 	 * permitted to receive raw traffic.
1657 	 */
1658 	if (is_system_labeled()) {
1659 		if (zoneid == ALL_ZONES)
1660 			zoneid = tsol_packet_to_zoneid(mp);
1661 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1662 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1663 			    zoneid));
1664 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1665 			freemsg(first_mp);
1666 			return;
1667 		}
1668 	}
1669 
1670 	/*
1671 	 * We have accepted the ICMP message. It means that we will
1672 	 * respond to the packet if needed. It may not be delivered
1673 	 * to the upper client depending on the policy constraints
1674 	 * and the disposition in ipsec_inbound_accept_clear.
1675 	 */
1676 
1677 	ASSERT(ill != NULL);
1678 
1679 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1680 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1681 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1682 		/* Last chance to get real. */
1683 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1684 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1685 			freemsg(first_mp);
1686 			return;
1687 		}
1688 		/* Refresh iph following the pullup. */
1689 		ipha = (ipha_t *)mp->b_rptr;
1690 	}
1691 	/* ICMP header checksum, including checksum field, should be zero. */
1692 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1693 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1694 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1695 		freemsg(first_mp);
1696 		return;
1697 	}
1698 	/* The IP header will always be a multiple of four bytes */
1699 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1700 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1701 	    icmph->icmph_code));
1702 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1703 	/* We will set "interested" to "true" if we want a copy */
1704 	interested = B_FALSE;
1705 	switch (icmph->icmph_type) {
1706 	case ICMP_ECHO_REPLY:
1707 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1708 		break;
1709 	case ICMP_DEST_UNREACHABLE:
1710 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1711 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1712 		interested = B_TRUE;	/* Pass up to transport */
1713 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1714 		break;
1715 	case ICMP_SOURCE_QUENCH:
1716 		interested = B_TRUE;	/* Pass up to transport */
1717 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1718 		break;
1719 	case ICMP_REDIRECT:
1720 		if (!ipst->ips_ip_ignore_redirect)
1721 			interested = B_TRUE;
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1723 		break;
1724 	case ICMP_ECHO_REQUEST:
1725 		/*
1726 		 * Whether to respond to echo requests that come in as IP
1727 		 * broadcasts or as IP multicast is subject to debate
1728 		 * (what isn't?).  We aim to please, you pick it.
1729 		 * Default is do it.
1730 		 */
1731 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1732 			/* unicast: always respond */
1733 			interested = B_TRUE;
1734 		} else if (CLASSD(ipha->ipha_dst)) {
1735 			/* multicast: respond based on tunable */
1736 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1737 		} else if (broadcast) {
1738 			/* broadcast: respond based on tunable */
1739 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1740 		}
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1742 		break;
1743 	case ICMP_ROUTER_ADVERTISEMENT:
1744 	case ICMP_ROUTER_SOLICITATION:
1745 		break;
1746 	case ICMP_TIME_EXCEEDED:
1747 		interested = B_TRUE;	/* Pass up to transport */
1748 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1749 		break;
1750 	case ICMP_PARAM_PROBLEM:
1751 		interested = B_TRUE;	/* Pass up to transport */
1752 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1753 		break;
1754 	case ICMP_TIME_STAMP_REQUEST:
1755 		/* Response to Time Stamp Requests is local policy. */
1756 		if (ipst->ips_ip_g_resp_to_timestamp &&
1757 		    /* So is whether to respond if it was an IP broadcast. */
1758 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1759 			int tstamp_len = 3 * sizeof (uint32_t);
1760 
1761 			if (wptr +  tstamp_len > mp->b_wptr) {
1762 				if (!pullupmsg(mp, wptr + tstamp_len -
1763 				    mp->b_rptr)) {
1764 					BUMP_MIB(ill->ill_ip_mib,
1765 					    ipIfStatsInDiscards);
1766 					freemsg(first_mp);
1767 					return;
1768 				}
1769 				/* Refresh ipha following the pullup. */
1770 				ipha = (ipha_t *)mp->b_rptr;
1771 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1772 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1773 			}
1774 			interested = B_TRUE;
1775 		}
1776 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1777 		break;
1778 	case ICMP_TIME_STAMP_REPLY:
1779 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1780 		break;
1781 	case ICMP_INFO_REQUEST:
1782 		/* Per RFC 1122 3.2.2.7, ignore this. */
1783 	case ICMP_INFO_REPLY:
1784 		break;
1785 	case ICMP_ADDRESS_MASK_REQUEST:
1786 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1787 		    !broadcast) &&
1788 		    /* TODO m_pullup of complete header? */
1789 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1790 			interested = B_TRUE;
1791 		}
1792 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1793 		break;
1794 	case ICMP_ADDRESS_MASK_REPLY:
1795 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1796 		break;
1797 	default:
1798 		interested = B_TRUE;	/* Pass up to transport */
1799 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1800 		break;
1801 	}
1802 	/* See if there is an ICMP client. */
1803 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1804 		/* If there is an ICMP client and we want one too, copy it. */
1805 		mblk_t *first_mp1;
1806 
1807 		if (!interested) {
1808 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1809 			    ip_policy, recv_ill, zoneid);
1810 			return;
1811 		}
1812 		first_mp1 = ip_copymsg(first_mp);
1813 		if (first_mp1 != NULL) {
1814 			ip_fanout_proto(q, first_mp1, ill, ipha,
1815 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1816 		}
1817 	} else if (!interested) {
1818 		freemsg(first_mp);
1819 		return;
1820 	} else {
1821 		/*
1822 		 * Initiate policy processing for this packet if ip_policy
1823 		 * is true.
1824 		 */
1825 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1826 			ill_index = ill->ill_phyint->phyint_ifindex;
1827 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1828 			if (mp == NULL) {
1829 				if (mctl_present) {
1830 					freeb(first_mp);
1831 				}
1832 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1833 				return;
1834 			}
1835 		}
1836 	}
1837 	/* We want to do something with it. */
1838 	/* Check db_ref to make sure we can modify the packet. */
1839 	if (mp->b_datap->db_ref > 1) {
1840 		mblk_t	*first_mp1;
1841 
1842 		first_mp1 = ip_copymsg(first_mp);
1843 		freemsg(first_mp);
1844 		if (!first_mp1) {
1845 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1846 			return;
1847 		}
1848 		first_mp = first_mp1;
1849 		if (mctl_present) {
1850 			mp = first_mp->b_cont;
1851 			ASSERT(mp != NULL);
1852 		} else {
1853 			mp = first_mp;
1854 		}
1855 		ipha = (ipha_t *)mp->b_rptr;
1856 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1857 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1858 	}
1859 	switch (icmph->icmph_type) {
1860 	case ICMP_ADDRESS_MASK_REQUEST:
1861 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1862 		if (ipif == NULL) {
1863 			freemsg(first_mp);
1864 			return;
1865 		}
1866 		/*
1867 		 * outging interface must be IPv4
1868 		 */
1869 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1870 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1871 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1872 		ipif_refrele(ipif);
1873 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1874 		break;
1875 	case ICMP_ECHO_REQUEST:
1876 		icmph->icmph_type = ICMP_ECHO_REPLY;
1877 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1878 		break;
1879 	case ICMP_TIME_STAMP_REQUEST: {
1880 		uint32_t *tsp;
1881 
1882 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1883 		tsp = (uint32_t *)wptr;
1884 		tsp++;		/* Skip past 'originate time' */
1885 		/* Compute # of milliseconds since midnight */
1886 		gethrestime(&now);
1887 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1888 		    now.tv_nsec / (NANOSEC / MILLISEC);
1889 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1890 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1891 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1892 		break;
1893 	}
1894 	default:
1895 		ipha = (ipha_t *)&icmph[1];
1896 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1897 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1898 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1899 				freemsg(first_mp);
1900 				return;
1901 			}
1902 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1903 			ipha = (ipha_t *)&icmph[1];
1904 		}
1905 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1906 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1907 			freemsg(first_mp);
1908 			return;
1909 		}
1910 		hdr_length = IPH_HDR_LENGTH(ipha);
1911 		if (hdr_length < sizeof (ipha_t)) {
1912 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1913 			freemsg(first_mp);
1914 			return;
1915 		}
1916 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1917 			if (!pullupmsg(mp,
1918 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1919 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1920 				freemsg(first_mp);
1921 				return;
1922 			}
1923 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1924 			ipha = (ipha_t *)&icmph[1];
1925 		}
1926 		switch (icmph->icmph_type) {
1927 		case ICMP_REDIRECT:
1928 			/*
1929 			 * As there is no upper client to deliver, we don't
1930 			 * need the first_mp any more.
1931 			 */
1932 			if (mctl_present) {
1933 				freeb(first_mp);
1934 			}
1935 			icmp_redirect(ill, mp);
1936 			return;
1937 		case ICMP_DEST_UNREACHABLE:
1938 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1939 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1940 				    zoneid, mp, iph_hdr_length, ipst)) {
1941 					freemsg(first_mp);
1942 					return;
1943 				}
1944 				/*
1945 				 * icmp_inbound_too_big() may alter mp.
1946 				 * Resynch ipha and icmph accordingly.
1947 				 */
1948 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1949 				ipha = (ipha_t *)&icmph[1];
1950 			}
1951 			/* FALLTHRU */
1952 		default :
1953 			/*
1954 			 * IPQoS notes: Since we have already done IPQoS
1955 			 * processing we don't want to do it again in
1956 			 * the fanout routines called by
1957 			 * icmp_inbound_error_fanout, hence the last
1958 			 * argument, ip_policy, is B_FALSE.
1959 			 */
1960 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1961 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1962 			    B_FALSE, recv_ill, zoneid);
1963 		}
1964 		return;
1965 	}
1966 	/* Send out an ICMP packet */
1967 	icmph->icmph_checksum = 0;
1968 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1969 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1970 		ipif_t	*ipif_chosen;
1971 		/*
1972 		 * Make it look like it was directed to us, so we don't look
1973 		 * like a fool with a broadcast or multicast source address.
1974 		 */
1975 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1976 		/*
1977 		 * Make sure that we haven't grabbed an interface that's DOWN.
1978 		 */
1979 		if (ipif != NULL) {
1980 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1981 			    ipha->ipha_src, zoneid);
1982 			if (ipif_chosen != NULL) {
1983 				ipif_refrele(ipif);
1984 				ipif = ipif_chosen;
1985 			}
1986 		}
1987 		if (ipif == NULL) {
1988 			ip0dbg(("icmp_inbound: "
1989 			    "No source for broadcast/multicast:\n"
1990 			    "\tsrc 0x%x dst 0x%x ill %p "
1991 			    "ipif_lcl_addr 0x%x\n",
1992 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1993 			    (void *)ill,
1994 			    ill->ill_ipif->ipif_lcl_addr));
1995 			freemsg(first_mp);
1996 			return;
1997 		}
1998 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1999 		ipha->ipha_dst = ipif->ipif_src_addr;
2000 		ipif_refrele(ipif);
2001 	}
2002 	/* Reset time to live. */
2003 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
2004 	{
2005 		/* Swap source and destination addresses */
2006 		ipaddr_t tmp;
2007 
2008 		tmp = ipha->ipha_src;
2009 		ipha->ipha_src = ipha->ipha_dst;
2010 		ipha->ipha_dst = tmp;
2011 	}
2012 	ipha->ipha_ident = 0;
2013 	if (!IS_SIMPLE_IPH(ipha))
2014 		icmp_options_update(ipha);
2015 
2016 	/*
2017 	 * ICMP echo replies should go out on the same interface
2018 	 * the request came on as probes used by in.mpathd for detecting
2019 	 * NIC failures are ECHO packets. We turn-off load spreading
2020 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2021 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2022 	 * function. This is in turn handled by ip_wput and ip_newroute
2023 	 * to make sure that the packet goes out on the interface it came
2024 	 * in on. If we don't turnoff load spreading, the packets might get
2025 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2026 	 * to go out and in.mpathd would wrongly detect a failure or
2027 	 * mis-detect a NIC failure for link failure. As load spreading
2028 	 * can happen only if ill_group is not NULL, we do only for
2029 	 * that case and this does not affect the normal case.
2030 	 *
2031 	 * We turn off load spreading only on echo packets that came from
2032 	 * on-link hosts. If the interface route has been deleted, this will
2033 	 * not be enforced as we can't do much. For off-link hosts, as the
2034 	 * default routes in IPv4 does not typically have an ire_ipif
2035 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2036 	 * Moreover, expecting a default route through this interface may
2037 	 * not be correct. We use ipha_dst because of the swap above.
2038 	 */
2039 	onlink = B_FALSE;
2040 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2041 		/*
2042 		 * First, we need to make sure that it is not one of our
2043 		 * local addresses. If we set onlink when it is one of
2044 		 * our local addresses, we will end up creating IRE_CACHES
2045 		 * for one of our local addresses. Then, we will never
2046 		 * accept packets for them afterwards.
2047 		 */
2048 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2049 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2050 		if (src_ire == NULL) {
2051 			ipif = ipif_get_next_ipif(NULL, ill);
2052 			if (ipif == NULL) {
2053 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2054 				freemsg(mp);
2055 				return;
2056 			}
2057 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2058 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2059 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2060 			ipif_refrele(ipif);
2061 			if (src_ire != NULL) {
2062 				onlink = B_TRUE;
2063 				ire_refrele(src_ire);
2064 			}
2065 		} else {
2066 			ire_refrele(src_ire);
2067 		}
2068 	}
2069 	if (!mctl_present) {
2070 		/*
2071 		 * This packet should go out the same way as it
2072 		 * came in i.e in clear. To make sure that global
2073 		 * policy will not be applied to this in ip_wput_ire,
2074 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2075 		 */
2076 		ASSERT(first_mp == mp);
2077 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2078 		if (first_mp == NULL) {
2079 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2080 			freemsg(mp);
2081 			return;
2082 		}
2083 		ii = (ipsec_in_t *)first_mp->b_rptr;
2084 
2085 		/* This is not a secure packet */
2086 		ii->ipsec_in_secure = B_FALSE;
2087 		if (onlink) {
2088 			ii->ipsec_in_attach_if = B_TRUE;
2089 			ii->ipsec_in_ill_index =
2090 			    ill->ill_phyint->phyint_ifindex;
2091 			ii->ipsec_in_rill_index =
2092 			    recv_ill->ill_phyint->phyint_ifindex;
2093 		}
2094 		first_mp->b_cont = mp;
2095 	} else if (onlink) {
2096 		ii = (ipsec_in_t *)first_mp->b_rptr;
2097 		ii->ipsec_in_attach_if = B_TRUE;
2098 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2099 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2100 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2101 	} else {
2102 		ii = (ipsec_in_t *)first_mp->b_rptr;
2103 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2104 	}
2105 	ii->ipsec_in_zoneid = zoneid;
2106 	ASSERT(zoneid != ALL_ZONES);
2107 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2108 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2109 		return;
2110 	}
2111 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2112 	put(WR(q), first_mp);
2113 }
2114 
2115 static ipaddr_t
2116 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2117 {
2118 	conn_t *connp;
2119 	connf_t *connfp;
2120 	ipaddr_t nexthop_addr = INADDR_ANY;
2121 	int hdr_length = IPH_HDR_LENGTH(ipha);
2122 	uint16_t *up;
2123 	uint32_t ports;
2124 	ip_stack_t *ipst = ill->ill_ipst;
2125 
2126 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2127 	switch (ipha->ipha_protocol) {
2128 		case IPPROTO_TCP:
2129 		{
2130 			tcph_t *tcph;
2131 
2132 			/* do a reverse lookup */
2133 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2134 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2135 			    TCPS_LISTEN, ipst);
2136 			break;
2137 		}
2138 		case IPPROTO_UDP:
2139 		{
2140 			uint32_t dstport, srcport;
2141 
2142 			((uint16_t *)&ports)[0] = up[1];
2143 			((uint16_t *)&ports)[1] = up[0];
2144 
2145 			/* Extract ports in net byte order */
2146 			dstport = htons(ntohl(ports) & 0xFFFF);
2147 			srcport = htons(ntohl(ports) >> 16);
2148 
2149 			connfp = &ipst->ips_ipcl_udp_fanout[
2150 			    IPCL_UDP_HASH(dstport, ipst)];
2151 			mutex_enter(&connfp->connf_lock);
2152 			connp = connfp->connf_head;
2153 
2154 			/* do a reverse lookup */
2155 			while ((connp != NULL) &&
2156 			    (!IPCL_UDP_MATCH(connp, dstport,
2157 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2158 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2159 				connp = connp->conn_next;
2160 			}
2161 			if (connp != NULL)
2162 				CONN_INC_REF(connp);
2163 			mutex_exit(&connfp->connf_lock);
2164 			break;
2165 		}
2166 		case IPPROTO_SCTP:
2167 		{
2168 			in6_addr_t map_src, map_dst;
2169 
2170 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2171 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2172 			((uint16_t *)&ports)[0] = up[1];
2173 			((uint16_t *)&ports)[1] = up[0];
2174 
2175 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2176 			    zoneid, ipst->ips_netstack->netstack_sctp);
2177 			if (connp == NULL) {
2178 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2179 				    zoneid, ports, ipha, ipst);
2180 			} else {
2181 				CONN_INC_REF(connp);
2182 				SCTP_REFRELE(CONN2SCTP(connp));
2183 			}
2184 			break;
2185 		}
2186 		default:
2187 		{
2188 			ipha_t ripha;
2189 
2190 			ripha.ipha_src = ipha->ipha_dst;
2191 			ripha.ipha_dst = ipha->ipha_src;
2192 			ripha.ipha_protocol = ipha->ipha_protocol;
2193 
2194 			connfp = &ipst->ips_ipcl_proto_fanout[
2195 			    ipha->ipha_protocol];
2196 			mutex_enter(&connfp->connf_lock);
2197 			connp = connfp->connf_head;
2198 			for (connp = connfp->connf_head; connp != NULL;
2199 			    connp = connp->conn_next) {
2200 				if (IPCL_PROTO_MATCH(connp,
2201 				    ipha->ipha_protocol, &ripha, ill,
2202 				    0, zoneid)) {
2203 					CONN_INC_REF(connp);
2204 					break;
2205 				}
2206 			}
2207 			mutex_exit(&connfp->connf_lock);
2208 		}
2209 	}
2210 	if (connp != NULL) {
2211 		if (connp->conn_nexthop_set)
2212 			nexthop_addr = connp->conn_nexthop_v4;
2213 		CONN_DEC_REF(connp);
2214 	}
2215 	return (nexthop_addr);
2216 }
2217 
2218 /* Table from RFC 1191 */
2219 static int icmp_frag_size_table[] =
2220 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2221 
2222 /*
2223  * Process received ICMP Packet too big.
2224  * After updating any IRE it does the fanout to any matching transport streams.
2225  * Assumes the message has been pulled up till the IP header that caused
2226  * the error.
2227  *
2228  * Returns B_FALSE on failure and B_TRUE on success.
2229  */
2230 static boolean_t
2231 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2232     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2233     ip_stack_t *ipst)
2234 {
2235 	ire_t	*ire, *first_ire;
2236 	int	mtu;
2237 	int	hdr_length;
2238 	ipaddr_t nexthop_addr;
2239 
2240 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2241 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2242 	ASSERT(ill != NULL);
2243 
2244 	hdr_length = IPH_HDR_LENGTH(ipha);
2245 
2246 	/* Drop if the original packet contained a source route */
2247 	if (ip_source_route_included(ipha)) {
2248 		return (B_FALSE);
2249 	}
2250 	/*
2251 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2252 	 * header.
2253 	 */
2254 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2255 	    mp->b_wptr) {
2256 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2257 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2258 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2259 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2260 			return (B_FALSE);
2261 		}
2262 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2263 		ipha = (ipha_t *)&icmph[1];
2264 	}
2265 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2266 	if (nexthop_addr != INADDR_ANY) {
2267 		/* nexthop set */
2268 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2269 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2270 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2271 	} else {
2272 		/* nexthop not set */
2273 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2274 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2275 	}
2276 
2277 	if (!first_ire) {
2278 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2279 		    ntohl(ipha->ipha_dst)));
2280 		return (B_FALSE);
2281 	}
2282 	/* Check for MTU discovery advice as described in RFC 1191 */
2283 	mtu = ntohs(icmph->icmph_du_mtu);
2284 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2285 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2286 	    ire = ire->ire_next) {
2287 		/*
2288 		 * Look for the connection to which this ICMP message is
2289 		 * directed. If it has the IP_NEXTHOP option set, then the
2290 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2291 		 * option. Else the search is limited to regular IREs.
2292 		 */
2293 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2294 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2295 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2296 		    (nexthop_addr != INADDR_ANY)))
2297 			continue;
2298 
2299 		mutex_enter(&ire->ire_lock);
2300 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2301 			/* Reduce the IRE max frag value as advised. */
2302 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2303 			    mtu, ire->ire_max_frag));
2304 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2305 		} else {
2306 			uint32_t length;
2307 			int	i;
2308 
2309 			/*
2310 			 * Use the table from RFC 1191 to figure out
2311 			 * the next "plateau" based on the length in
2312 			 * the original IP packet.
2313 			 */
2314 			length = ntohs(ipha->ipha_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 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2323 				    length, ire->ire_max_frag));
2324 				length -= hdr_length;
2325 			}
2326 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2327 				if (length > icmp_frag_size_table[i])
2328 					break;
2329 			}
2330 			if (i == A_CNT(icmp_frag_size_table)) {
2331 				/* Smaller than 68! */
2332 				ip1dbg(("Too big for packet size %d\n",
2333 				    length));
2334 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2335 				ire->ire_frag_flag = 0;
2336 			} else {
2337 				mtu = icmp_frag_size_table[i];
2338 				ip1dbg(("Calculated mtu %d, packet size %d, "
2339 				    "before %d", mtu, length,
2340 				    ire->ire_max_frag));
2341 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2342 				ip1dbg((", after %d\n", ire->ire_max_frag));
2343 			}
2344 			/* Record the new max frag size for the ULP. */
2345 			icmph->icmph_du_zero = 0;
2346 			icmph->icmph_du_mtu =
2347 			    htons((uint16_t)ire->ire_max_frag);
2348 		}
2349 		mutex_exit(&ire->ire_lock);
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_fill(connp->conn_sqp, first_mp, tcp_input,
2565 		    connp, 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 	clock_t timeout;
5368 
5369 	/*
5370 	 * Wait for the ACKs of all deferred control messages to be processed.
5371 	 * In particular, we wait for a potential capability reset initiated
5372 	 * in ip_sioctl_plink() to complete before proceeding.
5373 	 *
5374 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5375 	 * in case the driver never replies.
5376 	 */
5377 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5378 	mutex_enter(&ill->ill_lock);
5379 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5380 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5381 			/* Timeout */
5382 			break;
5383 		}
5384 	}
5385 	mutex_exit(&ill->ill_lock);
5386 
5387 	/*
5388 	 * Forcibly enter the ipsq after some delay. This is to take
5389 	 * care of the case when some ioctl does not complete because
5390 	 * we sent a control message to the driver and it did not
5391 	 * send us a reply. We want to be able to at least unplumb
5392 	 * and replumb rather than force the user to reboot the system.
5393 	 */
5394 	success = ipsq_enter(ill, B_FALSE);
5395 
5396 	/*
5397 	 * Open/close/push/pop is guaranteed to be single threaded
5398 	 * per stream by STREAMS. FS guarantees that all references
5399 	 * from top are gone before close is called. So there can't
5400 	 * be another close thread that has set CONDEMNED on this ill.
5401 	 * and cause ipsq_enter to return failure.
5402 	 */
5403 	ASSERT(success);
5404 	ipsq = ill->ill_phyint->phyint_ipsq;
5405 
5406 	/*
5407 	 * Mark it condemned. No new reference will be made to this ill.
5408 	 * Lookup functions will return an error. Threads that try to
5409 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5410 	 * that the refcnt will drop down to zero.
5411 	 */
5412 	mutex_enter(&ill->ill_lock);
5413 	ill->ill_state_flags |= ILL_CONDEMNED;
5414 	for (ipif = ill->ill_ipif; ipif != NULL;
5415 	    ipif = ipif->ipif_next) {
5416 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5417 	}
5418 	/*
5419 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5420 	 * returns  error if ILL_CONDEMNED is set
5421 	 */
5422 	cv_broadcast(&ill->ill_cv);
5423 	mutex_exit(&ill->ill_lock);
5424 
5425 	/*
5426 	 * Send all the deferred DLPI messages downstream which came in
5427 	 * during the small window right before ipsq_enter(). We do this
5428 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5429 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5430 	 */
5431 	ill_dlpi_send_deferred(ill);
5432 
5433 	/*
5434 	 * Shut down fragmentation reassembly.
5435 	 * ill_frag_timer won't start a timer again.
5436 	 * Now cancel any existing timer
5437 	 */
5438 	(void) untimeout(ill->ill_frag_timer_id);
5439 	(void) ill_frag_timeout(ill, 0);
5440 
5441 	/*
5442 	 * If MOVE was in progress, clear the
5443 	 * move_in_progress fields also.
5444 	 */
5445 	if (ill->ill_move_in_progress) {
5446 		ILL_CLEAR_MOVE(ill);
5447 	}
5448 
5449 	/*
5450 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5451 	 * this ill. Then wait for the refcnts to drop to zero.
5452 	 * ill_is_freeable checks whether the ill is really quiescent.
5453 	 * Then make sure that threads that are waiting to enter the
5454 	 * ipsq have seen the error returned by ipsq_enter and have
5455 	 * gone away. Then we call ill_delete_tail which does the
5456 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5457 	 */
5458 	ill_delete(ill);
5459 	mutex_enter(&ill->ill_lock);
5460 	while (!ill_is_freeable(ill))
5461 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5462 	while (ill->ill_waiters)
5463 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5464 
5465 	mutex_exit(&ill->ill_lock);
5466 
5467 	/*
5468 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5469 	 * it held until the end of the function since the cleanup
5470 	 * below needs to be able to use the ip_stack_t.
5471 	 */
5472 	netstack_hold(ipst->ips_netstack);
5473 
5474 	/* qprocsoff is called in ill_delete_tail */
5475 	ill_delete_tail(ill);
5476 	ASSERT(ill->ill_ipst == NULL);
5477 
5478 	/*
5479 	 * Walk through all upper (conn) streams and qenable
5480 	 * those that have queued data.
5481 	 * close synchronization needs this to
5482 	 * be done to ensure that all upper layers blocked
5483 	 * due to flow control to the closing device
5484 	 * get unblocked.
5485 	 */
5486 	ip1dbg(("ip_wsrv: walking\n"));
5487 	conn_walk_drain(ipst);
5488 
5489 	mutex_enter(&ipst->ips_ip_mi_lock);
5490 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5491 	mutex_exit(&ipst->ips_ip_mi_lock);
5492 
5493 	/*
5494 	 * credp could be null if the open didn't succeed and ip_modopen
5495 	 * itself calls ip_close.
5496 	 */
5497 	if (ill->ill_credp != NULL)
5498 		crfree(ill->ill_credp);
5499 
5500 	/*
5501 	 * Now we are done with the module close pieces that
5502 	 * need the netstack_t.
5503 	 */
5504 	netstack_rele(ipst->ips_netstack);
5505 
5506 	mi_close_free((IDP)ill);
5507 	q->q_ptr = WR(q)->q_ptr = NULL;
5508 
5509 	ipsq_exit(ipsq);
5510 
5511 	return (0);
5512 }
5513 
5514 /*
5515  * This is called as part of close() for IP, UDP, ICMP, and RTS
5516  * in order to quiesce the conn.
5517  */
5518 void
5519 ip_quiesce_conn(conn_t *connp)
5520 {
5521 	boolean_t	drain_cleanup_reqd = B_FALSE;
5522 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5523 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5524 	ip_stack_t	*ipst;
5525 
5526 	ASSERT(!IPCL_IS_TCP(connp));
5527 	ipst = connp->conn_netstack->netstack_ip;
5528 
5529 	/*
5530 	 * Mark the conn as closing, and this conn must not be
5531 	 * inserted in future into any list. Eg. conn_drain_insert(),
5532 	 * won't insert this conn into the conn_drain_list.
5533 	 * Similarly ill_pending_mp_add() will not add any mp to
5534 	 * the pending mp list, after this conn has started closing.
5535 	 *
5536 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5537 	 * cannot get set henceforth.
5538 	 */
5539 	mutex_enter(&connp->conn_lock);
5540 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5541 	connp->conn_state_flags |= CONN_CLOSING;
5542 	if (connp->conn_idl != NULL)
5543 		drain_cleanup_reqd = B_TRUE;
5544 	if (connp->conn_oper_pending_ill != NULL)
5545 		conn_ioctl_cleanup_reqd = B_TRUE;
5546 	if (connp->conn_dhcpinit_ill != NULL) {
5547 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5548 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5549 		connp->conn_dhcpinit_ill = NULL;
5550 	}
5551 	if (connp->conn_ilg_inuse != 0)
5552 		ilg_cleanup_reqd = B_TRUE;
5553 	mutex_exit(&connp->conn_lock);
5554 
5555 	if (conn_ioctl_cleanup_reqd)
5556 		conn_ioctl_cleanup(connp);
5557 
5558 	if (is_system_labeled() && connp->conn_anon_port) {
5559 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5560 		    connp->conn_mlp_type, connp->conn_ulp,
5561 		    ntohs(connp->conn_lport), B_FALSE);
5562 		connp->conn_anon_port = 0;
5563 	}
5564 	connp->conn_mlp_type = mlptSingle;
5565 
5566 	/*
5567 	 * Remove this conn from any fanout list it is on.
5568 	 * and then wait for any threads currently operating
5569 	 * on this endpoint to finish
5570 	 */
5571 	ipcl_hash_remove(connp);
5572 
5573 	/*
5574 	 * Remove this conn from the drain list, and do
5575 	 * any other cleanup that may be required.
5576 	 * (Only non-tcp streams may have a non-null conn_idl.
5577 	 * TCP streams are never flow controlled, and
5578 	 * conn_idl will be null)
5579 	 */
5580 	if (drain_cleanup_reqd)
5581 		conn_drain_tail(connp, B_TRUE);
5582 
5583 	if (connp == ipst->ips_ip_g_mrouter)
5584 		(void) ip_mrouter_done(NULL, ipst);
5585 
5586 	if (ilg_cleanup_reqd)
5587 		ilg_delete_all(connp);
5588 
5589 	conn_delete_ire(connp, NULL);
5590 
5591 	/*
5592 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5593 	 * callers from write side can't be there now because close
5594 	 * is in progress. The only other caller is ipcl_walk
5595 	 * which checks for the condemned flag.
5596 	 */
5597 	mutex_enter(&connp->conn_lock);
5598 	connp->conn_state_flags |= CONN_CONDEMNED;
5599 	while (connp->conn_ref != 1)
5600 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5601 	connp->conn_state_flags |= CONN_QUIESCED;
5602 	mutex_exit(&connp->conn_lock);
5603 }
5604 
5605 /* ARGSUSED */
5606 int
5607 ip_close(queue_t *q, int flags)
5608 {
5609 	conn_t		*connp;
5610 
5611 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5612 
5613 	/*
5614 	 * Call the appropriate delete routine depending on whether this is
5615 	 * a module or device.
5616 	 */
5617 	if (WR(q)->q_next != NULL) {
5618 		/* This is a module close */
5619 		return (ip_modclose((ill_t *)q->q_ptr));
5620 	}
5621 
5622 	connp = q->q_ptr;
5623 	ip_quiesce_conn(connp);
5624 
5625 	qprocsoff(q);
5626 
5627 	/*
5628 	 * Now we are truly single threaded on this stream, and can
5629 	 * delete the things hanging off the connp, and finally the connp.
5630 	 * We removed this connp from the fanout list, it cannot be
5631 	 * accessed thru the fanouts, and we already waited for the
5632 	 * conn_ref to drop to 0. We are already in close, so
5633 	 * there cannot be any other thread from the top. qprocsoff
5634 	 * has completed, and service has completed or won't run in
5635 	 * future.
5636 	 */
5637 	ASSERT(connp->conn_ref == 1);
5638 
5639 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5640 
5641 	connp->conn_ref--;
5642 	ipcl_conn_destroy(connp);
5643 
5644 	q->q_ptr = WR(q)->q_ptr = NULL;
5645 	return (0);
5646 }
5647 
5648 /*
5649  * Wapper around putnext() so that ip_rts_request can merely use
5650  * conn_recv.
5651  */
5652 /*ARGSUSED2*/
5653 static void
5654 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5655 {
5656 	conn_t *connp = (conn_t *)arg1;
5657 
5658 	putnext(connp->conn_rq, mp);
5659 }
5660 
5661 /* Return the IP checksum for the IP header at "iph". */
5662 uint16_t
5663 ip_csum_hdr(ipha_t *ipha)
5664 {
5665 	uint16_t	*uph;
5666 	uint32_t	sum;
5667 	int		opt_len;
5668 
5669 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5670 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5671 	uph = (uint16_t *)ipha;
5672 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5673 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5674 	if (opt_len > 0) {
5675 		do {
5676 			sum += uph[10];
5677 			sum += uph[11];
5678 			uph += 2;
5679 		} while (--opt_len);
5680 	}
5681 	sum = (sum & 0xFFFF) + (sum >> 16);
5682 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5683 	if (sum == 0xffff)
5684 		sum = 0;
5685 	return ((uint16_t)sum);
5686 }
5687 
5688 /*
5689  * Called when the module is about to be unloaded
5690  */
5691 void
5692 ip_ddi_destroy(void)
5693 {
5694 	tnet_fini();
5695 
5696 	icmp_ddi_destroy();
5697 	rts_ddi_destroy();
5698 	udp_ddi_destroy();
5699 	sctp_ddi_g_destroy();
5700 	tcp_ddi_g_destroy();
5701 	ipsec_policy_g_destroy();
5702 	ipcl_g_destroy();
5703 	ip_net_g_destroy();
5704 	ip_ire_g_fini();
5705 	inet_minor_destroy(ip_minor_arena_sa);
5706 #if defined(_LP64)
5707 	inet_minor_destroy(ip_minor_arena_la);
5708 #endif
5709 
5710 #ifdef DEBUG
5711 	list_destroy(&ip_thread_list);
5712 	rw_destroy(&ip_thread_rwlock);
5713 	tsd_destroy(&ip_thread_data);
5714 #endif
5715 
5716 	netstack_unregister(NS_IP);
5717 }
5718 
5719 /*
5720  * First step in cleanup.
5721  */
5722 /* ARGSUSED */
5723 static void
5724 ip_stack_shutdown(netstackid_t stackid, void *arg)
5725 {
5726 	ip_stack_t *ipst = (ip_stack_t *)arg;
5727 
5728 #ifdef NS_DEBUG
5729 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5730 #endif
5731 
5732 	/* Get rid of loopback interfaces and their IREs */
5733 	ip_loopback_cleanup(ipst);
5734 
5735 	/*
5736 	 * The *_hook_shutdown()s start the process of notifying any
5737 	 * consumers that things are going away.... nothing is destroyed.
5738 	 */
5739 	ipv4_hook_shutdown(ipst);
5740 	ipv6_hook_shutdown(ipst);
5741 }
5742 
5743 /*
5744  * Free the IP stack instance.
5745  */
5746 static void
5747 ip_stack_fini(netstackid_t stackid, void *arg)
5748 {
5749 	ip_stack_t *ipst = (ip_stack_t *)arg;
5750 	int ret;
5751 
5752 	/*
5753 	 * At this point, all of the notifications that the events and
5754 	 * protocols are going away have been run, meaning that we can
5755 	 * now set about starting to clean things up.
5756 	 */
5757 	ipv4_hook_destroy(ipst);
5758 	ipv6_hook_destroy(ipst);
5759 	ip_net_destroy(ipst);
5760 
5761 #ifdef NS_DEBUG
5762 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5763 #endif
5764 	rw_destroy(&ipst->ips_srcid_lock);
5765 
5766 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5767 	ipst->ips_ip_mibkp = NULL;
5768 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5769 	ipst->ips_icmp_mibkp = NULL;
5770 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5771 	ipst->ips_ip_kstat = NULL;
5772 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5773 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5774 	ipst->ips_ip6_kstat = NULL;
5775 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5776 
5777 	nd_free(&ipst->ips_ip_g_nd);
5778 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5779 	ipst->ips_param_arr = NULL;
5780 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5781 	ipst->ips_ndp_arr = NULL;
5782 
5783 	ip_mrouter_stack_destroy(ipst);
5784 
5785 	mutex_destroy(&ipst->ips_ip_mi_lock);
5786 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5787 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5788 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5789 
5790 	ret = untimeout(ipst->ips_igmp_timeout_id);
5791 	if (ret == -1) {
5792 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5793 	} else {
5794 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5795 		ipst->ips_igmp_timeout_id = 0;
5796 	}
5797 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5798 	if (ret == -1) {
5799 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5800 	} else {
5801 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5802 		ipst->ips_igmp_slowtimeout_id = 0;
5803 	}
5804 	ret = untimeout(ipst->ips_mld_timeout_id);
5805 	if (ret == -1) {
5806 		ASSERT(ipst->ips_mld_timeout_id == 0);
5807 	} else {
5808 		ASSERT(ipst->ips_mld_timeout_id != 0);
5809 		ipst->ips_mld_timeout_id = 0;
5810 	}
5811 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5812 	if (ret == -1) {
5813 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5814 	} else {
5815 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5816 		ipst->ips_mld_slowtimeout_id = 0;
5817 	}
5818 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5819 	if (ret == -1) {
5820 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5821 	} else {
5822 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5823 		ipst->ips_ip_ire_expire_id = 0;
5824 	}
5825 
5826 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5827 	mutex_destroy(&ipst->ips_mld_timer_lock);
5828 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5829 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5830 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5831 	rw_destroy(&ipst->ips_ill_g_lock);
5832 
5833 	ipobs_fini(ipst);
5834 	ip_ire_fini(ipst);
5835 	ip6_asp_free(ipst);
5836 	conn_drain_fini(ipst);
5837 	ipcl_destroy(ipst);
5838 
5839 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5840 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5841 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5842 	ipst->ips_ndp4 = NULL;
5843 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5844 	ipst->ips_ndp6 = NULL;
5845 
5846 	if (ipst->ips_loopback_ksp != NULL) {
5847 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5848 		ipst->ips_loopback_ksp = NULL;
5849 	}
5850 
5851 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5852 	ipst->ips_phyint_g_list = NULL;
5853 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5854 	ipst->ips_ill_g_heads = NULL;
5855 
5856 	kmem_free(ipst, sizeof (*ipst));
5857 }
5858 
5859 /*
5860  * This function is called from the TSD destructor, and is used to debug
5861  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5862  * details.
5863  */
5864 static void
5865 ip_thread_exit(void *phash)
5866 {
5867 	th_hash_t *thh = phash;
5868 
5869 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5870 	list_remove(&ip_thread_list, thh);
5871 	rw_exit(&ip_thread_rwlock);
5872 	mod_hash_destroy_hash(thh->thh_hash);
5873 	kmem_free(thh, sizeof (*thh));
5874 }
5875 
5876 /*
5877  * Called when the IP kernel module is loaded into the kernel
5878  */
5879 void
5880 ip_ddi_init(void)
5881 {
5882 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5883 
5884 	/*
5885 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5886 	 * initial devices: ip, ip6, tcp, tcp6.
5887 	 */
5888 	/*
5889 	 * If this is a 64-bit kernel, then create two separate arenas -
5890 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5891 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5892 	 */
5893 	ip_minor_arena_la = NULL;
5894 	ip_minor_arena_sa = NULL;
5895 #if defined(_LP64)
5896 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5897 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5898 		cmn_err(CE_PANIC,
5899 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5900 	}
5901 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5902 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5903 		cmn_err(CE_PANIC,
5904 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5905 	}
5906 #else
5907 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5908 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5909 		cmn_err(CE_PANIC,
5910 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5911 	}
5912 #endif
5913 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5914 
5915 	ipcl_g_init();
5916 	ip_ire_g_init();
5917 	ip_net_g_init();
5918 
5919 #ifdef DEBUG
5920 	tsd_create(&ip_thread_data, ip_thread_exit);
5921 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5922 	list_create(&ip_thread_list, sizeof (th_hash_t),
5923 	    offsetof(th_hash_t, thh_link));
5924 #endif
5925 
5926 	/*
5927 	 * We want to be informed each time a stack is created or
5928 	 * destroyed in the kernel, so we can maintain the
5929 	 * set of udp_stack_t's.
5930 	 */
5931 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5932 	    ip_stack_fini);
5933 
5934 	ipsec_policy_g_init();
5935 	tcp_ddi_g_init();
5936 	sctp_ddi_g_init();
5937 
5938 	tnet_init();
5939 
5940 	udp_ddi_init();
5941 	rts_ddi_init();
5942 	icmp_ddi_init();
5943 }
5944 
5945 /*
5946  * Initialize the IP stack instance.
5947  */
5948 static void *
5949 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5950 {
5951 	ip_stack_t	*ipst;
5952 	ipparam_t	*pa;
5953 	ipndp_t		*na;
5954 
5955 #ifdef NS_DEBUG
5956 	printf("ip_stack_init(stack %d)\n", stackid);
5957 #endif
5958 
5959 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5960 	ipst->ips_netstack = ns;
5961 
5962 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5963 	    KM_SLEEP);
5964 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5965 	    KM_SLEEP);
5966 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5967 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5968 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5969 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5970 
5971 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5972 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5973 	ipst->ips_igmp_deferred_next = INFINITY;
5974 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5975 	ipst->ips_mld_deferred_next = INFINITY;
5976 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5977 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5978 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5979 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5980 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5981 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5982 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5983 
5984 	ipcl_init(ipst);
5985 	ip_ire_init(ipst);
5986 	ip6_asp_init(ipst);
5987 	ipif_init(ipst);
5988 	conn_drain_init(ipst);
5989 	ip_mrouter_stack_init(ipst);
5990 
5991 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5992 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5993 
5994 	ipst->ips_ip_multirt_log_interval = 1000;
5995 
5996 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5997 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5998 	ipst->ips_ill_index = 1;
5999 
6000 	ipst->ips_saved_ip_g_forward = -1;
6001 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6002 
6003 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6004 	ipst->ips_param_arr = pa;
6005 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6006 
6007 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6008 	ipst->ips_ndp_arr = na;
6009 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6010 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6011 	    (caddr_t)&ipst->ips_ip_g_forward;
6012 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6013 	    (caddr_t)&ipst->ips_ipv6_forward;
6014 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6015 	    "ip_cgtp_filter") == 0);
6016 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6017 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6018 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6019 	    "ipmp_hook_emulation") == 0);
6020 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6021 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6022 
6023 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6024 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6025 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6026 
6027 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6028 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6029 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6030 	ipst->ips_ip6_kstat =
6031 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6032 
6033 	ipst->ips_ipmp_enable_failback = B_TRUE;
6034 
6035 	ipst->ips_ip_src_id = 1;
6036 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6037 
6038 	ipobs_init(ipst);
6039 	ip_net_init(ipst, ns);
6040 	ipv4_hook_init(ipst);
6041 	ipv6_hook_init(ipst);
6042 
6043 	return (ipst);
6044 }
6045 
6046 /*
6047  * Allocate and initialize a DLPI template of the specified length.  (May be
6048  * called as writer.)
6049  */
6050 mblk_t *
6051 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6052 {
6053 	mblk_t	*mp;
6054 
6055 	mp = allocb(len, BPRI_MED);
6056 	if (!mp)
6057 		return (NULL);
6058 
6059 	/*
6060 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6061 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6062 	 * that other DLPI are M_PROTO.
6063 	 */
6064 	if (prim == DL_INFO_REQ) {
6065 		mp->b_datap->db_type = M_PCPROTO;
6066 	} else {
6067 		mp->b_datap->db_type = M_PROTO;
6068 	}
6069 
6070 	mp->b_wptr = mp->b_rptr + len;
6071 	bzero(mp->b_rptr, len);
6072 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6073 	return (mp);
6074 }
6075 
6076 /*
6077  * Debug formatting routine.  Returns a character string representation of the
6078  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6079  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6080  *
6081  * Once the ndd table-printing interfaces are removed, this can be changed to
6082  * standard dotted-decimal form.
6083  */
6084 char *
6085 ip_dot_addr(ipaddr_t addr, char *buf)
6086 {
6087 	uint8_t *ap = (uint8_t *)&addr;
6088 
6089 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6090 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6091 	return (buf);
6092 }
6093 
6094 /*
6095  * Write the given MAC address as a printable string in the usual colon-
6096  * separated format.
6097  */
6098 const char *
6099 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6100 {
6101 	char *bp;
6102 
6103 	if (alen == 0 || buflen < 4)
6104 		return ("?");
6105 	bp = buf;
6106 	for (;;) {
6107 		/*
6108 		 * If there are more MAC address bytes available, but we won't
6109 		 * have any room to print them, then add "..." to the string
6110 		 * instead.  See below for the 'magic number' explanation.
6111 		 */
6112 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6113 			(void) strcpy(bp, "...");
6114 			break;
6115 		}
6116 		(void) sprintf(bp, "%02x", *addr++);
6117 		bp += 2;
6118 		if (--alen == 0)
6119 			break;
6120 		*bp++ = ':';
6121 		buflen -= 3;
6122 		/*
6123 		 * At this point, based on the first 'if' statement above,
6124 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6125 		 * buflen >= 4.  The first case leaves room for the final "xx"
6126 		 * number and trailing NUL byte.  The second leaves room for at
6127 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6128 		 * that statement.
6129 		 */
6130 	}
6131 	return (buf);
6132 }
6133 
6134 /*
6135  * Send an ICMP error after patching up the packet appropriately.  Returns
6136  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6137  */
6138 static boolean_t
6139 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6140     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6141     zoneid_t zoneid, ip_stack_t *ipst)
6142 {
6143 	ipha_t *ipha;
6144 	mblk_t *first_mp;
6145 	boolean_t secure;
6146 	unsigned char db_type;
6147 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6148 
6149 	first_mp = mp;
6150 	if (mctl_present) {
6151 		mp = mp->b_cont;
6152 		secure = ipsec_in_is_secure(first_mp);
6153 		ASSERT(mp != NULL);
6154 	} else {
6155 		/*
6156 		 * If this is an ICMP error being reported - which goes
6157 		 * up as M_CTLs, we need to convert them to M_DATA till
6158 		 * we finish checking with global policy because
6159 		 * ipsec_check_global_policy() assumes M_DATA as clear
6160 		 * and M_CTL as secure.
6161 		 */
6162 		db_type = DB_TYPE(mp);
6163 		DB_TYPE(mp) = M_DATA;
6164 		secure = B_FALSE;
6165 	}
6166 	/*
6167 	 * We are generating an icmp error for some inbound packet.
6168 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6169 	 * Before we generate an error, check with global policy
6170 	 * to see whether this is allowed to enter the system. As
6171 	 * there is no "conn", we are checking with global policy.
6172 	 */
6173 	ipha = (ipha_t *)mp->b_rptr;
6174 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6175 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6176 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6177 		if (first_mp == NULL)
6178 			return (B_FALSE);
6179 	}
6180 
6181 	if (!mctl_present)
6182 		DB_TYPE(mp) = db_type;
6183 
6184 	if (flags & IP_FF_SEND_ICMP) {
6185 		if (flags & IP_FF_HDR_COMPLETE) {
6186 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6187 				freemsg(first_mp);
6188 				return (B_TRUE);
6189 			}
6190 		}
6191 		if (flags & IP_FF_CKSUM) {
6192 			/*
6193 			 * Have to correct checksum since
6194 			 * the packet might have been
6195 			 * fragmented and the reassembly code in ip_rput
6196 			 * does not restore the IP checksum.
6197 			 */
6198 			ipha->ipha_hdr_checksum = 0;
6199 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6200 		}
6201 		switch (icmp_type) {
6202 		case ICMP_DEST_UNREACHABLE:
6203 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6204 			    ipst);
6205 			break;
6206 		default:
6207 			freemsg(first_mp);
6208 			break;
6209 		}
6210 	} else {
6211 		freemsg(first_mp);
6212 		return (B_FALSE);
6213 	}
6214 
6215 	return (B_TRUE);
6216 }
6217 
6218 /*
6219  * Used to send an ICMP error message when a packet is received for
6220  * a protocol that is not supported. The mblk passed as argument
6221  * is consumed by this function.
6222  */
6223 void
6224 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6225     ip_stack_t *ipst)
6226 {
6227 	mblk_t *mp;
6228 	ipha_t *ipha;
6229 	ill_t *ill;
6230 	ipsec_in_t *ii;
6231 
6232 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6233 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6234 
6235 	mp = ipsec_mp->b_cont;
6236 	ipsec_mp->b_cont = NULL;
6237 	ipha = (ipha_t *)mp->b_rptr;
6238 	/* Get ill from index in ipsec_in_t. */
6239 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6240 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6241 	    ipst);
6242 	if (ill != NULL) {
6243 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6244 			if (ip_fanout_send_icmp(q, mp, flags,
6245 			    ICMP_DEST_UNREACHABLE,
6246 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6247 				BUMP_MIB(ill->ill_ip_mib,
6248 				    ipIfStatsInUnknownProtos);
6249 			}
6250 		} else {
6251 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6252 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6253 			    0, B_FALSE, zoneid, ipst)) {
6254 				BUMP_MIB(ill->ill_ip_mib,
6255 				    ipIfStatsInUnknownProtos);
6256 			}
6257 		}
6258 		ill_refrele(ill);
6259 	} else { /* re-link for the freemsg() below. */
6260 		ipsec_mp->b_cont = mp;
6261 	}
6262 
6263 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6264 	freemsg(ipsec_mp);
6265 }
6266 
6267 /*
6268  * See if the inbound datagram has had IPsec processing applied to it.
6269  */
6270 boolean_t
6271 ipsec_in_is_secure(mblk_t *ipsec_mp)
6272 {
6273 	ipsec_in_t *ii;
6274 
6275 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6276 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6277 
6278 	if (ii->ipsec_in_loopback) {
6279 		return (ii->ipsec_in_secure);
6280 	} else {
6281 		return (ii->ipsec_in_ah_sa != NULL ||
6282 		    ii->ipsec_in_esp_sa != NULL ||
6283 		    ii->ipsec_in_decaps);
6284 	}
6285 }
6286 
6287 /*
6288  * Handle protocols with which IP is less intimate.  There
6289  * can be more than one stream bound to a particular
6290  * protocol.  When this is the case, normally each one gets a copy
6291  * of any incoming packets.
6292  *
6293  * IPsec NOTE :
6294  *
6295  * Don't allow a secure packet going up a non-secure connection.
6296  * We don't allow this because
6297  *
6298  * 1) Reply might go out in clear which will be dropped at
6299  *    the sending side.
6300  * 2) If the reply goes out in clear it will give the
6301  *    adversary enough information for getting the key in
6302  *    most of the cases.
6303  *
6304  * Moreover getting a secure packet when we expect clear
6305  * implies that SA's were added without checking for
6306  * policy on both ends. This should not happen once ISAKMP
6307  * is used to negotiate SAs as SAs will be added only after
6308  * verifying the policy.
6309  *
6310  * NOTE : If the packet was tunneled and not multicast we only send
6311  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6312  * back to delivering packets to AF_INET6 raw sockets.
6313  *
6314  * IPQoS Notes:
6315  * Once we have determined the client, invoke IPPF processing.
6316  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6317  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6318  * ip_policy will be false.
6319  *
6320  * Zones notes:
6321  * Currently only applications in the global zone can create raw sockets for
6322  * protocols other than ICMP. So unlike the broadcast / multicast case of
6323  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6324  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6325  */
6326 static void
6327 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6328     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6329     zoneid_t zoneid)
6330 {
6331 	queue_t	*rq;
6332 	mblk_t	*mp1, *first_mp1;
6333 	uint_t	protocol = ipha->ipha_protocol;
6334 	ipaddr_t dst;
6335 	boolean_t one_only;
6336 	mblk_t *first_mp = mp;
6337 	boolean_t secure;
6338 	uint32_t ill_index;
6339 	conn_t	*connp, *first_connp, *next_connp;
6340 	connf_t	*connfp;
6341 	boolean_t shared_addr;
6342 	mib2_ipIfStatsEntry_t *mibptr;
6343 	ip_stack_t *ipst = recv_ill->ill_ipst;
6344 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6345 
6346 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6347 	if (mctl_present) {
6348 		mp = first_mp->b_cont;
6349 		secure = ipsec_in_is_secure(first_mp);
6350 		ASSERT(mp != NULL);
6351 	} else {
6352 		secure = B_FALSE;
6353 	}
6354 	dst = ipha->ipha_dst;
6355 	/*
6356 	 * If the packet was tunneled and not multicast we only send to it
6357 	 * the first match.
6358 	 */
6359 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6360 	    !CLASSD(dst));
6361 
6362 	shared_addr = (zoneid == ALL_ZONES);
6363 	if (shared_addr) {
6364 		/*
6365 		 * We don't allow multilevel ports for raw IP, so no need to
6366 		 * check for that here.
6367 		 */
6368 		zoneid = tsol_packet_to_zoneid(mp);
6369 	}
6370 
6371 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6372 	mutex_enter(&connfp->connf_lock);
6373 	connp = connfp->connf_head;
6374 	for (connp = connfp->connf_head; connp != NULL;
6375 	    connp = connp->conn_next) {
6376 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6377 		    zoneid) &&
6378 		    (!is_system_labeled() ||
6379 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6380 		    connp))) {
6381 			break;
6382 		}
6383 	}
6384 
6385 	if (connp == NULL || connp->conn_upq == NULL) {
6386 		/*
6387 		 * No one bound to these addresses.  Is
6388 		 * there a client that wants all
6389 		 * unclaimed datagrams?
6390 		 */
6391 		mutex_exit(&connfp->connf_lock);
6392 		/*
6393 		 * Check for IPPROTO_ENCAP...
6394 		 */
6395 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6396 			/*
6397 			 * If an IPsec mblk is here on a multicast
6398 			 * tunnel (using ip_mroute stuff), check policy here,
6399 			 * THEN ship off to ip_mroute_decap().
6400 			 *
6401 			 * BTW,  If I match a configured IP-in-IP
6402 			 * tunnel, this path will not be reached, and
6403 			 * ip_mroute_decap will never be called.
6404 			 */
6405 			first_mp = ipsec_check_global_policy(first_mp, connp,
6406 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6407 			if (first_mp != NULL) {
6408 				if (mctl_present)
6409 					freeb(first_mp);
6410 				ip_mroute_decap(q, mp, ill);
6411 			} /* Else we already freed everything! */
6412 		} else {
6413 			/*
6414 			 * Otherwise send an ICMP protocol unreachable.
6415 			 */
6416 			if (ip_fanout_send_icmp(q, first_mp, flags,
6417 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6418 			    mctl_present, zoneid, ipst)) {
6419 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6420 			}
6421 		}
6422 		return;
6423 	}
6424 	CONN_INC_REF(connp);
6425 	first_connp = connp;
6426 
6427 	/*
6428 	 * Only send message to one tunnel driver by immediately
6429 	 * terminating the loop.
6430 	 */
6431 	connp = one_only ? NULL : connp->conn_next;
6432 
6433 	for (;;) {
6434 		while (connp != NULL) {
6435 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6436 			    flags, zoneid) &&
6437 			    (!is_system_labeled() ||
6438 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6439 			    shared_addr, connp)))
6440 				break;
6441 			connp = connp->conn_next;
6442 		}
6443 
6444 		/*
6445 		 * Copy the packet.
6446 		 */
6447 		if (connp == NULL || connp->conn_upq == NULL ||
6448 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6449 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6450 			/*
6451 			 * No more interested clients or memory
6452 			 * allocation failed
6453 			 */
6454 			connp = first_connp;
6455 			break;
6456 		}
6457 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6458 		CONN_INC_REF(connp);
6459 		mutex_exit(&connfp->connf_lock);
6460 		rq = connp->conn_rq;
6461 		if (!canputnext(rq)) {
6462 			if (flags & IP_FF_RAWIP) {
6463 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6464 			} else {
6465 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6466 			}
6467 
6468 			freemsg(first_mp1);
6469 		} else {
6470 			/*
6471 			 * Don't enforce here if we're an actual tunnel -
6472 			 * let "tun" do it instead.
6473 			 */
6474 			if (!IPCL_IS_IPTUN(connp) &&
6475 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6476 			    secure)) {
6477 				first_mp1 = ipsec_check_inbound_policy
6478 				    (first_mp1, connp, ipha, NULL,
6479 				    mctl_present);
6480 			}
6481 			if (first_mp1 != NULL) {
6482 				int in_flags = 0;
6483 				/*
6484 				 * ip_fanout_proto also gets called from
6485 				 * icmp_inbound_error_fanout, in which case
6486 				 * the msg type is M_CTL.  Don't add info
6487 				 * in this case for the time being. In future
6488 				 * when there is a need for knowing the
6489 				 * inbound iface index for ICMP error msgs,
6490 				 * then this can be changed.
6491 				 */
6492 				if (connp->conn_recvif)
6493 					in_flags = IPF_RECVIF;
6494 				/*
6495 				 * The ULP may support IP_RECVPKTINFO for both
6496 				 * IP v4 and v6 so pass the appropriate argument
6497 				 * based on conn IP version.
6498 				 */
6499 				if (connp->conn_ip_recvpktinfo) {
6500 					if (connp->conn_af_isv6) {
6501 						/*
6502 						 * V6 only needs index
6503 						 */
6504 						in_flags |= IPF_RECVIF;
6505 					} else {
6506 						/*
6507 						 * V4 needs index +
6508 						 * matching address.
6509 						 */
6510 						in_flags |= IPF_RECVADDR;
6511 					}
6512 				}
6513 				if ((in_flags != 0) &&
6514 				    (mp->b_datap->db_type != M_CTL)) {
6515 					/*
6516 					 * the actual data will be
6517 					 * contained in b_cont upon
6518 					 * successful return of the
6519 					 * following call else
6520 					 * original mblk is returned
6521 					 */
6522 					ASSERT(recv_ill != NULL);
6523 					mp1 = ip_add_info(mp1, recv_ill,
6524 					    in_flags, IPCL_ZONEID(connp), ipst);
6525 				}
6526 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6527 				if (mctl_present)
6528 					freeb(first_mp1);
6529 				(connp->conn_recv)(connp, mp1, NULL);
6530 			}
6531 		}
6532 		mutex_enter(&connfp->connf_lock);
6533 		/* Follow the next pointer before releasing the conn. */
6534 		next_connp = connp->conn_next;
6535 		CONN_DEC_REF(connp);
6536 		connp = next_connp;
6537 	}
6538 
6539 	/* Last one.  Send it upstream. */
6540 	mutex_exit(&connfp->connf_lock);
6541 
6542 	/*
6543 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6544 	 * will be set to false.
6545 	 */
6546 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6547 		ill_index = ill->ill_phyint->phyint_ifindex;
6548 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6549 		if (mp == NULL) {
6550 			CONN_DEC_REF(connp);
6551 			if (mctl_present) {
6552 				freeb(first_mp);
6553 			}
6554 			return;
6555 		}
6556 	}
6557 
6558 	rq = connp->conn_rq;
6559 	if (!canputnext(rq)) {
6560 		if (flags & IP_FF_RAWIP) {
6561 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6562 		} else {
6563 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6564 		}
6565 
6566 		freemsg(first_mp);
6567 	} else {
6568 		if (IPCL_IS_IPTUN(connp)) {
6569 			/*
6570 			 * Tunneled packet.  We enforce policy in the tunnel
6571 			 * module itself.
6572 			 *
6573 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6574 			 * a policy check.
6575 			 * FIXME to use conn_recv for tun later.
6576 			 */
6577 			putnext(rq, first_mp);
6578 			CONN_DEC_REF(connp);
6579 			return;
6580 		}
6581 
6582 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6583 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6584 			    ipha, NULL, mctl_present);
6585 		}
6586 
6587 		if (first_mp != NULL) {
6588 			int in_flags = 0;
6589 
6590 			/*
6591 			 * ip_fanout_proto also gets called
6592 			 * from icmp_inbound_error_fanout, in
6593 			 * which case the msg type is M_CTL.
6594 			 * Don't add info in this case for time
6595 			 * being. In future when there is a
6596 			 * need for knowing the inbound iface
6597 			 * index for ICMP error msgs, then this
6598 			 * can be changed
6599 			 */
6600 			if (connp->conn_recvif)
6601 				in_flags = IPF_RECVIF;
6602 			if (connp->conn_ip_recvpktinfo) {
6603 				if (connp->conn_af_isv6) {
6604 					/*
6605 					 * V6 only needs index
6606 					 */
6607 					in_flags |= IPF_RECVIF;
6608 				} else {
6609 					/*
6610 					 * V4 needs index +
6611 					 * matching address.
6612 					 */
6613 					in_flags |= IPF_RECVADDR;
6614 				}
6615 			}
6616 			if ((in_flags != 0) &&
6617 			    (mp->b_datap->db_type != M_CTL)) {
6618 
6619 				/*
6620 				 * the actual data will be contained in
6621 				 * b_cont upon successful return
6622 				 * of the following call else original
6623 				 * mblk is returned
6624 				 */
6625 				ASSERT(recv_ill != NULL);
6626 				mp = ip_add_info(mp, recv_ill,
6627 				    in_flags, IPCL_ZONEID(connp), ipst);
6628 			}
6629 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6630 			(connp->conn_recv)(connp, mp, NULL);
6631 			if (mctl_present)
6632 				freeb(first_mp);
6633 		}
6634 	}
6635 	CONN_DEC_REF(connp);
6636 }
6637 
6638 /*
6639  * Fanout for TCP packets
6640  * The caller puts <fport, lport> in the ports parameter.
6641  *
6642  * IPQoS Notes
6643  * Before sending it to the client, invoke IPPF processing.
6644  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6645  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6646  * ip_policy is false.
6647  */
6648 static void
6649 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6650     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6651 {
6652 	mblk_t  *first_mp;
6653 	boolean_t secure;
6654 	uint32_t ill_index;
6655 	int	ip_hdr_len;
6656 	tcph_t	*tcph;
6657 	boolean_t syn_present = B_FALSE;
6658 	conn_t	*connp;
6659 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6660 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6661 
6662 	ASSERT(recv_ill != NULL);
6663 
6664 	first_mp = mp;
6665 	if (mctl_present) {
6666 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6667 		mp = first_mp->b_cont;
6668 		secure = ipsec_in_is_secure(first_mp);
6669 		ASSERT(mp != NULL);
6670 	} else {
6671 		secure = B_FALSE;
6672 	}
6673 
6674 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6675 
6676 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6677 	    zoneid, ipst)) == NULL) {
6678 		/*
6679 		 * No connected connection or listener. Send a
6680 		 * TH_RST via tcp_xmit_listeners_reset.
6681 		 */
6682 
6683 		/* Initiate IPPf processing, if needed. */
6684 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6685 			uint32_t ill_index;
6686 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6687 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6688 			if (first_mp == NULL)
6689 				return;
6690 		}
6691 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6692 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6693 		    zoneid));
6694 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6695 		    ipst->ips_netstack->netstack_tcp, NULL);
6696 		return;
6697 	}
6698 
6699 	/*
6700 	 * Allocate the SYN for the TCP connection here itself
6701 	 */
6702 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6703 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6704 		if (IPCL_IS_TCP(connp)) {
6705 			squeue_t *sqp;
6706 
6707 			/*
6708 			 * For fused tcp loopback, assign the eager's
6709 			 * squeue to be that of the active connect's.
6710 			 * Note that we don't check for IP_FF_LOOPBACK
6711 			 * here since this routine gets called only
6712 			 * for loopback (unlike the IPv6 counterpart).
6713 			 */
6714 			ASSERT(Q_TO_CONN(q) != NULL);
6715 			if (do_tcp_fusion &&
6716 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6717 			    !secure &&
6718 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6719 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6720 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6721 				sqp = Q_TO_CONN(q)->conn_sqp;
6722 			} else {
6723 				sqp = IP_SQUEUE_GET(lbolt);
6724 			}
6725 
6726 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6727 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6728 			syn_present = B_TRUE;
6729 		}
6730 	}
6731 
6732 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6733 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6734 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6735 		if ((flags & TH_RST) || (flags & TH_URG)) {
6736 			CONN_DEC_REF(connp);
6737 			freemsg(first_mp);
6738 			return;
6739 		}
6740 		if (flags & TH_ACK) {
6741 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6742 			    ipst->ips_netstack->netstack_tcp, connp);
6743 			CONN_DEC_REF(connp);
6744 			return;
6745 		}
6746 
6747 		CONN_DEC_REF(connp);
6748 		freemsg(first_mp);
6749 		return;
6750 	}
6751 
6752 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6753 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6754 		    NULL, mctl_present);
6755 		if (first_mp == NULL) {
6756 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6757 			CONN_DEC_REF(connp);
6758 			return;
6759 		}
6760 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6761 			ASSERT(syn_present);
6762 			if (mctl_present) {
6763 				ASSERT(first_mp != mp);
6764 				first_mp->b_datap->db_struioflag |=
6765 				    STRUIO_POLICY;
6766 			} else {
6767 				ASSERT(first_mp == mp);
6768 				mp->b_datap->db_struioflag &=
6769 				    ~STRUIO_EAGER;
6770 				mp->b_datap->db_struioflag |=
6771 				    STRUIO_POLICY;
6772 			}
6773 		} else {
6774 			/*
6775 			 * Discard first_mp early since we're dealing with a
6776 			 * fully-connected conn_t and tcp doesn't do policy in
6777 			 * this case.
6778 			 */
6779 			if (mctl_present) {
6780 				freeb(first_mp);
6781 				mctl_present = B_FALSE;
6782 			}
6783 			first_mp = mp;
6784 		}
6785 	}
6786 
6787 	/*
6788 	 * Initiate policy processing here if needed. If we get here from
6789 	 * icmp_inbound_error_fanout, ip_policy is false.
6790 	 */
6791 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6792 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6793 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6794 		if (mp == NULL) {
6795 			CONN_DEC_REF(connp);
6796 			if (mctl_present)
6797 				freeb(first_mp);
6798 			return;
6799 		} else if (mctl_present) {
6800 			ASSERT(first_mp != mp);
6801 			first_mp->b_cont = mp;
6802 		} else {
6803 			first_mp = mp;
6804 		}
6805 	}
6806 
6807 
6808 
6809 	/* Handle socket options. */
6810 	if (!syn_present &&
6811 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6812 		/* Add header */
6813 		ASSERT(recv_ill != NULL);
6814 		/*
6815 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6816 		 * IPF_RECVIF.
6817 		 */
6818 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6819 		    ipst);
6820 		if (mp == NULL) {
6821 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6822 			CONN_DEC_REF(connp);
6823 			if (mctl_present)
6824 				freeb(first_mp);
6825 			return;
6826 		} else if (mctl_present) {
6827 			/*
6828 			 * ip_add_info might return a new mp.
6829 			 */
6830 			ASSERT(first_mp != mp);
6831 			first_mp->b_cont = mp;
6832 		} else {
6833 			first_mp = mp;
6834 		}
6835 	}
6836 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6837 	if (IPCL_IS_TCP(connp)) {
6838 		/* do not drain, certain use cases can blow the stack */
6839 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6840 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6841 	} else {
6842 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6843 		(connp->conn_recv)(connp, first_mp, NULL);
6844 		CONN_DEC_REF(connp);
6845 	}
6846 }
6847 
6848 /*
6849  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6850  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6851  * is not consumed.
6852  *
6853  * One of four things can happen, all of which affect the passed-in mblk:
6854  *
6855  * 1.) ICMP messages that go through here just get returned TRUE.
6856  *
6857  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6858  *
6859  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6860  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6861  *
6862  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6863  */
6864 static boolean_t
6865 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6866     ipsec_stack_t *ipss)
6867 {
6868 	int shift, plen, iph_len;
6869 	ipha_t *ipha;
6870 	udpha_t *udpha;
6871 	uint32_t *spi;
6872 	uint32_t esp_ports;
6873 	uint8_t *orptr;
6874 	boolean_t free_ire;
6875 
6876 	if (DB_TYPE(mp) == M_CTL) {
6877 		/*
6878 		 * ICMP message with UDP inside.  Don't bother stripping, just
6879 		 * send it up.
6880 		 *
6881 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6882 		 * to ignore errors set by ICMP anyway ('cause they might be
6883 		 * forged), but that's the app's decision, not ours.
6884 		 */
6885 
6886 		/* Bunch of reality checks for DEBUG kernels... */
6887 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6888 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6889 
6890 		return (B_TRUE);
6891 	}
6892 
6893 	ipha = (ipha_t *)mp->b_rptr;
6894 	iph_len = IPH_HDR_LENGTH(ipha);
6895 	plen = ntohs(ipha->ipha_length);
6896 
6897 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6898 		/*
6899 		 * Most likely a keepalive for the benefit of an intervening
6900 		 * NAT.  These aren't for us, per se, so drop it.
6901 		 *
6902 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6903 		 * byte packets (keepalives are 1-byte), but we'll drop them
6904 		 * also.
6905 		 */
6906 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6907 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6908 		return (B_FALSE);
6909 	}
6910 
6911 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6912 		/* might as well pull it all up - it might be ESP. */
6913 		if (!pullupmsg(mp, -1)) {
6914 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6915 			    DROPPER(ipss, ipds_esp_nomem),
6916 			    &ipss->ipsec_dropper);
6917 			return (B_FALSE);
6918 		}
6919 
6920 		ipha = (ipha_t *)mp->b_rptr;
6921 	}
6922 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6923 	if (*spi == 0) {
6924 		/* UDP packet - remove 0-spi. */
6925 		shift = sizeof (uint32_t);
6926 	} else {
6927 		/* ESP-in-UDP packet - reduce to ESP. */
6928 		ipha->ipha_protocol = IPPROTO_ESP;
6929 		shift = sizeof (udpha_t);
6930 	}
6931 
6932 	/* Fix IP header */
6933 	ipha->ipha_length = htons(plen - shift);
6934 	ipha->ipha_hdr_checksum = 0;
6935 
6936 	orptr = mp->b_rptr;
6937 	mp->b_rptr += shift;
6938 
6939 	udpha = (udpha_t *)(orptr + iph_len);
6940 	if (*spi == 0) {
6941 		ASSERT((uint8_t *)ipha == orptr);
6942 		udpha->uha_length = htons(plen - shift - iph_len);
6943 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6944 		esp_ports = 0;
6945 	} else {
6946 		esp_ports = *((uint32_t *)udpha);
6947 		ASSERT(esp_ports != 0);
6948 	}
6949 	ovbcopy(orptr, orptr + shift, iph_len);
6950 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6951 		ipha = (ipha_t *)(orptr + shift);
6952 
6953 		free_ire = (ire == NULL);
6954 		if (free_ire) {
6955 			/* Re-acquire ire. */
6956 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6957 			    ipss->ipsec_netstack->netstack_ip);
6958 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6959 				if (ire != NULL)
6960 					ire_refrele(ire);
6961 				/*
6962 				 * Do a regular freemsg(), as this is an IP
6963 				 * error (no local route) not an IPsec one.
6964 				 */
6965 				freemsg(mp);
6966 			}
6967 		}
6968 
6969 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
6970 		if (free_ire)
6971 			ire_refrele(ire);
6972 	}
6973 
6974 	return (esp_ports == 0);
6975 }
6976 
6977 /*
6978  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6979  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6980  * Caller is responsible for dropping references to the conn, and freeing
6981  * first_mp.
6982  *
6983  * IPQoS Notes
6984  * Before sending it to the client, invoke IPPF processing. Policy processing
6985  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6986  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6987  * ip_wput_local, ip_policy is false.
6988  */
6989 static void
6990 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6991     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6992     boolean_t ip_policy)
6993 {
6994 	boolean_t	mctl_present = (first_mp != NULL);
6995 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6996 	uint32_t	ill_index;
6997 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6998 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6999 
7000 	ASSERT(ill != NULL);
7001 
7002 	if (mctl_present)
7003 		first_mp->b_cont = mp;
7004 	else
7005 		first_mp = mp;
7006 
7007 	if (CONN_UDP_FLOWCTLD(connp)) {
7008 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7009 		freemsg(first_mp);
7010 		return;
7011 	}
7012 
7013 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7014 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7015 		    NULL, mctl_present);
7016 		if (first_mp == NULL) {
7017 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7018 			return;	/* Freed by ipsec_check_inbound_policy(). */
7019 		}
7020 	}
7021 	if (mctl_present)
7022 		freeb(first_mp);
7023 
7024 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7025 	if (connp->conn_udp->udp_nat_t_endpoint) {
7026 		if (mctl_present) {
7027 			/* mctl_present *shouldn't* happen. */
7028 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7029 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7030 			    &ipss->ipsec_dropper);
7031 			return;
7032 		}
7033 
7034 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7035 			return;
7036 	}
7037 
7038 	/* Handle options. */
7039 	if (connp->conn_recvif)
7040 		in_flags = IPF_RECVIF;
7041 	/*
7042 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7043 	 * passed to ip_add_info is based on IP version of connp.
7044 	 */
7045 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7046 		if (connp->conn_af_isv6) {
7047 			/*
7048 			 * V6 only needs index
7049 			 */
7050 			in_flags |= IPF_RECVIF;
7051 		} else {
7052 			/*
7053 			 * V4 needs index + matching address.
7054 			 */
7055 			in_flags |= IPF_RECVADDR;
7056 		}
7057 	}
7058 
7059 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7060 		in_flags |= IPF_RECVSLLA;
7061 
7062 	/*
7063 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7064 	 * freed if the packet is dropped. The caller will do so.
7065 	 */
7066 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7067 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7068 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7069 		if (mp == NULL) {
7070 			return;
7071 		}
7072 	}
7073 	if ((in_flags != 0) &&
7074 	    (mp->b_datap->db_type != M_CTL)) {
7075 		/*
7076 		 * The actual data will be contained in b_cont
7077 		 * upon successful return of the following call
7078 		 * else original mblk is returned
7079 		 */
7080 		ASSERT(recv_ill != NULL);
7081 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7082 		    ipst);
7083 	}
7084 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7085 	/* Send it upstream */
7086 	(connp->conn_recv)(connp, mp, NULL);
7087 }
7088 
7089 /*
7090  * Fanout for UDP packets.
7091  * The caller puts <fport, lport> in the ports parameter.
7092  *
7093  * If SO_REUSEADDR is set all multicast and broadcast packets
7094  * will be delivered to all streams bound to the same port.
7095  *
7096  * Zones notes:
7097  * Multicast and broadcast packets will be distributed to streams in all zones.
7098  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7099  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7100  * packets. To maintain this behavior with multiple zones, the conns are grouped
7101  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7102  * each zone. If unset, all the following conns in the same zone are skipped.
7103  */
7104 static void
7105 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7106     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7107     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7108 {
7109 	uint32_t	dstport, srcport;
7110 	ipaddr_t	dst;
7111 	mblk_t		*first_mp;
7112 	boolean_t	secure;
7113 	in6_addr_t	v6src;
7114 	conn_t		*connp;
7115 	connf_t		*connfp;
7116 	conn_t		*first_connp;
7117 	conn_t		*next_connp;
7118 	mblk_t		*mp1, *first_mp1;
7119 	ipaddr_t	src;
7120 	zoneid_t	last_zoneid;
7121 	boolean_t	reuseaddr;
7122 	boolean_t	shared_addr;
7123 	boolean_t	unlabeled;
7124 	ip_stack_t	*ipst;
7125 
7126 	ASSERT(recv_ill != NULL);
7127 	ipst = recv_ill->ill_ipst;
7128 
7129 	first_mp = mp;
7130 	if (mctl_present) {
7131 		mp = first_mp->b_cont;
7132 		first_mp->b_cont = NULL;
7133 		secure = ipsec_in_is_secure(first_mp);
7134 		ASSERT(mp != NULL);
7135 	} else {
7136 		first_mp = NULL;
7137 		secure = B_FALSE;
7138 	}
7139 
7140 	/* Extract ports in net byte order */
7141 	dstport = htons(ntohl(ports) & 0xFFFF);
7142 	srcport = htons(ntohl(ports) >> 16);
7143 	dst = ipha->ipha_dst;
7144 	src = ipha->ipha_src;
7145 
7146 	unlabeled = B_FALSE;
7147 	if (is_system_labeled())
7148 		/* Cred cannot be null on IPv4 */
7149 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7150 		    TSLF_UNLABELED) != 0;
7151 	shared_addr = (zoneid == ALL_ZONES);
7152 	if (shared_addr) {
7153 		/*
7154 		 * No need to handle exclusive-stack zones since ALL_ZONES
7155 		 * only applies to the shared stack.
7156 		 */
7157 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7158 		/*
7159 		 * If no shared MLP is found, tsol_mlp_findzone returns
7160 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7161 		 * search for the zone based on the packet label.
7162 		 *
7163 		 * If there is such a zone, we prefer to find a
7164 		 * connection in it.  Otherwise, we look for a
7165 		 * MAC-exempt connection in any zone whose label
7166 		 * dominates the default label on the packet.
7167 		 */
7168 		if (zoneid == ALL_ZONES)
7169 			zoneid = tsol_packet_to_zoneid(mp);
7170 		else
7171 			unlabeled = B_FALSE;
7172 	}
7173 
7174 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7175 	mutex_enter(&connfp->connf_lock);
7176 	connp = connfp->connf_head;
7177 	if (!broadcast && !CLASSD(dst)) {
7178 		/*
7179 		 * Not broadcast or multicast. Send to the one (first)
7180 		 * client we find. No need to check conn_wantpacket()
7181 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7182 		 * IPv4 unicast packets.
7183 		 */
7184 		while ((connp != NULL) &&
7185 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7186 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7187 		    !(unlabeled && connp->conn_mac_exempt)))) {
7188 			/*
7189 			 * We keep searching since the conn did not match,
7190 			 * or its zone did not match and it is not either
7191 			 * an allzones conn or a mac exempt conn (if the
7192 			 * sender is unlabeled.)
7193 			 */
7194 			connp = connp->conn_next;
7195 		}
7196 
7197 		if (connp == NULL || connp->conn_upq == NULL)
7198 			goto notfound;
7199 
7200 		if (is_system_labeled() &&
7201 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7202 		    connp))
7203 			goto notfound;
7204 
7205 		CONN_INC_REF(connp);
7206 		mutex_exit(&connfp->connf_lock);
7207 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7208 		    flags, recv_ill, ip_policy);
7209 		IP_STAT(ipst, ip_udp_fannorm);
7210 		CONN_DEC_REF(connp);
7211 		return;
7212 	}
7213 
7214 	/*
7215 	 * Broadcast and multicast case
7216 	 *
7217 	 * Need to check conn_wantpacket().
7218 	 * If SO_REUSEADDR has been set on the first we send the
7219 	 * packet to all clients that have joined the group and
7220 	 * match the port.
7221 	 */
7222 
7223 	while (connp != NULL) {
7224 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7225 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7226 		    (!is_system_labeled() ||
7227 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7228 		    connp)))
7229 			break;
7230 		connp = connp->conn_next;
7231 	}
7232 
7233 	if (connp == NULL || connp->conn_upq == NULL)
7234 		goto notfound;
7235 
7236 	first_connp = connp;
7237 	/*
7238 	 * When SO_REUSEADDR is not set, send the packet only to the first
7239 	 * matching connection in its zone by keeping track of the zoneid.
7240 	 */
7241 	reuseaddr = first_connp->conn_reuseaddr;
7242 	last_zoneid = first_connp->conn_zoneid;
7243 
7244 	CONN_INC_REF(connp);
7245 	connp = connp->conn_next;
7246 	for (;;) {
7247 		while (connp != NULL) {
7248 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7249 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7250 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7251 			    (!is_system_labeled() ||
7252 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7253 			    shared_addr, connp)))
7254 				break;
7255 			connp = connp->conn_next;
7256 		}
7257 		/*
7258 		 * Just copy the data part alone. The mctl part is
7259 		 * needed just for verifying policy and it is never
7260 		 * sent up.
7261 		 */
7262 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7263 		    ((mp1 = copymsg(mp)) == NULL))) {
7264 			/*
7265 			 * No more interested clients or memory
7266 			 * allocation failed
7267 			 */
7268 			connp = first_connp;
7269 			break;
7270 		}
7271 		if (connp->conn_zoneid != last_zoneid) {
7272 			/*
7273 			 * Update the zoneid so that the packet isn't sent to
7274 			 * any more conns in the same zone unless SO_REUSEADDR
7275 			 * is set.
7276 			 */
7277 			reuseaddr = connp->conn_reuseaddr;
7278 			last_zoneid = connp->conn_zoneid;
7279 		}
7280 		if (first_mp != NULL) {
7281 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7282 			    ipsec_info_type == IPSEC_IN);
7283 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7284 			    ipst->ips_netstack);
7285 			if (first_mp1 == NULL) {
7286 				freemsg(mp1);
7287 				connp = first_connp;
7288 				break;
7289 			}
7290 		} else {
7291 			first_mp1 = NULL;
7292 		}
7293 		CONN_INC_REF(connp);
7294 		mutex_exit(&connfp->connf_lock);
7295 		/*
7296 		 * IPQoS notes: We don't send the packet for policy
7297 		 * processing here, will do it for the last one (below).
7298 		 * i.e. we do it per-packet now, but if we do policy
7299 		 * processing per-conn, then we would need to do it
7300 		 * here too.
7301 		 */
7302 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7303 		    ipha, flags, recv_ill, B_FALSE);
7304 		mutex_enter(&connfp->connf_lock);
7305 		/* Follow the next pointer before releasing the conn. */
7306 		next_connp = connp->conn_next;
7307 		IP_STAT(ipst, ip_udp_fanmb);
7308 		CONN_DEC_REF(connp);
7309 		connp = next_connp;
7310 	}
7311 
7312 	/* Last one.  Send it upstream. */
7313 	mutex_exit(&connfp->connf_lock);
7314 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7315 	    recv_ill, ip_policy);
7316 	IP_STAT(ipst, ip_udp_fanmb);
7317 	CONN_DEC_REF(connp);
7318 	return;
7319 
7320 notfound:
7321 
7322 	mutex_exit(&connfp->connf_lock);
7323 	IP_STAT(ipst, ip_udp_fanothers);
7324 	/*
7325 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7326 	 * have already been matched above, since they live in the IPv4
7327 	 * fanout tables. This implies we only need to
7328 	 * check for IPv6 in6addr_any endpoints here.
7329 	 * Thus we compare using ipv6_all_zeros instead of the destination
7330 	 * address, except for the multicast group membership lookup which
7331 	 * uses the IPv4 destination.
7332 	 */
7333 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7334 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7335 	mutex_enter(&connfp->connf_lock);
7336 	connp = connfp->connf_head;
7337 	if (!broadcast && !CLASSD(dst)) {
7338 		while (connp != NULL) {
7339 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7340 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7341 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7342 			    !connp->conn_ipv6_v6only)
7343 				break;
7344 			connp = connp->conn_next;
7345 		}
7346 
7347 		if (connp != NULL && is_system_labeled() &&
7348 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7349 		    connp))
7350 			connp = NULL;
7351 
7352 		if (connp == NULL || connp->conn_upq == NULL) {
7353 			/*
7354 			 * No one bound to this port.  Is
7355 			 * there a client that wants all
7356 			 * unclaimed datagrams?
7357 			 */
7358 			mutex_exit(&connfp->connf_lock);
7359 
7360 			if (mctl_present)
7361 				first_mp->b_cont = mp;
7362 			else
7363 				first_mp = mp;
7364 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7365 			    connf_head != NULL) {
7366 				ip_fanout_proto(q, first_mp, ill, ipha,
7367 				    flags | IP_FF_RAWIP, mctl_present,
7368 				    ip_policy, recv_ill, zoneid);
7369 			} else {
7370 				if (ip_fanout_send_icmp(q, first_mp, flags,
7371 				    ICMP_DEST_UNREACHABLE,
7372 				    ICMP_PORT_UNREACHABLE,
7373 				    mctl_present, zoneid, ipst)) {
7374 					BUMP_MIB(ill->ill_ip_mib,
7375 					    udpIfStatsNoPorts);
7376 				}
7377 			}
7378 			return;
7379 		}
7380 
7381 		CONN_INC_REF(connp);
7382 		mutex_exit(&connfp->connf_lock);
7383 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7384 		    flags, recv_ill, ip_policy);
7385 		CONN_DEC_REF(connp);
7386 		return;
7387 	}
7388 	/*
7389 	 * IPv4 multicast packet being delivered to an AF_INET6
7390 	 * in6addr_any endpoint.
7391 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7392 	 * and not conn_wantpacket_v6() since any multicast membership is
7393 	 * for an IPv4-mapped multicast address.
7394 	 * The packet is sent to all clients in all zones that have joined the
7395 	 * group and match the port.
7396 	 */
7397 	while (connp != NULL) {
7398 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7399 		    srcport, v6src) &&
7400 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7401 		    (!is_system_labeled() ||
7402 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7403 		    connp)))
7404 			break;
7405 		connp = connp->conn_next;
7406 	}
7407 
7408 	if (connp == NULL || connp->conn_upq == NULL) {
7409 		/*
7410 		 * No one bound to this port.  Is
7411 		 * there a client that wants all
7412 		 * unclaimed datagrams?
7413 		 */
7414 		mutex_exit(&connfp->connf_lock);
7415 
7416 		if (mctl_present)
7417 			first_mp->b_cont = mp;
7418 		else
7419 			first_mp = mp;
7420 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7421 		    NULL) {
7422 			ip_fanout_proto(q, first_mp, ill, ipha,
7423 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7424 			    recv_ill, zoneid);
7425 		} else {
7426 			/*
7427 			 * We used to attempt to send an icmp error here, but
7428 			 * since this is known to be a multicast packet
7429 			 * and we don't send icmp errors in response to
7430 			 * multicast, just drop the packet and give up sooner.
7431 			 */
7432 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7433 			freemsg(first_mp);
7434 		}
7435 		return;
7436 	}
7437 
7438 	first_connp = connp;
7439 
7440 	CONN_INC_REF(connp);
7441 	connp = connp->conn_next;
7442 	for (;;) {
7443 		while (connp != NULL) {
7444 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7445 			    ipv6_all_zeros, srcport, v6src) &&
7446 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7447 			    (!is_system_labeled() ||
7448 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7449 			    shared_addr, connp)))
7450 				break;
7451 			connp = connp->conn_next;
7452 		}
7453 		/*
7454 		 * Just copy the data part alone. The mctl part is
7455 		 * needed just for verifying policy and it is never
7456 		 * sent up.
7457 		 */
7458 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7459 		    ((mp1 = copymsg(mp)) == NULL))) {
7460 			/*
7461 			 * No more intested clients or memory
7462 			 * allocation failed
7463 			 */
7464 			connp = first_connp;
7465 			break;
7466 		}
7467 		if (first_mp != NULL) {
7468 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7469 			    ipsec_info_type == IPSEC_IN);
7470 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7471 			    ipst->ips_netstack);
7472 			if (first_mp1 == NULL) {
7473 				freemsg(mp1);
7474 				connp = first_connp;
7475 				break;
7476 			}
7477 		} else {
7478 			first_mp1 = NULL;
7479 		}
7480 		CONN_INC_REF(connp);
7481 		mutex_exit(&connfp->connf_lock);
7482 		/*
7483 		 * IPQoS notes: We don't send the packet for policy
7484 		 * processing here, will do it for the last one (below).
7485 		 * i.e. we do it per-packet now, but if we do policy
7486 		 * processing per-conn, then we would need to do it
7487 		 * here too.
7488 		 */
7489 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7490 		    ipha, flags, recv_ill, B_FALSE);
7491 		mutex_enter(&connfp->connf_lock);
7492 		/* Follow the next pointer before releasing the conn. */
7493 		next_connp = connp->conn_next;
7494 		CONN_DEC_REF(connp);
7495 		connp = next_connp;
7496 	}
7497 
7498 	/* Last one.  Send it upstream. */
7499 	mutex_exit(&connfp->connf_lock);
7500 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7501 	    recv_ill, ip_policy);
7502 	CONN_DEC_REF(connp);
7503 }
7504 
7505 /*
7506  * Complete the ip_wput header so that it
7507  * is possible to generate ICMP
7508  * errors.
7509  */
7510 int
7511 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7512 {
7513 	ire_t *ire;
7514 
7515 	if (ipha->ipha_src == INADDR_ANY) {
7516 		ire = ire_lookup_local(zoneid, ipst);
7517 		if (ire == NULL) {
7518 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7519 			return (1);
7520 		}
7521 		ipha->ipha_src = ire->ire_addr;
7522 		ire_refrele(ire);
7523 	}
7524 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7525 	ipha->ipha_hdr_checksum = 0;
7526 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7527 	return (0);
7528 }
7529 
7530 /*
7531  * Nobody should be sending
7532  * packets up this stream
7533  */
7534 static void
7535 ip_lrput(queue_t *q, mblk_t *mp)
7536 {
7537 	mblk_t *mp1;
7538 
7539 	switch (mp->b_datap->db_type) {
7540 	case M_FLUSH:
7541 		/* Turn around */
7542 		if (*mp->b_rptr & FLUSHW) {
7543 			*mp->b_rptr &= ~FLUSHR;
7544 			qreply(q, mp);
7545 			return;
7546 		}
7547 		break;
7548 	}
7549 	/* Could receive messages that passed through ar_rput */
7550 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7551 		mp1->b_prev = mp1->b_next = NULL;
7552 	freemsg(mp);
7553 }
7554 
7555 /* Nobody should be sending packets down this stream */
7556 /* ARGSUSED */
7557 void
7558 ip_lwput(queue_t *q, mblk_t *mp)
7559 {
7560 	freemsg(mp);
7561 }
7562 
7563 /*
7564  * Move the first hop in any source route to ipha_dst and remove that part of
7565  * the source route.  Called by other protocols.  Errors in option formatting
7566  * are ignored - will be handled by ip_wput_options Return the final
7567  * destination (either ipha_dst or the last entry in a source route.)
7568  */
7569 ipaddr_t
7570 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7571 {
7572 	ipoptp_t	opts;
7573 	uchar_t		*opt;
7574 	uint8_t		optval;
7575 	uint8_t		optlen;
7576 	ipaddr_t	dst;
7577 	int		i;
7578 	ire_t		*ire;
7579 	ip_stack_t	*ipst = ns->netstack_ip;
7580 
7581 	ip2dbg(("ip_massage_options\n"));
7582 	dst = ipha->ipha_dst;
7583 	for (optval = ipoptp_first(&opts, ipha);
7584 	    optval != IPOPT_EOL;
7585 	    optval = ipoptp_next(&opts)) {
7586 		opt = opts.ipoptp_cur;
7587 		switch (optval) {
7588 			uint8_t off;
7589 		case IPOPT_SSRR:
7590 		case IPOPT_LSRR:
7591 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7592 				ip1dbg(("ip_massage_options: bad src route\n"));
7593 				break;
7594 			}
7595 			optlen = opts.ipoptp_len;
7596 			off = opt[IPOPT_OFFSET];
7597 			off--;
7598 		redo_srr:
7599 			if (optlen < IP_ADDR_LEN ||
7600 			    off > optlen - IP_ADDR_LEN) {
7601 				/* End of source route */
7602 				ip1dbg(("ip_massage_options: end of SR\n"));
7603 				break;
7604 			}
7605 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7606 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7607 			    ntohl(dst)));
7608 			/*
7609 			 * Check if our address is present more than
7610 			 * once as consecutive hops in source route.
7611 			 * XXX verify per-interface ip_forwarding
7612 			 * for source route?
7613 			 */
7614 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7615 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7616 			if (ire != NULL) {
7617 				ire_refrele(ire);
7618 				off += IP_ADDR_LEN;
7619 				goto redo_srr;
7620 			}
7621 			if (dst == htonl(INADDR_LOOPBACK)) {
7622 				ip1dbg(("ip_massage_options: loopback addr in "
7623 				    "source route!\n"));
7624 				break;
7625 			}
7626 			/*
7627 			 * Update ipha_dst to be the first hop and remove the
7628 			 * first hop from the source route (by overwriting
7629 			 * part of the option with NOP options).
7630 			 */
7631 			ipha->ipha_dst = dst;
7632 			/* Put the last entry in dst */
7633 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7634 			    3;
7635 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7636 
7637 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7638 			    ntohl(dst)));
7639 			/* Move down and overwrite */
7640 			opt[IP_ADDR_LEN] = opt[0];
7641 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7642 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7643 			for (i = 0; i < IP_ADDR_LEN; i++)
7644 				opt[i] = IPOPT_NOP;
7645 			break;
7646 		}
7647 	}
7648 	return (dst);
7649 }
7650 
7651 /*
7652  * Return the network mask
7653  * associated with the specified address.
7654  */
7655 ipaddr_t
7656 ip_net_mask(ipaddr_t addr)
7657 {
7658 	uchar_t	*up = (uchar_t *)&addr;
7659 	ipaddr_t mask = 0;
7660 	uchar_t	*maskp = (uchar_t *)&mask;
7661 
7662 #if defined(__i386) || defined(__amd64)
7663 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7664 #endif
7665 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7666 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7667 #endif
7668 	if (CLASSD(addr)) {
7669 		maskp[0] = 0xF0;
7670 		return (mask);
7671 	}
7672 
7673 	/* We assume Class E default netmask to be 32 */
7674 	if (CLASSE(addr))
7675 		return (0xffffffffU);
7676 
7677 	if (addr == 0)
7678 		return (0);
7679 	maskp[0] = 0xFF;
7680 	if ((up[0] & 0x80) == 0)
7681 		return (mask);
7682 
7683 	maskp[1] = 0xFF;
7684 	if ((up[0] & 0xC0) == 0x80)
7685 		return (mask);
7686 
7687 	maskp[2] = 0xFF;
7688 	if ((up[0] & 0xE0) == 0xC0)
7689 		return (mask);
7690 
7691 	/* Otherwise return no mask */
7692 	return ((ipaddr_t)0);
7693 }
7694 
7695 /*
7696  * Select an ill for the packet by considering load spreading across
7697  * a different ill in the group if dst_ill is part of some group.
7698  */
7699 ill_t *
7700 ip_newroute_get_dst_ill(ill_t *dst_ill)
7701 {
7702 	ill_t *ill;
7703 
7704 	/*
7705 	 * We schedule irrespective of whether the source address is
7706 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7707 	 */
7708 	ill = illgrp_scheduler(dst_ill);
7709 	if (ill == NULL)
7710 		return (NULL);
7711 
7712 	/*
7713 	 * For groups with names ip_sioctl_groupname ensures that all
7714 	 * ills are of same type. For groups without names, ifgrp_insert
7715 	 * ensures this.
7716 	 */
7717 	ASSERT(dst_ill->ill_type == ill->ill_type);
7718 
7719 	return (ill);
7720 }
7721 
7722 /*
7723  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7724  */
7725 ill_t *
7726 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7727     ip_stack_t *ipst)
7728 {
7729 	ill_t *ret_ill;
7730 
7731 	ASSERT(ifindex != 0);
7732 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7733 	    ipst);
7734 	if (ret_ill == NULL ||
7735 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7736 		if (isv6) {
7737 			if (ill != NULL) {
7738 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7739 			} else {
7740 				BUMP_MIB(&ipst->ips_ip6_mib,
7741 				    ipIfStatsOutDiscards);
7742 			}
7743 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7744 			    "bad ifindex %d.\n", ifindex));
7745 		} else {
7746 			if (ill != NULL) {
7747 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7748 			} else {
7749 				BUMP_MIB(&ipst->ips_ip_mib,
7750 				    ipIfStatsOutDiscards);
7751 			}
7752 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7753 			    "bad ifindex %d.\n", ifindex));
7754 		}
7755 		if (ret_ill != NULL)
7756 			ill_refrele(ret_ill);
7757 		freemsg(first_mp);
7758 		return (NULL);
7759 	}
7760 
7761 	return (ret_ill);
7762 }
7763 
7764 /*
7765  * IPv4 -
7766  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7767  * out a packet to a destination address for which we do not have specific
7768  * (or sufficient) routing information.
7769  *
7770  * NOTE : These are the scopes of some of the variables that point at IRE,
7771  *	  which needs to be followed while making any future modifications
7772  *	  to avoid memory leaks.
7773  *
7774  *	- ire and sire are the entries looked up initially by
7775  *	  ire_ftable_lookup.
7776  *	- ipif_ire is used to hold the interface ire associated with
7777  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7778  *	  it before branching out to error paths.
7779  *	- save_ire is initialized before ire_create, so that ire returned
7780  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7781  *	  before breaking out of the switch.
7782  *
7783  *	Thus on failures, we have to REFRELE only ire and sire, if they
7784  *	are not NULL.
7785  */
7786 void
7787 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7788     zoneid_t zoneid, ip_stack_t *ipst)
7789 {
7790 	areq_t	*areq;
7791 	ipaddr_t gw = 0;
7792 	ire_t	*ire = NULL;
7793 	mblk_t	*res_mp;
7794 	ipaddr_t *addrp;
7795 	ipaddr_t nexthop_addr;
7796 	ipif_t  *src_ipif = NULL;
7797 	ill_t	*dst_ill = NULL;
7798 	ipha_t  *ipha;
7799 	ire_t	*sire = NULL;
7800 	mblk_t	*first_mp;
7801 	ire_t	*save_ire;
7802 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7803 	ushort_t ire_marks = 0;
7804 	boolean_t mctl_present;
7805 	ipsec_out_t *io;
7806 	mblk_t	*saved_mp;
7807 	ire_t	*first_sire = NULL;
7808 	mblk_t	*copy_mp = NULL;
7809 	mblk_t	*xmit_mp = NULL;
7810 	ipaddr_t save_dst;
7811 	uint32_t multirt_flags =
7812 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7813 	boolean_t multirt_is_resolvable;
7814 	boolean_t multirt_resolve_next;
7815 	boolean_t unspec_src;
7816 	boolean_t do_attach_ill = B_FALSE;
7817 	boolean_t ip_nexthop = B_FALSE;
7818 	tsol_ire_gw_secattr_t *attrp = NULL;
7819 	tsol_gcgrp_t *gcgrp = NULL;
7820 	tsol_gcgrp_addr_t ga;
7821 
7822 	if (ip_debug > 2) {
7823 		/* ip1dbg */
7824 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7825 	}
7826 
7827 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7828 	if (mctl_present) {
7829 		io = (ipsec_out_t *)first_mp->b_rptr;
7830 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7831 		ASSERT(zoneid == io->ipsec_out_zoneid);
7832 		ASSERT(zoneid != ALL_ZONES);
7833 	}
7834 
7835 	ipha = (ipha_t *)mp->b_rptr;
7836 
7837 	/* All multicast lookups come through ip_newroute_ipif() */
7838 	if (CLASSD(dst)) {
7839 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7840 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7841 		freemsg(first_mp);
7842 		return;
7843 	}
7844 
7845 	if (mctl_present && io->ipsec_out_attach_if) {
7846 		/* ip_grab_attach_ill returns a held ill */
7847 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7848 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7849 
7850 		/* Failure case frees things for us. */
7851 		if (attach_ill == NULL)
7852 			return;
7853 
7854 		/*
7855 		 * Check if we need an ire that will not be
7856 		 * looked up by anybody else i.e. HIDDEN.
7857 		 */
7858 		if (ill_is_probeonly(attach_ill))
7859 			ire_marks = IRE_MARK_HIDDEN;
7860 	}
7861 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7862 		ip_nexthop = B_TRUE;
7863 		nexthop_addr = io->ipsec_out_nexthop_addr;
7864 	}
7865 	/*
7866 	 * If this IRE is created for forwarding or it is not for
7867 	 * traffic for congestion controlled protocols, mark it as temporary.
7868 	 */
7869 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7870 		ire_marks |= IRE_MARK_TEMPORARY;
7871 
7872 	/*
7873 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7874 	 * chain until it gets the most specific information available.
7875 	 * For example, we know that there is no IRE_CACHE for this dest,
7876 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7877 	 * ire_ftable_lookup will look up the gateway, etc.
7878 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7879 	 * to the destination, of equal netmask length in the forward table,
7880 	 * will be recursively explored. If no information is available
7881 	 * for the final gateway of that route, we force the returned ire
7882 	 * to be equal to sire using MATCH_IRE_PARENT.
7883 	 * At least, in this case we have a starting point (in the buckets)
7884 	 * to look for other routes to the destination in the forward table.
7885 	 * This is actually used only for multirouting, where a list
7886 	 * of routes has to be processed in sequence.
7887 	 *
7888 	 * In the process of coming up with the most specific information,
7889 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7890 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7891 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7892 	 * Two caveats when handling incomplete ire's in ip_newroute:
7893 	 * - we should be careful when accessing its ire_nce (specifically
7894 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7895 	 * - not all legacy code path callers are prepared to handle
7896 	 *   incomplete ire's, so we should not create/add incomplete
7897 	 *   ire_cache entries here. (See discussion about temporary solution
7898 	 *   further below).
7899 	 *
7900 	 * In order to minimize packet dropping, and to preserve existing
7901 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7902 	 * gateway, and instead use the IF_RESOLVER ire to send out
7903 	 * another request to ARP (this is achieved by passing the
7904 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7905 	 * arp response comes back in ip_wput_nondata, we will create
7906 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7907 	 *
7908 	 * Note that this is a temporary solution; the correct solution is
7909 	 * to create an incomplete  per-dst ire_cache entry, and send the
7910 	 * packet out when the gw's nce is resolved. In order to achieve this,
7911 	 * all packet processing must have been completed prior to calling
7912 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7913 	 * to be modified to accomodate this solution.
7914 	 */
7915 	if (ip_nexthop) {
7916 		/*
7917 		 * The first time we come here, we look for an IRE_INTERFACE
7918 		 * entry for the specified nexthop, set the dst to be the
7919 		 * nexthop address and create an IRE_CACHE entry for the
7920 		 * nexthop. The next time around, we are able to find an
7921 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7922 		 * nexthop address and create an IRE_CACHE entry for the
7923 		 * destination address via the specified nexthop.
7924 		 */
7925 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7926 		    MBLK_GETLABEL(mp), ipst);
7927 		if (ire != NULL) {
7928 			gw = nexthop_addr;
7929 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7930 		} else {
7931 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7932 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7933 			    MBLK_GETLABEL(mp),
7934 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7935 			    ipst);
7936 			if (ire != NULL) {
7937 				dst = nexthop_addr;
7938 			}
7939 		}
7940 	} else if (attach_ill == NULL) {
7941 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7942 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7943 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7944 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7945 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7946 		    ipst);
7947 	} else {
7948 		/*
7949 		 * attach_ill is set only for communicating with
7950 		 * on-link hosts. So, don't look for DEFAULT.
7951 		 */
7952 		ipif_t	*attach_ipif;
7953 
7954 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7955 		if (attach_ipif == NULL) {
7956 			ill_refrele(attach_ill);
7957 			goto icmp_err_ret;
7958 		}
7959 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7960 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7961 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7962 		    MATCH_IRE_SECATTR, ipst);
7963 		ipif_refrele(attach_ipif);
7964 	}
7965 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7966 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7967 
7968 	/*
7969 	 * This loop is run only once in most cases.
7970 	 * We loop to resolve further routes only when the destination
7971 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7972 	 */
7973 	do {
7974 		/* Clear the previous iteration's values */
7975 		if (src_ipif != NULL) {
7976 			ipif_refrele(src_ipif);
7977 			src_ipif = NULL;
7978 		}
7979 		if (dst_ill != NULL) {
7980 			ill_refrele(dst_ill);
7981 			dst_ill = NULL;
7982 		}
7983 
7984 		multirt_resolve_next = B_FALSE;
7985 		/*
7986 		 * We check if packets have to be multirouted.
7987 		 * In this case, given the current <ire, sire> couple,
7988 		 * we look for the next suitable <ire, sire>.
7989 		 * This check is done in ire_multirt_lookup(),
7990 		 * which applies various criteria to find the next route
7991 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7992 		 * unchanged if it detects it has not been tried yet.
7993 		 */
7994 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7995 			ip3dbg(("ip_newroute: starting next_resolution "
7996 			    "with first_mp %p, tag %d\n",
7997 			    (void *)first_mp,
7998 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7999 
8000 			ASSERT(sire != NULL);
8001 			multirt_is_resolvable =
8002 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8003 			    MBLK_GETLABEL(mp), ipst);
8004 
8005 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8006 			    "ire %p, sire %p\n",
8007 			    multirt_is_resolvable,
8008 			    (void *)ire, (void *)sire));
8009 
8010 			if (!multirt_is_resolvable) {
8011 				/*
8012 				 * No more multirt route to resolve; give up
8013 				 * (all routes resolved or no more
8014 				 * resolvable routes).
8015 				 */
8016 				if (ire != NULL) {
8017 					ire_refrele(ire);
8018 					ire = NULL;
8019 				}
8020 			} else {
8021 				ASSERT(sire != NULL);
8022 				ASSERT(ire != NULL);
8023 				/*
8024 				 * We simply use first_sire as a flag that
8025 				 * indicates if a resolvable multirt route
8026 				 * has already been found.
8027 				 * If it is not the case, we may have to send
8028 				 * an ICMP error to report that the
8029 				 * destination is unreachable.
8030 				 * We do not IRE_REFHOLD first_sire.
8031 				 */
8032 				if (first_sire == NULL) {
8033 					first_sire = sire;
8034 				}
8035 			}
8036 		}
8037 		if (ire == NULL) {
8038 			if (ip_debug > 3) {
8039 				/* ip2dbg */
8040 				pr_addr_dbg("ip_newroute: "
8041 				    "can't resolve %s\n", AF_INET, &dst);
8042 			}
8043 			ip3dbg(("ip_newroute: "
8044 			    "ire %p, sire %p, first_sire %p\n",
8045 			    (void *)ire, (void *)sire, (void *)first_sire));
8046 
8047 			if (sire != NULL) {
8048 				ire_refrele(sire);
8049 				sire = NULL;
8050 			}
8051 
8052 			if (first_sire != NULL) {
8053 				/*
8054 				 * At least one multirt route has been found
8055 				 * in the same call to ip_newroute();
8056 				 * there is no need to report an ICMP error.
8057 				 * first_sire was not IRE_REFHOLDed.
8058 				 */
8059 				MULTIRT_DEBUG_UNTAG(first_mp);
8060 				freemsg(first_mp);
8061 				return;
8062 			}
8063 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8064 			    RTA_DST, ipst);
8065 			if (attach_ill != NULL)
8066 				ill_refrele(attach_ill);
8067 			goto icmp_err_ret;
8068 		}
8069 
8070 		/*
8071 		 * Verify that the returned IRE does not have either
8072 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8073 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8074 		 */
8075 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8076 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8077 			if (attach_ill != NULL)
8078 				ill_refrele(attach_ill);
8079 			goto icmp_err_ret;
8080 		}
8081 		/*
8082 		 * Increment the ire_ob_pkt_count field for ire if it is an
8083 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8084 		 * increment the same for the parent IRE, sire, if it is some
8085 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8086 		 */
8087 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8088 			UPDATE_OB_PKT_COUNT(ire);
8089 			ire->ire_last_used_time = lbolt;
8090 		}
8091 
8092 		if (sire != NULL) {
8093 			gw = sire->ire_gateway_addr;
8094 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8095 			    IRE_INTERFACE)) == 0);
8096 			UPDATE_OB_PKT_COUNT(sire);
8097 			sire->ire_last_used_time = lbolt;
8098 		}
8099 		/*
8100 		 * We have a route to reach the destination.
8101 		 *
8102 		 * 1) If the interface is part of ill group, try to get a new
8103 		 *    ill taking load spreading into account.
8104 		 *
8105 		 * 2) After selecting the ill, get a source address that
8106 		 *    might create good inbound load spreading.
8107 		 *    ipif_select_source does this for us.
8108 		 *
8109 		 * If the application specified the ill (ifindex), we still
8110 		 * load spread. Only if the packets needs to go out
8111 		 * specifically on a given ill e.g. binding to
8112 		 * IPIF_NOFAILOVER address, then we don't try to use a
8113 		 * different ill for load spreading.
8114 		 */
8115 		if (attach_ill == NULL) {
8116 			/*
8117 			 * Don't perform outbound load spreading in the
8118 			 * case of an RTF_MULTIRT route, as we actually
8119 			 * typically want to replicate outgoing packets
8120 			 * through particular interfaces.
8121 			 */
8122 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8123 				dst_ill = ire->ire_ipif->ipif_ill;
8124 				/* for uniformity */
8125 				ill_refhold(dst_ill);
8126 			} else {
8127 				/*
8128 				 * If we are here trying to create an IRE_CACHE
8129 				 * for an offlink destination and have the
8130 				 * IRE_CACHE for the next hop and the latter is
8131 				 * using virtual IP source address selection i.e
8132 				 * it's ire->ire_ipif is pointing to a virtual
8133 				 * network interface (vni) then
8134 				 * ip_newroute_get_dst_ll() will return the vni
8135 				 * interface as the dst_ill. Since the vni is
8136 				 * virtual i.e not associated with any physical
8137 				 * interface, it cannot be the dst_ill, hence
8138 				 * in such a case call ip_newroute_get_dst_ll()
8139 				 * with the stq_ill instead of the ire_ipif ILL.
8140 				 * The function returns a refheld ill.
8141 				 */
8142 				if ((ire->ire_type == IRE_CACHE) &&
8143 				    IS_VNI(ire->ire_ipif->ipif_ill))
8144 					dst_ill = ip_newroute_get_dst_ill(
8145 					    ire->ire_stq->q_ptr);
8146 				else
8147 					dst_ill = ip_newroute_get_dst_ill(
8148 					    ire->ire_ipif->ipif_ill);
8149 			}
8150 			if (dst_ill == NULL) {
8151 				if (ip_debug > 2) {
8152 					pr_addr_dbg("ip_newroute: "
8153 					    "no dst ill for dst"
8154 					    " %s\n", AF_INET, &dst);
8155 				}
8156 				goto icmp_err_ret;
8157 			}
8158 		} else {
8159 			dst_ill = ire->ire_ipif->ipif_ill;
8160 			/* for uniformity */
8161 			ill_refhold(dst_ill);
8162 			/*
8163 			 * We should have found a route matching ill as we
8164 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8165 			 * Rather than asserting, when there is a mismatch,
8166 			 * we just drop the packet.
8167 			 */
8168 			if (dst_ill != attach_ill) {
8169 				ip0dbg(("ip_newroute: Packet dropped as "
8170 				    "IPIF_NOFAILOVER ill is %s, "
8171 				    "ire->ire_ipif->ipif_ill is %s\n",
8172 				    attach_ill->ill_name,
8173 				    dst_ill->ill_name));
8174 				ill_refrele(attach_ill);
8175 				goto icmp_err_ret;
8176 			}
8177 		}
8178 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8179 		if (attach_ill != NULL) {
8180 			ill_refrele(attach_ill);
8181 			attach_ill = NULL;
8182 			do_attach_ill = B_TRUE;
8183 		}
8184 		ASSERT(dst_ill != NULL);
8185 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8186 
8187 		/*
8188 		 * Pick the best source address from dst_ill.
8189 		 *
8190 		 * 1) If it is part of a multipathing group, we would
8191 		 *    like to spread the inbound packets across different
8192 		 *    interfaces. ipif_select_source picks a random source
8193 		 *    across the different ills in the group.
8194 		 *
8195 		 * 2) If it is not part of a multipathing group, we try
8196 		 *    to pick the source address from the destination
8197 		 *    route. Clustering assumes that when we have multiple
8198 		 *    prefixes hosted on an interface, the prefix of the
8199 		 *    source address matches the prefix of the destination
8200 		 *    route. We do this only if the address is not
8201 		 *    DEPRECATED.
8202 		 *
8203 		 * 3) If the conn is in a different zone than the ire, we
8204 		 *    need to pick a source address from the right zone.
8205 		 *
8206 		 * NOTE : If we hit case (1) above, the prefix of the source
8207 		 *	  address picked may not match the prefix of the
8208 		 *	  destination routes prefix as ipif_select_source
8209 		 *	  does not look at "dst" while picking a source
8210 		 *	  address.
8211 		 *	  If we want the same behavior as (2), we will need
8212 		 *	  to change the behavior of ipif_select_source.
8213 		 */
8214 		ASSERT(src_ipif == NULL);
8215 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8216 			/*
8217 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8218 			 * Check that the ipif matching the requested source
8219 			 * address still exists.
8220 			 */
8221 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8222 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8223 		}
8224 
8225 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8226 
8227 		if (src_ipif == NULL &&
8228 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8229 			ire_marks |= IRE_MARK_USESRC_CHECK;
8230 			if ((dst_ill->ill_group != NULL) ||
8231 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8232 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8233 			    ire->ire_zoneid != ALL_ZONES) ||
8234 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8235 				/*
8236 				 * If the destination is reachable via a
8237 				 * given gateway, the selected source address
8238 				 * should be in the same subnet as the gateway.
8239 				 * Otherwise, the destination is not reachable.
8240 				 *
8241 				 * If there are no interfaces on the same subnet
8242 				 * as the destination, ipif_select_source gives
8243 				 * first non-deprecated interface which might be
8244 				 * on a different subnet than the gateway.
8245 				 * This is not desirable. Hence pass the dst_ire
8246 				 * source address to ipif_select_source.
8247 				 * It is sure that the destination is reachable
8248 				 * with the dst_ire source address subnet.
8249 				 * So passing dst_ire source address to
8250 				 * ipif_select_source will make sure that the
8251 				 * selected source will be on the same subnet
8252 				 * as dst_ire source address.
8253 				 */
8254 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8255 				src_ipif = ipif_select_source(dst_ill, saddr,
8256 				    zoneid);
8257 				if (src_ipif == NULL) {
8258 					if (ip_debug > 2) {
8259 						pr_addr_dbg("ip_newroute: "
8260 						    "no src for dst %s ",
8261 						    AF_INET, &dst);
8262 						printf("through interface %s\n",
8263 						    dst_ill->ill_name);
8264 					}
8265 					goto icmp_err_ret;
8266 				}
8267 			} else {
8268 				src_ipif = ire->ire_ipif;
8269 				ASSERT(src_ipif != NULL);
8270 				/* hold src_ipif for uniformity */
8271 				ipif_refhold(src_ipif);
8272 			}
8273 		}
8274 
8275 		/*
8276 		 * Assign a source address while we have the conn.
8277 		 * We can't have ip_wput_ire pick a source address when the
8278 		 * packet returns from arp since we need to look at
8279 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8280 		 * going through arp.
8281 		 *
8282 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8283 		 *	  it uses ip6i to store this information.
8284 		 */
8285 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8286 			ipha->ipha_src = src_ipif->ipif_src_addr;
8287 
8288 		if (ip_debug > 3) {
8289 			/* ip2dbg */
8290 			pr_addr_dbg("ip_newroute: first hop %s\n",
8291 			    AF_INET, &gw);
8292 		}
8293 		ip2dbg(("\tire type %s (%d)\n",
8294 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8295 
8296 		/*
8297 		 * The TTL of multirouted packets is bounded by the
8298 		 * ip_multirt_ttl ndd variable.
8299 		 */
8300 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8301 			/* Force TTL of multirouted packets */
8302 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8303 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8304 				ip2dbg(("ip_newroute: forcing multirt TTL "
8305 				    "to %d (was %d), dst 0x%08x\n",
8306 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8307 				    ntohl(sire->ire_addr)));
8308 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8309 			}
8310 		}
8311 		/*
8312 		 * At this point in ip_newroute(), ire is either the
8313 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8314 		 * destination or an IRE_INTERFACE type that should be used
8315 		 * to resolve an on-subnet destination or an on-subnet
8316 		 * next-hop gateway.
8317 		 *
8318 		 * In the IRE_CACHE case, we have the following :
8319 		 *
8320 		 * 1) src_ipif - used for getting a source address.
8321 		 *
8322 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8323 		 *    means packets using this IRE_CACHE will go out on
8324 		 *    dst_ill.
8325 		 *
8326 		 * 3) The IRE sire will point to the prefix that is the
8327 		 *    longest  matching route for the destination. These
8328 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8329 		 *
8330 		 *    The newly created IRE_CACHE entry for the off-subnet
8331 		 *    destination is tied to both the prefix route and the
8332 		 *    interface route used to resolve the next-hop gateway
8333 		 *    via the ire_phandle and ire_ihandle fields,
8334 		 *    respectively.
8335 		 *
8336 		 * In the IRE_INTERFACE case, we have the following :
8337 		 *
8338 		 * 1) src_ipif - used for getting a source address.
8339 		 *
8340 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8341 		 *    means packets using the IRE_CACHE that we will build
8342 		 *    here will go out on dst_ill.
8343 		 *
8344 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8345 		 *    to be created will only be tied to the IRE_INTERFACE
8346 		 *    that was derived from the ire_ihandle field.
8347 		 *
8348 		 *    If sire is non-NULL, it means the destination is
8349 		 *    off-link and we will first create the IRE_CACHE for the
8350 		 *    gateway. Next time through ip_newroute, we will create
8351 		 *    the IRE_CACHE for the final destination as described
8352 		 *    above.
8353 		 *
8354 		 * In both cases, after the current resolution has been
8355 		 * completed (or possibly initialised, in the IRE_INTERFACE
8356 		 * case), the loop may be re-entered to attempt the resolution
8357 		 * of another RTF_MULTIRT route.
8358 		 *
8359 		 * When an IRE_CACHE entry for the off-subnet destination is
8360 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8361 		 * for further processing in emission loops.
8362 		 */
8363 		save_ire = ire;
8364 		switch (ire->ire_type) {
8365 		case IRE_CACHE: {
8366 			ire_t	*ipif_ire;
8367 
8368 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8369 			if (gw == 0)
8370 				gw = ire->ire_gateway_addr;
8371 			/*
8372 			 * We need 3 ire's to create a new cache ire for an
8373 			 * off-link destination from the cache ire of the
8374 			 * gateway.
8375 			 *
8376 			 *	1. The prefix ire 'sire' (Note that this does
8377 			 *	   not apply to the conn_nexthop_set case)
8378 			 *	2. The cache ire of the gateway 'ire'
8379 			 *	3. The interface ire 'ipif_ire'
8380 			 *
8381 			 * We have (1) and (2). We lookup (3) below.
8382 			 *
8383 			 * If there is no interface route to the gateway,
8384 			 * it is a race condition, where we found the cache
8385 			 * but the interface route has been deleted.
8386 			 */
8387 			if (ip_nexthop) {
8388 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8389 			} else {
8390 				ipif_ire =
8391 				    ire_ihandle_lookup_offlink(ire, sire);
8392 			}
8393 			if (ipif_ire == NULL) {
8394 				ip1dbg(("ip_newroute: "
8395 				    "ire_ihandle_lookup_offlink failed\n"));
8396 				goto icmp_err_ret;
8397 			}
8398 
8399 			/*
8400 			 * Check cached gateway IRE for any security
8401 			 * attributes; if found, associate the gateway
8402 			 * credentials group to the destination IRE.
8403 			 */
8404 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8405 				mutex_enter(&attrp->igsa_lock);
8406 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8407 					GCGRP_REFHOLD(gcgrp);
8408 				mutex_exit(&attrp->igsa_lock);
8409 			}
8410 
8411 			/*
8412 			 * XXX For the source of the resolver mp,
8413 			 * we are using the same DL_UNITDATA_REQ
8414 			 * (from save_ire->ire_nce->nce_res_mp)
8415 			 * though the save_ire is not pointing at the same ill.
8416 			 * This is incorrect. We need to send it up to the
8417 			 * resolver to get the right res_mp. For ethernets
8418 			 * this may be okay (ill_type == DL_ETHER).
8419 			 */
8420 
8421 			ire = ire_create(
8422 			    (uchar_t *)&dst,		/* dest address */
8423 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8424 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8425 			    (uchar_t *)&gw,		/* gateway address */
8426 			    &save_ire->ire_max_frag,
8427 			    save_ire->ire_nce,		/* src nce */
8428 			    dst_ill->ill_rq,		/* recv-from queue */
8429 			    dst_ill->ill_wq,		/* send-to queue */
8430 			    IRE_CACHE,			/* IRE type */
8431 			    src_ipif,
8432 			    (sire != NULL) ?
8433 			    sire->ire_mask : 0, 	/* Parent mask */
8434 			    (sire != NULL) ?
8435 			    sire->ire_phandle : 0,	/* Parent handle */
8436 			    ipif_ire->ire_ihandle,	/* Interface handle */
8437 			    (sire != NULL) ? (sire->ire_flags &
8438 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8439 			    (sire != NULL) ?
8440 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8441 			    NULL,
8442 			    gcgrp,
8443 			    ipst);
8444 
8445 			if (ire == NULL) {
8446 				if (gcgrp != NULL) {
8447 					GCGRP_REFRELE(gcgrp);
8448 					gcgrp = NULL;
8449 				}
8450 				ire_refrele(ipif_ire);
8451 				ire_refrele(save_ire);
8452 				break;
8453 			}
8454 
8455 			/* reference now held by IRE */
8456 			gcgrp = NULL;
8457 
8458 			ire->ire_marks |= ire_marks;
8459 
8460 			/*
8461 			 * Prevent sire and ipif_ire from getting deleted.
8462 			 * The newly created ire is tied to both of them via
8463 			 * the phandle and ihandle respectively.
8464 			 */
8465 			if (sire != NULL) {
8466 				IRB_REFHOLD(sire->ire_bucket);
8467 				/* Has it been removed already ? */
8468 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8469 					IRB_REFRELE(sire->ire_bucket);
8470 					ire_refrele(ipif_ire);
8471 					ire_refrele(save_ire);
8472 					break;
8473 				}
8474 			}
8475 
8476 			IRB_REFHOLD(ipif_ire->ire_bucket);
8477 			/* Has it been removed already ? */
8478 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8479 				IRB_REFRELE(ipif_ire->ire_bucket);
8480 				if (sire != NULL)
8481 					IRB_REFRELE(sire->ire_bucket);
8482 				ire_refrele(ipif_ire);
8483 				ire_refrele(save_ire);
8484 				break;
8485 			}
8486 
8487 			xmit_mp = first_mp;
8488 			/*
8489 			 * In the case of multirouting, a copy
8490 			 * of the packet is done before its sending.
8491 			 * The copy is used to attempt another
8492 			 * route resolution, in a next loop.
8493 			 */
8494 			if (ire->ire_flags & RTF_MULTIRT) {
8495 				copy_mp = copymsg(first_mp);
8496 				if (copy_mp != NULL) {
8497 					xmit_mp = copy_mp;
8498 					MULTIRT_DEBUG_TAG(first_mp);
8499 				}
8500 			}
8501 			ire_add_then_send(q, ire, xmit_mp);
8502 			ire_refrele(save_ire);
8503 
8504 			/* Assert that sire is not deleted yet. */
8505 			if (sire != NULL) {
8506 				ASSERT(sire->ire_ptpn != NULL);
8507 				IRB_REFRELE(sire->ire_bucket);
8508 			}
8509 
8510 			/* Assert that ipif_ire is not deleted yet. */
8511 			ASSERT(ipif_ire->ire_ptpn != NULL);
8512 			IRB_REFRELE(ipif_ire->ire_bucket);
8513 			ire_refrele(ipif_ire);
8514 
8515 			/*
8516 			 * If copy_mp is not NULL, multirouting was
8517 			 * requested. We loop to initiate a next
8518 			 * route resolution attempt, starting from sire.
8519 			 */
8520 			if (copy_mp != NULL) {
8521 				/*
8522 				 * Search for the next unresolved
8523 				 * multirt route.
8524 				 */
8525 				copy_mp = NULL;
8526 				ipif_ire = NULL;
8527 				ire = NULL;
8528 				multirt_resolve_next = B_TRUE;
8529 				continue;
8530 			}
8531 			if (sire != NULL)
8532 				ire_refrele(sire);
8533 			ipif_refrele(src_ipif);
8534 			ill_refrele(dst_ill);
8535 			return;
8536 		}
8537 		case IRE_IF_NORESOLVER: {
8538 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8539 			    dst_ill->ill_resolver_mp == NULL) {
8540 				ip1dbg(("ip_newroute: dst_ill %p "
8541 				    "for IRE_IF_NORESOLVER ire %p has "
8542 				    "no ill_resolver_mp\n",
8543 				    (void *)dst_ill, (void *)ire));
8544 				break;
8545 			}
8546 
8547 			/*
8548 			 * TSol note: We are creating the ire cache for the
8549 			 * destination 'dst'. If 'dst' is offlink, going
8550 			 * through the first hop 'gw', the security attributes
8551 			 * of 'dst' must be set to point to the gateway
8552 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8553 			 * is possible that 'dst' is a potential gateway that is
8554 			 * referenced by some route that has some security
8555 			 * attributes. Thus in the former case, we need to do a
8556 			 * gcgrp_lookup of 'gw' while in the latter case we
8557 			 * need to do gcgrp_lookup of 'dst' itself.
8558 			 */
8559 			ga.ga_af = AF_INET;
8560 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8561 			    &ga.ga_addr);
8562 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8563 
8564 			ire = ire_create(
8565 			    (uchar_t *)&dst,		/* dest address */
8566 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8567 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8568 			    (uchar_t *)&gw,		/* gateway address */
8569 			    &save_ire->ire_max_frag,
8570 			    NULL,			/* no src nce */
8571 			    dst_ill->ill_rq,		/* recv-from queue */
8572 			    dst_ill->ill_wq,		/* send-to queue */
8573 			    IRE_CACHE,
8574 			    src_ipif,
8575 			    save_ire->ire_mask,		/* Parent mask */
8576 			    (sire != NULL) ?		/* Parent handle */
8577 			    sire->ire_phandle : 0,
8578 			    save_ire->ire_ihandle,	/* Interface handle */
8579 			    (sire != NULL) ? sire->ire_flags &
8580 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8581 			    &(save_ire->ire_uinfo),
8582 			    NULL,
8583 			    gcgrp,
8584 			    ipst);
8585 
8586 			if (ire == NULL) {
8587 				if (gcgrp != NULL) {
8588 					GCGRP_REFRELE(gcgrp);
8589 					gcgrp = NULL;
8590 				}
8591 				ire_refrele(save_ire);
8592 				break;
8593 			}
8594 
8595 			/* reference now held by IRE */
8596 			gcgrp = NULL;
8597 
8598 			ire->ire_marks |= ire_marks;
8599 
8600 			/* Prevent save_ire from getting deleted */
8601 			IRB_REFHOLD(save_ire->ire_bucket);
8602 			/* Has it been removed already ? */
8603 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8604 				IRB_REFRELE(save_ire->ire_bucket);
8605 				ire_refrele(save_ire);
8606 				break;
8607 			}
8608 
8609 			/*
8610 			 * In the case of multirouting, a copy
8611 			 * of the packet is made before it is sent.
8612 			 * The copy is used in the next
8613 			 * loop to attempt another resolution.
8614 			 */
8615 			xmit_mp = first_mp;
8616 			if ((sire != NULL) &&
8617 			    (sire->ire_flags & RTF_MULTIRT)) {
8618 				copy_mp = copymsg(first_mp);
8619 				if (copy_mp != NULL) {
8620 					xmit_mp = copy_mp;
8621 					MULTIRT_DEBUG_TAG(first_mp);
8622 				}
8623 			}
8624 			ire_add_then_send(q, ire, xmit_mp);
8625 
8626 			/* Assert that it is not deleted yet. */
8627 			ASSERT(save_ire->ire_ptpn != NULL);
8628 			IRB_REFRELE(save_ire->ire_bucket);
8629 			ire_refrele(save_ire);
8630 
8631 			if (copy_mp != NULL) {
8632 				/*
8633 				 * If we found a (no)resolver, we ignore any
8634 				 * trailing top priority IRE_CACHE in further
8635 				 * loops. This ensures that we do not omit any
8636 				 * (no)resolver.
8637 				 * This IRE_CACHE, if any, will be processed
8638 				 * by another thread entering ip_newroute().
8639 				 * IRE_CACHE entries, if any, will be processed
8640 				 * by another thread entering ip_newroute(),
8641 				 * (upon resolver response, for instance).
8642 				 * This aims to force parallel multirt
8643 				 * resolutions as soon as a packet must be sent.
8644 				 * In the best case, after the tx of only one
8645 				 * packet, all reachable routes are resolved.
8646 				 * Otherwise, the resolution of all RTF_MULTIRT
8647 				 * routes would require several emissions.
8648 				 */
8649 				multirt_flags &= ~MULTIRT_CACHEGW;
8650 
8651 				/*
8652 				 * Search for the next unresolved multirt
8653 				 * route.
8654 				 */
8655 				copy_mp = NULL;
8656 				save_ire = NULL;
8657 				ire = NULL;
8658 				multirt_resolve_next = B_TRUE;
8659 				continue;
8660 			}
8661 
8662 			/*
8663 			 * Don't need sire anymore
8664 			 */
8665 			if (sire != NULL)
8666 				ire_refrele(sire);
8667 
8668 			ipif_refrele(src_ipif);
8669 			ill_refrele(dst_ill);
8670 			return;
8671 		}
8672 		case IRE_IF_RESOLVER:
8673 			/*
8674 			 * We can't build an IRE_CACHE yet, but at least we
8675 			 * found a resolver that can help.
8676 			 */
8677 			res_mp = dst_ill->ill_resolver_mp;
8678 			if (!OK_RESOLVER_MP(res_mp))
8679 				break;
8680 
8681 			/*
8682 			 * To be at this point in the code with a non-zero gw
8683 			 * means that dst is reachable through a gateway that
8684 			 * we have never resolved.  By changing dst to the gw
8685 			 * addr we resolve the gateway first.
8686 			 * When ire_add_then_send() tries to put the IP dg
8687 			 * to dst, it will reenter ip_newroute() at which
8688 			 * time we will find the IRE_CACHE for the gw and
8689 			 * create another IRE_CACHE in case IRE_CACHE above.
8690 			 */
8691 			if (gw != INADDR_ANY) {
8692 				/*
8693 				 * The source ipif that was determined above was
8694 				 * relative to the destination address, not the
8695 				 * gateway's. If src_ipif was not taken out of
8696 				 * the IRE_IF_RESOLVER entry, we'll need to call
8697 				 * ipif_select_source() again.
8698 				 */
8699 				if (src_ipif != ire->ire_ipif) {
8700 					ipif_refrele(src_ipif);
8701 					src_ipif = ipif_select_source(dst_ill,
8702 					    gw, zoneid);
8703 					if (src_ipif == NULL) {
8704 						if (ip_debug > 2) {
8705 							pr_addr_dbg(
8706 							    "ip_newroute: no "
8707 							    "src for gw %s ",
8708 							    AF_INET, &gw);
8709 							printf("through "
8710 							    "interface %s\n",
8711 							    dst_ill->ill_name);
8712 						}
8713 						goto icmp_err_ret;
8714 					}
8715 				}
8716 				save_dst = dst;
8717 				dst = gw;
8718 				gw = INADDR_ANY;
8719 			}
8720 
8721 			/*
8722 			 * We obtain a partial IRE_CACHE which we will pass
8723 			 * along with the resolver query.  When the response
8724 			 * comes back it will be there ready for us to add.
8725 			 * The ire_max_frag is atomically set under the
8726 			 * irebucket lock in ire_add_v[46].
8727 			 */
8728 
8729 			ire = ire_create_mp(
8730 			    (uchar_t *)&dst,		/* dest address */
8731 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8732 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8733 			    (uchar_t *)&gw,		/* gateway address */
8734 			    NULL,			/* ire_max_frag */
8735 			    NULL,			/* no src nce */
8736 			    dst_ill->ill_rq,		/* recv-from queue */
8737 			    dst_ill->ill_wq,		/* send-to queue */
8738 			    IRE_CACHE,
8739 			    src_ipif,			/* Interface ipif */
8740 			    save_ire->ire_mask,		/* Parent mask */
8741 			    0,
8742 			    save_ire->ire_ihandle,	/* Interface handle */
8743 			    0,				/* flags if any */
8744 			    &(save_ire->ire_uinfo),
8745 			    NULL,
8746 			    NULL,
8747 			    ipst);
8748 
8749 			if (ire == NULL) {
8750 				ire_refrele(save_ire);
8751 				break;
8752 			}
8753 
8754 			if ((sire != NULL) &&
8755 			    (sire->ire_flags & RTF_MULTIRT)) {
8756 				copy_mp = copymsg(first_mp);
8757 				if (copy_mp != NULL)
8758 					MULTIRT_DEBUG_TAG(copy_mp);
8759 			}
8760 
8761 			ire->ire_marks |= ire_marks;
8762 
8763 			/*
8764 			 * Construct message chain for the resolver
8765 			 * of the form:
8766 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8767 			 * Packet could contain a IPSEC_OUT mp.
8768 			 *
8769 			 * NOTE : ire will be added later when the response
8770 			 * comes back from ARP. If the response does not
8771 			 * come back, ARP frees the packet. For this reason,
8772 			 * we can't REFHOLD the bucket of save_ire to prevent
8773 			 * deletions. We may not be able to REFRELE the bucket
8774 			 * if the response never comes back. Thus, before
8775 			 * adding the ire, ire_add_v4 will make sure that the
8776 			 * interface route does not get deleted. This is the
8777 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8778 			 * where we can always prevent deletions because of
8779 			 * the synchronous nature of adding IRES i.e
8780 			 * ire_add_then_send is called after creating the IRE.
8781 			 */
8782 			ASSERT(ire->ire_mp != NULL);
8783 			ire->ire_mp->b_cont = first_mp;
8784 			/* Have saved_mp handy, for cleanup if canput fails */
8785 			saved_mp = mp;
8786 			mp = copyb(res_mp);
8787 			if (mp == NULL) {
8788 				/* Prepare for cleanup */
8789 				mp = saved_mp; /* pkt */
8790 				ire_delete(ire); /* ire_mp */
8791 				ire = NULL;
8792 				ire_refrele(save_ire);
8793 				if (copy_mp != NULL) {
8794 					MULTIRT_DEBUG_UNTAG(copy_mp);
8795 					freemsg(copy_mp);
8796 					copy_mp = NULL;
8797 				}
8798 				break;
8799 			}
8800 			linkb(mp, ire->ire_mp);
8801 
8802 			/*
8803 			 * Fill in the source and dest addrs for the resolver.
8804 			 * NOTE: this depends on memory layouts imposed by
8805 			 * ill_init().
8806 			 */
8807 			areq = (areq_t *)mp->b_rptr;
8808 			addrp = (ipaddr_t *)((char *)areq +
8809 			    areq->areq_sender_addr_offset);
8810 			if (do_attach_ill) {
8811 				/*
8812 				 * This is bind to no failover case.
8813 				 * arp packet also must go out on attach_ill.
8814 				 */
8815 				ASSERT(ipha->ipha_src != NULL);
8816 				*addrp = ipha->ipha_src;
8817 			} else {
8818 				*addrp = save_ire->ire_src_addr;
8819 			}
8820 
8821 			ire_refrele(save_ire);
8822 			addrp = (ipaddr_t *)((char *)areq +
8823 			    areq->areq_target_addr_offset);
8824 			*addrp = dst;
8825 			/* Up to the resolver. */
8826 			if (canputnext(dst_ill->ill_rq) &&
8827 			    !(dst_ill->ill_arp_closing)) {
8828 				putnext(dst_ill->ill_rq, mp);
8829 				ire = NULL;
8830 				if (copy_mp != NULL) {
8831 					/*
8832 					 * If we found a resolver, we ignore
8833 					 * any trailing top priority IRE_CACHE
8834 					 * in the further loops. This ensures
8835 					 * that we do not omit any resolver.
8836 					 * IRE_CACHE entries, if any, will be
8837 					 * processed next time we enter
8838 					 * ip_newroute().
8839 					 */
8840 					multirt_flags &= ~MULTIRT_CACHEGW;
8841 					/*
8842 					 * Search for the next unresolved
8843 					 * multirt route.
8844 					 */
8845 					first_mp = copy_mp;
8846 					copy_mp = NULL;
8847 					/* Prepare the next resolution loop. */
8848 					mp = first_mp;
8849 					EXTRACT_PKT_MP(mp, first_mp,
8850 					    mctl_present);
8851 					if (mctl_present)
8852 						io = (ipsec_out_t *)
8853 						    first_mp->b_rptr;
8854 					ipha = (ipha_t *)mp->b_rptr;
8855 
8856 					ASSERT(sire != NULL);
8857 
8858 					dst = save_dst;
8859 					multirt_resolve_next = B_TRUE;
8860 					continue;
8861 				}
8862 
8863 				if (sire != NULL)
8864 					ire_refrele(sire);
8865 
8866 				/*
8867 				 * The response will come back in ip_wput
8868 				 * with db_type IRE_DB_TYPE.
8869 				 */
8870 				ipif_refrele(src_ipif);
8871 				ill_refrele(dst_ill);
8872 				return;
8873 			} else {
8874 				/* Prepare for cleanup */
8875 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8876 				    mp);
8877 				mp->b_cont = NULL;
8878 				freeb(mp); /* areq */
8879 				/*
8880 				 * this is an ire that is not added to the
8881 				 * cache. ire_freemblk will handle the release
8882 				 * of any resources associated with the ire.
8883 				 */
8884 				ire_delete(ire); /* ire_mp */
8885 				mp = saved_mp; /* pkt */
8886 				ire = NULL;
8887 				if (copy_mp != NULL) {
8888 					MULTIRT_DEBUG_UNTAG(copy_mp);
8889 					freemsg(copy_mp);
8890 					copy_mp = NULL;
8891 				}
8892 				break;
8893 			}
8894 		default:
8895 			break;
8896 		}
8897 	} while (multirt_resolve_next);
8898 
8899 	ip1dbg(("ip_newroute: dropped\n"));
8900 	/* Did this packet originate externally? */
8901 	if (mp->b_prev) {
8902 		mp->b_next = NULL;
8903 		mp->b_prev = NULL;
8904 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8905 	} else {
8906 		if (dst_ill != NULL) {
8907 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8908 		} else {
8909 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8910 		}
8911 	}
8912 	ASSERT(copy_mp == NULL);
8913 	MULTIRT_DEBUG_UNTAG(first_mp);
8914 	freemsg(first_mp);
8915 	if (ire != NULL)
8916 		ire_refrele(ire);
8917 	if (sire != NULL)
8918 		ire_refrele(sire);
8919 	if (src_ipif != NULL)
8920 		ipif_refrele(src_ipif);
8921 	if (dst_ill != NULL)
8922 		ill_refrele(dst_ill);
8923 	return;
8924 
8925 icmp_err_ret:
8926 	ip1dbg(("ip_newroute: no route\n"));
8927 	if (src_ipif != NULL)
8928 		ipif_refrele(src_ipif);
8929 	if (dst_ill != NULL)
8930 		ill_refrele(dst_ill);
8931 	if (sire != NULL)
8932 		ire_refrele(sire);
8933 	/* Did this packet originate externally? */
8934 	if (mp->b_prev) {
8935 		mp->b_next = NULL;
8936 		mp->b_prev = NULL;
8937 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8938 		q = WR(q);
8939 	} else {
8940 		/*
8941 		 * There is no outgoing ill, so just increment the
8942 		 * system MIB.
8943 		 */
8944 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8945 		/*
8946 		 * Since ip_wput() isn't close to finished, we fill
8947 		 * in enough of the header for credible error reporting.
8948 		 */
8949 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8950 			/* Failed */
8951 			MULTIRT_DEBUG_UNTAG(first_mp);
8952 			freemsg(first_mp);
8953 			if (ire != NULL)
8954 				ire_refrele(ire);
8955 			return;
8956 		}
8957 	}
8958 
8959 	/*
8960 	 * At this point we will have ire only if RTF_BLACKHOLE
8961 	 * or RTF_REJECT flags are set on the IRE. It will not
8962 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8963 	 */
8964 	if (ire != NULL) {
8965 		if (ire->ire_flags & RTF_BLACKHOLE) {
8966 			ire_refrele(ire);
8967 			MULTIRT_DEBUG_UNTAG(first_mp);
8968 			freemsg(first_mp);
8969 			return;
8970 		}
8971 		ire_refrele(ire);
8972 	}
8973 	if (ip_source_routed(ipha, ipst)) {
8974 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8975 		    zoneid, ipst);
8976 		return;
8977 	}
8978 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8979 }
8980 
8981 ip_opt_info_t zero_info;
8982 
8983 /*
8984  * IPv4 -
8985  * ip_newroute_ipif is called by ip_wput_multicast and
8986  * ip_rput_forward_multicast whenever we need to send
8987  * out a packet to a destination address for which we do not have specific
8988  * routing information. It is used when the packet will be sent out
8989  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8990  * socket option is set or icmp error message wants to go out on a particular
8991  * interface for a unicast packet.
8992  *
8993  * In most cases, the destination address is resolved thanks to the ipif
8994  * intrinsic resolver. However, there are some cases where the call to
8995  * ip_newroute_ipif must take into account the potential presence of
8996  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8997  * that uses the interface. This is specified through flags,
8998  * which can be a combination of:
8999  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9000  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9001  *   and flags. Additionally, the packet source address has to be set to
9002  *   the specified address. The caller is thus expected to set this flag
9003  *   if the packet has no specific source address yet.
9004  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9005  *   flag, the resulting ire will inherit the flag. All unresolved routes
9006  *   to the destination must be explored in the same call to
9007  *   ip_newroute_ipif().
9008  */
9009 static void
9010 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9011     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9012 {
9013 	areq_t	*areq;
9014 	ire_t	*ire = NULL;
9015 	mblk_t	*res_mp;
9016 	ipaddr_t *addrp;
9017 	mblk_t *first_mp;
9018 	ire_t	*save_ire = NULL;
9019 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9020 	ipif_t	*src_ipif = NULL;
9021 	ushort_t ire_marks = 0;
9022 	ill_t	*dst_ill = NULL;
9023 	boolean_t mctl_present;
9024 	ipsec_out_t *io;
9025 	ipha_t *ipha;
9026 	int	ihandle = 0;
9027 	mblk_t	*saved_mp;
9028 	ire_t   *fire = NULL;
9029 	mblk_t  *copy_mp = NULL;
9030 	boolean_t multirt_resolve_next;
9031 	boolean_t unspec_src;
9032 	ipaddr_t ipha_dst;
9033 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9034 
9035 	/*
9036 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9037 	 * here for uniformity
9038 	 */
9039 	ipif_refhold(ipif);
9040 
9041 	/*
9042 	 * This loop is run only once in most cases.
9043 	 * We loop to resolve further routes only when the destination
9044 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9045 	 */
9046 	do {
9047 		if (dst_ill != NULL) {
9048 			ill_refrele(dst_ill);
9049 			dst_ill = NULL;
9050 		}
9051 		if (src_ipif != NULL) {
9052 			ipif_refrele(src_ipif);
9053 			src_ipif = NULL;
9054 		}
9055 		multirt_resolve_next = B_FALSE;
9056 
9057 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9058 		    ipif->ipif_ill->ill_name));
9059 
9060 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9061 		if (mctl_present)
9062 			io = (ipsec_out_t *)first_mp->b_rptr;
9063 
9064 		ipha = (ipha_t *)mp->b_rptr;
9065 
9066 		/*
9067 		 * Save the packet destination address, we may need it after
9068 		 * the packet has been consumed.
9069 		 */
9070 		ipha_dst = ipha->ipha_dst;
9071 
9072 		/*
9073 		 * If the interface is a pt-pt interface we look for an
9074 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9075 		 * local_address and the pt-pt destination address. Otherwise
9076 		 * we just match the local address.
9077 		 * NOTE: dst could be different than ipha->ipha_dst in case
9078 		 * of sending igmp multicast packets over a point-to-point
9079 		 * connection.
9080 		 * Thus we must be careful enough to check ipha_dst to be a
9081 		 * multicast address, otherwise it will take xmit_if path for
9082 		 * multicast packets resulting into kernel stack overflow by
9083 		 * repeated calls to ip_newroute_ipif from ire_send().
9084 		 */
9085 		if (CLASSD(ipha_dst) &&
9086 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9087 			goto err_ret;
9088 		}
9089 
9090 		/*
9091 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9092 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9093 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9094 		 * propagate its flags to the new ire.
9095 		 */
9096 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9097 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9098 			ip2dbg(("ip_newroute_ipif: "
9099 			    "ipif_lookup_multi_ire("
9100 			    "ipif %p, dst %08x) = fire %p\n",
9101 			    (void *)ipif, ntohl(dst), (void *)fire));
9102 		}
9103 
9104 		if (mctl_present && io->ipsec_out_attach_if) {
9105 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9106 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9107 
9108 			/* Failure case frees things for us. */
9109 			if (attach_ill == NULL) {
9110 				ipif_refrele(ipif);
9111 				if (fire != NULL)
9112 					ire_refrele(fire);
9113 				return;
9114 			}
9115 
9116 			/*
9117 			 * Check if we need an ire that will not be
9118 			 * looked up by anybody else i.e. HIDDEN.
9119 			 */
9120 			if (ill_is_probeonly(attach_ill)) {
9121 				ire_marks = IRE_MARK_HIDDEN;
9122 			}
9123 			/*
9124 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9125 			 * case.
9126 			 */
9127 			dst_ill = ipif->ipif_ill;
9128 			/* attach_ill has been refheld by ip_grab_attach_ill */
9129 			ASSERT(dst_ill == attach_ill);
9130 		} else {
9131 			/*
9132 			 * If the interface belongs to an interface group,
9133 			 * make sure the next possible interface in the group
9134 			 * is used.  This encourages load spreading among
9135 			 * peers in an interface group.
9136 			 * Note: load spreading is disabled for RTF_MULTIRT
9137 			 * routes.
9138 			 */
9139 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9140 			    (fire->ire_flags & RTF_MULTIRT)) {
9141 				/*
9142 				 * Don't perform outbound load spreading
9143 				 * in the case of an RTF_MULTIRT issued route,
9144 				 * we actually typically want to replicate
9145 				 * outgoing packets through particular
9146 				 * interfaces.
9147 				 */
9148 				dst_ill = ipif->ipif_ill;
9149 				ill_refhold(dst_ill);
9150 			} else {
9151 				dst_ill = ip_newroute_get_dst_ill(
9152 				    ipif->ipif_ill);
9153 			}
9154 			if (dst_ill == NULL) {
9155 				if (ip_debug > 2) {
9156 					pr_addr_dbg("ip_newroute_ipif: "
9157 					    "no dst ill for dst %s\n",
9158 					    AF_INET, &dst);
9159 				}
9160 				goto err_ret;
9161 			}
9162 		}
9163 
9164 		/*
9165 		 * Pick a source address preferring non-deprecated ones.
9166 		 * Unlike ip_newroute, we don't do any source address
9167 		 * selection here since for multicast it really does not help
9168 		 * in inbound load spreading as in the unicast case.
9169 		 */
9170 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9171 		    (fire->ire_flags & RTF_SETSRC)) {
9172 			/*
9173 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9174 			 * on that interface. This ire has RTF_SETSRC flag, so
9175 			 * the source address of the packet must be changed.
9176 			 * Check that the ipif matching the requested source
9177 			 * address still exists.
9178 			 */
9179 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9180 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9181 		}
9182 
9183 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9184 
9185 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9186 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9187 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9188 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9189 		    (src_ipif == NULL) &&
9190 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9191 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9192 			if (src_ipif == NULL) {
9193 				if (ip_debug > 2) {
9194 					/* ip1dbg */
9195 					pr_addr_dbg("ip_newroute_ipif: "
9196 					    "no src for dst %s",
9197 					    AF_INET, &dst);
9198 				}
9199 				ip1dbg((" through interface %s\n",
9200 				    dst_ill->ill_name));
9201 				goto err_ret;
9202 			}
9203 			ipif_refrele(ipif);
9204 			ipif = src_ipif;
9205 			ipif_refhold(ipif);
9206 		}
9207 		if (src_ipif == NULL) {
9208 			src_ipif = ipif;
9209 			ipif_refhold(src_ipif);
9210 		}
9211 
9212 		/*
9213 		 * Assign a source address while we have the conn.
9214 		 * We can't have ip_wput_ire pick a source address when the
9215 		 * packet returns from arp since conn_unspec_src might be set
9216 		 * and we lose the conn when going through arp.
9217 		 */
9218 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9219 			ipha->ipha_src = src_ipif->ipif_src_addr;
9220 
9221 		/*
9222 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9223 		 * that the outgoing interface does not have an interface ire.
9224 		 */
9225 		if (CLASSD(ipha_dst) && (connp == NULL ||
9226 		    connp->conn_outgoing_ill == NULL) &&
9227 		    infop->ip_opt_ill_index == 0) {
9228 			/* ipif_to_ire returns an held ire */
9229 			ire = ipif_to_ire(ipif);
9230 			if (ire == NULL)
9231 				goto err_ret;
9232 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9233 				goto err_ret;
9234 			/*
9235 			 * ihandle is needed when the ire is added to
9236 			 * cache table.
9237 			 */
9238 			save_ire = ire;
9239 			ihandle = save_ire->ire_ihandle;
9240 
9241 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9242 			    "flags %04x\n",
9243 			    (void *)ire, (void *)ipif, flags));
9244 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9245 			    (fire->ire_flags & RTF_MULTIRT)) {
9246 				/*
9247 				 * As requested by flags, an IRE_OFFSUBNET was
9248 				 * looked up on that interface. This ire has
9249 				 * RTF_MULTIRT flag, so the resolution loop will
9250 				 * be re-entered to resolve additional routes on
9251 				 * other interfaces. For that purpose, a copy of
9252 				 * the packet is performed at this point.
9253 				 */
9254 				fire->ire_last_used_time = lbolt;
9255 				copy_mp = copymsg(first_mp);
9256 				if (copy_mp) {
9257 					MULTIRT_DEBUG_TAG(copy_mp);
9258 				}
9259 			}
9260 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9261 			    (fire->ire_flags & RTF_SETSRC)) {
9262 				/*
9263 				 * As requested by flags, an IRE_OFFSUBET was
9264 				 * looked up on that interface. This ire has
9265 				 * RTF_SETSRC flag, so the source address of the
9266 				 * packet must be changed.
9267 				 */
9268 				ipha->ipha_src = fire->ire_src_addr;
9269 			}
9270 		} else {
9271 			ASSERT((connp == NULL) ||
9272 			    (connp->conn_outgoing_ill != NULL) ||
9273 			    (connp->conn_dontroute) ||
9274 			    infop->ip_opt_ill_index != 0);
9275 			/*
9276 			 * The only ways we can come here are:
9277 			 * 1) IP_BOUND_IF socket option is set
9278 			 * 2) SO_DONTROUTE socket option is set
9279 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9280 			 * In all cases, the new ire will not be added
9281 			 * into cache table.
9282 			 */
9283 			ire_marks |= IRE_MARK_NOADD;
9284 		}
9285 
9286 		switch (ipif->ipif_net_type) {
9287 		case IRE_IF_NORESOLVER: {
9288 			/* We have what we need to build an IRE_CACHE. */
9289 
9290 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9291 			    (dst_ill->ill_resolver_mp == NULL)) {
9292 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9293 				    "for IRE_IF_NORESOLVER ire %p has "
9294 				    "no ill_resolver_mp\n",
9295 				    (void *)dst_ill, (void *)ire));
9296 				break;
9297 			}
9298 
9299 			/*
9300 			 * The new ire inherits the IRE_OFFSUBNET flags
9301 			 * and source address, if this was requested.
9302 			 */
9303 			ire = ire_create(
9304 			    (uchar_t *)&dst,		/* dest address */
9305 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9306 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9307 			    NULL,			/* gateway address */
9308 			    &ipif->ipif_mtu,
9309 			    NULL,			/* no src nce */
9310 			    dst_ill->ill_rq,		/* recv-from queue */
9311 			    dst_ill->ill_wq,		/* send-to queue */
9312 			    IRE_CACHE,
9313 			    src_ipif,
9314 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9315 			    (fire != NULL) ?		/* Parent handle */
9316 			    fire->ire_phandle : 0,
9317 			    ihandle,			/* Interface handle */
9318 			    (fire != NULL) ?
9319 			    (fire->ire_flags &
9320 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9321 			    (save_ire == NULL ? &ire_uinfo_null :
9322 			    &save_ire->ire_uinfo),
9323 			    NULL,
9324 			    NULL,
9325 			    ipst);
9326 
9327 			if (ire == NULL) {
9328 				if (save_ire != NULL)
9329 					ire_refrele(save_ire);
9330 				break;
9331 			}
9332 
9333 			ire->ire_marks |= ire_marks;
9334 
9335 			/*
9336 			 * If IRE_MARK_NOADD is set then we need to convert
9337 			 * the max_fragp to a useable value now. This is
9338 			 * normally done in ire_add_v[46]. We also need to
9339 			 * associate the ire with an nce (normally would be
9340 			 * done in ip_wput_nondata()).
9341 			 *
9342 			 * Note that IRE_MARK_NOADD packets created here
9343 			 * do not have a non-null ire_mp pointer. The null
9344 			 * value of ire_bucket indicates that they were
9345 			 * never added.
9346 			 */
9347 			if (ire->ire_marks & IRE_MARK_NOADD) {
9348 				uint_t  max_frag;
9349 
9350 				max_frag = *ire->ire_max_fragp;
9351 				ire->ire_max_fragp = NULL;
9352 				ire->ire_max_frag = max_frag;
9353 
9354 				if ((ire->ire_nce = ndp_lookup_v4(
9355 				    ire_to_ill(ire),
9356 				    (ire->ire_gateway_addr != INADDR_ANY ?
9357 				    &ire->ire_gateway_addr : &ire->ire_addr),
9358 				    B_FALSE)) == NULL) {
9359 					if (save_ire != NULL)
9360 						ire_refrele(save_ire);
9361 					break;
9362 				}
9363 				ASSERT(ire->ire_nce->nce_state ==
9364 				    ND_REACHABLE);
9365 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9366 			}
9367 
9368 			/* Prevent save_ire from getting deleted */
9369 			if (save_ire != NULL) {
9370 				IRB_REFHOLD(save_ire->ire_bucket);
9371 				/* Has it been removed already ? */
9372 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9373 					IRB_REFRELE(save_ire->ire_bucket);
9374 					ire_refrele(save_ire);
9375 					break;
9376 				}
9377 			}
9378 
9379 			ire_add_then_send(q, ire, first_mp);
9380 
9381 			/* Assert that save_ire is not deleted yet. */
9382 			if (save_ire != NULL) {
9383 				ASSERT(save_ire->ire_ptpn != NULL);
9384 				IRB_REFRELE(save_ire->ire_bucket);
9385 				ire_refrele(save_ire);
9386 				save_ire = NULL;
9387 			}
9388 			if (fire != NULL) {
9389 				ire_refrele(fire);
9390 				fire = NULL;
9391 			}
9392 
9393 			/*
9394 			 * the resolution loop is re-entered if this
9395 			 * was requested through flags and if we
9396 			 * actually are in a multirouting case.
9397 			 */
9398 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9399 				boolean_t need_resolve =
9400 				    ire_multirt_need_resolve(ipha_dst,
9401 				    MBLK_GETLABEL(copy_mp), ipst);
9402 				if (!need_resolve) {
9403 					MULTIRT_DEBUG_UNTAG(copy_mp);
9404 					freemsg(copy_mp);
9405 					copy_mp = NULL;
9406 				} else {
9407 					/*
9408 					 * ipif_lookup_group() calls
9409 					 * ire_lookup_multi() that uses
9410 					 * ire_ftable_lookup() to find
9411 					 * an IRE_INTERFACE for the group.
9412 					 * In the multirt case,
9413 					 * ire_lookup_multi() then invokes
9414 					 * ire_multirt_lookup() to find
9415 					 * the next resolvable ire.
9416 					 * As a result, we obtain an new
9417 					 * interface, derived from the
9418 					 * next ire.
9419 					 */
9420 					ipif_refrele(ipif);
9421 					ipif = ipif_lookup_group(ipha_dst,
9422 					    zoneid, ipst);
9423 					ip2dbg(("ip_newroute_ipif: "
9424 					    "multirt dst %08x, ipif %p\n",
9425 					    htonl(dst), (void *)ipif));
9426 					if (ipif != NULL) {
9427 						mp = copy_mp;
9428 						copy_mp = NULL;
9429 						multirt_resolve_next = B_TRUE;
9430 						continue;
9431 					} else {
9432 						freemsg(copy_mp);
9433 					}
9434 				}
9435 			}
9436 			if (ipif != NULL)
9437 				ipif_refrele(ipif);
9438 			ill_refrele(dst_ill);
9439 			ipif_refrele(src_ipif);
9440 			return;
9441 		}
9442 		case IRE_IF_RESOLVER:
9443 			/*
9444 			 * We can't build an IRE_CACHE yet, but at least
9445 			 * we found a resolver that can help.
9446 			 */
9447 			res_mp = dst_ill->ill_resolver_mp;
9448 			if (!OK_RESOLVER_MP(res_mp))
9449 				break;
9450 
9451 			/*
9452 			 * We obtain a partial IRE_CACHE which we will pass
9453 			 * along with the resolver query.  When the response
9454 			 * comes back it will be there ready for us to add.
9455 			 * The new ire inherits the IRE_OFFSUBNET flags
9456 			 * and source address, if this was requested.
9457 			 * The ire_max_frag is atomically set under the
9458 			 * irebucket lock in ire_add_v[46]. Only in the
9459 			 * case of IRE_MARK_NOADD, we set it here itself.
9460 			 */
9461 			ire = ire_create_mp(
9462 			    (uchar_t *)&dst,		/* dest address */
9463 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9464 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9465 			    NULL,			/* gateway address */
9466 			    (ire_marks & IRE_MARK_NOADD) ?
9467 			    ipif->ipif_mtu : 0,		/* max_frag */
9468 			    NULL,			/* no src nce */
9469 			    dst_ill->ill_rq,		/* recv-from queue */
9470 			    dst_ill->ill_wq,		/* send-to queue */
9471 			    IRE_CACHE,
9472 			    src_ipif,
9473 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9474 			    (fire != NULL) ?		/* Parent handle */
9475 			    fire->ire_phandle : 0,
9476 			    ihandle,			/* Interface handle */
9477 			    (fire != NULL) ?		/* flags if any */
9478 			    (fire->ire_flags &
9479 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9480 			    (save_ire == NULL ? &ire_uinfo_null :
9481 			    &save_ire->ire_uinfo),
9482 			    NULL,
9483 			    NULL,
9484 			    ipst);
9485 
9486 			if (save_ire != NULL) {
9487 				ire_refrele(save_ire);
9488 				save_ire = NULL;
9489 			}
9490 			if (ire == NULL)
9491 				break;
9492 
9493 			ire->ire_marks |= ire_marks;
9494 			/*
9495 			 * Construct message chain for the resolver of the
9496 			 * form:
9497 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9498 			 *
9499 			 * NOTE : ire will be added later when the response
9500 			 * comes back from ARP. If the response does not
9501 			 * come back, ARP frees the packet. For this reason,
9502 			 * we can't REFHOLD the bucket of save_ire to prevent
9503 			 * deletions. We may not be able to REFRELE the
9504 			 * bucket if the response never comes back.
9505 			 * Thus, before adding the ire, ire_add_v4 will make
9506 			 * sure that the interface route does not get deleted.
9507 			 * This is the only case unlike ip_newroute_v6,
9508 			 * ip_newroute_ipif_v6 where we can always prevent
9509 			 * deletions because ire_add_then_send is called after
9510 			 * creating the IRE.
9511 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9512 			 * does not add this IRE into the IRE CACHE.
9513 			 */
9514 			ASSERT(ire->ire_mp != NULL);
9515 			ire->ire_mp->b_cont = first_mp;
9516 			/* Have saved_mp handy, for cleanup if canput fails */
9517 			saved_mp = mp;
9518 			mp = copyb(res_mp);
9519 			if (mp == NULL) {
9520 				/* Prepare for cleanup */
9521 				mp = saved_mp; /* pkt */
9522 				ire_delete(ire); /* ire_mp */
9523 				ire = NULL;
9524 				if (copy_mp != NULL) {
9525 					MULTIRT_DEBUG_UNTAG(copy_mp);
9526 					freemsg(copy_mp);
9527 					copy_mp = NULL;
9528 				}
9529 				break;
9530 			}
9531 			linkb(mp, ire->ire_mp);
9532 
9533 			/*
9534 			 * Fill in the source and dest addrs for the resolver.
9535 			 * NOTE: this depends on memory layouts imposed by
9536 			 * ill_init().
9537 			 */
9538 			areq = (areq_t *)mp->b_rptr;
9539 			addrp = (ipaddr_t *)((char *)areq +
9540 			    areq->areq_sender_addr_offset);
9541 			*addrp = ire->ire_src_addr;
9542 			addrp = (ipaddr_t *)((char *)areq +
9543 			    areq->areq_target_addr_offset);
9544 			*addrp = dst;
9545 			/* Up to the resolver. */
9546 			if (canputnext(dst_ill->ill_rq) &&
9547 			    !(dst_ill->ill_arp_closing)) {
9548 				putnext(dst_ill->ill_rq, mp);
9549 				/*
9550 				 * The response will come back in ip_wput
9551 				 * with db_type IRE_DB_TYPE.
9552 				 */
9553 			} else {
9554 				mp->b_cont = NULL;
9555 				freeb(mp); /* areq */
9556 				ire_delete(ire); /* ire_mp */
9557 				saved_mp->b_next = NULL;
9558 				saved_mp->b_prev = NULL;
9559 				freemsg(first_mp); /* pkt */
9560 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9561 			}
9562 
9563 			if (fire != NULL) {
9564 				ire_refrele(fire);
9565 				fire = NULL;
9566 			}
9567 
9568 
9569 			/*
9570 			 * The resolution loop is re-entered if this was
9571 			 * requested through flags and we actually are
9572 			 * in a multirouting case.
9573 			 */
9574 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9575 				boolean_t need_resolve =
9576 				    ire_multirt_need_resolve(ipha_dst,
9577 				    MBLK_GETLABEL(copy_mp), ipst);
9578 				if (!need_resolve) {
9579 					MULTIRT_DEBUG_UNTAG(copy_mp);
9580 					freemsg(copy_mp);
9581 					copy_mp = NULL;
9582 				} else {
9583 					/*
9584 					 * ipif_lookup_group() calls
9585 					 * ire_lookup_multi() that uses
9586 					 * ire_ftable_lookup() to find
9587 					 * an IRE_INTERFACE for the group.
9588 					 * In the multirt case,
9589 					 * ire_lookup_multi() then invokes
9590 					 * ire_multirt_lookup() to find
9591 					 * the next resolvable ire.
9592 					 * As a result, we obtain an new
9593 					 * interface, derived from the
9594 					 * next ire.
9595 					 */
9596 					ipif_refrele(ipif);
9597 					ipif = ipif_lookup_group(ipha_dst,
9598 					    zoneid, ipst);
9599 					if (ipif != NULL) {
9600 						mp = copy_mp;
9601 						copy_mp = NULL;
9602 						multirt_resolve_next = B_TRUE;
9603 						continue;
9604 					} else {
9605 						freemsg(copy_mp);
9606 					}
9607 				}
9608 			}
9609 			if (ipif != NULL)
9610 				ipif_refrele(ipif);
9611 			ill_refrele(dst_ill);
9612 			ipif_refrele(src_ipif);
9613 			return;
9614 		default:
9615 			break;
9616 		}
9617 	} while (multirt_resolve_next);
9618 
9619 err_ret:
9620 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9621 	if (fire != NULL)
9622 		ire_refrele(fire);
9623 	ipif_refrele(ipif);
9624 	/* Did this packet originate externally? */
9625 	if (dst_ill != NULL)
9626 		ill_refrele(dst_ill);
9627 	if (src_ipif != NULL)
9628 		ipif_refrele(src_ipif);
9629 	if (mp->b_prev || mp->b_next) {
9630 		mp->b_next = NULL;
9631 		mp->b_prev = NULL;
9632 	} else {
9633 		/*
9634 		 * Since ip_wput() isn't close to finished, we fill
9635 		 * in enough of the header for credible error reporting.
9636 		 */
9637 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9638 			/* Failed */
9639 			freemsg(first_mp);
9640 			if (ire != NULL)
9641 				ire_refrele(ire);
9642 			return;
9643 		}
9644 	}
9645 	/*
9646 	 * At this point we will have ire only if RTF_BLACKHOLE
9647 	 * or RTF_REJECT flags are set on the IRE. It will not
9648 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9649 	 */
9650 	if (ire != NULL) {
9651 		if (ire->ire_flags & RTF_BLACKHOLE) {
9652 			ire_refrele(ire);
9653 			freemsg(first_mp);
9654 			return;
9655 		}
9656 		ire_refrele(ire);
9657 	}
9658 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9659 }
9660 
9661 /* Name/Value Table Lookup Routine */
9662 char *
9663 ip_nv_lookup(nv_t *nv, int value)
9664 {
9665 	if (!nv)
9666 		return (NULL);
9667 	for (; nv->nv_name; nv++) {
9668 		if (nv->nv_value == value)
9669 			return (nv->nv_name);
9670 	}
9671 	return ("unknown");
9672 }
9673 
9674 /*
9675  * This is a module open, i.e. this is a control stream for access
9676  * to a DLPI device.  We allocate an ill_t as the instance data in
9677  * this case.
9678  */
9679 int
9680 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9681 {
9682 	ill_t	*ill;
9683 	int	err;
9684 	zoneid_t zoneid;
9685 	netstack_t *ns;
9686 	ip_stack_t *ipst;
9687 
9688 	/*
9689 	 * Prevent unprivileged processes from pushing IP so that
9690 	 * they can't send raw IP.
9691 	 */
9692 	if (secpolicy_net_rawaccess(credp) != 0)
9693 		return (EPERM);
9694 
9695 	ns = netstack_find_by_cred(credp);
9696 	ASSERT(ns != NULL);
9697 	ipst = ns->netstack_ip;
9698 	ASSERT(ipst != NULL);
9699 
9700 	/*
9701 	 * For exclusive stacks we set the zoneid to zero
9702 	 * to make IP operate as if in the global zone.
9703 	 */
9704 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9705 		zoneid = GLOBAL_ZONEID;
9706 	else
9707 		zoneid = crgetzoneid(credp);
9708 
9709 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9710 	q->q_ptr = WR(q)->q_ptr = ill;
9711 	ill->ill_ipst = ipst;
9712 	ill->ill_zoneid = zoneid;
9713 
9714 	/*
9715 	 * ill_init initializes the ill fields and then sends down
9716 	 * down a DL_INFO_REQ after calling qprocson.
9717 	 */
9718 	err = ill_init(q, ill);
9719 	if (err != 0) {
9720 		mi_free(ill);
9721 		netstack_rele(ipst->ips_netstack);
9722 		q->q_ptr = NULL;
9723 		WR(q)->q_ptr = NULL;
9724 		return (err);
9725 	}
9726 
9727 	/* ill_init initializes the ipsq marking this thread as writer */
9728 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9729 	/* Wait for the DL_INFO_ACK */
9730 	mutex_enter(&ill->ill_lock);
9731 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9732 		/*
9733 		 * Return value of 0 indicates a pending signal.
9734 		 */
9735 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9736 		if (err == 0) {
9737 			mutex_exit(&ill->ill_lock);
9738 			(void) ip_close(q, 0);
9739 			return (EINTR);
9740 		}
9741 	}
9742 	mutex_exit(&ill->ill_lock);
9743 
9744 	/*
9745 	 * ip_rput_other could have set an error  in ill_error on
9746 	 * receipt of M_ERROR.
9747 	 */
9748 
9749 	err = ill->ill_error;
9750 	if (err != 0) {
9751 		(void) ip_close(q, 0);
9752 		return (err);
9753 	}
9754 
9755 	ill->ill_credp = credp;
9756 	crhold(credp);
9757 
9758 	mutex_enter(&ipst->ips_ip_mi_lock);
9759 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9760 	    credp);
9761 	mutex_exit(&ipst->ips_ip_mi_lock);
9762 	if (err) {
9763 		(void) ip_close(q, 0);
9764 		return (err);
9765 	}
9766 	return (0);
9767 }
9768 
9769 /* For /dev/ip aka AF_INET open */
9770 int
9771 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9772 {
9773 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9774 }
9775 
9776 /* For /dev/ip6 aka AF_INET6 open */
9777 int
9778 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9779 {
9780 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9781 }
9782 
9783 /* IP open routine. */
9784 int
9785 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9786     boolean_t isv6)
9787 {
9788 	conn_t 		*connp;
9789 	major_t		maj;
9790 	zoneid_t	zoneid;
9791 	netstack_t	*ns;
9792 	ip_stack_t	*ipst;
9793 
9794 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9795 
9796 	/* Allow reopen. */
9797 	if (q->q_ptr != NULL)
9798 		return (0);
9799 
9800 	if (sflag & MODOPEN) {
9801 		/* This is a module open */
9802 		return (ip_modopen(q, devp, flag, sflag, credp));
9803 	}
9804 
9805 	ns = netstack_find_by_cred(credp);
9806 	ASSERT(ns != NULL);
9807 	ipst = ns->netstack_ip;
9808 	ASSERT(ipst != NULL);
9809 
9810 	/*
9811 	 * For exclusive stacks we set the zoneid to zero
9812 	 * to make IP operate as if in the global zone.
9813 	 */
9814 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9815 		zoneid = GLOBAL_ZONEID;
9816 	else
9817 		zoneid = crgetzoneid(credp);
9818 
9819 	/*
9820 	 * We are opening as a device. This is an IP client stream, and we
9821 	 * allocate an conn_t as the instance data.
9822 	 */
9823 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9824 
9825 	/*
9826 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9827 	 * done by netstack_find_by_cred()
9828 	 */
9829 	netstack_rele(ipst->ips_netstack);
9830 
9831 	connp->conn_zoneid = zoneid;
9832 
9833 	connp->conn_upq = q;
9834 	q->q_ptr = WR(q)->q_ptr = connp;
9835 
9836 	if (flag & SO_SOCKSTR)
9837 		connp->conn_flags |= IPCL_SOCKET;
9838 
9839 	/* Minor tells us which /dev entry was opened */
9840 	if (isv6) {
9841 		connp->conn_flags |= IPCL_ISV6;
9842 		connp->conn_af_isv6 = B_TRUE;
9843 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9844 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9845 	} else {
9846 		connp->conn_af_isv6 = B_FALSE;
9847 		connp->conn_pkt_isv6 = B_FALSE;
9848 	}
9849 
9850 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9851 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9852 		connp->conn_minor_arena = ip_minor_arena_la;
9853 	} else {
9854 		/*
9855 		 * Either minor numbers in the large arena were exhausted
9856 		 * or a non socket application is doing the open.
9857 		 * Try to allocate from the small arena.
9858 		 */
9859 		if ((connp->conn_dev =
9860 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9861 			/* CONN_DEC_REF takes care of netstack_rele() */
9862 			q->q_ptr = WR(q)->q_ptr = NULL;
9863 			CONN_DEC_REF(connp);
9864 			return (EBUSY);
9865 		}
9866 		connp->conn_minor_arena = ip_minor_arena_sa;
9867 	}
9868 
9869 	maj = getemajor(*devp);
9870 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9871 
9872 	/*
9873 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9874 	 */
9875 	connp->conn_cred = credp;
9876 
9877 	/*
9878 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9879 	 */
9880 	connp->conn_recv = ip_conn_input;
9881 
9882 	crhold(connp->conn_cred);
9883 
9884 	/*
9885 	 * If the caller has the process-wide flag set, then default to MAC
9886 	 * exempt mode.  This allows read-down to unlabeled hosts.
9887 	 */
9888 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9889 		connp->conn_mac_exempt = B_TRUE;
9890 
9891 	connp->conn_rq = q;
9892 	connp->conn_wq = WR(q);
9893 
9894 	/* Non-zero default values */
9895 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9896 
9897 	/*
9898 	 * Make the conn globally visible to walkers
9899 	 */
9900 	ASSERT(connp->conn_ref == 1);
9901 	mutex_enter(&connp->conn_lock);
9902 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9903 	mutex_exit(&connp->conn_lock);
9904 
9905 	qprocson(q);
9906 
9907 	return (0);
9908 }
9909 
9910 /*
9911  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9912  * Note that there is no race since either ip_output function works - it
9913  * is just an optimization to enter the best ip_output routine directly.
9914  */
9915 void
9916 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9917     ip_stack_t *ipst)
9918 {
9919 	if (isv6)  {
9920 		if (bump_mib) {
9921 			BUMP_MIB(&ipst->ips_ip6_mib,
9922 			    ipIfStatsOutSwitchIPVersion);
9923 		}
9924 		connp->conn_send = ip_output_v6;
9925 		connp->conn_pkt_isv6 = B_TRUE;
9926 	} else {
9927 		if (bump_mib) {
9928 			BUMP_MIB(&ipst->ips_ip_mib,
9929 			    ipIfStatsOutSwitchIPVersion);
9930 		}
9931 		connp->conn_send = ip_output;
9932 		connp->conn_pkt_isv6 = B_FALSE;
9933 	}
9934 
9935 }
9936 
9937 /*
9938  * See if IPsec needs loading because of the options in mp.
9939  */
9940 static boolean_t
9941 ipsec_opt_present(mblk_t *mp)
9942 {
9943 	uint8_t *optcp, *next_optcp, *opt_endcp;
9944 	struct opthdr *opt;
9945 	struct T_opthdr *topt;
9946 	int opthdr_len;
9947 	t_uscalar_t optname, optlevel;
9948 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9949 	ipsec_req_t *ipsr;
9950 
9951 	/*
9952 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9953 	 * return TRUE.
9954 	 */
9955 
9956 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9957 	opt_endcp = optcp + tor->OPT_length;
9958 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9959 		opthdr_len = sizeof (struct T_opthdr);
9960 	} else {		/* O_OPTMGMT_REQ */
9961 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9962 		opthdr_len = sizeof (struct opthdr);
9963 	}
9964 	for (; optcp < opt_endcp; optcp = next_optcp) {
9965 		if (optcp + opthdr_len > opt_endcp)
9966 			return (B_FALSE);	/* Not enough option header. */
9967 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9968 			topt = (struct T_opthdr *)optcp;
9969 			optlevel = topt->level;
9970 			optname = topt->name;
9971 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9972 		} else {
9973 			opt = (struct opthdr *)optcp;
9974 			optlevel = opt->level;
9975 			optname = opt->name;
9976 			next_optcp = optcp + opthdr_len +
9977 			    _TPI_ALIGN_OPT(opt->len);
9978 		}
9979 		if ((next_optcp < optcp) || /* wraparound pointer space */
9980 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9981 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9982 			return (B_FALSE); /* bad option buffer */
9983 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9984 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9985 			/*
9986 			 * Check to see if it's an all-bypass or all-zeroes
9987 			 * IPsec request.  Don't bother loading IPsec if
9988 			 * the socket doesn't want to use it.  (A good example
9989 			 * is a bypass request.)
9990 			 *
9991 			 * Basically, if any of the non-NEVER bits are set,
9992 			 * load IPsec.
9993 			 */
9994 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9995 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9996 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9997 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9998 			    != 0)
9999 				return (B_TRUE);
10000 		}
10001 	}
10002 	return (B_FALSE);
10003 }
10004 
10005 /*
10006  * If conn is is waiting for ipsec to finish loading, kick it.
10007  */
10008 /* ARGSUSED */
10009 static void
10010 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10011 {
10012 	t_scalar_t	optreq_prim;
10013 	mblk_t		*mp;
10014 	cred_t		*cr;
10015 	int		err = 0;
10016 
10017 	/*
10018 	 * This function is called, after ipsec loading is complete.
10019 	 * Since IP checks exclusively and atomically (i.e it prevents
10020 	 * ipsec load from completing until ip_optcom_req completes)
10021 	 * whether ipsec load is complete, there cannot be a race with IP
10022 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10023 	 */
10024 	mutex_enter(&connp->conn_lock);
10025 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10026 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10027 		mp = connp->conn_ipsec_opt_mp;
10028 		connp->conn_ipsec_opt_mp = NULL;
10029 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10030 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10031 		mutex_exit(&connp->conn_lock);
10032 
10033 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10034 
10035 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10036 		if (optreq_prim == T_OPTMGMT_REQ) {
10037 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10038 			    &ip_opt_obj, B_FALSE);
10039 		} else {
10040 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10041 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10042 			    &ip_opt_obj, B_FALSE);
10043 		}
10044 		if (err != EINPROGRESS)
10045 			CONN_OPER_PENDING_DONE(connp);
10046 		return;
10047 	}
10048 	mutex_exit(&connp->conn_lock);
10049 }
10050 
10051 /*
10052  * Called from the ipsec_loader thread, outside any perimeter, to tell
10053  * ip qenable any of the queues waiting for the ipsec loader to
10054  * complete.
10055  */
10056 void
10057 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10058 {
10059 	netstack_t *ns = ipss->ipsec_netstack;
10060 
10061 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10062 }
10063 
10064 /*
10065  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10066  * determines the grp on which it has to become exclusive, queues the mp
10067  * and sq draining restarts the optmgmt
10068  */
10069 static boolean_t
10070 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10071 {
10072 	conn_t *connp = Q_TO_CONN(q);
10073 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10074 
10075 	/*
10076 	 * Take IPsec requests and treat them special.
10077 	 */
10078 	if (ipsec_opt_present(mp)) {
10079 		/* First check if IPsec is loaded. */
10080 		mutex_enter(&ipss->ipsec_loader_lock);
10081 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10082 			mutex_exit(&ipss->ipsec_loader_lock);
10083 			return (B_FALSE);
10084 		}
10085 		mutex_enter(&connp->conn_lock);
10086 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10087 
10088 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10089 		connp->conn_ipsec_opt_mp = mp;
10090 		mutex_exit(&connp->conn_lock);
10091 		mutex_exit(&ipss->ipsec_loader_lock);
10092 
10093 		ipsec_loader_loadnow(ipss);
10094 		return (B_TRUE);
10095 	}
10096 	return (B_FALSE);
10097 }
10098 
10099 /*
10100  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10101  * all of them are copied to the conn_t. If the req is "zero", the policy is
10102  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10103  * fields.
10104  * We keep only the latest setting of the policy and thus policy setting
10105  * is not incremental/cumulative.
10106  *
10107  * Requests to set policies with multiple alternative actions will
10108  * go through a different API.
10109  */
10110 int
10111 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10112 {
10113 	uint_t ah_req = 0;
10114 	uint_t esp_req = 0;
10115 	uint_t se_req = 0;
10116 	ipsec_selkey_t sel;
10117 	ipsec_act_t *actp = NULL;
10118 	uint_t nact;
10119 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10120 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10121 	ipsec_policy_root_t *pr;
10122 	ipsec_policy_head_t *ph;
10123 	int fam;
10124 	boolean_t is_pol_reset;
10125 	int error = 0;
10126 	netstack_t	*ns = connp->conn_netstack;
10127 	ip_stack_t	*ipst = ns->netstack_ip;
10128 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10129 
10130 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10131 
10132 	/*
10133 	 * The IP_SEC_OPT option does not allow variable length parameters,
10134 	 * hence a request cannot be NULL.
10135 	 */
10136 	if (req == NULL)
10137 		return (EINVAL);
10138 
10139 	ah_req = req->ipsr_ah_req;
10140 	esp_req = req->ipsr_esp_req;
10141 	se_req = req->ipsr_self_encap_req;
10142 
10143 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10144 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10145 		return (EINVAL);
10146 
10147 	/*
10148 	 * Are we dealing with a request to reset the policy (i.e.
10149 	 * zero requests).
10150 	 */
10151 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10152 	    (esp_req & REQ_MASK) == 0 &&
10153 	    (se_req & REQ_MASK) == 0);
10154 
10155 	if (!is_pol_reset) {
10156 		/*
10157 		 * If we couldn't load IPsec, fail with "protocol
10158 		 * not supported".
10159 		 * IPsec may not have been loaded for a request with zero
10160 		 * policies, so we don't fail in this case.
10161 		 */
10162 		mutex_enter(&ipss->ipsec_loader_lock);
10163 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10164 			mutex_exit(&ipss->ipsec_loader_lock);
10165 			return (EPROTONOSUPPORT);
10166 		}
10167 		mutex_exit(&ipss->ipsec_loader_lock);
10168 
10169 		/*
10170 		 * Test for valid requests. Invalid algorithms
10171 		 * need to be tested by IPsec code because new
10172 		 * algorithms can be added dynamically.
10173 		 */
10174 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10175 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10176 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10177 			return (EINVAL);
10178 		}
10179 
10180 		/*
10181 		 * Only privileged users can issue these
10182 		 * requests.
10183 		 */
10184 		if (((ah_req & IPSEC_PREF_NEVER) ||
10185 		    (esp_req & IPSEC_PREF_NEVER) ||
10186 		    (se_req & IPSEC_PREF_NEVER)) &&
10187 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10188 			return (EPERM);
10189 		}
10190 
10191 		/*
10192 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10193 		 * are mutually exclusive.
10194 		 */
10195 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10196 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10197 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10198 			/* Both of them are set */
10199 			return (EINVAL);
10200 		}
10201 	}
10202 
10203 	mutex_enter(&connp->conn_lock);
10204 
10205 	/*
10206 	 * If we have already cached policies in ip_bind_connected*(), don't
10207 	 * let them change now. We cache policies for connections
10208 	 * whose src,dst [addr, port] is known.
10209 	 */
10210 	if (connp->conn_policy_cached) {
10211 		mutex_exit(&connp->conn_lock);
10212 		return (EINVAL);
10213 	}
10214 
10215 	/*
10216 	 * We have a zero policies, reset the connection policy if already
10217 	 * set. This will cause the connection to inherit the
10218 	 * global policy, if any.
10219 	 */
10220 	if (is_pol_reset) {
10221 		if (connp->conn_policy != NULL) {
10222 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10223 			connp->conn_policy = NULL;
10224 		}
10225 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10226 		connp->conn_in_enforce_policy = B_FALSE;
10227 		connp->conn_out_enforce_policy = B_FALSE;
10228 		mutex_exit(&connp->conn_lock);
10229 		return (0);
10230 	}
10231 
10232 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10233 	    ipst->ips_netstack);
10234 	if (ph == NULL)
10235 		goto enomem;
10236 
10237 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10238 	if (actp == NULL)
10239 		goto enomem;
10240 
10241 	/*
10242 	 * Always allocate IPv4 policy entries, since they can also
10243 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10244 	 */
10245 	bzero(&sel, sizeof (sel));
10246 	sel.ipsl_valid = IPSL_IPV4;
10247 
10248 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10249 	    ipst->ips_netstack);
10250 	if (pin4 == NULL)
10251 		goto enomem;
10252 
10253 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10254 	    ipst->ips_netstack);
10255 	if (pout4 == NULL)
10256 		goto enomem;
10257 
10258 	if (connp->conn_af_isv6) {
10259 		/*
10260 		 * We're looking at a v6 socket, also allocate the
10261 		 * v6-specific entries...
10262 		 */
10263 		sel.ipsl_valid = IPSL_IPV6;
10264 		pin6 = ipsec_policy_create(&sel, actp, nact,
10265 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10266 		if (pin6 == NULL)
10267 			goto enomem;
10268 
10269 		pout6 = ipsec_policy_create(&sel, actp, nact,
10270 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10271 		if (pout6 == NULL)
10272 			goto enomem;
10273 
10274 		/*
10275 		 * .. and file them away in the right place.
10276 		 */
10277 		fam = IPSEC_AF_V6;
10278 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10279 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10280 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10281 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10282 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10283 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10284 	}
10285 
10286 	ipsec_actvec_free(actp, nact);
10287 
10288 	/*
10289 	 * File the v4 policies.
10290 	 */
10291 	fam = IPSEC_AF_V4;
10292 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10293 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10294 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10295 
10296 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10297 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10298 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10299 
10300 	/*
10301 	 * If the requests need security, set enforce_policy.
10302 	 * If the requests are IPSEC_PREF_NEVER, one should
10303 	 * still set conn_out_enforce_policy so that an ipsec_out
10304 	 * gets attached in ip_wput. This is needed so that
10305 	 * for connections that we don't cache policy in ip_bind,
10306 	 * if global policy matches in ip_wput_attach_policy, we
10307 	 * don't wrongly inherit global policy. Similarly, we need
10308 	 * to set conn_in_enforce_policy also so that we don't verify
10309 	 * policy wrongly.
10310 	 */
10311 	if ((ah_req & REQ_MASK) != 0 ||
10312 	    (esp_req & REQ_MASK) != 0 ||
10313 	    (se_req & REQ_MASK) != 0) {
10314 		connp->conn_in_enforce_policy = B_TRUE;
10315 		connp->conn_out_enforce_policy = B_TRUE;
10316 		connp->conn_flags |= IPCL_CHECK_POLICY;
10317 	}
10318 
10319 	mutex_exit(&connp->conn_lock);
10320 	return (error);
10321 #undef REQ_MASK
10322 
10323 	/*
10324 	 * Common memory-allocation-failure exit path.
10325 	 */
10326 enomem:
10327 	mutex_exit(&connp->conn_lock);
10328 	if (actp != NULL)
10329 		ipsec_actvec_free(actp, nact);
10330 	if (pin4 != NULL)
10331 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10332 	if (pout4 != NULL)
10333 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10334 	if (pin6 != NULL)
10335 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10336 	if (pout6 != NULL)
10337 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10338 	return (ENOMEM);
10339 }
10340 
10341 /*
10342  * Only for options that pass in an IP addr. Currently only V4 options
10343  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10344  * So this function assumes level is IPPROTO_IP
10345  */
10346 int
10347 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10348     mblk_t *first_mp)
10349 {
10350 	ipif_t *ipif = NULL;
10351 	int error;
10352 	ill_t *ill;
10353 	int zoneid;
10354 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10355 
10356 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10357 
10358 	if (addr != INADDR_ANY || checkonly) {
10359 		ASSERT(connp != NULL);
10360 		zoneid = IPCL_ZONEID(connp);
10361 		if (option == IP_NEXTHOP) {
10362 			ipif = ipif_lookup_onlink_addr(addr,
10363 			    connp->conn_zoneid, ipst);
10364 		} else {
10365 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10366 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10367 			    &error, ipst);
10368 		}
10369 		if (ipif == NULL) {
10370 			if (error == EINPROGRESS)
10371 				return (error);
10372 			else if ((option == IP_MULTICAST_IF) ||
10373 			    (option == IP_NEXTHOP))
10374 				return (EHOSTUNREACH);
10375 			else
10376 				return (EINVAL);
10377 		} else if (checkonly) {
10378 			if (option == IP_MULTICAST_IF) {
10379 				ill = ipif->ipif_ill;
10380 				/* not supported by the virtual network iface */
10381 				if (IS_VNI(ill)) {
10382 					ipif_refrele(ipif);
10383 					return (EINVAL);
10384 				}
10385 			}
10386 			ipif_refrele(ipif);
10387 			return (0);
10388 		}
10389 		ill = ipif->ipif_ill;
10390 		mutex_enter(&connp->conn_lock);
10391 		mutex_enter(&ill->ill_lock);
10392 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10393 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10394 			mutex_exit(&ill->ill_lock);
10395 			mutex_exit(&connp->conn_lock);
10396 			ipif_refrele(ipif);
10397 			return (option == IP_MULTICAST_IF ?
10398 			    EHOSTUNREACH : EINVAL);
10399 		}
10400 	} else {
10401 		mutex_enter(&connp->conn_lock);
10402 	}
10403 
10404 	/* None of the options below are supported on the VNI */
10405 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10406 		mutex_exit(&ill->ill_lock);
10407 		mutex_exit(&connp->conn_lock);
10408 		ipif_refrele(ipif);
10409 		return (EINVAL);
10410 	}
10411 
10412 	switch (option) {
10413 	case IP_DONTFAILOVER_IF:
10414 		/*
10415 		 * This option is used by in.mpathd to ensure
10416 		 * that IPMP probe packets only go out on the
10417 		 * test interfaces. in.mpathd sets this option
10418 		 * on the non-failover interfaces.
10419 		 * For backward compatibility, this option
10420 		 * implicitly sets IP_MULTICAST_IF, as used
10421 		 * be done in bind(), so that ip_wput gets
10422 		 * this ipif to send mcast packets.
10423 		 */
10424 		if (ipif != NULL) {
10425 			ASSERT(addr != INADDR_ANY);
10426 			connp->conn_nofailover_ill = ipif->ipif_ill;
10427 			connp->conn_multicast_ipif = ipif;
10428 		} else {
10429 			ASSERT(addr == INADDR_ANY);
10430 			connp->conn_nofailover_ill = NULL;
10431 			connp->conn_multicast_ipif = NULL;
10432 		}
10433 		break;
10434 
10435 	case IP_MULTICAST_IF:
10436 		connp->conn_multicast_ipif = ipif;
10437 		break;
10438 	case IP_NEXTHOP:
10439 		connp->conn_nexthop_v4 = addr;
10440 		connp->conn_nexthop_set = B_TRUE;
10441 		break;
10442 	}
10443 
10444 	if (ipif != NULL) {
10445 		mutex_exit(&ill->ill_lock);
10446 		mutex_exit(&connp->conn_lock);
10447 		ipif_refrele(ipif);
10448 		return (0);
10449 	}
10450 	mutex_exit(&connp->conn_lock);
10451 	/* We succeded in cleared the option */
10452 	return (0);
10453 }
10454 
10455 /*
10456  * For options that pass in an ifindex specifying the ill. V6 options always
10457  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10458  */
10459 int
10460 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10461     int level, int option, mblk_t *first_mp)
10462 {
10463 	ill_t *ill = NULL;
10464 	int error = 0;
10465 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10466 
10467 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10468 	if (ifindex != 0) {
10469 		ASSERT(connp != NULL);
10470 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10471 		    first_mp, ip_restart_optmgmt, &error, ipst);
10472 		if (ill != NULL) {
10473 			if (checkonly) {
10474 				/* not supported by the virtual network iface */
10475 				if (IS_VNI(ill)) {
10476 					ill_refrele(ill);
10477 					return (EINVAL);
10478 				}
10479 				ill_refrele(ill);
10480 				return (0);
10481 			}
10482 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10483 			    0, NULL)) {
10484 				ill_refrele(ill);
10485 				ill = NULL;
10486 				mutex_enter(&connp->conn_lock);
10487 				goto setit;
10488 			}
10489 			mutex_enter(&connp->conn_lock);
10490 			mutex_enter(&ill->ill_lock);
10491 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10492 				mutex_exit(&ill->ill_lock);
10493 				mutex_exit(&connp->conn_lock);
10494 				ill_refrele(ill);
10495 				ill = NULL;
10496 				mutex_enter(&connp->conn_lock);
10497 			}
10498 			goto setit;
10499 		} else if (error == EINPROGRESS) {
10500 			return (error);
10501 		} else {
10502 			error = 0;
10503 		}
10504 	}
10505 	mutex_enter(&connp->conn_lock);
10506 setit:
10507 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10508 
10509 	/*
10510 	 * The options below assume that the ILL (if any) transmits and/or
10511 	 * receives traffic. Neither of which is true for the virtual network
10512 	 * interface, so fail setting these on a VNI.
10513 	 */
10514 	if (IS_VNI(ill)) {
10515 		ASSERT(ill != NULL);
10516 		mutex_exit(&ill->ill_lock);
10517 		mutex_exit(&connp->conn_lock);
10518 		ill_refrele(ill);
10519 		return (EINVAL);
10520 	}
10521 
10522 	if (level == IPPROTO_IP) {
10523 		switch (option) {
10524 		case IP_BOUND_IF:
10525 			connp->conn_incoming_ill = ill;
10526 			connp->conn_outgoing_ill = ill;
10527 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10528 			    0 : ifindex;
10529 			break;
10530 
10531 		case IP_MULTICAST_IF:
10532 			/*
10533 			 * This option is an internal special. The socket
10534 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10535 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10536 			 * specifies an ifindex and we try first on V6 ill's.
10537 			 * If we don't find one, we they try using on v4 ill's
10538 			 * intenally and we come here.
10539 			 */
10540 			if (!checkonly && ill != NULL) {
10541 				ipif_t	*ipif;
10542 				ipif = ill->ill_ipif;
10543 
10544 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10545 					mutex_exit(&ill->ill_lock);
10546 					mutex_exit(&connp->conn_lock);
10547 					ill_refrele(ill);
10548 					ill = NULL;
10549 					mutex_enter(&connp->conn_lock);
10550 				} else {
10551 					connp->conn_multicast_ipif = ipif;
10552 				}
10553 			}
10554 			break;
10555 
10556 		case IP_DHCPINIT_IF:
10557 			if (connp->conn_dhcpinit_ill != NULL) {
10558 				/*
10559 				 * We've locked the conn so conn_cleanup_ill()
10560 				 * cannot clear conn_dhcpinit_ill -- so it's
10561 				 * safe to access the ill.
10562 				 */
10563 				ill_t *oill = connp->conn_dhcpinit_ill;
10564 
10565 				ASSERT(oill->ill_dhcpinit != 0);
10566 				atomic_dec_32(&oill->ill_dhcpinit);
10567 				connp->conn_dhcpinit_ill = NULL;
10568 			}
10569 
10570 			if (ill != NULL) {
10571 				connp->conn_dhcpinit_ill = ill;
10572 				atomic_inc_32(&ill->ill_dhcpinit);
10573 			}
10574 			break;
10575 		}
10576 	} else {
10577 		switch (option) {
10578 		case IPV6_BOUND_IF:
10579 			connp->conn_incoming_ill = ill;
10580 			connp->conn_outgoing_ill = ill;
10581 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10582 			    0 : ifindex;
10583 			break;
10584 
10585 		case IPV6_BOUND_PIF:
10586 			/*
10587 			 * Limit all transmit to this ill.
10588 			 * Unlike IPV6_BOUND_IF, using this option
10589 			 * prevents load spreading and failover from
10590 			 * happening when the interface is part of the
10591 			 * group. That's why we don't need to remember
10592 			 * the ifindex in orig_bound_ifindex as in
10593 			 * IPV6_BOUND_IF.
10594 			 */
10595 			connp->conn_outgoing_pill = ill;
10596 			break;
10597 
10598 		case IPV6_DONTFAILOVER_IF:
10599 			/*
10600 			 * This option is used by in.mpathd to ensure
10601 			 * that IPMP probe packets only go out on the
10602 			 * test interfaces. in.mpathd sets this option
10603 			 * on the non-failover interfaces.
10604 			 */
10605 			connp->conn_nofailover_ill = ill;
10606 			/*
10607 			 * For backward compatibility, this option
10608 			 * implicitly sets ip_multicast_ill as used in
10609 			 * IPV6_MULTICAST_IF so that ip_wput gets
10610 			 * this ill to send mcast packets.
10611 			 */
10612 			connp->conn_multicast_ill = ill;
10613 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10614 			    0 : ifindex;
10615 			break;
10616 
10617 		case IPV6_MULTICAST_IF:
10618 			/*
10619 			 * Set conn_multicast_ill to be the IPv6 ill.
10620 			 * Set conn_multicast_ipif to be an IPv4 ipif
10621 			 * for ifindex to make IPv4 mapped addresses
10622 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10623 			 * Even if no IPv6 ill exists for the ifindex
10624 			 * we need to check for an IPv4 ifindex in order
10625 			 * for this to work with mapped addresses. In that
10626 			 * case only set conn_multicast_ipif.
10627 			 */
10628 			if (!checkonly) {
10629 				if (ifindex == 0) {
10630 					connp->conn_multicast_ill = NULL;
10631 					connp->conn_orig_multicast_ifindex = 0;
10632 					connp->conn_multicast_ipif = NULL;
10633 				} else if (ill != NULL) {
10634 					connp->conn_multicast_ill = ill;
10635 					connp->conn_orig_multicast_ifindex =
10636 					    ifindex;
10637 				}
10638 			}
10639 			break;
10640 		}
10641 	}
10642 
10643 	if (ill != NULL) {
10644 		mutex_exit(&ill->ill_lock);
10645 		mutex_exit(&connp->conn_lock);
10646 		ill_refrele(ill);
10647 		return (0);
10648 	}
10649 	mutex_exit(&connp->conn_lock);
10650 	/*
10651 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10652 	 * locate the ill and could not set the option (ifindex != 0)
10653 	 */
10654 	return (ifindex == 0 ? 0 : EINVAL);
10655 }
10656 
10657 /* This routine sets socket options. */
10658 /* ARGSUSED */
10659 int
10660 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10661     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10662     void *dummy, cred_t *cr, mblk_t *first_mp)
10663 {
10664 	int		*i1 = (int *)invalp;
10665 	conn_t		*connp = Q_TO_CONN(q);
10666 	int		error = 0;
10667 	boolean_t	checkonly;
10668 	ire_t		*ire;
10669 	boolean_t	found;
10670 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10671 
10672 	switch (optset_context) {
10673 
10674 	case SETFN_OPTCOM_CHECKONLY:
10675 		checkonly = B_TRUE;
10676 		/*
10677 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10678 		 * inlen != 0 implies value supplied and
10679 		 * 	we have to "pretend" to set it.
10680 		 * inlen == 0 implies that there is no
10681 		 * 	value part in T_CHECK request and just validation
10682 		 * done elsewhere should be enough, we just return here.
10683 		 */
10684 		if (inlen == 0) {
10685 			*outlenp = 0;
10686 			return (0);
10687 		}
10688 		break;
10689 	case SETFN_OPTCOM_NEGOTIATE:
10690 	case SETFN_UD_NEGOTIATE:
10691 	case SETFN_CONN_NEGOTIATE:
10692 		checkonly = B_FALSE;
10693 		break;
10694 	default:
10695 		/*
10696 		 * We should never get here
10697 		 */
10698 		*outlenp = 0;
10699 		return (EINVAL);
10700 	}
10701 
10702 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10703 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10704 
10705 	/*
10706 	 * For fixed length options, no sanity check
10707 	 * of passed in length is done. It is assumed *_optcom_req()
10708 	 * routines do the right thing.
10709 	 */
10710 
10711 	switch (level) {
10712 	case SOL_SOCKET:
10713 		/*
10714 		 * conn_lock protects the bitfields, and is used to
10715 		 * set the fields atomically.
10716 		 */
10717 		switch (name) {
10718 		case SO_BROADCAST:
10719 			if (!checkonly) {
10720 				/* TODO: use value someplace? */
10721 				mutex_enter(&connp->conn_lock);
10722 				connp->conn_broadcast = *i1 ? 1 : 0;
10723 				mutex_exit(&connp->conn_lock);
10724 			}
10725 			break;	/* goto sizeof (int) option return */
10726 		case SO_USELOOPBACK:
10727 			if (!checkonly) {
10728 				/* TODO: use value someplace? */
10729 				mutex_enter(&connp->conn_lock);
10730 				connp->conn_loopback = *i1 ? 1 : 0;
10731 				mutex_exit(&connp->conn_lock);
10732 			}
10733 			break;	/* goto sizeof (int) option return */
10734 		case SO_DONTROUTE:
10735 			if (!checkonly) {
10736 				mutex_enter(&connp->conn_lock);
10737 				connp->conn_dontroute = *i1 ? 1 : 0;
10738 				mutex_exit(&connp->conn_lock);
10739 			}
10740 			break;	/* goto sizeof (int) option return */
10741 		case SO_REUSEADDR:
10742 			if (!checkonly) {
10743 				mutex_enter(&connp->conn_lock);
10744 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10745 				mutex_exit(&connp->conn_lock);
10746 			}
10747 			break;	/* goto sizeof (int) option return */
10748 		case SO_PROTOTYPE:
10749 			if (!checkonly) {
10750 				mutex_enter(&connp->conn_lock);
10751 				connp->conn_proto = *i1;
10752 				mutex_exit(&connp->conn_lock);
10753 			}
10754 			break;	/* goto sizeof (int) option return */
10755 		case SO_ALLZONES:
10756 			if (!checkonly) {
10757 				mutex_enter(&connp->conn_lock);
10758 				if (IPCL_IS_BOUND(connp)) {
10759 					mutex_exit(&connp->conn_lock);
10760 					return (EINVAL);
10761 				}
10762 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10763 				mutex_exit(&connp->conn_lock);
10764 			}
10765 			break;	/* goto sizeof (int) option return */
10766 		case SO_ANON_MLP:
10767 			if (!checkonly) {
10768 				mutex_enter(&connp->conn_lock);
10769 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10770 				mutex_exit(&connp->conn_lock);
10771 			}
10772 			break;	/* goto sizeof (int) option return */
10773 		case SO_MAC_EXEMPT:
10774 			if (secpolicy_net_mac_aware(cr) != 0 ||
10775 			    IPCL_IS_BOUND(connp))
10776 				return (EACCES);
10777 			if (!checkonly) {
10778 				mutex_enter(&connp->conn_lock);
10779 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10780 				mutex_exit(&connp->conn_lock);
10781 			}
10782 			break;	/* goto sizeof (int) option return */
10783 		default:
10784 			/*
10785 			 * "soft" error (negative)
10786 			 * option not handled at this level
10787 			 * Note: Do not modify *outlenp
10788 			 */
10789 			return (-EINVAL);
10790 		}
10791 		break;
10792 	case IPPROTO_IP:
10793 		switch (name) {
10794 		case IP_NEXTHOP:
10795 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10796 				return (EPERM);
10797 			/* FALLTHRU */
10798 		case IP_MULTICAST_IF:
10799 		case IP_DONTFAILOVER_IF: {
10800 			ipaddr_t addr = *i1;
10801 
10802 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10803 			    first_mp);
10804 			if (error != 0)
10805 				return (error);
10806 			break;	/* goto sizeof (int) option return */
10807 		}
10808 
10809 		case IP_MULTICAST_TTL:
10810 			/* Recorded in transport above IP */
10811 			*outvalp = *invalp;
10812 			*outlenp = sizeof (uchar_t);
10813 			return (0);
10814 		case IP_MULTICAST_LOOP:
10815 			if (!checkonly) {
10816 				mutex_enter(&connp->conn_lock);
10817 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10818 				mutex_exit(&connp->conn_lock);
10819 			}
10820 			*outvalp = *invalp;
10821 			*outlenp = sizeof (uchar_t);
10822 			return (0);
10823 		case IP_ADD_MEMBERSHIP:
10824 		case MCAST_JOIN_GROUP:
10825 		case IP_DROP_MEMBERSHIP:
10826 		case MCAST_LEAVE_GROUP: {
10827 			struct ip_mreq *mreqp;
10828 			struct group_req *greqp;
10829 			ire_t *ire;
10830 			boolean_t done = B_FALSE;
10831 			ipaddr_t group, ifaddr;
10832 			struct sockaddr_in *sin;
10833 			uint32_t *ifindexp;
10834 			boolean_t mcast_opt = B_TRUE;
10835 			mcast_record_t fmode;
10836 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10837 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10838 
10839 			switch (name) {
10840 			case IP_ADD_MEMBERSHIP:
10841 				mcast_opt = B_FALSE;
10842 				/* FALLTHRU */
10843 			case MCAST_JOIN_GROUP:
10844 				fmode = MODE_IS_EXCLUDE;
10845 				optfn = ip_opt_add_group;
10846 				break;
10847 
10848 			case IP_DROP_MEMBERSHIP:
10849 				mcast_opt = B_FALSE;
10850 				/* FALLTHRU */
10851 			case MCAST_LEAVE_GROUP:
10852 				fmode = MODE_IS_INCLUDE;
10853 				optfn = ip_opt_delete_group;
10854 				break;
10855 			}
10856 
10857 			if (mcast_opt) {
10858 				greqp = (struct group_req *)i1;
10859 				sin = (struct sockaddr_in *)&greqp->gr_group;
10860 				if (sin->sin_family != AF_INET) {
10861 					*outlenp = 0;
10862 					return (ENOPROTOOPT);
10863 				}
10864 				group = (ipaddr_t)sin->sin_addr.s_addr;
10865 				ifaddr = INADDR_ANY;
10866 				ifindexp = &greqp->gr_interface;
10867 			} else {
10868 				mreqp = (struct ip_mreq *)i1;
10869 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10870 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10871 				ifindexp = NULL;
10872 			}
10873 
10874 			/*
10875 			 * In the multirouting case, we need to replicate
10876 			 * the request on all interfaces that will take part
10877 			 * in replication.  We do so because multirouting is
10878 			 * reflective, thus we will probably receive multi-
10879 			 * casts on those interfaces.
10880 			 * The ip_multirt_apply_membership() succeeds if the
10881 			 * operation succeeds on at least one interface.
10882 			 */
10883 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10884 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10885 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10886 			if (ire != NULL) {
10887 				if (ire->ire_flags & RTF_MULTIRT) {
10888 					error = ip_multirt_apply_membership(
10889 					    optfn, ire, connp, checkonly, group,
10890 					    fmode, INADDR_ANY, first_mp);
10891 					done = B_TRUE;
10892 				}
10893 				ire_refrele(ire);
10894 			}
10895 			if (!done) {
10896 				error = optfn(connp, checkonly, group, ifaddr,
10897 				    ifindexp, fmode, INADDR_ANY, first_mp);
10898 			}
10899 			if (error) {
10900 				/*
10901 				 * EINPROGRESS is a soft error, needs retry
10902 				 * so don't make *outlenp zero.
10903 				 */
10904 				if (error != EINPROGRESS)
10905 					*outlenp = 0;
10906 				return (error);
10907 			}
10908 			/* OK return - copy input buffer into output buffer */
10909 			if (invalp != outvalp) {
10910 				/* don't trust bcopy for identical src/dst */
10911 				bcopy(invalp, outvalp, inlen);
10912 			}
10913 			*outlenp = inlen;
10914 			return (0);
10915 		}
10916 		case IP_BLOCK_SOURCE:
10917 		case IP_UNBLOCK_SOURCE:
10918 		case IP_ADD_SOURCE_MEMBERSHIP:
10919 		case IP_DROP_SOURCE_MEMBERSHIP:
10920 		case MCAST_BLOCK_SOURCE:
10921 		case MCAST_UNBLOCK_SOURCE:
10922 		case MCAST_JOIN_SOURCE_GROUP:
10923 		case MCAST_LEAVE_SOURCE_GROUP: {
10924 			struct ip_mreq_source *imreqp;
10925 			struct group_source_req *gsreqp;
10926 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10927 			uint32_t ifindex = 0;
10928 			mcast_record_t fmode;
10929 			struct sockaddr_in *sin;
10930 			ire_t *ire;
10931 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10932 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10933 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10934 
10935 			switch (name) {
10936 			case IP_BLOCK_SOURCE:
10937 				mcast_opt = B_FALSE;
10938 				/* FALLTHRU */
10939 			case MCAST_BLOCK_SOURCE:
10940 				fmode = MODE_IS_EXCLUDE;
10941 				optfn = ip_opt_add_group;
10942 				break;
10943 
10944 			case IP_UNBLOCK_SOURCE:
10945 				mcast_opt = B_FALSE;
10946 				/* FALLTHRU */
10947 			case MCAST_UNBLOCK_SOURCE:
10948 				fmode = MODE_IS_EXCLUDE;
10949 				optfn = ip_opt_delete_group;
10950 				break;
10951 
10952 			case IP_ADD_SOURCE_MEMBERSHIP:
10953 				mcast_opt = B_FALSE;
10954 				/* FALLTHRU */
10955 			case MCAST_JOIN_SOURCE_GROUP:
10956 				fmode = MODE_IS_INCLUDE;
10957 				optfn = ip_opt_add_group;
10958 				break;
10959 
10960 			case IP_DROP_SOURCE_MEMBERSHIP:
10961 				mcast_opt = B_FALSE;
10962 				/* FALLTHRU */
10963 			case MCAST_LEAVE_SOURCE_GROUP:
10964 				fmode = MODE_IS_INCLUDE;
10965 				optfn = ip_opt_delete_group;
10966 				break;
10967 			}
10968 
10969 			if (mcast_opt) {
10970 				gsreqp = (struct group_source_req *)i1;
10971 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10972 					*outlenp = 0;
10973 					return (ENOPROTOOPT);
10974 				}
10975 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10976 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10977 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10978 				src = (ipaddr_t)sin->sin_addr.s_addr;
10979 				ifindex = gsreqp->gsr_interface;
10980 			} else {
10981 				imreqp = (struct ip_mreq_source *)i1;
10982 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10983 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10984 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10985 			}
10986 
10987 			/*
10988 			 * In the multirouting case, we need to replicate
10989 			 * the request as noted in the mcast cases above.
10990 			 */
10991 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10992 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10993 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10994 			if (ire != NULL) {
10995 				if (ire->ire_flags & RTF_MULTIRT) {
10996 					error = ip_multirt_apply_membership(
10997 					    optfn, ire, connp, checkonly, grp,
10998 					    fmode, src, first_mp);
10999 					done = B_TRUE;
11000 				}
11001 				ire_refrele(ire);
11002 			}
11003 			if (!done) {
11004 				error = optfn(connp, checkonly, grp, ifaddr,
11005 				    &ifindex, fmode, src, first_mp);
11006 			}
11007 			if (error != 0) {
11008 				/*
11009 				 * EINPROGRESS is a soft error, needs retry
11010 				 * so don't make *outlenp zero.
11011 				 */
11012 				if (error != EINPROGRESS)
11013 					*outlenp = 0;
11014 				return (error);
11015 			}
11016 			/* OK return - copy input buffer into output buffer */
11017 			if (invalp != outvalp) {
11018 				bcopy(invalp, outvalp, inlen);
11019 			}
11020 			*outlenp = inlen;
11021 			return (0);
11022 		}
11023 		case IP_SEC_OPT:
11024 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11025 			if (error != 0) {
11026 				*outlenp = 0;
11027 				return (error);
11028 			}
11029 			break;
11030 		case IP_HDRINCL:
11031 		case IP_OPTIONS:
11032 		case T_IP_OPTIONS:
11033 		case IP_TOS:
11034 		case T_IP_TOS:
11035 		case IP_TTL:
11036 		case IP_RECVDSTADDR:
11037 		case IP_RECVOPTS:
11038 			/* OK return - copy input buffer into output buffer */
11039 			if (invalp != outvalp) {
11040 				/* don't trust bcopy for identical src/dst */
11041 				bcopy(invalp, outvalp, inlen);
11042 			}
11043 			*outlenp = inlen;
11044 			return (0);
11045 		case IP_RECVIF:
11046 			/* Retrieve the inbound interface index */
11047 			if (!checkonly) {
11048 				mutex_enter(&connp->conn_lock);
11049 				connp->conn_recvif = *i1 ? 1 : 0;
11050 				mutex_exit(&connp->conn_lock);
11051 			}
11052 			break;	/* goto sizeof (int) option return */
11053 		case IP_RECVPKTINFO:
11054 			if (!checkonly) {
11055 				mutex_enter(&connp->conn_lock);
11056 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11057 				mutex_exit(&connp->conn_lock);
11058 			}
11059 			break;	/* goto sizeof (int) option return */
11060 		case IP_RECVSLLA:
11061 			/* Retrieve the source link layer address */
11062 			if (!checkonly) {
11063 				mutex_enter(&connp->conn_lock);
11064 				connp->conn_recvslla = *i1 ? 1 : 0;
11065 				mutex_exit(&connp->conn_lock);
11066 			}
11067 			break;	/* goto sizeof (int) option return */
11068 		case MRT_INIT:
11069 		case MRT_DONE:
11070 		case MRT_ADD_VIF:
11071 		case MRT_DEL_VIF:
11072 		case MRT_ADD_MFC:
11073 		case MRT_DEL_MFC:
11074 		case MRT_ASSERT:
11075 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11076 				*outlenp = 0;
11077 				return (error);
11078 			}
11079 			error = ip_mrouter_set((int)name, q, checkonly,
11080 			    (uchar_t *)invalp, inlen, first_mp);
11081 			if (error) {
11082 				*outlenp = 0;
11083 				return (error);
11084 			}
11085 			/* OK return - copy input buffer into output buffer */
11086 			if (invalp != outvalp) {
11087 				/* don't trust bcopy for identical src/dst */
11088 				bcopy(invalp, outvalp, inlen);
11089 			}
11090 			*outlenp = inlen;
11091 			return (0);
11092 		case IP_BOUND_IF:
11093 		case IP_DHCPINIT_IF:
11094 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11095 			    level, name, first_mp);
11096 			if (error != 0)
11097 				return (error);
11098 			break; 		/* goto sizeof (int) option return */
11099 
11100 		case IP_UNSPEC_SRC:
11101 			/* Allow sending with a zero source address */
11102 			if (!checkonly) {
11103 				mutex_enter(&connp->conn_lock);
11104 				connp->conn_unspec_src = *i1 ? 1 : 0;
11105 				mutex_exit(&connp->conn_lock);
11106 			}
11107 			break;	/* goto sizeof (int) option return */
11108 		default:
11109 			/*
11110 			 * "soft" error (negative)
11111 			 * option not handled at this level
11112 			 * Note: Do not modify *outlenp
11113 			 */
11114 			return (-EINVAL);
11115 		}
11116 		break;
11117 	case IPPROTO_IPV6:
11118 		switch (name) {
11119 		case IPV6_BOUND_IF:
11120 		case IPV6_BOUND_PIF:
11121 		case IPV6_DONTFAILOVER_IF:
11122 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11123 			    level, name, first_mp);
11124 			if (error != 0)
11125 				return (error);
11126 			break; 		/* goto sizeof (int) option return */
11127 
11128 		case IPV6_MULTICAST_IF:
11129 			/*
11130 			 * The only possible errors are EINPROGRESS and
11131 			 * EINVAL. EINPROGRESS will be restarted and is not
11132 			 * a hard error. We call this option on both V4 and V6
11133 			 * If both return EINVAL, then this call returns
11134 			 * EINVAL. If at least one of them succeeds we
11135 			 * return success.
11136 			 */
11137 			found = B_FALSE;
11138 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11139 			    level, name, first_mp);
11140 			if (error == EINPROGRESS)
11141 				return (error);
11142 			if (error == 0)
11143 				found = B_TRUE;
11144 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11145 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11146 			if (error == 0)
11147 				found = B_TRUE;
11148 			if (!found)
11149 				return (error);
11150 			break; 		/* goto sizeof (int) option return */
11151 
11152 		case IPV6_MULTICAST_HOPS:
11153 			/* Recorded in transport above IP */
11154 			break;	/* goto sizeof (int) option return */
11155 		case IPV6_MULTICAST_LOOP:
11156 			if (!checkonly) {
11157 				mutex_enter(&connp->conn_lock);
11158 				connp->conn_multicast_loop = *i1;
11159 				mutex_exit(&connp->conn_lock);
11160 			}
11161 			break;	/* goto sizeof (int) option return */
11162 		case IPV6_JOIN_GROUP:
11163 		case MCAST_JOIN_GROUP:
11164 		case IPV6_LEAVE_GROUP:
11165 		case MCAST_LEAVE_GROUP: {
11166 			struct ipv6_mreq *ip_mreqp;
11167 			struct group_req *greqp;
11168 			ire_t *ire;
11169 			boolean_t done = B_FALSE;
11170 			in6_addr_t groupv6;
11171 			uint32_t ifindex;
11172 			boolean_t mcast_opt = B_TRUE;
11173 			mcast_record_t fmode;
11174 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11175 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11176 
11177 			switch (name) {
11178 			case IPV6_JOIN_GROUP:
11179 				mcast_opt = B_FALSE;
11180 				/* FALLTHRU */
11181 			case MCAST_JOIN_GROUP:
11182 				fmode = MODE_IS_EXCLUDE;
11183 				optfn = ip_opt_add_group_v6;
11184 				break;
11185 
11186 			case IPV6_LEAVE_GROUP:
11187 				mcast_opt = B_FALSE;
11188 				/* FALLTHRU */
11189 			case MCAST_LEAVE_GROUP:
11190 				fmode = MODE_IS_INCLUDE;
11191 				optfn = ip_opt_delete_group_v6;
11192 				break;
11193 			}
11194 
11195 			if (mcast_opt) {
11196 				struct sockaddr_in *sin;
11197 				struct sockaddr_in6 *sin6;
11198 				greqp = (struct group_req *)i1;
11199 				if (greqp->gr_group.ss_family == AF_INET) {
11200 					sin = (struct sockaddr_in *)
11201 					    &(greqp->gr_group);
11202 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11203 					    &groupv6);
11204 				} else {
11205 					sin6 = (struct sockaddr_in6 *)
11206 					    &(greqp->gr_group);
11207 					groupv6 = sin6->sin6_addr;
11208 				}
11209 				ifindex = greqp->gr_interface;
11210 			} else {
11211 				ip_mreqp = (struct ipv6_mreq *)i1;
11212 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11213 				ifindex = ip_mreqp->ipv6mr_interface;
11214 			}
11215 			/*
11216 			 * In the multirouting case, we need to replicate
11217 			 * the request on all interfaces that will take part
11218 			 * in replication.  We do so because multirouting is
11219 			 * reflective, thus we will probably receive multi-
11220 			 * casts on those interfaces.
11221 			 * The ip_multirt_apply_membership_v6() succeeds if
11222 			 * the operation succeeds on at least one interface.
11223 			 */
11224 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11225 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11226 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11227 			if (ire != NULL) {
11228 				if (ire->ire_flags & RTF_MULTIRT) {
11229 					error = ip_multirt_apply_membership_v6(
11230 					    optfn, ire, connp, checkonly,
11231 					    &groupv6, fmode, &ipv6_all_zeros,
11232 					    first_mp);
11233 					done = B_TRUE;
11234 				}
11235 				ire_refrele(ire);
11236 			}
11237 			if (!done) {
11238 				error = optfn(connp, checkonly, &groupv6,
11239 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11240 			}
11241 			if (error) {
11242 				/*
11243 				 * EINPROGRESS is a soft error, needs retry
11244 				 * so don't make *outlenp zero.
11245 				 */
11246 				if (error != EINPROGRESS)
11247 					*outlenp = 0;
11248 				return (error);
11249 			}
11250 			/* OK return - copy input buffer into output buffer */
11251 			if (invalp != outvalp) {
11252 				/* don't trust bcopy for identical src/dst */
11253 				bcopy(invalp, outvalp, inlen);
11254 			}
11255 			*outlenp = inlen;
11256 			return (0);
11257 		}
11258 		case MCAST_BLOCK_SOURCE:
11259 		case MCAST_UNBLOCK_SOURCE:
11260 		case MCAST_JOIN_SOURCE_GROUP:
11261 		case MCAST_LEAVE_SOURCE_GROUP: {
11262 			struct group_source_req *gsreqp;
11263 			in6_addr_t v6grp, v6src;
11264 			uint32_t ifindex;
11265 			mcast_record_t fmode;
11266 			ire_t *ire;
11267 			boolean_t done = B_FALSE;
11268 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11269 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11270 
11271 			switch (name) {
11272 			case MCAST_BLOCK_SOURCE:
11273 				fmode = MODE_IS_EXCLUDE;
11274 				optfn = ip_opt_add_group_v6;
11275 				break;
11276 			case MCAST_UNBLOCK_SOURCE:
11277 				fmode = MODE_IS_EXCLUDE;
11278 				optfn = ip_opt_delete_group_v6;
11279 				break;
11280 			case MCAST_JOIN_SOURCE_GROUP:
11281 				fmode = MODE_IS_INCLUDE;
11282 				optfn = ip_opt_add_group_v6;
11283 				break;
11284 			case MCAST_LEAVE_SOURCE_GROUP:
11285 				fmode = MODE_IS_INCLUDE;
11286 				optfn = ip_opt_delete_group_v6;
11287 				break;
11288 			}
11289 
11290 			gsreqp = (struct group_source_req *)i1;
11291 			ifindex = gsreqp->gsr_interface;
11292 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11293 				struct sockaddr_in *s;
11294 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11295 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11296 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11297 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11298 			} else {
11299 				struct sockaddr_in6 *s6;
11300 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11301 				v6grp = s6->sin6_addr;
11302 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11303 				v6src = s6->sin6_addr;
11304 			}
11305 
11306 			/*
11307 			 * In the multirouting case, we need to replicate
11308 			 * the request as noted in the mcast cases above.
11309 			 */
11310 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11311 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11312 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11313 			if (ire != NULL) {
11314 				if (ire->ire_flags & RTF_MULTIRT) {
11315 					error = ip_multirt_apply_membership_v6(
11316 					    optfn, ire, connp, checkonly,
11317 					    &v6grp, fmode, &v6src, first_mp);
11318 					done = B_TRUE;
11319 				}
11320 				ire_refrele(ire);
11321 			}
11322 			if (!done) {
11323 				error = optfn(connp, checkonly, &v6grp,
11324 				    ifindex, fmode, &v6src, first_mp);
11325 			}
11326 			if (error != 0) {
11327 				/*
11328 				 * EINPROGRESS is a soft error, needs retry
11329 				 * so don't make *outlenp zero.
11330 				 */
11331 				if (error != EINPROGRESS)
11332 					*outlenp = 0;
11333 				return (error);
11334 			}
11335 			/* OK return - copy input buffer into output buffer */
11336 			if (invalp != outvalp) {
11337 				bcopy(invalp, outvalp, inlen);
11338 			}
11339 			*outlenp = inlen;
11340 			return (0);
11341 		}
11342 		case IPV6_UNICAST_HOPS:
11343 			/* Recorded in transport above IP */
11344 			break;	/* goto sizeof (int) option return */
11345 		case IPV6_UNSPEC_SRC:
11346 			/* Allow sending with a zero source address */
11347 			if (!checkonly) {
11348 				mutex_enter(&connp->conn_lock);
11349 				connp->conn_unspec_src = *i1 ? 1 : 0;
11350 				mutex_exit(&connp->conn_lock);
11351 			}
11352 			break;	/* goto sizeof (int) option return */
11353 		case IPV6_RECVPKTINFO:
11354 			if (!checkonly) {
11355 				mutex_enter(&connp->conn_lock);
11356 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11357 				mutex_exit(&connp->conn_lock);
11358 			}
11359 			break;	/* goto sizeof (int) option return */
11360 		case IPV6_RECVTCLASS:
11361 			if (!checkonly) {
11362 				if (*i1 < 0 || *i1 > 1) {
11363 					return (EINVAL);
11364 				}
11365 				mutex_enter(&connp->conn_lock);
11366 				connp->conn_ipv6_recvtclass = *i1;
11367 				mutex_exit(&connp->conn_lock);
11368 			}
11369 			break;
11370 		case IPV6_RECVPATHMTU:
11371 			if (!checkonly) {
11372 				if (*i1 < 0 || *i1 > 1) {
11373 					return (EINVAL);
11374 				}
11375 				mutex_enter(&connp->conn_lock);
11376 				connp->conn_ipv6_recvpathmtu = *i1;
11377 				mutex_exit(&connp->conn_lock);
11378 			}
11379 			break;
11380 		case IPV6_RECVHOPLIMIT:
11381 			if (!checkonly) {
11382 				mutex_enter(&connp->conn_lock);
11383 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11384 				mutex_exit(&connp->conn_lock);
11385 			}
11386 			break;	/* goto sizeof (int) option return */
11387 		case IPV6_RECVHOPOPTS:
11388 			if (!checkonly) {
11389 				mutex_enter(&connp->conn_lock);
11390 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11391 				mutex_exit(&connp->conn_lock);
11392 			}
11393 			break;	/* goto sizeof (int) option return */
11394 		case IPV6_RECVDSTOPTS:
11395 			if (!checkonly) {
11396 				mutex_enter(&connp->conn_lock);
11397 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11398 				mutex_exit(&connp->conn_lock);
11399 			}
11400 			break;	/* goto sizeof (int) option return */
11401 		case IPV6_RECVRTHDR:
11402 			if (!checkonly) {
11403 				mutex_enter(&connp->conn_lock);
11404 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11405 				mutex_exit(&connp->conn_lock);
11406 			}
11407 			break;	/* goto sizeof (int) option return */
11408 		case IPV6_RECVRTHDRDSTOPTS:
11409 			if (!checkonly) {
11410 				mutex_enter(&connp->conn_lock);
11411 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11412 				mutex_exit(&connp->conn_lock);
11413 			}
11414 			break;	/* goto sizeof (int) option return */
11415 		case IPV6_PKTINFO:
11416 			if (inlen == 0)
11417 				return (-EINVAL);	/* clearing option */
11418 			error = ip6_set_pktinfo(cr, connp,
11419 			    (struct in6_pktinfo *)invalp, first_mp);
11420 			if (error != 0)
11421 				*outlenp = 0;
11422 			else
11423 				*outlenp = inlen;
11424 			return (error);
11425 		case IPV6_NEXTHOP: {
11426 			struct sockaddr_in6 *sin6;
11427 
11428 			/* Verify that the nexthop is reachable */
11429 			if (inlen == 0)
11430 				return (-EINVAL);	/* clearing option */
11431 
11432 			sin6 = (struct sockaddr_in6 *)invalp;
11433 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11434 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11435 			    NULL, MATCH_IRE_DEFAULT, ipst);
11436 
11437 			if (ire == NULL) {
11438 				*outlenp = 0;
11439 				return (EHOSTUNREACH);
11440 			}
11441 			ire_refrele(ire);
11442 			return (-EINVAL);
11443 		}
11444 		case IPV6_SEC_OPT:
11445 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11446 			if (error != 0) {
11447 				*outlenp = 0;
11448 				return (error);
11449 			}
11450 			break;
11451 		case IPV6_SRC_PREFERENCES: {
11452 			/*
11453 			 * This is implemented strictly in the ip module
11454 			 * (here and in tcp_opt_*() to accomodate tcp
11455 			 * sockets).  Modules above ip pass this option
11456 			 * down here since ip is the only one that needs to
11457 			 * be aware of source address preferences.
11458 			 *
11459 			 * This socket option only affects connected
11460 			 * sockets that haven't already bound to a specific
11461 			 * IPv6 address.  In other words, sockets that
11462 			 * don't call bind() with an address other than the
11463 			 * unspecified address and that call connect().
11464 			 * ip_bind_connected_v6() passes these preferences
11465 			 * to the ipif_select_source_v6() function.
11466 			 */
11467 			if (inlen != sizeof (uint32_t))
11468 				return (EINVAL);
11469 			error = ip6_set_src_preferences(connp,
11470 			    *(uint32_t *)invalp);
11471 			if (error != 0) {
11472 				*outlenp = 0;
11473 				return (error);
11474 			} else {
11475 				*outlenp = sizeof (uint32_t);
11476 			}
11477 			break;
11478 		}
11479 		case IPV6_V6ONLY:
11480 			if (*i1 < 0 || *i1 > 1) {
11481 				return (EINVAL);
11482 			}
11483 			mutex_enter(&connp->conn_lock);
11484 			connp->conn_ipv6_v6only = *i1;
11485 			mutex_exit(&connp->conn_lock);
11486 			break;
11487 		default:
11488 			return (-EINVAL);
11489 		}
11490 		break;
11491 	default:
11492 		/*
11493 		 * "soft" error (negative)
11494 		 * option not handled at this level
11495 		 * Note: Do not modify *outlenp
11496 		 */
11497 		return (-EINVAL);
11498 	}
11499 	/*
11500 	 * Common case of return from an option that is sizeof (int)
11501 	 */
11502 	*(int *)outvalp = *i1;
11503 	*outlenp = sizeof (int);
11504 	return (0);
11505 }
11506 
11507 /*
11508  * This routine gets default values of certain options whose default
11509  * values are maintained by protocol specific code
11510  */
11511 /* ARGSUSED */
11512 int
11513 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11514 {
11515 	int *i1 = (int *)ptr;
11516 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11517 
11518 	switch (level) {
11519 	case IPPROTO_IP:
11520 		switch (name) {
11521 		case IP_MULTICAST_TTL:
11522 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11523 			return (sizeof (uchar_t));
11524 		case IP_MULTICAST_LOOP:
11525 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11526 			return (sizeof (uchar_t));
11527 		default:
11528 			return (-1);
11529 		}
11530 	case IPPROTO_IPV6:
11531 		switch (name) {
11532 		case IPV6_UNICAST_HOPS:
11533 			*i1 = ipst->ips_ipv6_def_hops;
11534 			return (sizeof (int));
11535 		case IPV6_MULTICAST_HOPS:
11536 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11537 			return (sizeof (int));
11538 		case IPV6_MULTICAST_LOOP:
11539 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11540 			return (sizeof (int));
11541 		case IPV6_V6ONLY:
11542 			*i1 = 1;
11543 			return (sizeof (int));
11544 		default:
11545 			return (-1);
11546 		}
11547 	default:
11548 		return (-1);
11549 	}
11550 	/* NOTREACHED */
11551 }
11552 
11553 /*
11554  * Given a destination address and a pointer to where to put the information
11555  * this routine fills in the mtuinfo.
11556  */
11557 int
11558 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11559     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11560 {
11561 	ire_t *ire;
11562 	ip_stack_t	*ipst = ns->netstack_ip;
11563 
11564 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11565 		return (-1);
11566 
11567 	bzero(mtuinfo, sizeof (*mtuinfo));
11568 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11569 	mtuinfo->ip6m_addr.sin6_port = port;
11570 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11571 
11572 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11573 	if (ire != NULL) {
11574 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11575 		ire_refrele(ire);
11576 	} else {
11577 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11578 	}
11579 	return (sizeof (struct ip6_mtuinfo));
11580 }
11581 
11582 /*
11583  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11584  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11585  * isn't.  This doesn't matter as the error checking is done properly for the
11586  * other MRT options coming in through ip_opt_set.
11587  */
11588 int
11589 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11590 {
11591 	conn_t		*connp = Q_TO_CONN(q);
11592 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11593 
11594 	switch (level) {
11595 	case IPPROTO_IP:
11596 		switch (name) {
11597 		case MRT_VERSION:
11598 		case MRT_ASSERT:
11599 			(void) ip_mrouter_get(name, q, ptr);
11600 			return (sizeof (int));
11601 		case IP_SEC_OPT:
11602 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11603 		case IP_NEXTHOP:
11604 			if (connp->conn_nexthop_set) {
11605 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11606 				return (sizeof (ipaddr_t));
11607 			} else
11608 				return (0);
11609 		case IP_RECVPKTINFO:
11610 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11611 			return (sizeof (int));
11612 		default:
11613 			break;
11614 		}
11615 		break;
11616 	case IPPROTO_IPV6:
11617 		switch (name) {
11618 		case IPV6_SEC_OPT:
11619 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11620 		case IPV6_SRC_PREFERENCES: {
11621 			return (ip6_get_src_preferences(connp,
11622 			    (uint32_t *)ptr));
11623 		}
11624 		case IPV6_V6ONLY:
11625 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11626 			return (sizeof (int));
11627 		case IPV6_PATHMTU:
11628 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11629 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11630 		default:
11631 			break;
11632 		}
11633 		break;
11634 	default:
11635 		break;
11636 	}
11637 	return (-1);
11638 }
11639 
11640 /* Named Dispatch routine to get a current value out of our parameter table. */
11641 /* ARGSUSED */
11642 static int
11643 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11644 {
11645 	ipparam_t *ippa = (ipparam_t *)cp;
11646 
11647 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11648 	return (0);
11649 }
11650 
11651 /* ARGSUSED */
11652 static int
11653 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11654 {
11655 
11656 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11657 	return (0);
11658 }
11659 
11660 /*
11661  * Set ip{,6}_forwarding values.  This means walking through all of the
11662  * ill's and toggling their forwarding values.
11663  */
11664 /* ARGSUSED */
11665 static int
11666 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11667 {
11668 	long new_value;
11669 	int *forwarding_value = (int *)cp;
11670 	ill_t *ill;
11671 	boolean_t isv6;
11672 	ill_walk_context_t ctx;
11673 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11674 
11675 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11676 
11677 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11678 	    new_value < 0 || new_value > 1) {
11679 		return (EINVAL);
11680 	}
11681 
11682 	*forwarding_value = new_value;
11683 
11684 	/*
11685 	 * Regardless of the current value of ip_forwarding, set all per-ill
11686 	 * values of ip_forwarding to the value being set.
11687 	 *
11688 	 * Bring all the ill's up to date with the new global value.
11689 	 */
11690 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11691 
11692 	if (isv6)
11693 		ill = ILL_START_WALK_V6(&ctx, ipst);
11694 	else
11695 		ill = ILL_START_WALK_V4(&ctx, ipst);
11696 
11697 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11698 		(void) ill_forward_set(ill, new_value != 0);
11699 
11700 	rw_exit(&ipst->ips_ill_g_lock);
11701 	return (0);
11702 }
11703 
11704 /*
11705  * Walk through the param array specified registering each element with the
11706  * Named Dispatch handler. This is called only during init. So it is ok
11707  * not to acquire any locks
11708  */
11709 static boolean_t
11710 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11711     ipndp_t *ipnd, size_t ipnd_cnt)
11712 {
11713 	for (; ippa_cnt-- > 0; ippa++) {
11714 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11715 			if (!nd_load(ndp, ippa->ip_param_name,
11716 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11717 				nd_free(ndp);
11718 				return (B_FALSE);
11719 			}
11720 		}
11721 	}
11722 
11723 	for (; ipnd_cnt-- > 0; ipnd++) {
11724 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11725 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11726 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11727 			    ipnd->ip_ndp_data)) {
11728 				nd_free(ndp);
11729 				return (B_FALSE);
11730 			}
11731 		}
11732 	}
11733 
11734 	return (B_TRUE);
11735 }
11736 
11737 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11738 /* ARGSUSED */
11739 static int
11740 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11741 {
11742 	long		new_value;
11743 	ipparam_t	*ippa = (ipparam_t *)cp;
11744 
11745 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11746 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11747 		return (EINVAL);
11748 	}
11749 	ippa->ip_param_value = new_value;
11750 	return (0);
11751 }
11752 
11753 /*
11754  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11755  * When an ipf is passed here for the first time, if
11756  * we already have in-order fragments on the queue, we convert from the fast-
11757  * path reassembly scheme to the hard-case scheme.  From then on, additional
11758  * fragments are reassembled here.  We keep track of the start and end offsets
11759  * of each piece, and the number of holes in the chain.  When the hole count
11760  * goes to zero, we are done!
11761  *
11762  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11763  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11764  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11765  * after the call to ip_reassemble().
11766  */
11767 int
11768 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11769     size_t msg_len)
11770 {
11771 	uint_t	end;
11772 	mblk_t	*next_mp;
11773 	mblk_t	*mp1;
11774 	uint_t	offset;
11775 	boolean_t incr_dups = B_TRUE;
11776 	boolean_t offset_zero_seen = B_FALSE;
11777 	boolean_t pkt_boundary_checked = B_FALSE;
11778 
11779 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11780 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11781 
11782 	/* Add in byte count */
11783 	ipf->ipf_count += msg_len;
11784 	if (ipf->ipf_end) {
11785 		/*
11786 		 * We were part way through in-order reassembly, but now there
11787 		 * is a hole.  We walk through messages already queued, and
11788 		 * mark them for hard case reassembly.  We know that up till
11789 		 * now they were in order starting from offset zero.
11790 		 */
11791 		offset = 0;
11792 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11793 			IP_REASS_SET_START(mp1, offset);
11794 			if (offset == 0) {
11795 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11796 				offset = -ipf->ipf_nf_hdr_len;
11797 			}
11798 			offset += mp1->b_wptr - mp1->b_rptr;
11799 			IP_REASS_SET_END(mp1, offset);
11800 		}
11801 		/* One hole at the end. */
11802 		ipf->ipf_hole_cnt = 1;
11803 		/* Brand it as a hard case, forever. */
11804 		ipf->ipf_end = 0;
11805 	}
11806 	/* Walk through all the new pieces. */
11807 	do {
11808 		end = start + (mp->b_wptr - mp->b_rptr);
11809 		/*
11810 		 * If start is 0, decrease 'end' only for the first mblk of
11811 		 * the fragment. Otherwise 'end' can get wrong value in the
11812 		 * second pass of the loop if first mblk is exactly the
11813 		 * size of ipf_nf_hdr_len.
11814 		 */
11815 		if (start == 0 && !offset_zero_seen) {
11816 			/* First segment */
11817 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11818 			end -= ipf->ipf_nf_hdr_len;
11819 			offset_zero_seen = B_TRUE;
11820 		}
11821 		next_mp = mp->b_cont;
11822 		/*
11823 		 * We are checking to see if there is any interesing data
11824 		 * to process.  If there isn't and the mblk isn't the
11825 		 * one which carries the unfragmentable header then we
11826 		 * drop it.  It's possible to have just the unfragmentable
11827 		 * header come through without any data.  That needs to be
11828 		 * saved.
11829 		 *
11830 		 * If the assert at the top of this function holds then the
11831 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11832 		 * is infrequently traveled enough that the test is left in
11833 		 * to protect against future code changes which break that
11834 		 * invariant.
11835 		 */
11836 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11837 			/* Empty.  Blast it. */
11838 			IP_REASS_SET_START(mp, 0);
11839 			IP_REASS_SET_END(mp, 0);
11840 			/*
11841 			 * If the ipf points to the mblk we are about to free,
11842 			 * update ipf to point to the next mblk (or NULL
11843 			 * if none).
11844 			 */
11845 			if (ipf->ipf_mp->b_cont == mp)
11846 				ipf->ipf_mp->b_cont = next_mp;
11847 			freeb(mp);
11848 			continue;
11849 		}
11850 		mp->b_cont = NULL;
11851 		IP_REASS_SET_START(mp, start);
11852 		IP_REASS_SET_END(mp, end);
11853 		if (!ipf->ipf_tail_mp) {
11854 			ipf->ipf_tail_mp = mp;
11855 			ipf->ipf_mp->b_cont = mp;
11856 			if (start == 0 || !more) {
11857 				ipf->ipf_hole_cnt = 1;
11858 				/*
11859 				 * if the first fragment comes in more than one
11860 				 * mblk, this loop will be executed for each
11861 				 * mblk. Need to adjust hole count so exiting
11862 				 * this routine will leave hole count at 1.
11863 				 */
11864 				if (next_mp)
11865 					ipf->ipf_hole_cnt++;
11866 			} else
11867 				ipf->ipf_hole_cnt = 2;
11868 			continue;
11869 		} else if (ipf->ipf_last_frag_seen && !more &&
11870 		    !pkt_boundary_checked) {
11871 			/*
11872 			 * We check datagram boundary only if this fragment
11873 			 * claims to be the last fragment and we have seen a
11874 			 * last fragment in the past too. We do this only
11875 			 * once for a given fragment.
11876 			 *
11877 			 * start cannot be 0 here as fragments with start=0
11878 			 * and MF=0 gets handled as a complete packet. These
11879 			 * fragments should not reach here.
11880 			 */
11881 
11882 			if (start + msgdsize(mp) !=
11883 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11884 				/*
11885 				 * We have two fragments both of which claim
11886 				 * to be the last fragment but gives conflicting
11887 				 * information about the whole datagram size.
11888 				 * Something fishy is going on. Drop the
11889 				 * fragment and free up the reassembly list.
11890 				 */
11891 				return (IP_REASS_FAILED);
11892 			}
11893 
11894 			/*
11895 			 * We shouldn't come to this code block again for this
11896 			 * particular fragment.
11897 			 */
11898 			pkt_boundary_checked = B_TRUE;
11899 		}
11900 
11901 		/* New stuff at or beyond tail? */
11902 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11903 		if (start >= offset) {
11904 			if (ipf->ipf_last_frag_seen) {
11905 				/* current fragment is beyond last fragment */
11906 				return (IP_REASS_FAILED);
11907 			}
11908 			/* Link it on end. */
11909 			ipf->ipf_tail_mp->b_cont = mp;
11910 			ipf->ipf_tail_mp = mp;
11911 			if (more) {
11912 				if (start != offset)
11913 					ipf->ipf_hole_cnt++;
11914 			} else if (start == offset && next_mp == NULL)
11915 					ipf->ipf_hole_cnt--;
11916 			continue;
11917 		}
11918 		mp1 = ipf->ipf_mp->b_cont;
11919 		offset = IP_REASS_START(mp1);
11920 		/* New stuff at the front? */
11921 		if (start < offset) {
11922 			if (start == 0) {
11923 				if (end >= offset) {
11924 					/* Nailed the hole at the begining. */
11925 					ipf->ipf_hole_cnt--;
11926 				}
11927 			} else if (end < offset) {
11928 				/*
11929 				 * A hole, stuff, and a hole where there used
11930 				 * to be just a hole.
11931 				 */
11932 				ipf->ipf_hole_cnt++;
11933 			}
11934 			mp->b_cont = mp1;
11935 			/* Check for overlap. */
11936 			while (end > offset) {
11937 				if (end < IP_REASS_END(mp1)) {
11938 					mp->b_wptr -= end - offset;
11939 					IP_REASS_SET_END(mp, offset);
11940 					BUMP_MIB(ill->ill_ip_mib,
11941 					    ipIfStatsReasmPartDups);
11942 					break;
11943 				}
11944 				/* Did we cover another hole? */
11945 				if ((mp1->b_cont &&
11946 				    IP_REASS_END(mp1) !=
11947 				    IP_REASS_START(mp1->b_cont) &&
11948 				    end >= IP_REASS_START(mp1->b_cont)) ||
11949 				    (!ipf->ipf_last_frag_seen && !more)) {
11950 					ipf->ipf_hole_cnt--;
11951 				}
11952 				/* Clip out mp1. */
11953 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11954 					/*
11955 					 * After clipping out mp1, this guy
11956 					 * is now hanging off the end.
11957 					 */
11958 					ipf->ipf_tail_mp = mp;
11959 				}
11960 				IP_REASS_SET_START(mp1, 0);
11961 				IP_REASS_SET_END(mp1, 0);
11962 				/* Subtract byte count */
11963 				ipf->ipf_count -= mp1->b_datap->db_lim -
11964 				    mp1->b_datap->db_base;
11965 				freeb(mp1);
11966 				BUMP_MIB(ill->ill_ip_mib,
11967 				    ipIfStatsReasmPartDups);
11968 				mp1 = mp->b_cont;
11969 				if (!mp1)
11970 					break;
11971 				offset = IP_REASS_START(mp1);
11972 			}
11973 			ipf->ipf_mp->b_cont = mp;
11974 			continue;
11975 		}
11976 		/*
11977 		 * The new piece starts somewhere between the start of the head
11978 		 * and before the end of the tail.
11979 		 */
11980 		for (; mp1; mp1 = mp1->b_cont) {
11981 			offset = IP_REASS_END(mp1);
11982 			if (start < offset) {
11983 				if (end <= offset) {
11984 					/* Nothing new. */
11985 					IP_REASS_SET_START(mp, 0);
11986 					IP_REASS_SET_END(mp, 0);
11987 					/* Subtract byte count */
11988 					ipf->ipf_count -= mp->b_datap->db_lim -
11989 					    mp->b_datap->db_base;
11990 					if (incr_dups) {
11991 						ipf->ipf_num_dups++;
11992 						incr_dups = B_FALSE;
11993 					}
11994 					freeb(mp);
11995 					BUMP_MIB(ill->ill_ip_mib,
11996 					    ipIfStatsReasmDuplicates);
11997 					break;
11998 				}
11999 				/*
12000 				 * Trim redundant stuff off beginning of new
12001 				 * piece.
12002 				 */
12003 				IP_REASS_SET_START(mp, offset);
12004 				mp->b_rptr += offset - start;
12005 				BUMP_MIB(ill->ill_ip_mib,
12006 				    ipIfStatsReasmPartDups);
12007 				start = offset;
12008 				if (!mp1->b_cont) {
12009 					/*
12010 					 * After trimming, this guy is now
12011 					 * hanging off the end.
12012 					 */
12013 					mp1->b_cont = mp;
12014 					ipf->ipf_tail_mp = mp;
12015 					if (!more) {
12016 						ipf->ipf_hole_cnt--;
12017 					}
12018 					break;
12019 				}
12020 			}
12021 			if (start >= IP_REASS_START(mp1->b_cont))
12022 				continue;
12023 			/* Fill a hole */
12024 			if (start > offset)
12025 				ipf->ipf_hole_cnt++;
12026 			mp->b_cont = mp1->b_cont;
12027 			mp1->b_cont = mp;
12028 			mp1 = mp->b_cont;
12029 			offset = IP_REASS_START(mp1);
12030 			if (end >= offset) {
12031 				ipf->ipf_hole_cnt--;
12032 				/* Check for overlap. */
12033 				while (end > offset) {
12034 					if (end < IP_REASS_END(mp1)) {
12035 						mp->b_wptr -= end - offset;
12036 						IP_REASS_SET_END(mp, offset);
12037 						/*
12038 						 * TODO we might bump
12039 						 * this up twice if there is
12040 						 * overlap at both ends.
12041 						 */
12042 						BUMP_MIB(ill->ill_ip_mib,
12043 						    ipIfStatsReasmPartDups);
12044 						break;
12045 					}
12046 					/* Did we cover another hole? */
12047 					if ((mp1->b_cont &&
12048 					    IP_REASS_END(mp1)
12049 					    != IP_REASS_START(mp1->b_cont) &&
12050 					    end >=
12051 					    IP_REASS_START(mp1->b_cont)) ||
12052 					    (!ipf->ipf_last_frag_seen &&
12053 					    !more)) {
12054 						ipf->ipf_hole_cnt--;
12055 					}
12056 					/* Clip out mp1. */
12057 					if ((mp->b_cont = mp1->b_cont) ==
12058 					    NULL) {
12059 						/*
12060 						 * After clipping out mp1,
12061 						 * this guy is now hanging
12062 						 * off the end.
12063 						 */
12064 						ipf->ipf_tail_mp = mp;
12065 					}
12066 					IP_REASS_SET_START(mp1, 0);
12067 					IP_REASS_SET_END(mp1, 0);
12068 					/* Subtract byte count */
12069 					ipf->ipf_count -=
12070 					    mp1->b_datap->db_lim -
12071 					    mp1->b_datap->db_base;
12072 					freeb(mp1);
12073 					BUMP_MIB(ill->ill_ip_mib,
12074 					    ipIfStatsReasmPartDups);
12075 					mp1 = mp->b_cont;
12076 					if (!mp1)
12077 						break;
12078 					offset = IP_REASS_START(mp1);
12079 				}
12080 			}
12081 			break;
12082 		}
12083 	} while (start = end, mp = next_mp);
12084 
12085 	/* Fragment just processed could be the last one. Remember this fact */
12086 	if (!more)
12087 		ipf->ipf_last_frag_seen = B_TRUE;
12088 
12089 	/* Still got holes? */
12090 	if (ipf->ipf_hole_cnt)
12091 		return (IP_REASS_PARTIAL);
12092 	/* Clean up overloaded fields to avoid upstream disasters. */
12093 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12094 		IP_REASS_SET_START(mp1, 0);
12095 		IP_REASS_SET_END(mp1, 0);
12096 	}
12097 	return (IP_REASS_COMPLETE);
12098 }
12099 
12100 /*
12101  * ipsec processing for the fast path, used for input UDP Packets
12102  * Returns true if ready for passup to UDP.
12103  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12104  * was an ESP-in-UDP packet, etc.).
12105  */
12106 static boolean_t
12107 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12108     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12109 {
12110 	uint32_t	ill_index;
12111 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12112 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12113 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12114 	udp_t		*udp = connp->conn_udp;
12115 
12116 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12117 	/* The ill_index of the incoming ILL */
12118 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12119 
12120 	/* pass packet up to the transport */
12121 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12122 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12123 		    NULL, mctl_present);
12124 		if (*first_mpp == NULL) {
12125 			return (B_FALSE);
12126 		}
12127 	}
12128 
12129 	/* Initiate IPPF processing for fastpath UDP */
12130 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12131 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12132 		if (*mpp == NULL) {
12133 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12134 			    "deferred/dropped during IPPF processing\n"));
12135 			return (B_FALSE);
12136 		}
12137 	}
12138 	/*
12139 	 * Remove 0-spi if it's 0, or move everything behind
12140 	 * the UDP header over it and forward to ESP via
12141 	 * ip_proto_input().
12142 	 */
12143 	if (udp->udp_nat_t_endpoint) {
12144 		if (mctl_present) {
12145 			/* mctl_present *shouldn't* happen. */
12146 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12147 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12148 			    &ipss->ipsec_dropper);
12149 			*first_mpp = NULL;
12150 			return (B_FALSE);
12151 		}
12152 
12153 		/* "ill" is "recv_ill" in actuality. */
12154 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12155 			return (B_FALSE);
12156 
12157 		/* Else continue like a normal UDP packet. */
12158 	}
12159 
12160 	/*
12161 	 * We make the checks as below since we are in the fast path
12162 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12163 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12164 	 */
12165 	if (connp->conn_recvif || connp->conn_recvslla ||
12166 	    connp->conn_ip_recvpktinfo) {
12167 		if (connp->conn_recvif) {
12168 			in_flags = IPF_RECVIF;
12169 		}
12170 		/*
12171 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12172 		 * so the flag passed to ip_add_info is based on IP version
12173 		 * of connp.
12174 		 */
12175 		if (connp->conn_ip_recvpktinfo) {
12176 			if (connp->conn_af_isv6) {
12177 				/*
12178 				 * V6 only needs index
12179 				 */
12180 				in_flags |= IPF_RECVIF;
12181 			} else {
12182 				/*
12183 				 * V4 needs index + matching address.
12184 				 */
12185 				in_flags |= IPF_RECVADDR;
12186 			}
12187 		}
12188 		if (connp->conn_recvslla) {
12189 			in_flags |= IPF_RECVSLLA;
12190 		}
12191 		/*
12192 		 * since in_flags are being set ill will be
12193 		 * referenced in ip_add_info, so it better not
12194 		 * be NULL.
12195 		 */
12196 		/*
12197 		 * the actual data will be contained in b_cont
12198 		 * upon successful return of the following call.
12199 		 * If the call fails then the original mblk is
12200 		 * returned.
12201 		 */
12202 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12203 		    ipst);
12204 	}
12205 
12206 	return (B_TRUE);
12207 }
12208 
12209 /*
12210  * Fragmentation reassembly.  Each ILL has a hash table for
12211  * queuing packets undergoing reassembly for all IPIFs
12212  * associated with the ILL.  The hash is based on the packet
12213  * IP ident field.  The ILL frag hash table was allocated
12214  * as a timer block at the time the ILL was created.  Whenever
12215  * there is anything on the reassembly queue, the timer will
12216  * be running.  Returns B_TRUE if successful else B_FALSE;
12217  * frees mp on failure.
12218  */
12219 static boolean_t
12220 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12221     uint32_t *cksum_val, uint16_t *cksum_flags)
12222 {
12223 	uint32_t	frag_offset_flags;
12224 	ill_t		*ill = (ill_t *)q->q_ptr;
12225 	mblk_t		*mp = *mpp;
12226 	mblk_t		*t_mp;
12227 	ipaddr_t	dst;
12228 	uint8_t		proto = ipha->ipha_protocol;
12229 	uint32_t	sum_val;
12230 	uint16_t	sum_flags;
12231 	ipf_t		*ipf;
12232 	ipf_t		**ipfp;
12233 	ipfb_t		*ipfb;
12234 	uint16_t	ident;
12235 	uint32_t	offset;
12236 	ipaddr_t	src;
12237 	uint_t		hdr_length;
12238 	uint32_t	end;
12239 	mblk_t		*mp1;
12240 	mblk_t		*tail_mp;
12241 	size_t		count;
12242 	size_t		msg_len;
12243 	uint8_t		ecn_info = 0;
12244 	uint32_t	packet_size;
12245 	boolean_t	pruned = B_FALSE;
12246 	ip_stack_t *ipst = ill->ill_ipst;
12247 
12248 	if (cksum_val != NULL)
12249 		*cksum_val = 0;
12250 	if (cksum_flags != NULL)
12251 		*cksum_flags = 0;
12252 
12253 	/*
12254 	 * Drop the fragmented as early as possible, if
12255 	 * we don't have resource(s) to re-assemble.
12256 	 */
12257 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12258 		freemsg(mp);
12259 		return (B_FALSE);
12260 	}
12261 
12262 	/* Check for fragmentation offset; return if there's none */
12263 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12264 	    (IPH_MF | IPH_OFFSET)) == 0)
12265 		return (B_TRUE);
12266 
12267 	/*
12268 	 * We utilize hardware computed checksum info only for UDP since
12269 	 * IP fragmentation is a normal occurence for the protocol.  In
12270 	 * addition, checksum offload support for IP fragments carrying
12271 	 * UDP payload is commonly implemented across network adapters.
12272 	 */
12273 	ASSERT(ill != NULL);
12274 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12275 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12276 		mblk_t *mp1 = mp->b_cont;
12277 		int32_t len;
12278 
12279 		/* Record checksum information from the packet */
12280 		sum_val = (uint32_t)DB_CKSUM16(mp);
12281 		sum_flags = DB_CKSUMFLAGS(mp);
12282 
12283 		/* IP payload offset from beginning of mblk */
12284 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12285 
12286 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12287 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12288 		    offset >= DB_CKSUMSTART(mp) &&
12289 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12290 			uint32_t adj;
12291 			/*
12292 			 * Partial checksum has been calculated by hardware
12293 			 * and attached to the packet; in addition, any
12294 			 * prepended extraneous data is even byte aligned.
12295 			 * If any such data exists, we adjust the checksum;
12296 			 * this would also handle any postpended data.
12297 			 */
12298 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12299 			    mp, mp1, len, adj);
12300 
12301 			/* One's complement subtract extraneous checksum */
12302 			if (adj >= sum_val)
12303 				sum_val = ~(adj - sum_val) & 0xFFFF;
12304 			else
12305 				sum_val -= adj;
12306 		}
12307 	} else {
12308 		sum_val = 0;
12309 		sum_flags = 0;
12310 	}
12311 
12312 	/* Clear hardware checksumming flag */
12313 	DB_CKSUMFLAGS(mp) = 0;
12314 
12315 	ident = ipha->ipha_ident;
12316 	offset = (frag_offset_flags << 3) & 0xFFFF;
12317 	src = ipha->ipha_src;
12318 	dst = ipha->ipha_dst;
12319 	hdr_length = IPH_HDR_LENGTH(ipha);
12320 	end = ntohs(ipha->ipha_length) - hdr_length;
12321 
12322 	/* If end == 0 then we have a packet with no data, so just free it */
12323 	if (end == 0) {
12324 		freemsg(mp);
12325 		return (B_FALSE);
12326 	}
12327 
12328 	/* Record the ECN field info. */
12329 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12330 	if (offset != 0) {
12331 		/*
12332 		 * If this isn't the first piece, strip the header, and
12333 		 * add the offset to the end value.
12334 		 */
12335 		mp->b_rptr += hdr_length;
12336 		end += offset;
12337 	}
12338 
12339 	msg_len = MBLKSIZE(mp);
12340 	tail_mp = mp;
12341 	while (tail_mp->b_cont != NULL) {
12342 		tail_mp = tail_mp->b_cont;
12343 		msg_len += MBLKSIZE(tail_mp);
12344 	}
12345 
12346 	/* If the reassembly list for this ILL will get too big, prune it */
12347 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12348 	    ipst->ips_ip_reass_queue_bytes) {
12349 		ill_frag_prune(ill,
12350 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12351 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12352 		pruned = B_TRUE;
12353 	}
12354 
12355 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12356 	mutex_enter(&ipfb->ipfb_lock);
12357 
12358 	ipfp = &ipfb->ipfb_ipf;
12359 	/* Try to find an existing fragment queue for this packet. */
12360 	for (;;) {
12361 		ipf = ipfp[0];
12362 		if (ipf != NULL) {
12363 			/*
12364 			 * It has to match on ident and src/dst address.
12365 			 */
12366 			if (ipf->ipf_ident == ident &&
12367 			    ipf->ipf_src == src &&
12368 			    ipf->ipf_dst == dst &&
12369 			    ipf->ipf_protocol == proto) {
12370 				/*
12371 				 * If we have received too many
12372 				 * duplicate fragments for this packet
12373 				 * free it.
12374 				 */
12375 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12376 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12377 					freemsg(mp);
12378 					mutex_exit(&ipfb->ipfb_lock);
12379 					return (B_FALSE);
12380 				}
12381 				/* Found it. */
12382 				break;
12383 			}
12384 			ipfp = &ipf->ipf_hash_next;
12385 			continue;
12386 		}
12387 
12388 		/*
12389 		 * If we pruned the list, do we want to store this new
12390 		 * fragment?. We apply an optimization here based on the
12391 		 * fact that most fragments will be received in order.
12392 		 * So if the offset of this incoming fragment is zero,
12393 		 * it is the first fragment of a new packet. We will
12394 		 * keep it.  Otherwise drop the fragment, as we have
12395 		 * probably pruned the packet already (since the
12396 		 * packet cannot be found).
12397 		 */
12398 		if (pruned && offset != 0) {
12399 			mutex_exit(&ipfb->ipfb_lock);
12400 			freemsg(mp);
12401 			return (B_FALSE);
12402 		}
12403 
12404 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12405 			/*
12406 			 * Too many fragmented packets in this hash
12407 			 * bucket. Free the oldest.
12408 			 */
12409 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12410 		}
12411 
12412 		/* New guy.  Allocate a frag message. */
12413 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12414 		if (mp1 == NULL) {
12415 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12416 			freemsg(mp);
12417 reass_done:
12418 			mutex_exit(&ipfb->ipfb_lock);
12419 			return (B_FALSE);
12420 		}
12421 
12422 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12423 		mp1->b_cont = mp;
12424 
12425 		/* Initialize the fragment header. */
12426 		ipf = (ipf_t *)mp1->b_rptr;
12427 		ipf->ipf_mp = mp1;
12428 		ipf->ipf_ptphn = ipfp;
12429 		ipfp[0] = ipf;
12430 		ipf->ipf_hash_next = NULL;
12431 		ipf->ipf_ident = ident;
12432 		ipf->ipf_protocol = proto;
12433 		ipf->ipf_src = src;
12434 		ipf->ipf_dst = dst;
12435 		ipf->ipf_nf_hdr_len = 0;
12436 		/* Record reassembly start time. */
12437 		ipf->ipf_timestamp = gethrestime_sec();
12438 		/* Record ipf generation and account for frag header */
12439 		ipf->ipf_gen = ill->ill_ipf_gen++;
12440 		ipf->ipf_count = MBLKSIZE(mp1);
12441 		ipf->ipf_last_frag_seen = B_FALSE;
12442 		ipf->ipf_ecn = ecn_info;
12443 		ipf->ipf_num_dups = 0;
12444 		ipfb->ipfb_frag_pkts++;
12445 		ipf->ipf_checksum = 0;
12446 		ipf->ipf_checksum_flags = 0;
12447 
12448 		/* Store checksum value in fragment header */
12449 		if (sum_flags != 0) {
12450 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12451 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12452 			ipf->ipf_checksum = sum_val;
12453 			ipf->ipf_checksum_flags = sum_flags;
12454 		}
12455 
12456 		/*
12457 		 * We handle reassembly two ways.  In the easy case,
12458 		 * where all the fragments show up in order, we do
12459 		 * minimal bookkeeping, and just clip new pieces on
12460 		 * the end.  If we ever see a hole, then we go off
12461 		 * to ip_reassemble which has to mark the pieces and
12462 		 * keep track of the number of holes, etc.  Obviously,
12463 		 * the point of having both mechanisms is so we can
12464 		 * handle the easy case as efficiently as possible.
12465 		 */
12466 		if (offset == 0) {
12467 			/* Easy case, in-order reassembly so far. */
12468 			ipf->ipf_count += msg_len;
12469 			ipf->ipf_tail_mp = tail_mp;
12470 			/*
12471 			 * Keep track of next expected offset in
12472 			 * ipf_end.
12473 			 */
12474 			ipf->ipf_end = end;
12475 			ipf->ipf_nf_hdr_len = hdr_length;
12476 		} else {
12477 			/* Hard case, hole at the beginning. */
12478 			ipf->ipf_tail_mp = NULL;
12479 			/*
12480 			 * ipf_end == 0 means that we have given up
12481 			 * on easy reassembly.
12482 			 */
12483 			ipf->ipf_end = 0;
12484 
12485 			/* Forget checksum offload from now on */
12486 			ipf->ipf_checksum_flags = 0;
12487 
12488 			/*
12489 			 * ipf_hole_cnt is set by ip_reassemble.
12490 			 * ipf_count is updated by ip_reassemble.
12491 			 * No need to check for return value here
12492 			 * as we don't expect reassembly to complete
12493 			 * or fail for the first fragment itself.
12494 			 */
12495 			(void) ip_reassemble(mp, ipf,
12496 			    (frag_offset_flags & IPH_OFFSET) << 3,
12497 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12498 		}
12499 		/* Update per ipfb and ill byte counts */
12500 		ipfb->ipfb_count += ipf->ipf_count;
12501 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12502 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12503 		/* If the frag timer wasn't already going, start it. */
12504 		mutex_enter(&ill->ill_lock);
12505 		ill_frag_timer_start(ill);
12506 		mutex_exit(&ill->ill_lock);
12507 		goto reass_done;
12508 	}
12509 
12510 	/*
12511 	 * If the packet's flag has changed (it could be coming up
12512 	 * from an interface different than the previous, therefore
12513 	 * possibly different checksum capability), then forget about
12514 	 * any stored checksum states.  Otherwise add the value to
12515 	 * the existing one stored in the fragment header.
12516 	 */
12517 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12518 		sum_val += ipf->ipf_checksum;
12519 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12520 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12521 		ipf->ipf_checksum = sum_val;
12522 	} else if (ipf->ipf_checksum_flags != 0) {
12523 		/* Forget checksum offload from now on */
12524 		ipf->ipf_checksum_flags = 0;
12525 	}
12526 
12527 	/*
12528 	 * We have a new piece of a datagram which is already being
12529 	 * reassembled.  Update the ECN info if all IP fragments
12530 	 * are ECN capable.  If there is one which is not, clear
12531 	 * all the info.  If there is at least one which has CE
12532 	 * code point, IP needs to report that up to transport.
12533 	 */
12534 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12535 		if (ecn_info == IPH_ECN_CE)
12536 			ipf->ipf_ecn = IPH_ECN_CE;
12537 	} else {
12538 		ipf->ipf_ecn = IPH_ECN_NECT;
12539 	}
12540 	if (offset && ipf->ipf_end == offset) {
12541 		/* The new fragment fits at the end */
12542 		ipf->ipf_tail_mp->b_cont = mp;
12543 		/* Update the byte count */
12544 		ipf->ipf_count += msg_len;
12545 		/* Update per ipfb and ill byte counts */
12546 		ipfb->ipfb_count += msg_len;
12547 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12548 		atomic_add_32(&ill->ill_frag_count, msg_len);
12549 		if (frag_offset_flags & IPH_MF) {
12550 			/* More to come. */
12551 			ipf->ipf_end = end;
12552 			ipf->ipf_tail_mp = tail_mp;
12553 			goto reass_done;
12554 		}
12555 	} else {
12556 		/* Go do the hard cases. */
12557 		int ret;
12558 
12559 		if (offset == 0)
12560 			ipf->ipf_nf_hdr_len = hdr_length;
12561 
12562 		/* Save current byte count */
12563 		count = ipf->ipf_count;
12564 		ret = ip_reassemble(mp, ipf,
12565 		    (frag_offset_flags & IPH_OFFSET) << 3,
12566 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12567 		/* Count of bytes added and subtracted (freeb()ed) */
12568 		count = ipf->ipf_count - count;
12569 		if (count) {
12570 			/* Update per ipfb and ill byte counts */
12571 			ipfb->ipfb_count += count;
12572 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12573 			atomic_add_32(&ill->ill_frag_count, count);
12574 		}
12575 		if (ret == IP_REASS_PARTIAL) {
12576 			goto reass_done;
12577 		} else if (ret == IP_REASS_FAILED) {
12578 			/* Reassembly failed. Free up all resources */
12579 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12580 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12581 				IP_REASS_SET_START(t_mp, 0);
12582 				IP_REASS_SET_END(t_mp, 0);
12583 			}
12584 			freemsg(mp);
12585 			goto reass_done;
12586 		}
12587 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12588 	}
12589 	/*
12590 	 * We have completed reassembly.  Unhook the frag header from
12591 	 * the reassembly list.
12592 	 *
12593 	 * Before we free the frag header, record the ECN info
12594 	 * to report back to the transport.
12595 	 */
12596 	ecn_info = ipf->ipf_ecn;
12597 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12598 	ipfp = ipf->ipf_ptphn;
12599 
12600 	/* We need to supply these to caller */
12601 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12602 		sum_val = ipf->ipf_checksum;
12603 	else
12604 		sum_val = 0;
12605 
12606 	mp1 = ipf->ipf_mp;
12607 	count = ipf->ipf_count;
12608 	ipf = ipf->ipf_hash_next;
12609 	if (ipf != NULL)
12610 		ipf->ipf_ptphn = ipfp;
12611 	ipfp[0] = ipf;
12612 	atomic_add_32(&ill->ill_frag_count, -count);
12613 	ASSERT(ipfb->ipfb_count >= count);
12614 	ipfb->ipfb_count -= count;
12615 	ipfb->ipfb_frag_pkts--;
12616 	mutex_exit(&ipfb->ipfb_lock);
12617 	/* Ditch the frag header. */
12618 	mp = mp1->b_cont;
12619 
12620 	freeb(mp1);
12621 
12622 	/* Restore original IP length in header. */
12623 	packet_size = (uint32_t)msgdsize(mp);
12624 	if (packet_size > IP_MAXPACKET) {
12625 		freemsg(mp);
12626 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12627 		return (B_FALSE);
12628 	}
12629 
12630 	if (DB_REF(mp) > 1) {
12631 		mblk_t *mp2 = copymsg(mp);
12632 
12633 		freemsg(mp);
12634 		if (mp2 == NULL) {
12635 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12636 			return (B_FALSE);
12637 		}
12638 		mp = mp2;
12639 	}
12640 	ipha = (ipha_t *)mp->b_rptr;
12641 
12642 	ipha->ipha_length = htons((uint16_t)packet_size);
12643 	/* We're now complete, zip the frag state */
12644 	ipha->ipha_fragment_offset_and_flags = 0;
12645 	/* Record the ECN info. */
12646 	ipha->ipha_type_of_service &= 0xFC;
12647 	ipha->ipha_type_of_service |= ecn_info;
12648 	*mpp = mp;
12649 
12650 	/* Reassembly is successful; return checksum information if needed */
12651 	if (cksum_val != NULL)
12652 		*cksum_val = sum_val;
12653 	if (cksum_flags != NULL)
12654 		*cksum_flags = sum_flags;
12655 
12656 	return (B_TRUE);
12657 }
12658 
12659 /*
12660  * Perform ip header check sum update local options.
12661  * return B_TRUE if all is well, else return B_FALSE and release
12662  * the mp. caller is responsible for decrementing ire ref cnt.
12663  */
12664 static boolean_t
12665 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12666     ip_stack_t *ipst)
12667 {
12668 	mblk_t		*first_mp;
12669 	boolean_t	mctl_present;
12670 	uint16_t	sum;
12671 
12672 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12673 	/*
12674 	 * Don't do the checksum if it has gone through AH/ESP
12675 	 * processing.
12676 	 */
12677 	if (!mctl_present) {
12678 		sum = ip_csum_hdr(ipha);
12679 		if (sum != 0) {
12680 			if (ill != NULL) {
12681 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12682 			} else {
12683 				BUMP_MIB(&ipst->ips_ip_mib,
12684 				    ipIfStatsInCksumErrs);
12685 			}
12686 			freemsg(first_mp);
12687 			return (B_FALSE);
12688 		}
12689 	}
12690 
12691 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12692 		if (mctl_present)
12693 			freeb(first_mp);
12694 		return (B_FALSE);
12695 	}
12696 
12697 	return (B_TRUE);
12698 }
12699 
12700 /*
12701  * All udp packet are delivered to the local host via this routine.
12702  */
12703 void
12704 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12705     ill_t *recv_ill)
12706 {
12707 	uint32_t	sum;
12708 	uint32_t	u1;
12709 	boolean_t	mctl_present;
12710 	conn_t		*connp;
12711 	mblk_t		*first_mp;
12712 	uint16_t	*up;
12713 	ill_t		*ill = (ill_t *)q->q_ptr;
12714 	uint16_t	reass_hck_flags = 0;
12715 	ip_stack_t	*ipst;
12716 
12717 	ASSERT(recv_ill != NULL);
12718 	ipst = recv_ill->ill_ipst;
12719 
12720 #define	rptr    ((uchar_t *)ipha)
12721 
12722 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12723 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12724 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12725 	ASSERT(ill != NULL);
12726 
12727 	/*
12728 	 * FAST PATH for udp packets
12729 	 */
12730 
12731 	/* u1 is # words of IP options */
12732 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12733 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12734 
12735 	/* IP options present */
12736 	if (u1 != 0)
12737 		goto ipoptions;
12738 
12739 	/* Check the IP header checksum.  */
12740 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12741 		/* Clear the IP header h/w cksum flag */
12742 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12743 	} else if (!mctl_present) {
12744 		/*
12745 		 * Don't verify header checksum if this packet is coming
12746 		 * back from AH/ESP as we already did it.
12747 		 */
12748 #define	uph	((uint16_t *)ipha)
12749 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12750 		    uph[6] + uph[7] + uph[8] + uph[9];
12751 #undef	uph
12752 		/* finish doing IP checksum */
12753 		sum = (sum & 0xFFFF) + (sum >> 16);
12754 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12755 		if (sum != 0 && sum != 0xFFFF) {
12756 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12757 			freemsg(first_mp);
12758 			return;
12759 		}
12760 	}
12761 
12762 	/*
12763 	 * Count for SNMP of inbound packets for ire.
12764 	 * if mctl is present this might be a secure packet and
12765 	 * has already been counted for in ip_proto_input().
12766 	 */
12767 	if (!mctl_present) {
12768 		UPDATE_IB_PKT_COUNT(ire);
12769 		ire->ire_last_used_time = lbolt;
12770 	}
12771 
12772 	/* packet part of fragmented IP packet? */
12773 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12774 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12775 		goto fragmented;
12776 	}
12777 
12778 	/* u1 = IP header length (20 bytes) */
12779 	u1 = IP_SIMPLE_HDR_LENGTH;
12780 
12781 	/* packet does not contain complete IP & UDP headers */
12782 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12783 		goto udppullup;
12784 
12785 	/* up points to UDP header */
12786 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12787 #define	iphs    ((uint16_t *)ipha)
12788 
12789 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12790 	if (up[3] != 0) {
12791 		mblk_t *mp1 = mp->b_cont;
12792 		boolean_t cksum_err;
12793 		uint16_t hck_flags = 0;
12794 
12795 		/* Pseudo-header checksum */
12796 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12797 		    iphs[9] + up[2];
12798 
12799 		/*
12800 		 * Revert to software checksum calculation if the interface
12801 		 * isn't capable of checksum offload or if IPsec is present.
12802 		 */
12803 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12804 			hck_flags = DB_CKSUMFLAGS(mp);
12805 
12806 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12807 			IP_STAT(ipst, ip_in_sw_cksum);
12808 
12809 		IP_CKSUM_RECV(hck_flags, u1,
12810 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12811 		    (int32_t)((uchar_t *)up - rptr),
12812 		    mp, mp1, cksum_err);
12813 
12814 		if (cksum_err) {
12815 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12816 			if (hck_flags & HCK_FULLCKSUM)
12817 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12818 			else if (hck_flags & HCK_PARTIALCKSUM)
12819 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12820 			else
12821 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12822 
12823 			freemsg(first_mp);
12824 			return;
12825 		}
12826 	}
12827 
12828 	/* Non-fragmented broadcast or multicast packet? */
12829 	if (ire->ire_type == IRE_BROADCAST)
12830 		goto udpslowpath;
12831 
12832 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12833 	    ire->ire_zoneid, ipst)) != NULL) {
12834 		ASSERT(connp->conn_upq != NULL);
12835 		IP_STAT(ipst, ip_udp_fast_path);
12836 
12837 		if (CONN_UDP_FLOWCTLD(connp)) {
12838 			freemsg(mp);
12839 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12840 		} else {
12841 			if (!mctl_present) {
12842 				BUMP_MIB(ill->ill_ip_mib,
12843 				    ipIfStatsHCInDelivers);
12844 			}
12845 			/*
12846 			 * mp and first_mp can change.
12847 			 */
12848 			if (ip_udp_check(q, connp, recv_ill,
12849 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12850 				/* Send it upstream */
12851 				(connp->conn_recv)(connp, mp, NULL);
12852 			}
12853 		}
12854 		/*
12855 		 * freeb() cannot deal with null mblk being passed
12856 		 * in and first_mp can be set to null in the call
12857 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12858 		 */
12859 		if (mctl_present && first_mp != NULL) {
12860 			freeb(first_mp);
12861 		}
12862 		CONN_DEC_REF(connp);
12863 		return;
12864 	}
12865 
12866 	/*
12867 	 * if we got here we know the packet is not fragmented and
12868 	 * has no options. The classifier could not find a conn_t and
12869 	 * most likely its an icmp packet so send it through slow path.
12870 	 */
12871 
12872 	goto udpslowpath;
12873 
12874 ipoptions:
12875 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12876 		goto slow_done;
12877 	}
12878 
12879 	UPDATE_IB_PKT_COUNT(ire);
12880 	ire->ire_last_used_time = lbolt;
12881 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12882 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12883 fragmented:
12884 		/*
12885 		 * "sum" and "reass_hck_flags" are non-zero if the
12886 		 * reassembled packet has a valid hardware computed
12887 		 * checksum information associated with it.
12888 		 */
12889 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12890 			goto slow_done;
12891 		/*
12892 		 * Make sure that first_mp points back to mp as
12893 		 * the mp we came in with could have changed in
12894 		 * ip_rput_fragment().
12895 		 */
12896 		ASSERT(!mctl_present);
12897 		ipha = (ipha_t *)mp->b_rptr;
12898 		first_mp = mp;
12899 	}
12900 
12901 	/* Now we have a complete datagram, destined for this machine. */
12902 	u1 = IPH_HDR_LENGTH(ipha);
12903 	/* Pull up the UDP header, if necessary. */
12904 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12905 udppullup:
12906 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12907 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12908 			freemsg(first_mp);
12909 			goto slow_done;
12910 		}
12911 		ipha = (ipha_t *)mp->b_rptr;
12912 	}
12913 
12914 	/*
12915 	 * Validate the checksum for the reassembled packet; for the
12916 	 * pullup case we calculate the payload checksum in software.
12917 	 */
12918 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12919 	if (up[3] != 0) {
12920 		boolean_t cksum_err;
12921 
12922 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12923 			IP_STAT(ipst, ip_in_sw_cksum);
12924 
12925 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12926 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12927 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12928 		    iphs[9] + up[2], sum, cksum_err);
12929 
12930 		if (cksum_err) {
12931 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12932 
12933 			if (reass_hck_flags & HCK_FULLCKSUM)
12934 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12935 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12936 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12937 			else
12938 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12939 
12940 			freemsg(first_mp);
12941 			goto slow_done;
12942 		}
12943 	}
12944 udpslowpath:
12945 
12946 	/* Clear hardware checksum flag to be safe */
12947 	DB_CKSUMFLAGS(mp) = 0;
12948 
12949 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12950 	    (ire->ire_type == IRE_BROADCAST),
12951 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12952 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12953 
12954 slow_done:
12955 	IP_STAT(ipst, ip_udp_slow_path);
12956 	return;
12957 
12958 #undef  iphs
12959 #undef  rptr
12960 }
12961 
12962 /* ARGSUSED */
12963 static mblk_t *
12964 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12965     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12966     ill_rx_ring_t *ill_ring)
12967 {
12968 	conn_t		*connp;
12969 	uint32_t	sum;
12970 	uint32_t	u1;
12971 	uint16_t	*up;
12972 	int		offset;
12973 	ssize_t		len;
12974 	mblk_t		*mp1;
12975 	boolean_t	syn_present = B_FALSE;
12976 	tcph_t		*tcph;
12977 	uint_t		ip_hdr_len;
12978 	ill_t		*ill = (ill_t *)q->q_ptr;
12979 	zoneid_t	zoneid = ire->ire_zoneid;
12980 	boolean_t	cksum_err;
12981 	uint16_t	hck_flags = 0;
12982 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12983 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12984 
12985 #define	rptr	((uchar_t *)ipha)
12986 
12987 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12988 	ASSERT(ill != NULL);
12989 
12990 	/*
12991 	 * FAST PATH for tcp packets
12992 	 */
12993 
12994 	/* u1 is # words of IP options */
12995 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12996 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12997 
12998 	/* IP options present */
12999 	if (u1) {
13000 		goto ipoptions;
13001 	} else if (!mctl_present) {
13002 		/* Check the IP header checksum.  */
13003 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13004 			/* Clear the IP header h/w cksum flag */
13005 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13006 		} else if (!mctl_present) {
13007 			/*
13008 			 * Don't verify header checksum if this packet
13009 			 * is coming back from AH/ESP as we already did it.
13010 			 */
13011 #define	uph	((uint16_t *)ipha)
13012 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13013 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13014 #undef	uph
13015 			/* finish doing IP checksum */
13016 			sum = (sum & 0xFFFF) + (sum >> 16);
13017 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13018 			if (sum != 0 && sum != 0xFFFF) {
13019 				BUMP_MIB(ill->ill_ip_mib,
13020 				    ipIfStatsInCksumErrs);
13021 				goto error;
13022 			}
13023 		}
13024 	}
13025 
13026 	if (!mctl_present) {
13027 		UPDATE_IB_PKT_COUNT(ire);
13028 		ire->ire_last_used_time = lbolt;
13029 	}
13030 
13031 	/* packet part of fragmented IP packet? */
13032 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13033 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13034 		goto fragmented;
13035 	}
13036 
13037 	/* u1 = IP header length (20 bytes) */
13038 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13039 
13040 	/* does packet contain IP+TCP headers? */
13041 	len = mp->b_wptr - rptr;
13042 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13043 		IP_STAT(ipst, ip_tcppullup);
13044 		goto tcppullup;
13045 	}
13046 
13047 	/* TCP options present? */
13048 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13049 
13050 	/*
13051 	 * If options need to be pulled up, then goto tcpoptions.
13052 	 * otherwise we are still in the fast path
13053 	 */
13054 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13055 		IP_STAT(ipst, ip_tcpoptions);
13056 		goto tcpoptions;
13057 	}
13058 
13059 	/* multiple mblks of tcp data? */
13060 	if ((mp1 = mp->b_cont) != NULL) {
13061 		/* more then two? */
13062 		if (mp1->b_cont != NULL) {
13063 			IP_STAT(ipst, ip_multipkttcp);
13064 			goto multipkttcp;
13065 		}
13066 		len += mp1->b_wptr - mp1->b_rptr;
13067 	}
13068 
13069 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13070 
13071 	/* part of pseudo checksum */
13072 
13073 	/* TCP datagram length */
13074 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13075 
13076 #define	iphs    ((uint16_t *)ipha)
13077 
13078 #ifdef	_BIG_ENDIAN
13079 	u1 += IPPROTO_TCP;
13080 #else
13081 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13082 #endif
13083 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13084 
13085 	/*
13086 	 * Revert to software checksum calculation if the interface
13087 	 * isn't capable of checksum offload or if IPsec is present.
13088 	 */
13089 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13090 		hck_flags = DB_CKSUMFLAGS(mp);
13091 
13092 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13093 		IP_STAT(ipst, ip_in_sw_cksum);
13094 
13095 	IP_CKSUM_RECV(hck_flags, u1,
13096 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13097 	    (int32_t)((uchar_t *)up - rptr),
13098 	    mp, mp1, cksum_err);
13099 
13100 	if (cksum_err) {
13101 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13102 
13103 		if (hck_flags & HCK_FULLCKSUM)
13104 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13105 		else if (hck_flags & HCK_PARTIALCKSUM)
13106 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13107 		else
13108 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13109 
13110 		goto error;
13111 	}
13112 
13113 try_again:
13114 
13115 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13116 	    zoneid, ipst)) == NULL) {
13117 		/* Send the TH_RST */
13118 		goto no_conn;
13119 	}
13120 
13121 	/*
13122 	 * TCP FAST PATH for AF_INET socket.
13123 	 *
13124 	 * TCP fast path to avoid extra work. An AF_INET socket type
13125 	 * does not have facility to receive extra information via
13126 	 * ip_process or ip_add_info. Also, when the connection was
13127 	 * established, we made a check if this connection is impacted
13128 	 * by any global IPsec policy or per connection policy (a
13129 	 * policy that comes in effect later will not apply to this
13130 	 * connection). Since all this can be determined at the
13131 	 * connection establishment time, a quick check of flags
13132 	 * can avoid extra work.
13133 	 */
13134 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13135 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13136 		ASSERT(first_mp == mp);
13137 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13138 		SET_SQUEUE(mp, tcp_rput_data, connp);
13139 		return (mp);
13140 	}
13141 
13142 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13143 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13144 		if (IPCL_IS_TCP(connp)) {
13145 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13146 			DB_CKSUMSTART(mp) =
13147 			    (intptr_t)ip_squeue_get(ill_ring);
13148 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13149 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13150 				BUMP_MIB(ill->ill_ip_mib,
13151 				    ipIfStatsHCInDelivers);
13152 				SET_SQUEUE(mp, connp->conn_recv, connp);
13153 				return (mp);
13154 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13155 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13156 				BUMP_MIB(ill->ill_ip_mib,
13157 				    ipIfStatsHCInDelivers);
13158 				ip_squeue_enter_unbound++;
13159 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13160 				    connp);
13161 				return (mp);
13162 			}
13163 			syn_present = B_TRUE;
13164 		}
13165 
13166 	}
13167 
13168 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13169 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13170 
13171 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13172 		/* No need to send this packet to TCP */
13173 		if ((flags & TH_RST) || (flags & TH_URG)) {
13174 			CONN_DEC_REF(connp);
13175 			freemsg(first_mp);
13176 			return (NULL);
13177 		}
13178 		if (flags & TH_ACK) {
13179 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13180 			    ipst->ips_netstack->netstack_tcp, connp);
13181 			CONN_DEC_REF(connp);
13182 			return (NULL);
13183 		}
13184 
13185 		CONN_DEC_REF(connp);
13186 		freemsg(first_mp);
13187 		return (NULL);
13188 	}
13189 
13190 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13191 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13192 		    ipha, NULL, mctl_present);
13193 		if (first_mp == NULL) {
13194 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13195 			CONN_DEC_REF(connp);
13196 			return (NULL);
13197 		}
13198 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13199 			ASSERT(syn_present);
13200 			if (mctl_present) {
13201 				ASSERT(first_mp != mp);
13202 				first_mp->b_datap->db_struioflag |=
13203 				    STRUIO_POLICY;
13204 			} else {
13205 				ASSERT(first_mp == mp);
13206 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13207 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13208 			}
13209 		} else {
13210 			/*
13211 			 * Discard first_mp early since we're dealing with a
13212 			 * fully-connected conn_t and tcp doesn't do policy in
13213 			 * this case.
13214 			 */
13215 			if (mctl_present) {
13216 				freeb(first_mp);
13217 				mctl_present = B_FALSE;
13218 			}
13219 			first_mp = mp;
13220 		}
13221 	}
13222 
13223 	/* Initiate IPPF processing for fastpath */
13224 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13225 		uint32_t	ill_index;
13226 
13227 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13228 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13229 		if (mp == NULL) {
13230 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13231 			    "deferred/dropped during IPPF processing\n"));
13232 			CONN_DEC_REF(connp);
13233 			if (mctl_present)
13234 				freeb(first_mp);
13235 			return (NULL);
13236 		} else if (mctl_present) {
13237 			/*
13238 			 * ip_process might return a new mp.
13239 			 */
13240 			ASSERT(first_mp != mp);
13241 			first_mp->b_cont = mp;
13242 		} else {
13243 			first_mp = mp;
13244 		}
13245 
13246 	}
13247 
13248 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13249 		/*
13250 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13251 		 * make sure IPF_RECVIF is passed to ip_add_info.
13252 		 */
13253 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13254 		    IPCL_ZONEID(connp), ipst);
13255 		if (mp == NULL) {
13256 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13257 			CONN_DEC_REF(connp);
13258 			if (mctl_present)
13259 				freeb(first_mp);
13260 			return (NULL);
13261 		} else if (mctl_present) {
13262 			/*
13263 			 * ip_add_info might return a new mp.
13264 			 */
13265 			ASSERT(first_mp != mp);
13266 			first_mp->b_cont = mp;
13267 		} else {
13268 			first_mp = mp;
13269 		}
13270 	}
13271 
13272 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13273 	if (IPCL_IS_TCP(connp)) {
13274 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13275 		return (first_mp);
13276 	} else {
13277 		/* SOCK_RAW, IPPROTO_TCP case */
13278 		(connp->conn_recv)(connp, first_mp, NULL);
13279 		CONN_DEC_REF(connp);
13280 		return (NULL);
13281 	}
13282 
13283 no_conn:
13284 	/* Initiate IPPf processing, if needed. */
13285 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13286 		uint32_t ill_index;
13287 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13288 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13289 		if (first_mp == NULL) {
13290 			return (NULL);
13291 		}
13292 	}
13293 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13294 
13295 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13296 	    ipst->ips_netstack->netstack_tcp, NULL);
13297 	return (NULL);
13298 ipoptions:
13299 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13300 		goto slow_done;
13301 	}
13302 
13303 	UPDATE_IB_PKT_COUNT(ire);
13304 	ire->ire_last_used_time = lbolt;
13305 
13306 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13307 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13308 fragmented:
13309 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13310 			if (mctl_present)
13311 				freeb(first_mp);
13312 			goto slow_done;
13313 		}
13314 		/*
13315 		 * Make sure that first_mp points back to mp as
13316 		 * the mp we came in with could have changed in
13317 		 * ip_rput_fragment().
13318 		 */
13319 		ASSERT(!mctl_present);
13320 		ipha = (ipha_t *)mp->b_rptr;
13321 		first_mp = mp;
13322 	}
13323 
13324 	/* Now we have a complete datagram, destined for this machine. */
13325 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13326 
13327 	len = mp->b_wptr - mp->b_rptr;
13328 	/* Pull up a minimal TCP header, if necessary. */
13329 	if (len < (u1 + 20)) {
13330 tcppullup:
13331 		if (!pullupmsg(mp, u1 + 20)) {
13332 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13333 			goto error;
13334 		}
13335 		ipha = (ipha_t *)mp->b_rptr;
13336 		len = mp->b_wptr - mp->b_rptr;
13337 	}
13338 
13339 	/*
13340 	 * Extract the offset field from the TCP header.  As usual, we
13341 	 * try to help the compiler more than the reader.
13342 	 */
13343 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13344 	if (offset != 5) {
13345 tcpoptions:
13346 		if (offset < 5) {
13347 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13348 			goto error;
13349 		}
13350 		/*
13351 		 * There must be TCP options.
13352 		 * Make sure we can grab them.
13353 		 */
13354 		offset <<= 2;
13355 		offset += u1;
13356 		if (len < offset) {
13357 			if (!pullupmsg(mp, offset)) {
13358 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13359 				goto error;
13360 			}
13361 			ipha = (ipha_t *)mp->b_rptr;
13362 			len = mp->b_wptr - rptr;
13363 		}
13364 	}
13365 
13366 	/* Get the total packet length in len, including headers. */
13367 	if (mp->b_cont) {
13368 multipkttcp:
13369 		len = msgdsize(mp);
13370 	}
13371 
13372 	/*
13373 	 * Check the TCP checksum by pulling together the pseudo-
13374 	 * header checksum, and passing it to ip_csum to be added in
13375 	 * with the TCP datagram.
13376 	 *
13377 	 * Since we are not using the hwcksum if available we must
13378 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13379 	 * If either of these fails along the way the mblk is freed.
13380 	 * If this logic ever changes and mblk is reused to say send
13381 	 * ICMP's back, then this flag may need to be cleared in
13382 	 * other places as well.
13383 	 */
13384 	DB_CKSUMFLAGS(mp) = 0;
13385 
13386 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13387 
13388 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13389 #ifdef	_BIG_ENDIAN
13390 	u1 += IPPROTO_TCP;
13391 #else
13392 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13393 #endif
13394 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13395 	/*
13396 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13397 	 */
13398 	IP_STAT(ipst, ip_in_sw_cksum);
13399 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13400 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13401 		goto error;
13402 	}
13403 
13404 	IP_STAT(ipst, ip_tcp_slow_path);
13405 	goto try_again;
13406 #undef  iphs
13407 #undef  rptr
13408 
13409 error:
13410 	freemsg(first_mp);
13411 slow_done:
13412 	return (NULL);
13413 }
13414 
13415 /* ARGSUSED */
13416 static void
13417 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13418     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13419 {
13420 	conn_t		*connp;
13421 	uint32_t	sum;
13422 	uint32_t	u1;
13423 	ssize_t		len;
13424 	sctp_hdr_t	*sctph;
13425 	zoneid_t	zoneid = ire->ire_zoneid;
13426 	uint32_t	pktsum;
13427 	uint32_t	calcsum;
13428 	uint32_t	ports;
13429 	in6_addr_t	map_src, map_dst;
13430 	ill_t		*ill = (ill_t *)q->q_ptr;
13431 	ip_stack_t	*ipst;
13432 	sctp_stack_t	*sctps;
13433 	boolean_t	sctp_csum_err = B_FALSE;
13434 
13435 	ASSERT(recv_ill != NULL);
13436 	ipst = recv_ill->ill_ipst;
13437 	sctps = ipst->ips_netstack->netstack_sctp;
13438 
13439 #define	rptr	((uchar_t *)ipha)
13440 
13441 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13442 	ASSERT(ill != NULL);
13443 
13444 	/* u1 is # words of IP options */
13445 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13446 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13447 
13448 	/* IP options present */
13449 	if (u1 > 0) {
13450 		goto ipoptions;
13451 	} else {
13452 		/* Check the IP header checksum.  */
13453 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13454 		    !mctl_present) {
13455 #define	uph	((uint16_t *)ipha)
13456 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13457 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13458 #undef	uph
13459 			/* finish doing IP checksum */
13460 			sum = (sum & 0xFFFF) + (sum >> 16);
13461 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13462 			/*
13463 			 * Don't verify header checksum if this packet
13464 			 * is coming back from AH/ESP as we already did it.
13465 			 */
13466 			if (sum != 0 && sum != 0xFFFF) {
13467 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13468 				goto error;
13469 			}
13470 		}
13471 		/*
13472 		 * Since there is no SCTP h/w cksum support yet, just
13473 		 * clear the flag.
13474 		 */
13475 		DB_CKSUMFLAGS(mp) = 0;
13476 	}
13477 
13478 	/*
13479 	 * Don't verify header checksum if this packet is coming
13480 	 * back from AH/ESP as we already did it.
13481 	 */
13482 	if (!mctl_present) {
13483 		UPDATE_IB_PKT_COUNT(ire);
13484 		ire->ire_last_used_time = lbolt;
13485 	}
13486 
13487 	/* packet part of fragmented IP packet? */
13488 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13489 	if (u1 & (IPH_MF | IPH_OFFSET))
13490 		goto fragmented;
13491 
13492 	/* u1 = IP header length (20 bytes) */
13493 	u1 = IP_SIMPLE_HDR_LENGTH;
13494 
13495 find_sctp_client:
13496 	/* Pullup if we don't have the sctp common header. */
13497 	len = MBLKL(mp);
13498 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13499 		if (mp->b_cont == NULL ||
13500 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13501 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13502 			goto error;
13503 		}
13504 		ipha = (ipha_t *)mp->b_rptr;
13505 		len = MBLKL(mp);
13506 	}
13507 
13508 	sctph = (sctp_hdr_t *)(rptr + u1);
13509 #ifdef	DEBUG
13510 	if (!skip_sctp_cksum) {
13511 #endif
13512 		pktsum = sctph->sh_chksum;
13513 		sctph->sh_chksum = 0;
13514 		calcsum = sctp_cksum(mp, u1);
13515 		sctph->sh_chksum = pktsum;
13516 		if (calcsum != pktsum)
13517 			sctp_csum_err = B_TRUE;
13518 #ifdef	DEBUG	/* skip_sctp_cksum */
13519 	}
13520 #endif
13521 	/* get the ports */
13522 	ports = *(uint32_t *)&sctph->sh_sport;
13523 
13524 	IRE_REFRELE(ire);
13525 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13526 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13527 	if (sctp_csum_err) {
13528 		/*
13529 		 * No potential sctp checksum errors go to the Sun
13530 		 * sctp stack however they might be Adler-32 summed
13531 		 * packets a userland stack bound to a raw IP socket
13532 		 * could reasonably use. Note though that Adler-32 is
13533 		 * a long deprecated algorithm and customer sctp
13534 		 * networks should eventually migrate to CRC-32 at
13535 		 * which time this facility should be removed.
13536 		 */
13537 		flags |= IP_FF_SCTP_CSUM_ERR;
13538 		goto no_conn;
13539 	}
13540 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13541 	    sctps)) == NULL) {
13542 		/* Check for raw socket or OOTB handling */
13543 		goto no_conn;
13544 	}
13545 
13546 	/* Found a client; up it goes */
13547 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13548 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13549 	return;
13550 
13551 no_conn:
13552 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13553 	    ports, mctl_present, flags, B_TRUE, zoneid);
13554 	return;
13555 
13556 ipoptions:
13557 	DB_CKSUMFLAGS(mp) = 0;
13558 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13559 		goto slow_done;
13560 
13561 	UPDATE_IB_PKT_COUNT(ire);
13562 	ire->ire_last_used_time = lbolt;
13563 
13564 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13565 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13566 fragmented:
13567 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13568 			goto slow_done;
13569 		/*
13570 		 * Make sure that first_mp points back to mp as
13571 		 * the mp we came in with could have changed in
13572 		 * ip_rput_fragment().
13573 		 */
13574 		ASSERT(!mctl_present);
13575 		ipha = (ipha_t *)mp->b_rptr;
13576 		first_mp = mp;
13577 	}
13578 
13579 	/* Now we have a complete datagram, destined for this machine. */
13580 	u1 = IPH_HDR_LENGTH(ipha);
13581 	goto find_sctp_client;
13582 #undef  iphs
13583 #undef  rptr
13584 
13585 error:
13586 	freemsg(first_mp);
13587 slow_done:
13588 	IRE_REFRELE(ire);
13589 }
13590 
13591 #define	VER_BITS	0xF0
13592 #define	VERSION_6	0x60
13593 
13594 static boolean_t
13595 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13596     ipaddr_t *dstp, ip_stack_t *ipst)
13597 {
13598 	uint_t	opt_len;
13599 	ipha_t *ipha;
13600 	ssize_t len;
13601 	uint_t	pkt_len;
13602 
13603 	ASSERT(ill != NULL);
13604 	IP_STAT(ipst, ip_ipoptions);
13605 	ipha = *iphapp;
13606 
13607 #define	rptr    ((uchar_t *)ipha)
13608 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13609 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13610 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13611 		freemsg(mp);
13612 		return (B_FALSE);
13613 	}
13614 
13615 	/* multiple mblk or too short */
13616 	pkt_len = ntohs(ipha->ipha_length);
13617 
13618 	/* Get the number of words of IP options in the IP header. */
13619 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13620 	if (opt_len) {
13621 		/* IP Options present!  Validate and process. */
13622 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13623 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13624 			goto done;
13625 		}
13626 		/*
13627 		 * Recompute complete header length and make sure we
13628 		 * have access to all of it.
13629 		 */
13630 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13631 		if (len > (mp->b_wptr - rptr)) {
13632 			if (len > pkt_len) {
13633 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13634 				goto done;
13635 			}
13636 			if (!pullupmsg(mp, len)) {
13637 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13638 				goto done;
13639 			}
13640 			ipha = (ipha_t *)mp->b_rptr;
13641 		}
13642 		/*
13643 		 * Go off to ip_rput_options which returns the next hop
13644 		 * destination address, which may have been affected
13645 		 * by source routing.
13646 		 */
13647 		IP_STAT(ipst, ip_opt);
13648 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13649 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13650 			return (B_FALSE);
13651 		}
13652 	}
13653 	*iphapp = ipha;
13654 	return (B_TRUE);
13655 done:
13656 	/* clear b_prev - used by ip_mroute_decap */
13657 	mp->b_prev = NULL;
13658 	freemsg(mp);
13659 	return (B_FALSE);
13660 #undef  rptr
13661 }
13662 
13663 /*
13664  * Deal with the fact that there is no ire for the destination.
13665  */
13666 static ire_t *
13667 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13668 {
13669 	ipha_t	*ipha;
13670 	ill_t	*ill;
13671 	ire_t	*ire;
13672 	ip_stack_t *ipst;
13673 	enum	ire_forward_action ret_action;
13674 
13675 	ipha = (ipha_t *)mp->b_rptr;
13676 	ill = (ill_t *)q->q_ptr;
13677 
13678 	ASSERT(ill != NULL);
13679 	ipst = ill->ill_ipst;
13680 
13681 	/*
13682 	 * No IRE for this destination, so it can't be for us.
13683 	 * Unless we are forwarding, drop the packet.
13684 	 * We have to let source routed packets through
13685 	 * since we don't yet know if they are 'ping -l'
13686 	 * packets i.e. if they will go out over the
13687 	 * same interface as they came in on.
13688 	 */
13689 	if (ll_multicast) {
13690 		freemsg(mp);
13691 		return (NULL);
13692 	}
13693 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13694 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13695 		freemsg(mp);
13696 		return (NULL);
13697 	}
13698 
13699 	/*
13700 	 * Mark this packet as having originated externally.
13701 	 *
13702 	 * For non-forwarding code path, ire_send later double
13703 	 * checks this interface to see if it is still exists
13704 	 * post-ARP resolution.
13705 	 *
13706 	 * Also, IPQOS uses this to differentiate between
13707 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13708 	 * QOS packet processing in ip_wput_attach_llhdr().
13709 	 * The QoS module can mark the b_band for a fastpath message
13710 	 * or the dl_priority field in a unitdata_req header for
13711 	 * CoS marking. This info can only be found in
13712 	 * ip_wput_attach_llhdr().
13713 	 */
13714 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13715 	/*
13716 	 * Clear the indication that this may have a hardware checksum
13717 	 * as we are not using it
13718 	 */
13719 	DB_CKSUMFLAGS(mp) = 0;
13720 
13721 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13722 	    MBLK_GETLABEL(mp), ipst);
13723 
13724 	if (ire == NULL && ret_action == Forward_check_multirt) {
13725 		/* Let ip_newroute handle CGTP  */
13726 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13727 		return (NULL);
13728 	}
13729 
13730 	if (ire != NULL)
13731 		return (ire);
13732 
13733 	mp->b_prev = mp->b_next = 0;
13734 
13735 	if (ret_action == Forward_blackhole) {
13736 		freemsg(mp);
13737 		return (NULL);
13738 	}
13739 	/* send icmp unreachable */
13740 	q = WR(q);
13741 	/* Sent by forwarding path, and router is global zone */
13742 	if (ip_source_routed(ipha, ipst)) {
13743 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13744 		    GLOBAL_ZONEID, ipst);
13745 	} else {
13746 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13747 		    ipst);
13748 	}
13749 
13750 	return (NULL);
13751 
13752 }
13753 
13754 /*
13755  * check ip header length and align it.
13756  */
13757 static boolean_t
13758 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13759 {
13760 	ssize_t len;
13761 	ill_t *ill;
13762 	ipha_t	*ipha;
13763 
13764 	len = MBLKL(mp);
13765 
13766 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13767 		ill = (ill_t *)q->q_ptr;
13768 
13769 		if (!OK_32PTR(mp->b_rptr))
13770 			IP_STAT(ipst, ip_notaligned1);
13771 		else
13772 			IP_STAT(ipst, ip_notaligned2);
13773 		/* Guard against bogus device drivers */
13774 		if (len < 0) {
13775 			/* clear b_prev - used by ip_mroute_decap */
13776 			mp->b_prev = NULL;
13777 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13778 			freemsg(mp);
13779 			return (B_FALSE);
13780 		}
13781 
13782 		if (ip_rput_pullups++ == 0) {
13783 			ipha = (ipha_t *)mp->b_rptr;
13784 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13785 			    "ip_check_and_align_header: %s forced us to "
13786 			    " pullup pkt, hdr len %ld, hdr addr %p",
13787 			    ill->ill_name, len, (void *)ipha);
13788 		}
13789 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13790 			/* clear b_prev - used by ip_mroute_decap */
13791 			mp->b_prev = NULL;
13792 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13793 			freemsg(mp);
13794 			return (B_FALSE);
13795 		}
13796 	}
13797 	return (B_TRUE);
13798 }
13799 
13800 ire_t *
13801 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13802 {
13803 	ire_t		*new_ire;
13804 	ill_t		*ire_ill;
13805 	uint_t		ifindex;
13806 	ip_stack_t	*ipst = ill->ill_ipst;
13807 	boolean_t	strict_check = B_FALSE;
13808 
13809 	/*
13810 	 * This packet came in on an interface other than the one associated
13811 	 * with the first ire we found for the destination address. We do
13812 	 * another ire lookup here, using the ingress ill, to see if the
13813 	 * interface is in an interface group.
13814 	 * As long as the ills belong to the same group, we don't consider
13815 	 * them to be arriving on the wrong interface. Thus, if the switch
13816 	 * is doing inbound load spreading, we won't drop packets when the
13817 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13818 	 * for 'usesrc groups' where the destination address may belong to
13819 	 * another interface to allow multipathing to happen.
13820 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13821 	 * where the local address may not be unique. In this case we were
13822 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13823 	 * actually returned. The new lookup, which is more specific, should
13824 	 * only find the IRE_LOCAL associated with the ingress ill if one
13825 	 * exists.
13826 	 */
13827 
13828 	if (ire->ire_ipversion == IPV4_VERSION) {
13829 		if (ipst->ips_ip_strict_dst_multihoming)
13830 			strict_check = B_TRUE;
13831 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13832 		    ill->ill_ipif, ALL_ZONES, NULL,
13833 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13834 	} else {
13835 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13836 		if (ipst->ips_ipv6_strict_dst_multihoming)
13837 			strict_check = B_TRUE;
13838 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13839 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13840 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13841 	}
13842 	/*
13843 	 * If the same ire that was returned in ip_input() is found then this
13844 	 * is an indication that interface groups are in use. The packet
13845 	 * arrived on a different ill in the group than the one associated with
13846 	 * the destination address.  If a different ire was found then the same
13847 	 * IP address must be hosted on multiple ills. This is possible with
13848 	 * unnumbered point2point interfaces. We switch to use this new ire in
13849 	 * order to have accurate interface statistics.
13850 	 */
13851 	if (new_ire != NULL) {
13852 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13853 			ire_refrele(ire);
13854 			ire = new_ire;
13855 		} else {
13856 			ire_refrele(new_ire);
13857 		}
13858 		return (ire);
13859 	} else if ((ire->ire_rfq == NULL) &&
13860 	    (ire->ire_ipversion == IPV4_VERSION)) {
13861 		/*
13862 		 * The best match could have been the original ire which
13863 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13864 		 * the strict multihoming checks are irrelevant as we consider
13865 		 * local addresses hosted on lo0 to be interface agnostic. We
13866 		 * only expect a null ire_rfq on IREs which are associated with
13867 		 * lo0 hence we can return now.
13868 		 */
13869 		return (ire);
13870 	}
13871 
13872 	/*
13873 	 * Chase pointers once and store locally.
13874 	 */
13875 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13876 	    (ill_t *)(ire->ire_rfq->q_ptr);
13877 	ifindex = ill->ill_usesrc_ifindex;
13878 
13879 	/*
13880 	 * Check if it's a legal address on the 'usesrc' interface.
13881 	 */
13882 	if ((ifindex != 0) && (ire_ill != NULL) &&
13883 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13884 		return (ire);
13885 	}
13886 
13887 	/*
13888 	 * If the ip*_strict_dst_multihoming switch is on then we can
13889 	 * only accept this packet if the interface is marked as routing.
13890 	 */
13891 	if (!(strict_check))
13892 		return (ire);
13893 
13894 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13895 	    ILLF_ROUTER) != 0) {
13896 		return (ire);
13897 	}
13898 
13899 	ire_refrele(ire);
13900 	return (NULL);
13901 }
13902 
13903 ire_t *
13904 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13905 {
13906 	ipha_t	*ipha;
13907 	ire_t	*src_ire;
13908 	ill_t	*stq_ill;
13909 	uint_t	hlen;
13910 	uint_t	pkt_len;
13911 	uint32_t sum;
13912 	queue_t	*dev_q;
13913 	ip_stack_t *ipst = ill->ill_ipst;
13914 	mblk_t *fpmp;
13915 	enum	ire_forward_action ret_action;
13916 
13917 	ipha = (ipha_t *)mp->b_rptr;
13918 
13919 	if (ire != NULL &&
13920 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13921 	    ire->ire_zoneid != ALL_ZONES) {
13922 		/*
13923 		 * Should only use IREs that are visible to the global
13924 		 * zone for forwarding.
13925 		 */
13926 		ire_refrele(ire);
13927 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13928 	}
13929 
13930 	/*
13931 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13932 	 * The loopback address check for both src and dst has already
13933 	 * been checked in ip_input
13934 	 */
13935 
13936 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13937 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13938 		goto drop;
13939 	}
13940 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13941 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13942 
13943 	if (src_ire != NULL) {
13944 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13945 		ire_refrele(src_ire);
13946 		goto drop;
13947 	}
13948 
13949 	/* No ire cache of nexthop. So first create one  */
13950 	if (ire == NULL) {
13951 
13952 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13953 		    NULL, ipst);
13954 		/*
13955 		 * We only come to ip_fast_forward if ip_cgtp_filter
13956 		 * is not set. So ire_forward() should not return with
13957 		 * Forward_check_multirt as the next action.
13958 		 */
13959 		ASSERT(ret_action != Forward_check_multirt);
13960 		if (ire == NULL) {
13961 			/* An attempt was made to forward the packet */
13962 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13963 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13964 			mp->b_prev = mp->b_next = 0;
13965 			/* send icmp unreachable */
13966 			/* Sent by forwarding path, and router is global zone */
13967 			if (ret_action == Forward_ret_icmp_err) {
13968 				if (ip_source_routed(ipha, ipst)) {
13969 					icmp_unreachable(ill->ill_wq, mp,
13970 					    ICMP_SOURCE_ROUTE_FAILED,
13971 					    GLOBAL_ZONEID, ipst);
13972 				} else {
13973 					icmp_unreachable(ill->ill_wq, mp,
13974 					    ICMP_HOST_UNREACHABLE,
13975 					    GLOBAL_ZONEID, ipst);
13976 				}
13977 			} else {
13978 				freemsg(mp);
13979 			}
13980 			return (NULL);
13981 		}
13982 	}
13983 
13984 	/*
13985 	 * Forwarding fastpath exception case:
13986 	 * If either of the follwoing case is true, we take
13987 	 * the slowpath
13988 	 *	o forwarding is not enabled
13989 	 *	o incoming and outgoing interface are the same, or the same
13990 	 *	  IPMP group
13991 	 *	o corresponding ire is in incomplete state
13992 	 *	o packet needs fragmentation
13993 	 *	o ARP cache is not resolved
13994 	 *
13995 	 * The codeflow from here on is thus:
13996 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13997 	 */
13998 	pkt_len = ntohs(ipha->ipha_length);
13999 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14000 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14001 	    !(ill->ill_flags & ILLF_ROUTER) ||
14002 	    (ill == stq_ill) ||
14003 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14004 	    (ire->ire_nce == NULL) ||
14005 	    (pkt_len > ire->ire_max_frag) ||
14006 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14007 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14008 	    ipha->ipha_ttl <= 1) {
14009 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14010 		    ipha, ill, B_FALSE);
14011 		return (ire);
14012 	}
14013 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14014 
14015 	DTRACE_PROBE4(ip4__forwarding__start,
14016 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14017 
14018 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14019 	    ipst->ips_ipv4firewall_forwarding,
14020 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14021 
14022 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14023 
14024 	if (mp == NULL)
14025 		goto drop;
14026 
14027 	mp->b_datap->db_struioun.cksum.flags = 0;
14028 	/* Adjust the checksum to reflect the ttl decrement. */
14029 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14030 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14031 	ipha->ipha_ttl--;
14032 
14033 	/*
14034 	 * Write the link layer header.  We can do this safely here,
14035 	 * because we have already tested to make sure that the IP
14036 	 * policy is not set, and that we have a fast path destination
14037 	 * header.
14038 	 */
14039 	mp->b_rptr -= hlen;
14040 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14041 
14042 	UPDATE_IB_PKT_COUNT(ire);
14043 	ire->ire_last_used_time = lbolt;
14044 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14045 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14046 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14047 
14048 	dev_q = ire->ire_stq->q_next;
14049 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14050 	    !canputnext(ire->ire_stq)) {
14051 		goto indiscard;
14052 	}
14053 	if (ILL_DLS_CAPABLE(stq_ill)) {
14054 		/*
14055 		 * Send the packet directly to DLD, where it
14056 		 * may be queued depending on the availability
14057 		 * of transmit resources at the media layer.
14058 		 */
14059 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst, hlen);
14060 	} else {
14061 		DTRACE_PROBE4(ip4__physical__out__start,
14062 		    ill_t *, NULL, ill_t *, stq_ill,
14063 		    ipha_t *, ipha, mblk_t *, mp);
14064 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14065 		    ipst->ips_ipv4firewall_physical_out,
14066 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14067 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14068 		if (mp == NULL)
14069 			goto drop;
14070 
14071 		DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14072 		    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14073 		    ip6_t *, NULL, int, 0);
14074 
14075 		putnext(ire->ire_stq, mp);
14076 	}
14077 	return (ire);
14078 
14079 indiscard:
14080 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14081 drop:
14082 	if (mp != NULL)
14083 		freemsg(mp);
14084 	return (ire);
14085 
14086 }
14087 
14088 /*
14089  * This function is called in the forwarding slowpath, when
14090  * either the ire lacks the link-layer address, or the packet needs
14091  * further processing(eg. fragmentation), before transmission.
14092  */
14093 
14094 static void
14095 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14096     ill_t *ill, boolean_t ll_multicast)
14097 {
14098 	ill_group_t	*ill_group;
14099 	ill_group_t	*ire_group;
14100 	queue_t		*dev_q;
14101 	ire_t		*src_ire;
14102 	ip_stack_t	*ipst = ill->ill_ipst;
14103 
14104 	ASSERT(ire->ire_stq != NULL);
14105 
14106 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14107 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14108 
14109 	if (ll_multicast != 0) {
14110 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14111 		goto drop_pkt;
14112 	}
14113 
14114 	/*
14115 	 * check if ipha_src is a broadcast address. Note that this
14116 	 * check is redundant when we get here from ip_fast_forward()
14117 	 * which has already done this check. However, since we can
14118 	 * also get here from ip_rput_process_broadcast() or, for
14119 	 * for the slow path through ip_fast_forward(), we perform
14120 	 * the check again for code-reusability
14121 	 */
14122 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14123 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14124 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14125 		if (src_ire != NULL)
14126 			ire_refrele(src_ire);
14127 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14128 		ip2dbg(("ip_rput_process_forward: Received packet with"
14129 		    " bad src/dst address on %s\n", ill->ill_name));
14130 		goto drop_pkt;
14131 	}
14132 
14133 	ill_group = ill->ill_group;
14134 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14135 	/*
14136 	 * Check if we want to forward this one at this time.
14137 	 * We allow source routed packets on a host provided that
14138 	 * they go out the same interface or same interface group
14139 	 * as they came in on.
14140 	 *
14141 	 * XXX To be quicker, we may wish to not chase pointers to
14142 	 * get the ILLF_ROUTER flag and instead store the
14143 	 * forwarding policy in the ire.  An unfortunate
14144 	 * side-effect of that would be requiring an ire flush
14145 	 * whenever the ILLF_ROUTER flag changes.
14146 	 */
14147 	if (((ill->ill_flags &
14148 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14149 	    ILLF_ROUTER) == 0) &&
14150 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14151 	    (ill_group != NULL && ill_group == ire_group)))) {
14152 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14153 		if (ip_source_routed(ipha, ipst)) {
14154 			q = WR(q);
14155 			/*
14156 			 * Clear the indication that this may have
14157 			 * hardware checksum as we are not using it.
14158 			 */
14159 			DB_CKSUMFLAGS(mp) = 0;
14160 			/* Sent by forwarding path, and router is global zone */
14161 			icmp_unreachable(q, mp,
14162 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14163 			return;
14164 		}
14165 		goto drop_pkt;
14166 	}
14167 
14168 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14169 
14170 	/* Packet is being forwarded. Turning off hwcksum flag. */
14171 	DB_CKSUMFLAGS(mp) = 0;
14172 	if (ipst->ips_ip_g_send_redirects) {
14173 		/*
14174 		 * Check whether the incoming interface and outgoing
14175 		 * interface is part of the same group. If so,
14176 		 * send redirects.
14177 		 *
14178 		 * Check the source address to see if it originated
14179 		 * on the same logical subnet it is going back out on.
14180 		 * If so, we should be able to send it a redirect.
14181 		 * Avoid sending a redirect if the destination
14182 		 * is directly connected (i.e., ipha_dst is the same
14183 		 * as ire_gateway_addr or the ire_addr of the
14184 		 * nexthop IRE_CACHE ), or if the packet was source
14185 		 * routed out this interface.
14186 		 */
14187 		ipaddr_t src, nhop;
14188 		mblk_t	*mp1;
14189 		ire_t	*nhop_ire = NULL;
14190 
14191 		/*
14192 		 * Check whether ire_rfq and q are from the same ill
14193 		 * or if they are not same, they at least belong
14194 		 * to the same group. If so, send redirects.
14195 		 */
14196 		if ((ire->ire_rfq == q ||
14197 		    (ill_group != NULL && ill_group == ire_group)) &&
14198 		    !ip_source_routed(ipha, ipst)) {
14199 
14200 			nhop = (ire->ire_gateway_addr != 0 ?
14201 			    ire->ire_gateway_addr : ire->ire_addr);
14202 
14203 			if (ipha->ipha_dst == nhop) {
14204 				/*
14205 				 * We avoid sending a redirect if the
14206 				 * destination is directly connected
14207 				 * because it is possible that multiple
14208 				 * IP subnets may have been configured on
14209 				 * the link, and the source may not
14210 				 * be on the same subnet as ip destination,
14211 				 * even though they are on the same
14212 				 * physical link.
14213 				 */
14214 				goto sendit;
14215 			}
14216 
14217 			src = ipha->ipha_src;
14218 
14219 			/*
14220 			 * We look up the interface ire for the nexthop,
14221 			 * to see if ipha_src is in the same subnet
14222 			 * as the nexthop.
14223 			 *
14224 			 * Note that, if, in the future, IRE_CACHE entries
14225 			 * are obsoleted,  this lookup will not be needed,
14226 			 * as the ire passed to this function will be the
14227 			 * same as the nhop_ire computed below.
14228 			 */
14229 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14230 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14231 			    0, NULL, MATCH_IRE_TYPE, ipst);
14232 
14233 			if (nhop_ire != NULL) {
14234 				if ((src & nhop_ire->ire_mask) ==
14235 				    (nhop & nhop_ire->ire_mask)) {
14236 					/*
14237 					 * The source is directly connected.
14238 					 * Just copy the ip header (which is
14239 					 * in the first mblk)
14240 					 */
14241 					mp1 = copyb(mp);
14242 					if (mp1 != NULL) {
14243 						icmp_send_redirect(WR(q), mp1,
14244 						    nhop, ipst);
14245 					}
14246 				}
14247 				ire_refrele(nhop_ire);
14248 			}
14249 		}
14250 	}
14251 sendit:
14252 	dev_q = ire->ire_stq->q_next;
14253 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14254 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14255 		freemsg(mp);
14256 		return;
14257 	}
14258 
14259 	ip_rput_forward(ire, ipha, mp, ill);
14260 	return;
14261 
14262 drop_pkt:
14263 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14264 	freemsg(mp);
14265 }
14266 
14267 ire_t *
14268 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14269     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14270 {
14271 	queue_t		*q;
14272 	uint16_t	hcksumflags;
14273 	ip_stack_t	*ipst = ill->ill_ipst;
14274 
14275 	q = *qp;
14276 
14277 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14278 
14279 	/*
14280 	 * Clear the indication that this may have hardware
14281 	 * checksum as we are not using it for forwarding.
14282 	 */
14283 	hcksumflags = DB_CKSUMFLAGS(mp);
14284 	DB_CKSUMFLAGS(mp) = 0;
14285 
14286 	/*
14287 	 * Directed broadcast forwarding: if the packet came in over a
14288 	 * different interface then it is routed out over we can forward it.
14289 	 */
14290 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14291 		ire_refrele(ire);
14292 		freemsg(mp);
14293 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14294 		return (NULL);
14295 	}
14296 	/*
14297 	 * For multicast we have set dst to be INADDR_BROADCAST
14298 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14299 	 * only for broadcast packets.
14300 	 */
14301 	if (!CLASSD(ipha->ipha_dst)) {
14302 		ire_t *new_ire;
14303 		ipif_t *ipif;
14304 		/*
14305 		 * For ill groups, as the switch duplicates broadcasts
14306 		 * across all the ports, we need to filter out and
14307 		 * send up only one copy. There is one copy for every
14308 		 * broadcast address on each ill. Thus, we look for a
14309 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14310 		 * later to see whether this ill is eligible to receive
14311 		 * them or not. ill_nominate_bcast_rcv() nominates only
14312 		 * one set of IREs for receiving.
14313 		 */
14314 
14315 		ipif = ipif_get_next_ipif(NULL, ill);
14316 		if (ipif == NULL) {
14317 			ire_refrele(ire);
14318 			freemsg(mp);
14319 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14320 			return (NULL);
14321 		}
14322 		new_ire = ire_ctable_lookup(dst, 0, 0,
14323 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14324 		ipif_refrele(ipif);
14325 
14326 		if (new_ire != NULL) {
14327 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14328 				ire_refrele(ire);
14329 				ire_refrele(new_ire);
14330 				freemsg(mp);
14331 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14332 				return (NULL);
14333 			}
14334 			/*
14335 			 * In the special case of multirouted broadcast
14336 			 * packets, we unconditionally need to "gateway"
14337 			 * them to the appropriate interface here.
14338 			 * In the normal case, this cannot happen, because
14339 			 * there is no broadcast IRE tagged with the
14340 			 * RTF_MULTIRT flag.
14341 			 */
14342 			if (new_ire->ire_flags & RTF_MULTIRT) {
14343 				ire_refrele(new_ire);
14344 				if (ire->ire_rfq != NULL) {
14345 					q = ire->ire_rfq;
14346 					*qp = q;
14347 				}
14348 			} else {
14349 				ire_refrele(ire);
14350 				ire = new_ire;
14351 			}
14352 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14353 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14354 				/*
14355 				 * Free the message if
14356 				 * ip_g_forward_directed_bcast is turned
14357 				 * off for non-local broadcast.
14358 				 */
14359 				ire_refrele(ire);
14360 				freemsg(mp);
14361 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14362 				return (NULL);
14363 			}
14364 		} else {
14365 			/*
14366 			 * This CGTP packet successfully passed the
14367 			 * CGTP filter, but the related CGTP
14368 			 * broadcast IRE has not been found,
14369 			 * meaning that the redundant ipif is
14370 			 * probably down. However, if we discarded
14371 			 * this packet, its duplicate would be
14372 			 * filtered out by the CGTP filter so none
14373 			 * of them would get through. So we keep
14374 			 * going with this one.
14375 			 */
14376 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14377 			if (ire->ire_rfq != NULL) {
14378 				q = ire->ire_rfq;
14379 				*qp = q;
14380 			}
14381 		}
14382 	}
14383 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14384 		/*
14385 		 * Verify that there are not more then one
14386 		 * IRE_BROADCAST with this broadcast address which
14387 		 * has ire_stq set.
14388 		 * TODO: simplify, loop over all IRE's
14389 		 */
14390 		ire_t	*ire1;
14391 		int	num_stq = 0;
14392 		mblk_t	*mp1;
14393 
14394 		/* Find the first one with ire_stq set */
14395 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14396 		for (ire1 = ire; ire1 &&
14397 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14398 		    ire1 = ire1->ire_next)
14399 			;
14400 		if (ire1) {
14401 			ire_refrele(ire);
14402 			ire = ire1;
14403 			IRE_REFHOLD(ire);
14404 		}
14405 
14406 		/* Check if there are additional ones with stq set */
14407 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14408 			if (ire->ire_addr != ire1->ire_addr)
14409 				break;
14410 			if (ire1->ire_stq) {
14411 				num_stq++;
14412 				break;
14413 			}
14414 		}
14415 		rw_exit(&ire->ire_bucket->irb_lock);
14416 		if (num_stq == 1 && ire->ire_stq != NULL) {
14417 			ip1dbg(("ip_rput_process_broadcast: directed "
14418 			    "broadcast to 0x%x\n",
14419 			    ntohl(ire->ire_addr)));
14420 			mp1 = copymsg(mp);
14421 			if (mp1) {
14422 				switch (ipha->ipha_protocol) {
14423 				case IPPROTO_UDP:
14424 					ip_udp_input(q, mp1, ipha, ire, ill);
14425 					break;
14426 				default:
14427 					ip_proto_input(q, mp1, ipha, ire, ill,
14428 					    0);
14429 					break;
14430 				}
14431 			}
14432 			/*
14433 			 * Adjust ttl to 2 (1+1 - the forward engine
14434 			 * will decrement it by one.
14435 			 */
14436 			if (ip_csum_hdr(ipha)) {
14437 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14438 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14439 				freemsg(mp);
14440 				ire_refrele(ire);
14441 				return (NULL);
14442 			}
14443 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14444 			ipha->ipha_hdr_checksum = 0;
14445 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14446 			ip_rput_process_forward(q, mp, ire, ipha,
14447 			    ill, ll_multicast);
14448 			ire_refrele(ire);
14449 			return (NULL);
14450 		}
14451 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14452 		    ntohl(ire->ire_addr)));
14453 	}
14454 
14455 
14456 	/* Restore any hardware checksum flags */
14457 	DB_CKSUMFLAGS(mp) = hcksumflags;
14458 	return (ire);
14459 }
14460 
14461 /* ARGSUSED */
14462 static boolean_t
14463 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14464     int *ll_multicast, ipaddr_t *dstp)
14465 {
14466 	ip_stack_t	*ipst = ill->ill_ipst;
14467 
14468 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14469 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14470 	    ntohs(ipha->ipha_length));
14471 
14472 	/*
14473 	 * Forward packets only if we have joined the allmulti
14474 	 * group on this interface.
14475 	 */
14476 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14477 		int retval;
14478 
14479 		/*
14480 		 * Clear the indication that this may have hardware
14481 		 * checksum as we are not using it.
14482 		 */
14483 		DB_CKSUMFLAGS(mp) = 0;
14484 		retval = ip_mforward(ill, ipha, mp);
14485 		/* ip_mforward updates mib variables if needed */
14486 		/* clear b_prev - used by ip_mroute_decap */
14487 		mp->b_prev = NULL;
14488 
14489 		switch (retval) {
14490 		case 0:
14491 			/*
14492 			 * pkt is okay and arrived on phyint.
14493 			 *
14494 			 * If we are running as a multicast router
14495 			 * we need to see all IGMP and/or PIM packets.
14496 			 */
14497 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14498 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14499 				goto done;
14500 			}
14501 			break;
14502 		case -1:
14503 			/* pkt is mal-formed, toss it */
14504 			goto drop_pkt;
14505 		case 1:
14506 			/* pkt is okay and arrived on a tunnel */
14507 			/*
14508 			 * If we are running a multicast router
14509 			 *  we need to see all igmp packets.
14510 			 */
14511 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14512 				*dstp = INADDR_BROADCAST;
14513 				*ll_multicast = 1;
14514 				return (B_FALSE);
14515 			}
14516 
14517 			goto drop_pkt;
14518 		}
14519 	}
14520 
14521 	ILM_WALKER_HOLD(ill);
14522 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14523 		/*
14524 		 * This might just be caused by the fact that
14525 		 * multiple IP Multicast addresses map to the same
14526 		 * link layer multicast - no need to increment counter!
14527 		 */
14528 		ILM_WALKER_RELE(ill);
14529 		freemsg(mp);
14530 		return (B_TRUE);
14531 	}
14532 	ILM_WALKER_RELE(ill);
14533 done:
14534 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14535 	/*
14536 	 * This assumes the we deliver to all streams for multicast
14537 	 * and broadcast packets.
14538 	 */
14539 	*dstp = INADDR_BROADCAST;
14540 	*ll_multicast = 1;
14541 	return (B_FALSE);
14542 drop_pkt:
14543 	ip2dbg(("ip_rput: drop pkt\n"));
14544 	freemsg(mp);
14545 	return (B_TRUE);
14546 }
14547 
14548 /*
14549  * This function is used to both return an indication of whether or not
14550  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14551  * and in doing so, determine whether or not it is broadcast vs multicast.
14552  * For it to be a broadcast packet, we must have the appropriate mblk_t
14553  * hanging off the ill_t.  If this is either not present or doesn't match
14554  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14555  * to be multicast.  Thus NICs that have no broadcast address (or no
14556  * capability for one, such as point to point links) cannot return as
14557  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14558  * the return values simplifies the current use of the return value of this
14559  * function, which is to pass through the multicast/broadcast characteristic
14560  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14561  * changing the return value to some other symbol demands the appropriate
14562  * "translation" when hpe_flags is set prior to calling hook_run() for
14563  * packet events.
14564  */
14565 int
14566 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14567 {
14568 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14569 	mblk_t *bmp;
14570 
14571 	if (ind->dl_group_address) {
14572 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14573 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14574 		    MBLKL(mb) &&
14575 		    (bmp = ill->ill_bcast_mp) != NULL) {
14576 			dl_unitdata_req_t *dlur;
14577 			uint8_t *bphys_addr;
14578 
14579 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14580 			if (ill->ill_sap_length < 0)
14581 				bphys_addr = (uchar_t *)dlur +
14582 				    dlur->dl_dest_addr_offset;
14583 			else
14584 				bphys_addr = (uchar_t *)dlur +
14585 				    dlur->dl_dest_addr_offset +
14586 				    ill->ill_sap_length;
14587 
14588 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14589 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14590 				return (HPE_BROADCAST);
14591 			}
14592 			return (HPE_MULTICAST);
14593 		}
14594 		return (HPE_MULTICAST);
14595 	}
14596 	return (0);
14597 }
14598 
14599 static boolean_t
14600 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14601     int *ll_multicast, mblk_t **mpp)
14602 {
14603 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14604 	boolean_t must_copy = B_FALSE;
14605 	struct iocblk   *iocp;
14606 	ipha_t		*ipha;
14607 	ip_stack_t	*ipst = ill->ill_ipst;
14608 
14609 #define	rptr    ((uchar_t *)ipha)
14610 
14611 	first_mp = *first_mpp;
14612 	mp = *mpp;
14613 
14614 	ASSERT(first_mp == mp);
14615 
14616 	/*
14617 	 * if db_ref > 1 then copymsg and free original. Packet may be
14618 	 * changed and do not want other entity who has a reference to this
14619 	 * message to trip over the changes. This is a blind change because
14620 	 * trying to catch all places that might change packet is too
14621 	 * difficult (since it may be a module above this one)
14622 	 *
14623 	 * This corresponds to the non-fast path case. We walk down the full
14624 	 * chain in this case, and check the db_ref count of all the dblks,
14625 	 * and do a copymsg if required. It is possible that the db_ref counts
14626 	 * of the data blocks in the mblk chain can be different.
14627 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14628 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14629 	 * 'snoop' is running.
14630 	 */
14631 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14632 		if (mp1->b_datap->db_ref > 1) {
14633 			must_copy = B_TRUE;
14634 			break;
14635 		}
14636 	}
14637 
14638 	if (must_copy) {
14639 		mp1 = copymsg(mp);
14640 		if (mp1 == NULL) {
14641 			for (mp1 = mp; mp1 != NULL;
14642 			    mp1 = mp1->b_cont) {
14643 				mp1->b_next = NULL;
14644 				mp1->b_prev = NULL;
14645 			}
14646 			freemsg(mp);
14647 			if (ill != NULL) {
14648 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14649 			} else {
14650 				BUMP_MIB(&ipst->ips_ip_mib,
14651 				    ipIfStatsInDiscards);
14652 			}
14653 			return (B_TRUE);
14654 		}
14655 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14656 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14657 			/* Copy b_prev - used by ip_mroute_decap */
14658 			to_mp->b_prev = from_mp->b_prev;
14659 			from_mp->b_prev = NULL;
14660 		}
14661 		*first_mpp = first_mp = mp1;
14662 		freemsg(mp);
14663 		mp = mp1;
14664 		*mpp = mp1;
14665 	}
14666 
14667 	ipha = (ipha_t *)mp->b_rptr;
14668 
14669 	/*
14670 	 * previous code has a case for M_DATA.
14671 	 * We want to check how that happens.
14672 	 */
14673 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14674 	switch (first_mp->b_datap->db_type) {
14675 	case M_PROTO:
14676 	case M_PCPROTO:
14677 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14678 		    DL_UNITDATA_IND) {
14679 			/* Go handle anything other than data elsewhere. */
14680 			ip_rput_dlpi(q, mp);
14681 			return (B_TRUE);
14682 		}
14683 
14684 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14685 		/* Ditch the DLPI header. */
14686 		mp1 = mp->b_cont;
14687 		ASSERT(first_mp == mp);
14688 		*first_mpp = mp1;
14689 		freeb(mp);
14690 		*mpp = mp1;
14691 		return (B_FALSE);
14692 	case M_IOCACK:
14693 		ip1dbg(("got iocack "));
14694 		iocp = (struct iocblk *)mp->b_rptr;
14695 		switch (iocp->ioc_cmd) {
14696 		case DL_IOC_HDR_INFO:
14697 			ill = (ill_t *)q->q_ptr;
14698 			ill_fastpath_ack(ill, mp);
14699 			return (B_TRUE);
14700 		case SIOCSTUNPARAM:
14701 		case OSIOCSTUNPARAM:
14702 			/* Go through qwriter_ip */
14703 			break;
14704 		case SIOCGTUNPARAM:
14705 		case OSIOCGTUNPARAM:
14706 			ip_rput_other(NULL, q, mp, NULL);
14707 			return (B_TRUE);
14708 		default:
14709 			putnext(q, mp);
14710 			return (B_TRUE);
14711 		}
14712 		/* FALLTHRU */
14713 	case M_ERROR:
14714 	case M_HANGUP:
14715 		/*
14716 		 * Since this is on the ill stream we unconditionally
14717 		 * bump up the refcount
14718 		 */
14719 		ill_refhold(ill);
14720 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14721 		return (B_TRUE);
14722 	case M_CTL:
14723 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14724 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14725 		    IPHADA_M_CTL)) {
14726 			/*
14727 			 * It's an IPsec accelerated packet.
14728 			 * Make sure that the ill from which we received the
14729 			 * packet has enabled IPsec hardware acceleration.
14730 			 */
14731 			if (!(ill->ill_capabilities &
14732 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14733 				/* IPsec kstats: bean counter */
14734 				freemsg(mp);
14735 				return (B_TRUE);
14736 			}
14737 
14738 			/*
14739 			 * Make mp point to the mblk following the M_CTL,
14740 			 * then process according to type of mp.
14741 			 * After this processing, first_mp will point to
14742 			 * the data-attributes and mp to the pkt following
14743 			 * the M_CTL.
14744 			 */
14745 			mp = first_mp->b_cont;
14746 			if (mp == NULL) {
14747 				freemsg(first_mp);
14748 				return (B_TRUE);
14749 			}
14750 			/*
14751 			 * A Hardware Accelerated packet can only be M_DATA
14752 			 * ESP or AH packet.
14753 			 */
14754 			if (mp->b_datap->db_type != M_DATA) {
14755 				/* non-M_DATA IPsec accelerated packet */
14756 				IPSECHW_DEBUG(IPSECHW_PKT,
14757 				    ("non-M_DATA IPsec accelerated pkt\n"));
14758 				freemsg(first_mp);
14759 				return (B_TRUE);
14760 			}
14761 			ipha = (ipha_t *)mp->b_rptr;
14762 			if (ipha->ipha_protocol != IPPROTO_AH &&
14763 			    ipha->ipha_protocol != IPPROTO_ESP) {
14764 				IPSECHW_DEBUG(IPSECHW_PKT,
14765 				    ("non-M_DATA IPsec accelerated pkt\n"));
14766 				freemsg(first_mp);
14767 				return (B_TRUE);
14768 			}
14769 			*mpp = mp;
14770 			return (B_FALSE);
14771 		}
14772 		putnext(q, mp);
14773 		return (B_TRUE);
14774 	case M_IOCNAK:
14775 		ip1dbg(("got iocnak "));
14776 		iocp = (struct iocblk *)mp->b_rptr;
14777 		switch (iocp->ioc_cmd) {
14778 		case SIOCSTUNPARAM:
14779 		case OSIOCSTUNPARAM:
14780 			/*
14781 			 * Since this is on the ill stream we unconditionally
14782 			 * bump up the refcount
14783 			 */
14784 			ill_refhold(ill);
14785 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14786 			return (B_TRUE);
14787 		case DL_IOC_HDR_INFO:
14788 		case SIOCGTUNPARAM:
14789 		case OSIOCGTUNPARAM:
14790 			ip_rput_other(NULL, q, mp, NULL);
14791 			return (B_TRUE);
14792 		default:
14793 			break;
14794 		}
14795 		/* FALLTHRU */
14796 	default:
14797 		putnext(q, mp);
14798 		return (B_TRUE);
14799 	}
14800 }
14801 
14802 /* Read side put procedure.  Packets coming from the wire arrive here. */
14803 void
14804 ip_rput(queue_t *q, mblk_t *mp)
14805 {
14806 	ill_t	*ill;
14807 	union DL_primitives *dl;
14808 
14809 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14810 
14811 	ill = (ill_t *)q->q_ptr;
14812 
14813 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14814 		/*
14815 		 * If things are opening or closing, only accept high-priority
14816 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14817 		 * created; on close, things hanging off the ill may have been
14818 		 * freed already.)
14819 		 */
14820 		dl = (union DL_primitives *)mp->b_rptr;
14821 		if (DB_TYPE(mp) != M_PCPROTO ||
14822 		    dl->dl_primitive == DL_UNITDATA_IND) {
14823 			/*
14824 			 * SIOC[GS]TUNPARAM ioctls can come here.
14825 			 */
14826 			inet_freemsg(mp);
14827 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14828 			    "ip_rput_end: q %p (%S)", q, "uninit");
14829 			return;
14830 		}
14831 	}
14832 
14833 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14834 	    "ip_rput_end: q %p (%S)", q, "end");
14835 
14836 	ip_input(ill, NULL, mp, NULL);
14837 }
14838 
14839 static mblk_t *
14840 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14841 {
14842 	mblk_t *mp1;
14843 	boolean_t adjusted = B_FALSE;
14844 	ip_stack_t *ipst = ill->ill_ipst;
14845 
14846 	IP_STAT(ipst, ip_db_ref);
14847 	/*
14848 	 * The IP_RECVSLLA option depends on having the
14849 	 * link layer header. First check that:
14850 	 * a> the underlying device is of type ether,
14851 	 * since this option is currently supported only
14852 	 * over ethernet.
14853 	 * b> there is enough room to copy over the link
14854 	 * layer header.
14855 	 *
14856 	 * Once the checks are done, adjust rptr so that
14857 	 * the link layer header will be copied via
14858 	 * copymsg. Note that, IFT_ETHER may be returned
14859 	 * by some non-ethernet drivers but in this case
14860 	 * the second check will fail.
14861 	 */
14862 	if (ill->ill_type == IFT_ETHER &&
14863 	    (mp->b_rptr - mp->b_datap->db_base) >=
14864 	    sizeof (struct ether_header)) {
14865 		mp->b_rptr -= sizeof (struct ether_header);
14866 		adjusted = B_TRUE;
14867 	}
14868 	mp1 = copymsg(mp);
14869 
14870 	if (mp1 == NULL) {
14871 		mp->b_next = NULL;
14872 		/* clear b_prev - used by ip_mroute_decap */
14873 		mp->b_prev = NULL;
14874 		freemsg(mp);
14875 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14876 		return (NULL);
14877 	}
14878 
14879 	if (adjusted) {
14880 		/*
14881 		 * Copy is done. Restore the pointer in
14882 		 * the _new_ mblk
14883 		 */
14884 		mp1->b_rptr += sizeof (struct ether_header);
14885 	}
14886 
14887 	/* Copy b_prev - used by ip_mroute_decap */
14888 	mp1->b_prev = mp->b_prev;
14889 	mp->b_prev = NULL;
14890 
14891 	/* preserve the hardware checksum flags and data, if present */
14892 	if (DB_CKSUMFLAGS(mp) != 0) {
14893 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14894 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14895 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14896 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14897 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14898 	}
14899 
14900 	freemsg(mp);
14901 	return (mp1);
14902 }
14903 
14904 /*
14905  * Direct read side procedure capable of dealing with chains. GLDv3 based
14906  * drivers call this function directly with mblk chains while STREAMS
14907  * read side procedure ip_rput() calls this for single packet with ip_ring
14908  * set to NULL to process one packet at a time.
14909  *
14910  * The ill will always be valid if this function is called directly from
14911  * the driver.
14912  *
14913  * If ip_input() is called from GLDv3:
14914  *
14915  *   - This must be a non-VLAN IP stream.
14916  *   - 'mp' is either an untagged or a special priority-tagged packet.
14917  *   - Any VLAN tag that was in the MAC header has been stripped.
14918  *
14919  * If the IP header in packet is not 32-bit aligned, every message in the
14920  * chain will be aligned before further operations. This is required on SPARC
14921  * platform.
14922  */
14923 /* ARGSUSED */
14924 void
14925 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14926     struct mac_header_info_s *mhip)
14927 {
14928 	ipaddr_t		dst = NULL;
14929 	ipaddr_t		prev_dst;
14930 	ire_t			*ire = NULL;
14931 	ipha_t			*ipha;
14932 	uint_t			pkt_len;
14933 	ssize_t			len;
14934 	uint_t			opt_len;
14935 	int			ll_multicast;
14936 	int			cgtp_flt_pkt;
14937 	queue_t			*q = ill->ill_rq;
14938 	squeue_t		*curr_sqp = NULL;
14939 	mblk_t 			*head = NULL;
14940 	mblk_t			*tail = NULL;
14941 	mblk_t			*first_mp;
14942 	mblk_t 			*mp;
14943 	mblk_t			*dmp;
14944 	int			cnt = 0;
14945 	ip_stack_t		*ipst = ill->ill_ipst;
14946 
14947 	ASSERT(mp_chain != NULL);
14948 	ASSERT(ill != NULL);
14949 
14950 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14951 
14952 #define	rptr	((uchar_t *)ipha)
14953 
14954 	while (mp_chain != NULL) {
14955 		first_mp = mp = mp_chain;
14956 		mp_chain = mp_chain->b_next;
14957 		mp->b_next = NULL;
14958 		ll_multicast = 0;
14959 
14960 		/*
14961 		 * We do ire caching from one iteration to
14962 		 * another. In the event the packet chain contains
14963 		 * all packets from the same dst, this caching saves
14964 		 * an ire_cache_lookup for each of the succeeding
14965 		 * packets in a packet chain.
14966 		 */
14967 		prev_dst = dst;
14968 
14969 		/*
14970 		 * if db_ref > 1 then copymsg and free original. Packet
14971 		 * may be changed and we do not want the other entity
14972 		 * who has a reference to this message to trip over the
14973 		 * changes. This is a blind change because trying to
14974 		 * catch all places that might change the packet is too
14975 		 * difficult.
14976 		 *
14977 		 * This corresponds to the fast path case, where we have
14978 		 * a chain of M_DATA mblks.  We check the db_ref count
14979 		 * of only the 1st data block in the mblk chain. There
14980 		 * doesn't seem to be a reason why a device driver would
14981 		 * send up data with varying db_ref counts in the mblk
14982 		 * chain. In any case the Fast path is a private
14983 		 * interface, and our drivers don't do such a thing.
14984 		 * Given the above assumption, there is no need to walk
14985 		 * down the entire mblk chain (which could have a
14986 		 * potential performance problem)
14987 		 */
14988 
14989 		if (DB_REF(mp) > 1) {
14990 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14991 				continue;
14992 		}
14993 
14994 		/*
14995 		 * Check and align the IP header.
14996 		 */
14997 		first_mp = mp;
14998 		if (DB_TYPE(mp) == M_DATA) {
14999 			dmp = mp;
15000 		} else if (DB_TYPE(mp) == M_PROTO &&
15001 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15002 			dmp = mp->b_cont;
15003 		} else {
15004 			dmp = NULL;
15005 		}
15006 		if (dmp != NULL) {
15007 			/*
15008 			 * IP header ptr not aligned?
15009 			 * OR IP header not complete in first mblk
15010 			 */
15011 			if (!OK_32PTR(dmp->b_rptr) ||
15012 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15013 				if (!ip_check_and_align_header(q, dmp, ipst))
15014 					continue;
15015 			}
15016 		}
15017 
15018 		/*
15019 		 * ip_input fast path
15020 		 */
15021 
15022 		/* mblk type is not M_DATA */
15023 		if (DB_TYPE(mp) != M_DATA) {
15024 			if (ip_rput_process_notdata(q, &first_mp, ill,
15025 			    &ll_multicast, &mp))
15026 				continue;
15027 
15028 			/*
15029 			 * The only way we can get here is if we had a
15030 			 * packet that was either a DL_UNITDATA_IND or
15031 			 * an M_CTL for an IPsec accelerated packet.
15032 			 *
15033 			 * In either case, the first_mp will point to
15034 			 * the leading M_PROTO or M_CTL.
15035 			 */
15036 			ASSERT(first_mp != NULL);
15037 		} else if (mhip != NULL) {
15038 			/*
15039 			 * ll_multicast is set here so that it is ready
15040 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15041 			 * manipulates ll_multicast in the same fashion when
15042 			 * called from ip_rput_process_notdata.
15043 			 */
15044 			switch (mhip->mhi_dsttype) {
15045 			case MAC_ADDRTYPE_MULTICAST :
15046 				ll_multicast = HPE_MULTICAST;
15047 				break;
15048 			case MAC_ADDRTYPE_BROADCAST :
15049 				ll_multicast = HPE_BROADCAST;
15050 				break;
15051 			default :
15052 				break;
15053 			}
15054 		}
15055 
15056 		/* Make sure its an M_DATA and that its aligned */
15057 		ASSERT(DB_TYPE(mp) == M_DATA);
15058 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15059 
15060 		ipha = (ipha_t *)mp->b_rptr;
15061 		len = mp->b_wptr - rptr;
15062 		pkt_len = ntohs(ipha->ipha_length);
15063 
15064 		/*
15065 		 * We must count all incoming packets, even if they end
15066 		 * up being dropped later on.
15067 		 */
15068 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15069 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15070 
15071 		/* multiple mblk or too short */
15072 		len -= pkt_len;
15073 		if (len != 0) {
15074 			/*
15075 			 * Make sure we have data length consistent
15076 			 * with the IP header.
15077 			 */
15078 			if (mp->b_cont == NULL) {
15079 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15080 					BUMP_MIB(ill->ill_ip_mib,
15081 					    ipIfStatsInHdrErrors);
15082 					ip2dbg(("ip_input: drop pkt\n"));
15083 					freemsg(mp);
15084 					continue;
15085 				}
15086 				mp->b_wptr = rptr + pkt_len;
15087 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15088 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15089 					BUMP_MIB(ill->ill_ip_mib,
15090 					    ipIfStatsInHdrErrors);
15091 					ip2dbg(("ip_input: drop pkt\n"));
15092 					freemsg(mp);
15093 					continue;
15094 				}
15095 				(void) adjmsg(mp, -len);
15096 				IP_STAT(ipst, ip_multimblk3);
15097 			}
15098 		}
15099 
15100 		/* Obtain the dst of the current packet */
15101 		dst = ipha->ipha_dst;
15102 
15103 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15104 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15105 		    ipha, ip6_t *, NULL, int, 0);
15106 
15107 		/*
15108 		 * The following test for loopback is faster than
15109 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15110 		 * operations.
15111 		 * Note that these addresses are always in network byte order
15112 		 */
15113 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15114 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15115 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15116 			freemsg(mp);
15117 			continue;
15118 		}
15119 
15120 		/*
15121 		 * The event for packets being received from a 'physical'
15122 		 * interface is placed after validation of the source and/or
15123 		 * destination address as being local so that packets can be
15124 		 * redirected to loopback addresses using ipnat.
15125 		 */
15126 		DTRACE_PROBE4(ip4__physical__in__start,
15127 		    ill_t *, ill, ill_t *, NULL,
15128 		    ipha_t *, ipha, mblk_t *, first_mp);
15129 
15130 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15131 		    ipst->ips_ipv4firewall_physical_in,
15132 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15133 
15134 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15135 
15136 		if (first_mp == NULL) {
15137 			continue;
15138 		}
15139 		dst = ipha->ipha_dst;
15140 
15141 		/*
15142 		 * Attach any necessary label information to
15143 		 * this packet
15144 		 */
15145 		if (is_system_labeled() &&
15146 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15147 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15148 			freemsg(mp);
15149 			continue;
15150 		}
15151 
15152 		if (ipst->ips_ipobs_enabled) {
15153 			zoneid_t dzone;
15154 
15155 			/*
15156 			 * On the inbound path the src zone will be unknown as
15157 			 * this packet has come from the wire.
15158 			 */
15159 			dzone = ip_get_zoneid_v4(dst, mp, ipst, ALL_ZONES);
15160 			ipobs_hook(mp, IPOBS_HOOK_INBOUND, ALL_ZONES, dzone,
15161 			    ill, IPV4_VERSION, 0, ipst);
15162 		}
15163 
15164 		/*
15165 		 * Reuse the cached ire only if the ipha_dst of the previous
15166 		 * packet is the same as the current packet AND it is not
15167 		 * INADDR_ANY.
15168 		 */
15169 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15170 		    (ire != NULL)) {
15171 			ire_refrele(ire);
15172 			ire = NULL;
15173 		}
15174 
15175 		opt_len = ipha->ipha_version_and_hdr_length -
15176 		    IP_SIMPLE_HDR_VERSION;
15177 
15178 		/*
15179 		 * Check to see if we can take the fastpath.
15180 		 * That is possible if the following conditions are met
15181 		 *	o Tsol disabled
15182 		 *	o CGTP disabled
15183 		 *	o ipp_action_count is 0
15184 		 *	o no options in the packet
15185 		 *	o not a RSVP packet
15186 		 * 	o not a multicast packet
15187 		 *	o ill not in IP_DHCPINIT_IF mode
15188 		 */
15189 		if (!is_system_labeled() &&
15190 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15191 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15192 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15193 			if (ire == NULL)
15194 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15195 				    ipst);
15196 
15197 			/* incoming packet is for forwarding */
15198 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15199 				ire = ip_fast_forward(ire, dst, ill, mp);
15200 				continue;
15201 			}
15202 			/* incoming packet is for local consumption */
15203 			if (ire->ire_type & IRE_LOCAL)
15204 				goto local;
15205 		}
15206 
15207 		/*
15208 		 * Disable ire caching for anything more complex
15209 		 * than the simple fast path case we checked for above.
15210 		 */
15211 		if (ire != NULL) {
15212 			ire_refrele(ire);
15213 			ire = NULL;
15214 		}
15215 
15216 		/*
15217 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15218 		 * server to unicast DHCP packets to a DHCP client using the
15219 		 * IP address it is offering to the client.  This can be
15220 		 * disabled through the "broadcast bit", but not all DHCP
15221 		 * servers honor that bit.  Therefore, to interoperate with as
15222 		 * many DHCP servers as possible, the DHCP client allows the
15223 		 * server to unicast, but we treat those packets as broadcast
15224 		 * here.  Note that we don't rewrite the packet itself since
15225 		 * (a) that would mess up the checksums and (b) the DHCP
15226 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15227 		 * hand it the packet regardless.
15228 		 */
15229 		if (ill->ill_dhcpinit != 0 &&
15230 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15231 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15232 			udpha_t *udpha;
15233 
15234 			/*
15235 			 * Reload ipha since pullupmsg() can change b_rptr.
15236 			 */
15237 			ipha = (ipha_t *)mp->b_rptr;
15238 			udpha = (udpha_t *)&ipha[1];
15239 
15240 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15241 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15242 				    mblk_t *, mp);
15243 				dst = INADDR_BROADCAST;
15244 			}
15245 		}
15246 
15247 		/* Full-blown slow path */
15248 		if (opt_len != 0) {
15249 			if (len != 0)
15250 				IP_STAT(ipst, ip_multimblk4);
15251 			else
15252 				IP_STAT(ipst, ip_ipoptions);
15253 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15254 			    &dst, ipst))
15255 				continue;
15256 		}
15257 
15258 		/*
15259 		 * Invoke the CGTP (multirouting) filtering module to process
15260 		 * the incoming packet. Packets identified as duplicates
15261 		 * must be discarded. Filtering is active only if the
15262 		 * the ip_cgtp_filter ndd variable is non-zero.
15263 		 */
15264 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15265 		if (ipst->ips_ip_cgtp_filter &&
15266 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15267 			netstackid_t stackid;
15268 
15269 			stackid = ipst->ips_netstack->netstack_stackid;
15270 			cgtp_flt_pkt =
15271 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15272 			    ill->ill_phyint->phyint_ifindex, mp);
15273 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15274 				freemsg(first_mp);
15275 				continue;
15276 			}
15277 		}
15278 
15279 		/*
15280 		 * If rsvpd is running, let RSVP daemon handle its processing
15281 		 * and forwarding of RSVP multicast/unicast packets.
15282 		 * If rsvpd is not running but mrouted is running, RSVP
15283 		 * multicast packets are forwarded as multicast traffic
15284 		 * and RSVP unicast packets are forwarded by unicast router.
15285 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15286 		 * packets are not forwarded, but the unicast packets are
15287 		 * forwarded like unicast traffic.
15288 		 */
15289 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15290 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15291 		    NULL) {
15292 			/* RSVP packet and rsvpd running. Treat as ours */
15293 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15294 			/*
15295 			 * This assumes that we deliver to all streams for
15296 			 * multicast and broadcast packets.
15297 			 * We have to force ll_multicast to 1 to handle the
15298 			 * M_DATA messages passed in from ip_mroute_decap.
15299 			 */
15300 			dst = INADDR_BROADCAST;
15301 			ll_multicast = 1;
15302 		} else if (CLASSD(dst)) {
15303 			/* packet is multicast */
15304 			mp->b_next = NULL;
15305 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15306 			    &ll_multicast, &dst))
15307 				continue;
15308 		}
15309 
15310 		if (ire == NULL) {
15311 			ire = ire_cache_lookup(dst, ALL_ZONES,
15312 			    MBLK_GETLABEL(mp), ipst);
15313 		}
15314 
15315 		if (ire != NULL && ire->ire_stq != NULL &&
15316 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15317 		    ire->ire_zoneid != ALL_ZONES) {
15318 			/*
15319 			 * Should only use IREs that are visible from the
15320 			 * global zone for forwarding.
15321 			 */
15322 			ire_refrele(ire);
15323 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15324 			    MBLK_GETLABEL(mp), ipst);
15325 		}
15326 
15327 		if (ire == NULL) {
15328 			/*
15329 			 * No IRE for this destination, so it can't be for us.
15330 			 * Unless we are forwarding, drop the packet.
15331 			 * We have to let source routed packets through
15332 			 * since we don't yet know if they are 'ping -l'
15333 			 * packets i.e. if they will go out over the
15334 			 * same interface as they came in on.
15335 			 */
15336 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15337 			if (ire == NULL)
15338 				continue;
15339 		}
15340 
15341 		/*
15342 		 * Broadcast IRE may indicate either broadcast or
15343 		 * multicast packet
15344 		 */
15345 		if (ire->ire_type == IRE_BROADCAST) {
15346 			/*
15347 			 * Skip broadcast checks if packet is UDP multicast;
15348 			 * we'd rather not enter ip_rput_process_broadcast()
15349 			 * unless the packet is broadcast for real, since
15350 			 * that routine is a no-op for multicast.
15351 			 */
15352 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15353 			    !CLASSD(ipha->ipha_dst)) {
15354 				ire = ip_rput_process_broadcast(&q, mp,
15355 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15356 				    ll_multicast);
15357 				if (ire == NULL)
15358 					continue;
15359 			}
15360 		} else if (ire->ire_stq != NULL) {
15361 			/* fowarding? */
15362 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15363 			    ll_multicast);
15364 			/* ip_rput_process_forward consumed the packet */
15365 			continue;
15366 		}
15367 
15368 local:
15369 		/*
15370 		 * If the queue in the ire is different to the ingress queue
15371 		 * then we need to check to see if we can accept the packet.
15372 		 * Note that for multicast packets and broadcast packets sent
15373 		 * to a broadcast address which is shared between multiple
15374 		 * interfaces we should not do this since we just got a random
15375 		 * broadcast ire.
15376 		 */
15377 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15378 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15379 			    ill)) == NULL) {
15380 				/* Drop packet */
15381 				BUMP_MIB(ill->ill_ip_mib,
15382 				    ipIfStatsForwProhibits);
15383 				freemsg(mp);
15384 				continue;
15385 			}
15386 			if (ire->ire_rfq != NULL)
15387 				q = ire->ire_rfq;
15388 		}
15389 
15390 		switch (ipha->ipha_protocol) {
15391 		case IPPROTO_TCP:
15392 			ASSERT(first_mp == mp);
15393 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15394 			    mp, 0, q, ip_ring)) != NULL) {
15395 				if (curr_sqp == NULL) {
15396 					curr_sqp = GET_SQUEUE(mp);
15397 					ASSERT(cnt == 0);
15398 					cnt++;
15399 					head = tail = mp;
15400 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15401 					ASSERT(tail != NULL);
15402 					cnt++;
15403 					tail->b_next = mp;
15404 					tail = mp;
15405 				} else {
15406 					/*
15407 					 * A different squeue. Send the
15408 					 * chain for the previous squeue on
15409 					 * its way. This shouldn't happen
15410 					 * often unless interrupt binding
15411 					 * changes.
15412 					 */
15413 					IP_STAT(ipst, ip_input_multi_squeue);
15414 					squeue_enter_chain(curr_sqp, head,
15415 					    tail, cnt, SQTAG_IP_INPUT);
15416 					curr_sqp = GET_SQUEUE(mp);
15417 					head = mp;
15418 					tail = mp;
15419 					cnt = 1;
15420 				}
15421 			}
15422 			continue;
15423 		case IPPROTO_UDP:
15424 			ASSERT(first_mp == mp);
15425 			ip_udp_input(q, mp, ipha, ire, ill);
15426 			continue;
15427 		case IPPROTO_SCTP:
15428 			ASSERT(first_mp == mp);
15429 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15430 			    q, dst);
15431 			/* ire has been released by ip_sctp_input */
15432 			ire = NULL;
15433 			continue;
15434 		default:
15435 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15436 			continue;
15437 		}
15438 	}
15439 
15440 	if (ire != NULL)
15441 		ire_refrele(ire);
15442 
15443 	if (head != NULL)
15444 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15445 
15446 	/*
15447 	 * This code is there just to make netperf/ttcp look good.
15448 	 *
15449 	 * Its possible that after being in polling mode (and having cleared
15450 	 * the backlog), squeues have turned the interrupt frequency higher
15451 	 * to improve latency at the expense of more CPU utilization (less
15452 	 * packets per interrupts or more number of interrupts). Workloads
15453 	 * like ttcp/netperf do manage to tickle polling once in a while
15454 	 * but for the remaining time, stay in higher interrupt mode since
15455 	 * their packet arrival rate is pretty uniform and this shows up
15456 	 * as higher CPU utilization. Since people care about CPU utilization
15457 	 * while running netperf/ttcp, turn the interrupt frequency back to
15458 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15459 	 */
15460 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15461 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15462 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15463 			ip_ring->rr_blank(ip_ring->rr_handle,
15464 			    ip_ring->rr_normal_blank_time,
15465 			    ip_ring->rr_normal_pkt_cnt);
15466 		}
15467 		}
15468 
15469 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15470 	    "ip_input_end: q %p (%S)", q, "end");
15471 #undef  rptr
15472 }
15473 
15474 static void
15475 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15476     t_uscalar_t err)
15477 {
15478 	if (dl_err == DL_SYSERR) {
15479 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15480 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15481 		    ill->ill_name, dl_primstr(prim), err);
15482 		return;
15483 	}
15484 
15485 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15486 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15487 	    dl_errstr(dl_err));
15488 }
15489 
15490 /*
15491  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15492  * than DL_UNITDATA_IND messages. If we need to process this message
15493  * exclusively, we call qwriter_ip, in which case we also need to call
15494  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15495  */
15496 void
15497 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15498 {
15499 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15500 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15501 	ill_t		*ill = q->q_ptr;
15502 	t_uscalar_t	prim = dloa->dl_primitive;
15503 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15504 
15505 	ip1dbg(("ip_rput_dlpi"));
15506 
15507 	/*
15508 	 * If we received an ACK but didn't send a request for it, then it
15509 	 * can't be part of any pending operation; discard up-front.
15510 	 */
15511 	switch (prim) {
15512 	case DL_ERROR_ACK:
15513 		reqprim = dlea->dl_error_primitive;
15514 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15515 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15516 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15517 		    dlea->dl_unix_errno));
15518 		break;
15519 	case DL_OK_ACK:
15520 		reqprim = dloa->dl_correct_primitive;
15521 		break;
15522 	case DL_INFO_ACK:
15523 		reqprim = DL_INFO_REQ;
15524 		break;
15525 	case DL_BIND_ACK:
15526 		reqprim = DL_BIND_REQ;
15527 		break;
15528 	case DL_PHYS_ADDR_ACK:
15529 		reqprim = DL_PHYS_ADDR_REQ;
15530 		break;
15531 	case DL_NOTIFY_ACK:
15532 		reqprim = DL_NOTIFY_REQ;
15533 		break;
15534 	case DL_CONTROL_ACK:
15535 		reqprim = DL_CONTROL_REQ;
15536 		break;
15537 	case DL_CAPABILITY_ACK:
15538 		reqprim = DL_CAPABILITY_REQ;
15539 		break;
15540 	}
15541 
15542 	if (prim != DL_NOTIFY_IND) {
15543 		if (reqprim == DL_PRIM_INVAL ||
15544 		    !ill_dlpi_pending(ill, reqprim)) {
15545 			/* Not a DLPI message we support or expected */
15546 			freemsg(mp);
15547 			return;
15548 		}
15549 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15550 		    dl_primstr(reqprim)));
15551 	}
15552 
15553 	switch (reqprim) {
15554 	case DL_UNBIND_REQ:
15555 		/*
15556 		 * NOTE: we mark the unbind as complete even if we got a
15557 		 * DL_ERROR_ACK, since there's not much else we can do.
15558 		 */
15559 		mutex_enter(&ill->ill_lock);
15560 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15561 		cv_signal(&ill->ill_cv);
15562 		mutex_exit(&ill->ill_lock);
15563 		break;
15564 
15565 	case DL_ENABMULTI_REQ:
15566 		if (prim == DL_OK_ACK) {
15567 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15568 				ill->ill_dlpi_multicast_state = IDS_OK;
15569 		}
15570 		break;
15571 	}
15572 
15573 	/*
15574 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15575 	 * need to become writer to continue to process it.  Because an
15576 	 * exclusive operation doesn't complete until replies to all queued
15577 	 * DLPI messages have been received, we know we're in the middle of an
15578 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15579 	 *
15580 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15581 	 * Since this is on the ill stream we unconditionally bump up the
15582 	 * refcount without doing ILL_CAN_LOOKUP().
15583 	 */
15584 	ill_refhold(ill);
15585 	if (prim == DL_NOTIFY_IND)
15586 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15587 	else
15588 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15589 }
15590 
15591 /*
15592  * Handling of DLPI messages that require exclusive access to the ipsq.
15593  *
15594  * Need to do ill_pending_mp_release on ioctl completion, which could
15595  * happen here. (along with mi_copy_done)
15596  */
15597 /* ARGSUSED */
15598 static void
15599 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15600 {
15601 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15602 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15603 	int		err = 0;
15604 	ill_t		*ill;
15605 	ipif_t		*ipif = NULL;
15606 	mblk_t		*mp1 = NULL;
15607 	conn_t		*connp = NULL;
15608 	t_uscalar_t	paddrreq;
15609 	mblk_t		*mp_hw;
15610 	boolean_t	success;
15611 	boolean_t	ioctl_aborted = B_FALSE;
15612 	boolean_t	log = B_TRUE;
15613 	ip_stack_t		*ipst;
15614 
15615 	ip1dbg(("ip_rput_dlpi_writer .."));
15616 	ill = (ill_t *)q->q_ptr;
15617 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15618 
15619 	ASSERT(IAM_WRITER_ILL(ill));
15620 
15621 	ipst = ill->ill_ipst;
15622 
15623 	/*
15624 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15625 	 * both are null or non-null. However we can assert that only
15626 	 * after grabbing the ipsq_lock. So we don't make any assertion
15627 	 * here and in other places in the code.
15628 	 */
15629 	ipif = ipsq->ipsq_pending_ipif;
15630 	/*
15631 	 * The current ioctl could have been aborted by the user and a new
15632 	 * ioctl to bring up another ill could have started. We could still
15633 	 * get a response from the driver later.
15634 	 */
15635 	if (ipif != NULL && ipif->ipif_ill != ill)
15636 		ioctl_aborted = B_TRUE;
15637 
15638 	switch (dloa->dl_primitive) {
15639 	case DL_ERROR_ACK:
15640 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15641 		    dl_primstr(dlea->dl_error_primitive)));
15642 
15643 		switch (dlea->dl_error_primitive) {
15644 		case DL_DISABMULTI_REQ:
15645 			if (!ill->ill_isv6)
15646 				ipsq_current_finish(ipsq);
15647 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15648 			break;
15649 		case DL_PROMISCON_REQ:
15650 		case DL_PROMISCOFF_REQ:
15651 		case DL_UNBIND_REQ:
15652 		case DL_ATTACH_REQ:
15653 		case DL_INFO_REQ:
15654 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15655 			break;
15656 		case DL_NOTIFY_REQ:
15657 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15658 			log = B_FALSE;
15659 			break;
15660 		case DL_PHYS_ADDR_REQ:
15661 			/*
15662 			 * For IPv6 only, there are two additional
15663 			 * phys_addr_req's sent to the driver to get the
15664 			 * IPv6 token and lla. This allows IP to acquire
15665 			 * the hardware address format for a given interface
15666 			 * without having built in knowledge of the hardware
15667 			 * address. ill_phys_addr_pend keeps track of the last
15668 			 * DL_PAR sent so we know which response we are
15669 			 * dealing with. ill_dlpi_done will update
15670 			 * ill_phys_addr_pend when it sends the next req.
15671 			 * We don't complete the IOCTL until all three DL_PARs
15672 			 * have been attempted, so set *_len to 0 and break.
15673 			 */
15674 			paddrreq = ill->ill_phys_addr_pend;
15675 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15676 			if (paddrreq == DL_IPV6_TOKEN) {
15677 				ill->ill_token_length = 0;
15678 				log = B_FALSE;
15679 				break;
15680 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15681 				ill->ill_nd_lla_len = 0;
15682 				log = B_FALSE;
15683 				break;
15684 			}
15685 			/*
15686 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15687 			 * We presumably have an IOCTL hanging out waiting
15688 			 * for completion. Find it and complete the IOCTL
15689 			 * with the error noted.
15690 			 * However, ill_dl_phys was called on an ill queue
15691 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15692 			 * set. But the ioctl is known to be pending on ill_wq.
15693 			 */
15694 			if (!ill->ill_ifname_pending)
15695 				break;
15696 			ill->ill_ifname_pending = 0;
15697 			if (!ioctl_aborted)
15698 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15699 			if (mp1 != NULL) {
15700 				/*
15701 				 * This operation (SIOCSLIFNAME) must have
15702 				 * happened on the ill. Assert there is no conn
15703 				 */
15704 				ASSERT(connp == NULL);
15705 				q = ill->ill_wq;
15706 			}
15707 			break;
15708 		case DL_BIND_REQ:
15709 			ill_dlpi_done(ill, DL_BIND_REQ);
15710 			if (ill->ill_ifname_pending)
15711 				break;
15712 			/*
15713 			 * Something went wrong with the bind.  We presumably
15714 			 * have an IOCTL hanging out waiting for completion.
15715 			 * Find it, take down the interface that was coming
15716 			 * up, and complete the IOCTL with the error noted.
15717 			 */
15718 			if (!ioctl_aborted)
15719 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15720 			if (mp1 != NULL) {
15721 				/*
15722 				 * This operation (SIOCSLIFFLAGS) must have
15723 				 * happened from a conn.
15724 				 */
15725 				ASSERT(connp != NULL);
15726 				q = CONNP_TO_WQ(connp);
15727 				if (ill->ill_move_in_progress) {
15728 					ILL_CLEAR_MOVE(ill);
15729 				}
15730 				(void) ipif_down(ipif, NULL, NULL);
15731 				/* error is set below the switch */
15732 			}
15733 			break;
15734 		case DL_ENABMULTI_REQ:
15735 			if (!ill->ill_isv6)
15736 				ipsq_current_finish(ipsq);
15737 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15738 
15739 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15740 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15741 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15742 				ipif_t *ipif;
15743 
15744 				printf("ip: joining multicasts failed (%d)"
15745 				    " on %s - will use link layer "
15746 				    "broadcasts for multicast\n",
15747 				    dlea->dl_errno, ill->ill_name);
15748 
15749 				/*
15750 				 * Set up the multicast mapping alone.
15751 				 * writer, so ok to access ill->ill_ipif
15752 				 * without any lock.
15753 				 */
15754 				ipif = ill->ill_ipif;
15755 				mutex_enter(&ill->ill_phyint->phyint_lock);
15756 				ill->ill_phyint->phyint_flags |=
15757 				    PHYI_MULTI_BCAST;
15758 				mutex_exit(&ill->ill_phyint->phyint_lock);
15759 
15760 				if (!ill->ill_isv6) {
15761 					(void) ipif_arp_setup_multicast(ipif,
15762 					    NULL);
15763 				} else {
15764 					(void) ipif_ndp_setup_multicast(ipif,
15765 					    NULL);
15766 				}
15767 			}
15768 			freemsg(mp);	/* Don't want to pass this up */
15769 			return;
15770 
15771 		case DL_CAPABILITY_REQ:
15772 		case DL_CONTROL_REQ:
15773 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15774 			ill->ill_dlpi_capab_state = IDS_FAILED;
15775 			freemsg(mp);
15776 			return;
15777 		}
15778 		/*
15779 		 * Note the error for IOCTL completion (mp1 is set when
15780 		 * ready to complete ioctl). If ill_ifname_pending_err is
15781 		 * set, an error occured during plumbing (ill_ifname_pending),
15782 		 * so we want to report that error.
15783 		 *
15784 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15785 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15786 		 * expected to get errack'd if the driver doesn't support
15787 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15788 		 * if these error conditions are encountered.
15789 		 */
15790 		if (mp1 != NULL) {
15791 			if (ill->ill_ifname_pending_err != 0)  {
15792 				err = ill->ill_ifname_pending_err;
15793 				ill->ill_ifname_pending_err = 0;
15794 			} else {
15795 				err = dlea->dl_unix_errno ?
15796 				    dlea->dl_unix_errno : ENXIO;
15797 			}
15798 		/*
15799 		 * If we're plumbing an interface and an error hasn't already
15800 		 * been saved, set ill_ifname_pending_err to the error passed
15801 		 * up. Ignore the error if log is B_FALSE (see comment above).
15802 		 */
15803 		} else if (log && ill->ill_ifname_pending &&
15804 		    ill->ill_ifname_pending_err == 0) {
15805 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15806 			    dlea->dl_unix_errno : ENXIO;
15807 		}
15808 
15809 		if (log)
15810 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15811 			    dlea->dl_errno, dlea->dl_unix_errno);
15812 		break;
15813 	case DL_CAPABILITY_ACK:
15814 		/* Call a routine to handle this one. */
15815 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15816 		ill_capability_ack(ill, mp);
15817 
15818 		/*
15819 		 * If the ack is due to renegotiation, we will need to send
15820 		 * a new CAPABILITY_REQ to start the renegotiation.
15821 		 */
15822 		if (ill->ill_capab_reneg) {
15823 			ill->ill_capab_reneg = B_FALSE;
15824 			ill_capability_probe(ill);
15825 		}
15826 		break;
15827 	case DL_CONTROL_ACK:
15828 		/* We treat all of these as "fire and forget" */
15829 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15830 		break;
15831 	case DL_INFO_ACK:
15832 		/* Call a routine to handle this one. */
15833 		ill_dlpi_done(ill, DL_INFO_REQ);
15834 		ip_ll_subnet_defaults(ill, mp);
15835 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15836 		return;
15837 	case DL_BIND_ACK:
15838 		/*
15839 		 * We should have an IOCTL waiting on this unless
15840 		 * sent by ill_dl_phys, in which case just return
15841 		 */
15842 		ill_dlpi_done(ill, DL_BIND_REQ);
15843 		if (ill->ill_ifname_pending)
15844 			break;
15845 
15846 		if (!ioctl_aborted)
15847 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15848 		if (mp1 == NULL)
15849 			break;
15850 		/*
15851 		 * Because mp1 was added by ill_dl_up(), and it always
15852 		 * passes a valid connp, connp must be valid here.
15853 		 */
15854 		ASSERT(connp != NULL);
15855 		q = CONNP_TO_WQ(connp);
15856 
15857 		/*
15858 		 * We are exclusive. So nothing can change even after
15859 		 * we get the pending mp. If need be we can put it back
15860 		 * and restart, as in calling ipif_arp_up()  below.
15861 		 */
15862 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15863 
15864 		mutex_enter(&ill->ill_lock);
15865 		ill->ill_dl_up = 1;
15866 		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);
15867 		mutex_exit(&ill->ill_lock);
15868 
15869 		/*
15870 		 * Now bring up the resolver; when that is complete, we'll
15871 		 * create IREs.  Note that we intentionally mirror what
15872 		 * ipif_up() would have done, because we got here by way of
15873 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15874 		 */
15875 		if (ill->ill_isv6) {
15876 			/*
15877 			 * v6 interfaces.
15878 			 * Unlike ARP which has to do another bind
15879 			 * and attach, once we get here we are
15880 			 * done with NDP. Except in the case of
15881 			 * ILLF_XRESOLV, in which case we send an
15882 			 * AR_INTERFACE_UP to the external resolver.
15883 			 * If all goes well, the ioctl will complete
15884 			 * in ip_rput(). If there's an error, we
15885 			 * complete it here.
15886 			 */
15887 			if ((err = ipif_ndp_up(ipif)) == 0) {
15888 				if (ill->ill_flags & ILLF_XRESOLV) {
15889 					mutex_enter(&connp->conn_lock);
15890 					mutex_enter(&ill->ill_lock);
15891 					success = ipsq_pending_mp_add(
15892 					    connp, ipif, q, mp1, 0);
15893 					mutex_exit(&ill->ill_lock);
15894 					mutex_exit(&connp->conn_lock);
15895 					if (success) {
15896 						err = ipif_resolver_up(ipif,
15897 						    Res_act_initial);
15898 						if (err == EINPROGRESS) {
15899 							freemsg(mp);
15900 							return;
15901 						}
15902 						ASSERT(err != 0);
15903 						mp1 = ipsq_pending_mp_get(ipsq,
15904 						    &connp);
15905 						ASSERT(mp1 != NULL);
15906 					} else {
15907 						/* conn has started closing */
15908 						err = EINTR;
15909 					}
15910 				} else { /* Non XRESOLV interface */
15911 					(void) ipif_resolver_up(ipif,
15912 					    Res_act_initial);
15913 					err = ipif_up_done_v6(ipif);
15914 				}
15915 			}
15916 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15917 			/*
15918 			 * ARP and other v4 external resolvers.
15919 			 * Leave the pending mblk intact so that
15920 			 * the ioctl completes in ip_rput().
15921 			 */
15922 			mutex_enter(&connp->conn_lock);
15923 			mutex_enter(&ill->ill_lock);
15924 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15925 			mutex_exit(&ill->ill_lock);
15926 			mutex_exit(&connp->conn_lock);
15927 			if (success) {
15928 				err = ipif_resolver_up(ipif, Res_act_initial);
15929 				if (err == EINPROGRESS) {
15930 					freemsg(mp);
15931 					return;
15932 				}
15933 				ASSERT(err != 0);
15934 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15935 			} else {
15936 				/* The conn has started closing */
15937 				err = EINTR;
15938 			}
15939 		} else {
15940 			/*
15941 			 * This one is complete. Reply to pending ioctl.
15942 			 */
15943 			(void) ipif_resolver_up(ipif, Res_act_initial);
15944 			err = ipif_up_done(ipif);
15945 		}
15946 
15947 		if ((err == 0) && (ill->ill_up_ipifs)) {
15948 			err = ill_up_ipifs(ill, q, mp1);
15949 			if (err == EINPROGRESS) {
15950 				freemsg(mp);
15951 				return;
15952 			}
15953 		}
15954 
15955 		if (ill->ill_up_ipifs) {
15956 			ill_group_cleanup(ill);
15957 		}
15958 
15959 		break;
15960 	case DL_NOTIFY_IND: {
15961 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15962 		ire_t *ire;
15963 		boolean_t need_ire_walk_v4 = B_FALSE;
15964 		boolean_t need_ire_walk_v6 = B_FALSE;
15965 
15966 		switch (notify->dl_notification) {
15967 		case DL_NOTE_PHYS_ADDR:
15968 			err = ill_set_phys_addr(ill, mp);
15969 			break;
15970 
15971 		case DL_NOTE_FASTPATH_FLUSH:
15972 			ill_fastpath_flush(ill);
15973 			break;
15974 
15975 		case DL_NOTE_SDU_SIZE:
15976 			/*
15977 			 * Change the MTU size of the interface, of all
15978 			 * attached ipif's, and of all relevant ire's.  The
15979 			 * new value's a uint32_t at notify->dl_data.
15980 			 * Mtu change Vs. new ire creation - protocol below.
15981 			 *
15982 			 * a Mark the ipif as IPIF_CHANGING.
15983 			 * b Set the new mtu in the ipif.
15984 			 * c Change the ire_max_frag on all affected ires
15985 			 * d Unmark the IPIF_CHANGING
15986 			 *
15987 			 * To see how the protocol works, assume an interface
15988 			 * route is also being added simultaneously by
15989 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15990 			 * the ire. If the ire is created before step a,
15991 			 * it will be cleaned up by step c. If the ire is
15992 			 * created after step d, it will see the new value of
15993 			 * ipif_mtu. Any attempt to create the ire between
15994 			 * steps a to d will fail because of the IPIF_CHANGING
15995 			 * flag. Note that ire_create() is passed a pointer to
15996 			 * the ipif_mtu, and not the value. During ire_add
15997 			 * under the bucket lock, the ire_max_frag of the
15998 			 * new ire being created is set from the ipif/ire from
15999 			 * which it is being derived.
16000 			 */
16001 			mutex_enter(&ill->ill_lock);
16002 			ill->ill_max_frag = (uint_t)notify->dl_data;
16003 
16004 			/*
16005 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16006 			 * leave it alone
16007 			 */
16008 			if (ill->ill_mtu_userspecified) {
16009 				mutex_exit(&ill->ill_lock);
16010 				break;
16011 			}
16012 			ill->ill_max_mtu = ill->ill_max_frag;
16013 			if (ill->ill_isv6) {
16014 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16015 					ill->ill_max_mtu = IPV6_MIN_MTU;
16016 			} else {
16017 				if (ill->ill_max_mtu < IP_MIN_MTU)
16018 					ill->ill_max_mtu = IP_MIN_MTU;
16019 			}
16020 			for (ipif = ill->ill_ipif; ipif != NULL;
16021 			    ipif = ipif->ipif_next) {
16022 				/*
16023 				 * Don't override the mtu if the user
16024 				 * has explicitly set it.
16025 				 */
16026 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16027 					continue;
16028 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16029 				if (ipif->ipif_isv6)
16030 					ire = ipif_to_ire_v6(ipif);
16031 				else
16032 					ire = ipif_to_ire(ipif);
16033 				if (ire != NULL) {
16034 					ire->ire_max_frag = ipif->ipif_mtu;
16035 					ire_refrele(ire);
16036 				}
16037 				if (ipif->ipif_flags & IPIF_UP) {
16038 					if (ill->ill_isv6)
16039 						need_ire_walk_v6 = B_TRUE;
16040 					else
16041 						need_ire_walk_v4 = B_TRUE;
16042 				}
16043 			}
16044 			mutex_exit(&ill->ill_lock);
16045 			if (need_ire_walk_v4)
16046 				ire_walk_v4(ill_mtu_change, (char *)ill,
16047 				    ALL_ZONES, ipst);
16048 			if (need_ire_walk_v6)
16049 				ire_walk_v6(ill_mtu_change, (char *)ill,
16050 				    ALL_ZONES, ipst);
16051 			break;
16052 		case DL_NOTE_LINK_UP:
16053 		case DL_NOTE_LINK_DOWN: {
16054 			/*
16055 			 * We are writer. ill / phyint / ipsq assocs stable.
16056 			 * The RUNNING flag reflects the state of the link.
16057 			 */
16058 			phyint_t *phyint = ill->ill_phyint;
16059 			uint64_t new_phyint_flags;
16060 			boolean_t changed = B_FALSE;
16061 			boolean_t went_up;
16062 
16063 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16064 			mutex_enter(&phyint->phyint_lock);
16065 			new_phyint_flags = went_up ?
16066 			    phyint->phyint_flags | PHYI_RUNNING :
16067 			    phyint->phyint_flags & ~PHYI_RUNNING;
16068 			if (new_phyint_flags != phyint->phyint_flags) {
16069 				phyint->phyint_flags = new_phyint_flags;
16070 				changed = B_TRUE;
16071 			}
16072 			mutex_exit(&phyint->phyint_lock);
16073 			/*
16074 			 * ill_restart_dad handles the DAD restart and routing
16075 			 * socket notification logic.
16076 			 */
16077 			if (changed) {
16078 				ill_restart_dad(phyint->phyint_illv4, went_up);
16079 				ill_restart_dad(phyint->phyint_illv6, went_up);
16080 			}
16081 			break;
16082 		}
16083 		case DL_NOTE_PROMISC_ON_PHYS:
16084 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16085 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16086 			mutex_enter(&ill->ill_lock);
16087 			ill->ill_promisc_on_phys = B_TRUE;
16088 			mutex_exit(&ill->ill_lock);
16089 			break;
16090 		case DL_NOTE_PROMISC_OFF_PHYS:
16091 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16092 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16093 			mutex_enter(&ill->ill_lock);
16094 			ill->ill_promisc_on_phys = B_FALSE;
16095 			mutex_exit(&ill->ill_lock);
16096 			break;
16097 		case DL_NOTE_CAPAB_RENEG:
16098 			/*
16099 			 * Something changed on the driver side.
16100 			 * It wants us to renegotiate the capabilities
16101 			 * on this ill. One possible cause is the aggregation
16102 			 * interface under us where a port got added or
16103 			 * went away.
16104 			 *
16105 			 * If the capability negotiation is already done
16106 			 * or is in progress, reset the capabilities and
16107 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16108 			 * so that when the ack comes back, we can start
16109 			 * the renegotiation process.
16110 			 *
16111 			 * Note that if ill_capab_reneg is already B_TRUE
16112 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16113 			 * the capability resetting request has been sent
16114 			 * and the renegotiation has not been started yet;
16115 			 * nothing needs to be done in this case.
16116 			 */
16117 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16118 				ill_capability_reset(ill);
16119 				ill->ill_capab_reneg = B_TRUE;
16120 			}
16121 			break;
16122 		default:
16123 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16124 			    "type 0x%x for DL_NOTIFY_IND\n",
16125 			    notify->dl_notification));
16126 			break;
16127 		}
16128 
16129 		/*
16130 		 * As this is an asynchronous operation, we
16131 		 * should not call ill_dlpi_done
16132 		 */
16133 		break;
16134 	}
16135 	case DL_NOTIFY_ACK: {
16136 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16137 
16138 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16139 			ill->ill_note_link = 1;
16140 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16141 		break;
16142 	}
16143 	case DL_PHYS_ADDR_ACK: {
16144 		/*
16145 		 * As part of plumbing the interface via SIOCSLIFNAME,
16146 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16147 		 * whose answers we receive here.  As each answer is received,
16148 		 * we call ill_dlpi_done() to dispatch the next request as
16149 		 * we're processing the current one.  Once all answers have
16150 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16151 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16152 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16153 		 * available, but we know the ioctl is pending on ill_wq.)
16154 		 */
16155 		uint_t paddrlen, paddroff;
16156 
16157 		paddrreq = ill->ill_phys_addr_pend;
16158 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16159 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16160 
16161 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16162 		if (paddrreq == DL_IPV6_TOKEN) {
16163 			/*
16164 			 * bcopy to low-order bits of ill_token
16165 			 *
16166 			 * XXX Temporary hack - currently, all known tokens
16167 			 * are 64 bits, so I'll cheat for the moment.
16168 			 */
16169 			bcopy(mp->b_rptr + paddroff,
16170 			    &ill->ill_token.s6_addr32[2], paddrlen);
16171 			ill->ill_token_length = paddrlen;
16172 			break;
16173 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16174 			ASSERT(ill->ill_nd_lla_mp == NULL);
16175 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16176 			mp = NULL;
16177 			break;
16178 		}
16179 
16180 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16181 		ASSERT(ill->ill_phys_addr_mp == NULL);
16182 		if (!ill->ill_ifname_pending)
16183 			break;
16184 		ill->ill_ifname_pending = 0;
16185 		if (!ioctl_aborted)
16186 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16187 		if (mp1 != NULL) {
16188 			ASSERT(connp == NULL);
16189 			q = ill->ill_wq;
16190 		}
16191 		/*
16192 		 * If any error acks received during the plumbing sequence,
16193 		 * ill_ifname_pending_err will be set. Break out and send up
16194 		 * the error to the pending ioctl.
16195 		 */
16196 		if (ill->ill_ifname_pending_err != 0) {
16197 			err = ill->ill_ifname_pending_err;
16198 			ill->ill_ifname_pending_err = 0;
16199 			break;
16200 		}
16201 
16202 		ill->ill_phys_addr_mp = mp;
16203 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16204 		mp = NULL;
16205 
16206 		/*
16207 		 * If paddrlen is zero, the DLPI provider doesn't support
16208 		 * physical addresses.  The other two tests were historical
16209 		 * workarounds for bugs in our former PPP implementation, but
16210 		 * now other things have grown dependencies on them -- e.g.,
16211 		 * the tun module specifies a dl_addr_length of zero in its
16212 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16213 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16214 		 * but only after careful testing ensures that all dependent
16215 		 * broken DLPI providers have been fixed.
16216 		 */
16217 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16218 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16219 			ill->ill_phys_addr = NULL;
16220 		} else if (paddrlen != ill->ill_phys_addr_length) {
16221 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16222 			    paddrlen, ill->ill_phys_addr_length));
16223 			err = EINVAL;
16224 			break;
16225 		}
16226 
16227 		if (ill->ill_nd_lla_mp == NULL) {
16228 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16229 				err = ENOMEM;
16230 				break;
16231 			}
16232 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16233 		}
16234 
16235 		/*
16236 		 * Set the interface token.  If the zeroth interface address
16237 		 * is unspecified, then set it to the link local address.
16238 		 */
16239 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16240 			(void) ill_setdefaulttoken(ill);
16241 
16242 		ASSERT(ill->ill_ipif->ipif_id == 0);
16243 		if (ipif != NULL &&
16244 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16245 			(void) ipif_setlinklocal(ipif);
16246 		}
16247 		break;
16248 	}
16249 	case DL_OK_ACK:
16250 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16251 		    dl_primstr((int)dloa->dl_correct_primitive),
16252 		    dloa->dl_correct_primitive));
16253 		switch (dloa->dl_correct_primitive) {
16254 		case DL_ENABMULTI_REQ:
16255 		case DL_DISABMULTI_REQ:
16256 			if (!ill->ill_isv6)
16257 				ipsq_current_finish(ipsq);
16258 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16259 			break;
16260 		case DL_PROMISCON_REQ:
16261 		case DL_PROMISCOFF_REQ:
16262 		case DL_UNBIND_REQ:
16263 		case DL_ATTACH_REQ:
16264 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16265 			break;
16266 		}
16267 		break;
16268 	default:
16269 		break;
16270 	}
16271 
16272 	freemsg(mp);
16273 	if (mp1 != NULL) {
16274 		/*
16275 		 * The operation must complete without EINPROGRESS
16276 		 * since ipsq_pending_mp_get() has removed the mblk
16277 		 * from ipsq_pending_mp.  Otherwise, the operation
16278 		 * will be stuck forever in the ipsq.
16279 		 */
16280 		ASSERT(err != EINPROGRESS);
16281 
16282 		switch (ipsq->ipsq_current_ioctl) {
16283 		case 0:
16284 			ipsq_current_finish(ipsq);
16285 			break;
16286 
16287 		case SIOCLIFADDIF:
16288 		case SIOCSLIFNAME:
16289 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16290 			break;
16291 
16292 		default:
16293 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16294 			break;
16295 		}
16296 	}
16297 }
16298 
16299 /*
16300  * ip_rput_other is called by ip_rput to handle messages modifying the global
16301  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16302  */
16303 /* ARGSUSED */
16304 void
16305 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16306 {
16307 	ill_t		*ill;
16308 	struct iocblk	*iocp;
16309 	mblk_t		*mp1;
16310 	conn_t		*connp = NULL;
16311 
16312 	ip1dbg(("ip_rput_other "));
16313 	ill = (ill_t *)q->q_ptr;
16314 	/*
16315 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16316 	 * in which case ipsq is NULL.
16317 	 */
16318 	if (ipsq != NULL) {
16319 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16320 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16321 	}
16322 
16323 	switch (mp->b_datap->db_type) {
16324 	case M_ERROR:
16325 	case M_HANGUP:
16326 		/*
16327 		 * The device has a problem.  We force the ILL down.  It can
16328 		 * be brought up again manually using SIOCSIFFLAGS (via
16329 		 * ifconfig or equivalent).
16330 		 */
16331 		ASSERT(ipsq != NULL);
16332 		if (mp->b_rptr < mp->b_wptr)
16333 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16334 		if (ill->ill_error == 0)
16335 			ill->ill_error = ENXIO;
16336 		if (!ill_down_start(q, mp))
16337 			return;
16338 		ipif_all_down_tail(ipsq, q, mp, NULL);
16339 		break;
16340 	case M_IOCACK:
16341 		iocp = (struct iocblk *)mp->b_rptr;
16342 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16343 		switch (iocp->ioc_cmd) {
16344 		case SIOCSTUNPARAM:
16345 		case OSIOCSTUNPARAM:
16346 			ASSERT(ipsq != NULL);
16347 			/*
16348 			 * Finish socket ioctl passed through to tun.
16349 			 * We should have an IOCTL waiting on this.
16350 			 */
16351 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16352 			if (ill->ill_isv6) {
16353 				struct iftun_req *ta;
16354 
16355 				/*
16356 				 * if a source or destination is
16357 				 * being set, try and set the link
16358 				 * local address for the tunnel
16359 				 */
16360 				ta = (struct iftun_req *)mp->b_cont->
16361 				    b_cont->b_rptr;
16362 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16363 					ipif_set_tun_llink(ill, ta);
16364 				}
16365 
16366 			}
16367 			if (mp1 != NULL) {
16368 				/*
16369 				 * Now copy back the b_next/b_prev used by
16370 				 * mi code for the mi_copy* functions.
16371 				 * See ip_sioctl_tunparam() for the reason.
16372 				 * Also protect against missing b_cont.
16373 				 */
16374 				if (mp->b_cont != NULL) {
16375 					mp->b_cont->b_next =
16376 					    mp1->b_cont->b_next;
16377 					mp->b_cont->b_prev =
16378 					    mp1->b_cont->b_prev;
16379 				}
16380 				inet_freemsg(mp1);
16381 				ASSERT(connp != NULL);
16382 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16383 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16384 			} else {
16385 				ASSERT(connp == NULL);
16386 				putnext(q, mp);
16387 			}
16388 			break;
16389 		case SIOCGTUNPARAM:
16390 		case OSIOCGTUNPARAM:
16391 			/*
16392 			 * This is really M_IOCDATA from the tunnel driver.
16393 			 * convert back and complete the ioctl.
16394 			 * We should have an IOCTL waiting on this.
16395 			 */
16396 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16397 			if (mp1) {
16398 				/*
16399 				 * Now copy back the b_next/b_prev used by
16400 				 * mi code for the mi_copy* functions.
16401 				 * See ip_sioctl_tunparam() for the reason.
16402 				 * Also protect against missing b_cont.
16403 				 */
16404 				if (mp->b_cont != NULL) {
16405 					mp->b_cont->b_next =
16406 					    mp1->b_cont->b_next;
16407 					mp->b_cont->b_prev =
16408 					    mp1->b_cont->b_prev;
16409 				}
16410 				inet_freemsg(mp1);
16411 				if (iocp->ioc_error == 0)
16412 					mp->b_datap->db_type = M_IOCDATA;
16413 				ASSERT(connp != NULL);
16414 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16415 				    iocp->ioc_error, COPYOUT, NULL);
16416 			} else {
16417 				ASSERT(connp == NULL);
16418 				putnext(q, mp);
16419 			}
16420 			break;
16421 		default:
16422 			break;
16423 		}
16424 		break;
16425 	case M_IOCNAK:
16426 		iocp = (struct iocblk *)mp->b_rptr;
16427 
16428 		switch (iocp->ioc_cmd) {
16429 			int mode;
16430 
16431 		case DL_IOC_HDR_INFO:
16432 			/*
16433 			 * If this was the first attempt turn of the
16434 			 * fastpath probing.
16435 			 */
16436 			mutex_enter(&ill->ill_lock);
16437 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16438 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16439 				mutex_exit(&ill->ill_lock);
16440 				ill_fastpath_nack(ill);
16441 				ip1dbg(("ip_rput: DLPI fastpath off on "
16442 				    "interface %s\n",
16443 				    ill->ill_name));
16444 			} else {
16445 				mutex_exit(&ill->ill_lock);
16446 			}
16447 			freemsg(mp);
16448 			break;
16449 		case SIOCSTUNPARAM:
16450 		case OSIOCSTUNPARAM:
16451 			ASSERT(ipsq != NULL);
16452 			/*
16453 			 * Finish socket ioctl passed through to tun
16454 			 * We should have an IOCTL waiting on this.
16455 			 */
16456 			/* FALLTHRU */
16457 		case SIOCGTUNPARAM:
16458 		case OSIOCGTUNPARAM:
16459 			/*
16460 			 * This is really M_IOCDATA from the tunnel driver.
16461 			 * convert back and complete the ioctl.
16462 			 * We should have an IOCTL waiting on this.
16463 			 */
16464 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16465 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16466 				mp1 = ill_pending_mp_get(ill, &connp,
16467 				    iocp->ioc_id);
16468 				mode = COPYOUT;
16469 				ipsq = NULL;
16470 			} else {
16471 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16472 				mode = NO_COPYOUT;
16473 			}
16474 			if (mp1 != NULL) {
16475 				/*
16476 				 * Now copy back the b_next/b_prev used by
16477 				 * mi code for the mi_copy* functions.
16478 				 * See ip_sioctl_tunparam() for the reason.
16479 				 * Also protect against missing b_cont.
16480 				 */
16481 				if (mp->b_cont != NULL) {
16482 					mp->b_cont->b_next =
16483 					    mp1->b_cont->b_next;
16484 					mp->b_cont->b_prev =
16485 					    mp1->b_cont->b_prev;
16486 				}
16487 				inet_freemsg(mp1);
16488 				if (iocp->ioc_error == 0)
16489 					iocp->ioc_error = EINVAL;
16490 				ASSERT(connp != NULL);
16491 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16492 				    iocp->ioc_error, mode, ipsq);
16493 			} else {
16494 				ASSERT(connp == NULL);
16495 				putnext(q, mp);
16496 			}
16497 			break;
16498 		default:
16499 			break;
16500 		}
16501 	default:
16502 		break;
16503 	}
16504 }
16505 
16506 /*
16507  * NOTE : This function does not ire_refrele the ire argument passed in.
16508  *
16509  * IPQoS notes
16510  * IP policy is invoked twice for a forwarded packet, once on the read side
16511  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16512  * enabled. An additional parameter, in_ill, has been added for this purpose.
16513  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16514  * because ip_mroute drops this information.
16515  *
16516  */
16517 void
16518 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16519 {
16520 	uint32_t	old_pkt_len;
16521 	uint32_t	pkt_len;
16522 	queue_t	*q;
16523 	uint32_t	sum;
16524 #define	rptr	((uchar_t *)ipha)
16525 	uint32_t	max_frag;
16526 	uint32_t	ill_index;
16527 	ill_t		*out_ill;
16528 	mib2_ipIfStatsEntry_t *mibptr;
16529 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16530 
16531 	/* Get the ill_index of the incoming ILL */
16532 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16533 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16534 
16535 	/* Initiate Read side IPPF processing */
16536 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16537 		ip_process(IPP_FWD_IN, &mp, ill_index);
16538 		if (mp == NULL) {
16539 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16540 			    "during IPPF processing\n"));
16541 			return;
16542 		}
16543 	}
16544 
16545 	/* Adjust the checksum to reflect the ttl decrement. */
16546 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16547 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16548 
16549 	if (ipha->ipha_ttl-- <= 1) {
16550 		if (ip_csum_hdr(ipha)) {
16551 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16552 			goto drop_pkt;
16553 		}
16554 		/*
16555 		 * Note: ire_stq this will be NULL for multicast
16556 		 * datagrams using the long path through arp (the IRE
16557 		 * is not an IRE_CACHE). This should not cause
16558 		 * problems since we don't generate ICMP errors for
16559 		 * multicast packets.
16560 		 */
16561 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16562 		q = ire->ire_stq;
16563 		if (q != NULL) {
16564 			/* Sent by forwarding path, and router is global zone */
16565 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16566 			    GLOBAL_ZONEID, ipst);
16567 		} else
16568 			freemsg(mp);
16569 		return;
16570 	}
16571 
16572 	/*
16573 	 * Don't forward if the interface is down
16574 	 */
16575 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16576 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16577 		ip2dbg(("ip_rput_forward:interface is down\n"));
16578 		goto drop_pkt;
16579 	}
16580 
16581 	/* Get the ill_index of the outgoing ILL */
16582 	out_ill = ire_to_ill(ire);
16583 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16584 
16585 	DTRACE_PROBE4(ip4__forwarding__start,
16586 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16587 
16588 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16589 	    ipst->ips_ipv4firewall_forwarding,
16590 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16591 
16592 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16593 
16594 	if (mp == NULL)
16595 		return;
16596 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16597 
16598 	if (is_system_labeled()) {
16599 		mblk_t *mp1;
16600 
16601 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16602 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16603 			goto drop_pkt;
16604 		}
16605 		/* Size may have changed */
16606 		mp = mp1;
16607 		ipha = (ipha_t *)mp->b_rptr;
16608 		pkt_len = ntohs(ipha->ipha_length);
16609 	}
16610 
16611 	/* Check if there are options to update */
16612 	if (!IS_SIMPLE_IPH(ipha)) {
16613 		if (ip_csum_hdr(ipha)) {
16614 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16615 			goto drop_pkt;
16616 		}
16617 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16618 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16619 			return;
16620 		}
16621 
16622 		ipha->ipha_hdr_checksum = 0;
16623 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16624 	}
16625 	max_frag = ire->ire_max_frag;
16626 	if (pkt_len > max_frag) {
16627 		/*
16628 		 * It needs fragging on its way out.  We haven't
16629 		 * verified the header checksum yet.  Since we
16630 		 * are going to put a surely good checksum in the
16631 		 * outgoing header, we have to make sure that it
16632 		 * was good coming in.
16633 		 */
16634 		if (ip_csum_hdr(ipha)) {
16635 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16636 			goto drop_pkt;
16637 		}
16638 		/* Initiate Write side IPPF processing */
16639 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16640 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16641 			if (mp == NULL) {
16642 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16643 				    " during IPPF processing\n"));
16644 				return;
16645 			}
16646 		}
16647 		/*
16648 		 * Handle labeled packet resizing.
16649 		 *
16650 		 * If we have added a label, inform ip_wput_frag() of its
16651 		 * effect on the MTU for ICMP messages.
16652 		 */
16653 		if (pkt_len > old_pkt_len) {
16654 			uint32_t secopt_size;
16655 
16656 			secopt_size = pkt_len - old_pkt_len;
16657 			if (secopt_size < max_frag)
16658 				max_frag -= secopt_size;
16659 		}
16660 
16661 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16662 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16663 		return;
16664 	}
16665 
16666 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16667 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16668 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16669 	    ipst->ips_ipv4firewall_physical_out,
16670 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16671 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16672 	if (mp == NULL)
16673 		return;
16674 
16675 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16676 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16677 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16678 	/* ip_xmit_v4 always consumes the packet */
16679 	return;
16680 
16681 drop_pkt:;
16682 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16683 	freemsg(mp);
16684 #undef	rptr
16685 }
16686 
16687 void
16688 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16689 {
16690 	ire_t	*ire;
16691 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16692 
16693 	ASSERT(!ipif->ipif_isv6);
16694 	/*
16695 	 * Find an IRE which matches the destination and the outgoing
16696 	 * queue in the cache table. All we need is an IRE_CACHE which
16697 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16698 	 * then it is enough to have some IRE_CACHE in the group.
16699 	 */
16700 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16701 		dst = ipif->ipif_pp_dst_addr;
16702 
16703 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16704 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16705 	if (ire == NULL) {
16706 		/*
16707 		 * Mark this packet to make it be delivered to
16708 		 * ip_rput_forward after the new ire has been
16709 		 * created.
16710 		 */
16711 		mp->b_prev = NULL;
16712 		mp->b_next = mp;
16713 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16714 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16715 	} else {
16716 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16717 		IRE_REFRELE(ire);
16718 	}
16719 }
16720 
16721 /* Update any source route, record route or timestamp options */
16722 static int
16723 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16724 {
16725 	ipoptp_t	opts;
16726 	uchar_t		*opt;
16727 	uint8_t		optval;
16728 	uint8_t		optlen;
16729 	ipaddr_t	dst;
16730 	uint32_t	ts;
16731 	ire_t		*dst_ire = NULL;
16732 	ire_t		*tmp_ire = NULL;
16733 	timestruc_t	now;
16734 
16735 	ip2dbg(("ip_rput_forward_options\n"));
16736 	dst = ipha->ipha_dst;
16737 	for (optval = ipoptp_first(&opts, ipha);
16738 	    optval != IPOPT_EOL;
16739 	    optval = ipoptp_next(&opts)) {
16740 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16741 		opt = opts.ipoptp_cur;
16742 		optlen = opts.ipoptp_len;
16743 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16744 		    optval, opts.ipoptp_len));
16745 		switch (optval) {
16746 			uint32_t off;
16747 		case IPOPT_SSRR:
16748 		case IPOPT_LSRR:
16749 			/* Check if adminstratively disabled */
16750 			if (!ipst->ips_ip_forward_src_routed) {
16751 				if (ire->ire_stq != NULL) {
16752 					/*
16753 					 * Sent by forwarding path, and router
16754 					 * is global zone
16755 					 */
16756 					icmp_unreachable(ire->ire_stq, mp,
16757 					    ICMP_SOURCE_ROUTE_FAILED,
16758 					    GLOBAL_ZONEID, ipst);
16759 				} else {
16760 					ip0dbg(("ip_rput_forward_options: "
16761 					    "unable to send unreach\n"));
16762 					freemsg(mp);
16763 				}
16764 				return (-1);
16765 			}
16766 
16767 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16768 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16769 			if (dst_ire == NULL) {
16770 				/*
16771 				 * Must be partial since ip_rput_options
16772 				 * checked for strict.
16773 				 */
16774 				break;
16775 			}
16776 			off = opt[IPOPT_OFFSET];
16777 			off--;
16778 		redo_srr:
16779 			if (optlen < IP_ADDR_LEN ||
16780 			    off > optlen - IP_ADDR_LEN) {
16781 				/* End of source route */
16782 				ip1dbg((
16783 				    "ip_rput_forward_options: end of SR\n"));
16784 				ire_refrele(dst_ire);
16785 				break;
16786 			}
16787 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16788 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16789 			    IP_ADDR_LEN);
16790 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16791 			    ntohl(dst)));
16792 
16793 			/*
16794 			 * Check if our address is present more than
16795 			 * once as consecutive hops in source route.
16796 			 */
16797 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16798 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16799 			if (tmp_ire != NULL) {
16800 				ire_refrele(tmp_ire);
16801 				off += IP_ADDR_LEN;
16802 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16803 				goto redo_srr;
16804 			}
16805 			ipha->ipha_dst = dst;
16806 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16807 			ire_refrele(dst_ire);
16808 			break;
16809 		case IPOPT_RR:
16810 			off = opt[IPOPT_OFFSET];
16811 			off--;
16812 			if (optlen < IP_ADDR_LEN ||
16813 			    off > optlen - IP_ADDR_LEN) {
16814 				/* No more room - ignore */
16815 				ip1dbg((
16816 				    "ip_rput_forward_options: end of RR\n"));
16817 				break;
16818 			}
16819 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16820 			    IP_ADDR_LEN);
16821 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16822 			break;
16823 		case IPOPT_TS:
16824 			/* Insert timestamp if there is room */
16825 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16826 			case IPOPT_TS_TSONLY:
16827 				off = IPOPT_TS_TIMELEN;
16828 				break;
16829 			case IPOPT_TS_PRESPEC:
16830 			case IPOPT_TS_PRESPEC_RFC791:
16831 				/* Verify that the address matched */
16832 				off = opt[IPOPT_OFFSET] - 1;
16833 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16834 				dst_ire = ire_ctable_lookup(dst, 0,
16835 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16836 				    MATCH_IRE_TYPE, ipst);
16837 				if (dst_ire == NULL) {
16838 					/* Not for us */
16839 					break;
16840 				}
16841 				ire_refrele(dst_ire);
16842 				/* FALLTHRU */
16843 			case IPOPT_TS_TSANDADDR:
16844 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16845 				break;
16846 			default:
16847 				/*
16848 				 * ip_*put_options should have already
16849 				 * dropped this packet.
16850 				 */
16851 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16852 				    "unknown IT - bug in ip_rput_options?\n");
16853 				return (0);	/* Keep "lint" happy */
16854 			}
16855 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16856 				/* Increase overflow counter */
16857 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16858 				opt[IPOPT_POS_OV_FLG] =
16859 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16860 				    (off << 4));
16861 				break;
16862 			}
16863 			off = opt[IPOPT_OFFSET] - 1;
16864 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16865 			case IPOPT_TS_PRESPEC:
16866 			case IPOPT_TS_PRESPEC_RFC791:
16867 			case IPOPT_TS_TSANDADDR:
16868 				bcopy(&ire->ire_src_addr,
16869 				    (char *)opt + off, IP_ADDR_LEN);
16870 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16871 				/* FALLTHRU */
16872 			case IPOPT_TS_TSONLY:
16873 				off = opt[IPOPT_OFFSET] - 1;
16874 				/* Compute # of milliseconds since midnight */
16875 				gethrestime(&now);
16876 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16877 				    now.tv_nsec / (NANOSEC / MILLISEC);
16878 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16879 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16880 				break;
16881 			}
16882 			break;
16883 		}
16884 	}
16885 	return (0);
16886 }
16887 
16888 /*
16889  * This is called after processing at least one of AH/ESP headers.
16890  *
16891  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16892  * the actual, physical interface on which the packet was received,
16893  * but, when ip_strict_dst_multihoming is set to 1, could be the
16894  * interface which had the ipha_dst configured when the packet went
16895  * through ip_rput. The ill_index corresponding to the recv_ill
16896  * is saved in ipsec_in_rill_index
16897  *
16898  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16899  * cannot assume "ire" points to valid data for any IPv6 cases.
16900  */
16901 void
16902 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16903 {
16904 	mblk_t *mp;
16905 	ipaddr_t dst;
16906 	in6_addr_t *v6dstp;
16907 	ipha_t *ipha;
16908 	ip6_t *ip6h;
16909 	ipsec_in_t *ii;
16910 	boolean_t ill_need_rele = B_FALSE;
16911 	boolean_t rill_need_rele = B_FALSE;
16912 	boolean_t ire_need_rele = B_FALSE;
16913 	netstack_t	*ns;
16914 	ip_stack_t	*ipst;
16915 
16916 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16917 	ASSERT(ii->ipsec_in_ill_index != 0);
16918 	ns = ii->ipsec_in_ns;
16919 	ASSERT(ii->ipsec_in_ns != NULL);
16920 	ipst = ns->netstack_ip;
16921 
16922 	mp = ipsec_mp->b_cont;
16923 	ASSERT(mp != NULL);
16924 
16925 
16926 	if (ill == NULL) {
16927 		ASSERT(recv_ill == NULL);
16928 		/*
16929 		 * We need to get the original queue on which ip_rput_local
16930 		 * or ip_rput_data_v6 was called.
16931 		 */
16932 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16933 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16934 		ill_need_rele = B_TRUE;
16935 
16936 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16937 			recv_ill = ill_lookup_on_ifindex(
16938 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16939 			    NULL, NULL, NULL, NULL, ipst);
16940 			rill_need_rele = B_TRUE;
16941 		} else {
16942 			recv_ill = ill;
16943 		}
16944 
16945 		if ((ill == NULL) || (recv_ill == NULL)) {
16946 			ip0dbg(("ip_fanout_proto_again: interface "
16947 			    "disappeared\n"));
16948 			if (ill != NULL)
16949 				ill_refrele(ill);
16950 			if (recv_ill != NULL)
16951 				ill_refrele(recv_ill);
16952 			freemsg(ipsec_mp);
16953 			return;
16954 		}
16955 	}
16956 
16957 	ASSERT(ill != NULL && recv_ill != NULL);
16958 
16959 	if (mp->b_datap->db_type == M_CTL) {
16960 		/*
16961 		 * AH/ESP is returning the ICMP message after
16962 		 * removing their headers. Fanout again till
16963 		 * it gets to the right protocol.
16964 		 */
16965 		if (ii->ipsec_in_v4) {
16966 			icmph_t *icmph;
16967 			int iph_hdr_length;
16968 			int hdr_length;
16969 
16970 			ipha = (ipha_t *)mp->b_rptr;
16971 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16972 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16973 			ipha = (ipha_t *)&icmph[1];
16974 			hdr_length = IPH_HDR_LENGTH(ipha);
16975 			/*
16976 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16977 			 * Reset the type to M_DATA.
16978 			 */
16979 			mp->b_datap->db_type = M_DATA;
16980 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16981 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16982 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16983 		} else {
16984 			icmp6_t *icmp6;
16985 			int hdr_length;
16986 
16987 			ip6h = (ip6_t *)mp->b_rptr;
16988 			/* Don't call hdr_length_v6() unless you have to. */
16989 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16990 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16991 			else
16992 				hdr_length = IPV6_HDR_LEN;
16993 
16994 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16995 			/*
16996 			 * icmp_inbound_error_fanout_v6 may need to do
16997 			 * pullupmsg.  Reset the type to M_DATA.
16998 			 */
16999 			mp->b_datap->db_type = M_DATA;
17000 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17001 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17002 		}
17003 		if (ill_need_rele)
17004 			ill_refrele(ill);
17005 		if (rill_need_rele)
17006 			ill_refrele(recv_ill);
17007 		return;
17008 	}
17009 
17010 	if (ii->ipsec_in_v4) {
17011 		ipha = (ipha_t *)mp->b_rptr;
17012 		dst = ipha->ipha_dst;
17013 		if (CLASSD(dst)) {
17014 			/*
17015 			 * Multicast has to be delivered to all streams.
17016 			 */
17017 			dst = INADDR_BROADCAST;
17018 		}
17019 
17020 		if (ire == NULL) {
17021 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17022 			    MBLK_GETLABEL(mp), ipst);
17023 			if (ire == NULL) {
17024 				if (ill_need_rele)
17025 					ill_refrele(ill);
17026 				if (rill_need_rele)
17027 					ill_refrele(recv_ill);
17028 				ip1dbg(("ip_fanout_proto_again: "
17029 				    "IRE not found"));
17030 				freemsg(ipsec_mp);
17031 				return;
17032 			}
17033 			ire_need_rele = B_TRUE;
17034 		}
17035 
17036 		switch (ipha->ipha_protocol) {
17037 			case IPPROTO_UDP:
17038 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17039 				    recv_ill);
17040 				if (ire_need_rele)
17041 					ire_refrele(ire);
17042 				break;
17043 			case IPPROTO_TCP:
17044 				if (!ire_need_rele)
17045 					IRE_REFHOLD(ire);
17046 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17047 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17048 				IRE_REFRELE(ire);
17049 				if (mp != NULL)
17050 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17051 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17052 				break;
17053 			case IPPROTO_SCTP:
17054 				if (!ire_need_rele)
17055 					IRE_REFHOLD(ire);
17056 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17057 				    ipsec_mp, 0, ill->ill_rq, dst);
17058 				break;
17059 			default:
17060 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17061 				    recv_ill, 0);
17062 				if (ire_need_rele)
17063 					ire_refrele(ire);
17064 				break;
17065 		}
17066 	} else {
17067 		uint32_t rput_flags = 0;
17068 
17069 		ip6h = (ip6_t *)mp->b_rptr;
17070 		v6dstp = &ip6h->ip6_dst;
17071 		/*
17072 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17073 		 * address.
17074 		 *
17075 		 * Currently, we don't store that state in the IPSEC_IN
17076 		 * message, and we may need to.
17077 		 */
17078 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17079 		    IP6_IN_LLMCAST : 0);
17080 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17081 		    NULL, NULL);
17082 	}
17083 	if (ill_need_rele)
17084 		ill_refrele(ill);
17085 	if (rill_need_rele)
17086 		ill_refrele(recv_ill);
17087 }
17088 
17089 /*
17090  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17091  * returns 'true' if there are still fragments left on the queue, in
17092  * which case we restart the timer.
17093  */
17094 void
17095 ill_frag_timer(void *arg)
17096 {
17097 	ill_t	*ill = (ill_t *)arg;
17098 	boolean_t frag_pending;
17099 	ip_stack_t	*ipst = ill->ill_ipst;
17100 
17101 	mutex_enter(&ill->ill_lock);
17102 	ASSERT(!ill->ill_fragtimer_executing);
17103 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17104 		ill->ill_frag_timer_id = 0;
17105 		mutex_exit(&ill->ill_lock);
17106 		return;
17107 	}
17108 	ill->ill_fragtimer_executing = 1;
17109 	mutex_exit(&ill->ill_lock);
17110 
17111 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17112 
17113 	/*
17114 	 * Restart the timer, if we have fragments pending or if someone
17115 	 * wanted us to be scheduled again.
17116 	 */
17117 	mutex_enter(&ill->ill_lock);
17118 	ill->ill_fragtimer_executing = 0;
17119 	ill->ill_frag_timer_id = 0;
17120 	if (frag_pending || ill->ill_fragtimer_needrestart)
17121 		ill_frag_timer_start(ill);
17122 	mutex_exit(&ill->ill_lock);
17123 }
17124 
17125 void
17126 ill_frag_timer_start(ill_t *ill)
17127 {
17128 	ip_stack_t	*ipst = ill->ill_ipst;
17129 
17130 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17131 
17132 	/* If the ill is closing or opening don't proceed */
17133 	if (ill->ill_state_flags & ILL_CONDEMNED)
17134 		return;
17135 
17136 	if (ill->ill_fragtimer_executing) {
17137 		/*
17138 		 * ill_frag_timer is currently executing. Just record the
17139 		 * the fact that we want the timer to be restarted.
17140 		 * ill_frag_timer will post a timeout before it returns,
17141 		 * ensuring it will be called again.
17142 		 */
17143 		ill->ill_fragtimer_needrestart = 1;
17144 		return;
17145 	}
17146 
17147 	if (ill->ill_frag_timer_id == 0) {
17148 		/*
17149 		 * The timer is neither running nor is the timeout handler
17150 		 * executing. Post a timeout so that ill_frag_timer will be
17151 		 * called
17152 		 */
17153 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17154 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17155 		ill->ill_fragtimer_needrestart = 0;
17156 	}
17157 }
17158 
17159 /*
17160  * This routine is needed for loopback when forwarding multicasts.
17161  *
17162  * IPQoS Notes:
17163  * IPPF processing is done in fanout routines.
17164  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17165  * processing for IPsec packets is done when it comes back in clear.
17166  * NOTE : The callers of this function need to do the ire_refrele for the
17167  *	  ire that is being passed in.
17168  */
17169 void
17170 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17171     ill_t *recv_ill, uint32_t esp_udp_ports)
17172 {
17173 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17174 	ill_t	*ill = (ill_t *)q->q_ptr;
17175 	uint32_t	sum;
17176 	uint32_t	u1;
17177 	uint32_t	u2;
17178 	int		hdr_length;
17179 	boolean_t	mctl_present;
17180 	mblk_t		*first_mp = mp;
17181 	mblk_t		*hada_mp = NULL;
17182 	ipha_t		*inner_ipha;
17183 	ip_stack_t	*ipst;
17184 
17185 	ASSERT(recv_ill != NULL);
17186 	ipst = recv_ill->ill_ipst;
17187 
17188 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17189 	    "ip_rput_locl_start: q %p", q);
17190 
17191 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17192 	ASSERT(ill != NULL);
17193 
17194 
17195 #define	rptr	((uchar_t *)ipha)
17196 #define	iphs	((uint16_t *)ipha)
17197 
17198 	/*
17199 	 * no UDP or TCP packet should come here anymore.
17200 	 */
17201 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17202 	    ipha->ipha_protocol != IPPROTO_UDP);
17203 
17204 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17205 	if (mctl_present &&
17206 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17207 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17208 
17209 		/*
17210 		 * It's an IPsec accelerated packet.
17211 		 * Keep a pointer to the data attributes around until
17212 		 * we allocate the ipsec_info_t.
17213 		 */
17214 		IPSECHW_DEBUG(IPSECHW_PKT,
17215 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17216 		hada_mp = first_mp;
17217 		hada_mp->b_cont = NULL;
17218 		/*
17219 		 * Since it is accelerated, it comes directly from
17220 		 * the ill and the data attributes is followed by
17221 		 * the packet data.
17222 		 */
17223 		ASSERT(mp->b_datap->db_type != M_CTL);
17224 		first_mp = mp;
17225 		mctl_present = B_FALSE;
17226 	}
17227 
17228 	/*
17229 	 * IF M_CTL is not present, then ipsec_in_is_secure
17230 	 * should return B_TRUE. There is a case where loopback
17231 	 * packets has an M_CTL in the front with all the
17232 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17233 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17234 	 * packets never comes here, it is safe to ASSERT the
17235 	 * following.
17236 	 */
17237 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17238 
17239 	/*
17240 	 * Also, we should never have an mctl_present if this is an
17241 	 * ESP-in-UDP packet.
17242 	 */
17243 	ASSERT(!mctl_present || !esp_in_udp_packet);
17244 
17245 
17246 	/* u1 is # words of IP options */
17247 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17248 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17249 
17250 	/*
17251 	 * Don't verify header checksum if we just removed UDP header or
17252 	 * packet is coming back from AH/ESP.
17253 	 */
17254 	if (!esp_in_udp_packet && !mctl_present) {
17255 		if (u1) {
17256 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17257 				if (hada_mp != NULL)
17258 					freemsg(hada_mp);
17259 				return;
17260 			}
17261 		} else {
17262 			/* Check the IP header checksum.  */
17263 #define	uph	((uint16_t *)ipha)
17264 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17265 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17266 #undef  uph
17267 			/* finish doing IP checksum */
17268 			sum = (sum & 0xFFFF) + (sum >> 16);
17269 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17270 			if (sum && sum != 0xFFFF) {
17271 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17272 				goto drop_pkt;
17273 			}
17274 		}
17275 	}
17276 
17277 	/*
17278 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17279 	 * might be called more than once for secure packets, count only
17280 	 * the first time.
17281 	 */
17282 	if (!mctl_present) {
17283 		UPDATE_IB_PKT_COUNT(ire);
17284 		ire->ire_last_used_time = lbolt;
17285 	}
17286 
17287 	/* Check for fragmentation offset. */
17288 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17289 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17290 	if (u1) {
17291 		/*
17292 		 * We re-assemble fragments before we do the AH/ESP
17293 		 * processing. Thus, M_CTL should not be present
17294 		 * while we are re-assembling.
17295 		 */
17296 		ASSERT(!mctl_present);
17297 		ASSERT(first_mp == mp);
17298 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17299 			return;
17300 		}
17301 		/*
17302 		 * Make sure that first_mp points back to mp as
17303 		 * the mp we came in with could have changed in
17304 		 * ip_rput_fragment().
17305 		 */
17306 		ipha = (ipha_t *)mp->b_rptr;
17307 		first_mp = mp;
17308 	}
17309 
17310 	/*
17311 	 * Clear hardware checksumming flag as it is currently only
17312 	 * used by TCP and UDP.
17313 	 */
17314 	DB_CKSUMFLAGS(mp) = 0;
17315 
17316 	/* Now we have a complete datagram, destined for this machine. */
17317 	u1 = IPH_HDR_LENGTH(ipha);
17318 	switch (ipha->ipha_protocol) {
17319 	case IPPROTO_ICMP: {
17320 		ire_t		*ire_zone;
17321 		ilm_t		*ilm;
17322 		mblk_t		*mp1;
17323 		zoneid_t	last_zoneid;
17324 
17325 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17326 			ASSERT(ire->ire_type == IRE_BROADCAST);
17327 			/*
17328 			 * Inactive/Failed interfaces are not supposed to
17329 			 * respond to the multicast packets.
17330 			 */
17331 			if (ill_is_probeonly(ill)) {
17332 				freemsg(first_mp);
17333 				return;
17334 			}
17335 
17336 			/*
17337 			 * In the multicast case, applications may have joined
17338 			 * the group from different zones, so we need to deliver
17339 			 * the packet to each of them. Loop through the
17340 			 * multicast memberships structures (ilm) on the receive
17341 			 * ill and send a copy of the packet up each matching
17342 			 * one. However, we don't do this for multicasts sent on
17343 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17344 			 * they must stay in the sender's zone.
17345 			 *
17346 			 * ilm_add_v6() ensures that ilms in the same zone are
17347 			 * contiguous in the ill_ilm list. We use this property
17348 			 * to avoid sending duplicates needed when two
17349 			 * applications in the same zone join the same group on
17350 			 * different logical interfaces: we ignore the ilm if
17351 			 * its zoneid is the same as the last matching one.
17352 			 * In addition, the sending of the packet for
17353 			 * ire_zoneid is delayed until all of the other ilms
17354 			 * have been exhausted.
17355 			 */
17356 			last_zoneid = -1;
17357 			ILM_WALKER_HOLD(recv_ill);
17358 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17359 			    ilm = ilm->ilm_next) {
17360 				if ((ilm->ilm_flags & ILM_DELETED) ||
17361 				    ipha->ipha_dst != ilm->ilm_addr ||
17362 				    ilm->ilm_zoneid == last_zoneid ||
17363 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17364 				    ilm->ilm_zoneid == ALL_ZONES ||
17365 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17366 					continue;
17367 				mp1 = ip_copymsg(first_mp);
17368 				if (mp1 == NULL)
17369 					continue;
17370 				icmp_inbound(q, mp1, B_TRUE, ill,
17371 				    0, sum, mctl_present, B_TRUE,
17372 				    recv_ill, ilm->ilm_zoneid);
17373 				last_zoneid = ilm->ilm_zoneid;
17374 			}
17375 			ILM_WALKER_RELE(recv_ill);
17376 		} else if (ire->ire_type == IRE_BROADCAST) {
17377 			/*
17378 			 * In the broadcast case, there may be many zones
17379 			 * which need a copy of the packet delivered to them.
17380 			 * There is one IRE_BROADCAST per broadcast address
17381 			 * and per zone; we walk those using a helper function.
17382 			 * In addition, the sending of the packet for ire is
17383 			 * delayed until all of the other ires have been
17384 			 * processed.
17385 			 */
17386 			IRB_REFHOLD(ire->ire_bucket);
17387 			ire_zone = NULL;
17388 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17389 			    ire)) != NULL) {
17390 				mp1 = ip_copymsg(first_mp);
17391 				if (mp1 == NULL)
17392 					continue;
17393 
17394 				UPDATE_IB_PKT_COUNT(ire_zone);
17395 				ire_zone->ire_last_used_time = lbolt;
17396 				icmp_inbound(q, mp1, B_TRUE, ill,
17397 				    0, sum, mctl_present, B_TRUE,
17398 				    recv_ill, ire_zone->ire_zoneid);
17399 			}
17400 			IRB_REFRELE(ire->ire_bucket);
17401 		}
17402 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17403 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17404 		    ire->ire_zoneid);
17405 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17406 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17407 		return;
17408 	}
17409 	case IPPROTO_IGMP:
17410 		/*
17411 		 * If we are not willing to accept IGMP packets in clear,
17412 		 * then check with global policy.
17413 		 */
17414 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17415 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17416 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17417 			if (first_mp == NULL)
17418 				return;
17419 		}
17420 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17421 			freemsg(first_mp);
17422 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17423 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17424 			return;
17425 		}
17426 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17427 			/* Bad packet - discarded by igmp_input */
17428 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17429 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17430 			if (mctl_present)
17431 				freeb(first_mp);
17432 			return;
17433 		}
17434 		/*
17435 		 * igmp_input() may have returned the pulled up message.
17436 		 * So first_mp and ipha need to be reinitialized.
17437 		 */
17438 		ipha = (ipha_t *)mp->b_rptr;
17439 		if (mctl_present)
17440 			first_mp->b_cont = mp;
17441 		else
17442 			first_mp = mp;
17443 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17444 		    connf_head != NULL) {
17445 			/* No user-level listener for IGMP packets */
17446 			goto drop_pkt;
17447 		}
17448 		/* deliver to local raw users */
17449 		break;
17450 	case IPPROTO_PIM:
17451 		/*
17452 		 * If we are not willing to accept PIM packets in clear,
17453 		 * then check with global policy.
17454 		 */
17455 		if (ipst->ips_pim_accept_clear_messages == 0) {
17456 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17457 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17458 			if (first_mp == NULL)
17459 				return;
17460 		}
17461 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17462 			freemsg(first_mp);
17463 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17464 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17465 			return;
17466 		}
17467 		if (pim_input(q, mp, ill) != 0) {
17468 			/* Bad packet - discarded by pim_input */
17469 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17470 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17471 			if (mctl_present)
17472 				freeb(first_mp);
17473 			return;
17474 		}
17475 
17476 		/*
17477 		 * pim_input() may have pulled up the message so ipha needs to
17478 		 * be reinitialized.
17479 		 */
17480 		ipha = (ipha_t *)mp->b_rptr;
17481 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17482 		    connf_head != NULL) {
17483 			/* No user-level listener for PIM packets */
17484 			goto drop_pkt;
17485 		}
17486 		/* deliver to local raw users */
17487 		break;
17488 	case IPPROTO_ENCAP:
17489 		/*
17490 		 * Handle self-encapsulated packets (IP-in-IP where
17491 		 * the inner addresses == the outer addresses).
17492 		 */
17493 		hdr_length = IPH_HDR_LENGTH(ipha);
17494 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17495 		    mp->b_wptr) {
17496 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17497 			    sizeof (ipha_t) - mp->b_rptr)) {
17498 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17499 				freemsg(first_mp);
17500 				return;
17501 			}
17502 			ipha = (ipha_t *)mp->b_rptr;
17503 		}
17504 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17505 		/*
17506 		 * Check the sanity of the inner IP header.
17507 		 */
17508 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17509 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17510 			freemsg(first_mp);
17511 			return;
17512 		}
17513 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17514 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17515 			freemsg(first_mp);
17516 			return;
17517 		}
17518 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17519 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17520 			ipsec_in_t *ii;
17521 
17522 			/*
17523 			 * Self-encapsulated tunnel packet. Remove
17524 			 * the outer IP header and fanout again.
17525 			 * We also need to make sure that the inner
17526 			 * header is pulled up until options.
17527 			 */
17528 			mp->b_rptr = (uchar_t *)inner_ipha;
17529 			ipha = inner_ipha;
17530 			hdr_length = IPH_HDR_LENGTH(ipha);
17531 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17532 				if (!pullupmsg(mp, (uchar_t *)ipha +
17533 				    + hdr_length - mp->b_rptr)) {
17534 					freemsg(first_mp);
17535 					return;
17536 				}
17537 				ipha = (ipha_t *)mp->b_rptr;
17538 			}
17539 			if (hdr_length > sizeof (ipha_t)) {
17540 				/* We got options on the inner packet. */
17541 				ipaddr_t dst = ipha->ipha_dst;
17542 
17543 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17544 				    -1) {
17545 					/* Bad options! */
17546 					return;
17547 				}
17548 				if (dst != ipha->ipha_dst) {
17549 					/*
17550 					 * Someone put a source-route in
17551 					 * the inside header of a self-
17552 					 * encapsulated packet.  Drop it
17553 					 * with extreme prejudice and let
17554 					 * the sender know.
17555 					 */
17556 					icmp_unreachable(q, first_mp,
17557 					    ICMP_SOURCE_ROUTE_FAILED,
17558 					    recv_ill->ill_zoneid, ipst);
17559 					return;
17560 				}
17561 			}
17562 			if (!mctl_present) {
17563 				ASSERT(first_mp == mp);
17564 				/*
17565 				 * This means that somebody is sending
17566 				 * Self-encapsualted packets without AH/ESP.
17567 				 * If AH/ESP was present, we would have already
17568 				 * allocated the first_mp.
17569 				 *
17570 				 * Send this packet to find a tunnel endpoint.
17571 				 * if I can't find one, an ICMP
17572 				 * PROTOCOL_UNREACHABLE will get sent.
17573 				 */
17574 				goto fanout;
17575 			}
17576 			/*
17577 			 * We generally store the ill_index if we need to
17578 			 * do IPsec processing as we lose the ill queue when
17579 			 * we come back. But in this case, we never should
17580 			 * have to store the ill_index here as it should have
17581 			 * been stored previously when we processed the
17582 			 * AH/ESP header in this routine or for non-ipsec
17583 			 * cases, we still have the queue. But for some bad
17584 			 * packets from the wire, we can get to IPsec after
17585 			 * this and we better store the index for that case.
17586 			 */
17587 			ill = (ill_t *)q->q_ptr;
17588 			ii = (ipsec_in_t *)first_mp->b_rptr;
17589 			ii->ipsec_in_ill_index =
17590 			    ill->ill_phyint->phyint_ifindex;
17591 			ii->ipsec_in_rill_index =
17592 			    recv_ill->ill_phyint->phyint_ifindex;
17593 			if (ii->ipsec_in_decaps) {
17594 				/*
17595 				 * This packet is self-encapsulated multiple
17596 				 * times. We don't want to recurse infinitely.
17597 				 * To keep it simple, drop the packet.
17598 				 */
17599 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17600 				freemsg(first_mp);
17601 				return;
17602 			}
17603 			ii->ipsec_in_decaps = B_TRUE;
17604 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17605 			    ire);
17606 			return;
17607 		}
17608 		break;
17609 	case IPPROTO_AH:
17610 	case IPPROTO_ESP: {
17611 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17612 
17613 		/*
17614 		 * Fast path for AH/ESP. If this is the first time
17615 		 * we are sending a datagram to AH/ESP, allocate
17616 		 * a IPSEC_IN message and prepend it. Otherwise,
17617 		 * just fanout.
17618 		 */
17619 
17620 		int ipsec_rc;
17621 		ipsec_in_t *ii;
17622 		netstack_t *ns = ipst->ips_netstack;
17623 
17624 		IP_STAT(ipst, ipsec_proto_ahesp);
17625 		if (!mctl_present) {
17626 			ASSERT(first_mp == mp);
17627 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17628 			if (first_mp == NULL) {
17629 				ip1dbg(("ip_proto_input: IPSEC_IN "
17630 				    "allocation failure.\n"));
17631 				freemsg(hada_mp); /* okay ifnull */
17632 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17633 				freemsg(mp);
17634 				return;
17635 			}
17636 			/*
17637 			 * Store the ill_index so that when we come back
17638 			 * from IPsec we ride on the same queue.
17639 			 */
17640 			ill = (ill_t *)q->q_ptr;
17641 			ii = (ipsec_in_t *)first_mp->b_rptr;
17642 			ii->ipsec_in_ill_index =
17643 			    ill->ill_phyint->phyint_ifindex;
17644 			ii->ipsec_in_rill_index =
17645 			    recv_ill->ill_phyint->phyint_ifindex;
17646 			first_mp->b_cont = mp;
17647 			/*
17648 			 * Cache hardware acceleration info.
17649 			 */
17650 			if (hada_mp != NULL) {
17651 				IPSECHW_DEBUG(IPSECHW_PKT,
17652 				    ("ip_rput_local: caching data attr.\n"));
17653 				ii->ipsec_in_accelerated = B_TRUE;
17654 				ii->ipsec_in_da = hada_mp;
17655 				hada_mp = NULL;
17656 			}
17657 		} else {
17658 			ii = (ipsec_in_t *)first_mp->b_rptr;
17659 		}
17660 
17661 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17662 
17663 		if (!ipsec_loaded(ipss)) {
17664 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17665 			    ire->ire_zoneid, ipst);
17666 			return;
17667 		}
17668 
17669 		ns = ipst->ips_netstack;
17670 		/* select inbound SA and have IPsec process the pkt */
17671 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17672 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17673 			boolean_t esp_in_udp_sa;
17674 			if (esph == NULL)
17675 				return;
17676 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17677 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17678 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17679 			    IPSA_F_NATT) != 0);
17680 			/*
17681 			 * The following is a fancy, but quick, way of saying:
17682 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17683 			 *    OR
17684 			 * ESP SA and ESP-in-UDP packet --> drop
17685 			 */
17686 			if (esp_in_udp_sa != esp_in_udp_packet) {
17687 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17688 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17689 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17690 				    &ns->netstack_ipsec->ipsec_dropper);
17691 				return;
17692 			}
17693 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17694 			    first_mp, esph);
17695 		} else {
17696 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17697 			if (ah == NULL)
17698 				return;
17699 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17700 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17701 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17702 			    first_mp, ah);
17703 		}
17704 
17705 		switch (ipsec_rc) {
17706 		case IPSEC_STATUS_SUCCESS:
17707 			break;
17708 		case IPSEC_STATUS_FAILED:
17709 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17710 			/* FALLTHRU */
17711 		case IPSEC_STATUS_PENDING:
17712 			return;
17713 		}
17714 		/* we're done with IPsec processing, send it up */
17715 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17716 		return;
17717 	}
17718 	default:
17719 		break;
17720 	}
17721 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17722 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17723 		    ire->ire_zoneid));
17724 		goto drop_pkt;
17725 	}
17726 	/*
17727 	 * Handle protocols with which IP is less intimate.  There
17728 	 * can be more than one stream bound to a particular
17729 	 * protocol.  When this is the case, each one gets a copy
17730 	 * of any incoming packets.
17731 	 */
17732 fanout:
17733 	ip_fanout_proto(q, first_mp, ill, ipha,
17734 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17735 	    B_TRUE, recv_ill, ire->ire_zoneid);
17736 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17737 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17738 	return;
17739 
17740 drop_pkt:
17741 	freemsg(first_mp);
17742 	if (hada_mp != NULL)
17743 		freeb(hada_mp);
17744 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17745 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17746 #undef	rptr
17747 #undef  iphs
17748 
17749 }
17750 
17751 /*
17752  * Update any source route, record route or timestamp options.
17753  * Check that we are at end of strict source route.
17754  * The options have already been checked for sanity in ip_rput_options().
17755  */
17756 static boolean_t
17757 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17758     ip_stack_t *ipst)
17759 {
17760 	ipoptp_t	opts;
17761 	uchar_t		*opt;
17762 	uint8_t		optval;
17763 	uint8_t		optlen;
17764 	ipaddr_t	dst;
17765 	uint32_t	ts;
17766 	ire_t		*dst_ire;
17767 	timestruc_t	now;
17768 	zoneid_t	zoneid;
17769 	ill_t		*ill;
17770 
17771 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17772 
17773 	ip2dbg(("ip_rput_local_options\n"));
17774 
17775 	for (optval = ipoptp_first(&opts, ipha);
17776 	    optval != IPOPT_EOL;
17777 	    optval = ipoptp_next(&opts)) {
17778 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17779 		opt = opts.ipoptp_cur;
17780 		optlen = opts.ipoptp_len;
17781 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17782 		    optval, optlen));
17783 		switch (optval) {
17784 			uint32_t off;
17785 		case IPOPT_SSRR:
17786 		case IPOPT_LSRR:
17787 			off = opt[IPOPT_OFFSET];
17788 			off--;
17789 			if (optlen < IP_ADDR_LEN ||
17790 			    off > optlen - IP_ADDR_LEN) {
17791 				/* End of source route */
17792 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17793 				break;
17794 			}
17795 			/*
17796 			 * This will only happen if two consecutive entries
17797 			 * in the source route contains our address or if
17798 			 * it is a packet with a loose source route which
17799 			 * reaches us before consuming the whole source route
17800 			 */
17801 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17802 			if (optval == IPOPT_SSRR) {
17803 				goto bad_src_route;
17804 			}
17805 			/*
17806 			 * Hack: instead of dropping the packet truncate the
17807 			 * source route to what has been used by filling the
17808 			 * rest with IPOPT_NOP.
17809 			 */
17810 			opt[IPOPT_OLEN] = (uint8_t)off;
17811 			while (off < optlen) {
17812 				opt[off++] = IPOPT_NOP;
17813 			}
17814 			break;
17815 		case IPOPT_RR:
17816 			off = opt[IPOPT_OFFSET];
17817 			off--;
17818 			if (optlen < IP_ADDR_LEN ||
17819 			    off > optlen - IP_ADDR_LEN) {
17820 				/* No more room - ignore */
17821 				ip1dbg((
17822 				    "ip_rput_local_options: end of RR\n"));
17823 				break;
17824 			}
17825 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17826 			    IP_ADDR_LEN);
17827 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17828 			break;
17829 		case IPOPT_TS:
17830 			/* Insert timestamp if there is romm */
17831 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17832 			case IPOPT_TS_TSONLY:
17833 				off = IPOPT_TS_TIMELEN;
17834 				break;
17835 			case IPOPT_TS_PRESPEC:
17836 			case IPOPT_TS_PRESPEC_RFC791:
17837 				/* Verify that the address matched */
17838 				off = opt[IPOPT_OFFSET] - 1;
17839 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17840 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17841 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17842 				    ipst);
17843 				if (dst_ire == NULL) {
17844 					/* Not for us */
17845 					break;
17846 				}
17847 				ire_refrele(dst_ire);
17848 				/* FALLTHRU */
17849 			case IPOPT_TS_TSANDADDR:
17850 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17851 				break;
17852 			default:
17853 				/*
17854 				 * ip_*put_options should have already
17855 				 * dropped this packet.
17856 				 */
17857 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17858 				    "unknown IT - bug in ip_rput_options?\n");
17859 				return (B_TRUE);	/* Keep "lint" happy */
17860 			}
17861 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17862 				/* Increase overflow counter */
17863 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17864 				opt[IPOPT_POS_OV_FLG] =
17865 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17866 				    (off << 4));
17867 				break;
17868 			}
17869 			off = opt[IPOPT_OFFSET] - 1;
17870 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17871 			case IPOPT_TS_PRESPEC:
17872 			case IPOPT_TS_PRESPEC_RFC791:
17873 			case IPOPT_TS_TSANDADDR:
17874 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17875 				    IP_ADDR_LEN);
17876 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17877 				/* FALLTHRU */
17878 			case IPOPT_TS_TSONLY:
17879 				off = opt[IPOPT_OFFSET] - 1;
17880 				/* Compute # of milliseconds since midnight */
17881 				gethrestime(&now);
17882 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17883 				    now.tv_nsec / (NANOSEC / MILLISEC);
17884 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17885 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17886 				break;
17887 			}
17888 			break;
17889 		}
17890 	}
17891 	return (B_TRUE);
17892 
17893 bad_src_route:
17894 	q = WR(q);
17895 	if (q->q_next != NULL)
17896 		ill = q->q_ptr;
17897 	else
17898 		ill = NULL;
17899 
17900 	/* make sure we clear any indication of a hardware checksum */
17901 	DB_CKSUMFLAGS(mp) = 0;
17902 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17903 	if (zoneid == ALL_ZONES)
17904 		freemsg(mp);
17905 	else
17906 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17907 	return (B_FALSE);
17908 
17909 }
17910 
17911 /*
17912  * Process IP options in an inbound packet.  If an option affects the
17913  * effective destination address, return the next hop address via dstp.
17914  * Returns -1 if something fails in which case an ICMP error has been sent
17915  * and mp freed.
17916  */
17917 static int
17918 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17919     ip_stack_t *ipst)
17920 {
17921 	ipoptp_t	opts;
17922 	uchar_t		*opt;
17923 	uint8_t		optval;
17924 	uint8_t		optlen;
17925 	ipaddr_t	dst;
17926 	intptr_t	code = 0;
17927 	ire_t		*ire = NULL;
17928 	zoneid_t	zoneid;
17929 	ill_t		*ill;
17930 
17931 	ip2dbg(("ip_rput_options\n"));
17932 	dst = ipha->ipha_dst;
17933 	for (optval = ipoptp_first(&opts, ipha);
17934 	    optval != IPOPT_EOL;
17935 	    optval = ipoptp_next(&opts)) {
17936 		opt = opts.ipoptp_cur;
17937 		optlen = opts.ipoptp_len;
17938 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17939 		    optval, optlen));
17940 		/*
17941 		 * Note: we need to verify the checksum before we
17942 		 * modify anything thus this routine only extracts the next
17943 		 * hop dst from any source route.
17944 		 */
17945 		switch (optval) {
17946 			uint32_t off;
17947 		case IPOPT_SSRR:
17948 		case IPOPT_LSRR:
17949 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17950 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17951 			if (ire == NULL) {
17952 				if (optval == IPOPT_SSRR) {
17953 					ip1dbg(("ip_rput_options: not next"
17954 					    " strict source route 0x%x\n",
17955 					    ntohl(dst)));
17956 					code = (char *)&ipha->ipha_dst -
17957 					    (char *)ipha;
17958 					goto param_prob; /* RouterReq's */
17959 				}
17960 				ip2dbg(("ip_rput_options: "
17961 				    "not next source route 0x%x\n",
17962 				    ntohl(dst)));
17963 				break;
17964 			}
17965 			ire_refrele(ire);
17966 
17967 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17968 				ip1dbg((
17969 				    "ip_rput_options: bad option offset\n"));
17970 				code = (char *)&opt[IPOPT_OLEN] -
17971 				    (char *)ipha;
17972 				goto param_prob;
17973 			}
17974 			off = opt[IPOPT_OFFSET];
17975 			off--;
17976 		redo_srr:
17977 			if (optlen < IP_ADDR_LEN ||
17978 			    off > optlen - IP_ADDR_LEN) {
17979 				/* End of source route */
17980 				ip1dbg(("ip_rput_options: end of SR\n"));
17981 				break;
17982 			}
17983 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17984 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17985 			    ntohl(dst)));
17986 
17987 			/*
17988 			 * Check if our address is present more than
17989 			 * once as consecutive hops in source route.
17990 			 * XXX verify per-interface ip_forwarding
17991 			 * for source route?
17992 			 */
17993 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17994 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17995 
17996 			if (ire != NULL) {
17997 				ire_refrele(ire);
17998 				off += IP_ADDR_LEN;
17999 				goto redo_srr;
18000 			}
18001 
18002 			if (dst == htonl(INADDR_LOOPBACK)) {
18003 				ip1dbg(("ip_rput_options: loopback addr in "
18004 				    "source route!\n"));
18005 				goto bad_src_route;
18006 			}
18007 			/*
18008 			 * For strict: verify that dst is directly
18009 			 * reachable.
18010 			 */
18011 			if (optval == IPOPT_SSRR) {
18012 				ire = ire_ftable_lookup(dst, 0, 0,
18013 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18014 				    MBLK_GETLABEL(mp),
18015 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18016 				if (ire == NULL) {
18017 					ip1dbg(("ip_rput_options: SSRR not "
18018 					    "directly reachable: 0x%x\n",
18019 					    ntohl(dst)));
18020 					goto bad_src_route;
18021 				}
18022 				ire_refrele(ire);
18023 			}
18024 			/*
18025 			 * Defer update of the offset and the record route
18026 			 * until the packet is forwarded.
18027 			 */
18028 			break;
18029 		case IPOPT_RR:
18030 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18031 				ip1dbg((
18032 				    "ip_rput_options: bad option offset\n"));
18033 				code = (char *)&opt[IPOPT_OLEN] -
18034 				    (char *)ipha;
18035 				goto param_prob;
18036 			}
18037 			break;
18038 		case IPOPT_TS:
18039 			/*
18040 			 * Verify that length >= 5 and that there is either
18041 			 * room for another timestamp or that the overflow
18042 			 * counter is not maxed out.
18043 			 */
18044 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18045 			if (optlen < IPOPT_MINLEN_IT) {
18046 				goto param_prob;
18047 			}
18048 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18049 				ip1dbg((
18050 				    "ip_rput_options: bad option offset\n"));
18051 				code = (char *)&opt[IPOPT_OFFSET] -
18052 				    (char *)ipha;
18053 				goto param_prob;
18054 			}
18055 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18056 			case IPOPT_TS_TSONLY:
18057 				off = IPOPT_TS_TIMELEN;
18058 				break;
18059 			case IPOPT_TS_TSANDADDR:
18060 			case IPOPT_TS_PRESPEC:
18061 			case IPOPT_TS_PRESPEC_RFC791:
18062 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18063 				break;
18064 			default:
18065 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18066 				    (char *)ipha;
18067 				goto param_prob;
18068 			}
18069 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18070 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18071 				/*
18072 				 * No room and the overflow counter is 15
18073 				 * already.
18074 				 */
18075 				goto param_prob;
18076 			}
18077 			break;
18078 		}
18079 	}
18080 
18081 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18082 		*dstp = dst;
18083 		return (0);
18084 	}
18085 
18086 	ip1dbg(("ip_rput_options: error processing IP options."));
18087 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18088 
18089 param_prob:
18090 	q = WR(q);
18091 	if (q->q_next != NULL)
18092 		ill = q->q_ptr;
18093 	else
18094 		ill = NULL;
18095 
18096 	/* make sure we clear any indication of a hardware checksum */
18097 	DB_CKSUMFLAGS(mp) = 0;
18098 	/* Don't know whether this is for non-global or global/forwarding */
18099 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18100 	if (zoneid == ALL_ZONES)
18101 		freemsg(mp);
18102 	else
18103 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18104 	return (-1);
18105 
18106 bad_src_route:
18107 	q = WR(q);
18108 	if (q->q_next != NULL)
18109 		ill = q->q_ptr;
18110 	else
18111 		ill = NULL;
18112 
18113 	/* make sure we clear any indication of a hardware checksum */
18114 	DB_CKSUMFLAGS(mp) = 0;
18115 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18116 	if (zoneid == ALL_ZONES)
18117 		freemsg(mp);
18118 	else
18119 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18120 	return (-1);
18121 }
18122 
18123 /*
18124  * IP & ICMP info in >=14 msg's ...
18125  *  - ip fixed part (mib2_ip_t)
18126  *  - icmp fixed part (mib2_icmp_t)
18127  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18128  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18129  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18130  *  - ipRouteAttributeTable (ip 102)	labeled routes
18131  *  - ip multicast membership (ip_member_t)
18132  *  - ip multicast source filtering (ip_grpsrc_t)
18133  *  - igmp fixed part (struct igmpstat)
18134  *  - multicast routing stats (struct mrtstat)
18135  *  - multicast routing vifs (array of struct vifctl)
18136  *  - multicast routing routes (array of struct mfcctl)
18137  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18138  *					One per ill plus one generic
18139  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18140  *					One per ill plus one generic
18141  *  - ipv6RouteEntry			all IPv6 IREs
18142  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18143  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18144  *  - ipv6AddrEntry			all IPv6 ipifs
18145  *  - ipv6 multicast membership (ipv6_member_t)
18146  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18147  *
18148  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18149  *
18150  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18151  * already filled in by the caller.
18152  * Return value of 0 indicates that no messages were sent and caller
18153  * should free mpctl.
18154  */
18155 int
18156 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18157 {
18158 	ip_stack_t *ipst;
18159 	sctp_stack_t *sctps;
18160 
18161 	if (q->q_next != NULL) {
18162 		ipst = ILLQ_TO_IPST(q);
18163 	} else {
18164 		ipst = CONNQ_TO_IPST(q);
18165 	}
18166 	ASSERT(ipst != NULL);
18167 	sctps = ipst->ips_netstack->netstack_sctp;
18168 
18169 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18170 		return (0);
18171 	}
18172 
18173 	/*
18174 	 * For the purposes of the (broken) packet shell use
18175 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18176 	 * to make TCP and UDP appear first in the list of mib items.
18177 	 * TBD: We could expand this and use it in netstat so that
18178 	 * the kernel doesn't have to produce large tables (connections,
18179 	 * routes, etc) when netstat only wants the statistics or a particular
18180 	 * table.
18181 	 */
18182 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18183 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18184 			return (1);
18185 		}
18186 	}
18187 
18188 	if (level != MIB2_TCP) {
18189 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18190 			return (1);
18191 		}
18192 	}
18193 
18194 	if (level != MIB2_UDP) {
18195 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18196 			return (1);
18197 		}
18198 	}
18199 
18200 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18201 	    ipst)) == NULL) {
18202 		return (1);
18203 	}
18204 
18205 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18206 		return (1);
18207 	}
18208 
18209 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18210 		return (1);
18211 	}
18212 
18213 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18214 		return (1);
18215 	}
18216 
18217 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18218 		return (1);
18219 	}
18220 
18221 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18222 		return (1);
18223 	}
18224 
18225 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18226 		return (1);
18227 	}
18228 
18229 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18230 		return (1);
18231 	}
18232 
18233 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18234 		return (1);
18235 	}
18236 
18237 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18238 		return (1);
18239 	}
18240 
18241 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18242 		return (1);
18243 	}
18244 
18245 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18246 		return (1);
18247 	}
18248 
18249 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18250 		return (1);
18251 	}
18252 
18253 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18254 		return (1);
18255 	}
18256 
18257 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18258 		return (1);
18259 	}
18260 
18261 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18262 	if (mpctl == NULL) {
18263 		return (1);
18264 	}
18265 
18266 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18267 		return (1);
18268 	}
18269 	freemsg(mpctl);
18270 	return (1);
18271 }
18272 
18273 
18274 /* Get global (legacy) IPv4 statistics */
18275 static mblk_t *
18276 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18277     ip_stack_t *ipst)
18278 {
18279 	mib2_ip_t		old_ip_mib;
18280 	struct opthdr		*optp;
18281 	mblk_t			*mp2ctl;
18282 
18283 	/*
18284 	 * make a copy of the original message
18285 	 */
18286 	mp2ctl = copymsg(mpctl);
18287 
18288 	/* fixed length IP structure... */
18289 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18290 	optp->level = MIB2_IP;
18291 	optp->name = 0;
18292 	SET_MIB(old_ip_mib.ipForwarding,
18293 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18294 	SET_MIB(old_ip_mib.ipDefaultTTL,
18295 	    (uint32_t)ipst->ips_ip_def_ttl);
18296 	SET_MIB(old_ip_mib.ipReasmTimeout,
18297 	    ipst->ips_ip_g_frag_timeout);
18298 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18299 	    sizeof (mib2_ipAddrEntry_t));
18300 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18301 	    sizeof (mib2_ipRouteEntry_t));
18302 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18303 	    sizeof (mib2_ipNetToMediaEntry_t));
18304 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18305 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18306 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18307 	    sizeof (mib2_ipAttributeEntry_t));
18308 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18309 
18310 	/*
18311 	 * Grab the statistics from the new IP MIB
18312 	 */
18313 	SET_MIB(old_ip_mib.ipInReceives,
18314 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18315 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18316 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18317 	SET_MIB(old_ip_mib.ipForwDatagrams,
18318 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18319 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18320 	    ipmib->ipIfStatsInUnknownProtos);
18321 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18322 	SET_MIB(old_ip_mib.ipInDelivers,
18323 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18324 	SET_MIB(old_ip_mib.ipOutRequests,
18325 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18326 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18327 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18328 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18329 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18330 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18331 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18332 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18333 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18334 
18335 	/* ipRoutingDiscards is not being used */
18336 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18337 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18338 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18339 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18340 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18341 	    ipmib->ipIfStatsReasmDuplicates);
18342 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18343 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18344 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18345 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18346 	SET_MIB(old_ip_mib.rawipInOverflows,
18347 	    ipmib->rawipIfStatsInOverflows);
18348 
18349 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18350 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18351 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18352 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18353 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18354 	    ipmib->ipIfStatsOutSwitchIPVersion);
18355 
18356 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18357 	    (int)sizeof (old_ip_mib))) {
18358 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18359 		    (uint_t)sizeof (old_ip_mib)));
18360 	}
18361 
18362 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18363 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18364 	    (int)optp->level, (int)optp->name, (int)optp->len));
18365 	qreply(q, mpctl);
18366 	return (mp2ctl);
18367 }
18368 
18369 /* Per interface IPv4 statistics */
18370 static mblk_t *
18371 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18372 {
18373 	struct opthdr		*optp;
18374 	mblk_t			*mp2ctl;
18375 	ill_t			*ill;
18376 	ill_walk_context_t	ctx;
18377 	mblk_t			*mp_tail = NULL;
18378 	mib2_ipIfStatsEntry_t	global_ip_mib;
18379 
18380 	/*
18381 	 * Make a copy of the original message
18382 	 */
18383 	mp2ctl = copymsg(mpctl);
18384 
18385 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18386 	optp->level = MIB2_IP;
18387 	optp->name = MIB2_IP_TRAFFIC_STATS;
18388 	/* Include "unknown interface" ip_mib */
18389 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18390 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18391 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18392 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18393 	    (ipst->ips_ip_g_forward ? 1 : 2));
18394 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18395 	    (uint32_t)ipst->ips_ip_def_ttl);
18396 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18397 	    sizeof (mib2_ipIfStatsEntry_t));
18398 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18399 	    sizeof (mib2_ipAddrEntry_t));
18400 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18401 	    sizeof (mib2_ipRouteEntry_t));
18402 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18403 	    sizeof (mib2_ipNetToMediaEntry_t));
18404 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18405 	    sizeof (ip_member_t));
18406 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18407 	    sizeof (ip_grpsrc_t));
18408 
18409 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18410 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18411 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18412 		    "failed to allocate %u bytes\n",
18413 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18414 	}
18415 
18416 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18417 
18418 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18419 	ill = ILL_START_WALK_V4(&ctx, ipst);
18420 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18421 		ill->ill_ip_mib->ipIfStatsIfIndex =
18422 		    ill->ill_phyint->phyint_ifindex;
18423 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18424 		    (ipst->ips_ip_g_forward ? 1 : 2));
18425 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18426 		    (uint32_t)ipst->ips_ip_def_ttl);
18427 
18428 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18429 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18430 		    (char *)ill->ill_ip_mib,
18431 		    (int)sizeof (*ill->ill_ip_mib))) {
18432 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18433 			    "failed to allocate %u bytes\n",
18434 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18435 		}
18436 	}
18437 	rw_exit(&ipst->ips_ill_g_lock);
18438 
18439 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18440 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18441 	    "level %d, name %d, len %d\n",
18442 	    (int)optp->level, (int)optp->name, (int)optp->len));
18443 	qreply(q, mpctl);
18444 
18445 	if (mp2ctl == NULL)
18446 		return (NULL);
18447 
18448 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18449 }
18450 
18451 /* Global IPv4 ICMP statistics */
18452 static mblk_t *
18453 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18454 {
18455 	struct opthdr		*optp;
18456 	mblk_t			*mp2ctl;
18457 
18458 	/*
18459 	 * Make a copy of the original message
18460 	 */
18461 	mp2ctl = copymsg(mpctl);
18462 
18463 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18464 	optp->level = MIB2_ICMP;
18465 	optp->name = 0;
18466 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18467 	    (int)sizeof (ipst->ips_icmp_mib))) {
18468 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18469 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18470 	}
18471 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18472 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18473 	    (int)optp->level, (int)optp->name, (int)optp->len));
18474 	qreply(q, mpctl);
18475 	return (mp2ctl);
18476 }
18477 
18478 /* Global IPv4 IGMP statistics */
18479 static mblk_t *
18480 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18481 {
18482 	struct opthdr		*optp;
18483 	mblk_t			*mp2ctl;
18484 
18485 	/*
18486 	 * make a copy of the original message
18487 	 */
18488 	mp2ctl = copymsg(mpctl);
18489 
18490 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18491 	optp->level = EXPER_IGMP;
18492 	optp->name = 0;
18493 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18494 	    (int)sizeof (ipst->ips_igmpstat))) {
18495 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18496 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18497 	}
18498 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18499 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18500 	    (int)optp->level, (int)optp->name, (int)optp->len));
18501 	qreply(q, mpctl);
18502 	return (mp2ctl);
18503 }
18504 
18505 /* Global IPv4 Multicast Routing statistics */
18506 static mblk_t *
18507 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18508 {
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 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18518 	optp->level = EXPER_DVMRP;
18519 	optp->name = 0;
18520 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18521 		ip0dbg(("ip_mroute_stats: failed\n"));
18522 	}
18523 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18524 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18525 	    (int)optp->level, (int)optp->name, (int)optp->len));
18526 	qreply(q, mpctl);
18527 	return (mp2ctl);
18528 }
18529 
18530 /* IPv4 address information */
18531 static mblk_t *
18532 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18533 {
18534 	struct opthdr		*optp;
18535 	mblk_t			*mp2ctl;
18536 	mblk_t			*mp_tail = NULL;
18537 	ill_t			*ill;
18538 	ipif_t			*ipif;
18539 	uint_t			bitval;
18540 	mib2_ipAddrEntry_t	mae;
18541 	zoneid_t		zoneid;
18542 	ill_walk_context_t ctx;
18543 
18544 	/*
18545 	 * make a copy of the original message
18546 	 */
18547 	mp2ctl = copymsg(mpctl);
18548 
18549 	/* ipAddrEntryTable */
18550 
18551 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18552 	optp->level = MIB2_IP;
18553 	optp->name = MIB2_IP_ADDR;
18554 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18555 
18556 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18557 	ill = ILL_START_WALK_V4(&ctx, ipst);
18558 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18559 		for (ipif = ill->ill_ipif; ipif != NULL;
18560 		    ipif = ipif->ipif_next) {
18561 			if (ipif->ipif_zoneid != zoneid &&
18562 			    ipif->ipif_zoneid != ALL_ZONES)
18563 				continue;
18564 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18565 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18566 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18567 
18568 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18569 			    OCTET_LENGTH);
18570 			mae.ipAdEntIfIndex.o_length =
18571 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18572 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18573 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18574 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18575 			mae.ipAdEntInfo.ae_subnet_len =
18576 			    ip_mask_to_plen(ipif->ipif_net_mask);
18577 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18578 			for (bitval = 1;
18579 			    bitval &&
18580 			    !(bitval & ipif->ipif_brd_addr);
18581 			    bitval <<= 1)
18582 				noop;
18583 			mae.ipAdEntBcastAddr = bitval;
18584 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18585 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18586 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18587 			mae.ipAdEntInfo.ae_broadcast_addr =
18588 			    ipif->ipif_brd_addr;
18589 			mae.ipAdEntInfo.ae_pp_dst_addr =
18590 			    ipif->ipif_pp_dst_addr;
18591 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18592 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18593 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18594 
18595 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18596 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18597 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18598 				    "allocate %u bytes\n",
18599 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18600 			}
18601 		}
18602 	}
18603 	rw_exit(&ipst->ips_ill_g_lock);
18604 
18605 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18606 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18607 	    (int)optp->level, (int)optp->name, (int)optp->len));
18608 	qreply(q, mpctl);
18609 	return (mp2ctl);
18610 }
18611 
18612 /* IPv6 address information */
18613 static mblk_t *
18614 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18615 {
18616 	struct opthdr		*optp;
18617 	mblk_t			*mp2ctl;
18618 	mblk_t			*mp_tail = NULL;
18619 	ill_t			*ill;
18620 	ipif_t			*ipif;
18621 	mib2_ipv6AddrEntry_t	mae6;
18622 	zoneid_t		zoneid;
18623 	ill_walk_context_t	ctx;
18624 
18625 	/*
18626 	 * make a copy of the original message
18627 	 */
18628 	mp2ctl = copymsg(mpctl);
18629 
18630 	/* ipv6AddrEntryTable */
18631 
18632 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18633 	optp->level = MIB2_IP6;
18634 	optp->name = MIB2_IP6_ADDR;
18635 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18636 
18637 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18638 	ill = ILL_START_WALK_V6(&ctx, ipst);
18639 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18640 		for (ipif = ill->ill_ipif; ipif != NULL;
18641 		    ipif = ipif->ipif_next) {
18642 			if (ipif->ipif_zoneid != zoneid &&
18643 			    ipif->ipif_zoneid != ALL_ZONES)
18644 				continue;
18645 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18646 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18647 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18648 
18649 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18650 			    OCTET_LENGTH);
18651 			mae6.ipv6AddrIfIndex.o_length =
18652 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18653 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18654 			mae6.ipv6AddrPfxLength =
18655 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18656 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18657 			mae6.ipv6AddrInfo.ae_subnet_len =
18658 			    mae6.ipv6AddrPfxLength;
18659 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18660 
18661 			/* Type: stateless(1), stateful(2), unknown(3) */
18662 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18663 				mae6.ipv6AddrType = 1;
18664 			else
18665 				mae6.ipv6AddrType = 2;
18666 			/* Anycast: true(1), false(2) */
18667 			if (ipif->ipif_flags & IPIF_ANYCAST)
18668 				mae6.ipv6AddrAnycastFlag = 1;
18669 			else
18670 				mae6.ipv6AddrAnycastFlag = 2;
18671 
18672 			/*
18673 			 * Address status: preferred(1), deprecated(2),
18674 			 * invalid(3), inaccessible(4), unknown(5)
18675 			 */
18676 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18677 				mae6.ipv6AddrStatus = 3;
18678 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18679 				mae6.ipv6AddrStatus = 2;
18680 			else
18681 				mae6.ipv6AddrStatus = 1;
18682 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18683 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18684 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18685 			    ipif->ipif_v6pp_dst_addr;
18686 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18687 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18688 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18689 			mae6.ipv6AddrIdentifier = ill->ill_token;
18690 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18691 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18692 			mae6.ipv6AddrRetransmitTime =
18693 			    ill->ill_reachable_retrans_time;
18694 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18695 			    (char *)&mae6,
18696 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18697 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18698 				    "allocate %u bytes\n",
18699 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18700 			}
18701 		}
18702 	}
18703 	rw_exit(&ipst->ips_ill_g_lock);
18704 
18705 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18706 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18707 	    (int)optp->level, (int)optp->name, (int)optp->len));
18708 	qreply(q, mpctl);
18709 	return (mp2ctl);
18710 }
18711 
18712 /* IPv4 multicast group membership. */
18713 static mblk_t *
18714 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18715 {
18716 	struct opthdr		*optp;
18717 	mblk_t			*mp2ctl;
18718 	ill_t			*ill;
18719 	ipif_t			*ipif;
18720 	ilm_t			*ilm;
18721 	ip_member_t		ipm;
18722 	mblk_t			*mp_tail = NULL;
18723 	ill_walk_context_t	ctx;
18724 	zoneid_t		zoneid;
18725 
18726 	/*
18727 	 * make a copy of the original message
18728 	 */
18729 	mp2ctl = copymsg(mpctl);
18730 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18731 
18732 	/* ipGroupMember table */
18733 	optp = (struct opthdr *)&mpctl->b_rptr[
18734 	    sizeof (struct T_optmgmt_ack)];
18735 	optp->level = MIB2_IP;
18736 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18737 
18738 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18739 	ill = ILL_START_WALK_V4(&ctx, ipst);
18740 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18741 		ILM_WALKER_HOLD(ill);
18742 		for (ipif = ill->ill_ipif; ipif != NULL;
18743 		    ipif = ipif->ipif_next) {
18744 			if (ipif->ipif_zoneid != zoneid &&
18745 			    ipif->ipif_zoneid != ALL_ZONES)
18746 				continue;	/* not this zone */
18747 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18748 			    OCTET_LENGTH);
18749 			ipm.ipGroupMemberIfIndex.o_length =
18750 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18751 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18752 				ASSERT(ilm->ilm_ipif != NULL);
18753 				ASSERT(ilm->ilm_ill == NULL);
18754 				if (ilm->ilm_ipif != ipif)
18755 					continue;
18756 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18757 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18758 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18759 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18760 				    (char *)&ipm, (int)sizeof (ipm))) {
18761 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18762 					    "failed to allocate %u bytes\n",
18763 					    (uint_t)sizeof (ipm)));
18764 				}
18765 			}
18766 		}
18767 		ILM_WALKER_RELE(ill);
18768 	}
18769 	rw_exit(&ipst->ips_ill_g_lock);
18770 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18771 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18772 	    (int)optp->level, (int)optp->name, (int)optp->len));
18773 	qreply(q, mpctl);
18774 	return (mp2ctl);
18775 }
18776 
18777 /* IPv6 multicast group membership. */
18778 static mblk_t *
18779 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18780 {
18781 	struct opthdr		*optp;
18782 	mblk_t			*mp2ctl;
18783 	ill_t			*ill;
18784 	ilm_t			*ilm;
18785 	ipv6_member_t		ipm6;
18786 	mblk_t			*mp_tail = NULL;
18787 	ill_walk_context_t	ctx;
18788 	zoneid_t		zoneid;
18789 
18790 	/*
18791 	 * make a copy of the original message
18792 	 */
18793 	mp2ctl = copymsg(mpctl);
18794 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18795 
18796 	/* ip6GroupMember table */
18797 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18798 	optp->level = MIB2_IP6;
18799 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18800 
18801 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18802 	ill = ILL_START_WALK_V6(&ctx, ipst);
18803 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18804 		ILM_WALKER_HOLD(ill);
18805 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18806 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18807 			ASSERT(ilm->ilm_ipif == NULL);
18808 			ASSERT(ilm->ilm_ill != NULL);
18809 			if (ilm->ilm_zoneid != zoneid)
18810 				continue;	/* not this zone */
18811 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18812 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18813 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18814 			if (!snmp_append_data2(mpctl->b_cont,
18815 			    &mp_tail,
18816 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18817 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18818 				    "failed to allocate %u bytes\n",
18819 				    (uint_t)sizeof (ipm6)));
18820 			}
18821 		}
18822 		ILM_WALKER_RELE(ill);
18823 	}
18824 	rw_exit(&ipst->ips_ill_g_lock);
18825 
18826 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18827 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18828 	    (int)optp->level, (int)optp->name, (int)optp->len));
18829 	qreply(q, mpctl);
18830 	return (mp2ctl);
18831 }
18832 
18833 /* IP multicast filtered sources */
18834 static mblk_t *
18835 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18836 {
18837 	struct opthdr		*optp;
18838 	mblk_t			*mp2ctl;
18839 	ill_t			*ill;
18840 	ipif_t			*ipif;
18841 	ilm_t			*ilm;
18842 	ip_grpsrc_t		ips;
18843 	mblk_t			*mp_tail = NULL;
18844 	ill_walk_context_t	ctx;
18845 	zoneid_t		zoneid;
18846 	int			i;
18847 	slist_t			*sl;
18848 
18849 	/*
18850 	 * make a copy of the original message
18851 	 */
18852 	mp2ctl = copymsg(mpctl);
18853 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18854 
18855 	/* ipGroupSource table */
18856 	optp = (struct opthdr *)&mpctl->b_rptr[
18857 	    sizeof (struct T_optmgmt_ack)];
18858 	optp->level = MIB2_IP;
18859 	optp->name = EXPER_IP_GROUP_SOURCES;
18860 
18861 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18862 	ill = ILL_START_WALK_V4(&ctx, ipst);
18863 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18864 		ILM_WALKER_HOLD(ill);
18865 		for (ipif = ill->ill_ipif; ipif != NULL;
18866 		    ipif = ipif->ipif_next) {
18867 			if (ipif->ipif_zoneid != zoneid)
18868 				continue;	/* not this zone */
18869 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18870 			    OCTET_LENGTH);
18871 			ips.ipGroupSourceIfIndex.o_length =
18872 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18873 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18874 				ASSERT(ilm->ilm_ipif != NULL);
18875 				ASSERT(ilm->ilm_ill == NULL);
18876 				sl = ilm->ilm_filter;
18877 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18878 					continue;
18879 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18880 				for (i = 0; i < sl->sl_numsrc; i++) {
18881 					if (!IN6_IS_ADDR_V4MAPPED(
18882 					    &sl->sl_addr[i]))
18883 						continue;
18884 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18885 					    ips.ipGroupSourceAddress);
18886 					if (snmp_append_data2(mpctl->b_cont,
18887 					    &mp_tail, (char *)&ips,
18888 					    (int)sizeof (ips)) == 0) {
18889 						ip1dbg(("ip_snmp_get_mib2_"
18890 						    "ip_group_src: failed to "
18891 						    "allocate %u bytes\n",
18892 						    (uint_t)sizeof (ips)));
18893 					}
18894 				}
18895 			}
18896 		}
18897 		ILM_WALKER_RELE(ill);
18898 	}
18899 	rw_exit(&ipst->ips_ill_g_lock);
18900 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18901 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18902 	    (int)optp->level, (int)optp->name, (int)optp->len));
18903 	qreply(q, mpctl);
18904 	return (mp2ctl);
18905 }
18906 
18907 /* IPv6 multicast filtered sources. */
18908 static mblk_t *
18909 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18910 {
18911 	struct opthdr		*optp;
18912 	mblk_t			*mp2ctl;
18913 	ill_t			*ill;
18914 	ilm_t			*ilm;
18915 	ipv6_grpsrc_t		ips6;
18916 	mblk_t			*mp_tail = NULL;
18917 	ill_walk_context_t	ctx;
18918 	zoneid_t		zoneid;
18919 	int			i;
18920 	slist_t			*sl;
18921 
18922 	/*
18923 	 * make a copy of the original message
18924 	 */
18925 	mp2ctl = copymsg(mpctl);
18926 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18927 
18928 	/* ip6GroupMember table */
18929 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18930 	optp->level = MIB2_IP6;
18931 	optp->name = EXPER_IP6_GROUP_SOURCES;
18932 
18933 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18934 	ill = ILL_START_WALK_V6(&ctx, ipst);
18935 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18936 		ILM_WALKER_HOLD(ill);
18937 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18938 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18939 			ASSERT(ilm->ilm_ipif == NULL);
18940 			ASSERT(ilm->ilm_ill != NULL);
18941 			sl = ilm->ilm_filter;
18942 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18943 				continue;
18944 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18945 			for (i = 0; i < sl->sl_numsrc; i++) {
18946 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18947 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18948 				    (char *)&ips6, (int)sizeof (ips6))) {
18949 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18950 					    "group_src: failed to allocate "
18951 					    "%u bytes\n",
18952 					    (uint_t)sizeof (ips6)));
18953 				}
18954 			}
18955 		}
18956 		ILM_WALKER_RELE(ill);
18957 	}
18958 	rw_exit(&ipst->ips_ill_g_lock);
18959 
18960 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18961 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18962 	    (int)optp->level, (int)optp->name, (int)optp->len));
18963 	qreply(q, mpctl);
18964 	return (mp2ctl);
18965 }
18966 
18967 /* Multicast routing virtual interface table. */
18968 static mblk_t *
18969 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18970 {
18971 	struct opthdr		*optp;
18972 	mblk_t			*mp2ctl;
18973 
18974 	/*
18975 	 * make a copy of the original message
18976 	 */
18977 	mp2ctl = copymsg(mpctl);
18978 
18979 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18980 	optp->level = EXPER_DVMRP;
18981 	optp->name = EXPER_DVMRP_VIF;
18982 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18983 		ip0dbg(("ip_mroute_vif: failed\n"));
18984 	}
18985 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18986 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18987 	    (int)optp->level, (int)optp->name, (int)optp->len));
18988 	qreply(q, mpctl);
18989 	return (mp2ctl);
18990 }
18991 
18992 /* Multicast routing table. */
18993 static mblk_t *
18994 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18995 {
18996 	struct opthdr		*optp;
18997 	mblk_t			*mp2ctl;
18998 
18999 	/*
19000 	 * make a copy of the original message
19001 	 */
19002 	mp2ctl = copymsg(mpctl);
19003 
19004 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19005 	optp->level = EXPER_DVMRP;
19006 	optp->name = EXPER_DVMRP_MRT;
19007 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19008 		ip0dbg(("ip_mroute_mrt: failed\n"));
19009 	}
19010 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19011 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19012 	    (int)optp->level, (int)optp->name, (int)optp->len));
19013 	qreply(q, mpctl);
19014 	return (mp2ctl);
19015 }
19016 
19017 /*
19018  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19019  * in one IRE walk.
19020  */
19021 static mblk_t *
19022 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19023 {
19024 	struct opthdr	*optp;
19025 	mblk_t		*mp2ctl;	/* Returned */
19026 	mblk_t		*mp3ctl;	/* nettomedia */
19027 	mblk_t		*mp4ctl;	/* routeattrs */
19028 	iproutedata_t	ird;
19029 	zoneid_t	zoneid;
19030 
19031 	/*
19032 	 * make copies of the original message
19033 	 *	- mp2ctl is returned unchanged to the caller for his use
19034 	 *	- mpctl is sent upstream as ipRouteEntryTable
19035 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19036 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19037 	 */
19038 	mp2ctl = copymsg(mpctl);
19039 	mp3ctl = copymsg(mpctl);
19040 	mp4ctl = copymsg(mpctl);
19041 	if (mp3ctl == NULL || mp4ctl == NULL) {
19042 		freemsg(mp4ctl);
19043 		freemsg(mp3ctl);
19044 		freemsg(mp2ctl);
19045 		freemsg(mpctl);
19046 		return (NULL);
19047 	}
19048 
19049 	bzero(&ird, sizeof (ird));
19050 
19051 	ird.ird_route.lp_head = mpctl->b_cont;
19052 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19053 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19054 
19055 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19056 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19057 
19058 	/* ipRouteEntryTable in mpctl */
19059 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19060 	optp->level = MIB2_IP;
19061 	optp->name = MIB2_IP_ROUTE;
19062 	optp->len = msgdsize(ird.ird_route.lp_head);
19063 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19064 	    (int)optp->level, (int)optp->name, (int)optp->len));
19065 	qreply(q, mpctl);
19066 
19067 	/* ipNetToMediaEntryTable in mp3ctl */
19068 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19069 	optp->level = MIB2_IP;
19070 	optp->name = MIB2_IP_MEDIA;
19071 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19072 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19073 	    (int)optp->level, (int)optp->name, (int)optp->len));
19074 	qreply(q, mp3ctl);
19075 
19076 	/* ipRouteAttributeTable in mp4ctl */
19077 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19078 	optp->level = MIB2_IP;
19079 	optp->name = EXPER_IP_RTATTR;
19080 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19081 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19082 	    (int)optp->level, (int)optp->name, (int)optp->len));
19083 	if (optp->len == 0)
19084 		freemsg(mp4ctl);
19085 	else
19086 		qreply(q, mp4ctl);
19087 
19088 	return (mp2ctl);
19089 }
19090 
19091 /*
19092  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19093  * ipv6NetToMediaEntryTable in an NDP walk.
19094  */
19095 static mblk_t *
19096 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19097 {
19098 	struct opthdr	*optp;
19099 	mblk_t		*mp2ctl;	/* Returned */
19100 	mblk_t		*mp3ctl;	/* nettomedia */
19101 	mblk_t		*mp4ctl;	/* routeattrs */
19102 	iproutedata_t	ird;
19103 	zoneid_t	zoneid;
19104 
19105 	/*
19106 	 * make copies of the original message
19107 	 *	- mp2ctl is returned unchanged to the caller for his use
19108 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19109 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19110 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19111 	 */
19112 	mp2ctl = copymsg(mpctl);
19113 	mp3ctl = copymsg(mpctl);
19114 	mp4ctl = copymsg(mpctl);
19115 	if (mp3ctl == NULL || mp4ctl == NULL) {
19116 		freemsg(mp4ctl);
19117 		freemsg(mp3ctl);
19118 		freemsg(mp2ctl);
19119 		freemsg(mpctl);
19120 		return (NULL);
19121 	}
19122 
19123 	bzero(&ird, sizeof (ird));
19124 
19125 	ird.ird_route.lp_head = mpctl->b_cont;
19126 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19127 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19128 
19129 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19130 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19131 
19132 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19133 	optp->level = MIB2_IP6;
19134 	optp->name = MIB2_IP6_ROUTE;
19135 	optp->len = msgdsize(ird.ird_route.lp_head);
19136 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19137 	    (int)optp->level, (int)optp->name, (int)optp->len));
19138 	qreply(q, mpctl);
19139 
19140 	/* ipv6NetToMediaEntryTable in mp3ctl */
19141 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19142 
19143 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19144 	optp->level = MIB2_IP6;
19145 	optp->name = MIB2_IP6_MEDIA;
19146 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19147 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19148 	    (int)optp->level, (int)optp->name, (int)optp->len));
19149 	qreply(q, mp3ctl);
19150 
19151 	/* ipv6RouteAttributeTable in mp4ctl */
19152 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19153 	optp->level = MIB2_IP6;
19154 	optp->name = EXPER_IP_RTATTR;
19155 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19156 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19157 	    (int)optp->level, (int)optp->name, (int)optp->len));
19158 	if (optp->len == 0)
19159 		freemsg(mp4ctl);
19160 	else
19161 		qreply(q, mp4ctl);
19162 
19163 	return (mp2ctl);
19164 }
19165 
19166 /*
19167  * IPv6 mib: One per ill
19168  */
19169 static mblk_t *
19170 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19171 {
19172 	struct opthdr		*optp;
19173 	mblk_t			*mp2ctl;
19174 	ill_t			*ill;
19175 	ill_walk_context_t	ctx;
19176 	mblk_t			*mp_tail = NULL;
19177 
19178 	/*
19179 	 * Make a copy of the original message
19180 	 */
19181 	mp2ctl = copymsg(mpctl);
19182 
19183 	/* fixed length IPv6 structure ... */
19184 
19185 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19186 	optp->level = MIB2_IP6;
19187 	optp->name = 0;
19188 	/* Include "unknown interface" ip6_mib */
19189 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19190 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19191 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19192 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19193 	    ipst->ips_ipv6_forward ? 1 : 2);
19194 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19195 	    ipst->ips_ipv6_def_hops);
19196 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19197 	    sizeof (mib2_ipIfStatsEntry_t));
19198 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19199 	    sizeof (mib2_ipv6AddrEntry_t));
19200 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19201 	    sizeof (mib2_ipv6RouteEntry_t));
19202 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19203 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19204 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19205 	    sizeof (ipv6_member_t));
19206 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19207 	    sizeof (ipv6_grpsrc_t));
19208 
19209 	/*
19210 	 * Synchronize 64- and 32-bit counters
19211 	 */
19212 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19213 	    ipIfStatsHCInReceives);
19214 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19215 	    ipIfStatsHCInDelivers);
19216 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19217 	    ipIfStatsHCOutRequests);
19218 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19219 	    ipIfStatsHCOutForwDatagrams);
19220 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19221 	    ipIfStatsHCOutMcastPkts);
19222 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19223 	    ipIfStatsHCInMcastPkts);
19224 
19225 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19226 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19227 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19228 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19229 	}
19230 
19231 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19232 	ill = ILL_START_WALK_V6(&ctx, ipst);
19233 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19234 		ill->ill_ip_mib->ipIfStatsIfIndex =
19235 		    ill->ill_phyint->phyint_ifindex;
19236 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19237 		    ipst->ips_ipv6_forward ? 1 : 2);
19238 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19239 		    ill->ill_max_hops);
19240 
19241 		/*
19242 		 * Synchronize 64- and 32-bit counters
19243 		 */
19244 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19245 		    ipIfStatsHCInReceives);
19246 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19247 		    ipIfStatsHCInDelivers);
19248 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19249 		    ipIfStatsHCOutRequests);
19250 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19251 		    ipIfStatsHCOutForwDatagrams);
19252 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19253 		    ipIfStatsHCOutMcastPkts);
19254 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19255 		    ipIfStatsHCInMcastPkts);
19256 
19257 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19258 		    (char *)ill->ill_ip_mib,
19259 		    (int)sizeof (*ill->ill_ip_mib))) {
19260 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19261 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19262 		}
19263 	}
19264 	rw_exit(&ipst->ips_ill_g_lock);
19265 
19266 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19267 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19268 	    (int)optp->level, (int)optp->name, (int)optp->len));
19269 	qreply(q, mpctl);
19270 	return (mp2ctl);
19271 }
19272 
19273 /*
19274  * ICMPv6 mib: One per ill
19275  */
19276 static mblk_t *
19277 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19278 {
19279 	struct opthdr		*optp;
19280 	mblk_t			*mp2ctl;
19281 	ill_t			*ill;
19282 	ill_walk_context_t	ctx;
19283 	mblk_t			*mp_tail = NULL;
19284 	/*
19285 	 * Make a copy of the original message
19286 	 */
19287 	mp2ctl = copymsg(mpctl);
19288 
19289 	/* fixed length ICMPv6 structure ... */
19290 
19291 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19292 	optp->level = MIB2_ICMP6;
19293 	optp->name = 0;
19294 	/* Include "unknown interface" icmp6_mib */
19295 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19296 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19297 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19298 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19299 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19300 	    (char *)&ipst->ips_icmp6_mib,
19301 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19302 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19303 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19304 	}
19305 
19306 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19307 	ill = ILL_START_WALK_V6(&ctx, ipst);
19308 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19309 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19310 		    ill->ill_phyint->phyint_ifindex;
19311 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19312 		    (char *)ill->ill_icmp6_mib,
19313 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19314 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19315 			    "%u bytes\n",
19316 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19317 		}
19318 	}
19319 	rw_exit(&ipst->ips_ill_g_lock);
19320 
19321 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19322 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19323 	    (int)optp->level, (int)optp->name, (int)optp->len));
19324 	qreply(q, mpctl);
19325 	return (mp2ctl);
19326 }
19327 
19328 /*
19329  * ire_walk routine to create both ipRouteEntryTable and
19330  * ipRouteAttributeTable in one IRE walk
19331  */
19332 static void
19333 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19334 {
19335 	ill_t				*ill;
19336 	ipif_t				*ipif;
19337 	mib2_ipRouteEntry_t		*re;
19338 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19339 	ipaddr_t			gw_addr;
19340 	tsol_ire_gw_secattr_t		*attrp;
19341 	tsol_gc_t			*gc = NULL;
19342 	tsol_gcgrp_t			*gcgrp = NULL;
19343 	uint_t				sacnt = 0;
19344 	int				i;
19345 
19346 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19347 
19348 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19349 		return;
19350 
19351 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19352 		mutex_enter(&attrp->igsa_lock);
19353 		if ((gc = attrp->igsa_gc) != NULL) {
19354 			gcgrp = gc->gc_grp;
19355 			ASSERT(gcgrp != NULL);
19356 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19357 			sacnt = 1;
19358 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19359 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19360 			gc = gcgrp->gcgrp_head;
19361 			sacnt = gcgrp->gcgrp_count;
19362 		}
19363 		mutex_exit(&attrp->igsa_lock);
19364 
19365 		/* do nothing if there's no gc to report */
19366 		if (gc == NULL) {
19367 			ASSERT(sacnt == 0);
19368 			if (gcgrp != NULL) {
19369 				/* we might as well drop the lock now */
19370 				rw_exit(&gcgrp->gcgrp_rwlock);
19371 				gcgrp = NULL;
19372 			}
19373 			attrp = NULL;
19374 		}
19375 
19376 		ASSERT(gc == NULL || (gcgrp != NULL &&
19377 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19378 	}
19379 	ASSERT(sacnt == 0 || gc != NULL);
19380 
19381 	if (sacnt != 0 &&
19382 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19383 		kmem_free(re, sizeof (*re));
19384 		rw_exit(&gcgrp->gcgrp_rwlock);
19385 		return;
19386 	}
19387 
19388 	/*
19389 	 * Return all IRE types for route table... let caller pick and choose
19390 	 */
19391 	re->ipRouteDest = ire->ire_addr;
19392 	ipif = ire->ire_ipif;
19393 	re->ipRouteIfIndex.o_length = 0;
19394 	if (ire->ire_type == IRE_CACHE) {
19395 		ill = (ill_t *)ire->ire_stq->q_ptr;
19396 		re->ipRouteIfIndex.o_length =
19397 		    ill->ill_name_length == 0 ? 0 :
19398 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19399 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19400 		    re->ipRouteIfIndex.o_length);
19401 	} else if (ipif != NULL) {
19402 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19403 		re->ipRouteIfIndex.o_length =
19404 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19405 	}
19406 	re->ipRouteMetric1 = -1;
19407 	re->ipRouteMetric2 = -1;
19408 	re->ipRouteMetric3 = -1;
19409 	re->ipRouteMetric4 = -1;
19410 
19411 	gw_addr = ire->ire_gateway_addr;
19412 
19413 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19414 		re->ipRouteNextHop = ire->ire_src_addr;
19415 	else
19416 		re->ipRouteNextHop = gw_addr;
19417 	/* indirect(4), direct(3), or invalid(2) */
19418 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19419 		re->ipRouteType = 2;
19420 	else
19421 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19422 	re->ipRouteProto = -1;
19423 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19424 	re->ipRouteMask = ire->ire_mask;
19425 	re->ipRouteMetric5 = -1;
19426 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19427 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19428 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19429 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19430 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19431 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19432 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19433 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19434 
19435 	if (ire->ire_flags & RTF_DYNAMIC) {
19436 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19437 	} else {
19438 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19439 	}
19440 
19441 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19442 	    (char *)re, (int)sizeof (*re))) {
19443 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19444 		    (uint_t)sizeof (*re)));
19445 	}
19446 
19447 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19448 		iaeptr->iae_routeidx = ird->ird_idx;
19449 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19450 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19451 	}
19452 
19453 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19454 	    (char *)iae, sacnt * sizeof (*iae))) {
19455 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19456 		    (unsigned)(sacnt * sizeof (*iae))));
19457 	}
19458 
19459 	/* bump route index for next pass */
19460 	ird->ird_idx++;
19461 
19462 	kmem_free(re, sizeof (*re));
19463 	if (sacnt != 0)
19464 		kmem_free(iae, sacnt * sizeof (*iae));
19465 
19466 	if (gcgrp != NULL)
19467 		rw_exit(&gcgrp->gcgrp_rwlock);
19468 }
19469 
19470 /*
19471  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19472  */
19473 static void
19474 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19475 {
19476 	ill_t				*ill;
19477 	ipif_t				*ipif;
19478 	mib2_ipv6RouteEntry_t		*re;
19479 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19480 	in6_addr_t			gw_addr_v6;
19481 	tsol_ire_gw_secattr_t		*attrp;
19482 	tsol_gc_t			*gc = NULL;
19483 	tsol_gcgrp_t			*gcgrp = NULL;
19484 	uint_t				sacnt = 0;
19485 	int				i;
19486 
19487 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19488 
19489 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19490 		return;
19491 
19492 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19493 		mutex_enter(&attrp->igsa_lock);
19494 		if ((gc = attrp->igsa_gc) != NULL) {
19495 			gcgrp = gc->gc_grp;
19496 			ASSERT(gcgrp != NULL);
19497 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19498 			sacnt = 1;
19499 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19500 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19501 			gc = gcgrp->gcgrp_head;
19502 			sacnt = gcgrp->gcgrp_count;
19503 		}
19504 		mutex_exit(&attrp->igsa_lock);
19505 
19506 		/* do nothing if there's no gc to report */
19507 		if (gc == NULL) {
19508 			ASSERT(sacnt == 0);
19509 			if (gcgrp != NULL) {
19510 				/* we might as well drop the lock now */
19511 				rw_exit(&gcgrp->gcgrp_rwlock);
19512 				gcgrp = NULL;
19513 			}
19514 			attrp = NULL;
19515 		}
19516 
19517 		ASSERT(gc == NULL || (gcgrp != NULL &&
19518 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19519 	}
19520 	ASSERT(sacnt == 0 || gc != NULL);
19521 
19522 	if (sacnt != 0 &&
19523 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19524 		kmem_free(re, sizeof (*re));
19525 		rw_exit(&gcgrp->gcgrp_rwlock);
19526 		return;
19527 	}
19528 
19529 	/*
19530 	 * Return all IRE types for route table... let caller pick and choose
19531 	 */
19532 	re->ipv6RouteDest = ire->ire_addr_v6;
19533 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19534 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19535 	re->ipv6RouteIfIndex.o_length = 0;
19536 	ipif = ire->ire_ipif;
19537 	if (ire->ire_type == IRE_CACHE) {
19538 		ill = (ill_t *)ire->ire_stq->q_ptr;
19539 		re->ipv6RouteIfIndex.o_length =
19540 		    ill->ill_name_length == 0 ? 0 :
19541 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19542 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19543 		    re->ipv6RouteIfIndex.o_length);
19544 	} else if (ipif != NULL) {
19545 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19546 		re->ipv6RouteIfIndex.o_length =
19547 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19548 	}
19549 
19550 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19551 
19552 	mutex_enter(&ire->ire_lock);
19553 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19554 	mutex_exit(&ire->ire_lock);
19555 
19556 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19557 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19558 	else
19559 		re->ipv6RouteNextHop = gw_addr_v6;
19560 
19561 	/* remote(4), local(3), or discard(2) */
19562 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19563 		re->ipv6RouteType = 2;
19564 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19565 		re->ipv6RouteType = 3;
19566 	else
19567 		re->ipv6RouteType = 4;
19568 
19569 	re->ipv6RouteProtocol	= -1;
19570 	re->ipv6RoutePolicy	= 0;
19571 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19572 	re->ipv6RouteNextHopRDI	= 0;
19573 	re->ipv6RouteWeight	= 0;
19574 	re->ipv6RouteMetric	= 0;
19575 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19576 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19577 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19578 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19579 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19580 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19581 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19582 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19583 
19584 	if (ire->ire_flags & RTF_DYNAMIC) {
19585 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19586 	} else {
19587 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19588 	}
19589 
19590 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19591 	    (char *)re, (int)sizeof (*re))) {
19592 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19593 		    (uint_t)sizeof (*re)));
19594 	}
19595 
19596 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19597 		iaeptr->iae_routeidx = ird->ird_idx;
19598 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19599 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19600 	}
19601 
19602 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19603 	    (char *)iae, sacnt * sizeof (*iae))) {
19604 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19605 		    (unsigned)(sacnt * sizeof (*iae))));
19606 	}
19607 
19608 	/* bump route index for next pass */
19609 	ird->ird_idx++;
19610 
19611 	kmem_free(re, sizeof (*re));
19612 	if (sacnt != 0)
19613 		kmem_free(iae, sacnt * sizeof (*iae));
19614 
19615 	if (gcgrp != NULL)
19616 		rw_exit(&gcgrp->gcgrp_rwlock);
19617 }
19618 
19619 /*
19620  * ndp_walk routine to create ipv6NetToMediaEntryTable
19621  */
19622 static int
19623 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19624 {
19625 	ill_t				*ill;
19626 	mib2_ipv6NetToMediaEntry_t	ntme;
19627 	dl_unitdata_req_t		*dl;
19628 
19629 	ill = nce->nce_ill;
19630 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19631 		return (0);
19632 
19633 	/*
19634 	 * Neighbor cache entry attached to IRE with on-link
19635 	 * destination.
19636 	 */
19637 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19638 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19639 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19640 	    (nce->nce_res_mp != NULL)) {
19641 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19642 		ntme.ipv6NetToMediaPhysAddress.o_length =
19643 		    dl->dl_dest_addr_length;
19644 	} else {
19645 		ntme.ipv6NetToMediaPhysAddress.o_length =
19646 		    ill->ill_phys_addr_length;
19647 	}
19648 	if (nce->nce_res_mp != NULL) {
19649 		bcopy((char *)nce->nce_res_mp->b_rptr +
19650 		    NCE_LL_ADDR_OFFSET(ill),
19651 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19652 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19653 	} else {
19654 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19655 		    ill->ill_phys_addr_length);
19656 	}
19657 	/*
19658 	 * Note: Returns ND_* states. Should be:
19659 	 * reachable(1), stale(2), delay(3), probe(4),
19660 	 * invalid(5), unknown(6)
19661 	 */
19662 	ntme.ipv6NetToMediaState = nce->nce_state;
19663 	ntme.ipv6NetToMediaLastUpdated = 0;
19664 
19665 	/* other(1), dynamic(2), static(3), local(4) */
19666 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19667 		ntme.ipv6NetToMediaType = 4;
19668 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19669 		ntme.ipv6NetToMediaType = 1;
19670 	} else {
19671 		ntme.ipv6NetToMediaType = 2;
19672 	}
19673 
19674 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19675 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19676 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19677 		    (uint_t)sizeof (ntme)));
19678 	}
19679 	return (0);
19680 }
19681 
19682 /*
19683  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19684  */
19685 /* ARGSUSED */
19686 int
19687 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19688 {
19689 	switch (level) {
19690 	case MIB2_IP:
19691 	case MIB2_ICMP:
19692 		switch (name) {
19693 		default:
19694 			break;
19695 		}
19696 		return (1);
19697 	default:
19698 		return (1);
19699 	}
19700 }
19701 
19702 /*
19703  * When there exists both a 64- and 32-bit counter of a particular type
19704  * (i.e., InReceives), only the 64-bit counters are added.
19705  */
19706 void
19707 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19708 {
19709 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19710 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19711 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19712 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19713 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19714 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19715 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19716 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19717 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19718 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19719 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19720 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19721 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19722 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19723 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19724 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19725 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19726 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19727 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19728 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19729 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19730 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19731 	    o2->ipIfStatsInWrongIPVersion);
19732 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19733 	    o2->ipIfStatsInWrongIPVersion);
19734 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19735 	    o2->ipIfStatsOutSwitchIPVersion);
19736 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19737 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19738 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19739 	    o2->ipIfStatsHCInForwDatagrams);
19740 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19741 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19742 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19743 	    o2->ipIfStatsHCOutForwDatagrams);
19744 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19745 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19746 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19747 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19748 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19749 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19750 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19751 	    o2->ipIfStatsHCOutMcastOctets);
19752 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19753 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19754 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19755 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19756 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19757 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19758 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19759 }
19760 
19761 void
19762 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19763 {
19764 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19765 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19766 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19767 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19768 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19769 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19770 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19771 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19772 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19773 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19774 	    o2->ipv6IfIcmpInRouterSolicits);
19775 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19776 	    o2->ipv6IfIcmpInRouterAdvertisements);
19777 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19778 	    o2->ipv6IfIcmpInNeighborSolicits);
19779 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19780 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19781 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19782 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19783 	    o2->ipv6IfIcmpInGroupMembQueries);
19784 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19785 	    o2->ipv6IfIcmpInGroupMembResponses);
19786 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19787 	    o2->ipv6IfIcmpInGroupMembReductions);
19788 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19789 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19790 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19791 	    o2->ipv6IfIcmpOutDestUnreachs);
19792 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19793 	    o2->ipv6IfIcmpOutAdminProhibs);
19794 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19795 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19796 	    o2->ipv6IfIcmpOutParmProblems);
19797 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19798 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19799 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19800 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19801 	    o2->ipv6IfIcmpOutRouterSolicits);
19802 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19803 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19804 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19805 	    o2->ipv6IfIcmpOutNeighborSolicits);
19806 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19807 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19808 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19809 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19810 	    o2->ipv6IfIcmpOutGroupMembQueries);
19811 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19812 	    o2->ipv6IfIcmpOutGroupMembResponses);
19813 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19814 	    o2->ipv6IfIcmpOutGroupMembReductions);
19815 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19816 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19817 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19818 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19819 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19820 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19821 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19822 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19823 	    o2->ipv6IfIcmpInGroupMembTotal);
19824 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19825 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19826 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19827 	    o2->ipv6IfIcmpInGroupMembBadReports);
19828 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19829 	    o2->ipv6IfIcmpInGroupMembOurReports);
19830 }
19831 
19832 /*
19833  * Called before the options are updated to check if this packet will
19834  * be source routed from here.
19835  * This routine assumes that the options are well formed i.e. that they
19836  * have already been checked.
19837  */
19838 static boolean_t
19839 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19840 {
19841 	ipoptp_t	opts;
19842 	uchar_t		*opt;
19843 	uint8_t		optval;
19844 	uint8_t		optlen;
19845 	ipaddr_t	dst;
19846 	ire_t		*ire;
19847 
19848 	if (IS_SIMPLE_IPH(ipha)) {
19849 		ip2dbg(("not source routed\n"));
19850 		return (B_FALSE);
19851 	}
19852 	dst = ipha->ipha_dst;
19853 	for (optval = ipoptp_first(&opts, ipha);
19854 	    optval != IPOPT_EOL;
19855 	    optval = ipoptp_next(&opts)) {
19856 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19857 		opt = opts.ipoptp_cur;
19858 		optlen = opts.ipoptp_len;
19859 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19860 		    optval, optlen));
19861 		switch (optval) {
19862 			uint32_t off;
19863 		case IPOPT_SSRR:
19864 		case IPOPT_LSRR:
19865 			/*
19866 			 * If dst is one of our addresses and there are some
19867 			 * entries left in the source route return (true).
19868 			 */
19869 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19870 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19871 			if (ire == NULL) {
19872 				ip2dbg(("ip_source_routed: not next"
19873 				    " source route 0x%x\n",
19874 				    ntohl(dst)));
19875 				return (B_FALSE);
19876 			}
19877 			ire_refrele(ire);
19878 			off = opt[IPOPT_OFFSET];
19879 			off--;
19880 			if (optlen < IP_ADDR_LEN ||
19881 			    off > optlen - IP_ADDR_LEN) {
19882 				/* End of source route */
19883 				ip1dbg(("ip_source_routed: end of SR\n"));
19884 				return (B_FALSE);
19885 			}
19886 			return (B_TRUE);
19887 		}
19888 	}
19889 	ip2dbg(("not source routed\n"));
19890 	return (B_FALSE);
19891 }
19892 
19893 /*
19894  * Check if the packet contains any source route.
19895  */
19896 static boolean_t
19897 ip_source_route_included(ipha_t *ipha)
19898 {
19899 	ipoptp_t	opts;
19900 	uint8_t		optval;
19901 
19902 	if (IS_SIMPLE_IPH(ipha))
19903 		return (B_FALSE);
19904 	for (optval = ipoptp_first(&opts, ipha);
19905 	    optval != IPOPT_EOL;
19906 	    optval = ipoptp_next(&opts)) {
19907 		switch (optval) {
19908 		case IPOPT_SSRR:
19909 		case IPOPT_LSRR:
19910 			return (B_TRUE);
19911 		}
19912 	}
19913 	return (B_FALSE);
19914 }
19915 
19916 /*
19917  * Called when the IRE expiration timer fires.
19918  */
19919 void
19920 ip_trash_timer_expire(void *args)
19921 {
19922 	int			flush_flag = 0;
19923 	ire_expire_arg_t	iea;
19924 	ip_stack_t		*ipst = (ip_stack_t *)args;
19925 
19926 	iea.iea_ipst = ipst;	/* No netstack_hold */
19927 
19928 	/*
19929 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19930 	 * This lock makes sure that a new invocation of this function
19931 	 * that occurs due to an almost immediate timer firing will not
19932 	 * progress beyond this point until the current invocation is done
19933 	 */
19934 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19935 	ipst->ips_ip_ire_expire_id = 0;
19936 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19937 
19938 	/* Periodic timer */
19939 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19940 	    ipst->ips_ip_ire_arp_interval) {
19941 		/*
19942 		 * Remove all IRE_CACHE entries since they might
19943 		 * contain arp information.
19944 		 */
19945 		flush_flag |= FLUSH_ARP_TIME;
19946 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19947 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19948 	}
19949 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19950 	    ipst->ips_ip_ire_redir_interval) {
19951 		/* Remove all redirects */
19952 		flush_flag |= FLUSH_REDIRECT_TIME;
19953 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19954 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19955 	}
19956 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19957 	    ipst->ips_ip_ire_pathmtu_interval) {
19958 		/* Increase path mtu */
19959 		flush_flag |= FLUSH_MTU_TIME;
19960 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19961 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19962 	}
19963 
19964 	/*
19965 	 * Optimize for the case when there are no redirects in the
19966 	 * ftable, that is, no need to walk the ftable in that case.
19967 	 */
19968 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19969 		iea.iea_flush_flag = flush_flag;
19970 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19971 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19972 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19973 		    NULL, ALL_ZONES, ipst);
19974 	}
19975 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19976 	    ipst->ips_ip_redirect_cnt > 0) {
19977 		iea.iea_flush_flag = flush_flag;
19978 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19979 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19980 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19981 	}
19982 	if (flush_flag & FLUSH_MTU_TIME) {
19983 		/*
19984 		 * Walk all IPv6 IRE's and update them
19985 		 * Note that ARP and redirect timers are not
19986 		 * needed since NUD handles stale entries.
19987 		 */
19988 		flush_flag = FLUSH_MTU_TIME;
19989 		iea.iea_flush_flag = flush_flag;
19990 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19991 		    ALL_ZONES, ipst);
19992 	}
19993 
19994 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19995 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19996 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19997 
19998 	/*
19999 	 * Hold the lock to serialize timeout calls and prevent
20000 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20001 	 * for the timer to fire and a new invocation of this function
20002 	 * to start before the return value of timeout has been stored
20003 	 * in ip_ire_expire_id by the current invocation.
20004 	 */
20005 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20006 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20007 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20008 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20009 }
20010 
20011 /*
20012  * Called by the memory allocator subsystem directly, when the system
20013  * is running low on memory.
20014  */
20015 /* ARGSUSED */
20016 void
20017 ip_trash_ire_reclaim(void *args)
20018 {
20019 	netstack_handle_t nh;
20020 	netstack_t *ns;
20021 
20022 	netstack_next_init(&nh);
20023 	while ((ns = netstack_next(&nh)) != NULL) {
20024 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20025 		netstack_rele(ns);
20026 	}
20027 	netstack_next_fini(&nh);
20028 }
20029 
20030 static void
20031 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20032 {
20033 	ire_cache_count_t icc;
20034 	ire_cache_reclaim_t icr;
20035 	ncc_cache_count_t ncc;
20036 	nce_cache_reclaim_t ncr;
20037 	uint_t delete_cnt;
20038 	/*
20039 	 * Memory reclaim call back.
20040 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20041 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20042 	 * entries, determine what fraction to free for
20043 	 * each category of IRE_CACHE entries giving absolute priority
20044 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20045 	 * entry will be freed unless all offlink entries are freed).
20046 	 */
20047 	icc.icc_total = 0;
20048 	icc.icc_unused = 0;
20049 	icc.icc_offlink = 0;
20050 	icc.icc_pmtu = 0;
20051 	icc.icc_onlink = 0;
20052 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20053 
20054 	/*
20055 	 * Free NCEs for IPv6 like the onlink ires.
20056 	 */
20057 	ncc.ncc_total = 0;
20058 	ncc.ncc_host = 0;
20059 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20060 
20061 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20062 	    icc.icc_pmtu + icc.icc_onlink);
20063 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20064 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20065 	if (delete_cnt == 0)
20066 		return;
20067 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20068 	/* Always delete all unused offlink entries */
20069 	icr.icr_ipst = ipst;
20070 	icr.icr_unused = 1;
20071 	if (delete_cnt <= icc.icc_unused) {
20072 		/*
20073 		 * Only need to free unused entries.  In other words,
20074 		 * there are enough unused entries to free to meet our
20075 		 * target number of freed ire cache entries.
20076 		 */
20077 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20078 		ncr.ncr_host = 0;
20079 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20080 		/*
20081 		 * Only need to free unused entries, plus a fraction of offlink
20082 		 * entries.  It follows from the first if statement that
20083 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20084 		 */
20085 		delete_cnt -= icc.icc_unused;
20086 		/* Round up # deleted by truncating fraction */
20087 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20088 		icr.icr_pmtu = icr.icr_onlink = 0;
20089 		ncr.ncr_host = 0;
20090 	} else if (delete_cnt <=
20091 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20092 		/*
20093 		 * Free all unused and offlink entries, plus a fraction of
20094 		 * pmtu entries.  It follows from the previous if statement
20095 		 * that icc_pmtu is non-zero, and that
20096 		 * delete_cnt != icc_unused + icc_offlink.
20097 		 */
20098 		icr.icr_offlink = 1;
20099 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20100 		/* Round up # deleted by truncating fraction */
20101 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20102 		icr.icr_onlink = 0;
20103 		ncr.ncr_host = 0;
20104 	} else {
20105 		/*
20106 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20107 		 * of onlink entries.  If we're here, then we know that
20108 		 * icc_onlink is non-zero, and that
20109 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20110 		 */
20111 		icr.icr_offlink = icr.icr_pmtu = 1;
20112 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20113 		    icc.icc_pmtu;
20114 		/* Round up # deleted by truncating fraction */
20115 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20116 		/* Using the same delete fraction as for onlink IREs */
20117 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20118 	}
20119 #ifdef DEBUG
20120 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20121 	    "fractions %d/%d/%d/%d\n",
20122 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20123 	    icc.icc_unused, icc.icc_offlink,
20124 	    icc.icc_pmtu, icc.icc_onlink,
20125 	    icr.icr_unused, icr.icr_offlink,
20126 	    icr.icr_pmtu, icr.icr_onlink));
20127 #endif
20128 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20129 	if (ncr.ncr_host != 0)
20130 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20131 		    (uchar_t *)&ncr, ipst);
20132 #ifdef DEBUG
20133 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20134 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20135 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20136 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20137 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20138 	    icc.icc_pmtu, icc.icc_onlink));
20139 #endif
20140 }
20141 
20142 /*
20143  * ip_unbind is called when a copy of an unbind request is received from the
20144  * upper level protocol.  We remove this conn from any fanout hash list it is
20145  * on, and zero out the bind information.  No reply is expected up above.
20146  */
20147 mblk_t *
20148 ip_unbind(queue_t *q, mblk_t *mp)
20149 {
20150 	conn_t  *connp = Q_TO_CONN(q);
20151 
20152 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20153 
20154 	if (is_system_labeled() && connp->conn_anon_port) {
20155 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20156 		    connp->conn_mlp_type, connp->conn_ulp,
20157 		    ntohs(connp->conn_lport), B_FALSE);
20158 		connp->conn_anon_port = 0;
20159 	}
20160 	connp->conn_mlp_type = mlptSingle;
20161 
20162 	ipcl_hash_remove(connp);
20163 
20164 	ASSERT(mp->b_cont == NULL);
20165 	/*
20166 	 * Convert mp into a T_OK_ACK
20167 	 */
20168 	mp = mi_tpi_ok_ack_alloc(mp);
20169 
20170 	/*
20171 	 * should not happen in practice... T_OK_ACK is smaller than the
20172 	 * original message.
20173 	 */
20174 	if (mp == NULL)
20175 		return (NULL);
20176 
20177 	return (mp);
20178 }
20179 
20180 /*
20181  * Write side put procedure.  Outbound data, IOCTLs, responses from
20182  * resolvers, etc, come down through here.
20183  *
20184  * arg2 is always a queue_t *.
20185  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20186  * the zoneid.
20187  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20188  */
20189 void
20190 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20191 {
20192 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20193 }
20194 
20195 void
20196 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20197     ip_opt_info_t *infop)
20198 {
20199 	conn_t		*connp = NULL;
20200 	queue_t		*q = (queue_t *)arg2;
20201 	ipha_t		*ipha;
20202 #define	rptr	((uchar_t *)ipha)
20203 	ire_t		*ire = NULL;
20204 	ire_t		*sctp_ire = NULL;
20205 	uint32_t	v_hlen_tos_len;
20206 	ipaddr_t	dst;
20207 	mblk_t		*first_mp = NULL;
20208 	boolean_t	mctl_present;
20209 	ipsec_out_t	*io;
20210 	int		match_flags;
20211 	ill_t		*attach_ill = NULL;
20212 					/* Bind to IPIF_NOFAILOVER ill etc. */
20213 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20214 	ipif_t		*dst_ipif;
20215 	boolean_t	multirt_need_resolve = B_FALSE;
20216 	mblk_t		*copy_mp = NULL;
20217 	int		err;
20218 	zoneid_t	zoneid;
20219 	boolean_t	need_decref = B_FALSE;
20220 	boolean_t	ignore_dontroute = B_FALSE;
20221 	boolean_t	ignore_nexthop = B_FALSE;
20222 	boolean_t	ip_nexthop = B_FALSE;
20223 	ipaddr_t	nexthop_addr;
20224 	ip_stack_t	*ipst;
20225 
20226 #ifdef	_BIG_ENDIAN
20227 #define	V_HLEN	(v_hlen_tos_len >> 24)
20228 #else
20229 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20230 #endif
20231 
20232 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20233 	    "ip_wput_start: q %p", q);
20234 
20235 	/*
20236 	 * ip_wput fast path
20237 	 */
20238 
20239 	/* is packet from ARP ? */
20240 	if (q->q_next != NULL) {
20241 		zoneid = (zoneid_t)(uintptr_t)arg;
20242 		goto qnext;
20243 	}
20244 
20245 	connp = (conn_t *)arg;
20246 	ASSERT(connp != NULL);
20247 	zoneid = connp->conn_zoneid;
20248 	ipst = connp->conn_netstack->netstack_ip;
20249 
20250 	/* is queue flow controlled? */
20251 	if ((q->q_first != NULL || connp->conn_draining) &&
20252 	    (caller == IP_WPUT)) {
20253 		ASSERT(!need_decref);
20254 		(void) putq(q, mp);
20255 		return;
20256 	}
20257 
20258 	/* Multidata transmit? */
20259 	if (DB_TYPE(mp) == M_MULTIDATA) {
20260 		/*
20261 		 * We should never get here, since all Multidata messages
20262 		 * originating from tcp should have been directed over to
20263 		 * tcp_multisend() in the first place.
20264 		 */
20265 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20266 		freemsg(mp);
20267 		return;
20268 	} else if (DB_TYPE(mp) != M_DATA)
20269 		goto notdata;
20270 
20271 	if (mp->b_flag & MSGHASREF) {
20272 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20273 		mp->b_flag &= ~MSGHASREF;
20274 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20275 		need_decref = B_TRUE;
20276 	}
20277 	ipha = (ipha_t *)mp->b_rptr;
20278 
20279 	/* is IP header non-aligned or mblk smaller than basic IP header */
20280 #ifndef SAFETY_BEFORE_SPEED
20281 	if (!OK_32PTR(rptr) ||
20282 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20283 		goto hdrtoosmall;
20284 #endif
20285 
20286 	ASSERT(OK_32PTR(ipha));
20287 
20288 	/*
20289 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20290 	 * wrong version, we'll catch it again in ip_output_v6.
20291 	 *
20292 	 * Note that this is *only* locally-generated output here, and never
20293 	 * forwarded data, and that we need to deal only with transports that
20294 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20295 	 * label.)
20296 	 */
20297 	if (is_system_labeled() &&
20298 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20299 	    !connp->conn_ulp_labeled) {
20300 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20301 		    connp->conn_mac_exempt, ipst);
20302 		ipha = (ipha_t *)mp->b_rptr;
20303 		if (err != 0) {
20304 			first_mp = mp;
20305 			if (err == EINVAL)
20306 				goto icmp_parameter_problem;
20307 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20308 			goto discard_pkt;
20309 		}
20310 	}
20311 
20312 	ASSERT(infop != NULL);
20313 
20314 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20315 		/*
20316 		 * IP_PKTINFO ancillary option is present.
20317 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20318 		 * allows using address of any zone as the source address.
20319 		 */
20320 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20321 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20322 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20323 		if (ire == NULL)
20324 			goto drop_pkt;
20325 		ire_refrele(ire);
20326 		ire = NULL;
20327 	}
20328 
20329 	/*
20330 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20331 	 * passed in IP_PKTINFO.
20332 	 */
20333 	if (infop->ip_opt_ill_index != 0 &&
20334 	    connp->conn_outgoing_ill == NULL &&
20335 	    connp->conn_nofailover_ill == NULL) {
20336 
20337 		xmit_ill = ill_lookup_on_ifindex(
20338 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20339 		    ipst);
20340 
20341 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20342 			goto drop_pkt;
20343 		/*
20344 		 * check that there is an ipif belonging
20345 		 * to our zone. IPCL_ZONEID is not used because
20346 		 * IP_ALLZONES option is valid only when the ill is
20347 		 * accessible from all zones i.e has a valid ipif in
20348 		 * all zones.
20349 		 */
20350 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20351 			goto drop_pkt;
20352 		}
20353 	}
20354 
20355 	/*
20356 	 * If there is a policy, try to attach an ipsec_out in
20357 	 * the front. At the end, first_mp either points to a
20358 	 * M_DATA message or IPSEC_OUT message linked to a
20359 	 * M_DATA message. We have to do it now as we might
20360 	 * lose the "conn" if we go through ip_newroute.
20361 	 */
20362 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20363 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20364 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20365 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20366 			if (need_decref)
20367 				CONN_DEC_REF(connp);
20368 			return;
20369 		} else {
20370 			ASSERT(mp->b_datap->db_type == M_CTL);
20371 			first_mp = mp;
20372 			mp = mp->b_cont;
20373 			mctl_present = B_TRUE;
20374 		}
20375 	} else {
20376 		first_mp = mp;
20377 		mctl_present = B_FALSE;
20378 	}
20379 
20380 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20381 
20382 	/* is wrong version or IP options present */
20383 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20384 		goto version_hdrlen_check;
20385 	dst = ipha->ipha_dst;
20386 
20387 	if (connp->conn_nofailover_ill != NULL) {
20388 		attach_ill = conn_get_held_ill(connp,
20389 		    &connp->conn_nofailover_ill, &err);
20390 		if (err == ILL_LOOKUP_FAILED) {
20391 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20392 			if (need_decref)
20393 				CONN_DEC_REF(connp);
20394 			freemsg(first_mp);
20395 			return;
20396 		}
20397 	}
20398 
20399 	/* If IP_BOUND_IF has been set, use that ill. */
20400 	if (connp->conn_outgoing_ill != NULL) {
20401 		xmit_ill = conn_get_held_ill(connp,
20402 		    &connp->conn_outgoing_ill, &err);
20403 		if (err == ILL_LOOKUP_FAILED)
20404 			goto drop_pkt;
20405 
20406 		goto send_from_ill;
20407 	}
20408 
20409 	/* is packet multicast? */
20410 	if (CLASSD(dst))
20411 		goto multicast;
20412 
20413 	/*
20414 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20415 	 * takes precedence over conn_dontroute and conn_nexthop_set
20416 	 */
20417 	if (xmit_ill != NULL)
20418 		goto send_from_ill;
20419 
20420 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20421 		/*
20422 		 * If the destination is a broadcast, local, or loopback
20423 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20424 		 * standard path.
20425 		 */
20426 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20427 		if ((ire == NULL) || (ire->ire_type &
20428 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20429 			if (ire != NULL) {
20430 				ire_refrele(ire);
20431 				/* No more access to ire */
20432 				ire = NULL;
20433 			}
20434 			/*
20435 			 * bypass routing checks and go directly to interface.
20436 			 */
20437 			if (connp->conn_dontroute)
20438 				goto dontroute;
20439 
20440 			ASSERT(connp->conn_nexthop_set);
20441 			ip_nexthop = B_TRUE;
20442 			nexthop_addr = connp->conn_nexthop_v4;
20443 			goto send_from_ill;
20444 		}
20445 
20446 		/* Must be a broadcast, a loopback or a local ire */
20447 		ire_refrele(ire);
20448 		/* No more access to ire */
20449 		ire = NULL;
20450 	}
20451 
20452 	if (attach_ill != NULL)
20453 		goto send_from_ill;
20454 
20455 	/*
20456 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20457 	 * this for the tcp global queue and listen end point
20458 	 * as it does not really have a real destination to
20459 	 * talk to.  This is also true for SCTP.
20460 	 */
20461 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20462 	    !connp->conn_fully_bound) {
20463 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20464 		if (ire == NULL)
20465 			goto noirefound;
20466 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20467 		    "ip_wput_end: q %p (%S)", q, "end");
20468 
20469 		/*
20470 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20471 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20472 		 */
20473 		if (ire->ire_flags & RTF_MULTIRT) {
20474 
20475 			/*
20476 			 * Force the TTL of multirouted packets if required.
20477 			 * The TTL of such packets is bounded by the
20478 			 * ip_multirt_ttl ndd variable.
20479 			 */
20480 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20481 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20482 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20483 				    "(was %d), dst 0x%08x\n",
20484 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20485 				    ntohl(ire->ire_addr)));
20486 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20487 			}
20488 			/*
20489 			 * We look at this point if there are pending
20490 			 * unresolved routes. ire_multirt_resolvable()
20491 			 * checks in O(n) that all IRE_OFFSUBNET ire
20492 			 * entries for the packet's destination and
20493 			 * flagged RTF_MULTIRT are currently resolved.
20494 			 * If some remain unresolved, we make a copy
20495 			 * of the current message. It will be used
20496 			 * to initiate additional route resolutions.
20497 			 */
20498 			multirt_need_resolve =
20499 			    ire_multirt_need_resolve(ire->ire_addr,
20500 			    MBLK_GETLABEL(first_mp), ipst);
20501 			ip2dbg(("ip_wput[TCP]: ire %p, "
20502 			    "multirt_need_resolve %d, first_mp %p\n",
20503 			    (void *)ire, multirt_need_resolve,
20504 			    (void *)first_mp));
20505 			if (multirt_need_resolve) {
20506 				copy_mp = copymsg(first_mp);
20507 				if (copy_mp != NULL) {
20508 					MULTIRT_DEBUG_TAG(copy_mp);
20509 				}
20510 			}
20511 		}
20512 
20513 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20514 
20515 		/*
20516 		 * Try to resolve another multiroute if
20517 		 * ire_multirt_need_resolve() deemed it necessary.
20518 		 */
20519 		if (copy_mp != NULL)
20520 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20521 		if (need_decref)
20522 			CONN_DEC_REF(connp);
20523 		return;
20524 	}
20525 
20526 	/*
20527 	 * Access to conn_ire_cache. (protected by conn_lock)
20528 	 *
20529 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20530 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20531 	 * send a packet or two with the IRE_CACHE that is going away.
20532 	 * Access to the ire requires an ire refhold on the ire prior to
20533 	 * its use since an interface unplumb thread may delete the cached
20534 	 * ire and release the refhold at any time.
20535 	 *
20536 	 * Caching an ire in the conn_ire_cache
20537 	 *
20538 	 * o Caching an ire pointer in the conn requires a strict check for
20539 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20540 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20541 	 * in the conn is done after making sure under the bucket lock that the
20542 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20543 	 * caching an ire after the unplumb thread has cleaned up the conn.
20544 	 * If the conn does not send a packet subsequently the unplumb thread
20545 	 * will be hanging waiting for the ire count to drop to zero.
20546 	 *
20547 	 * o We also need to atomically test for a null conn_ire_cache and
20548 	 * set the conn_ire_cache under the the protection of the conn_lock
20549 	 * to avoid races among concurrent threads trying to simultaneously
20550 	 * cache an ire in the conn_ire_cache.
20551 	 */
20552 	mutex_enter(&connp->conn_lock);
20553 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20554 
20555 	if (ire != NULL && ire->ire_addr == dst &&
20556 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20557 
20558 		IRE_REFHOLD(ire);
20559 		mutex_exit(&connp->conn_lock);
20560 
20561 	} else {
20562 		boolean_t cached = B_FALSE;
20563 		connp->conn_ire_cache = NULL;
20564 		mutex_exit(&connp->conn_lock);
20565 		/* Release the old ire */
20566 		if (ire != NULL && sctp_ire == NULL)
20567 			IRE_REFRELE_NOTR(ire);
20568 
20569 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20570 		if (ire == NULL)
20571 			goto noirefound;
20572 		IRE_REFHOLD_NOTR(ire);
20573 
20574 		mutex_enter(&connp->conn_lock);
20575 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20576 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20577 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20578 				if (connp->conn_ulp == IPPROTO_TCP)
20579 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20580 				connp->conn_ire_cache = ire;
20581 				cached = B_TRUE;
20582 			}
20583 			rw_exit(&ire->ire_bucket->irb_lock);
20584 		}
20585 		mutex_exit(&connp->conn_lock);
20586 
20587 		/*
20588 		 * We can continue to use the ire but since it was
20589 		 * not cached, we should drop the extra reference.
20590 		 */
20591 		if (!cached)
20592 			IRE_REFRELE_NOTR(ire);
20593 	}
20594 
20595 
20596 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20597 	    "ip_wput_end: q %p (%S)", q, "end");
20598 
20599 	/*
20600 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20601 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20602 	 */
20603 	if (ire->ire_flags & RTF_MULTIRT) {
20604 
20605 		/*
20606 		 * Force the TTL of multirouted packets if required.
20607 		 * The TTL of such packets is bounded by the
20608 		 * ip_multirt_ttl ndd variable.
20609 		 */
20610 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20611 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20612 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20613 			    "(was %d), dst 0x%08x\n",
20614 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20615 			    ntohl(ire->ire_addr)));
20616 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20617 		}
20618 
20619 		/*
20620 		 * At this point, we check to see if there are any pending
20621 		 * unresolved routes. ire_multirt_resolvable()
20622 		 * checks in O(n) that all IRE_OFFSUBNET ire
20623 		 * entries for the packet's destination and
20624 		 * flagged RTF_MULTIRT are currently resolved.
20625 		 * If some remain unresolved, we make a copy
20626 		 * of the current message. It will be used
20627 		 * to initiate additional route resolutions.
20628 		 */
20629 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20630 		    MBLK_GETLABEL(first_mp), ipst);
20631 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20632 		    "multirt_need_resolve %d, first_mp %p\n",
20633 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20634 		if (multirt_need_resolve) {
20635 			copy_mp = copymsg(first_mp);
20636 			if (copy_mp != NULL) {
20637 				MULTIRT_DEBUG_TAG(copy_mp);
20638 			}
20639 		}
20640 	}
20641 
20642 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20643 
20644 	/*
20645 	 * Try to resolve another multiroute if
20646 	 * ire_multirt_resolvable() deemed it necessary
20647 	 */
20648 	if (copy_mp != NULL)
20649 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20650 	if (need_decref)
20651 		CONN_DEC_REF(connp);
20652 	return;
20653 
20654 qnext:
20655 	/*
20656 	 * Upper Level Protocols pass down complete IP datagrams
20657 	 * as M_DATA messages.	Everything else is a sideshow.
20658 	 *
20659 	 * 1) We could be re-entering ip_wput because of ip_neworute
20660 	 *    in which case we could have a IPSEC_OUT message. We
20661 	 *    need to pass through ip_wput like other datagrams and
20662 	 *    hence cannot branch to ip_wput_nondata.
20663 	 *
20664 	 * 2) ARP, AH, ESP, and other clients who are on the module
20665 	 *    instance of IP stream, give us something to deal with.
20666 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20667 	 *
20668 	 * 3) ICMP replies also could come here.
20669 	 */
20670 	ipst = ILLQ_TO_IPST(q);
20671 
20672 	if (DB_TYPE(mp) != M_DATA) {
20673 notdata:
20674 		if (DB_TYPE(mp) == M_CTL) {
20675 			/*
20676 			 * M_CTL messages are used by ARP, AH and ESP to
20677 			 * communicate with IP. We deal with IPSEC_IN and
20678 			 * IPSEC_OUT here. ip_wput_nondata handles other
20679 			 * cases.
20680 			 */
20681 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20682 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20683 				first_mp = mp->b_cont;
20684 				first_mp->b_flag &= ~MSGHASREF;
20685 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20686 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20687 				CONN_DEC_REF(connp);
20688 				connp = NULL;
20689 			}
20690 			if (ii->ipsec_info_type == IPSEC_IN) {
20691 				/*
20692 				 * Either this message goes back to
20693 				 * IPsec for further processing or to
20694 				 * ULP after policy checks.
20695 				 */
20696 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20697 				return;
20698 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20699 				io = (ipsec_out_t *)ii;
20700 				if (io->ipsec_out_proc_begin) {
20701 					/*
20702 					 * IPsec processing has already started.
20703 					 * Complete it.
20704 					 * IPQoS notes: We don't care what is
20705 					 * in ipsec_out_ill_index since this
20706 					 * won't be processed for IPQoS policies
20707 					 * in ipsec_out_process.
20708 					 */
20709 					ipsec_out_process(q, mp, NULL,
20710 					    io->ipsec_out_ill_index);
20711 					return;
20712 				} else {
20713 					connp = (q->q_next != NULL) ?
20714 					    NULL : Q_TO_CONN(q);
20715 					first_mp = mp;
20716 					mp = mp->b_cont;
20717 					mctl_present = B_TRUE;
20718 				}
20719 				zoneid = io->ipsec_out_zoneid;
20720 				ASSERT(zoneid != ALL_ZONES);
20721 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20722 				/*
20723 				 * It's an IPsec control message requesting
20724 				 * an SADB update to be sent to the IPsec
20725 				 * hardware acceleration capable ills.
20726 				 */
20727 				ipsec_ctl_t *ipsec_ctl =
20728 				    (ipsec_ctl_t *)mp->b_rptr;
20729 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20730 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20731 				mblk_t *cmp = mp->b_cont;
20732 
20733 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20734 				ASSERT(cmp != NULL);
20735 
20736 				freeb(mp);
20737 				ill_ipsec_capab_send_all(satype, cmp, sa,
20738 				    ipst->ips_netstack);
20739 				return;
20740 			} else {
20741 				/*
20742 				 * This must be ARP or special TSOL signaling.
20743 				 */
20744 				ip_wput_nondata(NULL, q, mp, NULL);
20745 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20746 				    "ip_wput_end: q %p (%S)", q, "nondata");
20747 				return;
20748 			}
20749 		} else {
20750 			/*
20751 			 * This must be non-(ARP/AH/ESP) messages.
20752 			 */
20753 			ASSERT(!need_decref);
20754 			ip_wput_nondata(NULL, q, mp, NULL);
20755 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20756 			    "ip_wput_end: q %p (%S)", q, "nondata");
20757 			return;
20758 		}
20759 	} else {
20760 		first_mp = mp;
20761 		mctl_present = B_FALSE;
20762 	}
20763 
20764 	ASSERT(first_mp != NULL);
20765 	/*
20766 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20767 	 * to make sure that this packet goes out on the same interface it
20768 	 * came in. We handle that here.
20769 	 */
20770 	if (mctl_present) {
20771 		uint_t ifindex;
20772 
20773 		io = (ipsec_out_t *)first_mp->b_rptr;
20774 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20775 			/*
20776 			 * We may have lost the conn context if we are
20777 			 * coming here from ip_newroute(). Copy the
20778 			 * nexthop information.
20779 			 */
20780 			if (io->ipsec_out_ip_nexthop) {
20781 				ip_nexthop = B_TRUE;
20782 				nexthop_addr = io->ipsec_out_nexthop_addr;
20783 
20784 				ipha = (ipha_t *)mp->b_rptr;
20785 				dst = ipha->ipha_dst;
20786 				goto send_from_ill;
20787 			} else {
20788 				ASSERT(io->ipsec_out_ill_index != 0);
20789 				ifindex = io->ipsec_out_ill_index;
20790 				attach_ill = ill_lookup_on_ifindex(ifindex,
20791 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20792 				if (attach_ill == NULL) {
20793 					ASSERT(xmit_ill == NULL);
20794 					ip1dbg(("ip_output: bad ifindex for "
20795 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20796 					    ifindex));
20797 					freemsg(first_mp);
20798 					BUMP_MIB(&ipst->ips_ip_mib,
20799 					    ipIfStatsOutDiscards);
20800 					ASSERT(!need_decref);
20801 					return;
20802 				}
20803 			}
20804 		}
20805 	}
20806 
20807 	ASSERT(xmit_ill == NULL);
20808 
20809 	/* We have a complete IP datagram heading outbound. */
20810 	ipha = (ipha_t *)mp->b_rptr;
20811 
20812 #ifndef SPEED_BEFORE_SAFETY
20813 	/*
20814 	 * Make sure we have a full-word aligned message and that at least
20815 	 * a simple IP header is accessible in the first message.  If not,
20816 	 * try a pullup.  For labeled systems we need to always take this
20817 	 * path as M_CTLs are "notdata" but have trailing data to process.
20818 	 */
20819 	if (!OK_32PTR(rptr) ||
20820 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20821 hdrtoosmall:
20822 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20823 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20824 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20825 			if (first_mp == NULL)
20826 				first_mp = mp;
20827 			goto discard_pkt;
20828 		}
20829 
20830 		/* This function assumes that mp points to an IPv4 packet. */
20831 		if (is_system_labeled() && q->q_next == NULL &&
20832 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20833 		    !connp->conn_ulp_labeled) {
20834 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20835 			    connp->conn_mac_exempt, ipst);
20836 			ipha = (ipha_t *)mp->b_rptr;
20837 			if (first_mp != NULL)
20838 				first_mp->b_cont = mp;
20839 			if (err != 0) {
20840 				if (first_mp == NULL)
20841 					first_mp = mp;
20842 				if (err == EINVAL)
20843 					goto icmp_parameter_problem;
20844 				ip2dbg(("ip_wput: label check failed (%d)\n",
20845 				    err));
20846 				goto discard_pkt;
20847 			}
20848 		}
20849 
20850 		ipha = (ipha_t *)mp->b_rptr;
20851 		if (first_mp == NULL) {
20852 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20853 			/*
20854 			 * If we got here because of "goto hdrtoosmall"
20855 			 * We need to attach a IPSEC_OUT.
20856 			 */
20857 			if (connp->conn_out_enforce_policy) {
20858 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20859 				    NULL, ipha->ipha_protocol,
20860 				    ipst->ips_netstack)) == NULL)) {
20861 					BUMP_MIB(&ipst->ips_ip_mib,
20862 					    ipIfStatsOutDiscards);
20863 					if (need_decref)
20864 						CONN_DEC_REF(connp);
20865 					return;
20866 				} else {
20867 					ASSERT(mp->b_datap->db_type == M_CTL);
20868 					first_mp = mp;
20869 					mp = mp->b_cont;
20870 					mctl_present = B_TRUE;
20871 				}
20872 			} else {
20873 				first_mp = mp;
20874 				mctl_present = B_FALSE;
20875 			}
20876 		}
20877 	}
20878 #endif
20879 
20880 	/* Most of the code below is written for speed, not readability */
20881 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20882 
20883 	/*
20884 	 * If ip_newroute() fails, we're going to need a full
20885 	 * header for the icmp wraparound.
20886 	 */
20887 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20888 		uint_t	v_hlen;
20889 version_hdrlen_check:
20890 		ASSERT(first_mp != NULL);
20891 		v_hlen = V_HLEN;
20892 		/*
20893 		 * siphon off IPv6 packets coming down from transport
20894 		 * layer modules here.
20895 		 * Note: high-order bit carries NUD reachability confirmation
20896 		 */
20897 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20898 			/*
20899 			 * FIXME: assume that callers of ip_output* call
20900 			 * the right version?
20901 			 */
20902 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20903 			ASSERT(xmit_ill == NULL);
20904 			if (attach_ill != NULL)
20905 				ill_refrele(attach_ill);
20906 			if (need_decref)
20907 				mp->b_flag |= MSGHASREF;
20908 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20909 			return;
20910 		}
20911 
20912 		if ((v_hlen >> 4) != IP_VERSION) {
20913 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20914 			    "ip_wput_end: q %p (%S)", q, "badvers");
20915 			goto discard_pkt;
20916 		}
20917 		/*
20918 		 * Is the header length at least 20 bytes?
20919 		 *
20920 		 * Are there enough bytes accessible in the header?  If
20921 		 * not, try a pullup.
20922 		 */
20923 		v_hlen &= 0xF;
20924 		v_hlen <<= 2;
20925 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20926 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20927 			    "ip_wput_end: q %p (%S)", q, "badlen");
20928 			goto discard_pkt;
20929 		}
20930 		if (v_hlen > (mp->b_wptr - rptr)) {
20931 			if (!pullupmsg(mp, v_hlen)) {
20932 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20933 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20934 				goto discard_pkt;
20935 			}
20936 			ipha = (ipha_t *)mp->b_rptr;
20937 		}
20938 		/*
20939 		 * Move first entry from any source route into ipha_dst and
20940 		 * verify the options
20941 		 */
20942 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20943 		    zoneid, ipst)) {
20944 			ASSERT(xmit_ill == NULL);
20945 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20946 			if (attach_ill != NULL)
20947 				ill_refrele(attach_ill);
20948 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20949 			    "ip_wput_end: q %p (%S)", q, "badopts");
20950 			if (need_decref)
20951 				CONN_DEC_REF(connp);
20952 			return;
20953 		}
20954 	}
20955 	dst = ipha->ipha_dst;
20956 
20957 	/*
20958 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20959 	 * we have to run the packet through ip_newroute which will take
20960 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20961 	 * a resolver, or assigning a default gateway, etc.
20962 	 */
20963 	if (CLASSD(dst)) {
20964 		ipif_t	*ipif;
20965 		uint32_t setsrc = 0;
20966 
20967 multicast:
20968 		ASSERT(first_mp != NULL);
20969 		ip2dbg(("ip_wput: CLASSD\n"));
20970 		if (connp == NULL) {
20971 			/*
20972 			 * Use the first good ipif on the ill.
20973 			 * XXX Should this ever happen? (Appears
20974 			 * to show up with just ppp and no ethernet due
20975 			 * to in.rdisc.)
20976 			 * However, ire_send should be able to
20977 			 * call ip_wput_ire directly.
20978 			 *
20979 			 * XXX Also, this can happen for ICMP and other packets
20980 			 * with multicast source addresses.  Perhaps we should
20981 			 * fix things so that we drop the packet in question,
20982 			 * but for now, just run with it.
20983 			 */
20984 			ill_t *ill = (ill_t *)q->q_ptr;
20985 
20986 			/*
20987 			 * Don't honor attach_if for this case. If ill
20988 			 * is part of the group, ipif could belong to
20989 			 * any ill and we cannot maintain attach_ill
20990 			 * and ipif_ill same anymore and the assert
20991 			 * below would fail.
20992 			 */
20993 			if (mctl_present && io->ipsec_out_attach_if) {
20994 				io->ipsec_out_ill_index = 0;
20995 				io->ipsec_out_attach_if = B_FALSE;
20996 				ASSERT(attach_ill != NULL);
20997 				ill_refrele(attach_ill);
20998 				attach_ill = NULL;
20999 			}
21000 
21001 			ASSERT(attach_ill == NULL);
21002 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21003 			if (ipif == NULL) {
21004 				if (need_decref)
21005 					CONN_DEC_REF(connp);
21006 				freemsg(first_mp);
21007 				return;
21008 			}
21009 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21010 			    ntohl(dst), ill->ill_name));
21011 		} else {
21012 			/*
21013 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
21014 			 * and IP_MULTICAST_IF.  The block comment above this
21015 			 * function explains the locking mechanism used here.
21016 			 */
21017 			if (xmit_ill == NULL) {
21018 				xmit_ill = conn_get_held_ill(connp,
21019 				    &connp->conn_outgoing_ill, &err);
21020 				if (err == ILL_LOOKUP_FAILED) {
21021 					ip1dbg(("ip_wput: No ill for "
21022 					    "IP_BOUND_IF\n"));
21023 					BUMP_MIB(&ipst->ips_ip_mib,
21024 					    ipIfStatsOutNoRoutes);
21025 					goto drop_pkt;
21026 				}
21027 			}
21028 
21029 			if (xmit_ill == NULL) {
21030 				ipif = conn_get_held_ipif(connp,
21031 				    &connp->conn_multicast_ipif, &err);
21032 				if (err == IPIF_LOOKUP_FAILED) {
21033 					ip1dbg(("ip_wput: No ipif for "
21034 					    "multicast\n"));
21035 					BUMP_MIB(&ipst->ips_ip_mib,
21036 					    ipIfStatsOutNoRoutes);
21037 					goto drop_pkt;
21038 				}
21039 			}
21040 			if (xmit_ill != NULL) {
21041 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21042 				if (ipif == NULL) {
21043 					ip1dbg(("ip_wput: No ipif for "
21044 					    "xmit_ill\n"));
21045 					BUMP_MIB(&ipst->ips_ip_mib,
21046 					    ipIfStatsOutNoRoutes);
21047 					goto drop_pkt;
21048 				}
21049 			} else if (ipif == NULL || ipif->ipif_isv6) {
21050 				/*
21051 				 * We must do this ipif determination here
21052 				 * else we could pass through ip_newroute
21053 				 * and come back here without the conn context.
21054 				 *
21055 				 * Note: we do late binding i.e. we bind to
21056 				 * the interface when the first packet is sent.
21057 				 * For performance reasons we do not rebind on
21058 				 * each packet but keep the binding until the
21059 				 * next IP_MULTICAST_IF option.
21060 				 *
21061 				 * conn_multicast_{ipif,ill} are shared between
21062 				 * IPv4 and IPv6 and AF_INET6 sockets can
21063 				 * send both IPv4 and IPv6 packets. Hence
21064 				 * we have to check that "isv6" matches above.
21065 				 */
21066 				if (ipif != NULL)
21067 					ipif_refrele(ipif);
21068 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21069 				if (ipif == NULL) {
21070 					ip1dbg(("ip_wput: No ipif for "
21071 					    "multicast\n"));
21072 					BUMP_MIB(&ipst->ips_ip_mib,
21073 					    ipIfStatsOutNoRoutes);
21074 					goto drop_pkt;
21075 				}
21076 				err = conn_set_held_ipif(connp,
21077 				    &connp->conn_multicast_ipif, ipif);
21078 				if (err == IPIF_LOOKUP_FAILED) {
21079 					ipif_refrele(ipif);
21080 					ip1dbg(("ip_wput: No ipif for "
21081 					    "multicast\n"));
21082 					BUMP_MIB(&ipst->ips_ip_mib,
21083 					    ipIfStatsOutNoRoutes);
21084 					goto drop_pkt;
21085 				}
21086 			}
21087 		}
21088 		ASSERT(!ipif->ipif_isv6);
21089 		/*
21090 		 * As we may lose the conn by the time we reach ip_wput_ire,
21091 		 * we copy conn_multicast_loop and conn_dontroute on to an
21092 		 * ipsec_out. In case if this datagram goes out secure,
21093 		 * we need the ill_index also. Copy that also into the
21094 		 * ipsec_out.
21095 		 */
21096 		if (mctl_present) {
21097 			io = (ipsec_out_t *)first_mp->b_rptr;
21098 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21099 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21100 		} else {
21101 			ASSERT(mp == first_mp);
21102 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21103 			    BPRI_HI)) == NULL) {
21104 				ipif_refrele(ipif);
21105 				first_mp = mp;
21106 				goto discard_pkt;
21107 			}
21108 			first_mp->b_datap->db_type = M_CTL;
21109 			first_mp->b_wptr += sizeof (ipsec_info_t);
21110 			/* ipsec_out_secure is B_FALSE now */
21111 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21112 			io = (ipsec_out_t *)first_mp->b_rptr;
21113 			io->ipsec_out_type = IPSEC_OUT;
21114 			io->ipsec_out_len = sizeof (ipsec_out_t);
21115 			io->ipsec_out_use_global_policy = B_TRUE;
21116 			io->ipsec_out_ns = ipst->ips_netstack;
21117 			first_mp->b_cont = mp;
21118 			mctl_present = B_TRUE;
21119 		}
21120 		if (attach_ill != NULL) {
21121 			ASSERT(attach_ill == ipif->ipif_ill);
21122 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21123 
21124 			/*
21125 			 * Check if we need an ire that will not be
21126 			 * looked up by anybody else i.e. HIDDEN.
21127 			 */
21128 			if (ill_is_probeonly(attach_ill)) {
21129 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21130 			}
21131 			io->ipsec_out_ill_index =
21132 			    attach_ill->ill_phyint->phyint_ifindex;
21133 			io->ipsec_out_attach_if = B_TRUE;
21134 		} else {
21135 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21136 			io->ipsec_out_ill_index =
21137 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21138 		}
21139 		if (connp != NULL) {
21140 			io->ipsec_out_multicast_loop =
21141 			    connp->conn_multicast_loop;
21142 			io->ipsec_out_dontroute = connp->conn_dontroute;
21143 			io->ipsec_out_zoneid = connp->conn_zoneid;
21144 		}
21145 		/*
21146 		 * If the application uses IP_MULTICAST_IF with
21147 		 * different logical addresses of the same ILL, we
21148 		 * need to make sure that the soruce address of
21149 		 * the packet matches the logical IP address used
21150 		 * in the option. We do it by initializing ipha_src
21151 		 * here. This should keep IPsec also happy as
21152 		 * when we return from IPsec processing, we don't
21153 		 * have to worry about getting the right address on
21154 		 * the packet. Thus it is sufficient to look for
21155 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21156 		 * MATCH_IRE_IPIF.
21157 		 *
21158 		 * NOTE : We need to do it for non-secure case also as
21159 		 * this might go out secure if there is a global policy
21160 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21161 		 * address, the source should be initialized already and
21162 		 * hence we won't be initializing here.
21163 		 *
21164 		 * As we do not have the ire yet, it is possible that
21165 		 * we set the source address here and then later discover
21166 		 * that the ire implies the source address to be assigned
21167 		 * through the RTF_SETSRC flag.
21168 		 * In that case, the setsrc variable will remind us
21169 		 * that overwritting the source address by the one
21170 		 * of the RTF_SETSRC-flagged ire is allowed.
21171 		 */
21172 		if (ipha->ipha_src == INADDR_ANY &&
21173 		    (connp == NULL || !connp->conn_unspec_src)) {
21174 			ipha->ipha_src = ipif->ipif_src_addr;
21175 			setsrc = RTF_SETSRC;
21176 		}
21177 		/*
21178 		 * Find an IRE which matches the destination and the outgoing
21179 		 * queue (i.e. the outgoing interface.)
21180 		 * For loopback use a unicast IP address for
21181 		 * the ire lookup.
21182 		 */
21183 		if (IS_LOOPBACK(ipif->ipif_ill))
21184 			dst = ipif->ipif_lcl_addr;
21185 
21186 		/*
21187 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21188 		 * We don't need to lookup ire in ctable as the packet
21189 		 * needs to be sent to the destination through the specified
21190 		 * ill irrespective of ires in the cache table.
21191 		 */
21192 		ire = NULL;
21193 		if (xmit_ill == NULL) {
21194 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21195 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21196 		}
21197 
21198 		/*
21199 		 * refrele attach_ill as its not needed anymore.
21200 		 */
21201 		if (attach_ill != NULL) {
21202 			ill_refrele(attach_ill);
21203 			attach_ill = NULL;
21204 		}
21205 
21206 		if (ire == NULL) {
21207 			/*
21208 			 * Multicast loopback and multicast forwarding is
21209 			 * done in ip_wput_ire.
21210 			 *
21211 			 * Mark this packet to make it be delivered to
21212 			 * ip_wput_ire after the new ire has been
21213 			 * created.
21214 			 *
21215 			 * The call to ip_newroute_ipif takes into account
21216 			 * the setsrc reminder. In any case, we take care
21217 			 * of the RTF_MULTIRT flag.
21218 			 */
21219 			mp->b_prev = mp->b_next = NULL;
21220 			if (xmit_ill == NULL ||
21221 			    xmit_ill->ill_ipif_up_count > 0) {
21222 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21223 				    setsrc | RTF_MULTIRT, zoneid, infop);
21224 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21225 				    "ip_wput_end: q %p (%S)", q, "noire");
21226 			} else {
21227 				freemsg(first_mp);
21228 			}
21229 			ipif_refrele(ipif);
21230 			if (xmit_ill != NULL)
21231 				ill_refrele(xmit_ill);
21232 			if (need_decref)
21233 				CONN_DEC_REF(connp);
21234 			return;
21235 		}
21236 
21237 		ipif_refrele(ipif);
21238 		ipif = NULL;
21239 		ASSERT(xmit_ill == NULL);
21240 
21241 		/*
21242 		 * Honor the RTF_SETSRC flag for multicast packets,
21243 		 * if allowed by the setsrc reminder.
21244 		 */
21245 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21246 			ipha->ipha_src = ire->ire_src_addr;
21247 		}
21248 
21249 		/*
21250 		 * Unconditionally force the TTL to 1 for
21251 		 * multirouted multicast packets:
21252 		 * multirouted multicast should not cross
21253 		 * multicast routers.
21254 		 */
21255 		if (ire->ire_flags & RTF_MULTIRT) {
21256 			if (ipha->ipha_ttl > 1) {
21257 				ip2dbg(("ip_wput: forcing multicast "
21258 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21259 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21260 				ipha->ipha_ttl = 1;
21261 			}
21262 		}
21263 	} else {
21264 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21265 		if ((ire != NULL) && (ire->ire_type &
21266 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21267 			ignore_dontroute = B_TRUE;
21268 			ignore_nexthop = B_TRUE;
21269 		}
21270 		if (ire != NULL) {
21271 			ire_refrele(ire);
21272 			ire = NULL;
21273 		}
21274 		/*
21275 		 * Guard against coming in from arp in which case conn is NULL.
21276 		 * Also guard against non M_DATA with dontroute set but
21277 		 * destined to local, loopback or broadcast addresses.
21278 		 */
21279 		if (connp != NULL && connp->conn_dontroute &&
21280 		    !ignore_dontroute) {
21281 dontroute:
21282 			/*
21283 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21284 			 * routing protocols from seeing false direct
21285 			 * connectivity.
21286 			 */
21287 			ipha->ipha_ttl = 1;
21288 
21289 			/* If suitable ipif not found, drop packet */
21290 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21291 			if (dst_ipif == NULL) {
21292 noroute:
21293 				ip1dbg(("ip_wput: no route for dst using"
21294 				    " SO_DONTROUTE\n"));
21295 				BUMP_MIB(&ipst->ips_ip_mib,
21296 				    ipIfStatsOutNoRoutes);
21297 				mp->b_prev = mp->b_next = NULL;
21298 				if (first_mp == NULL)
21299 					first_mp = mp;
21300 				goto drop_pkt;
21301 			} else {
21302 				/*
21303 				 * If suitable ipif has been found, set
21304 				 * xmit_ill to the corresponding
21305 				 * ipif_ill because we'll be using the
21306 				 * send_from_ill logic below.
21307 				 */
21308 				ASSERT(xmit_ill == NULL);
21309 				xmit_ill = dst_ipif->ipif_ill;
21310 				mutex_enter(&xmit_ill->ill_lock);
21311 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21312 					mutex_exit(&xmit_ill->ill_lock);
21313 					xmit_ill = NULL;
21314 					ipif_refrele(dst_ipif);
21315 					goto noroute;
21316 				}
21317 				ill_refhold_locked(xmit_ill);
21318 				mutex_exit(&xmit_ill->ill_lock);
21319 				ipif_refrele(dst_ipif);
21320 			}
21321 		}
21322 		/*
21323 		 * If we are bound to IPIF_NOFAILOVER address, look for
21324 		 * an IRE_CACHE matching the ill.
21325 		 */
21326 send_from_ill:
21327 		if (attach_ill != NULL) {
21328 			ipif_t	*attach_ipif;
21329 
21330 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21331 
21332 			/*
21333 			 * Check if we need an ire that will not be
21334 			 * looked up by anybody else i.e. HIDDEN.
21335 			 */
21336 			if (ill_is_probeonly(attach_ill)) {
21337 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21338 			}
21339 
21340 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21341 			if (attach_ipif == NULL) {
21342 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21343 				goto discard_pkt;
21344 			}
21345 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21346 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21347 			ipif_refrele(attach_ipif);
21348 		} else if (xmit_ill != NULL) {
21349 			ipif_t *ipif;
21350 
21351 			/*
21352 			 * Mark this packet as originated locally
21353 			 */
21354 			mp->b_prev = mp->b_next = NULL;
21355 
21356 			/*
21357 			 * Could be SO_DONTROUTE case also.
21358 			 * Verify that at least one ipif is up on the ill.
21359 			 */
21360 			if (xmit_ill->ill_ipif_up_count == 0) {
21361 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21362 				    xmit_ill->ill_name));
21363 				goto drop_pkt;
21364 			}
21365 
21366 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21367 			if (ipif == NULL) {
21368 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21369 				    xmit_ill->ill_name));
21370 				goto drop_pkt;
21371 			}
21372 
21373 			/*
21374 			 * Look for a ire that is part of the group,
21375 			 * if found use it else call ip_newroute_ipif.
21376 			 * IPCL_ZONEID is not used for matching because
21377 			 * IP_ALLZONES option is valid only when the
21378 			 * ill is accessible from all zones i.e has a
21379 			 * valid ipif in all zones.
21380 			 */
21381 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21382 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21383 			    MBLK_GETLABEL(mp), match_flags, ipst);
21384 			/*
21385 			 * If an ire exists use it or else create
21386 			 * an ire but don't add it to the cache.
21387 			 * Adding an ire may cause issues with
21388 			 * asymmetric routing.
21389 			 * In case of multiroute always act as if
21390 			 * ire does not exist.
21391 			 */
21392 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21393 				if (ire != NULL)
21394 					ire_refrele(ire);
21395 				ip_newroute_ipif(q, first_mp, ipif,
21396 				    dst, connp, 0, zoneid, infop);
21397 				ipif_refrele(ipif);
21398 				ip1dbg(("ip_output: xmit_ill via %s\n",
21399 				    xmit_ill->ill_name));
21400 				ill_refrele(xmit_ill);
21401 				if (need_decref)
21402 					CONN_DEC_REF(connp);
21403 				return;
21404 			}
21405 			ipif_refrele(ipif);
21406 		} else if (ip_nexthop || (connp != NULL &&
21407 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21408 			if (!ip_nexthop) {
21409 				ip_nexthop = B_TRUE;
21410 				nexthop_addr = connp->conn_nexthop_v4;
21411 			}
21412 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21413 			    MATCH_IRE_GW;
21414 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21415 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21416 		} else {
21417 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21418 			    ipst);
21419 		}
21420 		if (!ire) {
21421 			/*
21422 			 * Make sure we don't load spread if this
21423 			 * is IPIF_NOFAILOVER case.
21424 			 */
21425 			if ((attach_ill != NULL) ||
21426 			    (ip_nexthop && !ignore_nexthop)) {
21427 				if (mctl_present) {
21428 					io = (ipsec_out_t *)first_mp->b_rptr;
21429 					ASSERT(first_mp->b_datap->db_type ==
21430 					    M_CTL);
21431 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21432 				} else {
21433 					ASSERT(mp == first_mp);
21434 					first_mp = allocb(
21435 					    sizeof (ipsec_info_t), BPRI_HI);
21436 					if (first_mp == NULL) {
21437 						first_mp = mp;
21438 						goto discard_pkt;
21439 					}
21440 					first_mp->b_datap->db_type = M_CTL;
21441 					first_mp->b_wptr +=
21442 					    sizeof (ipsec_info_t);
21443 					/* ipsec_out_secure is B_FALSE now */
21444 					bzero(first_mp->b_rptr,
21445 					    sizeof (ipsec_info_t));
21446 					io = (ipsec_out_t *)first_mp->b_rptr;
21447 					io->ipsec_out_type = IPSEC_OUT;
21448 					io->ipsec_out_len =
21449 					    sizeof (ipsec_out_t);
21450 					io->ipsec_out_use_global_policy =
21451 					    B_TRUE;
21452 					io->ipsec_out_ns = ipst->ips_netstack;
21453 					first_mp->b_cont = mp;
21454 					mctl_present = B_TRUE;
21455 				}
21456 				if (attach_ill != NULL) {
21457 					io->ipsec_out_ill_index = attach_ill->
21458 					    ill_phyint->phyint_ifindex;
21459 					io->ipsec_out_attach_if = B_TRUE;
21460 				} else {
21461 					io->ipsec_out_ip_nexthop = ip_nexthop;
21462 					io->ipsec_out_nexthop_addr =
21463 					    nexthop_addr;
21464 				}
21465 			}
21466 noirefound:
21467 			/*
21468 			 * Mark this packet as having originated on
21469 			 * this machine.  This will be noted in
21470 			 * ire_add_then_send, which needs to know
21471 			 * whether to run it back through ip_wput or
21472 			 * ip_rput following successful resolution.
21473 			 */
21474 			mp->b_prev = NULL;
21475 			mp->b_next = NULL;
21476 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21477 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21478 			    "ip_wput_end: q %p (%S)", q, "newroute");
21479 			if (attach_ill != NULL)
21480 				ill_refrele(attach_ill);
21481 			if (xmit_ill != NULL)
21482 				ill_refrele(xmit_ill);
21483 			if (need_decref)
21484 				CONN_DEC_REF(connp);
21485 			return;
21486 		}
21487 	}
21488 
21489 	/* We now know where we are going with it. */
21490 
21491 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21492 	    "ip_wput_end: q %p (%S)", q, "end");
21493 
21494 	/*
21495 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21496 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21497 	 */
21498 	if (ire->ire_flags & RTF_MULTIRT) {
21499 		/*
21500 		 * Force the TTL of multirouted packets if required.
21501 		 * The TTL of such packets is bounded by the
21502 		 * ip_multirt_ttl ndd variable.
21503 		 */
21504 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21505 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21506 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21507 			    "(was %d), dst 0x%08x\n",
21508 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21509 			    ntohl(ire->ire_addr)));
21510 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21511 		}
21512 		/*
21513 		 * At this point, we check to see if there are any pending
21514 		 * unresolved routes. ire_multirt_resolvable()
21515 		 * checks in O(n) that all IRE_OFFSUBNET ire
21516 		 * entries for the packet's destination and
21517 		 * flagged RTF_MULTIRT are currently resolved.
21518 		 * If some remain unresolved, we make a copy
21519 		 * of the current message. It will be used
21520 		 * to initiate additional route resolutions.
21521 		 */
21522 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21523 		    MBLK_GETLABEL(first_mp), ipst);
21524 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21525 		    "multirt_need_resolve %d, first_mp %p\n",
21526 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21527 		if (multirt_need_resolve) {
21528 			copy_mp = copymsg(first_mp);
21529 			if (copy_mp != NULL) {
21530 				MULTIRT_DEBUG_TAG(copy_mp);
21531 			}
21532 		}
21533 	}
21534 
21535 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21536 	/*
21537 	 * Try to resolve another multiroute if
21538 	 * ire_multirt_resolvable() deemed it necessary.
21539 	 * At this point, we need to distinguish
21540 	 * multicasts from other packets. For multicasts,
21541 	 * we call ip_newroute_ipif() and request that both
21542 	 * multirouting and setsrc flags are checked.
21543 	 */
21544 	if (copy_mp != NULL) {
21545 		if (CLASSD(dst)) {
21546 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21547 			if (ipif) {
21548 				ASSERT(infop->ip_opt_ill_index == 0);
21549 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21550 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21551 				ipif_refrele(ipif);
21552 			} else {
21553 				MULTIRT_DEBUG_UNTAG(copy_mp);
21554 				freemsg(copy_mp);
21555 				copy_mp = NULL;
21556 			}
21557 		} else {
21558 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21559 		}
21560 	}
21561 	if (attach_ill != NULL)
21562 		ill_refrele(attach_ill);
21563 	if (xmit_ill != NULL)
21564 		ill_refrele(xmit_ill);
21565 	if (need_decref)
21566 		CONN_DEC_REF(connp);
21567 	return;
21568 
21569 icmp_parameter_problem:
21570 	/* could not have originated externally */
21571 	ASSERT(mp->b_prev == NULL);
21572 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21573 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21574 		/* it's the IP header length that's in trouble */
21575 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21576 		first_mp = NULL;
21577 	}
21578 
21579 discard_pkt:
21580 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21581 drop_pkt:
21582 	ip1dbg(("ip_wput: dropped packet\n"));
21583 	if (ire != NULL)
21584 		ire_refrele(ire);
21585 	if (need_decref)
21586 		CONN_DEC_REF(connp);
21587 	freemsg(first_mp);
21588 	if (attach_ill != NULL)
21589 		ill_refrele(attach_ill);
21590 	if (xmit_ill != NULL)
21591 		ill_refrele(xmit_ill);
21592 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21593 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21594 }
21595 
21596 /*
21597  * If this is a conn_t queue, then we pass in the conn. This includes the
21598  * zoneid.
21599  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21600  * in which case we use the global zoneid since those are all part of
21601  * the global zone.
21602  */
21603 void
21604 ip_wput(queue_t *q, mblk_t *mp)
21605 {
21606 	if (CONN_Q(q))
21607 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21608 	else
21609 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21610 }
21611 
21612 /*
21613  *
21614  * The following rules must be observed when accessing any ipif or ill
21615  * that has been cached in the conn. Typically conn_nofailover_ill,
21616  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21617  *
21618  * Access: The ipif or ill pointed to from the conn can be accessed under
21619  * the protection of the conn_lock or after it has been refheld under the
21620  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21621  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21622  * The reason for this is that a concurrent unplumb could actually be
21623  * cleaning up these cached pointers by walking the conns and might have
21624  * finished cleaning up the conn in question. The macros check that an
21625  * unplumb has not yet started on the ipif or ill.
21626  *
21627  * Caching: An ipif or ill pointer may be cached in the conn only after
21628  * making sure that an unplumb has not started. So the caching is done
21629  * while holding both the conn_lock and the ill_lock and after using the
21630  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21631  * flag before starting the cleanup of conns.
21632  *
21633  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21634  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21635  * or a reference to the ipif or a reference to an ire that references the
21636  * ipif. An ipif does not change its ill except for failover/failback. Since
21637  * failover/failback happens only after bringing down the ipif and making sure
21638  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21639  * the above holds.
21640  */
21641 ipif_t *
21642 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21643 {
21644 	ipif_t	*ipif;
21645 	ill_t	*ill;
21646 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21647 
21648 	*err = 0;
21649 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21650 	mutex_enter(&connp->conn_lock);
21651 	ipif = *ipifp;
21652 	if (ipif != NULL) {
21653 		ill = ipif->ipif_ill;
21654 		mutex_enter(&ill->ill_lock);
21655 		if (IPIF_CAN_LOOKUP(ipif)) {
21656 			ipif_refhold_locked(ipif);
21657 			mutex_exit(&ill->ill_lock);
21658 			mutex_exit(&connp->conn_lock);
21659 			rw_exit(&ipst->ips_ill_g_lock);
21660 			return (ipif);
21661 		} else {
21662 			*err = IPIF_LOOKUP_FAILED;
21663 		}
21664 		mutex_exit(&ill->ill_lock);
21665 	}
21666 	mutex_exit(&connp->conn_lock);
21667 	rw_exit(&ipst->ips_ill_g_lock);
21668 	return (NULL);
21669 }
21670 
21671 ill_t *
21672 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21673 {
21674 	ill_t	*ill;
21675 
21676 	*err = 0;
21677 	mutex_enter(&connp->conn_lock);
21678 	ill = *illp;
21679 	if (ill != NULL) {
21680 		mutex_enter(&ill->ill_lock);
21681 		if (ILL_CAN_LOOKUP(ill)) {
21682 			ill_refhold_locked(ill);
21683 			mutex_exit(&ill->ill_lock);
21684 			mutex_exit(&connp->conn_lock);
21685 			return (ill);
21686 		} else {
21687 			*err = ILL_LOOKUP_FAILED;
21688 		}
21689 		mutex_exit(&ill->ill_lock);
21690 	}
21691 	mutex_exit(&connp->conn_lock);
21692 	return (NULL);
21693 }
21694 
21695 static int
21696 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21697 {
21698 	ill_t	*ill;
21699 
21700 	ill = ipif->ipif_ill;
21701 	mutex_enter(&connp->conn_lock);
21702 	mutex_enter(&ill->ill_lock);
21703 	if (IPIF_CAN_LOOKUP(ipif)) {
21704 		*ipifp = ipif;
21705 		mutex_exit(&ill->ill_lock);
21706 		mutex_exit(&connp->conn_lock);
21707 		return (0);
21708 	}
21709 	mutex_exit(&ill->ill_lock);
21710 	mutex_exit(&connp->conn_lock);
21711 	return (IPIF_LOOKUP_FAILED);
21712 }
21713 
21714 /*
21715  * This is called if the outbound datagram needs fragmentation.
21716  *
21717  * NOTE : This function does not ire_refrele the ire argument passed in.
21718  */
21719 static void
21720 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21721     ip_stack_t *ipst)
21722 {
21723 	ipha_t		*ipha;
21724 	mblk_t		*mp;
21725 	uint32_t	v_hlen_tos_len;
21726 	uint32_t	max_frag;
21727 	uint32_t	frag_flag;
21728 	boolean_t	dont_use;
21729 
21730 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21731 		mp = ipsec_mp->b_cont;
21732 	} else {
21733 		mp = ipsec_mp;
21734 	}
21735 
21736 	ipha = (ipha_t *)mp->b_rptr;
21737 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21738 
21739 #ifdef	_BIG_ENDIAN
21740 #define	V_HLEN	(v_hlen_tos_len >> 24)
21741 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21742 #else
21743 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21744 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21745 #endif
21746 
21747 #ifndef SPEED_BEFORE_SAFETY
21748 	/*
21749 	 * Check that ipha_length is consistent with
21750 	 * the mblk length
21751 	 */
21752 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21753 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21754 		    LENGTH, msgdsize(mp)));
21755 		freemsg(ipsec_mp);
21756 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21757 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21758 		    "packet length mismatch");
21759 		return;
21760 	}
21761 #endif
21762 	/*
21763 	 * Don't use frag_flag if pre-built packet or source
21764 	 * routed or if multicast (since multicast packets do not solicit
21765 	 * ICMP "packet too big" messages). Get the values of
21766 	 * max_frag and frag_flag atomically by acquiring the
21767 	 * ire_lock.
21768 	 */
21769 	mutex_enter(&ire->ire_lock);
21770 	max_frag = ire->ire_max_frag;
21771 	frag_flag = ire->ire_frag_flag;
21772 	mutex_exit(&ire->ire_lock);
21773 
21774 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21775 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21776 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21777 
21778 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21779 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21780 }
21781 
21782 /*
21783  * Used for deciding the MSS size for the upper layer. Thus
21784  * we need to check the outbound policy values in the conn.
21785  */
21786 int
21787 conn_ipsec_length(conn_t *connp)
21788 {
21789 	ipsec_latch_t *ipl;
21790 
21791 	ipl = connp->conn_latch;
21792 	if (ipl == NULL)
21793 		return (0);
21794 
21795 	if (ipl->ipl_out_policy == NULL)
21796 		return (0);
21797 
21798 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21799 }
21800 
21801 /*
21802  * Returns an estimate of the IPsec headers size. This is used if
21803  * we don't want to call into IPsec to get the exact size.
21804  */
21805 int
21806 ipsec_out_extra_length(mblk_t *ipsec_mp)
21807 {
21808 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21809 	ipsec_action_t *a;
21810 
21811 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21812 	if (!io->ipsec_out_secure)
21813 		return (0);
21814 
21815 	a = io->ipsec_out_act;
21816 
21817 	if (a == NULL) {
21818 		ASSERT(io->ipsec_out_policy != NULL);
21819 		a = io->ipsec_out_policy->ipsp_act;
21820 	}
21821 	ASSERT(a != NULL);
21822 
21823 	return (a->ipa_ovhd);
21824 }
21825 
21826 /*
21827  * Returns an estimate of the IPsec headers size. This is used if
21828  * we don't want to call into IPsec to get the exact size.
21829  */
21830 int
21831 ipsec_in_extra_length(mblk_t *ipsec_mp)
21832 {
21833 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21834 	ipsec_action_t *a;
21835 
21836 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21837 
21838 	a = ii->ipsec_in_action;
21839 	return (a == NULL ? 0 : a->ipa_ovhd);
21840 }
21841 
21842 /*
21843  * If there are any source route options, return the true final
21844  * destination. Otherwise, return the destination.
21845  */
21846 ipaddr_t
21847 ip_get_dst(ipha_t *ipha)
21848 {
21849 	ipoptp_t	opts;
21850 	uchar_t		*opt;
21851 	uint8_t		optval;
21852 	uint8_t		optlen;
21853 	ipaddr_t	dst;
21854 	uint32_t off;
21855 
21856 	dst = ipha->ipha_dst;
21857 
21858 	if (IS_SIMPLE_IPH(ipha))
21859 		return (dst);
21860 
21861 	for (optval = ipoptp_first(&opts, ipha);
21862 	    optval != IPOPT_EOL;
21863 	    optval = ipoptp_next(&opts)) {
21864 		opt = opts.ipoptp_cur;
21865 		optlen = opts.ipoptp_len;
21866 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21867 		switch (optval) {
21868 		case IPOPT_SSRR:
21869 		case IPOPT_LSRR:
21870 			off = opt[IPOPT_OFFSET];
21871 			/*
21872 			 * If one of the conditions is true, it means
21873 			 * end of options and dst already has the right
21874 			 * value.
21875 			 */
21876 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21877 				off = optlen - IP_ADDR_LEN;
21878 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21879 			}
21880 			return (dst);
21881 		default:
21882 			break;
21883 		}
21884 	}
21885 
21886 	return (dst);
21887 }
21888 
21889 mblk_t *
21890 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21891     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21892 {
21893 	ipsec_out_t	*io;
21894 	mblk_t		*first_mp;
21895 	boolean_t policy_present;
21896 	ip_stack_t	*ipst;
21897 	ipsec_stack_t	*ipss;
21898 
21899 	ASSERT(ire != NULL);
21900 	ipst = ire->ire_ipst;
21901 	ipss = ipst->ips_netstack->netstack_ipsec;
21902 
21903 	first_mp = mp;
21904 	if (mp->b_datap->db_type == M_CTL) {
21905 		io = (ipsec_out_t *)first_mp->b_rptr;
21906 		/*
21907 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21908 		 *
21909 		 * 1) There is per-socket policy (including cached global
21910 		 *    policy) or a policy on the IP-in-IP tunnel.
21911 		 * 2) There is no per-socket policy, but it is
21912 		 *    a multicast packet that needs to go out
21913 		 *    on a specific interface. This is the case
21914 		 *    where (ip_wput and ip_wput_multicast) attaches
21915 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21916 		 *
21917 		 * In case (2) we check with global policy to
21918 		 * see if there is a match and set the ill_index
21919 		 * appropriately so that we can lookup the ire
21920 		 * properly in ip_wput_ipsec_out.
21921 		 */
21922 
21923 		/*
21924 		 * ipsec_out_use_global_policy is set to B_FALSE
21925 		 * in ipsec_in_to_out(). Refer to that function for
21926 		 * details.
21927 		 */
21928 		if ((io->ipsec_out_latch == NULL) &&
21929 		    (io->ipsec_out_use_global_policy)) {
21930 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21931 			    ire, connp, unspec_src, zoneid));
21932 		}
21933 		if (!io->ipsec_out_secure) {
21934 			/*
21935 			 * If this is not a secure packet, drop
21936 			 * the IPSEC_OUT mp and treat it as a clear
21937 			 * packet. This happens when we are sending
21938 			 * a ICMP reply back to a clear packet. See
21939 			 * ipsec_in_to_out() for details.
21940 			 */
21941 			mp = first_mp->b_cont;
21942 			freeb(first_mp);
21943 		}
21944 		return (mp);
21945 	}
21946 	/*
21947 	 * See whether we need to attach a global policy here. We
21948 	 * don't depend on the conn (as it could be null) for deciding
21949 	 * what policy this datagram should go through because it
21950 	 * should have happened in ip_wput if there was some
21951 	 * policy. This normally happens for connections which are not
21952 	 * fully bound preventing us from caching policies in
21953 	 * ip_bind. Packets coming from the TCP listener/global queue
21954 	 * - which are non-hard_bound - could also be affected by
21955 	 * applying policy here.
21956 	 *
21957 	 * If this packet is coming from tcp global queue or listener,
21958 	 * we will be applying policy here.  This may not be *right*
21959 	 * if these packets are coming from the detached connection as
21960 	 * it could have gone in clear before. This happens only if a
21961 	 * TCP connection started when there is no policy and somebody
21962 	 * added policy before it became detached. Thus packets of the
21963 	 * detached connection could go out secure and the other end
21964 	 * would drop it because it will be expecting in clear. The
21965 	 * converse is not true i.e if somebody starts a TCP
21966 	 * connection and deletes the policy, all the packets will
21967 	 * still go out with the policy that existed before deleting
21968 	 * because ip_unbind sends up policy information which is used
21969 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21970 	 * TCP to attach a dummy IPSEC_OUT and set
21971 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21972 	 * affect performance for normal cases, we are not doing it.
21973 	 * Thus, set policy before starting any TCP connections.
21974 	 *
21975 	 * NOTE - We might apply policy even for a hard bound connection
21976 	 * - for which we cached policy in ip_bind - if somebody added
21977 	 * global policy after we inherited the policy in ip_bind.
21978 	 * This means that the packets that were going out in clear
21979 	 * previously would start going secure and hence get dropped
21980 	 * on the other side. To fix this, TCP attaches a dummy
21981 	 * ipsec_out and make sure that we don't apply global policy.
21982 	 */
21983 	if (ipha != NULL)
21984 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21985 	else
21986 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21987 	if (!policy_present)
21988 		return (mp);
21989 
21990 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21991 	    zoneid));
21992 }
21993 
21994 ire_t *
21995 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21996 {
21997 	ipaddr_t addr;
21998 	ire_t *save_ire;
21999 	irb_t *irb;
22000 	ill_group_t *illgrp;
22001 	int	err;
22002 
22003 	save_ire = ire;
22004 	addr = ire->ire_addr;
22005 
22006 	ASSERT(ire->ire_type == IRE_BROADCAST);
22007 
22008 	illgrp = connp->conn_outgoing_ill->ill_group;
22009 	if (illgrp == NULL) {
22010 		*conn_outgoing_ill = conn_get_held_ill(connp,
22011 		    &connp->conn_outgoing_ill, &err);
22012 		if (err == ILL_LOOKUP_FAILED) {
22013 			ire_refrele(save_ire);
22014 			return (NULL);
22015 		}
22016 		return (save_ire);
22017 	}
22018 	/*
22019 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22020 	 * If it is part of the group, we need to send on the ire
22021 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22022 	 * to this group. This is okay as IP_BOUND_IF really means
22023 	 * any ill in the group. We depend on the fact that the
22024 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22025 	 * if such an ire exists. This is possible only if you have
22026 	 * at least one ill in the group that has not failed.
22027 	 *
22028 	 * First get to the ire that matches the address and group.
22029 	 *
22030 	 * We don't look for an ire with a matching zoneid because a given zone
22031 	 * won't always have broadcast ires on all ills in the group.
22032 	 */
22033 	irb = ire->ire_bucket;
22034 	rw_enter(&irb->irb_lock, RW_READER);
22035 	if (ire->ire_marks & IRE_MARK_NORECV) {
22036 		/*
22037 		 * If the current zone only has an ire broadcast for this
22038 		 * address marked NORECV, the ire we want is ahead in the
22039 		 * bucket, so we look it up deliberately ignoring the zoneid.
22040 		 */
22041 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22042 			if (ire->ire_addr != addr)
22043 				continue;
22044 			/* skip over deleted ires */
22045 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22046 				continue;
22047 		}
22048 	}
22049 	while (ire != NULL) {
22050 		/*
22051 		 * If a new interface is coming up, we could end up
22052 		 * seeing the loopback ire and the non-loopback ire
22053 		 * may not have been added yet. So check for ire_stq
22054 		 */
22055 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22056 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22057 			break;
22058 		}
22059 		ire = ire->ire_next;
22060 	}
22061 	if (ire != NULL && ire->ire_addr == addr &&
22062 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22063 		IRE_REFHOLD(ire);
22064 		rw_exit(&irb->irb_lock);
22065 		ire_refrele(save_ire);
22066 		*conn_outgoing_ill = ire_to_ill(ire);
22067 		/*
22068 		 * Refhold the ill to make the conn_outgoing_ill
22069 		 * independent of the ire. ip_wput_ire goes in a loop
22070 		 * and may refrele the ire. Since we have an ire at this
22071 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22072 		 */
22073 		ill_refhold(*conn_outgoing_ill);
22074 		return (ire);
22075 	}
22076 	rw_exit(&irb->irb_lock);
22077 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22078 	/*
22079 	 * If we can't find a suitable ire, return the original ire.
22080 	 */
22081 	return (save_ire);
22082 }
22083 
22084 /*
22085  * This function does the ire_refrele of the ire passed in as the
22086  * argument. As this function looks up more ires i.e broadcast ires,
22087  * it needs to REFRELE them. Currently, for simplicity we don't
22088  * differentiate the one passed in and looked up here. We always
22089  * REFRELE.
22090  * IPQoS Notes:
22091  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22092  * IPsec packets are done in ipsec_out_process.
22093  *
22094  */
22095 void
22096 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22097     zoneid_t zoneid)
22098 {
22099 	ipha_t		*ipha;
22100 #define	rptr	((uchar_t *)ipha)
22101 	queue_t		*stq;
22102 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22103 	uint32_t	v_hlen_tos_len;
22104 	uint32_t	ttl_protocol;
22105 	ipaddr_t	src;
22106 	ipaddr_t	dst;
22107 	uint32_t	cksum;
22108 	ipaddr_t	orig_src;
22109 	ire_t		*ire1;
22110 	mblk_t		*next_mp;
22111 	uint_t		hlen;
22112 	uint16_t	*up;
22113 	uint32_t	max_frag = ire->ire_max_frag;
22114 	ill_t		*ill = ire_to_ill(ire);
22115 	int		clusterwide;
22116 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22117 	int		ipsec_len;
22118 	mblk_t		*first_mp;
22119 	ipsec_out_t	*io;
22120 	boolean_t	conn_dontroute;		/* conn value for multicast */
22121 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22122 	boolean_t	multicast_forward;	/* Should we forward ? */
22123 	boolean_t	unspec_src;
22124 	ill_t		*conn_outgoing_ill = NULL;
22125 	ill_t		*ire_ill;
22126 	ill_t		*ire1_ill;
22127 	ill_t		*out_ill;
22128 	uint32_t 	ill_index = 0;
22129 	boolean_t	multirt_send = B_FALSE;
22130 	int		err;
22131 	ipxmit_state_t	pktxmit_state;
22132 	ip_stack_t	*ipst = ire->ire_ipst;
22133 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22134 
22135 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22136 	    "ip_wput_ire_start: q %p", q);
22137 
22138 	multicast_forward = B_FALSE;
22139 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22140 
22141 	if (ire->ire_flags & RTF_MULTIRT) {
22142 		/*
22143 		 * Multirouting case. The bucket where ire is stored
22144 		 * probably holds other RTF_MULTIRT flagged ire
22145 		 * to the destination. In this call to ip_wput_ire,
22146 		 * we attempt to send the packet through all
22147 		 * those ires. Thus, we first ensure that ire is the
22148 		 * first RTF_MULTIRT ire in the bucket,
22149 		 * before walking the ire list.
22150 		 */
22151 		ire_t *first_ire;
22152 		irb_t *irb = ire->ire_bucket;
22153 		ASSERT(irb != NULL);
22154 
22155 		/* Make sure we do not omit any multiroute ire. */
22156 		IRB_REFHOLD(irb);
22157 		for (first_ire = irb->irb_ire;
22158 		    first_ire != NULL;
22159 		    first_ire = first_ire->ire_next) {
22160 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22161 			    (first_ire->ire_addr == ire->ire_addr) &&
22162 			    !(first_ire->ire_marks &
22163 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22164 				break;
22165 			}
22166 		}
22167 
22168 		if ((first_ire != NULL) && (first_ire != ire)) {
22169 			IRE_REFHOLD(first_ire);
22170 			ire_refrele(ire);
22171 			ire = first_ire;
22172 			ill = ire_to_ill(ire);
22173 		}
22174 		IRB_REFRELE(irb);
22175 	}
22176 
22177 	/*
22178 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22179 	 * for performance we don't grab the mutexs in the fastpath
22180 	 */
22181 	if ((connp != NULL) &&
22182 	    (ire->ire_type == IRE_BROADCAST) &&
22183 	    ((connp->conn_nofailover_ill != NULL) ||
22184 	    (connp->conn_outgoing_ill != NULL))) {
22185 		/*
22186 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22187 		 * option. So, see if this endpoint is bound to a
22188 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22189 		 * that if the interface is failed, we will still send
22190 		 * the packet on the same ill which is what we want.
22191 		 */
22192 		conn_outgoing_ill = conn_get_held_ill(connp,
22193 		    &connp->conn_nofailover_ill, &err);
22194 		if (err == ILL_LOOKUP_FAILED) {
22195 			ire_refrele(ire);
22196 			freemsg(mp);
22197 			return;
22198 		}
22199 		if (conn_outgoing_ill == NULL) {
22200 			/*
22201 			 * Choose a good ill in the group to send the
22202 			 * packets on.
22203 			 */
22204 			ire = conn_set_outgoing_ill(connp, ire,
22205 			    &conn_outgoing_ill);
22206 			if (ire == NULL) {
22207 				freemsg(mp);
22208 				return;
22209 			}
22210 		}
22211 	}
22212 
22213 	if (mp->b_datap->db_type != M_CTL) {
22214 		ipha = (ipha_t *)mp->b_rptr;
22215 	} else {
22216 		io = (ipsec_out_t *)mp->b_rptr;
22217 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22218 		ASSERT(zoneid == io->ipsec_out_zoneid);
22219 		ASSERT(zoneid != ALL_ZONES);
22220 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22221 		dst = ipha->ipha_dst;
22222 		/*
22223 		 * For the multicast case, ipsec_out carries conn_dontroute and
22224 		 * conn_multicast_loop as conn may not be available here. We
22225 		 * need this for multicast loopback and forwarding which is done
22226 		 * later in the code.
22227 		 */
22228 		if (CLASSD(dst)) {
22229 			conn_dontroute = io->ipsec_out_dontroute;
22230 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22231 			/*
22232 			 * If conn_dontroute is not set or conn_multicast_loop
22233 			 * is set, we need to do forwarding/loopback. For
22234 			 * datagrams from ip_wput_multicast, conn_dontroute is
22235 			 * set to B_TRUE and conn_multicast_loop is set to
22236 			 * B_FALSE so that we neither do forwarding nor
22237 			 * loopback.
22238 			 */
22239 			if (!conn_dontroute || conn_multicast_loop)
22240 				multicast_forward = B_TRUE;
22241 		}
22242 	}
22243 
22244 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22245 	    ire->ire_zoneid != ALL_ZONES) {
22246 		/*
22247 		 * When a zone sends a packet to another zone, we try to deliver
22248 		 * the packet under the same conditions as if the destination
22249 		 * was a real node on the network. To do so, we look for a
22250 		 * matching route in the forwarding table.
22251 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22252 		 * ip_newroute() does.
22253 		 * Note that IRE_LOCAL are special, since they are used
22254 		 * when the zoneid doesn't match in some cases. This means that
22255 		 * we need to handle ipha_src differently since ire_src_addr
22256 		 * belongs to the receiving zone instead of the sending zone.
22257 		 * When ip_restrict_interzone_loopback is set, then
22258 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22259 		 * for loopback between zones when the logical "Ethernet" would
22260 		 * have looped them back.
22261 		 */
22262 		ire_t *src_ire;
22263 
22264 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22265 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22266 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22267 		if (src_ire != NULL &&
22268 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22269 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22270 		    ire_local_same_ill_group(ire, src_ire))) {
22271 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22272 				ipha->ipha_src = src_ire->ire_src_addr;
22273 			ire_refrele(src_ire);
22274 		} else {
22275 			ire_refrele(ire);
22276 			if (conn_outgoing_ill != NULL)
22277 				ill_refrele(conn_outgoing_ill);
22278 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22279 			if (src_ire != NULL) {
22280 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22281 					ire_refrele(src_ire);
22282 					freemsg(mp);
22283 					return;
22284 				}
22285 				ire_refrele(src_ire);
22286 			}
22287 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22288 				/* Failed */
22289 				freemsg(mp);
22290 				return;
22291 			}
22292 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22293 			    ipst);
22294 			return;
22295 		}
22296 	}
22297 
22298 	if (mp->b_datap->db_type == M_CTL ||
22299 	    ipss->ipsec_outbound_v4_policy_present) {
22300 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22301 		    unspec_src, zoneid);
22302 		if (mp == NULL) {
22303 			ire_refrele(ire);
22304 			if (conn_outgoing_ill != NULL)
22305 				ill_refrele(conn_outgoing_ill);
22306 			return;
22307 		}
22308 		/*
22309 		 * Trusted Extensions supports all-zones interfaces, so
22310 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22311 		 * the global zone.
22312 		 */
22313 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22314 			io = (ipsec_out_t *)mp->b_rptr;
22315 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22316 			zoneid = io->ipsec_out_zoneid;
22317 		}
22318 	}
22319 
22320 	first_mp = mp;
22321 	ipsec_len = 0;
22322 
22323 	if (first_mp->b_datap->db_type == M_CTL) {
22324 		io = (ipsec_out_t *)first_mp->b_rptr;
22325 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22326 		mp = first_mp->b_cont;
22327 		ipsec_len = ipsec_out_extra_length(first_mp);
22328 		ASSERT(ipsec_len >= 0);
22329 		/* We already picked up the zoneid from the M_CTL above */
22330 		ASSERT(zoneid == io->ipsec_out_zoneid);
22331 		ASSERT(zoneid != ALL_ZONES);
22332 
22333 		/*
22334 		 * Drop M_CTL here if IPsec processing is not needed.
22335 		 * (Non-IPsec use of M_CTL extracted any information it
22336 		 * needed above).
22337 		 */
22338 		if (ipsec_len == 0) {
22339 			freeb(first_mp);
22340 			first_mp = mp;
22341 		}
22342 	}
22343 
22344 	/*
22345 	 * Fast path for ip_wput_ire
22346 	 */
22347 
22348 	ipha = (ipha_t *)mp->b_rptr;
22349 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22350 	dst = ipha->ipha_dst;
22351 
22352 	/*
22353 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22354 	 * if the socket is a SOCK_RAW type. The transport checksum should
22355 	 * be provided in the pre-built packet, so we don't need to compute it.
22356 	 * Also, other application set flags, like DF, should not be altered.
22357 	 * Other transport MUST pass down zero.
22358 	 */
22359 	ip_hdr_included = ipha->ipha_ident;
22360 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22361 
22362 	if (CLASSD(dst)) {
22363 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22364 		    ntohl(dst),
22365 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22366 		    ntohl(ire->ire_addr)));
22367 	}
22368 
22369 /* Macros to extract header fields from data already in registers */
22370 #ifdef	_BIG_ENDIAN
22371 #define	V_HLEN	(v_hlen_tos_len >> 24)
22372 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22373 #define	PROTO	(ttl_protocol & 0xFF)
22374 #else
22375 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22376 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22377 #define	PROTO	(ttl_protocol >> 8)
22378 #endif
22379 
22380 
22381 	orig_src = src = ipha->ipha_src;
22382 	/* (The loop back to "another" is explained down below.) */
22383 another:;
22384 	/*
22385 	 * Assign an ident value for this packet.  We assign idents on
22386 	 * a per destination basis out of the IRE.  There could be
22387 	 * other threads targeting the same destination, so we have to
22388 	 * arrange for a atomic increment.  Note that we use a 32-bit
22389 	 * atomic add because it has better performance than its
22390 	 * 16-bit sibling.
22391 	 *
22392 	 * If running in cluster mode and if the source address
22393 	 * belongs to a replicated service then vector through
22394 	 * cl_inet_ipident vector to allocate ip identifier
22395 	 * NOTE: This is a contract private interface with the
22396 	 * clustering group.
22397 	 */
22398 	clusterwide = 0;
22399 	if (cl_inet_ipident) {
22400 		ASSERT(cl_inet_isclusterwide);
22401 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22402 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22403 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22404 			    AF_INET, (uint8_t *)(uintptr_t)src,
22405 			    (uint8_t *)(uintptr_t)dst);
22406 			clusterwide = 1;
22407 		}
22408 	}
22409 	if (!clusterwide) {
22410 		ipha->ipha_ident =
22411 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22412 	}
22413 
22414 #ifndef _BIG_ENDIAN
22415 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22416 #endif
22417 
22418 	/*
22419 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22420 	 * This is needed to obey conn_unspec_src when packets go through
22421 	 * ip_newroute + arp.
22422 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22423 	 */
22424 	if (src == INADDR_ANY && !unspec_src) {
22425 		/*
22426 		 * Assign the appropriate source address from the IRE if none
22427 		 * was specified.
22428 		 */
22429 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22430 
22431 		/*
22432 		 * With IP multipathing, broadcast packets are sent on the ire
22433 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22434 		 * the group. However, this ire might not be in the same zone so
22435 		 * we can't always use its source address. We look for a
22436 		 * broadcast ire in the same group and in the right zone.
22437 		 */
22438 		if (ire->ire_type == IRE_BROADCAST &&
22439 		    ire->ire_zoneid != zoneid) {
22440 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22441 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22442 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22443 			if (src_ire != NULL) {
22444 				src = src_ire->ire_src_addr;
22445 				ire_refrele(src_ire);
22446 			} else {
22447 				ire_refrele(ire);
22448 				if (conn_outgoing_ill != NULL)
22449 					ill_refrele(conn_outgoing_ill);
22450 				freemsg(first_mp);
22451 				if (ill != NULL) {
22452 					BUMP_MIB(ill->ill_ip_mib,
22453 					    ipIfStatsOutDiscards);
22454 				} else {
22455 					BUMP_MIB(&ipst->ips_ip_mib,
22456 					    ipIfStatsOutDiscards);
22457 				}
22458 				return;
22459 			}
22460 		} else {
22461 			src = ire->ire_src_addr;
22462 		}
22463 
22464 		if (connp == NULL) {
22465 			ip1dbg(("ip_wput_ire: no connp and no src "
22466 			    "address for dst 0x%x, using src 0x%x\n",
22467 			    ntohl(dst),
22468 			    ntohl(src)));
22469 		}
22470 		ipha->ipha_src = src;
22471 	}
22472 	stq = ire->ire_stq;
22473 
22474 	/*
22475 	 * We only allow ire chains for broadcasts since there will
22476 	 * be multiple IRE_CACHE entries for the same multicast
22477 	 * address (one per ipif).
22478 	 */
22479 	next_mp = NULL;
22480 
22481 	/* broadcast packet */
22482 	if (ire->ire_type == IRE_BROADCAST)
22483 		goto broadcast;
22484 
22485 	/* loopback ? */
22486 	if (stq == NULL)
22487 		goto nullstq;
22488 
22489 	/* The ill_index for outbound ILL */
22490 	ill_index = Q_TO_INDEX(stq);
22491 
22492 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22493 	ttl_protocol = ((uint16_t *)ipha)[4];
22494 
22495 	/* pseudo checksum (do it in parts for IP header checksum) */
22496 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22497 
22498 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22499 		queue_t *dev_q = stq->q_next;
22500 
22501 		/* flow controlled */
22502 		if ((dev_q->q_next || dev_q->q_first) &&
22503 		    !canput(dev_q))
22504 			goto blocked;
22505 		if ((PROTO == IPPROTO_UDP) &&
22506 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22507 			hlen = (V_HLEN & 0xF) << 2;
22508 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22509 			if (*up != 0) {
22510 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22511 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22512 				/* Software checksum? */
22513 				if (DB_CKSUMFLAGS(mp) == 0) {
22514 					IP_STAT(ipst, ip_out_sw_cksum);
22515 					IP_STAT_UPDATE(ipst,
22516 					    ip_udp_out_sw_cksum_bytes,
22517 					    LENGTH - hlen);
22518 				}
22519 			}
22520 		}
22521 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22522 		hlen = (V_HLEN & 0xF) << 2;
22523 		if (PROTO == IPPROTO_TCP) {
22524 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22525 			/*
22526 			 * The packet header is processed once and for all, even
22527 			 * in the multirouting case. We disable hardware
22528 			 * checksum if the packet is multirouted, as it will be
22529 			 * replicated via several interfaces, and not all of
22530 			 * them may have this capability.
22531 			 */
22532 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22533 			    LENGTH, max_frag, ipsec_len, cksum);
22534 			/* Software checksum? */
22535 			if (DB_CKSUMFLAGS(mp) == 0) {
22536 				IP_STAT(ipst, ip_out_sw_cksum);
22537 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22538 				    LENGTH - hlen);
22539 			}
22540 		} else {
22541 			sctp_hdr_t	*sctph;
22542 
22543 			ASSERT(PROTO == IPPROTO_SCTP);
22544 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22545 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22546 			/*
22547 			 * Zero out the checksum field to ensure proper
22548 			 * checksum calculation.
22549 			 */
22550 			sctph->sh_chksum = 0;
22551 #ifdef	DEBUG
22552 			if (!skip_sctp_cksum)
22553 #endif
22554 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22555 		}
22556 	}
22557 
22558 	/*
22559 	 * If this is a multicast packet and originated from ip_wput
22560 	 * we need to do loopback and forwarding checks. If it comes
22561 	 * from ip_wput_multicast, we SHOULD not do this.
22562 	 */
22563 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22564 
22565 	/* checksum */
22566 	cksum += ttl_protocol;
22567 
22568 	/* fragment the packet */
22569 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22570 		goto fragmentit;
22571 	/*
22572 	 * Don't use frag_flag if packet is pre-built or source
22573 	 * routed or if multicast (since multicast packets do
22574 	 * not solicit ICMP "packet too big" messages).
22575 	 */
22576 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22577 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22578 	    !ip_source_route_included(ipha)) &&
22579 	    !CLASSD(ipha->ipha_dst))
22580 		ipha->ipha_fragment_offset_and_flags |=
22581 		    htons(ire->ire_frag_flag);
22582 
22583 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22584 		/* calculate IP header checksum */
22585 		cksum += ipha->ipha_ident;
22586 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22587 		cksum += ipha->ipha_fragment_offset_and_flags;
22588 
22589 		/* IP options present */
22590 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22591 		if (hlen)
22592 			goto checksumoptions;
22593 
22594 		/* calculate hdr checksum */
22595 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22596 		cksum = ~(cksum + (cksum >> 16));
22597 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22598 	}
22599 	if (ipsec_len != 0) {
22600 		/*
22601 		 * We will do the rest of the processing after
22602 		 * we come back from IPsec in ip_wput_ipsec_out().
22603 		 */
22604 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22605 
22606 		io = (ipsec_out_t *)first_mp->b_rptr;
22607 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22608 		    ill_phyint->phyint_ifindex;
22609 
22610 		ipsec_out_process(q, first_mp, ire, ill_index);
22611 		ire_refrele(ire);
22612 		if (conn_outgoing_ill != NULL)
22613 			ill_refrele(conn_outgoing_ill);
22614 		return;
22615 	}
22616 
22617 	/*
22618 	 * In most cases, the emission loop below is entered only
22619 	 * once. Only in the case where the ire holds the
22620 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22621 	 * flagged ires in the bucket, and send the packet
22622 	 * through all crossed RTF_MULTIRT routes.
22623 	 */
22624 	if (ire->ire_flags & RTF_MULTIRT) {
22625 		multirt_send = B_TRUE;
22626 	}
22627 	do {
22628 		if (multirt_send) {
22629 			irb_t *irb;
22630 			/*
22631 			 * We are in a multiple send case, need to get
22632 			 * the next ire and make a duplicate of the packet.
22633 			 * ire1 holds here the next ire to process in the
22634 			 * bucket. If multirouting is expected,
22635 			 * any non-RTF_MULTIRT ire that has the
22636 			 * right destination address is ignored.
22637 			 */
22638 			irb = ire->ire_bucket;
22639 			ASSERT(irb != NULL);
22640 
22641 			IRB_REFHOLD(irb);
22642 			for (ire1 = ire->ire_next;
22643 			    ire1 != NULL;
22644 			    ire1 = ire1->ire_next) {
22645 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22646 					continue;
22647 				if (ire1->ire_addr != ire->ire_addr)
22648 					continue;
22649 				if (ire1->ire_marks &
22650 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22651 					continue;
22652 
22653 				/* Got one */
22654 				IRE_REFHOLD(ire1);
22655 				break;
22656 			}
22657 			IRB_REFRELE(irb);
22658 
22659 			if (ire1 != NULL) {
22660 				next_mp = copyb(mp);
22661 				if ((next_mp == NULL) ||
22662 				    ((mp->b_cont != NULL) &&
22663 				    ((next_mp->b_cont =
22664 				    dupmsg(mp->b_cont)) == NULL))) {
22665 					freemsg(next_mp);
22666 					next_mp = NULL;
22667 					ire_refrele(ire1);
22668 					ire1 = NULL;
22669 				}
22670 			}
22671 
22672 			/* Last multiroute ire; don't loop anymore. */
22673 			if (ire1 == NULL) {
22674 				multirt_send = B_FALSE;
22675 			}
22676 		}
22677 
22678 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22679 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22680 		    mblk_t *, mp);
22681 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22682 		    ipst->ips_ipv4firewall_physical_out,
22683 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22684 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22685 		if (mp == NULL)
22686 			goto release_ire_and_ill;
22687 
22688 		if (ipst->ips_ipobs_enabled) {
22689 			zoneid_t szone;
22690 
22691 			/*
22692 			 * On the outbound path the destination zone will be
22693 			 * unknown as we're sending this packet out on the
22694 			 * wire.
22695 			 */
22696 			szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
22697 			    ALL_ZONES);
22698 			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
22699 			    ire->ire_ipif->ipif_ill, IPV4_VERSION, 0, ipst);
22700 		}
22701 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22702 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22703 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22704 		if ((pktxmit_state == SEND_FAILED) ||
22705 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22706 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22707 			    "- packet dropped\n"));
22708 release_ire_and_ill:
22709 			ire_refrele(ire);
22710 			if (next_mp != NULL) {
22711 				freemsg(next_mp);
22712 				ire_refrele(ire1);
22713 			}
22714 			if (conn_outgoing_ill != NULL)
22715 				ill_refrele(conn_outgoing_ill);
22716 			return;
22717 		}
22718 
22719 		if (CLASSD(dst)) {
22720 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22721 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22722 			    LENGTH);
22723 		}
22724 
22725 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22726 		    "ip_wput_ire_end: q %p (%S)",
22727 		    q, "last copy out");
22728 		IRE_REFRELE(ire);
22729 
22730 		if (multirt_send) {
22731 			ASSERT(ire1);
22732 			/*
22733 			 * Proceed with the next RTF_MULTIRT ire,
22734 			 * Also set up the send-to queue accordingly.
22735 			 */
22736 			ire = ire1;
22737 			ire1 = NULL;
22738 			stq = ire->ire_stq;
22739 			mp = next_mp;
22740 			next_mp = NULL;
22741 			ipha = (ipha_t *)mp->b_rptr;
22742 			ill_index = Q_TO_INDEX(stq);
22743 			ill = (ill_t *)stq->q_ptr;
22744 		}
22745 	} while (multirt_send);
22746 	if (conn_outgoing_ill != NULL)
22747 		ill_refrele(conn_outgoing_ill);
22748 	return;
22749 
22750 	/*
22751 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22752 	 */
22753 broadcast:
22754 	{
22755 		/*
22756 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22757 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22758 		 * can be overridden stack-wide through the ip_broadcast_ttl
22759 		 * ndd tunable, or on a per-connection basis through the
22760 		 * IP_BROADCAST_TTL socket option.
22761 		 *
22762 		 * In the event that we are replying to incoming ICMP packets,
22763 		 * connp could be NULL.
22764 		 */
22765 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22766 		if (connp != NULL) {
22767 			if (connp->conn_dontroute)
22768 				ipha->ipha_ttl = 1;
22769 			else if (connp->conn_broadcast_ttl != 0)
22770 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22771 		}
22772 
22773 		/*
22774 		 * Note that we are not doing a IRB_REFHOLD here.
22775 		 * Actually we don't care if the list changes i.e
22776 		 * if somebody deletes an IRE from the list while
22777 		 * we drop the lock, the next time we come around
22778 		 * ire_next will be NULL and hence we won't send
22779 		 * out multiple copies which is fine.
22780 		 */
22781 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22782 		ire1 = ire->ire_next;
22783 		if (conn_outgoing_ill != NULL) {
22784 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22785 				ASSERT(ire1 == ire->ire_next);
22786 				if (ire1 != NULL && ire1->ire_addr == dst) {
22787 					ire_refrele(ire);
22788 					ire = ire1;
22789 					IRE_REFHOLD(ire);
22790 					ire1 = ire->ire_next;
22791 					continue;
22792 				}
22793 				rw_exit(&ire->ire_bucket->irb_lock);
22794 				/* Did not find a matching ill */
22795 				ip1dbg(("ip_wput_ire: broadcast with no "
22796 				    "matching IP_BOUND_IF ill %s dst %x\n",
22797 				    conn_outgoing_ill->ill_name, dst));
22798 				freemsg(first_mp);
22799 				if (ire != NULL)
22800 					ire_refrele(ire);
22801 				ill_refrele(conn_outgoing_ill);
22802 				return;
22803 			}
22804 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22805 			/*
22806 			 * If the next IRE has the same address and is not one
22807 			 * of the two copies that we need to send, try to see
22808 			 * whether this copy should be sent at all. This
22809 			 * assumes that we insert loopbacks first and then
22810 			 * non-loopbacks. This is acheived by inserting the
22811 			 * loopback always before non-loopback.
22812 			 * This is used to send a single copy of a broadcast
22813 			 * packet out all physical interfaces that have an
22814 			 * matching IRE_BROADCAST while also looping
22815 			 * back one copy (to ip_wput_local) for each
22816 			 * matching physical interface. However, we avoid
22817 			 * sending packets out different logical that match by
22818 			 * having ipif_up/ipif_down supress duplicate
22819 			 * IRE_BROADCASTS.
22820 			 *
22821 			 * This feature is currently used to get broadcasts
22822 			 * sent to multiple interfaces, when the broadcast
22823 			 * address being used applies to multiple interfaces.
22824 			 * For example, a whole net broadcast will be
22825 			 * replicated on every connected subnet of
22826 			 * the target net.
22827 			 *
22828 			 * Each zone has its own set of IRE_BROADCASTs, so that
22829 			 * we're able to distribute inbound packets to multiple
22830 			 * zones who share a broadcast address. We avoid looping
22831 			 * back outbound packets in different zones but on the
22832 			 * same ill, as the application would see duplicates.
22833 			 *
22834 			 * If the interfaces are part of the same group,
22835 			 * we would want to send only one copy out for
22836 			 * whole group.
22837 			 *
22838 			 * This logic assumes that ire_add_v4() groups the
22839 			 * IRE_BROADCAST entries so that those with the same
22840 			 * ire_addr and ill_group are kept together.
22841 			 */
22842 			ire_ill = ire->ire_ipif->ipif_ill;
22843 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22844 				if (ire_ill->ill_group != NULL &&
22845 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22846 					/*
22847 					 * If the current zone only has an ire
22848 					 * broadcast for this address marked
22849 					 * NORECV, the ire we want is ahead in
22850 					 * the bucket, so we look it up
22851 					 * deliberately ignoring the zoneid.
22852 					 */
22853 					for (ire1 = ire->ire_bucket->irb_ire;
22854 					    ire1 != NULL;
22855 					    ire1 = ire1->ire_next) {
22856 						ire1_ill =
22857 						    ire1->ire_ipif->ipif_ill;
22858 						if (ire1->ire_addr != dst)
22859 							continue;
22860 						/* skip over the current ire */
22861 						if (ire1 == ire)
22862 							continue;
22863 						/* skip over deleted ires */
22864 						if (ire1->ire_marks &
22865 						    IRE_MARK_CONDEMNED)
22866 							continue;
22867 						/*
22868 						 * non-loopback ire in our
22869 						 * group: use it for the next
22870 						 * pass in the loop
22871 						 */
22872 						if (ire1->ire_stq != NULL &&
22873 						    ire1_ill->ill_group ==
22874 						    ire_ill->ill_group)
22875 							break;
22876 					}
22877 				}
22878 			} else {
22879 				while (ire1 != NULL && ire1->ire_addr == dst) {
22880 					ire1_ill = ire1->ire_ipif->ipif_ill;
22881 					/*
22882 					 * We can have two broadcast ires on the
22883 					 * same ill in different zones; here
22884 					 * we'll send a copy of the packet on
22885 					 * each ill and the fanout code will
22886 					 * call conn_wantpacket() to check that
22887 					 * the zone has the broadcast address
22888 					 * configured on the ill. If the two
22889 					 * ires are in the same group we only
22890 					 * send one copy up.
22891 					 */
22892 					if (ire1_ill != ire_ill &&
22893 					    (ire1_ill->ill_group == NULL ||
22894 					    ire_ill->ill_group == NULL ||
22895 					    ire1_ill->ill_group !=
22896 					    ire_ill->ill_group)) {
22897 						break;
22898 					}
22899 					ire1 = ire1->ire_next;
22900 				}
22901 			}
22902 		}
22903 		ASSERT(multirt_send == B_FALSE);
22904 		if (ire1 != NULL && ire1->ire_addr == dst) {
22905 			if ((ire->ire_flags & RTF_MULTIRT) &&
22906 			    (ire1->ire_flags & RTF_MULTIRT)) {
22907 				/*
22908 				 * We are in the multirouting case.
22909 				 * The message must be sent at least
22910 				 * on both ires. These ires have been
22911 				 * inserted AFTER the standard ones
22912 				 * in ip_rt_add(). There are thus no
22913 				 * other ire entries for the destination
22914 				 * address in the rest of the bucket
22915 				 * that do not have the RTF_MULTIRT
22916 				 * flag. We don't process a copy
22917 				 * of the message here. This will be
22918 				 * done in the final sending loop.
22919 				 */
22920 				multirt_send = B_TRUE;
22921 			} else {
22922 				next_mp = ip_copymsg(first_mp);
22923 				if (next_mp != NULL)
22924 					IRE_REFHOLD(ire1);
22925 			}
22926 		}
22927 		rw_exit(&ire->ire_bucket->irb_lock);
22928 	}
22929 
22930 	if (stq) {
22931 		/*
22932 		 * A non-NULL send-to queue means this packet is going
22933 		 * out of this machine.
22934 		 */
22935 		out_ill = (ill_t *)stq->q_ptr;
22936 
22937 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22938 		ttl_protocol = ((uint16_t *)ipha)[4];
22939 		/*
22940 		 * We accumulate the pseudo header checksum in cksum.
22941 		 * This is pretty hairy code, so watch close.  One
22942 		 * thing to keep in mind is that UDP and TCP have
22943 		 * stored their respective datagram lengths in their
22944 		 * checksum fields.  This lines things up real nice.
22945 		 */
22946 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22947 		    (src >> 16) + (src & 0xFFFF);
22948 		/*
22949 		 * We assume the udp checksum field contains the
22950 		 * length, so to compute the pseudo header checksum,
22951 		 * all we need is the protocol number and src/dst.
22952 		 */
22953 		/* Provide the checksums for UDP and TCP. */
22954 		if ((PROTO == IPPROTO_TCP) &&
22955 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22956 			/* hlen gets the number of uchar_ts in the IP header */
22957 			hlen = (V_HLEN & 0xF) << 2;
22958 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22959 			IP_STAT(ipst, ip_out_sw_cksum);
22960 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22961 			    LENGTH - hlen);
22962 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22963 		} else if (PROTO == IPPROTO_SCTP &&
22964 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22965 			sctp_hdr_t	*sctph;
22966 
22967 			hlen = (V_HLEN & 0xF) << 2;
22968 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22969 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22970 			sctph->sh_chksum = 0;
22971 #ifdef	DEBUG
22972 			if (!skip_sctp_cksum)
22973 #endif
22974 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22975 		} else {
22976 			queue_t *dev_q = stq->q_next;
22977 
22978 			if ((dev_q->q_next || dev_q->q_first) &&
22979 			    !canput(dev_q)) {
22980 blocked:
22981 				ipha->ipha_ident = ip_hdr_included;
22982 				/*
22983 				 * If we don't have a conn to apply
22984 				 * backpressure, free the message.
22985 				 * In the ire_send path, we don't know
22986 				 * the position to requeue the packet. Rather
22987 				 * than reorder packets, we just drop this
22988 				 * packet.
22989 				 */
22990 				if (ipst->ips_ip_output_queue &&
22991 				    connp != NULL &&
22992 				    caller != IRE_SEND) {
22993 					if (caller == IP_WSRV) {
22994 						connp->conn_did_putbq = 1;
22995 						(void) putbq(connp->conn_wq,
22996 						    first_mp);
22997 						conn_drain_insert(connp);
22998 						/*
22999 						 * This is the service thread,
23000 						 * and the queue is already
23001 						 * noenabled. The check for
23002 						 * canput and the putbq is not
23003 						 * atomic. So we need to check
23004 						 * again.
23005 						 */
23006 						if (canput(stq->q_next))
23007 							connp->conn_did_putbq
23008 							    = 0;
23009 						IP_STAT(ipst, ip_conn_flputbq);
23010 					} else {
23011 						/*
23012 						 * We are not the service proc.
23013 						 * ip_wsrv will be scheduled or
23014 						 * is already running.
23015 						 */
23016 						(void) putq(connp->conn_wq,
23017 						    first_mp);
23018 					}
23019 				} else {
23020 					out_ill = (ill_t *)stq->q_ptr;
23021 					BUMP_MIB(out_ill->ill_ip_mib,
23022 					    ipIfStatsOutDiscards);
23023 					freemsg(first_mp);
23024 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23025 					    "ip_wput_ire_end: q %p (%S)",
23026 					    q, "discard");
23027 				}
23028 				ire_refrele(ire);
23029 				if (next_mp) {
23030 					ire_refrele(ire1);
23031 					freemsg(next_mp);
23032 				}
23033 				if (conn_outgoing_ill != NULL)
23034 					ill_refrele(conn_outgoing_ill);
23035 				return;
23036 			}
23037 			if ((PROTO == IPPROTO_UDP) &&
23038 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23039 				/*
23040 				 * hlen gets the number of uchar_ts in the
23041 				 * IP header
23042 				 */
23043 				hlen = (V_HLEN & 0xF) << 2;
23044 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23045 				max_frag = ire->ire_max_frag;
23046 				if (*up != 0) {
23047 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
23048 					    up, PROTO, hlen, LENGTH, max_frag,
23049 					    ipsec_len, cksum);
23050 					/* Software checksum? */
23051 					if (DB_CKSUMFLAGS(mp) == 0) {
23052 						IP_STAT(ipst, ip_out_sw_cksum);
23053 						IP_STAT_UPDATE(ipst,
23054 						    ip_udp_out_sw_cksum_bytes,
23055 						    LENGTH - hlen);
23056 					}
23057 				}
23058 			}
23059 		}
23060 		/*
23061 		 * Need to do this even when fragmenting. The local
23062 		 * loopback can be done without computing checksums
23063 		 * but forwarding out other interface must be done
23064 		 * after the IP checksum (and ULP checksums) have been
23065 		 * computed.
23066 		 *
23067 		 * NOTE : multicast_forward is set only if this packet
23068 		 * originated from ip_wput. For packets originating from
23069 		 * ip_wput_multicast, it is not set.
23070 		 */
23071 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23072 multi_loopback:
23073 			ip2dbg(("ip_wput: multicast, loop %d\n",
23074 			    conn_multicast_loop));
23075 
23076 			/*  Forget header checksum offload */
23077 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23078 
23079 			/*
23080 			 * Local loopback of multicasts?  Check the
23081 			 * ill.
23082 			 *
23083 			 * Note that the loopback function will not come
23084 			 * in through ip_rput - it will only do the
23085 			 * client fanout thus we need to do an mforward
23086 			 * as well.  The is different from the BSD
23087 			 * logic.
23088 			 */
23089 			if (ill != NULL) {
23090 				ilm_t	*ilm;
23091 
23092 				ILM_WALKER_HOLD(ill);
23093 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23094 				    ALL_ZONES);
23095 				ILM_WALKER_RELE(ill);
23096 				if (ilm != NULL) {
23097 					/*
23098 					 * Pass along the virtual output q.
23099 					 * ip_wput_local() will distribute the
23100 					 * packet to all the matching zones,
23101 					 * except the sending zone when
23102 					 * IP_MULTICAST_LOOP is false.
23103 					 */
23104 					ip_multicast_loopback(q, ill, first_mp,
23105 					    conn_multicast_loop ? 0 :
23106 					    IP_FF_NO_MCAST_LOOP, zoneid);
23107 				}
23108 			}
23109 			if (ipha->ipha_ttl == 0) {
23110 				/*
23111 				 * 0 => only to this host i.e. we are
23112 				 * done. We are also done if this was the
23113 				 * loopback interface since it is sufficient
23114 				 * to loopback one copy of a multicast packet.
23115 				 */
23116 				freemsg(first_mp);
23117 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23118 				    "ip_wput_ire_end: q %p (%S)",
23119 				    q, "loopback");
23120 				ire_refrele(ire);
23121 				if (conn_outgoing_ill != NULL)
23122 					ill_refrele(conn_outgoing_ill);
23123 				return;
23124 			}
23125 			/*
23126 			 * ILLF_MULTICAST is checked in ip_newroute
23127 			 * i.e. we don't need to check it here since
23128 			 * all IRE_CACHEs come from ip_newroute.
23129 			 * For multicast traffic, SO_DONTROUTE is interpreted
23130 			 * to mean only send the packet out the interface
23131 			 * (optionally specified with IP_MULTICAST_IF)
23132 			 * and do not forward it out additional interfaces.
23133 			 * RSVP and the rsvp daemon is an example of a
23134 			 * protocol and user level process that
23135 			 * handles it's own routing. Hence, it uses the
23136 			 * SO_DONTROUTE option to accomplish this.
23137 			 */
23138 
23139 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23140 			    ill != NULL) {
23141 				/* Unconditionally redo the checksum */
23142 				ipha->ipha_hdr_checksum = 0;
23143 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23144 
23145 				/*
23146 				 * If this needs to go out secure, we need
23147 				 * to wait till we finish the IPsec
23148 				 * processing.
23149 				 */
23150 				if (ipsec_len == 0 &&
23151 				    ip_mforward(ill, ipha, mp)) {
23152 					freemsg(first_mp);
23153 					ip1dbg(("ip_wput: mforward failed\n"));
23154 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23155 					    "ip_wput_ire_end: q %p (%S)",
23156 					    q, "mforward failed");
23157 					ire_refrele(ire);
23158 					if (conn_outgoing_ill != NULL)
23159 						ill_refrele(conn_outgoing_ill);
23160 					return;
23161 				}
23162 			}
23163 		}
23164 		max_frag = ire->ire_max_frag;
23165 		cksum += ttl_protocol;
23166 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23167 			/* No fragmentation required for this one. */
23168 			/*
23169 			 * Don't use frag_flag if packet is pre-built or source
23170 			 * routed or if multicast (since multicast packets do
23171 			 * not solicit ICMP "packet too big" messages).
23172 			 */
23173 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23174 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23175 			    !ip_source_route_included(ipha)) &&
23176 			    !CLASSD(ipha->ipha_dst))
23177 				ipha->ipha_fragment_offset_and_flags |=
23178 				    htons(ire->ire_frag_flag);
23179 
23180 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23181 				/* Complete the IP header checksum. */
23182 				cksum += ipha->ipha_ident;
23183 				cksum += (v_hlen_tos_len >> 16)+
23184 				    (v_hlen_tos_len & 0xFFFF);
23185 				cksum += ipha->ipha_fragment_offset_and_flags;
23186 				hlen = (V_HLEN & 0xF) -
23187 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23188 				if (hlen) {
23189 checksumoptions:
23190 					/*
23191 					 * Account for the IP Options in the IP
23192 					 * header checksum.
23193 					 */
23194 					up = (uint16_t *)(rptr+
23195 					    IP_SIMPLE_HDR_LENGTH);
23196 					do {
23197 						cksum += up[0];
23198 						cksum += up[1];
23199 						up += 2;
23200 					} while (--hlen);
23201 				}
23202 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23203 				cksum = ~(cksum + (cksum >> 16));
23204 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23205 			}
23206 			if (ipsec_len != 0) {
23207 				ipsec_out_process(q, first_mp, ire, ill_index);
23208 				if (!next_mp) {
23209 					ire_refrele(ire);
23210 					if (conn_outgoing_ill != NULL)
23211 						ill_refrele(conn_outgoing_ill);
23212 					return;
23213 				}
23214 				goto next;
23215 			}
23216 
23217 			/*
23218 			 * multirt_send has already been handled
23219 			 * for broadcast, but not yet for multicast
23220 			 * or IP options.
23221 			 */
23222 			if (next_mp == NULL) {
23223 				if (ire->ire_flags & RTF_MULTIRT) {
23224 					multirt_send = B_TRUE;
23225 				}
23226 			}
23227 
23228 			/*
23229 			 * In most cases, the emission loop below is
23230 			 * entered only once. Only in the case where
23231 			 * the ire holds the RTF_MULTIRT flag, do we loop
23232 			 * to process all RTF_MULTIRT ires in the bucket,
23233 			 * and send the packet through all crossed
23234 			 * RTF_MULTIRT routes.
23235 			 */
23236 			do {
23237 				if (multirt_send) {
23238 					irb_t *irb;
23239 
23240 					irb = ire->ire_bucket;
23241 					ASSERT(irb != NULL);
23242 					/*
23243 					 * We are in a multiple send case,
23244 					 * need to get the next IRE and make
23245 					 * a duplicate of the packet.
23246 					 */
23247 					IRB_REFHOLD(irb);
23248 					for (ire1 = ire->ire_next;
23249 					    ire1 != NULL;
23250 					    ire1 = ire1->ire_next) {
23251 						if (!(ire1->ire_flags &
23252 						    RTF_MULTIRT)) {
23253 							continue;
23254 						}
23255 						if (ire1->ire_addr !=
23256 						    ire->ire_addr) {
23257 							continue;
23258 						}
23259 						if (ire1->ire_marks &
23260 						    (IRE_MARK_CONDEMNED|
23261 						    IRE_MARK_HIDDEN)) {
23262 							continue;
23263 						}
23264 
23265 						/* Got one */
23266 						IRE_REFHOLD(ire1);
23267 						break;
23268 					}
23269 					IRB_REFRELE(irb);
23270 
23271 					if (ire1 != NULL) {
23272 						next_mp = copyb(mp);
23273 						if ((next_mp == NULL) ||
23274 						    ((mp->b_cont != NULL) &&
23275 						    ((next_mp->b_cont =
23276 						    dupmsg(mp->b_cont))
23277 						    == NULL))) {
23278 							freemsg(next_mp);
23279 							next_mp = NULL;
23280 							ire_refrele(ire1);
23281 							ire1 = NULL;
23282 						}
23283 					}
23284 
23285 					/*
23286 					 * Last multiroute ire; don't loop
23287 					 * anymore. The emission is over
23288 					 * and next_mp is NULL.
23289 					 */
23290 					if (ire1 == NULL) {
23291 						multirt_send = B_FALSE;
23292 					}
23293 				}
23294 
23295 				out_ill = ire_to_ill(ire);
23296 				DTRACE_PROBE4(ip4__physical__out__start,
23297 				    ill_t *, NULL,
23298 				    ill_t *, out_ill,
23299 				    ipha_t *, ipha, mblk_t *, mp);
23300 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23301 				    ipst->ips_ipv4firewall_physical_out,
23302 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23303 				DTRACE_PROBE1(ip4__physical__out__end,
23304 				    mblk_t *, mp);
23305 				if (mp == NULL)
23306 					goto release_ire_and_ill_2;
23307 
23308 				ASSERT(ipsec_len == 0);
23309 				mp->b_prev =
23310 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23311 				DTRACE_PROBE2(ip__xmit__2,
23312 				    mblk_t *, mp, ire_t *, ire);
23313 				pktxmit_state = ip_xmit_v4(mp, ire,
23314 				    NULL, B_TRUE);
23315 				if ((pktxmit_state == SEND_FAILED) ||
23316 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23317 release_ire_and_ill_2:
23318 					if (next_mp) {
23319 						freemsg(next_mp);
23320 						ire_refrele(ire1);
23321 					}
23322 					ire_refrele(ire);
23323 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23324 					    "ip_wput_ire_end: q %p (%S)",
23325 					    q, "discard MDATA");
23326 					if (conn_outgoing_ill != NULL)
23327 						ill_refrele(conn_outgoing_ill);
23328 					return;
23329 				}
23330 
23331 				if (CLASSD(dst)) {
23332 					BUMP_MIB(out_ill->ill_ip_mib,
23333 					    ipIfStatsHCOutMcastPkts);
23334 					UPDATE_MIB(out_ill->ill_ip_mib,
23335 					    ipIfStatsHCOutMcastOctets,
23336 					    LENGTH);
23337 				} else if (ire->ire_type == IRE_BROADCAST) {
23338 					BUMP_MIB(out_ill->ill_ip_mib,
23339 					    ipIfStatsHCOutBcastPkts);
23340 				}
23341 
23342 				if (multirt_send) {
23343 					/*
23344 					 * We are in a multiple send case,
23345 					 * need to re-enter the sending loop
23346 					 * using the next ire.
23347 					 */
23348 					ire_refrele(ire);
23349 					ire = ire1;
23350 					stq = ire->ire_stq;
23351 					mp = next_mp;
23352 					next_mp = NULL;
23353 					ipha = (ipha_t *)mp->b_rptr;
23354 					ill_index = Q_TO_INDEX(stq);
23355 				}
23356 			} while (multirt_send);
23357 
23358 			if (!next_mp) {
23359 				/*
23360 				 * Last copy going out (the ultra-common
23361 				 * case).  Note that we intentionally replicate
23362 				 * the putnext rather than calling it before
23363 				 * the next_mp check in hopes of a little
23364 				 * tail-call action out of the compiler.
23365 				 */
23366 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23367 				    "ip_wput_ire_end: q %p (%S)",
23368 				    q, "last copy out(1)");
23369 				ire_refrele(ire);
23370 				if (conn_outgoing_ill != NULL)
23371 					ill_refrele(conn_outgoing_ill);
23372 				return;
23373 			}
23374 			/* More copies going out below. */
23375 		} else {
23376 			int offset;
23377 fragmentit:
23378 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23379 			/*
23380 			 * If this would generate a icmp_frag_needed message,
23381 			 * we need to handle it before we do the IPsec
23382 			 * processing. Otherwise, we need to strip the IPsec
23383 			 * headers before we send up the message to the ULPs
23384 			 * which becomes messy and difficult.
23385 			 */
23386 			if (ipsec_len != 0) {
23387 				if ((max_frag < (unsigned int)(LENGTH +
23388 				    ipsec_len)) && (offset & IPH_DF)) {
23389 					out_ill = (ill_t *)stq->q_ptr;
23390 					BUMP_MIB(out_ill->ill_ip_mib,
23391 					    ipIfStatsOutFragFails);
23392 					BUMP_MIB(out_ill->ill_ip_mib,
23393 					    ipIfStatsOutFragReqds);
23394 					ipha->ipha_hdr_checksum = 0;
23395 					ipha->ipha_hdr_checksum =
23396 					    (uint16_t)ip_csum_hdr(ipha);
23397 					icmp_frag_needed(ire->ire_stq, first_mp,
23398 					    max_frag, zoneid, ipst);
23399 					if (!next_mp) {
23400 						ire_refrele(ire);
23401 						if (conn_outgoing_ill != NULL) {
23402 							ill_refrele(
23403 							    conn_outgoing_ill);
23404 						}
23405 						return;
23406 					}
23407 				} else {
23408 					/*
23409 					 * This won't cause a icmp_frag_needed
23410 					 * message. to be generated. Send it on
23411 					 * the wire. Note that this could still
23412 					 * cause fragmentation and all we
23413 					 * do is the generation of the message
23414 					 * to the ULP if needed before IPsec.
23415 					 */
23416 					if (!next_mp) {
23417 						ipsec_out_process(q, first_mp,
23418 						    ire, ill_index);
23419 						TRACE_2(TR_FAC_IP,
23420 						    TR_IP_WPUT_IRE_END,
23421 						    "ip_wput_ire_end: q %p "
23422 						    "(%S)", q,
23423 						    "last ipsec_out_process");
23424 						ire_refrele(ire);
23425 						if (conn_outgoing_ill != NULL) {
23426 							ill_refrele(
23427 							    conn_outgoing_ill);
23428 						}
23429 						return;
23430 					}
23431 					ipsec_out_process(q, first_mp,
23432 					    ire, ill_index);
23433 				}
23434 			} else {
23435 				/*
23436 				 * Initiate IPPF processing. For
23437 				 * fragmentable packets we finish
23438 				 * all QOS packet processing before
23439 				 * calling:
23440 				 * ip_wput_ire_fragmentit->ip_wput_frag
23441 				 */
23442 
23443 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23444 					ip_process(IPP_LOCAL_OUT, &mp,
23445 					    ill_index);
23446 					if (mp == NULL) {
23447 						out_ill = (ill_t *)stq->q_ptr;
23448 						BUMP_MIB(out_ill->ill_ip_mib,
23449 						    ipIfStatsOutDiscards);
23450 						if (next_mp != NULL) {
23451 							freemsg(next_mp);
23452 							ire_refrele(ire1);
23453 						}
23454 						ire_refrele(ire);
23455 						TRACE_2(TR_FAC_IP,
23456 						    TR_IP_WPUT_IRE_END,
23457 						    "ip_wput_ire: q %p (%S)",
23458 						    q, "discard MDATA");
23459 						if (conn_outgoing_ill != NULL) {
23460 							ill_refrele(
23461 							    conn_outgoing_ill);
23462 						}
23463 						return;
23464 					}
23465 				}
23466 				if (!next_mp) {
23467 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23468 					    "ip_wput_ire_end: q %p (%S)",
23469 					    q, "last fragmentation");
23470 					ip_wput_ire_fragmentit(mp, ire,
23471 					    zoneid, ipst);
23472 					ire_refrele(ire);
23473 					if (conn_outgoing_ill != NULL)
23474 						ill_refrele(conn_outgoing_ill);
23475 					return;
23476 				}
23477 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23478 			}
23479 		}
23480 	} else {
23481 nullstq:
23482 		/* A NULL stq means the destination address is local. */
23483 		UPDATE_OB_PKT_COUNT(ire);
23484 		ire->ire_last_used_time = lbolt;
23485 		ASSERT(ire->ire_ipif != NULL);
23486 		if (!next_mp) {
23487 			/*
23488 			 * Is there an "in" and "out" for traffic local
23489 			 * to a host (loopback)?  The code in Solaris doesn't
23490 			 * explicitly draw a line in its code for in vs out,
23491 			 * so we've had to draw a line in the sand: ip_wput_ire
23492 			 * is considered to be the "output" side and
23493 			 * ip_wput_local to be the "input" side.
23494 			 */
23495 			out_ill = ire_to_ill(ire);
23496 
23497 			/*
23498 			 * DTrace this as ip:::send.  A blocked packet will
23499 			 * fire the send probe, but not the receive probe.
23500 			 */
23501 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23502 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23503 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23504 
23505 			DTRACE_PROBE4(ip4__loopback__out__start,
23506 			    ill_t *, NULL, ill_t *, out_ill,
23507 			    ipha_t *, ipha, mblk_t *, first_mp);
23508 
23509 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23510 			    ipst->ips_ipv4firewall_loopback_out,
23511 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23512 
23513 			DTRACE_PROBE1(ip4__loopback__out_end,
23514 			    mblk_t *, first_mp);
23515 
23516 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23517 			    "ip_wput_ire_end: q %p (%S)",
23518 			    q, "local address");
23519 
23520 			if (first_mp != NULL)
23521 				ip_wput_local(q, out_ill, ipha,
23522 				    first_mp, ire, 0, ire->ire_zoneid);
23523 			ire_refrele(ire);
23524 			if (conn_outgoing_ill != NULL)
23525 				ill_refrele(conn_outgoing_ill);
23526 			return;
23527 		}
23528 
23529 		out_ill = ire_to_ill(ire);
23530 
23531 		/*
23532 		 * DTrace this as ip:::send.  A blocked packet will fire the
23533 		 * send probe, but not the receive probe.
23534 		 */
23535 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23536 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23537 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23538 
23539 		DTRACE_PROBE4(ip4__loopback__out__start,
23540 		    ill_t *, NULL, ill_t *, out_ill,
23541 		    ipha_t *, ipha, mblk_t *, first_mp);
23542 
23543 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23544 		    ipst->ips_ipv4firewall_loopback_out,
23545 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23546 
23547 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23548 
23549 		if (first_mp != NULL)
23550 			ip_wput_local(q, out_ill, ipha,
23551 			    first_mp, ire, 0, ire->ire_zoneid);
23552 	}
23553 next:
23554 	/*
23555 	 * More copies going out to additional interfaces.
23556 	 * ire1 has already been held. We don't need the
23557 	 * "ire" anymore.
23558 	 */
23559 	ire_refrele(ire);
23560 	ire = ire1;
23561 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23562 	mp = next_mp;
23563 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23564 	ill = ire_to_ill(ire);
23565 	first_mp = mp;
23566 	if (ipsec_len != 0) {
23567 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23568 		mp = mp->b_cont;
23569 	}
23570 	dst = ire->ire_addr;
23571 	ipha = (ipha_t *)mp->b_rptr;
23572 	/*
23573 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23574 	 * Restore ipha_ident "no checksum" flag.
23575 	 */
23576 	src = orig_src;
23577 	ipha->ipha_ident = ip_hdr_included;
23578 	goto another;
23579 
23580 #undef	rptr
23581 #undef	Q_TO_INDEX
23582 }
23583 
23584 /*
23585  * Routine to allocate a message that is used to notify the ULP about MDT.
23586  * The caller may provide a pointer to the link-layer MDT capabilities,
23587  * or NULL if MDT is to be disabled on the stream.
23588  */
23589 mblk_t *
23590 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23591 {
23592 	mblk_t *mp;
23593 	ip_mdt_info_t *mdti;
23594 	ill_mdt_capab_t *idst;
23595 
23596 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23597 		DB_TYPE(mp) = M_CTL;
23598 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23599 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23600 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23601 		idst = &(mdti->mdt_capab);
23602 
23603 		/*
23604 		 * If the caller provides us with the capability, copy
23605 		 * it over into our notification message; otherwise
23606 		 * we zero out the capability portion.
23607 		 */
23608 		if (isrc != NULL)
23609 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23610 		else
23611 			bzero((caddr_t)idst, sizeof (*idst));
23612 	}
23613 	return (mp);
23614 }
23615 
23616 /*
23617  * Routine which determines whether MDT can be enabled on the destination
23618  * IRE and IPC combination, and if so, allocates and returns the MDT
23619  * notification mblk that may be used by ULP.  We also check if we need to
23620  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23621  * MDT usage in the past have been lifted.  This gets called during IP
23622  * and ULP binding.
23623  */
23624 mblk_t *
23625 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23626     ill_mdt_capab_t *mdt_cap)
23627 {
23628 	mblk_t *mp;
23629 	boolean_t rc = B_FALSE;
23630 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23631 
23632 	ASSERT(dst_ire != NULL);
23633 	ASSERT(connp != NULL);
23634 	ASSERT(mdt_cap != NULL);
23635 
23636 	/*
23637 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23638 	 * Multidata, which is handled in tcp_multisend().  This
23639 	 * is the reason why we do all these checks here, to ensure
23640 	 * that we don't enable Multidata for the cases which we
23641 	 * can't handle at the moment.
23642 	 */
23643 	do {
23644 		/* Only do TCP at the moment */
23645 		if (connp->conn_ulp != IPPROTO_TCP)
23646 			break;
23647 
23648 		/*
23649 		 * IPsec outbound policy present?  Note that we get here
23650 		 * after calling ipsec_conn_cache_policy() where the global
23651 		 * policy checking is performed.  conn_latch will be
23652 		 * non-NULL as long as there's a policy defined,
23653 		 * i.e. conn_out_enforce_policy may be NULL in such case
23654 		 * when the connection is non-secure, and hence we check
23655 		 * further if the latch refers to an outbound policy.
23656 		 */
23657 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23658 			break;
23659 
23660 		/* CGTP (multiroute) is enabled? */
23661 		if (dst_ire->ire_flags & RTF_MULTIRT)
23662 			break;
23663 
23664 		/* Outbound IPQoS enabled? */
23665 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23666 			/*
23667 			 * In this case, we disable MDT for this and all
23668 			 * future connections going over the interface.
23669 			 */
23670 			mdt_cap->ill_mdt_on = 0;
23671 			break;
23672 		}
23673 
23674 		/* socket option(s) present? */
23675 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23676 			break;
23677 
23678 		rc = B_TRUE;
23679 	/* CONSTCOND */
23680 	} while (0);
23681 
23682 	/* Remember the result */
23683 	connp->conn_mdt_ok = rc;
23684 
23685 	if (!rc)
23686 		return (NULL);
23687 	else if (!mdt_cap->ill_mdt_on) {
23688 		/*
23689 		 * If MDT has been previously turned off in the past, and we
23690 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23691 		 * then enable it for this interface.
23692 		 */
23693 		mdt_cap->ill_mdt_on = 1;
23694 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23695 		    "interface %s\n", ill_name));
23696 	}
23697 
23698 	/* Allocate the MDT info mblk */
23699 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23700 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23701 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23702 		return (NULL);
23703 	}
23704 	return (mp);
23705 }
23706 
23707 /*
23708  * Routine to allocate a message that is used to notify the ULP about LSO.
23709  * The caller may provide a pointer to the link-layer LSO capabilities,
23710  * or NULL if LSO is to be disabled on the stream.
23711  */
23712 mblk_t *
23713 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23714 {
23715 	mblk_t *mp;
23716 	ip_lso_info_t *lsoi;
23717 	ill_lso_capab_t *idst;
23718 
23719 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23720 		DB_TYPE(mp) = M_CTL;
23721 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23722 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23723 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23724 		idst = &(lsoi->lso_capab);
23725 
23726 		/*
23727 		 * If the caller provides us with the capability, copy
23728 		 * it over into our notification message; otherwise
23729 		 * we zero out the capability portion.
23730 		 */
23731 		if (isrc != NULL)
23732 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23733 		else
23734 			bzero((caddr_t)idst, sizeof (*idst));
23735 	}
23736 	return (mp);
23737 }
23738 
23739 /*
23740  * Routine which determines whether LSO can be enabled on the destination
23741  * IRE and IPC combination, and if so, allocates and returns the LSO
23742  * notification mblk that may be used by ULP.  We also check if we need to
23743  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23744  * LSO usage in the past have been lifted.  This gets called during IP
23745  * and ULP binding.
23746  */
23747 mblk_t *
23748 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23749     ill_lso_capab_t *lso_cap)
23750 {
23751 	mblk_t *mp;
23752 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23753 
23754 	ASSERT(dst_ire != NULL);
23755 	ASSERT(connp != NULL);
23756 	ASSERT(lso_cap != NULL);
23757 
23758 	connp->conn_lso_ok = B_TRUE;
23759 
23760 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23761 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23762 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23763 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23764 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23765 		connp->conn_lso_ok = B_FALSE;
23766 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23767 			/*
23768 			 * Disable LSO for this and all future connections going
23769 			 * over the interface.
23770 			 */
23771 			lso_cap->ill_lso_on = 0;
23772 		}
23773 	}
23774 
23775 	if (!connp->conn_lso_ok)
23776 		return (NULL);
23777 	else if (!lso_cap->ill_lso_on) {
23778 		/*
23779 		 * If LSO has been previously turned off in the past, and we
23780 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23781 		 * then enable it for this interface.
23782 		 */
23783 		lso_cap->ill_lso_on = 1;
23784 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23785 		    ill_name));
23786 	}
23787 
23788 	/* Allocate the LSO info mblk */
23789 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23790 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23791 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23792 
23793 	return (mp);
23794 }
23795 
23796 /*
23797  * Create destination address attribute, and fill it with the physical
23798  * destination address and SAP taken from the template DL_UNITDATA_REQ
23799  * message block.
23800  */
23801 boolean_t
23802 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23803 {
23804 	dl_unitdata_req_t *dlurp;
23805 	pattr_t *pa;
23806 	pattrinfo_t pa_info;
23807 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23808 	uint_t das_len, das_off;
23809 
23810 	ASSERT(dlmp != NULL);
23811 
23812 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23813 	das_len = dlurp->dl_dest_addr_length;
23814 	das_off = dlurp->dl_dest_addr_offset;
23815 
23816 	pa_info.type = PATTR_DSTADDRSAP;
23817 	pa_info.len = sizeof (**das) + das_len - 1;
23818 
23819 	/* create and associate the attribute */
23820 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23821 	if (pa != NULL) {
23822 		ASSERT(*das != NULL);
23823 		(*das)->addr_is_group = 0;
23824 		(*das)->addr_len = (uint8_t)das_len;
23825 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23826 	}
23827 
23828 	return (pa != NULL);
23829 }
23830 
23831 /*
23832  * Create hardware checksum attribute and fill it with the values passed.
23833  */
23834 boolean_t
23835 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23836     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23837 {
23838 	pattr_t *pa;
23839 	pattrinfo_t pa_info;
23840 
23841 	ASSERT(mmd != NULL);
23842 
23843 	pa_info.type = PATTR_HCKSUM;
23844 	pa_info.len = sizeof (pattr_hcksum_t);
23845 
23846 	/* create and associate the attribute */
23847 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23848 	if (pa != NULL) {
23849 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23850 
23851 		hck->hcksum_start_offset = start_offset;
23852 		hck->hcksum_stuff_offset = stuff_offset;
23853 		hck->hcksum_end_offset = end_offset;
23854 		hck->hcksum_flags = flags;
23855 	}
23856 	return (pa != NULL);
23857 }
23858 
23859 /*
23860  * Create zerocopy attribute and fill it with the specified flags
23861  */
23862 boolean_t
23863 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23864 {
23865 	pattr_t *pa;
23866 	pattrinfo_t pa_info;
23867 
23868 	ASSERT(mmd != NULL);
23869 	pa_info.type = PATTR_ZCOPY;
23870 	pa_info.len = sizeof (pattr_zcopy_t);
23871 
23872 	/* create and associate the attribute */
23873 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23874 	if (pa != NULL) {
23875 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23876 
23877 		zcopy->zcopy_flags = flags;
23878 	}
23879 	return (pa != NULL);
23880 }
23881 
23882 /*
23883  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23884  * block chain. We could rewrite to handle arbitrary message block chains but
23885  * that would make the code complicated and slow. Right now there three
23886  * restrictions:
23887  *
23888  *   1. The first message block must contain the complete IP header and
23889  *	at least 1 byte of payload data.
23890  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23891  *	so that we can use a single Multidata message.
23892  *   3. No frag must be distributed over two or more message blocks so
23893  *	that we don't need more than two packet descriptors per frag.
23894  *
23895  * The above restrictions allow us to support userland applications (which
23896  * will send down a single message block) and NFS over UDP (which will
23897  * send down a chain of at most three message blocks).
23898  *
23899  * We also don't use MDT for payloads with less than or equal to
23900  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23901  */
23902 boolean_t
23903 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23904 {
23905 	int	blocks;
23906 	ssize_t	total, missing, size;
23907 
23908 	ASSERT(mp != NULL);
23909 	ASSERT(hdr_len > 0);
23910 
23911 	size = MBLKL(mp) - hdr_len;
23912 	if (size <= 0)
23913 		return (B_FALSE);
23914 
23915 	/* The first mblk contains the header and some payload. */
23916 	blocks = 1;
23917 	total = size;
23918 	size %= len;
23919 	missing = (size == 0) ? 0 : (len - size);
23920 	mp = mp->b_cont;
23921 
23922 	while (mp != NULL) {
23923 		/*
23924 		 * Give up if we encounter a zero length message block.
23925 		 * In practice, this should rarely happen and therefore
23926 		 * not worth the trouble of freeing and re-linking the
23927 		 * mblk from the chain to handle such case.
23928 		 */
23929 		if ((size = MBLKL(mp)) == 0)
23930 			return (B_FALSE);
23931 
23932 		/* Too many payload buffers for a single Multidata message? */
23933 		if (++blocks > MULTIDATA_MAX_PBUFS)
23934 			return (B_FALSE);
23935 
23936 		total += size;
23937 		/* Is a frag distributed over two or more message blocks? */
23938 		if (missing > size)
23939 			return (B_FALSE);
23940 		size -= missing;
23941 
23942 		size %= len;
23943 		missing = (size == 0) ? 0 : (len - size);
23944 
23945 		mp = mp->b_cont;
23946 	}
23947 
23948 	return (total > ip_wput_frag_mdt_min);
23949 }
23950 
23951 /*
23952  * Outbound IPv4 fragmentation routine using MDT.
23953  */
23954 static void
23955 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23956     uint32_t frag_flag, int offset)
23957 {
23958 	ipha_t		*ipha_orig;
23959 	int		i1, ip_data_end;
23960 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23961 	mblk_t		*hdr_mp, *md_mp = NULL;
23962 	unsigned char	*hdr_ptr, *pld_ptr;
23963 	multidata_t	*mmd;
23964 	ip_pdescinfo_t	pdi;
23965 	ill_t		*ill;
23966 	ip_stack_t	*ipst = ire->ire_ipst;
23967 
23968 	ASSERT(DB_TYPE(mp) == M_DATA);
23969 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23970 
23971 	ill = ire_to_ill(ire);
23972 	ASSERT(ill != NULL);
23973 
23974 	ipha_orig = (ipha_t *)mp->b_rptr;
23975 	mp->b_rptr += sizeof (ipha_t);
23976 
23977 	/* Calculate how many packets we will send out */
23978 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23979 	pkts = (i1 + len - 1) / len;
23980 	ASSERT(pkts > 1);
23981 
23982 	/* Allocate a message block which will hold all the IP Headers. */
23983 	wroff = ipst->ips_ip_wroff_extra;
23984 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23985 
23986 	i1 = pkts * hdr_chunk_len;
23987 	/*
23988 	 * Create the header buffer, Multidata and destination address
23989 	 * and SAP attribute that should be associated with it.
23990 	 */
23991 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23992 	    ((hdr_mp->b_wptr += i1),
23993 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23994 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23995 		freemsg(mp);
23996 		if (md_mp == NULL) {
23997 			freemsg(hdr_mp);
23998 		} else {
23999 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24000 			freemsg(md_mp);
24001 		}
24002 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24003 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24004 		return;
24005 	}
24006 	IP_STAT(ipst, ip_frag_mdt_allocd);
24007 
24008 	/*
24009 	 * Add a payload buffer to the Multidata; this operation must not
24010 	 * fail, or otherwise our logic in this routine is broken.  There
24011 	 * is no memory allocation done by the routine, so any returned
24012 	 * failure simply tells us that we've done something wrong.
24013 	 *
24014 	 * A failure tells us that either we're adding the same payload
24015 	 * buffer more than once, or we're trying to add more buffers than
24016 	 * allowed.  None of the above cases should happen, and we panic
24017 	 * because either there's horrible heap corruption, and/or
24018 	 * programming mistake.
24019 	 */
24020 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24021 		goto pbuf_panic;
24022 
24023 	hdr_ptr = hdr_mp->b_rptr;
24024 	pld_ptr = mp->b_rptr;
24025 
24026 	/* Establish the ending byte offset, based on the starting offset. */
24027 	offset <<= 3;
24028 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24029 	    IP_SIMPLE_HDR_LENGTH;
24030 
24031 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24032 
24033 	while (pld_ptr < mp->b_wptr) {
24034 		ipha_t		*ipha;
24035 		uint16_t	offset_and_flags;
24036 		uint16_t	ip_len;
24037 		int		error;
24038 
24039 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24040 		ipha = (ipha_t *)(hdr_ptr + wroff);
24041 		ASSERT(OK_32PTR(ipha));
24042 		*ipha = *ipha_orig;
24043 
24044 		if (ip_data_end - offset > len) {
24045 			offset_and_flags = IPH_MF;
24046 		} else {
24047 			/*
24048 			 * Last frag. Set len to the length of this last piece.
24049 			 */
24050 			len = ip_data_end - offset;
24051 			/* A frag of a frag might have IPH_MF non-zero */
24052 			offset_and_flags =
24053 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24054 			    IPH_MF;
24055 		}
24056 		offset_and_flags |= (uint16_t)(offset >> 3);
24057 		offset_and_flags |= (uint16_t)frag_flag;
24058 		/* Store the offset and flags in the IP header. */
24059 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24060 
24061 		/* Store the length in the IP header. */
24062 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24063 		ipha->ipha_length = htons(ip_len);
24064 
24065 		/*
24066 		 * Set the IP header checksum.  Note that mp is just
24067 		 * the header, so this is easy to pass to ip_csum.
24068 		 */
24069 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24070 
24071 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24072 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24073 		    NULL, int, 0);
24074 
24075 		/*
24076 		 * Record offset and size of header and data of the next packet
24077 		 * in the multidata message.
24078 		 */
24079 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24080 		PDESC_PLD_INIT(&pdi);
24081 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24082 		ASSERT(i1 > 0);
24083 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24084 		if (i1 == len) {
24085 			pld_ptr += len;
24086 		} else {
24087 			i1 = len - i1;
24088 			mp = mp->b_cont;
24089 			ASSERT(mp != NULL);
24090 			ASSERT(MBLKL(mp) >= i1);
24091 			/*
24092 			 * Attach the next payload message block to the
24093 			 * multidata message.
24094 			 */
24095 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24096 				goto pbuf_panic;
24097 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24098 			pld_ptr = mp->b_rptr + i1;
24099 		}
24100 
24101 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24102 		    KM_NOSLEEP)) == NULL) {
24103 			/*
24104 			 * Any failure other than ENOMEM indicates that we
24105 			 * have passed in invalid pdesc info or parameters
24106 			 * to mmd_addpdesc, which must not happen.
24107 			 *
24108 			 * EINVAL is a result of failure on boundary checks
24109 			 * against the pdesc info contents.  It should not
24110 			 * happen, and we panic because either there's
24111 			 * horrible heap corruption, and/or programming
24112 			 * mistake.
24113 			 */
24114 			if (error != ENOMEM) {
24115 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24116 				    "pdesc logic error detected for "
24117 				    "mmd %p pinfo %p (%d)\n",
24118 				    (void *)mmd, (void *)&pdi, error);
24119 				/* NOTREACHED */
24120 			}
24121 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24122 			/* Free unattached payload message blocks as well */
24123 			md_mp->b_cont = mp->b_cont;
24124 			goto free_mmd;
24125 		}
24126 
24127 		/* Advance fragment offset. */
24128 		offset += len;
24129 
24130 		/* Advance to location for next header in the buffer. */
24131 		hdr_ptr += hdr_chunk_len;
24132 
24133 		/* Did we reach the next payload message block? */
24134 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24135 			mp = mp->b_cont;
24136 			/*
24137 			 * Attach the next message block with payload
24138 			 * data to the multidata message.
24139 			 */
24140 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24141 				goto pbuf_panic;
24142 			pld_ptr = mp->b_rptr;
24143 		}
24144 	}
24145 
24146 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24147 	ASSERT(mp->b_wptr == pld_ptr);
24148 
24149 	/* Update IP statistics */
24150 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24151 
24152 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24153 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24154 
24155 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24156 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24157 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24158 
24159 	if (pkt_type == OB_PKT) {
24160 		ire->ire_ob_pkt_count += pkts;
24161 		if (ire->ire_ipif != NULL)
24162 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24163 	} else {
24164 		/* The type is IB_PKT in the forwarding path. */
24165 		ire->ire_ib_pkt_count += pkts;
24166 		ASSERT(!IRE_IS_LOCAL(ire));
24167 		if (ire->ire_type & IRE_BROADCAST) {
24168 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24169 		} else {
24170 			UPDATE_MIB(ill->ill_ip_mib,
24171 			    ipIfStatsHCOutForwDatagrams, pkts);
24172 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24173 		}
24174 	}
24175 	ire->ire_last_used_time = lbolt;
24176 	/* Send it down */
24177 	putnext(ire->ire_stq, md_mp);
24178 	return;
24179 
24180 pbuf_panic:
24181 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24182 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24183 	    pbuf_idx);
24184 	/* NOTREACHED */
24185 }
24186 
24187 /*
24188  * Outbound IP fragmentation routine.
24189  *
24190  * NOTE : This routine does not ire_refrele the ire that is passed in
24191  * as the argument.
24192  */
24193 static void
24194 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24195     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24196 {
24197 	int		i1;
24198 	mblk_t		*ll_hdr_mp;
24199 	int 		ll_hdr_len;
24200 	int		hdr_len;
24201 	mblk_t		*hdr_mp;
24202 	ipha_t		*ipha;
24203 	int		ip_data_end;
24204 	int		len;
24205 	mblk_t		*mp = mp_orig, *mp1;
24206 	int		offset;
24207 	queue_t		*q;
24208 	uint32_t	v_hlen_tos_len;
24209 	mblk_t		*first_mp;
24210 	boolean_t	mctl_present;
24211 	ill_t		*ill;
24212 	ill_t		*out_ill;
24213 	mblk_t		*xmit_mp;
24214 	mblk_t		*carve_mp;
24215 	ire_t		*ire1 = NULL;
24216 	ire_t		*save_ire = NULL;
24217 	mblk_t  	*next_mp = NULL;
24218 	boolean_t	last_frag = B_FALSE;
24219 	boolean_t	multirt_send = B_FALSE;
24220 	ire_t		*first_ire = NULL;
24221 	irb_t		*irb = NULL;
24222 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24223 
24224 	ill = ire_to_ill(ire);
24225 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24226 
24227 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24228 
24229 	if (max_frag == 0) {
24230 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24231 		    " -  dropping packet\n"));
24232 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24233 		freemsg(mp);
24234 		return;
24235 	}
24236 
24237 	/*
24238 	 * IPsec does not allow hw accelerated packets to be fragmented
24239 	 * This check is made in ip_wput_ipsec_out prior to coming here
24240 	 * via ip_wput_ire_fragmentit.
24241 	 *
24242 	 * If at this point we have an ire whose ARP request has not
24243 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24244 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24245 	 * This packet and all fragmentable packets for this ire will
24246 	 * continue to get dropped while ire_nce->nce_state remains in
24247 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24248 	 * ND_REACHABLE, all subsquent large packets for this ire will
24249 	 * get fragemented and sent out by this function.
24250 	 */
24251 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24252 		/* If nce_state is ND_INITIAL, trigger ARP query */
24253 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24254 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24255 		    " -  dropping packet\n"));
24256 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24257 		freemsg(mp);
24258 		return;
24259 	}
24260 
24261 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24262 	    "ip_wput_frag_start:");
24263 
24264 	if (mp->b_datap->db_type == M_CTL) {
24265 		first_mp = mp;
24266 		mp_orig = mp = mp->b_cont;
24267 		mctl_present = B_TRUE;
24268 	} else {
24269 		first_mp = mp;
24270 		mctl_present = B_FALSE;
24271 	}
24272 
24273 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24274 	ipha = (ipha_t *)mp->b_rptr;
24275 
24276 	/*
24277 	 * If the Don't Fragment flag is on, generate an ICMP destination
24278 	 * unreachable, fragmentation needed.
24279 	 */
24280 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24281 	if (offset & IPH_DF) {
24282 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24283 		if (is_system_labeled()) {
24284 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24285 			    ire->ire_max_frag - max_frag, AF_INET);
24286 		}
24287 		/*
24288 		 * Need to compute hdr checksum if called from ip_wput_ire.
24289 		 * Note that ip_rput_forward verifies the checksum before
24290 		 * calling this routine so in that case this is a noop.
24291 		 */
24292 		ipha->ipha_hdr_checksum = 0;
24293 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24294 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24295 		    ipst);
24296 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24297 		    "ip_wput_frag_end:(%S)",
24298 		    "don't fragment");
24299 		return;
24300 	}
24301 	/*
24302 	 * Labeled systems adjust max_frag if they add a label
24303 	 * to send the correct path mtu.  We need the real mtu since we
24304 	 * are fragmenting the packet after label adjustment.
24305 	 */
24306 	if (is_system_labeled())
24307 		max_frag = ire->ire_max_frag;
24308 	if (mctl_present)
24309 		freeb(first_mp);
24310 	/*
24311 	 * Establish the starting offset.  May not be zero if we are fragging
24312 	 * a fragment that is being forwarded.
24313 	 */
24314 	offset = offset & IPH_OFFSET;
24315 
24316 	/* TODO why is this test needed? */
24317 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24318 	if (((max_frag - LENGTH) & ~7) < 8) {
24319 		/* TODO: notify ulp somehow */
24320 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24321 		freemsg(mp);
24322 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24323 		    "ip_wput_frag_end:(%S)",
24324 		    "len < 8");
24325 		return;
24326 	}
24327 
24328 	hdr_len = (V_HLEN & 0xF) << 2;
24329 
24330 	ipha->ipha_hdr_checksum = 0;
24331 
24332 	/*
24333 	 * Establish the number of bytes maximum per frag, after putting
24334 	 * in the header.
24335 	 */
24336 	len = (max_frag - hdr_len) & ~7;
24337 
24338 	/* Check if we can use MDT to send out the frags. */
24339 	ASSERT(!IRE_IS_LOCAL(ire));
24340 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24341 	    ipst->ips_ip_multidata_outbound &&
24342 	    !(ire->ire_flags & RTF_MULTIRT) &&
24343 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24344 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24345 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24346 		ASSERT(ill->ill_mdt_capab != NULL);
24347 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24348 			/*
24349 			 * If MDT has been previously turned off in the past,
24350 			 * and we currently can do MDT (due to IPQoS policy
24351 			 * removal, etc.) then enable it for this interface.
24352 			 */
24353 			ill->ill_mdt_capab->ill_mdt_on = 1;
24354 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24355 			    ill->ill_name));
24356 		}
24357 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24358 		    offset);
24359 		return;
24360 	}
24361 
24362 	/* Get a copy of the header for the trailing frags */
24363 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24364 	if (!hdr_mp) {
24365 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24366 		freemsg(mp);
24367 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24368 		    "ip_wput_frag_end:(%S)",
24369 		    "couldn't copy hdr");
24370 		return;
24371 	}
24372 	if (DB_CRED(mp) != NULL)
24373 		mblk_setcred(hdr_mp, DB_CRED(mp));
24374 
24375 	/* Store the starting offset, with the MoreFrags flag. */
24376 	i1 = offset | IPH_MF | frag_flag;
24377 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24378 
24379 	/* Establish the ending byte offset, based on the starting offset. */
24380 	offset <<= 3;
24381 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24382 
24383 	/* Store the length of the first fragment in the IP header. */
24384 	i1 = len + hdr_len;
24385 	ASSERT(i1 <= IP_MAXPACKET);
24386 	ipha->ipha_length = htons((uint16_t)i1);
24387 
24388 	/*
24389 	 * Compute the IP header checksum for the first frag.  We have to
24390 	 * watch out that we stop at the end of the header.
24391 	 */
24392 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24393 
24394 	/*
24395 	 * Now carve off the first frag.  Note that this will include the
24396 	 * original IP header.
24397 	 */
24398 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24399 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24400 		freeb(hdr_mp);
24401 		freemsg(mp_orig);
24402 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24403 		    "ip_wput_frag_end:(%S)",
24404 		    "couldn't carve first");
24405 		return;
24406 	}
24407 
24408 	/*
24409 	 * Multirouting case. Each fragment is replicated
24410 	 * via all non-condemned RTF_MULTIRT routes
24411 	 * currently resolved.
24412 	 * We ensure that first_ire is the first RTF_MULTIRT
24413 	 * ire in the bucket.
24414 	 */
24415 	if (ire->ire_flags & RTF_MULTIRT) {
24416 		irb = ire->ire_bucket;
24417 		ASSERT(irb != NULL);
24418 
24419 		multirt_send = B_TRUE;
24420 
24421 		/* Make sure we do not omit any multiroute ire. */
24422 		IRB_REFHOLD(irb);
24423 		for (first_ire = irb->irb_ire;
24424 		    first_ire != NULL;
24425 		    first_ire = first_ire->ire_next) {
24426 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24427 			    (first_ire->ire_addr == ire->ire_addr) &&
24428 			    !(first_ire->ire_marks &
24429 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24430 				break;
24431 			}
24432 		}
24433 
24434 		if (first_ire != NULL) {
24435 			if (first_ire != ire) {
24436 				IRE_REFHOLD(first_ire);
24437 				/*
24438 				 * Do not release the ire passed in
24439 				 * as the argument.
24440 				 */
24441 				ire = first_ire;
24442 			} else {
24443 				first_ire = NULL;
24444 			}
24445 		}
24446 		IRB_REFRELE(irb);
24447 
24448 		/*
24449 		 * Save the first ire; we will need to restore it
24450 		 * for the trailing frags.
24451 		 * We REFHOLD save_ire, as each iterated ire will be
24452 		 * REFRELEd.
24453 		 */
24454 		save_ire = ire;
24455 		IRE_REFHOLD(save_ire);
24456 	}
24457 
24458 	/*
24459 	 * First fragment emission loop.
24460 	 * In most cases, the emission loop below is entered only
24461 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24462 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24463 	 * bucket, and send the fragment through all crossed
24464 	 * RTF_MULTIRT routes.
24465 	 */
24466 	do {
24467 		if (ire->ire_flags & RTF_MULTIRT) {
24468 			/*
24469 			 * We are in a multiple send case, need to get
24470 			 * the next ire and make a copy of the packet.
24471 			 * ire1 holds here the next ire to process in the
24472 			 * bucket. If multirouting is expected,
24473 			 * any non-RTF_MULTIRT ire that has the
24474 			 * right destination address is ignored.
24475 			 *
24476 			 * We have to take into account the MTU of
24477 			 * each walked ire. max_frag is set by the
24478 			 * the caller and generally refers to
24479 			 * the primary ire entry. Here we ensure that
24480 			 * no route with a lower MTU will be used, as
24481 			 * fragments are carved once for all ires,
24482 			 * then replicated.
24483 			 */
24484 			ASSERT(irb != NULL);
24485 			IRB_REFHOLD(irb);
24486 			for (ire1 = ire->ire_next;
24487 			    ire1 != NULL;
24488 			    ire1 = ire1->ire_next) {
24489 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24490 					continue;
24491 				if (ire1->ire_addr != ire->ire_addr)
24492 					continue;
24493 				if (ire1->ire_marks &
24494 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24495 					continue;
24496 				/*
24497 				 * Ensure we do not exceed the MTU
24498 				 * of the next route.
24499 				 */
24500 				if (ire1->ire_max_frag < max_frag) {
24501 					ip_multirt_bad_mtu(ire1, max_frag);
24502 					continue;
24503 				}
24504 
24505 				/* Got one. */
24506 				IRE_REFHOLD(ire1);
24507 				break;
24508 			}
24509 			IRB_REFRELE(irb);
24510 
24511 			if (ire1 != NULL) {
24512 				next_mp = copyb(mp);
24513 				if ((next_mp == NULL) ||
24514 				    ((mp->b_cont != NULL) &&
24515 				    ((next_mp->b_cont =
24516 				    dupmsg(mp->b_cont)) == NULL))) {
24517 					freemsg(next_mp);
24518 					next_mp = NULL;
24519 					ire_refrele(ire1);
24520 					ire1 = NULL;
24521 				}
24522 			}
24523 
24524 			/* Last multiroute ire; don't loop anymore. */
24525 			if (ire1 == NULL) {
24526 				multirt_send = B_FALSE;
24527 			}
24528 		}
24529 
24530 		ll_hdr_len = 0;
24531 		LOCK_IRE_FP_MP(ire);
24532 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24533 		if (ll_hdr_mp != NULL) {
24534 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24535 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24536 		} else {
24537 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24538 		}
24539 
24540 		/* If there is a transmit header, get a copy for this frag. */
24541 		/*
24542 		 * TODO: should check db_ref before calling ip_carve_mp since
24543 		 * it might give us a dup.
24544 		 */
24545 		if (!ll_hdr_mp) {
24546 			/* No xmit header. */
24547 			xmit_mp = mp;
24548 
24549 		/* We have a link-layer header that can fit in our mblk. */
24550 		} else if (mp->b_datap->db_ref == 1 &&
24551 		    ll_hdr_len != 0 &&
24552 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24553 			/* M_DATA fastpath */
24554 			mp->b_rptr -= ll_hdr_len;
24555 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24556 			xmit_mp = mp;
24557 
24558 		/* Corner case if copyb has failed */
24559 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24560 			UNLOCK_IRE_FP_MP(ire);
24561 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24562 			freeb(hdr_mp);
24563 			freemsg(mp);
24564 			freemsg(mp_orig);
24565 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24566 			    "ip_wput_frag_end:(%S)",
24567 			    "discard");
24568 
24569 			if (multirt_send) {
24570 				ASSERT(ire1);
24571 				ASSERT(next_mp);
24572 
24573 				freemsg(next_mp);
24574 				ire_refrele(ire1);
24575 			}
24576 			if (save_ire != NULL)
24577 				IRE_REFRELE(save_ire);
24578 
24579 			if (first_ire != NULL)
24580 				ire_refrele(first_ire);
24581 			return;
24582 
24583 		/*
24584 		 * Case of res_mp OR the fastpath mp can't fit
24585 		 * in the mblk
24586 		 */
24587 		} else {
24588 			xmit_mp->b_cont = mp;
24589 			if (DB_CRED(mp) != NULL)
24590 				mblk_setcred(xmit_mp, DB_CRED(mp));
24591 			/*
24592 			 * Get priority marking, if any.
24593 			 * We propagate the CoS marking from the
24594 			 * original packet that went to QoS processing
24595 			 * in ip_wput_ire to the newly carved mp.
24596 			 */
24597 			if (DB_TYPE(xmit_mp) == M_DATA)
24598 				xmit_mp->b_band = mp->b_band;
24599 		}
24600 		UNLOCK_IRE_FP_MP(ire);
24601 
24602 		q = ire->ire_stq;
24603 		out_ill = (ill_t *)q->q_ptr;
24604 
24605 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24606 
24607 		DTRACE_PROBE4(ip4__physical__out__start,
24608 		    ill_t *, NULL, ill_t *, out_ill,
24609 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24610 
24611 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24612 		    ipst->ips_ipv4firewall_physical_out,
24613 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24614 
24615 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24616 
24617 		if (xmit_mp != NULL) {
24618 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24619 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24620 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24621 
24622 			putnext(q, xmit_mp);
24623 
24624 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24625 			UPDATE_MIB(out_ill->ill_ip_mib,
24626 			    ipIfStatsHCOutOctets, i1);
24627 
24628 			if (pkt_type != OB_PKT) {
24629 				/*
24630 				 * Update the packet count and MIB stats
24631 				 * of trailing RTF_MULTIRT ires.
24632 				 */
24633 				UPDATE_OB_PKT_COUNT(ire);
24634 				BUMP_MIB(out_ill->ill_ip_mib,
24635 				    ipIfStatsOutFragReqds);
24636 			}
24637 		}
24638 
24639 		if (multirt_send) {
24640 			/*
24641 			 * We are in a multiple send case; look for
24642 			 * the next ire and re-enter the loop.
24643 			 */
24644 			ASSERT(ire1);
24645 			ASSERT(next_mp);
24646 			/* REFRELE the current ire before looping */
24647 			ire_refrele(ire);
24648 			ire = ire1;
24649 			ire1 = NULL;
24650 			mp = next_mp;
24651 			next_mp = NULL;
24652 		}
24653 	} while (multirt_send);
24654 
24655 	ASSERT(ire1 == NULL);
24656 
24657 	/* Restore the original ire; we need it for the trailing frags */
24658 	if (save_ire != NULL) {
24659 		/* REFRELE the last iterated ire */
24660 		ire_refrele(ire);
24661 		/* save_ire has been REFHOLDed */
24662 		ire = save_ire;
24663 		save_ire = NULL;
24664 		q = ire->ire_stq;
24665 	}
24666 
24667 	if (pkt_type == OB_PKT) {
24668 		UPDATE_OB_PKT_COUNT(ire);
24669 	} else {
24670 		out_ill = (ill_t *)q->q_ptr;
24671 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24672 		UPDATE_IB_PKT_COUNT(ire);
24673 	}
24674 
24675 	/* Advance the offset to the second frag starting point. */
24676 	offset += len;
24677 	/*
24678 	 * Update hdr_len from the copied header - there might be less options
24679 	 * in the later fragments.
24680 	 */
24681 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24682 	/* Loop until done. */
24683 	for (;;) {
24684 		uint16_t	offset_and_flags;
24685 		uint16_t	ip_len;
24686 
24687 		if (ip_data_end - offset > len) {
24688 			/*
24689 			 * Carve off the appropriate amount from the original
24690 			 * datagram.
24691 			 */
24692 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24693 				mp = NULL;
24694 				break;
24695 			}
24696 			/*
24697 			 * More frags after this one.  Get another copy
24698 			 * of the header.
24699 			 */
24700 			if (carve_mp->b_datap->db_ref == 1 &&
24701 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24702 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24703 				/* Inline IP header */
24704 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24705 				    hdr_mp->b_rptr;
24706 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24707 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24708 				mp = carve_mp;
24709 			} else {
24710 				if (!(mp = copyb(hdr_mp))) {
24711 					freemsg(carve_mp);
24712 					break;
24713 				}
24714 				/* Get priority marking, if any. */
24715 				mp->b_band = carve_mp->b_band;
24716 				mp->b_cont = carve_mp;
24717 			}
24718 			ipha = (ipha_t *)mp->b_rptr;
24719 			offset_and_flags = IPH_MF;
24720 		} else {
24721 			/*
24722 			 * Last frag.  Consume the header. Set len to
24723 			 * the length of this last piece.
24724 			 */
24725 			len = ip_data_end - offset;
24726 
24727 			/*
24728 			 * Carve off the appropriate amount from the original
24729 			 * datagram.
24730 			 */
24731 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24732 				mp = NULL;
24733 				break;
24734 			}
24735 			if (carve_mp->b_datap->db_ref == 1 &&
24736 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24737 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24738 				/* Inline IP header */
24739 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24740 				    hdr_mp->b_rptr;
24741 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24742 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24743 				mp = carve_mp;
24744 				freeb(hdr_mp);
24745 				hdr_mp = mp;
24746 			} else {
24747 				mp = hdr_mp;
24748 				/* Get priority marking, if any. */
24749 				mp->b_band = carve_mp->b_band;
24750 				mp->b_cont = carve_mp;
24751 			}
24752 			ipha = (ipha_t *)mp->b_rptr;
24753 			/* A frag of a frag might have IPH_MF non-zero */
24754 			offset_and_flags =
24755 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24756 			    IPH_MF;
24757 		}
24758 		offset_and_flags |= (uint16_t)(offset >> 3);
24759 		offset_and_flags |= (uint16_t)frag_flag;
24760 		/* Store the offset and flags in the IP header. */
24761 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24762 
24763 		/* Store the length in the IP header. */
24764 		ip_len = (uint16_t)(len + hdr_len);
24765 		ipha->ipha_length = htons(ip_len);
24766 
24767 		/*
24768 		 * Set the IP header checksum.	Note that mp is just
24769 		 * the header, so this is easy to pass to ip_csum.
24770 		 */
24771 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24772 
24773 		/* Attach a transmit header, if any, and ship it. */
24774 		if (pkt_type == OB_PKT) {
24775 			UPDATE_OB_PKT_COUNT(ire);
24776 		} else {
24777 			out_ill = (ill_t *)q->q_ptr;
24778 			BUMP_MIB(out_ill->ill_ip_mib,
24779 			    ipIfStatsHCOutForwDatagrams);
24780 			UPDATE_IB_PKT_COUNT(ire);
24781 		}
24782 
24783 		if (ire->ire_flags & RTF_MULTIRT) {
24784 			irb = ire->ire_bucket;
24785 			ASSERT(irb != NULL);
24786 
24787 			multirt_send = B_TRUE;
24788 
24789 			/*
24790 			 * Save the original ire; we will need to restore it
24791 			 * for the tailing frags.
24792 			 */
24793 			save_ire = ire;
24794 			IRE_REFHOLD(save_ire);
24795 		}
24796 		/*
24797 		 * Emission loop for this fragment, similar
24798 		 * to what is done for the first fragment.
24799 		 */
24800 		do {
24801 			if (multirt_send) {
24802 				/*
24803 				 * We are in a multiple send case, need to get
24804 				 * the next ire and make a copy of the packet.
24805 				 */
24806 				ASSERT(irb != NULL);
24807 				IRB_REFHOLD(irb);
24808 				for (ire1 = ire->ire_next;
24809 				    ire1 != NULL;
24810 				    ire1 = ire1->ire_next) {
24811 					if (!(ire1->ire_flags & RTF_MULTIRT))
24812 						continue;
24813 					if (ire1->ire_addr != ire->ire_addr)
24814 						continue;
24815 					if (ire1->ire_marks &
24816 					    (IRE_MARK_CONDEMNED|
24817 					    IRE_MARK_HIDDEN)) {
24818 						continue;
24819 					}
24820 					/*
24821 					 * Ensure we do not exceed the MTU
24822 					 * of the next route.
24823 					 */
24824 					if (ire1->ire_max_frag < max_frag) {
24825 						ip_multirt_bad_mtu(ire1,
24826 						    max_frag);
24827 						continue;
24828 					}
24829 
24830 					/* Got one. */
24831 					IRE_REFHOLD(ire1);
24832 					break;
24833 				}
24834 				IRB_REFRELE(irb);
24835 
24836 				if (ire1 != NULL) {
24837 					next_mp = copyb(mp);
24838 					if ((next_mp == NULL) ||
24839 					    ((mp->b_cont != NULL) &&
24840 					    ((next_mp->b_cont =
24841 					    dupmsg(mp->b_cont)) == NULL))) {
24842 						freemsg(next_mp);
24843 						next_mp = NULL;
24844 						ire_refrele(ire1);
24845 						ire1 = NULL;
24846 					}
24847 				}
24848 
24849 				/* Last multiroute ire; don't loop anymore. */
24850 				if (ire1 == NULL) {
24851 					multirt_send = B_FALSE;
24852 				}
24853 			}
24854 
24855 			/* Update transmit header */
24856 			ll_hdr_len = 0;
24857 			LOCK_IRE_FP_MP(ire);
24858 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24859 			if (ll_hdr_mp != NULL) {
24860 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24861 				ll_hdr_len = MBLKL(ll_hdr_mp);
24862 			} else {
24863 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24864 			}
24865 
24866 			if (!ll_hdr_mp) {
24867 				xmit_mp = mp;
24868 
24869 			/*
24870 			 * We have link-layer header that can fit in
24871 			 * our mblk.
24872 			 */
24873 			} else if (mp->b_datap->db_ref == 1 &&
24874 			    ll_hdr_len != 0 &&
24875 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24876 				/* M_DATA fastpath */
24877 				mp->b_rptr -= ll_hdr_len;
24878 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24879 				    ll_hdr_len);
24880 				xmit_mp = mp;
24881 
24882 			/*
24883 			 * Case of res_mp OR the fastpath mp can't fit
24884 			 * in the mblk
24885 			 */
24886 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24887 				xmit_mp->b_cont = mp;
24888 				if (DB_CRED(mp) != NULL)
24889 					mblk_setcred(xmit_mp, DB_CRED(mp));
24890 				/* Get priority marking, if any. */
24891 				if (DB_TYPE(xmit_mp) == M_DATA)
24892 					xmit_mp->b_band = mp->b_band;
24893 
24894 			/* Corner case if copyb failed */
24895 			} else {
24896 				/*
24897 				 * Exit both the replication and
24898 				 * fragmentation loops.
24899 				 */
24900 				UNLOCK_IRE_FP_MP(ire);
24901 				goto drop_pkt;
24902 			}
24903 			UNLOCK_IRE_FP_MP(ire);
24904 
24905 			mp1 = mp;
24906 			out_ill = (ill_t *)q->q_ptr;
24907 
24908 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24909 
24910 			DTRACE_PROBE4(ip4__physical__out__start,
24911 			    ill_t *, NULL, ill_t *, out_ill,
24912 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24913 
24914 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24915 			    ipst->ips_ipv4firewall_physical_out,
24916 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24917 
24918 			DTRACE_PROBE1(ip4__physical__out__end,
24919 			    mblk_t *, xmit_mp);
24920 
24921 			if (mp != mp1 && hdr_mp == mp1)
24922 				hdr_mp = mp;
24923 			if (mp != mp1 && mp_orig == mp1)
24924 				mp_orig = mp;
24925 
24926 			if (xmit_mp != NULL) {
24927 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24928 				    NULL, void_ip_t *, ipha,
24929 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24930 				    ipha, ip6_t *, NULL, int, 0);
24931 
24932 				putnext(q, xmit_mp);
24933 
24934 				BUMP_MIB(out_ill->ill_ip_mib,
24935 				    ipIfStatsHCOutTransmits);
24936 				UPDATE_MIB(out_ill->ill_ip_mib,
24937 				    ipIfStatsHCOutOctets, ip_len);
24938 
24939 				if (pkt_type != OB_PKT) {
24940 					/*
24941 					 * Update the packet count of trailing
24942 					 * RTF_MULTIRT ires.
24943 					 */
24944 					UPDATE_OB_PKT_COUNT(ire);
24945 				}
24946 			}
24947 
24948 			/* All done if we just consumed the hdr_mp. */
24949 			if (mp == hdr_mp) {
24950 				last_frag = B_TRUE;
24951 				BUMP_MIB(out_ill->ill_ip_mib,
24952 				    ipIfStatsOutFragOKs);
24953 			}
24954 
24955 			if (multirt_send) {
24956 				/*
24957 				 * We are in a multiple send case; look for
24958 				 * the next ire and re-enter the loop.
24959 				 */
24960 				ASSERT(ire1);
24961 				ASSERT(next_mp);
24962 				/* REFRELE the current ire before looping */
24963 				ire_refrele(ire);
24964 				ire = ire1;
24965 				ire1 = NULL;
24966 				q = ire->ire_stq;
24967 				mp = next_mp;
24968 				next_mp = NULL;
24969 			}
24970 		} while (multirt_send);
24971 		/*
24972 		 * Restore the original ire; we need it for the
24973 		 * trailing frags
24974 		 */
24975 		if (save_ire != NULL) {
24976 			ASSERT(ire1 == NULL);
24977 			/* REFRELE the last iterated ire */
24978 			ire_refrele(ire);
24979 			/* save_ire has been REFHOLDed */
24980 			ire = save_ire;
24981 			q = ire->ire_stq;
24982 			save_ire = NULL;
24983 		}
24984 
24985 		if (last_frag) {
24986 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24987 			    "ip_wput_frag_end:(%S)",
24988 			    "consumed hdr_mp");
24989 
24990 			if (first_ire != NULL)
24991 				ire_refrele(first_ire);
24992 			return;
24993 		}
24994 		/* Otherwise, advance and loop. */
24995 		offset += len;
24996 	}
24997 
24998 drop_pkt:
24999 	/* Clean up following allocation failure. */
25000 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25001 	freemsg(mp);
25002 	if (mp != hdr_mp)
25003 		freeb(hdr_mp);
25004 	if (mp != mp_orig)
25005 		freemsg(mp_orig);
25006 
25007 	if (save_ire != NULL)
25008 		IRE_REFRELE(save_ire);
25009 	if (first_ire != NULL)
25010 		ire_refrele(first_ire);
25011 
25012 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25013 	    "ip_wput_frag_end:(%S)",
25014 	    "end--alloc failure");
25015 }
25016 
25017 /*
25018  * Copy the header plus those options which have the copy bit set
25019  */
25020 static mblk_t *
25021 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25022 {
25023 	mblk_t	*mp;
25024 	uchar_t	*up;
25025 
25026 	/*
25027 	 * Quick check if we need to look for options without the copy bit
25028 	 * set
25029 	 */
25030 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25031 	if (!mp)
25032 		return (mp);
25033 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25034 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25035 		bcopy(rptr, mp->b_rptr, hdr_len);
25036 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25037 		return (mp);
25038 	}
25039 	up  = mp->b_rptr;
25040 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25041 	up += IP_SIMPLE_HDR_LENGTH;
25042 	rptr += IP_SIMPLE_HDR_LENGTH;
25043 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25044 	while (hdr_len > 0) {
25045 		uint32_t optval;
25046 		uint32_t optlen;
25047 
25048 		optval = *rptr;
25049 		if (optval == IPOPT_EOL)
25050 			break;
25051 		if (optval == IPOPT_NOP)
25052 			optlen = 1;
25053 		else
25054 			optlen = rptr[1];
25055 		if (optval & IPOPT_COPY) {
25056 			bcopy(rptr, up, optlen);
25057 			up += optlen;
25058 		}
25059 		rptr += optlen;
25060 		hdr_len -= optlen;
25061 	}
25062 	/*
25063 	 * Make sure that we drop an even number of words by filling
25064 	 * with EOL to the next word boundary.
25065 	 */
25066 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25067 	    hdr_len & 0x3; hdr_len++)
25068 		*up++ = IPOPT_EOL;
25069 	mp->b_wptr = up;
25070 	/* Update header length */
25071 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25072 	return (mp);
25073 }
25074 
25075 /*
25076  * Delivery to local recipients including fanout to multiple recipients.
25077  * Does not do checksumming of UDP/TCP.
25078  * Note: q should be the read side queue for either the ill or conn.
25079  * Note: rq should be the read side q for the lower (ill) stream.
25080  * We don't send packets to IPPF processing, thus the last argument
25081  * to all the fanout calls are B_FALSE.
25082  */
25083 void
25084 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25085     int fanout_flags, zoneid_t zoneid)
25086 {
25087 	uint32_t	protocol;
25088 	mblk_t		*first_mp;
25089 	boolean_t	mctl_present;
25090 	int		ire_type;
25091 #define	rptr	((uchar_t *)ipha)
25092 	ip_stack_t	*ipst = ill->ill_ipst;
25093 
25094 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25095 	    "ip_wput_local_start: q %p", q);
25096 
25097 	if (ire != NULL) {
25098 		ire_type = ire->ire_type;
25099 	} else {
25100 		/*
25101 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25102 		 * packet is not multicast, we can't tell the ire type.
25103 		 */
25104 		ASSERT(CLASSD(ipha->ipha_dst));
25105 		ire_type = IRE_BROADCAST;
25106 	}
25107 
25108 	first_mp = mp;
25109 	if (first_mp->b_datap->db_type == M_CTL) {
25110 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25111 		if (!io->ipsec_out_secure) {
25112 			/*
25113 			 * This ipsec_out_t was allocated in ip_wput
25114 			 * for multicast packets to store the ill_index.
25115 			 * As this is being delivered locally, we don't
25116 			 * need this anymore.
25117 			 */
25118 			mp = first_mp->b_cont;
25119 			freeb(first_mp);
25120 			first_mp = mp;
25121 			mctl_present = B_FALSE;
25122 		} else {
25123 			/*
25124 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25125 			 * security properties for the looped-back packet.
25126 			 */
25127 			mctl_present = B_TRUE;
25128 			mp = first_mp->b_cont;
25129 			ASSERT(mp != NULL);
25130 			ipsec_out_to_in(first_mp);
25131 		}
25132 	} else {
25133 		mctl_present = B_FALSE;
25134 	}
25135 
25136 	DTRACE_PROBE4(ip4__loopback__in__start,
25137 	    ill_t *, ill, ill_t *, NULL,
25138 	    ipha_t *, ipha, mblk_t *, first_mp);
25139 
25140 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25141 	    ipst->ips_ipv4firewall_loopback_in,
25142 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25143 
25144 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25145 
25146 	if (first_mp == NULL)
25147 		return;
25148 
25149 	if (ipst->ips_ipobs_enabled) {
25150 		zoneid_t szone, dzone, lookup_zoneid = ALL_ZONES;
25151 		zoneid_t stackzoneid = netstackid_to_zoneid(
25152 		    ipst->ips_netstack->netstack_stackid);
25153 
25154 		dzone = (stackzoneid == GLOBAL_ZONEID) ? zoneid : stackzoneid;
25155 		/*
25156 		 * 127.0.0.1 is special, as we cannot lookup its zoneid by
25157 		 * address.  Restrict the lookup below to the destination zone.
25158 		 */
25159 		if (ipha->ipha_src == ntohl(INADDR_LOOPBACK))
25160 			lookup_zoneid = zoneid;
25161 		szone = ip_get_zoneid_v4(ipha->ipha_src, mp, ipst,
25162 		    lookup_zoneid);
25163 		ipobs_hook(mp, IPOBS_HOOK_LOCAL, szone, dzone, ill,
25164 		    IPV4_VERSION, 0, ipst);
25165 	}
25166 
25167 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25168 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25169 	    int, 1);
25170 
25171 	ipst->ips_loopback_packets++;
25172 
25173 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25174 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25175 	if (!IS_SIMPLE_IPH(ipha)) {
25176 		ip_wput_local_options(ipha, ipst);
25177 	}
25178 
25179 	protocol = ipha->ipha_protocol;
25180 	switch (protocol) {
25181 	case IPPROTO_ICMP: {
25182 		ire_t		*ire_zone;
25183 		ilm_t		*ilm;
25184 		mblk_t		*mp1;
25185 		zoneid_t	last_zoneid;
25186 
25187 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25188 			ASSERT(ire_type == IRE_BROADCAST);
25189 			/*
25190 			 * In the multicast case, applications may have joined
25191 			 * the group from different zones, so we need to deliver
25192 			 * the packet to each of them. Loop through the
25193 			 * multicast memberships structures (ilm) on the receive
25194 			 * ill and send a copy of the packet up each matching
25195 			 * one. However, we don't do this for multicasts sent on
25196 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25197 			 * they must stay in the sender's zone.
25198 			 *
25199 			 * ilm_add_v6() ensures that ilms in the same zone are
25200 			 * contiguous in the ill_ilm list. We use this property
25201 			 * to avoid sending duplicates needed when two
25202 			 * applications in the same zone join the same group on
25203 			 * different logical interfaces: we ignore the ilm if
25204 			 * it's zoneid is the same as the last matching one.
25205 			 * In addition, the sending of the packet for
25206 			 * ire_zoneid is delayed until all of the other ilms
25207 			 * have been exhausted.
25208 			 */
25209 			last_zoneid = -1;
25210 			ILM_WALKER_HOLD(ill);
25211 			for (ilm = ill->ill_ilm; ilm != NULL;
25212 			    ilm = ilm->ilm_next) {
25213 				if ((ilm->ilm_flags & ILM_DELETED) ||
25214 				    ipha->ipha_dst != ilm->ilm_addr ||
25215 				    ilm->ilm_zoneid == last_zoneid ||
25216 				    ilm->ilm_zoneid == zoneid ||
25217 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25218 					continue;
25219 				mp1 = ip_copymsg(first_mp);
25220 				if (mp1 == NULL)
25221 					continue;
25222 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25223 				    mctl_present, B_FALSE, ill,
25224 				    ilm->ilm_zoneid);
25225 				last_zoneid = ilm->ilm_zoneid;
25226 			}
25227 			ILM_WALKER_RELE(ill);
25228 			/*
25229 			 * Loopback case: the sending endpoint has
25230 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25231 			 * dispatch the multicast packet to the sending zone.
25232 			 */
25233 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25234 				freemsg(first_mp);
25235 				return;
25236 			}
25237 		} else if (ire_type == IRE_BROADCAST) {
25238 			/*
25239 			 * In the broadcast case, there may be many zones
25240 			 * which need a copy of the packet delivered to them.
25241 			 * There is one IRE_BROADCAST per broadcast address
25242 			 * and per zone; we walk those using a helper function.
25243 			 * In addition, the sending of the packet for zoneid is
25244 			 * delayed until all of the other ires have been
25245 			 * processed.
25246 			 */
25247 			IRB_REFHOLD(ire->ire_bucket);
25248 			ire_zone = NULL;
25249 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25250 			    ire)) != NULL) {
25251 				mp1 = ip_copymsg(first_mp);
25252 				if (mp1 == NULL)
25253 					continue;
25254 
25255 				UPDATE_IB_PKT_COUNT(ire_zone);
25256 				ire_zone->ire_last_used_time = lbolt;
25257 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25258 				    mctl_present, B_FALSE, ill,
25259 				    ire_zone->ire_zoneid);
25260 			}
25261 			IRB_REFRELE(ire->ire_bucket);
25262 		}
25263 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25264 		    0, mctl_present, B_FALSE, ill, zoneid);
25265 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25266 		    "ip_wput_local_end: q %p (%S)",
25267 		    q, "icmp");
25268 		return;
25269 	}
25270 	case IPPROTO_IGMP:
25271 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25272 			/* Bad packet - discarded by igmp_input */
25273 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25274 			    "ip_wput_local_end: q %p (%S)",
25275 			    q, "igmp_input--bad packet");
25276 			if (mctl_present)
25277 				freeb(first_mp);
25278 			return;
25279 		}
25280 		/*
25281 		 * igmp_input() may have returned the pulled up message.
25282 		 * So first_mp and ipha need to be reinitialized.
25283 		 */
25284 		ipha = (ipha_t *)mp->b_rptr;
25285 		if (mctl_present)
25286 			first_mp->b_cont = mp;
25287 		else
25288 			first_mp = mp;
25289 		/* deliver to local raw users */
25290 		break;
25291 	case IPPROTO_ENCAP:
25292 		/*
25293 		 * This case is covered by either ip_fanout_proto, or by
25294 		 * the above security processing for self-tunneled packets.
25295 		 */
25296 		break;
25297 	case IPPROTO_UDP: {
25298 		uint16_t	*up;
25299 		uint32_t	ports;
25300 
25301 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25302 		    UDP_PORTS_OFFSET);
25303 		/* Force a 'valid' checksum. */
25304 		up[3] = 0;
25305 
25306 		ports = *(uint32_t *)up;
25307 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25308 		    (ire_type == IRE_BROADCAST),
25309 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25310 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25311 		    ill, zoneid);
25312 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25313 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25314 		return;
25315 	}
25316 	case IPPROTO_TCP: {
25317 
25318 		/*
25319 		 * For TCP, discard broadcast packets.
25320 		 */
25321 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25322 			freemsg(first_mp);
25323 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25324 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25325 			return;
25326 		}
25327 
25328 		if (mp->b_datap->db_type == M_DATA) {
25329 			/*
25330 			 * M_DATA mblk, so init mblk (chain) for no struio().
25331 			 */
25332 			mblk_t	*mp1 = mp;
25333 
25334 			do {
25335 				mp1->b_datap->db_struioflag = 0;
25336 			} while ((mp1 = mp1->b_cont) != NULL);
25337 		}
25338 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25339 		    <= mp->b_wptr);
25340 		ip_fanout_tcp(q, first_mp, ill, ipha,
25341 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25342 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25343 		    mctl_present, B_FALSE, zoneid);
25344 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25345 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25346 		return;
25347 	}
25348 	case IPPROTO_SCTP:
25349 	{
25350 		uint32_t	ports;
25351 
25352 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25353 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25354 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25355 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25356 		return;
25357 	}
25358 
25359 	default:
25360 		break;
25361 	}
25362 	/*
25363 	 * Find a client for some other protocol.  We give
25364 	 * copies to multiple clients, if more than one is
25365 	 * bound.
25366 	 */
25367 	ip_fanout_proto(q, first_mp, ill, ipha,
25368 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25369 	    mctl_present, B_FALSE, ill, zoneid);
25370 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25371 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25372 #undef	rptr
25373 }
25374 
25375 /*
25376  * Update any source route, record route, or timestamp options.
25377  * Check that we are at end of strict source route.
25378  * The options have been sanity checked by ip_wput_options().
25379  */
25380 static void
25381 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25382 {
25383 	ipoptp_t	opts;
25384 	uchar_t		*opt;
25385 	uint8_t		optval;
25386 	uint8_t		optlen;
25387 	ipaddr_t	dst;
25388 	uint32_t	ts;
25389 	ire_t		*ire;
25390 	timestruc_t	now;
25391 
25392 	ip2dbg(("ip_wput_local_options\n"));
25393 	for (optval = ipoptp_first(&opts, ipha);
25394 	    optval != IPOPT_EOL;
25395 	    optval = ipoptp_next(&opts)) {
25396 		opt = opts.ipoptp_cur;
25397 		optlen = opts.ipoptp_len;
25398 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25399 		switch (optval) {
25400 			uint32_t off;
25401 		case IPOPT_SSRR:
25402 		case IPOPT_LSRR:
25403 			off = opt[IPOPT_OFFSET];
25404 			off--;
25405 			if (optlen < IP_ADDR_LEN ||
25406 			    off > optlen - IP_ADDR_LEN) {
25407 				/* End of source route */
25408 				break;
25409 			}
25410 			/*
25411 			 * This will only happen if two consecutive entries
25412 			 * in the source route contains our address or if
25413 			 * it is a packet with a loose source route which
25414 			 * reaches us before consuming the whole source route
25415 			 */
25416 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25417 			if (optval == IPOPT_SSRR) {
25418 				return;
25419 			}
25420 			/*
25421 			 * Hack: instead of dropping the packet truncate the
25422 			 * source route to what has been used by filling the
25423 			 * rest with IPOPT_NOP.
25424 			 */
25425 			opt[IPOPT_OLEN] = (uint8_t)off;
25426 			while (off < optlen) {
25427 				opt[off++] = IPOPT_NOP;
25428 			}
25429 			break;
25430 		case IPOPT_RR:
25431 			off = opt[IPOPT_OFFSET];
25432 			off--;
25433 			if (optlen < IP_ADDR_LEN ||
25434 			    off > optlen - IP_ADDR_LEN) {
25435 				/* No more room - ignore */
25436 				ip1dbg((
25437 				    "ip_wput_forward_options: end of RR\n"));
25438 				break;
25439 			}
25440 			dst = htonl(INADDR_LOOPBACK);
25441 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25442 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25443 			break;
25444 		case IPOPT_TS:
25445 			/* Insert timestamp if there is romm */
25446 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25447 			case IPOPT_TS_TSONLY:
25448 				off = IPOPT_TS_TIMELEN;
25449 				break;
25450 			case IPOPT_TS_PRESPEC:
25451 			case IPOPT_TS_PRESPEC_RFC791:
25452 				/* Verify that the address matched */
25453 				off = opt[IPOPT_OFFSET] - 1;
25454 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25455 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25456 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25457 				    ipst);
25458 				if (ire == NULL) {
25459 					/* Not for us */
25460 					break;
25461 				}
25462 				ire_refrele(ire);
25463 				/* FALLTHRU */
25464 			case IPOPT_TS_TSANDADDR:
25465 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25466 				break;
25467 			default:
25468 				/*
25469 				 * ip_*put_options should have already
25470 				 * dropped this packet.
25471 				 */
25472 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25473 				    "unknown IT - bug in ip_wput_options?\n");
25474 				return;	/* Keep "lint" happy */
25475 			}
25476 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25477 				/* Increase overflow counter */
25478 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25479 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25480 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25481 				    (off << 4);
25482 				break;
25483 			}
25484 			off = opt[IPOPT_OFFSET] - 1;
25485 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25486 			case IPOPT_TS_PRESPEC:
25487 			case IPOPT_TS_PRESPEC_RFC791:
25488 			case IPOPT_TS_TSANDADDR:
25489 				dst = htonl(INADDR_LOOPBACK);
25490 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25491 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25492 				/* FALLTHRU */
25493 			case IPOPT_TS_TSONLY:
25494 				off = opt[IPOPT_OFFSET] - 1;
25495 				/* Compute # of milliseconds since midnight */
25496 				gethrestime(&now);
25497 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25498 				    now.tv_nsec / (NANOSEC / MILLISEC);
25499 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25500 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25501 				break;
25502 			}
25503 			break;
25504 		}
25505 	}
25506 }
25507 
25508 /*
25509  * Send out a multicast packet on interface ipif.
25510  * The sender does not have an conn.
25511  * Caller verifies that this isn't a PHYI_LOOPBACK.
25512  */
25513 void
25514 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25515 {
25516 	ipha_t	*ipha;
25517 	ire_t	*ire;
25518 	ipaddr_t	dst;
25519 	mblk_t		*first_mp;
25520 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25521 
25522 	/* igmp_sendpkt always allocates a ipsec_out_t */
25523 	ASSERT(mp->b_datap->db_type == M_CTL);
25524 	ASSERT(!ipif->ipif_isv6);
25525 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25526 
25527 	first_mp = mp;
25528 	mp = first_mp->b_cont;
25529 	ASSERT(mp->b_datap->db_type == M_DATA);
25530 	ipha = (ipha_t *)mp->b_rptr;
25531 
25532 	/*
25533 	 * Find an IRE which matches the destination and the outgoing
25534 	 * queue (i.e. the outgoing interface.)
25535 	 */
25536 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25537 		dst = ipif->ipif_pp_dst_addr;
25538 	else
25539 		dst = ipha->ipha_dst;
25540 	/*
25541 	 * The source address has already been initialized by the
25542 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25543 	 * be sufficient rather than MATCH_IRE_IPIF.
25544 	 *
25545 	 * This function is used for sending IGMP packets. We need
25546 	 * to make sure that we send the packet out of the interface
25547 	 * (ipif->ipif_ill) where we joined the group. This is to
25548 	 * prevent from switches doing IGMP snooping to send us multicast
25549 	 * packets for a given group on the interface we have joined.
25550 	 * If we can't find an ire, igmp_sendpkt has already initialized
25551 	 * ipsec_out_attach_if so that this will not be load spread in
25552 	 * ip_newroute_ipif.
25553 	 */
25554 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25555 	    MATCH_IRE_ILL, ipst);
25556 	if (!ire) {
25557 		/*
25558 		 * Mark this packet to make it be delivered to
25559 		 * ip_wput_ire after the new ire has been
25560 		 * created.
25561 		 */
25562 		mp->b_prev = NULL;
25563 		mp->b_next = NULL;
25564 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25565 		    zoneid, &zero_info);
25566 		return;
25567 	}
25568 
25569 	/*
25570 	 * Honor the RTF_SETSRC flag; this is the only case
25571 	 * where we force this addr whatever the current src addr is,
25572 	 * because this address is set by igmp_sendpkt(), and
25573 	 * cannot be specified by any user.
25574 	 */
25575 	if (ire->ire_flags & RTF_SETSRC) {
25576 		ipha->ipha_src = ire->ire_src_addr;
25577 	}
25578 
25579 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25580 }
25581 
25582 /*
25583  * NOTE : This function does not ire_refrele the ire argument passed in.
25584  *
25585  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25586  * failure. The nce_fp_mp can vanish any time in the case of
25587  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25588  * the ire_lock to access the nce_fp_mp in this case.
25589  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25590  * prepending a fastpath message IPQoS processing must precede it, we also set
25591  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25592  * (IPQoS might have set the b_band for CoS marking).
25593  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25594  * must follow it so that IPQoS can mark the dl_priority field for CoS
25595  * marking, if needed.
25596  */
25597 static mblk_t *
25598 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25599     uint32_t ill_index, ipha_t **iphap)
25600 {
25601 	uint_t	hlen;
25602 	ipha_t *ipha;
25603 	mblk_t *mp1;
25604 	boolean_t qos_done = B_FALSE;
25605 	uchar_t	*ll_hdr;
25606 	ip_stack_t	*ipst = ire->ire_ipst;
25607 
25608 #define	rptr	((uchar_t *)ipha)
25609 
25610 	ipha = (ipha_t *)mp->b_rptr;
25611 	hlen = 0;
25612 	LOCK_IRE_FP_MP(ire);
25613 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25614 		ASSERT(DB_TYPE(mp1) == M_DATA);
25615 		/* Initiate IPPF processing */
25616 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25617 			UNLOCK_IRE_FP_MP(ire);
25618 			ip_process(proc, &mp, ill_index);
25619 			if (mp == NULL)
25620 				return (NULL);
25621 
25622 			ipha = (ipha_t *)mp->b_rptr;
25623 			LOCK_IRE_FP_MP(ire);
25624 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25625 				qos_done = B_TRUE;
25626 				goto no_fp_mp;
25627 			}
25628 			ASSERT(DB_TYPE(mp1) == M_DATA);
25629 		}
25630 		hlen = MBLKL(mp1);
25631 		/*
25632 		 * Check if we have enough room to prepend fastpath
25633 		 * header
25634 		 */
25635 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25636 			ll_hdr = rptr - hlen;
25637 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25638 			/*
25639 			 * Set the b_rptr to the start of the link layer
25640 			 * header
25641 			 */
25642 			mp->b_rptr = ll_hdr;
25643 			mp1 = mp;
25644 		} else {
25645 			mp1 = copyb(mp1);
25646 			if (mp1 == NULL)
25647 				goto unlock_err;
25648 			mp1->b_band = mp->b_band;
25649 			mp1->b_cont = mp;
25650 			/*
25651 			 * certain system generated traffic may not
25652 			 * have cred/label in ip header block. This
25653 			 * is true even for a labeled system. But for
25654 			 * labeled traffic, inherit the label in the
25655 			 * new header.
25656 			 */
25657 			if (DB_CRED(mp) != NULL)
25658 				mblk_setcred(mp1, DB_CRED(mp));
25659 			/*
25660 			 * XXX disable ICK_VALID and compute checksum
25661 			 * here; can happen if nce_fp_mp changes and
25662 			 * it can't be copied now due to insufficient
25663 			 * space. (unlikely, fp mp can change, but it
25664 			 * does not increase in length)
25665 			 */
25666 		}
25667 		UNLOCK_IRE_FP_MP(ire);
25668 	} else {
25669 no_fp_mp:
25670 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25671 		if (mp1 == NULL) {
25672 unlock_err:
25673 			UNLOCK_IRE_FP_MP(ire);
25674 			freemsg(mp);
25675 			return (NULL);
25676 		}
25677 		UNLOCK_IRE_FP_MP(ire);
25678 		mp1->b_cont = mp;
25679 		/*
25680 		 * certain system generated traffic may not
25681 		 * have cred/label in ip header block. This
25682 		 * is true even for a labeled system. But for
25683 		 * labeled traffic, inherit the label in the
25684 		 * new header.
25685 		 */
25686 		if (DB_CRED(mp) != NULL)
25687 			mblk_setcred(mp1, DB_CRED(mp));
25688 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25689 			ip_process(proc, &mp1, ill_index);
25690 			if (mp1 == NULL)
25691 				return (NULL);
25692 
25693 			if (mp1->b_cont == NULL)
25694 				ipha = NULL;
25695 			else
25696 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25697 		}
25698 	}
25699 
25700 	*iphap = ipha;
25701 	return (mp1);
25702 #undef rptr
25703 }
25704 
25705 /*
25706  * Finish the outbound IPsec processing for an IPv6 packet. This function
25707  * is called from ipsec_out_process() if the IPsec packet was processed
25708  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25709  * asynchronously.
25710  */
25711 void
25712 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25713     ire_t *ire_arg)
25714 {
25715 	in6_addr_t *v6dstp;
25716 	ire_t *ire;
25717 	mblk_t *mp;
25718 	ip6_t *ip6h1;
25719 	uint_t	ill_index;
25720 	ipsec_out_t *io;
25721 	boolean_t attach_if, hwaccel;
25722 	uint32_t flags = IP6_NO_IPPOLICY;
25723 	int match_flags;
25724 	zoneid_t zoneid;
25725 	boolean_t ill_need_rele = B_FALSE;
25726 	boolean_t ire_need_rele = B_FALSE;
25727 	ip_stack_t	*ipst;
25728 
25729 	mp = ipsec_mp->b_cont;
25730 	ip6h1 = (ip6_t *)mp->b_rptr;
25731 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25732 	ASSERT(io->ipsec_out_ns != NULL);
25733 	ipst = io->ipsec_out_ns->netstack_ip;
25734 	ill_index = io->ipsec_out_ill_index;
25735 	if (io->ipsec_out_reachable) {
25736 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25737 	}
25738 	attach_if = io->ipsec_out_attach_if;
25739 	hwaccel = io->ipsec_out_accelerated;
25740 	zoneid = io->ipsec_out_zoneid;
25741 	ASSERT(zoneid != ALL_ZONES);
25742 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25743 	/* Multicast addresses should have non-zero ill_index. */
25744 	v6dstp = &ip6h->ip6_dst;
25745 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25746 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25747 	ASSERT(!attach_if || ill_index != 0);
25748 	if (ill_index != 0) {
25749 		if (ill == NULL) {
25750 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25751 			    B_TRUE, ipst);
25752 
25753 			/* Failure case frees things for us. */
25754 			if (ill == NULL)
25755 				return;
25756 
25757 			ill_need_rele = B_TRUE;
25758 		}
25759 		/*
25760 		 * If this packet needs to go out on a particular interface
25761 		 * honor it.
25762 		 */
25763 		if (attach_if) {
25764 			match_flags = MATCH_IRE_ILL;
25765 
25766 			/*
25767 			 * Check if we need an ire that will not be
25768 			 * looked up by anybody else i.e. HIDDEN.
25769 			 */
25770 			if (ill_is_probeonly(ill)) {
25771 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25772 			}
25773 		}
25774 	}
25775 	ASSERT(mp != NULL);
25776 
25777 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25778 		boolean_t unspec_src;
25779 		ipif_t	*ipif;
25780 
25781 		/*
25782 		 * Use the ill_index to get the right ill.
25783 		 */
25784 		unspec_src = io->ipsec_out_unspec_src;
25785 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25786 		if (ipif == NULL) {
25787 			if (ill_need_rele)
25788 				ill_refrele(ill);
25789 			freemsg(ipsec_mp);
25790 			return;
25791 		}
25792 
25793 		if (ire_arg != NULL) {
25794 			ire = ire_arg;
25795 		} else {
25796 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25797 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25798 			ire_need_rele = B_TRUE;
25799 		}
25800 		if (ire != NULL) {
25801 			ipif_refrele(ipif);
25802 			/*
25803 			 * XXX Do the multicast forwarding now, as the IPsec
25804 			 * processing has been done.
25805 			 */
25806 			goto send;
25807 		}
25808 
25809 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25810 		mp->b_prev = NULL;
25811 		mp->b_next = NULL;
25812 
25813 		/*
25814 		 * If the IPsec packet was processed asynchronously,
25815 		 * drop it now.
25816 		 */
25817 		if (q == NULL) {
25818 			if (ill_need_rele)
25819 				ill_refrele(ill);
25820 			freemsg(ipsec_mp);
25821 			return;
25822 		}
25823 
25824 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25825 		    unspec_src, zoneid);
25826 		ipif_refrele(ipif);
25827 	} else {
25828 		if (attach_if) {
25829 			ipif_t	*ipif;
25830 
25831 			ipif = ipif_get_next_ipif(NULL, ill);
25832 			if (ipif == NULL) {
25833 				if (ill_need_rele)
25834 					ill_refrele(ill);
25835 				freemsg(ipsec_mp);
25836 				return;
25837 			}
25838 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25839 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25840 			ire_need_rele = B_TRUE;
25841 			ipif_refrele(ipif);
25842 		} else {
25843 			if (ire_arg != NULL) {
25844 				ire = ire_arg;
25845 			} else {
25846 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25847 				    ipst);
25848 				ire_need_rele = B_TRUE;
25849 			}
25850 		}
25851 		if (ire != NULL)
25852 			goto send;
25853 		/*
25854 		 * ire disappeared underneath.
25855 		 *
25856 		 * What we need to do here is the ip_newroute
25857 		 * logic to get the ire without doing the IPsec
25858 		 * processing. Follow the same old path. But this
25859 		 * time, ip_wput or ire_add_then_send will call us
25860 		 * directly as all the IPsec operations are done.
25861 		 */
25862 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25863 		mp->b_prev = NULL;
25864 		mp->b_next = NULL;
25865 
25866 		/*
25867 		 * If the IPsec packet was processed asynchronously,
25868 		 * drop it now.
25869 		 */
25870 		if (q == NULL) {
25871 			if (ill_need_rele)
25872 				ill_refrele(ill);
25873 			freemsg(ipsec_mp);
25874 			return;
25875 		}
25876 
25877 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25878 		    zoneid, ipst);
25879 	}
25880 	if (ill != NULL && ill_need_rele)
25881 		ill_refrele(ill);
25882 	return;
25883 send:
25884 	if (ill != NULL && ill_need_rele)
25885 		ill_refrele(ill);
25886 
25887 	/* Local delivery */
25888 	if (ire->ire_stq == NULL) {
25889 		ill_t	*out_ill;
25890 		ASSERT(q != NULL);
25891 
25892 		/* PFHooks: LOOPBACK_OUT */
25893 		out_ill = ire_to_ill(ire);
25894 
25895 		/*
25896 		 * DTrace this as ip:::send.  A blocked packet will fire the
25897 		 * send probe, but not the receive probe.
25898 		 */
25899 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25900 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25901 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25902 
25903 		DTRACE_PROBE4(ip6__loopback__out__start,
25904 		    ill_t *, NULL, ill_t *, out_ill,
25905 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25906 
25907 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25908 		    ipst->ips_ipv6firewall_loopback_out,
25909 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25910 
25911 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25912 
25913 		if (ipsec_mp != NULL) {
25914 			ip_wput_local_v6(RD(q), out_ill,
25915 			    ip6h, ipsec_mp, ire, 0, zoneid);
25916 		}
25917 		if (ire_need_rele)
25918 			ire_refrele(ire);
25919 		return;
25920 	}
25921 	/*
25922 	 * Everything is done. Send it out on the wire.
25923 	 * We force the insertion of a fragment header using the
25924 	 * IPH_FRAG_HDR flag in two cases:
25925 	 * - after reception of an ICMPv6 "packet too big" message
25926 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25927 	 * - for multirouted IPv6 packets, so that the receiver can
25928 	 *   discard duplicates according to their fragment identifier
25929 	 */
25930 	/* XXX fix flow control problems. */
25931 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25932 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25933 		if (hwaccel) {
25934 			/*
25935 			 * hardware acceleration does not handle these
25936 			 * "slow path" cases.
25937 			 */
25938 			/* IPsec KSTATS: should bump bean counter here. */
25939 			if (ire_need_rele)
25940 				ire_refrele(ire);
25941 			freemsg(ipsec_mp);
25942 			return;
25943 		}
25944 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25945 		    (mp->b_cont ? msgdsize(mp) :
25946 		    mp->b_wptr - (uchar_t *)ip6h)) {
25947 			/* IPsec KSTATS: should bump bean counter here. */
25948 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25949 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25950 			    msgdsize(mp)));
25951 			if (ire_need_rele)
25952 				ire_refrele(ire);
25953 			freemsg(ipsec_mp);
25954 			return;
25955 		}
25956 		ASSERT(mp->b_prev == NULL);
25957 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25958 		    ntohs(ip6h->ip6_plen) +
25959 		    IPV6_HDR_LEN, ire->ire_max_frag));
25960 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25961 		    ire->ire_max_frag);
25962 	} else {
25963 		UPDATE_OB_PKT_COUNT(ire);
25964 		ire->ire_last_used_time = lbolt;
25965 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25966 	}
25967 	if (ire_need_rele)
25968 		ire_refrele(ire);
25969 	freeb(ipsec_mp);
25970 }
25971 
25972 void
25973 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25974 {
25975 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25976 	da_ipsec_t *hada;	/* data attributes */
25977 	ill_t *ill = (ill_t *)q->q_ptr;
25978 
25979 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25980 
25981 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25982 		/* IPsec KSTATS: Bump lose counter here! */
25983 		freemsg(mp);
25984 		return;
25985 	}
25986 
25987 	/*
25988 	 * It's an IPsec packet that must be
25989 	 * accelerated by the Provider, and the
25990 	 * outbound ill is IPsec acceleration capable.
25991 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25992 	 * to the ill.
25993 	 * IPsec KSTATS: should bump packet counter here.
25994 	 */
25995 
25996 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25997 	if (hada_mp == NULL) {
25998 		/* IPsec KSTATS: should bump packet counter here. */
25999 		freemsg(mp);
26000 		return;
26001 	}
26002 
26003 	hada_mp->b_datap->db_type = M_CTL;
26004 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26005 	hada_mp->b_cont = mp;
26006 
26007 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26008 	bzero(hada, sizeof (da_ipsec_t));
26009 	hada->da_type = IPHADA_M_CTL;
26010 
26011 	putnext(q, hada_mp);
26012 }
26013 
26014 /*
26015  * Finish the outbound IPsec processing. This function is called from
26016  * ipsec_out_process() if the IPsec packet was processed
26017  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26018  * asynchronously.
26019  */
26020 void
26021 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26022     ire_t *ire_arg)
26023 {
26024 	uint32_t v_hlen_tos_len;
26025 	ipaddr_t	dst;
26026 	ipif_t	*ipif = NULL;
26027 	ire_t *ire;
26028 	ire_t *ire1 = NULL;
26029 	mblk_t *next_mp = NULL;
26030 	uint32_t max_frag;
26031 	boolean_t multirt_send = B_FALSE;
26032 	mblk_t *mp;
26033 	ipha_t *ipha1;
26034 	uint_t	ill_index;
26035 	ipsec_out_t *io;
26036 	boolean_t attach_if;
26037 	int match_flags;
26038 	irb_t *irb = NULL;
26039 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26040 	zoneid_t zoneid;
26041 	ipxmit_state_t	pktxmit_state;
26042 	ip_stack_t	*ipst;
26043 
26044 #ifdef	_BIG_ENDIAN
26045 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26046 #else
26047 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26048 #endif
26049 
26050 	mp = ipsec_mp->b_cont;
26051 	ipha1 = (ipha_t *)mp->b_rptr;
26052 	ASSERT(mp != NULL);
26053 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26054 	dst = ipha->ipha_dst;
26055 
26056 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26057 	ill_index = io->ipsec_out_ill_index;
26058 	attach_if = io->ipsec_out_attach_if;
26059 	zoneid = io->ipsec_out_zoneid;
26060 	ASSERT(zoneid != ALL_ZONES);
26061 	ipst = io->ipsec_out_ns->netstack_ip;
26062 	ASSERT(io->ipsec_out_ns != NULL);
26063 
26064 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26065 	if (ill_index != 0) {
26066 		if (ill == NULL) {
26067 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26068 			    ill_index, B_FALSE, ipst);
26069 
26070 			/* Failure case frees things for us. */
26071 			if (ill == NULL)
26072 				return;
26073 
26074 			ill_need_rele = B_TRUE;
26075 		}
26076 		/*
26077 		 * If this packet needs to go out on a particular interface
26078 		 * honor it.
26079 		 */
26080 		if (attach_if) {
26081 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26082 
26083 			/*
26084 			 * Check if we need an ire that will not be
26085 			 * looked up by anybody else i.e. HIDDEN.
26086 			 */
26087 			if (ill_is_probeonly(ill)) {
26088 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26089 			}
26090 		}
26091 	}
26092 
26093 	if (CLASSD(dst)) {
26094 		boolean_t conn_dontroute;
26095 		/*
26096 		 * Use the ill_index to get the right ipif.
26097 		 */
26098 		conn_dontroute = io->ipsec_out_dontroute;
26099 		if (ill_index == 0)
26100 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26101 		else
26102 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26103 		if (ipif == NULL) {
26104 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26105 			    " multicast\n"));
26106 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26107 			freemsg(ipsec_mp);
26108 			goto done;
26109 		}
26110 		/*
26111 		 * ipha_src has already been intialized with the
26112 		 * value of the ipif in ip_wput. All we need now is
26113 		 * an ire to send this downstream.
26114 		 */
26115 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26116 		    MBLK_GETLABEL(mp), match_flags, ipst);
26117 		if (ire != NULL) {
26118 			ill_t *ill1;
26119 			/*
26120 			 * Do the multicast forwarding now, as the IPsec
26121 			 * processing has been done.
26122 			 */
26123 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26124 			    (ill1 = ire_to_ill(ire))) {
26125 				if (ip_mforward(ill1, ipha, mp)) {
26126 					freemsg(ipsec_mp);
26127 					ip1dbg(("ip_wput_ipsec_out: mforward "
26128 					    "failed\n"));
26129 					ire_refrele(ire);
26130 					goto done;
26131 				}
26132 			}
26133 			goto send;
26134 		}
26135 
26136 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26137 		mp->b_prev = NULL;
26138 		mp->b_next = NULL;
26139 
26140 		/*
26141 		 * If the IPsec packet was processed asynchronously,
26142 		 * drop it now.
26143 		 */
26144 		if (q == NULL) {
26145 			freemsg(ipsec_mp);
26146 			goto done;
26147 		}
26148 
26149 		/*
26150 		 * We may be using a wrong ipif to create the ire.
26151 		 * But it is okay as the source address is assigned
26152 		 * for the packet already. Next outbound packet would
26153 		 * create the IRE with the right IPIF in ip_wput.
26154 		 *
26155 		 * Also handle RTF_MULTIRT routes.
26156 		 */
26157 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26158 		    zoneid, &zero_info);
26159 	} else {
26160 		if (attach_if) {
26161 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26162 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26163 		} else {
26164 			if (ire_arg != NULL) {
26165 				ire = ire_arg;
26166 				ire_need_rele = B_FALSE;
26167 			} else {
26168 				ire = ire_cache_lookup(dst, zoneid,
26169 				    MBLK_GETLABEL(mp), ipst);
26170 			}
26171 		}
26172 		if (ire != NULL) {
26173 			goto send;
26174 		}
26175 
26176 		/*
26177 		 * ire disappeared underneath.
26178 		 *
26179 		 * What we need to do here is the ip_newroute
26180 		 * logic to get the ire without doing the IPsec
26181 		 * processing. Follow the same old path. But this
26182 		 * time, ip_wput or ire_add_then_put will call us
26183 		 * directly as all the IPsec operations are done.
26184 		 */
26185 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26186 		mp->b_prev = NULL;
26187 		mp->b_next = NULL;
26188 
26189 		/*
26190 		 * If the IPsec packet was processed asynchronously,
26191 		 * drop it now.
26192 		 */
26193 		if (q == NULL) {
26194 			freemsg(ipsec_mp);
26195 			goto done;
26196 		}
26197 
26198 		/*
26199 		 * Since we're going through ip_newroute() again, we
26200 		 * need to make sure we don't:
26201 		 *
26202 		 *	1.) Trigger the ASSERT() with the ipha_ident
26203 		 *	    overloading.
26204 		 *	2.) Redo transport-layer checksumming, since we've
26205 		 *	    already done all that to get this far.
26206 		 *
26207 		 * The easiest way not do either of the above is to set
26208 		 * the ipha_ident field to IP_HDR_INCLUDED.
26209 		 */
26210 		ipha->ipha_ident = IP_HDR_INCLUDED;
26211 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26212 		    zoneid, ipst);
26213 	}
26214 	goto done;
26215 send:
26216 	if (ire->ire_stq == NULL) {
26217 		ill_t	*out_ill;
26218 		/*
26219 		 * Loopbacks go through ip_wput_local except for one case.
26220 		 * We come here if we generate a icmp_frag_needed message
26221 		 * after IPsec processing is over. When this function calls
26222 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26223 		 * icmp_frag_needed. The message generated comes back here
26224 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26225 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26226 		 * source address as it is usually set in ip_wput_ire. As
26227 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26228 		 * and we end up here. We can't enter ip_wput_ire once the
26229 		 * IPsec processing is over and hence we need to do it here.
26230 		 */
26231 		ASSERT(q != NULL);
26232 		UPDATE_OB_PKT_COUNT(ire);
26233 		ire->ire_last_used_time = lbolt;
26234 		if (ipha->ipha_src == 0)
26235 			ipha->ipha_src = ire->ire_src_addr;
26236 
26237 		/* PFHooks: LOOPBACK_OUT */
26238 		out_ill = ire_to_ill(ire);
26239 
26240 		/*
26241 		 * DTrace this as ip:::send.  A blocked packet will fire the
26242 		 * send probe, but not the receive probe.
26243 		 */
26244 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26245 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26246 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26247 
26248 		DTRACE_PROBE4(ip4__loopback__out__start,
26249 		    ill_t *, NULL, ill_t *, out_ill,
26250 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26251 
26252 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26253 		    ipst->ips_ipv4firewall_loopback_out,
26254 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26255 
26256 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26257 
26258 		if (ipsec_mp != NULL)
26259 			ip_wput_local(RD(q), out_ill,
26260 			    ipha, ipsec_mp, ire, 0, zoneid);
26261 		if (ire_need_rele)
26262 			ire_refrele(ire);
26263 		goto done;
26264 	}
26265 
26266 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26267 		/*
26268 		 * We are through with IPsec processing.
26269 		 * Fragment this and send it on the wire.
26270 		 */
26271 		if (io->ipsec_out_accelerated) {
26272 			/*
26273 			 * The packet has been accelerated but must
26274 			 * be fragmented. This should not happen
26275 			 * since AH and ESP must not accelerate
26276 			 * packets that need fragmentation, however
26277 			 * the configuration could have changed
26278 			 * since the AH or ESP processing.
26279 			 * Drop packet.
26280 			 * IPsec KSTATS: bump bean counter here.
26281 			 */
26282 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26283 			    "fragmented accelerated packet!\n"));
26284 			freemsg(ipsec_mp);
26285 		} else {
26286 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26287 		}
26288 		if (ire_need_rele)
26289 			ire_refrele(ire);
26290 		goto done;
26291 	}
26292 
26293 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26294 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26295 	    (void *)ire->ire_ipif, (void *)ipif));
26296 
26297 	/*
26298 	 * Multiroute the secured packet, unless IPsec really
26299 	 * requires the packet to go out only through a particular
26300 	 * interface.
26301 	 */
26302 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26303 		ire_t *first_ire;
26304 		irb = ire->ire_bucket;
26305 		ASSERT(irb != NULL);
26306 		/*
26307 		 * This ire has been looked up as the one that
26308 		 * goes through the given ipif;
26309 		 * make sure we do not omit any other multiroute ire
26310 		 * that may be present in the bucket before this one.
26311 		 */
26312 		IRB_REFHOLD(irb);
26313 		for (first_ire = irb->irb_ire;
26314 		    first_ire != NULL;
26315 		    first_ire = first_ire->ire_next) {
26316 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26317 			    (first_ire->ire_addr == ire->ire_addr) &&
26318 			    !(first_ire->ire_marks &
26319 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26320 				break;
26321 			}
26322 		}
26323 
26324 		if ((first_ire != NULL) && (first_ire != ire)) {
26325 			/*
26326 			 * Don't change the ire if the packet must
26327 			 * be fragmented if sent via this new one.
26328 			 */
26329 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26330 				IRE_REFHOLD(first_ire);
26331 				if (ire_need_rele)
26332 					ire_refrele(ire);
26333 				else
26334 					ire_need_rele = B_TRUE;
26335 				ire = first_ire;
26336 			}
26337 		}
26338 		IRB_REFRELE(irb);
26339 
26340 		multirt_send = B_TRUE;
26341 		max_frag = ire->ire_max_frag;
26342 	} else {
26343 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26344 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26345 			    "flag, attach_if %d\n", attach_if));
26346 		}
26347 	}
26348 
26349 	/*
26350 	 * In most cases, the emission loop below is entered only once.
26351 	 * Only in the case where the ire holds the RTF_MULTIRT
26352 	 * flag, we loop to process all RTF_MULTIRT ires in the
26353 	 * bucket, and send the packet through all crossed
26354 	 * RTF_MULTIRT routes.
26355 	 */
26356 	do {
26357 		if (multirt_send) {
26358 			/*
26359 			 * ire1 holds here the next ire to process in the
26360 			 * bucket. If multirouting is expected,
26361 			 * any non-RTF_MULTIRT ire that has the
26362 			 * right destination address is ignored.
26363 			 */
26364 			ASSERT(irb != NULL);
26365 			IRB_REFHOLD(irb);
26366 			for (ire1 = ire->ire_next;
26367 			    ire1 != NULL;
26368 			    ire1 = ire1->ire_next) {
26369 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26370 					continue;
26371 				if (ire1->ire_addr != ire->ire_addr)
26372 					continue;
26373 				if (ire1->ire_marks &
26374 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26375 					continue;
26376 				/* No loopback here */
26377 				if (ire1->ire_stq == NULL)
26378 					continue;
26379 				/*
26380 				 * Ensure we do not exceed the MTU
26381 				 * of the next route.
26382 				 */
26383 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26384 					ip_multirt_bad_mtu(ire1, max_frag);
26385 					continue;
26386 				}
26387 
26388 				IRE_REFHOLD(ire1);
26389 				break;
26390 			}
26391 			IRB_REFRELE(irb);
26392 			if (ire1 != NULL) {
26393 				/*
26394 				 * We are in a multiple send case, need to
26395 				 * make a copy of the packet.
26396 				 */
26397 				next_mp = copymsg(ipsec_mp);
26398 				if (next_mp == NULL) {
26399 					ire_refrele(ire1);
26400 					ire1 = NULL;
26401 				}
26402 			}
26403 		}
26404 		/*
26405 		 * Everything is done. Send it out on the wire
26406 		 *
26407 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26408 		 * either send it on the wire or, in the case of
26409 		 * HW acceleration, call ipsec_hw_putnext.
26410 		 */
26411 		if (ire->ire_nce &&
26412 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26413 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26414 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26415 			/*
26416 			 * If ire's link-layer is unresolved (this
26417 			 * would only happen if the incomplete ire
26418 			 * was added to cachetable via forwarding path)
26419 			 * don't bother going to ip_xmit_v4. Just drop the
26420 			 * packet.
26421 			 * There is a slight risk here, in that, if we
26422 			 * have the forwarding path create an incomplete
26423 			 * IRE, then until the IRE is completed, any
26424 			 * transmitted IPsec packets will be dropped
26425 			 * instead of being queued waiting for resolution.
26426 			 *
26427 			 * But the likelihood of a forwarding packet and a wput
26428 			 * packet sending to the same dst at the same time
26429 			 * and there not yet be an ARP entry for it is small.
26430 			 * Furthermore, if this actually happens, it might
26431 			 * be likely that wput would generate multiple
26432 			 * packets (and forwarding would also have a train
26433 			 * of packets) for that destination. If this is
26434 			 * the case, some of them would have been dropped
26435 			 * anyway, since ARP only queues a few packets while
26436 			 * waiting for resolution
26437 			 *
26438 			 * NOTE: We should really call ip_xmit_v4,
26439 			 * and let it queue the packet and send the
26440 			 * ARP query and have ARP come back thus:
26441 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26442 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26443 			 * hw accel work. But it's too complex to get
26444 			 * the IPsec hw  acceleration approach to fit
26445 			 * well with ip_xmit_v4 doing ARP without
26446 			 * doing IPsec simplification. For now, we just
26447 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26448 			 * that we can continue with the send on the next
26449 			 * attempt.
26450 			 *
26451 			 * XXX THis should be revisited, when
26452 			 * the IPsec/IP interaction is cleaned up
26453 			 */
26454 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26455 			    " - dropping packet\n"));
26456 			freemsg(ipsec_mp);
26457 			/*
26458 			 * Call ip_xmit_v4() to trigger ARP query
26459 			 * in case the nce_state is ND_INITIAL
26460 			 */
26461 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26462 			goto drop_pkt;
26463 		}
26464 
26465 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26466 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26467 		    mblk_t *, ipsec_mp);
26468 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26469 		    ipst->ips_ipv4firewall_physical_out, NULL,
26470 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26471 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26472 		if (ipsec_mp == NULL)
26473 			goto drop_pkt;
26474 
26475 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26476 		pktxmit_state = ip_xmit_v4(mp, ire,
26477 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26478 
26479 		if ((pktxmit_state ==  SEND_FAILED) ||
26480 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26481 
26482 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26483 drop_pkt:
26484 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26485 			    ipIfStatsOutDiscards);
26486 			if (ire_need_rele)
26487 				ire_refrele(ire);
26488 			if (ire1 != NULL) {
26489 				ire_refrele(ire1);
26490 				freemsg(next_mp);
26491 			}
26492 			goto done;
26493 		}
26494 
26495 		freeb(ipsec_mp);
26496 		if (ire_need_rele)
26497 			ire_refrele(ire);
26498 
26499 		if (ire1 != NULL) {
26500 			ire = ire1;
26501 			ire_need_rele = B_TRUE;
26502 			ASSERT(next_mp);
26503 			ipsec_mp = next_mp;
26504 			mp = ipsec_mp->b_cont;
26505 			ire1 = NULL;
26506 			next_mp = NULL;
26507 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26508 		} else {
26509 			multirt_send = B_FALSE;
26510 		}
26511 	} while (multirt_send);
26512 done:
26513 	if (ill != NULL && ill_need_rele)
26514 		ill_refrele(ill);
26515 	if (ipif != NULL)
26516 		ipif_refrele(ipif);
26517 }
26518 
26519 /*
26520  * Get the ill corresponding to the specified ire, and compare its
26521  * capabilities with the protocol and algorithms specified by the
26522  * the SA obtained from ipsec_out. If they match, annotate the
26523  * ipsec_out structure to indicate that the packet needs acceleration.
26524  *
26525  *
26526  * A packet is eligible for outbound hardware acceleration if the
26527  * following conditions are satisfied:
26528  *
26529  * 1. the packet will not be fragmented
26530  * 2. the provider supports the algorithm
26531  * 3. there is no pending control message being exchanged
26532  * 4. snoop is not attached
26533  * 5. the destination address is not a broadcast or multicast address.
26534  *
26535  * Rationale:
26536  *	- Hardware drivers do not support fragmentation with
26537  *	  the current interface.
26538  *	- snoop, multicast, and broadcast may result in exposure of
26539  *	  a cleartext datagram.
26540  * We check all five of these conditions here.
26541  *
26542  * XXX would like to nuke "ire_t *" parameter here; problem is that
26543  * IRE is only way to figure out if a v4 address is a broadcast and
26544  * thus ineligible for acceleration...
26545  */
26546 static void
26547 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26548 {
26549 	ipsec_out_t *io;
26550 	mblk_t *data_mp;
26551 	uint_t plen, overhead;
26552 	ip_stack_t	*ipst;
26553 
26554 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26555 		return;
26556 
26557 	if (ill == NULL)
26558 		return;
26559 	ipst = ill->ill_ipst;
26560 	/*
26561 	 * Destination address is a broadcast or multicast.  Punt.
26562 	 */
26563 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26564 	    IRE_LOCAL)))
26565 		return;
26566 
26567 	data_mp = ipsec_mp->b_cont;
26568 
26569 	if (ill->ill_isv6) {
26570 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26571 
26572 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26573 			return;
26574 
26575 		plen = ip6h->ip6_plen;
26576 	} else {
26577 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26578 
26579 		if (CLASSD(ipha->ipha_dst))
26580 			return;
26581 
26582 		plen = ipha->ipha_length;
26583 	}
26584 	/*
26585 	 * Is there a pending DLPI control message being exchanged
26586 	 * between IP/IPsec and the DLS Provider? If there is, it
26587 	 * could be a SADB update, and the state of the DLS Provider
26588 	 * SADB might not be in sync with the SADB maintained by
26589 	 * IPsec. To avoid dropping packets or using the wrong keying
26590 	 * material, we do not accelerate this packet.
26591 	 */
26592 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26593 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26594 		    "ill_dlpi_pending! don't accelerate packet\n"));
26595 		return;
26596 	}
26597 
26598 	/*
26599 	 * Is the Provider in promiscous mode? If it does, we don't
26600 	 * accelerate the packet since it will bounce back up to the
26601 	 * listeners in the clear.
26602 	 */
26603 	if (ill->ill_promisc_on_phys) {
26604 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26605 		    "ill in promiscous mode, don't accelerate packet\n"));
26606 		return;
26607 	}
26608 
26609 	/*
26610 	 * Will the packet require fragmentation?
26611 	 */
26612 
26613 	/*
26614 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26615 	 * as is used elsewhere.
26616 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26617 	 *	+ 2-byte trailer
26618 	 */
26619 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26620 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26621 
26622 	if ((plen + overhead) > ill->ill_max_mtu)
26623 		return;
26624 
26625 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26626 
26627 	/*
26628 	 * Can the ill accelerate this IPsec protocol and algorithm
26629 	 * specified by the SA?
26630 	 */
26631 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26632 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26633 		return;
26634 	}
26635 
26636 	/*
26637 	 * Tell AH or ESP that the outbound ill is capable of
26638 	 * accelerating this packet.
26639 	 */
26640 	io->ipsec_out_is_capab_ill = B_TRUE;
26641 }
26642 
26643 /*
26644  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26645  *
26646  * If this function returns B_TRUE, the requested SA's have been filled
26647  * into the ipsec_out_*_sa pointers.
26648  *
26649  * If the function returns B_FALSE, the packet has been "consumed", most
26650  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26651  *
26652  * The SA references created by the protocol-specific "select"
26653  * function will be released when the ipsec_mp is freed, thanks to the
26654  * ipsec_out_free destructor -- see spd.c.
26655  */
26656 static boolean_t
26657 ipsec_out_select_sa(mblk_t *ipsec_mp)
26658 {
26659 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26660 	ipsec_out_t *io;
26661 	ipsec_policy_t *pp;
26662 	ipsec_action_t *ap;
26663 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26664 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26665 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26666 
26667 	if (!io->ipsec_out_secure) {
26668 		/*
26669 		 * We came here by mistake.
26670 		 * Don't bother with ipsec processing
26671 		 * We should "discourage" this path in the future.
26672 		 */
26673 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26674 		return (B_FALSE);
26675 	}
26676 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26677 	ASSERT((io->ipsec_out_policy != NULL) ||
26678 	    (io->ipsec_out_act != NULL));
26679 
26680 	ASSERT(io->ipsec_out_failed == B_FALSE);
26681 
26682 	/*
26683 	 * IPsec processing has started.
26684 	 */
26685 	io->ipsec_out_proc_begin = B_TRUE;
26686 	ap = io->ipsec_out_act;
26687 	if (ap == NULL) {
26688 		pp = io->ipsec_out_policy;
26689 		ASSERT(pp != NULL);
26690 		ap = pp->ipsp_act;
26691 		ASSERT(ap != NULL);
26692 	}
26693 
26694 	/*
26695 	 * We have an action.  now, let's select SA's.
26696 	 * (In the future, we can cache this in the conn_t..)
26697 	 */
26698 	if (ap->ipa_want_esp) {
26699 		if (io->ipsec_out_esp_sa == NULL) {
26700 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26701 			    IPPROTO_ESP);
26702 		}
26703 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26704 	}
26705 
26706 	if (ap->ipa_want_ah) {
26707 		if (io->ipsec_out_ah_sa == NULL) {
26708 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26709 			    IPPROTO_AH);
26710 		}
26711 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26712 		/*
26713 		 * The ESP and AH processing order needs to be preserved
26714 		 * when both protocols are required (ESP should be applied
26715 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26716 		 * when both ESP and AH are required, and an AH ACQUIRE
26717 		 * is needed.
26718 		 */
26719 		if (ap->ipa_want_esp && need_ah_acquire)
26720 			need_esp_acquire = B_TRUE;
26721 	}
26722 
26723 	/*
26724 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26725 	 * Release SAs that got referenced, but will not be used until we
26726 	 * acquire _all_ of the SAs we need.
26727 	 */
26728 	if (need_ah_acquire || need_esp_acquire) {
26729 		if (io->ipsec_out_ah_sa != NULL) {
26730 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26731 			io->ipsec_out_ah_sa = NULL;
26732 		}
26733 		if (io->ipsec_out_esp_sa != NULL) {
26734 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26735 			io->ipsec_out_esp_sa = NULL;
26736 		}
26737 
26738 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26739 		return (B_FALSE);
26740 	}
26741 
26742 	return (B_TRUE);
26743 }
26744 
26745 /*
26746  * Process an IPSEC_OUT message and see what you can
26747  * do with it.
26748  * IPQoS Notes:
26749  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26750  * IPsec.
26751  * XXX would like to nuke ire_t.
26752  * XXX ill_index better be "real"
26753  */
26754 void
26755 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26756 {
26757 	ipsec_out_t *io;
26758 	ipsec_policy_t *pp;
26759 	ipsec_action_t *ap;
26760 	ipha_t *ipha;
26761 	ip6_t *ip6h;
26762 	mblk_t *mp;
26763 	ill_t *ill;
26764 	zoneid_t zoneid;
26765 	ipsec_status_t ipsec_rc;
26766 	boolean_t ill_need_rele = B_FALSE;
26767 	ip_stack_t	*ipst;
26768 	ipsec_stack_t	*ipss;
26769 
26770 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26771 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26772 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26773 	ipst = io->ipsec_out_ns->netstack_ip;
26774 	mp = ipsec_mp->b_cont;
26775 
26776 	/*
26777 	 * Initiate IPPF processing. We do it here to account for packets
26778 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26779 	 * We can check for ipsec_out_proc_begin even for such packets, as
26780 	 * they will always be false (asserted below).
26781 	 */
26782 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26783 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26784 		    io->ipsec_out_ill_index : ill_index);
26785 		if (mp == NULL) {
26786 			ip2dbg(("ipsec_out_process: packet dropped "\
26787 			    "during IPPF processing\n"));
26788 			freeb(ipsec_mp);
26789 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26790 			return;
26791 		}
26792 	}
26793 
26794 	if (!io->ipsec_out_secure) {
26795 		/*
26796 		 * We came here by mistake.
26797 		 * Don't bother with ipsec processing
26798 		 * Should "discourage" this path in the future.
26799 		 */
26800 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26801 		goto done;
26802 	}
26803 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26804 	ASSERT((io->ipsec_out_policy != NULL) ||
26805 	    (io->ipsec_out_act != NULL));
26806 	ASSERT(io->ipsec_out_failed == B_FALSE);
26807 
26808 	ipss = ipst->ips_netstack->netstack_ipsec;
26809 	if (!ipsec_loaded(ipss)) {
26810 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26811 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26812 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26813 		} else {
26814 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26815 		}
26816 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26817 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26818 		    &ipss->ipsec_dropper);
26819 		return;
26820 	}
26821 
26822 	/*
26823 	 * IPsec processing has started.
26824 	 */
26825 	io->ipsec_out_proc_begin = B_TRUE;
26826 	ap = io->ipsec_out_act;
26827 	if (ap == NULL) {
26828 		pp = io->ipsec_out_policy;
26829 		ASSERT(pp != NULL);
26830 		ap = pp->ipsp_act;
26831 		ASSERT(ap != NULL);
26832 	}
26833 
26834 	/*
26835 	 * Save the outbound ill index. When the packet comes back
26836 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26837 	 * before sending it the accelerated packet.
26838 	 */
26839 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26840 		int ifindex;
26841 		ill = ire_to_ill(ire);
26842 		ifindex = ill->ill_phyint->phyint_ifindex;
26843 		io->ipsec_out_capab_ill_index = ifindex;
26844 	}
26845 
26846 	/*
26847 	 * The order of processing is first insert a IP header if needed.
26848 	 * Then insert the ESP header and then the AH header.
26849 	 */
26850 	if ((io->ipsec_out_se_done == B_FALSE) &&
26851 	    (ap->ipa_want_se)) {
26852 		/*
26853 		 * First get the outer IP header before sending
26854 		 * it to ESP.
26855 		 */
26856 		ipha_t *oipha, *iipha;
26857 		mblk_t *outer_mp, *inner_mp;
26858 
26859 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26860 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26861 			    "ipsec_out_process: "
26862 			    "Self-Encapsulation failed: Out of memory\n");
26863 			freemsg(ipsec_mp);
26864 			if (ill != NULL) {
26865 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26866 			} else {
26867 				BUMP_MIB(&ipst->ips_ip_mib,
26868 				    ipIfStatsOutDiscards);
26869 			}
26870 			return;
26871 		}
26872 		inner_mp = ipsec_mp->b_cont;
26873 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26874 		oipha = (ipha_t *)outer_mp->b_rptr;
26875 		iipha = (ipha_t *)inner_mp->b_rptr;
26876 		*oipha = *iipha;
26877 		outer_mp->b_wptr += sizeof (ipha_t);
26878 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26879 		    sizeof (ipha_t));
26880 		oipha->ipha_protocol = IPPROTO_ENCAP;
26881 		oipha->ipha_version_and_hdr_length =
26882 		    IP_SIMPLE_HDR_VERSION;
26883 		oipha->ipha_hdr_checksum = 0;
26884 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26885 		outer_mp->b_cont = inner_mp;
26886 		ipsec_mp->b_cont = outer_mp;
26887 
26888 		io->ipsec_out_se_done = B_TRUE;
26889 		io->ipsec_out_tunnel = B_TRUE;
26890 	}
26891 
26892 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26893 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26894 	    !ipsec_out_select_sa(ipsec_mp))
26895 		return;
26896 
26897 	/*
26898 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26899 	 * to do the heavy lifting.
26900 	 */
26901 	zoneid = io->ipsec_out_zoneid;
26902 	ASSERT(zoneid != ALL_ZONES);
26903 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26904 		ASSERT(io->ipsec_out_esp_sa != NULL);
26905 		io->ipsec_out_esp_done = B_TRUE;
26906 		/*
26907 		 * Note that since hw accel can only apply one transform,
26908 		 * not two, we skip hw accel for ESP if we also have AH
26909 		 * This is an design limitation of the interface
26910 		 * which should be revisited.
26911 		 */
26912 		ASSERT(ire != NULL);
26913 		if (io->ipsec_out_ah_sa == NULL) {
26914 			ill = (ill_t *)ire->ire_stq->q_ptr;
26915 			ipsec_out_is_accelerated(ipsec_mp,
26916 			    io->ipsec_out_esp_sa, ill, ire);
26917 		}
26918 
26919 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26920 		switch (ipsec_rc) {
26921 		case IPSEC_STATUS_SUCCESS:
26922 			break;
26923 		case IPSEC_STATUS_FAILED:
26924 			if (ill != NULL) {
26925 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26926 			} else {
26927 				BUMP_MIB(&ipst->ips_ip_mib,
26928 				    ipIfStatsOutDiscards);
26929 			}
26930 			/* FALLTHRU */
26931 		case IPSEC_STATUS_PENDING:
26932 			return;
26933 		}
26934 	}
26935 
26936 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26937 		ASSERT(io->ipsec_out_ah_sa != NULL);
26938 		io->ipsec_out_ah_done = B_TRUE;
26939 		if (ire == NULL) {
26940 			int idx = io->ipsec_out_capab_ill_index;
26941 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26942 			    NULL, NULL, NULL, NULL, ipst);
26943 			ill_need_rele = B_TRUE;
26944 		} else {
26945 			ill = (ill_t *)ire->ire_stq->q_ptr;
26946 		}
26947 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26948 		    ire);
26949 
26950 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26951 		switch (ipsec_rc) {
26952 		case IPSEC_STATUS_SUCCESS:
26953 			break;
26954 		case IPSEC_STATUS_FAILED:
26955 			if (ill != NULL) {
26956 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26957 			} else {
26958 				BUMP_MIB(&ipst->ips_ip_mib,
26959 				    ipIfStatsOutDiscards);
26960 			}
26961 			/* FALLTHRU */
26962 		case IPSEC_STATUS_PENDING:
26963 			if (ill != NULL && ill_need_rele)
26964 				ill_refrele(ill);
26965 			return;
26966 		}
26967 	}
26968 	/*
26969 	 * We are done with IPsec processing. Send it over
26970 	 * the wire.
26971 	 */
26972 done:
26973 	mp = ipsec_mp->b_cont;
26974 	ipha = (ipha_t *)mp->b_rptr;
26975 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26976 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26977 	} else {
26978 		ip6h = (ip6_t *)ipha;
26979 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26980 	}
26981 	if (ill != NULL && ill_need_rele)
26982 		ill_refrele(ill);
26983 }
26984 
26985 /* ARGSUSED */
26986 void
26987 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26988 {
26989 	opt_restart_t	*or;
26990 	int	err;
26991 	conn_t	*connp;
26992 
26993 	ASSERT(CONN_Q(q));
26994 	connp = Q_TO_CONN(q);
26995 
26996 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26997 	or = (opt_restart_t *)first_mp->b_rptr;
26998 	/*
26999 	 * We don't need to pass any credentials here since this is just
27000 	 * a restart. The credentials are passed in when svr4_optcom_req
27001 	 * is called the first time (from ip_wput_nondata).
27002 	 */
27003 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27004 		err = svr4_optcom_req(q, first_mp, NULL,
27005 		    &ip_opt_obj, B_FALSE);
27006 	} else {
27007 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27008 		err = tpi_optcom_req(q, first_mp, NULL,
27009 		    &ip_opt_obj, B_FALSE);
27010 	}
27011 	if (err != EINPROGRESS) {
27012 		/* operation is done */
27013 		CONN_OPER_PENDING_DONE(connp);
27014 	}
27015 }
27016 
27017 /*
27018  * ioctls that go through a down/up sequence may need to wait for the down
27019  * to complete. This involves waiting for the ire and ipif refcnts to go down
27020  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27021  */
27022 /* ARGSUSED */
27023 void
27024 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27025 {
27026 	struct iocblk *iocp;
27027 	mblk_t *mp1;
27028 	ip_ioctl_cmd_t *ipip;
27029 	int err;
27030 	sin_t	*sin;
27031 	struct lifreq *lifr;
27032 	struct ifreq *ifr;
27033 
27034 	iocp = (struct iocblk *)mp->b_rptr;
27035 	ASSERT(ipsq != NULL);
27036 	/* Existence of mp1 verified in ip_wput_nondata */
27037 	mp1 = mp->b_cont->b_cont;
27038 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27039 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27040 		/*
27041 		 * Special case where ipsq_current_ipif is not set:
27042 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27043 		 * ill could also have become part of a ipmp group in the
27044 		 * process, we are here as were not able to complete the
27045 		 * operation in ipif_set_values because we could not become
27046 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27047 		 * will not be set so we need to set it.
27048 		 */
27049 		ill_t *ill = q->q_ptr;
27050 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27051 	}
27052 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27053 
27054 	if (ipip->ipi_cmd_type == IF_CMD) {
27055 		/* This a old style SIOC[GS]IF* command */
27056 		ifr = (struct ifreq *)mp1->b_rptr;
27057 		sin = (sin_t *)&ifr->ifr_addr;
27058 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27059 		/* This a new style SIOC[GS]LIF* command */
27060 		lifr = (struct lifreq *)mp1->b_rptr;
27061 		sin = (sin_t *)&lifr->lifr_addr;
27062 	} else {
27063 		sin = NULL;
27064 	}
27065 
27066 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27067 	    ipip, mp1->b_rptr);
27068 
27069 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27070 }
27071 
27072 /*
27073  * ioctl processing
27074  *
27075  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
27076  * the ioctl command in the ioctl tables, determines the copyin data size
27077  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
27078  *
27079  * ioctl processing then continues when the M_IOCDATA makes its way down to
27080  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
27081  * associated 'conn' is refheld till the end of the ioctl and the general
27082  * ioctl processing function ip_process_ioctl() is called to extract the
27083  * arguments and process the ioctl.  To simplify extraction, ioctl commands
27084  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
27085  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27086  * is used to extract the ioctl's arguments.
27087  *
27088  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27089  * so goes thru the serialization primitive ipsq_try_enter. Then the
27090  * appropriate function to handle the ioctl is called based on the entry in
27091  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27092  * which also refreleases the 'conn' that was refheld at the start of the
27093  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27094  *
27095  * Many exclusive ioctls go thru an internal down up sequence as part of
27096  * the operation. For example an attempt to change the IP address of an
27097  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27098  * does all the cleanup such as deleting all ires that use this address.
27099  * Then we need to wait till all references to the interface go away.
27100  */
27101 void
27102 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27103 {
27104 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27105 	ip_ioctl_cmd_t *ipip = arg;
27106 	ip_extract_func_t *extract_funcp;
27107 	cmd_info_t ci;
27108 	int err;
27109 
27110 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27111 
27112 	if (ipip == NULL)
27113 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27114 
27115 	/*
27116 	 * SIOCLIFADDIF needs to go thru a special path since the
27117 	 * ill may not exist yet. This happens in the case of lo0
27118 	 * which is created using this ioctl.
27119 	 */
27120 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27121 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27122 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27123 		return;
27124 	}
27125 
27126 	ci.ci_ipif = NULL;
27127 	if (ipip->ipi_cmd_type == MISC_CMD) {
27128 		/*
27129 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27130 		 */
27131 		if (ipip->ipi_cmd == IF_UNITSEL) {
27132 			/* ioctl comes down the ill */
27133 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27134 			ipif_refhold(ci.ci_ipif);
27135 		}
27136 		err = 0;
27137 		ci.ci_sin = NULL;
27138 		ci.ci_sin6 = NULL;
27139 		ci.ci_lifr = NULL;
27140 	} else {
27141 		switch (ipip->ipi_cmd_type) {
27142 		case IF_CMD:
27143 		case LIF_CMD:
27144 			extract_funcp = ip_extract_lifreq;
27145 			break;
27146 
27147 		case ARP_CMD:
27148 		case XARP_CMD:
27149 			extract_funcp = ip_extract_arpreq;
27150 			break;
27151 
27152 		case TUN_CMD:
27153 			extract_funcp = ip_extract_tunreq;
27154 			break;
27155 
27156 		case MSFILT_CMD:
27157 			extract_funcp = ip_extract_msfilter;
27158 			break;
27159 
27160 		default:
27161 			ASSERT(0);
27162 		}
27163 
27164 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27165 		if (err != 0) {
27166 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27167 			return;
27168 		}
27169 
27170 		/*
27171 		 * All of the extraction functions return a refheld ipif.
27172 		 */
27173 		ASSERT(ci.ci_ipif != NULL);
27174 	}
27175 
27176 	if (!(ipip->ipi_flags & IPI_WR)) {
27177 		/*
27178 		 * A return value of EINPROGRESS means the ioctl is
27179 		 * either queued and waiting for some reason or has
27180 		 * already completed.
27181 		 */
27182 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27183 		    ci.ci_lifr);
27184 		if (ci.ci_ipif != NULL)
27185 			ipif_refrele(ci.ci_ipif);
27186 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27187 		return;
27188 	}
27189 
27190 	/*
27191 	 * If ipsq is non-null, we are already being called exclusively on an
27192 	 * ill but in the case of a failover in progress it is the "from" ill,
27193 	 *  rather than the "to" ill (which is the ill ptr passed in).
27194 	 * In order to ensure we are exclusive on both ILLs we rerun
27195 	 * ipsq_try_enter() here, ipsq's support recursive entry.
27196 	 */
27197 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27198 	ASSERT(ci.ci_ipif != NULL);
27199 
27200 	ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
27201 	    NEW_OP, B_TRUE);
27202 
27203 	/*
27204 	 * Release the ipif so that ipif_down and friends that wait for
27205 	 * references to go away are not misled about the current ipif_refcnt
27206 	 * values. We are writer so we can access the ipif even after releasing
27207 	 * the ipif.
27208 	 */
27209 	ipif_refrele(ci.ci_ipif);
27210 	if (ipsq == NULL)
27211 		return;
27212 
27213 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27214 
27215 	/*
27216 	 * For most set ioctls that come here, this serves as a single point
27217 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27218 	 * be any new references to the ipif. This helps functions that go
27219 	 * through this path and end up trying to wait for the refcnts
27220 	 * associated with the ipif to go down to zero. Some exceptions are
27221 	 * Failover, Failback, and Groupname commands that operate on more than
27222 	 * just the ci.ci_ipif. These commands internally determine the
27223 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27224 	 * flags on that set. Another exception is the Removeif command that
27225 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27226 	 * ipif to operate on.
27227 	 */
27228 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27229 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27230 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27231 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27232 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27233 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27234 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27235 
27236 	/*
27237 	 * A return value of EINPROGRESS means the ioctl is
27238 	 * either queued and waiting for some reason or has
27239 	 * already completed.
27240 	 */
27241 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27242 
27243 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27244 
27245 	ipsq_exit(ipsq);
27246 }
27247 
27248 /*
27249  * Complete the ioctl. Typically ioctls use the mi package and need to
27250  * do mi_copyout/mi_copy_done.
27251  */
27252 void
27253 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27254 {
27255 	conn_t	*connp = NULL;
27256 
27257 	if (err == EINPROGRESS)
27258 		return;
27259 
27260 	if (CONN_Q(q)) {
27261 		connp = Q_TO_CONN(q);
27262 		ASSERT(connp->conn_ref >= 2);
27263 	}
27264 
27265 	switch (mode) {
27266 	case COPYOUT:
27267 		if (err == 0)
27268 			mi_copyout(q, mp);
27269 		else
27270 			mi_copy_done(q, mp, err);
27271 		break;
27272 
27273 	case NO_COPYOUT:
27274 		mi_copy_done(q, mp, err);
27275 		break;
27276 
27277 	default:
27278 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27279 		break;
27280 	}
27281 
27282 	/*
27283 	 * The refhold placed at the start of the ioctl is released here.
27284 	 */
27285 	if (connp != NULL)
27286 		CONN_OPER_PENDING_DONE(connp);
27287 
27288 	if (ipsq != NULL)
27289 		ipsq_current_finish(ipsq);
27290 }
27291 
27292 /*
27293  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27294  */
27295 /* ARGSUSED */
27296 void
27297 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27298 {
27299 	conn_t *connp = arg;
27300 	tcp_t	*tcp;
27301 
27302 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27303 	tcp = connp->conn_tcp;
27304 
27305 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27306 		freemsg(mp);
27307 	else
27308 		tcp_rput_other(tcp, mp);
27309 	CONN_OPER_PENDING_DONE(connp);
27310 }
27311 
27312 /* Called from ip_wput for all non data messages */
27313 /* ARGSUSED */
27314 void
27315 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27316 {
27317 	mblk_t		*mp1;
27318 	ire_t		*ire, *fake_ire;
27319 	ill_t		*ill;
27320 	struct iocblk	*iocp;
27321 	ip_ioctl_cmd_t	*ipip;
27322 	cred_t		*cr;
27323 	conn_t		*connp;
27324 	int		err;
27325 	nce_t		*nce;
27326 	ipif_t		*ipif;
27327 	ip_stack_t	*ipst;
27328 	char		*proto_str;
27329 
27330 	if (CONN_Q(q)) {
27331 		connp = Q_TO_CONN(q);
27332 		ipst = connp->conn_netstack->netstack_ip;
27333 	} else {
27334 		connp = NULL;
27335 		ipst = ILLQ_TO_IPST(q);
27336 	}
27337 
27338 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27339 
27340 	switch (DB_TYPE(mp)) {
27341 	case M_IOCTL:
27342 		/*
27343 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27344 		 * will arrange to copy in associated control structures.
27345 		 */
27346 		ip_sioctl_copyin_setup(q, mp);
27347 		return;
27348 	case M_IOCDATA:
27349 		/*
27350 		 * Ensure that this is associated with one of our trans-
27351 		 * parent ioctls.  If it's not ours, discard it if we're
27352 		 * running as a driver, or pass it on if we're a module.
27353 		 */
27354 		iocp = (struct iocblk *)mp->b_rptr;
27355 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27356 		if (ipip == NULL) {
27357 			if (q->q_next == NULL) {
27358 				goto nak;
27359 			} else {
27360 				putnext(q, mp);
27361 			}
27362 			return;
27363 		}
27364 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27365 			/*
27366 			 * the ioctl is one we recognise, but is not
27367 			 * consumed by IP as a module, pass M_IOCDATA
27368 			 * for processing downstream, but only for
27369 			 * common Streams ioctls.
27370 			 */
27371 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27372 				putnext(q, mp);
27373 				return;
27374 			} else {
27375 				goto nak;
27376 			}
27377 		}
27378 
27379 		/* IOCTL continuation following copyin or copyout. */
27380 		if (mi_copy_state(q, mp, NULL) == -1) {
27381 			/*
27382 			 * The copy operation failed.  mi_copy_state already
27383 			 * cleaned up, so we're out of here.
27384 			 */
27385 			return;
27386 		}
27387 		/*
27388 		 * If we just completed a copy in, we become writer and
27389 		 * continue processing in ip_sioctl_copyin_done.  If it
27390 		 * was a copy out, we call mi_copyout again.  If there is
27391 		 * nothing more to copy out, it will complete the IOCTL.
27392 		 */
27393 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27394 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27395 				mi_copy_done(q, mp, EPROTO);
27396 				return;
27397 			}
27398 			/*
27399 			 * Check for cases that need more copying.  A return
27400 			 * value of 0 means a second copyin has been started,
27401 			 * so we return; a return value of 1 means no more
27402 			 * copying is needed, so we continue.
27403 			 */
27404 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27405 			    MI_COPY_COUNT(mp) == 1) {
27406 				if (ip_copyin_msfilter(q, mp) == 0)
27407 					return;
27408 			}
27409 			/*
27410 			 * Refhold the conn, till the ioctl completes. This is
27411 			 * needed in case the ioctl ends up in the pending mp
27412 			 * list. Every mp in the ill_pending_mp list and
27413 			 * the ipsq_pending_mp must have a refhold on the conn
27414 			 * to resume processing. The refhold is released when
27415 			 * the ioctl completes. (normally or abnormally)
27416 			 * In all cases ip_ioctl_finish is called to finish
27417 			 * the ioctl.
27418 			 */
27419 			if (connp != NULL) {
27420 				/* This is not a reentry */
27421 				ASSERT(ipsq == NULL);
27422 				CONN_INC_REF(connp);
27423 			} else {
27424 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27425 					mi_copy_done(q, mp, EINVAL);
27426 					return;
27427 				}
27428 			}
27429 
27430 			ip_process_ioctl(ipsq, q, mp, ipip);
27431 
27432 		} else {
27433 			mi_copyout(q, mp);
27434 		}
27435 		return;
27436 nak:
27437 		iocp->ioc_error = EINVAL;
27438 		mp->b_datap->db_type = M_IOCNAK;
27439 		iocp->ioc_count = 0;
27440 		qreply(q, mp);
27441 		return;
27442 
27443 	case M_IOCNAK:
27444 		/*
27445 		 * The only way we could get here is if a resolver didn't like
27446 		 * an IOCTL we sent it.	 This shouldn't happen.
27447 		 */
27448 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27449 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27450 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27451 		freemsg(mp);
27452 		return;
27453 	case M_IOCACK:
27454 		/* /dev/ip shouldn't see this */
27455 		if (CONN_Q(q))
27456 			goto nak;
27457 
27458 		/* Finish socket ioctls passed through to ARP. */
27459 		ip_sioctl_iocack(q, mp);
27460 		return;
27461 	case M_FLUSH:
27462 		if (*mp->b_rptr & FLUSHW)
27463 			flushq(q, FLUSHALL);
27464 		if (q->q_next) {
27465 			putnext(q, mp);
27466 			return;
27467 		}
27468 		if (*mp->b_rptr & FLUSHR) {
27469 			*mp->b_rptr &= ~FLUSHW;
27470 			qreply(q, mp);
27471 			return;
27472 		}
27473 		freemsg(mp);
27474 		return;
27475 	case IRE_DB_REQ_TYPE:
27476 		if (connp == NULL) {
27477 			proto_str = "IRE_DB_REQ_TYPE";
27478 			goto protonak;
27479 		}
27480 		/* An Upper Level Protocol wants a copy of an IRE. */
27481 		ip_ire_req(q, mp);
27482 		return;
27483 	case M_CTL:
27484 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27485 			break;
27486 
27487 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27488 		    TUN_HELLO) {
27489 			ASSERT(connp != NULL);
27490 			connp->conn_flags |= IPCL_IPTUN;
27491 			freeb(mp);
27492 			return;
27493 		}
27494 
27495 		/* M_CTL messages are used by ARP to tell us things. */
27496 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27497 			break;
27498 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27499 		case AR_ENTRY_SQUERY:
27500 			ip_wput_ctl(q, mp);
27501 			return;
27502 		case AR_CLIENT_NOTIFY:
27503 			ip_arp_news(q, mp);
27504 			return;
27505 		case AR_DLPIOP_DONE:
27506 			ASSERT(q->q_next != NULL);
27507 			ill = (ill_t *)q->q_ptr;
27508 			/* qwriter_ip releases the refhold */
27509 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27510 			ill_refhold(ill);
27511 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27512 			return;
27513 		case AR_ARP_CLOSING:
27514 			/*
27515 			 * ARP (above us) is closing. If no ARP bringup is
27516 			 * currently pending, ack the message so that ARP
27517 			 * can complete its close. Also mark ill_arp_closing
27518 			 * so that new ARP bringups will fail. If any
27519 			 * ARP bringup is currently in progress, we will
27520 			 * ack this when the current ARP bringup completes.
27521 			 */
27522 			ASSERT(q->q_next != NULL);
27523 			ill = (ill_t *)q->q_ptr;
27524 			mutex_enter(&ill->ill_lock);
27525 			ill->ill_arp_closing = 1;
27526 			if (!ill->ill_arp_bringup_pending) {
27527 				mutex_exit(&ill->ill_lock);
27528 				qreply(q, mp);
27529 			} else {
27530 				mutex_exit(&ill->ill_lock);
27531 				freemsg(mp);
27532 			}
27533 			return;
27534 		case AR_ARP_EXTEND:
27535 			/*
27536 			 * The ARP module above us is capable of duplicate
27537 			 * address detection.  Old ATM drivers will not send
27538 			 * this message.
27539 			 */
27540 			ASSERT(q->q_next != NULL);
27541 			ill = (ill_t *)q->q_ptr;
27542 			ill->ill_arp_extend = B_TRUE;
27543 			freemsg(mp);
27544 			return;
27545 		default:
27546 			break;
27547 		}
27548 		break;
27549 	case M_PROTO:
27550 	case M_PCPROTO:
27551 		/*
27552 		 * The only PROTO messages we expect are ULP binds and
27553 		 * copies of option negotiation acknowledgements.
27554 		 */
27555 		switch (((union T_primitives *)mp->b_rptr)->type) {
27556 		case O_T_BIND_REQ:
27557 		case T_BIND_REQ: {
27558 			/* Request can get queued in bind */
27559 			if (connp == NULL) {
27560 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27561 				goto protonak;
27562 			}
27563 			/*
27564 			 * The transports except SCTP call ip_bind_{v4,v6}()
27565 			 * directly instead of a a putnext. SCTP doesn't
27566 			 * generate any T_BIND_REQ since it has its own
27567 			 * fanout data structures. However, ESP and AH
27568 			 * come in for regular binds; all other cases are
27569 			 * bind retries.
27570 			 */
27571 			ASSERT(!IPCL_IS_SCTP(connp));
27572 
27573 			/* Don't increment refcnt if this is a re-entry */
27574 			if (ipsq == NULL)
27575 				CONN_INC_REF(connp);
27576 
27577 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27578 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27579 			if (mp == NULL)
27580 				return;
27581 			if (IPCL_IS_TCP(connp)) {
27582 				/*
27583 				 * In the case of TCP endpoint we
27584 				 * come here only for bind retries
27585 				 */
27586 				ASSERT(ipsq != NULL);
27587 				CONN_INC_REF(connp);
27588 				squeue_fill(connp->conn_sqp, mp,
27589 				    ip_resume_tcp_bind, connp,
27590 				    SQTAG_BIND_RETRY);
27591 			} else if (IPCL_IS_UDP(connp)) {
27592 				/*
27593 				 * In the case of UDP endpoint we
27594 				 * come here only for bind retries
27595 				 */
27596 				ASSERT(ipsq != NULL);
27597 				udp_resume_bind(connp, mp);
27598 			} else if (IPCL_IS_RAWIP(connp)) {
27599 				/*
27600 				 * In the case of RAWIP endpoint we
27601 				 * come here only for bind retries
27602 				 */
27603 				ASSERT(ipsq != NULL);
27604 				rawip_resume_bind(connp, mp);
27605 			} else {
27606 				/* The case of AH and ESP */
27607 				qreply(q, mp);
27608 				CONN_OPER_PENDING_DONE(connp);
27609 			}
27610 			return;
27611 		}
27612 		case T_SVR4_OPTMGMT_REQ:
27613 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27614 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27615 
27616 			if (connp == NULL) {
27617 				proto_str = "T_SVR4_OPTMGMT_REQ";
27618 				goto protonak;
27619 			}
27620 
27621 			if (!snmpcom_req(q, mp, ip_snmp_set,
27622 			    ip_snmp_get, cr)) {
27623 				/*
27624 				 * Call svr4_optcom_req so that it can
27625 				 * generate the ack. We don't come here
27626 				 * if this operation is being restarted.
27627 				 * ip_restart_optmgmt will drop the conn ref.
27628 				 * In the case of ipsec option after the ipsec
27629 				 * load is complete conn_restart_ipsec_waiter
27630 				 * drops the conn ref.
27631 				 */
27632 				ASSERT(ipsq == NULL);
27633 				CONN_INC_REF(connp);
27634 				if (ip_check_for_ipsec_opt(q, mp))
27635 					return;
27636 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27637 				    B_FALSE);
27638 				if (err != EINPROGRESS) {
27639 					/* Operation is done */
27640 					CONN_OPER_PENDING_DONE(connp);
27641 				}
27642 			}
27643 			return;
27644 		case T_OPTMGMT_REQ:
27645 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27646 			/*
27647 			 * Note: No snmpcom_req support through new
27648 			 * T_OPTMGMT_REQ.
27649 			 * Call tpi_optcom_req so that it can
27650 			 * generate the ack.
27651 			 */
27652 			if (connp == NULL) {
27653 				proto_str = "T_OPTMGMT_REQ";
27654 				goto protonak;
27655 			}
27656 
27657 			ASSERT(ipsq == NULL);
27658 			/*
27659 			 * We don't come here for restart. ip_restart_optmgmt
27660 			 * will drop the conn ref. In the case of ipsec option
27661 			 * after the ipsec load is complete
27662 			 * conn_restart_ipsec_waiter drops the conn ref.
27663 			 */
27664 			CONN_INC_REF(connp);
27665 			if (ip_check_for_ipsec_opt(q, mp))
27666 				return;
27667 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27668 			if (err != EINPROGRESS) {
27669 				/* Operation is done */
27670 				CONN_OPER_PENDING_DONE(connp);
27671 			}
27672 			return;
27673 		case T_UNBIND_REQ:
27674 			if (connp == NULL) {
27675 				proto_str = "T_UNBIND_REQ";
27676 				goto protonak;
27677 			}
27678 			mp = ip_unbind(q, mp);
27679 			qreply(q, mp);
27680 			return;
27681 		default:
27682 			/*
27683 			 * Have to drop any DLPI messages coming down from
27684 			 * arp (such as an info_req which would cause ip
27685 			 * to receive an extra info_ack if it was passed
27686 			 * through.
27687 			 */
27688 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27689 			    (int)*(uint_t *)mp->b_rptr));
27690 			freemsg(mp);
27691 			return;
27692 		}
27693 		/* NOTREACHED */
27694 	case IRE_DB_TYPE: {
27695 		nce_t		*nce;
27696 		ill_t		*ill;
27697 		in6_addr_t	gw_addr_v6;
27698 
27699 
27700 		/*
27701 		 * This is a response back from a resolver.  It
27702 		 * consists of a message chain containing:
27703 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27704 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27705 		 * The LL_HDR_MBLK is the DLPI header to use to get
27706 		 * the attached packet, and subsequent ones for the
27707 		 * same destination, transmitted.
27708 		 */
27709 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27710 			break;
27711 		/*
27712 		 * First, check to make sure the resolution succeeded.
27713 		 * If it failed, the second mblk will be empty.
27714 		 * If it is, free the chain, dropping the packet.
27715 		 * (We must ire_delete the ire; that frees the ire mblk)
27716 		 * We're doing this now to support PVCs for ATM; it's
27717 		 * a partial xresolv implementation. When we fully implement
27718 		 * xresolv interfaces, instead of freeing everything here
27719 		 * we'll initiate neighbor discovery.
27720 		 *
27721 		 * For v4 (ARP and other external resolvers) the resolver
27722 		 * frees the message, so no check is needed. This check
27723 		 * is required, though, for a full xresolve implementation.
27724 		 * Including this code here now both shows how external
27725 		 * resolvers can NACK a resolution request using an
27726 		 * existing design that has no specific provisions for NACKs,
27727 		 * and also takes into account that the current non-ARP
27728 		 * external resolver has been coded to use this method of
27729 		 * NACKing for all IPv6 (xresolv) cases,
27730 		 * whether our xresolv implementation is complete or not.
27731 		 *
27732 		 */
27733 		ire = (ire_t *)mp->b_rptr;
27734 		ill = ire_to_ill(ire);
27735 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27736 		if (mp1->b_rptr == mp1->b_wptr) {
27737 			if (ire->ire_ipversion == IPV6_VERSION) {
27738 				/*
27739 				 * XRESOLV interface.
27740 				 */
27741 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27742 				mutex_enter(&ire->ire_lock);
27743 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27744 				mutex_exit(&ire->ire_lock);
27745 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27746 					nce = ndp_lookup_v6(ill,
27747 					    &ire->ire_addr_v6, B_FALSE);
27748 				} else {
27749 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27750 					    B_FALSE);
27751 				}
27752 				if (nce != NULL) {
27753 					nce_resolv_failed(nce);
27754 					ndp_delete(nce);
27755 					NCE_REFRELE(nce);
27756 				}
27757 			}
27758 			mp->b_cont = NULL;
27759 			freemsg(mp1);		/* frees the pkt as well */
27760 			ASSERT(ire->ire_nce == NULL);
27761 			ire_delete((ire_t *)mp->b_rptr);
27762 			return;
27763 		}
27764 
27765 		/*
27766 		 * Split them into IRE_MBLK and pkt and feed it into
27767 		 * ire_add_then_send. Then in ire_add_then_send
27768 		 * the IRE will be added, and then the packet will be
27769 		 * run back through ip_wput. This time it will make
27770 		 * it to the wire.
27771 		 */
27772 		mp->b_cont = NULL;
27773 		mp = mp1->b_cont;		/* now, mp points to pkt */
27774 		mp1->b_cont = NULL;
27775 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27776 		if (ire->ire_ipversion == IPV6_VERSION) {
27777 			/*
27778 			 * XRESOLV interface. Find the nce and put a copy
27779 			 * of the dl_unitdata_req in nce_res_mp
27780 			 */
27781 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27782 			mutex_enter(&ire->ire_lock);
27783 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27784 			mutex_exit(&ire->ire_lock);
27785 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27786 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27787 				    B_FALSE);
27788 			} else {
27789 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27790 			}
27791 			if (nce != NULL) {
27792 				/*
27793 				 * We have to protect nce_res_mp here
27794 				 * from being accessed by other threads
27795 				 * while we change the mblk pointer.
27796 				 * Other functions will also lock the nce when
27797 				 * accessing nce_res_mp.
27798 				 *
27799 				 * The reason we change the mblk pointer
27800 				 * here rather than copying the resolved address
27801 				 * into the template is that, unlike with
27802 				 * ethernet, we have no guarantee that the
27803 				 * resolved address length will be
27804 				 * smaller than or equal to the lla length
27805 				 * with which the template was allocated,
27806 				 * (for ethernet, they're equal)
27807 				 * so we have to use the actual resolved
27808 				 * address mblk - which holds the real
27809 				 * dl_unitdata_req with the resolved address.
27810 				 *
27811 				 * Doing this is the same behavior as was
27812 				 * previously used in the v4 ARP case.
27813 				 */
27814 				mutex_enter(&nce->nce_lock);
27815 				if (nce->nce_res_mp != NULL)
27816 					freemsg(nce->nce_res_mp);
27817 				nce->nce_res_mp = mp1;
27818 				mutex_exit(&nce->nce_lock);
27819 				/*
27820 				 * We do a fastpath probe here because
27821 				 * we have resolved the address without
27822 				 * using Neighbor Discovery.
27823 				 * In the non-XRESOLV v6 case, the fastpath
27824 				 * probe is done right after neighbor
27825 				 * discovery completes.
27826 				 */
27827 				if (nce->nce_res_mp != NULL) {
27828 					int res;
27829 					nce_fastpath_list_add(nce);
27830 					res = ill_fastpath_probe(ill,
27831 					    nce->nce_res_mp);
27832 					if (res != 0 && res != EAGAIN)
27833 						nce_fastpath_list_delete(nce);
27834 				}
27835 
27836 				ire_add_then_send(q, ire, mp);
27837 				/*
27838 				 * Now we have to clean out any packets
27839 				 * that may have been queued on the nce
27840 				 * while it was waiting for address resolution
27841 				 * to complete.
27842 				 */
27843 				mutex_enter(&nce->nce_lock);
27844 				mp1 = nce->nce_qd_mp;
27845 				nce->nce_qd_mp = NULL;
27846 				mutex_exit(&nce->nce_lock);
27847 				while (mp1 != NULL) {
27848 					mblk_t *nxt_mp;
27849 					queue_t *fwdq = NULL;
27850 					ill_t   *inbound_ill;
27851 					uint_t ifindex;
27852 
27853 					nxt_mp = mp1->b_next;
27854 					mp1->b_next = NULL;
27855 					/*
27856 					 * Retrieve ifindex stored in
27857 					 * ip_rput_data_v6()
27858 					 */
27859 					ifindex =
27860 					    (uint_t)(uintptr_t)mp1->b_prev;
27861 					inbound_ill =
27862 					    ill_lookup_on_ifindex(ifindex,
27863 					    B_TRUE, NULL, NULL, NULL,
27864 					    NULL, ipst);
27865 					mp1->b_prev = NULL;
27866 					if (inbound_ill != NULL)
27867 						fwdq = inbound_ill->ill_rq;
27868 
27869 					if (fwdq != NULL) {
27870 						put(fwdq, mp1);
27871 						ill_refrele(inbound_ill);
27872 					} else
27873 						put(WR(ill->ill_rq), mp1);
27874 					mp1 = nxt_mp;
27875 				}
27876 				NCE_REFRELE(nce);
27877 			} else {	/* nce is NULL; clean up */
27878 				ire_delete(ire);
27879 				freemsg(mp);
27880 				freemsg(mp1);
27881 				return;
27882 			}
27883 		} else {
27884 			nce_t *arpce;
27885 			/*
27886 			 * Link layer resolution succeeded. Recompute the
27887 			 * ire_nce.
27888 			 */
27889 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27890 			if ((arpce = ndp_lookup_v4(ill,
27891 			    (ire->ire_gateway_addr != INADDR_ANY ?
27892 			    &ire->ire_gateway_addr : &ire->ire_addr),
27893 			    B_FALSE)) == NULL) {
27894 				freeb(ire->ire_mp);
27895 				freeb(mp1);
27896 				freemsg(mp);
27897 				return;
27898 			}
27899 			mutex_enter(&arpce->nce_lock);
27900 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27901 			if (arpce->nce_state == ND_REACHABLE) {
27902 				/*
27903 				 * Someone resolved this before us;
27904 				 * cleanup the res_mp. Since ire has
27905 				 * not been added yet, the call to ire_add_v4
27906 				 * from ire_add_then_send (when a dup is
27907 				 * detected) will clean up the ire.
27908 				 */
27909 				freeb(mp1);
27910 			} else {
27911 				ASSERT(arpce->nce_res_mp == NULL);
27912 				arpce->nce_res_mp = mp1;
27913 				arpce->nce_state = ND_REACHABLE;
27914 			}
27915 			mutex_exit(&arpce->nce_lock);
27916 			if (ire->ire_marks & IRE_MARK_NOADD) {
27917 				/*
27918 				 * this ire will not be added to the ire
27919 				 * cache table, so we can set the ire_nce
27920 				 * here, as there are no atomicity constraints.
27921 				 */
27922 				ire->ire_nce = arpce;
27923 				/*
27924 				 * We are associating this nce with the ire
27925 				 * so change the nce ref taken in
27926 				 * ndp_lookup_v4() from
27927 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27928 				 */
27929 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27930 			} else {
27931 				NCE_REFRELE(arpce);
27932 			}
27933 			ire_add_then_send(q, ire, mp);
27934 		}
27935 		return;	/* All is well, the packet has been sent. */
27936 	}
27937 	case IRE_ARPRESOLVE_TYPE: {
27938 
27939 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27940 			break;
27941 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27942 		mp->b_cont = NULL;
27943 		/*
27944 		 * First, check to make sure the resolution succeeded.
27945 		 * If it failed, the second mblk will be empty.
27946 		 */
27947 		if (mp1->b_rptr == mp1->b_wptr) {
27948 			/* cleanup  the incomplete ire, free queued packets */
27949 			freemsg(mp); /* fake ire */
27950 			freeb(mp1);  /* dl_unitdata response */
27951 			return;
27952 		}
27953 
27954 		/*
27955 		 * Update any incomplete nce_t found. We search the ctable
27956 		 * and find the nce from the ire->ire_nce because we need
27957 		 * to pass the ire to ip_xmit_v4 later, and can find both
27958 		 * ire and nce in one lookup.
27959 		 */
27960 		fake_ire = (ire_t *)mp->b_rptr;
27961 
27962 		/*
27963 		 * By the time we come back here from ARP the incomplete ire
27964 		 * created in ire_forward() could have been removed. We use
27965 		 * the parameters stored in the fake_ire to specify the real
27966 		 * ire as explicitly as possible. This avoids problems when
27967 		 * IPMP groups are configured as an ipif can 'float'
27968 		 * across several ill queues. We can be confident that the
27969 		 * the inability to find an ire is because it no longer exists.
27970 		 */
27971 		ill = ill_lookup_on_ifindex(fake_ire->ire_ipif_ifindex, B_FALSE,
27972 		    NULL, NULL, NULL, NULL, ipst);
27973 		if (ill == NULL) {
27974 			ip1dbg(("ill for incomplete ire vanished\n"));
27975 			freemsg(mp); /* fake ire */
27976 			freeb(mp1);  /* dl_unitdata response */
27977 			return;
27978 		}
27979 
27980 		/* Get the outgoing ipif */
27981 		mutex_enter(&ill->ill_lock);
27982 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27983 		if (ipif == NULL) {
27984 			mutex_exit(&ill->ill_lock);
27985 			ill_refrele(ill);
27986 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27987 			freemsg(mp); /* fake_ire */
27988 			freeb(mp1);  /* dl_unitdata response */
27989 			return;
27990 		}
27991 
27992 		ipif_refhold_locked(ipif);
27993 		mutex_exit(&ill->ill_lock);
27994 		ill_refrele(ill);
27995 		ire = ire_arpresolve_lookup(fake_ire->ire_addr,
27996 		    fake_ire->ire_gateway_addr, ipif, fake_ire->ire_zoneid,
27997 		    ipst, ((ill_t *)q->q_ptr)->ill_wq);
27998 		ipif_refrele(ipif);
27999 		if (ire == NULL) {
28000 			/*
28001 			 * no ire was found; check if there is an nce
28002 			 * for this lookup; if it has no ire's pointing at it
28003 			 * cleanup.
28004 			 */
28005 			if ((nce = ndp_lookup_v4(q->q_ptr,
28006 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28007 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28008 			    B_FALSE)) != NULL) {
28009 				/*
28010 				 * cleanup:
28011 				 * We check for refcnt 2 (one for the nce
28012 				 * hash list + 1 for the ref taken by
28013 				 * ndp_lookup_v4) to check that there are
28014 				 * no ire's pointing at the nce.
28015 				 */
28016 				if (nce->nce_refcnt == 2)
28017 					ndp_delete(nce);
28018 				NCE_REFRELE(nce);
28019 			}
28020 			freeb(mp1);  /* dl_unitdata response */
28021 			freemsg(mp); /* fake ire */
28022 			return;
28023 		}
28024 		nce = ire->ire_nce;
28025 		DTRACE_PROBE2(ire__arpresolve__type,
28026 		    ire_t *, ire, nce_t *, nce);
28027 		ASSERT(nce->nce_state != ND_INITIAL);
28028 		mutex_enter(&nce->nce_lock);
28029 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28030 		if (nce->nce_state == ND_REACHABLE) {
28031 			/*
28032 			 * Someone resolved this before us;
28033 			 * our response is not needed any more.
28034 			 */
28035 			mutex_exit(&nce->nce_lock);
28036 			freeb(mp1);  /* dl_unitdata response */
28037 		} else {
28038 			ASSERT(nce->nce_res_mp == NULL);
28039 			nce->nce_res_mp = mp1;
28040 			nce->nce_state = ND_REACHABLE;
28041 			mutex_exit(&nce->nce_lock);
28042 			nce_fastpath(nce);
28043 		}
28044 		/*
28045 		 * The cached nce_t has been updated to be reachable;
28046 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
28047 		 */
28048 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28049 		freemsg(mp);
28050 		/*
28051 		 * send out queued packets.
28052 		 */
28053 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28054 
28055 		IRE_REFRELE(ire);
28056 		return;
28057 	}
28058 	default:
28059 		break;
28060 	}
28061 	if (q->q_next) {
28062 		putnext(q, mp);
28063 	} else
28064 		freemsg(mp);
28065 	return;
28066 
28067 protonak:
28068 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28069 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28070 		qreply(q, mp);
28071 }
28072 
28073 /*
28074  * Process IP options in an outbound packet.  Modify the destination if there
28075  * is a source route option.
28076  * Returns non-zero if something fails in which case an ICMP error has been
28077  * sent and mp freed.
28078  */
28079 static int
28080 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28081     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28082 {
28083 	ipoptp_t	opts;
28084 	uchar_t		*opt;
28085 	uint8_t		optval;
28086 	uint8_t		optlen;
28087 	ipaddr_t	dst;
28088 	intptr_t	code = 0;
28089 	mblk_t		*mp;
28090 	ire_t		*ire = NULL;
28091 
28092 	ip2dbg(("ip_wput_options\n"));
28093 	mp = ipsec_mp;
28094 	if (mctl_present) {
28095 		mp = ipsec_mp->b_cont;
28096 	}
28097 
28098 	dst = ipha->ipha_dst;
28099 	for (optval = ipoptp_first(&opts, ipha);
28100 	    optval != IPOPT_EOL;
28101 	    optval = ipoptp_next(&opts)) {
28102 		opt = opts.ipoptp_cur;
28103 		optlen = opts.ipoptp_len;
28104 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28105 		    optval, optlen));
28106 		switch (optval) {
28107 			uint32_t off;
28108 		case IPOPT_SSRR:
28109 		case IPOPT_LSRR:
28110 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28111 				ip1dbg((
28112 				    "ip_wput_options: bad option offset\n"));
28113 				code = (char *)&opt[IPOPT_OLEN] -
28114 				    (char *)ipha;
28115 				goto param_prob;
28116 			}
28117 			off = opt[IPOPT_OFFSET];
28118 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28119 			    ntohl(dst)));
28120 			/*
28121 			 * For strict: verify that dst is directly
28122 			 * reachable.
28123 			 */
28124 			if (optval == IPOPT_SSRR) {
28125 				ire = ire_ftable_lookup(dst, 0, 0,
28126 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28127 				    MBLK_GETLABEL(mp),
28128 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28129 				if (ire == NULL) {
28130 					ip1dbg(("ip_wput_options: SSRR not"
28131 					    " directly reachable: 0x%x\n",
28132 					    ntohl(dst)));
28133 					goto bad_src_route;
28134 				}
28135 				ire_refrele(ire);
28136 			}
28137 			break;
28138 		case IPOPT_RR:
28139 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28140 				ip1dbg((
28141 				    "ip_wput_options: bad option offset\n"));
28142 				code = (char *)&opt[IPOPT_OLEN] -
28143 				    (char *)ipha;
28144 				goto param_prob;
28145 			}
28146 			break;
28147 		case IPOPT_TS:
28148 			/*
28149 			 * Verify that length >=5 and that there is either
28150 			 * room for another timestamp or that the overflow
28151 			 * counter is not maxed out.
28152 			 */
28153 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28154 			if (optlen < IPOPT_MINLEN_IT) {
28155 				goto param_prob;
28156 			}
28157 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28158 				ip1dbg((
28159 				    "ip_wput_options: bad option offset\n"));
28160 				code = (char *)&opt[IPOPT_OFFSET] -
28161 				    (char *)ipha;
28162 				goto param_prob;
28163 			}
28164 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28165 			case IPOPT_TS_TSONLY:
28166 				off = IPOPT_TS_TIMELEN;
28167 				break;
28168 			case IPOPT_TS_TSANDADDR:
28169 			case IPOPT_TS_PRESPEC:
28170 			case IPOPT_TS_PRESPEC_RFC791:
28171 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28172 				break;
28173 			default:
28174 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28175 				    (char *)ipha;
28176 				goto param_prob;
28177 			}
28178 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28179 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28180 				/*
28181 				 * No room and the overflow counter is 15
28182 				 * already.
28183 				 */
28184 				goto param_prob;
28185 			}
28186 			break;
28187 		}
28188 	}
28189 
28190 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28191 		return (0);
28192 
28193 	ip1dbg(("ip_wput_options: error processing IP options."));
28194 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28195 
28196 param_prob:
28197 	/*
28198 	 * Since ip_wput() isn't close to finished, we fill
28199 	 * in enough of the header for credible error reporting.
28200 	 */
28201 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28202 		/* Failed */
28203 		freemsg(ipsec_mp);
28204 		return (-1);
28205 	}
28206 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28207 	return (-1);
28208 
28209 bad_src_route:
28210 	/*
28211 	 * Since ip_wput() isn't close to finished, we fill
28212 	 * in enough of the header for credible error reporting.
28213 	 */
28214 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28215 		/* Failed */
28216 		freemsg(ipsec_mp);
28217 		return (-1);
28218 	}
28219 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28220 	return (-1);
28221 }
28222 
28223 /*
28224  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28225  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28226  * thru /etc/system.
28227  */
28228 #define	CONN_MAXDRAINCNT	64
28229 
28230 static void
28231 conn_drain_init(ip_stack_t *ipst)
28232 {
28233 	int i;
28234 
28235 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28236 
28237 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28238 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28239 		/*
28240 		 * Default value of the number of drainers is the
28241 		 * number of cpus, subject to maximum of 8 drainers.
28242 		 */
28243 		if (boot_max_ncpus != -1)
28244 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28245 		else
28246 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28247 	}
28248 
28249 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28250 	    sizeof (idl_t), KM_SLEEP);
28251 
28252 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28253 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28254 		    MUTEX_DEFAULT, NULL);
28255 	}
28256 }
28257 
28258 static void
28259 conn_drain_fini(ip_stack_t *ipst)
28260 {
28261 	int i;
28262 
28263 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28264 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28265 	kmem_free(ipst->ips_conn_drain_list,
28266 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28267 	ipst->ips_conn_drain_list = NULL;
28268 }
28269 
28270 /*
28271  * Note: For an overview of how flowcontrol is handled in IP please see the
28272  * IP Flowcontrol notes at the top of this file.
28273  *
28274  * Flow control has blocked us from proceeding. Insert the given conn in one
28275  * of the conn drain lists. These conn wq's will be qenabled later on when
28276  * STREAMS flow control does a backenable. conn_walk_drain will enable
28277  * the first conn in each of these drain lists. Each of these qenabled conns
28278  * in turn enables the next in the list, after it runs, or when it closes,
28279  * thus sustaining the drain process.
28280  *
28281  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28282  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28283  * running at any time, on a given conn, since there can be only 1 service proc
28284  * running on a queue at any time.
28285  */
28286 void
28287 conn_drain_insert(conn_t *connp)
28288 {
28289 	idl_t	*idl;
28290 	uint_t	index;
28291 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28292 
28293 	mutex_enter(&connp->conn_lock);
28294 	if (connp->conn_state_flags & CONN_CLOSING) {
28295 		/*
28296 		 * The conn is closing as a result of which CONN_CLOSING
28297 		 * is set. Return.
28298 		 */
28299 		mutex_exit(&connp->conn_lock);
28300 		return;
28301 	} else if (connp->conn_idl == NULL) {
28302 		/*
28303 		 * Assign the next drain list round robin. We dont' use
28304 		 * a lock, and thus it may not be strictly round robin.
28305 		 * Atomicity of load/stores is enough to make sure that
28306 		 * conn_drain_list_index is always within bounds.
28307 		 */
28308 		index = ipst->ips_conn_drain_list_index;
28309 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28310 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28311 		index++;
28312 		if (index == ipst->ips_conn_drain_list_cnt)
28313 			index = 0;
28314 		ipst->ips_conn_drain_list_index = index;
28315 	}
28316 	mutex_exit(&connp->conn_lock);
28317 
28318 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28319 	if ((connp->conn_drain_prev != NULL) ||
28320 	    (connp->conn_state_flags & CONN_CLOSING)) {
28321 		/*
28322 		 * The conn is already in the drain list, OR
28323 		 * the conn is closing. We need to check again for
28324 		 * the closing case again since close can happen
28325 		 * after we drop the conn_lock, and before we
28326 		 * acquire the CONN_DRAIN_LIST_LOCK.
28327 		 */
28328 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28329 		return;
28330 	} else {
28331 		idl = connp->conn_idl;
28332 	}
28333 
28334 	/*
28335 	 * The conn is not in the drain list. Insert it at the
28336 	 * tail of the drain list. The drain list is circular
28337 	 * and doubly linked. idl_conn points to the 1st element
28338 	 * in the list.
28339 	 */
28340 	if (idl->idl_conn == NULL) {
28341 		idl->idl_conn = connp;
28342 		connp->conn_drain_next = connp;
28343 		connp->conn_drain_prev = connp;
28344 	} else {
28345 		conn_t *head = idl->idl_conn;
28346 
28347 		connp->conn_drain_next = head;
28348 		connp->conn_drain_prev = head->conn_drain_prev;
28349 		head->conn_drain_prev->conn_drain_next = connp;
28350 		head->conn_drain_prev = connp;
28351 	}
28352 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28353 }
28354 
28355 /*
28356  * This conn is closing, and we are called from ip_close. OR
28357  * This conn has been serviced by ip_wsrv, and we need to do the tail
28358  * processing.
28359  * If this conn is part of the drain list, we may need to sustain the drain
28360  * process by qenabling the next conn in the drain list. We may also need to
28361  * remove this conn from the list, if it is done.
28362  */
28363 static void
28364 conn_drain_tail(conn_t *connp, boolean_t closing)
28365 {
28366 	idl_t *idl;
28367 
28368 	/*
28369 	 * connp->conn_idl is stable at this point, and no lock is needed
28370 	 * to check it. If we are called from ip_close, close has already
28371 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28372 	 * called us only because conn_idl is non-null. If we are called thru
28373 	 * service, conn_idl could be null, but it cannot change because
28374 	 * service is single-threaded per queue, and there cannot be another
28375 	 * instance of service trying to call conn_drain_insert on this conn
28376 	 * now.
28377 	 */
28378 	ASSERT(!closing || (connp->conn_idl != NULL));
28379 
28380 	/*
28381 	 * If connp->conn_idl is null, the conn has not been inserted into any
28382 	 * drain list even once since creation of the conn. Just return.
28383 	 */
28384 	if (connp->conn_idl == NULL)
28385 		return;
28386 
28387 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28388 
28389 	if (connp->conn_drain_prev == NULL) {
28390 		/* This conn is currently not in the drain list.  */
28391 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28392 		return;
28393 	}
28394 	idl = connp->conn_idl;
28395 	if (idl->idl_conn_draining == connp) {
28396 		/*
28397 		 * This conn is the current drainer. If this is the last conn
28398 		 * in the drain list, we need to do more checks, in the 'if'
28399 		 * below. Otherwwise we need to just qenable the next conn,
28400 		 * to sustain the draining, and is handled in the 'else'
28401 		 * below.
28402 		 */
28403 		if (connp->conn_drain_next == idl->idl_conn) {
28404 			/*
28405 			 * This conn is the last in this list. This round
28406 			 * of draining is complete. If idl_repeat is set,
28407 			 * it means another flow enabling has happened from
28408 			 * the driver/streams and we need to another round
28409 			 * of draining.
28410 			 * If there are more than 2 conns in the drain list,
28411 			 * do a left rotate by 1, so that all conns except the
28412 			 * conn at the head move towards the head by 1, and the
28413 			 * the conn at the head goes to the tail. This attempts
28414 			 * a more even share for all queues that are being
28415 			 * drained.
28416 			 */
28417 			if ((connp->conn_drain_next != connp) &&
28418 			    (idl->idl_conn->conn_drain_next != connp)) {
28419 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28420 			}
28421 			if (idl->idl_repeat) {
28422 				qenable(idl->idl_conn->conn_wq);
28423 				idl->idl_conn_draining = idl->idl_conn;
28424 				idl->idl_repeat = 0;
28425 			} else {
28426 				idl->idl_conn_draining = NULL;
28427 			}
28428 		} else {
28429 			/*
28430 			 * If the next queue that we are now qenable'ing,
28431 			 * is closing, it will remove itself from this list
28432 			 * and qenable the subsequent queue in ip_close().
28433 			 * Serialization is acheived thru idl_lock.
28434 			 */
28435 			qenable(connp->conn_drain_next->conn_wq);
28436 			idl->idl_conn_draining = connp->conn_drain_next;
28437 		}
28438 	}
28439 	if (!connp->conn_did_putbq || closing) {
28440 		/*
28441 		 * Remove ourself from the drain list, if we did not do
28442 		 * a putbq, or if the conn is closing.
28443 		 * Note: It is possible that q->q_first is non-null. It means
28444 		 * that these messages landed after we did a enableok() in
28445 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28446 		 * service them.
28447 		 */
28448 		if (connp->conn_drain_next == connp) {
28449 			/* Singleton in the list */
28450 			ASSERT(connp->conn_drain_prev == connp);
28451 			idl->idl_conn = NULL;
28452 			idl->idl_conn_draining = NULL;
28453 		} else {
28454 			connp->conn_drain_prev->conn_drain_next =
28455 			    connp->conn_drain_next;
28456 			connp->conn_drain_next->conn_drain_prev =
28457 			    connp->conn_drain_prev;
28458 			if (idl->idl_conn == connp)
28459 				idl->idl_conn = connp->conn_drain_next;
28460 			ASSERT(idl->idl_conn_draining != connp);
28461 
28462 		}
28463 		connp->conn_drain_next = NULL;
28464 		connp->conn_drain_prev = NULL;
28465 	}
28466 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28467 }
28468 
28469 /*
28470  * Write service routine. Shared perimeter entry point.
28471  * ip_wsrv can be called in any of the following ways.
28472  * 1. The device queue's messages has fallen below the low water mark
28473  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28474  *    the drain lists and backenable the first conn in each list.
28475  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28476  *    qenabled non-tcp upper layers. We start dequeing messages and call
28477  *    ip_wput for each message.
28478  */
28479 
28480 void
28481 ip_wsrv(queue_t *q)
28482 {
28483 	conn_t	*connp;
28484 	ill_t	*ill;
28485 	mblk_t	*mp;
28486 
28487 	if (q->q_next) {
28488 		ill = (ill_t *)q->q_ptr;
28489 		if (ill->ill_state_flags == 0) {
28490 			/*
28491 			 * The device flow control has opened up.
28492 			 * Walk through conn drain lists and qenable the
28493 			 * first conn in each list. This makes sense only
28494 			 * if the stream is fully plumbed and setup.
28495 			 * Hence the if check above.
28496 			 */
28497 			ip1dbg(("ip_wsrv: walking\n"));
28498 			conn_walk_drain(ill->ill_ipst);
28499 		}
28500 		return;
28501 	}
28502 
28503 	connp = Q_TO_CONN(q);
28504 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28505 
28506 	/*
28507 	 * 1. Set conn_draining flag to signal that service is active.
28508 	 *
28509 	 * 2. ip_output determines whether it has been called from service,
28510 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28511 	 *    has been called from service.
28512 	 *
28513 	 * 3. Message ordering is preserved by the following logic.
28514 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28515 	 *    the message at the tail, if conn_draining is set (i.e. service
28516 	 *    is running) or if q->q_first is non-null.
28517 	 *
28518 	 *    ii. If ip_output is called from service, and if ip_output cannot
28519 	 *    putnext due to flow control, it does a putbq.
28520 	 *
28521 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28522 	 *    (causing an infinite loop).
28523 	 */
28524 	ASSERT(!connp->conn_did_putbq);
28525 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28526 		connp->conn_draining = 1;
28527 		noenable(q);
28528 		while ((mp = getq(q)) != NULL) {
28529 			ASSERT(CONN_Q(q));
28530 
28531 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28532 			if (connp->conn_did_putbq) {
28533 				/* ip_wput did a putbq */
28534 				break;
28535 			}
28536 		}
28537 		/*
28538 		 * At this point, a thread coming down from top, calling
28539 		 * ip_wput, may end up queueing the message. We have not yet
28540 		 * enabled the queue, so ip_wsrv won't be called again.
28541 		 * To avoid this race, check q->q_first again (in the loop)
28542 		 * If the other thread queued the message before we call
28543 		 * enableok(), we will catch it in the q->q_first check.
28544 		 * If the other thread queues the message after we call
28545 		 * enableok(), ip_wsrv will be called again by STREAMS.
28546 		 */
28547 		connp->conn_draining = 0;
28548 		enableok(q);
28549 	}
28550 
28551 	/* Enable the next conn for draining */
28552 	conn_drain_tail(connp, B_FALSE);
28553 
28554 	connp->conn_did_putbq = 0;
28555 }
28556 
28557 /*
28558  * Walk the list of all conn's calling the function provided with the
28559  * specified argument for each.	 Note that this only walks conn's that
28560  * have been bound.
28561  * Applies to both IPv4 and IPv6.
28562  */
28563 static void
28564 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28565 {
28566 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28567 	    ipst->ips_ipcl_udp_fanout_size,
28568 	    func, arg, zoneid);
28569 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28570 	    ipst->ips_ipcl_conn_fanout_size,
28571 	    func, arg, zoneid);
28572 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28573 	    ipst->ips_ipcl_bind_fanout_size,
28574 	    func, arg, zoneid);
28575 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28576 	    IPPROTO_MAX, func, arg, zoneid);
28577 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28578 	    IPPROTO_MAX, func, arg, zoneid);
28579 }
28580 
28581 /*
28582  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28583  * of conns that need to be drained, check if drain is already in progress.
28584  * If so set the idl_repeat bit, indicating that the last conn in the list
28585  * needs to reinitiate the drain once again, for the list. If drain is not
28586  * in progress for the list, initiate the draining, by qenabling the 1st
28587  * conn in the list. The drain is self-sustaining, each qenabled conn will
28588  * in turn qenable the next conn, when it is done/blocked/closing.
28589  */
28590 static void
28591 conn_walk_drain(ip_stack_t *ipst)
28592 {
28593 	int i;
28594 	idl_t *idl;
28595 
28596 	IP_STAT(ipst, ip_conn_walk_drain);
28597 
28598 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28599 		idl = &ipst->ips_conn_drain_list[i];
28600 		mutex_enter(&idl->idl_lock);
28601 		if (idl->idl_conn == NULL) {
28602 			mutex_exit(&idl->idl_lock);
28603 			continue;
28604 		}
28605 		/*
28606 		 * If this list is not being drained currently by
28607 		 * an ip_wsrv thread, start the process.
28608 		 */
28609 		if (idl->idl_conn_draining == NULL) {
28610 			ASSERT(idl->idl_repeat == 0);
28611 			qenable(idl->idl_conn->conn_wq);
28612 			idl->idl_conn_draining = idl->idl_conn;
28613 		} else {
28614 			idl->idl_repeat = 1;
28615 		}
28616 		mutex_exit(&idl->idl_lock);
28617 	}
28618 }
28619 
28620 /*
28621  * Walk an conn hash table of `count' buckets, calling func for each entry.
28622  */
28623 static void
28624 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28625     zoneid_t zoneid)
28626 {
28627 	conn_t	*connp;
28628 
28629 	while (count-- > 0) {
28630 		mutex_enter(&connfp->connf_lock);
28631 		for (connp = connfp->connf_head; connp != NULL;
28632 		    connp = connp->conn_next) {
28633 			if (zoneid == GLOBAL_ZONEID ||
28634 			    zoneid == connp->conn_zoneid) {
28635 				CONN_INC_REF(connp);
28636 				mutex_exit(&connfp->connf_lock);
28637 				(*func)(connp, arg);
28638 				mutex_enter(&connfp->connf_lock);
28639 				CONN_DEC_REF(connp);
28640 			}
28641 		}
28642 		mutex_exit(&connfp->connf_lock);
28643 		connfp++;
28644 	}
28645 }
28646 
28647 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28648 static void
28649 conn_report1(conn_t *connp, void *mp)
28650 {
28651 	char	buf1[INET6_ADDRSTRLEN];
28652 	char	buf2[INET6_ADDRSTRLEN];
28653 	uint_t	print_len, buf_len;
28654 
28655 	ASSERT(connp != NULL);
28656 
28657 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28658 	if (buf_len <= 0)
28659 		return;
28660 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28661 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28662 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28663 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28664 	    "%5d %s/%05d %s/%05d\n",
28665 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28666 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28667 	    buf1, connp->conn_lport,
28668 	    buf2, connp->conn_fport);
28669 	if (print_len < buf_len) {
28670 		((mblk_t *)mp)->b_wptr += print_len;
28671 	} else {
28672 		((mblk_t *)mp)->b_wptr += buf_len;
28673 	}
28674 }
28675 
28676 /*
28677  * Named Dispatch routine to produce a formatted report on all conns
28678  * that are listed in one of the fanout tables.
28679  * This report is accessed by using the ndd utility to "get" ND variable
28680  * "ip_conn_status".
28681  */
28682 /* ARGSUSED */
28683 static int
28684 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28685 {
28686 	conn_t *connp = Q_TO_CONN(q);
28687 
28688 	(void) mi_mpprintf(mp,
28689 	    "CONN      " MI_COL_HDRPAD_STR
28690 	    "rfq      " MI_COL_HDRPAD_STR
28691 	    "stq      " MI_COL_HDRPAD_STR
28692 	    " zone local                 remote");
28693 
28694 	/*
28695 	 * Because of the ndd constraint, at most we can have 64K buffer
28696 	 * to put in all conn info.  So to be more efficient, just
28697 	 * allocate a 64K buffer here, assuming we need that large buffer.
28698 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28699 	 */
28700 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28701 		/* The following may work even if we cannot get a large buf. */
28702 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28703 		return (0);
28704 	}
28705 
28706 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28707 	    connp->conn_netstack->netstack_ip);
28708 	return (0);
28709 }
28710 
28711 /*
28712  * Determine if the ill and multicast aspects of that packets
28713  * "matches" the conn.
28714  */
28715 boolean_t
28716 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28717     zoneid_t zoneid)
28718 {
28719 	ill_t *in_ill;
28720 	boolean_t found;
28721 	ipif_t *ipif;
28722 	ire_t *ire;
28723 	ipaddr_t dst, src;
28724 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28725 
28726 	dst = ipha->ipha_dst;
28727 	src = ipha->ipha_src;
28728 
28729 	/*
28730 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28731 	 * unicast, broadcast and multicast reception to
28732 	 * conn_incoming_ill. conn_wantpacket itself is called
28733 	 * only for BROADCAST and multicast.
28734 	 *
28735 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28736 	 *    is part of a group. Hence, we should be receiving
28737 	 *    just one copy of broadcast for the whole group.
28738 	 *    Thus, if it is part of the group the packet could
28739 	 *    come on any ill of the group and hence we need a
28740 	 *    match on the group. Otherwise, match on ill should
28741 	 *    be sufficient.
28742 	 *
28743 	 * 2) ip_rput does not suppress duplicate multicast packets.
28744 	 *    If there are two interfaces in a ill group and we have
28745 	 *    2 applications (conns) joined a multicast group G on
28746 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28747 	 *    will give us two packets because we join G on both the
28748 	 *    interfaces rather than nominating just one interface
28749 	 *    for receiving multicast like broadcast above. So,
28750 	 *    we have to call ilg_lookup_ill to filter out duplicate
28751 	 *    copies, if ill is part of a group.
28752 	 */
28753 	in_ill = connp->conn_incoming_ill;
28754 	if (in_ill != NULL) {
28755 		if (in_ill->ill_group == NULL) {
28756 			if (in_ill != ill)
28757 				return (B_FALSE);
28758 		} else if (in_ill->ill_group != ill->ill_group) {
28759 			return (B_FALSE);
28760 		}
28761 	}
28762 
28763 	if (!CLASSD(dst)) {
28764 		if (IPCL_ZONE_MATCH(connp, zoneid))
28765 			return (B_TRUE);
28766 		/*
28767 		 * The conn is in a different zone; we need to check that this
28768 		 * broadcast address is configured in the application's zone and
28769 		 * on one ill in the group.
28770 		 */
28771 		ipif = ipif_get_next_ipif(NULL, ill);
28772 		if (ipif == NULL)
28773 			return (B_FALSE);
28774 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28775 		    connp->conn_zoneid, NULL,
28776 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28777 		ipif_refrele(ipif);
28778 		if (ire != NULL) {
28779 			ire_refrele(ire);
28780 			return (B_TRUE);
28781 		} else {
28782 			return (B_FALSE);
28783 		}
28784 	}
28785 
28786 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28787 	    connp->conn_zoneid == zoneid) {
28788 		/*
28789 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28790 		 * disabled, therefore we don't dispatch the multicast packet to
28791 		 * the sending zone.
28792 		 */
28793 		return (B_FALSE);
28794 	}
28795 
28796 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28797 		/*
28798 		 * Multicast packet on the loopback interface: we only match
28799 		 * conns who joined the group in the specified zone.
28800 		 */
28801 		return (B_FALSE);
28802 	}
28803 
28804 	if (connp->conn_multi_router) {
28805 		/* multicast packet and multicast router socket: send up */
28806 		return (B_TRUE);
28807 	}
28808 
28809 	mutex_enter(&connp->conn_lock);
28810 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28811 	mutex_exit(&connp->conn_lock);
28812 	return (found);
28813 }
28814 
28815 /*
28816  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28817  */
28818 /* ARGSUSED */
28819 static void
28820 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28821 {
28822 	ill_t *ill = (ill_t *)q->q_ptr;
28823 	mblk_t	*mp1, *mp2;
28824 	ipif_t  *ipif;
28825 	int err = 0;
28826 	conn_t *connp = NULL;
28827 	ipsq_t	*ipsq;
28828 	arc_t	*arc;
28829 
28830 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28831 
28832 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28833 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28834 
28835 	ASSERT(IAM_WRITER_ILL(ill));
28836 	mp2 = mp->b_cont;
28837 	mp->b_cont = NULL;
28838 
28839 	/*
28840 	 * We have now received the arp bringup completion message
28841 	 * from ARP. Mark the arp bringup as done. Also if the arp
28842 	 * stream has already started closing, send up the AR_ARP_CLOSING
28843 	 * ack now since ARP is waiting in close for this ack.
28844 	 */
28845 	mutex_enter(&ill->ill_lock);
28846 	ill->ill_arp_bringup_pending = 0;
28847 	if (ill->ill_arp_closing) {
28848 		mutex_exit(&ill->ill_lock);
28849 		/* Let's reuse the mp for sending the ack */
28850 		arc = (arc_t *)mp->b_rptr;
28851 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28852 		arc->arc_cmd = AR_ARP_CLOSING;
28853 		qreply(q, mp);
28854 	} else {
28855 		mutex_exit(&ill->ill_lock);
28856 		freeb(mp);
28857 	}
28858 
28859 	ipsq = ill->ill_phyint->phyint_ipsq;
28860 	ipif = ipsq->ipsq_pending_ipif;
28861 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28862 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28863 	if (mp1 == NULL) {
28864 		/* bringup was aborted by the user */
28865 		freemsg(mp2);
28866 		return;
28867 	}
28868 
28869 	/*
28870 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28871 	 * must have an associated conn_t.  Otherwise, we're bringing this
28872 	 * interface back up as part of handling an asynchronous event (e.g.,
28873 	 * physical address change).
28874 	 */
28875 	if (ipsq->ipsq_current_ioctl != 0) {
28876 		ASSERT(connp != NULL);
28877 		q = CONNP_TO_WQ(connp);
28878 	} else {
28879 		ASSERT(connp == NULL);
28880 		q = ill->ill_rq;
28881 	}
28882 
28883 	/*
28884 	 * If the DL_BIND_REQ fails, it is noted
28885 	 * in arc_name_offset.
28886 	 */
28887 	err = *((int *)mp2->b_rptr);
28888 	if (err == 0) {
28889 		if (ipif->ipif_isv6) {
28890 			if ((err = ipif_up_done_v6(ipif)) != 0)
28891 				ip0dbg(("ip_arp_done: init failed\n"));
28892 		} else {
28893 			if ((err = ipif_up_done(ipif)) != 0)
28894 				ip0dbg(("ip_arp_done: init failed\n"));
28895 		}
28896 	} else {
28897 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28898 	}
28899 
28900 	freemsg(mp2);
28901 
28902 	if ((err == 0) && (ill->ill_up_ipifs)) {
28903 		err = ill_up_ipifs(ill, q, mp1);
28904 		if (err == EINPROGRESS)
28905 			return;
28906 	}
28907 
28908 	if (ill->ill_up_ipifs)
28909 		ill_group_cleanup(ill);
28910 
28911 	/*
28912 	 * The operation must complete without EINPROGRESS since
28913 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28914 	 * Otherwise, the operation will be stuck forever in the ipsq.
28915 	 */
28916 	ASSERT(err != EINPROGRESS);
28917 	if (ipsq->ipsq_current_ioctl != 0)
28918 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28919 	else
28920 		ipsq_current_finish(ipsq);
28921 }
28922 
28923 /* Allocate the private structure */
28924 static int
28925 ip_priv_alloc(void **bufp)
28926 {
28927 	void	*buf;
28928 
28929 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28930 		return (ENOMEM);
28931 
28932 	*bufp = buf;
28933 	return (0);
28934 }
28935 
28936 /* Function to delete the private structure */
28937 void
28938 ip_priv_free(void *buf)
28939 {
28940 	ASSERT(buf != NULL);
28941 	kmem_free(buf, sizeof (ip_priv_t));
28942 }
28943 
28944 /*
28945  * The entry point for IPPF processing.
28946  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28947  * routine just returns.
28948  *
28949  * When called, ip_process generates an ipp_packet_t structure
28950  * which holds the state information for this packet and invokes the
28951  * the classifier (via ipp_packet_process). The classification, depending on
28952  * configured filters, results in a list of actions for this packet. Invoking
28953  * an action may cause the packet to be dropped, in which case the resulting
28954  * mblk (*mpp) is NULL. proc indicates the callout position for
28955  * this packet and ill_index is the interface this packet on or will leave
28956  * on (inbound and outbound resp.).
28957  */
28958 void
28959 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28960 {
28961 	mblk_t		*mp;
28962 	ip_priv_t	*priv;
28963 	ipp_action_id_t	aid;
28964 	int		rc = 0;
28965 	ipp_packet_t	*pp;
28966 #define	IP_CLASS	"ip"
28967 
28968 	/* If the classifier is not loaded, return  */
28969 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28970 		return;
28971 	}
28972 
28973 	mp = *mpp;
28974 	ASSERT(mp != NULL);
28975 
28976 	/* Allocate the packet structure */
28977 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28978 	if (rc != 0) {
28979 		*mpp = NULL;
28980 		freemsg(mp);
28981 		return;
28982 	}
28983 
28984 	/* Allocate the private structure */
28985 	rc = ip_priv_alloc((void **)&priv);
28986 	if (rc != 0) {
28987 		*mpp = NULL;
28988 		freemsg(mp);
28989 		ipp_packet_free(pp);
28990 		return;
28991 	}
28992 	priv->proc = proc;
28993 	priv->ill_index = ill_index;
28994 	ipp_packet_set_private(pp, priv, ip_priv_free);
28995 	ipp_packet_set_data(pp, mp);
28996 
28997 	/* Invoke the classifier */
28998 	rc = ipp_packet_process(&pp);
28999 	if (pp != NULL) {
29000 		mp = ipp_packet_get_data(pp);
29001 		ipp_packet_free(pp);
29002 		if (rc != 0) {
29003 			freemsg(mp);
29004 			*mpp = NULL;
29005 		}
29006 	} else {
29007 		*mpp = NULL;
29008 	}
29009 #undef	IP_CLASS
29010 }
29011 
29012 /*
29013  * Propagate a multicast group membership operation (add/drop) on
29014  * all the interfaces crossed by the related multirt routes.
29015  * The call is considered successful if the operation succeeds
29016  * on at least one interface.
29017  */
29018 static int
29019 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29020     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29021     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29022     mblk_t *first_mp)
29023 {
29024 	ire_t		*ire_gw;
29025 	irb_t		*irb;
29026 	int		error = 0;
29027 	opt_restart_t	*or;
29028 	ip_stack_t	*ipst = ire->ire_ipst;
29029 
29030 	irb = ire->ire_bucket;
29031 	ASSERT(irb != NULL);
29032 
29033 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29034 
29035 	or = (opt_restart_t *)first_mp->b_rptr;
29036 	IRB_REFHOLD(irb);
29037 	for (; ire != NULL; ire = ire->ire_next) {
29038 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29039 			continue;
29040 		if (ire->ire_addr != group)
29041 			continue;
29042 
29043 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29044 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29045 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29046 		/* No resolver exists for the gateway; skip this ire. */
29047 		if (ire_gw == NULL)
29048 			continue;
29049 
29050 		/*
29051 		 * This function can return EINPROGRESS. If so the operation
29052 		 * will be restarted from ip_restart_optmgmt which will
29053 		 * call ip_opt_set and option processing will restart for
29054 		 * this option. So we may end up calling 'fn' more than once.
29055 		 * This requires that 'fn' is idempotent except for the
29056 		 * return value. The operation is considered a success if
29057 		 * it succeeds at least once on any one interface.
29058 		 */
29059 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29060 		    NULL, fmode, src, first_mp);
29061 		if (error == 0)
29062 			or->or_private = CGTP_MCAST_SUCCESS;
29063 
29064 		if (ip_debug > 0) {
29065 			ulong_t	off;
29066 			char	*ksym;
29067 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29068 			ip2dbg(("ip_multirt_apply_membership: "
29069 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29070 			    "error %d [success %u]\n",
29071 			    ksym ? ksym : "?",
29072 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29073 			    error, or->or_private));
29074 		}
29075 
29076 		ire_refrele(ire_gw);
29077 		if (error == EINPROGRESS) {
29078 			IRB_REFRELE(irb);
29079 			return (error);
29080 		}
29081 	}
29082 	IRB_REFRELE(irb);
29083 	/*
29084 	 * Consider the call as successful if we succeeded on at least
29085 	 * one interface. Otherwise, return the last encountered error.
29086 	 */
29087 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29088 }
29089 
29090 
29091 /*
29092  * Issue a warning regarding a route crossing an interface with an
29093  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29094  * amount of time is logged.
29095  */
29096 static void
29097 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29098 {
29099 	hrtime_t	current = gethrtime();
29100 	char		buf[INET_ADDRSTRLEN];
29101 	ip_stack_t	*ipst = ire->ire_ipst;
29102 
29103 	/* Convert interval in ms to hrtime in ns */
29104 	if (ipst->ips_multirt_bad_mtu_last_time +
29105 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29106 	    current) {
29107 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29108 		    "to %s, incorrect MTU %u (expected %u)\n",
29109 		    ip_dot_addr(ire->ire_addr, buf),
29110 		    ire->ire_max_frag, max_frag);
29111 
29112 		ipst->ips_multirt_bad_mtu_last_time = current;
29113 	}
29114 }
29115 
29116 
29117 /*
29118  * Get the CGTP (multirouting) filtering status.
29119  * If 0, the CGTP hooks are transparent.
29120  */
29121 /* ARGSUSED */
29122 static int
29123 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29124 {
29125 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29126 
29127 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29128 	return (0);
29129 }
29130 
29131 
29132 /*
29133  * Set the CGTP (multirouting) filtering status.
29134  * If the status is changed from active to transparent
29135  * or from transparent to active, forward the new status
29136  * to the filtering module (if loaded).
29137  */
29138 /* ARGSUSED */
29139 static int
29140 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29141     cred_t *ioc_cr)
29142 {
29143 	long		new_value;
29144 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29145 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29146 
29147 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29148 		return (EPERM);
29149 
29150 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29151 	    new_value < 0 || new_value > 1) {
29152 		return (EINVAL);
29153 	}
29154 
29155 	if ((!*ip_cgtp_filter_value) && new_value) {
29156 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29157 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29158 		    " (module not loaded)" : "");
29159 	}
29160 	if (*ip_cgtp_filter_value && (!new_value)) {
29161 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29162 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29163 		    " (module not loaded)" : "");
29164 	}
29165 
29166 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29167 		int	res;
29168 		netstackid_t stackid;
29169 
29170 		stackid = ipst->ips_netstack->netstack_stackid;
29171 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29172 		    new_value);
29173 		if (res)
29174 			return (res);
29175 	}
29176 
29177 	*ip_cgtp_filter_value = (boolean_t)new_value;
29178 
29179 	return (0);
29180 }
29181 
29182 
29183 /*
29184  * Return the expected CGTP hooks version number.
29185  */
29186 int
29187 ip_cgtp_filter_supported(void)
29188 {
29189 	return (ip_cgtp_filter_rev);
29190 }
29191 
29192 
29193 /*
29194  * CGTP hooks can be registered by invoking this function.
29195  * Checks that the version number matches.
29196  */
29197 int
29198 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29199 {
29200 	netstack_t *ns;
29201 	ip_stack_t *ipst;
29202 
29203 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29204 		return (ENOTSUP);
29205 
29206 	ns = netstack_find_by_stackid(stackid);
29207 	if (ns == NULL)
29208 		return (EINVAL);
29209 	ipst = ns->netstack_ip;
29210 	ASSERT(ipst != NULL);
29211 
29212 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29213 		netstack_rele(ns);
29214 		return (EALREADY);
29215 	}
29216 
29217 	ipst->ips_ip_cgtp_filter_ops = ops;
29218 	netstack_rele(ns);
29219 	return (0);
29220 }
29221 
29222 /*
29223  * CGTP hooks can be unregistered by invoking this function.
29224  * Returns ENXIO if there was no registration.
29225  * Returns EBUSY if the ndd variable has not been turned off.
29226  */
29227 int
29228 ip_cgtp_filter_unregister(netstackid_t stackid)
29229 {
29230 	netstack_t *ns;
29231 	ip_stack_t *ipst;
29232 
29233 	ns = netstack_find_by_stackid(stackid);
29234 	if (ns == NULL)
29235 		return (EINVAL);
29236 	ipst = ns->netstack_ip;
29237 	ASSERT(ipst != NULL);
29238 
29239 	if (ipst->ips_ip_cgtp_filter) {
29240 		netstack_rele(ns);
29241 		return (EBUSY);
29242 	}
29243 
29244 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29245 		netstack_rele(ns);
29246 		return (ENXIO);
29247 	}
29248 	ipst->ips_ip_cgtp_filter_ops = NULL;
29249 	netstack_rele(ns);
29250 	return (0);
29251 }
29252 
29253 /*
29254  * Check whether there is a CGTP filter registration.
29255  * Returns non-zero if there is a registration, otherwise returns zero.
29256  * Note: returns zero if bad stackid.
29257  */
29258 int
29259 ip_cgtp_filter_is_registered(netstackid_t stackid)
29260 {
29261 	netstack_t *ns;
29262 	ip_stack_t *ipst;
29263 	int ret;
29264 
29265 	ns = netstack_find_by_stackid(stackid);
29266 	if (ns == NULL)
29267 		return (0);
29268 	ipst = ns->netstack_ip;
29269 	ASSERT(ipst != NULL);
29270 
29271 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29272 		ret = 1;
29273 	else
29274 		ret = 0;
29275 
29276 	netstack_rele(ns);
29277 	return (ret);
29278 }
29279 
29280 static squeue_func_t
29281 ip_squeue_switch(int val)
29282 {
29283 	squeue_func_t rval = squeue_fill;
29284 
29285 	switch (val) {
29286 	case IP_SQUEUE_ENTER_NODRAIN:
29287 		rval = squeue_enter_nodrain;
29288 		break;
29289 	case IP_SQUEUE_ENTER:
29290 		rval = squeue_enter;
29291 		break;
29292 	default:
29293 		break;
29294 	}
29295 	return (rval);
29296 }
29297 
29298 /* ARGSUSED */
29299 static int
29300 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29301     caddr_t addr, cred_t *cr)
29302 {
29303 	int *v = (int *)addr;
29304 	long new_value;
29305 
29306 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29307 		return (EPERM);
29308 
29309 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29310 		return (EINVAL);
29311 
29312 	ip_input_proc = ip_squeue_switch(new_value);
29313 	*v = new_value;
29314 	return (0);
29315 }
29316 
29317 /*
29318  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29319  * ip_debug.
29320  */
29321 /* ARGSUSED */
29322 static int
29323 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29324     caddr_t addr, cred_t *cr)
29325 {
29326 	int *v = (int *)addr;
29327 	long new_value;
29328 
29329 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29330 		return (EPERM);
29331 
29332 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29333 		return (EINVAL);
29334 
29335 	*v = new_value;
29336 	return (0);
29337 }
29338 
29339 /*
29340  * Handle changes to ipmp_hook_emulation ndd variable.
29341  * Need to update phyint_hook_ifindex.
29342  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29343  */
29344 static void
29345 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29346 {
29347 	phyint_t *phyi;
29348 	phyint_t *phyi_tmp;
29349 	char *groupname;
29350 	int namelen;
29351 	ill_t	*ill;
29352 	boolean_t new_group;
29353 
29354 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29355 	/*
29356 	 * Group indicies are stored in the phyint - a common structure
29357 	 * to both IPv4 and IPv6.
29358 	 */
29359 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29360 	for (; phyi != NULL;
29361 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29362 	    phyi, AVL_AFTER)) {
29363 		/* Ignore the ones that do not have a group */
29364 		if (phyi->phyint_groupname_len == 0)
29365 			continue;
29366 
29367 		/*
29368 		 * Look for other phyint in group.
29369 		 * Clear name/namelen so the lookup doesn't find ourselves.
29370 		 */
29371 		namelen = phyi->phyint_groupname_len;
29372 		groupname = phyi->phyint_groupname;
29373 		phyi->phyint_groupname_len = 0;
29374 		phyi->phyint_groupname = NULL;
29375 
29376 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29377 		/* Restore */
29378 		phyi->phyint_groupname_len = namelen;
29379 		phyi->phyint_groupname = groupname;
29380 
29381 		new_group = B_FALSE;
29382 		if (ipst->ips_ipmp_hook_emulation) {
29383 			/*
29384 			 * If the group already exists and has already
29385 			 * been assigned a group ifindex, we use the existing
29386 			 * group_ifindex, otherwise we pick a new group_ifindex
29387 			 * here.
29388 			 */
29389 			if (phyi_tmp != NULL &&
29390 			    phyi_tmp->phyint_group_ifindex != 0) {
29391 				phyi->phyint_group_ifindex =
29392 				    phyi_tmp->phyint_group_ifindex;
29393 			} else {
29394 				/* XXX We need a recovery strategy here. */
29395 				if (!ip_assign_ifindex(
29396 				    &phyi->phyint_group_ifindex, ipst))
29397 					cmn_err(CE_PANIC,
29398 					    "ip_assign_ifindex() failed");
29399 				new_group = B_TRUE;
29400 			}
29401 		} else {
29402 			phyi->phyint_group_ifindex = 0;
29403 		}
29404 		if (ipst->ips_ipmp_hook_emulation)
29405 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29406 		else
29407 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29408 
29409 		/*
29410 		 * For IP Filter to find out the relationship between
29411 		 * names and interface indicies, we need to generate
29412 		 * a NE_PLUMB event when a new group can appear.
29413 		 * We always generate events when a new interface appears
29414 		 * (even when ipmp_hook_emulation is set) so there
29415 		 * is no need to generate NE_PLUMB events when
29416 		 * ipmp_hook_emulation is turned off.
29417 		 * And since it isn't critical for IP Filter to get
29418 		 * the NE_UNPLUMB events we skip those here.
29419 		 */
29420 		if (new_group) {
29421 			/*
29422 			 * First phyint in group - generate group PLUMB event.
29423 			 * Since we are not running inside the ipsq we do
29424 			 * the dispatch immediately.
29425 			 */
29426 			if (phyi->phyint_illv4 != NULL)
29427 				ill = phyi->phyint_illv4;
29428 			else
29429 				ill = phyi->phyint_illv6;
29430 
29431 			if (ill != NULL)
29432 				ill_nic_event_plumb(ill, B_TRUE);
29433 		}
29434 	}
29435 	rw_exit(&ipst->ips_ill_g_lock);
29436 }
29437 
29438 /* ARGSUSED */
29439 static int
29440 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29441     caddr_t addr, cred_t *cr)
29442 {
29443 	int *v = (int *)addr;
29444 	long new_value;
29445 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29446 
29447 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29448 		return (EINVAL);
29449 
29450 	if (*v != new_value) {
29451 		*v = new_value;
29452 		ipmp_hook_emulation_changed(ipst);
29453 	}
29454 	return (0);
29455 }
29456 
29457 static void *
29458 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29459 {
29460 	kstat_t *ksp;
29461 
29462 	ip_stat_t template = {
29463 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29464 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29465 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29466 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29467 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29468 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29469 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29470 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29471 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29472 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29473 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29474 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29475 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29476 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29477 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29478 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29479 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29480 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29481 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29482 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29483 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29484 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29485 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29486 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29487 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29488 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29489 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29490 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29491 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29492 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29493 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29494 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29495 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29496 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29497 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29498 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29499 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29500 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29501 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29502 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29503 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29504 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29505 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29506 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29507 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29508 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29509 	};
29510 
29511 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29512 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29513 	    KSTAT_FLAG_VIRTUAL, stackid);
29514 
29515 	if (ksp == NULL)
29516 		return (NULL);
29517 
29518 	bcopy(&template, ip_statisticsp, sizeof (template));
29519 	ksp->ks_data = (void *)ip_statisticsp;
29520 	ksp->ks_private = (void *)(uintptr_t)stackid;
29521 
29522 	kstat_install(ksp);
29523 	return (ksp);
29524 }
29525 
29526 static void
29527 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29528 {
29529 	if (ksp != NULL) {
29530 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29531 		kstat_delete_netstack(ksp, stackid);
29532 	}
29533 }
29534 
29535 static void *
29536 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29537 {
29538 	kstat_t	*ksp;
29539 
29540 	ip_named_kstat_t template = {
29541 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29542 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29543 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29544 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29545 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29546 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29547 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29548 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29549 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29550 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29551 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29552 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29553 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29554 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29555 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29556 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29557 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29558 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29559 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29560 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29561 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29562 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29563 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29564 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29565 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29566 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29567 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29568 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29569 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29570 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29571 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29572 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29573 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29574 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29575 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29576 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29577 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29578 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29579 	};
29580 
29581 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29582 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29583 	if (ksp == NULL || ksp->ks_data == NULL)
29584 		return (NULL);
29585 
29586 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29587 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29588 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29589 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29590 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29591 
29592 	template.netToMediaEntrySize.value.i32 =
29593 	    sizeof (mib2_ipNetToMediaEntry_t);
29594 
29595 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29596 
29597 	bcopy(&template, ksp->ks_data, sizeof (template));
29598 	ksp->ks_update = ip_kstat_update;
29599 	ksp->ks_private = (void *)(uintptr_t)stackid;
29600 
29601 	kstat_install(ksp);
29602 	return (ksp);
29603 }
29604 
29605 static void
29606 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29607 {
29608 	if (ksp != NULL) {
29609 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29610 		kstat_delete_netstack(ksp, stackid);
29611 	}
29612 }
29613 
29614 static int
29615 ip_kstat_update(kstat_t *kp, int rw)
29616 {
29617 	ip_named_kstat_t *ipkp;
29618 	mib2_ipIfStatsEntry_t ipmib;
29619 	ill_walk_context_t ctx;
29620 	ill_t *ill;
29621 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29622 	netstack_t	*ns;
29623 	ip_stack_t	*ipst;
29624 
29625 	if (kp == NULL || kp->ks_data == NULL)
29626 		return (EIO);
29627 
29628 	if (rw == KSTAT_WRITE)
29629 		return (EACCES);
29630 
29631 	ns = netstack_find_by_stackid(stackid);
29632 	if (ns == NULL)
29633 		return (-1);
29634 	ipst = ns->netstack_ip;
29635 	if (ipst == NULL) {
29636 		netstack_rele(ns);
29637 		return (-1);
29638 	}
29639 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29640 
29641 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29642 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29643 	ill = ILL_START_WALK_V4(&ctx, ipst);
29644 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29645 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29646 	rw_exit(&ipst->ips_ill_g_lock);
29647 
29648 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29649 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29650 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29651 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29652 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29653 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29654 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29655 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29656 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29657 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29658 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29659 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29660 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29661 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29662 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29663 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29664 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29665 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29666 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29667 
29668 	ipkp->routingDiscards.value.ui32 =	0;
29669 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29670 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29671 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29672 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29673 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29674 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29675 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29676 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29677 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29678 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29679 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29680 
29681 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29682 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29683 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29684 
29685 	netstack_rele(ns);
29686 
29687 	return (0);
29688 }
29689 
29690 static void *
29691 icmp_kstat_init(netstackid_t stackid)
29692 {
29693 	kstat_t	*ksp;
29694 
29695 	icmp_named_kstat_t template = {
29696 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29697 		{ "inErrors",		KSTAT_DATA_UINT32 },
29698 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29699 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29700 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29701 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29702 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29703 		{ "inEchos",		KSTAT_DATA_UINT32 },
29704 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29705 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29706 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29707 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29708 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29709 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29710 		{ "outErrors",		KSTAT_DATA_UINT32 },
29711 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29712 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29713 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29714 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29715 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29716 		{ "outEchos",		KSTAT_DATA_UINT32 },
29717 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29718 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29719 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29720 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29721 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29722 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29723 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29724 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29725 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29726 		{ "outDrops",		KSTAT_DATA_UINT32 },
29727 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29728 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29729 	};
29730 
29731 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29732 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29733 	if (ksp == NULL || ksp->ks_data == NULL)
29734 		return (NULL);
29735 
29736 	bcopy(&template, ksp->ks_data, sizeof (template));
29737 
29738 	ksp->ks_update = icmp_kstat_update;
29739 	ksp->ks_private = (void *)(uintptr_t)stackid;
29740 
29741 	kstat_install(ksp);
29742 	return (ksp);
29743 }
29744 
29745 static void
29746 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29747 {
29748 	if (ksp != NULL) {
29749 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29750 		kstat_delete_netstack(ksp, stackid);
29751 	}
29752 }
29753 
29754 static int
29755 icmp_kstat_update(kstat_t *kp, int rw)
29756 {
29757 	icmp_named_kstat_t *icmpkp;
29758 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29759 	netstack_t	*ns;
29760 	ip_stack_t	*ipst;
29761 
29762 	if ((kp == NULL) || (kp->ks_data == NULL))
29763 		return (EIO);
29764 
29765 	if (rw == KSTAT_WRITE)
29766 		return (EACCES);
29767 
29768 	ns = netstack_find_by_stackid(stackid);
29769 	if (ns == NULL)
29770 		return (-1);
29771 	ipst = ns->netstack_ip;
29772 	if (ipst == NULL) {
29773 		netstack_rele(ns);
29774 		return (-1);
29775 	}
29776 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29777 
29778 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29779 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29780 	icmpkp->inDestUnreachs.value.ui32 =
29781 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29782 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29783 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29784 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29785 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29786 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29787 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29788 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29789 	icmpkp->inTimestampReps.value.ui32 =
29790 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29791 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29792 	icmpkp->inAddrMaskReps.value.ui32 =
29793 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29794 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29795 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29796 	icmpkp->outDestUnreachs.value.ui32 =
29797 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29798 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29799 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29800 	icmpkp->outSrcQuenchs.value.ui32 =
29801 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29802 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29803 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29804 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29805 	icmpkp->outTimestamps.value.ui32 =
29806 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29807 	icmpkp->outTimestampReps.value.ui32 =
29808 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29809 	icmpkp->outAddrMasks.value.ui32 =
29810 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29811 	icmpkp->outAddrMaskReps.value.ui32 =
29812 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29813 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29814 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29815 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29816 	icmpkp->outFragNeeded.value.ui32 =
29817 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29818 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29819 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29820 	icmpkp->inBadRedirects.value.ui32 =
29821 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29822 
29823 	netstack_rele(ns);
29824 	return (0);
29825 }
29826 
29827 /*
29828  * This is the fanout function for raw socket opened for SCTP.  Note
29829  * that it is called after SCTP checks that there is no socket which
29830  * wants a packet.  Then before SCTP handles this out of the blue packet,
29831  * this function is called to see if there is any raw socket for SCTP.
29832  * If there is and it is bound to the correct address, the packet will
29833  * be sent to that socket.  Note that only one raw socket can be bound to
29834  * a port.  This is assured in ipcl_sctp_hash_insert();
29835  */
29836 void
29837 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29838     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29839     zoneid_t zoneid)
29840 {
29841 	conn_t		*connp;
29842 	queue_t		*rq;
29843 	mblk_t		*first_mp;
29844 	boolean_t	secure;
29845 	ip6_t		*ip6h;
29846 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29847 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29848 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29849 	boolean_t	sctp_csum_err = B_FALSE;
29850 
29851 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29852 		sctp_csum_err = B_TRUE;
29853 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29854 	}
29855 
29856 	first_mp = mp;
29857 	if (mctl_present) {
29858 		mp = first_mp->b_cont;
29859 		secure = ipsec_in_is_secure(first_mp);
29860 		ASSERT(mp != NULL);
29861 	} else {
29862 		secure = B_FALSE;
29863 	}
29864 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29865 
29866 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29867 	if (connp == NULL) {
29868 		/*
29869 		 * Although raw sctp is not summed, OOB chunks must be.
29870 		 * Drop the packet here if the sctp checksum failed.
29871 		 */
29872 		if (sctp_csum_err) {
29873 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29874 			freemsg(first_mp);
29875 			return;
29876 		}
29877 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29878 		return;
29879 	}
29880 	rq = connp->conn_rq;
29881 	if (!canputnext(rq)) {
29882 		CONN_DEC_REF(connp);
29883 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29884 		freemsg(first_mp);
29885 		return;
29886 	}
29887 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29888 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29889 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29890 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29891 		if (first_mp == NULL) {
29892 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29893 			CONN_DEC_REF(connp);
29894 			return;
29895 		}
29896 	}
29897 	/*
29898 	 * We probably should not send M_CTL message up to
29899 	 * raw socket.
29900 	 */
29901 	if (mctl_present)
29902 		freeb(first_mp);
29903 
29904 	/* Initiate IPPF processing here if needed. */
29905 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29906 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29907 		ip_process(IPP_LOCAL_IN, &mp,
29908 		    recv_ill->ill_phyint->phyint_ifindex);
29909 		if (mp == NULL) {
29910 			CONN_DEC_REF(connp);
29911 			return;
29912 		}
29913 	}
29914 
29915 	if (connp->conn_recvif || connp->conn_recvslla ||
29916 	    ((connp->conn_ip_recvpktinfo ||
29917 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29918 	    (flags & IP_FF_IPINFO))) {
29919 		int in_flags = 0;
29920 
29921 		/*
29922 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29923 		 * IPF_RECVIF.
29924 		 */
29925 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29926 			in_flags = IPF_RECVIF;
29927 		}
29928 		if (connp->conn_recvslla) {
29929 			in_flags |= IPF_RECVSLLA;
29930 		}
29931 		if (isv4) {
29932 			mp = ip_add_info(mp, recv_ill, in_flags,
29933 			    IPCL_ZONEID(connp), ipst);
29934 		} else {
29935 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29936 			if (mp == NULL) {
29937 				BUMP_MIB(recv_ill->ill_ip_mib,
29938 				    ipIfStatsInDiscards);
29939 				CONN_DEC_REF(connp);
29940 				return;
29941 			}
29942 		}
29943 	}
29944 
29945 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29946 	/*
29947 	 * We are sending the IPSEC_IN message also up. Refer
29948 	 * to comments above this function.
29949 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29950 	 */
29951 	(connp->conn_recv)(connp, mp, NULL);
29952 	CONN_DEC_REF(connp);
29953 }
29954 
29955 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29956 {									\
29957 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29958 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29959 }
29960 /*
29961  * This function should be called only if all packet processing
29962  * including fragmentation is complete. Callers of this function
29963  * must set mp->b_prev to one of these values:
29964  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29965  * prior to handing over the mp as first argument to this function.
29966  *
29967  * If the ire passed by caller is incomplete, this function
29968  * queues the packet and if necessary, sends ARP request and bails.
29969  * If the ire passed is fully resolved, we simply prepend
29970  * the link-layer header to the packet, do ipsec hw acceleration
29971  * work if necessary, and send the packet out on the wire.
29972  *
29973  * NOTE: IPsec will only call this function with fully resolved
29974  * ires if hw acceleration is involved.
29975  * TODO list :
29976  * 	a Handle M_MULTIDATA so that
29977  *	  tcp_multisend->tcp_multisend_data can
29978  *	  call ip_xmit_v4 directly
29979  *	b Handle post-ARP work for fragments so that
29980  *	  ip_wput_frag can call this function.
29981  */
29982 ipxmit_state_t
29983 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29984 {
29985 	nce_t		*arpce;
29986 	ipha_t		*ipha;
29987 	queue_t		*q;
29988 	int		ill_index;
29989 	mblk_t		*nxt_mp, *first_mp;
29990 	boolean_t	xmit_drop = B_FALSE;
29991 	ip_proc_t	proc;
29992 	ill_t		*out_ill;
29993 	int		pkt_len;
29994 
29995 	arpce = ire->ire_nce;
29996 	ASSERT(arpce != NULL);
29997 
29998 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29999 
30000 	mutex_enter(&arpce->nce_lock);
30001 	switch (arpce->nce_state) {
30002 	case ND_REACHABLE:
30003 		/* If there are other queued packets, queue this packet */
30004 		if (arpce->nce_qd_mp != NULL) {
30005 			if (mp != NULL)
30006 				nce_queue_mp_common(arpce, mp, B_FALSE);
30007 			mp = arpce->nce_qd_mp;
30008 		}
30009 		arpce->nce_qd_mp = NULL;
30010 		mutex_exit(&arpce->nce_lock);
30011 
30012 		/*
30013 		 * Flush the queue.  In the common case, where the
30014 		 * ARP is already resolved,  it will go through the
30015 		 * while loop only once.
30016 		 */
30017 		while (mp != NULL) {
30018 
30019 			nxt_mp = mp->b_next;
30020 			mp->b_next = NULL;
30021 			ASSERT(mp->b_datap->db_type != M_CTL);
30022 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30023 			/*
30024 			 * This info is needed for IPQOS to do COS marking
30025 			 * in ip_wput_attach_llhdr->ip_process.
30026 			 */
30027 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30028 			mp->b_prev = NULL;
30029 
30030 			/* set up ill index for outbound qos processing */
30031 			out_ill = ire_to_ill(ire);
30032 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30033 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30034 			    ill_index, &ipha);
30035 			if (first_mp == NULL) {
30036 				xmit_drop = B_TRUE;
30037 				BUMP_MIB(out_ill->ill_ip_mib,
30038 				    ipIfStatsOutDiscards);
30039 				goto next_mp;
30040 			}
30041 
30042 			/* non-ipsec hw accel case */
30043 			if (io == NULL || !io->ipsec_out_accelerated) {
30044 				/* send it */
30045 				q = ire->ire_stq;
30046 				if (proc == IPP_FWD_OUT) {
30047 					UPDATE_IB_PKT_COUNT(ire);
30048 				} else {
30049 					UPDATE_OB_PKT_COUNT(ire);
30050 				}
30051 				ire->ire_last_used_time = lbolt;
30052 
30053 				if (flow_ctl_enabled || canputnext(q)) {
30054 					if (proc == IPP_FWD_OUT) {
30055 
30056 					BUMP_MIB(out_ill->ill_ip_mib,
30057 					    ipIfStatsHCOutForwDatagrams);
30058 
30059 					}
30060 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30061 					    pkt_len);
30062 
30063 					DTRACE_IP7(send, mblk_t *, first_mp,
30064 					    conn_t *, NULL, void_ip_t *, ipha,
30065 					    __dtrace_ipsr_ill_t *, out_ill,
30066 					    ipha_t *, ipha, ip6_t *, NULL, int,
30067 					    0);
30068 
30069 					putnext(q, first_mp);
30070 				} else {
30071 					BUMP_MIB(out_ill->ill_ip_mib,
30072 					    ipIfStatsOutDiscards);
30073 					xmit_drop = B_TRUE;
30074 					freemsg(first_mp);
30075 				}
30076 			} else {
30077 				/*
30078 				 * Safety Pup says: make sure this
30079 				 *  is going to the right interface!
30080 				 */
30081 				ill_t *ill1 =
30082 				    (ill_t *)ire->ire_stq->q_ptr;
30083 				int ifindex =
30084 				    ill1->ill_phyint->phyint_ifindex;
30085 				if (ifindex !=
30086 				    io->ipsec_out_capab_ill_index) {
30087 					xmit_drop = B_TRUE;
30088 					freemsg(mp);
30089 				} else {
30090 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30091 					    pkt_len);
30092 
30093 					DTRACE_IP7(send, mblk_t *, first_mp,
30094 					    conn_t *, NULL, void_ip_t *, ipha,
30095 					    __dtrace_ipsr_ill_t *, ill1,
30096 					    ipha_t *, ipha, ip6_t *, NULL,
30097 					    int, 0);
30098 
30099 					ipsec_hw_putnext(ire->ire_stq, mp);
30100 				}
30101 			}
30102 next_mp:
30103 			mp = nxt_mp;
30104 		} /* while (mp != NULL) */
30105 		if (xmit_drop)
30106 			return (SEND_FAILED);
30107 		else
30108 			return (SEND_PASSED);
30109 
30110 	case ND_INITIAL:
30111 	case ND_INCOMPLETE:
30112 
30113 		/*
30114 		 * While we do send off packets to dests that
30115 		 * use fully-resolved CGTP routes, we do not
30116 		 * handle unresolved CGTP routes.
30117 		 */
30118 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30119 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30120 
30121 		if (mp != NULL) {
30122 			/* queue the packet */
30123 			nce_queue_mp_common(arpce, mp, B_FALSE);
30124 		}
30125 
30126 		if (arpce->nce_state == ND_INCOMPLETE) {
30127 			mutex_exit(&arpce->nce_lock);
30128 			DTRACE_PROBE3(ip__xmit__incomplete,
30129 			    (ire_t *), ire, (mblk_t *), mp,
30130 			    (ipsec_out_t *), io);
30131 			return (LOOKUP_IN_PROGRESS);
30132 		}
30133 
30134 		arpce->nce_state = ND_INCOMPLETE;
30135 		mutex_exit(&arpce->nce_lock);
30136 		/*
30137 		 * Note that ire_add() (called from ire_forward())
30138 		 * holds a ref on the ire until ARP is completed.
30139 		 */
30140 
30141 		ire_arpresolve(ire, ire_to_ill(ire));
30142 		return (LOOKUP_IN_PROGRESS);
30143 	default:
30144 		ASSERT(0);
30145 		mutex_exit(&arpce->nce_lock);
30146 		return (LLHDR_RESLV_FAILED);
30147 	}
30148 }
30149 
30150 #undef	UPDATE_IP_MIB_OB_COUNTERS
30151 
30152 /*
30153  * Return B_TRUE if the buffers differ in length or content.
30154  * This is used for comparing extension header buffers.
30155  * Note that an extension header would be declared different
30156  * even if all that changed was the next header value in that header i.e.
30157  * what really changed is the next extension header.
30158  */
30159 boolean_t
30160 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30161     uint_t blen)
30162 {
30163 	if (!b_valid)
30164 		blen = 0;
30165 
30166 	if (alen != blen)
30167 		return (B_TRUE);
30168 	if (alen == 0)
30169 		return (B_FALSE);	/* Both zero length */
30170 	return (bcmp(abuf, bbuf, alen));
30171 }
30172 
30173 /*
30174  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30175  * Return B_FALSE if memory allocation fails - don't change any state!
30176  */
30177 boolean_t
30178 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30179     const void *src, uint_t srclen)
30180 {
30181 	void *dst;
30182 
30183 	if (!src_valid)
30184 		srclen = 0;
30185 
30186 	ASSERT(*dstlenp == 0);
30187 	if (src != NULL && srclen != 0) {
30188 		dst = mi_alloc(srclen, BPRI_MED);
30189 		if (dst == NULL)
30190 			return (B_FALSE);
30191 	} else {
30192 		dst = NULL;
30193 	}
30194 	if (*dstp != NULL)
30195 		mi_free(*dstp);
30196 	*dstp = dst;
30197 	*dstlenp = dst == NULL ? 0 : srclen;
30198 	return (B_TRUE);
30199 }
30200 
30201 /*
30202  * Replace what is in *dst, *dstlen with the source.
30203  * Assumes ip_allocbuf has already been called.
30204  */
30205 void
30206 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30207     const void *src, uint_t srclen)
30208 {
30209 	if (!src_valid)
30210 		srclen = 0;
30211 
30212 	ASSERT(*dstlenp == srclen);
30213 	if (src != NULL && srclen != 0)
30214 		bcopy(src, *dstp, srclen);
30215 }
30216 
30217 /*
30218  * Free the storage pointed to by the members of an ip6_pkt_t.
30219  */
30220 void
30221 ip6_pkt_free(ip6_pkt_t *ipp)
30222 {
30223 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30224 
30225 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30226 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30227 		ipp->ipp_hopopts = NULL;
30228 		ipp->ipp_hopoptslen = 0;
30229 	}
30230 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30231 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30232 		ipp->ipp_rtdstopts = NULL;
30233 		ipp->ipp_rtdstoptslen = 0;
30234 	}
30235 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30236 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30237 		ipp->ipp_dstopts = NULL;
30238 		ipp->ipp_dstoptslen = 0;
30239 	}
30240 	if (ipp->ipp_fields & IPPF_RTHDR) {
30241 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30242 		ipp->ipp_rthdr = NULL;
30243 		ipp->ipp_rthdrlen = 0;
30244 	}
30245 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30246 	    IPPF_RTHDR);
30247 }
30248 
30249 zoneid_t
30250 ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_stack_t *ipst,
30251     zoneid_t lookup_zoneid)
30252 {
30253 	ire_t		*ire;
30254 	int		ire_flags = MATCH_IRE_TYPE;
30255 	zoneid_t	zoneid = ALL_ZONES;
30256 
30257 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30258 		return (ALL_ZONES);
30259 
30260 	if (lookup_zoneid != ALL_ZONES)
30261 		ire_flags |= MATCH_IRE_ZONEONLY;
30262 	ire = ire_ctable_lookup(addr, NULL, IRE_LOCAL | IRE_LOOPBACK, NULL,
30263 	    lookup_zoneid, NULL, ire_flags, ipst);
30264 	if (ire != NULL) {
30265 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30266 		ire_refrele(ire);
30267 	}
30268 	return (zoneid);
30269 }
30270 
30271 zoneid_t
30272 ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
30273     ip_stack_t *ipst, zoneid_t lookup_zoneid)
30274 {
30275 	ire_t		*ire;
30276 	int		ire_flags = MATCH_IRE_TYPE;
30277 	zoneid_t	zoneid = ALL_ZONES;
30278 	ipif_t		*ipif_arg = NULL;
30279 
30280 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE))
30281 		return (ALL_ZONES);
30282 
30283 	if (IN6_IS_ADDR_LINKLOCAL(addr)) {
30284 		ire_flags |= MATCH_IRE_ILL_GROUP;
30285 		ipif_arg = ill->ill_ipif;
30286 	}
30287 	if (lookup_zoneid != ALL_ZONES)
30288 		ire_flags |= MATCH_IRE_ZONEONLY;
30289 	ire = ire_ctable_lookup_v6(addr, NULL, IRE_LOCAL | IRE_LOOPBACK,
30290 	    ipif_arg, lookup_zoneid, NULL, ire_flags, ipst);
30291 	if (ire != NULL) {
30292 		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
30293 		ire_refrele(ire);
30294 	}
30295 	return (zoneid);
30296 }
30297 
30298 /*
30299  * IP obserability hook support functions.
30300  */
30301 
30302 static void
30303 ipobs_init(ip_stack_t *ipst)
30304 {
30305 	ipst->ips_ipobs_enabled = B_FALSE;
30306 	list_create(&ipst->ips_ipobs_cb_list, sizeof (ipobs_cb_t),
30307 	    offsetof(ipobs_cb_t, ipobs_cbnext));
30308 	mutex_init(&ipst->ips_ipobs_cb_lock, NULL, MUTEX_DEFAULT, NULL);
30309 	ipst->ips_ipobs_cb_nwalkers = 0;
30310 	cv_init(&ipst->ips_ipobs_cb_cv, NULL, CV_DRIVER, NULL);
30311 }
30312 
30313 static void
30314 ipobs_fini(ip_stack_t *ipst)
30315 {
30316 	ipobs_cb_t *cb;
30317 
30318 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30319 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30320 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30321 
30322 	while ((cb = list_head(&ipst->ips_ipobs_cb_list)) != NULL) {
30323 		list_remove(&ipst->ips_ipobs_cb_list, cb);
30324 		kmem_free(cb, sizeof (*cb));
30325 	}
30326 	list_destroy(&ipst->ips_ipobs_cb_list);
30327 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30328 	mutex_destroy(&ipst->ips_ipobs_cb_lock);
30329 	cv_destroy(&ipst->ips_ipobs_cb_cv);
30330 }
30331 
30332 void
30333 ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
30334     const ill_t *ill, int ipver, uint32_t hlen, ip_stack_t *ipst)
30335 {
30336 	ipobs_cb_t *ipobs_cb;
30337 
30338 	ASSERT(DB_TYPE(mp) == M_DATA);
30339 
30340 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30341 	ipst->ips_ipobs_cb_nwalkers++;
30342 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30343 	for (ipobs_cb = list_head(&ipst->ips_ipobs_cb_list); ipobs_cb != NULL;
30344 	    ipobs_cb = list_next(&ipst->ips_ipobs_cb_list, ipobs_cb)) {
30345 		mblk_t  *mp2 = allocb(sizeof (ipobs_hook_data_t),
30346 		    BPRI_HI);
30347 		if (mp2 != NULL) {
30348 			ipobs_hook_data_t *ihd =
30349 			    (ipobs_hook_data_t *)mp2->b_rptr;
30350 			if (((ihd->ihd_mp = dupmsg(mp)) == NULL) &&
30351 			    ((ihd->ihd_mp = copymsg(mp)) == NULL)) {
30352 				freemsg(mp2);
30353 				continue;
30354 			}
30355 			ihd->ihd_mp->b_rptr += hlen;
30356 			ihd->ihd_htype = htype;
30357 			ihd->ihd_ipver = ipver;
30358 			ihd->ihd_zsrc = zsrc;
30359 			ihd->ihd_zdst = zdst;
30360 			ihd->ihd_ifindex = ill->ill_phyint->phyint_ifindex;
30361 			ihd->ihd_stack = ipst->ips_netstack;
30362 			mp2->b_wptr += sizeof (*ihd);
30363 			ipobs_cb->ipobs_cbfunc(mp2);
30364 		}
30365 	}
30366 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30367 	ipst->ips_ipobs_cb_nwalkers--;
30368 	if (ipst->ips_ipobs_cb_nwalkers == 0)
30369 		cv_broadcast(&ipst->ips_ipobs_cb_cv);
30370 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30371 }
30372 
30373 void
30374 ipobs_register_hook(netstack_t *ns, pfv_t func)
30375 {
30376 	ipobs_cb_t   *cb;
30377 	ip_stack_t *ipst = ns->netstack_ip;
30378 
30379 	cb = kmem_alloc(sizeof (*cb), KM_SLEEP);
30380 
30381 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30382 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30383 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30384 	ASSERT(ipst->ips_ipobs_cb_nwalkers == 0);
30385 
30386 	cb->ipobs_cbfunc = func;
30387 	list_insert_head(&ipst->ips_ipobs_cb_list, cb);
30388 	ipst->ips_ipobs_enabled = B_TRUE;
30389 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30390 }
30391 
30392 void
30393 ipobs_unregister_hook(netstack_t *ns, pfv_t func)
30394 {
30395 	ipobs_cb_t	*curcb;
30396 	ip_stack_t	*ipst = ns->netstack_ip;
30397 
30398 	mutex_enter(&ipst->ips_ipobs_cb_lock);
30399 	while (ipst->ips_ipobs_cb_nwalkers != 0)
30400 		cv_wait(&ipst->ips_ipobs_cb_cv, &ipst->ips_ipobs_cb_lock);
30401 
30402 	for (curcb = list_head(&ipst->ips_ipobs_cb_list); curcb != NULL;
30403 	    curcb = list_next(&ipst->ips_ipobs_cb_list, curcb)) {
30404 		if (func == curcb->ipobs_cbfunc) {
30405 			list_remove(&ipst->ips_ipobs_cb_list, curcb);
30406 			kmem_free(curcb, sizeof (*curcb));
30407 			break;
30408 		}
30409 	}
30410 	if (list_is_empty(&ipst->ips_ipobs_cb_list))
30411 		ipst->ips_ipobs_enabled = B_FALSE;
30412 	mutex_exit(&ipst->ips_ipobs_cb_lock);
30413 }
30414