xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision 396a100be44de1a20eabaee45519160dea8333b4)
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 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/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/optcom.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <sys/sunddi.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
131  * IP_SQUEUE_ENTER: squeue_enter
132  * IP_SQUEUE_FILL: squeue_fill
133  */
134 int ip_squeue_enter = 2;	/* Setable in /etc/system */
135 
136 squeue_func_t ip_input_proc;
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 #define	TCP6 "tcp6"
140 #define	TCP "tcp"
141 #define	SCTP "sctp"
142 #define	SCTP6 "sctp6"
143 
144 major_t TCP6_MAJ;
145 major_t TCP_MAJ;
146 major_t SCTP_MAJ;
147 major_t SCTP6_MAJ;
148 
149 /*
150  * Setable in /etc/system
151  */
152 int ip_poll_normal_ms = 100;
153 int ip_poll_normal_ticks = 0;
154 int ip_modclose_ackwait_ms = 3000;
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  * Synchronization notes:
201  *
202  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
203  * MT level protection given by STREAMS. IP uses a combination of its own
204  * internal serialization mechanism and standard Solaris locking techniques.
205  * The internal serialization is per phyint (no IPMP) or per IPMP group.
206  * This is used to serialize plumbing operations, IPMP operations, certain
207  * multicast operations, most set ioctls, igmp/mld timers etc.
208  *
209  * Plumbing is a long sequence of operations involving message
210  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
211  * involved in plumbing operations. A natural model is to serialize these
212  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
213  * parallel without any interference. But various set ioctls on hme0 are best
214  * serialized. However if the system uses IPMP, the operations are easier if
215  * they are serialized on a per IPMP group basis since IPMP operations
216  * happen across ill's of a group. Thus the lowest common denominator is to
217  * serialize most set ioctls, multicast join/leave operations, IPMP operations
218  * igmp/mld timer operations, and processing of DLPI control messages received
219  * from drivers on a per IPMP group basis. If the system does not employ
220  * IPMP the serialization is on a per phyint basis. This serialization is
221  * provided by the ipsq_t and primitives operating on this. Details can
222  * be found in ip_if.c above the core primitives operating on ipsq_t.
223  *
224  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
225  * Simiarly lookup of an ire by a thread also returns a refheld ire.
226  * In addition ipif's and ill's referenced by the ire are also indirectly
227  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
228  * the ipif's address or netmask change as long as an ipif is refheld
229  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
230  * address of an ipif has to go through the ipsq_t. This ensures that only
231  * 1 such exclusive operation proceeds at any time on the ipif. It then
232  * deletes all ires associated with this ipif, and waits for all refcnts
233  * associated with this ipif to come down to zero. The address is changed
234  * only after the ipif has been quiesced. Then the ipif is brought up again.
235  * More details are described above the comment in ip_sioctl_flags.
236  *
237  * Packet processing is based mostly on IREs and are fully multi-threaded
238  * using standard Solaris MT techniques.
239  *
240  * There are explicit locks in IP to handle:
241  * - The ip_g_head list maintained by mi_open_link() and friends.
242  *
243  * - The reassembly data structures (one lock per hash bucket)
244  *
245  * - conn_lock is meant to protect conn_t fields. The fields actually
246  *   protected by conn_lock are documented in the conn_t definition.
247  *
248  * - ire_lock to protect some of the fields of the ire, IRE tables
249  *   (one lock per hash bucket). Refer to ip_ire.c for details.
250  *
251  * - ndp_g_lock and nce_lock for protecting NCEs.
252  *
253  * - ill_lock protects fields of the ill and ipif. Details in ip.h
254  *
255  * - ill_g_lock: This is a global reader/writer lock. Protects the following
256  *	* The AVL tree based global multi list of all ills.
257  *	* The linked list of all ipifs of an ill
258  *	* The <ill-ipsq> mapping
259  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
260  *	* The illgroup list threaded by ill_group_next.
261  *	* <ill-phyint> association
262  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
263  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
264  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
265  *   will all have to hold the ill_g_lock as writer for the actual duration
266  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
267  *   may be found in the IPMP section.
268  *
269  * - ill_lock:  This is a per ill mutex.
270  *   It protects some members of the ill and is documented below.
271  *   It also protects the <ill-ipsq> mapping
272  *   It also protects the illgroup list threaded by ill_group_next.
273  *   It also protects the <ill-phyint> assoc.
274  *   It also protects the list of ipifs hanging off the ill.
275  *
276  * - ipsq_lock: This is a per ipsq_t mutex lock.
277  *   This protects all the other members of the ipsq struct except
278  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
279  *
280  * - illgrp_lock: This is a per ill_group mutex lock.
281  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
282  *   which dictates which is the next ill in an ill_group that is to be chosen
283  *   for sending outgoing packets, through creation of an IRE_CACHE that
284  *   references this ill.
285  *
286  * - phyint_lock: This is a per phyint mutex lock. Protects just the
287  *   phyint_flags
288  *
289  * - ip_g_nd_lock: This is a global reader/writer lock.
290  *   Any call to nd_load to load a new parameter to the ND table must hold the
291  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
292  *   as reader.
293  *
294  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
295  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
296  *   uniqueness check also done atomically.
297  *
298  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
299  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
300  *   as a writer when adding or deleting elements from these lists, and
301  *   as a reader when walking these lists to send a SADB update to the
302  *   IPsec capable ills.
303  *
304  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
305  *   group list linked by ill_usesrc_grp_next. It also protects the
306  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
307  *   group is being added or deleted.  This lock is taken as a reader when
308  *   walking the list/group(eg: to get the number of members in a usesrc group).
309  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
310  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
311  *   example, it is not necessary to take this lock in the initial portion
312  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
313  *   ip_sioctl_flags since the these operations are executed exclusively and
314  *   that ensures that the "usesrc group state" cannot change. The "usesrc
315  *   group state" change can happen only in the latter part of
316  *   ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
325  * and the ill_lock of the ill in question must be held.
326  *
327  * To change the <ill-illgroup> association the ill_g_lock must be held as
328  * writer and the ill_lock of the ill in question must be held.
329  *
330  * To add or delete an ipif from the list of ipifs hanging off the ill,
331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
332  * a writer on the associated ipsq,.
333  *
334  * To add or delete an ill to the system, the ill_g_lock must be held as
335  * writer and the thread must be a writer on the associated ipsq.
336  *
337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
338  * must be a writer on the associated ipsq.
339  *
340  * Lock hierarchy
341  *
342  * Some lock hierarchy scenarios are listed below.
343  *
344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
345  * ill_g_lock -> illgrp_lock -> ill_lock
346  * ill_g_lock -> ill_lock(s) -> phyint_lock
347  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
348  * ill_g_lock -> ip_addr_avail_lock
349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
350  * ill_g_lock -> ip_g_nd_lock
351  *
352  * When more than 1 ill lock is needed to be held, all ill lock addresses
353  * are sorted on address and locked starting from highest addressed lock
354  * downward.
355  *
356  * Mobile-IP scenarios
357  *
358  * irb_lock -> ill_lock -> ire_mrtun_lock
359  * irb_lock -> ill_lock -> ire_srcif_table_lock
360  *
361  * IPsec scenarios
362  *
363  * ipsa_lock -> ill_g_lock -> ill_lock
364  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
365  * ipsec_capab_ills_lock -> ipsa_lock
366  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
367  *
368  * Trusted Solaris scenarios
369  *
370  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
371  * igsa_lock -> gcdb_lock
372  * gcgrp_rwlock -> ire_lock
373  * gcgrp_rwlock -> gcdb_lock
374  *
375  *
376  * Routing/forwarding table locking notes:
377  *
378  * Lock acquisition order: Radix tree lock, irb_lock.
379  * Requirements:
380  * i.  Walker must not hold any locks during the walker callback.
381  * ii  Walker must not see a truncated tree during the walk because of any node
382  *     deletion.
383  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
384  *     in many places in the code to walk the irb list. Thus even if all the
385  *     ires in a bucket have been deleted, we still can't free the radix node
386  *     until the ires have actually been inactive'd (freed).
387  *
388  * Tree traversal - Need to hold the global tree lock in read mode.
389  * Before dropping the global tree lock, need to either increment the ire_refcnt
390  * to ensure that the radix node can't be deleted.
391  *
392  * Tree add - Need to hold the global tree lock in write mode to add a
393  * radix node. To prevent the node from being deleted, increment the
394  * irb_refcnt, after the node is added to the tree. The ire itself is
395  * added later while holding the irb_lock, but not the tree lock.
396  *
397  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
398  * All associated ires must be inactive (i.e. freed), and irb_refcnt
399  * must be zero.
400  *
401  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
402  * global tree lock (read mode) for traversal.
403  *
404  * IPSEC notes :
405  *
406  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
407  * in front of the actual packet. For outbound datagrams, the M_CTL
408  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
409  * information used by the IPSEC code for applying the right level of
410  * protection. The information initialized by IP in the ipsec_out_t
411  * is determined by the per-socket policy or global policy in the system.
412  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
413  * ipsec_info.h) which starts out with nothing in it. It gets filled
414  * with the right information if it goes through the AH/ESP code, which
415  * happens if the incoming packet is secure. The information initialized
416  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
417  * the policy requirements needed by per-socket policy or global policy
418  * is met or not.
419  *
420  * If there is both per-socket policy (set using setsockopt) and there
421  * is also global policy match for the 5 tuples of the socket,
422  * ipsec_override_policy() makes the decision of which one to use.
423  *
424  * For fully connected sockets i.e dst, src [addr, port] is known,
425  * conn_policy_cached is set indicating that policy has been cached.
426  * conn_in_enforce_policy may or may not be set depending on whether
427  * there is a global policy match or per-socket policy match.
428  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
429  * Once the right policy is set on the conn_t, policy cannot change for
430  * this socket. This makes life simpler for TCP (UDP ?) where
431  * re-transmissions go out with the same policy. For symmetry, policy
432  * is cached for fully connected UDP sockets also. Thus if policy is cached,
433  * it also implies that policy is latched i.e policy cannot change
434  * on these sockets. As we have the right policy on the conn, we don't
435  * have to lookup global policy for every outbound and inbound datagram
436  * and thus serving as an optimization. Note that a global policy change
437  * does not affect fully connected sockets if they have policy. If fully
438  * connected sockets did not have any policy associated with it, global
439  * policy change may affect them.
440  *
441  * IP Flow control notes:
442  *
443  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
444  * cannot be sent down to the driver by IP, because of a canput failure, IP
445  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
446  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
447  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
448  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
449  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
450  * the queued messages, and removes the conn from the drain list, if all
451  * messages were drained. It also qenables the next conn in the drain list to
452  * continue the drain process.
453  *
454  * In reality the drain list is not a single list, but a configurable number
455  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
456  * list. If the ip_wsrv of the next qenabled conn does not run, because the
457  * stream closes, ip_close takes responsibility to qenable the next conn in
458  * the drain list. The directly called ip_wput path always does a putq, if
459  * it cannot putnext. Thus synchronization problems are handled between
460  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
461  * functions that manipulate this drain list. Furthermore conn_drain_insert
462  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
463  * running on a queue at any time. conn_drain_tail can be simultaneously called
464  * from both ip_wsrv and ip_close.
465  *
466  * IPQOS notes:
467  *
468  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
469  * and IPQoS modules. IPPF includes hooks in IP at different control points
470  * (callout positions) which direct packets to IPQoS modules for policy
471  * processing. Policies, if present, are global.
472  *
473  * The callout positions are located in the following paths:
474  *		o local_in (packets destined for this host)
475  *		o local_out (packets orginating from this host )
476  *		o fwd_in  (packets forwarded by this m/c - inbound)
477  *		o fwd_out (packets forwarded by this m/c - outbound)
478  * Hooks at these callout points can be enabled/disabled using the ndd variable
479  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
480  * By default all the callout positions are enabled.
481  *
482  * Outbound (local_out)
483  * Hooks are placed in ip_wput_ire and ipsec_out_process.
484  *
485  * Inbound (local_in)
486  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
487  * TCP and UDP fanout routines.
488  *
489  * Forwarding (in and out)
490  * Hooks are placed in ip_rput_forward and ip_mrtun_forward.
491  *
492  * IP Policy Framework processing (IPPF processing)
493  * Policy processing for a packet is initiated by ip_process, which ascertains
494  * that the classifier (ipgpc) is loaded and configured, failing which the
495  * packet resumes normal processing in IP. If the clasifier is present, the
496  * packet is acted upon by one or more IPQoS modules (action instances), per
497  * filters configured in ipgpc and resumes normal IP processing thereafter.
498  * An action instance can drop a packet in course of its processing.
499  *
500  * A boolean variable, ip_policy, is used in all the fanout routines that can
501  * invoke ip_process for a packet. This variable indicates if the packet should
502  * to be sent for policy processing. The variable is set to B_TRUE by default,
503  * i.e. when the routines are invoked in the normal ip procesing path for a
504  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
505  * ip_policy is set to B_FALSE for all the routines called in these two
506  * functions because, in the former case,  we don't process loopback traffic
507  * currently while in the latter, the packets have already been processed in
508  * icmp_inbound.
509  *
510  * Zones notes:
511  *
512  * The partitioning rules for networking are as follows:
513  * 1) Packets coming from a zone must have a source address belonging to that
514  * zone.
515  * 2) Packets coming from a zone can only be sent on a physical interface on
516  * which the zone has an IP address.
517  * 3) Between two zones on the same machine, packet delivery is only allowed if
518  * there's a matching route for the destination and zone in the forwarding
519  * table.
520  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
521  * different zones can bind to the same port with the wildcard address
522  * (INADDR_ANY).
523  *
524  * The granularity of interface partitioning is at the logical interface level.
525  * Therefore, every zone has its own IP addresses, and incoming packets can be
526  * attributed to a zone unambiguously. A logical interface is placed into a zone
527  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
528  * structure. Rule (1) is implemented by modifying the source address selection
529  * algorithm so that the list of eligible addresses is filtered based on the
530  * sending process zone.
531  *
532  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
533  * across all zones, depending on their type. Here is the break-up:
534  *
535  * IRE type				Shared/exclusive
536  * --------				----------------
537  * IRE_BROADCAST			Exclusive
538  * IRE_DEFAULT (default routes)		Shared (*)
539  * IRE_LOCAL				Exclusive (x)
540  * IRE_LOOPBACK				Exclusive
541  * IRE_PREFIX (net routes)		Shared (*)
542  * IRE_CACHE				Exclusive
543  * IRE_IF_NORESOLVER (interface routes)	Exclusive
544  * IRE_IF_RESOLVER (interface routes)	Exclusive
545  * IRE_HOST (host routes)		Shared (*)
546  *
547  * (*) A zone can only use a default or off-subnet route if the gateway is
548  * directly reachable from the zone, that is, if the gateway's address matches
549  * one of the zone's logical interfaces.
550  *
551  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
552  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
553  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
554  * address of the zone itself (the destination). Since IRE_LOCAL is used
555  * for communication between zones, ip_wput_ire has special logic to set
556  * the right source address when sending using an IRE_LOCAL.
557  *
558  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
559  * ire_cache_lookup restricts loopback using an IRE_LOCAL
560  * between zone to the case when L2 would have conceptually looped the packet
561  * back, i.e. the loopback which is required since neither Ethernet drivers
562  * nor Ethernet hardware loops them back. This is the case when the normal
563  * routes (ignoring IREs with different zoneids) would send out the packet on
564  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
565  * associated.
566  *
567  * Multiple zones can share a common broadcast address; typically all zones
568  * share the 255.255.255.255 address. Incoming as well as locally originated
569  * broadcast packets must be dispatched to all the zones on the broadcast
570  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
571  * since some zones may not be on the 10.16.72/24 network. To handle this, each
572  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
573  * sent to every zone that has an IRE_BROADCAST entry for the destination
574  * address on the input ill, see conn_wantpacket().
575  *
576  * Applications in different zones can join the same multicast group address.
577  * For IPv4, group memberships are per-logical interface, so they're already
578  * inherently part of a zone. For IPv6, group memberships are per-physical
579  * interface, so we distinguish IPv6 group memberships based on group address,
580  * interface and zoneid. In both cases, received multicast packets are sent to
581  * every zone for which a group membership entry exists. On IPv6 we need to
582  * check that the target zone still has an address on the receiving physical
583  * interface; it could have been removed since the application issued the
584  * IPV6_JOIN_GROUP.
585  */
586 
587 /*
588  * Squeue Fanout flags:
589  *	0: No fanout.
590  *	1: Fanout across all squeues
591  */
592 boolean_t	ip_squeue_fanout = 0;
593 
594 /*
595  * Maximum dups allowed per packet.
596  */
597 uint_t ip_max_frag_dups = 10;
598 
599 #define	IS_SIMPLE_IPH(ipha)						\
600 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
601 
602 /* RFC1122 Conformance */
603 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
604 
605 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
606 
607 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
608 
609 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
610 static void	ip_ipsec_out_prepend(mblk_t *, mblk_t *, ill_t *);
611 
612 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
613 		    ip_stack_t *);
614 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
615 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
616 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
617 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
618 		    mblk_t *, int, ip_stack_t *);
619 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
620 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
621 		    ill_t *, zoneid_t);
622 static void	icmp_options_update(ipha_t *);
623 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
624 		    ip_stack_t *);
625 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
626 		    zoneid_t zoneid, ip_stack_t *);
627 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
628 static void	icmp_redirect(ill_t *, mblk_t *);
629 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
630 		    ip_stack_t *);
631 
632 static void	ip_arp_news(queue_t *, mblk_t *);
633 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
634 		    ip_stack_t *);
635 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
636 char		*ip_dot_addr(ipaddr_t, char *);
637 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
638 int		ip_close(queue_t *, int);
639 static char	*ip_dot_saddr(uchar_t *, char *);
640 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
641 		    boolean_t, boolean_t, ill_t *, zoneid_t);
642 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
643 		    boolean_t, boolean_t, zoneid_t);
644 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
645 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
646 static void	ip_lrput(queue_t *, mblk_t *);
647 static void	ip_mrtun_forward(ire_t *, ill_t *, mblk_t *);
648 ipaddr_t	ip_net_mask(ipaddr_t);
649 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, ill_t *, conn_t *,
650 		    zoneid_t, ip_stack_t *);
651 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
652 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
653 char		*ip_nv_lookup(nv_t *, int);
654 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
655 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
656 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
657 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
658     ipndp_t *, size_t);
659 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
660 void	ip_rput(queue_t *, mblk_t *);
661 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
662 		    void *dummy_arg);
663 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
664 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
665     ip_stack_t *);
666 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
667 			    ire_t *, ip_stack_t *);
668 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
669 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
670 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
671     ip_stack_t *);
672 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
673 		    uint16_t *);
674 int		ip_snmp_get(queue_t *, mblk_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
676 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
678 		    ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
680 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
703 		    ip_stack_t *ipst);
704 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
705 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
706 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
707 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
708 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
709 static boolean_t	ip_source_route_included(ipha_t *);
710 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
711 
712 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
713 		    zoneid_t, ip_stack_t *);
714 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
715 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
716 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
717 		    zoneid_t, ip_stack_t *);
718 
719 static void	conn_drain_init(ip_stack_t *);
720 static void	conn_drain_fini(ip_stack_t *);
721 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
722 
723 static void	conn_walk_drain(ip_stack_t *);
724 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
725     zoneid_t);
726 
727 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
728 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
729 static void	ip_stack_fini(netstackid_t stackid, void *arg);
730 
731 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
732     zoneid_t);
733 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
734     void *dummy_arg);
735 
736 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
737 
738 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
739     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
740     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
741 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
742 
743 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
744 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
745     caddr_t, cred_t *);
746 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
751     caddr_t cp, cred_t *cr);
752 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
753     cred_t *);
754 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
755     cred_t *);
756 static squeue_func_t ip_squeue_switch(int);
757 
758 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
759 static void	ip_kstat_fini(netstackid_t, kstat_t *);
760 static int	ip_kstat_update(kstat_t *kp, int rw);
761 static void	*icmp_kstat_init(netstackid_t);
762 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
763 static int	icmp_kstat_update(kstat_t *kp, int rw);
764 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
765 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
766 
767 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
768 
769 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
770     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
771 
772 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
773     ipha_t *, ill_t *, boolean_t);
774 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
775 
776 /* How long, in seconds, we allow frags to hang around. */
777 #define	IP_FRAG_TIMEOUT	60
778 
779 /*
780  * Threshold which determines whether MDT should be used when
781  * generating IP fragments; payload size must be greater than
782  * this threshold for MDT to take place.
783  */
784 #define	IP_WPUT_FRAG_MDT_MIN	32768
785 
786 /* Setable in /etc/system only */
787 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
788 
789 static long ip_rput_pullups;
790 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
791 
792 vmem_t *ip_minor_arena;
793 
794 int	ip_debug;
795 
796 #ifdef DEBUG
797 uint32_t ipsechw_debug = 0;
798 #endif
799 
800 /*
801  * Multirouting/CGTP stuff
802  */
803 cgtp_filter_ops_t	*ip_cgtp_filter_ops;	/* CGTP hooks */
804 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
805 boolean_t	ip_cgtp_filter;		/* Enable/disable CGTP hooks */
806 
807 /*
808  * XXX following really should only be in a header. Would need more
809  * header and .c clean up first.
810  */
811 extern optdb_obj_t	ip_opt_obj;
812 
813 ulong_t ip_squeue_enter_unbound = 0;
814 
815 /*
816  * Named Dispatch Parameter Table.
817  * All of these are alterable, within the min/max values given, at run time.
818  */
819 static ipparam_t	lcl_param_arr[] = {
820 	/* min	max	value	name */
821 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
822 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
823 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
824 	{  0,	1,	0,	"ip_respond_to_timestamp"},
825 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
826 	{  0,	1,	1,	"ip_send_redirects"},
827 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
828 	{  0,	10,	0,	"ip_debug"},
829 	{  0,	10,	0,	"ip_mrtdebug"},
830 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
831 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
832 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
833 	{  1,	255,	255,	"ip_def_ttl" },
834 	{  0,	1,	0,	"ip_forward_src_routed"},
835 	{  0,	256,	32,	"ip_wroff_extra" },
836 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
837 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
838 	{  0,	1,	1,	"ip_path_mtu_discovery" },
839 	{  0,	240,	30,	"ip_ignore_delete_time" },
840 	{  0,	1,	0,	"ip_ignore_redirect" },
841 	{  0,	1,	1,	"ip_output_queue" },
842 	{  1,	254,	1,	"ip_broadcast_ttl" },
843 	{  0,	99999,	100,	"ip_icmp_err_interval" },
844 	{  1,	99999,	10,	"ip_icmp_err_burst" },
845 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
846 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
847 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
848 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
849 	{  0,	1,	1,	"icmp_accept_clear_messages" },
850 	{  0,	1,	1,	"igmp_accept_clear_messages" },
851 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
852 				"ip_ndp_delay_first_probe_time"},
853 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
854 				"ip_ndp_max_unicast_solicit"},
855 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
856 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
857 	{  0,	1,	0,	"ip6_forward_src_routed"},
858 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
859 	{  0,	1,	1,	"ip6_send_redirects"},
860 	{  0,	1,	0,	"ip6_ignore_redirect" },
861 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
862 
863 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
864 
865 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
866 
867 	{  0,	1,	1,	"pim_accept_clear_messages" },
868 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
869 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
870 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
871 	{  0,	15,	0,	"ip_policy_mask" },
872 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
873 	{  0,	255,	1,	"ip_multirt_ttl" },
874 	{  0,	1,	1,	"ip_multidata_outbound" },
875 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
876 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
877 	{  0,	1000,	1,	"ip_max_temp_defend" },
878 	{  0,	1000,	3,	"ip_max_defend" },
879 	{  0,	999999,	30,	"ip_defend_interval" },
880 	{  0,	3600000, 300000, "ip_dup_recovery" },
881 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
882 	{  0,	1,	1,	"ip_lso_outbound" },
883 #ifdef DEBUG
884 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
885 #else
886 	{  0,	0,	0,	"" },
887 #endif
888 };
889 
890 /*
891  * Extended NDP table
892  * The addresses for the first two are filled in to be ips_ip_g_forward
893  * and ips_ipv6_forward at init time.
894  */
895 static ipndp_t	lcl_ndp_arr[] = {
896 	/* getf			setf		data			name */
897 #define	IPNDP_IP_FORWARDING_OFFSET	0
898 	{  ip_param_generic_get,	ip_forward_set,	NULL,
899 	    "ip_forwarding" },
900 #define	IPNDP_IP6_FORWARDING_OFFSET	1
901 	{  ip_param_generic_get,	ip_forward_set,	NULL,
902 	    "ip6_forwarding" },
903 	{  ip_ill_report,	NULL,		NULL,
904 	    "ip_ill_status" },
905 	{  ip_ipif_report,	NULL,		NULL,
906 	    "ip_ipif_status" },
907 	{  ip_ire_report,	NULL,		NULL,
908 	    "ipv4_ire_status" },
909 	{  ip_ire_report_mrtun,	NULL,		NULL,
910 	    "ipv4_mrtun_ire_status" },
911 	{  ip_ire_report_srcif,	NULL,		NULL,
912 	    "ipv4_srcif_ire_status" },
913 	{  ip_ire_report_v6,	NULL,		NULL,
914 	    "ipv6_ire_status" },
915 	{  ip_conn_report,	NULL,		NULL,
916 	    "ip_conn_status" },
917 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
918 	    "ip_rput_pullups" },
919 	{  ndp_report,		NULL,		NULL,
920 	    "ip_ndp_cache_report" },
921 	{  ip_srcid_report,	NULL,		NULL,
922 	    "ip_srcid_status" },
923 	{ ip_param_generic_get, ip_squeue_profile_set,
924 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
925 	{ ip_param_generic_get, ip_squeue_bind_set,
926 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
927 	{ ip_param_generic_get, ip_input_proc_set,
928 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
929 	{ ip_param_generic_get, ip_int_set,
930 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
931 #define	IPNDP_CGTP_FILTER_OFFSET	16
932 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
933 	    "ip_cgtp_filter" },
934 	{ ip_param_generic_get, ip_int_set,
935 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
936 #define	IPNDP_IPMP_HOOK_OFFSET	18
937 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
938 	    "ipmp_hook_emulation" },
939 };
940 
941 /*
942  * Table of IP ioctls encoding the various properties of the ioctl and
943  * indexed based on the last byte of the ioctl command. Occasionally there
944  * is a clash, and there is more than 1 ioctl with the same last byte.
945  * In such a case 1 ioctl is encoded in the ndx table and the remaining
946  * ioctls are encoded in the misc table. An entry in the ndx table is
947  * retrieved by indexing on the last byte of the ioctl command and comparing
948  * the ioctl command with the value in the ndx table. In the event of a
949  * mismatch the misc table is then searched sequentially for the desired
950  * ioctl command.
951  *
952  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
953  */
954 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
955 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
963 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 
966 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
967 			MISC_CMD, ip_siocaddrt, NULL },
968 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
969 			MISC_CMD, ip_siocdelrt, NULL },
970 
971 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
972 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
973 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
974 			IF_CMD, ip_sioctl_get_addr, NULL },
975 
976 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
977 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
978 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
979 			IPI_GET_CMD | IPI_REPL,
980 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
981 
982 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
983 			IPI_PRIV | IPI_WR | IPI_REPL,
984 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
985 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
986 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
987 			IF_CMD, ip_sioctl_get_flags, NULL },
988 
989 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
990 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
991 
992 	/* copyin size cannot be coded for SIOCGIFCONF */
993 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
994 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
995 
996 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
997 			IF_CMD, ip_sioctl_mtu, NULL },
998 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
999 			IF_CMD, ip_sioctl_get_mtu, NULL },
1000 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1001 			IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1003 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1004 			IF_CMD, ip_sioctl_brdaddr, NULL },
1005 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1006 			IPI_GET_CMD | IPI_REPL,
1007 			IF_CMD, ip_sioctl_get_netmask, NULL },
1008 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1009 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1010 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1011 			IPI_GET_CMD | IPI_REPL,
1012 			IF_CMD, ip_sioctl_get_metric, NULL },
1013 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1014 			IF_CMD, ip_sioctl_metric, NULL },
1015 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 
1017 	/* See 166-168 below for extended SIOC*XARP ioctls */
1018 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1019 			MISC_CMD, ip_sioctl_arp, NULL },
1020 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1021 			MISC_CMD, ip_sioctl_arp, NULL },
1022 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1023 			MISC_CMD, ip_sioctl_arp, NULL },
1024 
1025 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 
1047 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1048 			MISC_CMD, if_unitsel, if_unitsel_restart },
1049 
1050 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 
1069 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1070 			IPI_PRIV | IPI_WR | IPI_MODOK,
1071 			IF_CMD, ip_sioctl_sifname, NULL },
1072 
1073 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 
1087 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1088 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1089 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1090 			IF_CMD, ip_sioctl_get_muxid, NULL },
1091 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1092 			IPI_PRIV | IPI_WR | IPI_REPL,
1093 			IF_CMD, ip_sioctl_muxid, NULL },
1094 
1095 	/* Both if and lif variants share same func */
1096 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1097 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1098 	/* Both if and lif variants share same func */
1099 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1100 			IPI_PRIV | IPI_WR | IPI_REPL,
1101 			IF_CMD, ip_sioctl_slifindex, NULL },
1102 
1103 	/* copyin size cannot be coded for SIOCGIFCONF */
1104 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1105 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1106 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 
1124 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1125 			IPI_PRIV | IPI_WR | IPI_REPL,
1126 			LIF_CMD, ip_sioctl_removeif,
1127 			ip_sioctl_removeif_restart },
1128 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1129 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1130 			LIF_CMD, ip_sioctl_addif, NULL },
1131 #define	SIOCLIFADDR_NDX 112
1132 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1133 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1134 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_addr, NULL },
1137 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1138 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1139 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1140 			IPI_GET_CMD | IPI_REPL,
1141 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1142 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1143 			IPI_PRIV | IPI_WR | IPI_REPL,
1144 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1145 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1146 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1147 			LIF_CMD, ip_sioctl_get_flags, NULL },
1148 
1149 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1150 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1151 
1152 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1153 			ip_sioctl_get_lifconf, NULL },
1154 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1155 			LIF_CMD, ip_sioctl_mtu, NULL },
1156 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1157 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1158 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1161 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1162 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1163 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1164 			IPI_GET_CMD | IPI_REPL,
1165 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1166 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1167 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1168 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1169 			IPI_GET_CMD | IPI_REPL,
1170 			LIF_CMD, ip_sioctl_get_metric, NULL },
1171 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1172 			LIF_CMD, ip_sioctl_metric, NULL },
1173 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1174 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_slifname,
1176 			ip_sioctl_slifname_restart },
1177 
1178 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1179 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1180 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1181 			IPI_GET_CMD | IPI_REPL,
1182 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1183 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1184 			IPI_PRIV | IPI_WR | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_muxid, NULL },
1186 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1187 			IPI_GET_CMD | IPI_REPL,
1188 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1189 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1190 			IPI_PRIV | IPI_WR | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_slifindex, 0 },
1192 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_token, NULL },
1194 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_token, NULL },
1197 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1198 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1199 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1200 			IPI_GET_CMD | IPI_REPL,
1201 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1202 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1203 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1204 
1205 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1206 			IPI_GET_CMD | IPI_REPL,
1207 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1208 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1209 			LIF_CMD, ip_siocdelndp_v6, NULL },
1210 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1211 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1212 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1213 			LIF_CMD, ip_siocsetndp_v6, NULL },
1214 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1215 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1216 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1217 			MISC_CMD, ip_sioctl_tonlink, NULL },
1218 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1219 			MISC_CMD, ip_sioctl_tmysite, NULL },
1220 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1221 			TUN_CMD, ip_sioctl_tunparam, NULL },
1222 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1223 			IPI_PRIV | IPI_WR,
1224 			TUN_CMD, ip_sioctl_tunparam, NULL },
1225 
1226 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1227 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1228 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1229 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1230 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1231 
1232 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1233 			IPI_PRIV | IPI_WR | IPI_REPL,
1234 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1235 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1236 			IPI_PRIV | IPI_WR | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1238 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1239 			IPI_PRIV | IPI_WR,
1240 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1241 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1242 			IPI_GET_CMD | IPI_REPL,
1243 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1244 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1245 			IPI_GET_CMD | IPI_REPL,
1246 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1247 
1248 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1249 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1250 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1251 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1252 
1253 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1254 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1255 
1256 	/* These are handled in ip_sioctl_copyin_setup itself */
1257 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1258 			MISC_CMD, NULL, NULL },
1259 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1260 			MISC_CMD, NULL, NULL },
1261 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1262 
1263 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1264 			ip_sioctl_get_lifconf, NULL },
1265 
1266 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1267 			MISC_CMD, ip_sioctl_xarp, NULL },
1268 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1269 			MISC_CMD, ip_sioctl_xarp, NULL },
1270 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1271 			MISC_CMD, ip_sioctl_xarp, NULL },
1272 
1273 	/* SIOCPOPSOCKFS is not handled by IP */
1274 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1275 
1276 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1277 			IPI_GET_CMD | IPI_REPL,
1278 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1279 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1280 			IPI_PRIV | IPI_WR | IPI_REPL,
1281 			LIF_CMD, ip_sioctl_slifzone,
1282 			ip_sioctl_slifzone_restart },
1283 	/* 172-174 are SCTP ioctls and not handled by IP */
1284 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1285 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1286 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1287 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1288 			IPI_GET_CMD, LIF_CMD,
1289 			ip_sioctl_get_lifusesrc, 0 },
1290 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1291 			IPI_PRIV | IPI_WR,
1292 			LIF_CMD, ip_sioctl_slifusesrc,
1293 			NULL },
1294 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1295 			ip_sioctl_get_lifsrcof, NULL },
1296 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1297 			MISC_CMD, ip_sioctl_msfilter, NULL },
1298 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1299 			MISC_CMD, ip_sioctl_msfilter, NULL },
1300 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1301 			MISC_CMD, ip_sioctl_msfilter, NULL },
1302 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1303 			MISC_CMD, ip_sioctl_msfilter, NULL },
1304 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1305 			ip_sioctl_set_ipmpfailback, NULL }
1306 };
1307 
1308 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1309 
1310 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1311 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1312 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1313 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1314 		TUN_CMD, ip_sioctl_tunparam, NULL },
1315 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1319 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1320 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1321 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1322 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1323 		MISC_CMD, mrt_ioctl},
1324 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1325 		MISC_CMD, mrt_ioctl},
1326 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1327 		MISC_CMD, mrt_ioctl}
1328 };
1329 
1330 int ip_misc_ioctl_count =
1331     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1332 
1333 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1334 					/* Settable in /etc/system */
1335 /* Defined in ip_ire.c */
1336 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1337 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1338 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1339 
1340 static nv_t	ire_nv_arr[] = {
1341 	{ IRE_BROADCAST, "BROADCAST" },
1342 	{ IRE_LOCAL, "LOCAL" },
1343 	{ IRE_LOOPBACK, "LOOPBACK" },
1344 	{ IRE_CACHE, "CACHE" },
1345 	{ IRE_DEFAULT, "DEFAULT" },
1346 	{ IRE_PREFIX, "PREFIX" },
1347 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1348 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1349 	{ IRE_HOST, "HOST" },
1350 	{ 0 }
1351 };
1352 
1353 nv_t	*ire_nv_tbl = ire_nv_arr;
1354 
1355 /* Defined in ip_netinfo.c */
1356 extern ddi_taskq_t	*eventq_queue_nic;
1357 
1358 /* Simple ICMP IP Header Template */
1359 static ipha_t icmp_ipha = {
1360 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1361 };
1362 
1363 struct module_info ip_mod_info = {
1364 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1365 };
1366 
1367 /*
1368  * Duplicate static symbols within a module confuses mdb; so we avoid the
1369  * problem by making the symbols here distinct from those in udp.c.
1370  */
1371 
1372 static struct qinit iprinit = {
1373 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1374 	&ip_mod_info
1375 };
1376 
1377 static struct qinit ipwinit = {
1378 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1379 	&ip_mod_info
1380 };
1381 
1382 static struct qinit iplrinit = {
1383 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1384 	&ip_mod_info
1385 };
1386 
1387 static struct qinit iplwinit = {
1388 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1389 	&ip_mod_info
1390 };
1391 
1392 struct streamtab ipinfo = {
1393 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1394 };
1395 
1396 #ifdef	DEBUG
1397 static boolean_t skip_sctp_cksum = B_FALSE;
1398 #endif
1399 
1400 /*
1401  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1402  * ip_rput_v6(), ip_output(), etc.  If the message
1403  * block already has a M_CTL at the front of it, then simply set the zoneid
1404  * appropriately.
1405  */
1406 mblk_t *
1407 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1408 {
1409 	mblk_t		*first_mp;
1410 	ipsec_out_t	*io;
1411 
1412 	ASSERT(zoneid != ALL_ZONES);
1413 	if (mp->b_datap->db_type == M_CTL) {
1414 		io = (ipsec_out_t *)mp->b_rptr;
1415 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1416 		io->ipsec_out_zoneid = zoneid;
1417 		return (mp);
1418 	}
1419 
1420 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1421 	if (first_mp == NULL)
1422 		return (NULL);
1423 	io = (ipsec_out_t *)first_mp->b_rptr;
1424 	/* This is not a secure packet */
1425 	io->ipsec_out_secure = B_FALSE;
1426 	io->ipsec_out_zoneid = zoneid;
1427 	first_mp->b_cont = mp;
1428 	return (first_mp);
1429 }
1430 
1431 /*
1432  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1433  */
1434 mblk_t *
1435 ip_copymsg(mblk_t *mp)
1436 {
1437 	mblk_t *nmp;
1438 	ipsec_info_t *in;
1439 
1440 	if (mp->b_datap->db_type != M_CTL)
1441 		return (copymsg(mp));
1442 
1443 	in = (ipsec_info_t *)mp->b_rptr;
1444 
1445 	/*
1446 	 * Note that M_CTL is also used for delivering ICMP error messages
1447 	 * upstream to transport layers.
1448 	 */
1449 	if (in->ipsec_info_type != IPSEC_OUT &&
1450 	    in->ipsec_info_type != IPSEC_IN)
1451 		return (copymsg(mp));
1452 
1453 	nmp = copymsg(mp->b_cont);
1454 
1455 	if (in->ipsec_info_type == IPSEC_OUT) {
1456 		return (ipsec_out_tag(mp, nmp,
1457 			    ((ipsec_out_t *)in)->ipsec_out_ns));
1458 	} else {
1459 		return (ipsec_in_tag(mp, nmp,
1460 			    ((ipsec_in_t *)in)->ipsec_in_ns));
1461 	}
1462 }
1463 
1464 /* Generate an ICMP fragmentation needed message. */
1465 static void
1466 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1467     ip_stack_t *ipst)
1468 {
1469 	icmph_t	icmph;
1470 	mblk_t *first_mp;
1471 	boolean_t mctl_present;
1472 
1473 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1474 
1475 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1476 		if (mctl_present)
1477 			freeb(first_mp);
1478 		return;
1479 	}
1480 
1481 	bzero(&icmph, sizeof (icmph_t));
1482 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1483 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1484 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1485 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1486 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1487 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1488 	    ipst);
1489 }
1490 
1491 /*
1492  * icmp_inbound deals with ICMP messages in the following ways.
1493  *
1494  * 1) It needs to send a reply back and possibly delivering it
1495  *    to the "interested" upper clients.
1496  * 2) It needs to send it to the upper clients only.
1497  * 3) It needs to change some values in IP only.
1498  * 4) It needs to change some values in IP and upper layers e.g TCP.
1499  *
1500  * We need to accomodate icmp messages coming in clear until we get
1501  * everything secure from the wire. If icmp_accept_clear_messages
1502  * is zero we check with the global policy and act accordingly. If
1503  * it is non-zero, we accept the message without any checks. But
1504  * *this does not mean* that this will be delivered to the upper
1505  * clients. By accepting we might send replies back, change our MTU
1506  * value etc. but delivery to the ULP/clients depends on their policy
1507  * dispositions.
1508  *
1509  * We handle the above 4 cases in the context of IPSEC in the
1510  * following way :
1511  *
1512  * 1) Send the reply back in the same way as the request came in.
1513  *    If it came in encrypted, it goes out encrypted. If it came in
1514  *    clear, it goes out in clear. Thus, this will prevent chosen
1515  *    plain text attack.
1516  * 2) The client may or may not expect things to come in secure.
1517  *    If it comes in secure, the policy constraints are checked
1518  *    before delivering it to the upper layers. If it comes in
1519  *    clear, ipsec_inbound_accept_clear will decide whether to
1520  *    accept this in clear or not. In both the cases, if the returned
1521  *    message (IP header + 8 bytes) that caused the icmp message has
1522  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1523  *    sending up. If there are only 8 bytes of returned message, then
1524  *    upper client will not be notified.
1525  * 3) Check with global policy to see whether it matches the constaints.
1526  *    But this will be done only if icmp_accept_messages_in_clear is
1527  *    zero.
1528  * 4) If we need to change both in IP and ULP, then the decision taken
1529  *    while affecting the values in IP and while delivering up to TCP
1530  *    should be the same.
1531  *
1532  * 	There are two cases.
1533  *
1534  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1535  *	   failed), we will not deliver it to the ULP, even though they
1536  *	   are *willing* to accept in *clear*. This is fine as our global
1537  *	   disposition to icmp messages asks us reject the datagram.
1538  *
1539  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1540  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1541  *	   to deliver it to ULP (policy failed), it can lead to
1542  *	   consistency problems. The cases known at this time are
1543  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1544  *	   values :
1545  *
1546  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1547  *	     and Upper layer rejects. Then the communication will
1548  *	     come to a stop. This is solved by making similar decisions
1549  *	     at both levels. Currently, when we are unable to deliver
1550  *	     to the Upper Layer (due to policy failures) while IP has
1551  *	     adjusted ire_max_frag, the next outbound datagram would
1552  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1553  *	     will be with the right level of protection. Thus the right
1554  *	     value will be communicated even if we are not able to
1555  *	     communicate when we get from the wire initially. But this
1556  *	     assumes there would be at least one outbound datagram after
1557  *	     IP has adjusted its ire_max_frag value. To make things
1558  *	     simpler, we accept in clear after the validation of
1559  *	     AH/ESP headers.
1560  *
1561  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1562  *	     upper layer depending on the level of protection the upper
1563  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1564  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1565  *	     should be accepted in clear when the Upper layer expects secure.
1566  *	     Thus the communication may get aborted by some bad ICMP
1567  *	     packets.
1568  *
1569  * IPQoS Notes:
1570  * The only instance when a packet is sent for processing is when there
1571  * isn't an ICMP client and if we are interested in it.
1572  * If there is a client, IPPF processing will take place in the
1573  * ip_fanout_proto routine.
1574  *
1575  * Zones notes:
1576  * The packet is only processed in the context of the specified zone: typically
1577  * only this zone will reply to an echo request, and only interested clients in
1578  * this zone will receive a copy of the packet. This means that the caller must
1579  * call icmp_inbound() for each relevant zone.
1580  */
1581 static void
1582 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1583     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1584     ill_t *recv_ill, zoneid_t zoneid)
1585 {
1586 	icmph_t	*icmph;
1587 	ipha_t	*ipha;
1588 	int	iph_hdr_length;
1589 	int	hdr_length;
1590 	boolean_t	interested;
1591 	uint32_t	ts;
1592 	uchar_t	*wptr;
1593 	ipif_t	*ipif;
1594 	mblk_t *first_mp;
1595 	ipsec_in_t *ii;
1596 	ire_t *src_ire;
1597 	boolean_t onlink;
1598 	timestruc_t now;
1599 	uint32_t ill_index;
1600 	ip_stack_t *ipst;
1601 
1602 	ASSERT(ill != NULL);
1603 	ipst = ill->ill_ipst;
1604 
1605 	first_mp = mp;
1606 	if (mctl_present) {
1607 		mp = first_mp->b_cont;
1608 		ASSERT(mp != NULL);
1609 	}
1610 
1611 	ipha = (ipha_t *)mp->b_rptr;
1612 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1613 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1614 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1615 		if (first_mp == NULL)
1616 			return;
1617 	}
1618 
1619 	/*
1620 	 * On a labeled system, we have to check whether the zone itself is
1621 	 * permitted to receive raw traffic.
1622 	 */
1623 	if (is_system_labeled()) {
1624 		if (zoneid == ALL_ZONES)
1625 			zoneid = tsol_packet_to_zoneid(mp);
1626 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1627 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1628 			    zoneid));
1629 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1630 			freemsg(first_mp);
1631 			return;
1632 		}
1633 	}
1634 
1635 	/*
1636 	 * We have accepted the ICMP message. It means that we will
1637 	 * respond to the packet if needed. It may not be delivered
1638 	 * to the upper client depending on the policy constraints
1639 	 * and the disposition in ipsec_inbound_accept_clear.
1640 	 */
1641 
1642 	ASSERT(ill != NULL);
1643 
1644 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1645 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1646 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1647 		/* Last chance to get real. */
1648 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1649 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1650 			freemsg(first_mp);
1651 			return;
1652 		}
1653 		/* Refresh iph following the pullup. */
1654 		ipha = (ipha_t *)mp->b_rptr;
1655 	}
1656 	/* ICMP header checksum, including checksum field, should be zero. */
1657 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1658 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1659 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1660 		freemsg(first_mp);
1661 		return;
1662 	}
1663 	/* The IP header will always be a multiple of four bytes */
1664 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1665 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1666 	    icmph->icmph_code));
1667 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1668 	/* We will set "interested" to "true" if we want a copy */
1669 	interested = B_FALSE;
1670 	switch (icmph->icmph_type) {
1671 	case ICMP_ECHO_REPLY:
1672 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1673 		break;
1674 	case ICMP_DEST_UNREACHABLE:
1675 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1676 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1677 		interested = B_TRUE;	/* Pass up to transport */
1678 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1679 		break;
1680 	case ICMP_SOURCE_QUENCH:
1681 		interested = B_TRUE;	/* Pass up to transport */
1682 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1683 		break;
1684 	case ICMP_REDIRECT:
1685 		if (!ipst->ips_ip_ignore_redirect)
1686 			interested = B_TRUE;
1687 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1688 		break;
1689 	case ICMP_ECHO_REQUEST:
1690 		/*
1691 		 * Whether to respond to echo requests that come in as IP
1692 		 * broadcasts or as IP multicast is subject to debate
1693 		 * (what isn't?).  We aim to please, you pick it.
1694 		 * Default is do it.
1695 		 */
1696 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1697 			/* unicast: always respond */
1698 			interested = B_TRUE;
1699 		} else if (CLASSD(ipha->ipha_dst)) {
1700 			/* multicast: respond based on tunable */
1701 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1702 		} else if (broadcast) {
1703 			/* broadcast: respond based on tunable */
1704 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1705 		}
1706 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1707 		break;
1708 	case ICMP_ROUTER_ADVERTISEMENT:
1709 	case ICMP_ROUTER_SOLICITATION:
1710 		break;
1711 	case ICMP_TIME_EXCEEDED:
1712 		interested = B_TRUE;	/* Pass up to transport */
1713 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1714 		break;
1715 	case ICMP_PARAM_PROBLEM:
1716 		interested = B_TRUE;	/* Pass up to transport */
1717 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1718 		break;
1719 	case ICMP_TIME_STAMP_REQUEST:
1720 		/* Response to Time Stamp Requests is local policy. */
1721 		if (ipst->ips_ip_g_resp_to_timestamp &&
1722 		    /* So is whether to respond if it was an IP broadcast. */
1723 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1724 			int tstamp_len = 3 * sizeof (uint32_t);
1725 
1726 			if (wptr +  tstamp_len > mp->b_wptr) {
1727 				if (!pullupmsg(mp, wptr + tstamp_len -
1728 				    mp->b_rptr)) {
1729 					BUMP_MIB(ill->ill_ip_mib,
1730 					    ipIfStatsInDiscards);
1731 					freemsg(first_mp);
1732 					return;
1733 				}
1734 				/* Refresh ipha following the pullup. */
1735 				ipha = (ipha_t *)mp->b_rptr;
1736 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1737 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1738 			}
1739 			interested = B_TRUE;
1740 		}
1741 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1742 		break;
1743 	case ICMP_TIME_STAMP_REPLY:
1744 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1745 		break;
1746 	case ICMP_INFO_REQUEST:
1747 		/* Per RFC 1122 3.2.2.7, ignore this. */
1748 	case ICMP_INFO_REPLY:
1749 		break;
1750 	case ICMP_ADDRESS_MASK_REQUEST:
1751 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1752 			!broadcast) &&
1753 		    /* TODO m_pullup of complete header? */
1754 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN)
1755 			interested = B_TRUE;
1756 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1757 		break;
1758 	case ICMP_ADDRESS_MASK_REPLY:
1759 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1760 		break;
1761 	default:
1762 		interested = B_TRUE;	/* Pass up to transport */
1763 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1764 		break;
1765 	}
1766 	/* See if there is an ICMP client. */
1767 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1768 		/* If there is an ICMP client and we want one too, copy it. */
1769 		mblk_t *first_mp1;
1770 
1771 		if (!interested) {
1772 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1773 			    ip_policy, recv_ill, zoneid);
1774 			return;
1775 		}
1776 		first_mp1 = ip_copymsg(first_mp);
1777 		if (first_mp1 != NULL) {
1778 			ip_fanout_proto(q, first_mp1, ill, ipha,
1779 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1780 		}
1781 	} else if (!interested) {
1782 		freemsg(first_mp);
1783 		return;
1784 	} else {
1785 		/*
1786 		 * Initiate policy processing for this packet if ip_policy
1787 		 * is true.
1788 		 */
1789 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1790 			ill_index = ill->ill_phyint->phyint_ifindex;
1791 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1792 			if (mp == NULL) {
1793 				if (mctl_present) {
1794 					freeb(first_mp);
1795 				}
1796 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1797 				return;
1798 			}
1799 		}
1800 	}
1801 	/* We want to do something with it. */
1802 	/* Check db_ref to make sure we can modify the packet. */
1803 	if (mp->b_datap->db_ref > 1) {
1804 		mblk_t	*first_mp1;
1805 
1806 		first_mp1 = ip_copymsg(first_mp);
1807 		freemsg(first_mp);
1808 		if (!first_mp1) {
1809 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1810 			return;
1811 		}
1812 		first_mp = first_mp1;
1813 		if (mctl_present) {
1814 			mp = first_mp->b_cont;
1815 			ASSERT(mp != NULL);
1816 		} else {
1817 			mp = first_mp;
1818 		}
1819 		ipha = (ipha_t *)mp->b_rptr;
1820 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1821 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1822 	}
1823 	switch (icmph->icmph_type) {
1824 	case ICMP_ADDRESS_MASK_REQUEST:
1825 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1826 		if (ipif == NULL) {
1827 			freemsg(first_mp);
1828 			return;
1829 		}
1830 		/*
1831 		 * outging interface must be IPv4
1832 		 */
1833 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1834 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1835 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1836 		ipif_refrele(ipif);
1837 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1838 		break;
1839 	case ICMP_ECHO_REQUEST:
1840 		icmph->icmph_type = ICMP_ECHO_REPLY;
1841 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1842 		break;
1843 	case ICMP_TIME_STAMP_REQUEST: {
1844 		uint32_t *tsp;
1845 
1846 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1847 		tsp = (uint32_t *)wptr;
1848 		tsp++;		/* Skip past 'originate time' */
1849 		/* Compute # of milliseconds since midnight */
1850 		gethrestime(&now);
1851 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1852 		    now.tv_nsec / (NANOSEC / MILLISEC);
1853 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1854 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1855 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1856 		break;
1857 	}
1858 	default:
1859 		ipha = (ipha_t *)&icmph[1];
1860 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1861 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1862 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1863 				freemsg(first_mp);
1864 				return;
1865 			}
1866 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1867 			ipha = (ipha_t *)&icmph[1];
1868 		}
1869 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1870 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1871 			freemsg(first_mp);
1872 			return;
1873 		}
1874 		hdr_length = IPH_HDR_LENGTH(ipha);
1875 		if (hdr_length < sizeof (ipha_t)) {
1876 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1877 			freemsg(first_mp);
1878 			return;
1879 		}
1880 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1881 			if (!pullupmsg(mp,
1882 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1883 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1884 				freemsg(first_mp);
1885 				return;
1886 			}
1887 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1888 			ipha = (ipha_t *)&icmph[1];
1889 		}
1890 		switch (icmph->icmph_type) {
1891 		case ICMP_REDIRECT:
1892 			/*
1893 			 * As there is no upper client to deliver, we don't
1894 			 * need the first_mp any more.
1895 			 */
1896 			if (mctl_present) {
1897 				freeb(first_mp);
1898 			}
1899 			icmp_redirect(ill, mp);
1900 			return;
1901 		case ICMP_DEST_UNREACHABLE:
1902 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1903 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1904 				    zoneid, mp, iph_hdr_length, ipst)) {
1905 					freemsg(first_mp);
1906 					return;
1907 				}
1908 				/*
1909 				 * icmp_inbound_too_big() may alter mp.
1910 				 * Resynch ipha and icmph accordingly.
1911 				 */
1912 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1913 				ipha = (ipha_t *)&icmph[1];
1914 			}
1915 			/* FALLTHRU */
1916 		default :
1917 			/*
1918 			 * IPQoS notes: Since we have already done IPQoS
1919 			 * processing we don't want to do it again in
1920 			 * the fanout routines called by
1921 			 * icmp_inbound_error_fanout, hence the last
1922 			 * argument, ip_policy, is B_FALSE.
1923 			 */
1924 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1925 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1926 			    B_FALSE, recv_ill, zoneid);
1927 		}
1928 		return;
1929 	}
1930 	/* Send out an ICMP packet */
1931 	icmph->icmph_checksum = 0;
1932 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1933 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1934 		ipif_t	*ipif_chosen;
1935 		/*
1936 		 * Make it look like it was directed to us, so we don't look
1937 		 * like a fool with a broadcast or multicast source address.
1938 		 */
1939 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1940 		/*
1941 		 * Make sure that we haven't grabbed an interface that's DOWN.
1942 		 */
1943 		if (ipif != NULL) {
1944 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1945 			    ipha->ipha_src, zoneid);
1946 			if (ipif_chosen != NULL) {
1947 				ipif_refrele(ipif);
1948 				ipif = ipif_chosen;
1949 			}
1950 		}
1951 		if (ipif == NULL) {
1952 			ip0dbg(("icmp_inbound: "
1953 			    "No source for broadcast/multicast:\n"
1954 			    "\tsrc 0x%x dst 0x%x ill %p "
1955 			    "ipif_lcl_addr 0x%x\n",
1956 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1957 			    (void *)ill,
1958 			    ill->ill_ipif->ipif_lcl_addr));
1959 			freemsg(first_mp);
1960 			return;
1961 		}
1962 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1963 		ipha->ipha_dst = ipif->ipif_src_addr;
1964 		ipif_refrele(ipif);
1965 	}
1966 	/* Reset time to live. */
1967 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1968 	{
1969 		/* Swap source and destination addresses */
1970 		ipaddr_t tmp;
1971 
1972 		tmp = ipha->ipha_src;
1973 		ipha->ipha_src = ipha->ipha_dst;
1974 		ipha->ipha_dst = tmp;
1975 	}
1976 	ipha->ipha_ident = 0;
1977 	if (!IS_SIMPLE_IPH(ipha))
1978 		icmp_options_update(ipha);
1979 
1980 	/*
1981 	 * ICMP echo replies should go out on the same interface
1982 	 * the request came on as probes used by in.mpathd for detecting
1983 	 * NIC failures are ECHO packets. We turn-off load spreading
1984 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1985 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1986 	 * function. This is in turn handled by ip_wput and ip_newroute
1987 	 * to make sure that the packet goes out on the interface it came
1988 	 * in on. If we don't turnoff load spreading, the packets might get
1989 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1990 	 * to go out and in.mpathd would wrongly detect a failure or
1991 	 * mis-detect a NIC failure for link failure. As load spreading
1992 	 * can happen only if ill_group is not NULL, we do only for
1993 	 * that case and this does not affect the normal case.
1994 	 *
1995 	 * We turn off load spreading only on echo packets that came from
1996 	 * on-link hosts. If the interface route has been deleted, this will
1997 	 * not be enforced as we can't do much. For off-link hosts, as the
1998 	 * default routes in IPv4 does not typically have an ire_ipif
1999 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2000 	 * Moreover, expecting a default route through this interface may
2001 	 * not be correct. We use ipha_dst because of the swap above.
2002 	 */
2003 	onlink = B_FALSE;
2004 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2005 		/*
2006 		 * First, we need to make sure that it is not one of our
2007 		 * local addresses. If we set onlink when it is one of
2008 		 * our local addresses, we will end up creating IRE_CACHES
2009 		 * for one of our local addresses. Then, we will never
2010 		 * accept packets for them afterwards.
2011 		 */
2012 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2013 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2014 		if (src_ire == NULL) {
2015 			ipif = ipif_get_next_ipif(NULL, ill);
2016 			if (ipif == NULL) {
2017 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2018 				freemsg(mp);
2019 				return;
2020 			}
2021 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2022 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2023 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2024 			ipif_refrele(ipif);
2025 			if (src_ire != NULL) {
2026 				onlink = B_TRUE;
2027 				ire_refrele(src_ire);
2028 			}
2029 		} else {
2030 			ire_refrele(src_ire);
2031 		}
2032 	}
2033 	if (!mctl_present) {
2034 		/*
2035 		 * This packet should go out the same way as it
2036 		 * came in i.e in clear. To make sure that global
2037 		 * policy will not be applied to this in ip_wput_ire,
2038 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2039 		 */
2040 		ASSERT(first_mp == mp);
2041 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2042 		if (first_mp == NULL) {
2043 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2044 			freemsg(mp);
2045 			return;
2046 		}
2047 		ii = (ipsec_in_t *)first_mp->b_rptr;
2048 
2049 		/* This is not a secure packet */
2050 		ii->ipsec_in_secure = B_FALSE;
2051 		if (onlink) {
2052 			ii->ipsec_in_attach_if = B_TRUE;
2053 			ii->ipsec_in_ill_index =
2054 			    ill->ill_phyint->phyint_ifindex;
2055 			ii->ipsec_in_rill_index =
2056 			    recv_ill->ill_phyint->phyint_ifindex;
2057 		}
2058 		first_mp->b_cont = mp;
2059 	} else if (onlink) {
2060 		ii = (ipsec_in_t *)first_mp->b_rptr;
2061 		ii->ipsec_in_attach_if = B_TRUE;
2062 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2063 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2064 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2065 	} else {
2066 		ii = (ipsec_in_t *)first_mp->b_rptr;
2067 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2068 	}
2069 	ii->ipsec_in_zoneid = zoneid;
2070 	ASSERT(zoneid != ALL_ZONES);
2071 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2072 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2073 		return;
2074 	}
2075 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2076 	put(WR(q), first_mp);
2077 }
2078 
2079 static ipaddr_t
2080 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2081 {
2082 	conn_t *connp;
2083 	connf_t *connfp;
2084 	ipaddr_t nexthop_addr = INADDR_ANY;
2085 	int hdr_length = IPH_HDR_LENGTH(ipha);
2086 	uint16_t *up;
2087 	uint32_t ports;
2088 	ip_stack_t *ipst = ill->ill_ipst;
2089 
2090 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2091 	switch (ipha->ipha_protocol) {
2092 		case IPPROTO_TCP:
2093 		{
2094 			tcph_t *tcph;
2095 
2096 			/* do a reverse lookup */
2097 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2098 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2099 			    TCPS_LISTEN, ipst);
2100 			break;
2101 		}
2102 		case IPPROTO_UDP:
2103 		{
2104 			uint32_t dstport, srcport;
2105 
2106 			((uint16_t *)&ports)[0] = up[1];
2107 			((uint16_t *)&ports)[1] = up[0];
2108 
2109 			/* Extract ports in net byte order */
2110 			dstport = htons(ntohl(ports) & 0xFFFF);
2111 			srcport = htons(ntohl(ports) >> 16);
2112 
2113 			connfp = &ipst->ips_ipcl_udp_fanout[
2114 			    IPCL_UDP_HASH(dstport, ipst)];
2115 			mutex_enter(&connfp->connf_lock);
2116 			connp = connfp->connf_head;
2117 
2118 			/* do a reverse lookup */
2119 			while ((connp != NULL) &&
2120 			    (!IPCL_UDP_MATCH(connp, dstport,
2121 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2122 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2123 				connp = connp->conn_next;
2124 			}
2125 			if (connp != NULL)
2126 				CONN_INC_REF(connp);
2127 			mutex_exit(&connfp->connf_lock);
2128 			break;
2129 		}
2130 		case IPPROTO_SCTP:
2131 		{
2132 			in6_addr_t map_src, map_dst;
2133 
2134 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2135 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2136 			((uint16_t *)&ports)[0] = up[1];
2137 			((uint16_t *)&ports)[1] = up[0];
2138 
2139 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2140 			    zoneid, ipst->ips_netstack->netstack_sctp);
2141 			if (connp == NULL) {
2142 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2143 				    zoneid, ports, ipha, ipst);
2144 			} else {
2145 				CONN_INC_REF(connp);
2146 				SCTP_REFRELE(CONN2SCTP(connp));
2147 			}
2148 			break;
2149 		}
2150 		default:
2151 		{
2152 			ipha_t ripha;
2153 
2154 			ripha.ipha_src = ipha->ipha_dst;
2155 			ripha.ipha_dst = ipha->ipha_src;
2156 			ripha.ipha_protocol = ipha->ipha_protocol;
2157 
2158 			connfp = &ipst->ips_ipcl_proto_fanout[
2159 			    ipha->ipha_protocol];
2160 			mutex_enter(&connfp->connf_lock);
2161 			connp = connfp->connf_head;
2162 			for (connp = connfp->connf_head; connp != NULL;
2163 			    connp = connp->conn_next) {
2164 				if (IPCL_PROTO_MATCH(connp,
2165 				    ipha->ipha_protocol, &ripha, ill,
2166 				    0, zoneid)) {
2167 					CONN_INC_REF(connp);
2168 					break;
2169 				}
2170 			}
2171 			mutex_exit(&connfp->connf_lock);
2172 		}
2173 	}
2174 	if (connp != NULL) {
2175 		if (connp->conn_nexthop_set)
2176 			nexthop_addr = connp->conn_nexthop_v4;
2177 		CONN_DEC_REF(connp);
2178 	}
2179 	return (nexthop_addr);
2180 }
2181 
2182 /* Table from RFC 1191 */
2183 static int icmp_frag_size_table[] =
2184 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2185 
2186 /*
2187  * Process received ICMP Packet too big.
2188  * After updating any IRE it does the fanout to any matching transport streams.
2189  * Assumes the message has been pulled up till the IP header that caused
2190  * the error.
2191  *
2192  * Returns B_FALSE on failure and B_TRUE on success.
2193  */
2194 static boolean_t
2195 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2196     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2197     ip_stack_t *ipst)
2198 {
2199 	ire_t	*ire, *first_ire;
2200 	int	mtu;
2201 	int	hdr_length;
2202 	ipaddr_t nexthop_addr;
2203 
2204 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2205 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2206 	ASSERT(ill != NULL);
2207 
2208 	hdr_length = IPH_HDR_LENGTH(ipha);
2209 
2210 	/* Drop if the original packet contained a source route */
2211 	if (ip_source_route_included(ipha)) {
2212 		return (B_FALSE);
2213 	}
2214 	/*
2215 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2216 	 * header.
2217 	 */
2218 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2219 	    mp->b_wptr) {
2220 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2221 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2222 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2223 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2224 			return (B_FALSE);
2225 		}
2226 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2227 		ipha = (ipha_t *)&icmph[1];
2228 	}
2229 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2230 	if (nexthop_addr != INADDR_ANY) {
2231 		/* nexthop set */
2232 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2233 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2234 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2235 	} else {
2236 		/* nexthop not set */
2237 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2238 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2239 	}
2240 
2241 	if (!first_ire) {
2242 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2243 		    ntohl(ipha->ipha_dst)));
2244 		return (B_FALSE);
2245 	}
2246 	/* Check for MTU discovery advice as described in RFC 1191 */
2247 	mtu = ntohs(icmph->icmph_du_mtu);
2248 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2249 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2250 	    ire = ire->ire_next) {
2251 		/*
2252 		 * Look for the connection to which this ICMP message is
2253 		 * directed. If it has the IP_NEXTHOP option set, then the
2254 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2255 		 * option. Else the search is limited to regular IREs.
2256 		 */
2257 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2258 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2259 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2260 		    (nexthop_addr != INADDR_ANY)))
2261 			continue;
2262 
2263 		mutex_enter(&ire->ire_lock);
2264 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2265 			/* Reduce the IRE max frag value as advised. */
2266 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2267 			    mtu, ire->ire_max_frag));
2268 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2269 		} else {
2270 			uint32_t length;
2271 			int	i;
2272 
2273 			/*
2274 			 * Use the table from RFC 1191 to figure out
2275 			 * the next "plateau" based on the length in
2276 			 * the original IP packet.
2277 			 */
2278 			length = ntohs(ipha->ipha_length);
2279 			if (ire->ire_max_frag <= length &&
2280 			    ire->ire_max_frag >= length - hdr_length) {
2281 				/*
2282 				 * Handle broken BSD 4.2 systems that
2283 				 * return the wrong iph_length in ICMP
2284 				 * errors.
2285 				 */
2286 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2287 				    length, ire->ire_max_frag));
2288 				length -= hdr_length;
2289 			}
2290 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2291 				if (length > icmp_frag_size_table[i])
2292 					break;
2293 			}
2294 			if (i == A_CNT(icmp_frag_size_table)) {
2295 				/* Smaller than 68! */
2296 				ip1dbg(("Too big for packet size %d\n",
2297 				    length));
2298 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2299 				ire->ire_frag_flag = 0;
2300 			} else {
2301 				mtu = icmp_frag_size_table[i];
2302 				ip1dbg(("Calculated mtu %d, packet size %d, "
2303 				    "before %d", mtu, length,
2304 				    ire->ire_max_frag));
2305 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2306 				ip1dbg((", after %d\n", ire->ire_max_frag));
2307 			}
2308 			/* Record the new max frag size for the ULP. */
2309 			icmph->icmph_du_zero = 0;
2310 			icmph->icmph_du_mtu =
2311 			    htons((uint16_t)ire->ire_max_frag);
2312 		}
2313 		mutex_exit(&ire->ire_lock);
2314 	}
2315 	rw_exit(&first_ire->ire_bucket->irb_lock);
2316 	ire_refrele(first_ire);
2317 	return (B_TRUE);
2318 }
2319 
2320 /*
2321  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2322  * calls this function.
2323  */
2324 static mblk_t *
2325 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2326 {
2327 	ipha_t *ipha;
2328 	icmph_t *icmph;
2329 	ipha_t *in_ipha;
2330 	int length;
2331 
2332 	ASSERT(mp->b_datap->db_type == M_DATA);
2333 
2334 	/*
2335 	 * For Self-encapsulated packets, we added an extra IP header
2336 	 * without the options. Inner IP header is the one from which
2337 	 * the outer IP header was formed. Thus, we need to remove the
2338 	 * outer IP header. To do this, we pullup the whole message
2339 	 * and overlay whatever follows the outer IP header over the
2340 	 * outer IP header.
2341 	 */
2342 
2343 	if (!pullupmsg(mp, -1))
2344 		return (NULL);
2345 
2346 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2347 	ipha = (ipha_t *)&icmph[1];
2348 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2349 
2350 	/*
2351 	 * The length that we want to overlay is following the inner
2352 	 * IP header. Subtracting the IP header + icmp header + outer
2353 	 * IP header's length should give us the length that we want to
2354 	 * overlay.
2355 	 */
2356 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2357 	    hdr_length;
2358 	/*
2359 	 * Overlay whatever follows the inner header over the
2360 	 * outer header.
2361 	 */
2362 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2363 
2364 	/* Set the wptr to account for the outer header */
2365 	mp->b_wptr -= hdr_length;
2366 	return (mp);
2367 }
2368 
2369 /*
2370  * Try to pass the ICMP message upstream in case the ULP cares.
2371  *
2372  * If the packet that caused the ICMP error is secure, we send
2373  * it to AH/ESP to make sure that the attached packet has a
2374  * valid association. ipha in the code below points to the
2375  * IP header of the packet that caused the error.
2376  *
2377  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2378  * in the context of IPSEC. Normally we tell the upper layer
2379  * whenever we send the ire (including ip_bind), the IPSEC header
2380  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2381  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2382  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2383  * same thing. As TCP has the IPSEC options size that needs to be
2384  * adjusted, we just pass the MTU unchanged.
2385  *
2386  * IFN could have been generated locally or by some router.
2387  *
2388  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2389  *	    This happens because IP adjusted its value of MTU on an
2390  *	    earlier IFN message and could not tell the upper layer,
2391  *	    the new adjusted value of MTU e.g. Packet was encrypted
2392  *	    or there was not enough information to fanout to upper
2393  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2394  *	    generates the IFN, where IPSEC processing has *not* been
2395  *	    done.
2396  *
2397  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2398  *	    could have generated this. This happens because ire_max_frag
2399  *	    value in IP was set to a new value, while the IPSEC processing
2400  *	    was being done and after we made the fragmentation check in
2401  *	    ip_wput_ire. Thus on return from IPSEC processing,
2402  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2403  *	    and generates the IFN. As IPSEC processing is over, we fanout
2404  *	    to AH/ESP to remove the header.
2405  *
2406  *	    In both these cases, ipsec_in_loopback will be set indicating
2407  *	    that IFN was generated locally.
2408  *
2409  * ROUTER : IFN could be secure or non-secure.
2410  *
2411  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2412  *	      packet in error has AH/ESP headers to validate the AH/ESP
2413  *	      headers. AH/ESP will verify whether there is a valid SA or
2414  *	      not and send it back. We will fanout again if we have more
2415  *	      data in the packet.
2416  *
2417  *	      If the packet in error does not have AH/ESP, we handle it
2418  *	      like any other case.
2419  *
2420  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2421  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2422  *	      for validation. AH/ESP will verify whether there is a
2423  *	      valid SA or not and send it back. We will fanout again if
2424  *	      we have more data in the packet.
2425  *
2426  *	      If the packet in error does not have AH/ESP, we handle it
2427  *	      like any other case.
2428  */
2429 static void
2430 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2431     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2432     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2433     zoneid_t zoneid)
2434 {
2435 	uint16_t *up;	/* Pointer to ports in ULP header */
2436 	uint32_t ports;	/* reversed ports for fanout */
2437 	ipha_t ripha;	/* With reversed addresses */
2438 	mblk_t *first_mp;
2439 	ipsec_in_t *ii;
2440 	tcph_t	*tcph;
2441 	conn_t	*connp;
2442 	ip_stack_t *ipst;
2443 
2444 	ASSERT(ill != NULL);
2445 
2446 	ASSERT(recv_ill != NULL);
2447 	ipst = recv_ill->ill_ipst;
2448 
2449 	first_mp = mp;
2450 	if (mctl_present) {
2451 		mp = first_mp->b_cont;
2452 		ASSERT(mp != NULL);
2453 
2454 		ii = (ipsec_in_t *)first_mp->b_rptr;
2455 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2456 	} else {
2457 		ii = NULL;
2458 	}
2459 
2460 	switch (ipha->ipha_protocol) {
2461 	case IPPROTO_UDP:
2462 		/*
2463 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2464 		 * transport header.
2465 		 */
2466 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2467 		    mp->b_wptr) {
2468 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2469 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2470 				goto discard_pkt;
2471 			}
2472 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2473 			ipha = (ipha_t *)&icmph[1];
2474 		}
2475 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2476 
2477 		/*
2478 		 * Attempt to find a client stream based on port.
2479 		 * Note that we do a reverse lookup since the header is
2480 		 * in the form we sent it out.
2481 		 * The ripha header is only used for the IP_UDP_MATCH and we
2482 		 * only set the src and dst addresses and protocol.
2483 		 */
2484 		ripha.ipha_src = ipha->ipha_dst;
2485 		ripha.ipha_dst = ipha->ipha_src;
2486 		ripha.ipha_protocol = ipha->ipha_protocol;
2487 		((uint16_t *)&ports)[0] = up[1];
2488 		((uint16_t *)&ports)[1] = up[0];
2489 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2490 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2491 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2492 		    icmph->icmph_type, icmph->icmph_code));
2493 
2494 		/* Have to change db_type after any pullupmsg */
2495 		DB_TYPE(mp) = M_CTL;
2496 
2497 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2498 		    mctl_present, ip_policy, recv_ill, zoneid);
2499 		return;
2500 
2501 	case IPPROTO_TCP:
2502 		/*
2503 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2504 		 * transport header.
2505 		 */
2506 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2507 		    mp->b_wptr) {
2508 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2509 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2510 				goto discard_pkt;
2511 			}
2512 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2513 			ipha = (ipha_t *)&icmph[1];
2514 		}
2515 		/*
2516 		 * Find a TCP client stream for this packet.
2517 		 * Note that we do a reverse lookup since the header is
2518 		 * in the form we sent it out.
2519 		 */
2520 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2521 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2522 		    ipst);
2523 		if (connp == NULL)
2524 			goto discard_pkt;
2525 
2526 		/* Have to change db_type after any pullupmsg */
2527 		DB_TYPE(mp) = M_CTL;
2528 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2529 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2530 		return;
2531 
2532 	case IPPROTO_SCTP:
2533 		/*
2534 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2535 		 * transport header.
2536 		 */
2537 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2538 		    mp->b_wptr) {
2539 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2540 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2541 				goto discard_pkt;
2542 			}
2543 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2544 			ipha = (ipha_t *)&icmph[1];
2545 		}
2546 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2547 		/*
2548 		 * Find a SCTP client stream for this packet.
2549 		 * Note that we do a reverse lookup since the header is
2550 		 * in the form we sent it out.
2551 		 * The ripha header is only used for the matching and we
2552 		 * only set the src and dst addresses, protocol, and version.
2553 		 */
2554 		ripha.ipha_src = ipha->ipha_dst;
2555 		ripha.ipha_dst = ipha->ipha_src;
2556 		ripha.ipha_protocol = ipha->ipha_protocol;
2557 		ripha.ipha_version_and_hdr_length =
2558 		    ipha->ipha_version_and_hdr_length;
2559 		((uint16_t *)&ports)[0] = up[1];
2560 		((uint16_t *)&ports)[1] = up[0];
2561 
2562 		/* Have to change db_type after any pullupmsg */
2563 		DB_TYPE(mp) = M_CTL;
2564 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2565 		    mctl_present, ip_policy, zoneid);
2566 		return;
2567 
2568 	case IPPROTO_ESP:
2569 	case IPPROTO_AH: {
2570 		int ipsec_rc;
2571 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2572 
2573 		/*
2574 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2575 		 * We will re-use the IPSEC_IN if it is already present as
2576 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2577 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2578 		 * one and attach it in the front.
2579 		 */
2580 		if (ii != NULL) {
2581 			/*
2582 			 * ip_fanout_proto_again converts the ICMP errors
2583 			 * that come back from AH/ESP to M_DATA so that
2584 			 * if it is non-AH/ESP and we do a pullupmsg in
2585 			 * this function, it would work. Convert it back
2586 			 * to M_CTL before we send up as this is a ICMP
2587 			 * error. This could have been generated locally or
2588 			 * by some router. Validate the inner IPSEC
2589 			 * headers.
2590 			 *
2591 			 * NOTE : ill_index is used by ip_fanout_proto_again
2592 			 * to locate the ill.
2593 			 */
2594 			ASSERT(ill != NULL);
2595 			ii->ipsec_in_ill_index =
2596 			    ill->ill_phyint->phyint_ifindex;
2597 			ii->ipsec_in_rill_index =
2598 			    recv_ill->ill_phyint->phyint_ifindex;
2599 			DB_TYPE(first_mp->b_cont) = M_CTL;
2600 		} else {
2601 			/*
2602 			 * IPSEC_IN is not present. We attach a ipsec_in
2603 			 * message and send up to IPSEC for validating
2604 			 * and removing the IPSEC headers. Clear
2605 			 * ipsec_in_secure so that when we return
2606 			 * from IPSEC, we don't mistakenly think that this
2607 			 * is a secure packet came from the network.
2608 			 *
2609 			 * NOTE : ill_index is used by ip_fanout_proto_again
2610 			 * to locate the ill.
2611 			 */
2612 			ASSERT(first_mp == mp);
2613 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2614 			if (first_mp == NULL) {
2615 				freemsg(mp);
2616 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2617 				return;
2618 			}
2619 			ii = (ipsec_in_t *)first_mp->b_rptr;
2620 
2621 			/* This is not a secure packet */
2622 			ii->ipsec_in_secure = B_FALSE;
2623 			first_mp->b_cont = mp;
2624 			DB_TYPE(mp) = M_CTL;
2625 			ASSERT(ill != NULL);
2626 			ii->ipsec_in_ill_index =
2627 			    ill->ill_phyint->phyint_ifindex;
2628 			ii->ipsec_in_rill_index =
2629 			    recv_ill->ill_phyint->phyint_ifindex;
2630 		}
2631 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2632 
2633 		if (!ipsec_loaded(ipss)) {
2634 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2635 			return;
2636 		}
2637 
2638 		if (ipha->ipha_protocol == IPPROTO_ESP)
2639 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2640 		else
2641 			ipsec_rc = ipsecah_icmp_error(first_mp);
2642 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2643 			return;
2644 
2645 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2646 		return;
2647 	}
2648 	default:
2649 		/*
2650 		 * The ripha header is only used for the lookup and we
2651 		 * only set the src and dst addresses and protocol.
2652 		 */
2653 		ripha.ipha_src = ipha->ipha_dst;
2654 		ripha.ipha_dst = ipha->ipha_src;
2655 		ripha.ipha_protocol = ipha->ipha_protocol;
2656 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2657 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2658 		    ntohl(ipha->ipha_dst),
2659 		    icmph->icmph_type, icmph->icmph_code));
2660 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2661 			ipha_t *in_ipha;
2662 
2663 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2664 			    mp->b_wptr) {
2665 				if (!pullupmsg(mp, (uchar_t *)ipha +
2666 				    hdr_length + sizeof (ipha_t) -
2667 				    mp->b_rptr)) {
2668 					goto discard_pkt;
2669 				}
2670 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2671 				ipha = (ipha_t *)&icmph[1];
2672 			}
2673 			/*
2674 			 * Caller has verified that length has to be
2675 			 * at least the size of IP header.
2676 			 */
2677 			ASSERT(hdr_length >= sizeof (ipha_t));
2678 			/*
2679 			 * Check the sanity of the inner IP header like
2680 			 * we did for the outer header.
2681 			 */
2682 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2683 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2684 				goto discard_pkt;
2685 			}
2686 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2687 				goto discard_pkt;
2688 			}
2689 			/* Check for Self-encapsulated tunnels */
2690 			if (in_ipha->ipha_src == ipha->ipha_src &&
2691 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2692 
2693 				mp = icmp_inbound_self_encap_error(mp,
2694 				    iph_hdr_length, hdr_length);
2695 				if (mp == NULL)
2696 					goto discard_pkt;
2697 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2698 				ipha = (ipha_t *)&icmph[1];
2699 				hdr_length = IPH_HDR_LENGTH(ipha);
2700 				/*
2701 				 * The packet in error is self-encapsualted.
2702 				 * And we are finding it further encapsulated
2703 				 * which we could not have possibly generated.
2704 				 */
2705 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2706 					goto discard_pkt;
2707 				}
2708 				icmp_inbound_error_fanout(q, ill, first_mp,
2709 				    icmph, ipha, iph_hdr_length, hdr_length,
2710 				    mctl_present, ip_policy, recv_ill, zoneid);
2711 				return;
2712 			}
2713 		}
2714 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2715 			ipha->ipha_protocol == IPPROTO_IPV6) &&
2716 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2717 		    ii != NULL &&
2718 		    ii->ipsec_in_loopback &&
2719 		    ii->ipsec_in_secure) {
2720 			/*
2721 			 * For IP tunnels that get a looped-back
2722 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2723 			 * reported new MTU to take into account the IPsec
2724 			 * headers protecting this configured tunnel.
2725 			 *
2726 			 * This allows the tunnel module (tun.c) to blindly
2727 			 * accept the MTU reported in an ICMP "too big"
2728 			 * message.
2729 			 *
2730 			 * Non-looped back ICMP messages will just be
2731 			 * handled by the security protocols (if needed),
2732 			 * and the first subsequent packet will hit this
2733 			 * path.
2734 			 */
2735 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2736 			    ipsec_in_extra_length(first_mp));
2737 		}
2738 		/* Have to change db_type after any pullupmsg */
2739 		DB_TYPE(mp) = M_CTL;
2740 
2741 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2742 		    ip_policy, recv_ill, zoneid);
2743 		return;
2744 	}
2745 	/* NOTREACHED */
2746 discard_pkt:
2747 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2748 drop_pkt:;
2749 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2750 	freemsg(first_mp);
2751 }
2752 
2753 /*
2754  * Common IP options parser.
2755  *
2756  * Setup routine: fill in *optp with options-parsing state, then
2757  * tail-call ipoptp_next to return the first option.
2758  */
2759 uint8_t
2760 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2761 {
2762 	uint32_t totallen; /* total length of all options */
2763 
2764 	totallen = ipha->ipha_version_and_hdr_length -
2765 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2766 	totallen <<= 2;
2767 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2768 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2769 	optp->ipoptp_flags = 0;
2770 	return (ipoptp_next(optp));
2771 }
2772 
2773 /*
2774  * Common IP options parser: extract next option.
2775  */
2776 uint8_t
2777 ipoptp_next(ipoptp_t *optp)
2778 {
2779 	uint8_t *end = optp->ipoptp_end;
2780 	uint8_t *cur = optp->ipoptp_next;
2781 	uint8_t opt, len, pointer;
2782 
2783 	/*
2784 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2785 	 * has been corrupted.
2786 	 */
2787 	ASSERT(cur <= end);
2788 
2789 	if (cur == end)
2790 		return (IPOPT_EOL);
2791 
2792 	opt = cur[IPOPT_OPTVAL];
2793 
2794 	/*
2795 	 * Skip any NOP options.
2796 	 */
2797 	while (opt == IPOPT_NOP) {
2798 		cur++;
2799 		if (cur == end)
2800 			return (IPOPT_EOL);
2801 		opt = cur[IPOPT_OPTVAL];
2802 	}
2803 
2804 	if (opt == IPOPT_EOL)
2805 		return (IPOPT_EOL);
2806 
2807 	/*
2808 	 * Option requiring a length.
2809 	 */
2810 	if ((cur + 1) >= end) {
2811 		optp->ipoptp_flags |= IPOPTP_ERROR;
2812 		return (IPOPT_EOL);
2813 	}
2814 	len = cur[IPOPT_OLEN];
2815 	if (len < 2) {
2816 		optp->ipoptp_flags |= IPOPTP_ERROR;
2817 		return (IPOPT_EOL);
2818 	}
2819 	optp->ipoptp_cur = cur;
2820 	optp->ipoptp_len = len;
2821 	optp->ipoptp_next = cur + len;
2822 	if (cur + len > end) {
2823 		optp->ipoptp_flags |= IPOPTP_ERROR;
2824 		return (IPOPT_EOL);
2825 	}
2826 
2827 	/*
2828 	 * For the options which require a pointer field, make sure
2829 	 * its there, and make sure it points to either something
2830 	 * inside this option, or the end of the option.
2831 	 */
2832 	switch (opt) {
2833 	case IPOPT_RR:
2834 	case IPOPT_TS:
2835 	case IPOPT_LSRR:
2836 	case IPOPT_SSRR:
2837 		if (len <= IPOPT_OFFSET) {
2838 			optp->ipoptp_flags |= IPOPTP_ERROR;
2839 			return (opt);
2840 		}
2841 		pointer = cur[IPOPT_OFFSET];
2842 		if (pointer - 1 > len) {
2843 			optp->ipoptp_flags |= IPOPTP_ERROR;
2844 			return (opt);
2845 		}
2846 		break;
2847 	}
2848 
2849 	/*
2850 	 * Sanity check the pointer field based on the type of the
2851 	 * option.
2852 	 */
2853 	switch (opt) {
2854 	case IPOPT_RR:
2855 	case IPOPT_SSRR:
2856 	case IPOPT_LSRR:
2857 		if (pointer < IPOPT_MINOFF_SR)
2858 			optp->ipoptp_flags |= IPOPTP_ERROR;
2859 		break;
2860 	case IPOPT_TS:
2861 		if (pointer < IPOPT_MINOFF_IT)
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 		/*
2864 		 * Note that the Internet Timestamp option also
2865 		 * contains two four bit fields (the Overflow field,
2866 		 * and the Flag field), which follow the pointer
2867 		 * field.  We don't need to check that these fields
2868 		 * fall within the length of the option because this
2869 		 * was implicitely done above.  We've checked that the
2870 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2871 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2872 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2873 		 */
2874 		ASSERT(len > IPOPT_POS_OV_FLG);
2875 		break;
2876 	}
2877 
2878 	return (opt);
2879 }
2880 
2881 /*
2882  * Use the outgoing IP header to create an IP_OPTIONS option the way
2883  * it was passed down from the application.
2884  */
2885 int
2886 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2887 {
2888 	ipoptp_t	opts;
2889 	const uchar_t	*opt;
2890 	uint8_t		optval;
2891 	uint8_t		optlen;
2892 	uint32_t	len = 0;
2893 	uchar_t	*buf1 = buf;
2894 
2895 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2896 	len += IP_ADDR_LEN;
2897 	bzero(buf1, IP_ADDR_LEN);
2898 
2899 	/*
2900 	 * OK to cast away const here, as we don't store through the returned
2901 	 * opts.ipoptp_cur pointer.
2902 	 */
2903 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2904 	    optval != IPOPT_EOL;
2905 	    optval = ipoptp_next(&opts)) {
2906 		int	off;
2907 
2908 		opt = opts.ipoptp_cur;
2909 		optlen = opts.ipoptp_len;
2910 		switch (optval) {
2911 		case IPOPT_SSRR:
2912 		case IPOPT_LSRR:
2913 
2914 			/*
2915 			 * Insert ipha_dst as the first entry in the source
2916 			 * route and move down the entries on step.
2917 			 * The last entry gets placed at buf1.
2918 			 */
2919 			buf[IPOPT_OPTVAL] = optval;
2920 			buf[IPOPT_OLEN] = optlen;
2921 			buf[IPOPT_OFFSET] = optlen;
2922 
2923 			off = optlen - IP_ADDR_LEN;
2924 			if (off < 0) {
2925 				/* No entries in source route */
2926 				break;
2927 			}
2928 			/* Last entry in source route */
2929 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2930 			off -= IP_ADDR_LEN;
2931 
2932 			while (off > 0) {
2933 				bcopy(opt + off,
2934 				    buf + off + IP_ADDR_LEN,
2935 				    IP_ADDR_LEN);
2936 				off -= IP_ADDR_LEN;
2937 			}
2938 			/* ipha_dst into first slot */
2939 			bcopy(&ipha->ipha_dst,
2940 			    buf + off + IP_ADDR_LEN,
2941 			    IP_ADDR_LEN);
2942 			buf += optlen;
2943 			len += optlen;
2944 			break;
2945 
2946 		case IPOPT_COMSEC:
2947 		case IPOPT_SECURITY:
2948 			/* if passing up a label is not ok, then remove */
2949 			if (is_system_labeled())
2950 				break;
2951 			/* FALLTHROUGH */
2952 		default:
2953 			bcopy(opt, buf, optlen);
2954 			buf += optlen;
2955 			len += optlen;
2956 			break;
2957 		}
2958 	}
2959 done:
2960 	/* Pad the resulting options */
2961 	while (len & 0x3) {
2962 		*buf++ = IPOPT_EOL;
2963 		len++;
2964 	}
2965 	return (len);
2966 }
2967 
2968 /*
2969  * Update any record route or timestamp options to include this host.
2970  * Reverse any source route option.
2971  * This routine assumes that the options are well formed i.e. that they
2972  * have already been checked.
2973  */
2974 static void
2975 icmp_options_update(ipha_t *ipha)
2976 {
2977 	ipoptp_t	opts;
2978 	uchar_t		*opt;
2979 	uint8_t		optval;
2980 	ipaddr_t	src;		/* Our local address */
2981 	ipaddr_t	dst;
2982 
2983 	ip2dbg(("icmp_options_update\n"));
2984 	src = ipha->ipha_src;
2985 	dst = ipha->ipha_dst;
2986 
2987 	for (optval = ipoptp_first(&opts, ipha);
2988 	    optval != IPOPT_EOL;
2989 	    optval = ipoptp_next(&opts)) {
2990 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2991 		opt = opts.ipoptp_cur;
2992 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2993 		    optval, opts.ipoptp_len));
2994 		switch (optval) {
2995 			int off1, off2;
2996 		case IPOPT_SSRR:
2997 		case IPOPT_LSRR:
2998 			/*
2999 			 * Reverse the source route.  The first entry
3000 			 * should be the next to last one in the current
3001 			 * source route (the last entry is our address).
3002 			 * The last entry should be the final destination.
3003 			 */
3004 			off1 = IPOPT_MINOFF_SR - 1;
3005 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3006 			if (off2 < 0) {
3007 				/* No entries in source route */
3008 				ip1dbg((
3009 				    "icmp_options_update: bad src route\n"));
3010 				break;
3011 			}
3012 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3013 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3014 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3015 			off2 -= IP_ADDR_LEN;
3016 
3017 			while (off1 < off2) {
3018 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3019 				bcopy((char *)opt + off2, (char *)opt + off1,
3020 				    IP_ADDR_LEN);
3021 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3022 				off1 += IP_ADDR_LEN;
3023 				off2 -= IP_ADDR_LEN;
3024 			}
3025 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3026 			break;
3027 		}
3028 	}
3029 }
3030 
3031 /*
3032  * Process received ICMP Redirect messages.
3033  */
3034 static void
3035 icmp_redirect(ill_t *ill, mblk_t *mp)
3036 {
3037 	ipha_t	*ipha;
3038 	int	iph_hdr_length;
3039 	icmph_t	*icmph;
3040 	ipha_t	*ipha_err;
3041 	ire_t	*ire;
3042 	ire_t	*prev_ire;
3043 	ire_t	*save_ire;
3044 	ipaddr_t  src, dst, gateway;
3045 	iulp_t	ulp_info = { 0 };
3046 	int	error;
3047 	ip_stack_t *ipst;
3048 
3049 	ASSERT(ill != NULL);
3050 	ipst = ill->ill_ipst;
3051 
3052 	ipha = (ipha_t *)mp->b_rptr;
3053 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3054 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3055 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3056 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3057 		freemsg(mp);
3058 		return;
3059 	}
3060 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3061 	ipha_err = (ipha_t *)&icmph[1];
3062 	src = ipha->ipha_src;
3063 	dst = ipha_err->ipha_dst;
3064 	gateway = icmph->icmph_rd_gateway;
3065 	/* Make sure the new gateway is reachable somehow. */
3066 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3067 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3068 	/*
3069 	 * Make sure we had a route for the dest in question and that
3070 	 * that route was pointing to the old gateway (the source of the
3071 	 * redirect packet.)
3072 	 */
3073 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3074 	    NULL, MATCH_IRE_GW, ipst);
3075 	/*
3076 	 * Check that
3077 	 *	the redirect was not from ourselves
3078 	 *	the new gateway and the old gateway are directly reachable
3079 	 */
3080 	if (!prev_ire ||
3081 	    !ire ||
3082 	    ire->ire_type == IRE_LOCAL) {
3083 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3084 		freemsg(mp);
3085 		if (ire != NULL)
3086 			ire_refrele(ire);
3087 		if (prev_ire != NULL)
3088 			ire_refrele(prev_ire);
3089 		return;
3090 	}
3091 
3092 	/*
3093 	 * Should we use the old ULP info to create the new gateway?  From
3094 	 * a user's perspective, we should inherit the info so that it
3095 	 * is a "smooth" transition.  If we do not do that, then new
3096 	 * connections going thru the new gateway will have no route metrics,
3097 	 * which is counter-intuitive to user.  From a network point of
3098 	 * view, this may or may not make sense even though the new gateway
3099 	 * is still directly connected to us so the route metrics should not
3100 	 * change much.
3101 	 *
3102 	 * But if the old ire_uinfo is not initialized, we do another
3103 	 * recursive lookup on the dest using the new gateway.  There may
3104 	 * be a route to that.  If so, use it to initialize the redirect
3105 	 * route.
3106 	 */
3107 	if (prev_ire->ire_uinfo.iulp_set) {
3108 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3109 	} else {
3110 		ire_t *tmp_ire;
3111 		ire_t *sire;
3112 
3113 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3114 		    ALL_ZONES, 0, NULL,
3115 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3116 		    ipst);
3117 		if (sire != NULL) {
3118 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3119 			/*
3120 			 * If sire != NULL, ire_ftable_lookup() should not
3121 			 * return a NULL value.
3122 			 */
3123 			ASSERT(tmp_ire != NULL);
3124 			ire_refrele(tmp_ire);
3125 			ire_refrele(sire);
3126 		} else if (tmp_ire != NULL) {
3127 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3128 			    sizeof (iulp_t));
3129 			ire_refrele(tmp_ire);
3130 		}
3131 	}
3132 	if (prev_ire->ire_type == IRE_CACHE)
3133 		ire_delete(prev_ire);
3134 	ire_refrele(prev_ire);
3135 	/*
3136 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3137 	 * require TOS routing
3138 	 */
3139 	switch (icmph->icmph_code) {
3140 	case 0:
3141 	case 1:
3142 		/* TODO: TOS specificity for cases 2 and 3 */
3143 	case 2:
3144 	case 3:
3145 		break;
3146 	default:
3147 		freemsg(mp);
3148 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3149 		ire_refrele(ire);
3150 		return;
3151 	}
3152 	/*
3153 	 * Create a Route Association.  This will allow us to remember that
3154 	 * someone we believe told us to use the particular gateway.
3155 	 */
3156 	save_ire = ire;
3157 	ire = ire_create(
3158 		(uchar_t *)&dst,			/* dest addr */
3159 		(uchar_t *)&ip_g_all_ones,		/* mask */
3160 		(uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3161 		(uchar_t *)&gateway,			/* gateway addr */
3162 		NULL,					/* no in_srcaddr */
3163 		&save_ire->ire_max_frag,		/* max frag */
3164 		NULL,					/* Fast Path header */
3165 		NULL,					/* no rfq */
3166 		NULL,					/* no stq */
3167 		IRE_HOST,
3168 		NULL,
3169 		NULL,
3170 		NULL,
3171 		0,
3172 		0,
3173 		0,
3174 		(RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3175 		&ulp_info,
3176 		NULL,
3177 		NULL,
3178 		ipst);
3179 
3180 	if (ire == NULL) {
3181 		freemsg(mp);
3182 		ire_refrele(save_ire);
3183 		return;
3184 	}
3185 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3186 	ire_refrele(save_ire);
3187 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3188 
3189 	if (error == 0) {
3190 		ire_refrele(ire);		/* Held in ire_add_v4 */
3191 		/* tell routing sockets that we received a redirect */
3192 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3193 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3194 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3195 	}
3196 
3197 	/*
3198 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3199 	 * This together with the added IRE has the effect of
3200 	 * modifying an existing redirect.
3201 	 */
3202 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3203 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3204 	if (prev_ire != NULL) {
3205 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3206 			ire_delete(prev_ire);
3207 		ire_refrele(prev_ire);
3208 	}
3209 
3210 	freemsg(mp);
3211 }
3212 
3213 /*
3214  * Generate an ICMP parameter problem message.
3215  */
3216 static void
3217 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3218 	ip_stack_t *ipst)
3219 {
3220 	icmph_t	icmph;
3221 	boolean_t mctl_present;
3222 	mblk_t *first_mp;
3223 
3224 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3225 
3226 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3227 		if (mctl_present)
3228 			freeb(first_mp);
3229 		return;
3230 	}
3231 
3232 	bzero(&icmph, sizeof (icmph_t));
3233 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3234 	icmph.icmph_pp_ptr = ptr;
3235 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3236 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3237 	    ipst);
3238 }
3239 
3240 /*
3241  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3242  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3243  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3244  * an icmp error packet can be sent.
3245  * Assigns an appropriate source address to the packet. If ipha_dst is
3246  * one of our addresses use it for source. Otherwise pick a source based
3247  * on a route lookup back to ipha_src.
3248  * Note that ipha_src must be set here since the
3249  * packet is likely to arrive on an ill queue in ip_wput() which will
3250  * not set a source address.
3251  */
3252 static void
3253 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3254     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3255 {
3256 	ipaddr_t dst;
3257 	icmph_t	*icmph;
3258 	ipha_t	*ipha;
3259 	uint_t	len_needed;
3260 	size_t	msg_len;
3261 	mblk_t	*mp1;
3262 	ipaddr_t src;
3263 	ire_t	*ire;
3264 	mblk_t *ipsec_mp;
3265 	ipsec_out_t	*io = NULL;
3266 	boolean_t xmit_if_on = B_FALSE;
3267 
3268 	if (mctl_present) {
3269 		/*
3270 		 * If it is :
3271 		 *
3272 		 * 1) a IPSEC_OUT, then this is caused by outbound
3273 		 *    datagram originating on this host. IPSEC processing
3274 		 *    may or may not have been done. Refer to comments above
3275 		 *    icmp_inbound_error_fanout for details.
3276 		 *
3277 		 * 2) a IPSEC_IN if we are generating a icmp_message
3278 		 *    for an incoming datagram destined for us i.e called
3279 		 *    from ip_fanout_send_icmp.
3280 		 */
3281 		ipsec_info_t *in;
3282 		ipsec_mp = mp;
3283 		mp = ipsec_mp->b_cont;
3284 
3285 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3286 		ipha = (ipha_t *)mp->b_rptr;
3287 
3288 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3289 		    in->ipsec_info_type == IPSEC_IN);
3290 
3291 		if (in->ipsec_info_type == IPSEC_IN) {
3292 			/*
3293 			 * Convert the IPSEC_IN to IPSEC_OUT.
3294 			 */
3295 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3296 				BUMP_MIB(&ipst->ips_ip_mib,
3297 				    ipIfStatsOutDiscards);
3298 				return;
3299 			}
3300 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3301 		} else {
3302 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3303 			io = (ipsec_out_t *)in;
3304 			if (io->ipsec_out_xmit_if)
3305 				xmit_if_on = B_TRUE;
3306 			/*
3307 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3308 			 * ire lookup.
3309 			 */
3310 			io->ipsec_out_proc_begin = B_FALSE;
3311 		}
3312 		ASSERT(zoneid == io->ipsec_out_zoneid);
3313 		ASSERT(zoneid != ALL_ZONES);
3314 	} else {
3315 		/*
3316 		 * This is in clear. The icmp message we are building
3317 		 * here should go out in clear.
3318 		 *
3319 		 * Pardon the convolution of it all, but it's easier to
3320 		 * allocate a "use cleartext" IPSEC_IN message and convert
3321 		 * it than it is to allocate a new one.
3322 		 */
3323 		ipsec_in_t *ii;
3324 		ASSERT(DB_TYPE(mp) == M_DATA);
3325 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3326 		if (ipsec_mp == NULL) {
3327 			freemsg(mp);
3328 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3329 			return;
3330 		}
3331 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3332 
3333 		/* This is not a secure packet */
3334 		ii->ipsec_in_secure = B_FALSE;
3335 		/*
3336 		 * For trusted extensions using a shared IP address we can
3337 		 * send using any zoneid.
3338 		 */
3339 		if (zoneid == ALL_ZONES)
3340 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3341 		else
3342 			ii->ipsec_in_zoneid = zoneid;
3343 		ipsec_mp->b_cont = mp;
3344 		ipha = (ipha_t *)mp->b_rptr;
3345 		/*
3346 		 * Convert the IPSEC_IN to IPSEC_OUT.
3347 		 */
3348 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3349 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3350 			return;
3351 		}
3352 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3353 	}
3354 
3355 	/* Remember our eventual destination */
3356 	dst = ipha->ipha_src;
3357 
3358 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3359 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3360 	if (ire != NULL &&
3361 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3362 		src = ipha->ipha_dst;
3363 	} else if (!xmit_if_on) {
3364 		if (ire != NULL)
3365 			ire_refrele(ire);
3366 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3367 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3368 		    ipst);
3369 		if (ire == NULL) {
3370 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3371 			freemsg(ipsec_mp);
3372 			return;
3373 		}
3374 		src = ire->ire_src_addr;
3375 	} else {
3376 		ipif_t	*ipif = NULL;
3377 		ill_t	*ill;
3378 		/*
3379 		 * This must be an ICMP error coming from
3380 		 * ip_mrtun_forward(). The src addr should
3381 		 * be equal to the IP-addr of the outgoing
3382 		 * interface.
3383 		 */
3384 		if (io == NULL) {
3385 			/* This is not a IPSEC_OUT type control msg */
3386 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3387 			freemsg(ipsec_mp);
3388 			return;
3389 		}
3390 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3391 		    NULL, NULL, NULL, NULL, ipst);
3392 		if (ill != NULL) {
3393 			ipif = ipif_get_next_ipif(NULL, ill);
3394 			ill_refrele(ill);
3395 		}
3396 		if (ipif == NULL) {
3397 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3398 			freemsg(ipsec_mp);
3399 			return;
3400 		}
3401 		src = ipif->ipif_src_addr;
3402 		ipif_refrele(ipif);
3403 	}
3404 
3405 	if (ire != NULL)
3406 		ire_refrele(ire);
3407 
3408 	/*
3409 	 * Check if we can send back more then 8 bytes in addition
3410 	 * to the IP header. We will include as much as 64 bytes.
3411 	 */
3412 	len_needed = IPH_HDR_LENGTH(ipha);
3413 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3414 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3415 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3416 	}
3417 	len_needed += ipst->ips_ip_icmp_return;
3418 	msg_len = msgdsize(mp);
3419 	if (msg_len > len_needed) {
3420 		(void) adjmsg(mp, len_needed - msg_len);
3421 		msg_len = len_needed;
3422 	}
3423 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3424 	if (mp1 == NULL) {
3425 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3426 		freemsg(ipsec_mp);
3427 		return;
3428 	}
3429 	/*
3430 	 * On an unlabeled system, dblks don't necessarily have creds.
3431 	 */
3432 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3433 	if (DB_CRED(mp) != NULL)
3434 		mblk_setcred(mp1, DB_CRED(mp));
3435 	mp1->b_cont = mp;
3436 	mp = mp1;
3437 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3438 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3439 	    io->ipsec_out_type == IPSEC_OUT);
3440 	ipsec_mp->b_cont = mp;
3441 
3442 	/*
3443 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3444 	 * node generates be accepted in peace by all on-host destinations.
3445 	 * If we do NOT assume that all on-host destinations trust
3446 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3447 	 * (Look for ipsec_out_icmp_loopback).
3448 	 */
3449 	io->ipsec_out_icmp_loopback = B_TRUE;
3450 
3451 	ipha = (ipha_t *)mp->b_rptr;
3452 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3453 	*ipha = icmp_ipha;
3454 	ipha->ipha_src = src;
3455 	ipha->ipha_dst = dst;
3456 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3457 	msg_len += sizeof (icmp_ipha) + len;
3458 	if (msg_len > IP_MAXPACKET) {
3459 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3460 		msg_len = IP_MAXPACKET;
3461 	}
3462 	ipha->ipha_length = htons((uint16_t)msg_len);
3463 	icmph = (icmph_t *)&ipha[1];
3464 	bcopy(stuff, icmph, len);
3465 	icmph->icmph_checksum = 0;
3466 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3467 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3468 	put(q, ipsec_mp);
3469 }
3470 
3471 /*
3472  * Determine if an ICMP error packet can be sent given the rate limit.
3473  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3474  * in milliseconds) and a burst size. Burst size number of packets can
3475  * be sent arbitrarely closely spaced.
3476  * The state is tracked using two variables to implement an approximate
3477  * token bucket filter:
3478  *	icmp_pkt_err_last - lbolt value when the last burst started
3479  *	icmp_pkt_err_sent - number of packets sent in current burst
3480  */
3481 boolean_t
3482 icmp_err_rate_limit(ip_stack_t *ipst)
3483 {
3484 	clock_t now = TICK_TO_MSEC(lbolt);
3485 	uint_t refilled; /* Number of packets refilled in tbf since last */
3486 	/* Guard against changes by loading into local variable */
3487 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3488 
3489 	if (err_interval == 0)
3490 		return (B_FALSE);
3491 
3492 	if (ipst->ips_icmp_pkt_err_last > now) {
3493 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3494 		ipst->ips_icmp_pkt_err_last = 0;
3495 		ipst->ips_icmp_pkt_err_sent = 0;
3496 	}
3497 	/*
3498 	 * If we are in a burst update the token bucket filter.
3499 	 * Update the "last" time to be close to "now" but make sure
3500 	 * we don't loose precision.
3501 	 */
3502 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3503 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3504 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3505 			ipst->ips_icmp_pkt_err_sent = 0;
3506 		} else {
3507 			ipst->ips_icmp_pkt_err_sent -= refilled;
3508 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3509 		}
3510 	}
3511 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3512 		/* Start of new burst */
3513 		ipst->ips_icmp_pkt_err_last = now;
3514 	}
3515 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3516 		ipst->ips_icmp_pkt_err_sent++;
3517 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3518 			    ipst->ips_icmp_pkt_err_sent));
3519 		return (B_FALSE);
3520 	}
3521 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3522 	return (B_TRUE);
3523 }
3524 
3525 /*
3526  * Check if it is ok to send an IPv4 ICMP error packet in
3527  * response to the IPv4 packet in mp.
3528  * Free the message and return null if no
3529  * ICMP error packet should be sent.
3530  */
3531 static mblk_t *
3532 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3533 {
3534 	icmph_t	*icmph;
3535 	ipha_t	*ipha;
3536 	uint_t	len_needed;
3537 	ire_t	*src_ire;
3538 	ire_t	*dst_ire;
3539 
3540 	if (!mp)
3541 		return (NULL);
3542 	ipha = (ipha_t *)mp->b_rptr;
3543 	if (ip_csum_hdr(ipha)) {
3544 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3545 		freemsg(mp);
3546 		return (NULL);
3547 	}
3548 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3549 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3550 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3551 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3552 	if (src_ire != NULL || dst_ire != NULL ||
3553 	    CLASSD(ipha->ipha_dst) ||
3554 	    CLASSD(ipha->ipha_src) ||
3555 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3556 		/* Note: only errors to the fragment with offset 0 */
3557 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3558 		freemsg(mp);
3559 		if (src_ire != NULL)
3560 			ire_refrele(src_ire);
3561 		if (dst_ire != NULL)
3562 			ire_refrele(dst_ire);
3563 		return (NULL);
3564 	}
3565 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3566 		/*
3567 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3568 		 * errors in response to any ICMP errors.
3569 		 */
3570 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3571 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3572 			if (!pullupmsg(mp, len_needed)) {
3573 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3574 				freemsg(mp);
3575 				return (NULL);
3576 			}
3577 			ipha = (ipha_t *)mp->b_rptr;
3578 		}
3579 		icmph = (icmph_t *)
3580 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3581 		switch (icmph->icmph_type) {
3582 		case ICMP_DEST_UNREACHABLE:
3583 		case ICMP_SOURCE_QUENCH:
3584 		case ICMP_TIME_EXCEEDED:
3585 		case ICMP_PARAM_PROBLEM:
3586 		case ICMP_REDIRECT:
3587 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3588 			freemsg(mp);
3589 			return (NULL);
3590 		default:
3591 			break;
3592 		}
3593 	}
3594 	/*
3595 	 * If this is a labeled system, then check to see if we're allowed to
3596 	 * send a response to this particular sender.  If not, then just drop.
3597 	 */
3598 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3599 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3600 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3601 		freemsg(mp);
3602 		return (NULL);
3603 	}
3604 	if (icmp_err_rate_limit(ipst)) {
3605 		/*
3606 		 * Only send ICMP error packets every so often.
3607 		 * This should be done on a per port/source basis,
3608 		 * but for now this will suffice.
3609 		 */
3610 		freemsg(mp);
3611 		return (NULL);
3612 	}
3613 	return (mp);
3614 }
3615 
3616 /*
3617  * Generate an ICMP redirect message.
3618  */
3619 static void
3620 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3621 {
3622 	icmph_t	icmph;
3623 
3624 	/*
3625 	 * We are called from ip_rput where we could
3626 	 * not have attached an IPSEC_IN.
3627 	 */
3628 	ASSERT(mp->b_datap->db_type == M_DATA);
3629 
3630 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3631 		return;
3632 	}
3633 
3634 	bzero(&icmph, sizeof (icmph_t));
3635 	icmph.icmph_type = ICMP_REDIRECT;
3636 	icmph.icmph_code = 1;
3637 	icmph.icmph_rd_gateway = gateway;
3638 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3639 	/* Redirects sent by router, and router is global zone */
3640 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3641 }
3642 
3643 /*
3644  * Generate an ICMP time exceeded message.
3645  */
3646 void
3647 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3648     ip_stack_t *ipst)
3649 {
3650 	icmph_t	icmph;
3651 	boolean_t mctl_present;
3652 	mblk_t *first_mp;
3653 
3654 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3655 
3656 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3657 		if (mctl_present)
3658 			freeb(first_mp);
3659 		return;
3660 	}
3661 
3662 	bzero(&icmph, sizeof (icmph_t));
3663 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3664 	icmph.icmph_code = code;
3665 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3666 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3667 	    ipst);
3668 }
3669 
3670 /*
3671  * Generate an ICMP unreachable message.
3672  */
3673 void
3674 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3675     ip_stack_t *ipst)
3676 {
3677 	icmph_t	icmph;
3678 	mblk_t *first_mp;
3679 	boolean_t mctl_present;
3680 
3681 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3682 
3683 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3684 		if (mctl_present)
3685 			freeb(first_mp);
3686 		return;
3687 	}
3688 
3689 	bzero(&icmph, sizeof (icmph_t));
3690 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3691 	icmph.icmph_code = code;
3692 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3693 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3694 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3695 	    zoneid, ipst);
3696 }
3697 
3698 /*
3699  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3700  * duplicate.  As long as someone else holds the address, the interface will
3701  * stay down.  When that conflict goes away, the interface is brought back up.
3702  * This is done so that accidental shutdowns of addresses aren't made
3703  * permanent.  Your server will recover from a failure.
3704  *
3705  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3706  * user space process (dhcpagent).
3707  *
3708  * Recovery completes if ARP reports that the address is now ours (via
3709  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3710  *
3711  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3712  */
3713 static void
3714 ipif_dup_recovery(void *arg)
3715 {
3716 	ipif_t *ipif = arg;
3717 	ill_t *ill = ipif->ipif_ill;
3718 	mblk_t *arp_add_mp;
3719 	mblk_t *arp_del_mp;
3720 	area_t *area;
3721 	ip_stack_t *ipst = ill->ill_ipst;
3722 
3723 	ipif->ipif_recovery_id = 0;
3724 
3725 	/*
3726 	 * No lock needed for moving or condemned check, as this is just an
3727 	 * optimization.
3728 	 */
3729 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3730 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3731 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3732 		/* No reason to try to bring this address back. */
3733 		return;
3734 	}
3735 
3736 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3737 		goto alloc_fail;
3738 
3739 	if (ipif->ipif_arp_del_mp == NULL) {
3740 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3741 			goto alloc_fail;
3742 		ipif->ipif_arp_del_mp = arp_del_mp;
3743 	}
3744 
3745 	/* Setting the 'unverified' flag restarts DAD */
3746 	area = (area_t *)arp_add_mp->b_rptr;
3747 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3748 	    ACE_F_UNVERIFIED;
3749 	putnext(ill->ill_rq, arp_add_mp);
3750 	return;
3751 
3752 alloc_fail:
3753 	/*
3754 	 * On allocation failure, just restart the timer.  Note that the ipif
3755 	 * is down here, so no other thread could be trying to start a recovery
3756 	 * timer.  The ill_lock protects the condemned flag and the recovery
3757 	 * timer ID.
3758 	 */
3759 	freemsg(arp_add_mp);
3760 	mutex_enter(&ill->ill_lock);
3761 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3762 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3763 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3764 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3765 	}
3766 	mutex_exit(&ill->ill_lock);
3767 }
3768 
3769 /*
3770  * This is for exclusive changes due to ARP.  Either tear down an interface due
3771  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3772  */
3773 /* ARGSUSED */
3774 static void
3775 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3776 {
3777 	ill_t	*ill = rq->q_ptr;
3778 	arh_t *arh;
3779 	ipaddr_t src;
3780 	ipif_t	*ipif;
3781 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3782 	char hbuf[MAC_STR_LEN];
3783 	char sbuf[INET_ADDRSTRLEN];
3784 	const char *failtype;
3785 	boolean_t bring_up;
3786 	ip_stack_t *ipst = ill->ill_ipst;
3787 
3788 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3789 	case AR_CN_READY:
3790 		failtype = NULL;
3791 		bring_up = B_TRUE;
3792 		break;
3793 	case AR_CN_FAILED:
3794 		failtype = "in use";
3795 		bring_up = B_FALSE;
3796 		break;
3797 	default:
3798 		failtype = "claimed";
3799 		bring_up = B_FALSE;
3800 		break;
3801 	}
3802 
3803 	arh = (arh_t *)mp->b_cont->b_rptr;
3804 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3805 
3806 	/* Handle failures due to probes */
3807 	if (src == 0) {
3808 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3809 		    IP_ADDR_LEN);
3810 	}
3811 
3812 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3813 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3814 	    sizeof (hbuf));
3815 	(void) ip_dot_addr(src, sbuf);
3816 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3817 
3818 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3819 		    ipif->ipif_lcl_addr != src) {
3820 			continue;
3821 		}
3822 
3823 		/*
3824 		 * If we failed on a recovery probe, then restart the timer to
3825 		 * try again later.
3826 		 */
3827 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3828 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3829 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3830 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3831 		    ipst->ips_ip_dup_recovery > 0 &&
3832 		    ipif->ipif_recovery_id == 0) {
3833 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3834 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3835 			continue;
3836 		}
3837 
3838 		/*
3839 		 * If what we're trying to do has already been done, then do
3840 		 * nothing.
3841 		 */
3842 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3843 			continue;
3844 
3845 		if (ipif->ipif_id != 0) {
3846 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3847 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3848 			    ipif->ipif_id);
3849 		}
3850 		if (failtype == NULL) {
3851 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3852 			    ibuf);
3853 		} else {
3854 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3855 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3856 		}
3857 
3858 		if (bring_up) {
3859 			ASSERT(ill->ill_dl_up);
3860 			/*
3861 			 * Free up the ARP delete message so we can allocate
3862 			 * a fresh one through the normal path.
3863 			 */
3864 			freemsg(ipif->ipif_arp_del_mp);
3865 			ipif->ipif_arp_del_mp = NULL;
3866 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3867 			    EINPROGRESS) {
3868 				ipif->ipif_addr_ready = 1;
3869 				(void) ipif_up_done(ipif);
3870 			}
3871 			continue;
3872 		}
3873 
3874 		mutex_enter(&ill->ill_lock);
3875 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3876 		ipif->ipif_flags |= IPIF_DUPLICATE;
3877 		ill->ill_ipif_dup_count++;
3878 		mutex_exit(&ill->ill_lock);
3879 		/*
3880 		 * Already exclusive on the ill; no need to handle deferred
3881 		 * processing here.
3882 		 */
3883 		(void) ipif_down(ipif, NULL, NULL);
3884 		ipif_down_tail(ipif);
3885 		mutex_enter(&ill->ill_lock);
3886 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3887 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3888 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3889 		    ipst->ips_ip_dup_recovery > 0) {
3890 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3891 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3892 		}
3893 		mutex_exit(&ill->ill_lock);
3894 	}
3895 	freemsg(mp);
3896 }
3897 
3898 /* ARGSUSED */
3899 static void
3900 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3901 {
3902 	ill_t	*ill = rq->q_ptr;
3903 	arh_t *arh;
3904 	ipaddr_t src;
3905 	ipif_t	*ipif;
3906 
3907 	arh = (arh_t *)mp->b_cont->b_rptr;
3908 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3909 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3910 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3911 			(void) ipif_resolver_up(ipif, Res_act_defend);
3912 	}
3913 	freemsg(mp);
3914 }
3915 
3916 /*
3917  * News from ARP.  ARP sends notification of interesting events down
3918  * to its clients using M_CTL messages with the interesting ARP packet
3919  * attached via b_cont.
3920  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3921  * queue as opposed to ARP sending the message to all the clients, i.e. all
3922  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3923  * table if a cache IRE is found to delete all the entries for the address in
3924  * the packet.
3925  */
3926 static void
3927 ip_arp_news(queue_t *q, mblk_t *mp)
3928 {
3929 	arcn_t		*arcn;
3930 	arh_t		*arh;
3931 	ire_t		*ire = NULL;
3932 	char		hbuf[MAC_STR_LEN];
3933 	char		sbuf[INET_ADDRSTRLEN];
3934 	ipaddr_t	src;
3935 	in6_addr_t	v6src;
3936 	boolean_t	isv6 = B_FALSE;
3937 	ipif_t		*ipif;
3938 	ill_t		*ill;
3939 	ip_stack_t	*ipst;
3940 
3941 	if (CONN_Q(q)) {
3942 		conn_t *connp = Q_TO_CONN(q);
3943 
3944 		ipst = connp->conn_netstack->netstack_ip;
3945 	} else {
3946 		ill_t *ill = (ill_t *)q->q_ptr;
3947 
3948 		ipst = ill->ill_ipst;
3949 	}
3950 
3951 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3952 		if (q->q_next) {
3953 			putnext(q, mp);
3954 		} else
3955 			freemsg(mp);
3956 		return;
3957 	}
3958 	arh = (arh_t *)mp->b_cont->b_rptr;
3959 	/* Is it one we are interested in? */
3960 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3961 		isv6 = B_TRUE;
3962 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3963 		    IPV6_ADDR_LEN);
3964 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3965 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3966 		    IP_ADDR_LEN);
3967 	} else {
3968 		freemsg(mp);
3969 		return;
3970 	}
3971 
3972 	ill = q->q_ptr;
3973 
3974 	arcn = (arcn_t *)mp->b_rptr;
3975 	switch (arcn->arcn_code) {
3976 	case AR_CN_BOGON:
3977 		/*
3978 		 * Someone is sending ARP packets with a source protocol
3979 		 * address that we have published and for which we believe our
3980 		 * entry is authoritative and (when ill_arp_extend is set)
3981 		 * verified to be unique on the network.
3982 		 *
3983 		 * The ARP module internally handles the cases where the sender
3984 		 * is just probing (for DAD) and where the hardware address of
3985 		 * a non-authoritative entry has changed.  Thus, these are the
3986 		 * real conflicts, and we have to do resolution.
3987 		 *
3988 		 * We back away quickly from the address if it's from DHCP or
3989 		 * otherwise temporary and hasn't been used recently (or at
3990 		 * all).  We'd like to include "deprecated" addresses here as
3991 		 * well (as there's no real reason to defend something we're
3992 		 * discarding), but IPMP "reuses" this flag to mean something
3993 		 * other than the standard meaning.
3994 		 *
3995 		 * If the ARP module above is not extended (meaning that it
3996 		 * doesn't know how to defend the address), then we just log
3997 		 * the problem as we always did and continue on.  It's not
3998 		 * right, but there's little else we can do, and those old ATM
3999 		 * users are going away anyway.
4000 		 */
4001 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4002 		    hbuf, sizeof (hbuf));
4003 		(void) ip_dot_addr(src, sbuf);
4004 		if (isv6) {
4005 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4006 			    ipst);
4007 		} else {
4008 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4009 		}
4010 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4011 			uint32_t now;
4012 			uint32_t maxage;
4013 			clock_t lused;
4014 			uint_t maxdefense;
4015 			uint_t defs;
4016 
4017 			/*
4018 			 * First, figure out if this address hasn't been used
4019 			 * in a while.  If it hasn't, then it's a better
4020 			 * candidate for abandoning.
4021 			 */
4022 			ipif = ire->ire_ipif;
4023 			ASSERT(ipif != NULL);
4024 			now = gethrestime_sec();
4025 			maxage = now - ire->ire_create_time;
4026 			if (maxage > ipst->ips_ip_max_temp_idle)
4027 				maxage = ipst->ips_ip_max_temp_idle;
4028 			lused = drv_hztousec(ddi_get_lbolt() -
4029 			    ire->ire_last_used_time) / MICROSEC + 1;
4030 			if (lused >= maxage && (ipif->ipif_flags &
4031 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4032 				maxdefense = ipst->ips_ip_max_temp_defend;
4033 			else
4034 				maxdefense = ipst->ips_ip_max_defend;
4035 
4036 			/*
4037 			 * Now figure out how many times we've defended
4038 			 * ourselves.  Ignore defenses that happened long in
4039 			 * the past.
4040 			 */
4041 			mutex_enter(&ire->ire_lock);
4042 			if ((defs = ire->ire_defense_count) > 0 &&
4043 			    now - ire->ire_defense_time >
4044 			    ipst->ips_ip_defend_interval) {
4045 				ire->ire_defense_count = defs = 0;
4046 			}
4047 			ire->ire_defense_count++;
4048 			ire->ire_defense_time = now;
4049 			mutex_exit(&ire->ire_lock);
4050 			ill_refhold(ill);
4051 			ire_refrele(ire);
4052 
4053 			/*
4054 			 * If we've defended ourselves too many times already,
4055 			 * then give up and tear down the interface(s) using
4056 			 * this address.  Otherwise, defend by sending out a
4057 			 * gratuitous ARP.
4058 			 */
4059 			if (defs >= maxdefense && ill->ill_arp_extend) {
4060 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4061 				    B_FALSE);
4062 			} else {
4063 				cmn_err(CE_WARN,
4064 				    "node %s is using our IP address %s on %s",
4065 				    hbuf, sbuf, ill->ill_name);
4066 				/*
4067 				 * If this is an old (ATM) ARP module, then
4068 				 * don't try to defend the address.  Remain
4069 				 * compatible with the old behavior.  Defend
4070 				 * only with new ARP.
4071 				 */
4072 				if (ill->ill_arp_extend) {
4073 					qwriter_ip(ill, q, mp, ip_arp_defend,
4074 					    NEW_OP, B_FALSE);
4075 				} else {
4076 					ill_refrele(ill);
4077 				}
4078 			}
4079 			return;
4080 		}
4081 		cmn_err(CE_WARN,
4082 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4083 		    hbuf, sbuf, ill->ill_name);
4084 		if (ire != NULL)
4085 			ire_refrele(ire);
4086 		break;
4087 	case AR_CN_ANNOUNCE:
4088 		if (isv6) {
4089 			/*
4090 			 * For XRESOLV interfaces.
4091 			 * Delete the IRE cache entry and NCE for this
4092 			 * v6 address
4093 			 */
4094 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4095 			/*
4096 			 * If v6src is a non-zero, it's a router address
4097 			 * as below. Do the same sort of thing to clean
4098 			 * out off-net IRE_CACHE entries that go through
4099 			 * the router.
4100 			 */
4101 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4102 				ire_walk_v6(ire_delete_cache_gw_v6,
4103 				    (char *)&v6src, ALL_ZONES, ipst);
4104 			}
4105 		} else {
4106 			nce_hw_map_t hwm;
4107 
4108 			/*
4109 			 * ARP gives us a copy of any packet where it thinks
4110 			 * the address has changed, so that we can update our
4111 			 * caches.  We're responsible for caching known answers
4112 			 * in the current design.  We check whether the
4113 			 * hardware address really has changed in all of our
4114 			 * entries that have cached this mapping, and if so, we
4115 			 * blow them away.  This way we will immediately pick
4116 			 * up the rare case of a host changing hardware
4117 			 * address.
4118 			 */
4119 			if (src == 0)
4120 				break;
4121 			hwm.hwm_addr = src;
4122 			hwm.hwm_hwlen = arh->arh_hlen;
4123 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4124 			ndp_walk_common(ipst->ips_ndp4, NULL,
4125 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4126 		}
4127 		break;
4128 	case AR_CN_READY:
4129 		/* No external v6 resolver has a contract to use this */
4130 		if (isv6)
4131 			break;
4132 		/* If the link is down, we'll retry this later */
4133 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4134 			break;
4135 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4136 		    NULL, NULL, ipst);
4137 		if (ipif != NULL) {
4138 			/*
4139 			 * If this is a duplicate recovery, then we now need to
4140 			 * go exclusive to bring this thing back up.
4141 			 */
4142 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4143 			    IPIF_DUPLICATE) {
4144 				ipif_refrele(ipif);
4145 				ill_refhold(ill);
4146 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4147 				    B_FALSE);
4148 				return;
4149 			}
4150 			/*
4151 			 * If this is the first notice that this address is
4152 			 * ready, then let the user know now.
4153 			 */
4154 			if ((ipif->ipif_flags & IPIF_UP) &&
4155 			    !ipif->ipif_addr_ready) {
4156 				ipif_mask_reply(ipif);
4157 				ip_rts_ifmsg(ipif);
4158 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4159 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4160 			}
4161 			ipif->ipif_addr_ready = 1;
4162 			ipif_refrele(ipif);
4163 		}
4164 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4165 		if (ire != NULL) {
4166 			ire->ire_defense_count = 0;
4167 			ire_refrele(ire);
4168 		}
4169 		break;
4170 	case AR_CN_FAILED:
4171 		/* No external v6 resolver has a contract to use this */
4172 		if (isv6)
4173 			break;
4174 		ill_refhold(ill);
4175 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4176 		return;
4177 	}
4178 	freemsg(mp);
4179 }
4180 
4181 /*
4182  * Create a mblk suitable for carrying the interface index and/or source link
4183  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4184  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4185  * application.
4186  */
4187 mblk_t *
4188 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4189     ip_stack_t *ipst)
4190 {
4191 	mblk_t		*mp;
4192 	ip_pktinfo_t	*pinfo;
4193 	ipha_t *ipha;
4194 	struct ether_header *pether;
4195 
4196 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4197 	if (mp == NULL) {
4198 		ip1dbg(("ip_add_info: allocation failure.\n"));
4199 		return (data_mp);
4200 	}
4201 
4202 	ipha	= (ipha_t *)data_mp->b_rptr;
4203 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4204 	bzero(pinfo, sizeof (ip_pktinfo_t));
4205 	pinfo->ip_pkt_flags = (uchar_t)flags;
4206 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4207 
4208 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4209 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4210 	if (flags & IPF_RECVADDR) {
4211 		ipif_t	*ipif;
4212 		ire_t	*ire;
4213 
4214 		/*
4215 		 * Only valid for V4
4216 		 */
4217 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4218 		    (IPV4_VERSION << 4));
4219 
4220 		ipif = ipif_get_next_ipif(NULL, ill);
4221 		if (ipif != NULL) {
4222 			/*
4223 			 * Since a decision has already been made to deliver the
4224 			 * packet, there is no need to test for SECATTR and
4225 			 * ZONEONLY.
4226 			 */
4227 			ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0, ipif,
4228 			    zoneid, NULL, MATCH_IRE_ILL_GROUP, ipst);
4229 			if (ire == NULL) {
4230 				/*
4231 				 * packet must have come on a different
4232 				 * interface.
4233 				 * Since a decision has already been made to
4234 				 * deliver the packet, there is no need to test
4235 				 * for SECATTR and ZONEONLY.
4236 				 */
4237 				ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0,
4238 				    ipif, zoneid, NULL, NULL, ipst);
4239 			}
4240 
4241 			if (ire == NULL) {
4242 				/*
4243 				 * This is either a multicast packet or
4244 				 * the address has been removed since
4245 				 * the packet was received.
4246 				 * Return INADDR_ANY so that normal source
4247 				 * selection occurs for the response.
4248 				 */
4249 
4250 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4251 			} else {
4252 				ASSERT(ire->ire_type != IRE_CACHE);
4253 				pinfo->ip_pkt_match_addr.s_addr =
4254 				    ire->ire_src_addr;
4255 				ire_refrele(ire);
4256 			}
4257 			ipif_refrele(ipif);
4258 		} else {
4259 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4260 		}
4261 	}
4262 
4263 	pether = (struct ether_header *)((char *)ipha
4264 	    - sizeof (struct ether_header));
4265 	/*
4266 	 * Make sure the interface is an ethernet type, since this option
4267 	 * is currently supported only on this type of interface. Also make
4268 	 * sure we are pointing correctly above db_base.
4269 	 */
4270 
4271 	if ((flags & IPF_RECVSLLA) &&
4272 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4273 	    (ill->ill_type == IFT_ETHER) &&
4274 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4275 
4276 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4277 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4278 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4279 	} else {
4280 		/*
4281 		 * Clear the bit. Indicate to upper layer that IP is not
4282 		 * sending this ancillary info.
4283 		 */
4284 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4285 	}
4286 
4287 	mp->b_datap->db_type = M_CTL;
4288 	mp->b_wptr += sizeof (ip_pktinfo_t);
4289 	mp->b_cont = data_mp;
4290 
4291 	return (mp);
4292 }
4293 
4294 /*
4295  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4296  * part of the bind request.
4297  */
4298 
4299 boolean_t
4300 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4301 {
4302 	ipsec_in_t *ii;
4303 
4304 	ASSERT(policy_mp != NULL);
4305 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4306 
4307 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4308 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4309 
4310 	connp->conn_policy = ii->ipsec_in_policy;
4311 	ii->ipsec_in_policy = NULL;
4312 
4313 	if (ii->ipsec_in_action != NULL) {
4314 		if (connp->conn_latch == NULL) {
4315 			connp->conn_latch = iplatch_create();
4316 			if (connp->conn_latch == NULL)
4317 				return (B_FALSE);
4318 		}
4319 		ipsec_latch_inbound(connp->conn_latch, ii);
4320 	}
4321 	return (B_TRUE);
4322 }
4323 
4324 /*
4325  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4326  * and to arrange for power-fanout assist.  The ULP is identified by
4327  * adding a single byte at the end of the original bind message.
4328  * A ULP other than UDP or TCP that wishes to be recognized passes
4329  * down a bind with a zero length address.
4330  *
4331  * The binding works as follows:
4332  * - A zero byte address means just bind to the protocol.
4333  * - A four byte address is treated as a request to validate
4334  *   that the address is a valid local address, appropriate for
4335  *   an application to bind to. This does not affect any fanout
4336  *   information in IP.
4337  * - A sizeof sin_t byte address is used to bind to only the local address
4338  *   and port.
4339  * - A sizeof ipa_conn_t byte address contains complete fanout information
4340  *   consisting of local and remote addresses and ports.  In
4341  *   this case, the addresses are both validated as appropriate
4342  *   for this operation, and, if so, the information is retained
4343  *   for use in the inbound fanout.
4344  *
4345  * The ULP (except in the zero-length bind) can append an
4346  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4347  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4348  * a copy of the source or destination IRE (source for local bind;
4349  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4350  * policy information contained should be copied on to the conn.
4351  *
4352  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4353  */
4354 mblk_t *
4355 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4356 {
4357 	ssize_t		len;
4358 	struct T_bind_req	*tbr;
4359 	sin_t		*sin;
4360 	ipa_conn_t	*ac;
4361 	uchar_t		*ucp;
4362 	mblk_t		*mp1;
4363 	boolean_t	ire_requested;
4364 	boolean_t	ipsec_policy_set = B_FALSE;
4365 	int		error = 0;
4366 	int		protocol;
4367 	ipa_conn_x_t	*acx;
4368 
4369 	ASSERT(!connp->conn_af_isv6);
4370 	connp->conn_pkt_isv6 = B_FALSE;
4371 
4372 	len = MBLKL(mp);
4373 	if (len < (sizeof (*tbr) + 1)) {
4374 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4375 		    "ip_bind: bogus msg, len %ld", len);
4376 		/* XXX: Need to return something better */
4377 		goto bad_addr;
4378 	}
4379 	/* Back up and extract the protocol identifier. */
4380 	mp->b_wptr--;
4381 	protocol = *mp->b_wptr & 0xFF;
4382 	tbr = (struct T_bind_req *)mp->b_rptr;
4383 	/* Reset the message type in preparation for shipping it back. */
4384 	DB_TYPE(mp) = M_PCPROTO;
4385 
4386 	connp->conn_ulp = (uint8_t)protocol;
4387 
4388 	/*
4389 	 * Check for a zero length address.  This is from a protocol that
4390 	 * wants to register to receive all packets of its type.
4391 	 */
4392 	if (tbr->ADDR_length == 0) {
4393 		/*
4394 		 * These protocols are now intercepted in ip_bind_v6().
4395 		 * Reject protocol-level binds here for now.
4396 		 *
4397 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4398 		 * so that the protocol type cannot be SCTP.
4399 		 */
4400 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4401 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4402 			goto bad_addr;
4403 		}
4404 
4405 		/*
4406 		 *
4407 		 * The udp module never sends down a zero-length address,
4408 		 * and allowing this on a labeled system will break MLP
4409 		 * functionality.
4410 		 */
4411 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4412 			goto bad_addr;
4413 
4414 		if (connp->conn_mac_exempt)
4415 			goto bad_addr;
4416 
4417 		/* No hash here really.  The table is big enough. */
4418 		connp->conn_srcv6 = ipv6_all_zeros;
4419 
4420 		ipcl_proto_insert(connp, protocol);
4421 
4422 		tbr->PRIM_type = T_BIND_ACK;
4423 		return (mp);
4424 	}
4425 
4426 	/* Extract the address pointer from the message. */
4427 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4428 	    tbr->ADDR_length);
4429 	if (ucp == NULL) {
4430 		ip1dbg(("ip_bind: no address\n"));
4431 		goto bad_addr;
4432 	}
4433 	if (!OK_32PTR(ucp)) {
4434 		ip1dbg(("ip_bind: unaligned address\n"));
4435 		goto bad_addr;
4436 	}
4437 	/*
4438 	 * Check for trailing mps.
4439 	 */
4440 
4441 	mp1 = mp->b_cont;
4442 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4443 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4444 
4445 	switch (tbr->ADDR_length) {
4446 	default:
4447 		ip1dbg(("ip_bind: bad address length %d\n",
4448 		    (int)tbr->ADDR_length));
4449 		goto bad_addr;
4450 
4451 	case IP_ADDR_LEN:
4452 		/* Verification of local address only */
4453 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4454 		    ire_requested, ipsec_policy_set, B_FALSE);
4455 		break;
4456 
4457 	case sizeof (sin_t):
4458 		sin = (sin_t *)ucp;
4459 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4460 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4461 		break;
4462 
4463 	case sizeof (ipa_conn_t):
4464 		ac = (ipa_conn_t *)ucp;
4465 		/* For raw socket, the local port is not set. */
4466 		if (ac->ac_lport == 0)
4467 			ac->ac_lport = connp->conn_lport;
4468 		/* Always verify destination reachability. */
4469 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4470 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4471 		    ipsec_policy_set, B_TRUE, B_TRUE);
4472 		break;
4473 
4474 	case sizeof (ipa_conn_x_t):
4475 		acx = (ipa_conn_x_t *)ucp;
4476 		/*
4477 		 * Whether or not to verify destination reachability depends
4478 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4479 		 */
4480 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4481 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4482 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4483 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4484 		break;
4485 	}
4486 	if (error == EINPROGRESS)
4487 		return (NULL);
4488 	else if (error != 0)
4489 		goto bad_addr;
4490 	/*
4491 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4492 	 * We can't do this in ip_bind_insert_ire because the policy
4493 	 * may not have been inherited at that point in time and hence
4494 	 * conn_out_enforce_policy may not be set.
4495 	 */
4496 	mp1 = mp->b_cont;
4497 	if (ire_requested && connp->conn_out_enforce_policy &&
4498 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4499 		ire_t *ire = (ire_t *)mp1->b_rptr;
4500 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4501 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4502 	}
4503 
4504 	/* Send it home. */
4505 	mp->b_datap->db_type = M_PCPROTO;
4506 	tbr->PRIM_type = T_BIND_ACK;
4507 	return (mp);
4508 
4509 bad_addr:
4510 	/*
4511 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4512 	 * a unix errno.
4513 	 */
4514 	if (error > 0)
4515 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4516 	else
4517 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4518 	return (mp);
4519 }
4520 
4521 /*
4522  * Here address is verified to be a valid local address.
4523  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4524  * address is also considered a valid local address.
4525  * In the case of a broadcast/multicast address, however, the
4526  * upper protocol is expected to reset the src address
4527  * to 0 if it sees a IRE_BROADCAST type returned so that
4528  * no packets are emitted with broadcast/multicast address as
4529  * source address (that violates hosts requirements RFC1122)
4530  * The addresses valid for bind are:
4531  *	(1) - INADDR_ANY (0)
4532  *	(2) - IP address of an UP interface
4533  *	(3) - IP address of a DOWN interface
4534  *	(4) - valid local IP broadcast addresses. In this case
4535  *	the conn will only receive packets destined to
4536  *	the specified broadcast address.
4537  *	(5) - a multicast address. In this case
4538  *	the conn will only receive packets destined to
4539  *	the specified multicast address. Note: the
4540  *	application still has to issue an
4541  *	IP_ADD_MEMBERSHIP socket option.
4542  *
4543  * On error, return -1 for TBADADDR otherwise pass the
4544  * errno with TSYSERR reply.
4545  *
4546  * In all the above cases, the bound address must be valid in the current zone.
4547  * When the address is loopback, multicast or broadcast, there might be many
4548  * matching IREs so bind has to look up based on the zone.
4549  *
4550  * Note: lport is in network byte order.
4551  */
4552 int
4553 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4554     boolean_t ire_requested, boolean_t ipsec_policy_set,
4555     boolean_t fanout_insert)
4556 {
4557 	int		error = 0;
4558 	ire_t		*src_ire;
4559 	mblk_t		*policy_mp;
4560 	ipif_t		*ipif;
4561 	zoneid_t	zoneid;
4562 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4563 
4564 	if (ipsec_policy_set) {
4565 		policy_mp = mp->b_cont;
4566 	}
4567 
4568 	/*
4569 	 * If it was previously connected, conn_fully_bound would have
4570 	 * been set.
4571 	 */
4572 	connp->conn_fully_bound = B_FALSE;
4573 
4574 	src_ire = NULL;
4575 	ipif = NULL;
4576 
4577 	zoneid = IPCL_ZONEID(connp);
4578 
4579 	if (src_addr) {
4580 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4581 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4582 		/*
4583 		 * If an address other than 0.0.0.0 is requested,
4584 		 * we verify that it is a valid address for bind
4585 		 * Note: Following code is in if-else-if form for
4586 		 * readability compared to a condition check.
4587 		 */
4588 		/* LINTED - statement has no consequent */
4589 		if (IRE_IS_LOCAL(src_ire)) {
4590 			/*
4591 			 * (2) Bind to address of local UP interface
4592 			 */
4593 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4594 			/*
4595 			 * (4) Bind to broadcast address
4596 			 * Note: permitted only from transports that
4597 			 * request IRE
4598 			 */
4599 			if (!ire_requested)
4600 				error = EADDRNOTAVAIL;
4601 		} else {
4602 			/*
4603 			 * (3) Bind to address of local DOWN interface
4604 			 * (ipif_lookup_addr() looks up all interfaces
4605 			 * but we do not get here for UP interfaces
4606 			 * - case (2) above)
4607 			 * We put the protocol byte back into the mblk
4608 			 * since we may come back via ip_wput_nondata()
4609 			 * later with this mblk if ipif_lookup_addr chooses
4610 			 * to defer processing.
4611 			 */
4612 			*mp->b_wptr++ = (char)connp->conn_ulp;
4613 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4614 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4615 			    &error, ipst)) != NULL) {
4616 				ipif_refrele(ipif);
4617 			} else if (error == EINPROGRESS) {
4618 				if (src_ire != NULL)
4619 					ire_refrele(src_ire);
4620 				return (EINPROGRESS);
4621 			} else if (CLASSD(src_addr)) {
4622 				error = 0;
4623 				if (src_ire != NULL)
4624 					ire_refrele(src_ire);
4625 				/*
4626 				 * (5) bind to multicast address.
4627 				 * Fake out the IRE returned to upper
4628 				 * layer to be a broadcast IRE.
4629 				 */
4630 				src_ire = ire_ctable_lookup(
4631 				    INADDR_BROADCAST, INADDR_ANY,
4632 				    IRE_BROADCAST, NULL, zoneid, NULL,
4633 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4634 				    ipst);
4635 				if (src_ire == NULL || !ire_requested)
4636 					error = EADDRNOTAVAIL;
4637 			} else {
4638 				/*
4639 				 * Not a valid address for bind
4640 				 */
4641 				error = EADDRNOTAVAIL;
4642 			}
4643 			/*
4644 			 * Just to keep it consistent with the processing in
4645 			 * ip_bind_v4()
4646 			 */
4647 			mp->b_wptr--;
4648 		}
4649 		if (error) {
4650 			/* Red Alert!  Attempting to be a bogon! */
4651 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4652 			    ntohl(src_addr)));
4653 			goto bad_addr;
4654 		}
4655 	}
4656 
4657 	/*
4658 	 * Allow setting new policies. For example, disconnects come
4659 	 * down as ipa_t bind. As we would have set conn_policy_cached
4660 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4661 	 * can change after the disconnect.
4662 	 */
4663 	connp->conn_policy_cached = B_FALSE;
4664 
4665 	/*
4666 	 * If not fanout_insert this was just an address verification
4667 	 */
4668 	if (fanout_insert) {
4669 		/*
4670 		 * The addresses have been verified. Time to insert in
4671 		 * the correct fanout list.
4672 		 */
4673 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4674 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4675 		connp->conn_lport = lport;
4676 		connp->conn_fport = 0;
4677 		/*
4678 		 * Do we need to add a check to reject Multicast packets
4679 		 *
4680 		 * We need to make sure that the conn_recv is set to a non-null
4681 		 * value before we insert the conn into the classifier table.
4682 		 * This is to avoid a race with an incoming packet which does an
4683 		 * ipcl_classify().
4684 		 */
4685 		if (*mp->b_wptr == IPPROTO_TCP)
4686 			connp->conn_recv = tcp_conn_request;
4687 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4688 	}
4689 
4690 	if (error == 0) {
4691 		if (ire_requested) {
4692 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4693 				error = -1;
4694 				/* Falls through to bad_addr */
4695 			}
4696 		} else if (ipsec_policy_set) {
4697 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4698 				error = -1;
4699 				/* Falls through to bad_addr */
4700 			}
4701 		}
4702 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4703 		connp->conn_recv = tcp_input;
4704 	}
4705 bad_addr:
4706 	if (error != 0) {
4707 		if (connp->conn_anon_port) {
4708 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4709 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4710 			    B_FALSE);
4711 		}
4712 		connp->conn_mlp_type = mlptSingle;
4713 	}
4714 	if (src_ire != NULL)
4715 		IRE_REFRELE(src_ire);
4716 	if (ipsec_policy_set) {
4717 		ASSERT(policy_mp == mp->b_cont);
4718 		ASSERT(policy_mp != NULL);
4719 		freeb(policy_mp);
4720 		/*
4721 		 * As of now assume that nothing else accompanies
4722 		 * IPSEC_POLICY_SET.
4723 		 */
4724 		mp->b_cont = NULL;
4725 	}
4726 	return (error);
4727 }
4728 
4729 /*
4730  * Verify that both the source and destination addresses
4731  * are valid.  If verify_dst is false, then the destination address may be
4732  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4733  * destination reachability, while tunnels do not.
4734  * Note that we allow connect to broadcast and multicast
4735  * addresses when ire_requested is set. Thus the ULP
4736  * has to check for IRE_BROADCAST and multicast.
4737  *
4738  * Returns zero if ok.
4739  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4740  * (for use with TSYSERR reply).
4741  *
4742  * Note: lport and fport are in network byte order.
4743  */
4744 int
4745 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4746     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4747     boolean_t ire_requested, boolean_t ipsec_policy_set,
4748     boolean_t fanout_insert, boolean_t verify_dst)
4749 {
4750 	ire_t		*src_ire;
4751 	ire_t		*dst_ire;
4752 	int		error = 0;
4753 	int 		protocol;
4754 	mblk_t		*policy_mp;
4755 	ire_t		*sire = NULL;
4756 	ire_t		*md_dst_ire = NULL;
4757 	ire_t		*lso_dst_ire = NULL;
4758 	ill_t		*ill = NULL;
4759 	zoneid_t	zoneid;
4760 	ipaddr_t	src_addr = *src_addrp;
4761 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4762 
4763 	src_ire = dst_ire = NULL;
4764 	protocol = *mp->b_wptr & 0xFF;
4765 
4766 	/*
4767 	 * If we never got a disconnect before, clear it now.
4768 	 */
4769 	connp->conn_fully_bound = B_FALSE;
4770 
4771 	if (ipsec_policy_set) {
4772 		policy_mp = mp->b_cont;
4773 	}
4774 
4775 	zoneid = IPCL_ZONEID(connp);
4776 
4777 	if (CLASSD(dst_addr)) {
4778 		/* Pick up an IRE_BROADCAST */
4779 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4780 		    NULL, zoneid, MBLK_GETLABEL(mp),
4781 		    (MATCH_IRE_RECURSIVE |
4782 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4783 		    MATCH_IRE_SECATTR), ipst);
4784 	} else {
4785 		/*
4786 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4787 		 * and onlink ipif is not found set ENETUNREACH error.
4788 		 */
4789 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4790 			ipif_t *ipif;
4791 
4792 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4793 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4794 			if (ipif == NULL) {
4795 				error = ENETUNREACH;
4796 				goto bad_addr;
4797 			}
4798 			ipif_refrele(ipif);
4799 		}
4800 
4801 		if (connp->conn_nexthop_set) {
4802 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4803 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4804 			    MATCH_IRE_SECATTR, ipst);
4805 		} else {
4806 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4807 			    &sire, zoneid, MBLK_GETLABEL(mp),
4808 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4809 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4810 			    MATCH_IRE_SECATTR), ipst);
4811 		}
4812 	}
4813 	/*
4814 	 * dst_ire can't be a broadcast when not ire_requested.
4815 	 * We also prevent ire's with src address INADDR_ANY to
4816 	 * be used, which are created temporarily for
4817 	 * sending out packets from endpoints that have
4818 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4819 	 * reachable.  If verify_dst is false, the destination needn't be
4820 	 * reachable.
4821 	 *
4822 	 * If we match on a reject or black hole, then we've got a
4823 	 * local failure.  May as well fail out the connect() attempt,
4824 	 * since it's never going to succeed.
4825 	 */
4826 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4827 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4828 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4829 		/*
4830 		 * If we're verifying destination reachability, we always want
4831 		 * to complain here.
4832 		 *
4833 		 * If we're not verifying destination reachability but the
4834 		 * destination has a route, we still want to fail on the
4835 		 * temporary address and broadcast address tests.
4836 		 */
4837 		if (verify_dst || (dst_ire != NULL)) {
4838 			if (ip_debug > 2) {
4839 				pr_addr_dbg("ip_bind_connected: bad connected "
4840 				    "dst %s\n", AF_INET, &dst_addr);
4841 			}
4842 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4843 				error = ENETUNREACH;
4844 			else
4845 				error = EHOSTUNREACH;
4846 			goto bad_addr;
4847 		}
4848 	}
4849 
4850 	/*
4851 	 * We now know that routing will allow us to reach the destination.
4852 	 * Check whether Trusted Solaris policy allows communication with this
4853 	 * host, and pretend that the destination is unreachable if not.
4854 	 *
4855 	 * This is never a problem for TCP, since that transport is known to
4856 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4857 	 * handling.  If the remote is unreachable, it will be detected at that
4858 	 * point, so there's no reason to check it here.
4859 	 *
4860 	 * Note that for sendto (and other datagram-oriented friends), this
4861 	 * check is done as part of the data path label computation instead.
4862 	 * The check here is just to make non-TCP connect() report the right
4863 	 * error.
4864 	 */
4865 	if (dst_ire != NULL && is_system_labeled() &&
4866 	    !IPCL_IS_TCP(connp) &&
4867 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4868 	    connp->conn_mac_exempt, ipst) != 0) {
4869 		error = EHOSTUNREACH;
4870 		if (ip_debug > 2) {
4871 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4872 			    AF_INET, &dst_addr);
4873 		}
4874 		goto bad_addr;
4875 	}
4876 
4877 	/*
4878 	 * If the app does a connect(), it means that it will most likely
4879 	 * send more than 1 packet to the destination.  It makes sense
4880 	 * to clear the temporary flag.
4881 	 */
4882 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4883 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4884 		irb_t *irb = dst_ire->ire_bucket;
4885 
4886 		rw_enter(&irb->irb_lock, RW_WRITER);
4887 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4888 		irb->irb_tmp_ire_cnt--;
4889 		rw_exit(&irb->irb_lock);
4890 	}
4891 
4892 	/*
4893 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4894 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4895 	 * eligibility tests for passive connects are handled separately
4896 	 * through tcp_adapt_ire().  We do this before the source address
4897 	 * selection, because dst_ire may change after a call to
4898 	 * ipif_select_source().  This is a best-effort check, as the
4899 	 * packet for this connection may not actually go through
4900 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4901 	 * calling ip_newroute().  This is why we further check on the
4902 	 * IRE during LSO/Multidata packet transmission in
4903 	 * tcp_lsosend()/tcp_multisend().
4904 	 */
4905 	if (!ipsec_policy_set && dst_ire != NULL &&
4906 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4907 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4908 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4909 			lso_dst_ire = dst_ire;
4910 			IRE_REFHOLD(lso_dst_ire);
4911 		} else if (ipst->ips_ip_multidata_outbound &&
4912 		    ILL_MDT_CAPABLE(ill)) {
4913 			md_dst_ire = dst_ire;
4914 			IRE_REFHOLD(md_dst_ire);
4915 		}
4916 	}
4917 
4918 	if (dst_ire != NULL &&
4919 	    dst_ire->ire_type == IRE_LOCAL &&
4920 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4921 		/*
4922 		 * If the IRE belongs to a different zone, look for a matching
4923 		 * route in the forwarding table and use the source address from
4924 		 * that route.
4925 		 */
4926 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4927 		    zoneid, 0, NULL,
4928 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4929 		    MATCH_IRE_RJ_BHOLE, ipst);
4930 		if (src_ire == NULL) {
4931 			error = EHOSTUNREACH;
4932 			goto bad_addr;
4933 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4934 			if (!(src_ire->ire_type & IRE_HOST))
4935 				error = ENETUNREACH;
4936 			else
4937 				error = EHOSTUNREACH;
4938 			goto bad_addr;
4939 		}
4940 		if (src_addr == INADDR_ANY)
4941 			src_addr = src_ire->ire_src_addr;
4942 		ire_refrele(src_ire);
4943 		src_ire = NULL;
4944 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4945 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4946 			src_addr = sire->ire_src_addr;
4947 			ire_refrele(dst_ire);
4948 			dst_ire = sire;
4949 			sire = NULL;
4950 		} else {
4951 			/*
4952 			 * Pick a source address so that a proper inbound
4953 			 * load spreading would happen.
4954 			 */
4955 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4956 			ipif_t *src_ipif = NULL;
4957 			ire_t *ipif_ire;
4958 
4959 			/*
4960 			 * Supply a local source address such that inbound
4961 			 * load spreading happens.
4962 			 *
4963 			 * Determine the best source address on this ill for
4964 			 * the destination.
4965 			 *
4966 			 * 1) For broadcast, we should return a broadcast ire
4967 			 *    found above so that upper layers know that the
4968 			 *    destination address is a broadcast address.
4969 			 *
4970 			 * 2) If this is part of a group, select a better
4971 			 *    source address so that better inbound load
4972 			 *    balancing happens. Do the same if the ipif
4973 			 *    is DEPRECATED.
4974 			 *
4975 			 * 3) If the outgoing interface is part of a usesrc
4976 			 *    group, then try selecting a source address from
4977 			 *    the usesrc ILL.
4978 			 */
4979 			if ((dst_ire->ire_zoneid != zoneid &&
4980 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4981 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4982 			    ((dst_ill->ill_group != NULL) ||
4983 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4984 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4985 				/*
4986 				 * If the destination is reachable via a
4987 				 * given gateway, the selected source address
4988 				 * should be in the same subnet as the gateway.
4989 				 * Otherwise, the destination is not reachable.
4990 				 *
4991 				 * If there are no interfaces on the same subnet
4992 				 * as the destination, ipif_select_source gives
4993 				 * first non-deprecated interface which might be
4994 				 * on a different subnet than the gateway.
4995 				 * This is not desirable. Hence pass the dst_ire
4996 				 * source address to ipif_select_source.
4997 				 * It is sure that the destination is reachable
4998 				 * with the dst_ire source address subnet.
4999 				 * So passing dst_ire source address to
5000 				 * ipif_select_source will make sure that the
5001 				 * selected source will be on the same subnet
5002 				 * as dst_ire source address.
5003 				 */
5004 				ipaddr_t saddr =
5005 				    dst_ire->ire_ipif->ipif_src_addr;
5006 				src_ipif = ipif_select_source(dst_ill,
5007 				    saddr, zoneid);
5008 				if (src_ipif != NULL) {
5009 					if (IS_VNI(src_ipif->ipif_ill)) {
5010 						/*
5011 						 * For VNI there is no
5012 						 * interface route
5013 						 */
5014 						src_addr =
5015 						    src_ipif->ipif_src_addr;
5016 					} else {
5017 						ipif_ire =
5018 						    ipif_to_ire(src_ipif);
5019 						if (ipif_ire != NULL) {
5020 							IRE_REFRELE(dst_ire);
5021 							dst_ire = ipif_ire;
5022 						}
5023 						src_addr =
5024 						    dst_ire->ire_src_addr;
5025 					}
5026 					ipif_refrele(src_ipif);
5027 				} else {
5028 					src_addr = dst_ire->ire_src_addr;
5029 				}
5030 			} else {
5031 				src_addr = dst_ire->ire_src_addr;
5032 			}
5033 		}
5034 	}
5035 
5036 	/*
5037 	 * We do ire_route_lookup() here (and not
5038 	 * interface lookup as we assert that
5039 	 * src_addr should only come from an
5040 	 * UP interface for hard binding.
5041 	 */
5042 	ASSERT(src_ire == NULL);
5043 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5044 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5045 	/* src_ire must be a local|loopback */
5046 	if (!IRE_IS_LOCAL(src_ire)) {
5047 		if (ip_debug > 2) {
5048 			pr_addr_dbg("ip_bind_connected: bad connected "
5049 			    "src %s\n", AF_INET, &src_addr);
5050 		}
5051 		error = EADDRNOTAVAIL;
5052 		goto bad_addr;
5053 	}
5054 
5055 	/*
5056 	 * If the source address is a loopback address, the
5057 	 * destination had best be local or multicast.
5058 	 * The transports that can't handle multicast will reject
5059 	 * those addresses.
5060 	 */
5061 	if (src_ire->ire_type == IRE_LOOPBACK &&
5062 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5063 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5064 		error = -1;
5065 		goto bad_addr;
5066 	}
5067 
5068 	/*
5069 	 * Allow setting new policies. For example, disconnects come
5070 	 * down as ipa_t bind. As we would have set conn_policy_cached
5071 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5072 	 * can change after the disconnect.
5073 	 */
5074 	connp->conn_policy_cached = B_FALSE;
5075 
5076 	/*
5077 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5078 	 * can handle their passed-in conn's.
5079 	 */
5080 
5081 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5082 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5083 	connp->conn_lport = lport;
5084 	connp->conn_fport = fport;
5085 	*src_addrp = src_addr;
5086 
5087 	ASSERT(!(ipsec_policy_set && ire_requested));
5088 	if (ire_requested) {
5089 		iulp_t *ulp_info = NULL;
5090 
5091 		/*
5092 		 * Note that sire will not be NULL if this is an off-link
5093 		 * connection and there is not cache for that dest yet.
5094 		 *
5095 		 * XXX Because of an existing bug, if there are multiple
5096 		 * default routes, the IRE returned now may not be the actual
5097 		 * default route used (default routes are chosen in a
5098 		 * round robin fashion).  So if the metrics for different
5099 		 * default routes are different, we may return the wrong
5100 		 * metrics.  This will not be a problem if the existing
5101 		 * bug is fixed.
5102 		 */
5103 		if (sire != NULL) {
5104 			ulp_info = &(sire->ire_uinfo);
5105 		}
5106 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5107 			error = -1;
5108 			goto bad_addr;
5109 		}
5110 	} else if (ipsec_policy_set) {
5111 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5112 			error = -1;
5113 			goto bad_addr;
5114 		}
5115 	}
5116 
5117 	/*
5118 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5119 	 * we'll cache that.  If we don't, we'll inherit global policy.
5120 	 *
5121 	 * We can't insert until the conn reflects the policy. Note that
5122 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5123 	 * connections where we don't have a policy. This is to prevent
5124 	 * global policy lookups in the inbound path.
5125 	 *
5126 	 * If we insert before we set conn_policy_cached,
5127 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5128 	 * because global policy cound be non-empty. We normally call
5129 	 * ipsec_check_policy() for conn_policy_cached connections only if
5130 	 * ipc_in_enforce_policy is set. But in this case,
5131 	 * conn_policy_cached can get set anytime since we made the
5132 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5133 	 * called, which will make the above assumption false.  Thus, we
5134 	 * need to insert after we set conn_policy_cached.
5135 	 */
5136 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5137 		goto bad_addr;
5138 
5139 	if (fanout_insert) {
5140 		/*
5141 		 * The addresses have been verified. Time to insert in
5142 		 * the correct fanout list.
5143 		 * We need to make sure that the conn_recv is set to a non-null
5144 		 * value before we insert into the classifier table to avoid a
5145 		 * race with an incoming packet which does an ipcl_classify().
5146 		 */
5147 		if (protocol == IPPROTO_TCP)
5148 			connp->conn_recv = tcp_input;
5149 		error = ipcl_conn_insert(connp, protocol, src_addr,
5150 		    dst_addr, connp->conn_ports);
5151 	}
5152 
5153 	if (error == 0) {
5154 		connp->conn_fully_bound = B_TRUE;
5155 		/*
5156 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5157 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5158 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5159 		 * ip_xxinfo_return(), which performs further checks
5160 		 * against them and upon success, returns the LSO/MDT info
5161 		 * mblk which we will attach to the bind acknowledgment.
5162 		 */
5163 		if (lso_dst_ire != NULL) {
5164 			mblk_t *lsoinfo_mp;
5165 
5166 			ASSERT(ill->ill_lso_capab != NULL);
5167 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5168 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5169 				linkb(mp, lsoinfo_mp);
5170 		} else if (md_dst_ire != NULL) {
5171 			mblk_t *mdinfo_mp;
5172 
5173 			ASSERT(ill->ill_mdt_capab != NULL);
5174 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5175 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5176 				linkb(mp, mdinfo_mp);
5177 		}
5178 	}
5179 bad_addr:
5180 	if (ipsec_policy_set) {
5181 		ASSERT(policy_mp == mp->b_cont);
5182 		ASSERT(policy_mp != NULL);
5183 		freeb(policy_mp);
5184 		/*
5185 		 * As of now assume that nothing else accompanies
5186 		 * IPSEC_POLICY_SET.
5187 		 */
5188 		mp->b_cont = NULL;
5189 	}
5190 	if (src_ire != NULL)
5191 		IRE_REFRELE(src_ire);
5192 	if (dst_ire != NULL)
5193 		IRE_REFRELE(dst_ire);
5194 	if (sire != NULL)
5195 		IRE_REFRELE(sire);
5196 	if (md_dst_ire != NULL)
5197 		IRE_REFRELE(md_dst_ire);
5198 	if (lso_dst_ire != NULL)
5199 		IRE_REFRELE(lso_dst_ire);
5200 	return (error);
5201 }
5202 
5203 /*
5204  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5205  * Prefers dst_ire over src_ire.
5206  */
5207 static boolean_t
5208 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5209 {
5210 	mblk_t	*mp1;
5211 	ire_t *ret_ire = NULL;
5212 
5213 	mp1 = mp->b_cont;
5214 	ASSERT(mp1 != NULL);
5215 
5216 	if (ire != NULL) {
5217 		/*
5218 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5219 		 * appended mblk. Its <upper protocol>'s
5220 		 * job to make sure there is room.
5221 		 */
5222 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5223 			return (0);
5224 
5225 		mp1->b_datap->db_type = IRE_DB_TYPE;
5226 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5227 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5228 		ret_ire = (ire_t *)mp1->b_rptr;
5229 		/*
5230 		 * Pass the latest setting of the ip_path_mtu_discovery and
5231 		 * copy the ulp info if any.
5232 		 */
5233 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5234 		    IPH_DF : 0;
5235 		if (ulp_info != NULL) {
5236 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5237 			    sizeof (iulp_t));
5238 		}
5239 		ret_ire->ire_mp = mp1;
5240 	} else {
5241 		/*
5242 		 * No IRE was found. Remove IRE mblk.
5243 		 */
5244 		mp->b_cont = mp1->b_cont;
5245 		freeb(mp1);
5246 	}
5247 
5248 	return (1);
5249 }
5250 
5251 /*
5252  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5253  * the final piece where we don't.  Return a pointer to the first mblk in the
5254  * result, and update the pointer to the next mblk to chew on.  If anything
5255  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5256  * NULL pointer.
5257  */
5258 mblk_t *
5259 ip_carve_mp(mblk_t **mpp, ssize_t len)
5260 {
5261 	mblk_t	*mp0;
5262 	mblk_t	*mp1;
5263 	mblk_t	*mp2;
5264 
5265 	if (!len || !mpp || !(mp0 = *mpp))
5266 		return (NULL);
5267 	/* If we aren't going to consume the first mblk, we need a dup. */
5268 	if (mp0->b_wptr - mp0->b_rptr > len) {
5269 		mp1 = dupb(mp0);
5270 		if (mp1) {
5271 			/* Partition the data between the two mblks. */
5272 			mp1->b_wptr = mp1->b_rptr + len;
5273 			mp0->b_rptr = mp1->b_wptr;
5274 			/*
5275 			 * after adjustments if mblk not consumed is now
5276 			 * unaligned, try to align it. If this fails free
5277 			 * all messages and let upper layer recover.
5278 			 */
5279 			if (!OK_32PTR(mp0->b_rptr)) {
5280 				if (!pullupmsg(mp0, -1)) {
5281 					freemsg(mp0);
5282 					freemsg(mp1);
5283 					*mpp = NULL;
5284 					return (NULL);
5285 				}
5286 			}
5287 		}
5288 		return (mp1);
5289 	}
5290 	/* Eat through as many mblks as we need to get len bytes. */
5291 	len -= mp0->b_wptr - mp0->b_rptr;
5292 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5293 		if (mp2->b_wptr - mp2->b_rptr > len) {
5294 			/*
5295 			 * We won't consume the entire last mblk.  Like
5296 			 * above, dup and partition it.
5297 			 */
5298 			mp1->b_cont = dupb(mp2);
5299 			mp1 = mp1->b_cont;
5300 			if (!mp1) {
5301 				/*
5302 				 * Trouble.  Rather than go to a lot of
5303 				 * trouble to clean up, we free the messages.
5304 				 * This won't be any worse than losing it on
5305 				 * the wire.
5306 				 */
5307 				freemsg(mp0);
5308 				freemsg(mp2);
5309 				*mpp = NULL;
5310 				return (NULL);
5311 			}
5312 			mp1->b_wptr = mp1->b_rptr + len;
5313 			mp2->b_rptr = mp1->b_wptr;
5314 			/*
5315 			 * after adjustments if mblk not consumed is now
5316 			 * unaligned, try to align it. If this fails free
5317 			 * all messages and let upper layer recover.
5318 			 */
5319 			if (!OK_32PTR(mp2->b_rptr)) {
5320 				if (!pullupmsg(mp2, -1)) {
5321 					freemsg(mp0);
5322 					freemsg(mp2);
5323 					*mpp = NULL;
5324 					return (NULL);
5325 				}
5326 			}
5327 			*mpp = mp2;
5328 			return (mp0);
5329 		}
5330 		/* Decrement len by the amount we just got. */
5331 		len -= mp2->b_wptr - mp2->b_rptr;
5332 	}
5333 	/*
5334 	 * len should be reduced to zero now.  If not our caller has
5335 	 * screwed up.
5336 	 */
5337 	if (len) {
5338 		/* Shouldn't happen! */
5339 		freemsg(mp0);
5340 		*mpp = NULL;
5341 		return (NULL);
5342 	}
5343 	/*
5344 	 * We consumed up to exactly the end of an mblk.  Detach the part
5345 	 * we are returning from the rest of the chain.
5346 	 */
5347 	mp1->b_cont = NULL;
5348 	*mpp = mp2;
5349 	return (mp0);
5350 }
5351 
5352 /* The ill stream is being unplumbed. Called from ip_close */
5353 int
5354 ip_modclose(ill_t *ill)
5355 {
5356 	boolean_t success;
5357 	ipsq_t	*ipsq;
5358 	ipif_t	*ipif;
5359 	queue_t	*q = ill->ill_rq;
5360 	ip_stack_t	*ipst = ill->ill_ipst;
5361 	clock_t timeout;
5362 
5363 	/*
5364 	 * Wait for the ACKs of all deferred control messages to be processed.
5365 	 * In particular, we wait for a potential capability reset initiated
5366 	 * in ip_sioctl_plink() to complete before proceeding.
5367 	 *
5368 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5369 	 * in case the driver never replies.
5370 	 */
5371 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5372 	mutex_enter(&ill->ill_lock);
5373 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5374 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5375 			/* Timeout */
5376 			break;
5377 		}
5378 	}
5379 	mutex_exit(&ill->ill_lock);
5380 
5381 	/*
5382 	 * Forcibly enter the ipsq after some delay. This is to take
5383 	 * care of the case when some ioctl does not complete because
5384 	 * we sent a control message to the driver and it did not
5385 	 * send us a reply. We want to be able to at least unplumb
5386 	 * and replumb rather than force the user to reboot the system.
5387 	 */
5388 	success = ipsq_enter(ill, B_FALSE);
5389 
5390 	/*
5391 	 * Open/close/push/pop is guaranteed to be single threaded
5392 	 * per stream by STREAMS. FS guarantees that all references
5393 	 * from top are gone before close is called. So there can't
5394 	 * be another close thread that has set CONDEMNED on this ill.
5395 	 * and cause ipsq_enter to return failure.
5396 	 */
5397 	ASSERT(success);
5398 	ipsq = ill->ill_phyint->phyint_ipsq;
5399 
5400 	/*
5401 	 * Mark it condemned. No new reference will be made to this ill.
5402 	 * Lookup functions will return an error. Threads that try to
5403 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5404 	 * that the refcnt will drop down to zero.
5405 	 */
5406 	mutex_enter(&ill->ill_lock);
5407 	ill->ill_state_flags |= ILL_CONDEMNED;
5408 	for (ipif = ill->ill_ipif; ipif != NULL;
5409 	    ipif = ipif->ipif_next) {
5410 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5411 	}
5412 	/*
5413 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5414 	 * returns  error if ILL_CONDEMNED is set
5415 	 */
5416 	cv_broadcast(&ill->ill_cv);
5417 	mutex_exit(&ill->ill_lock);
5418 
5419 	/*
5420 	 * Send all the deferred DLPI messages downstream which came in
5421 	 * during the small window right before ipsq_enter(). We do this
5422 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5423 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5424 	 */
5425 	ill_dlpi_send_deferred(ill);
5426 
5427 	/*
5428 	 * Shut down fragmentation reassembly.
5429 	 * ill_frag_timer won't start a timer again.
5430 	 * Now cancel any existing timer
5431 	 */
5432 	(void) untimeout(ill->ill_frag_timer_id);
5433 	(void) ill_frag_timeout(ill, 0);
5434 
5435 	/*
5436 	 * If MOVE was in progress, clear the
5437 	 * move_in_progress fields also.
5438 	 */
5439 	if (ill->ill_move_in_progress) {
5440 		ILL_CLEAR_MOVE(ill);
5441 	}
5442 
5443 	/*
5444 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5445 	 * this ill. Then wait for the refcnts to drop to zero.
5446 	 * ill_is_quiescent checks whether the ill is really quiescent.
5447 	 * Then make sure that threads that are waiting to enter the
5448 	 * ipsq have seen the error returned by ipsq_enter and have
5449 	 * gone away. Then we call ill_delete_tail which does the
5450 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5451 	 */
5452 	ill_delete(ill);
5453 	mutex_enter(&ill->ill_lock);
5454 	while (!ill_is_quiescent(ill))
5455 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5456 	while (ill->ill_waiters)
5457 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5458 
5459 	mutex_exit(&ill->ill_lock);
5460 
5461 	/*
5462 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5463 	 * it held until the end of the function since the cleanup
5464 	 * below needs to be able to use the ip_stack_t.
5465 	 */
5466 	netstack_hold(ipst->ips_netstack);
5467 
5468 	/* qprocsoff is called in ill_delete_tail */
5469 	ill_delete_tail(ill);
5470 	ASSERT(ill->ill_ipst == NULL);
5471 
5472 	/*
5473 	 * Walk through all upper (conn) streams and qenable
5474 	 * those that have queued data.
5475 	 * close synchronization needs this to
5476 	 * be done to ensure that all upper layers blocked
5477 	 * due to flow control to the closing device
5478 	 * get unblocked.
5479 	 */
5480 	ip1dbg(("ip_wsrv: walking\n"));
5481 	conn_walk_drain(ipst);
5482 
5483 	mutex_enter(&ipst->ips_ip_mi_lock);
5484 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5485 	mutex_exit(&ipst->ips_ip_mi_lock);
5486 
5487 	/*
5488 	 * credp could be null if the open didn't succeed and ip_modopen
5489 	 * itself calls ip_close.
5490 	 */
5491 	if (ill->ill_credp != NULL)
5492 		crfree(ill->ill_credp);
5493 
5494 	mutex_enter(&ill->ill_lock);
5495 	ill_nic_info_dispatch(ill);
5496 	mutex_exit(&ill->ill_lock);
5497 
5498 	/*
5499 	 * Now we are done with the module close pieces that
5500 	 * need the netstack_t.
5501 	 */
5502 	netstack_rele(ipst->ips_netstack);
5503 
5504 	mi_close_free((IDP)ill);
5505 	q->q_ptr = WR(q)->q_ptr = NULL;
5506 
5507 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5508 
5509 	return (0);
5510 }
5511 
5512 /*
5513  * This is called as part of close() for both IP and UDP
5514  * in order to quiesce the conn.
5515  */
5516 void
5517 ip_quiesce_conn(conn_t *connp)
5518 {
5519 	boolean_t	drain_cleanup_reqd = B_FALSE;
5520 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5521 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5522 	ip_stack_t	*ipst;
5523 
5524 	ASSERT(!IPCL_IS_TCP(connp));
5525 	ipst = connp->conn_netstack->netstack_ip;
5526 
5527 	/*
5528 	 * Mark the conn as closing, and this conn must not be
5529 	 * inserted in future into any list. Eg. conn_drain_insert(),
5530 	 * won't insert this conn into the conn_drain_list.
5531 	 * Similarly ill_pending_mp_add() will not add any mp to
5532 	 * the pending mp list, after this conn has started closing.
5533 	 *
5534 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5535 	 * cannot get set henceforth.
5536 	 */
5537 	mutex_enter(&connp->conn_lock);
5538 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5539 	connp->conn_state_flags |= CONN_CLOSING;
5540 	if (connp->conn_idl != NULL)
5541 		drain_cleanup_reqd = B_TRUE;
5542 	if (connp->conn_oper_pending_ill != NULL)
5543 		conn_ioctl_cleanup_reqd = B_TRUE;
5544 	if (connp->conn_ilg_inuse != 0)
5545 		ilg_cleanup_reqd = B_TRUE;
5546 	mutex_exit(&connp->conn_lock);
5547 
5548 	if (IPCL_IS_UDP(connp))
5549 		udp_quiesce_conn(connp);
5550 
5551 	if (conn_ioctl_cleanup_reqd)
5552 		conn_ioctl_cleanup(connp);
5553 
5554 	if (is_system_labeled() && connp->conn_anon_port) {
5555 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5556 		    connp->conn_mlp_type, connp->conn_ulp,
5557 		    ntohs(connp->conn_lport), B_FALSE);
5558 		connp->conn_anon_port = 0;
5559 	}
5560 	connp->conn_mlp_type = mlptSingle;
5561 
5562 	/*
5563 	 * Remove this conn from any fanout list it is on.
5564 	 * and then wait for any threads currently operating
5565 	 * on this endpoint to finish
5566 	 */
5567 	ipcl_hash_remove(connp);
5568 
5569 	/*
5570 	 * Remove this conn from the drain list, and do
5571 	 * any other cleanup that may be required.
5572 	 * (Only non-tcp streams may have a non-null conn_idl.
5573 	 * TCP streams are never flow controlled, and
5574 	 * conn_idl will be null)
5575 	 */
5576 	if (drain_cleanup_reqd)
5577 		conn_drain_tail(connp, B_TRUE);
5578 
5579 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5580 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5581 		(void) ip_mrouter_done(NULL, ipst);
5582 
5583 	if (ilg_cleanup_reqd)
5584 		ilg_delete_all(connp);
5585 
5586 	conn_delete_ire(connp, NULL);
5587 
5588 	/*
5589 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5590 	 * callers from write side can't be there now because close
5591 	 * is in progress. The only other caller is ipcl_walk
5592 	 * which checks for the condemned flag.
5593 	 */
5594 	mutex_enter(&connp->conn_lock);
5595 	connp->conn_state_flags |= CONN_CONDEMNED;
5596 	while (connp->conn_ref != 1)
5597 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5598 	connp->conn_state_flags |= CONN_QUIESCED;
5599 	mutex_exit(&connp->conn_lock);
5600 }
5601 
5602 /* ARGSUSED */
5603 int
5604 ip_close(queue_t *q, int flags)
5605 {
5606 	conn_t		*connp;
5607 
5608 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5609 
5610 	/*
5611 	 * Call the appropriate delete routine depending on whether this is
5612 	 * a module or device.
5613 	 */
5614 	if (WR(q)->q_next != NULL) {
5615 		/* This is a module close */
5616 		return (ip_modclose((ill_t *)q->q_ptr));
5617 	}
5618 
5619 	connp = q->q_ptr;
5620 	ip_quiesce_conn(connp);
5621 
5622 	qprocsoff(q);
5623 
5624 	/*
5625 	 * Now we are truly single threaded on this stream, and can
5626 	 * delete the things hanging off the connp, and finally the connp.
5627 	 * We removed this connp from the fanout list, it cannot be
5628 	 * accessed thru the fanouts, and we already waited for the
5629 	 * conn_ref to drop to 0. We are already in close, so
5630 	 * there cannot be any other thread from the top. qprocsoff
5631 	 * has completed, and service has completed or won't run in
5632 	 * future.
5633 	 */
5634 	ASSERT(connp->conn_ref == 1);
5635 
5636 	/*
5637 	 * A conn which was previously marked as IPCL_UDP cannot
5638 	 * retain the flag because it would have been cleared by
5639 	 * udp_close().
5640 	 */
5641 	ASSERT(!IPCL_IS_UDP(connp));
5642 
5643 	if (connp->conn_latch != NULL) {
5644 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5645 		connp->conn_latch = NULL;
5646 	}
5647 	if (connp->conn_policy != NULL) {
5648 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5649 		connp->conn_policy = NULL;
5650 	}
5651 	if (connp->conn_ipsec_opt_mp != NULL) {
5652 		freemsg(connp->conn_ipsec_opt_mp);
5653 		connp->conn_ipsec_opt_mp = NULL;
5654 	}
5655 
5656 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5657 
5658 	connp->conn_ref--;
5659 	ipcl_conn_destroy(connp);
5660 
5661 	q->q_ptr = WR(q)->q_ptr = NULL;
5662 	return (0);
5663 }
5664 
5665 int
5666 ip_snmpmod_close(queue_t *q)
5667 {
5668 	conn_t *connp = Q_TO_CONN(q);
5669 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5670 
5671 	qprocsoff(q);
5672 
5673 	if (connp->conn_flags & IPCL_UDPMOD)
5674 		udp_close_free(connp);
5675 
5676 	if (connp->conn_cred != NULL) {
5677 		crfree(connp->conn_cred);
5678 		connp->conn_cred = NULL;
5679 	}
5680 	CONN_DEC_REF(connp);
5681 	q->q_ptr = WR(q)->q_ptr = NULL;
5682 	return (0);
5683 }
5684 
5685 /*
5686  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5687  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5688  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5689  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5690  * queues as we never enqueue messages there and we don't handle any ioctls.
5691  * Everything else is freed.
5692  */
5693 void
5694 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5695 {
5696 	conn_t	*connp = q->q_ptr;
5697 	pfi_t	setfn;
5698 	pfi_t	getfn;
5699 
5700 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5701 
5702 	switch (DB_TYPE(mp)) {
5703 	case M_PROTO:
5704 	case M_PCPROTO:
5705 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5706 		    ((((union T_primitives *)mp->b_rptr)->type ==
5707 			T_SVR4_OPTMGMT_REQ) ||
5708 		    (((union T_primitives *)mp->b_rptr)->type ==
5709 			T_OPTMGMT_REQ))) {
5710 			/*
5711 			 * This is the only TPI primitive supported. Its
5712 			 * handling does not require tcp_t, but it does require
5713 			 * conn_t to check permissions.
5714 			 */
5715 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5716 
5717 			if (connp->conn_flags & IPCL_TCPMOD) {
5718 				setfn = tcp_snmp_set;
5719 				getfn = tcp_snmp_get;
5720 			} else {
5721 				setfn = udp_snmp_set;
5722 				getfn = udp_snmp_get;
5723 			}
5724 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5725 				freemsg(mp);
5726 				return;
5727 			}
5728 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5729 		    != NULL)
5730 			qreply(q, mp);
5731 		break;
5732 	case M_FLUSH:
5733 	case M_IOCTL:
5734 		putnext(q, mp);
5735 		break;
5736 	default:
5737 		freemsg(mp);
5738 		break;
5739 	}
5740 }
5741 
5742 /* Return the IP checksum for the IP header at "iph". */
5743 uint16_t
5744 ip_csum_hdr(ipha_t *ipha)
5745 {
5746 	uint16_t	*uph;
5747 	uint32_t	sum;
5748 	int		opt_len;
5749 
5750 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5751 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5752 	uph = (uint16_t *)ipha;
5753 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5754 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5755 	if (opt_len > 0) {
5756 		do {
5757 			sum += uph[10];
5758 			sum += uph[11];
5759 			uph += 2;
5760 		} while (--opt_len);
5761 	}
5762 	sum = (sum & 0xFFFF) + (sum >> 16);
5763 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5764 	if (sum == 0xffff)
5765 		sum = 0;
5766 	return ((uint16_t)sum);
5767 }
5768 
5769 /*
5770  * Called when the module is about to be unloaded
5771  */
5772 void
5773 ip_ddi_destroy(void)
5774 {
5775 	tnet_fini();
5776 
5777 	sctp_ddi_g_destroy();
5778 	tcp_ddi_g_destroy();
5779 	ipsec_policy_g_destroy();
5780 	ipcl_g_destroy();
5781 	ip_net_g_destroy();
5782 	ip_ire_g_fini();
5783 	inet_minor_destroy(ip_minor_arena);
5784 
5785 	netstack_unregister(NS_IP);
5786 }
5787 
5788 /*
5789  * First step in cleanup.
5790  */
5791 /* ARGSUSED */
5792 static void
5793 ip_stack_shutdown(netstackid_t stackid, void *arg)
5794 {
5795 	ip_stack_t *ipst = (ip_stack_t *)arg;
5796 
5797 #ifdef NS_DEBUG
5798 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5799 #endif
5800 
5801 	/* Get rid of loopback interfaces and their IREs */
5802 	ip_loopback_cleanup(ipst);
5803 }
5804 
5805 /*
5806  * Free the IP stack instance.
5807  */
5808 static void
5809 ip_stack_fini(netstackid_t stackid, void *arg)
5810 {
5811 	ip_stack_t *ipst = (ip_stack_t *)arg;
5812 	int ret;
5813 
5814 #ifdef NS_DEBUG
5815 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5816 #endif
5817 	ipv4_hook_destroy(ipst);
5818 	ipv6_hook_destroy(ipst);
5819 	ip_net_destroy(ipst);
5820 
5821 	rw_destroy(&ipst->ips_srcid_lock);
5822 
5823 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5824 	ipst->ips_ip_mibkp = NULL;
5825 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5826 	ipst->ips_icmp_mibkp = NULL;
5827 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5828 	ipst->ips_ip_kstat = NULL;
5829 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5830 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5831 	ipst->ips_ip6_kstat = NULL;
5832 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5833 
5834 	nd_free(&ipst->ips_ip_g_nd);
5835 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5836 	ipst->ips_param_arr = NULL;
5837 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5838 	ipst->ips_ndp_arr = NULL;
5839 
5840 	ip_mrouter_stack_destroy(ipst);
5841 
5842 	mutex_destroy(&ipst->ips_ip_mi_lock);
5843 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5844 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5845 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5846 
5847 	ret = untimeout(ipst->ips_igmp_timeout_id);
5848 	if (ret == -1) {
5849 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5850 	} else {
5851 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5852 		ipst->ips_igmp_timeout_id = 0;
5853 	}
5854 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5855 	if (ret == -1) {
5856 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5857 	} else {
5858 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5859 		ipst->ips_igmp_slowtimeout_id = 0;
5860 	}
5861 	ret = untimeout(ipst->ips_mld_timeout_id);
5862 	if (ret == -1) {
5863 		ASSERT(ipst->ips_mld_timeout_id == 0);
5864 	} else {
5865 		ASSERT(ipst->ips_mld_timeout_id != 0);
5866 		ipst->ips_mld_timeout_id = 0;
5867 	}
5868 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5869 	if (ret == -1) {
5870 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5871 	} else {
5872 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5873 		ipst->ips_mld_slowtimeout_id = 0;
5874 	}
5875 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5876 	if (ret == -1) {
5877 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5878 	} else {
5879 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5880 		ipst->ips_ip_ire_expire_id = 0;
5881 	}
5882 
5883 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5884 	mutex_destroy(&ipst->ips_mld_timer_lock);
5885 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5886 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5887 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5888 	rw_destroy(&ipst->ips_ill_g_lock);
5889 
5890 	ip_ire_fini(ipst);
5891 	ip6_asp_free(ipst);
5892 	conn_drain_fini(ipst);
5893 	ipcl_destroy(ipst);
5894 
5895 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5896 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5897 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5898 	ipst->ips_ndp4 = NULL;
5899 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5900 	ipst->ips_ndp6 = NULL;
5901 
5902 	if (ipst->ips_loopback_ksp != NULL) {
5903 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5904 		ipst->ips_loopback_ksp = NULL;
5905 	}
5906 
5907 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5908 	ipst->ips_phyint_g_list = NULL;
5909 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5910 	ipst->ips_ill_g_heads = NULL;
5911 
5912 	kmem_free(ipst, sizeof (*ipst));
5913 }
5914 
5915 /*
5916  * Called when the IP kernel module is loaded into the kernel
5917  */
5918 void
5919 ip_ddi_init(void)
5920 {
5921 	TCP6_MAJ = ddi_name_to_major(TCP6);
5922 	TCP_MAJ	= ddi_name_to_major(TCP);
5923 	SCTP_MAJ = ddi_name_to_major(SCTP);
5924 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5925 
5926 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5927 
5928 	/*
5929 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5930 	 * initial devices: ip, ip6, tcp, tcp6.
5931 	 */
5932 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5933 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5934 		cmn_err(CE_PANIC,
5935 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5936 	}
5937 
5938 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5939 
5940 	ipcl_g_init();
5941 	ip_ire_g_init();
5942 	ip_net_g_init();
5943 
5944 #ifdef ILL_DEBUG
5945 	/* Default cleanup function */
5946 	ip_cleanup_func = ip_thread_exit;
5947 #endif
5948 
5949 	/*
5950 	 * We want to be informed each time a stack is created or
5951 	 * destroyed in the kernel, so we can maintain the
5952 	 * set of udp_stack_t's.
5953 	 */
5954 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5955 	    ip_stack_fini);
5956 
5957 	ipsec_policy_g_init();
5958 	tcp_ddi_g_init();
5959 	sctp_ddi_g_init();
5960 
5961 	tnet_init();
5962 }
5963 
5964 /*
5965  * Initialize the IP stack instance.
5966  */
5967 static void *
5968 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5969 {
5970 	ip_stack_t	*ipst;
5971 	ipparam_t	*pa;
5972 	ipndp_t		*na;
5973 
5974 #ifdef NS_DEBUG
5975 	printf("ip_stack_init(stack %d)\n", stackid);
5976 #endif
5977 
5978 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5979 	ipst->ips_netstack = ns;
5980 
5981 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5982 	    KM_SLEEP);
5983 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5984 	    KM_SLEEP);
5985 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5986 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5987 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5988 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5989 
5990 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5991 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5992 	ipst->ips_igmp_deferred_next = INFINITY;
5993 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5994 	ipst->ips_mld_deferred_next = INFINITY;
5995 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5996 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5997 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5998 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5999 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6000 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6001 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6002 
6003 	ipcl_init(ipst);
6004 	ip_ire_init(ipst);
6005 	ip6_asp_init(ipst);
6006 	ipif_init(ipst);
6007 	conn_drain_init(ipst);
6008 	ip_mrouter_stack_init(ipst);
6009 
6010 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6011 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6012 
6013 	ipst->ips_ip_multirt_log_interval = 1000;
6014 
6015 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6016 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6017 	ipst->ips_ill_index = 1;
6018 
6019 	ipst->ips_saved_ip_g_forward = -1;
6020 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6021 
6022 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6023 	ipst->ips_param_arr = pa;
6024 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6025 
6026 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6027 	ipst->ips_ndp_arr = na;
6028 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6029 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6030 	    (caddr_t)&ipst->ips_ip_g_forward;
6031 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6032 	    (caddr_t)&ipst->ips_ipv6_forward;
6033 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6034 		"ip_cgtp_filter") == 0);
6035 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6036 	    (caddr_t)&ip_cgtp_filter;
6037 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6038 		"ipmp_hook_emulation") == 0);
6039 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6040 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6041 
6042 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6043 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6044 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6045 
6046 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6047 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6048 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6049 	ipst->ips_ip6_kstat =
6050 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6051 
6052 	ipst->ips_ipmp_enable_failback = B_TRUE;
6053 
6054 	ipst->ips_ip_src_id = 1;
6055 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6056 
6057 	ip_net_init(ipst, ns);
6058 	ipv4_hook_init(ipst);
6059 	ipv6_hook_init(ipst);
6060 
6061 	return (ipst);
6062 }
6063 
6064 /*
6065  * Allocate and initialize a DLPI template of the specified length.  (May be
6066  * called as writer.)
6067  */
6068 mblk_t *
6069 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6070 {
6071 	mblk_t	*mp;
6072 
6073 	mp = allocb(len, BPRI_MED);
6074 	if (!mp)
6075 		return (NULL);
6076 
6077 	/*
6078 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6079 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6080 	 * that other DLPI are M_PROTO.
6081 	 */
6082 	if (prim == DL_INFO_REQ) {
6083 		mp->b_datap->db_type = M_PCPROTO;
6084 	} else {
6085 		mp->b_datap->db_type = M_PROTO;
6086 	}
6087 
6088 	mp->b_wptr = mp->b_rptr + len;
6089 	bzero(mp->b_rptr, len);
6090 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6091 	return (mp);
6092 }
6093 
6094 const char *
6095 dlpi_prim_str(int prim)
6096 {
6097 	switch (prim) {
6098 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6099 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6100 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6101 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6102 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6103 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6104 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6105 	case DL_OK_ACK:		return ("DL_OK_ACK");
6106 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6107 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6108 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6109 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6110 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6111 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6112 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6113 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6114 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6115 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6116 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6117 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6118 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6119 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6120 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6121 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6122 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6123 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6124 	default:		return ("<unknown primitive>");
6125 	}
6126 }
6127 
6128 const char *
6129 dlpi_err_str(int err)
6130 {
6131 	switch (err) {
6132 	case DL_ACCESS:		return ("DL_ACCESS");
6133 	case DL_BADADDR:	return ("DL_BADADDR");
6134 	case DL_BADCORR:	return ("DL_BADCORR");
6135 	case DL_BADDATA:	return ("DL_BADDATA");
6136 	case DL_BADPPA:		return ("DL_BADPPA");
6137 	case DL_BADPRIM:	return ("DL_BADPRIM");
6138 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6139 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6140 	case DL_BADSAP:		return ("DL_BADSAP");
6141 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6142 	case DL_BOUND:		return ("DL_BOUND");
6143 	case DL_INITFAILED:	return ("DL_INITFAILED");
6144 	case DL_NOADDR:		return ("DL_NOADDR");
6145 	case DL_NOTINIT:	return ("DL_NOTINIT");
6146 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6147 	case DL_SYSERR:		return ("DL_SYSERR");
6148 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6149 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6150 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6151 	case DL_TOOMANY:	return ("DL_TOOMANY");
6152 	case DL_NOTENAB:	return ("DL_NOTENAB");
6153 	case DL_BUSY:		return ("DL_BUSY");
6154 	case DL_NOAUTO:		return ("DL_NOAUTO");
6155 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6156 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6157 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6158 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6159 	case DL_PENDING:	return ("DL_PENDING");
6160 	default:		return ("<unknown error>");
6161 	}
6162 }
6163 
6164 /*
6165  * Debug formatting routine.  Returns a character string representation of the
6166  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6167  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6168  *
6169  * Once the ndd table-printing interfaces are removed, this can be changed to
6170  * standard dotted-decimal form.
6171  */
6172 char *
6173 ip_dot_addr(ipaddr_t addr, char *buf)
6174 {
6175 	uint8_t *ap = (uint8_t *)&addr;
6176 
6177 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6178 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6179 	return (buf);
6180 }
6181 
6182 /*
6183  * Write the given MAC address as a printable string in the usual colon-
6184  * separated format.
6185  */
6186 const char *
6187 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6188 {
6189 	char *bp;
6190 
6191 	if (alen == 0 || buflen < 4)
6192 		return ("?");
6193 	bp = buf;
6194 	for (;;) {
6195 		/*
6196 		 * If there are more MAC address bytes available, but we won't
6197 		 * have any room to print them, then add "..." to the string
6198 		 * instead.  See below for the 'magic number' explanation.
6199 		 */
6200 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6201 			(void) strcpy(bp, "...");
6202 			break;
6203 		}
6204 		(void) sprintf(bp, "%02x", *addr++);
6205 		bp += 2;
6206 		if (--alen == 0)
6207 			break;
6208 		*bp++ = ':';
6209 		buflen -= 3;
6210 		/*
6211 		 * At this point, based on the first 'if' statement above,
6212 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6213 		 * buflen >= 4.  The first case leaves room for the final "xx"
6214 		 * number and trailing NUL byte.  The second leaves room for at
6215 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6216 		 * that statement.
6217 		 */
6218 	}
6219 	return (buf);
6220 }
6221 
6222 /*
6223  * Send an ICMP error after patching up the packet appropriately.  Returns
6224  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6225  */
6226 static boolean_t
6227 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6228     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6229     zoneid_t zoneid, ip_stack_t *ipst)
6230 {
6231 	ipha_t *ipha;
6232 	mblk_t *first_mp;
6233 	boolean_t secure;
6234 	unsigned char db_type;
6235 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6236 
6237 	first_mp = mp;
6238 	if (mctl_present) {
6239 		mp = mp->b_cont;
6240 		secure = ipsec_in_is_secure(first_mp);
6241 		ASSERT(mp != NULL);
6242 	} else {
6243 		/*
6244 		 * If this is an ICMP error being reported - which goes
6245 		 * up as M_CTLs, we need to convert them to M_DATA till
6246 		 * we finish checking with global policy because
6247 		 * ipsec_check_global_policy() assumes M_DATA as clear
6248 		 * and M_CTL as secure.
6249 		 */
6250 		db_type = DB_TYPE(mp);
6251 		DB_TYPE(mp) = M_DATA;
6252 		secure = B_FALSE;
6253 	}
6254 	/*
6255 	 * We are generating an icmp error for some inbound packet.
6256 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6257 	 * Before we generate an error, check with global policy
6258 	 * to see whether this is allowed to enter the system. As
6259 	 * there is no "conn", we are checking with global policy.
6260 	 */
6261 	ipha = (ipha_t *)mp->b_rptr;
6262 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6263 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6264 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6265 		if (first_mp == NULL)
6266 			return (B_FALSE);
6267 	}
6268 
6269 	if (!mctl_present)
6270 		DB_TYPE(mp) = db_type;
6271 
6272 	if (flags & IP_FF_SEND_ICMP) {
6273 		if (flags & IP_FF_HDR_COMPLETE) {
6274 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6275 				freemsg(first_mp);
6276 				return (B_TRUE);
6277 			}
6278 		}
6279 		if (flags & IP_FF_CKSUM) {
6280 			/*
6281 			 * Have to correct checksum since
6282 			 * the packet might have been
6283 			 * fragmented and the reassembly code in ip_rput
6284 			 * does not restore the IP checksum.
6285 			 */
6286 			ipha->ipha_hdr_checksum = 0;
6287 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6288 		}
6289 		switch (icmp_type) {
6290 		case ICMP_DEST_UNREACHABLE:
6291 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6292 			    ipst);
6293 			break;
6294 		default:
6295 			freemsg(first_mp);
6296 			break;
6297 		}
6298 	} else {
6299 		freemsg(first_mp);
6300 		return (B_FALSE);
6301 	}
6302 
6303 	return (B_TRUE);
6304 }
6305 
6306 /*
6307  * Used to send an ICMP error message when a packet is received for
6308  * a protocol that is not supported. The mblk passed as argument
6309  * is consumed by this function.
6310  */
6311 void
6312 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6313     ip_stack_t *ipst)
6314 {
6315 	mblk_t *mp;
6316 	ipha_t *ipha;
6317 	ill_t *ill;
6318 	ipsec_in_t *ii;
6319 
6320 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6321 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6322 
6323 	mp = ipsec_mp->b_cont;
6324 	ipsec_mp->b_cont = NULL;
6325 	ipha = (ipha_t *)mp->b_rptr;
6326 	/* Get ill from index in ipsec_in_t. */
6327 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6328 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6329 	    ipst);
6330 	if (ill != NULL) {
6331 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6332 			if (ip_fanout_send_icmp(q, mp, flags,
6333 			    ICMP_DEST_UNREACHABLE,
6334 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6335 				BUMP_MIB(ill->ill_ip_mib,
6336 				    ipIfStatsInUnknownProtos);
6337 			}
6338 		} else {
6339 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6340 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6341 			    0, B_FALSE, zoneid, ipst)) {
6342 				BUMP_MIB(ill->ill_ip_mib,
6343 				    ipIfStatsInUnknownProtos);
6344 			}
6345 		}
6346 		ill_refrele(ill);
6347 	} else { /* re-link for the freemsg() below. */
6348 		ipsec_mp->b_cont = mp;
6349 	}
6350 
6351 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6352 	freemsg(ipsec_mp);
6353 }
6354 
6355 /*
6356  * See if the inbound datagram has had IPsec processing applied to it.
6357  */
6358 boolean_t
6359 ipsec_in_is_secure(mblk_t *ipsec_mp)
6360 {
6361 	ipsec_in_t *ii;
6362 
6363 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6364 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6365 
6366 	if (ii->ipsec_in_loopback) {
6367 		return (ii->ipsec_in_secure);
6368 	} else {
6369 		return (ii->ipsec_in_ah_sa != NULL ||
6370 		    ii->ipsec_in_esp_sa != NULL ||
6371 		    ii->ipsec_in_decaps);
6372 	}
6373 }
6374 
6375 /*
6376  * Handle protocols with which IP is less intimate.  There
6377  * can be more than one stream bound to a particular
6378  * protocol.  When this is the case, normally each one gets a copy
6379  * of any incoming packets.
6380  *
6381  * IPSEC NOTE :
6382  *
6383  * Don't allow a secure packet going up a non-secure connection.
6384  * We don't allow this because
6385  *
6386  * 1) Reply might go out in clear which will be dropped at
6387  *    the sending side.
6388  * 2) If the reply goes out in clear it will give the
6389  *    adversary enough information for getting the key in
6390  *    most of the cases.
6391  *
6392  * Moreover getting a secure packet when we expect clear
6393  * implies that SA's were added without checking for
6394  * policy on both ends. This should not happen once ISAKMP
6395  * is used to negotiate SAs as SAs will be added only after
6396  * verifying the policy.
6397  *
6398  * NOTE : If the packet was tunneled and not multicast we only send
6399  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6400  * back to delivering packets to AF_INET6 raw sockets.
6401  *
6402  * IPQoS Notes:
6403  * Once we have determined the client, invoke IPPF processing.
6404  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6405  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6406  * ip_policy will be false.
6407  *
6408  * Zones notes:
6409  * Currently only applications in the global zone can create raw sockets for
6410  * protocols other than ICMP. So unlike the broadcast / multicast case of
6411  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6412  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6413  */
6414 static void
6415 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6416     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6417     zoneid_t zoneid)
6418 {
6419 	queue_t	*rq;
6420 	mblk_t	*mp1, *first_mp1;
6421 	uint_t	protocol = ipha->ipha_protocol;
6422 	ipaddr_t dst;
6423 	boolean_t one_only;
6424 	mblk_t *first_mp = mp;
6425 	boolean_t secure;
6426 	uint32_t ill_index;
6427 	conn_t	*connp, *first_connp, *next_connp;
6428 	connf_t	*connfp;
6429 	boolean_t shared_addr;
6430 	mib2_ipIfStatsEntry_t *mibptr;
6431 	ip_stack_t *ipst = recv_ill->ill_ipst;
6432 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6433 
6434 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6435 	if (mctl_present) {
6436 		mp = first_mp->b_cont;
6437 		secure = ipsec_in_is_secure(first_mp);
6438 		ASSERT(mp != NULL);
6439 	} else {
6440 		secure = B_FALSE;
6441 	}
6442 	dst = ipha->ipha_dst;
6443 	/*
6444 	 * If the packet was tunneled and not multicast we only send to it
6445 	 * the first match.
6446 	 */
6447 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6448 	    !CLASSD(dst));
6449 
6450 	shared_addr = (zoneid == ALL_ZONES);
6451 	if (shared_addr) {
6452 		/*
6453 		 * We don't allow multilevel ports for raw IP, so no need to
6454 		 * check for that here.
6455 		 */
6456 		zoneid = tsol_packet_to_zoneid(mp);
6457 	}
6458 
6459 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6460 	mutex_enter(&connfp->connf_lock);
6461 	connp = connfp->connf_head;
6462 	for (connp = connfp->connf_head; connp != NULL;
6463 		connp = connp->conn_next) {
6464 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6465 		    zoneid) &&
6466 		    (!is_system_labeled() ||
6467 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6468 		    connp)))
6469 			break;
6470 	}
6471 
6472 	if (connp == NULL || connp->conn_upq == NULL) {
6473 		/*
6474 		 * No one bound to these addresses.  Is
6475 		 * there a client that wants all
6476 		 * unclaimed datagrams?
6477 		 */
6478 		mutex_exit(&connfp->connf_lock);
6479 		/*
6480 		 * Check for IPPROTO_ENCAP...
6481 		 */
6482 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6483 			/*
6484 			 * If an IPsec mblk is here on a multicast
6485 			 * tunnel (using ip_mroute stuff), check policy here,
6486 			 * THEN ship off to ip_mroute_decap().
6487 			 *
6488 			 * BTW,  If I match a configured IP-in-IP
6489 			 * tunnel, this path will not be reached, and
6490 			 * ip_mroute_decap will never be called.
6491 			 */
6492 			first_mp = ipsec_check_global_policy(first_mp, connp,
6493 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6494 			if (first_mp != NULL) {
6495 				if (mctl_present)
6496 					freeb(first_mp);
6497 				ip_mroute_decap(q, mp, ill);
6498 			} /* Else we already freed everything! */
6499 		} else {
6500 			/*
6501 			 * Otherwise send an ICMP protocol unreachable.
6502 			 */
6503 			if (ip_fanout_send_icmp(q, first_mp, flags,
6504 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6505 			    mctl_present, zoneid, ipst)) {
6506 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6507 			}
6508 		}
6509 		return;
6510 	}
6511 	CONN_INC_REF(connp);
6512 	first_connp = connp;
6513 
6514 	/*
6515 	 * Only send message to one tunnel driver by immediately
6516 	 * terminating the loop.
6517 	 */
6518 	connp = one_only ? NULL : connp->conn_next;
6519 
6520 	for (;;) {
6521 		while (connp != NULL) {
6522 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6523 			    flags, zoneid) &&
6524 			    (!is_system_labeled() ||
6525 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6526 			    shared_addr, connp)))
6527 				break;
6528 			connp = connp->conn_next;
6529 		}
6530 
6531 		/*
6532 		 * Copy the packet.
6533 		 */
6534 		if (connp == NULL || connp->conn_upq == NULL ||
6535 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6536 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6537 			/*
6538 			 * No more interested clients or memory
6539 			 * allocation failed
6540 			 */
6541 			connp = first_connp;
6542 			break;
6543 		}
6544 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6545 		CONN_INC_REF(connp);
6546 		mutex_exit(&connfp->connf_lock);
6547 		rq = connp->conn_rq;
6548 		if (!canputnext(rq)) {
6549 			if (flags & IP_FF_RAWIP) {
6550 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6551 			} else {
6552 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6553 			}
6554 
6555 			freemsg(first_mp1);
6556 		} else {
6557 			/*
6558 			 * Don't enforce here if we're an actual tunnel -
6559 			 * let "tun" do it instead.
6560 			 */
6561 			if (!IPCL_IS_IPTUN(connp) &&
6562 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6563 			    secure)) {
6564 				first_mp1 = ipsec_check_inbound_policy
6565 				    (first_mp1, connp, ipha, NULL,
6566 				    mctl_present);
6567 			}
6568 			if (first_mp1 != NULL) {
6569 				int in_flags = 0;
6570 				/*
6571 				 * ip_fanout_proto also gets called from
6572 				 * icmp_inbound_error_fanout, in which case
6573 				 * the msg type is M_CTL.  Don't add info
6574 				 * in this case for the time being. In future
6575 				 * when there is a need for knowing the
6576 				 * inbound iface index for ICMP error msgs,
6577 				 * then this can be changed.
6578 				 */
6579 				if (connp->conn_recvif)
6580 					in_flags = IPF_RECVIF;
6581 				/*
6582 				 * The ULP may support IP_RECVPKTINFO for both
6583 				 * IP v4 and v6 so pass the appropriate argument
6584 				 * based on conn IP version.
6585 				 */
6586 				if (connp->conn_ip_recvpktinfo) {
6587 					if (connp->conn_af_isv6) {
6588 						/*
6589 						 * V6 only needs index
6590 						 */
6591 						in_flags |= IPF_RECVIF;
6592 					} else {
6593 						/*
6594 						 * V4 needs index +
6595 						 * matching address.
6596 						 */
6597 						in_flags |= IPF_RECVADDR;
6598 					}
6599 				}
6600 				if ((in_flags != 0) &&
6601 				    (mp->b_datap->db_type != M_CTL)) {
6602 					/*
6603 					 * the actual data will be
6604 					 * contained in b_cont upon
6605 					 * successful return of the
6606 					 * following call else
6607 					 * original mblk is returned
6608 					 */
6609 					ASSERT(recv_ill != NULL);
6610 					mp1 = ip_add_info(mp1, recv_ill,
6611 					    in_flags, IPCL_ZONEID(connp), ipst);
6612 				}
6613 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6614 				if (mctl_present)
6615 					freeb(first_mp1);
6616 				putnext(rq, mp1);
6617 			}
6618 		}
6619 		mutex_enter(&connfp->connf_lock);
6620 		/* Follow the next pointer before releasing the conn. */
6621 		next_connp = connp->conn_next;
6622 		CONN_DEC_REF(connp);
6623 		connp = next_connp;
6624 	}
6625 
6626 	/* Last one.  Send it upstream. */
6627 	mutex_exit(&connfp->connf_lock);
6628 
6629 	/*
6630 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6631 	 * will be set to false.
6632 	 */
6633 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6634 		ill_index = ill->ill_phyint->phyint_ifindex;
6635 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6636 		if (mp == NULL) {
6637 			CONN_DEC_REF(connp);
6638 			if (mctl_present) {
6639 				freeb(first_mp);
6640 			}
6641 			return;
6642 		}
6643 	}
6644 
6645 	rq = connp->conn_rq;
6646 	if (!canputnext(rq)) {
6647 		if (flags & IP_FF_RAWIP) {
6648 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6649 		} else {
6650 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6651 		}
6652 
6653 		freemsg(first_mp);
6654 	} else {
6655 		if (IPCL_IS_IPTUN(connp)) {
6656 			/*
6657 			 * Tunneled packet.  We enforce policy in the tunnel
6658 			 * module itself.
6659 			 *
6660 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6661 			 * a policy check.
6662 			 */
6663 			putnext(rq, first_mp);
6664 			CONN_DEC_REF(connp);
6665 			return;
6666 		}
6667 
6668 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6669 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6670 			    ipha, NULL, mctl_present);
6671 		}
6672 
6673 		if (first_mp != NULL) {
6674 			int in_flags = 0;
6675 
6676 			/*
6677 			 * ip_fanout_proto also gets called
6678 			 * from icmp_inbound_error_fanout, in
6679 			 * which case the msg type is M_CTL.
6680 			 * Don't add info in this case for time
6681 			 * being. In future when there is a
6682 			 * need for knowing the inbound iface
6683 			 * index for ICMP error msgs, then this
6684 			 * can be changed
6685 			 */
6686 			if (connp->conn_recvif)
6687 				in_flags = IPF_RECVIF;
6688 			if (connp->conn_ip_recvpktinfo) {
6689 				if (connp->conn_af_isv6) {
6690 					/*
6691 					 * V6 only needs index
6692 					 */
6693 					in_flags |= IPF_RECVIF;
6694 				} else {
6695 					/*
6696 					 * V4 needs index +
6697 					 * matching address.
6698 					 */
6699 					in_flags |= IPF_RECVADDR;
6700 				}
6701 			}
6702 			if ((in_flags != 0) &&
6703 			    (mp->b_datap->db_type != M_CTL)) {
6704 
6705 				/*
6706 				 * the actual data will be contained in
6707 				 * b_cont upon successful return
6708 				 * of the following call else original
6709 				 * mblk is returned
6710 				 */
6711 				ASSERT(recv_ill != NULL);
6712 				mp = ip_add_info(mp, recv_ill,
6713 				    in_flags, IPCL_ZONEID(connp), ipst);
6714 			}
6715 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6716 			putnext(rq, mp);
6717 			if (mctl_present)
6718 				freeb(first_mp);
6719 		}
6720 	}
6721 	CONN_DEC_REF(connp);
6722 }
6723 
6724 /*
6725  * Fanout for TCP packets
6726  * The caller puts <fport, lport> in the ports parameter.
6727  *
6728  * IPQoS Notes
6729  * Before sending it to the client, invoke IPPF processing.
6730  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6731  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6732  * ip_policy is false.
6733  */
6734 static void
6735 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6736     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6737 {
6738 	mblk_t  *first_mp;
6739 	boolean_t secure;
6740 	uint32_t ill_index;
6741 	int	ip_hdr_len;
6742 	tcph_t	*tcph;
6743 	boolean_t syn_present = B_FALSE;
6744 	conn_t	*connp;
6745 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6746 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6747 
6748 	ASSERT(recv_ill != NULL);
6749 
6750 	first_mp = mp;
6751 	if (mctl_present) {
6752 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6753 		mp = first_mp->b_cont;
6754 		secure = ipsec_in_is_secure(first_mp);
6755 		ASSERT(mp != NULL);
6756 	} else {
6757 		secure = B_FALSE;
6758 	}
6759 
6760 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6761 
6762 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6763 		    zoneid, ipst)) == NULL) {
6764 		/*
6765 		 * No connected connection or listener. Send a
6766 		 * TH_RST via tcp_xmit_listeners_reset.
6767 		 */
6768 
6769 		/* Initiate IPPf processing, if needed. */
6770 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6771 			uint32_t ill_index;
6772 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6773 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6774 			if (first_mp == NULL)
6775 				return;
6776 		}
6777 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6778 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6779 		    zoneid));
6780 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6781 		    ipst->ips_netstack->netstack_tcp);
6782 		return;
6783 	}
6784 
6785 	/*
6786 	 * Allocate the SYN for the TCP connection here itself
6787 	 */
6788 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6789 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6790 		if (IPCL_IS_TCP(connp)) {
6791 			squeue_t *sqp;
6792 
6793 			/*
6794 			 * For fused tcp loopback, assign the eager's
6795 			 * squeue to be that of the active connect's.
6796 			 * Note that we don't check for IP_FF_LOOPBACK
6797 			 * here since this routine gets called only
6798 			 * for loopback (unlike the IPv6 counterpart).
6799 			 */
6800 			ASSERT(Q_TO_CONN(q) != NULL);
6801 			if (do_tcp_fusion &&
6802 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6803 			    !secure &&
6804 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6805 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6806 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6807 				sqp = Q_TO_CONN(q)->conn_sqp;
6808 			} else {
6809 				sqp = IP_SQUEUE_GET(lbolt);
6810 			}
6811 
6812 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6813 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6814 			syn_present = B_TRUE;
6815 		}
6816 	}
6817 
6818 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6819 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6820 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6821 		if ((flags & TH_RST) || (flags & TH_URG)) {
6822 			CONN_DEC_REF(connp);
6823 			freemsg(first_mp);
6824 			return;
6825 		}
6826 		if (flags & TH_ACK) {
6827 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6828 			    ipst->ips_netstack->netstack_tcp);
6829 			CONN_DEC_REF(connp);
6830 			return;
6831 		}
6832 
6833 		CONN_DEC_REF(connp);
6834 		freemsg(first_mp);
6835 		return;
6836 	}
6837 
6838 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6839 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6840 		    NULL, mctl_present);
6841 		if (first_mp == NULL) {
6842 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6843 			CONN_DEC_REF(connp);
6844 			return;
6845 		}
6846 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6847 			ASSERT(syn_present);
6848 			if (mctl_present) {
6849 				ASSERT(first_mp != mp);
6850 				first_mp->b_datap->db_struioflag |=
6851 				    STRUIO_POLICY;
6852 			} else {
6853 				ASSERT(first_mp == mp);
6854 				mp->b_datap->db_struioflag &=
6855 				    ~STRUIO_EAGER;
6856 				mp->b_datap->db_struioflag |=
6857 				    STRUIO_POLICY;
6858 			}
6859 		} else {
6860 			/*
6861 			 * Discard first_mp early since we're dealing with a
6862 			 * fully-connected conn_t and tcp doesn't do policy in
6863 			 * this case.
6864 			 */
6865 			if (mctl_present) {
6866 				freeb(first_mp);
6867 				mctl_present = B_FALSE;
6868 			}
6869 			first_mp = mp;
6870 		}
6871 	}
6872 
6873 	/*
6874 	 * Initiate policy processing here if needed. If we get here from
6875 	 * icmp_inbound_error_fanout, ip_policy is false.
6876 	 */
6877 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6878 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6879 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6880 		if (mp == NULL) {
6881 			CONN_DEC_REF(connp);
6882 			if (mctl_present)
6883 				freeb(first_mp);
6884 			return;
6885 		} else if (mctl_present) {
6886 			ASSERT(first_mp != mp);
6887 			first_mp->b_cont = mp;
6888 		} else {
6889 			first_mp = mp;
6890 		}
6891 	}
6892 
6893 
6894 
6895 	/* Handle socket options. */
6896 	if (!syn_present &&
6897 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6898 		/* Add header */
6899 		ASSERT(recv_ill != NULL);
6900 		/*
6901 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6902 		 * IPF_RECVIF.
6903 		 */
6904 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6905 		    ipst);
6906 		if (mp == NULL) {
6907 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6908 			CONN_DEC_REF(connp);
6909 			if (mctl_present)
6910 				freeb(first_mp);
6911 			return;
6912 		} else if (mctl_present) {
6913 			/*
6914 			 * ip_add_info might return a new mp.
6915 			 */
6916 			ASSERT(first_mp != mp);
6917 			first_mp->b_cont = mp;
6918 		} else {
6919 			first_mp = mp;
6920 		}
6921 	}
6922 
6923 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6924 	if (IPCL_IS_TCP(connp)) {
6925 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6926 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6927 	} else {
6928 		putnext(connp->conn_rq, first_mp);
6929 		CONN_DEC_REF(connp);
6930 	}
6931 }
6932 
6933 /*
6934  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6935  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6936  * Caller is responsible for dropping references to the conn, and freeing
6937  * first_mp.
6938  *
6939  * IPQoS Notes
6940  * Before sending it to the client, invoke IPPF processing. Policy processing
6941  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6942  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6943  * ip_wput_local, ip_policy is false.
6944  */
6945 static void
6946 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6947     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6948     boolean_t ip_policy)
6949 {
6950 	boolean_t	mctl_present = (first_mp != NULL);
6951 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6952 	uint32_t	ill_index;
6953 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6954 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6955 
6956 	ASSERT(ill != NULL);
6957 
6958 	if (mctl_present)
6959 		first_mp->b_cont = mp;
6960 	else
6961 		first_mp = mp;
6962 
6963 	if (CONN_UDP_FLOWCTLD(connp)) {
6964 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6965 		freemsg(first_mp);
6966 		return;
6967 	}
6968 
6969 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6970 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6971 		    NULL, mctl_present);
6972 		if (first_mp == NULL) {
6973 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6974 			return;	/* Freed by ipsec_check_inbound_policy(). */
6975 		}
6976 	}
6977 	if (mctl_present)
6978 		freeb(first_mp);
6979 
6980 	/* Handle options. */
6981 	if (connp->conn_recvif)
6982 		in_flags = IPF_RECVIF;
6983 	/*
6984 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6985 	 * passed to ip_add_info is based on IP version of connp.
6986 	 */
6987 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6988 		if (connp->conn_af_isv6) {
6989 			/*
6990 			 * V6 only needs index
6991 			 */
6992 			in_flags |= IPF_RECVIF;
6993 		} else {
6994 			/*
6995 			 * V4 needs index + matching address.
6996 			 */
6997 			in_flags |= IPF_RECVADDR;
6998 		}
6999 	}
7000 
7001 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7002 		in_flags |= IPF_RECVSLLA;
7003 
7004 	/*
7005 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7006 	 * freed if the packet is dropped. The caller will do so.
7007 	 */
7008 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7009 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7010 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7011 		if (mp == NULL) {
7012 			return;
7013 		}
7014 	}
7015 	if ((in_flags != 0) &&
7016 	    (mp->b_datap->db_type != M_CTL)) {
7017 		/*
7018 		 * The actual data will be contained in b_cont
7019 		 * upon successful return of the following call
7020 		 * else original mblk is returned
7021 		 */
7022 		ASSERT(recv_ill != NULL);
7023 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7024 		    ipst);
7025 	}
7026 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7027 	/* Send it upstream */
7028 	CONN_UDP_RECV(connp, mp);
7029 }
7030 
7031 /*
7032  * Fanout for UDP packets.
7033  * The caller puts <fport, lport> in the ports parameter.
7034  *
7035  * If SO_REUSEADDR is set all multicast and broadcast packets
7036  * will be delivered to all streams bound to the same port.
7037  *
7038  * Zones notes:
7039  * Multicast and broadcast packets will be distributed to streams in all zones.
7040  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7041  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7042  * packets. To maintain this behavior with multiple zones, the conns are grouped
7043  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7044  * each zone. If unset, all the following conns in the same zone are skipped.
7045  */
7046 static void
7047 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7048     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7049     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7050 {
7051 	uint32_t	dstport, srcport;
7052 	ipaddr_t	dst;
7053 	mblk_t		*first_mp;
7054 	boolean_t	secure;
7055 	in6_addr_t	v6src;
7056 	conn_t		*connp;
7057 	connf_t		*connfp;
7058 	conn_t		*first_connp;
7059 	conn_t		*next_connp;
7060 	mblk_t		*mp1, *first_mp1;
7061 	ipaddr_t	src;
7062 	zoneid_t	last_zoneid;
7063 	boolean_t	reuseaddr;
7064 	boolean_t	shared_addr;
7065 	ip_stack_t	*ipst;
7066 
7067 	ASSERT(recv_ill != NULL);
7068 	ipst = recv_ill->ill_ipst;
7069 
7070 	first_mp = mp;
7071 	if (mctl_present) {
7072 		mp = first_mp->b_cont;
7073 		first_mp->b_cont = NULL;
7074 		secure = ipsec_in_is_secure(first_mp);
7075 		ASSERT(mp != NULL);
7076 	} else {
7077 		first_mp = NULL;
7078 		secure = B_FALSE;
7079 	}
7080 
7081 	/* Extract ports in net byte order */
7082 	dstport = htons(ntohl(ports) & 0xFFFF);
7083 	srcport = htons(ntohl(ports) >> 16);
7084 	dst = ipha->ipha_dst;
7085 	src = ipha->ipha_src;
7086 
7087 	shared_addr = (zoneid == ALL_ZONES);
7088 	if (shared_addr) {
7089 		/*
7090 		 * No need to handle exclusive-stack zones since ALL_ZONES
7091 		 * only applies to the shared stack.
7092 		 */
7093 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7094 		if (zoneid == ALL_ZONES)
7095 			zoneid = tsol_packet_to_zoneid(mp);
7096 	}
7097 
7098 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7099 	mutex_enter(&connfp->connf_lock);
7100 	connp = connfp->connf_head;
7101 	if (!broadcast && !CLASSD(dst)) {
7102 		/*
7103 		 * Not broadcast or multicast. Send to the one (first)
7104 		 * client we find. No need to check conn_wantpacket()
7105 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7106 		 * IPv4 unicast packets.
7107 		 */
7108 		while ((connp != NULL) &&
7109 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7110 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7111 			connp = connp->conn_next;
7112 		}
7113 
7114 		if (connp == NULL || connp->conn_upq == NULL)
7115 			goto notfound;
7116 
7117 		if (is_system_labeled() &&
7118 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7119 		    connp))
7120 			goto notfound;
7121 
7122 		CONN_INC_REF(connp);
7123 		mutex_exit(&connfp->connf_lock);
7124 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7125 		    flags, recv_ill, ip_policy);
7126 		IP_STAT(ipst, ip_udp_fannorm);
7127 		CONN_DEC_REF(connp);
7128 		return;
7129 	}
7130 
7131 	/*
7132 	 * Broadcast and multicast case
7133 	 *
7134 	 * Need to check conn_wantpacket().
7135 	 * If SO_REUSEADDR has been set on the first we send the
7136 	 * packet to all clients that have joined the group and
7137 	 * match the port.
7138 	 */
7139 
7140 	while (connp != NULL) {
7141 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7142 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7143 		    (!is_system_labeled() ||
7144 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7145 		    connp)))
7146 			break;
7147 		connp = connp->conn_next;
7148 	}
7149 
7150 	if (connp == NULL || connp->conn_upq == NULL)
7151 		goto notfound;
7152 
7153 	first_connp = connp;
7154 	/*
7155 	 * When SO_REUSEADDR is not set, send the packet only to the first
7156 	 * matching connection in its zone by keeping track of the zoneid.
7157 	 */
7158 	reuseaddr = first_connp->conn_reuseaddr;
7159 	last_zoneid = first_connp->conn_zoneid;
7160 
7161 	CONN_INC_REF(connp);
7162 	connp = connp->conn_next;
7163 	for (;;) {
7164 		while (connp != NULL) {
7165 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7166 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7167 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7168 			    (!is_system_labeled() ||
7169 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7170 			    shared_addr, connp)))
7171 				break;
7172 			connp = connp->conn_next;
7173 		}
7174 		/*
7175 		 * Just copy the data part alone. The mctl part is
7176 		 * needed just for verifying policy and it is never
7177 		 * sent up.
7178 		 */
7179 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7180 		    ((mp1 = copymsg(mp)) == NULL))) {
7181 			/*
7182 			 * No more interested clients or memory
7183 			 * allocation failed
7184 			 */
7185 			connp = first_connp;
7186 			break;
7187 		}
7188 		if (connp->conn_zoneid != last_zoneid) {
7189 			/*
7190 			 * Update the zoneid so that the packet isn't sent to
7191 			 * any more conns in the same zone unless SO_REUSEADDR
7192 			 * is set.
7193 			 */
7194 			reuseaddr = connp->conn_reuseaddr;
7195 			last_zoneid = connp->conn_zoneid;
7196 		}
7197 		if (first_mp != NULL) {
7198 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7199 			    ipsec_info_type == IPSEC_IN);
7200 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7201 			    ipst->ips_netstack);
7202 			if (first_mp1 == NULL) {
7203 				freemsg(mp1);
7204 				connp = first_connp;
7205 				break;
7206 			}
7207 		} else {
7208 			first_mp1 = NULL;
7209 		}
7210 		CONN_INC_REF(connp);
7211 		mutex_exit(&connfp->connf_lock);
7212 		/*
7213 		 * IPQoS notes: We don't send the packet for policy
7214 		 * processing here, will do it for the last one (below).
7215 		 * i.e. we do it per-packet now, but if we do policy
7216 		 * processing per-conn, then we would need to do it
7217 		 * here too.
7218 		 */
7219 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7220 		    ipha, flags, recv_ill, B_FALSE);
7221 		mutex_enter(&connfp->connf_lock);
7222 		/* Follow the next pointer before releasing the conn. */
7223 		next_connp = connp->conn_next;
7224 		IP_STAT(ipst, ip_udp_fanmb);
7225 		CONN_DEC_REF(connp);
7226 		connp = next_connp;
7227 	}
7228 
7229 	/* Last one.  Send it upstream. */
7230 	mutex_exit(&connfp->connf_lock);
7231 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7232 	    recv_ill, ip_policy);
7233 	IP_STAT(ipst, ip_udp_fanmb);
7234 	CONN_DEC_REF(connp);
7235 	return;
7236 
7237 notfound:
7238 
7239 	mutex_exit(&connfp->connf_lock);
7240 	IP_STAT(ipst, ip_udp_fanothers);
7241 	/*
7242 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7243 	 * have already been matched above, since they live in the IPv4
7244 	 * fanout tables. This implies we only need to
7245 	 * check for IPv6 in6addr_any endpoints here.
7246 	 * Thus we compare using ipv6_all_zeros instead of the destination
7247 	 * address, except for the multicast group membership lookup which
7248 	 * uses the IPv4 destination.
7249 	 */
7250 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7251 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7252 	mutex_enter(&connfp->connf_lock);
7253 	connp = connfp->connf_head;
7254 	if (!broadcast && !CLASSD(dst)) {
7255 		while (connp != NULL) {
7256 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7257 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7258 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7259 			    !connp->conn_ipv6_v6only)
7260 				break;
7261 			connp = connp->conn_next;
7262 		}
7263 
7264 		if (connp != NULL && is_system_labeled() &&
7265 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7266 		    connp))
7267 			connp = NULL;
7268 
7269 		if (connp == NULL || connp->conn_upq == NULL) {
7270 			/*
7271 			 * No one bound to this port.  Is
7272 			 * there a client that wants all
7273 			 * unclaimed datagrams?
7274 			 */
7275 			mutex_exit(&connfp->connf_lock);
7276 
7277 			if (mctl_present)
7278 				first_mp->b_cont = mp;
7279 			else
7280 				first_mp = mp;
7281 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7282 			    connf_head != NULL) {
7283 				ip_fanout_proto(q, first_mp, ill, ipha,
7284 				    flags | IP_FF_RAWIP, mctl_present,
7285 				    ip_policy, recv_ill, zoneid);
7286 			} else {
7287 				if (ip_fanout_send_icmp(q, first_mp, flags,
7288 				    ICMP_DEST_UNREACHABLE,
7289 				    ICMP_PORT_UNREACHABLE,
7290 				    mctl_present, zoneid, ipst)) {
7291 					BUMP_MIB(ill->ill_ip_mib,
7292 					    udpIfStatsNoPorts);
7293 				}
7294 			}
7295 			return;
7296 		}
7297 
7298 		CONN_INC_REF(connp);
7299 		mutex_exit(&connfp->connf_lock);
7300 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7301 		    flags, recv_ill, ip_policy);
7302 		CONN_DEC_REF(connp);
7303 		return;
7304 	}
7305 	/*
7306 	 * IPv4 multicast packet being delivered to an AF_INET6
7307 	 * in6addr_any endpoint.
7308 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7309 	 * and not conn_wantpacket_v6() since any multicast membership is
7310 	 * for an IPv4-mapped multicast address.
7311 	 * The packet is sent to all clients in all zones that have joined the
7312 	 * group and match the port.
7313 	 */
7314 	while (connp != NULL) {
7315 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7316 		    srcport, v6src) &&
7317 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7318 		    (!is_system_labeled() ||
7319 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7320 		    connp)))
7321 			break;
7322 		connp = connp->conn_next;
7323 	}
7324 
7325 	if (connp == NULL || connp->conn_upq == NULL) {
7326 		/*
7327 		 * No one bound to this port.  Is
7328 		 * there a client that wants all
7329 		 * unclaimed datagrams?
7330 		 */
7331 		mutex_exit(&connfp->connf_lock);
7332 
7333 		if (mctl_present)
7334 			first_mp->b_cont = mp;
7335 		else
7336 			first_mp = mp;
7337 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7338 		    NULL) {
7339 			ip_fanout_proto(q, first_mp, ill, ipha,
7340 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7341 			    recv_ill, zoneid);
7342 		} else {
7343 			/*
7344 			 * We used to attempt to send an icmp error here, but
7345 			 * since this is known to be a multicast packet
7346 			 * and we don't send icmp errors in response to
7347 			 * multicast, just drop the packet and give up sooner.
7348 			 */
7349 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7350 			freemsg(first_mp);
7351 		}
7352 		return;
7353 	}
7354 
7355 	first_connp = connp;
7356 
7357 	CONN_INC_REF(connp);
7358 	connp = connp->conn_next;
7359 	for (;;) {
7360 		while (connp != NULL) {
7361 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7362 			    ipv6_all_zeros, srcport, v6src) &&
7363 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7364 			    (!is_system_labeled() ||
7365 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7366 			    shared_addr, connp)))
7367 				break;
7368 			connp = connp->conn_next;
7369 		}
7370 		/*
7371 		 * Just copy the data part alone. The mctl part is
7372 		 * needed just for verifying policy and it is never
7373 		 * sent up.
7374 		 */
7375 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7376 		    ((mp1 = copymsg(mp)) == NULL))) {
7377 			/*
7378 			 * No more intested clients or memory
7379 			 * allocation failed
7380 			 */
7381 			connp = first_connp;
7382 			break;
7383 		}
7384 		if (first_mp != NULL) {
7385 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7386 			    ipsec_info_type == IPSEC_IN);
7387 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7388 			    ipst->ips_netstack);
7389 			if (first_mp1 == NULL) {
7390 				freemsg(mp1);
7391 				connp = first_connp;
7392 				break;
7393 			}
7394 		} else {
7395 			first_mp1 = NULL;
7396 		}
7397 		CONN_INC_REF(connp);
7398 		mutex_exit(&connfp->connf_lock);
7399 		/*
7400 		 * IPQoS notes: We don't send the packet for policy
7401 		 * processing here, will do it for the last one (below).
7402 		 * i.e. we do it per-packet now, but if we do policy
7403 		 * processing per-conn, then we would need to do it
7404 		 * here too.
7405 		 */
7406 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7407 		    ipha, flags, recv_ill, B_FALSE);
7408 		mutex_enter(&connfp->connf_lock);
7409 		/* Follow the next pointer before releasing the conn. */
7410 		next_connp = connp->conn_next;
7411 		CONN_DEC_REF(connp);
7412 		connp = next_connp;
7413 	}
7414 
7415 	/* Last one.  Send it upstream. */
7416 	mutex_exit(&connfp->connf_lock);
7417 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7418 	    recv_ill, ip_policy);
7419 	CONN_DEC_REF(connp);
7420 }
7421 
7422 /*
7423  * Complete the ip_wput header so that it
7424  * is possible to generate ICMP
7425  * errors.
7426  */
7427 int
7428 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7429 {
7430 	ire_t *ire;
7431 
7432 	if (ipha->ipha_src == INADDR_ANY) {
7433 		ire = ire_lookup_local(zoneid, ipst);
7434 		if (ire == NULL) {
7435 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7436 			return (1);
7437 		}
7438 		ipha->ipha_src = ire->ire_addr;
7439 		ire_refrele(ire);
7440 	}
7441 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7442 	ipha->ipha_hdr_checksum = 0;
7443 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7444 	return (0);
7445 }
7446 
7447 /*
7448  * Nobody should be sending
7449  * packets up this stream
7450  */
7451 static void
7452 ip_lrput(queue_t *q, mblk_t *mp)
7453 {
7454 	mblk_t *mp1;
7455 
7456 	switch (mp->b_datap->db_type) {
7457 	case M_FLUSH:
7458 		/* Turn around */
7459 		if (*mp->b_rptr & FLUSHW) {
7460 			*mp->b_rptr &= ~FLUSHR;
7461 			qreply(q, mp);
7462 			return;
7463 		}
7464 		break;
7465 	}
7466 	/* Could receive messages that passed through ar_rput */
7467 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7468 		mp1->b_prev = mp1->b_next = NULL;
7469 	freemsg(mp);
7470 }
7471 
7472 /* Nobody should be sending packets down this stream */
7473 /* ARGSUSED */
7474 void
7475 ip_lwput(queue_t *q, mblk_t *mp)
7476 {
7477 	freemsg(mp);
7478 }
7479 
7480 /*
7481  * Move the first hop in any source route to ipha_dst and remove that part of
7482  * the source route.  Called by other protocols.  Errors in option formatting
7483  * are ignored - will be handled by ip_wput_options Return the final
7484  * destination (either ipha_dst or the last entry in a source route.)
7485  */
7486 ipaddr_t
7487 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7488 {
7489 	ipoptp_t	opts;
7490 	uchar_t		*opt;
7491 	uint8_t		optval;
7492 	uint8_t		optlen;
7493 	ipaddr_t	dst;
7494 	int		i;
7495 	ire_t		*ire;
7496 	ip_stack_t	*ipst = ns->netstack_ip;
7497 
7498 	ip2dbg(("ip_massage_options\n"));
7499 	dst = ipha->ipha_dst;
7500 	for (optval = ipoptp_first(&opts, ipha);
7501 	    optval != IPOPT_EOL;
7502 	    optval = ipoptp_next(&opts)) {
7503 		opt = opts.ipoptp_cur;
7504 		switch (optval) {
7505 			uint8_t off;
7506 		case IPOPT_SSRR:
7507 		case IPOPT_LSRR:
7508 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7509 				ip1dbg(("ip_massage_options: bad src route\n"));
7510 				break;
7511 			}
7512 			optlen = opts.ipoptp_len;
7513 			off = opt[IPOPT_OFFSET];
7514 			off--;
7515 		redo_srr:
7516 			if (optlen < IP_ADDR_LEN ||
7517 			    off > optlen - IP_ADDR_LEN) {
7518 				/* End of source route */
7519 				ip1dbg(("ip_massage_options: end of SR\n"));
7520 				break;
7521 			}
7522 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7523 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7524 			    ntohl(dst)));
7525 			/*
7526 			 * Check if our address is present more than
7527 			 * once as consecutive hops in source route.
7528 			 * XXX verify per-interface ip_forwarding
7529 			 * for source route?
7530 			 */
7531 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7532 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7533 			if (ire != NULL) {
7534 				ire_refrele(ire);
7535 				off += IP_ADDR_LEN;
7536 				goto redo_srr;
7537 			}
7538 			if (dst == htonl(INADDR_LOOPBACK)) {
7539 				ip1dbg(("ip_massage_options: loopback addr in "
7540 				    "source route!\n"));
7541 				break;
7542 			}
7543 			/*
7544 			 * Update ipha_dst to be the first hop and remove the
7545 			 * first hop from the source route (by overwriting
7546 			 * part of the option with NOP options).
7547 			 */
7548 			ipha->ipha_dst = dst;
7549 			/* Put the last entry in dst */
7550 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7551 			    3;
7552 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7553 
7554 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7555 			    ntohl(dst)));
7556 			/* Move down and overwrite */
7557 			opt[IP_ADDR_LEN] = opt[0];
7558 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7559 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7560 			for (i = 0; i < IP_ADDR_LEN; i++)
7561 				opt[i] = IPOPT_NOP;
7562 			break;
7563 		}
7564 	}
7565 	return (dst);
7566 }
7567 
7568 /*
7569  * This function's job is to forward data to the reverse tunnel (FA->HA)
7570  * after doing a few checks. It is assumed that the incoming interface
7571  * of the packet is always different than the outgoing interface and the
7572  * ire_type of the found ire has to be a non-resolver type.
7573  *
7574  * IPQoS notes
7575  * IP policy is invoked twice for a forwarded packet, once on the read side
7576  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7577  * enabled.
7578  */
7579 static void
7580 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7581 {
7582 	ipha_t		*ipha;
7583 	queue_t		*q;
7584 	uint32_t 	pkt_len;
7585 #define	rptr    ((uchar_t *)ipha)
7586 	uint32_t 	sum;
7587 	uint32_t 	max_frag;
7588 	mblk_t		*first_mp;
7589 	uint32_t	ill_index;
7590 	ipxmit_state_t	pktxmit_state;
7591 	ill_t		*out_ill;
7592 	ip_stack_t	*ipst = in_ill->ill_ipst;
7593 
7594 	ASSERT(ire != NULL);
7595 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7596 	ASSERT(ire->ire_stq != NULL);
7597 
7598 	/* Initiate read side IPPF processing */
7599 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7600 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7601 		ip_process(IPP_FWD_IN, &mp, ill_index);
7602 		if (mp == NULL) {
7603 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7604 			    "dropped during IPPF processing\n"));
7605 			return;
7606 		}
7607 	}
7608 
7609 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7610 		ILLF_ROUTER) == 0) ||
7611 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7612 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7613 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7614 		    "forwarding is not turned on\n"));
7615 		goto drop_pkt;
7616 	}
7617 
7618 	/*
7619 	 * Don't forward if the interface is down
7620 	 */
7621 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7622 		goto discard_pkt;
7623 	}
7624 
7625 	ipha = (ipha_t *)mp->b_rptr;
7626 	pkt_len = ntohs(ipha->ipha_length);
7627 	/* Adjust the checksum to reflect the ttl decrement. */
7628 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7629 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7630 	if (ipha->ipha_ttl-- <= 1) {
7631 		if (ip_csum_hdr(ipha)) {
7632 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7633 			goto drop_pkt;
7634 		}
7635 		q = ire->ire_stq;
7636 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7637 		    BPRI_HI)) == NULL) {
7638 			goto discard_pkt;
7639 		}
7640 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7641 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7642 		/* Sent by forwarding path, and router is global zone */
7643 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7644 		    GLOBAL_ZONEID, ipst);
7645 		return;
7646 	}
7647 
7648 	/* Get the ill_index of the ILL */
7649 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7650 
7651 	/*
7652 	 * This location is chosen for the placement of the forwarding hook
7653 	 * because at this point we know that we have a path out for the
7654 	 * packet but haven't yet applied any logic (such as fragmenting)
7655 	 * that happen as part of transmitting the packet out.
7656 	 */
7657 	out_ill = ire->ire_ipif->ipif_ill;
7658 
7659 	DTRACE_PROBE4(ip4__forwarding__start,
7660 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7661 
7662 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7663 	    ipst->ips_ipv4firewall_forwarding,
7664 	    in_ill, out_ill, ipha, mp, mp, ipst);
7665 
7666 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7667 
7668 	if (mp == NULL)
7669 		return;
7670 	pkt_len = ntohs(ipha->ipha_length);
7671 
7672 	/*
7673 	 * ip_mrtun_forward is only used by foreign agent to reverse
7674 	 * tunnel the incoming packet. So it does not do any option
7675 	 * processing for source routing.
7676 	 */
7677 	max_frag = ire->ire_max_frag;
7678 	if (pkt_len > max_frag) {
7679 		/*
7680 		 * It needs fragging on its way out.  We haven't
7681 		 * verified the header checksum yet.  Since we
7682 		 * are going to put a surely good checksum in the
7683 		 * outgoing header, we have to make sure that it
7684 		 * was good coming in.
7685 		 */
7686 		if (ip_csum_hdr(ipha)) {
7687 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7688 			goto drop_pkt;
7689 		}
7690 
7691 		/* Initiate write side IPPF processing */
7692 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7693 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7694 			if (mp == NULL) {
7695 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7696 				    "dropped/deferred during ip policy "\
7697 				    "processing\n"));
7698 				return;
7699 			}
7700 		}
7701 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7702 		    BPRI_HI)) == NULL) {
7703 			goto discard_pkt;
7704 		}
7705 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7706 		mp = first_mp;
7707 
7708 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7709 		return;
7710 	}
7711 
7712 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7713 
7714 	ASSERT(ire->ire_ipif != NULL);
7715 
7716 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7717 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7718 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7719 	    ipst->ips_ipv4firewall_physical_out,
7720 	    NULL, out_ill, ipha, mp, mp, ipst);
7721 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7722 	if (mp == NULL)
7723 		return;
7724 
7725 	/* Now send the packet to the tunnel interface */
7726 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7727 	q = ire->ire_stq;
7728 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7729 	if ((pktxmit_state == SEND_FAILED) ||
7730 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7731 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7732 		    q->q_ptr));
7733 	}
7734 
7735 	return;
7736 discard_pkt:
7737 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7738 drop_pkt:;
7739 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7740 	freemsg(mp);
7741 #undef	rptr
7742 }
7743 
7744 /*
7745  * Fills the ipsec_out_t data structure with appropriate fields and
7746  * prepends it to mp which contains the IP hdr + data that was meant
7747  * to be forwarded. Please note that ipsec_out_info data structure
7748  * is used here to communicate the outgoing ill path at ip_wput()
7749  * for the ICMP error packet. This has nothing to do with ipsec IP
7750  * security. ipsec_out_t is really used to pass the info to the module
7751  * IP where this information cannot be extracted from conn.
7752  * This functions is called by ip_mrtun_forward().
7753  */
7754 void
7755 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7756 {
7757 	ipsec_out_t	*io;
7758 
7759 	ASSERT(xmit_ill != NULL);
7760 	first_mp->b_datap->db_type = M_CTL;
7761 	first_mp->b_wptr += sizeof (ipsec_info_t);
7762 	/*
7763 	 * This is to pass info to ip_wput in absence of conn.
7764 	 * ipsec_out_secure will be B_FALSE because of this.
7765 	 * Thus ipsec_out_secure being B_FALSE indicates that
7766 	 * this is not IPSEC security related information.
7767 	 */
7768 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7769 	io = (ipsec_out_t *)first_mp->b_rptr;
7770 	io->ipsec_out_type = IPSEC_OUT;
7771 	io->ipsec_out_len = sizeof (ipsec_out_t);
7772 	first_mp->b_cont = mp;
7773 	io->ipsec_out_ill_index =
7774 	    xmit_ill->ill_phyint->phyint_ifindex;
7775 	io->ipsec_out_xmit_if = B_TRUE;
7776 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7777 }
7778 
7779 /*
7780  * Return the network mask
7781  * associated with the specified address.
7782  */
7783 ipaddr_t
7784 ip_net_mask(ipaddr_t addr)
7785 {
7786 	uchar_t	*up = (uchar_t *)&addr;
7787 	ipaddr_t mask = 0;
7788 	uchar_t	*maskp = (uchar_t *)&mask;
7789 
7790 #if defined(__i386) || defined(__amd64)
7791 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7792 #endif
7793 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7794 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7795 #endif
7796 	if (CLASSD(addr)) {
7797 		maskp[0] = 0xF0;
7798 		return (mask);
7799 	}
7800 	if (addr == 0)
7801 		return (0);
7802 	maskp[0] = 0xFF;
7803 	if ((up[0] & 0x80) == 0)
7804 		return (mask);
7805 
7806 	maskp[1] = 0xFF;
7807 	if ((up[0] & 0xC0) == 0x80)
7808 		return (mask);
7809 
7810 	maskp[2] = 0xFF;
7811 	if ((up[0] & 0xE0) == 0xC0)
7812 		return (mask);
7813 
7814 	/* Must be experimental or multicast, indicate as much */
7815 	return ((ipaddr_t)0);
7816 }
7817 
7818 /*
7819  * Select an ill for the packet by considering load spreading across
7820  * a different ill in the group if dst_ill is part of some group.
7821  */
7822 ill_t *
7823 ip_newroute_get_dst_ill(ill_t *dst_ill)
7824 {
7825 	ill_t *ill;
7826 
7827 	/*
7828 	 * We schedule irrespective of whether the source address is
7829 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7830 	 */
7831 	ill = illgrp_scheduler(dst_ill);
7832 	if (ill == NULL)
7833 		return (NULL);
7834 
7835 	/*
7836 	 * For groups with names ip_sioctl_groupname ensures that all
7837 	 * ills are of same type. For groups without names, ifgrp_insert
7838 	 * ensures this.
7839 	 */
7840 	ASSERT(dst_ill->ill_type == ill->ill_type);
7841 
7842 	return (ill);
7843 }
7844 
7845 /*
7846  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7847  */
7848 ill_t *
7849 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7850     ip_stack_t *ipst)
7851 {
7852 	ill_t *ret_ill;
7853 
7854 	ASSERT(ifindex != 0);
7855 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7856 	    ipst);
7857 	if (ret_ill == NULL ||
7858 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7859 		if (isv6) {
7860 			if (ill != NULL) {
7861 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7862 			} else {
7863 				BUMP_MIB(&ipst->ips_ip6_mib,
7864 				    ipIfStatsOutDiscards);
7865 			}
7866 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7867 			    "bad ifindex %d.\n", ifindex));
7868 		} else {
7869 			if (ill != NULL) {
7870 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7871 			} else {
7872 				BUMP_MIB(&ipst->ips_ip_mib,
7873 				    ipIfStatsOutDiscards);
7874 			}
7875 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7876 			    "bad ifindex %d.\n", ifindex));
7877 		}
7878 		if (ret_ill != NULL)
7879 			ill_refrele(ret_ill);
7880 		freemsg(first_mp);
7881 		return (NULL);
7882 	}
7883 
7884 	return (ret_ill);
7885 }
7886 
7887 /*
7888  * IPv4 -
7889  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7890  * out a packet to a destination address for which we do not have specific
7891  * (or sufficient) routing information.
7892  *
7893  * NOTE : These are the scopes of some of the variables that point at IRE,
7894  *	  which needs to be followed while making any future modifications
7895  *	  to avoid memory leaks.
7896  *
7897  *	- ire and sire are the entries looked up initially by
7898  *	  ire_ftable_lookup.
7899  *	- ipif_ire is used to hold the interface ire associated with
7900  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7901  *	  it before branching out to error paths.
7902  *	- save_ire is initialized before ire_create, so that ire returned
7903  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7904  *	  before breaking out of the switch.
7905  *
7906  *	Thus on failures, we have to REFRELE only ire and sire, if they
7907  *	are not NULL.
7908  */
7909 void
7910 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7911     zoneid_t zoneid, ip_stack_t *ipst)
7912 {
7913 	areq_t	*areq;
7914 	ipaddr_t gw = 0;
7915 	ire_t	*ire = NULL;
7916 	mblk_t	*res_mp;
7917 	ipaddr_t *addrp;
7918 	ipaddr_t nexthop_addr;
7919 	ipif_t  *src_ipif = NULL;
7920 	ill_t	*dst_ill = NULL;
7921 	ipha_t  *ipha;
7922 	ire_t	*sire = NULL;
7923 	mblk_t	*first_mp;
7924 	ire_t	*save_ire;
7925 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7926 	ushort_t ire_marks = 0;
7927 	boolean_t mctl_present;
7928 	ipsec_out_t *io;
7929 	mblk_t	*saved_mp;
7930 	ire_t	*first_sire = NULL;
7931 	mblk_t	*copy_mp = NULL;
7932 	mblk_t	*xmit_mp = NULL;
7933 	ipaddr_t save_dst;
7934 	uint32_t multirt_flags =
7935 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7936 	boolean_t multirt_is_resolvable;
7937 	boolean_t multirt_resolve_next;
7938 	boolean_t do_attach_ill = B_FALSE;
7939 	boolean_t ip_nexthop = B_FALSE;
7940 	tsol_ire_gw_secattr_t *attrp = NULL;
7941 	tsol_gcgrp_t *gcgrp = NULL;
7942 	tsol_gcgrp_addr_t ga;
7943 
7944 	if (ip_debug > 2) {
7945 		/* ip1dbg */
7946 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7947 	}
7948 
7949 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7950 	if (mctl_present) {
7951 		io = (ipsec_out_t *)first_mp->b_rptr;
7952 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7953 		ASSERT(zoneid == io->ipsec_out_zoneid);
7954 		ASSERT(zoneid != ALL_ZONES);
7955 	}
7956 
7957 	ipha = (ipha_t *)mp->b_rptr;
7958 
7959 	/* All multicast lookups come through ip_newroute_ipif() */
7960 	if (CLASSD(dst)) {
7961 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7962 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7963 		freemsg(first_mp);
7964 		return;
7965 	}
7966 
7967 	if (mctl_present && io->ipsec_out_attach_if) {
7968 		/* ip_grab_attach_ill returns a held ill */
7969 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7970 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7971 
7972 		/* Failure case frees things for us. */
7973 		if (attach_ill == NULL)
7974 			return;
7975 
7976 		/*
7977 		 * Check if we need an ire that will not be
7978 		 * looked up by anybody else i.e. HIDDEN.
7979 		 */
7980 		if (ill_is_probeonly(attach_ill))
7981 			ire_marks = IRE_MARK_HIDDEN;
7982 	}
7983 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7984 		ip_nexthop = B_TRUE;
7985 		nexthop_addr = io->ipsec_out_nexthop_addr;
7986 	}
7987 	/*
7988 	 * If this IRE is created for forwarding or it is not for
7989 	 * traffic for congestion controlled protocols, mark it as temporary.
7990 	 */
7991 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7992 		ire_marks |= IRE_MARK_TEMPORARY;
7993 
7994 	/*
7995 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7996 	 * chain until it gets the most specific information available.
7997 	 * For example, we know that there is no IRE_CACHE for this dest,
7998 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7999 	 * ire_ftable_lookup will look up the gateway, etc.
8000 	 * Check if in_ill != NULL. If it is true, the packet must be
8001 	 * from an incoming interface where RTA_SRCIFP is set.
8002 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8003 	 * to the destination, of equal netmask length in the forward table,
8004 	 * will be recursively explored. If no information is available
8005 	 * for the final gateway of that route, we force the returned ire
8006 	 * to be equal to sire using MATCH_IRE_PARENT.
8007 	 * At least, in this case we have a starting point (in the buckets)
8008 	 * to look for other routes to the destination in the forward table.
8009 	 * This is actually used only for multirouting, where a list
8010 	 * of routes has to be processed in sequence.
8011 	 *
8012 	 * In the process of coming up with the most specific information,
8013 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8014 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8015 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8016 	 * Two caveats when handling incomplete ire's in ip_newroute:
8017 	 * - we should be careful when accessing its ire_nce (specifically
8018 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8019 	 * - not all legacy code path callers are prepared to handle
8020 	 *   incomplete ire's, so we should not create/add incomplete
8021 	 *   ire_cache entries here. (See discussion about temporary solution
8022 	 *   further below).
8023 	 *
8024 	 * In order to minimize packet dropping, and to preserve existing
8025 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8026 	 * gateway, and instead use the IF_RESOLVER ire to send out
8027 	 * another request to ARP (this is achieved by passing the
8028 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8029 	 * arp response comes back in ip_wput_nondata, we will create
8030 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8031 	 *
8032 	 * Note that this is a temporary solution; the correct solution is
8033 	 * to create an incomplete  per-dst ire_cache entry, and send the
8034 	 * packet out when the gw's nce is resolved. In order to achieve this,
8035 	 * all packet processing must have been completed prior to calling
8036 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8037 	 * to be modified to accomodate this solution.
8038 	 */
8039 	if (in_ill != NULL) {
8040 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8041 		    in_ill, MATCH_IRE_TYPE);
8042 	} else if (ip_nexthop) {
8043 		/*
8044 		 * The first time we come here, we look for an IRE_INTERFACE
8045 		 * entry for the specified nexthop, set the dst to be the
8046 		 * nexthop address and create an IRE_CACHE entry for the
8047 		 * nexthop. The next time around, we are able to find an
8048 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8049 		 * nexthop address and create an IRE_CACHE entry for the
8050 		 * destination address via the specified nexthop.
8051 		 */
8052 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8053 		    MBLK_GETLABEL(mp), ipst);
8054 		if (ire != NULL) {
8055 			gw = nexthop_addr;
8056 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8057 		} else {
8058 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8059 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8060 			    MBLK_GETLABEL(mp),
8061 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8062 			    ipst);
8063 			if (ire != NULL) {
8064 				dst = nexthop_addr;
8065 			}
8066 		}
8067 	} else if (attach_ill == NULL) {
8068 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8069 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8070 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8071 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8072 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8073 		    ipst);
8074 	} else {
8075 		/*
8076 		 * attach_ill is set only for communicating with
8077 		 * on-link hosts. So, don't look for DEFAULT.
8078 		 */
8079 		ipif_t	*attach_ipif;
8080 
8081 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8082 		if (attach_ipif == NULL) {
8083 			ill_refrele(attach_ill);
8084 			goto icmp_err_ret;
8085 		}
8086 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8087 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8088 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8089 		    MATCH_IRE_SECATTR, ipst);
8090 		ipif_refrele(attach_ipif);
8091 	}
8092 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8093 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8094 
8095 	/*
8096 	 * This loop is run only once in most cases.
8097 	 * We loop to resolve further routes only when the destination
8098 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8099 	 */
8100 	do {
8101 		/* Clear the previous iteration's values */
8102 		if (src_ipif != NULL) {
8103 			ipif_refrele(src_ipif);
8104 			src_ipif = NULL;
8105 		}
8106 		if (dst_ill != NULL) {
8107 			ill_refrele(dst_ill);
8108 			dst_ill = NULL;
8109 		}
8110 
8111 		multirt_resolve_next = B_FALSE;
8112 		/*
8113 		 * We check if packets have to be multirouted.
8114 		 * In this case, given the current <ire, sire> couple,
8115 		 * we look for the next suitable <ire, sire>.
8116 		 * This check is done in ire_multirt_lookup(),
8117 		 * which applies various criteria to find the next route
8118 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8119 		 * unchanged if it detects it has not been tried yet.
8120 		 */
8121 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8122 			ip3dbg(("ip_newroute: starting next_resolution "
8123 			    "with first_mp %p, tag %d\n",
8124 			    (void *)first_mp,
8125 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8126 
8127 			ASSERT(sire != NULL);
8128 			multirt_is_resolvable =
8129 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8130 				MBLK_GETLABEL(mp), ipst);
8131 
8132 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8133 			    "ire %p, sire %p\n",
8134 			    multirt_is_resolvable,
8135 			    (void *)ire, (void *)sire));
8136 
8137 			if (!multirt_is_resolvable) {
8138 				/*
8139 				 * No more multirt route to resolve; give up
8140 				 * (all routes resolved or no more
8141 				 * resolvable routes).
8142 				 */
8143 				if (ire != NULL) {
8144 					ire_refrele(ire);
8145 					ire = NULL;
8146 				}
8147 			} else {
8148 				ASSERT(sire != NULL);
8149 				ASSERT(ire != NULL);
8150 				/*
8151 				 * We simply use first_sire as a flag that
8152 				 * indicates if a resolvable multirt route
8153 				 * has already been found.
8154 				 * If it is not the case, we may have to send
8155 				 * an ICMP error to report that the
8156 				 * destination is unreachable.
8157 				 * We do not IRE_REFHOLD first_sire.
8158 				 */
8159 				if (first_sire == NULL) {
8160 					first_sire = sire;
8161 				}
8162 			}
8163 		}
8164 		if (ire == NULL) {
8165 			if (ip_debug > 3) {
8166 				/* ip2dbg */
8167 				pr_addr_dbg("ip_newroute: "
8168 				    "can't resolve %s\n", AF_INET, &dst);
8169 			}
8170 			ip3dbg(("ip_newroute: "
8171 			    "ire %p, sire %p, first_sire %p\n",
8172 			    (void *)ire, (void *)sire, (void *)first_sire));
8173 
8174 			if (sire != NULL) {
8175 				ire_refrele(sire);
8176 				sire = NULL;
8177 			}
8178 
8179 			if (first_sire != NULL) {
8180 				/*
8181 				 * At least one multirt route has been found
8182 				 * in the same call to ip_newroute();
8183 				 * there is no need to report an ICMP error.
8184 				 * first_sire was not IRE_REFHOLDed.
8185 				 */
8186 				MULTIRT_DEBUG_UNTAG(first_mp);
8187 				freemsg(first_mp);
8188 				return;
8189 			}
8190 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8191 			    RTA_DST, ipst);
8192 			if (attach_ill != NULL)
8193 				ill_refrele(attach_ill);
8194 			goto icmp_err_ret;
8195 		}
8196 
8197 		/*
8198 		 * When RTA_SRCIFP is used to add a route, then an interface
8199 		 * route is added in the source interface's routing table.
8200 		 * If the outgoing interface of this route is of type
8201 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8202 		 * ire_nce->nce_res_mp is set to NULL.
8203 		 * Later, when this route is first used for forwarding
8204 		 * a packet, ip_newroute() is called
8205 		 * to resolve the hardware address of the outgoing ipif.
8206 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8207 		 * source interface based table. We only come here if the
8208 		 * outgoing interface is a resolver interface and we don't
8209 		 * have the ire_nce->nce_res_mp information yet.
8210 		 * If in_ill is not null that means it is called from
8211 		 * ip_rput.
8212 		 */
8213 
8214 		ASSERT(ire->ire_in_ill == NULL ||
8215 		    (ire->ire_type == IRE_IF_RESOLVER &&
8216 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8217 
8218 		/*
8219 		 * Verify that the returned IRE does not have either
8220 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8221 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8222 		 */
8223 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8224 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8225 			if (attach_ill != NULL)
8226 				ill_refrele(attach_ill);
8227 			goto icmp_err_ret;
8228 		}
8229 		/*
8230 		 * Increment the ire_ob_pkt_count field for ire if it is an
8231 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8232 		 * increment the same for the parent IRE, sire, if it is some
8233 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8234 		 */
8235 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8236 			UPDATE_OB_PKT_COUNT(ire);
8237 			ire->ire_last_used_time = lbolt;
8238 		}
8239 
8240 		if (sire != NULL) {
8241 			gw = sire->ire_gateway_addr;
8242 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8243 			    IRE_INTERFACE)) == 0);
8244 			UPDATE_OB_PKT_COUNT(sire);
8245 			sire->ire_last_used_time = lbolt;
8246 		}
8247 		/*
8248 		 * We have a route to reach the destination.
8249 		 *
8250 		 * 1) If the interface is part of ill group, try to get a new
8251 		 *    ill taking load spreading into account.
8252 		 *
8253 		 * 2) After selecting the ill, get a source address that
8254 		 *    might create good inbound load spreading.
8255 		 *    ipif_select_source does this for us.
8256 		 *
8257 		 * If the application specified the ill (ifindex), we still
8258 		 * load spread. Only if the packets needs to go out
8259 		 * specifically on a given ill e.g. binding to
8260 		 * IPIF_NOFAILOVER address, then we don't try to use a
8261 		 * different ill for load spreading.
8262 		 */
8263 		if (attach_ill == NULL) {
8264 			/*
8265 			 * Don't perform outbound load spreading in the
8266 			 * case of an RTF_MULTIRT route, as we actually
8267 			 * typically want to replicate outgoing packets
8268 			 * through particular interfaces.
8269 			 */
8270 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8271 				dst_ill = ire->ire_ipif->ipif_ill;
8272 				/* for uniformity */
8273 				ill_refhold(dst_ill);
8274 			} else {
8275 				/*
8276 				 * If we are here trying to create an IRE_CACHE
8277 				 * for an offlink destination and have the
8278 				 * IRE_CACHE for the next hop and the latter is
8279 				 * using virtual IP source address selection i.e
8280 				 * it's ire->ire_ipif is pointing to a virtual
8281 				 * network interface (vni) then
8282 				 * ip_newroute_get_dst_ll() will return the vni
8283 				 * interface as the dst_ill. Since the vni is
8284 				 * virtual i.e not associated with any physical
8285 				 * interface, it cannot be the dst_ill, hence
8286 				 * in such a case call ip_newroute_get_dst_ll()
8287 				 * with the stq_ill instead of the ire_ipif ILL.
8288 				 * The function returns a refheld ill.
8289 				 */
8290 				if ((ire->ire_type == IRE_CACHE) &&
8291 				    IS_VNI(ire->ire_ipif->ipif_ill))
8292 					dst_ill = ip_newroute_get_dst_ill(
8293 						ire->ire_stq->q_ptr);
8294 				else
8295 					dst_ill = ip_newroute_get_dst_ill(
8296 						ire->ire_ipif->ipif_ill);
8297 			}
8298 			if (dst_ill == NULL) {
8299 				if (ip_debug > 2) {
8300 					pr_addr_dbg("ip_newroute: "
8301 					    "no dst ill for dst"
8302 					    " %s\n", AF_INET, &dst);
8303 				}
8304 				goto icmp_err_ret;
8305 			}
8306 		} else {
8307 			dst_ill = ire->ire_ipif->ipif_ill;
8308 			/* for uniformity */
8309 			ill_refhold(dst_ill);
8310 			/*
8311 			 * We should have found a route matching ill as we
8312 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8313 			 * Rather than asserting, when there is a mismatch,
8314 			 * we just drop the packet.
8315 			 */
8316 			if (dst_ill != attach_ill) {
8317 				ip0dbg(("ip_newroute: Packet dropped as "
8318 				    "IPIF_NOFAILOVER ill is %s, "
8319 				    "ire->ire_ipif->ipif_ill is %s\n",
8320 				    attach_ill->ill_name,
8321 				    dst_ill->ill_name));
8322 				ill_refrele(attach_ill);
8323 				goto icmp_err_ret;
8324 			}
8325 		}
8326 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8327 		if (attach_ill != NULL) {
8328 			ill_refrele(attach_ill);
8329 			attach_ill = NULL;
8330 			do_attach_ill = B_TRUE;
8331 		}
8332 		ASSERT(dst_ill != NULL);
8333 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8334 
8335 		/*
8336 		 * Pick the best source address from dst_ill.
8337 		 *
8338 		 * 1) If it is part of a multipathing group, we would
8339 		 *    like to spread the inbound packets across different
8340 		 *    interfaces. ipif_select_source picks a random source
8341 		 *    across the different ills in the group.
8342 		 *
8343 		 * 2) If it is not part of a multipathing group, we try
8344 		 *    to pick the source address from the destination
8345 		 *    route. Clustering assumes that when we have multiple
8346 		 *    prefixes hosted on an interface, the prefix of the
8347 		 *    source address matches the prefix of the destination
8348 		 *    route. We do this only if the address is not
8349 		 *    DEPRECATED.
8350 		 *
8351 		 * 3) If the conn is in a different zone than the ire, we
8352 		 *    need to pick a source address from the right zone.
8353 		 *
8354 		 * NOTE : If we hit case (1) above, the prefix of the source
8355 		 *	  address picked may not match the prefix of the
8356 		 *	  destination routes prefix as ipif_select_source
8357 		 *	  does not look at "dst" while picking a source
8358 		 *	  address.
8359 		 *	  If we want the same behavior as (2), we will need
8360 		 *	  to change the behavior of ipif_select_source.
8361 		 */
8362 		ASSERT(src_ipif == NULL);
8363 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8364 			/*
8365 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8366 			 * Check that the ipif matching the requested source
8367 			 * address still exists.
8368 			 */
8369 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8370 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8371 		}
8372 		if (src_ipif == NULL) {
8373 			ire_marks |= IRE_MARK_USESRC_CHECK;
8374 			if ((dst_ill->ill_group != NULL) ||
8375 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8376 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8377 			    ire->ire_zoneid != ALL_ZONES) ||
8378 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8379 				/*
8380 				 * If the destination is reachable via a
8381 				 * given gateway, the selected source address
8382 				 * should be in the same subnet as the gateway.
8383 				 * Otherwise, the destination is not reachable.
8384 				 *
8385 				 * If there are no interfaces on the same subnet
8386 				 * as the destination, ipif_select_source gives
8387 				 * first non-deprecated interface which might be
8388 				 * on a different subnet than the gateway.
8389 				 * This is not desirable. Hence pass the dst_ire
8390 				 * source address to ipif_select_source.
8391 				 * It is sure that the destination is reachable
8392 				 * with the dst_ire source address subnet.
8393 				 * So passing dst_ire source address to
8394 				 * ipif_select_source will make sure that the
8395 				 * selected source will be on the same subnet
8396 				 * as dst_ire source address.
8397 				 */
8398 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8399 				src_ipif = ipif_select_source(dst_ill, saddr,
8400 				    zoneid);
8401 				if (src_ipif == NULL) {
8402 					if (ip_debug > 2) {
8403 						pr_addr_dbg("ip_newroute: "
8404 						    "no src for dst %s ",
8405 						    AF_INET, &dst);
8406 						printf("through interface %s\n",
8407 						    dst_ill->ill_name);
8408 					}
8409 					goto icmp_err_ret;
8410 				}
8411 			} else {
8412 				src_ipif = ire->ire_ipif;
8413 				ASSERT(src_ipif != NULL);
8414 				/* hold src_ipif for uniformity */
8415 				ipif_refhold(src_ipif);
8416 			}
8417 		}
8418 
8419 		/*
8420 		 * Assign a source address while we have the conn.
8421 		 * We can't have ip_wput_ire pick a source address when the
8422 		 * packet returns from arp since we need to look at
8423 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8424 		 * going through arp.
8425 		 *
8426 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8427 		 *	  it uses ip6i to store this information.
8428 		 */
8429 		if (ipha->ipha_src == INADDR_ANY &&
8430 		    (connp == NULL || !connp->conn_unspec_src)) {
8431 			ipha->ipha_src = src_ipif->ipif_src_addr;
8432 		}
8433 		if (ip_debug > 3) {
8434 			/* ip2dbg */
8435 			pr_addr_dbg("ip_newroute: first hop %s\n",
8436 			    AF_INET, &gw);
8437 		}
8438 		ip2dbg(("\tire type %s (%d)\n",
8439 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8440 
8441 		/*
8442 		 * The TTL of multirouted packets is bounded by the
8443 		 * ip_multirt_ttl ndd variable.
8444 		 */
8445 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8446 			/* Force TTL of multirouted packets */
8447 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8448 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8449 				ip2dbg(("ip_newroute: forcing multirt TTL "
8450 				    "to %d (was %d), dst 0x%08x\n",
8451 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8452 				    ntohl(sire->ire_addr)));
8453 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8454 			}
8455 		}
8456 		/*
8457 		 * At this point in ip_newroute(), ire is either the
8458 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8459 		 * destination or an IRE_INTERFACE type that should be used
8460 		 * to resolve an on-subnet destination or an on-subnet
8461 		 * next-hop gateway.
8462 		 *
8463 		 * In the IRE_CACHE case, we have the following :
8464 		 *
8465 		 * 1) src_ipif - used for getting a source address.
8466 		 *
8467 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8468 		 *    means packets using this IRE_CACHE will go out on
8469 		 *    dst_ill.
8470 		 *
8471 		 * 3) The IRE sire will point to the prefix that is the
8472 		 *    longest  matching route for the destination. These
8473 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8474 		 *
8475 		 *    The newly created IRE_CACHE entry for the off-subnet
8476 		 *    destination is tied to both the prefix route and the
8477 		 *    interface route used to resolve the next-hop gateway
8478 		 *    via the ire_phandle and ire_ihandle fields,
8479 		 *    respectively.
8480 		 *
8481 		 * In the IRE_INTERFACE case, we have the following :
8482 		 *
8483 		 * 1) src_ipif - used for getting a source address.
8484 		 *
8485 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8486 		 *    means packets using the IRE_CACHE that we will build
8487 		 *    here will go out on dst_ill.
8488 		 *
8489 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8490 		 *    to be created will only be tied to the IRE_INTERFACE
8491 		 *    that was derived from the ire_ihandle field.
8492 		 *
8493 		 *    If sire is non-NULL, it means the destination is
8494 		 *    off-link and we will first create the IRE_CACHE for the
8495 		 *    gateway. Next time through ip_newroute, we will create
8496 		 *    the IRE_CACHE for the final destination as described
8497 		 *    above.
8498 		 *
8499 		 * In both cases, after the current resolution has been
8500 		 * completed (or possibly initialised, in the IRE_INTERFACE
8501 		 * case), the loop may be re-entered to attempt the resolution
8502 		 * of another RTF_MULTIRT route.
8503 		 *
8504 		 * When an IRE_CACHE entry for the off-subnet destination is
8505 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8506 		 * for further processing in emission loops.
8507 		 */
8508 		save_ire = ire;
8509 		switch (ire->ire_type) {
8510 		case IRE_CACHE: {
8511 			ire_t	*ipif_ire;
8512 			mblk_t	*ire_fp_mp;
8513 
8514 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8515 			if (gw == 0)
8516 				gw = ire->ire_gateway_addr;
8517 			/*
8518 			 * We need 3 ire's to create a new cache ire for an
8519 			 * off-link destination from the cache ire of the
8520 			 * gateway.
8521 			 *
8522 			 *	1. The prefix ire 'sire' (Note that this does
8523 			 *	   not apply to the conn_nexthop_set case)
8524 			 *	2. The cache ire of the gateway 'ire'
8525 			 *	3. The interface ire 'ipif_ire'
8526 			 *
8527 			 * We have (1) and (2). We lookup (3) below.
8528 			 *
8529 			 * If there is no interface route to the gateway,
8530 			 * it is a race condition, where we found the cache
8531 			 * but the interface route has been deleted.
8532 			 */
8533 			if (ip_nexthop) {
8534 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8535 			} else {
8536 				ipif_ire =
8537 				    ire_ihandle_lookup_offlink(ire, sire);
8538 			}
8539 			if (ipif_ire == NULL) {
8540 				ip1dbg(("ip_newroute: "
8541 				    "ire_ihandle_lookup_offlink failed\n"));
8542 				goto icmp_err_ret;
8543 			}
8544 			/*
8545 			 * XXX We are using the same res_mp
8546 			 * (DL_UNITDATA_REQ) though the save_ire is not
8547 			 * pointing at the same ill.
8548 			 * This is incorrect. We need to send it up to the
8549 			 * resolver to get the right res_mp. For ethernets
8550 			 * this may be okay (ill_type == DL_ETHER).
8551 			 */
8552 			res_mp = save_ire->ire_nce->nce_res_mp;
8553 			ire_fp_mp = NULL;
8554 
8555 			/*
8556 			 * Check cached gateway IRE for any security
8557 			 * attributes; if found, associate the gateway
8558 			 * credentials group to the destination IRE.
8559 			 */
8560 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8561 				mutex_enter(&attrp->igsa_lock);
8562 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8563 					GCGRP_REFHOLD(gcgrp);
8564 				mutex_exit(&attrp->igsa_lock);
8565 			}
8566 
8567 			ire = ire_create(
8568 			    (uchar_t *)&dst,		/* dest address */
8569 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8570 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8571 			    (uchar_t *)&gw,		/* gateway address */
8572 			    NULL,
8573 			    &save_ire->ire_max_frag,
8574 			    ire_fp_mp,			/* Fast Path header */
8575 			    dst_ill->ill_rq,		/* recv-from queue */
8576 			    dst_ill->ill_wq,		/* send-to queue */
8577 			    IRE_CACHE,			/* IRE type */
8578 			    res_mp,
8579 			    src_ipif,
8580 			    in_ill,			/* incoming ill */
8581 			    (sire != NULL) ?
8582 				sire->ire_mask : 0, 	/* Parent mask */
8583 			    (sire != NULL) ?
8584 				sire->ire_phandle : 0,  /* Parent handle */
8585 			    ipif_ire->ire_ihandle,	/* Interface handle */
8586 			    (sire != NULL) ? (sire->ire_flags &
8587 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8588 			    (sire != NULL) ?
8589 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8590 			    NULL,
8591 			    gcgrp,
8592 			    ipst);
8593 
8594 			if (ire == NULL) {
8595 				if (gcgrp != NULL) {
8596 					GCGRP_REFRELE(gcgrp);
8597 					gcgrp = NULL;
8598 				}
8599 				ire_refrele(ipif_ire);
8600 				ire_refrele(save_ire);
8601 				break;
8602 			}
8603 
8604 			/* reference now held by IRE */
8605 			gcgrp = NULL;
8606 
8607 			ire->ire_marks |= ire_marks;
8608 
8609 			/*
8610 			 * Prevent sire and ipif_ire from getting deleted.
8611 			 * The newly created ire is tied to both of them via
8612 			 * the phandle and ihandle respectively.
8613 			 */
8614 			if (sire != NULL) {
8615 				IRB_REFHOLD(sire->ire_bucket);
8616 				/* Has it been removed already ? */
8617 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8618 					IRB_REFRELE(sire->ire_bucket);
8619 					ire_refrele(ipif_ire);
8620 					ire_refrele(save_ire);
8621 					break;
8622 				}
8623 			}
8624 
8625 			IRB_REFHOLD(ipif_ire->ire_bucket);
8626 			/* Has it been removed already ? */
8627 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8628 				IRB_REFRELE(ipif_ire->ire_bucket);
8629 				if (sire != NULL)
8630 					IRB_REFRELE(sire->ire_bucket);
8631 				ire_refrele(ipif_ire);
8632 				ire_refrele(save_ire);
8633 				break;
8634 			}
8635 
8636 			xmit_mp = first_mp;
8637 			/*
8638 			 * In the case of multirouting, a copy
8639 			 * of the packet is done before its sending.
8640 			 * The copy is used to attempt another
8641 			 * route resolution, in a next loop.
8642 			 */
8643 			if (ire->ire_flags & RTF_MULTIRT) {
8644 				copy_mp = copymsg(first_mp);
8645 				if (copy_mp != NULL) {
8646 					xmit_mp = copy_mp;
8647 					MULTIRT_DEBUG_TAG(first_mp);
8648 				}
8649 			}
8650 			ire_add_then_send(q, ire, xmit_mp);
8651 			ire_refrele(save_ire);
8652 
8653 			/* Assert that sire is not deleted yet. */
8654 			if (sire != NULL) {
8655 				ASSERT(sire->ire_ptpn != NULL);
8656 				IRB_REFRELE(sire->ire_bucket);
8657 			}
8658 
8659 			/* Assert that ipif_ire is not deleted yet. */
8660 			ASSERT(ipif_ire->ire_ptpn != NULL);
8661 			IRB_REFRELE(ipif_ire->ire_bucket);
8662 			ire_refrele(ipif_ire);
8663 
8664 			/*
8665 			 * If copy_mp is not NULL, multirouting was
8666 			 * requested. We loop to initiate a next
8667 			 * route resolution attempt, starting from sire.
8668 			 */
8669 			if (copy_mp != NULL) {
8670 				/*
8671 				 * Search for the next unresolved
8672 				 * multirt route.
8673 				 */
8674 				copy_mp = NULL;
8675 				ipif_ire = NULL;
8676 				ire = NULL;
8677 				multirt_resolve_next = B_TRUE;
8678 				continue;
8679 			}
8680 			if (sire != NULL)
8681 				ire_refrele(sire);
8682 			ipif_refrele(src_ipif);
8683 			ill_refrele(dst_ill);
8684 			return;
8685 		}
8686 		case IRE_IF_NORESOLVER: {
8687 			/*
8688 			 * We have what we need to build an IRE_CACHE.
8689 			 *
8690 			 * Create a new res_mp with the IP gateway address
8691 			 * in destination address in the DLPI hdr if the
8692 			 * physical length is exactly 4 bytes.
8693 			 */
8694 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8695 				uchar_t *addr;
8696 
8697 				if (gw)
8698 					addr = (uchar_t *)&gw;
8699 				else
8700 					addr = (uchar_t *)&dst;
8701 
8702 				res_mp = ill_dlur_gen(addr,
8703 				    dst_ill->ill_phys_addr_length,
8704 				    dst_ill->ill_sap,
8705 				    dst_ill->ill_sap_length);
8706 
8707 				if (res_mp == NULL) {
8708 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8709 					break;
8710 				}
8711 			} else if (dst_ill->ill_resolver_mp == NULL) {
8712 				ip1dbg(("ip_newroute: dst_ill %p "
8713 				    "for IF_NORESOLV ire %p has "
8714 				    "no ill_resolver_mp\n",
8715 				    (void *)dst_ill, (void *)ire));
8716 				break;
8717 			} else {
8718 				res_mp = NULL;
8719 			}
8720 
8721 			/*
8722 			 * TSol note: We are creating the ire cache for the
8723 			 * destination 'dst'. If 'dst' is offlink, going
8724 			 * through the first hop 'gw', the security attributes
8725 			 * of 'dst' must be set to point to the gateway
8726 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8727 			 * is possible that 'dst' is a potential gateway that is
8728 			 * referenced by some route that has some security
8729 			 * attributes. Thus in the former case, we need to do a
8730 			 * gcgrp_lookup of 'gw' while in the latter case we
8731 			 * need to do gcgrp_lookup of 'dst' itself.
8732 			 */
8733 			ga.ga_af = AF_INET;
8734 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8735 			    &ga.ga_addr);
8736 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8737 
8738 			ire = ire_create(
8739 			    (uchar_t *)&dst,		/* dest address */
8740 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8741 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8742 			    (uchar_t *)&gw,		/* gateway address */
8743 			    NULL,
8744 			    &save_ire->ire_max_frag,
8745 			    NULL,			/* Fast Path header */
8746 			    dst_ill->ill_rq,		/* recv-from queue */
8747 			    dst_ill->ill_wq,		/* send-to queue */
8748 			    IRE_CACHE,
8749 			    res_mp,
8750 			    src_ipif,
8751 			    in_ill,			/* Incoming ill */
8752 			    save_ire->ire_mask,		/* Parent mask */
8753 			    (sire != NULL) ?		/* Parent handle */
8754 				sire->ire_phandle : 0,
8755 			    save_ire->ire_ihandle,	/* Interface handle */
8756 			    (sire != NULL) ? sire->ire_flags &
8757 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8758 			    &(save_ire->ire_uinfo),
8759 			    NULL,
8760 			    gcgrp,
8761 			    ipst);
8762 
8763 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8764 				freeb(res_mp);
8765 
8766 			if (ire == NULL) {
8767 				if (gcgrp != NULL) {
8768 					GCGRP_REFRELE(gcgrp);
8769 					gcgrp = NULL;
8770 				}
8771 				ire_refrele(save_ire);
8772 				break;
8773 			}
8774 
8775 			/* reference now held by IRE */
8776 			gcgrp = NULL;
8777 
8778 			ire->ire_marks |= ire_marks;
8779 
8780 			/* Prevent save_ire from getting deleted */
8781 			IRB_REFHOLD(save_ire->ire_bucket);
8782 			/* Has it been removed already ? */
8783 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8784 				IRB_REFRELE(save_ire->ire_bucket);
8785 				ire_refrele(save_ire);
8786 				break;
8787 			}
8788 
8789 			/*
8790 			 * In the case of multirouting, a copy
8791 			 * of the packet is made before it is sent.
8792 			 * The copy is used in the next
8793 			 * loop to attempt another resolution.
8794 			 */
8795 			xmit_mp = first_mp;
8796 			if ((sire != NULL) &&
8797 			    (sire->ire_flags & RTF_MULTIRT)) {
8798 				copy_mp = copymsg(first_mp);
8799 				if (copy_mp != NULL) {
8800 					xmit_mp = copy_mp;
8801 					MULTIRT_DEBUG_TAG(first_mp);
8802 				}
8803 			}
8804 			ire_add_then_send(q, ire, xmit_mp);
8805 
8806 			/* Assert that it is not deleted yet. */
8807 			ASSERT(save_ire->ire_ptpn != NULL);
8808 			IRB_REFRELE(save_ire->ire_bucket);
8809 			ire_refrele(save_ire);
8810 
8811 			if (copy_mp != NULL) {
8812 				/*
8813 				 * If we found a (no)resolver, we ignore any
8814 				 * trailing top priority IRE_CACHE in further
8815 				 * loops. This ensures that we do not omit any
8816 				 * (no)resolver.
8817 				 * This IRE_CACHE, if any, will be processed
8818 				 * by another thread entering ip_newroute().
8819 				 * IRE_CACHE entries, if any, will be processed
8820 				 * by another thread entering ip_newroute(),
8821 				 * (upon resolver response, for instance).
8822 				 * This aims to force parallel multirt
8823 				 * resolutions as soon as a packet must be sent.
8824 				 * In the best case, after the tx of only one
8825 				 * packet, all reachable routes are resolved.
8826 				 * Otherwise, the resolution of all RTF_MULTIRT
8827 				 * routes would require several emissions.
8828 				 */
8829 				multirt_flags &= ~MULTIRT_CACHEGW;
8830 
8831 				/*
8832 				 * Search for the next unresolved multirt
8833 				 * route.
8834 				 */
8835 				copy_mp = NULL;
8836 				save_ire = NULL;
8837 				ire = NULL;
8838 				multirt_resolve_next = B_TRUE;
8839 				continue;
8840 			}
8841 
8842 			/*
8843 			 * Don't need sire anymore
8844 			 */
8845 			if (sire != NULL)
8846 				ire_refrele(sire);
8847 
8848 			ipif_refrele(src_ipif);
8849 			ill_refrele(dst_ill);
8850 			return;
8851 		}
8852 		case IRE_IF_RESOLVER:
8853 			/*
8854 			 * We can't build an IRE_CACHE yet, but at least we
8855 			 * found a resolver that can help.
8856 			 */
8857 			res_mp = dst_ill->ill_resolver_mp;
8858 			if (!OK_RESOLVER_MP(res_mp))
8859 				break;
8860 
8861 			/*
8862 			 * To be at this point in the code with a non-zero gw
8863 			 * means that dst is reachable through a gateway that
8864 			 * we have never resolved.  By changing dst to the gw
8865 			 * addr we resolve the gateway first.
8866 			 * When ire_add_then_send() tries to put the IP dg
8867 			 * to dst, it will reenter ip_newroute() at which
8868 			 * time we will find the IRE_CACHE for the gw and
8869 			 * create another IRE_CACHE in case IRE_CACHE above.
8870 			 */
8871 			if (gw != INADDR_ANY) {
8872 				/*
8873 				 * The source ipif that was determined above was
8874 				 * relative to the destination address, not the
8875 				 * gateway's. If src_ipif was not taken out of
8876 				 * the IRE_IF_RESOLVER entry, we'll need to call
8877 				 * ipif_select_source() again.
8878 				 */
8879 				if (src_ipif != ire->ire_ipif) {
8880 					ipif_refrele(src_ipif);
8881 					src_ipif = ipif_select_source(dst_ill,
8882 					    gw, zoneid);
8883 					if (src_ipif == NULL) {
8884 						if (ip_debug > 2) {
8885 							pr_addr_dbg(
8886 							    "ip_newroute: no "
8887 							    "src for gw %s ",
8888 							    AF_INET, &gw);
8889 							printf("through "
8890 							    "interface %s\n",
8891 							    dst_ill->ill_name);
8892 						}
8893 						goto icmp_err_ret;
8894 					}
8895 				}
8896 				save_dst = dst;
8897 				dst = gw;
8898 				gw = INADDR_ANY;
8899 			}
8900 
8901 			/*
8902 			 * We obtain a partial IRE_CACHE which we will pass
8903 			 * along with the resolver query.  When the response
8904 			 * comes back it will be there ready for us to add.
8905 			 * The ire_max_frag is atomically set under the
8906 			 * irebucket lock in ire_add_v[46].
8907 			 */
8908 
8909 			ire = ire_create_mp(
8910 			    (uchar_t *)&dst,		/* dest address */
8911 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8912 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8913 			    (uchar_t *)&gw,		/* gateway address */
8914 			    NULL,			/* no in_src_addr */
8915 			    NULL,			/* ire_max_frag */
8916 			    NULL,			/* Fast Path header */
8917 			    dst_ill->ill_rq,		/* recv-from queue */
8918 			    dst_ill->ill_wq,		/* send-to queue */
8919 			    IRE_CACHE,
8920 			    NULL,
8921 			    src_ipif,			/* Interface ipif */
8922 			    in_ill,			/* Incoming ILL */
8923 			    save_ire->ire_mask,		/* Parent mask */
8924 			    0,
8925 			    save_ire->ire_ihandle,	/* Interface handle */
8926 			    0,				/* flags if any */
8927 			    &(save_ire->ire_uinfo),
8928 			    NULL,
8929 			    NULL,
8930 			    ipst);
8931 
8932 			if (ire == NULL) {
8933 				ire_refrele(save_ire);
8934 				break;
8935 			}
8936 
8937 			if ((sire != NULL) &&
8938 			    (sire->ire_flags & RTF_MULTIRT)) {
8939 				copy_mp = copymsg(first_mp);
8940 				if (copy_mp != NULL)
8941 					MULTIRT_DEBUG_TAG(copy_mp);
8942 			}
8943 
8944 			ire->ire_marks |= ire_marks;
8945 
8946 			/*
8947 			 * Construct message chain for the resolver
8948 			 * of the form:
8949 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8950 			 * Packet could contain a IPSEC_OUT mp.
8951 			 *
8952 			 * NOTE : ire will be added later when the response
8953 			 * comes back from ARP. If the response does not
8954 			 * come back, ARP frees the packet. For this reason,
8955 			 * we can't REFHOLD the bucket of save_ire to prevent
8956 			 * deletions. We may not be able to REFRELE the bucket
8957 			 * if the response never comes back. Thus, before
8958 			 * adding the ire, ire_add_v4 will make sure that the
8959 			 * interface route does not get deleted. This is the
8960 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8961 			 * where we can always prevent deletions because of
8962 			 * the synchronous nature of adding IRES i.e
8963 			 * ire_add_then_send is called after creating the IRE.
8964 			 */
8965 			ASSERT(ire->ire_mp != NULL);
8966 			ire->ire_mp->b_cont = first_mp;
8967 			/* Have saved_mp handy, for cleanup if canput fails */
8968 			saved_mp = mp;
8969 			mp = copyb(res_mp);
8970 			if (mp == NULL) {
8971 				/* Prepare for cleanup */
8972 				mp = saved_mp; /* pkt */
8973 				ire_delete(ire); /* ire_mp */
8974 				ire = NULL;
8975 				ire_refrele(save_ire);
8976 				if (copy_mp != NULL) {
8977 					MULTIRT_DEBUG_UNTAG(copy_mp);
8978 					freemsg(copy_mp);
8979 					copy_mp = NULL;
8980 				}
8981 				break;
8982 			}
8983 			linkb(mp, ire->ire_mp);
8984 
8985 			/*
8986 			 * Fill in the source and dest addrs for the resolver.
8987 			 * NOTE: this depends on memory layouts imposed by
8988 			 * ill_init().
8989 			 */
8990 			areq = (areq_t *)mp->b_rptr;
8991 			addrp = (ipaddr_t *)((char *)areq +
8992 			    areq->areq_sender_addr_offset);
8993 			if (do_attach_ill) {
8994 				/*
8995 				 * This is bind to no failover case.
8996 				 * arp packet also must go out on attach_ill.
8997 				 */
8998 				ASSERT(ipha->ipha_src != NULL);
8999 				*addrp = ipha->ipha_src;
9000 			} else {
9001 				*addrp = save_ire->ire_src_addr;
9002 			}
9003 
9004 			ire_refrele(save_ire);
9005 			addrp = (ipaddr_t *)((char *)areq +
9006 			    areq->areq_target_addr_offset);
9007 			*addrp = dst;
9008 			/* Up to the resolver. */
9009 			if (canputnext(dst_ill->ill_rq) &&
9010 			    !(dst_ill->ill_arp_closing)) {
9011 				putnext(dst_ill->ill_rq, mp);
9012 				ire = NULL;
9013 				if (copy_mp != NULL) {
9014 					/*
9015 					 * If we found a resolver, we ignore
9016 					 * any trailing top priority IRE_CACHE
9017 					 * in the further loops. This ensures
9018 					 * that we do not omit any resolver.
9019 					 * IRE_CACHE entries, if any, will be
9020 					 * processed next time we enter
9021 					 * ip_newroute().
9022 					 */
9023 					multirt_flags &= ~MULTIRT_CACHEGW;
9024 					/*
9025 					 * Search for the next unresolved
9026 					 * multirt route.
9027 					 */
9028 					first_mp = copy_mp;
9029 					copy_mp = NULL;
9030 					/* Prepare the next resolution loop. */
9031 					mp = first_mp;
9032 					EXTRACT_PKT_MP(mp, first_mp,
9033 					    mctl_present);
9034 					if (mctl_present)
9035 						io = (ipsec_out_t *)
9036 						    first_mp->b_rptr;
9037 					ipha = (ipha_t *)mp->b_rptr;
9038 
9039 					ASSERT(sire != NULL);
9040 
9041 					dst = save_dst;
9042 					multirt_resolve_next = B_TRUE;
9043 					continue;
9044 				}
9045 
9046 				if (sire != NULL)
9047 					ire_refrele(sire);
9048 
9049 				/*
9050 				 * The response will come back in ip_wput
9051 				 * with db_type IRE_DB_TYPE.
9052 				 */
9053 				ipif_refrele(src_ipif);
9054 				ill_refrele(dst_ill);
9055 				return;
9056 			} else {
9057 				/* Prepare for cleanup */
9058 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9059 				    mp);
9060 				mp->b_cont = NULL;
9061 				freeb(mp); /* areq */
9062 				/*
9063 				 * this is an ire that is not added to the
9064 				 * cache. ire_freemblk will handle the release
9065 				 * of any resources associated with the ire.
9066 				 */
9067 				ire_delete(ire); /* ire_mp */
9068 				mp = saved_mp; /* pkt */
9069 				ire = NULL;
9070 				if (copy_mp != NULL) {
9071 					MULTIRT_DEBUG_UNTAG(copy_mp);
9072 					freemsg(copy_mp);
9073 					copy_mp = NULL;
9074 				}
9075 				break;
9076 			}
9077 		default:
9078 			break;
9079 		}
9080 	} while (multirt_resolve_next);
9081 
9082 	ip1dbg(("ip_newroute: dropped\n"));
9083 	/* Did this packet originate externally? */
9084 	if (mp->b_prev) {
9085 		mp->b_next = NULL;
9086 		mp->b_prev = NULL;
9087 		if (in_ill != NULL) {
9088 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9089 		} else {
9090 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9091 		}
9092 	} else {
9093 		if (dst_ill != NULL) {
9094 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9095 		} else {
9096 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9097 		}
9098 	}
9099 	ASSERT(copy_mp == NULL);
9100 	MULTIRT_DEBUG_UNTAG(first_mp);
9101 	freemsg(first_mp);
9102 	if (ire != NULL)
9103 		ire_refrele(ire);
9104 	if (sire != NULL)
9105 		ire_refrele(sire);
9106 	if (src_ipif != NULL)
9107 		ipif_refrele(src_ipif);
9108 	if (dst_ill != NULL)
9109 		ill_refrele(dst_ill);
9110 	return;
9111 
9112 icmp_err_ret:
9113 	ip1dbg(("ip_newroute: no route\n"));
9114 	if (src_ipif != NULL)
9115 		ipif_refrele(src_ipif);
9116 	if (dst_ill != NULL)
9117 		ill_refrele(dst_ill);
9118 	if (sire != NULL)
9119 		ire_refrele(sire);
9120 	/* Did this packet originate externally? */
9121 	if (mp->b_prev) {
9122 		mp->b_next = NULL;
9123 		mp->b_prev = NULL;
9124 		if (in_ill != NULL) {
9125 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9126 		} else {
9127 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9128 		}
9129 		q = WR(q);
9130 	} else {
9131 		/*
9132 		 * There is no outgoing ill, so just increment the
9133 		 * system MIB.
9134 		 */
9135 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9136 		/*
9137 		 * Since ip_wput() isn't close to finished, we fill
9138 		 * in enough of the header for credible error reporting.
9139 		 */
9140 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9141 			/* Failed */
9142 			MULTIRT_DEBUG_UNTAG(first_mp);
9143 			freemsg(first_mp);
9144 			if (ire != NULL)
9145 				ire_refrele(ire);
9146 			return;
9147 		}
9148 	}
9149 
9150 	/*
9151 	 * At this point we will have ire only if RTF_BLACKHOLE
9152 	 * or RTF_REJECT flags are set on the IRE. It will not
9153 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9154 	 */
9155 	if (ire != NULL) {
9156 		if (ire->ire_flags & RTF_BLACKHOLE) {
9157 			ire_refrele(ire);
9158 			MULTIRT_DEBUG_UNTAG(first_mp);
9159 			freemsg(first_mp);
9160 			return;
9161 		}
9162 		ire_refrele(ire);
9163 	}
9164 	if (ip_source_routed(ipha, ipst)) {
9165 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9166 		    zoneid, ipst);
9167 		return;
9168 	}
9169 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9170 }
9171 
9172 ip_opt_info_t zero_info;
9173 
9174 /*
9175  * IPv4 -
9176  * ip_newroute_ipif is called by ip_wput_multicast and
9177  * ip_rput_forward_multicast whenever we need to send
9178  * out a packet to a destination address for which we do not have specific
9179  * routing information. It is used when the packet will be sent out
9180  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9181  * socket option is set or icmp error message wants to go out on a particular
9182  * interface for a unicast packet.
9183  *
9184  * In most cases, the destination address is resolved thanks to the ipif
9185  * intrinsic resolver. However, there are some cases where the call to
9186  * ip_newroute_ipif must take into account the potential presence of
9187  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9188  * that uses the interface. This is specified through flags,
9189  * which can be a combination of:
9190  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9191  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9192  *   and flags. Additionally, the packet source address has to be set to
9193  *   the specified address. The caller is thus expected to set this flag
9194  *   if the packet has no specific source address yet.
9195  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9196  *   flag, the resulting ire will inherit the flag. All unresolved routes
9197  *   to the destination must be explored in the same call to
9198  *   ip_newroute_ipif().
9199  */
9200 static void
9201 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9202     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9203 {
9204 	areq_t	*areq;
9205 	ire_t	*ire = NULL;
9206 	mblk_t	*res_mp;
9207 	ipaddr_t *addrp;
9208 	mblk_t *first_mp;
9209 	ire_t	*save_ire = NULL;
9210 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9211 	ipif_t	*src_ipif = NULL;
9212 	ushort_t ire_marks = 0;
9213 	ill_t	*dst_ill = NULL;
9214 	boolean_t mctl_present;
9215 	ipsec_out_t *io;
9216 	ipha_t *ipha;
9217 	int	ihandle = 0;
9218 	mblk_t	*saved_mp;
9219 	ire_t   *fire = NULL;
9220 	mblk_t  *copy_mp = NULL;
9221 	boolean_t multirt_resolve_next;
9222 	ipaddr_t ipha_dst;
9223 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9224 
9225 	/*
9226 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9227 	 * here for uniformity
9228 	 */
9229 	ipif_refhold(ipif);
9230 
9231 	/*
9232 	 * This loop is run only once in most cases.
9233 	 * We loop to resolve further routes only when the destination
9234 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9235 	 */
9236 	do {
9237 		if (dst_ill != NULL) {
9238 			ill_refrele(dst_ill);
9239 			dst_ill = NULL;
9240 		}
9241 		if (src_ipif != NULL) {
9242 			ipif_refrele(src_ipif);
9243 			src_ipif = NULL;
9244 		}
9245 		multirt_resolve_next = B_FALSE;
9246 
9247 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9248 		    ipif->ipif_ill->ill_name));
9249 
9250 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9251 		if (mctl_present)
9252 			io = (ipsec_out_t *)first_mp->b_rptr;
9253 
9254 		ipha = (ipha_t *)mp->b_rptr;
9255 
9256 		/*
9257 		 * Save the packet destination address, we may need it after
9258 		 * the packet has been consumed.
9259 		 */
9260 		ipha_dst = ipha->ipha_dst;
9261 
9262 		/*
9263 		 * If the interface is a pt-pt interface we look for an
9264 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9265 		 * local_address and the pt-pt destination address. Otherwise
9266 		 * we just match the local address.
9267 		 * NOTE: dst could be different than ipha->ipha_dst in case
9268 		 * of sending igmp multicast packets over a point-to-point
9269 		 * connection.
9270 		 * Thus we must be careful enough to check ipha_dst to be a
9271 		 * multicast address, otherwise it will take xmit_if path for
9272 		 * multicast packets resulting into kernel stack overflow by
9273 		 * repeated calls to ip_newroute_ipif from ire_send().
9274 		 */
9275 		if (CLASSD(ipha_dst) &&
9276 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9277 			goto err_ret;
9278 		}
9279 
9280 		/*
9281 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9282 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9283 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9284 		 * propagate its flags to the new ire.
9285 		 */
9286 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9287 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9288 			ip2dbg(("ip_newroute_ipif: "
9289 			    "ipif_lookup_multi_ire("
9290 			    "ipif %p, dst %08x) = fire %p\n",
9291 			    (void *)ipif, ntohl(dst), (void *)fire));
9292 		}
9293 
9294 		if (mctl_present && io->ipsec_out_attach_if) {
9295 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9296 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9297 
9298 			/* Failure case frees things for us. */
9299 			if (attach_ill == NULL) {
9300 				ipif_refrele(ipif);
9301 				if (fire != NULL)
9302 					ire_refrele(fire);
9303 				return;
9304 			}
9305 
9306 			/*
9307 			 * Check if we need an ire that will not be
9308 			 * looked up by anybody else i.e. HIDDEN.
9309 			 */
9310 			if (ill_is_probeonly(attach_ill)) {
9311 				ire_marks = IRE_MARK_HIDDEN;
9312 			}
9313 			/*
9314 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9315 			 * case.
9316 			 */
9317 			dst_ill = ipif->ipif_ill;
9318 			/* attach_ill has been refheld by ip_grab_attach_ill */
9319 			ASSERT(dst_ill == attach_ill);
9320 		} else {
9321 			/*
9322 			 * If this is set by IP_XMIT_IF, then make sure that
9323 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9324 			 * specified ill.
9325 			 */
9326 			ASSERT((connp == NULL) ||
9327 			    (connp->conn_xmit_if_ill == NULL) ||
9328 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9329 			/*
9330 			 * If the interface belongs to an interface group,
9331 			 * make sure the next possible interface in the group
9332 			 * is used.  This encourages load spreading among
9333 			 * peers in an interface group.
9334 			 * Note: load spreading is disabled for RTF_MULTIRT
9335 			 * routes.
9336 			 */
9337 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9338 			    (fire->ire_flags & RTF_MULTIRT)) {
9339 				/*
9340 				 * Don't perform outbound load spreading
9341 				 * in the case of an RTF_MULTIRT issued route,
9342 				 * we actually typically want to replicate
9343 				 * outgoing packets through particular
9344 				 * interfaces.
9345 				 */
9346 				dst_ill = ipif->ipif_ill;
9347 				ill_refhold(dst_ill);
9348 			} else {
9349 				dst_ill = ip_newroute_get_dst_ill(
9350 				    ipif->ipif_ill);
9351 			}
9352 			if (dst_ill == NULL) {
9353 				if (ip_debug > 2) {
9354 					pr_addr_dbg("ip_newroute_ipif: "
9355 					    "no dst ill for dst %s\n",
9356 					    AF_INET, &dst);
9357 				}
9358 				goto err_ret;
9359 			}
9360 		}
9361 
9362 		/*
9363 		 * Pick a source address preferring non-deprecated ones.
9364 		 * Unlike ip_newroute, we don't do any source address
9365 		 * selection here since for multicast it really does not help
9366 		 * in inbound load spreading as in the unicast case.
9367 		 */
9368 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9369 		    (fire->ire_flags & RTF_SETSRC)) {
9370 			/*
9371 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9372 			 * on that interface. This ire has RTF_SETSRC flag, so
9373 			 * the source address of the packet must be changed.
9374 			 * Check that the ipif matching the requested source
9375 			 * address still exists.
9376 			 */
9377 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9378 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9379 		}
9380 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9381 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9382 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9383 		    (src_ipif == NULL)) {
9384 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9385 			if (src_ipif == NULL) {
9386 				if (ip_debug > 2) {
9387 					/* ip1dbg */
9388 					pr_addr_dbg("ip_newroute_ipif: "
9389 					    "no src for dst %s",
9390 					    AF_INET, &dst);
9391 				}
9392 				ip1dbg((" through interface %s\n",
9393 				    dst_ill->ill_name));
9394 				goto err_ret;
9395 			}
9396 			ipif_refrele(ipif);
9397 			ipif = src_ipif;
9398 			ipif_refhold(ipif);
9399 		}
9400 		if (src_ipif == NULL) {
9401 			src_ipif = ipif;
9402 			ipif_refhold(src_ipif);
9403 		}
9404 
9405 		/*
9406 		 * Assign a source address while we have the conn.
9407 		 * We can't have ip_wput_ire pick a source address when the
9408 		 * packet returns from arp since conn_unspec_src might be set
9409 		 * and we loose the conn when going through arp.
9410 		 */
9411 		if (ipha->ipha_src == INADDR_ANY &&
9412 		    (connp == NULL || !connp->conn_unspec_src)) {
9413 			ipha->ipha_src = src_ipif->ipif_src_addr;
9414 		}
9415 
9416 		/*
9417 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9418 		 * interface does not have an interface ire.
9419 		 * Example: Thousands of mobileip PPP interfaces to mobile
9420 		 * nodes. We don't want to create interface ires because
9421 		 * packets from other mobile nodes must not take the route
9422 		 * via interface ires to the visiting mobile node without
9423 		 * going through the home agent, in absence of mobileip
9424 		 * route optimization.
9425 		 */
9426 		if (CLASSD(ipha_dst) && (connp == NULL ||
9427 		    connp->conn_xmit_if_ill == NULL) &&
9428 		    infop->ip_opt_ill_index == 0) {
9429 			/* ipif_to_ire returns an held ire */
9430 			ire = ipif_to_ire(ipif);
9431 			if (ire == NULL)
9432 				goto err_ret;
9433 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9434 				goto err_ret;
9435 			/*
9436 			 * ihandle is needed when the ire is added to
9437 			 * cache table.
9438 			 */
9439 			save_ire = ire;
9440 			ihandle = save_ire->ire_ihandle;
9441 
9442 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9443 			    "flags %04x\n",
9444 			    (void *)ire, (void *)ipif, flags));
9445 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9446 			    (fire->ire_flags & RTF_MULTIRT)) {
9447 				/*
9448 				 * As requested by flags, an IRE_OFFSUBNET was
9449 				 * looked up on that interface. This ire has
9450 				 * RTF_MULTIRT flag, so the resolution loop will
9451 				 * be re-entered to resolve additional routes on
9452 				 * other interfaces. For that purpose, a copy of
9453 				 * the packet is performed at this point.
9454 				 */
9455 				fire->ire_last_used_time = lbolt;
9456 				copy_mp = copymsg(first_mp);
9457 				if (copy_mp) {
9458 					MULTIRT_DEBUG_TAG(copy_mp);
9459 				}
9460 			}
9461 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9462 			    (fire->ire_flags & RTF_SETSRC)) {
9463 				/*
9464 				 * As requested by flags, an IRE_OFFSUBET was
9465 				 * looked up on that interface. This ire has
9466 				 * RTF_SETSRC flag, so the source address of the
9467 				 * packet must be changed.
9468 				 */
9469 				ipha->ipha_src = fire->ire_src_addr;
9470 			}
9471 		} else {
9472 			ASSERT((connp == NULL) ||
9473 			    (connp->conn_xmit_if_ill != NULL) ||
9474 			    (connp->conn_dontroute) ||
9475 			    infop->ip_opt_ill_index != 0);
9476 			/*
9477 			 * The only ways we can come here are:
9478 			 * 1) IP_XMIT_IF socket option is set
9479 			 * 2) ICMP error message generated from
9480 			 *    ip_mrtun_forward() routine and it needs
9481 			 *    to go through the specified ill.
9482 			 * 3) SO_DONTROUTE socket option is set
9483 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9484 			 * In all cases, the new ire will not be added
9485 			 * into cache table.
9486 			 */
9487 			ire_marks |= IRE_MARK_NOADD;
9488 		}
9489 
9490 		switch (ipif->ipif_net_type) {
9491 		case IRE_IF_NORESOLVER: {
9492 			/* We have what we need to build an IRE_CACHE. */
9493 			mblk_t	*res_mp;
9494 
9495 			/*
9496 			 * Create a new res_mp with the
9497 			 * IP gateway address as destination address in the
9498 			 * DLPI hdr if the physical length is exactly 4 bytes.
9499 			 */
9500 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9501 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9502 				    dst_ill->ill_phys_addr_length,
9503 				    dst_ill->ill_sap,
9504 				    dst_ill->ill_sap_length);
9505 			} else if (dst_ill->ill_resolver_mp == NULL) {
9506 				ip1dbg(("ip_newroute: dst_ill %p "
9507 				    "for IF_NORESOLV ire %p has "
9508 				    "no ill_resolver_mp\n",
9509 				    (void *)dst_ill, (void *)ire));
9510 				break;
9511 			} else {
9512 				/* use the value set in ip_ll_subnet_defaults */
9513 				res_mp = ill_dlur_gen(NULL,
9514 				    dst_ill->ill_phys_addr_length,
9515 				    dst_ill->ill_sap,
9516 				    dst_ill->ill_sap_length);
9517 			}
9518 
9519 			if (res_mp == NULL)
9520 				break;
9521 			/*
9522 			 * The new ire inherits the IRE_OFFSUBNET flags
9523 			 * and source address, if this was requested.
9524 			 */
9525 			ire = ire_create(
9526 			    (uchar_t *)&dst,		/* dest address */
9527 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9528 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9529 			    NULL,			/* gateway address */
9530 			    NULL,
9531 			    &ipif->ipif_mtu,
9532 			    NULL,			/* Fast Path header */
9533 			    dst_ill->ill_rq,		/* recv-from queue */
9534 			    dst_ill->ill_wq,		/* send-to queue */
9535 			    IRE_CACHE,
9536 			    res_mp,
9537 			    src_ipif,
9538 			    NULL,
9539 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9540 			    (fire != NULL) ?		/* Parent handle */
9541 				fire->ire_phandle : 0,
9542 			    ihandle,			/* Interface handle */
9543 			    (fire != NULL) ?
9544 				(fire->ire_flags &
9545 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9546 			    (save_ire == NULL ? &ire_uinfo_null :
9547 				&save_ire->ire_uinfo),
9548 			    NULL,
9549 			    NULL,
9550 			    ipst);
9551 
9552 			freeb(res_mp);
9553 
9554 			if (ire == NULL) {
9555 				if (save_ire != NULL)
9556 					ire_refrele(save_ire);
9557 				break;
9558 			}
9559 
9560 			ire->ire_marks |= ire_marks;
9561 
9562 			/*
9563 			 * If IRE_MARK_NOADD is set then we need to convert
9564 			 * the max_fragp to a useable value now. This is
9565 			 * normally done in ire_add_v[46]. We also need to
9566 			 * associate the ire with an nce (normally would be
9567 			 * done in ip_wput_nondata()).
9568 			 *
9569 			 * Note that IRE_MARK_NOADD packets created here
9570 			 * do not have a non-null ire_mp pointer. The null
9571 			 * value of ire_bucket indicates that they were
9572 			 * never added.
9573 			 */
9574 			if (ire->ire_marks & IRE_MARK_NOADD) {
9575 				uint_t  max_frag;
9576 
9577 				max_frag = *ire->ire_max_fragp;
9578 				ire->ire_max_fragp = NULL;
9579 				ire->ire_max_frag = max_frag;
9580 
9581 				if ((ire->ire_nce = ndp_lookup_v4(
9582 				    ire_to_ill(ire),
9583 				    (ire->ire_gateway_addr != INADDR_ANY ?
9584 				    &ire->ire_gateway_addr : &ire->ire_addr),
9585 				    B_FALSE)) == NULL) {
9586 					if (save_ire != NULL)
9587 						ire_refrele(save_ire);
9588 					break;
9589 				}
9590 				ASSERT(ire->ire_nce->nce_state ==
9591 				    ND_REACHABLE);
9592 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9593 			}
9594 
9595 			/* Prevent save_ire from getting deleted */
9596 			if (save_ire != NULL) {
9597 				IRB_REFHOLD(save_ire->ire_bucket);
9598 				/* Has it been removed already ? */
9599 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9600 					IRB_REFRELE(save_ire->ire_bucket);
9601 					ire_refrele(save_ire);
9602 					break;
9603 				}
9604 			}
9605 
9606 			ire_add_then_send(q, ire, first_mp);
9607 
9608 			/* Assert that save_ire is not deleted yet. */
9609 			if (save_ire != NULL) {
9610 				ASSERT(save_ire->ire_ptpn != NULL);
9611 				IRB_REFRELE(save_ire->ire_bucket);
9612 				ire_refrele(save_ire);
9613 				save_ire = NULL;
9614 			}
9615 			if (fire != NULL) {
9616 				ire_refrele(fire);
9617 				fire = NULL;
9618 			}
9619 
9620 			/*
9621 			 * the resolution loop is re-entered if this
9622 			 * was requested through flags and if we
9623 			 * actually are in a multirouting case.
9624 			 */
9625 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9626 				boolean_t need_resolve =
9627 				    ire_multirt_need_resolve(ipha_dst,
9628 					MBLK_GETLABEL(copy_mp), ipst);
9629 				if (!need_resolve) {
9630 					MULTIRT_DEBUG_UNTAG(copy_mp);
9631 					freemsg(copy_mp);
9632 					copy_mp = NULL;
9633 				} else {
9634 					/*
9635 					 * ipif_lookup_group() calls
9636 					 * ire_lookup_multi() that uses
9637 					 * ire_ftable_lookup() to find
9638 					 * an IRE_INTERFACE for the group.
9639 					 * In the multirt case,
9640 					 * ire_lookup_multi() then invokes
9641 					 * ire_multirt_lookup() to find
9642 					 * the next resolvable ire.
9643 					 * As a result, we obtain an new
9644 					 * interface, derived from the
9645 					 * next ire.
9646 					 */
9647 					ipif_refrele(ipif);
9648 					ipif = ipif_lookup_group(ipha_dst,
9649 					    zoneid, ipst);
9650 					ip2dbg(("ip_newroute_ipif: "
9651 					    "multirt dst %08x, ipif %p\n",
9652 					    htonl(dst), (void *)ipif));
9653 					if (ipif != NULL) {
9654 						mp = copy_mp;
9655 						copy_mp = NULL;
9656 						multirt_resolve_next = B_TRUE;
9657 						continue;
9658 					} else {
9659 						freemsg(copy_mp);
9660 					}
9661 				}
9662 			}
9663 			if (ipif != NULL)
9664 				ipif_refrele(ipif);
9665 			ill_refrele(dst_ill);
9666 			ipif_refrele(src_ipif);
9667 			return;
9668 		}
9669 		case IRE_IF_RESOLVER:
9670 			/*
9671 			 * We can't build an IRE_CACHE yet, but at least
9672 			 * we found a resolver that can help.
9673 			 */
9674 			res_mp = dst_ill->ill_resolver_mp;
9675 			if (!OK_RESOLVER_MP(res_mp))
9676 				break;
9677 
9678 			/*
9679 			 * We obtain a partial IRE_CACHE which we will pass
9680 			 * along with the resolver query.  When the response
9681 			 * comes back it will be there ready for us to add.
9682 			 * The new ire inherits the IRE_OFFSUBNET flags
9683 			 * and source address, if this was requested.
9684 			 * The ire_max_frag is atomically set under the
9685 			 * irebucket lock in ire_add_v[46]. Only in the
9686 			 * case of IRE_MARK_NOADD, we set it here itself.
9687 			 */
9688 			ire = ire_create_mp(
9689 			    (uchar_t *)&dst,		/* dest address */
9690 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9691 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9692 			    NULL,			/* gateway address */
9693 			    NULL,			/* no in_src_addr */
9694 			    (ire_marks & IRE_MARK_NOADD) ?
9695 				ipif->ipif_mtu : 0,	/* max_frag */
9696 			    NULL,			/* Fast path header */
9697 			    dst_ill->ill_rq,		/* recv-from queue */
9698 			    dst_ill->ill_wq,		/* send-to queue */
9699 			    IRE_CACHE,
9700 			    NULL,	/* let ire_nce_init figure res_mp out */
9701 			    src_ipif,
9702 			    NULL,
9703 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9704 			    (fire != NULL) ?		/* Parent handle */
9705 				fire->ire_phandle : 0,
9706 			    ihandle,			/* Interface handle */
9707 			    (fire != NULL) ?		/* flags if any */
9708 				(fire->ire_flags &
9709 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9710 			    (save_ire == NULL ? &ire_uinfo_null :
9711 				&save_ire->ire_uinfo),
9712 			    NULL,
9713 			    NULL,
9714 			    ipst);
9715 
9716 			if (save_ire != NULL) {
9717 				ire_refrele(save_ire);
9718 				save_ire = NULL;
9719 			}
9720 			if (ire == NULL)
9721 				break;
9722 
9723 			ire->ire_marks |= ire_marks;
9724 			/*
9725 			 * Construct message chain for the resolver of the
9726 			 * form:
9727 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9728 			 *
9729 			 * NOTE : ire will be added later when the response
9730 			 * comes back from ARP. If the response does not
9731 			 * come back, ARP frees the packet. For this reason,
9732 			 * we can't REFHOLD the bucket of save_ire to prevent
9733 			 * deletions. We may not be able to REFRELE the
9734 			 * bucket if the response never comes back.
9735 			 * Thus, before adding the ire, ire_add_v4 will make
9736 			 * sure that the interface route does not get deleted.
9737 			 * This is the only case unlike ip_newroute_v6,
9738 			 * ip_newroute_ipif_v6 where we can always prevent
9739 			 * deletions because ire_add_then_send is called after
9740 			 * creating the IRE.
9741 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9742 			 * does not add this IRE into the IRE CACHE.
9743 			 */
9744 			ASSERT(ire->ire_mp != NULL);
9745 			ire->ire_mp->b_cont = first_mp;
9746 			/* Have saved_mp handy, for cleanup if canput fails */
9747 			saved_mp = mp;
9748 			mp = copyb(res_mp);
9749 			if (mp == NULL) {
9750 				/* Prepare for cleanup */
9751 				mp = saved_mp; /* pkt */
9752 				ire_delete(ire); /* ire_mp */
9753 				ire = NULL;
9754 				if (copy_mp != NULL) {
9755 					MULTIRT_DEBUG_UNTAG(copy_mp);
9756 					freemsg(copy_mp);
9757 					copy_mp = NULL;
9758 				}
9759 				break;
9760 			}
9761 			linkb(mp, ire->ire_mp);
9762 
9763 			/*
9764 			 * Fill in the source and dest addrs for the resolver.
9765 			 * NOTE: this depends on memory layouts imposed by
9766 			 * ill_init().
9767 			 */
9768 			areq = (areq_t *)mp->b_rptr;
9769 			addrp = (ipaddr_t *)((char *)areq +
9770 			    areq->areq_sender_addr_offset);
9771 			*addrp = ire->ire_src_addr;
9772 			addrp = (ipaddr_t *)((char *)areq +
9773 			    areq->areq_target_addr_offset);
9774 			*addrp = dst;
9775 			/* Up to the resolver. */
9776 			if (canputnext(dst_ill->ill_rq) &&
9777 			    !(dst_ill->ill_arp_closing)) {
9778 				putnext(dst_ill->ill_rq, mp);
9779 				/*
9780 				 * The response will come back in ip_wput
9781 				 * with db_type IRE_DB_TYPE.
9782 				 */
9783 			} else {
9784 				mp->b_cont = NULL;
9785 				freeb(mp); /* areq */
9786 				ire_delete(ire); /* ire_mp */
9787 				saved_mp->b_next = NULL;
9788 				saved_mp->b_prev = NULL;
9789 				freemsg(first_mp); /* pkt */
9790 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9791 			}
9792 
9793 			if (fire != NULL) {
9794 				ire_refrele(fire);
9795 				fire = NULL;
9796 			}
9797 
9798 
9799 			/*
9800 			 * The resolution loop is re-entered if this was
9801 			 * requested through flags and we actually are
9802 			 * in a multirouting case.
9803 			 */
9804 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9805 				boolean_t need_resolve =
9806 				    ire_multirt_need_resolve(ipha_dst,
9807 					MBLK_GETLABEL(copy_mp), ipst);
9808 				if (!need_resolve) {
9809 					MULTIRT_DEBUG_UNTAG(copy_mp);
9810 					freemsg(copy_mp);
9811 					copy_mp = NULL;
9812 				} else {
9813 					/*
9814 					 * ipif_lookup_group() calls
9815 					 * ire_lookup_multi() that uses
9816 					 * ire_ftable_lookup() to find
9817 					 * an IRE_INTERFACE for the group.
9818 					 * In the multirt case,
9819 					 * ire_lookup_multi() then invokes
9820 					 * ire_multirt_lookup() to find
9821 					 * the next resolvable ire.
9822 					 * As a result, we obtain an new
9823 					 * interface, derived from the
9824 					 * next ire.
9825 					 */
9826 					ipif_refrele(ipif);
9827 					ipif = ipif_lookup_group(ipha_dst,
9828 					    zoneid, ipst);
9829 					if (ipif != NULL) {
9830 						mp = copy_mp;
9831 						copy_mp = NULL;
9832 						multirt_resolve_next = B_TRUE;
9833 						continue;
9834 					} else {
9835 						freemsg(copy_mp);
9836 					}
9837 				}
9838 			}
9839 			if (ipif != NULL)
9840 				ipif_refrele(ipif);
9841 			ill_refrele(dst_ill);
9842 			ipif_refrele(src_ipif);
9843 			return;
9844 		default:
9845 			break;
9846 		}
9847 	} while (multirt_resolve_next);
9848 
9849 err_ret:
9850 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9851 	if (fire != NULL)
9852 		ire_refrele(fire);
9853 	ipif_refrele(ipif);
9854 	/* Did this packet originate externally? */
9855 	if (dst_ill != NULL)
9856 		ill_refrele(dst_ill);
9857 	if (src_ipif != NULL)
9858 		ipif_refrele(src_ipif);
9859 	if (mp->b_prev || mp->b_next) {
9860 		mp->b_next = NULL;
9861 		mp->b_prev = NULL;
9862 	} else {
9863 		/*
9864 		 * Since ip_wput() isn't close to finished, we fill
9865 		 * in enough of the header for credible error reporting.
9866 		 */
9867 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9868 			/* Failed */
9869 			freemsg(first_mp);
9870 			if (ire != NULL)
9871 				ire_refrele(ire);
9872 			return;
9873 		}
9874 	}
9875 	/*
9876 	 * At this point we will have ire only if RTF_BLACKHOLE
9877 	 * or RTF_REJECT flags are set on the IRE. It will not
9878 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9879 	 */
9880 	if (ire != NULL) {
9881 		if (ire->ire_flags & RTF_BLACKHOLE) {
9882 			ire_refrele(ire);
9883 			freemsg(first_mp);
9884 			return;
9885 		}
9886 		ire_refrele(ire);
9887 	}
9888 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9889 }
9890 
9891 /* Name/Value Table Lookup Routine */
9892 char *
9893 ip_nv_lookup(nv_t *nv, int value)
9894 {
9895 	if (!nv)
9896 		return (NULL);
9897 	for (; nv->nv_name; nv++) {
9898 		if (nv->nv_value == value)
9899 			return (nv->nv_name);
9900 	}
9901 	return ("unknown");
9902 }
9903 
9904 /*
9905  * This is a module open, i.e. this is a control stream for access
9906  * to a DLPI device.  We allocate an ill_t as the instance data in
9907  * this case.
9908  */
9909 int
9910 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9911 {
9912 	ill_t	*ill;
9913 	int	err;
9914 	zoneid_t zoneid;
9915 	netstack_t *ns;
9916 	ip_stack_t *ipst;
9917 
9918 	/*
9919 	 * Prevent unprivileged processes from pushing IP so that
9920 	 * they can't send raw IP.
9921 	 */
9922 	if (secpolicy_net_rawaccess(credp) != 0)
9923 		return (EPERM);
9924 
9925 	ns = netstack_find_by_cred(credp);
9926 	ASSERT(ns != NULL);
9927 	ipst = ns->netstack_ip;
9928 	ASSERT(ipst != NULL);
9929 
9930 	/*
9931 	 * For exclusive stacks we set the zoneid to zero
9932 	 * to make IP operate as if in the global zone.
9933 	 */
9934 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9935 		zoneid = GLOBAL_ZONEID;
9936 	else
9937 		zoneid = crgetzoneid(credp);
9938 
9939 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9940 	q->q_ptr = WR(q)->q_ptr = ill;
9941 	ill->ill_ipst = ipst;
9942 	ill->ill_zoneid = zoneid;
9943 
9944 	/*
9945 	 * ill_init initializes the ill fields and then sends down
9946 	 * down a DL_INFO_REQ after calling qprocson.
9947 	 */
9948 	err = ill_init(q, ill);
9949 	if (err != 0) {
9950 		mi_free(ill);
9951 		netstack_rele(ipst->ips_netstack);
9952 		q->q_ptr = NULL;
9953 		WR(q)->q_ptr = NULL;
9954 		return (err);
9955 	}
9956 
9957 	/* ill_init initializes the ipsq marking this thread as writer */
9958 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9959 	/* Wait for the DL_INFO_ACK */
9960 	mutex_enter(&ill->ill_lock);
9961 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9962 		/*
9963 		 * Return value of 0 indicates a pending signal.
9964 		 */
9965 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9966 		if (err == 0) {
9967 			mutex_exit(&ill->ill_lock);
9968 			(void) ip_close(q, 0);
9969 			return (EINTR);
9970 		}
9971 	}
9972 	mutex_exit(&ill->ill_lock);
9973 
9974 	/*
9975 	 * ip_rput_other could have set an error  in ill_error on
9976 	 * receipt of M_ERROR.
9977 	 */
9978 
9979 	err = ill->ill_error;
9980 	if (err != 0) {
9981 		(void) ip_close(q, 0);
9982 		return (err);
9983 	}
9984 
9985 	ill->ill_credp = credp;
9986 	crhold(credp);
9987 
9988 	mutex_enter(&ipst->ips_ip_mi_lock);
9989 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9990 	    credp);
9991 	mutex_exit(&ipst->ips_ip_mi_lock);
9992 	if (err) {
9993 		(void) ip_close(q, 0);
9994 		return (err);
9995 	}
9996 	return (0);
9997 }
9998 
9999 /* IP open routine. */
10000 int
10001 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
10002 {
10003 	conn_t 		*connp;
10004 	major_t		maj;
10005 	zoneid_t	zoneid;
10006 	netstack_t	*ns;
10007 	ip_stack_t	*ipst;
10008 
10009 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
10010 
10011 	/* Allow reopen. */
10012 	if (q->q_ptr != NULL)
10013 		return (0);
10014 
10015 	if (sflag & MODOPEN) {
10016 		/* This is a module open */
10017 		return (ip_modopen(q, devp, flag, sflag, credp));
10018 	}
10019 
10020 	ns = netstack_find_by_cred(credp);
10021 	ASSERT(ns != NULL);
10022 	ipst = ns->netstack_ip;
10023 	ASSERT(ipst != NULL);
10024 
10025 	/*
10026 	 * For exclusive stacks we set the zoneid to zero
10027 	 * to make IP operate as if in the global zone.
10028 	 */
10029 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10030 		zoneid = GLOBAL_ZONEID;
10031 	else
10032 		zoneid = crgetzoneid(credp);
10033 
10034 	/*
10035 	 * We are opening as a device. This is an IP client stream, and we
10036 	 * allocate an conn_t as the instance data.
10037 	 */
10038 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10039 
10040 	/*
10041 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10042 	 * done by netstack_find_by_cred()
10043 	 */
10044 	netstack_rele(ipst->ips_netstack);
10045 
10046 	connp->conn_zoneid = zoneid;
10047 
10048 	connp->conn_upq = q;
10049 	q->q_ptr = WR(q)->q_ptr = connp;
10050 
10051 	if (flag & SO_SOCKSTR)
10052 		connp->conn_flags |= IPCL_SOCKET;
10053 
10054 	/* Minor tells us which /dev entry was opened */
10055 	if (geteminor(*devp) == IPV6_MINOR) {
10056 		connp->conn_flags |= IPCL_ISV6;
10057 		connp->conn_af_isv6 = B_TRUE;
10058 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10059 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10060 	} else {
10061 		connp->conn_af_isv6 = B_FALSE;
10062 		connp->conn_pkt_isv6 = B_FALSE;
10063 	}
10064 
10065 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10066 		/* CONN_DEC_REF takes care of netstack_rele() */
10067 		q->q_ptr = WR(q)->q_ptr = NULL;
10068 		CONN_DEC_REF(connp);
10069 		return (EBUSY);
10070 	}
10071 
10072 	maj = getemajor(*devp);
10073 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10074 
10075 	/*
10076 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10077 	 */
10078 	connp->conn_cred = credp;
10079 	crhold(connp->conn_cred);
10080 
10081 	/*
10082 	 * If the caller has the process-wide flag set, then default to MAC
10083 	 * exempt mode.  This allows read-down to unlabeled hosts.
10084 	 */
10085 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10086 		connp->conn_mac_exempt = B_TRUE;
10087 
10088 	/*
10089 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10090 	 * administrative ops.  In these cases, we just need a normal conn_t
10091 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10092 	 * an error will be returned.
10093 	 */
10094 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10095 		connp->conn_rq = q;
10096 		connp->conn_wq = WR(q);
10097 	} else {
10098 		connp->conn_ulp = IPPROTO_SCTP;
10099 		connp->conn_rq = connp->conn_wq = NULL;
10100 	}
10101 	/* Non-zero default values */
10102 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10103 
10104 	/*
10105 	 * Make the conn globally visible to walkers
10106 	 */
10107 	mutex_enter(&connp->conn_lock);
10108 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10109 	mutex_exit(&connp->conn_lock);
10110 	ASSERT(connp->conn_ref == 1);
10111 
10112 	qprocson(q);
10113 
10114 	return (0);
10115 }
10116 
10117 /*
10118  * Change q_qinfo based on the value of isv6.
10119  * This can not called on an ill queue.
10120  * Note that there is no race since either q_qinfo works for conn queues - it
10121  * is just an optimization to enter the best wput routine directly.
10122  */
10123 void
10124 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10125 {
10126 	ASSERT(q->q_flag & QREADR);
10127 	ASSERT(WR(q)->q_next == NULL);
10128 	ASSERT(q->q_ptr != NULL);
10129 
10130 	if (minor == IPV6_MINOR)  {
10131 		if (bump_mib) {
10132 			BUMP_MIB(&ipst->ips_ip6_mib,
10133 			    ipIfStatsOutSwitchIPVersion);
10134 		}
10135 		q->q_qinfo = &rinit_ipv6;
10136 		WR(q)->q_qinfo = &winit_ipv6;
10137 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10138 	} else {
10139 		if (bump_mib) {
10140 			BUMP_MIB(&ipst->ips_ip_mib,
10141 			    ipIfStatsOutSwitchIPVersion);
10142 		}
10143 		q->q_qinfo = &iprinit;
10144 		WR(q)->q_qinfo = &ipwinit;
10145 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10146 	}
10147 
10148 }
10149 
10150 /*
10151  * See if IPsec needs loading because of the options in mp.
10152  */
10153 static boolean_t
10154 ipsec_opt_present(mblk_t *mp)
10155 {
10156 	uint8_t *optcp, *next_optcp, *opt_endcp;
10157 	struct opthdr *opt;
10158 	struct T_opthdr *topt;
10159 	int opthdr_len;
10160 	t_uscalar_t optname, optlevel;
10161 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10162 	ipsec_req_t *ipsr;
10163 
10164 	/*
10165 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10166 	 * return TRUE.
10167 	 */
10168 
10169 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10170 	opt_endcp = optcp + tor->OPT_length;
10171 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10172 		opthdr_len = sizeof (struct T_opthdr);
10173 	} else {		/* O_OPTMGMT_REQ */
10174 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10175 		opthdr_len = sizeof (struct opthdr);
10176 	}
10177 	for (; optcp < opt_endcp; optcp = next_optcp) {
10178 		if (optcp + opthdr_len > opt_endcp)
10179 			return (B_FALSE);	/* Not enough option header. */
10180 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10181 			topt = (struct T_opthdr *)optcp;
10182 			optlevel = topt->level;
10183 			optname = topt->name;
10184 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10185 		} else {
10186 			opt = (struct opthdr *)optcp;
10187 			optlevel = opt->level;
10188 			optname = opt->name;
10189 			next_optcp = optcp + opthdr_len +
10190 			    _TPI_ALIGN_OPT(opt->len);
10191 		}
10192 		if ((next_optcp < optcp) || /* wraparound pointer space */
10193 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10194 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10195 			return (B_FALSE); /* bad option buffer */
10196 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10197 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10198 			/*
10199 			 * Check to see if it's an all-bypass or all-zeroes
10200 			 * IPsec request.  Don't bother loading IPsec if
10201 			 * the socket doesn't want to use it.  (A good example
10202 			 * is a bypass request.)
10203 			 *
10204 			 * Basically, if any of the non-NEVER bits are set,
10205 			 * load IPsec.
10206 			 */
10207 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10208 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10209 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10210 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10211 			    != 0)
10212 				return (B_TRUE);
10213 		}
10214 	}
10215 	return (B_FALSE);
10216 }
10217 
10218 /*
10219  * If conn is is waiting for ipsec to finish loading, kick it.
10220  */
10221 /* ARGSUSED */
10222 static void
10223 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10224 {
10225 	t_scalar_t	optreq_prim;
10226 	mblk_t		*mp;
10227 	cred_t		*cr;
10228 	int		err = 0;
10229 
10230 	/*
10231 	 * This function is called, after ipsec loading is complete.
10232 	 * Since IP checks exclusively and atomically (i.e it prevents
10233 	 * ipsec load from completing until ip_optcom_req completes)
10234 	 * whether ipsec load is complete, there cannot be a race with IP
10235 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10236 	 */
10237 	mutex_enter(&connp->conn_lock);
10238 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10239 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10240 		mp = connp->conn_ipsec_opt_mp;
10241 		connp->conn_ipsec_opt_mp = NULL;
10242 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10243 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10244 		mutex_exit(&connp->conn_lock);
10245 
10246 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10247 
10248 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10249 		if (optreq_prim == T_OPTMGMT_REQ) {
10250 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10251 			    &ip_opt_obj);
10252 		} else {
10253 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10254 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10255 			    &ip_opt_obj);
10256 		}
10257 		if (err != EINPROGRESS)
10258 			CONN_OPER_PENDING_DONE(connp);
10259 		return;
10260 	}
10261 	mutex_exit(&connp->conn_lock);
10262 }
10263 
10264 /*
10265  * Called from the ipsec_loader thread, outside any perimeter, to tell
10266  * ip qenable any of the queues waiting for the ipsec loader to
10267  * complete.
10268  */
10269 void
10270 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10271 {
10272 	netstack_t *ns = ipss->ipsec_netstack;
10273 
10274 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10275 }
10276 
10277 /*
10278  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10279  * determines the grp on which it has to become exclusive, queues the mp
10280  * and sq draining restarts the optmgmt
10281  */
10282 static boolean_t
10283 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10284 {
10285 	conn_t *connp = Q_TO_CONN(q);
10286 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10287 
10288 	/*
10289 	 * Take IPsec requests and treat them special.
10290 	 */
10291 	if (ipsec_opt_present(mp)) {
10292 		/* First check if IPsec is loaded. */
10293 		mutex_enter(&ipss->ipsec_loader_lock);
10294 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10295 			mutex_exit(&ipss->ipsec_loader_lock);
10296 			return (B_FALSE);
10297 		}
10298 		mutex_enter(&connp->conn_lock);
10299 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10300 
10301 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10302 		connp->conn_ipsec_opt_mp = mp;
10303 		mutex_exit(&connp->conn_lock);
10304 		mutex_exit(&ipss->ipsec_loader_lock);
10305 
10306 		ipsec_loader_loadnow(ipss);
10307 		return (B_TRUE);
10308 	}
10309 	return (B_FALSE);
10310 }
10311 
10312 /*
10313  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10314  * all of them are copied to the conn_t. If the req is "zero", the policy is
10315  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10316  * fields.
10317  * We keep only the latest setting of the policy and thus policy setting
10318  * is not incremental/cumulative.
10319  *
10320  * Requests to set policies with multiple alternative actions will
10321  * go through a different API.
10322  */
10323 int
10324 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10325 {
10326 	uint_t ah_req = 0;
10327 	uint_t esp_req = 0;
10328 	uint_t se_req = 0;
10329 	ipsec_selkey_t sel;
10330 	ipsec_act_t *actp = NULL;
10331 	uint_t nact;
10332 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10333 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10334 	ipsec_policy_root_t *pr;
10335 	ipsec_policy_head_t *ph;
10336 	int fam;
10337 	boolean_t is_pol_reset;
10338 	int error = 0;
10339 	netstack_t	*ns = connp->conn_netstack;
10340 	ip_stack_t	*ipst = ns->netstack_ip;
10341 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10342 
10343 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10344 
10345 	/*
10346 	 * The IP_SEC_OPT option does not allow variable length parameters,
10347 	 * hence a request cannot be NULL.
10348 	 */
10349 	if (req == NULL)
10350 		return (EINVAL);
10351 
10352 	ah_req = req->ipsr_ah_req;
10353 	esp_req = req->ipsr_esp_req;
10354 	se_req = req->ipsr_self_encap_req;
10355 
10356 	/*
10357 	 * Are we dealing with a request to reset the policy (i.e.
10358 	 * zero requests).
10359 	 */
10360 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10361 	    (esp_req & REQ_MASK) == 0 &&
10362 	    (se_req & REQ_MASK) == 0);
10363 
10364 	if (!is_pol_reset) {
10365 		/*
10366 		 * If we couldn't load IPsec, fail with "protocol
10367 		 * not supported".
10368 		 * IPsec may not have been loaded for a request with zero
10369 		 * policies, so we don't fail in this case.
10370 		 */
10371 		mutex_enter(&ipss->ipsec_loader_lock);
10372 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10373 			mutex_exit(&ipss->ipsec_loader_lock);
10374 			return (EPROTONOSUPPORT);
10375 		}
10376 		mutex_exit(&ipss->ipsec_loader_lock);
10377 
10378 		/*
10379 		 * Test for valid requests. Invalid algorithms
10380 		 * need to be tested by IPSEC code because new
10381 		 * algorithms can be added dynamically.
10382 		 */
10383 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10384 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10385 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10386 			return (EINVAL);
10387 		}
10388 
10389 		/*
10390 		 * Only privileged users can issue these
10391 		 * requests.
10392 		 */
10393 		if (((ah_req & IPSEC_PREF_NEVER) ||
10394 		    (esp_req & IPSEC_PREF_NEVER) ||
10395 		    (se_req & IPSEC_PREF_NEVER)) &&
10396 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10397 			return (EPERM);
10398 		}
10399 
10400 		/*
10401 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10402 		 * are mutually exclusive.
10403 		 */
10404 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10405 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10406 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10407 			/* Both of them are set */
10408 			return (EINVAL);
10409 		}
10410 	}
10411 
10412 	mutex_enter(&connp->conn_lock);
10413 
10414 	/*
10415 	 * If we have already cached policies in ip_bind_connected*(), don't
10416 	 * let them change now. We cache policies for connections
10417 	 * whose src,dst [addr, port] is known.
10418 	 */
10419 	if (connp->conn_policy_cached) {
10420 		mutex_exit(&connp->conn_lock);
10421 		return (EINVAL);
10422 	}
10423 
10424 	/*
10425 	 * We have a zero policies, reset the connection policy if already
10426 	 * set. This will cause the connection to inherit the
10427 	 * global policy, if any.
10428 	 */
10429 	if (is_pol_reset) {
10430 		if (connp->conn_policy != NULL) {
10431 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10432 			connp->conn_policy = NULL;
10433 		}
10434 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10435 		connp->conn_in_enforce_policy = B_FALSE;
10436 		connp->conn_out_enforce_policy = B_FALSE;
10437 		mutex_exit(&connp->conn_lock);
10438 		return (0);
10439 	}
10440 
10441 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10442 	    ipst->ips_netstack);
10443 	if (ph == NULL)
10444 		goto enomem;
10445 
10446 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10447 	if (actp == NULL)
10448 		goto enomem;
10449 
10450 	/*
10451 	 * Always allocate IPv4 policy entries, since they can also
10452 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10453 	 */
10454 	bzero(&sel, sizeof (sel));
10455 	sel.ipsl_valid = IPSL_IPV4;
10456 
10457 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10458 	    ipst->ips_netstack);
10459 	if (pin4 == NULL)
10460 		goto enomem;
10461 
10462 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10463 	    ipst->ips_netstack);
10464 	if (pout4 == NULL)
10465 		goto enomem;
10466 
10467 	if (connp->conn_pkt_isv6) {
10468 		/*
10469 		 * We're looking at a v6 socket, also allocate the
10470 		 * v6-specific entries...
10471 		 */
10472 		sel.ipsl_valid = IPSL_IPV6;
10473 		pin6 = ipsec_policy_create(&sel, actp, nact,
10474 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10475 		if (pin6 == NULL)
10476 			goto enomem;
10477 
10478 		pout6 = ipsec_policy_create(&sel, actp, nact,
10479 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10480 		if (pout6 == NULL)
10481 			goto enomem;
10482 
10483 		/*
10484 		 * .. and file them away in the right place.
10485 		 */
10486 		fam = IPSEC_AF_V6;
10487 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10488 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10489 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10490 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10491 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10492 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10493 	}
10494 
10495 	ipsec_actvec_free(actp, nact);
10496 
10497 	/*
10498 	 * File the v4 policies.
10499 	 */
10500 	fam = IPSEC_AF_V4;
10501 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10502 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10503 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10504 
10505 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10506 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10507 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10508 
10509 	/*
10510 	 * If the requests need security, set enforce_policy.
10511 	 * If the requests are IPSEC_PREF_NEVER, one should
10512 	 * still set conn_out_enforce_policy so that an ipsec_out
10513 	 * gets attached in ip_wput. This is needed so that
10514 	 * for connections that we don't cache policy in ip_bind,
10515 	 * if global policy matches in ip_wput_attach_policy, we
10516 	 * don't wrongly inherit global policy. Similarly, we need
10517 	 * to set conn_in_enforce_policy also so that we don't verify
10518 	 * policy wrongly.
10519 	 */
10520 	if ((ah_req & REQ_MASK) != 0 ||
10521 	    (esp_req & REQ_MASK) != 0 ||
10522 	    (se_req & REQ_MASK) != 0) {
10523 		connp->conn_in_enforce_policy = B_TRUE;
10524 		connp->conn_out_enforce_policy = B_TRUE;
10525 		connp->conn_flags |= IPCL_CHECK_POLICY;
10526 	}
10527 
10528 	mutex_exit(&connp->conn_lock);
10529 	return (error);
10530 #undef REQ_MASK
10531 
10532 	/*
10533 	 * Common memory-allocation-failure exit path.
10534 	 */
10535 enomem:
10536 	mutex_exit(&connp->conn_lock);
10537 	if (actp != NULL)
10538 		ipsec_actvec_free(actp, nact);
10539 	if (pin4 != NULL)
10540 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10541 	if (pout4 != NULL)
10542 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10543 	if (pin6 != NULL)
10544 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10545 	if (pout6 != NULL)
10546 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10547 	return (ENOMEM);
10548 }
10549 
10550 /*
10551  * Only for options that pass in an IP addr. Currently only V4 options
10552  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10553  * So this function assumes level is IPPROTO_IP
10554  */
10555 int
10556 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10557     mblk_t *first_mp)
10558 {
10559 	ipif_t *ipif = NULL;
10560 	int error;
10561 	ill_t *ill;
10562 	int zoneid;
10563 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10564 
10565 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10566 
10567 	if (addr != INADDR_ANY || checkonly) {
10568 		ASSERT(connp != NULL);
10569 		zoneid = IPCL_ZONEID(connp);
10570 		if (option == IP_NEXTHOP) {
10571 			ipif = ipif_lookup_onlink_addr(addr,
10572 			    connp->conn_zoneid, ipst);
10573 		} else {
10574 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10575 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10576 			    &error, ipst);
10577 		}
10578 		if (ipif == NULL) {
10579 			if (error == EINPROGRESS)
10580 				return (error);
10581 			else if ((option == IP_MULTICAST_IF) ||
10582 			    (option == IP_NEXTHOP))
10583 				return (EHOSTUNREACH);
10584 			else
10585 				return (EINVAL);
10586 		} else if (checkonly) {
10587 			if (option == IP_MULTICAST_IF) {
10588 				ill = ipif->ipif_ill;
10589 				/* not supported by the virtual network iface */
10590 				if (IS_VNI(ill)) {
10591 					ipif_refrele(ipif);
10592 					return (EINVAL);
10593 				}
10594 			}
10595 			ipif_refrele(ipif);
10596 			return (0);
10597 		}
10598 		ill = ipif->ipif_ill;
10599 		mutex_enter(&connp->conn_lock);
10600 		mutex_enter(&ill->ill_lock);
10601 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10602 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10603 			mutex_exit(&ill->ill_lock);
10604 			mutex_exit(&connp->conn_lock);
10605 			ipif_refrele(ipif);
10606 			return (option == IP_MULTICAST_IF ?
10607 			    EHOSTUNREACH : EINVAL);
10608 		}
10609 	} else {
10610 		mutex_enter(&connp->conn_lock);
10611 	}
10612 
10613 	/* None of the options below are supported on the VNI */
10614 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10615 		mutex_exit(&ill->ill_lock);
10616 		mutex_exit(&connp->conn_lock);
10617 		ipif_refrele(ipif);
10618 		return (EINVAL);
10619 	}
10620 
10621 	switch (option) {
10622 	case IP_DONTFAILOVER_IF:
10623 		/*
10624 		 * This option is used by in.mpathd to ensure
10625 		 * that IPMP probe packets only go out on the
10626 		 * test interfaces. in.mpathd sets this option
10627 		 * on the non-failover interfaces.
10628 		 * For backward compatibility, this option
10629 		 * implicitly sets IP_MULTICAST_IF, as used
10630 		 * be done in bind(), so that ip_wput gets
10631 		 * this ipif to send mcast packets.
10632 		 */
10633 		if (ipif != NULL) {
10634 			ASSERT(addr != INADDR_ANY);
10635 			connp->conn_nofailover_ill = ipif->ipif_ill;
10636 			connp->conn_multicast_ipif = ipif;
10637 		} else {
10638 			ASSERT(addr == INADDR_ANY);
10639 			connp->conn_nofailover_ill = NULL;
10640 			connp->conn_multicast_ipif = NULL;
10641 		}
10642 		break;
10643 
10644 	case IP_MULTICAST_IF:
10645 		connp->conn_multicast_ipif = ipif;
10646 		break;
10647 	case IP_NEXTHOP:
10648 		connp->conn_nexthop_v4 = addr;
10649 		connp->conn_nexthop_set = B_TRUE;
10650 		break;
10651 	}
10652 
10653 	if (ipif != NULL) {
10654 		mutex_exit(&ill->ill_lock);
10655 		mutex_exit(&connp->conn_lock);
10656 		ipif_refrele(ipif);
10657 		return (0);
10658 	}
10659 	mutex_exit(&connp->conn_lock);
10660 	/* We succeded in cleared the option */
10661 	return (0);
10662 }
10663 
10664 /*
10665  * For options that pass in an ifindex specifying the ill. V6 options always
10666  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10667  */
10668 int
10669 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10670     int level, int option, mblk_t *first_mp)
10671 {
10672 	ill_t *ill = NULL;
10673 	int error = 0;
10674 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10675 
10676 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10677 	if (ifindex != 0) {
10678 		ASSERT(connp != NULL);
10679 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10680 		    first_mp, ip_restart_optmgmt, &error, ipst);
10681 		if (ill != NULL) {
10682 			if (checkonly) {
10683 				/* not supported by the virtual network iface */
10684 				if (IS_VNI(ill)) {
10685 					ill_refrele(ill);
10686 					return (EINVAL);
10687 				}
10688 				ill_refrele(ill);
10689 				return (0);
10690 			}
10691 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10692 			    0, NULL)) {
10693 				ill_refrele(ill);
10694 				ill = NULL;
10695 				mutex_enter(&connp->conn_lock);
10696 				goto setit;
10697 			}
10698 			mutex_enter(&connp->conn_lock);
10699 			mutex_enter(&ill->ill_lock);
10700 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10701 				mutex_exit(&ill->ill_lock);
10702 				mutex_exit(&connp->conn_lock);
10703 				ill_refrele(ill);
10704 				ill = NULL;
10705 				mutex_enter(&connp->conn_lock);
10706 			}
10707 			goto setit;
10708 		} else if (error == EINPROGRESS) {
10709 			return (error);
10710 		} else {
10711 			error = 0;
10712 		}
10713 	}
10714 	mutex_enter(&connp->conn_lock);
10715 setit:
10716 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10717 
10718 	/*
10719 	 * The options below assume that the ILL (if any) transmits and/or
10720 	 * receives traffic. Neither of which is true for the virtual network
10721 	 * interface, so fail setting these on a VNI.
10722 	 */
10723 	if (IS_VNI(ill)) {
10724 		ASSERT(ill != NULL);
10725 		mutex_exit(&ill->ill_lock);
10726 		mutex_exit(&connp->conn_lock);
10727 		ill_refrele(ill);
10728 		return (EINVAL);
10729 	}
10730 
10731 	if (level == IPPROTO_IP) {
10732 		switch (option) {
10733 		case IP_BOUND_IF:
10734 			connp->conn_incoming_ill = ill;
10735 			connp->conn_outgoing_ill = ill;
10736 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10737 			    0 : ifindex;
10738 			break;
10739 
10740 		case IP_XMIT_IF:
10741 			/*
10742 			 * Similar to IP_BOUND_IF, but this only
10743 			 * determines the outgoing interface for
10744 			 * unicast packets. Also no IRE_CACHE entry
10745 			 * is added for the destination of the
10746 			 * outgoing packets. This feature is needed
10747 			 * for mobile IP.
10748 			 */
10749 			connp->conn_xmit_if_ill = ill;
10750 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10751 			    0 : ifindex;
10752 			break;
10753 
10754 		case IP_MULTICAST_IF:
10755 			/*
10756 			 * This option is an internal special. The socket
10757 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10758 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10759 			 * specifies an ifindex and we try first on V6 ill's.
10760 			 * If we don't find one, we they try using on v4 ill's
10761 			 * intenally and we come here.
10762 			 */
10763 			if (!checkonly && ill != NULL) {
10764 				ipif_t	*ipif;
10765 				ipif = ill->ill_ipif;
10766 
10767 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10768 					mutex_exit(&ill->ill_lock);
10769 					mutex_exit(&connp->conn_lock);
10770 					ill_refrele(ill);
10771 					ill = NULL;
10772 					mutex_enter(&connp->conn_lock);
10773 				} else {
10774 					connp->conn_multicast_ipif = ipif;
10775 				}
10776 			}
10777 			break;
10778 		}
10779 	} else {
10780 		switch (option) {
10781 		case IPV6_BOUND_IF:
10782 			connp->conn_incoming_ill = ill;
10783 			connp->conn_outgoing_ill = ill;
10784 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10785 			    0 : ifindex;
10786 			break;
10787 
10788 		case IPV6_BOUND_PIF:
10789 			/*
10790 			 * Limit all transmit to this ill.
10791 			 * Unlike IPV6_BOUND_IF, using this option
10792 			 * prevents load spreading and failover from
10793 			 * happening when the interface is part of the
10794 			 * group. That's why we don't need to remember
10795 			 * the ifindex in orig_bound_ifindex as in
10796 			 * IPV6_BOUND_IF.
10797 			 */
10798 			connp->conn_outgoing_pill = ill;
10799 			break;
10800 
10801 		case IPV6_DONTFAILOVER_IF:
10802 			/*
10803 			 * This option is used by in.mpathd to ensure
10804 			 * that IPMP probe packets only go out on the
10805 			 * test interfaces. in.mpathd sets this option
10806 			 * on the non-failover interfaces.
10807 			 */
10808 			connp->conn_nofailover_ill = ill;
10809 			/*
10810 			 * For backward compatibility, this option
10811 			 * implicitly sets ip_multicast_ill as used in
10812 			 * IP_MULTICAST_IF so that ip_wput gets
10813 			 * this ipif to send mcast packets.
10814 			 */
10815 			connp->conn_multicast_ill = ill;
10816 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10817 			    0 : ifindex;
10818 			break;
10819 
10820 		case IPV6_MULTICAST_IF:
10821 			/*
10822 			 * Set conn_multicast_ill to be the IPv6 ill.
10823 			 * Set conn_multicast_ipif to be an IPv4 ipif
10824 			 * for ifindex to make IPv4 mapped addresses
10825 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10826 			 * Even if no IPv6 ill exists for the ifindex
10827 			 * we need to check for an IPv4 ifindex in order
10828 			 * for this to work with mapped addresses. In that
10829 			 * case only set conn_multicast_ipif.
10830 			 */
10831 			if (!checkonly) {
10832 				if (ifindex == 0) {
10833 					connp->conn_multicast_ill = NULL;
10834 					connp->conn_orig_multicast_ifindex = 0;
10835 					connp->conn_multicast_ipif = NULL;
10836 				} else if (ill != NULL) {
10837 					connp->conn_multicast_ill = ill;
10838 					connp->conn_orig_multicast_ifindex =
10839 					    ifindex;
10840 				}
10841 			}
10842 			break;
10843 		}
10844 	}
10845 
10846 	if (ill != NULL) {
10847 		mutex_exit(&ill->ill_lock);
10848 		mutex_exit(&connp->conn_lock);
10849 		ill_refrele(ill);
10850 		return (0);
10851 	}
10852 	mutex_exit(&connp->conn_lock);
10853 	/*
10854 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10855 	 * locate the ill and could not set the option (ifindex != 0)
10856 	 */
10857 	return (ifindex == 0 ? 0 : EINVAL);
10858 }
10859 
10860 /* This routine sets socket options. */
10861 /* ARGSUSED */
10862 int
10863 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10864     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10865     void *dummy, cred_t *cr, mblk_t *first_mp)
10866 {
10867 	int		*i1 = (int *)invalp;
10868 	conn_t		*connp = Q_TO_CONN(q);
10869 	int		error = 0;
10870 	boolean_t	checkonly;
10871 	ire_t		*ire;
10872 	boolean_t	found;
10873 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10874 
10875 	switch (optset_context) {
10876 
10877 	case SETFN_OPTCOM_CHECKONLY:
10878 		checkonly = B_TRUE;
10879 		/*
10880 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10881 		 * inlen != 0 implies value supplied and
10882 		 * 	we have to "pretend" to set it.
10883 		 * inlen == 0 implies that there is no
10884 		 * 	value part in T_CHECK request and just validation
10885 		 * done elsewhere should be enough, we just return here.
10886 		 */
10887 		if (inlen == 0) {
10888 			*outlenp = 0;
10889 			return (0);
10890 		}
10891 		break;
10892 	case SETFN_OPTCOM_NEGOTIATE:
10893 	case SETFN_UD_NEGOTIATE:
10894 	case SETFN_CONN_NEGOTIATE:
10895 		checkonly = B_FALSE;
10896 		break;
10897 	default:
10898 		/*
10899 		 * We should never get here
10900 		 */
10901 		*outlenp = 0;
10902 		return (EINVAL);
10903 	}
10904 
10905 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10906 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10907 
10908 	/*
10909 	 * For fixed length options, no sanity check
10910 	 * of passed in length is done. It is assumed *_optcom_req()
10911 	 * routines do the right thing.
10912 	 */
10913 
10914 	switch (level) {
10915 	case SOL_SOCKET:
10916 		/*
10917 		 * conn_lock protects the bitfields, and is used to
10918 		 * set the fields atomically.
10919 		 */
10920 		switch (name) {
10921 		case SO_BROADCAST:
10922 			if (!checkonly) {
10923 				/* TODO: use value someplace? */
10924 				mutex_enter(&connp->conn_lock);
10925 				connp->conn_broadcast = *i1 ? 1 : 0;
10926 				mutex_exit(&connp->conn_lock);
10927 			}
10928 			break;	/* goto sizeof (int) option return */
10929 		case SO_USELOOPBACK:
10930 			if (!checkonly) {
10931 				/* TODO: use value someplace? */
10932 				mutex_enter(&connp->conn_lock);
10933 				connp->conn_loopback = *i1 ? 1 : 0;
10934 				mutex_exit(&connp->conn_lock);
10935 			}
10936 			break;	/* goto sizeof (int) option return */
10937 		case SO_DONTROUTE:
10938 			if (!checkonly) {
10939 				mutex_enter(&connp->conn_lock);
10940 				connp->conn_dontroute = *i1 ? 1 : 0;
10941 				mutex_exit(&connp->conn_lock);
10942 			}
10943 			break;	/* goto sizeof (int) option return */
10944 		case SO_REUSEADDR:
10945 			if (!checkonly) {
10946 				mutex_enter(&connp->conn_lock);
10947 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10948 				mutex_exit(&connp->conn_lock);
10949 			}
10950 			break;	/* goto sizeof (int) option return */
10951 		case SO_PROTOTYPE:
10952 			if (!checkonly) {
10953 				mutex_enter(&connp->conn_lock);
10954 				connp->conn_proto = *i1;
10955 				mutex_exit(&connp->conn_lock);
10956 			}
10957 			break;	/* goto sizeof (int) option return */
10958 		case SO_ALLZONES:
10959 			if (!checkonly) {
10960 				mutex_enter(&connp->conn_lock);
10961 				if (IPCL_IS_BOUND(connp)) {
10962 					mutex_exit(&connp->conn_lock);
10963 					return (EINVAL);
10964 				}
10965 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10966 				mutex_exit(&connp->conn_lock);
10967 			}
10968 			break;	/* goto sizeof (int) option return */
10969 		case SO_ANON_MLP:
10970 			if (!checkonly) {
10971 				mutex_enter(&connp->conn_lock);
10972 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10973 				mutex_exit(&connp->conn_lock);
10974 			}
10975 			break;	/* goto sizeof (int) option return */
10976 		case SO_MAC_EXEMPT:
10977 			if (secpolicy_net_mac_aware(cr) != 0 ||
10978 			    IPCL_IS_BOUND(connp))
10979 				return (EACCES);
10980 			if (!checkonly) {
10981 				mutex_enter(&connp->conn_lock);
10982 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10983 				mutex_exit(&connp->conn_lock);
10984 			}
10985 			break;	/* goto sizeof (int) option return */
10986 		default:
10987 			/*
10988 			 * "soft" error (negative)
10989 			 * option not handled at this level
10990 			 * Note: Do not modify *outlenp
10991 			 */
10992 			return (-EINVAL);
10993 		}
10994 		break;
10995 	case IPPROTO_IP:
10996 		switch (name) {
10997 		case IP_NEXTHOP:
10998 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10999 				return (EPERM);
11000 			/* FALLTHRU */
11001 		case IP_MULTICAST_IF:
11002 		case IP_DONTFAILOVER_IF: {
11003 			ipaddr_t addr = *i1;
11004 
11005 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
11006 			    first_mp);
11007 			if (error != 0)
11008 				return (error);
11009 			break;	/* goto sizeof (int) option return */
11010 		}
11011 
11012 		case IP_MULTICAST_TTL:
11013 			/* Recorded in transport above IP */
11014 			*outvalp = *invalp;
11015 			*outlenp = sizeof (uchar_t);
11016 			return (0);
11017 		case IP_MULTICAST_LOOP:
11018 			if (!checkonly) {
11019 				mutex_enter(&connp->conn_lock);
11020 				connp->conn_multicast_loop = *invalp ? 1 : 0;
11021 				mutex_exit(&connp->conn_lock);
11022 			}
11023 			*outvalp = *invalp;
11024 			*outlenp = sizeof (uchar_t);
11025 			return (0);
11026 		case IP_ADD_MEMBERSHIP:
11027 		case MCAST_JOIN_GROUP:
11028 		case IP_DROP_MEMBERSHIP:
11029 		case MCAST_LEAVE_GROUP: {
11030 			struct ip_mreq *mreqp;
11031 			struct group_req *greqp;
11032 			ire_t *ire;
11033 			boolean_t done = B_FALSE;
11034 			ipaddr_t group, ifaddr;
11035 			struct sockaddr_in *sin;
11036 			uint32_t *ifindexp;
11037 			boolean_t mcast_opt = B_TRUE;
11038 			mcast_record_t fmode;
11039 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11040 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11041 
11042 			switch (name) {
11043 			case IP_ADD_MEMBERSHIP:
11044 				mcast_opt = B_FALSE;
11045 				/* FALLTHRU */
11046 			case MCAST_JOIN_GROUP:
11047 				fmode = MODE_IS_EXCLUDE;
11048 				optfn = ip_opt_add_group;
11049 				break;
11050 
11051 			case IP_DROP_MEMBERSHIP:
11052 				mcast_opt = B_FALSE;
11053 				/* FALLTHRU */
11054 			case MCAST_LEAVE_GROUP:
11055 				fmode = MODE_IS_INCLUDE;
11056 				optfn = ip_opt_delete_group;
11057 				break;
11058 			}
11059 
11060 			if (mcast_opt) {
11061 				greqp = (struct group_req *)i1;
11062 				sin = (struct sockaddr_in *)&greqp->gr_group;
11063 				if (sin->sin_family != AF_INET) {
11064 					*outlenp = 0;
11065 					return (ENOPROTOOPT);
11066 				}
11067 				group = (ipaddr_t)sin->sin_addr.s_addr;
11068 				ifaddr = INADDR_ANY;
11069 				ifindexp = &greqp->gr_interface;
11070 			} else {
11071 				mreqp = (struct ip_mreq *)i1;
11072 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11073 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11074 				ifindexp = NULL;
11075 			}
11076 
11077 			/*
11078 			 * In the multirouting case, we need to replicate
11079 			 * the request on all interfaces that will take part
11080 			 * in replication.  We do so because multirouting is
11081 			 * reflective, thus we will probably receive multi-
11082 			 * casts on those interfaces.
11083 			 * The ip_multirt_apply_membership() succeeds if the
11084 			 * operation succeeds on at least one interface.
11085 			 */
11086 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11087 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11088 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11089 			if (ire != NULL) {
11090 				if (ire->ire_flags & RTF_MULTIRT) {
11091 					error = ip_multirt_apply_membership(
11092 					    optfn, ire, connp, checkonly, group,
11093 					    fmode, INADDR_ANY, first_mp);
11094 					done = B_TRUE;
11095 				}
11096 				ire_refrele(ire);
11097 			}
11098 			if (!done) {
11099 				error = optfn(connp, checkonly, group, ifaddr,
11100 				    ifindexp, fmode, INADDR_ANY, first_mp);
11101 			}
11102 			if (error) {
11103 				/*
11104 				 * EINPROGRESS is a soft error, needs retry
11105 				 * so don't make *outlenp zero.
11106 				 */
11107 				if (error != EINPROGRESS)
11108 					*outlenp = 0;
11109 				return (error);
11110 			}
11111 			/* OK return - copy input buffer into output buffer */
11112 			if (invalp != outvalp) {
11113 				/* don't trust bcopy for identical src/dst */
11114 				bcopy(invalp, outvalp, inlen);
11115 			}
11116 			*outlenp = inlen;
11117 			return (0);
11118 		}
11119 		case IP_BLOCK_SOURCE:
11120 		case IP_UNBLOCK_SOURCE:
11121 		case IP_ADD_SOURCE_MEMBERSHIP:
11122 		case IP_DROP_SOURCE_MEMBERSHIP:
11123 		case MCAST_BLOCK_SOURCE:
11124 		case MCAST_UNBLOCK_SOURCE:
11125 		case MCAST_JOIN_SOURCE_GROUP:
11126 		case MCAST_LEAVE_SOURCE_GROUP: {
11127 			struct ip_mreq_source *imreqp;
11128 			struct group_source_req *gsreqp;
11129 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11130 			uint32_t ifindex = 0;
11131 			mcast_record_t fmode;
11132 			struct sockaddr_in *sin;
11133 			ire_t *ire;
11134 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11135 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11136 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11137 
11138 			switch (name) {
11139 			case IP_BLOCK_SOURCE:
11140 				mcast_opt = B_FALSE;
11141 				/* FALLTHRU */
11142 			case MCAST_BLOCK_SOURCE:
11143 				fmode = MODE_IS_EXCLUDE;
11144 				optfn = ip_opt_add_group;
11145 				break;
11146 
11147 			case IP_UNBLOCK_SOURCE:
11148 				mcast_opt = B_FALSE;
11149 				/* FALLTHRU */
11150 			case MCAST_UNBLOCK_SOURCE:
11151 				fmode = MODE_IS_EXCLUDE;
11152 				optfn = ip_opt_delete_group;
11153 				break;
11154 
11155 			case IP_ADD_SOURCE_MEMBERSHIP:
11156 				mcast_opt = B_FALSE;
11157 				/* FALLTHRU */
11158 			case MCAST_JOIN_SOURCE_GROUP:
11159 				fmode = MODE_IS_INCLUDE;
11160 				optfn = ip_opt_add_group;
11161 				break;
11162 
11163 			case IP_DROP_SOURCE_MEMBERSHIP:
11164 				mcast_opt = B_FALSE;
11165 				/* FALLTHRU */
11166 			case MCAST_LEAVE_SOURCE_GROUP:
11167 				fmode = MODE_IS_INCLUDE;
11168 				optfn = ip_opt_delete_group;
11169 				break;
11170 			}
11171 
11172 			if (mcast_opt) {
11173 				gsreqp = (struct group_source_req *)i1;
11174 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11175 					*outlenp = 0;
11176 					return (ENOPROTOOPT);
11177 				}
11178 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11179 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11180 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11181 				src = (ipaddr_t)sin->sin_addr.s_addr;
11182 				ifindex = gsreqp->gsr_interface;
11183 			} else {
11184 				imreqp = (struct ip_mreq_source *)i1;
11185 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11186 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11187 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11188 			}
11189 
11190 			/*
11191 			 * In the multirouting case, we need to replicate
11192 			 * the request as noted in the mcast cases above.
11193 			 */
11194 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11195 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11196 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11197 			if (ire != NULL) {
11198 				if (ire->ire_flags & RTF_MULTIRT) {
11199 					error = ip_multirt_apply_membership(
11200 					    optfn, ire, connp, checkonly, grp,
11201 					    fmode, src, first_mp);
11202 					done = B_TRUE;
11203 				}
11204 				ire_refrele(ire);
11205 			}
11206 			if (!done) {
11207 				error = optfn(connp, checkonly, grp, ifaddr,
11208 				    &ifindex, fmode, src, first_mp);
11209 			}
11210 			if (error != 0) {
11211 				/*
11212 				 * EINPROGRESS is a soft error, needs retry
11213 				 * so don't make *outlenp zero.
11214 				 */
11215 				if (error != EINPROGRESS)
11216 					*outlenp = 0;
11217 				return (error);
11218 			}
11219 			/* OK return - copy input buffer into output buffer */
11220 			if (invalp != outvalp) {
11221 				bcopy(invalp, outvalp, inlen);
11222 			}
11223 			*outlenp = inlen;
11224 			return (0);
11225 		}
11226 		case IP_SEC_OPT:
11227 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11228 			if (error != 0) {
11229 				*outlenp = 0;
11230 				return (error);
11231 			}
11232 			break;
11233 		case IP_HDRINCL:
11234 		case IP_OPTIONS:
11235 		case T_IP_OPTIONS:
11236 		case IP_TOS:
11237 		case T_IP_TOS:
11238 		case IP_TTL:
11239 		case IP_RECVDSTADDR:
11240 		case IP_RECVOPTS:
11241 			/* OK return - copy input buffer into output buffer */
11242 			if (invalp != outvalp) {
11243 				/* don't trust bcopy for identical src/dst */
11244 				bcopy(invalp, outvalp, inlen);
11245 			}
11246 			*outlenp = inlen;
11247 			return (0);
11248 		case IP_RECVIF:
11249 			/* Retrieve the inbound interface index */
11250 			if (!checkonly) {
11251 				mutex_enter(&connp->conn_lock);
11252 				connp->conn_recvif = *i1 ? 1 : 0;
11253 				mutex_exit(&connp->conn_lock);
11254 			}
11255 			break;	/* goto sizeof (int) option return */
11256 		case IP_RECVPKTINFO:
11257 			if (!checkonly) {
11258 				mutex_enter(&connp->conn_lock);
11259 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11260 				mutex_exit(&connp->conn_lock);
11261 			}
11262 			break;	/* goto sizeof (int) option return */
11263 		case IP_RECVSLLA:
11264 			/* Retrieve the source link layer address */
11265 			if (!checkonly) {
11266 				mutex_enter(&connp->conn_lock);
11267 				connp->conn_recvslla = *i1 ? 1 : 0;
11268 				mutex_exit(&connp->conn_lock);
11269 			}
11270 			break;	/* goto sizeof (int) option return */
11271 		case MRT_INIT:
11272 		case MRT_DONE:
11273 		case MRT_ADD_VIF:
11274 		case MRT_DEL_VIF:
11275 		case MRT_ADD_MFC:
11276 		case MRT_DEL_MFC:
11277 		case MRT_ASSERT:
11278 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11279 				*outlenp = 0;
11280 				return (error);
11281 			}
11282 			error = ip_mrouter_set((int)name, q, checkonly,
11283 			    (uchar_t *)invalp, inlen, first_mp);
11284 			if (error) {
11285 				*outlenp = 0;
11286 				return (error);
11287 			}
11288 			/* OK return - copy input buffer into output buffer */
11289 			if (invalp != outvalp) {
11290 				/* don't trust bcopy for identical src/dst */
11291 				bcopy(invalp, outvalp, inlen);
11292 			}
11293 			*outlenp = inlen;
11294 			return (0);
11295 		case IP_BOUND_IF:
11296 		case IP_XMIT_IF:
11297 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11298 			    level, name, first_mp);
11299 			if (error != 0)
11300 				return (error);
11301 			break; 		/* goto sizeof (int) option return */
11302 
11303 		case IP_UNSPEC_SRC:
11304 			/* Allow sending with a zero source address */
11305 			if (!checkonly) {
11306 				mutex_enter(&connp->conn_lock);
11307 				connp->conn_unspec_src = *i1 ? 1 : 0;
11308 				mutex_exit(&connp->conn_lock);
11309 			}
11310 			break;	/* goto sizeof (int) option return */
11311 		default:
11312 			/*
11313 			 * "soft" error (negative)
11314 			 * option not handled at this level
11315 			 * Note: Do not modify *outlenp
11316 			 */
11317 			return (-EINVAL);
11318 		}
11319 		break;
11320 	case IPPROTO_IPV6:
11321 		switch (name) {
11322 		case IPV6_BOUND_IF:
11323 		case IPV6_BOUND_PIF:
11324 		case IPV6_DONTFAILOVER_IF:
11325 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11326 			    level, name, first_mp);
11327 			if (error != 0)
11328 				return (error);
11329 			break; 		/* goto sizeof (int) option return */
11330 
11331 		case IPV6_MULTICAST_IF:
11332 			/*
11333 			 * The only possible errors are EINPROGRESS and
11334 			 * EINVAL. EINPROGRESS will be restarted and is not
11335 			 * a hard error. We call this option on both V4 and V6
11336 			 * If both return EINVAL, then this call returns
11337 			 * EINVAL. If at least one of them succeeds we
11338 			 * return success.
11339 			 */
11340 			found = B_FALSE;
11341 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11342 			    level, name, first_mp);
11343 			if (error == EINPROGRESS)
11344 				return (error);
11345 			if (error == 0)
11346 				found = B_TRUE;
11347 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11348 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11349 			if (error == 0)
11350 				found = B_TRUE;
11351 			if (!found)
11352 				return (error);
11353 			break; 		/* goto sizeof (int) option return */
11354 
11355 		case IPV6_MULTICAST_HOPS:
11356 			/* Recorded in transport above IP */
11357 			break;	/* goto sizeof (int) option return */
11358 		case IPV6_MULTICAST_LOOP:
11359 			if (!checkonly) {
11360 				mutex_enter(&connp->conn_lock);
11361 				connp->conn_multicast_loop = *i1;
11362 				mutex_exit(&connp->conn_lock);
11363 			}
11364 			break;	/* goto sizeof (int) option return */
11365 		case IPV6_JOIN_GROUP:
11366 		case MCAST_JOIN_GROUP:
11367 		case IPV6_LEAVE_GROUP:
11368 		case MCAST_LEAVE_GROUP: {
11369 			struct ipv6_mreq *ip_mreqp;
11370 			struct group_req *greqp;
11371 			ire_t *ire;
11372 			boolean_t done = B_FALSE;
11373 			in6_addr_t groupv6;
11374 			uint32_t ifindex;
11375 			boolean_t mcast_opt = B_TRUE;
11376 			mcast_record_t fmode;
11377 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11378 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11379 
11380 			switch (name) {
11381 			case IPV6_JOIN_GROUP:
11382 				mcast_opt = B_FALSE;
11383 				/* FALLTHRU */
11384 			case MCAST_JOIN_GROUP:
11385 				fmode = MODE_IS_EXCLUDE;
11386 				optfn = ip_opt_add_group_v6;
11387 				break;
11388 
11389 			case IPV6_LEAVE_GROUP:
11390 				mcast_opt = B_FALSE;
11391 				/* FALLTHRU */
11392 			case MCAST_LEAVE_GROUP:
11393 				fmode = MODE_IS_INCLUDE;
11394 				optfn = ip_opt_delete_group_v6;
11395 				break;
11396 			}
11397 
11398 			if (mcast_opt) {
11399 				struct sockaddr_in *sin;
11400 				struct sockaddr_in6 *sin6;
11401 				greqp = (struct group_req *)i1;
11402 				if (greqp->gr_group.ss_family == AF_INET) {
11403 					sin = (struct sockaddr_in *)
11404 					    &(greqp->gr_group);
11405 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11406 					    &groupv6);
11407 				} else {
11408 					sin6 = (struct sockaddr_in6 *)
11409 					    &(greqp->gr_group);
11410 					groupv6 = sin6->sin6_addr;
11411 				}
11412 				ifindex = greqp->gr_interface;
11413 			} else {
11414 				ip_mreqp = (struct ipv6_mreq *)i1;
11415 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11416 				ifindex = ip_mreqp->ipv6mr_interface;
11417 			}
11418 			/*
11419 			 * In the multirouting case, we need to replicate
11420 			 * the request on all interfaces that will take part
11421 			 * in replication.  We do so because multirouting is
11422 			 * reflective, thus we will probably receive multi-
11423 			 * casts on those interfaces.
11424 			 * The ip_multirt_apply_membership_v6() succeeds if
11425 			 * the operation succeeds on at least one interface.
11426 			 */
11427 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11428 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11429 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11430 			if (ire != NULL) {
11431 				if (ire->ire_flags & RTF_MULTIRT) {
11432 					error = ip_multirt_apply_membership_v6(
11433 					    optfn, ire, connp, checkonly,
11434 					    &groupv6, fmode, &ipv6_all_zeros,
11435 					    first_mp);
11436 					done = B_TRUE;
11437 				}
11438 				ire_refrele(ire);
11439 			}
11440 			if (!done) {
11441 				error = optfn(connp, checkonly, &groupv6,
11442 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11443 			}
11444 			if (error) {
11445 				/*
11446 				 * EINPROGRESS is a soft error, needs retry
11447 				 * so don't make *outlenp zero.
11448 				 */
11449 				if (error != EINPROGRESS)
11450 					*outlenp = 0;
11451 				return (error);
11452 			}
11453 			/* OK return - copy input buffer into output buffer */
11454 			if (invalp != outvalp) {
11455 				/* don't trust bcopy for identical src/dst */
11456 				bcopy(invalp, outvalp, inlen);
11457 			}
11458 			*outlenp = inlen;
11459 			return (0);
11460 		}
11461 		case MCAST_BLOCK_SOURCE:
11462 		case MCAST_UNBLOCK_SOURCE:
11463 		case MCAST_JOIN_SOURCE_GROUP:
11464 		case MCAST_LEAVE_SOURCE_GROUP: {
11465 			struct group_source_req *gsreqp;
11466 			in6_addr_t v6grp, v6src;
11467 			uint32_t ifindex;
11468 			mcast_record_t fmode;
11469 			ire_t *ire;
11470 			boolean_t done = B_FALSE;
11471 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11472 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11473 
11474 			switch (name) {
11475 			case MCAST_BLOCK_SOURCE:
11476 				fmode = MODE_IS_EXCLUDE;
11477 				optfn = ip_opt_add_group_v6;
11478 				break;
11479 			case MCAST_UNBLOCK_SOURCE:
11480 				fmode = MODE_IS_EXCLUDE;
11481 				optfn = ip_opt_delete_group_v6;
11482 				break;
11483 			case MCAST_JOIN_SOURCE_GROUP:
11484 				fmode = MODE_IS_INCLUDE;
11485 				optfn = ip_opt_add_group_v6;
11486 				break;
11487 			case MCAST_LEAVE_SOURCE_GROUP:
11488 				fmode = MODE_IS_INCLUDE;
11489 				optfn = ip_opt_delete_group_v6;
11490 				break;
11491 			}
11492 
11493 			gsreqp = (struct group_source_req *)i1;
11494 			ifindex = gsreqp->gsr_interface;
11495 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11496 				struct sockaddr_in *s;
11497 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11498 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11499 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11500 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11501 			} else {
11502 				struct sockaddr_in6 *s6;
11503 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11504 				v6grp = s6->sin6_addr;
11505 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11506 				v6src = s6->sin6_addr;
11507 			}
11508 
11509 			/*
11510 			 * In the multirouting case, we need to replicate
11511 			 * the request as noted in the mcast cases above.
11512 			 */
11513 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11514 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11515 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11516 			if (ire != NULL) {
11517 				if (ire->ire_flags & RTF_MULTIRT) {
11518 					error = ip_multirt_apply_membership_v6(
11519 					    optfn, ire, connp, checkonly,
11520 					    &v6grp, fmode, &v6src, first_mp);
11521 					done = B_TRUE;
11522 				}
11523 				ire_refrele(ire);
11524 			}
11525 			if (!done) {
11526 				error = optfn(connp, checkonly, &v6grp,
11527 				    ifindex, fmode, &v6src, first_mp);
11528 			}
11529 			if (error != 0) {
11530 				/*
11531 				 * EINPROGRESS is a soft error, needs retry
11532 				 * so don't make *outlenp zero.
11533 				 */
11534 				if (error != EINPROGRESS)
11535 					*outlenp = 0;
11536 				return (error);
11537 			}
11538 			/* OK return - copy input buffer into output buffer */
11539 			if (invalp != outvalp) {
11540 				bcopy(invalp, outvalp, inlen);
11541 			}
11542 			*outlenp = inlen;
11543 			return (0);
11544 		}
11545 		case IPV6_UNICAST_HOPS:
11546 			/* Recorded in transport above IP */
11547 			break;	/* goto sizeof (int) option return */
11548 		case IPV6_UNSPEC_SRC:
11549 			/* Allow sending with a zero source address */
11550 			if (!checkonly) {
11551 				mutex_enter(&connp->conn_lock);
11552 				connp->conn_unspec_src = *i1 ? 1 : 0;
11553 				mutex_exit(&connp->conn_lock);
11554 			}
11555 			break;	/* goto sizeof (int) option return */
11556 		case IPV6_RECVPKTINFO:
11557 			if (!checkonly) {
11558 				mutex_enter(&connp->conn_lock);
11559 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11560 				mutex_exit(&connp->conn_lock);
11561 			}
11562 			break;	/* goto sizeof (int) option return */
11563 		case IPV6_RECVTCLASS:
11564 			if (!checkonly) {
11565 				if (*i1 < 0 || *i1 > 1) {
11566 					return (EINVAL);
11567 				}
11568 				mutex_enter(&connp->conn_lock);
11569 				connp->conn_ipv6_recvtclass = *i1;
11570 				mutex_exit(&connp->conn_lock);
11571 			}
11572 			break;
11573 		case IPV6_RECVPATHMTU:
11574 			if (!checkonly) {
11575 				if (*i1 < 0 || *i1 > 1) {
11576 					return (EINVAL);
11577 				}
11578 				mutex_enter(&connp->conn_lock);
11579 				connp->conn_ipv6_recvpathmtu = *i1;
11580 				mutex_exit(&connp->conn_lock);
11581 			}
11582 			break;
11583 		case IPV6_RECVHOPLIMIT:
11584 			if (!checkonly) {
11585 				mutex_enter(&connp->conn_lock);
11586 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11587 				mutex_exit(&connp->conn_lock);
11588 			}
11589 			break;	/* goto sizeof (int) option return */
11590 		case IPV6_RECVHOPOPTS:
11591 			if (!checkonly) {
11592 				mutex_enter(&connp->conn_lock);
11593 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11594 				mutex_exit(&connp->conn_lock);
11595 			}
11596 			break;	/* goto sizeof (int) option return */
11597 		case IPV6_RECVDSTOPTS:
11598 			if (!checkonly) {
11599 				mutex_enter(&connp->conn_lock);
11600 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11601 				mutex_exit(&connp->conn_lock);
11602 			}
11603 			break;	/* goto sizeof (int) option return */
11604 		case IPV6_RECVRTHDR:
11605 			if (!checkonly) {
11606 				mutex_enter(&connp->conn_lock);
11607 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11608 				mutex_exit(&connp->conn_lock);
11609 			}
11610 			break;	/* goto sizeof (int) option return */
11611 		case IPV6_RECVRTHDRDSTOPTS:
11612 			if (!checkonly) {
11613 				mutex_enter(&connp->conn_lock);
11614 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11615 				mutex_exit(&connp->conn_lock);
11616 			}
11617 			break;	/* goto sizeof (int) option return */
11618 		case IPV6_PKTINFO:
11619 			if (inlen == 0)
11620 				return (-EINVAL);	/* clearing option */
11621 			error = ip6_set_pktinfo(cr, connp,
11622 			    (struct in6_pktinfo *)invalp, first_mp);
11623 			if (error != 0)
11624 				*outlenp = 0;
11625 			else
11626 				*outlenp = inlen;
11627 			return (error);
11628 		case IPV6_NEXTHOP: {
11629 			struct sockaddr_in6 *sin6;
11630 
11631 			/* Verify that the nexthop is reachable */
11632 			if (inlen == 0)
11633 				return (-EINVAL);	/* clearing option */
11634 
11635 			sin6 = (struct sockaddr_in6 *)invalp;
11636 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11637 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11638 			    NULL, MATCH_IRE_DEFAULT, ipst);
11639 
11640 			if (ire == NULL) {
11641 				*outlenp = 0;
11642 				return (EHOSTUNREACH);
11643 			}
11644 			ire_refrele(ire);
11645 			return (-EINVAL);
11646 		}
11647 		case IPV6_SEC_OPT:
11648 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11649 			if (error != 0) {
11650 				*outlenp = 0;
11651 				return (error);
11652 			}
11653 			break;
11654 		case IPV6_SRC_PREFERENCES: {
11655 			/*
11656 			 * This is implemented strictly in the ip module
11657 			 * (here and in tcp_opt_*() to accomodate tcp
11658 			 * sockets).  Modules above ip pass this option
11659 			 * down here since ip is the only one that needs to
11660 			 * be aware of source address preferences.
11661 			 *
11662 			 * This socket option only affects connected
11663 			 * sockets that haven't already bound to a specific
11664 			 * IPv6 address.  In other words, sockets that
11665 			 * don't call bind() with an address other than the
11666 			 * unspecified address and that call connect().
11667 			 * ip_bind_connected_v6() passes these preferences
11668 			 * to the ipif_select_source_v6() function.
11669 			 */
11670 			if (inlen != sizeof (uint32_t))
11671 				return (EINVAL);
11672 			error = ip6_set_src_preferences(connp,
11673 			    *(uint32_t *)invalp);
11674 			if (error != 0) {
11675 				*outlenp = 0;
11676 				return (error);
11677 			} else {
11678 				*outlenp = sizeof (uint32_t);
11679 			}
11680 			break;
11681 		}
11682 		case IPV6_V6ONLY:
11683 			if (*i1 < 0 || *i1 > 1) {
11684 				return (EINVAL);
11685 			}
11686 			mutex_enter(&connp->conn_lock);
11687 			connp->conn_ipv6_v6only = *i1;
11688 			mutex_exit(&connp->conn_lock);
11689 			break;
11690 		default:
11691 			return (-EINVAL);
11692 		}
11693 		break;
11694 	default:
11695 		/*
11696 		 * "soft" error (negative)
11697 		 * option not handled at this level
11698 		 * Note: Do not modify *outlenp
11699 		 */
11700 		return (-EINVAL);
11701 	}
11702 	/*
11703 	 * Common case of return from an option that is sizeof (int)
11704 	 */
11705 	*(int *)outvalp = *i1;
11706 	*outlenp = sizeof (int);
11707 	return (0);
11708 }
11709 
11710 /*
11711  * This routine gets default values of certain options whose default
11712  * values are maintained by protocol specific code
11713  */
11714 /* ARGSUSED */
11715 int
11716 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11717 {
11718 	int *i1 = (int *)ptr;
11719 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11720 
11721 	switch (level) {
11722 	case IPPROTO_IP:
11723 		switch (name) {
11724 		case IP_MULTICAST_TTL:
11725 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11726 			return (sizeof (uchar_t));
11727 		case IP_MULTICAST_LOOP:
11728 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11729 			return (sizeof (uchar_t));
11730 		default:
11731 			return (-1);
11732 		}
11733 	case IPPROTO_IPV6:
11734 		switch (name) {
11735 		case IPV6_UNICAST_HOPS:
11736 			*i1 = ipst->ips_ipv6_def_hops;
11737 			return (sizeof (int));
11738 		case IPV6_MULTICAST_HOPS:
11739 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11740 			return (sizeof (int));
11741 		case IPV6_MULTICAST_LOOP:
11742 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11743 			return (sizeof (int));
11744 		case IPV6_V6ONLY:
11745 			*i1 = 1;
11746 			return (sizeof (int));
11747 		default:
11748 			return (-1);
11749 		}
11750 	default:
11751 		return (-1);
11752 	}
11753 	/* NOTREACHED */
11754 }
11755 
11756 /*
11757  * Given a destination address and a pointer to where to put the information
11758  * this routine fills in the mtuinfo.
11759  */
11760 int
11761 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11762     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11763 {
11764 	ire_t *ire;
11765 	ip_stack_t	*ipst = ns->netstack_ip;
11766 
11767 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11768 		return (-1);
11769 
11770 	bzero(mtuinfo, sizeof (*mtuinfo));
11771 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11772 	mtuinfo->ip6m_addr.sin6_port = port;
11773 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11774 
11775 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11776 	if (ire != NULL) {
11777 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11778 		ire_refrele(ire);
11779 	} else {
11780 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11781 	}
11782 	return (sizeof (struct ip6_mtuinfo));
11783 }
11784 
11785 /*
11786  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11787  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11788  * isn't.  This doesn't matter as the error checking is done properly for the
11789  * other MRT options coming in through ip_opt_set.
11790  */
11791 int
11792 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11793 {
11794 	conn_t		*connp = Q_TO_CONN(q);
11795 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11796 
11797 	switch (level) {
11798 	case IPPROTO_IP:
11799 		switch (name) {
11800 		case MRT_VERSION:
11801 		case MRT_ASSERT:
11802 			(void) ip_mrouter_get(name, q, ptr);
11803 			return (sizeof (int));
11804 		case IP_SEC_OPT:
11805 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11806 		case IP_NEXTHOP:
11807 			if (connp->conn_nexthop_set) {
11808 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11809 				return (sizeof (ipaddr_t));
11810 			} else
11811 				return (0);
11812 		case IP_RECVPKTINFO:
11813 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11814 			return (sizeof (int));
11815 		default:
11816 			break;
11817 		}
11818 		break;
11819 	case IPPROTO_IPV6:
11820 		switch (name) {
11821 		case IPV6_SEC_OPT:
11822 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11823 		case IPV6_SRC_PREFERENCES: {
11824 			return (ip6_get_src_preferences(connp,
11825 			    (uint32_t *)ptr));
11826 		}
11827 		case IPV6_V6ONLY:
11828 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11829 			return (sizeof (int));
11830 		case IPV6_PATHMTU:
11831 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11832 				(struct ip6_mtuinfo *)ptr,
11833 				connp->conn_netstack));
11834 		default:
11835 			break;
11836 		}
11837 		break;
11838 	default:
11839 		break;
11840 	}
11841 	return (-1);
11842 }
11843 
11844 /* Named Dispatch routine to get a current value out of our parameter table. */
11845 /* ARGSUSED */
11846 static int
11847 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11848 {
11849 	ipparam_t *ippa = (ipparam_t *)cp;
11850 
11851 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11852 	return (0);
11853 }
11854 
11855 /* ARGSUSED */
11856 static int
11857 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11858 {
11859 
11860 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11861 	return (0);
11862 }
11863 
11864 /*
11865  * Set ip{,6}_forwarding values.  This means walking through all of the
11866  * ill's and toggling their forwarding values.
11867  */
11868 /* ARGSUSED */
11869 static int
11870 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11871 {
11872 	long new_value;
11873 	int *forwarding_value = (int *)cp;
11874 	ill_t *ill;
11875 	boolean_t isv6;
11876 	ill_walk_context_t ctx;
11877 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11878 
11879 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11880 
11881 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11882 	    new_value < 0 || new_value > 1) {
11883 		return (EINVAL);
11884 	}
11885 
11886 	*forwarding_value = new_value;
11887 
11888 	/*
11889 	 * Regardless of the current value of ip_forwarding, set all per-ill
11890 	 * values of ip_forwarding to the value being set.
11891 	 *
11892 	 * Bring all the ill's up to date with the new global value.
11893 	 */
11894 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11895 
11896 	if (isv6)
11897 		ill = ILL_START_WALK_V6(&ctx, ipst);
11898 	else
11899 		ill = ILL_START_WALK_V4(&ctx, ipst);
11900 
11901 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11902 		(void) ill_forward_set(ill, new_value != 0);
11903 
11904 	rw_exit(&ipst->ips_ill_g_lock);
11905 	return (0);
11906 }
11907 
11908 /*
11909  * Walk through the param array specified registering each element with the
11910  * Named Dispatch handler. This is called only during init. So it is ok
11911  * not to acquire any locks
11912  */
11913 static boolean_t
11914 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11915     ipndp_t *ipnd, size_t ipnd_cnt)
11916 {
11917 	for (; ippa_cnt-- > 0; ippa++) {
11918 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11919 			if (!nd_load(ndp, ippa->ip_param_name,
11920 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11921 				nd_free(ndp);
11922 				return (B_FALSE);
11923 			}
11924 		}
11925 	}
11926 
11927 	for (; ipnd_cnt-- > 0; ipnd++) {
11928 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11929 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11930 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11931 			    ipnd->ip_ndp_data)) {
11932 				nd_free(ndp);
11933 				return (B_FALSE);
11934 			}
11935 		}
11936 	}
11937 
11938 	return (B_TRUE);
11939 }
11940 
11941 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11942 /* ARGSUSED */
11943 static int
11944 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11945 {
11946 	long		new_value;
11947 	ipparam_t	*ippa = (ipparam_t *)cp;
11948 
11949 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11950 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11951 		return (EINVAL);
11952 	}
11953 	ippa->ip_param_value = new_value;
11954 	return (0);
11955 }
11956 
11957 /*
11958  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11959  * When an ipf is passed here for the first time, if
11960  * we already have in-order fragments on the queue, we convert from the fast-
11961  * path reassembly scheme to the hard-case scheme.  From then on, additional
11962  * fragments are reassembled here.  We keep track of the start and end offsets
11963  * of each piece, and the number of holes in the chain.  When the hole count
11964  * goes to zero, we are done!
11965  *
11966  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11967  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11968  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11969  * after the call to ip_reassemble().
11970  */
11971 int
11972 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11973     size_t msg_len)
11974 {
11975 	uint_t	end;
11976 	mblk_t	*next_mp;
11977 	mblk_t	*mp1;
11978 	uint_t	offset;
11979 	boolean_t incr_dups = B_TRUE;
11980 	boolean_t offset_zero_seen = B_FALSE;
11981 	boolean_t pkt_boundary_checked = B_FALSE;
11982 
11983 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11984 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11985 
11986 	/* Add in byte count */
11987 	ipf->ipf_count += msg_len;
11988 	if (ipf->ipf_end) {
11989 		/*
11990 		 * We were part way through in-order reassembly, but now there
11991 		 * is a hole.  We walk through messages already queued, and
11992 		 * mark them for hard case reassembly.  We know that up till
11993 		 * now they were in order starting from offset zero.
11994 		 */
11995 		offset = 0;
11996 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11997 			IP_REASS_SET_START(mp1, offset);
11998 			if (offset == 0) {
11999 				ASSERT(ipf->ipf_nf_hdr_len != 0);
12000 				offset = -ipf->ipf_nf_hdr_len;
12001 			}
12002 			offset += mp1->b_wptr - mp1->b_rptr;
12003 			IP_REASS_SET_END(mp1, offset);
12004 		}
12005 		/* One hole at the end. */
12006 		ipf->ipf_hole_cnt = 1;
12007 		/* Brand it as a hard case, forever. */
12008 		ipf->ipf_end = 0;
12009 	}
12010 	/* Walk through all the new pieces. */
12011 	do {
12012 		end = start + (mp->b_wptr - mp->b_rptr);
12013 		/*
12014 		 * If start is 0, decrease 'end' only for the first mblk of
12015 		 * the fragment. Otherwise 'end' can get wrong value in the
12016 		 * second pass of the loop if first mblk is exactly the
12017 		 * size of ipf_nf_hdr_len.
12018 		 */
12019 		if (start == 0 && !offset_zero_seen) {
12020 			/* First segment */
12021 			ASSERT(ipf->ipf_nf_hdr_len != 0);
12022 			end -= ipf->ipf_nf_hdr_len;
12023 			offset_zero_seen = B_TRUE;
12024 		}
12025 		next_mp = mp->b_cont;
12026 		/*
12027 		 * We are checking to see if there is any interesing data
12028 		 * to process.  If there isn't and the mblk isn't the
12029 		 * one which carries the unfragmentable header then we
12030 		 * drop it.  It's possible to have just the unfragmentable
12031 		 * header come through without any data.  That needs to be
12032 		 * saved.
12033 		 *
12034 		 * If the assert at the top of this function holds then the
12035 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12036 		 * is infrequently traveled enough that the test is left in
12037 		 * to protect against future code changes which break that
12038 		 * invariant.
12039 		 */
12040 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12041 			/* Empty.  Blast it. */
12042 			IP_REASS_SET_START(mp, 0);
12043 			IP_REASS_SET_END(mp, 0);
12044 			/*
12045 			 * If the ipf points to the mblk we are about to free,
12046 			 * update ipf to point to the next mblk (or NULL
12047 			 * if none).
12048 			 */
12049 			if (ipf->ipf_mp->b_cont == mp)
12050 				ipf->ipf_mp->b_cont = next_mp;
12051 			freeb(mp);
12052 			continue;
12053 		}
12054 		mp->b_cont = NULL;
12055 		IP_REASS_SET_START(mp, start);
12056 		IP_REASS_SET_END(mp, end);
12057 		if (!ipf->ipf_tail_mp) {
12058 			ipf->ipf_tail_mp = mp;
12059 			ipf->ipf_mp->b_cont = mp;
12060 			if (start == 0 || !more) {
12061 				ipf->ipf_hole_cnt = 1;
12062 				/*
12063 				 * if the first fragment comes in more than one
12064 				 * mblk, this loop will be executed for each
12065 				 * mblk. Need to adjust hole count so exiting
12066 				 * this routine will leave hole count at 1.
12067 				 */
12068 				if (next_mp)
12069 					ipf->ipf_hole_cnt++;
12070 			} else
12071 				ipf->ipf_hole_cnt = 2;
12072 			continue;
12073 		} else if (ipf->ipf_last_frag_seen && !more &&
12074 			    !pkt_boundary_checked) {
12075 			/*
12076 			 * We check datagram boundary only if this fragment
12077 			 * claims to be the last fragment and we have seen a
12078 			 * last fragment in the past too. We do this only
12079 			 * once for a given fragment.
12080 			 *
12081 			 * start cannot be 0 here as fragments with start=0
12082 			 * and MF=0 gets handled as a complete packet. These
12083 			 * fragments should not reach here.
12084 			 */
12085 
12086 			if (start + msgdsize(mp) !=
12087 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12088 				/*
12089 				 * We have two fragments both of which claim
12090 				 * to be the last fragment but gives conflicting
12091 				 * information about the whole datagram size.
12092 				 * Something fishy is going on. Drop the
12093 				 * fragment and free up the reassembly list.
12094 				 */
12095 				return (IP_REASS_FAILED);
12096 			}
12097 
12098 			/*
12099 			 * We shouldn't come to this code block again for this
12100 			 * particular fragment.
12101 			 */
12102 			pkt_boundary_checked = B_TRUE;
12103 		}
12104 
12105 		/* New stuff at or beyond tail? */
12106 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12107 		if (start >= offset) {
12108 			if (ipf->ipf_last_frag_seen) {
12109 				/* current fragment is beyond last fragment */
12110 				return (IP_REASS_FAILED);
12111 			}
12112 			/* Link it on end. */
12113 			ipf->ipf_tail_mp->b_cont = mp;
12114 			ipf->ipf_tail_mp = mp;
12115 			if (more) {
12116 				if (start != offset)
12117 					ipf->ipf_hole_cnt++;
12118 			} else if (start == offset && next_mp == NULL)
12119 					ipf->ipf_hole_cnt--;
12120 			continue;
12121 		}
12122 		mp1 = ipf->ipf_mp->b_cont;
12123 		offset = IP_REASS_START(mp1);
12124 		/* New stuff at the front? */
12125 		if (start < offset) {
12126 			if (start == 0) {
12127 				if (end >= offset) {
12128 					/* Nailed the hole at the begining. */
12129 					ipf->ipf_hole_cnt--;
12130 				}
12131 			} else if (end < offset) {
12132 				/*
12133 				 * A hole, stuff, and a hole where there used
12134 				 * to be just a hole.
12135 				 */
12136 				ipf->ipf_hole_cnt++;
12137 			}
12138 			mp->b_cont = mp1;
12139 			/* Check for overlap. */
12140 			while (end > offset) {
12141 				if (end < IP_REASS_END(mp1)) {
12142 					mp->b_wptr -= end - offset;
12143 					IP_REASS_SET_END(mp, offset);
12144 					BUMP_MIB(ill->ill_ip_mib,
12145 					    ipIfStatsReasmPartDups);
12146 					break;
12147 				}
12148 				/* Did we cover another hole? */
12149 				if ((mp1->b_cont &&
12150 				    IP_REASS_END(mp1) !=
12151 				    IP_REASS_START(mp1->b_cont) &&
12152 				    end >= IP_REASS_START(mp1->b_cont)) ||
12153 				    (!ipf->ipf_last_frag_seen && !more)) {
12154 					ipf->ipf_hole_cnt--;
12155 				}
12156 				/* Clip out mp1. */
12157 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12158 					/*
12159 					 * After clipping out mp1, this guy
12160 					 * is now hanging off the end.
12161 					 */
12162 					ipf->ipf_tail_mp = mp;
12163 				}
12164 				IP_REASS_SET_START(mp1, 0);
12165 				IP_REASS_SET_END(mp1, 0);
12166 				/* Subtract byte count */
12167 				ipf->ipf_count -= mp1->b_datap->db_lim -
12168 				    mp1->b_datap->db_base;
12169 				freeb(mp1);
12170 				BUMP_MIB(ill->ill_ip_mib,
12171 				    ipIfStatsReasmPartDups);
12172 				mp1 = mp->b_cont;
12173 				if (!mp1)
12174 					break;
12175 				offset = IP_REASS_START(mp1);
12176 			}
12177 			ipf->ipf_mp->b_cont = mp;
12178 			continue;
12179 		}
12180 		/*
12181 		 * The new piece starts somewhere between the start of the head
12182 		 * and before the end of the tail.
12183 		 */
12184 		for (; mp1; mp1 = mp1->b_cont) {
12185 			offset = IP_REASS_END(mp1);
12186 			if (start < offset) {
12187 				if (end <= offset) {
12188 					/* Nothing new. */
12189 					IP_REASS_SET_START(mp, 0);
12190 					IP_REASS_SET_END(mp, 0);
12191 					/* Subtract byte count */
12192 					ipf->ipf_count -= mp->b_datap->db_lim -
12193 					    mp->b_datap->db_base;
12194 					if (incr_dups) {
12195 						ipf->ipf_num_dups++;
12196 						incr_dups = B_FALSE;
12197 					}
12198 					freeb(mp);
12199 					BUMP_MIB(ill->ill_ip_mib,
12200 					    ipIfStatsReasmDuplicates);
12201 					break;
12202 				}
12203 				/*
12204 				 * Trim redundant stuff off beginning of new
12205 				 * piece.
12206 				 */
12207 				IP_REASS_SET_START(mp, offset);
12208 				mp->b_rptr += offset - start;
12209 				BUMP_MIB(ill->ill_ip_mib,
12210 				    ipIfStatsReasmPartDups);
12211 				start = offset;
12212 				if (!mp1->b_cont) {
12213 					/*
12214 					 * After trimming, this guy is now
12215 					 * hanging off the end.
12216 					 */
12217 					mp1->b_cont = mp;
12218 					ipf->ipf_tail_mp = mp;
12219 					if (!more) {
12220 						ipf->ipf_hole_cnt--;
12221 					}
12222 					break;
12223 				}
12224 			}
12225 			if (start >= IP_REASS_START(mp1->b_cont))
12226 				continue;
12227 			/* Fill a hole */
12228 			if (start > offset)
12229 				ipf->ipf_hole_cnt++;
12230 			mp->b_cont = mp1->b_cont;
12231 			mp1->b_cont = mp;
12232 			mp1 = mp->b_cont;
12233 			offset = IP_REASS_START(mp1);
12234 			if (end >= offset) {
12235 				ipf->ipf_hole_cnt--;
12236 				/* Check for overlap. */
12237 				while (end > offset) {
12238 					if (end < IP_REASS_END(mp1)) {
12239 						mp->b_wptr -= end - offset;
12240 						IP_REASS_SET_END(mp, offset);
12241 						/*
12242 						 * TODO we might bump
12243 						 * this up twice if there is
12244 						 * overlap at both ends.
12245 						 */
12246 						BUMP_MIB(ill->ill_ip_mib,
12247 						    ipIfStatsReasmPartDups);
12248 						break;
12249 					}
12250 					/* Did we cover another hole? */
12251 					if ((mp1->b_cont &&
12252 					    IP_REASS_END(mp1)
12253 					    != IP_REASS_START(mp1->b_cont) &&
12254 					    end >=
12255 					    IP_REASS_START(mp1->b_cont)) ||
12256 					    (!ipf->ipf_last_frag_seen &&
12257 					    !more)) {
12258 						ipf->ipf_hole_cnt--;
12259 					}
12260 					/* Clip out mp1. */
12261 					if ((mp->b_cont = mp1->b_cont) ==
12262 					    NULL) {
12263 						/*
12264 						 * After clipping out mp1,
12265 						 * this guy is now hanging
12266 						 * off the end.
12267 						 */
12268 						ipf->ipf_tail_mp = mp;
12269 					}
12270 					IP_REASS_SET_START(mp1, 0);
12271 					IP_REASS_SET_END(mp1, 0);
12272 					/* Subtract byte count */
12273 					ipf->ipf_count -=
12274 					    mp1->b_datap->db_lim -
12275 					    mp1->b_datap->db_base;
12276 					freeb(mp1);
12277 					BUMP_MIB(ill->ill_ip_mib,
12278 					    ipIfStatsReasmPartDups);
12279 					mp1 = mp->b_cont;
12280 					if (!mp1)
12281 						break;
12282 					offset = IP_REASS_START(mp1);
12283 				}
12284 			}
12285 			break;
12286 		}
12287 	} while (start = end, mp = next_mp);
12288 
12289 	/* Fragment just processed could be the last one. Remember this fact */
12290 	if (!more)
12291 		ipf->ipf_last_frag_seen = B_TRUE;
12292 
12293 	/* Still got holes? */
12294 	if (ipf->ipf_hole_cnt)
12295 		return (IP_REASS_PARTIAL);
12296 	/* Clean up overloaded fields to avoid upstream disasters. */
12297 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12298 		IP_REASS_SET_START(mp1, 0);
12299 		IP_REASS_SET_END(mp1, 0);
12300 	}
12301 	return (IP_REASS_COMPLETE);
12302 }
12303 
12304 /*
12305  * ipsec processing for the fast path, used for input UDP Packets
12306  */
12307 static boolean_t
12308 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12309     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12310 {
12311 	uint32_t	ill_index;
12312 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12313 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12314 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12315 
12316 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12317 	/* The ill_index of the incoming ILL */
12318 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12319 
12320 	/* pass packet up to the transport */
12321 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12322 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12323 		    NULL, mctl_present);
12324 		if (*first_mpp == NULL) {
12325 			return (B_FALSE);
12326 		}
12327 	}
12328 
12329 	/* Initiate IPPF processing for fastpath UDP */
12330 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12331 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12332 		if (*mpp == NULL) {
12333 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12334 			    "deferred/dropped during IPPF processing\n"));
12335 			return (B_FALSE);
12336 		}
12337 	}
12338 	/*
12339 	 * We make the checks as below since we are in the fast path
12340 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12341 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12342 	 */
12343 	if (connp->conn_recvif || connp->conn_recvslla ||
12344 	    connp->conn_ip_recvpktinfo) {
12345 		if (connp->conn_recvif) {
12346 			in_flags = IPF_RECVIF;
12347 		}
12348 		/*
12349 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12350 		 * so the flag passed to ip_add_info is based on IP version
12351 		 * of connp.
12352 		 */
12353 		if (connp->conn_ip_recvpktinfo) {
12354 			if (connp->conn_af_isv6) {
12355 				/*
12356 				 * V6 only needs index
12357 				 */
12358 				in_flags |= IPF_RECVIF;
12359 			} else {
12360 				/*
12361 				 * V4 needs index + matching address.
12362 				 */
12363 				in_flags |= IPF_RECVADDR;
12364 			}
12365 		}
12366 		if (connp->conn_recvslla) {
12367 			in_flags |= IPF_RECVSLLA;
12368 		}
12369 		/*
12370 		 * since in_flags are being set ill will be
12371 		 * referenced in ip_add_info, so it better not
12372 		 * be NULL.
12373 		 */
12374 		/*
12375 		 * the actual data will be contained in b_cont
12376 		 * upon successful return of the following call.
12377 		 * If the call fails then the original mblk is
12378 		 * returned.
12379 		 */
12380 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12381 		    ipst);
12382 	}
12383 
12384 	return (B_TRUE);
12385 }
12386 
12387 /*
12388  * Fragmentation reassembly.  Each ILL has a hash table for
12389  * queuing packets undergoing reassembly for all IPIFs
12390  * associated with the ILL.  The hash is based on the packet
12391  * IP ident field.  The ILL frag hash table was allocated
12392  * as a timer block at the time the ILL was created.  Whenever
12393  * there is anything on the reassembly queue, the timer will
12394  * be running.  Returns B_TRUE if successful else B_FALSE;
12395  * frees mp on failure.
12396  */
12397 static boolean_t
12398 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12399     uint32_t *cksum_val, uint16_t *cksum_flags)
12400 {
12401 	uint32_t	frag_offset_flags;
12402 	ill_t		*ill = (ill_t *)q->q_ptr;
12403 	mblk_t		*mp = *mpp;
12404 	mblk_t		*t_mp;
12405 	ipaddr_t	dst;
12406 	uint8_t		proto = ipha->ipha_protocol;
12407 	uint32_t	sum_val;
12408 	uint16_t	sum_flags;
12409 	ipf_t		*ipf;
12410 	ipf_t		**ipfp;
12411 	ipfb_t		*ipfb;
12412 	uint16_t	ident;
12413 	uint32_t	offset;
12414 	ipaddr_t	src;
12415 	uint_t		hdr_length;
12416 	uint32_t	end;
12417 	mblk_t		*mp1;
12418 	mblk_t		*tail_mp;
12419 	size_t		count;
12420 	size_t		msg_len;
12421 	uint8_t		ecn_info = 0;
12422 	uint32_t	packet_size;
12423 	boolean_t	pruned = B_FALSE;
12424 	ip_stack_t *ipst = ill->ill_ipst;
12425 
12426 	if (cksum_val != NULL)
12427 		*cksum_val = 0;
12428 	if (cksum_flags != NULL)
12429 		*cksum_flags = 0;
12430 
12431 	/*
12432 	 * Drop the fragmented as early as possible, if
12433 	 * we don't have resource(s) to re-assemble.
12434 	 */
12435 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12436 		freemsg(mp);
12437 		return (B_FALSE);
12438 	}
12439 
12440 	/* Check for fragmentation offset; return if there's none */
12441 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12442 	    (IPH_MF | IPH_OFFSET)) == 0)
12443 		return (B_TRUE);
12444 
12445 	/*
12446 	 * We utilize hardware computed checksum info only for UDP since
12447 	 * IP fragmentation is a normal occurence for the protocol.  In
12448 	 * addition, checksum offload support for IP fragments carrying
12449 	 * UDP payload is commonly implemented across network adapters.
12450 	 */
12451 	ASSERT(ill != NULL);
12452 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12453 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12454 		mblk_t *mp1 = mp->b_cont;
12455 		int32_t len;
12456 
12457 		/* Record checksum information from the packet */
12458 		sum_val = (uint32_t)DB_CKSUM16(mp);
12459 		sum_flags = DB_CKSUMFLAGS(mp);
12460 
12461 		/* IP payload offset from beginning of mblk */
12462 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12463 
12464 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12465 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12466 		    offset >= DB_CKSUMSTART(mp) &&
12467 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12468 			uint32_t adj;
12469 			/*
12470 			 * Partial checksum has been calculated by hardware
12471 			 * and attached to the packet; in addition, any
12472 			 * prepended extraneous data is even byte aligned.
12473 			 * If any such data exists, we adjust the checksum;
12474 			 * this would also handle any postpended data.
12475 			 */
12476 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12477 			    mp, mp1, len, adj);
12478 
12479 			/* One's complement subtract extraneous checksum */
12480 			if (adj >= sum_val)
12481 				sum_val = ~(adj - sum_val) & 0xFFFF;
12482 			else
12483 				sum_val -= adj;
12484 		}
12485 	} else {
12486 		sum_val = 0;
12487 		sum_flags = 0;
12488 	}
12489 
12490 	/* Clear hardware checksumming flag */
12491 	DB_CKSUMFLAGS(mp) = 0;
12492 
12493 	ident = ipha->ipha_ident;
12494 	offset = (frag_offset_flags << 3) & 0xFFFF;
12495 	src = ipha->ipha_src;
12496 	dst = ipha->ipha_dst;
12497 	hdr_length = IPH_HDR_LENGTH(ipha);
12498 	end = ntohs(ipha->ipha_length) - hdr_length;
12499 
12500 	/* If end == 0 then we have a packet with no data, so just free it */
12501 	if (end == 0) {
12502 		freemsg(mp);
12503 		return (B_FALSE);
12504 	}
12505 
12506 	/* Record the ECN field info. */
12507 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12508 	if (offset != 0) {
12509 		/*
12510 		 * If this isn't the first piece, strip the header, and
12511 		 * add the offset to the end value.
12512 		 */
12513 		mp->b_rptr += hdr_length;
12514 		end += offset;
12515 	}
12516 
12517 	msg_len = MBLKSIZE(mp);
12518 	tail_mp = mp;
12519 	while (tail_mp->b_cont != NULL) {
12520 		tail_mp = tail_mp->b_cont;
12521 		msg_len += MBLKSIZE(tail_mp);
12522 	}
12523 
12524 	/* If the reassembly list for this ILL will get too big, prune it */
12525 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12526 	    ipst->ips_ip_reass_queue_bytes) {
12527 		ill_frag_prune(ill,
12528 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12529 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12530 		pruned = B_TRUE;
12531 	}
12532 
12533 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12534 	mutex_enter(&ipfb->ipfb_lock);
12535 
12536 	ipfp = &ipfb->ipfb_ipf;
12537 	/* Try to find an existing fragment queue for this packet. */
12538 	for (;;) {
12539 		ipf = ipfp[0];
12540 		if (ipf != NULL) {
12541 			/*
12542 			 * It has to match on ident and src/dst address.
12543 			 */
12544 			if (ipf->ipf_ident == ident &&
12545 			    ipf->ipf_src == src &&
12546 			    ipf->ipf_dst == dst &&
12547 			    ipf->ipf_protocol == proto) {
12548 				/*
12549 				 * If we have received too many
12550 				 * duplicate fragments for this packet
12551 				 * free it.
12552 				 */
12553 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12554 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12555 					freemsg(mp);
12556 					mutex_exit(&ipfb->ipfb_lock);
12557 					return (B_FALSE);
12558 				}
12559 				/* Found it. */
12560 				break;
12561 			}
12562 			ipfp = &ipf->ipf_hash_next;
12563 			continue;
12564 		}
12565 
12566 		/*
12567 		 * If we pruned the list, do we want to store this new
12568 		 * fragment?. We apply an optimization here based on the
12569 		 * fact that most fragments will be received in order.
12570 		 * So if the offset of this incoming fragment is zero,
12571 		 * it is the first fragment of a new packet. We will
12572 		 * keep it.  Otherwise drop the fragment, as we have
12573 		 * probably pruned the packet already (since the
12574 		 * packet cannot be found).
12575 		 */
12576 		if (pruned && offset != 0) {
12577 			mutex_exit(&ipfb->ipfb_lock);
12578 			freemsg(mp);
12579 			return (B_FALSE);
12580 		}
12581 
12582 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12583 			/*
12584 			 * Too many fragmented packets in this hash
12585 			 * bucket. Free the oldest.
12586 			 */
12587 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12588 		}
12589 
12590 		/* New guy.  Allocate a frag message. */
12591 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12592 		if (mp1 == NULL) {
12593 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12594 			freemsg(mp);
12595 reass_done:
12596 			mutex_exit(&ipfb->ipfb_lock);
12597 			return (B_FALSE);
12598 		}
12599 
12600 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12601 		mp1->b_cont = mp;
12602 
12603 		/* Initialize the fragment header. */
12604 		ipf = (ipf_t *)mp1->b_rptr;
12605 		ipf->ipf_mp = mp1;
12606 		ipf->ipf_ptphn = ipfp;
12607 		ipfp[0] = ipf;
12608 		ipf->ipf_hash_next = NULL;
12609 		ipf->ipf_ident = ident;
12610 		ipf->ipf_protocol = proto;
12611 		ipf->ipf_src = src;
12612 		ipf->ipf_dst = dst;
12613 		ipf->ipf_nf_hdr_len = 0;
12614 		/* Record reassembly start time. */
12615 		ipf->ipf_timestamp = gethrestime_sec();
12616 		/* Record ipf generation and account for frag header */
12617 		ipf->ipf_gen = ill->ill_ipf_gen++;
12618 		ipf->ipf_count = MBLKSIZE(mp1);
12619 		ipf->ipf_last_frag_seen = B_FALSE;
12620 		ipf->ipf_ecn = ecn_info;
12621 		ipf->ipf_num_dups = 0;
12622 		ipfb->ipfb_frag_pkts++;
12623 		ipf->ipf_checksum = 0;
12624 		ipf->ipf_checksum_flags = 0;
12625 
12626 		/* Store checksum value in fragment header */
12627 		if (sum_flags != 0) {
12628 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12629 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12630 			ipf->ipf_checksum = sum_val;
12631 			ipf->ipf_checksum_flags = sum_flags;
12632 		}
12633 
12634 		/*
12635 		 * We handle reassembly two ways.  In the easy case,
12636 		 * where all the fragments show up in order, we do
12637 		 * minimal bookkeeping, and just clip new pieces on
12638 		 * the end.  If we ever see a hole, then we go off
12639 		 * to ip_reassemble which has to mark the pieces and
12640 		 * keep track of the number of holes, etc.  Obviously,
12641 		 * the point of having both mechanisms is so we can
12642 		 * handle the easy case as efficiently as possible.
12643 		 */
12644 		if (offset == 0) {
12645 			/* Easy case, in-order reassembly so far. */
12646 			ipf->ipf_count += msg_len;
12647 			ipf->ipf_tail_mp = tail_mp;
12648 			/*
12649 			 * Keep track of next expected offset in
12650 			 * ipf_end.
12651 			 */
12652 			ipf->ipf_end = end;
12653 			ipf->ipf_nf_hdr_len = hdr_length;
12654 		} else {
12655 			/* Hard case, hole at the beginning. */
12656 			ipf->ipf_tail_mp = NULL;
12657 			/*
12658 			 * ipf_end == 0 means that we have given up
12659 			 * on easy reassembly.
12660 			 */
12661 			ipf->ipf_end = 0;
12662 
12663 			/* Forget checksum offload from now on */
12664 			ipf->ipf_checksum_flags = 0;
12665 
12666 			/*
12667 			 * ipf_hole_cnt is set by ip_reassemble.
12668 			 * ipf_count is updated by ip_reassemble.
12669 			 * No need to check for return value here
12670 			 * as we don't expect reassembly to complete
12671 			 * or fail for the first fragment itself.
12672 			 */
12673 			(void) ip_reassemble(mp, ipf,
12674 			    (frag_offset_flags & IPH_OFFSET) << 3,
12675 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12676 		}
12677 		/* Update per ipfb and ill byte counts */
12678 		ipfb->ipfb_count += ipf->ipf_count;
12679 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12680 		ill->ill_frag_count += ipf->ipf_count;
12681 		/* If the frag timer wasn't already going, start it. */
12682 		mutex_enter(&ill->ill_lock);
12683 		ill_frag_timer_start(ill);
12684 		mutex_exit(&ill->ill_lock);
12685 		goto reass_done;
12686 	}
12687 
12688 	/*
12689 	 * If the packet's flag has changed (it could be coming up
12690 	 * from an interface different than the previous, therefore
12691 	 * possibly different checksum capability), then forget about
12692 	 * any stored checksum states.  Otherwise add the value to
12693 	 * the existing one stored in the fragment header.
12694 	 */
12695 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12696 		sum_val += ipf->ipf_checksum;
12697 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12698 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12699 		ipf->ipf_checksum = sum_val;
12700 	} else if (ipf->ipf_checksum_flags != 0) {
12701 		/* Forget checksum offload from now on */
12702 		ipf->ipf_checksum_flags = 0;
12703 	}
12704 
12705 	/*
12706 	 * We have a new piece of a datagram which is already being
12707 	 * reassembled.  Update the ECN info if all IP fragments
12708 	 * are ECN capable.  If there is one which is not, clear
12709 	 * all the info.  If there is at least one which has CE
12710 	 * code point, IP needs to report that up to transport.
12711 	 */
12712 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12713 		if (ecn_info == IPH_ECN_CE)
12714 			ipf->ipf_ecn = IPH_ECN_CE;
12715 	} else {
12716 		ipf->ipf_ecn = IPH_ECN_NECT;
12717 	}
12718 	if (offset && ipf->ipf_end == offset) {
12719 		/* The new fragment fits at the end */
12720 		ipf->ipf_tail_mp->b_cont = mp;
12721 		/* Update the byte count */
12722 		ipf->ipf_count += msg_len;
12723 		/* Update per ipfb and ill byte counts */
12724 		ipfb->ipfb_count += msg_len;
12725 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12726 		ill->ill_frag_count += msg_len;
12727 		if (frag_offset_flags & IPH_MF) {
12728 			/* More to come. */
12729 			ipf->ipf_end = end;
12730 			ipf->ipf_tail_mp = tail_mp;
12731 			goto reass_done;
12732 		}
12733 	} else {
12734 		/* Go do the hard cases. */
12735 		int ret;
12736 
12737 		if (offset == 0)
12738 			ipf->ipf_nf_hdr_len = hdr_length;
12739 
12740 		/* Save current byte count */
12741 		count = ipf->ipf_count;
12742 		ret = ip_reassemble(mp, ipf,
12743 		    (frag_offset_flags & IPH_OFFSET) << 3,
12744 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12745 		/* Count of bytes added and subtracted (freeb()ed) */
12746 		count = ipf->ipf_count - count;
12747 		if (count) {
12748 			/* Update per ipfb and ill byte counts */
12749 			ipfb->ipfb_count += count;
12750 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12751 			ill->ill_frag_count += count;
12752 		}
12753 		if (ret == IP_REASS_PARTIAL) {
12754 			goto reass_done;
12755 		} else if (ret == IP_REASS_FAILED) {
12756 			/* Reassembly failed. Free up all resources */
12757 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12758 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12759 				IP_REASS_SET_START(t_mp, 0);
12760 				IP_REASS_SET_END(t_mp, 0);
12761 			}
12762 			freemsg(mp);
12763 			goto reass_done;
12764 		}
12765 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12766 	}
12767 	/*
12768 	 * We have completed reassembly.  Unhook the frag header from
12769 	 * the reassembly list.
12770 	 *
12771 	 * Before we free the frag header, record the ECN info
12772 	 * to report back to the transport.
12773 	 */
12774 	ecn_info = ipf->ipf_ecn;
12775 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12776 	ipfp = ipf->ipf_ptphn;
12777 
12778 	/* We need to supply these to caller */
12779 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12780 		sum_val = ipf->ipf_checksum;
12781 	else
12782 		sum_val = 0;
12783 
12784 	mp1 = ipf->ipf_mp;
12785 	count = ipf->ipf_count;
12786 	ipf = ipf->ipf_hash_next;
12787 	if (ipf != NULL)
12788 		ipf->ipf_ptphn = ipfp;
12789 	ipfp[0] = ipf;
12790 	ill->ill_frag_count -= count;
12791 	ASSERT(ipfb->ipfb_count >= count);
12792 	ipfb->ipfb_count -= count;
12793 	ipfb->ipfb_frag_pkts--;
12794 	mutex_exit(&ipfb->ipfb_lock);
12795 	/* Ditch the frag header. */
12796 	mp = mp1->b_cont;
12797 
12798 	freeb(mp1);
12799 
12800 	/* Restore original IP length in header. */
12801 	packet_size = (uint32_t)msgdsize(mp);
12802 	if (packet_size > IP_MAXPACKET) {
12803 		freemsg(mp);
12804 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12805 		return (B_FALSE);
12806 	}
12807 
12808 	if (DB_REF(mp) > 1) {
12809 		mblk_t *mp2 = copymsg(mp);
12810 
12811 		freemsg(mp);
12812 		if (mp2 == NULL) {
12813 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12814 			return (B_FALSE);
12815 		}
12816 		mp = mp2;
12817 	}
12818 	ipha = (ipha_t *)mp->b_rptr;
12819 
12820 	ipha->ipha_length = htons((uint16_t)packet_size);
12821 	/* We're now complete, zip the frag state */
12822 	ipha->ipha_fragment_offset_and_flags = 0;
12823 	/* Record the ECN info. */
12824 	ipha->ipha_type_of_service &= 0xFC;
12825 	ipha->ipha_type_of_service |= ecn_info;
12826 	*mpp = mp;
12827 
12828 	/* Reassembly is successful; return checksum information if needed */
12829 	if (cksum_val != NULL)
12830 		*cksum_val = sum_val;
12831 	if (cksum_flags != NULL)
12832 		*cksum_flags = sum_flags;
12833 
12834 	return (B_TRUE);
12835 }
12836 
12837 /*
12838  * Perform ip header check sum update local options.
12839  * return B_TRUE if all is well, else return B_FALSE and release
12840  * the mp. caller is responsible for decrementing ire ref cnt.
12841  */
12842 static boolean_t
12843 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12844     ip_stack_t *ipst)
12845 {
12846 	mblk_t		*first_mp;
12847 	boolean_t	mctl_present;
12848 	uint16_t	sum;
12849 
12850 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12851 	/*
12852 	 * Don't do the checksum if it has gone through AH/ESP
12853 	 * processing.
12854 	 */
12855 	if (!mctl_present) {
12856 		sum = ip_csum_hdr(ipha);
12857 		if (sum != 0) {
12858 			if (ill != NULL) {
12859 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12860 			} else {
12861 				BUMP_MIB(&ipst->ips_ip_mib,
12862 				    ipIfStatsInCksumErrs);
12863 			}
12864 			freemsg(first_mp);
12865 			return (B_FALSE);
12866 		}
12867 	}
12868 
12869 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12870 		if (mctl_present)
12871 			freeb(first_mp);
12872 		return (B_FALSE);
12873 	}
12874 
12875 	return (B_TRUE);
12876 }
12877 
12878 /*
12879  * All udp packet are delivered to the local host via this routine.
12880  */
12881 void
12882 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12883     ill_t *recv_ill)
12884 {
12885 	uint32_t	sum;
12886 	uint32_t	u1;
12887 	boolean_t	mctl_present;
12888 	conn_t		*connp;
12889 	mblk_t		*first_mp;
12890 	uint16_t	*up;
12891 	ill_t		*ill = (ill_t *)q->q_ptr;
12892 	uint16_t	reass_hck_flags = 0;
12893 	ip_stack_t	*ipst;
12894 
12895 	ASSERT(recv_ill != NULL);
12896 	ipst = recv_ill->ill_ipst;
12897 
12898 #define	rptr    ((uchar_t *)ipha)
12899 
12900 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12901 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12902 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12903 	ASSERT(ill != NULL);
12904 
12905 	/*
12906 	 * FAST PATH for udp packets
12907 	 */
12908 
12909 	/* u1 is # words of IP options */
12910 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12911 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12912 
12913 	/* IP options present */
12914 	if (u1 != 0)
12915 		goto ipoptions;
12916 
12917 	/* Check the IP header checksum.  */
12918 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12919 		/* Clear the IP header h/w cksum flag */
12920 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12921 	} else {
12922 #define	uph	((uint16_t *)ipha)
12923 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12924 		    uph[6] + uph[7] + uph[8] + uph[9];
12925 #undef	uph
12926 		/* finish doing IP checksum */
12927 		sum = (sum & 0xFFFF) + (sum >> 16);
12928 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12929 		/*
12930 		 * Don't verify header checksum if this packet is coming
12931 		 * back from AH/ESP as we already did it.
12932 		 */
12933 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12934 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12935 			freemsg(first_mp);
12936 			return;
12937 		}
12938 	}
12939 
12940 	/*
12941 	 * Count for SNMP of inbound packets for ire.
12942 	 * if mctl is present this might be a secure packet and
12943 	 * has already been counted for in ip_proto_input().
12944 	 */
12945 	if (!mctl_present) {
12946 		UPDATE_IB_PKT_COUNT(ire);
12947 		ire->ire_last_used_time = lbolt;
12948 	}
12949 
12950 	/* packet part of fragmented IP packet? */
12951 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12952 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12953 		goto fragmented;
12954 	}
12955 
12956 	/* u1 = IP header length (20 bytes) */
12957 	u1 = IP_SIMPLE_HDR_LENGTH;
12958 
12959 	/* packet does not contain complete IP & UDP headers */
12960 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12961 		goto udppullup;
12962 
12963 	/* up points to UDP header */
12964 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12965 #define	iphs    ((uint16_t *)ipha)
12966 
12967 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12968 	if (up[3] != 0) {
12969 		mblk_t *mp1 = mp->b_cont;
12970 		boolean_t cksum_err;
12971 		uint16_t hck_flags = 0;
12972 
12973 		/* Pseudo-header checksum */
12974 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12975 		    iphs[9] + up[2];
12976 
12977 		/*
12978 		 * Revert to software checksum calculation if the interface
12979 		 * isn't capable of checksum offload or if IPsec is present.
12980 		 */
12981 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12982 			hck_flags = DB_CKSUMFLAGS(mp);
12983 
12984 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12985 			IP_STAT(ipst, ip_in_sw_cksum);
12986 
12987 		IP_CKSUM_RECV(hck_flags, u1,
12988 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12989 		    (int32_t)((uchar_t *)up - rptr),
12990 		    mp, mp1, cksum_err);
12991 
12992 		if (cksum_err) {
12993 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12994 			if (hck_flags & HCK_FULLCKSUM)
12995 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12996 			else if (hck_flags & HCK_PARTIALCKSUM)
12997 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12998 			else
12999 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13000 
13001 			freemsg(first_mp);
13002 			return;
13003 		}
13004 	}
13005 
13006 	/* Non-fragmented broadcast or multicast packet? */
13007 	if (ire->ire_type == IRE_BROADCAST)
13008 		goto udpslowpath;
13009 
13010 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
13011 	    ire->ire_zoneid, ipst)) != NULL) {
13012 		ASSERT(connp->conn_upq != NULL);
13013 		IP_STAT(ipst, ip_udp_fast_path);
13014 
13015 		if (CONN_UDP_FLOWCTLD(connp)) {
13016 			freemsg(mp);
13017 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
13018 		} else {
13019 			if (!mctl_present) {
13020 				BUMP_MIB(ill->ill_ip_mib,
13021 				    ipIfStatsHCInDelivers);
13022 			}
13023 			/*
13024 			 * mp and first_mp can change.
13025 			 */
13026 			if (ip_udp_check(q, connp, recv_ill,
13027 			    ipha, &mp, &first_mp, mctl_present)) {
13028 				/* Send it upstream */
13029 				CONN_UDP_RECV(connp, mp);
13030 			}
13031 		}
13032 		/*
13033 		 * freeb() cannot deal with null mblk being passed
13034 		 * in and first_mp can be set to null in the call
13035 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13036 		 */
13037 		if (mctl_present && first_mp != NULL) {
13038 			freeb(first_mp);
13039 		}
13040 		CONN_DEC_REF(connp);
13041 		return;
13042 	}
13043 
13044 	/*
13045 	 * if we got here we know the packet is not fragmented and
13046 	 * has no options. The classifier could not find a conn_t and
13047 	 * most likely its an icmp packet so send it through slow path.
13048 	 */
13049 
13050 	goto udpslowpath;
13051 
13052 ipoptions:
13053 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13054 		goto slow_done;
13055 	}
13056 
13057 	UPDATE_IB_PKT_COUNT(ire);
13058 	ire->ire_last_used_time = lbolt;
13059 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13060 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13061 fragmented:
13062 		/*
13063 		 * "sum" and "reass_hck_flags" are non-zero if the
13064 		 * reassembled packet has a valid hardware computed
13065 		 * checksum information associated with it.
13066 		 */
13067 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13068 			goto slow_done;
13069 		/*
13070 		 * Make sure that first_mp points back to mp as
13071 		 * the mp we came in with could have changed in
13072 		 * ip_rput_fragment().
13073 		 */
13074 		ASSERT(!mctl_present);
13075 		ipha = (ipha_t *)mp->b_rptr;
13076 		first_mp = mp;
13077 	}
13078 
13079 	/* Now we have a complete datagram, destined for this machine. */
13080 	u1 = IPH_HDR_LENGTH(ipha);
13081 	/* Pull up the UDP header, if necessary. */
13082 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13083 udppullup:
13084 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13085 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13086 			freemsg(first_mp);
13087 			goto slow_done;
13088 		}
13089 		ipha = (ipha_t *)mp->b_rptr;
13090 	}
13091 
13092 	/*
13093 	 * Validate the checksum for the reassembled packet; for the
13094 	 * pullup case we calculate the payload checksum in software.
13095 	 */
13096 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13097 	if (up[3] != 0) {
13098 		boolean_t cksum_err;
13099 
13100 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13101 			IP_STAT(ipst, ip_in_sw_cksum);
13102 
13103 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13104 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13105 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13106 		    iphs[9] + up[2], sum, cksum_err);
13107 
13108 		if (cksum_err) {
13109 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13110 
13111 			if (reass_hck_flags & HCK_FULLCKSUM)
13112 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13113 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13114 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13115 			else
13116 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13117 
13118 			freemsg(first_mp);
13119 			goto slow_done;
13120 		}
13121 	}
13122 udpslowpath:
13123 
13124 	/* Clear hardware checksum flag to be safe */
13125 	DB_CKSUMFLAGS(mp) = 0;
13126 
13127 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13128 	    (ire->ire_type == IRE_BROADCAST),
13129 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13130 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13131 
13132 slow_done:
13133 	IP_STAT(ipst, ip_udp_slow_path);
13134 	return;
13135 
13136 #undef  iphs
13137 #undef  rptr
13138 }
13139 
13140 /* ARGSUSED */
13141 static mblk_t *
13142 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13143     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13144     ill_rx_ring_t *ill_ring)
13145 {
13146 	conn_t		*connp;
13147 	uint32_t	sum;
13148 	uint32_t	u1;
13149 	uint16_t	*up;
13150 	int		offset;
13151 	ssize_t		len;
13152 	mblk_t		*mp1;
13153 	boolean_t	syn_present = B_FALSE;
13154 	tcph_t		*tcph;
13155 	uint_t		ip_hdr_len;
13156 	ill_t		*ill = (ill_t *)q->q_ptr;
13157 	zoneid_t	zoneid = ire->ire_zoneid;
13158 	boolean_t	cksum_err;
13159 	uint16_t	hck_flags = 0;
13160 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13161 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13162 
13163 #define	rptr	((uchar_t *)ipha)
13164 
13165 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13166 	ASSERT(ill != NULL);
13167 
13168 	/*
13169 	 * FAST PATH for tcp packets
13170 	 */
13171 
13172 	/* u1 is # words of IP options */
13173 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13174 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13175 
13176 	/* IP options present */
13177 	if (u1) {
13178 		goto ipoptions;
13179 	} else {
13180 		/* Check the IP header checksum.  */
13181 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13182 			/* Clear the IP header h/w cksum flag */
13183 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13184 		} else {
13185 #define	uph	((uint16_t *)ipha)
13186 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13187 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13188 #undef	uph
13189 			/* finish doing IP checksum */
13190 			sum = (sum & 0xFFFF) + (sum >> 16);
13191 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13192 			/*
13193 			 * Don't verify header checksum if this packet
13194 			 * is coming back from AH/ESP as we already did it.
13195 			 */
13196 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13197 				BUMP_MIB(ill->ill_ip_mib,
13198 				    ipIfStatsInCksumErrs);
13199 				goto error;
13200 			}
13201 		}
13202 	}
13203 
13204 	if (!mctl_present) {
13205 		UPDATE_IB_PKT_COUNT(ire);
13206 		ire->ire_last_used_time = lbolt;
13207 	}
13208 
13209 	/* packet part of fragmented IP packet? */
13210 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13211 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13212 		goto fragmented;
13213 	}
13214 
13215 	/* u1 = IP header length (20 bytes) */
13216 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13217 
13218 	/* does packet contain IP+TCP headers? */
13219 	len = mp->b_wptr - rptr;
13220 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13221 		IP_STAT(ipst, ip_tcppullup);
13222 		goto tcppullup;
13223 	}
13224 
13225 	/* TCP options present? */
13226 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13227 
13228 	/*
13229 	 * If options need to be pulled up, then goto tcpoptions.
13230 	 * otherwise we are still in the fast path
13231 	 */
13232 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13233 		IP_STAT(ipst, ip_tcpoptions);
13234 		goto tcpoptions;
13235 	}
13236 
13237 	/* multiple mblks of tcp data? */
13238 	if ((mp1 = mp->b_cont) != NULL) {
13239 		/* more then two? */
13240 		if (mp1->b_cont != NULL) {
13241 			IP_STAT(ipst, ip_multipkttcp);
13242 			goto multipkttcp;
13243 		}
13244 		len += mp1->b_wptr - mp1->b_rptr;
13245 	}
13246 
13247 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13248 
13249 	/* part of pseudo checksum */
13250 
13251 	/* TCP datagram length */
13252 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13253 
13254 #define	iphs    ((uint16_t *)ipha)
13255 
13256 #ifdef	_BIG_ENDIAN
13257 	u1 += IPPROTO_TCP;
13258 #else
13259 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13260 #endif
13261 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13262 
13263 	/*
13264 	 * Revert to software checksum calculation if the interface
13265 	 * isn't capable of checksum offload or if IPsec is present.
13266 	 */
13267 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13268 		hck_flags = DB_CKSUMFLAGS(mp);
13269 
13270 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13271 		IP_STAT(ipst, ip_in_sw_cksum);
13272 
13273 	IP_CKSUM_RECV(hck_flags, u1,
13274 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13275 	    (int32_t)((uchar_t *)up - rptr),
13276 	    mp, mp1, cksum_err);
13277 
13278 	if (cksum_err) {
13279 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13280 
13281 		if (hck_flags & HCK_FULLCKSUM)
13282 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13283 		else if (hck_flags & HCK_PARTIALCKSUM)
13284 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13285 		else
13286 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13287 
13288 		goto error;
13289 	}
13290 
13291 try_again:
13292 
13293 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13294 		    zoneid, ipst)) == NULL) {
13295 		/* Send the TH_RST */
13296 		goto no_conn;
13297 	}
13298 
13299 	/*
13300 	 * TCP FAST PATH for AF_INET socket.
13301 	 *
13302 	 * TCP fast path to avoid extra work. An AF_INET socket type
13303 	 * does not have facility to receive extra information via
13304 	 * ip_process or ip_add_info. Also, when the connection was
13305 	 * established, we made a check if this connection is impacted
13306 	 * by any global IPSec policy or per connection policy (a
13307 	 * policy that comes in effect later will not apply to this
13308 	 * connection). Since all this can be determined at the
13309 	 * connection establishment time, a quick check of flags
13310 	 * can avoid extra work.
13311 	 */
13312 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13313 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13314 		ASSERT(first_mp == mp);
13315 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13316 		SET_SQUEUE(mp, tcp_rput_data, connp);
13317 		return (mp);
13318 	}
13319 
13320 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13321 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13322 		if (IPCL_IS_TCP(connp)) {
13323 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13324 			DB_CKSUMSTART(mp) =
13325 			    (intptr_t)ip_squeue_get(ill_ring);
13326 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13327 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13328 				BUMP_MIB(ill->ill_ip_mib,
13329 				    ipIfStatsHCInDelivers);
13330 				SET_SQUEUE(mp, connp->conn_recv, connp);
13331 				return (mp);
13332 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13333 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13334 				BUMP_MIB(ill->ill_ip_mib,
13335 				    ipIfStatsHCInDelivers);
13336 				ip_squeue_enter_unbound++;
13337 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13338 				    connp);
13339 				return (mp);
13340 			}
13341 			syn_present = B_TRUE;
13342 		}
13343 
13344 	}
13345 
13346 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13347 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13348 
13349 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13350 		/* No need to send this packet to TCP */
13351 		if ((flags & TH_RST) || (flags & TH_URG)) {
13352 			CONN_DEC_REF(connp);
13353 			freemsg(first_mp);
13354 			return (NULL);
13355 		}
13356 		if (flags & TH_ACK) {
13357 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13358 			    ipst->ips_netstack->netstack_tcp);
13359 			CONN_DEC_REF(connp);
13360 			return (NULL);
13361 		}
13362 
13363 		CONN_DEC_REF(connp);
13364 		freemsg(first_mp);
13365 		return (NULL);
13366 	}
13367 
13368 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13369 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13370 		    ipha, NULL, mctl_present);
13371 		if (first_mp == NULL) {
13372 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13373 			CONN_DEC_REF(connp);
13374 			return (NULL);
13375 		}
13376 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13377 			ASSERT(syn_present);
13378 			if (mctl_present) {
13379 				ASSERT(first_mp != mp);
13380 				first_mp->b_datap->db_struioflag |=
13381 				    STRUIO_POLICY;
13382 			} else {
13383 				ASSERT(first_mp == mp);
13384 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13385 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13386 			}
13387 		} else {
13388 			/*
13389 			 * Discard first_mp early since we're dealing with a
13390 			 * fully-connected conn_t and tcp doesn't do policy in
13391 			 * this case.
13392 			 */
13393 			if (mctl_present) {
13394 				freeb(first_mp);
13395 				mctl_present = B_FALSE;
13396 			}
13397 			first_mp = mp;
13398 		}
13399 	}
13400 
13401 	/* Initiate IPPF processing for fastpath */
13402 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13403 		uint32_t	ill_index;
13404 
13405 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13406 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13407 		if (mp == NULL) {
13408 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13409 			    "deferred/dropped during IPPF processing\n"));
13410 			CONN_DEC_REF(connp);
13411 			if (mctl_present)
13412 				freeb(first_mp);
13413 			return (NULL);
13414 		} else if (mctl_present) {
13415 			/*
13416 			 * ip_process might return a new mp.
13417 			 */
13418 			ASSERT(first_mp != mp);
13419 			first_mp->b_cont = mp;
13420 		} else {
13421 			first_mp = mp;
13422 		}
13423 
13424 	}
13425 
13426 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13427 		/*
13428 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13429 		 * make sure IPF_RECVIF is passed to ip_add_info.
13430 		 */
13431 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13432 		    IPCL_ZONEID(connp), ipst);
13433 		if (mp == NULL) {
13434 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13435 			CONN_DEC_REF(connp);
13436 			if (mctl_present)
13437 				freeb(first_mp);
13438 			return (NULL);
13439 		} else if (mctl_present) {
13440 			/*
13441 			 * ip_add_info might return a new mp.
13442 			 */
13443 			ASSERT(first_mp != mp);
13444 			first_mp->b_cont = mp;
13445 		} else {
13446 			first_mp = mp;
13447 		}
13448 	}
13449 
13450 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13451 	if (IPCL_IS_TCP(connp)) {
13452 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13453 		return (first_mp);
13454 	} else {
13455 		putnext(connp->conn_rq, first_mp);
13456 		CONN_DEC_REF(connp);
13457 		return (NULL);
13458 	}
13459 
13460 no_conn:
13461 	/* Initiate IPPf processing, if needed. */
13462 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13463 		uint32_t ill_index;
13464 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13465 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13466 		if (first_mp == NULL) {
13467 			return (NULL);
13468 		}
13469 	}
13470 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13471 
13472 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13473 	    ipst->ips_netstack->netstack_tcp);
13474 	return (NULL);
13475 ipoptions:
13476 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13477 		goto slow_done;
13478 	}
13479 
13480 	UPDATE_IB_PKT_COUNT(ire);
13481 	ire->ire_last_used_time = lbolt;
13482 
13483 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13484 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13485 fragmented:
13486 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13487 			if (mctl_present)
13488 				freeb(first_mp);
13489 			goto slow_done;
13490 		}
13491 		/*
13492 		 * Make sure that first_mp points back to mp as
13493 		 * the mp we came in with could have changed in
13494 		 * ip_rput_fragment().
13495 		 */
13496 		ASSERT(!mctl_present);
13497 		ipha = (ipha_t *)mp->b_rptr;
13498 		first_mp = mp;
13499 	}
13500 
13501 	/* Now we have a complete datagram, destined for this machine. */
13502 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13503 
13504 	len = mp->b_wptr - mp->b_rptr;
13505 	/* Pull up a minimal TCP header, if necessary. */
13506 	if (len < (u1 + 20)) {
13507 tcppullup:
13508 		if (!pullupmsg(mp, u1 + 20)) {
13509 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13510 			goto error;
13511 		}
13512 		ipha = (ipha_t *)mp->b_rptr;
13513 		len = mp->b_wptr - mp->b_rptr;
13514 	}
13515 
13516 	/*
13517 	 * Extract the offset field from the TCP header.  As usual, we
13518 	 * try to help the compiler more than the reader.
13519 	 */
13520 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13521 	if (offset != 5) {
13522 tcpoptions:
13523 		if (offset < 5) {
13524 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13525 			goto error;
13526 		}
13527 		/*
13528 		 * There must be TCP options.
13529 		 * Make sure we can grab them.
13530 		 */
13531 		offset <<= 2;
13532 		offset += u1;
13533 		if (len < offset) {
13534 			if (!pullupmsg(mp, offset)) {
13535 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13536 				goto error;
13537 			}
13538 			ipha = (ipha_t *)mp->b_rptr;
13539 			len = mp->b_wptr - rptr;
13540 		}
13541 	}
13542 
13543 	/* Get the total packet length in len, including headers. */
13544 	if (mp->b_cont) {
13545 multipkttcp:
13546 		len = msgdsize(mp);
13547 	}
13548 
13549 	/*
13550 	 * Check the TCP checksum by pulling together the pseudo-
13551 	 * header checksum, and passing it to ip_csum to be added in
13552 	 * with the TCP datagram.
13553 	 *
13554 	 * Since we are not using the hwcksum if available we must
13555 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13556 	 * If either of these fails along the way the mblk is freed.
13557 	 * If this logic ever changes and mblk is reused to say send
13558 	 * ICMP's back, then this flag may need to be cleared in
13559 	 * other places as well.
13560 	 */
13561 	DB_CKSUMFLAGS(mp) = 0;
13562 
13563 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13564 
13565 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13566 #ifdef	_BIG_ENDIAN
13567 	u1 += IPPROTO_TCP;
13568 #else
13569 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13570 #endif
13571 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13572 	/*
13573 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13574 	 */
13575 	IP_STAT(ipst, ip_in_sw_cksum);
13576 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13577 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13578 		goto error;
13579 	}
13580 
13581 	IP_STAT(ipst, ip_tcp_slow_path);
13582 	goto try_again;
13583 #undef  iphs
13584 #undef  rptr
13585 
13586 error:
13587 	freemsg(first_mp);
13588 slow_done:
13589 	return (NULL);
13590 }
13591 
13592 /* ARGSUSED */
13593 static void
13594 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13595     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13596 {
13597 	conn_t		*connp;
13598 	uint32_t	sum;
13599 	uint32_t	u1;
13600 	ssize_t		len;
13601 	sctp_hdr_t	*sctph;
13602 	zoneid_t	zoneid = ire->ire_zoneid;
13603 	uint32_t	pktsum;
13604 	uint32_t	calcsum;
13605 	uint32_t	ports;
13606 	in6_addr_t	map_src, map_dst;
13607 	ill_t		*ill = (ill_t *)q->q_ptr;
13608 	ip_stack_t	*ipst;
13609 	sctp_stack_t	*sctps;
13610 
13611 	ASSERT(recv_ill != NULL);
13612 	ipst = recv_ill->ill_ipst;
13613 	sctps = ipst->ips_netstack->netstack_sctp;
13614 
13615 #define	rptr	((uchar_t *)ipha)
13616 
13617 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13618 	ASSERT(ill != NULL);
13619 
13620 	/* u1 is # words of IP options */
13621 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13622 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13623 
13624 	/* IP options present */
13625 	if (u1 > 0) {
13626 		goto ipoptions;
13627 	} else {
13628 		/* Check the IP header checksum.  */
13629 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13630 #define	uph	((uint16_t *)ipha)
13631 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13632 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13633 #undef	uph
13634 			/* finish doing IP checksum */
13635 			sum = (sum & 0xFFFF) + (sum >> 16);
13636 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13637 			/*
13638 			 * Don't verify header checksum if this packet
13639 			 * is coming back from AH/ESP as we already did it.
13640 			 */
13641 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13642 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13643 				goto error;
13644 			}
13645 		}
13646 		/*
13647 		 * Since there is no SCTP h/w cksum support yet, just
13648 		 * clear the flag.
13649 		 */
13650 		DB_CKSUMFLAGS(mp) = 0;
13651 	}
13652 
13653 	/*
13654 	 * Don't verify header checksum if this packet is coming
13655 	 * back from AH/ESP as we already did it.
13656 	 */
13657 	if (!mctl_present) {
13658 		UPDATE_IB_PKT_COUNT(ire);
13659 		ire->ire_last_used_time = lbolt;
13660 	}
13661 
13662 	/* packet part of fragmented IP packet? */
13663 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13664 	if (u1 & (IPH_MF | IPH_OFFSET))
13665 		goto fragmented;
13666 
13667 	/* u1 = IP header length (20 bytes) */
13668 	u1 = IP_SIMPLE_HDR_LENGTH;
13669 
13670 find_sctp_client:
13671 	/* Pullup if we don't have the sctp common header. */
13672 	len = MBLKL(mp);
13673 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13674 		if (mp->b_cont == NULL ||
13675 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13676 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13677 			goto error;
13678 		}
13679 		ipha = (ipha_t *)mp->b_rptr;
13680 		len = MBLKL(mp);
13681 	}
13682 
13683 	sctph = (sctp_hdr_t *)(rptr + u1);
13684 #ifdef	DEBUG
13685 	if (!skip_sctp_cksum) {
13686 #endif
13687 		pktsum = sctph->sh_chksum;
13688 		sctph->sh_chksum = 0;
13689 		calcsum = sctp_cksum(mp, u1);
13690 		if (calcsum != pktsum) {
13691 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13692 			goto error;
13693 		}
13694 		sctph->sh_chksum = pktsum;
13695 #ifdef	DEBUG	/* skip_sctp_cksum */
13696 	}
13697 #endif
13698 	/* get the ports */
13699 	ports = *(uint32_t *)&sctph->sh_sport;
13700 
13701 	IRE_REFRELE(ire);
13702 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13703 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13704 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13705 	    sctps)) == NULL) {
13706 		/* Check for raw socket or OOTB handling */
13707 		goto no_conn;
13708 	}
13709 
13710 	/* Found a client; up it goes */
13711 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13712 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13713 	return;
13714 
13715 no_conn:
13716 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13717 	    ports, mctl_present, flags, B_TRUE, zoneid);
13718 	return;
13719 
13720 ipoptions:
13721 	DB_CKSUMFLAGS(mp) = 0;
13722 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13723 		goto slow_done;
13724 
13725 	UPDATE_IB_PKT_COUNT(ire);
13726 	ire->ire_last_used_time = lbolt;
13727 
13728 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13729 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13730 fragmented:
13731 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13732 			goto slow_done;
13733 		/*
13734 		 * Make sure that first_mp points back to mp as
13735 		 * the mp we came in with could have changed in
13736 		 * ip_rput_fragment().
13737 		 */
13738 		ASSERT(!mctl_present);
13739 		ipha = (ipha_t *)mp->b_rptr;
13740 		first_mp = mp;
13741 	}
13742 
13743 	/* Now we have a complete datagram, destined for this machine. */
13744 	u1 = IPH_HDR_LENGTH(ipha);
13745 	goto find_sctp_client;
13746 #undef  iphs
13747 #undef  rptr
13748 
13749 error:
13750 	freemsg(first_mp);
13751 slow_done:
13752 	IRE_REFRELE(ire);
13753 }
13754 
13755 #define	VER_BITS	0xF0
13756 #define	VERSION_6	0x60
13757 
13758 static boolean_t
13759 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13760     ipaddr_t *dstp, ip_stack_t *ipst)
13761 {
13762 	uint_t	opt_len;
13763 	ipha_t *ipha;
13764 	ssize_t len;
13765 	uint_t	pkt_len;
13766 
13767 	ASSERT(ill != NULL);
13768 	IP_STAT(ipst, ip_ipoptions);
13769 	ipha = *iphapp;
13770 
13771 #define	rptr    ((uchar_t *)ipha)
13772 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13773 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13774 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13775 		freemsg(mp);
13776 		return (B_FALSE);
13777 	}
13778 
13779 	/* multiple mblk or too short */
13780 	pkt_len = ntohs(ipha->ipha_length);
13781 
13782 	/* Get the number of words of IP options in the IP header. */
13783 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13784 	if (opt_len) {
13785 		/* IP Options present!  Validate and process. */
13786 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13787 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13788 			goto done;
13789 		}
13790 		/*
13791 		 * Recompute complete header length and make sure we
13792 		 * have access to all of it.
13793 		 */
13794 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13795 		if (len > (mp->b_wptr - rptr)) {
13796 			if (len > pkt_len) {
13797 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13798 				goto done;
13799 			}
13800 			if (!pullupmsg(mp, len)) {
13801 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13802 				goto done;
13803 			}
13804 			ipha = (ipha_t *)mp->b_rptr;
13805 		}
13806 		/*
13807 		 * Go off to ip_rput_options which returns the next hop
13808 		 * destination address, which may have been affected
13809 		 * by source routing.
13810 		 */
13811 		IP_STAT(ipst, ip_opt);
13812 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13813 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13814 			return (B_FALSE);
13815 		}
13816 	}
13817 	*iphapp = ipha;
13818 	return (B_TRUE);
13819 done:
13820 	/* clear b_prev - used by ip_mroute_decap */
13821 	mp->b_prev = NULL;
13822 	freemsg(mp);
13823 	return (B_FALSE);
13824 #undef  rptr
13825 }
13826 
13827 /*
13828  * Deal with the fact that there is no ire for the destination.
13829  * The incoming ill (in_ill) is passed in to ip_newroute only
13830  * in the case of packets coming from mobile ip forward tunnel.
13831  * It must be null otherwise.
13832  */
13833 static ire_t *
13834 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13835     ipaddr_t dst)
13836 {
13837 	ipha_t	*ipha;
13838 	ill_t	*ill;
13839 	ire_t	*ire;
13840 	boolean_t	check_multirt = B_FALSE;
13841 	ip_stack_t *ipst;
13842 
13843 	ipha = (ipha_t *)mp->b_rptr;
13844 	ill = (ill_t *)q->q_ptr;
13845 
13846 	ASSERT(ill != NULL);
13847 	ipst = ill->ill_ipst;
13848 
13849 	/*
13850 	 * No IRE for this destination, so it can't be for us.
13851 	 * Unless we are forwarding, drop the packet.
13852 	 * We have to let source routed packets through
13853 	 * since we don't yet know if they are 'ping -l'
13854 	 * packets i.e. if they will go out over the
13855 	 * same interface as they came in on.
13856 	 */
13857 	if (ll_multicast) {
13858 		freemsg(mp);
13859 		return (NULL);
13860 	}
13861 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13862 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13863 		freemsg(mp);
13864 		return (NULL);
13865 	}
13866 
13867 	/*
13868 	 * Mark this packet as having originated externally.
13869 	 *
13870 	 * For non-forwarding code path, ire_send later double
13871 	 * checks this interface to see if it is still exists
13872 	 * post-ARP resolution.
13873 	 *
13874 	 * Also, IPQOS uses this to differentiate between
13875 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13876 	 * QOS packet processing in ip_wput_attach_llhdr().
13877 	 * The QoS module can mark the b_band for a fastpath message
13878 	 * or the dl_priority field in a unitdata_req header for
13879 	 * CoS marking. This info can only be found in
13880 	 * ip_wput_attach_llhdr().
13881 	 */
13882 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13883 	/*
13884 	 * Clear the indication that this may have a hardware checksum
13885 	 * as we are not using it
13886 	 */
13887 	DB_CKSUMFLAGS(mp) = 0;
13888 
13889 	if (in_ill != NULL) {
13890 		/*
13891 		 * Now hand the packet to ip_newroute.
13892 		 */
13893 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13894 		return (NULL);
13895 	}
13896 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13897 	    MBLK_GETLABEL(mp), ipst);
13898 
13899 	if (ire == NULL && check_multirt) {
13900 		/* Let ip_newroute handle CGTP  */
13901 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13902 		return (NULL);
13903 	}
13904 
13905 	if (ire != NULL)
13906 		return (ire);
13907 
13908 	mp->b_prev = mp->b_next = 0;
13909 	/* send icmp unreachable */
13910 	q = WR(q);
13911 	/* Sent by forwarding path, and router is global zone */
13912 	if (ip_source_routed(ipha, ipst)) {
13913 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13914 		    GLOBAL_ZONEID, ipst);
13915 	} else {
13916 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13917 		    ipst);
13918 	}
13919 
13920 	return (NULL);
13921 
13922 }
13923 
13924 /*
13925  * check ip header length and align it.
13926  */
13927 static boolean_t
13928 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13929 {
13930 	ssize_t len;
13931 	ill_t *ill;
13932 	ipha_t	*ipha;
13933 
13934 	len = MBLKL(mp);
13935 
13936 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13937 		ill = (ill_t *)q->q_ptr;
13938 
13939 		if (!OK_32PTR(mp->b_rptr))
13940 			IP_STAT(ipst, ip_notaligned1);
13941 		else
13942 			IP_STAT(ipst, ip_notaligned2);
13943 		/* Guard against bogus device drivers */
13944 		if (len < 0) {
13945 			/* clear b_prev - used by ip_mroute_decap */
13946 			mp->b_prev = NULL;
13947 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13948 			freemsg(mp);
13949 			return (B_FALSE);
13950 		}
13951 
13952 		if (ip_rput_pullups++ == 0) {
13953 			ipha = (ipha_t *)mp->b_rptr;
13954 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13955 			    "ip_check_and_align_header: %s forced us to "
13956 			    " pullup pkt, hdr len %ld, hdr addr %p",
13957 			    ill->ill_name, len, ipha);
13958 		}
13959 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13960 			/* clear b_prev - used by ip_mroute_decap */
13961 			mp->b_prev = NULL;
13962 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13963 			freemsg(mp);
13964 			return (B_FALSE);
13965 		}
13966 	}
13967 	return (B_TRUE);
13968 }
13969 
13970 ire_t *
13971 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13972 {
13973 	ire_t		*new_ire;
13974 	ill_t		*ire_ill;
13975 	uint_t		ifindex;
13976 	ip_stack_t	*ipst = ill->ill_ipst;
13977 	boolean_t	strict_check = B_FALSE;
13978 
13979 	/*
13980 	 * This packet came in on an interface other than the one associated
13981 	 * with the first ire we found for the destination address. We do
13982 	 * another ire lookup here, using the ingress ill, to see if the
13983 	 * interface is in an interface group.
13984 	 * As long as the ills belong to the same group, we don't consider
13985 	 * them to be arriving on the wrong interface. Thus, if the switch
13986 	 * is doing inbound load spreading, we won't drop packets when the
13987 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13988 	 * for 'usesrc groups' where the destination address may belong to
13989 	 * another interface to allow multipathing to happen.
13990 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13991 	 * where the local address may not be unique. In this case we were
13992 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13993 	 * actually returned. The new lookup, which is more specific, should
13994 	 * only find the IRE_LOCAL associated with the ingress ill if one
13995 	 * exists.
13996 	 */
13997 
13998 	if (ire->ire_ipversion == IPV4_VERSION) {
13999 		if (ipst->ips_ip_strict_dst_multihoming)
14000 			strict_check = B_TRUE;
14001 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
14002 		    ill->ill_ipif, ALL_ZONES, NULL,
14003 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14004 	} else {
14005 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
14006 		if (ipst->ips_ipv6_strict_dst_multihoming)
14007 			strict_check = B_TRUE;
14008 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
14009 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
14010 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14011 	}
14012 	/*
14013 	 * If the same ire that was returned in ip_input() is found then this
14014 	 * is an indication that interface groups are in use. The packet
14015 	 * arrived on a different ill in the group than the one associated with
14016 	 * the destination address.  If a different ire was found then the same
14017 	 * IP address must be hosted on multiple ills. This is possible with
14018 	 * unnumbered point2point interfaces. We switch to use this new ire in
14019 	 * order to have accurate interface statistics.
14020 	 */
14021 	if (new_ire != NULL) {
14022 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
14023 			ire_refrele(ire);
14024 			ire = new_ire;
14025 		} else {
14026 			ire_refrele(new_ire);
14027 		}
14028 		return (ire);
14029 	} else if ((ire->ire_rfq == NULL) &&
14030 		    (ire->ire_ipversion == IPV4_VERSION)) {
14031 		/*
14032 		 * The best match could have been the original ire which
14033 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14034 		 * the strict multihoming checks are irrelevant as we consider
14035 		 * local addresses hosted on lo0 to be interface agnostic. We
14036 		 * only expect a null ire_rfq on IREs which are associated with
14037 		 * lo0 hence we can return now.
14038 		 */
14039 		return (ire);
14040 	}
14041 
14042 	/*
14043 	 * Chase pointers once and store locally.
14044 	 */
14045 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14046 	    (ill_t *)(ire->ire_rfq->q_ptr);
14047 	ifindex = ill->ill_usesrc_ifindex;
14048 
14049 	/*
14050 	 * Check if it's a legal address on the 'usesrc' interface.
14051 	 */
14052 	if ((ifindex != 0) && (ire_ill != NULL) &&
14053 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14054 		return (ire);
14055 	}
14056 
14057 	/*
14058 	 * If the ip*_strict_dst_multihoming switch is on then we can
14059 	 * only accept this packet if the interface is marked as routing.
14060 	 */
14061 	if (!(strict_check))
14062 		return (ire);
14063 
14064 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14065 	    ILLF_ROUTER) != 0) {
14066 		return (ire);
14067 	}
14068 
14069 	ire_refrele(ire);
14070 	return (NULL);
14071 }
14072 
14073 ire_t *
14074 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14075 {
14076 	ipha_t	*ipha;
14077 	ipaddr_t ip_dst, ip_src;
14078 	ire_t	*src_ire = NULL;
14079 	ill_t	*stq_ill;
14080 	uint_t	hlen;
14081 	uint_t	pkt_len;
14082 	uint32_t sum;
14083 	queue_t	*dev_q;
14084 	boolean_t check_multirt = B_FALSE;
14085 	ip_stack_t *ipst = ill->ill_ipst;
14086 
14087 	ipha = (ipha_t *)mp->b_rptr;
14088 
14089 	/*
14090 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14091 	 * The loopback address check for both src and dst has already
14092 	 * been checked in ip_input
14093 	 */
14094 	ip_dst = ntohl(dst);
14095 	ip_src = ntohl(ipha->ipha_src);
14096 
14097 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14098 	    IN_CLASSD(ip_src)) {
14099 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14100 		goto drop;
14101 	}
14102 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14103 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14104 
14105 	if (src_ire != NULL) {
14106 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14107 		goto drop;
14108 	}
14109 
14110 
14111 	/* No ire cache of nexthop. So first create one  */
14112 	if (ire == NULL) {
14113 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14114 		/*
14115 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14116 		 * is not set. So upon return from ire_forward
14117 		 * check_multirt should remain as false.
14118 		 */
14119 		ASSERT(!check_multirt);
14120 		if (ire == NULL) {
14121 			/* An attempt was made to forward the packet */
14122 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14123 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14124 			mp->b_prev = mp->b_next = 0;
14125 			/* send icmp unreachable */
14126 			/* Sent by forwarding path, and router is global zone */
14127 			if (ip_source_routed(ipha, ipst)) {
14128 				icmp_unreachable(ill->ill_wq, mp,
14129 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14130 				    ipst);
14131 			} else {
14132 				icmp_unreachable(ill->ill_wq, mp,
14133 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14134 				    ipst);
14135 			}
14136 			return (ire);
14137 		}
14138 	}
14139 
14140 	/*
14141 	 * Forwarding fastpath exception case:
14142 	 * If either of the follwoing case is true, we take
14143 	 * the slowpath
14144 	 *	o forwarding is not enabled
14145 	 *	o incoming and outgoing interface are the same, or the same
14146 	 *	  IPMP group
14147 	 *	o corresponding ire is in incomplete state
14148 	 *	o packet needs fragmentation
14149 	 *
14150 	 * The codeflow from here on is thus:
14151 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14152 	 */
14153 	pkt_len = ntohs(ipha->ipha_length);
14154 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14155 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14156 	    !(ill->ill_flags & ILLF_ROUTER) ||
14157 	    (ill == stq_ill) ||
14158 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14159 	    (ire->ire_nce == NULL) ||
14160 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14161 	    (pkt_len > ire->ire_max_frag) ||
14162 	    ipha->ipha_ttl <= 1) {
14163 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14164 		    ipha, ill, B_FALSE);
14165 		return (ire);
14166 	}
14167 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14168 
14169 	DTRACE_PROBE4(ip4__forwarding__start,
14170 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14171 
14172 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14173 	    ipst->ips_ipv4firewall_forwarding,
14174 	    ill, stq_ill, ipha, mp, mp, ipst);
14175 
14176 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14177 
14178 	if (mp == NULL)
14179 		goto drop;
14180 
14181 	mp->b_datap->db_struioun.cksum.flags = 0;
14182 	/* Adjust the checksum to reflect the ttl decrement. */
14183 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14184 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14185 	ipha->ipha_ttl--;
14186 
14187 	dev_q = ire->ire_stq->q_next;
14188 	if ((dev_q->q_next != NULL ||
14189 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14190 		goto indiscard;
14191 	}
14192 
14193 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14194 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14195 
14196 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14197 		mblk_t *mpip = mp;
14198 
14199 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14200 		if (mp != NULL) {
14201 			DTRACE_PROBE4(ip4__physical__out__start,
14202 			    ill_t *, NULL, ill_t *, stq_ill,
14203 			    ipha_t *, ipha, mblk_t *, mp);
14204 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14205 			    ipst->ips_ipv4firewall_physical_out,
14206 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14207 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14208 			    mp);
14209 			if (mp == NULL)
14210 				goto drop;
14211 
14212 			UPDATE_IB_PKT_COUNT(ire);
14213 			ire->ire_last_used_time = lbolt;
14214 			BUMP_MIB(stq_ill->ill_ip_mib,
14215 			    ipIfStatsHCOutForwDatagrams);
14216 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14217 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14218 			    pkt_len);
14219 			putnext(ire->ire_stq, mp);
14220 			return (ire);
14221 		}
14222 	}
14223 
14224 indiscard:
14225 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14226 drop:
14227 	if (mp != NULL)
14228 		freemsg(mp);
14229 	if (src_ire != NULL)
14230 		ire_refrele(src_ire);
14231 	return (ire);
14232 
14233 }
14234 
14235 /*
14236  * This function is called in the forwarding slowpath, when
14237  * either the ire lacks the link-layer address, or the packet needs
14238  * further processing(eg. fragmentation), before transmission.
14239  */
14240 
14241 static void
14242 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14243     ill_t *ill, boolean_t ll_multicast)
14244 {
14245 	ill_group_t	*ill_group;
14246 	ill_group_t	*ire_group;
14247 	queue_t		*dev_q;
14248 	ire_t		*src_ire;
14249 	ip_stack_t	*ipst = ill->ill_ipst;
14250 
14251 	ASSERT(ire->ire_stq != NULL);
14252 
14253 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14254 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14255 
14256 	if (ll_multicast != 0) {
14257 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14258 		goto drop_pkt;
14259 	}
14260 
14261 	/*
14262 	 * check if ipha_src is a broadcast address. Note that this
14263 	 * check is redundant when we get here from ip_fast_forward()
14264 	 * which has already done this check. However, since we can
14265 	 * also get here from ip_rput_process_broadcast() or, for
14266 	 * for the slow path through ip_fast_forward(), we perform
14267 	 * the check again for code-reusability
14268 	 */
14269 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14270 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14271 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14272 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14273 		if (src_ire != NULL)
14274 			ire_refrele(src_ire);
14275 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14276 		ip2dbg(("ip_rput_process_forward: Received packet with"
14277 		    " bad src/dst address on %s\n", ill->ill_name));
14278 		goto drop_pkt;
14279 	}
14280 
14281 	ill_group = ill->ill_group;
14282 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14283 	/*
14284 	 * Check if we want to forward this one at this time.
14285 	 * We allow source routed packets on a host provided that
14286 	 * they go out the same interface or same interface group
14287 	 * as they came in on.
14288 	 *
14289 	 * XXX To be quicker, we may wish to not chase pointers to
14290 	 * get the ILLF_ROUTER flag and instead store the
14291 	 * forwarding policy in the ire.  An unfortunate
14292 	 * side-effect of that would be requiring an ire flush
14293 	 * whenever the ILLF_ROUTER flag changes.
14294 	 */
14295 	if (((ill->ill_flags &
14296 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14297 	    ILLF_ROUTER) == 0) &&
14298 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14299 	    (ill_group != NULL && ill_group == ire_group)))) {
14300 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14301 		if (ip_source_routed(ipha, ipst)) {
14302 			q = WR(q);
14303 			/*
14304 			 * Clear the indication that this may have
14305 			 * hardware checksum as we are not using it.
14306 			 */
14307 			DB_CKSUMFLAGS(mp) = 0;
14308 			/* Sent by forwarding path, and router is global zone */
14309 			icmp_unreachable(q, mp,
14310 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14311 			return;
14312 		}
14313 		goto drop_pkt;
14314 	}
14315 
14316 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14317 
14318 	/* Packet is being forwarded. Turning off hwcksum flag. */
14319 	DB_CKSUMFLAGS(mp) = 0;
14320 	if (ipst->ips_ip_g_send_redirects) {
14321 		/*
14322 		 * Check whether the incoming interface and outgoing
14323 		 * interface is part of the same group. If so,
14324 		 * send redirects.
14325 		 *
14326 		 * Check the source address to see if it originated
14327 		 * on the same logical subnet it is going back out on.
14328 		 * If so, we should be able to send it a redirect.
14329 		 * Avoid sending a redirect if the destination
14330 		 * is directly connected (i.e., ipha_dst is the same
14331 		 * as ire_gateway_addr or the ire_addr of the
14332 		 * nexthop IRE_CACHE ), or if the packet was source
14333 		 * routed out this interface.
14334 		 */
14335 		ipaddr_t src, nhop;
14336 		mblk_t	*mp1;
14337 		ire_t	*nhop_ire = NULL;
14338 
14339 		/*
14340 		 * Check whether ire_rfq and q are from the same ill
14341 		 * or if they are not same, they at least belong
14342 		 * to the same group. If so, send redirects.
14343 		 */
14344 		if ((ire->ire_rfq == q ||
14345 		    (ill_group != NULL && ill_group == ire_group)) &&
14346 		    !ip_source_routed(ipha, ipst)) {
14347 
14348 			nhop = (ire->ire_gateway_addr != 0 ?
14349 			    ire->ire_gateway_addr : ire->ire_addr);
14350 
14351 			if (ipha->ipha_dst == nhop) {
14352 				/*
14353 				 * We avoid sending a redirect if the
14354 				 * destination is directly connected
14355 				 * because it is possible that multiple
14356 				 * IP subnets may have been configured on
14357 				 * the link, and the source may not
14358 				 * be on the same subnet as ip destination,
14359 				 * even though they are on the same
14360 				 * physical link.
14361 				 */
14362 				goto sendit;
14363 			}
14364 
14365 			src = ipha->ipha_src;
14366 
14367 			/*
14368 			 * We look up the interface ire for the nexthop,
14369 			 * to see if ipha_src is in the same subnet
14370 			 * as the nexthop.
14371 			 *
14372 			 * Note that, if, in the future, IRE_CACHE entries
14373 			 * are obsoleted,  this lookup will not be needed,
14374 			 * as the ire passed to this function will be the
14375 			 * same as the nhop_ire computed below.
14376 			 */
14377 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14378 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14379 			    0, NULL, MATCH_IRE_TYPE, ipst);
14380 
14381 			if (nhop_ire != NULL) {
14382 				if ((src & nhop_ire->ire_mask) ==
14383 				    (nhop & nhop_ire->ire_mask)) {
14384 					/*
14385 					 * The source is directly connected.
14386 					 * Just copy the ip header (which is
14387 					 * in the first mblk)
14388 					 */
14389 					mp1 = copyb(mp);
14390 					if (mp1 != NULL) {
14391 						icmp_send_redirect(WR(q), mp1,
14392 						    nhop, ipst);
14393 					}
14394 				}
14395 				ire_refrele(nhop_ire);
14396 			}
14397 		}
14398 	}
14399 sendit:
14400 	dev_q = ire->ire_stq->q_next;
14401 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14402 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14403 		freemsg(mp);
14404 		return;
14405 	}
14406 
14407 	ip_rput_forward(ire, ipha, mp, ill);
14408 	return;
14409 
14410 drop_pkt:
14411 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14412 	freemsg(mp);
14413 }
14414 
14415 ire_t *
14416 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14417     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14418 {
14419 	queue_t		*q;
14420 	uint16_t	hcksumflags;
14421 	ip_stack_t	*ipst = ill->ill_ipst;
14422 
14423 	q = *qp;
14424 
14425 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14426 
14427 	/*
14428 	 * Clear the indication that this may have hardware
14429 	 * checksum as we are not using it for forwarding.
14430 	 */
14431 	hcksumflags = DB_CKSUMFLAGS(mp);
14432 	DB_CKSUMFLAGS(mp) = 0;
14433 
14434 	/*
14435 	 * Directed broadcast forwarding: if the packet came in over a
14436 	 * different interface then it is routed out over we can forward it.
14437 	 */
14438 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14439 		ire_refrele(ire);
14440 		freemsg(mp);
14441 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14442 		return (NULL);
14443 	}
14444 	/*
14445 	 * For multicast we have set dst to be INADDR_BROADCAST
14446 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14447 	 * only for broadcast packets.
14448 	 */
14449 	if (!CLASSD(ipha->ipha_dst)) {
14450 		ire_t *new_ire;
14451 		ipif_t *ipif;
14452 		/*
14453 		 * For ill groups, as the switch duplicates broadcasts
14454 		 * across all the ports, we need to filter out and
14455 		 * send up only one copy. There is one copy for every
14456 		 * broadcast address on each ill. Thus, we look for a
14457 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14458 		 * later to see whether this ill is eligible to receive
14459 		 * them or not. ill_nominate_bcast_rcv() nominates only
14460 		 * one set of IREs for receiving.
14461 		 */
14462 
14463 		ipif = ipif_get_next_ipif(NULL, ill);
14464 		if (ipif == NULL) {
14465 			ire_refrele(ire);
14466 			freemsg(mp);
14467 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14468 			return (NULL);
14469 		}
14470 		new_ire = ire_ctable_lookup(dst, 0, 0,
14471 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14472 		ipif_refrele(ipif);
14473 
14474 		if (new_ire != NULL) {
14475 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14476 				ire_refrele(ire);
14477 				ire_refrele(new_ire);
14478 				freemsg(mp);
14479 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14480 				return (NULL);
14481 			}
14482 			/*
14483 			 * In the special case of multirouted broadcast
14484 			 * packets, we unconditionally need to "gateway"
14485 			 * them to the appropriate interface here.
14486 			 * In the normal case, this cannot happen, because
14487 			 * there is no broadcast IRE tagged with the
14488 			 * RTF_MULTIRT flag.
14489 			 */
14490 			if (new_ire->ire_flags & RTF_MULTIRT) {
14491 				ire_refrele(new_ire);
14492 				if (ire->ire_rfq != NULL) {
14493 					q = ire->ire_rfq;
14494 					*qp = q;
14495 				}
14496 			} else {
14497 				ire_refrele(ire);
14498 				ire = new_ire;
14499 			}
14500 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14501 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14502 				/*
14503 				 * Free the message if
14504 				 * ip_g_forward_directed_bcast is turned
14505 				 * off for non-local broadcast.
14506 				 */
14507 				ire_refrele(ire);
14508 				freemsg(mp);
14509 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14510 				return (NULL);
14511 			}
14512 		} else {
14513 			/*
14514 			 * This CGTP packet successfully passed the
14515 			 * CGTP filter, but the related CGTP
14516 			 * broadcast IRE has not been found,
14517 			 * meaning that the redundant ipif is
14518 			 * probably down. However, if we discarded
14519 			 * this packet, its duplicate would be
14520 			 * filtered out by the CGTP filter so none
14521 			 * of them would get through. So we keep
14522 			 * going with this one.
14523 			 */
14524 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14525 			if (ire->ire_rfq != NULL) {
14526 				q = ire->ire_rfq;
14527 				*qp = q;
14528 			}
14529 		}
14530 	}
14531 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14532 		/*
14533 		 * Verify that there are not more then one
14534 		 * IRE_BROADCAST with this broadcast address which
14535 		 * has ire_stq set.
14536 		 * TODO: simplify, loop over all IRE's
14537 		 */
14538 		ire_t	*ire1;
14539 		int	num_stq = 0;
14540 		mblk_t	*mp1;
14541 
14542 		/* Find the first one with ire_stq set */
14543 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14544 		for (ire1 = ire; ire1 &&
14545 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14546 		    ire1 = ire1->ire_next)
14547 			;
14548 		if (ire1) {
14549 			ire_refrele(ire);
14550 			ire = ire1;
14551 			IRE_REFHOLD(ire);
14552 		}
14553 
14554 		/* Check if there are additional ones with stq set */
14555 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14556 			if (ire->ire_addr != ire1->ire_addr)
14557 				break;
14558 			if (ire1->ire_stq) {
14559 				num_stq++;
14560 				break;
14561 			}
14562 		}
14563 		rw_exit(&ire->ire_bucket->irb_lock);
14564 		if (num_stq == 1 && ire->ire_stq != NULL) {
14565 			ip1dbg(("ip_rput_process_broadcast: directed "
14566 			    "broadcast to 0x%x\n",
14567 			    ntohl(ire->ire_addr)));
14568 			mp1 = copymsg(mp);
14569 			if (mp1) {
14570 				switch (ipha->ipha_protocol) {
14571 				case IPPROTO_UDP:
14572 					ip_udp_input(q, mp1, ipha, ire, ill);
14573 					break;
14574 				default:
14575 					ip_proto_input(q, mp1, ipha, ire, ill);
14576 					break;
14577 				}
14578 			}
14579 			/*
14580 			 * Adjust ttl to 2 (1+1 - the forward engine
14581 			 * will decrement it by one.
14582 			 */
14583 			if (ip_csum_hdr(ipha)) {
14584 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14585 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14586 				freemsg(mp);
14587 				ire_refrele(ire);
14588 				return (NULL);
14589 			}
14590 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14591 			ipha->ipha_hdr_checksum = 0;
14592 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14593 			ip_rput_process_forward(q, mp, ire, ipha,
14594 			    ill, ll_multicast);
14595 			ire_refrele(ire);
14596 			return (NULL);
14597 		}
14598 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14599 		    ntohl(ire->ire_addr)));
14600 	}
14601 
14602 
14603 	/* Restore any hardware checksum flags */
14604 	DB_CKSUMFLAGS(mp) = hcksumflags;
14605 	return (ire);
14606 }
14607 
14608 /* ARGSUSED */
14609 static boolean_t
14610 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14611     int *ll_multicast, ipaddr_t *dstp)
14612 {
14613 	ip_stack_t	*ipst = ill->ill_ipst;
14614 
14615 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14616 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14617 	    ntohs(ipha->ipha_length));
14618 
14619 	/*
14620 	 * Forward packets only if we have joined the allmulti
14621 	 * group on this interface.
14622 	 */
14623 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14624 		int retval;
14625 
14626 		/*
14627 		 * Clear the indication that this may have hardware
14628 		 * checksum as we are not using it.
14629 		 */
14630 		DB_CKSUMFLAGS(mp) = 0;
14631 		retval = ip_mforward(ill, ipha, mp);
14632 		/* ip_mforward updates mib variables if needed */
14633 		/* clear b_prev - used by ip_mroute_decap */
14634 		mp->b_prev = NULL;
14635 
14636 		switch (retval) {
14637 		case 0:
14638 			/*
14639 			 * pkt is okay and arrived on phyint.
14640 			 *
14641 			 * If we are running as a multicast router
14642 			 * we need to see all IGMP and/or PIM packets.
14643 			 */
14644 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14645 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14646 				goto done;
14647 			}
14648 			break;
14649 		case -1:
14650 			/* pkt is mal-formed, toss it */
14651 			goto drop_pkt;
14652 		case 1:
14653 			/* pkt is okay and arrived on a tunnel */
14654 			/*
14655 			 * If we are running a multicast router
14656 			 *  we need to see all igmp packets.
14657 			 */
14658 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14659 				*dstp = INADDR_BROADCAST;
14660 				*ll_multicast = 1;
14661 				return (B_FALSE);
14662 			}
14663 
14664 			goto drop_pkt;
14665 		}
14666 	}
14667 
14668 	ILM_WALKER_HOLD(ill);
14669 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14670 		/*
14671 		 * This might just be caused by the fact that
14672 		 * multiple IP Multicast addresses map to the same
14673 		 * link layer multicast - no need to increment counter!
14674 		 */
14675 		ILM_WALKER_RELE(ill);
14676 		freemsg(mp);
14677 		return (B_TRUE);
14678 	}
14679 	ILM_WALKER_RELE(ill);
14680 done:
14681 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14682 	/*
14683 	 * This assumes the we deliver to all streams for multicast
14684 	 * and broadcast packets.
14685 	 */
14686 	*dstp = INADDR_BROADCAST;
14687 	*ll_multicast = 1;
14688 	return (B_FALSE);
14689 drop_pkt:
14690 	ip2dbg(("ip_rput: drop pkt\n"));
14691 	freemsg(mp);
14692 	return (B_TRUE);
14693 }
14694 
14695 static boolean_t
14696 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14697     int *ll_multicast, mblk_t **mpp)
14698 {
14699 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14700 	boolean_t must_copy = B_FALSE;
14701 	struct iocblk   *iocp;
14702 	ipha_t		*ipha;
14703 	ip_stack_t	*ipst = ill->ill_ipst;
14704 
14705 #define	rptr    ((uchar_t *)ipha)
14706 
14707 	first_mp = *first_mpp;
14708 	mp = *mpp;
14709 
14710 	ASSERT(first_mp == mp);
14711 
14712 	/*
14713 	 * if db_ref > 1 then copymsg and free original. Packet may be
14714 	 * changed and do not want other entity who has a reference to this
14715 	 * message to trip over the changes. This is a blind change because
14716 	 * trying to catch all places that might change packet is too
14717 	 * difficult (since it may be a module above this one)
14718 	 *
14719 	 * This corresponds to the non-fast path case. We walk down the full
14720 	 * chain in this case, and check the db_ref count of all the dblks,
14721 	 * and do a copymsg if required. It is possible that the db_ref counts
14722 	 * of the data blocks in the mblk chain can be different.
14723 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14724 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14725 	 * 'snoop' is running.
14726 	 */
14727 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14728 		if (mp1->b_datap->db_ref > 1) {
14729 			must_copy = B_TRUE;
14730 			break;
14731 		}
14732 	}
14733 
14734 	if (must_copy) {
14735 		mp1 = copymsg(mp);
14736 		if (mp1 == NULL) {
14737 			for (mp1 = mp; mp1 != NULL;
14738 			    mp1 = mp1->b_cont) {
14739 				mp1->b_next = NULL;
14740 				mp1->b_prev = NULL;
14741 			}
14742 			freemsg(mp);
14743 			if (ill != NULL) {
14744 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14745 			} else {
14746 				BUMP_MIB(&ipst->ips_ip_mib,
14747 				    ipIfStatsInDiscards);
14748 			}
14749 			return (B_TRUE);
14750 		}
14751 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14752 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14753 			/* Copy b_prev - used by ip_mroute_decap */
14754 			to_mp->b_prev = from_mp->b_prev;
14755 			from_mp->b_prev = NULL;
14756 		}
14757 		*first_mpp = first_mp = mp1;
14758 		freemsg(mp);
14759 		mp = mp1;
14760 		*mpp = mp1;
14761 	}
14762 
14763 	ipha = (ipha_t *)mp->b_rptr;
14764 
14765 	/*
14766 	 * previous code has a case for M_DATA.
14767 	 * We want to check how that happens.
14768 	 */
14769 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14770 	switch (first_mp->b_datap->db_type) {
14771 	case M_PROTO:
14772 	case M_PCPROTO:
14773 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14774 		    DL_UNITDATA_IND) {
14775 			/* Go handle anything other than data elsewhere. */
14776 			ip_rput_dlpi(q, mp);
14777 			return (B_TRUE);
14778 		}
14779 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14780 		/* Ditch the DLPI header. */
14781 		mp1 = mp->b_cont;
14782 		ASSERT(first_mp == mp);
14783 		*first_mpp = mp1;
14784 		freeb(mp);
14785 		*mpp = mp1;
14786 		return (B_FALSE);
14787 	case M_IOCACK:
14788 		ip1dbg(("got iocack "));
14789 		iocp = (struct iocblk *)mp->b_rptr;
14790 		switch (iocp->ioc_cmd) {
14791 		case DL_IOC_HDR_INFO:
14792 			ill = (ill_t *)q->q_ptr;
14793 			ill_fastpath_ack(ill, mp);
14794 			return (B_TRUE);
14795 		case SIOCSTUNPARAM:
14796 		case OSIOCSTUNPARAM:
14797 			/* Go through qwriter_ip */
14798 			break;
14799 		case SIOCGTUNPARAM:
14800 		case OSIOCGTUNPARAM:
14801 			ip_rput_other(NULL, q, mp, NULL);
14802 			return (B_TRUE);
14803 		default:
14804 			putnext(q, mp);
14805 			return (B_TRUE);
14806 		}
14807 		/* FALLTHRU */
14808 	case M_ERROR:
14809 	case M_HANGUP:
14810 		/*
14811 		 * Since this is on the ill stream we unconditionally
14812 		 * bump up the refcount
14813 		 */
14814 		ill_refhold(ill);
14815 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14816 		return (B_TRUE);
14817 	case M_CTL:
14818 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14819 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14820 			IPHADA_M_CTL)) {
14821 			/*
14822 			 * It's an IPsec accelerated packet.
14823 			 * Make sure that the ill from which we received the
14824 			 * packet has enabled IPsec hardware acceleration.
14825 			 */
14826 			if (!(ill->ill_capabilities &
14827 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14828 				/* IPsec kstats: bean counter */
14829 				freemsg(mp);
14830 				return (B_TRUE);
14831 			}
14832 
14833 			/*
14834 			 * Make mp point to the mblk following the M_CTL,
14835 			 * then process according to type of mp.
14836 			 * After this processing, first_mp will point to
14837 			 * the data-attributes and mp to the pkt following
14838 			 * the M_CTL.
14839 			 */
14840 			mp = first_mp->b_cont;
14841 			if (mp == NULL) {
14842 				freemsg(first_mp);
14843 				return (B_TRUE);
14844 			}
14845 			/*
14846 			 * A Hardware Accelerated packet can only be M_DATA
14847 			 * ESP or AH packet.
14848 			 */
14849 			if (mp->b_datap->db_type != M_DATA) {
14850 				/* non-M_DATA IPsec accelerated packet */
14851 				IPSECHW_DEBUG(IPSECHW_PKT,
14852 				    ("non-M_DATA IPsec accelerated pkt\n"));
14853 				freemsg(first_mp);
14854 				return (B_TRUE);
14855 			}
14856 			ipha = (ipha_t *)mp->b_rptr;
14857 			if (ipha->ipha_protocol != IPPROTO_AH &&
14858 			    ipha->ipha_protocol != IPPROTO_ESP) {
14859 				IPSECHW_DEBUG(IPSECHW_PKT,
14860 				    ("non-M_DATA IPsec accelerated pkt\n"));
14861 				freemsg(first_mp);
14862 				return (B_TRUE);
14863 			}
14864 			*mpp = mp;
14865 			return (B_FALSE);
14866 		}
14867 		putnext(q, mp);
14868 		return (B_TRUE);
14869 	case M_IOCNAK:
14870 		ip1dbg(("got iocnak "));
14871 		iocp = (struct iocblk *)mp->b_rptr;
14872 		switch (iocp->ioc_cmd) {
14873 		case SIOCSTUNPARAM:
14874 		case OSIOCSTUNPARAM:
14875 			/*
14876 			 * Since this is on the ill stream we unconditionally
14877 			 * bump up the refcount
14878 			 */
14879 			ill_refhold(ill);
14880 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14881 			return (B_TRUE);
14882 		case DL_IOC_HDR_INFO:
14883 		case SIOCGTUNPARAM:
14884 		case OSIOCGTUNPARAM:
14885 			ip_rput_other(NULL, q, mp, NULL);
14886 			return (B_TRUE);
14887 		default:
14888 			break;
14889 		}
14890 		/* FALLTHRU */
14891 	default:
14892 		putnext(q, mp);
14893 		return (B_TRUE);
14894 	}
14895 }
14896 
14897 /* Read side put procedure.  Packets coming from the wire arrive here. */
14898 void
14899 ip_rput(queue_t *q, mblk_t *mp)
14900 {
14901 	ill_t		*ill = (ill_t *)q->q_ptr;
14902 	ip_stack_t	*ipst = ill->ill_ipst;
14903 	union DL_primitives *dl;
14904 
14905 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14906 
14907 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14908 		/*
14909 		 * If things are opening or closing, only accept high-priority
14910 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14911 		 * created; on close, things hanging off the ill may have been
14912 		 * freed already.)
14913 		 */
14914 		dl = (union DL_primitives *)mp->b_rptr;
14915 		if (DB_TYPE(mp) != M_PCPROTO ||
14916 		    dl->dl_primitive == DL_UNITDATA_IND) {
14917 			/*
14918 			 * SIOC[GS]TUNPARAM ioctls can come here.
14919 			 */
14920 			inet_freemsg(mp);
14921 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14922 			    "ip_rput_end: q %p (%S)", q, "uninit");
14923 			return;
14924 		}
14925 	}
14926 
14927 	/*
14928 	 * if db_ref > 1 then copymsg and free original. Packet may be
14929 	 * changed and we do not want the other entity who has a reference to
14930 	 * this message to trip over the changes. This is a blind change because
14931 	 * trying to catch all places that might change the packet is too
14932 	 * difficult.
14933 	 *
14934 	 * This corresponds to the fast path case, where we have a chain of
14935 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14936 	 * in the mblk chain. There doesn't seem to be a reason why a device
14937 	 * driver would send up data with varying db_ref counts in the mblk
14938 	 * chain. In any case the Fast path is a private interface, and our
14939 	 * drivers don't do such a thing. Given the above assumption, there is
14940 	 * no need to walk down the entire mblk chain (which could have a
14941 	 * potential performance problem)
14942 	 */
14943 	if (mp->b_datap->db_ref > 1) {
14944 		mblk_t  *mp1;
14945 		boolean_t adjusted = B_FALSE;
14946 		IP_STAT(ipst, ip_db_ref);
14947 
14948 		/*
14949 		 * The IP_RECVSLLA option depends on having the link layer
14950 		 * header. First check that:
14951 		 * a> the underlying device is of type ether, since this
14952 		 * option is currently supported only over ethernet.
14953 		 * b> there is enough room to copy over the link layer header.
14954 		 *
14955 		 * Once the checks are done, adjust rptr so that the link layer
14956 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14957 		 * be returned by some non-ethernet drivers but in this case the
14958 		 * second check will fail.
14959 		 */
14960 		if (ill->ill_type == IFT_ETHER &&
14961 		    (mp->b_rptr - mp->b_datap->db_base) >=
14962 		    sizeof (struct ether_header)) {
14963 			mp->b_rptr -= sizeof (struct ether_header);
14964 			adjusted = B_TRUE;
14965 		}
14966 		mp1 = copymsg(mp);
14967 		if (mp1 == NULL) {
14968 			mp->b_next = NULL;
14969 			/* clear b_prev - used by ip_mroute_decap */
14970 			mp->b_prev = NULL;
14971 			freemsg(mp);
14972 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14973 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14974 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14975 			return;
14976 		}
14977 		if (adjusted) {
14978 			/*
14979 			 * Copy is done. Restore the pointer in the _new_ mblk
14980 			 */
14981 			mp1->b_rptr += sizeof (struct ether_header);
14982 		}
14983 		/* Copy b_prev - used by ip_mroute_decap */
14984 		mp1->b_prev = mp->b_prev;
14985 		mp->b_prev = NULL;
14986 		freemsg(mp);
14987 		mp = mp1;
14988 	}
14989 
14990 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14991 	    "ip_rput_end: q %p (%S)", q, "end");
14992 
14993 	ip_input(ill, NULL, mp, NULL);
14994 }
14995 
14996 /*
14997  * Direct read side procedure capable of dealing with chains. GLDv3 based
14998  * drivers call this function directly with mblk chains while STREAMS
14999  * read side procedure ip_rput() calls this for single packet with ip_ring
15000  * set to NULL to process one packet at a time.
15001  *
15002  * The ill will always be valid if this function is called directly from
15003  * the driver.
15004  *
15005  * If ip_input() is called from GLDv3:
15006  *
15007  *   - This must be a non-VLAN IP stream.
15008  *   - 'mp' is either an untagged or a special priority-tagged packet.
15009  *   - Any VLAN tag that was in the MAC header has been stripped.
15010  *
15011  * If the IP header in packet is not 32-bit aligned, every message in the
15012  * chain will be aligned before further operations. This is required on SPARC
15013  * platform.
15014  */
15015 /* ARGSUSED */
15016 void
15017 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15018     struct mac_header_info_s *mhip)
15019 {
15020 	ipaddr_t		dst = NULL;
15021 	ipaddr_t		prev_dst;
15022 	ire_t			*ire = NULL;
15023 	ipha_t			*ipha;
15024 	uint_t			pkt_len;
15025 	ssize_t			len;
15026 	uint_t			opt_len;
15027 	int			ll_multicast;
15028 	int			cgtp_flt_pkt;
15029 	queue_t			*q = ill->ill_rq;
15030 	squeue_t		*curr_sqp = NULL;
15031 	mblk_t 			*head = NULL;
15032 	mblk_t			*tail = NULL;
15033 	mblk_t			*first_mp;
15034 	mblk_t 			*mp;
15035 	mblk_t			*dmp;
15036 	int			cnt = 0;
15037 	ip_stack_t		*ipst = ill->ill_ipst;
15038 
15039 	ASSERT(mp_chain != NULL);
15040 	ASSERT(ill != NULL);
15041 
15042 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15043 
15044 #define	rptr	((uchar_t *)ipha)
15045 
15046 	while (mp_chain != NULL) {
15047 		first_mp = mp = mp_chain;
15048 		mp_chain = mp_chain->b_next;
15049 		mp->b_next = NULL;
15050 		ll_multicast = 0;
15051 
15052 		/*
15053 		 * We do ire caching from one iteration to
15054 		 * another. In the event the packet chain contains
15055 		 * all packets from the same dst, this caching saves
15056 		 * an ire_cache_lookup for each of the succeeding
15057 		 * packets in a packet chain.
15058 		 */
15059 		prev_dst = dst;
15060 
15061 		/*
15062 		 * Check and align the IP header.
15063 		 */
15064 		if (DB_TYPE(mp) == M_DATA) {
15065 			dmp = mp;
15066 		} else if (DB_TYPE(mp) == M_PROTO &&
15067 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15068 			dmp = mp->b_cont;
15069 		} else {
15070 			dmp = NULL;
15071 		}
15072 		if (dmp != NULL) {
15073 			/*
15074 			 * IP header ptr not aligned?
15075 			 * OR IP header not complete in first mblk
15076 			 */
15077 			if (!OK_32PTR(dmp->b_rptr) ||
15078 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15079 				if (!ip_check_and_align_header(q, dmp, ipst))
15080 					continue;
15081 			}
15082 		}
15083 
15084 		/*
15085 		 * ip_input fast path
15086 		 */
15087 
15088 		/* mblk type is not M_DATA */
15089 		if (DB_TYPE(mp) != M_DATA) {
15090 			if (ip_rput_process_notdata(q, &first_mp, ill,
15091 			    &ll_multicast, &mp))
15092 				continue;
15093 		}
15094 
15095 		/* Make sure its an M_DATA and that its aligned */
15096 		ASSERT(DB_TYPE(mp) == M_DATA);
15097 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15098 
15099 		ipha = (ipha_t *)mp->b_rptr;
15100 		len = mp->b_wptr - rptr;
15101 		pkt_len = ntohs(ipha->ipha_length);
15102 
15103 		/*
15104 		 * We must count all incoming packets, even if they end
15105 		 * up being dropped later on.
15106 		 */
15107 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15108 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15109 
15110 		/* multiple mblk or too short */
15111 		len -= pkt_len;
15112 		if (len != 0) {
15113 			/*
15114 			 * Make sure we have data length consistent
15115 			 * with the IP header.
15116 			 */
15117 			if (mp->b_cont == NULL) {
15118 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15119 					BUMP_MIB(ill->ill_ip_mib,
15120 					    ipIfStatsInHdrErrors);
15121 					ip2dbg(("ip_input: drop pkt\n"));
15122 					freemsg(mp);
15123 					continue;
15124 				}
15125 				mp->b_wptr = rptr + pkt_len;
15126 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15127 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15128 					BUMP_MIB(ill->ill_ip_mib,
15129 					    ipIfStatsInHdrErrors);
15130 					ip2dbg(("ip_input: drop pkt\n"));
15131 					freemsg(mp);
15132 					continue;
15133 				}
15134 				(void) adjmsg(mp, -len);
15135 				IP_STAT(ipst, ip_multimblk3);
15136 			}
15137 		}
15138 
15139 		/* Obtain the dst of the current packet */
15140 		dst = ipha->ipha_dst;
15141 
15142 		if (IP_LOOPBACK_ADDR(dst) ||
15143 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15144 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15145 			cmn_err(CE_CONT, "dst %X src %X\n",
15146 			    dst, ipha->ipha_src);
15147 			freemsg(mp);
15148 			continue;
15149 		}
15150 
15151 		/*
15152 		 * The event for packets being received from a 'physical'
15153 		 * interface is placed after validation of the source and/or
15154 		 * destination address as being local so that packets can be
15155 		 * redirected to loopback addresses using ipnat.
15156 		 */
15157 		DTRACE_PROBE4(ip4__physical__in__start,
15158 		    ill_t *, ill, ill_t *, NULL,
15159 		    ipha_t *, ipha, mblk_t *, first_mp);
15160 
15161 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15162 		    ipst->ips_ipv4firewall_physical_in,
15163 		    ill, NULL, ipha, first_mp, mp, ipst);
15164 
15165 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15166 
15167 		if (first_mp == NULL) {
15168 			continue;
15169 		}
15170 		dst = ipha->ipha_dst;
15171 
15172 		/*
15173 		 * Attach any necessary label information to
15174 		 * this packet
15175 		 */
15176 		if (is_system_labeled() &&
15177 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15178 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15179 			freemsg(mp);
15180 			continue;
15181 		}
15182 
15183 		/*
15184 		 * Reuse the cached ire only if the ipha_dst of the previous
15185 		 * packet is the same as the current packet AND it is not
15186 		 * INADDR_ANY.
15187 		 */
15188 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15189 		    (ire != NULL)) {
15190 			ire_refrele(ire);
15191 			ire = NULL;
15192 		}
15193 		opt_len = ipha->ipha_version_and_hdr_length -
15194 		    IP_SIMPLE_HDR_VERSION;
15195 
15196 		/*
15197 		 * Check to see if we can take the fastpath.
15198 		 * That is possible if the following conditions are met
15199 		 *	o Tsol disabled
15200 		 *	o CGTP disabled
15201 		 *	o ipp_action_count is 0
15202 		 *	o Mobile IP not running
15203 		 *	o no options in the packet
15204 		 *	o not a RSVP packet
15205 		 * 	o not a multicast packet
15206 		 */
15207 		if (!is_system_labeled() &&
15208 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15209 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15210 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15211 		    !ll_multicast && !CLASSD(dst)) {
15212 			if (ire == NULL)
15213 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15214 				    ipst);
15215 
15216 			/* incoming packet is for forwarding */
15217 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15218 				ire = ip_fast_forward(ire, dst, ill, mp);
15219 				continue;
15220 			}
15221 			/* incoming packet is for local consumption */
15222 			if (ire->ire_type & IRE_LOCAL)
15223 				goto local;
15224 		}
15225 
15226 		/*
15227 		 * Disable ire caching for anything more complex
15228 		 * than the simple fast path case we checked for above.
15229 		 */
15230 		if (ire != NULL) {
15231 			ire_refrele(ire);
15232 			ire = NULL;
15233 		}
15234 
15235 		/* Full-blown slow path */
15236 		if (opt_len != 0) {
15237 			if (len != 0)
15238 				IP_STAT(ipst, ip_multimblk4);
15239 			else
15240 				IP_STAT(ipst, ip_ipoptions);
15241 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15242 			    &dst, ipst))
15243 				continue;
15244 		}
15245 
15246 		/*
15247 		 * Invoke the CGTP (multirouting) filtering module to process
15248 		 * the incoming packet. Packets identified as duplicates
15249 		 * must be discarded. Filtering is active only if the
15250 		 * the ip_cgtp_filter ndd variable is non-zero.
15251 		 *
15252 		 * Only applies to the shared stack since the filter_ops
15253 		 * do not carry an ip_stack_t or zoneid.
15254 		 */
15255 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15256 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15257 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15258 			cgtp_flt_pkt =
15259 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15260 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15261 				freemsg(first_mp);
15262 				continue;
15263 			}
15264 		}
15265 
15266 		/*
15267 		 * If rsvpd is running, let RSVP daemon handle its processing
15268 		 * and forwarding of RSVP multicast/unicast packets.
15269 		 * If rsvpd is not running but mrouted is running, RSVP
15270 		 * multicast packets are forwarded as multicast traffic
15271 		 * and RSVP unicast packets are forwarded by unicast router.
15272 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15273 		 * packets are not forwarded, but the unicast packets are
15274 		 * forwarded like unicast traffic.
15275 		 */
15276 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15277 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15278 		    NULL) {
15279 			/* RSVP packet and rsvpd running. Treat as ours */
15280 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15281 			/*
15282 			 * This assumes that we deliver to all streams for
15283 			 * multicast and broadcast packets.
15284 			 * We have to force ll_multicast to 1 to handle the
15285 			 * M_DATA messages passed in from ip_mroute_decap.
15286 			 */
15287 			dst = INADDR_BROADCAST;
15288 			ll_multicast = 1;
15289 		} else if (CLASSD(dst)) {
15290 			/* packet is multicast */
15291 			mp->b_next = NULL;
15292 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15293 			    &ll_multicast, &dst))
15294 				continue;
15295 		}
15296 
15297 
15298 		/*
15299 		 * Check if the packet is coming from the Mobile IP
15300 		 * forward tunnel interface
15301 		 */
15302 		if (ill->ill_srcif_refcnt > 0) {
15303 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15304 			    NULL, ill, MATCH_IRE_TYPE);
15305 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15306 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15307 
15308 				/* We need to resolve the link layer info */
15309 				ire_refrele(ire);
15310 				ire = NULL;
15311 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15312 				    ll_multicast, dst);
15313 				continue;
15314 			}
15315 		}
15316 
15317 		if (ire == NULL) {
15318 			ire = ire_cache_lookup(dst, ALL_ZONES,
15319 			    MBLK_GETLABEL(mp), ipst);
15320 		}
15321 
15322 		/*
15323 		 * If mipagent is running and reverse tunnel is created as per
15324 		 * mobile node request, then any packet coming through the
15325 		 * incoming interface from the mobile-node, should be reverse
15326 		 * tunneled to it's home agent except those that are destined
15327 		 * to foreign agent only.
15328 		 * This needs source address based ire lookup. The routing
15329 		 * entries for source address based lookup are only created by
15330 		 * mipagent program only when a reverse tunnel is created.
15331 		 * Reference : RFC2002, RFC2344
15332 		 */
15333 		if (ill->ill_mrtun_refcnt > 0) {
15334 			ipaddr_t	srcaddr;
15335 			ire_t		*tmp_ire;
15336 
15337 			tmp_ire = ire;	/* Save, we might need it later */
15338 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15339 			    ire->ire_type != IRE_BROADCAST)) {
15340 				srcaddr = ipha->ipha_src;
15341 				ire = ire_mrtun_lookup(srcaddr, ill);
15342 				if (ire != NULL) {
15343 					/*
15344 					 * Should not be getting iphada packet
15345 					 * here. we should only get those for
15346 					 * IRE_LOCAL traffic, excluded above.
15347 					 * Fail-safe (drop packet) in the event
15348 					 * hardware is misbehaving.
15349 					 */
15350 					if (first_mp != mp) {
15351 						/* IPsec KSTATS: beancount me */
15352 						freemsg(first_mp);
15353 					} else {
15354 						/*
15355 						 * This packet must be forwarded
15356 						 * to Reverse Tunnel
15357 						 */
15358 						ip_mrtun_forward(ire, ill, mp);
15359 					}
15360 					ire_refrele(ire);
15361 					ire = NULL;
15362 					if (tmp_ire != NULL) {
15363 						ire_refrele(tmp_ire);
15364 						tmp_ire = NULL;
15365 					}
15366 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15367 					    "ip_input_end: q %p (%S)",
15368 					    q, "uninit");
15369 					continue;
15370 				}
15371 			}
15372 			/*
15373 			 * If this packet is from a non-mobilenode  or a
15374 			 * mobile-node which does not request reverse
15375 			 * tunnel service
15376 			 */
15377 			ire = tmp_ire;
15378 		}
15379 
15380 
15381 		/*
15382 		 * If we reach here that means the incoming packet satisfies
15383 		 * one of the following conditions:
15384 		 *   - packet is from a mobile node which does not request
15385 		 *	reverse tunnel
15386 		 *   - packet is from a non-mobile node, which is the most
15387 		 *	common case
15388 		 *   - packet is from a reverse tunnel enabled mobile node
15389 		 *	and destined to foreign agent only
15390 		 */
15391 
15392 		if (ire == NULL) {
15393 			/*
15394 			 * No IRE for this destination, so it can't be for us.
15395 			 * Unless we are forwarding, drop the packet.
15396 			 * We have to let source routed packets through
15397 			 * since we don't yet know if they are 'ping -l'
15398 			 * packets i.e. if they will go out over the
15399 			 * same interface as they came in on.
15400 			 */
15401 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15402 			if (ire == NULL)
15403 				continue;
15404 		}
15405 
15406 		/*
15407 		 * Broadcast IRE may indicate either broadcast or
15408 		 * multicast packet
15409 		 */
15410 		if (ire->ire_type == IRE_BROADCAST) {
15411 			/*
15412 			 * Skip broadcast checks if packet is UDP multicast;
15413 			 * we'd rather not enter ip_rput_process_broadcast()
15414 			 * unless the packet is broadcast for real, since
15415 			 * that routine is a no-op for multicast.
15416 			 */
15417 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15418 			    !CLASSD(ipha->ipha_dst)) {
15419 				ire = ip_rput_process_broadcast(&q, mp,
15420 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15421 				    ll_multicast);
15422 				if (ire == NULL)
15423 					continue;
15424 			}
15425 		} else if (ire->ire_stq != NULL) {
15426 			/* fowarding? */
15427 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15428 			    ll_multicast);
15429 			/* ip_rput_process_forward consumed the packet */
15430 			continue;
15431 		}
15432 
15433 local:
15434 		/*
15435 		 * If the queue in the ire is different to the ingress queue
15436 		 * then we need to check to see if we can accept the packet.
15437 		 * Note that for multicast packets and broadcast packets sent
15438 		 * to a broadcast address which is shared between multiple
15439 		 * interfaces we should not do this since we just got a random
15440 		 * broadcast ire.
15441 		 */
15442 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15443 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15444 			    ill)) == NULL) {
15445 				/* Drop packet */
15446 				BUMP_MIB(ill->ill_ip_mib,
15447 				    ipIfStatsForwProhibits);
15448 				freemsg(mp);
15449 				continue;
15450 			}
15451 			if (ire->ire_rfq != NULL)
15452 				q = ire->ire_rfq;
15453 		}
15454 
15455 		switch (ipha->ipha_protocol) {
15456 		case IPPROTO_TCP:
15457 			ASSERT(first_mp == mp);
15458 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15459 				mp, 0, q, ip_ring)) != NULL) {
15460 				if (curr_sqp == NULL) {
15461 					curr_sqp = GET_SQUEUE(mp);
15462 					ASSERT(cnt == 0);
15463 					cnt++;
15464 					head = tail = mp;
15465 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15466 					ASSERT(tail != NULL);
15467 					cnt++;
15468 					tail->b_next = mp;
15469 					tail = mp;
15470 				} else {
15471 					/*
15472 					 * A different squeue. Send the
15473 					 * chain for the previous squeue on
15474 					 * its way. This shouldn't happen
15475 					 * often unless interrupt binding
15476 					 * changes.
15477 					 */
15478 					IP_STAT(ipst, ip_input_multi_squeue);
15479 					squeue_enter_chain(curr_sqp, head,
15480 					    tail, cnt, SQTAG_IP_INPUT);
15481 					curr_sqp = GET_SQUEUE(mp);
15482 					head = mp;
15483 					tail = mp;
15484 					cnt = 1;
15485 				}
15486 			}
15487 			continue;
15488 		case IPPROTO_UDP:
15489 			ASSERT(first_mp == mp);
15490 			ip_udp_input(q, mp, ipha, ire, ill);
15491 			continue;
15492 		case IPPROTO_SCTP:
15493 			ASSERT(first_mp == mp);
15494 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15495 			    q, dst);
15496 			/* ire has been released by ip_sctp_input */
15497 			ire = NULL;
15498 			continue;
15499 		default:
15500 			ip_proto_input(q, first_mp, ipha, ire, ill);
15501 			continue;
15502 		}
15503 	}
15504 
15505 	if (ire != NULL)
15506 		ire_refrele(ire);
15507 
15508 	if (head != NULL)
15509 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15510 
15511 	/*
15512 	 * This code is there just to make netperf/ttcp look good.
15513 	 *
15514 	 * Its possible that after being in polling mode (and having cleared
15515 	 * the backlog), squeues have turned the interrupt frequency higher
15516 	 * to improve latency at the expense of more CPU utilization (less
15517 	 * packets per interrupts or more number of interrupts). Workloads
15518 	 * like ttcp/netperf do manage to tickle polling once in a while
15519 	 * but for the remaining time, stay in higher interrupt mode since
15520 	 * their packet arrival rate is pretty uniform and this shows up
15521 	 * as higher CPU utilization. Since people care about CPU utilization
15522 	 * while running netperf/ttcp, turn the interrupt frequency back to
15523 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15524 	 */
15525 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15526 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15527 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15528 			ip_ring->rr_blank(ip_ring->rr_handle,
15529 			    ip_ring->rr_normal_blank_time,
15530 			    ip_ring->rr_normal_pkt_cnt);
15531 		}
15532 		}
15533 
15534 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15535 	    "ip_input_end: q %p (%S)", q, "end");
15536 #undef  rptr
15537 }
15538 
15539 static void
15540 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15541     t_uscalar_t err)
15542 {
15543 	if (dl_err == DL_SYSERR) {
15544 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15545 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15546 		    ill->ill_name, dlpi_prim_str(prim), err);
15547 		return;
15548 	}
15549 
15550 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15551 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15552 	    dlpi_err_str(dl_err));
15553 }
15554 
15555 /*
15556  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15557  * than DL_UNITDATA_IND messages. If we need to process this message
15558  * exclusively, we call qwriter_ip, in which case we also need to call
15559  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15560  */
15561 void
15562 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15563 {
15564 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15565 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15566 	ill_t		*ill = (ill_t *)q->q_ptr;
15567 	boolean_t	pending;
15568 
15569 	ip1dbg(("ip_rput_dlpi"));
15570 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15571 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15572 		    "%s (0x%x), unix %u\n", ill->ill_name,
15573 		    dlpi_prim_str(dlea->dl_error_primitive),
15574 		    dlea->dl_error_primitive,
15575 		    dlpi_err_str(dlea->dl_errno),
15576 		    dlea->dl_errno,
15577 		    dlea->dl_unix_errno));
15578 	}
15579 
15580 	/*
15581 	 * If we received an ACK but didn't send a request for it, then it
15582 	 * can't be part of any pending operation; discard up-front.
15583 	 */
15584 	switch (dloa->dl_primitive) {
15585 	case DL_NOTIFY_IND:
15586 		pending = B_TRUE;
15587 		break;
15588 	case DL_ERROR_ACK:
15589 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15590 		break;
15591 	case DL_OK_ACK:
15592 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15593 		break;
15594 	case DL_INFO_ACK:
15595 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15596 		break;
15597 	case DL_BIND_ACK:
15598 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15599 		break;
15600 	case DL_PHYS_ADDR_ACK:
15601 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15602 		break;
15603 	case DL_NOTIFY_ACK:
15604 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15605 		break;
15606 	case DL_CONTROL_ACK:
15607 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15608 		break;
15609 	case DL_CAPABILITY_ACK:
15610 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15611 		break;
15612 	default:
15613 		/* Not a DLPI message we support or were expecting */
15614 		freemsg(mp);
15615 		return;
15616 	}
15617 
15618 	if (!pending) {
15619 		freemsg(mp);
15620 		return;
15621 	}
15622 
15623 	switch (dloa->dl_primitive) {
15624 	case DL_ERROR_ACK:
15625 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15626 			mutex_enter(&ill->ill_lock);
15627 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15628 			cv_signal(&ill->ill_cv);
15629 			mutex_exit(&ill->ill_lock);
15630 		}
15631 		break;
15632 
15633 	case DL_OK_ACK:
15634 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15635 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15636 		switch (dloa->dl_correct_primitive) {
15637 		case DL_UNBIND_REQ:
15638 			mutex_enter(&ill->ill_lock);
15639 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15640 			cv_signal(&ill->ill_cv);
15641 			mutex_exit(&ill->ill_lock);
15642 			break;
15643 
15644 		case DL_ENABMULTI_REQ:
15645 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15646 				ill->ill_dlpi_multicast_state = IDS_OK;
15647 			break;
15648 		}
15649 		break;
15650 	default:
15651 		break;
15652 	}
15653 
15654 	/*
15655 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15656 	 * and we need to become writer to continue to process it. If it's not
15657 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15658 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15659 	 * some work as part of the current exclusive operation that actually
15660 	 * is not part of it -- which is wrong, but better than the
15661 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15662 	 * should track which DLPI requests have ACKs that we wait on
15663 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15664 	 *
15665 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15666 	 * Since this is on the ill stream we unconditionally bump up the
15667 	 * refcount without doing ILL_CAN_LOOKUP().
15668 	 */
15669 	ill_refhold(ill);
15670 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15671 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15672 	else
15673 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15674 }
15675 
15676 /*
15677  * Handling of DLPI messages that require exclusive access to the ipsq.
15678  *
15679  * Need to do ill_pending_mp_release on ioctl completion, which could
15680  * happen here. (along with mi_copy_done)
15681  */
15682 /* ARGSUSED */
15683 static void
15684 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15685 {
15686 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15687 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15688 	int		err = 0;
15689 	ill_t		*ill;
15690 	ipif_t		*ipif = NULL;
15691 	mblk_t		*mp1 = NULL;
15692 	conn_t		*connp = NULL;
15693 	t_uscalar_t	paddrreq;
15694 	mblk_t		*mp_hw;
15695 	boolean_t	success;
15696 	boolean_t	ioctl_aborted = B_FALSE;
15697 	boolean_t	log = B_TRUE;
15698 	hook_nic_event_t	*info;
15699 	ip_stack_t		*ipst;
15700 
15701 	ip1dbg(("ip_rput_dlpi_writer .."));
15702 	ill = (ill_t *)q->q_ptr;
15703 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15704 
15705 	ASSERT(IAM_WRITER_ILL(ill));
15706 
15707 	ipst = ill->ill_ipst;
15708 
15709 	/*
15710 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15711 	 * both are null or non-null. However we can assert that only
15712 	 * after grabbing the ipsq_lock. So we don't make any assertion
15713 	 * here and in other places in the code.
15714 	 */
15715 	ipif = ipsq->ipsq_pending_ipif;
15716 	/*
15717 	 * The current ioctl could have been aborted by the user and a new
15718 	 * ioctl to bring up another ill could have started. We could still
15719 	 * get a response from the driver later.
15720 	 */
15721 	if (ipif != NULL && ipif->ipif_ill != ill)
15722 		ioctl_aborted = B_TRUE;
15723 
15724 	switch (dloa->dl_primitive) {
15725 	case DL_ERROR_ACK:
15726 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15727 		    dlpi_prim_str(dlea->dl_error_primitive)));
15728 
15729 		switch (dlea->dl_error_primitive) {
15730 		case DL_PROMISCON_REQ:
15731 		case DL_PROMISCOFF_REQ:
15732 		case DL_DISABMULTI_REQ:
15733 		case DL_UNBIND_REQ:
15734 		case DL_ATTACH_REQ:
15735 		case DL_INFO_REQ:
15736 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15737 			break;
15738 		case DL_NOTIFY_REQ:
15739 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15740 			log = B_FALSE;
15741 			break;
15742 		case DL_PHYS_ADDR_REQ:
15743 			/*
15744 			 * For IPv6 only, there are two additional
15745 			 * phys_addr_req's sent to the driver to get the
15746 			 * IPv6 token and lla. This allows IP to acquire
15747 			 * the hardware address format for a given interface
15748 			 * without having built in knowledge of the hardware
15749 			 * address. ill_phys_addr_pend keeps track of the last
15750 			 * DL_PAR sent so we know which response we are
15751 			 * dealing with. ill_dlpi_done will update
15752 			 * ill_phys_addr_pend when it sends the next req.
15753 			 * We don't complete the IOCTL until all three DL_PARs
15754 			 * have been attempted, so set *_len to 0 and break.
15755 			 */
15756 			paddrreq = ill->ill_phys_addr_pend;
15757 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15758 			if (paddrreq == DL_IPV6_TOKEN) {
15759 				ill->ill_token_length = 0;
15760 				log = B_FALSE;
15761 				break;
15762 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15763 				ill->ill_nd_lla_len = 0;
15764 				log = B_FALSE;
15765 				break;
15766 			}
15767 			/*
15768 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15769 			 * We presumably have an IOCTL hanging out waiting
15770 			 * for completion. Find it and complete the IOCTL
15771 			 * with the error noted.
15772 			 * However, ill_dl_phys was called on an ill queue
15773 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15774 			 * set. But the ioctl is known to be pending on ill_wq.
15775 			 */
15776 			if (!ill->ill_ifname_pending)
15777 				break;
15778 			ill->ill_ifname_pending = 0;
15779 			if (!ioctl_aborted)
15780 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15781 			if (mp1 != NULL) {
15782 				/*
15783 				 * This operation (SIOCSLIFNAME) must have
15784 				 * happened on the ill. Assert there is no conn
15785 				 */
15786 				ASSERT(connp == NULL);
15787 				q = ill->ill_wq;
15788 			}
15789 			break;
15790 		case DL_BIND_REQ:
15791 			ill_dlpi_done(ill, DL_BIND_REQ);
15792 			if (ill->ill_ifname_pending)
15793 				break;
15794 			/*
15795 			 * Something went wrong with the bind.  We presumably
15796 			 * have an IOCTL hanging out waiting for completion.
15797 			 * Find it, take down the interface that was coming
15798 			 * up, and complete the IOCTL with the error noted.
15799 			 */
15800 			if (!ioctl_aborted)
15801 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15802 			if (mp1 != NULL) {
15803 				/*
15804 				 * This operation (SIOCSLIFFLAGS) must have
15805 				 * happened from a conn.
15806 				 */
15807 				ASSERT(connp != NULL);
15808 				q = CONNP_TO_WQ(connp);
15809 				if (ill->ill_move_in_progress) {
15810 					ILL_CLEAR_MOVE(ill);
15811 				}
15812 				(void) ipif_down(ipif, NULL, NULL);
15813 				/* error is set below the switch */
15814 			}
15815 			break;
15816 		case DL_ENABMULTI_REQ:
15817 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15818 
15819 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15820 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15821 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15822 				ipif_t *ipif;
15823 
15824 				printf("ip: joining multicasts failed (%d)"
15825 				    " on %s - will use link layer "
15826 				    "broadcasts for multicast\n",
15827 				    dlea->dl_errno, ill->ill_name);
15828 
15829 				/*
15830 				 * Set up the multicast mapping alone.
15831 				 * writer, so ok to access ill->ill_ipif
15832 				 * without any lock.
15833 				 */
15834 				ipif = ill->ill_ipif;
15835 				mutex_enter(&ill->ill_phyint->phyint_lock);
15836 				ill->ill_phyint->phyint_flags |=
15837 				    PHYI_MULTI_BCAST;
15838 				mutex_exit(&ill->ill_phyint->phyint_lock);
15839 
15840 				if (!ill->ill_isv6) {
15841 					(void) ipif_arp_setup_multicast(ipif,
15842 					    NULL);
15843 				} else {
15844 					(void) ipif_ndp_setup_multicast(ipif,
15845 					    NULL);
15846 				}
15847 			}
15848 			freemsg(mp);	/* Don't want to pass this up */
15849 			return;
15850 
15851 		case DL_CAPABILITY_REQ:
15852 		case DL_CONTROL_REQ:
15853 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15854 			ill->ill_dlpi_capab_state = IDS_FAILED;
15855 			freemsg(mp);
15856 			return;
15857 		}
15858 		/*
15859 		 * Note the error for IOCTL completion (mp1 is set when
15860 		 * ready to complete ioctl). If ill_ifname_pending_err is
15861 		 * set, an error occured during plumbing (ill_ifname_pending),
15862 		 * so we want to report that error.
15863 		 *
15864 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15865 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15866 		 * expected to get errack'd if the driver doesn't support
15867 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15868 		 * if these error conditions are encountered.
15869 		 */
15870 		if (mp1 != NULL) {
15871 			if (ill->ill_ifname_pending_err != 0)  {
15872 				err = ill->ill_ifname_pending_err;
15873 				ill->ill_ifname_pending_err = 0;
15874 			} else {
15875 				err = dlea->dl_unix_errno ?
15876 				    dlea->dl_unix_errno : ENXIO;
15877 			}
15878 		/*
15879 		 * If we're plumbing an interface and an error hasn't already
15880 		 * been saved, set ill_ifname_pending_err to the error passed
15881 		 * up. Ignore the error if log is B_FALSE (see comment above).
15882 		 */
15883 		} else if (log && ill->ill_ifname_pending &&
15884 		    ill->ill_ifname_pending_err == 0) {
15885 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15886 			dlea->dl_unix_errno : ENXIO;
15887 		}
15888 
15889 		if (log)
15890 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15891 			    dlea->dl_errno, dlea->dl_unix_errno);
15892 		break;
15893 	case DL_CAPABILITY_ACK: {
15894 		boolean_t reneg_flag = B_FALSE;
15895 		/* Call a routine to handle this one. */
15896 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15897 		/*
15898 		 * Check if the ACK is due to renegotiation case since we
15899 		 * will need to send a new CAPABILITY_REQ later.
15900 		 */
15901 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15902 			/* This is the ack for a renogiation case */
15903 			reneg_flag = B_TRUE;
15904 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15905 		}
15906 		ill_capability_ack(ill, mp);
15907 		if (reneg_flag)
15908 			ill_capability_probe(ill);
15909 		break;
15910 	}
15911 	case DL_CONTROL_ACK:
15912 		/* We treat all of these as "fire and forget" */
15913 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15914 		break;
15915 	case DL_INFO_ACK:
15916 		/* Call a routine to handle this one. */
15917 		ill_dlpi_done(ill, DL_INFO_REQ);
15918 		ip_ll_subnet_defaults(ill, mp);
15919 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15920 		return;
15921 	case DL_BIND_ACK:
15922 		/*
15923 		 * We should have an IOCTL waiting on this unless
15924 		 * sent by ill_dl_phys, in which case just return
15925 		 */
15926 		ill_dlpi_done(ill, DL_BIND_REQ);
15927 		if (ill->ill_ifname_pending)
15928 			break;
15929 
15930 		if (!ioctl_aborted)
15931 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15932 		if (mp1 == NULL)
15933 			break;
15934 		/*
15935 		 * Because mp1 was added by ill_dl_up(), and it always
15936 		 * passes a valid connp, connp must be valid here.
15937 		 */
15938 		ASSERT(connp != NULL);
15939 		q = CONNP_TO_WQ(connp);
15940 
15941 		/*
15942 		 * We are exclusive. So nothing can change even after
15943 		 * we get the pending mp. If need be we can put it back
15944 		 * and restart, as in calling ipif_arp_up()  below.
15945 		 */
15946 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15947 
15948 		mutex_enter(&ill->ill_lock);
15949 
15950 		ill->ill_dl_up = 1;
15951 
15952 		if ((info = ill->ill_nic_event_info) != NULL) {
15953 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15954 			    "attached for %s\n", info->hne_event,
15955 			    ill->ill_name));
15956 			if (info->hne_data != NULL)
15957 				kmem_free(info->hne_data, info->hne_datalen);
15958 			kmem_free(info, sizeof (hook_nic_event_t));
15959 		}
15960 
15961 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15962 		if (info != NULL) {
15963 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15964 			info->hne_lif = 0;
15965 			info->hne_event = NE_UP;
15966 			info->hne_data = NULL;
15967 			info->hne_datalen = 0;
15968 			info->hne_family = ill->ill_isv6 ?
15969 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15970 		} else
15971 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15972 			    "event information for %s (ENOMEM)\n",
15973 			    ill->ill_name));
15974 
15975 		ill->ill_nic_event_info = info;
15976 
15977 		mutex_exit(&ill->ill_lock);
15978 
15979 		/*
15980 		 * Now bring up the resolver; when that is complete, we'll
15981 		 * create IREs.  Note that we intentionally mirror what
15982 		 * ipif_up() would have done, because we got here by way of
15983 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15984 		 */
15985 		if (ill->ill_isv6) {
15986 			/*
15987 			 * v6 interfaces.
15988 			 * Unlike ARP which has to do another bind
15989 			 * and attach, once we get here we are
15990 			 * done with NDP. Except in the case of
15991 			 * ILLF_XRESOLV, in which case we send an
15992 			 * AR_INTERFACE_UP to the external resolver.
15993 			 * If all goes well, the ioctl will complete
15994 			 * in ip_rput(). If there's an error, we
15995 			 * complete it here.
15996 			 */
15997 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
15998 			if (err == 0) {
15999 				if (ill->ill_flags & ILLF_XRESOLV) {
16000 					mutex_enter(&connp->conn_lock);
16001 					mutex_enter(&ill->ill_lock);
16002 					success = ipsq_pending_mp_add(
16003 					    connp, ipif, q, mp1, 0);
16004 					mutex_exit(&ill->ill_lock);
16005 					mutex_exit(&connp->conn_lock);
16006 					if (success) {
16007 						err = ipif_resolver_up(ipif,
16008 						    Res_act_initial);
16009 						if (err == EINPROGRESS) {
16010 							freemsg(mp);
16011 							return;
16012 						}
16013 						ASSERT(err != 0);
16014 						mp1 = ipsq_pending_mp_get(ipsq,
16015 						    &connp);
16016 						ASSERT(mp1 != NULL);
16017 					} else {
16018 						/* conn has started closing */
16019 						err = EINTR;
16020 					}
16021 				} else { /* Non XRESOLV interface */
16022 					(void) ipif_resolver_up(ipif,
16023 					    Res_act_initial);
16024 					err = ipif_up_done_v6(ipif);
16025 				}
16026 			}
16027 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16028 			/*
16029 			 * ARP and other v4 external resolvers.
16030 			 * Leave the pending mblk intact so that
16031 			 * the ioctl completes in ip_rput().
16032 			 */
16033 			mutex_enter(&connp->conn_lock);
16034 			mutex_enter(&ill->ill_lock);
16035 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16036 			mutex_exit(&ill->ill_lock);
16037 			mutex_exit(&connp->conn_lock);
16038 			if (success) {
16039 				err = ipif_resolver_up(ipif, Res_act_initial);
16040 				if (err == EINPROGRESS) {
16041 					freemsg(mp);
16042 					return;
16043 				}
16044 				ASSERT(err != 0);
16045 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16046 			} else {
16047 				/* The conn has started closing */
16048 				err = EINTR;
16049 			}
16050 		} else {
16051 			/*
16052 			 * This one is complete. Reply to pending ioctl.
16053 			 */
16054 			(void) ipif_resolver_up(ipif, Res_act_initial);
16055 			err = ipif_up_done(ipif);
16056 		}
16057 
16058 		if ((err == 0) && (ill->ill_up_ipifs)) {
16059 			err = ill_up_ipifs(ill, q, mp1);
16060 			if (err == EINPROGRESS) {
16061 				freemsg(mp);
16062 				return;
16063 			}
16064 		}
16065 
16066 		if (ill->ill_up_ipifs) {
16067 			ill_group_cleanup(ill);
16068 		}
16069 
16070 		break;
16071 	case DL_NOTIFY_IND: {
16072 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16073 		ire_t *ire;
16074 		boolean_t need_ire_walk_v4 = B_FALSE;
16075 		boolean_t need_ire_walk_v6 = B_FALSE;
16076 
16077 		switch (notify->dl_notification) {
16078 		case DL_NOTE_PHYS_ADDR:
16079 			err = ill_set_phys_addr(ill, mp);
16080 			break;
16081 
16082 		case DL_NOTE_FASTPATH_FLUSH:
16083 			ill_fastpath_flush(ill);
16084 			break;
16085 
16086 		case DL_NOTE_SDU_SIZE:
16087 			/*
16088 			 * Change the MTU size of the interface, of all
16089 			 * attached ipif's, and of all relevant ire's.  The
16090 			 * new value's a uint32_t at notify->dl_data.
16091 			 * Mtu change Vs. new ire creation - protocol below.
16092 			 *
16093 			 * a Mark the ipif as IPIF_CHANGING.
16094 			 * b Set the new mtu in the ipif.
16095 			 * c Change the ire_max_frag on all affected ires
16096 			 * d Unmark the IPIF_CHANGING
16097 			 *
16098 			 * To see how the protocol works, assume an interface
16099 			 * route is also being added simultaneously by
16100 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16101 			 * the ire. If the ire is created before step a,
16102 			 * it will be cleaned up by step c. If the ire is
16103 			 * created after step d, it will see the new value of
16104 			 * ipif_mtu. Any attempt to create the ire between
16105 			 * steps a to d will fail because of the IPIF_CHANGING
16106 			 * flag. Note that ire_create() is passed a pointer to
16107 			 * the ipif_mtu, and not the value. During ire_add
16108 			 * under the bucket lock, the ire_max_frag of the
16109 			 * new ire being created is set from the ipif/ire from
16110 			 * which it is being derived.
16111 			 */
16112 			mutex_enter(&ill->ill_lock);
16113 			ill->ill_max_frag = (uint_t)notify->dl_data;
16114 
16115 			/*
16116 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16117 			 * leave it alone
16118 			 */
16119 			if (ill->ill_mtu_userspecified) {
16120 				mutex_exit(&ill->ill_lock);
16121 				break;
16122 			}
16123 			ill->ill_max_mtu = ill->ill_max_frag;
16124 			if (ill->ill_isv6) {
16125 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16126 					ill->ill_max_mtu = IPV6_MIN_MTU;
16127 			} else {
16128 				if (ill->ill_max_mtu < IP_MIN_MTU)
16129 					ill->ill_max_mtu = IP_MIN_MTU;
16130 			}
16131 			for (ipif = ill->ill_ipif; ipif != NULL;
16132 			    ipif = ipif->ipif_next) {
16133 				/*
16134 				 * Don't override the mtu if the user
16135 				 * has explicitly set it.
16136 				 */
16137 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16138 					continue;
16139 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16140 				if (ipif->ipif_isv6)
16141 					ire = ipif_to_ire_v6(ipif);
16142 				else
16143 					ire = ipif_to_ire(ipif);
16144 				if (ire != NULL) {
16145 					ire->ire_max_frag = ipif->ipif_mtu;
16146 					ire_refrele(ire);
16147 				}
16148 				if (ipif->ipif_flags & IPIF_UP) {
16149 					if (ill->ill_isv6)
16150 						need_ire_walk_v6 = B_TRUE;
16151 					else
16152 						need_ire_walk_v4 = B_TRUE;
16153 				}
16154 			}
16155 			mutex_exit(&ill->ill_lock);
16156 			if (need_ire_walk_v4)
16157 				ire_walk_v4(ill_mtu_change, (char *)ill,
16158 				    ALL_ZONES, ipst);
16159 			if (need_ire_walk_v6)
16160 				ire_walk_v6(ill_mtu_change, (char *)ill,
16161 				    ALL_ZONES, ipst);
16162 			break;
16163 		case DL_NOTE_LINK_UP:
16164 		case DL_NOTE_LINK_DOWN: {
16165 			/*
16166 			 * We are writer. ill / phyint / ipsq assocs stable.
16167 			 * The RUNNING flag reflects the state of the link.
16168 			 */
16169 			phyint_t *phyint = ill->ill_phyint;
16170 			uint64_t new_phyint_flags;
16171 			boolean_t changed = B_FALSE;
16172 			boolean_t went_up;
16173 
16174 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16175 			mutex_enter(&phyint->phyint_lock);
16176 			new_phyint_flags = went_up ?
16177 			    phyint->phyint_flags | PHYI_RUNNING :
16178 			    phyint->phyint_flags & ~PHYI_RUNNING;
16179 			if (new_phyint_flags != phyint->phyint_flags) {
16180 				phyint->phyint_flags = new_phyint_flags;
16181 				changed = B_TRUE;
16182 			}
16183 			mutex_exit(&phyint->phyint_lock);
16184 			/*
16185 			 * ill_restart_dad handles the DAD restart and routing
16186 			 * socket notification logic.
16187 			 */
16188 			if (changed) {
16189 				ill_restart_dad(phyint->phyint_illv4, went_up);
16190 				ill_restart_dad(phyint->phyint_illv6, went_up);
16191 			}
16192 			break;
16193 		}
16194 		case DL_NOTE_PROMISC_ON_PHYS:
16195 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16196 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16197 			mutex_enter(&ill->ill_lock);
16198 			ill->ill_promisc_on_phys = B_TRUE;
16199 			mutex_exit(&ill->ill_lock);
16200 			break;
16201 		case DL_NOTE_PROMISC_OFF_PHYS:
16202 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16203 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16204 			mutex_enter(&ill->ill_lock);
16205 			ill->ill_promisc_on_phys = B_FALSE;
16206 			mutex_exit(&ill->ill_lock);
16207 			break;
16208 		case DL_NOTE_CAPAB_RENEG:
16209 			/*
16210 			 * Something changed on the driver side.
16211 			 * It wants us to renegotiate the capabilities
16212 			 * on this ill. The most likely cause is the
16213 			 * aggregation interface under us where a
16214 			 * port got added or went away.
16215 			 *
16216 			 * We reset the capabilities and set the
16217 			 * state to IDS_RENG so that when the ack
16218 			 * comes back, we can start the
16219 			 * renegotiation process.
16220 			 */
16221 			ill_capability_reset(ill);
16222 			ill->ill_dlpi_capab_state = IDS_RENEG;
16223 			break;
16224 		default:
16225 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16226 			    "type 0x%x for DL_NOTIFY_IND\n",
16227 			    notify->dl_notification));
16228 			break;
16229 		}
16230 
16231 		/*
16232 		 * As this is an asynchronous operation, we
16233 		 * should not call ill_dlpi_done
16234 		 */
16235 		break;
16236 	}
16237 	case DL_NOTIFY_ACK: {
16238 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16239 
16240 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16241 			ill->ill_note_link = 1;
16242 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16243 		break;
16244 	}
16245 	case DL_PHYS_ADDR_ACK: {
16246 		/*
16247 		 * As part of plumbing the interface via SIOCSLIFNAME,
16248 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16249 		 * whose answers we receive here.  As each answer is received,
16250 		 * we call ill_dlpi_done() to dispatch the next request as
16251 		 * we're processing the current one.  Once all answers have
16252 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16253 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16254 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16255 		 * available, but we know the ioctl is pending on ill_wq.)
16256 		 */
16257 		uint_t paddrlen, paddroff;
16258 
16259 		paddrreq = ill->ill_phys_addr_pend;
16260 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16261 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16262 
16263 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16264 		if (paddrreq == DL_IPV6_TOKEN) {
16265 			/*
16266 			 * bcopy to low-order bits of ill_token
16267 			 *
16268 			 * XXX Temporary hack - currently, all known tokens
16269 			 * are 64 bits, so I'll cheat for the moment.
16270 			 */
16271 			bcopy(mp->b_rptr + paddroff,
16272 			    &ill->ill_token.s6_addr32[2], paddrlen);
16273 			ill->ill_token_length = paddrlen;
16274 			break;
16275 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16276 			ASSERT(ill->ill_nd_lla_mp == NULL);
16277 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16278 			mp = NULL;
16279 			break;
16280 		}
16281 
16282 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16283 		ASSERT(ill->ill_phys_addr_mp == NULL);
16284 		if (!ill->ill_ifname_pending)
16285 			break;
16286 		ill->ill_ifname_pending = 0;
16287 		if (!ioctl_aborted)
16288 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16289 		if (mp1 != NULL) {
16290 			ASSERT(connp == NULL);
16291 			q = ill->ill_wq;
16292 		}
16293 		/*
16294 		 * If any error acks received during the plumbing sequence,
16295 		 * ill_ifname_pending_err will be set. Break out and send up
16296 		 * the error to the pending ioctl.
16297 		 */
16298 		if (ill->ill_ifname_pending_err != 0) {
16299 			err = ill->ill_ifname_pending_err;
16300 			ill->ill_ifname_pending_err = 0;
16301 			break;
16302 		}
16303 
16304 		ill->ill_phys_addr_mp = mp;
16305 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16306 		mp = NULL;
16307 
16308 		/*
16309 		 * If paddrlen is zero, the DLPI provider doesn't support
16310 		 * physical addresses.  The other two tests were historical
16311 		 * workarounds for bugs in our former PPP implementation, but
16312 		 * now other things have grown dependencies on them -- e.g.,
16313 		 * the tun module specifies a dl_addr_length of zero in its
16314 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16315 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16316 		 * but only after careful testing ensures that all dependent
16317 		 * broken DLPI providers have been fixed.
16318 		 */
16319 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16320 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16321 			ill->ill_phys_addr = NULL;
16322 		} else if (paddrlen != ill->ill_phys_addr_length) {
16323 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16324 			    paddrlen, ill->ill_phys_addr_length));
16325 			err = EINVAL;
16326 			break;
16327 		}
16328 
16329 		if (ill->ill_nd_lla_mp == NULL) {
16330 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16331 				err = ENOMEM;
16332 				break;
16333 			}
16334 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16335 		}
16336 
16337 		/*
16338 		 * Set the interface token.  If the zeroth interface address
16339 		 * is unspecified, then set it to the link local address.
16340 		 */
16341 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16342 			(void) ill_setdefaulttoken(ill);
16343 
16344 		ASSERT(ill->ill_ipif->ipif_id == 0);
16345 		if (ipif != NULL &&
16346 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16347 			(void) ipif_setlinklocal(ipif);
16348 		}
16349 		break;
16350 	}
16351 	case DL_OK_ACK:
16352 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16353 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16354 		    dloa->dl_correct_primitive));
16355 		switch (dloa->dl_correct_primitive) {
16356 		case DL_PROMISCON_REQ:
16357 		case DL_PROMISCOFF_REQ:
16358 		case DL_ENABMULTI_REQ:
16359 		case DL_DISABMULTI_REQ:
16360 		case DL_UNBIND_REQ:
16361 		case DL_ATTACH_REQ:
16362 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16363 			break;
16364 		}
16365 		break;
16366 	default:
16367 		break;
16368 	}
16369 
16370 	freemsg(mp);
16371 	if (mp1 != NULL) {
16372 		/*
16373 		 * The operation must complete without EINPROGRESS
16374 		 * since ipsq_pending_mp_get() has removed the mblk
16375 		 * from ipsq_pending_mp.  Otherwise, the operation
16376 		 * will be stuck forever in the ipsq.
16377 		 */
16378 		ASSERT(err != EINPROGRESS);
16379 
16380 		switch (ipsq->ipsq_current_ioctl) {
16381 		case 0:
16382 			ipsq_current_finish(ipsq);
16383 			break;
16384 
16385 		case SIOCLIFADDIF:
16386 		case SIOCSLIFNAME:
16387 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16388 			break;
16389 
16390 		default:
16391 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16392 			break;
16393 		}
16394 	}
16395 }
16396 
16397 /*
16398  * ip_rput_other is called by ip_rput to handle messages modifying the global
16399  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16400  */
16401 /* ARGSUSED */
16402 void
16403 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16404 {
16405 	ill_t		*ill;
16406 	struct iocblk	*iocp;
16407 	mblk_t		*mp1;
16408 	conn_t		*connp = NULL;
16409 
16410 	ip1dbg(("ip_rput_other "));
16411 	ill = (ill_t *)q->q_ptr;
16412 	/*
16413 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16414 	 * in which case ipsq is NULL.
16415 	 */
16416 	if (ipsq != NULL) {
16417 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16418 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16419 	}
16420 
16421 	switch (mp->b_datap->db_type) {
16422 	case M_ERROR:
16423 	case M_HANGUP:
16424 		/*
16425 		 * The device has a problem.  We force the ILL down.  It can
16426 		 * be brought up again manually using SIOCSIFFLAGS (via
16427 		 * ifconfig or equivalent).
16428 		 */
16429 		ASSERT(ipsq != NULL);
16430 		if (mp->b_rptr < mp->b_wptr)
16431 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16432 		if (ill->ill_error == 0)
16433 			ill->ill_error = ENXIO;
16434 		if (!ill_down_start(q, mp))
16435 			return;
16436 		ipif_all_down_tail(ipsq, q, mp, NULL);
16437 		break;
16438 	case M_IOCACK:
16439 		iocp = (struct iocblk *)mp->b_rptr;
16440 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16441 		switch (iocp->ioc_cmd) {
16442 		case SIOCSTUNPARAM:
16443 		case OSIOCSTUNPARAM:
16444 			ASSERT(ipsq != NULL);
16445 			/*
16446 			 * Finish socket ioctl passed through to tun.
16447 			 * We should have an IOCTL waiting on this.
16448 			 */
16449 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16450 			if (ill->ill_isv6) {
16451 				struct iftun_req *ta;
16452 
16453 				/*
16454 				 * if a source or destination is
16455 				 * being set, try and set the link
16456 				 * local address for the tunnel
16457 				 */
16458 				ta = (struct iftun_req *)mp->b_cont->
16459 				    b_cont->b_rptr;
16460 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16461 					ipif_set_tun_llink(ill, ta);
16462 				}
16463 
16464 			}
16465 			if (mp1 != NULL) {
16466 				/*
16467 				 * Now copy back the b_next/b_prev used by
16468 				 * mi code for the mi_copy* functions.
16469 				 * See ip_sioctl_tunparam() for the reason.
16470 				 * Also protect against missing b_cont.
16471 				 */
16472 				if (mp->b_cont != NULL) {
16473 					mp->b_cont->b_next =
16474 					    mp1->b_cont->b_next;
16475 					mp->b_cont->b_prev =
16476 					    mp1->b_cont->b_prev;
16477 				}
16478 				inet_freemsg(mp1);
16479 				ASSERT(connp != NULL);
16480 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16481 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16482 			} else {
16483 				ASSERT(connp == NULL);
16484 				putnext(q, mp);
16485 			}
16486 			break;
16487 		case SIOCGTUNPARAM:
16488 		case OSIOCGTUNPARAM:
16489 			/*
16490 			 * This is really M_IOCDATA from the tunnel driver.
16491 			 * convert back and complete the ioctl.
16492 			 * We should have an IOCTL waiting on this.
16493 			 */
16494 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16495 			if (mp1) {
16496 				/*
16497 				 * Now copy back the b_next/b_prev used by
16498 				 * mi code for the mi_copy* functions.
16499 				 * See ip_sioctl_tunparam() for the reason.
16500 				 * Also protect against missing b_cont.
16501 				 */
16502 				if (mp->b_cont != NULL) {
16503 					mp->b_cont->b_next =
16504 					    mp1->b_cont->b_next;
16505 					mp->b_cont->b_prev =
16506 					    mp1->b_cont->b_prev;
16507 				}
16508 				inet_freemsg(mp1);
16509 				if (iocp->ioc_error == 0)
16510 					mp->b_datap->db_type = M_IOCDATA;
16511 				ASSERT(connp != NULL);
16512 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16513 				    iocp->ioc_error, COPYOUT, NULL);
16514 			} else {
16515 				ASSERT(connp == NULL);
16516 				putnext(q, mp);
16517 			}
16518 			break;
16519 		default:
16520 			break;
16521 		}
16522 		break;
16523 	case M_IOCNAK:
16524 		iocp = (struct iocblk *)mp->b_rptr;
16525 
16526 		switch (iocp->ioc_cmd) {
16527 		int mode;
16528 
16529 		case DL_IOC_HDR_INFO:
16530 			/*
16531 			 * If this was the first attempt turn of the
16532 			 * fastpath probing.
16533 			 */
16534 			mutex_enter(&ill->ill_lock);
16535 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16536 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16537 				mutex_exit(&ill->ill_lock);
16538 				ill_fastpath_nack(ill);
16539 				ip1dbg(("ip_rput: DLPI fastpath off on "
16540 				    "interface %s\n",
16541 				    ill->ill_name));
16542 			} else {
16543 				mutex_exit(&ill->ill_lock);
16544 			}
16545 			freemsg(mp);
16546 			break;
16547 		case SIOCSTUNPARAM:
16548 		case OSIOCSTUNPARAM:
16549 			ASSERT(ipsq != NULL);
16550 			/*
16551 			 * Finish socket ioctl passed through to tun
16552 			 * We should have an IOCTL waiting on this.
16553 			 */
16554 			/* FALLTHRU */
16555 		case SIOCGTUNPARAM:
16556 		case OSIOCGTUNPARAM:
16557 			/*
16558 			 * This is really M_IOCDATA from the tunnel driver.
16559 			 * convert back and complete the ioctl.
16560 			 * We should have an IOCTL waiting on this.
16561 			 */
16562 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16563 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16564 				mp1 = ill_pending_mp_get(ill, &connp,
16565 				    iocp->ioc_id);
16566 				mode = COPYOUT;
16567 				ipsq = NULL;
16568 			} else {
16569 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16570 				mode = NO_COPYOUT;
16571 			}
16572 			if (mp1 != NULL) {
16573 				/*
16574 				 * Now copy back the b_next/b_prev used by
16575 				 * mi code for the mi_copy* functions.
16576 				 * See ip_sioctl_tunparam() for the reason.
16577 				 * Also protect against missing b_cont.
16578 				 */
16579 				if (mp->b_cont != NULL) {
16580 					mp->b_cont->b_next =
16581 					    mp1->b_cont->b_next;
16582 					mp->b_cont->b_prev =
16583 					    mp1->b_cont->b_prev;
16584 				}
16585 				inet_freemsg(mp1);
16586 				if (iocp->ioc_error == 0)
16587 					iocp->ioc_error = EINVAL;
16588 				ASSERT(connp != NULL);
16589 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16590 				    iocp->ioc_error, mode, ipsq);
16591 			} else {
16592 				ASSERT(connp == NULL);
16593 				putnext(q, mp);
16594 			}
16595 			break;
16596 		default:
16597 			break;
16598 		}
16599 	default:
16600 		break;
16601 	}
16602 }
16603 
16604 /*
16605  * NOTE : This function does not ire_refrele the ire argument passed in.
16606  *
16607  * IPQoS notes
16608  * IP policy is invoked twice for a forwarded packet, once on the read side
16609  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16610  * enabled. An additional parameter, in_ill, has been added for this purpose.
16611  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16612  * because ip_mroute drops this information.
16613  *
16614  */
16615 void
16616 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16617 {
16618 	uint32_t	pkt_len;
16619 	queue_t	*q;
16620 	uint32_t	sum;
16621 #define	rptr	((uchar_t *)ipha)
16622 	uint32_t	max_frag;
16623 	uint32_t	ill_index;
16624 	ill_t		*out_ill;
16625 	mib2_ipIfStatsEntry_t *mibptr;
16626 	ip_stack_t	*ipst = in_ill->ill_ipst;
16627 
16628 	/* Get the ill_index of the incoming ILL */
16629 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16630 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16631 
16632 	/* Initiate Read side IPPF processing */
16633 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16634 		ip_process(IPP_FWD_IN, &mp, ill_index);
16635 		if (mp == NULL) {
16636 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16637 			    "during IPPF processing\n"));
16638 			return;
16639 		}
16640 	}
16641 
16642 	pkt_len = ntohs(ipha->ipha_length);
16643 
16644 	/* Adjust the checksum to reflect the ttl decrement. */
16645 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16646 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16647 
16648 	if (ipha->ipha_ttl-- <= 1) {
16649 		if (ip_csum_hdr(ipha)) {
16650 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16651 			goto drop_pkt;
16652 		}
16653 		/*
16654 		 * Note: ire_stq this will be NULL for multicast
16655 		 * datagrams using the long path through arp (the IRE
16656 		 * is not an IRE_CACHE). This should not cause
16657 		 * problems since we don't generate ICMP errors for
16658 		 * multicast packets.
16659 		 */
16660 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16661 		q = ire->ire_stq;
16662 		if (q != NULL) {
16663 			/* Sent by forwarding path, and router is global zone */
16664 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16665 			    GLOBAL_ZONEID, ipst);
16666 		} else
16667 			freemsg(mp);
16668 		return;
16669 	}
16670 
16671 	/*
16672 	 * Don't forward if the interface is down
16673 	 */
16674 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16675 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16676 		ip2dbg(("ip_rput_forward:interface is down\n"));
16677 		goto drop_pkt;
16678 	}
16679 
16680 	/* Get the ill_index of the outgoing ILL */
16681 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16682 
16683 	out_ill = ire->ire_ipif->ipif_ill;
16684 
16685 	DTRACE_PROBE4(ip4__forwarding__start,
16686 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16687 
16688 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16689 	    ipst->ips_ipv4firewall_forwarding,
16690 	    in_ill, out_ill, ipha, mp, mp, ipst);
16691 
16692 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16693 
16694 	if (mp == NULL)
16695 		return;
16696 	pkt_len = ntohs(ipha->ipha_length);
16697 
16698 	if (is_system_labeled()) {
16699 		mblk_t *mp1;
16700 
16701 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16702 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16703 			goto drop_pkt;
16704 		}
16705 		/* Size may have changed */
16706 		mp = mp1;
16707 		ipha = (ipha_t *)mp->b_rptr;
16708 		pkt_len = ntohs(ipha->ipha_length);
16709 	}
16710 
16711 	/* Check if there are options to update */
16712 	if (!IS_SIMPLE_IPH(ipha)) {
16713 		if (ip_csum_hdr(ipha)) {
16714 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16715 			goto drop_pkt;
16716 		}
16717 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16718 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16719 			return;
16720 		}
16721 
16722 		ipha->ipha_hdr_checksum = 0;
16723 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16724 	}
16725 	max_frag = ire->ire_max_frag;
16726 	if (pkt_len > max_frag) {
16727 		/*
16728 		 * It needs fragging on its way out.  We haven't
16729 		 * verified the header checksum yet.  Since we
16730 		 * are going to put a surely good checksum in the
16731 		 * outgoing header, we have to make sure that it
16732 		 * was good coming in.
16733 		 */
16734 		if (ip_csum_hdr(ipha)) {
16735 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16736 			goto drop_pkt;
16737 		}
16738 		/* Initiate Write side IPPF processing */
16739 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16740 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16741 			if (mp == NULL) {
16742 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16743 				    " during IPPF processing\n"));
16744 				return;
16745 			}
16746 		}
16747 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16748 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16749 		return;
16750 	}
16751 
16752 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16753 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16754 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16755 	    ipst->ips_ipv4firewall_physical_out,
16756 	    NULL, out_ill, ipha, mp, mp, ipst);
16757 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16758 	if (mp == NULL)
16759 		return;
16760 
16761 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16762 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16763 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16764 	/* ip_xmit_v4 always consumes the packet */
16765 	return;
16766 
16767 drop_pkt:;
16768 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16769 	freemsg(mp);
16770 #undef	rptr
16771 }
16772 
16773 void
16774 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16775 {
16776 	ire_t	*ire;
16777 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16778 
16779 	ASSERT(!ipif->ipif_isv6);
16780 	/*
16781 	 * Find an IRE which matches the destination and the outgoing
16782 	 * queue in the cache table. All we need is an IRE_CACHE which
16783 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16784 	 * then it is enough to have some IRE_CACHE in the group.
16785 	 */
16786 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16787 		dst = ipif->ipif_pp_dst_addr;
16788 
16789 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16790 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16791 	if (ire == NULL) {
16792 		/*
16793 		 * Mark this packet to make it be delivered to
16794 		 * ip_rput_forward after the new ire has been
16795 		 * created.
16796 		 */
16797 		mp->b_prev = NULL;
16798 		mp->b_next = mp;
16799 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16800 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16801 	} else {
16802 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16803 		IRE_REFRELE(ire);
16804 	}
16805 }
16806 
16807 /* Update any source route, record route or timestamp options */
16808 static int
16809 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16810 {
16811 	ipoptp_t	opts;
16812 	uchar_t		*opt;
16813 	uint8_t		optval;
16814 	uint8_t		optlen;
16815 	ipaddr_t	dst;
16816 	uint32_t	ts;
16817 	ire_t		*dst_ire = NULL;
16818 	ire_t		*tmp_ire = NULL;
16819 	timestruc_t	now;
16820 
16821 	ip2dbg(("ip_rput_forward_options\n"));
16822 	dst = ipha->ipha_dst;
16823 	for (optval = ipoptp_first(&opts, ipha);
16824 	    optval != IPOPT_EOL;
16825 	    optval = ipoptp_next(&opts)) {
16826 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16827 		opt = opts.ipoptp_cur;
16828 		optlen = opts.ipoptp_len;
16829 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16830 		    optval, opts.ipoptp_len));
16831 		switch (optval) {
16832 			uint32_t off;
16833 		case IPOPT_SSRR:
16834 		case IPOPT_LSRR:
16835 			/* Check if adminstratively disabled */
16836 			if (!ipst->ips_ip_forward_src_routed) {
16837 				if (ire->ire_stq != NULL) {
16838 					/*
16839 					 * Sent by forwarding path, and router
16840 					 * is global zone
16841 					 */
16842 					icmp_unreachable(ire->ire_stq, mp,
16843 					    ICMP_SOURCE_ROUTE_FAILED,
16844 					    GLOBAL_ZONEID, ipst);
16845 				} else {
16846 					ip0dbg(("ip_rput_forward_options: "
16847 					    "unable to send unreach\n"));
16848 					freemsg(mp);
16849 				}
16850 				return (-1);
16851 			}
16852 
16853 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16854 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16855 			if (dst_ire == NULL) {
16856 				/*
16857 				 * Must be partial since ip_rput_options
16858 				 * checked for strict.
16859 				 */
16860 				break;
16861 			}
16862 			off = opt[IPOPT_OFFSET];
16863 			off--;
16864 		redo_srr:
16865 			if (optlen < IP_ADDR_LEN ||
16866 			    off > optlen - IP_ADDR_LEN) {
16867 				/* End of source route */
16868 				ip1dbg((
16869 				    "ip_rput_forward_options: end of SR\n"));
16870 				ire_refrele(dst_ire);
16871 				break;
16872 			}
16873 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16874 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16875 			    IP_ADDR_LEN);
16876 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16877 			    ntohl(dst)));
16878 
16879 			/*
16880 			 * Check if our address is present more than
16881 			 * once as consecutive hops in source route.
16882 			 */
16883 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16884 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16885 			if (tmp_ire != NULL) {
16886 				ire_refrele(tmp_ire);
16887 				off += IP_ADDR_LEN;
16888 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16889 				goto redo_srr;
16890 			}
16891 			ipha->ipha_dst = dst;
16892 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16893 			ire_refrele(dst_ire);
16894 			break;
16895 		case IPOPT_RR:
16896 			off = opt[IPOPT_OFFSET];
16897 			off--;
16898 			if (optlen < IP_ADDR_LEN ||
16899 			    off > optlen - IP_ADDR_LEN) {
16900 				/* No more room - ignore */
16901 				ip1dbg((
16902 				    "ip_rput_forward_options: end of RR\n"));
16903 				break;
16904 			}
16905 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16906 			    IP_ADDR_LEN);
16907 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16908 			break;
16909 		case IPOPT_TS:
16910 			/* Insert timestamp if there is room */
16911 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16912 			case IPOPT_TS_TSONLY:
16913 				off = IPOPT_TS_TIMELEN;
16914 				break;
16915 			case IPOPT_TS_PRESPEC:
16916 			case IPOPT_TS_PRESPEC_RFC791:
16917 				/* Verify that the address matched */
16918 				off = opt[IPOPT_OFFSET] - 1;
16919 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16920 				dst_ire = ire_ctable_lookup(dst, 0,
16921 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16922 				    MATCH_IRE_TYPE, ipst);
16923 				if (dst_ire == NULL) {
16924 					/* Not for us */
16925 					break;
16926 				}
16927 				ire_refrele(dst_ire);
16928 				/* FALLTHRU */
16929 			case IPOPT_TS_TSANDADDR:
16930 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16931 				break;
16932 			default:
16933 				/*
16934 				 * ip_*put_options should have already
16935 				 * dropped this packet.
16936 				 */
16937 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16938 				    "unknown IT - bug in ip_rput_options?\n");
16939 				return (0);	/* Keep "lint" happy */
16940 			}
16941 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16942 				/* Increase overflow counter */
16943 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16944 				opt[IPOPT_POS_OV_FLG] =
16945 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16946 				    (off << 4));
16947 				break;
16948 			}
16949 			off = opt[IPOPT_OFFSET] - 1;
16950 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16951 			case IPOPT_TS_PRESPEC:
16952 			case IPOPT_TS_PRESPEC_RFC791:
16953 			case IPOPT_TS_TSANDADDR:
16954 				bcopy(&ire->ire_src_addr,
16955 				    (char *)opt + off, IP_ADDR_LEN);
16956 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16957 				/* FALLTHRU */
16958 			case IPOPT_TS_TSONLY:
16959 				off = opt[IPOPT_OFFSET] - 1;
16960 				/* Compute # of milliseconds since midnight */
16961 				gethrestime(&now);
16962 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16963 				    now.tv_nsec / (NANOSEC / MILLISEC);
16964 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16965 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16966 				break;
16967 			}
16968 			break;
16969 		}
16970 	}
16971 	return (0);
16972 }
16973 
16974 /*
16975  * This is called after processing at least one of AH/ESP headers.
16976  *
16977  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16978  * the actual, physical interface on which the packet was received,
16979  * but, when ip_strict_dst_multihoming is set to 1, could be the
16980  * interface which had the ipha_dst configured when the packet went
16981  * through ip_rput. The ill_index corresponding to the recv_ill
16982  * is saved in ipsec_in_rill_index
16983  *
16984  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16985  * cannot assume "ire" points to valid data for any IPv6 cases.
16986  */
16987 void
16988 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16989 {
16990 	mblk_t *mp;
16991 	ipaddr_t dst;
16992 	in6_addr_t *v6dstp;
16993 	ipha_t *ipha;
16994 	ip6_t *ip6h;
16995 	ipsec_in_t *ii;
16996 	boolean_t ill_need_rele = B_FALSE;
16997 	boolean_t rill_need_rele = B_FALSE;
16998 	boolean_t ire_need_rele = B_FALSE;
16999 	netstack_t	*ns;
17000 	ip_stack_t	*ipst;
17001 
17002 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17003 	ASSERT(ii->ipsec_in_ill_index != 0);
17004 	ns = ii->ipsec_in_ns;
17005 	ASSERT(ii->ipsec_in_ns != NULL);
17006 	ipst = ns->netstack_ip;
17007 
17008 	mp = ipsec_mp->b_cont;
17009 	ASSERT(mp != NULL);
17010 
17011 
17012 	if (ill == NULL) {
17013 		ASSERT(recv_ill == NULL);
17014 		/*
17015 		 * We need to get the original queue on which ip_rput_local
17016 		 * or ip_rput_data_v6 was called.
17017 		 */
17018 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17019 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17020 		ill_need_rele = B_TRUE;
17021 
17022 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17023 			recv_ill = ill_lookup_on_ifindex(
17024 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17025 			    NULL, NULL, NULL, NULL, ipst);
17026 			rill_need_rele = B_TRUE;
17027 		} else {
17028 			recv_ill = ill;
17029 		}
17030 
17031 		if ((ill == NULL) || (recv_ill == NULL)) {
17032 			ip0dbg(("ip_fanout_proto_again: interface "
17033 			    "disappeared\n"));
17034 			if (ill != NULL)
17035 				ill_refrele(ill);
17036 			if (recv_ill != NULL)
17037 				ill_refrele(recv_ill);
17038 			freemsg(ipsec_mp);
17039 			return;
17040 		}
17041 	}
17042 
17043 	ASSERT(ill != NULL && recv_ill != NULL);
17044 
17045 	if (mp->b_datap->db_type == M_CTL) {
17046 		/*
17047 		 * AH/ESP is returning the ICMP message after
17048 		 * removing their headers. Fanout again till
17049 		 * it gets to the right protocol.
17050 		 */
17051 		if (ii->ipsec_in_v4) {
17052 			icmph_t *icmph;
17053 			int iph_hdr_length;
17054 			int hdr_length;
17055 
17056 			ipha = (ipha_t *)mp->b_rptr;
17057 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17058 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17059 			ipha = (ipha_t *)&icmph[1];
17060 			hdr_length = IPH_HDR_LENGTH(ipha);
17061 			/*
17062 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17063 			 * Reset the type to M_DATA.
17064 			 */
17065 			mp->b_datap->db_type = M_DATA;
17066 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17067 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17068 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17069 		} else {
17070 			icmp6_t *icmp6;
17071 			int hdr_length;
17072 
17073 			ip6h = (ip6_t *)mp->b_rptr;
17074 			/* Don't call hdr_length_v6() unless you have to. */
17075 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17076 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17077 			else
17078 				hdr_length = IPV6_HDR_LEN;
17079 
17080 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17081 			/*
17082 			 * icmp_inbound_error_fanout_v6 may need to do
17083 			 * pullupmsg.  Reset the type to M_DATA.
17084 			 */
17085 			mp->b_datap->db_type = M_DATA;
17086 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17087 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17088 		}
17089 		if (ill_need_rele)
17090 			ill_refrele(ill);
17091 		if (rill_need_rele)
17092 			ill_refrele(recv_ill);
17093 		return;
17094 	}
17095 
17096 	if (ii->ipsec_in_v4) {
17097 		ipha = (ipha_t *)mp->b_rptr;
17098 		dst = ipha->ipha_dst;
17099 		if (CLASSD(dst)) {
17100 			/*
17101 			 * Multicast has to be delivered to all streams.
17102 			 */
17103 			dst = INADDR_BROADCAST;
17104 		}
17105 
17106 		if (ire == NULL) {
17107 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17108 			    MBLK_GETLABEL(mp), ipst);
17109 			if (ire == NULL) {
17110 				if (ill_need_rele)
17111 					ill_refrele(ill);
17112 				if (rill_need_rele)
17113 					ill_refrele(recv_ill);
17114 				ip1dbg(("ip_fanout_proto_again: "
17115 				    "IRE not found"));
17116 				freemsg(ipsec_mp);
17117 				return;
17118 			}
17119 			ire_need_rele = B_TRUE;
17120 		}
17121 
17122 		switch (ipha->ipha_protocol) {
17123 			case IPPROTO_UDP:
17124 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17125 				    recv_ill);
17126 				if (ire_need_rele)
17127 					ire_refrele(ire);
17128 				break;
17129 			case IPPROTO_TCP:
17130 				if (!ire_need_rele)
17131 					IRE_REFHOLD(ire);
17132 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17133 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17134 				IRE_REFRELE(ire);
17135 				if (mp != NULL)
17136 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17137 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17138 				break;
17139 			case IPPROTO_SCTP:
17140 				if (!ire_need_rele)
17141 					IRE_REFHOLD(ire);
17142 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17143 				    ipsec_mp, 0, ill->ill_rq, dst);
17144 				break;
17145 			default:
17146 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17147 				    recv_ill);
17148 				if (ire_need_rele)
17149 					ire_refrele(ire);
17150 				break;
17151 		}
17152 	} else {
17153 		uint32_t rput_flags = 0;
17154 
17155 		ip6h = (ip6_t *)mp->b_rptr;
17156 		v6dstp = &ip6h->ip6_dst;
17157 		/*
17158 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17159 		 * address.
17160 		 *
17161 		 * Currently, we don't store that state in the IPSEC_IN
17162 		 * message, and we may need to.
17163 		 */
17164 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17165 		    IP6_IN_LLMCAST : 0);
17166 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17167 		    NULL, NULL);
17168 	}
17169 	if (ill_need_rele)
17170 		ill_refrele(ill);
17171 	if (rill_need_rele)
17172 		ill_refrele(recv_ill);
17173 }
17174 
17175 /*
17176  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17177  * returns 'true' if there are still fragments left on the queue, in
17178  * which case we restart the timer.
17179  */
17180 void
17181 ill_frag_timer(void *arg)
17182 {
17183 	ill_t	*ill = (ill_t *)arg;
17184 	boolean_t frag_pending;
17185 	ip_stack_t	*ipst = ill->ill_ipst;
17186 
17187 	mutex_enter(&ill->ill_lock);
17188 	ASSERT(!ill->ill_fragtimer_executing);
17189 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17190 		ill->ill_frag_timer_id = 0;
17191 		mutex_exit(&ill->ill_lock);
17192 		return;
17193 	}
17194 	ill->ill_fragtimer_executing = 1;
17195 	mutex_exit(&ill->ill_lock);
17196 
17197 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17198 
17199 	/*
17200 	 * Restart the timer, if we have fragments pending or if someone
17201 	 * wanted us to be scheduled again.
17202 	 */
17203 	mutex_enter(&ill->ill_lock);
17204 	ill->ill_fragtimer_executing = 0;
17205 	ill->ill_frag_timer_id = 0;
17206 	if (frag_pending || ill->ill_fragtimer_needrestart)
17207 		ill_frag_timer_start(ill);
17208 	mutex_exit(&ill->ill_lock);
17209 }
17210 
17211 void
17212 ill_frag_timer_start(ill_t *ill)
17213 {
17214 	ip_stack_t	*ipst = ill->ill_ipst;
17215 
17216 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17217 
17218 	/* If the ill is closing or opening don't proceed */
17219 	if (ill->ill_state_flags & ILL_CONDEMNED)
17220 		return;
17221 
17222 	if (ill->ill_fragtimer_executing) {
17223 		/*
17224 		 * ill_frag_timer is currently executing. Just record the
17225 		 * the fact that we want the timer to be restarted.
17226 		 * ill_frag_timer will post a timeout before it returns,
17227 		 * ensuring it will be called again.
17228 		 */
17229 		ill->ill_fragtimer_needrestart = 1;
17230 		return;
17231 	}
17232 
17233 	if (ill->ill_frag_timer_id == 0) {
17234 		/*
17235 		 * The timer is neither running nor is the timeout handler
17236 		 * executing. Post a timeout so that ill_frag_timer will be
17237 		 * called
17238 		 */
17239 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17240 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17241 		ill->ill_fragtimer_needrestart = 0;
17242 	}
17243 }
17244 
17245 /*
17246  * This routine is needed for loopback when forwarding multicasts.
17247  *
17248  * IPQoS Notes:
17249  * IPPF processing is done in fanout routines.
17250  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17251  * processing for IPSec packets is done when it comes back in clear.
17252  * NOTE : The callers of this function need to do the ire_refrele for the
17253  *	  ire that is being passed in.
17254  */
17255 void
17256 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17257     ill_t *recv_ill)
17258 {
17259 	ill_t	*ill = (ill_t *)q->q_ptr;
17260 	uint32_t	sum;
17261 	uint32_t	u1;
17262 	uint32_t	u2;
17263 	int		hdr_length;
17264 	boolean_t	mctl_present;
17265 	mblk_t		*first_mp = mp;
17266 	mblk_t		*hada_mp = NULL;
17267 	ipha_t		*inner_ipha;
17268 	ip_stack_t	*ipst;
17269 
17270 	ASSERT(recv_ill != NULL);
17271 	ipst = recv_ill->ill_ipst;
17272 
17273 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17274 	    "ip_rput_locl_start: q %p", q);
17275 
17276 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17277 	ASSERT(ill != NULL);
17278 
17279 
17280 #define	rptr	((uchar_t *)ipha)
17281 #define	iphs	((uint16_t *)ipha)
17282 
17283 	/*
17284 	 * no UDP or TCP packet should come here anymore.
17285 	 */
17286 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17287 	    (ipha->ipha_protocol != IPPROTO_UDP));
17288 
17289 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17290 	if (mctl_present &&
17291 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17292 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17293 
17294 		/*
17295 		 * It's an IPsec accelerated packet.
17296 		 * Keep a pointer to the data attributes around until
17297 		 * we allocate the ipsec_info_t.
17298 		 */
17299 		IPSECHW_DEBUG(IPSECHW_PKT,
17300 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17301 		hada_mp = first_mp;
17302 		hada_mp->b_cont = NULL;
17303 		/*
17304 		 * Since it is accelerated, it comes directly from
17305 		 * the ill and the data attributes is followed by
17306 		 * the packet data.
17307 		 */
17308 		ASSERT(mp->b_datap->db_type != M_CTL);
17309 		first_mp = mp;
17310 		mctl_present = B_FALSE;
17311 	}
17312 
17313 	/*
17314 	 * IF M_CTL is not present, then ipsec_in_is_secure
17315 	 * should return B_TRUE. There is a case where loopback
17316 	 * packets has an M_CTL in the front with all the
17317 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17318 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17319 	 * packets never comes here, it is safe to ASSERT the
17320 	 * following.
17321 	 */
17322 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17323 
17324 
17325 	/* u1 is # words of IP options */
17326 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17327 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17328 
17329 	if (u1) {
17330 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17331 			if (hada_mp != NULL)
17332 				freemsg(hada_mp);
17333 			return;
17334 		}
17335 	} else {
17336 		/* Check the IP header checksum.  */
17337 #define	uph	((uint16_t *)ipha)
17338 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17339 		    uph[6] + uph[7] + uph[8] + uph[9];
17340 #undef  uph
17341 		/* finish doing IP checksum */
17342 		sum = (sum & 0xFFFF) + (sum >> 16);
17343 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17344 		/*
17345 		 * Don't verify header checksum if this packet is coming
17346 		 * back from AH/ESP as we already did it.
17347 		 */
17348 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17349 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17350 			goto drop_pkt;
17351 		}
17352 	}
17353 
17354 	/*
17355 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17356 	 * might be called more than once for secure packets, count only
17357 	 * the first time.
17358 	 */
17359 	if (!mctl_present) {
17360 		UPDATE_IB_PKT_COUNT(ire);
17361 		ire->ire_last_used_time = lbolt;
17362 	}
17363 
17364 	/* Check for fragmentation offset. */
17365 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17366 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17367 	if (u1) {
17368 		/*
17369 		 * We re-assemble fragments before we do the AH/ESP
17370 		 * processing. Thus, M_CTL should not be present
17371 		 * while we are re-assembling.
17372 		 */
17373 		ASSERT(!mctl_present);
17374 		ASSERT(first_mp == mp);
17375 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17376 			return;
17377 		}
17378 		/*
17379 		 * Make sure that first_mp points back to mp as
17380 		 * the mp we came in with could have changed in
17381 		 * ip_rput_fragment().
17382 		 */
17383 		ipha = (ipha_t *)mp->b_rptr;
17384 		first_mp = mp;
17385 	}
17386 
17387 	/*
17388 	 * Clear hardware checksumming flag as it is currently only
17389 	 * used by TCP and UDP.
17390 	 */
17391 	DB_CKSUMFLAGS(mp) = 0;
17392 
17393 	/* Now we have a complete datagram, destined for this machine. */
17394 	u1 = IPH_HDR_LENGTH(ipha);
17395 	switch (ipha->ipha_protocol) {
17396 	case IPPROTO_ICMP: {
17397 		ire_t		*ire_zone;
17398 		ilm_t		*ilm;
17399 		mblk_t		*mp1;
17400 		zoneid_t	last_zoneid;
17401 
17402 		if (CLASSD(ipha->ipha_dst) &&
17403 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17404 			ASSERT(ire->ire_type == IRE_BROADCAST);
17405 			/*
17406 			 * In the multicast case, applications may have joined
17407 			 * the group from different zones, so we need to deliver
17408 			 * the packet to each of them. Loop through the
17409 			 * multicast memberships structures (ilm) on the receive
17410 			 * ill and send a copy of the packet up each matching
17411 			 * one. However, we don't do this for multicasts sent on
17412 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17413 			 * they must stay in the sender's zone.
17414 			 *
17415 			 * ilm_add_v6() ensures that ilms in the same zone are
17416 			 * contiguous in the ill_ilm list. We use this property
17417 			 * to avoid sending duplicates needed when two
17418 			 * applications in the same zone join the same group on
17419 			 * different logical interfaces: we ignore the ilm if
17420 			 * its zoneid is the same as the last matching one.
17421 			 * In addition, the sending of the packet for
17422 			 * ire_zoneid is delayed until all of the other ilms
17423 			 * have been exhausted.
17424 			 */
17425 			last_zoneid = -1;
17426 			ILM_WALKER_HOLD(recv_ill);
17427 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17428 			    ilm = ilm->ilm_next) {
17429 				if ((ilm->ilm_flags & ILM_DELETED) ||
17430 				    ipha->ipha_dst != ilm->ilm_addr ||
17431 				    ilm->ilm_zoneid == last_zoneid ||
17432 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17433 				    ilm->ilm_zoneid == ALL_ZONES ||
17434 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17435 					continue;
17436 				mp1 = ip_copymsg(first_mp);
17437 				if (mp1 == NULL)
17438 					continue;
17439 				icmp_inbound(q, mp1, B_TRUE, ill,
17440 				    0, sum, mctl_present, B_TRUE,
17441 				    recv_ill, ilm->ilm_zoneid);
17442 				last_zoneid = ilm->ilm_zoneid;
17443 			}
17444 			ILM_WALKER_RELE(recv_ill);
17445 		} else if (ire->ire_type == IRE_BROADCAST) {
17446 			/*
17447 			 * In the broadcast case, there may be many zones
17448 			 * which need a copy of the packet delivered to them.
17449 			 * There is one IRE_BROADCAST per broadcast address
17450 			 * and per zone; we walk those using a helper function.
17451 			 * In addition, the sending of the packet for ire is
17452 			 * delayed until all of the other ires have been
17453 			 * processed.
17454 			 */
17455 			IRB_REFHOLD(ire->ire_bucket);
17456 			ire_zone = NULL;
17457 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17458 			    ire)) != NULL) {
17459 				mp1 = ip_copymsg(first_mp);
17460 				if (mp1 == NULL)
17461 					continue;
17462 
17463 				UPDATE_IB_PKT_COUNT(ire_zone);
17464 				ire_zone->ire_last_used_time = lbolt;
17465 				icmp_inbound(q, mp1, B_TRUE, ill,
17466 				    0, sum, mctl_present, B_TRUE,
17467 				    recv_ill, ire_zone->ire_zoneid);
17468 			}
17469 			IRB_REFRELE(ire->ire_bucket);
17470 		}
17471 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17472 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17473 		    ire->ire_zoneid);
17474 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17475 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17476 		return;
17477 	}
17478 	case IPPROTO_IGMP:
17479 		/*
17480 		 * If we are not willing to accept IGMP packets in clear,
17481 		 * then check with global policy.
17482 		 */
17483 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17484 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17485 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17486 			if (first_mp == NULL)
17487 				return;
17488 		}
17489 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17490 			freemsg(first_mp);
17491 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17492 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17493 			return;
17494 		}
17495 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17496 			/* Bad packet - discarded by igmp_input */
17497 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17498 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17499 			if (mctl_present)
17500 				freeb(first_mp);
17501 			return;
17502 		}
17503 		/*
17504 		 * igmp_input() may have returned the pulled up message.
17505 		 * So first_mp and ipha need to be reinitialized.
17506 		 */
17507 		ipha = (ipha_t *)mp->b_rptr;
17508 		if (mctl_present)
17509 			first_mp->b_cont = mp;
17510 		else
17511 			first_mp = mp;
17512 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17513 		    connf_head != NULL) {
17514 			/* No user-level listener for IGMP packets */
17515 			goto drop_pkt;
17516 		}
17517 		/* deliver to local raw users */
17518 		break;
17519 	case IPPROTO_PIM:
17520 		/*
17521 		 * If we are not willing to accept PIM packets in clear,
17522 		 * then check with global policy.
17523 		 */
17524 		if (ipst->ips_pim_accept_clear_messages == 0) {
17525 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17526 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17527 			if (first_mp == NULL)
17528 				return;
17529 		}
17530 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17531 			freemsg(first_mp);
17532 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17533 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17534 			return;
17535 		}
17536 		if (pim_input(q, mp, ill) != 0) {
17537 			/* Bad packet - discarded by pim_input */
17538 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17539 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17540 			if (mctl_present)
17541 				freeb(first_mp);
17542 			return;
17543 		}
17544 
17545 		/*
17546 		 * pim_input() may have pulled up the message so ipha needs to
17547 		 * be reinitialized.
17548 		 */
17549 		ipha = (ipha_t *)mp->b_rptr;
17550 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17551 		    connf_head != NULL) {
17552 			/* No user-level listener for PIM packets */
17553 			goto drop_pkt;
17554 		}
17555 		/* deliver to local raw users */
17556 		break;
17557 	case IPPROTO_ENCAP:
17558 		/*
17559 		 * Handle self-encapsulated packets (IP-in-IP where
17560 		 * the inner addresses == the outer addresses).
17561 		 */
17562 		hdr_length = IPH_HDR_LENGTH(ipha);
17563 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17564 		    mp->b_wptr) {
17565 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17566 			    sizeof (ipha_t) - mp->b_rptr)) {
17567 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17568 				freemsg(first_mp);
17569 				return;
17570 			}
17571 			ipha = (ipha_t *)mp->b_rptr;
17572 		}
17573 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17574 		/*
17575 		 * Check the sanity of the inner IP header.
17576 		 */
17577 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17578 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17579 			freemsg(first_mp);
17580 			return;
17581 		}
17582 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17583 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17584 			freemsg(first_mp);
17585 			return;
17586 		}
17587 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17588 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17589 			ipsec_in_t *ii;
17590 
17591 			/*
17592 			 * Self-encapsulated tunnel packet. Remove
17593 			 * the outer IP header and fanout again.
17594 			 * We also need to make sure that the inner
17595 			 * header is pulled up until options.
17596 			 */
17597 			mp->b_rptr = (uchar_t *)inner_ipha;
17598 			ipha = inner_ipha;
17599 			hdr_length = IPH_HDR_LENGTH(ipha);
17600 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17601 				if (!pullupmsg(mp, (uchar_t *)ipha +
17602 				    + hdr_length - mp->b_rptr)) {
17603 					freemsg(first_mp);
17604 					return;
17605 				}
17606 				ipha = (ipha_t *)mp->b_rptr;
17607 			}
17608 			if (!mctl_present) {
17609 				ASSERT(first_mp == mp);
17610 				/*
17611 				 * This means that somebody is sending
17612 				 * Self-encapsualted packets without AH/ESP.
17613 				 * If AH/ESP was present, we would have already
17614 				 * allocated the first_mp.
17615 				 */
17616 				first_mp = ipsec_in_alloc(B_TRUE,
17617 				    ipst->ips_netstack);
17618 				if (first_mp == NULL) {
17619 					ip1dbg(("ip_proto_input: IPSEC_IN "
17620 					    "allocation failure.\n"));
17621 					BUMP_MIB(ill->ill_ip_mib,
17622 					    ipIfStatsInDiscards);
17623 					freemsg(mp);
17624 					return;
17625 				}
17626 				first_mp->b_cont = mp;
17627 			}
17628 			/*
17629 			 * We generally store the ill_index if we need to
17630 			 * do IPSEC processing as we lose the ill queue when
17631 			 * we come back. But in this case, we never should
17632 			 * have to store the ill_index here as it should have
17633 			 * been stored previously when we processed the
17634 			 * AH/ESP header in this routine or for non-ipsec
17635 			 * cases, we still have the queue. But for some bad
17636 			 * packets from the wire, we can get to IPSEC after
17637 			 * this and we better store the index for that case.
17638 			 */
17639 			ill = (ill_t *)q->q_ptr;
17640 			ii = (ipsec_in_t *)first_mp->b_rptr;
17641 			ii->ipsec_in_ill_index =
17642 			    ill->ill_phyint->phyint_ifindex;
17643 			ii->ipsec_in_rill_index =
17644 			    recv_ill->ill_phyint->phyint_ifindex;
17645 			if (ii->ipsec_in_decaps) {
17646 				/*
17647 				 * This packet is self-encapsulated multiple
17648 				 * times. We don't want to recurse infinitely.
17649 				 * To keep it simple, drop the packet.
17650 				 */
17651 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17652 				freemsg(first_mp);
17653 				return;
17654 			}
17655 			ii->ipsec_in_decaps = B_TRUE;
17656 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17657 			    ire);
17658 			return;
17659 		}
17660 		break;
17661 	case IPPROTO_AH:
17662 	case IPPROTO_ESP: {
17663 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17664 
17665 		/*
17666 		 * Fast path for AH/ESP. If this is the first time
17667 		 * we are sending a datagram to AH/ESP, allocate
17668 		 * a IPSEC_IN message and prepend it. Otherwise,
17669 		 * just fanout.
17670 		 */
17671 
17672 		int ipsec_rc;
17673 		ipsec_in_t *ii;
17674 		netstack_t *ns = ipst->ips_netstack;
17675 
17676 		IP_STAT(ipst, ipsec_proto_ahesp);
17677 		if (!mctl_present) {
17678 			ASSERT(first_mp == mp);
17679 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17680 			if (first_mp == NULL) {
17681 				ip1dbg(("ip_proto_input: IPSEC_IN "
17682 				    "allocation failure.\n"));
17683 				freemsg(hada_mp); /* okay ifnull */
17684 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17685 				freemsg(mp);
17686 				return;
17687 			}
17688 			/*
17689 			 * Store the ill_index so that when we come back
17690 			 * from IPSEC we ride on the same queue.
17691 			 */
17692 			ill = (ill_t *)q->q_ptr;
17693 			ii = (ipsec_in_t *)first_mp->b_rptr;
17694 			ii->ipsec_in_ill_index =
17695 			    ill->ill_phyint->phyint_ifindex;
17696 			ii->ipsec_in_rill_index =
17697 			    recv_ill->ill_phyint->phyint_ifindex;
17698 			first_mp->b_cont = mp;
17699 			/*
17700 			 * Cache hardware acceleration info.
17701 			 */
17702 			if (hada_mp != NULL) {
17703 				IPSECHW_DEBUG(IPSECHW_PKT,
17704 				    ("ip_rput_local: caching data attr.\n"));
17705 				ii->ipsec_in_accelerated = B_TRUE;
17706 				ii->ipsec_in_da = hada_mp;
17707 				hada_mp = NULL;
17708 			}
17709 		} else {
17710 			ii = (ipsec_in_t *)first_mp->b_rptr;
17711 		}
17712 
17713 		if (!ipsec_loaded(ipss)) {
17714 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17715 			    ire->ire_zoneid, ipst);
17716 			return;
17717 		}
17718 
17719 		ns = ipst->ips_netstack;
17720 		/* select inbound SA and have IPsec process the pkt */
17721 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17722 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17723 			if (esph == NULL)
17724 				return;
17725 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17726 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17727 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17728 			    first_mp, esph);
17729 		} else {
17730 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17731 			if (ah == NULL)
17732 				return;
17733 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17734 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17735 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17736 			    first_mp, ah);
17737 		}
17738 
17739 		switch (ipsec_rc) {
17740 		case IPSEC_STATUS_SUCCESS:
17741 			break;
17742 		case IPSEC_STATUS_FAILED:
17743 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17744 			/* FALLTHRU */
17745 		case IPSEC_STATUS_PENDING:
17746 			return;
17747 		}
17748 		/* we're done with IPsec processing, send it up */
17749 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17750 		return;
17751 	}
17752 	default:
17753 		break;
17754 	}
17755 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17756 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17757 		    ire->ire_zoneid));
17758 		goto drop_pkt;
17759 	}
17760 	/*
17761 	 * Handle protocols with which IP is less intimate.  There
17762 	 * can be more than one stream bound to a particular
17763 	 * protocol.  When this is the case, each one gets a copy
17764 	 * of any incoming packets.
17765 	 */
17766 	ip_fanout_proto(q, first_mp, ill, ipha,
17767 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17768 	    B_TRUE, recv_ill, ire->ire_zoneid);
17769 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17770 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17771 	return;
17772 
17773 drop_pkt:
17774 	freemsg(first_mp);
17775 	if (hada_mp != NULL)
17776 		freeb(hada_mp);
17777 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17778 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17779 #undef	rptr
17780 #undef  iphs
17781 
17782 }
17783 
17784 /*
17785  * Update any source route, record route or timestamp options.
17786  * Check that we are at end of strict source route.
17787  * The options have already been checked for sanity in ip_rput_options().
17788  */
17789 static boolean_t
17790 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17791     ip_stack_t *ipst)
17792 {
17793 	ipoptp_t	opts;
17794 	uchar_t		*opt;
17795 	uint8_t		optval;
17796 	uint8_t		optlen;
17797 	ipaddr_t	dst;
17798 	uint32_t	ts;
17799 	ire_t		*dst_ire;
17800 	timestruc_t	now;
17801 	zoneid_t	zoneid;
17802 	ill_t		*ill;
17803 
17804 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17805 
17806 	ip2dbg(("ip_rput_local_options\n"));
17807 
17808 	for (optval = ipoptp_first(&opts, ipha);
17809 	    optval != IPOPT_EOL;
17810 	    optval = ipoptp_next(&opts)) {
17811 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17812 		opt = opts.ipoptp_cur;
17813 		optlen = opts.ipoptp_len;
17814 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17815 		    optval, optlen));
17816 		switch (optval) {
17817 			uint32_t off;
17818 		case IPOPT_SSRR:
17819 		case IPOPT_LSRR:
17820 			off = opt[IPOPT_OFFSET];
17821 			off--;
17822 			if (optlen < IP_ADDR_LEN ||
17823 			    off > optlen - IP_ADDR_LEN) {
17824 				/* End of source route */
17825 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17826 				break;
17827 			}
17828 			/*
17829 			 * This will only happen if two consecutive entries
17830 			 * in the source route contains our address or if
17831 			 * it is a packet with a loose source route which
17832 			 * reaches us before consuming the whole source route
17833 			 */
17834 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17835 			if (optval == IPOPT_SSRR) {
17836 				goto bad_src_route;
17837 			}
17838 			/*
17839 			 * Hack: instead of dropping the packet truncate the
17840 			 * source route to what has been used by filling the
17841 			 * rest with IPOPT_NOP.
17842 			 */
17843 			opt[IPOPT_OLEN] = (uint8_t)off;
17844 			while (off < optlen) {
17845 				opt[off++] = IPOPT_NOP;
17846 			}
17847 			break;
17848 		case IPOPT_RR:
17849 			off = opt[IPOPT_OFFSET];
17850 			off--;
17851 			if (optlen < IP_ADDR_LEN ||
17852 			    off > optlen - IP_ADDR_LEN) {
17853 				/* No more room - ignore */
17854 				ip1dbg((
17855 				    "ip_rput_local_options: end of RR\n"));
17856 				break;
17857 			}
17858 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17859 			    IP_ADDR_LEN);
17860 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17861 			break;
17862 		case IPOPT_TS:
17863 			/* Insert timestamp if there is romm */
17864 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17865 			case IPOPT_TS_TSONLY:
17866 				off = IPOPT_TS_TIMELEN;
17867 				break;
17868 			case IPOPT_TS_PRESPEC:
17869 			case IPOPT_TS_PRESPEC_RFC791:
17870 				/* Verify that the address matched */
17871 				off = opt[IPOPT_OFFSET] - 1;
17872 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17873 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17874 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17875 				    ipst);
17876 				if (dst_ire == NULL) {
17877 					/* Not for us */
17878 					break;
17879 				}
17880 				ire_refrele(dst_ire);
17881 				/* FALLTHRU */
17882 			case IPOPT_TS_TSANDADDR:
17883 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17884 				break;
17885 			default:
17886 				/*
17887 				 * ip_*put_options should have already
17888 				 * dropped this packet.
17889 				 */
17890 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17891 				    "unknown IT - bug in ip_rput_options?\n");
17892 				return (B_TRUE);	/* Keep "lint" happy */
17893 			}
17894 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17895 				/* Increase overflow counter */
17896 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17897 				opt[IPOPT_POS_OV_FLG] =
17898 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17899 				    (off << 4));
17900 				break;
17901 			}
17902 			off = opt[IPOPT_OFFSET] - 1;
17903 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17904 			case IPOPT_TS_PRESPEC:
17905 			case IPOPT_TS_PRESPEC_RFC791:
17906 			case IPOPT_TS_TSANDADDR:
17907 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17908 				    IP_ADDR_LEN);
17909 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17910 				/* FALLTHRU */
17911 			case IPOPT_TS_TSONLY:
17912 				off = opt[IPOPT_OFFSET] - 1;
17913 				/* Compute # of milliseconds since midnight */
17914 				gethrestime(&now);
17915 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17916 				    now.tv_nsec / (NANOSEC / MILLISEC);
17917 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17918 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17919 				break;
17920 			}
17921 			break;
17922 		}
17923 	}
17924 	return (B_TRUE);
17925 
17926 bad_src_route:
17927 	q = WR(q);
17928 	if (q->q_next != NULL)
17929 		ill = q->q_ptr;
17930 	else
17931 		ill = NULL;
17932 
17933 	/* make sure we clear any indication of a hardware checksum */
17934 	DB_CKSUMFLAGS(mp) = 0;
17935 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17936 	if (zoneid == ALL_ZONES)
17937 		freemsg(mp);
17938 	else
17939 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17940 	return (B_FALSE);
17941 
17942 }
17943 
17944 /*
17945  * Process IP options in an inbound packet.  If an option affects the
17946  * effective destination address, return the next hop address via dstp.
17947  * Returns -1 if something fails in which case an ICMP error has been sent
17948  * and mp freed.
17949  */
17950 static int
17951 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17952     ip_stack_t *ipst)
17953 {
17954 	ipoptp_t	opts;
17955 	uchar_t		*opt;
17956 	uint8_t		optval;
17957 	uint8_t		optlen;
17958 	ipaddr_t	dst;
17959 	intptr_t	code = 0;
17960 	ire_t		*ire = NULL;
17961 	zoneid_t	zoneid;
17962 	ill_t		*ill;
17963 
17964 	ip2dbg(("ip_rput_options\n"));
17965 	dst = ipha->ipha_dst;
17966 	for (optval = ipoptp_first(&opts, ipha);
17967 	    optval != IPOPT_EOL;
17968 	    optval = ipoptp_next(&opts)) {
17969 		opt = opts.ipoptp_cur;
17970 		optlen = opts.ipoptp_len;
17971 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17972 		    optval, optlen));
17973 		/*
17974 		 * Note: we need to verify the checksum before we
17975 		 * modify anything thus this routine only extracts the next
17976 		 * hop dst from any source route.
17977 		 */
17978 		switch (optval) {
17979 			uint32_t off;
17980 		case IPOPT_SSRR:
17981 		case IPOPT_LSRR:
17982 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17983 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17984 			if (ire == NULL) {
17985 				if (optval == IPOPT_SSRR) {
17986 					ip1dbg(("ip_rput_options: not next"
17987 					    " strict source route 0x%x\n",
17988 					    ntohl(dst)));
17989 					code = (char *)&ipha->ipha_dst -
17990 					    (char *)ipha;
17991 					goto param_prob; /* RouterReq's */
17992 				}
17993 				ip2dbg(("ip_rput_options: "
17994 				    "not next source route 0x%x\n",
17995 				    ntohl(dst)));
17996 				break;
17997 			}
17998 			ire_refrele(ire);
17999 
18000 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18001 				ip1dbg((
18002 				    "ip_rput_options: bad option offset\n"));
18003 				code = (char *)&opt[IPOPT_OLEN] -
18004 				    (char *)ipha;
18005 				goto param_prob;
18006 			}
18007 			off = opt[IPOPT_OFFSET];
18008 			off--;
18009 		redo_srr:
18010 			if (optlen < IP_ADDR_LEN ||
18011 			    off > optlen - IP_ADDR_LEN) {
18012 				/* End of source route */
18013 				ip1dbg(("ip_rput_options: end of SR\n"));
18014 				break;
18015 			}
18016 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18017 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18018 			    ntohl(dst)));
18019 
18020 			/*
18021 			 * Check if our address is present more than
18022 			 * once as consecutive hops in source route.
18023 			 * XXX verify per-interface ip_forwarding
18024 			 * for source route?
18025 			 */
18026 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18027 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18028 
18029 			if (ire != NULL) {
18030 				ire_refrele(ire);
18031 				off += IP_ADDR_LEN;
18032 				goto redo_srr;
18033 			}
18034 
18035 			if (dst == htonl(INADDR_LOOPBACK)) {
18036 				ip1dbg(("ip_rput_options: loopback addr in "
18037 				    "source route!\n"));
18038 				goto bad_src_route;
18039 			}
18040 			/*
18041 			 * For strict: verify that dst is directly
18042 			 * reachable.
18043 			 */
18044 			if (optval == IPOPT_SSRR) {
18045 				ire = ire_ftable_lookup(dst, 0, 0,
18046 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18047 				    MBLK_GETLABEL(mp),
18048 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18049 				if (ire == NULL) {
18050 					ip1dbg(("ip_rput_options: SSRR not "
18051 					    "directly reachable: 0x%x\n",
18052 					    ntohl(dst)));
18053 					goto bad_src_route;
18054 				}
18055 				ire_refrele(ire);
18056 			}
18057 			/*
18058 			 * Defer update of the offset and the record route
18059 			 * until the packet is forwarded.
18060 			 */
18061 			break;
18062 		case IPOPT_RR:
18063 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18064 				ip1dbg((
18065 				    "ip_rput_options: bad option offset\n"));
18066 				code = (char *)&opt[IPOPT_OLEN] -
18067 				    (char *)ipha;
18068 				goto param_prob;
18069 			}
18070 			break;
18071 		case IPOPT_TS:
18072 			/*
18073 			 * Verify that length >= 5 and that there is either
18074 			 * room for another timestamp or that the overflow
18075 			 * counter is not maxed out.
18076 			 */
18077 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18078 			if (optlen < IPOPT_MINLEN_IT) {
18079 				goto param_prob;
18080 			}
18081 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18082 				ip1dbg((
18083 				    "ip_rput_options: bad option offset\n"));
18084 				code = (char *)&opt[IPOPT_OFFSET] -
18085 				    (char *)ipha;
18086 				goto param_prob;
18087 			}
18088 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18089 			case IPOPT_TS_TSONLY:
18090 				off = IPOPT_TS_TIMELEN;
18091 				break;
18092 			case IPOPT_TS_TSANDADDR:
18093 			case IPOPT_TS_PRESPEC:
18094 			case IPOPT_TS_PRESPEC_RFC791:
18095 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18096 				break;
18097 			default:
18098 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18099 				    (char *)ipha;
18100 				goto param_prob;
18101 			}
18102 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18103 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18104 				/*
18105 				 * No room and the overflow counter is 15
18106 				 * already.
18107 				 */
18108 				goto param_prob;
18109 			}
18110 			break;
18111 		}
18112 	}
18113 
18114 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18115 		*dstp = dst;
18116 		return (0);
18117 	}
18118 
18119 	ip1dbg(("ip_rput_options: error processing IP options."));
18120 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18121 
18122 param_prob:
18123 	q = WR(q);
18124 	if (q->q_next != NULL)
18125 		ill = q->q_ptr;
18126 	else
18127 		ill = NULL;
18128 
18129 	/* make sure we clear any indication of a hardware checksum */
18130 	DB_CKSUMFLAGS(mp) = 0;
18131 	/* Don't know whether this is for non-global or global/forwarding */
18132 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18133 	if (zoneid == ALL_ZONES)
18134 		freemsg(mp);
18135 	else
18136 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18137 	return (-1);
18138 
18139 bad_src_route:
18140 	q = WR(q);
18141 	if (q->q_next != NULL)
18142 		ill = q->q_ptr;
18143 	else
18144 		ill = NULL;
18145 
18146 	/* make sure we clear any indication of a hardware checksum */
18147 	DB_CKSUMFLAGS(mp) = 0;
18148 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18149 	if (zoneid == ALL_ZONES)
18150 		freemsg(mp);
18151 	else
18152 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18153 	return (-1);
18154 }
18155 
18156 /*
18157  * IP & ICMP info in >=14 msg's ...
18158  *  - ip fixed part (mib2_ip_t)
18159  *  - icmp fixed part (mib2_icmp_t)
18160  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18161  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18162  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18163  *  - ipRouteAttributeTable (ip 102)	labeled routes
18164  *  - ip multicast membership (ip_member_t)
18165  *  - ip multicast source filtering (ip_grpsrc_t)
18166  *  - igmp fixed part (struct igmpstat)
18167  *  - multicast routing stats (struct mrtstat)
18168  *  - multicast routing vifs (array of struct vifctl)
18169  *  - multicast routing routes (array of struct mfcctl)
18170  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18171  *					One per ill plus one generic
18172  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18173  *					One per ill plus one generic
18174  *  - ipv6RouteEntry			all IPv6 IREs
18175  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18176  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18177  *  - ipv6AddrEntry			all IPv6 ipifs
18178  *  - ipv6 multicast membership (ipv6_member_t)
18179  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18180  *
18181  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18182  *
18183  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18184  * already filled in by the caller.
18185  * Return value of 0 indicates that no messages were sent and caller
18186  * should free mpctl.
18187  */
18188 int
18189 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18190 {
18191 	ip_stack_t *ipst;
18192 	sctp_stack_t *sctps;
18193 
18194 
18195 	if (q->q_next != NULL) {
18196 		ipst = ILLQ_TO_IPST(q);
18197 	} else {
18198 		ipst = CONNQ_TO_IPST(q);
18199 	}
18200 	ASSERT(ipst != NULL);
18201 	sctps = ipst->ips_netstack->netstack_sctp;
18202 
18203 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18204 		return (0);
18205 	}
18206 
18207 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18208 	    ipst)) == NULL) {
18209 		return (1);
18210 	}
18211 
18212 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18213 		return (1);
18214 	}
18215 
18216 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18217 		return (1);
18218 	}
18219 
18220 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18221 		return (1);
18222 	}
18223 
18224 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18225 		return (1);
18226 	}
18227 
18228 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18229 		return (1);
18230 	}
18231 
18232 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18233 		return (1);
18234 	}
18235 
18236 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18237 		return (1);
18238 	}
18239 
18240 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18241 		return (1);
18242 	}
18243 
18244 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18245 		return (1);
18246 	}
18247 
18248 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18249 		return (1);
18250 	}
18251 
18252 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18253 		return (1);
18254 	}
18255 
18256 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18257 		return (1);
18258 	}
18259 
18260 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18261 		return (1);
18262 	}
18263 
18264 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18265 		return (1);
18266 	}
18267 
18268 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18269 	if (mpctl == NULL) {
18270 		return (1);
18271 	}
18272 
18273 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18274 		return (1);
18275 	}
18276 	freemsg(mpctl);
18277 	return (1);
18278 }
18279 
18280 
18281 /* Get global (legacy) IPv4 statistics */
18282 static mblk_t *
18283 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18284     ip_stack_t *ipst)
18285 {
18286 	mib2_ip_t		old_ip_mib;
18287 	struct opthdr		*optp;
18288 	mblk_t			*mp2ctl;
18289 
18290 	/*
18291 	 * make a copy of the original message
18292 	 */
18293 	mp2ctl = copymsg(mpctl);
18294 
18295 	/* fixed length IP structure... */
18296 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18297 	optp->level = MIB2_IP;
18298 	optp->name = 0;
18299 	SET_MIB(old_ip_mib.ipForwarding,
18300 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18301 	SET_MIB(old_ip_mib.ipDefaultTTL,
18302 	    (uint32_t)ipst->ips_ip_def_ttl);
18303 	SET_MIB(old_ip_mib.ipReasmTimeout,
18304 	    ipst->ips_ip_g_frag_timeout);
18305 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18306 	    sizeof (mib2_ipAddrEntry_t));
18307 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18308 	    sizeof (mib2_ipRouteEntry_t));
18309 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18310 	    sizeof (mib2_ipNetToMediaEntry_t));
18311 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18312 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18313 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18314 	    sizeof (mib2_ipAttributeEntry_t));
18315 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18316 
18317 	/*
18318 	 * Grab the statistics from the new IP MIB
18319 	 */
18320 	SET_MIB(old_ip_mib.ipInReceives,
18321 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18322 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18323 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18324 	SET_MIB(old_ip_mib.ipForwDatagrams,
18325 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18326 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18327 	    ipmib->ipIfStatsInUnknownProtos);
18328 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18329 	SET_MIB(old_ip_mib.ipInDelivers,
18330 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18331 	SET_MIB(old_ip_mib.ipOutRequests,
18332 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18333 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18334 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18335 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18336 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18337 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18338 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18339 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18340 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18341 
18342 	/* ipRoutingDiscards is not being used */
18343 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18344 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18345 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18346 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18347 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18348 	    ipmib->ipIfStatsReasmDuplicates);
18349 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18350 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18351 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18352 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18353 	SET_MIB(old_ip_mib.rawipInOverflows,
18354 	    ipmib->rawipIfStatsInOverflows);
18355 
18356 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18357 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18358 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18359 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18360 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18361 	    ipmib->ipIfStatsOutSwitchIPVersion);
18362 
18363 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18364 	    (int)sizeof (old_ip_mib))) {
18365 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18366 		    (uint_t)sizeof (old_ip_mib)));
18367 	}
18368 
18369 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18370 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18371 	    (int)optp->level, (int)optp->name, (int)optp->len));
18372 	qreply(q, mpctl);
18373 	return (mp2ctl);
18374 }
18375 
18376 /* Per interface IPv4 statistics */
18377 static mblk_t *
18378 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18379 {
18380 	struct opthdr		*optp;
18381 	mblk_t			*mp2ctl;
18382 	ill_t			*ill;
18383 	ill_walk_context_t	ctx;
18384 	mblk_t			*mp_tail = NULL;
18385 	mib2_ipIfStatsEntry_t	global_ip_mib;
18386 
18387 	/*
18388 	 * Make a copy of the original message
18389 	 */
18390 	mp2ctl = copymsg(mpctl);
18391 
18392 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18393 	optp->level = MIB2_IP;
18394 	optp->name = MIB2_IP_TRAFFIC_STATS;
18395 	/* Include "unknown interface" ip_mib */
18396 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18397 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18398 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18399 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18400 	    (ipst->ips_ip_g_forward ? 1 : 2));
18401 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18402 	    (uint32_t)ipst->ips_ip_def_ttl);
18403 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18404 	    sizeof (mib2_ipIfStatsEntry_t));
18405 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18406 	    sizeof (mib2_ipAddrEntry_t));
18407 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18408 	    sizeof (mib2_ipRouteEntry_t));
18409 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18410 	    sizeof (mib2_ipNetToMediaEntry_t));
18411 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18412 	    sizeof (ip_member_t));
18413 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18414 	    sizeof (ip_grpsrc_t));
18415 
18416 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18417 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18418 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18419 		    "failed to allocate %u bytes\n",
18420 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18421 	}
18422 
18423 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18424 
18425 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18426 	ill = ILL_START_WALK_V4(&ctx, ipst);
18427 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18428 		ill->ill_ip_mib->ipIfStatsIfIndex =
18429 		    ill->ill_phyint->phyint_ifindex;
18430 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18431 		    (ipst->ips_ip_g_forward ? 1 : 2));
18432 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18433 		    (uint32_t)ipst->ips_ip_def_ttl);
18434 
18435 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18436 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18437 		    (char *)ill->ill_ip_mib,
18438 		    (int)sizeof (*ill->ill_ip_mib))) {
18439 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18440 			    "failed to allocate %u bytes\n",
18441 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18442 		}
18443 	}
18444 	rw_exit(&ipst->ips_ill_g_lock);
18445 
18446 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18447 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18448 	    "level %d, name %d, len %d\n",
18449 	    (int)optp->level, (int)optp->name, (int)optp->len));
18450 	qreply(q, mpctl);
18451 
18452 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18453 }
18454 
18455 /* Global IPv4 ICMP statistics */
18456 static mblk_t *
18457 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18458 {
18459 	struct opthdr		*optp;
18460 	mblk_t			*mp2ctl;
18461 
18462 	/*
18463 	 * Make a copy of the original message
18464 	 */
18465 	mp2ctl = copymsg(mpctl);
18466 
18467 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18468 	optp->level = MIB2_ICMP;
18469 	optp->name = 0;
18470 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18471 	    (int)sizeof (ipst->ips_icmp_mib))) {
18472 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18473 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18474 	}
18475 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18476 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18477 	    (int)optp->level, (int)optp->name, (int)optp->len));
18478 	qreply(q, mpctl);
18479 	return (mp2ctl);
18480 }
18481 
18482 /* Global IPv4 IGMP statistics */
18483 static mblk_t *
18484 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18485 {
18486 	struct opthdr		*optp;
18487 	mblk_t			*mp2ctl;
18488 
18489 	/*
18490 	 * make a copy of the original message
18491 	 */
18492 	mp2ctl = copymsg(mpctl);
18493 
18494 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18495 	optp->level = EXPER_IGMP;
18496 	optp->name = 0;
18497 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18498 	    (int)sizeof (ipst->ips_igmpstat))) {
18499 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18500 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18501 	}
18502 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18503 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18504 	    (int)optp->level, (int)optp->name, (int)optp->len));
18505 	qreply(q, mpctl);
18506 	return (mp2ctl);
18507 }
18508 
18509 /* Global IPv4 Multicast Routing statistics */
18510 static mblk_t *
18511 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18512 {
18513 	struct opthdr		*optp;
18514 	mblk_t			*mp2ctl;
18515 
18516 	/*
18517 	 * make a copy of the original message
18518 	 */
18519 	mp2ctl = copymsg(mpctl);
18520 
18521 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18522 	optp->level = EXPER_DVMRP;
18523 	optp->name = 0;
18524 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18525 		ip0dbg(("ip_mroute_stats: failed\n"));
18526 	}
18527 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18528 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18529 	    (int)optp->level, (int)optp->name, (int)optp->len));
18530 	qreply(q, mpctl);
18531 	return (mp2ctl);
18532 }
18533 
18534 /* IPv4 address information */
18535 static mblk_t *
18536 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18537 {
18538 	struct opthdr		*optp;
18539 	mblk_t			*mp2ctl;
18540 	mblk_t			*mp_tail = NULL;
18541 	ill_t			*ill;
18542 	ipif_t			*ipif;
18543 	uint_t			bitval;
18544 	mib2_ipAddrEntry_t	mae;
18545 	zoneid_t		zoneid;
18546 	ill_walk_context_t ctx;
18547 
18548 	/*
18549 	 * make a copy of the original message
18550 	 */
18551 	mp2ctl = copymsg(mpctl);
18552 
18553 	/* ipAddrEntryTable */
18554 
18555 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18556 	optp->level = MIB2_IP;
18557 	optp->name = MIB2_IP_ADDR;
18558 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18559 
18560 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18561 	ill = ILL_START_WALK_V4(&ctx, ipst);
18562 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18563 		for (ipif = ill->ill_ipif; ipif != NULL;
18564 		    ipif = ipif->ipif_next) {
18565 			if (ipif->ipif_zoneid != zoneid &&
18566 			    ipif->ipif_zoneid != ALL_ZONES)
18567 				continue;
18568 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18569 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18570 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18571 
18572 			(void) ipif_get_name(ipif,
18573 			    mae.ipAdEntIfIndex.o_bytes,
18574 			    OCTET_LENGTH);
18575 			mae.ipAdEntIfIndex.o_length =
18576 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18577 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18578 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18579 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18580 			mae.ipAdEntInfo.ae_subnet_len =
18581 			    ip_mask_to_plen(ipif->ipif_net_mask);
18582 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18583 			for (bitval = 1;
18584 			    bitval &&
18585 			    !(bitval & ipif->ipif_brd_addr);
18586 			    bitval <<= 1)
18587 				noop;
18588 			mae.ipAdEntBcastAddr = bitval;
18589 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18590 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18591 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18592 			mae.ipAdEntInfo.ae_broadcast_addr =
18593 			    ipif->ipif_brd_addr;
18594 			mae.ipAdEntInfo.ae_pp_dst_addr =
18595 			    ipif->ipif_pp_dst_addr;
18596 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18597 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18598 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18599 
18600 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18601 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18602 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18603 				    "allocate %u bytes\n",
18604 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18605 			}
18606 		}
18607 	}
18608 	rw_exit(&ipst->ips_ill_g_lock);
18609 
18610 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18611 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18612 	    (int)optp->level, (int)optp->name, (int)optp->len));
18613 	qreply(q, mpctl);
18614 	return (mp2ctl);
18615 }
18616 
18617 /* IPv6 address information */
18618 static mblk_t *
18619 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18620 {
18621 	struct opthdr		*optp;
18622 	mblk_t			*mp2ctl;
18623 	mblk_t			*mp_tail = NULL;
18624 	ill_t			*ill;
18625 	ipif_t			*ipif;
18626 	mib2_ipv6AddrEntry_t	mae6;
18627 	zoneid_t		zoneid;
18628 	ill_walk_context_t	ctx;
18629 
18630 	/*
18631 	 * make a copy of the original message
18632 	 */
18633 	mp2ctl = copymsg(mpctl);
18634 
18635 	/* ipv6AddrEntryTable */
18636 
18637 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18638 	optp->level = MIB2_IP6;
18639 	optp->name = MIB2_IP6_ADDR;
18640 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18641 
18642 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18643 	ill = ILL_START_WALK_V6(&ctx, ipst);
18644 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18645 		for (ipif = ill->ill_ipif; ipif != NULL;
18646 		    ipif = ipif->ipif_next) {
18647 			if (ipif->ipif_zoneid != zoneid &&
18648 			    ipif->ipif_zoneid != ALL_ZONES)
18649 				continue;
18650 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18651 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18652 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18653 
18654 			(void) ipif_get_name(ipif,
18655 			    mae6.ipv6AddrIfIndex.o_bytes,
18656 			    OCTET_LENGTH);
18657 			mae6.ipv6AddrIfIndex.o_length =
18658 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18659 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18660 			mae6.ipv6AddrPfxLength =
18661 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18662 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18663 			mae6.ipv6AddrInfo.ae_subnet_len =
18664 			    mae6.ipv6AddrPfxLength;
18665 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18666 
18667 			/* Type: stateless(1), stateful(2), unknown(3) */
18668 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18669 				mae6.ipv6AddrType = 1;
18670 			else
18671 				mae6.ipv6AddrType = 2;
18672 			/* Anycast: true(1), false(2) */
18673 			if (ipif->ipif_flags & IPIF_ANYCAST)
18674 				mae6.ipv6AddrAnycastFlag = 1;
18675 			else
18676 				mae6.ipv6AddrAnycastFlag = 2;
18677 
18678 			/*
18679 			 * Address status: preferred(1), deprecated(2),
18680 			 * invalid(3), inaccessible(4), unknown(5)
18681 			 */
18682 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18683 				mae6.ipv6AddrStatus = 3;
18684 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18685 				mae6.ipv6AddrStatus = 2;
18686 			else
18687 				mae6.ipv6AddrStatus = 1;
18688 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18689 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18690 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18691 						ipif->ipif_v6pp_dst_addr;
18692 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18693 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18694 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18695 			mae6.ipv6AddrIdentifier = ill->ill_token;
18696 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18697 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18698 			mae6.ipv6AddrRetransmitTime =
18699 			    ill->ill_reachable_retrans_time;
18700 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18701 				(char *)&mae6,
18702 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18703 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18704 				    "allocate %u bytes\n",
18705 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18706 			}
18707 		}
18708 	}
18709 	rw_exit(&ipst->ips_ill_g_lock);
18710 
18711 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18712 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18713 	    (int)optp->level, (int)optp->name, (int)optp->len));
18714 	qreply(q, mpctl);
18715 	return (mp2ctl);
18716 }
18717 
18718 /* IPv4 multicast group membership. */
18719 static mblk_t *
18720 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18721 {
18722 	struct opthdr		*optp;
18723 	mblk_t			*mp2ctl;
18724 	ill_t			*ill;
18725 	ipif_t			*ipif;
18726 	ilm_t			*ilm;
18727 	ip_member_t		ipm;
18728 	mblk_t			*mp_tail = NULL;
18729 	ill_walk_context_t	ctx;
18730 	zoneid_t		zoneid;
18731 
18732 	/*
18733 	 * make a copy of the original message
18734 	 */
18735 	mp2ctl = copymsg(mpctl);
18736 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18737 
18738 	/* ipGroupMember table */
18739 	optp = (struct opthdr *)&mpctl->b_rptr[
18740 	    sizeof (struct T_optmgmt_ack)];
18741 	optp->level = MIB2_IP;
18742 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18743 
18744 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18745 	ill = ILL_START_WALK_V4(&ctx, ipst);
18746 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18747 		ILM_WALKER_HOLD(ill);
18748 		for (ipif = ill->ill_ipif; ipif != NULL;
18749 		    ipif = ipif->ipif_next) {
18750 			if (ipif->ipif_zoneid != zoneid &&
18751 			    ipif->ipif_zoneid != ALL_ZONES)
18752 				continue;	/* not this zone */
18753 			(void) ipif_get_name(ipif,
18754 			    ipm.ipGroupMemberIfIndex.o_bytes,
18755 			    OCTET_LENGTH);
18756 			ipm.ipGroupMemberIfIndex.o_length =
18757 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18758 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18759 				ASSERT(ilm->ilm_ipif != NULL);
18760 				ASSERT(ilm->ilm_ill == NULL);
18761 				if (ilm->ilm_ipif != ipif)
18762 					continue;
18763 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18764 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18765 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18766 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18767 				    (char *)&ipm, (int)sizeof (ipm))) {
18768 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18769 					    "failed to allocate %u bytes\n",
18770 						(uint_t)sizeof (ipm)));
18771 				}
18772 			}
18773 		}
18774 		ILM_WALKER_RELE(ill);
18775 	}
18776 	rw_exit(&ipst->ips_ill_g_lock);
18777 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18778 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18779 	    (int)optp->level, (int)optp->name, (int)optp->len));
18780 	qreply(q, mpctl);
18781 	return (mp2ctl);
18782 }
18783 
18784 /* IPv6 multicast group membership. */
18785 static mblk_t *
18786 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18787 {
18788 	struct opthdr		*optp;
18789 	mblk_t			*mp2ctl;
18790 	ill_t			*ill;
18791 	ilm_t			*ilm;
18792 	ipv6_member_t		ipm6;
18793 	mblk_t			*mp_tail = NULL;
18794 	ill_walk_context_t	ctx;
18795 	zoneid_t		zoneid;
18796 
18797 	/*
18798 	 * make a copy of the original message
18799 	 */
18800 	mp2ctl = copymsg(mpctl);
18801 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18802 
18803 	/* ip6GroupMember table */
18804 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18805 	optp->level = MIB2_IP6;
18806 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18807 
18808 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18809 	ill = ILL_START_WALK_V6(&ctx, ipst);
18810 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18811 		ILM_WALKER_HOLD(ill);
18812 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18813 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18814 			ASSERT(ilm->ilm_ipif == NULL);
18815 			ASSERT(ilm->ilm_ill != NULL);
18816 			if (ilm->ilm_zoneid != zoneid)
18817 				continue;	/* not this zone */
18818 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18819 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18820 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18821 			if (!snmp_append_data2(mpctl->b_cont,
18822 			    &mp_tail,
18823 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18824 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18825 				    "failed to allocate %u bytes\n",
18826 				    (uint_t)sizeof (ipm6)));
18827 			}
18828 		}
18829 		ILM_WALKER_RELE(ill);
18830 	}
18831 	rw_exit(&ipst->ips_ill_g_lock);
18832 
18833 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18834 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18835 	    (int)optp->level, (int)optp->name, (int)optp->len));
18836 	qreply(q, mpctl);
18837 	return (mp2ctl);
18838 }
18839 
18840 /* IP multicast filtered sources */
18841 static mblk_t *
18842 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18843 {
18844 	struct opthdr		*optp;
18845 	mblk_t			*mp2ctl;
18846 	ill_t			*ill;
18847 	ipif_t			*ipif;
18848 	ilm_t			*ilm;
18849 	ip_grpsrc_t		ips;
18850 	mblk_t			*mp_tail = NULL;
18851 	ill_walk_context_t	ctx;
18852 	zoneid_t		zoneid;
18853 	int			i;
18854 	slist_t			*sl;
18855 
18856 	/*
18857 	 * make a copy of the original message
18858 	 */
18859 	mp2ctl = copymsg(mpctl);
18860 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18861 
18862 	/* ipGroupSource table */
18863 	optp = (struct opthdr *)&mpctl->b_rptr[
18864 	    sizeof (struct T_optmgmt_ack)];
18865 	optp->level = MIB2_IP;
18866 	optp->name = EXPER_IP_GROUP_SOURCES;
18867 
18868 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18869 	ill = ILL_START_WALK_V4(&ctx, ipst);
18870 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18871 		ILM_WALKER_HOLD(ill);
18872 		for (ipif = ill->ill_ipif; ipif != NULL;
18873 		    ipif = ipif->ipif_next) {
18874 			if (ipif->ipif_zoneid != zoneid)
18875 				continue;	/* not this zone */
18876 			(void) ipif_get_name(ipif,
18877 			    ips.ipGroupSourceIfIndex.o_bytes,
18878 			    OCTET_LENGTH);
18879 			ips.ipGroupSourceIfIndex.o_length =
18880 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18881 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18882 				ASSERT(ilm->ilm_ipif != NULL);
18883 				ASSERT(ilm->ilm_ill == NULL);
18884 				sl = ilm->ilm_filter;
18885 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18886 					continue;
18887 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18888 				for (i = 0; i < sl->sl_numsrc; i++) {
18889 					if (!IN6_IS_ADDR_V4MAPPED(
18890 					    &sl->sl_addr[i]))
18891 						continue;
18892 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18893 					    ips.ipGroupSourceAddress);
18894 					if (snmp_append_data2(mpctl->b_cont,
18895 					    &mp_tail, (char *)&ips,
18896 					    (int)sizeof (ips)) == 0) {
18897 						ip1dbg(("ip_snmp_get_mib2_"
18898 						    "ip_group_src: failed to "
18899 						    "allocate %u bytes\n",
18900 						    (uint_t)sizeof (ips)));
18901 					}
18902 				}
18903 			}
18904 		}
18905 		ILM_WALKER_RELE(ill);
18906 	}
18907 	rw_exit(&ipst->ips_ill_g_lock);
18908 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18909 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18910 	    (int)optp->level, (int)optp->name, (int)optp->len));
18911 	qreply(q, mpctl);
18912 	return (mp2ctl);
18913 }
18914 
18915 /* IPv6 multicast filtered sources. */
18916 static mblk_t *
18917 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18918 {
18919 	struct opthdr		*optp;
18920 	mblk_t			*mp2ctl;
18921 	ill_t			*ill;
18922 	ilm_t			*ilm;
18923 	ipv6_grpsrc_t		ips6;
18924 	mblk_t			*mp_tail = NULL;
18925 	ill_walk_context_t	ctx;
18926 	zoneid_t		zoneid;
18927 	int			i;
18928 	slist_t			*sl;
18929 
18930 	/*
18931 	 * make a copy of the original message
18932 	 */
18933 	mp2ctl = copymsg(mpctl);
18934 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18935 
18936 	/* ip6GroupMember table */
18937 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18938 	optp->level = MIB2_IP6;
18939 	optp->name = EXPER_IP6_GROUP_SOURCES;
18940 
18941 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18942 	ill = ILL_START_WALK_V6(&ctx, ipst);
18943 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18944 		ILM_WALKER_HOLD(ill);
18945 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18946 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18947 			ASSERT(ilm->ilm_ipif == NULL);
18948 			ASSERT(ilm->ilm_ill != NULL);
18949 			sl = ilm->ilm_filter;
18950 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18951 				continue;
18952 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18953 			for (i = 0; i < sl->sl_numsrc; i++) {
18954 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18955 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18956 				    (char *)&ips6, (int)sizeof (ips6))) {
18957 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18958 					    "group_src: failed to allocate "
18959 					    "%u bytes\n",
18960 					    (uint_t)sizeof (ips6)));
18961 				}
18962 			}
18963 		}
18964 		ILM_WALKER_RELE(ill);
18965 	}
18966 	rw_exit(&ipst->ips_ill_g_lock);
18967 
18968 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18969 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18970 	    (int)optp->level, (int)optp->name, (int)optp->len));
18971 	qreply(q, mpctl);
18972 	return (mp2ctl);
18973 }
18974 
18975 /* Multicast routing virtual interface table. */
18976 static mblk_t *
18977 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18978 {
18979 	struct opthdr		*optp;
18980 	mblk_t			*mp2ctl;
18981 
18982 	/*
18983 	 * make a copy of the original message
18984 	 */
18985 	mp2ctl = copymsg(mpctl);
18986 
18987 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18988 	optp->level = EXPER_DVMRP;
18989 	optp->name = EXPER_DVMRP_VIF;
18990 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18991 		ip0dbg(("ip_mroute_vif: failed\n"));
18992 	}
18993 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18994 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18995 	    (int)optp->level, (int)optp->name, (int)optp->len));
18996 	qreply(q, mpctl);
18997 	return (mp2ctl);
18998 }
18999 
19000 /* Multicast routing table. */
19001 static mblk_t *
19002 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19003 {
19004 	struct opthdr		*optp;
19005 	mblk_t			*mp2ctl;
19006 
19007 	/*
19008 	 * make a copy of the original message
19009 	 */
19010 	mp2ctl = copymsg(mpctl);
19011 
19012 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19013 	optp->level = EXPER_DVMRP;
19014 	optp->name = EXPER_DVMRP_MRT;
19015 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19016 		ip0dbg(("ip_mroute_mrt: failed\n"));
19017 	}
19018 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19019 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19020 	    (int)optp->level, (int)optp->name, (int)optp->len));
19021 	qreply(q, mpctl);
19022 	return (mp2ctl);
19023 }
19024 
19025 /*
19026  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19027  * in one IRE walk.
19028  */
19029 static mblk_t *
19030 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19031 {
19032 	struct opthdr	*optp;
19033 	mblk_t		*mp2ctl;	/* Returned */
19034 	mblk_t		*mp3ctl;	/* nettomedia */
19035 	mblk_t		*mp4ctl;	/* routeattrs */
19036 	iproutedata_t	ird;
19037 	zoneid_t	zoneid;
19038 
19039 	/*
19040 	 * make copies of the original message
19041 	 *	- mp2ctl is returned unchanged to the caller for his use
19042 	 *	- mpctl is sent upstream as ipRouteEntryTable
19043 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19044 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19045 	 */
19046 	mp2ctl = copymsg(mpctl);
19047 	mp3ctl = copymsg(mpctl);
19048 	mp4ctl = copymsg(mpctl);
19049 	if (mp3ctl == NULL || mp4ctl == NULL) {
19050 		freemsg(mp4ctl);
19051 		freemsg(mp3ctl);
19052 		freemsg(mp2ctl);
19053 		freemsg(mpctl);
19054 		return (NULL);
19055 	}
19056 
19057 	bzero(&ird, sizeof (ird));
19058 
19059 	ird.ird_route.lp_head = mpctl->b_cont;
19060 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19061 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19062 
19063 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19064 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19065 	if (zoneid == GLOBAL_ZONEID) {
19066 		/*
19067 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19068 		 * requires the sys_net_config or sys_ip_config privilege,
19069 		 * it can only run in the global zone or an exclusive-IP zone,
19070 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19071 		 */
19072 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19073 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19074 	}
19075 
19076 	/* ipRouteEntryTable in mpctl */
19077 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19078 	optp->level = MIB2_IP;
19079 	optp->name = MIB2_IP_ROUTE;
19080 	optp->len = msgdsize(ird.ird_route.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 	qreply(q, mpctl);
19084 
19085 	/* ipNetToMediaEntryTable in mp3ctl */
19086 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19087 	optp->level = MIB2_IP;
19088 	optp->name = MIB2_IP_MEDIA;
19089 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19090 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19091 	    (int)optp->level, (int)optp->name, (int)optp->len));
19092 	qreply(q, mp3ctl);
19093 
19094 	/* ipRouteAttributeTable in mp4ctl */
19095 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19096 	optp->level = MIB2_IP;
19097 	optp->name = EXPER_IP_RTATTR;
19098 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19099 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19100 	    (int)optp->level, (int)optp->name, (int)optp->len));
19101 	if (optp->len == 0)
19102 		freemsg(mp4ctl);
19103 	else
19104 		qreply(q, mp4ctl);
19105 
19106 	return (mp2ctl);
19107 }
19108 
19109 /*
19110  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19111  * ipv6NetToMediaEntryTable in an NDP walk.
19112  */
19113 static mblk_t *
19114 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19115 {
19116 	struct opthdr	*optp;
19117 	mblk_t		*mp2ctl;	/* Returned */
19118 	mblk_t		*mp3ctl;	/* nettomedia */
19119 	mblk_t		*mp4ctl;	/* routeattrs */
19120 	iproutedata_t	ird;
19121 	zoneid_t	zoneid;
19122 
19123 	/*
19124 	 * make copies of the original message
19125 	 *	- mp2ctl is returned unchanged to the caller for his use
19126 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19127 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19128 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19129 	 */
19130 	mp2ctl = copymsg(mpctl);
19131 	mp3ctl = copymsg(mpctl);
19132 	mp4ctl = copymsg(mpctl);
19133 	if (mp3ctl == NULL || mp4ctl == NULL) {
19134 		freemsg(mp4ctl);
19135 		freemsg(mp3ctl);
19136 		freemsg(mp2ctl);
19137 		freemsg(mpctl);
19138 		return (NULL);
19139 	}
19140 
19141 	bzero(&ird, sizeof (ird));
19142 
19143 	ird.ird_route.lp_head = mpctl->b_cont;
19144 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19145 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19146 
19147 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19148 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19149 
19150 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19151 	optp->level = MIB2_IP6;
19152 	optp->name = MIB2_IP6_ROUTE;
19153 	optp->len = msgdsize(ird.ird_route.lp_head);
19154 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19155 	    (int)optp->level, (int)optp->name, (int)optp->len));
19156 	qreply(q, mpctl);
19157 
19158 	/* ipv6NetToMediaEntryTable in mp3ctl */
19159 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19160 
19161 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19162 	optp->level = MIB2_IP6;
19163 	optp->name = MIB2_IP6_MEDIA;
19164 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19165 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19166 	    (int)optp->level, (int)optp->name, (int)optp->len));
19167 	qreply(q, mp3ctl);
19168 
19169 	/* ipv6RouteAttributeTable in mp4ctl */
19170 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19171 	optp->level = MIB2_IP6;
19172 	optp->name = EXPER_IP_RTATTR;
19173 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19174 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19175 	    (int)optp->level, (int)optp->name, (int)optp->len));
19176 	if (optp->len == 0)
19177 		freemsg(mp4ctl);
19178 	else
19179 		qreply(q, mp4ctl);
19180 
19181 	return (mp2ctl);
19182 }
19183 
19184 /*
19185  * IPv6 mib: One per ill
19186  */
19187 static mblk_t *
19188 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19189 {
19190 	struct opthdr		*optp;
19191 	mblk_t			*mp2ctl;
19192 	ill_t			*ill;
19193 	ill_walk_context_t	ctx;
19194 	mblk_t			*mp_tail = NULL;
19195 
19196 	/*
19197 	 * Make a copy of the original message
19198 	 */
19199 	mp2ctl = copymsg(mpctl);
19200 
19201 	/* fixed length IPv6 structure ... */
19202 
19203 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19204 	optp->level = MIB2_IP6;
19205 	optp->name = 0;
19206 	/* Include "unknown interface" ip6_mib */
19207 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19208 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19209 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19210 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19211 	    ipst->ips_ipv6_forward ? 1 : 2);
19212 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19213 	    ipst->ips_ipv6_def_hops);
19214 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19215 	    sizeof (mib2_ipIfStatsEntry_t));
19216 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19217 	    sizeof (mib2_ipv6AddrEntry_t));
19218 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19219 	    sizeof (mib2_ipv6RouteEntry_t));
19220 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19221 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19222 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19223 	    sizeof (ipv6_member_t));
19224 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19225 	    sizeof (ipv6_grpsrc_t));
19226 
19227 	/*
19228 	 * Synchronize 64- and 32-bit counters
19229 	 */
19230 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19231 	    ipIfStatsHCInReceives);
19232 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19233 	    ipIfStatsHCInDelivers);
19234 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19235 	    ipIfStatsHCOutRequests);
19236 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19237 	    ipIfStatsHCOutForwDatagrams);
19238 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19239 	    ipIfStatsHCOutMcastPkts);
19240 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19241 	    ipIfStatsHCInMcastPkts);
19242 
19243 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19244 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19245 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19246 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19247 	}
19248 
19249 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19250 	ill = ILL_START_WALK_V6(&ctx, ipst);
19251 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19252 		ill->ill_ip_mib->ipIfStatsIfIndex =
19253 		    ill->ill_phyint->phyint_ifindex;
19254 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19255 		    ipst->ips_ipv6_forward ? 1 : 2);
19256 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19257 		    ill->ill_max_hops);
19258 
19259 		/*
19260 		 * Synchronize 64- and 32-bit counters
19261 		 */
19262 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19263 		    ipIfStatsHCInReceives);
19264 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19265 		    ipIfStatsHCInDelivers);
19266 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19267 		    ipIfStatsHCOutRequests);
19268 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19269 		    ipIfStatsHCOutForwDatagrams);
19270 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19271 		    ipIfStatsHCOutMcastPkts);
19272 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19273 		    ipIfStatsHCInMcastPkts);
19274 
19275 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19276 		    (char *)ill->ill_ip_mib,
19277 		    (int)sizeof (*ill->ill_ip_mib))) {
19278 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19279 				"%u bytes\n",
19280 				(uint_t)sizeof (*ill->ill_ip_mib)));
19281 		}
19282 	}
19283 	rw_exit(&ipst->ips_ill_g_lock);
19284 
19285 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19286 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19287 	    (int)optp->level, (int)optp->name, (int)optp->len));
19288 	qreply(q, mpctl);
19289 	return (mp2ctl);
19290 }
19291 
19292 /*
19293  * ICMPv6 mib: One per ill
19294  */
19295 static mblk_t *
19296 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19297 {
19298 	struct opthdr		*optp;
19299 	mblk_t			*mp2ctl;
19300 	ill_t			*ill;
19301 	ill_walk_context_t	ctx;
19302 	mblk_t			*mp_tail = NULL;
19303 	/*
19304 	 * Make a copy of the original message
19305 	 */
19306 	mp2ctl = copymsg(mpctl);
19307 
19308 	/* fixed length ICMPv6 structure ... */
19309 
19310 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19311 	optp->level = MIB2_ICMP6;
19312 	optp->name = 0;
19313 	/* Include "unknown interface" icmp6_mib */
19314 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19315 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19316 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19317 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19318 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19319 	    (char *)&ipst->ips_icmp6_mib,
19320 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19321 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19322 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19323 	}
19324 
19325 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19326 	ill = ILL_START_WALK_V6(&ctx, ipst);
19327 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19328 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19329 		    ill->ill_phyint->phyint_ifindex;
19330 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19331 		    (char *)ill->ill_icmp6_mib,
19332 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19333 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19334 			    "%u bytes\n",
19335 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19336 		}
19337 	}
19338 	rw_exit(&ipst->ips_ill_g_lock);
19339 
19340 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19341 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19342 	    (int)optp->level, (int)optp->name, (int)optp->len));
19343 	qreply(q, mpctl);
19344 	return (mp2ctl);
19345 }
19346 
19347 /*
19348  * ire_walk routine to create both ipRouteEntryTable and
19349  * ipRouteAttributeTable in one IRE walk
19350  */
19351 static void
19352 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19353 {
19354 	ill_t				*ill;
19355 	ipif_t				*ipif;
19356 	mib2_ipRouteEntry_t		*re;
19357 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19358 	ipaddr_t			gw_addr;
19359 	tsol_ire_gw_secattr_t		*attrp;
19360 	tsol_gc_t			*gc = NULL;
19361 	tsol_gcgrp_t			*gcgrp = NULL;
19362 	uint_t				sacnt = 0;
19363 	int				i;
19364 
19365 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19366 
19367 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19368 		return;
19369 
19370 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19371 		mutex_enter(&attrp->igsa_lock);
19372 		if ((gc = attrp->igsa_gc) != NULL) {
19373 			gcgrp = gc->gc_grp;
19374 			ASSERT(gcgrp != NULL);
19375 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19376 			sacnt = 1;
19377 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19378 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19379 			gc = gcgrp->gcgrp_head;
19380 			sacnt = gcgrp->gcgrp_count;
19381 		}
19382 		mutex_exit(&attrp->igsa_lock);
19383 
19384 		/* do nothing if there's no gc to report */
19385 		if (gc == NULL) {
19386 			ASSERT(sacnt == 0);
19387 			if (gcgrp != NULL) {
19388 				/* we might as well drop the lock now */
19389 				rw_exit(&gcgrp->gcgrp_rwlock);
19390 				gcgrp = NULL;
19391 			}
19392 			attrp = NULL;
19393 		}
19394 
19395 		ASSERT(gc == NULL || (gcgrp != NULL &&
19396 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19397 	}
19398 	ASSERT(sacnt == 0 || gc != NULL);
19399 
19400 	if (sacnt != 0 &&
19401 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19402 		kmem_free(re, sizeof (*re));
19403 		rw_exit(&gcgrp->gcgrp_rwlock);
19404 		return;
19405 	}
19406 
19407 	/*
19408 	 * Return all IRE types for route table... let caller pick and choose
19409 	 */
19410 	re->ipRouteDest = ire->ire_addr;
19411 	ipif = ire->ire_ipif;
19412 	re->ipRouteIfIndex.o_length = 0;
19413 	if (ire->ire_type == IRE_CACHE) {
19414 		ill = (ill_t *)ire->ire_stq->q_ptr;
19415 		re->ipRouteIfIndex.o_length =
19416 		    ill->ill_name_length == 0 ? 0 :
19417 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19418 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19419 		    re->ipRouteIfIndex.o_length);
19420 	} else if (ipif != NULL) {
19421 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19422 		    OCTET_LENGTH);
19423 		re->ipRouteIfIndex.o_length =
19424 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19425 	}
19426 	re->ipRouteMetric1 = -1;
19427 	re->ipRouteMetric2 = -1;
19428 	re->ipRouteMetric3 = -1;
19429 	re->ipRouteMetric4 = -1;
19430 
19431 	gw_addr = ire->ire_gateway_addr;
19432 
19433 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19434 		re->ipRouteNextHop = ire->ire_src_addr;
19435 	else
19436 		re->ipRouteNextHop = gw_addr;
19437 	/* indirect(4), direct(3), or invalid(2) */
19438 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19439 		re->ipRouteType = 2;
19440 	else
19441 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19442 	re->ipRouteProto = -1;
19443 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19444 	re->ipRouteMask = ire->ire_mask;
19445 	re->ipRouteMetric5 = -1;
19446 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19447 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19448 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19449 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19450 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19451 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19452 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19453 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19454 	re->ipRouteInfo.re_in_ill.o_length = 0;
19455 
19456 	if (ire->ire_flags & RTF_DYNAMIC) {
19457 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19458 	} else {
19459 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19460 	}
19461 
19462 	if (ire->ire_in_ill != NULL) {
19463 		re->ipRouteInfo.re_in_ill.o_length =
19464 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19465 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19466 		bcopy(ire->ire_in_ill->ill_name,
19467 		    re->ipRouteInfo.re_in_ill.o_bytes,
19468 		    re->ipRouteInfo.re_in_ill.o_length);
19469 	}
19470 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19471 
19472 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19473 	    (char *)re, (int)sizeof (*re))) {
19474 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19475 		    (uint_t)sizeof (*re)));
19476 	}
19477 
19478 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19479 		iaeptr->iae_routeidx = ird->ird_idx;
19480 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19481 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19482 	}
19483 
19484 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19485 	    (char *)iae, sacnt * sizeof (*iae))) {
19486 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19487 		    (unsigned)(sacnt * sizeof (*iae))));
19488 	}
19489 
19490 	/* bump route index for next pass */
19491 	ird->ird_idx++;
19492 
19493 	kmem_free(re, sizeof (*re));
19494 	if (sacnt != 0)
19495 		kmem_free(iae, sacnt * sizeof (*iae));
19496 
19497 	if (gcgrp != NULL)
19498 		rw_exit(&gcgrp->gcgrp_rwlock);
19499 }
19500 
19501 /*
19502  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19503  */
19504 static void
19505 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19506 {
19507 	ill_t				*ill;
19508 	ipif_t				*ipif;
19509 	mib2_ipv6RouteEntry_t		*re;
19510 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19511 	in6_addr_t			gw_addr_v6;
19512 	tsol_ire_gw_secattr_t		*attrp;
19513 	tsol_gc_t			*gc = NULL;
19514 	tsol_gcgrp_t			*gcgrp = NULL;
19515 	uint_t				sacnt = 0;
19516 	int				i;
19517 
19518 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19519 
19520 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19521 		return;
19522 
19523 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19524 		mutex_enter(&attrp->igsa_lock);
19525 		if ((gc = attrp->igsa_gc) != NULL) {
19526 			gcgrp = gc->gc_grp;
19527 			ASSERT(gcgrp != NULL);
19528 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19529 			sacnt = 1;
19530 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19531 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19532 			gc = gcgrp->gcgrp_head;
19533 			sacnt = gcgrp->gcgrp_count;
19534 		}
19535 		mutex_exit(&attrp->igsa_lock);
19536 
19537 		/* do nothing if there's no gc to report */
19538 		if (gc == NULL) {
19539 			ASSERT(sacnt == 0);
19540 			if (gcgrp != NULL) {
19541 				/* we might as well drop the lock now */
19542 				rw_exit(&gcgrp->gcgrp_rwlock);
19543 				gcgrp = NULL;
19544 			}
19545 			attrp = NULL;
19546 		}
19547 
19548 		ASSERT(gc == NULL || (gcgrp != NULL &&
19549 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19550 	}
19551 	ASSERT(sacnt == 0 || gc != NULL);
19552 
19553 	if (sacnt != 0 &&
19554 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19555 		kmem_free(re, sizeof (*re));
19556 		rw_exit(&gcgrp->gcgrp_rwlock);
19557 		return;
19558 	}
19559 
19560 	/*
19561 	 * Return all IRE types for route table... let caller pick and choose
19562 	 */
19563 	re->ipv6RouteDest = ire->ire_addr_v6;
19564 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19565 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19566 	re->ipv6RouteIfIndex.o_length = 0;
19567 	ipif = ire->ire_ipif;
19568 	if (ire->ire_type == IRE_CACHE) {
19569 		ill = (ill_t *)ire->ire_stq->q_ptr;
19570 		re->ipv6RouteIfIndex.o_length =
19571 		    ill->ill_name_length == 0 ? 0 :
19572 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19573 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19574 		    re->ipv6RouteIfIndex.o_length);
19575 	} else if (ipif != NULL) {
19576 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19577 		    OCTET_LENGTH);
19578 		re->ipv6RouteIfIndex.o_length =
19579 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19580 	}
19581 
19582 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19583 
19584 	mutex_enter(&ire->ire_lock);
19585 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19586 	mutex_exit(&ire->ire_lock);
19587 
19588 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19589 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19590 	else
19591 		re->ipv6RouteNextHop = gw_addr_v6;
19592 
19593 	/* remote(4), local(3), or discard(2) */
19594 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19595 		re->ipv6RouteType = 2;
19596 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19597 		re->ipv6RouteType = 3;
19598 	else
19599 		re->ipv6RouteType = 4;
19600 
19601 	re->ipv6RouteProtocol	= -1;
19602 	re->ipv6RoutePolicy	= 0;
19603 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19604 	re->ipv6RouteNextHopRDI	= 0;
19605 	re->ipv6RouteWeight	= 0;
19606 	re->ipv6RouteMetric	= 0;
19607 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19608 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19609 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19610 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19611 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19612 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19613 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19614 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19615 
19616 	if (ire->ire_flags & RTF_DYNAMIC) {
19617 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19618 	} else {
19619 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19620 	}
19621 
19622 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19623 	    (char *)re, (int)sizeof (*re))) {
19624 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19625 		    (uint_t)sizeof (*re)));
19626 	}
19627 
19628 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19629 		iaeptr->iae_routeidx = ird->ird_idx;
19630 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19631 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19632 	}
19633 
19634 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19635 	    (char *)iae, sacnt * sizeof (*iae))) {
19636 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19637 		    (unsigned)(sacnt * sizeof (*iae))));
19638 	}
19639 
19640 	/* bump route index for next pass */
19641 	ird->ird_idx++;
19642 
19643 	kmem_free(re, sizeof (*re));
19644 	if (sacnt != 0)
19645 		kmem_free(iae, sacnt * sizeof (*iae));
19646 
19647 	if (gcgrp != NULL)
19648 		rw_exit(&gcgrp->gcgrp_rwlock);
19649 }
19650 
19651 /*
19652  * ndp_walk routine to create ipv6NetToMediaEntryTable
19653  */
19654 static int
19655 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19656 {
19657 	ill_t				*ill;
19658 	mib2_ipv6NetToMediaEntry_t	ntme;
19659 	dl_unitdata_req_t		*dl;
19660 
19661 	ill = nce->nce_ill;
19662 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19663 		return (0);
19664 
19665 	/*
19666 	 * Neighbor cache entry attached to IRE with on-link
19667 	 * destination.
19668 	 */
19669 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19670 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19671 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19672 	    (nce->nce_res_mp != NULL)) {
19673 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19674 		ntme.ipv6NetToMediaPhysAddress.o_length =
19675 		    dl->dl_dest_addr_length;
19676 	} else {
19677 		ntme.ipv6NetToMediaPhysAddress.o_length =
19678 		    ill->ill_phys_addr_length;
19679 	}
19680 	if (nce->nce_res_mp != NULL) {
19681 		bcopy((char *)nce->nce_res_mp->b_rptr +
19682 		    NCE_LL_ADDR_OFFSET(ill),
19683 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19684 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19685 	} else {
19686 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19687 		    ill->ill_phys_addr_length);
19688 	}
19689 	/*
19690 	 * Note: Returns ND_* states. Should be:
19691 	 * reachable(1), stale(2), delay(3), probe(4),
19692 	 * invalid(5), unknown(6)
19693 	 */
19694 	ntme.ipv6NetToMediaState = nce->nce_state;
19695 	ntme.ipv6NetToMediaLastUpdated = 0;
19696 
19697 	/* other(1), dynamic(2), static(3), local(4) */
19698 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19699 		ntme.ipv6NetToMediaType = 4;
19700 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19701 		ntme.ipv6NetToMediaType = 1;
19702 	} else {
19703 		ntme.ipv6NetToMediaType = 2;
19704 	}
19705 
19706 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19707 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19708 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19709 		    (uint_t)sizeof (ntme)));
19710 	}
19711 	return (0);
19712 }
19713 
19714 /*
19715  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19716  */
19717 /* ARGSUSED */
19718 int
19719 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19720 {
19721 	switch (level) {
19722 	case MIB2_IP:
19723 	case MIB2_ICMP:
19724 		switch (name) {
19725 		default:
19726 			break;
19727 		}
19728 		return (1);
19729 	default:
19730 		return (1);
19731 	}
19732 }
19733 
19734 /*
19735  * When there exists both a 64- and 32-bit counter of a particular type
19736  * (i.e., InReceives), only the 64-bit counters are added.
19737  */
19738 void
19739 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19740 {
19741 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19742 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19743 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19744 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19745 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19746 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19747 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19748 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19749 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19750 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19751 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19752 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19753 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19754 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19755 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19756 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19757 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19758 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19759 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19760 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19761 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19762 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19763 	    o2->ipIfStatsInWrongIPVersion);
19764 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19765 	    o2->ipIfStatsInWrongIPVersion);
19766 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19767 	    o2->ipIfStatsOutSwitchIPVersion);
19768 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19769 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19770 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19771 	    o2->ipIfStatsHCInForwDatagrams);
19772 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19773 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19774 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19775 	    o2->ipIfStatsHCOutForwDatagrams);
19776 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19777 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19778 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19779 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19780 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19781 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19782 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19783 	    o2->ipIfStatsHCOutMcastOctets);
19784 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19785 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19786 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19787 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19788 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19789 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19790 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19791 }
19792 
19793 void
19794 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19795 {
19796 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19797 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19798 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19799 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19800 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19801 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19802 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19803 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19804 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19805 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19806 	    o2->ipv6IfIcmpInRouterSolicits);
19807 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19808 	    o2->ipv6IfIcmpInRouterAdvertisements);
19809 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19810 	    o2->ipv6IfIcmpInNeighborSolicits);
19811 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19812 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19813 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19814 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19815 	    o2->ipv6IfIcmpInGroupMembQueries);
19816 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19817 	    o2->ipv6IfIcmpInGroupMembResponses);
19818 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19819 	    o2->ipv6IfIcmpInGroupMembReductions);
19820 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19821 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19822 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19823 	    o2->ipv6IfIcmpOutDestUnreachs);
19824 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19825 	    o2->ipv6IfIcmpOutAdminProhibs);
19826 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19827 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19828 	    o2->ipv6IfIcmpOutParmProblems);
19829 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19830 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19831 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19832 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19833 	    o2->ipv6IfIcmpOutRouterSolicits);
19834 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19835 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19836 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19837 	    o2->ipv6IfIcmpOutNeighborSolicits);
19838 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19839 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19840 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19841 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19842 	    o2->ipv6IfIcmpOutGroupMembQueries);
19843 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19844 	    o2->ipv6IfIcmpOutGroupMembResponses);
19845 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19846 	    o2->ipv6IfIcmpOutGroupMembReductions);
19847 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19848 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19849 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19850 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19851 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19852 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19853 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19854 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19855 	    o2->ipv6IfIcmpInGroupMembTotal);
19856 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19857 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19859 	    o2->ipv6IfIcmpInGroupMembBadReports);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19861 	    o2->ipv6IfIcmpInGroupMembOurReports);
19862 }
19863 
19864 /*
19865  * Called before the options are updated to check if this packet will
19866  * be source routed from here.
19867  * This routine assumes that the options are well formed i.e. that they
19868  * have already been checked.
19869  */
19870 static boolean_t
19871 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19872 {
19873 	ipoptp_t	opts;
19874 	uchar_t		*opt;
19875 	uint8_t		optval;
19876 	uint8_t		optlen;
19877 	ipaddr_t	dst;
19878 	ire_t		*ire;
19879 
19880 	if (IS_SIMPLE_IPH(ipha)) {
19881 		ip2dbg(("not source routed\n"));
19882 		return (B_FALSE);
19883 	}
19884 	dst = ipha->ipha_dst;
19885 	for (optval = ipoptp_first(&opts, ipha);
19886 	    optval != IPOPT_EOL;
19887 	    optval = ipoptp_next(&opts)) {
19888 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19889 		opt = opts.ipoptp_cur;
19890 		optlen = opts.ipoptp_len;
19891 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19892 		    optval, optlen));
19893 		switch (optval) {
19894 			uint32_t off;
19895 		case IPOPT_SSRR:
19896 		case IPOPT_LSRR:
19897 			/*
19898 			 * If dst is one of our addresses and there are some
19899 			 * entries left in the source route return (true).
19900 			 */
19901 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19902 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19903 			if (ire == NULL) {
19904 				ip2dbg(("ip_source_routed: not next"
19905 				    " source route 0x%x\n",
19906 				    ntohl(dst)));
19907 				return (B_FALSE);
19908 			}
19909 			ire_refrele(ire);
19910 			off = opt[IPOPT_OFFSET];
19911 			off--;
19912 			if (optlen < IP_ADDR_LEN ||
19913 			    off > optlen - IP_ADDR_LEN) {
19914 				/* End of source route */
19915 				ip1dbg(("ip_source_routed: end of SR\n"));
19916 				return (B_FALSE);
19917 			}
19918 			return (B_TRUE);
19919 		}
19920 	}
19921 	ip2dbg(("not source routed\n"));
19922 	return (B_FALSE);
19923 }
19924 
19925 /*
19926  * Check if the packet contains any source route.
19927  */
19928 static boolean_t
19929 ip_source_route_included(ipha_t *ipha)
19930 {
19931 	ipoptp_t	opts;
19932 	uint8_t		optval;
19933 
19934 	if (IS_SIMPLE_IPH(ipha))
19935 		return (B_FALSE);
19936 	for (optval = ipoptp_first(&opts, ipha);
19937 	    optval != IPOPT_EOL;
19938 	    optval = ipoptp_next(&opts)) {
19939 		switch (optval) {
19940 		case IPOPT_SSRR:
19941 		case IPOPT_LSRR:
19942 			return (B_TRUE);
19943 		}
19944 	}
19945 	return (B_FALSE);
19946 }
19947 
19948 /*
19949  * Called when the IRE expiration timer fires.
19950  */
19951 void
19952 ip_trash_timer_expire(void *args)
19953 {
19954 	int			flush_flag = 0;
19955 	ire_expire_arg_t	iea;
19956 	ip_stack_t		*ipst = (ip_stack_t *)args;
19957 
19958 	iea.iea_ipst = ipst;	/* No netstack_hold */
19959 
19960 	/*
19961 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19962 	 * This lock makes sure that a new invocation of this function
19963 	 * that occurs due to an almost immediate timer firing will not
19964 	 * progress beyond this point until the current invocation is done
19965 	 */
19966 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19967 	ipst->ips_ip_ire_expire_id = 0;
19968 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19969 
19970 	/* Periodic timer */
19971 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19972 	    ipst->ips_ip_ire_arp_interval) {
19973 		/*
19974 		 * Remove all IRE_CACHE entries since they might
19975 		 * contain arp information.
19976 		 */
19977 		flush_flag |= FLUSH_ARP_TIME;
19978 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19979 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19980 	}
19981 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19982 	    ipst->ips_ip_ire_redir_interval) {
19983 		/* Remove all redirects */
19984 		flush_flag |= FLUSH_REDIRECT_TIME;
19985 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19986 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19987 	}
19988 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19989 	    ipst->ips_ip_ire_pathmtu_interval) {
19990 		/* Increase path mtu */
19991 		flush_flag |= FLUSH_MTU_TIME;
19992 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19993 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19994 	}
19995 
19996 	/*
19997 	 * Optimize for the case when there are no redirects in the
19998 	 * ftable, that is, no need to walk the ftable in that case.
19999 	 */
20000 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20001 		iea.iea_flush_flag = flush_flag;
20002 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20003 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20004 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20005 		    NULL, ALL_ZONES, ipst);
20006 	}
20007 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20008 	    ipst->ips_ip_redirect_cnt > 0) {
20009 		iea.iea_flush_flag = flush_flag;
20010 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20011 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20012 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20013 	}
20014 	if (flush_flag & FLUSH_MTU_TIME) {
20015 		/*
20016 		 * Walk all IPv6 IRE's and update them
20017 		 * Note that ARP and redirect timers are not
20018 		 * needed since NUD handles stale entries.
20019 		 */
20020 		flush_flag = FLUSH_MTU_TIME;
20021 		iea.iea_flush_flag = flush_flag;
20022 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20023 		    ALL_ZONES, ipst);
20024 	}
20025 
20026 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20027 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20028 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20029 
20030 	/*
20031 	 * Hold the lock to serialize timeout calls and prevent
20032 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20033 	 * for the timer to fire and a new invocation of this function
20034 	 * to start before the return value of timeout has been stored
20035 	 * in ip_ire_expire_id by the current invocation.
20036 	 */
20037 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20038 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20039 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20040 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20041 }
20042 
20043 /*
20044  * Called by the memory allocator subsystem directly, when the system
20045  * is running low on memory.
20046  */
20047 /* ARGSUSED */
20048 void
20049 ip_trash_ire_reclaim(void *args)
20050 {
20051 	netstack_handle_t nh;
20052 	netstack_t *ns;
20053 
20054 	netstack_next_init(&nh);
20055 	while ((ns = netstack_next(&nh)) != NULL) {
20056 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20057 		netstack_rele(ns);
20058 	}
20059 	netstack_next_fini(&nh);
20060 }
20061 
20062 static void
20063 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20064 {
20065 	ire_cache_count_t icc;
20066 	ire_cache_reclaim_t icr;
20067 	ncc_cache_count_t ncc;
20068 	nce_cache_reclaim_t ncr;
20069 	uint_t delete_cnt;
20070 	/*
20071 	 * Memory reclaim call back.
20072 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20073 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20074 	 * entries, determine what fraction to free for
20075 	 * each category of IRE_CACHE entries giving absolute priority
20076 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20077 	 * entry will be freed unless all offlink entries are freed).
20078 	 */
20079 	icc.icc_total = 0;
20080 	icc.icc_unused = 0;
20081 	icc.icc_offlink = 0;
20082 	icc.icc_pmtu = 0;
20083 	icc.icc_onlink = 0;
20084 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20085 
20086 	/*
20087 	 * Free NCEs for IPv6 like the onlink ires.
20088 	 */
20089 	ncc.ncc_total = 0;
20090 	ncc.ncc_host = 0;
20091 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20092 
20093 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20094 	    icc.icc_pmtu + icc.icc_onlink);
20095 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20096 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20097 	if (delete_cnt == 0)
20098 		return;
20099 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20100 	/* Always delete all unused offlink entries */
20101 	icr.icr_ipst = ipst;
20102 	icr.icr_unused = 1;
20103 	if (delete_cnt <= icc.icc_unused) {
20104 		/*
20105 		 * Only need to free unused entries.  In other words,
20106 		 * there are enough unused entries to free to meet our
20107 		 * target number of freed ire cache entries.
20108 		 */
20109 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20110 		ncr.ncr_host = 0;
20111 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20112 		/*
20113 		 * Only need to free unused entries, plus a fraction of offlink
20114 		 * entries.  It follows from the first if statement that
20115 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20116 		 */
20117 		delete_cnt -= icc.icc_unused;
20118 		/* Round up # deleted by truncating fraction */
20119 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20120 		icr.icr_pmtu = icr.icr_onlink = 0;
20121 		ncr.ncr_host = 0;
20122 	} else if (delete_cnt <=
20123 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20124 		/*
20125 		 * Free all unused and offlink entries, plus a fraction of
20126 		 * pmtu entries.  It follows from the previous if statement
20127 		 * that icc_pmtu is non-zero, and that
20128 		 * delete_cnt != icc_unused + icc_offlink.
20129 		 */
20130 		icr.icr_offlink = 1;
20131 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20132 		/* Round up # deleted by truncating fraction */
20133 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20134 		icr.icr_onlink = 0;
20135 		ncr.ncr_host = 0;
20136 	} else {
20137 		/*
20138 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20139 		 * of onlink entries.  If we're here, then we know that
20140 		 * icc_onlink is non-zero, and that
20141 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20142 		 */
20143 		icr.icr_offlink = icr.icr_pmtu = 1;
20144 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20145 		    icc.icc_pmtu;
20146 		/* Round up # deleted by truncating fraction */
20147 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20148 		/* Using the same delete fraction as for onlink IREs */
20149 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20150 	}
20151 #ifdef DEBUG
20152 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20153 	    "fractions %d/%d/%d/%d\n",
20154 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20155 	    icc.icc_unused, icc.icc_offlink,
20156 	    icc.icc_pmtu, icc.icc_onlink,
20157 	    icr.icr_unused, icr.icr_offlink,
20158 	    icr.icr_pmtu, icr.icr_onlink));
20159 #endif
20160 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20161 	if (ncr.ncr_host != 0)
20162 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20163 		    (uchar_t *)&ncr, ipst);
20164 #ifdef DEBUG
20165 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20166 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20167 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20168 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20169 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20170 	    icc.icc_pmtu, icc.icc_onlink));
20171 #endif
20172 }
20173 
20174 /*
20175  * ip_unbind is called when a copy of an unbind request is received from the
20176  * upper level protocol.  We remove this conn from any fanout hash list it is
20177  * on, and zero out the bind information.  No reply is expected up above.
20178  */
20179 mblk_t *
20180 ip_unbind(queue_t *q, mblk_t *mp)
20181 {
20182 	conn_t	*connp = Q_TO_CONN(q);
20183 
20184 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20185 
20186 	if (is_system_labeled() && connp->conn_anon_port) {
20187 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20188 		    connp->conn_mlp_type, connp->conn_ulp,
20189 		    ntohs(connp->conn_lport), B_FALSE);
20190 		connp->conn_anon_port = 0;
20191 	}
20192 	connp->conn_mlp_type = mlptSingle;
20193 
20194 	ipcl_hash_remove(connp);
20195 
20196 	ASSERT(mp->b_cont == NULL);
20197 	/*
20198 	 * Convert mp into a T_OK_ACK
20199 	 */
20200 	mp = mi_tpi_ok_ack_alloc(mp);
20201 
20202 	/*
20203 	 * should not happen in practice... T_OK_ACK is smaller than the
20204 	 * original message.
20205 	 */
20206 	if (mp == NULL)
20207 		return (NULL);
20208 
20209 	/*
20210 	 * Don't bzero the ports if its TCP since TCP still needs the
20211 	 * lport to remove it from its own bind hash. TCP will do the
20212 	 * cleanup.
20213 	 */
20214 	if (!IPCL_IS_TCP(connp))
20215 		bzero(&connp->u_port, sizeof (connp->u_port));
20216 
20217 	return (mp);
20218 }
20219 
20220 /*
20221  * Write side put procedure.  Outbound data, IOCTLs, responses from
20222  * resolvers, etc, come down through here.
20223  *
20224  * arg2 is always a queue_t *.
20225  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20226  * the zoneid.
20227  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20228  */
20229 void
20230 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20231 {
20232 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20233 }
20234 
20235 void
20236 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20237     ip_opt_info_t *infop)
20238 {
20239 	conn_t		*connp = NULL;
20240 	queue_t		*q = (queue_t *)arg2;
20241 	ipha_t		*ipha;
20242 #define	rptr	((uchar_t *)ipha)
20243 	ire_t		*ire = NULL;
20244 	ire_t		*sctp_ire = NULL;
20245 	uint32_t	v_hlen_tos_len;
20246 	ipaddr_t	dst;
20247 	mblk_t		*first_mp = NULL;
20248 	boolean_t	mctl_present;
20249 	ipsec_out_t	*io;
20250 	int		match_flags;
20251 	ill_t		*attach_ill = NULL;
20252 					/* Bind to IPIF_NOFAILOVER ill etc. */
20253 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20254 	ipif_t		*dst_ipif;
20255 	boolean_t	multirt_need_resolve = B_FALSE;
20256 	mblk_t		*copy_mp = NULL;
20257 	int		err;
20258 	zoneid_t	zoneid;
20259 	int	adjust;
20260 	uint16_t iplen;
20261 	boolean_t	need_decref = B_FALSE;
20262 	boolean_t	ignore_dontroute = B_FALSE;
20263 	boolean_t	ignore_nexthop = B_FALSE;
20264 	boolean_t	ip_nexthop = B_FALSE;
20265 	ipaddr_t	nexthop_addr;
20266 	ip_stack_t	*ipst;
20267 
20268 #ifdef	_BIG_ENDIAN
20269 #define	V_HLEN	(v_hlen_tos_len >> 24)
20270 #else
20271 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20272 #endif
20273 
20274 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20275 	    "ip_wput_start: q %p", q);
20276 
20277 	/*
20278 	 * ip_wput fast path
20279 	 */
20280 
20281 	/* is packet from ARP ? */
20282 	if (q->q_next != NULL) {
20283 		zoneid = (zoneid_t)(uintptr_t)arg;
20284 		goto qnext;
20285 	}
20286 
20287 	connp = (conn_t *)arg;
20288 	ASSERT(connp != NULL);
20289 	zoneid = connp->conn_zoneid;
20290 	ipst = connp->conn_netstack->netstack_ip;
20291 
20292 	/* is queue flow controlled? */
20293 	if ((q->q_first != NULL || connp->conn_draining) &&
20294 	    (caller == IP_WPUT)) {
20295 		ASSERT(!need_decref);
20296 		(void) putq(q, mp);
20297 		return;
20298 	}
20299 
20300 	/* Multidata transmit? */
20301 	if (DB_TYPE(mp) == M_MULTIDATA) {
20302 		/*
20303 		 * We should never get here, since all Multidata messages
20304 		 * originating from tcp should have been directed over to
20305 		 * tcp_multisend() in the first place.
20306 		 */
20307 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20308 		freemsg(mp);
20309 		return;
20310 	} else if (DB_TYPE(mp) != M_DATA)
20311 		goto notdata;
20312 
20313 	if (mp->b_flag & MSGHASREF) {
20314 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20315 		mp->b_flag &= ~MSGHASREF;
20316 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20317 		need_decref = B_TRUE;
20318 	}
20319 	ipha = (ipha_t *)mp->b_rptr;
20320 
20321 	/* is IP header non-aligned or mblk smaller than basic IP header */
20322 #ifndef SAFETY_BEFORE_SPEED
20323 	if (!OK_32PTR(rptr) ||
20324 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20325 		goto hdrtoosmall;
20326 #endif
20327 
20328 	ASSERT(OK_32PTR(ipha));
20329 
20330 	/*
20331 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20332 	 * wrong version, we'll catch it again in ip_output_v6.
20333 	 *
20334 	 * Note that this is *only* locally-generated output here, and never
20335 	 * forwarded data, and that we need to deal only with transports that
20336 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20337 	 * label.)
20338 	 */
20339 	if (is_system_labeled() &&
20340 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20341 	    !connp->conn_ulp_labeled) {
20342 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20343 		    connp->conn_mac_exempt, ipst);
20344 		ipha = (ipha_t *)mp->b_rptr;
20345 		if (err != 0) {
20346 			first_mp = mp;
20347 			if (err == EINVAL)
20348 				goto icmp_parameter_problem;
20349 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20350 			goto discard_pkt;
20351 		}
20352 		iplen = ntohs(ipha->ipha_length) + adjust;
20353 		ipha->ipha_length = htons(iplen);
20354 	}
20355 
20356 	ASSERT(infop != NULL);
20357 
20358 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20359 		/*
20360 		 * IP_PKTINFO ancillary option is present.
20361 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20362 		 * allows using address of any zone as the source address.
20363 		 */
20364 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20365 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20366 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20367 		if (ire == NULL)
20368 			goto drop_pkt;
20369 		ire_refrele(ire);
20370 		ire = NULL;
20371 	}
20372 
20373 	/*
20374 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20375 	 * ill index passed in IP_PKTINFO.
20376 	 */
20377 	if (infop->ip_opt_ill_index != 0 &&
20378 	    connp->conn_xmit_if_ill == NULL &&
20379 	    connp->conn_nofailover_ill == NULL) {
20380 
20381 		xmit_ill = ill_lookup_on_ifindex(
20382 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20383 		    ipst);
20384 
20385 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20386 			goto drop_pkt;
20387 		/*
20388 		 * check that there is an ipif belonging
20389 		 * to our zone. IPCL_ZONEID is not used because
20390 		 * IP_ALLZONES option is valid only when the ill is
20391 		 * accessible from all zones i.e has a valid ipif in
20392 		 * all zones.
20393 		 */
20394 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20395 			goto drop_pkt;
20396 		}
20397 	}
20398 
20399 	/*
20400 	 * If there is a policy, try to attach an ipsec_out in
20401 	 * the front. At the end, first_mp either points to a
20402 	 * M_DATA message or IPSEC_OUT message linked to a
20403 	 * M_DATA message. We have to do it now as we might
20404 	 * lose the "conn" if we go through ip_newroute.
20405 	 */
20406 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20407 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20408 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20409 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20410 			if (need_decref)
20411 				CONN_DEC_REF(connp);
20412 			return;
20413 		} else {
20414 			ASSERT(mp->b_datap->db_type == M_CTL);
20415 			first_mp = mp;
20416 			mp = mp->b_cont;
20417 			mctl_present = B_TRUE;
20418 		}
20419 	} else {
20420 		first_mp = mp;
20421 		mctl_present = B_FALSE;
20422 	}
20423 
20424 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20425 
20426 	/* is wrong version or IP options present */
20427 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20428 		goto version_hdrlen_check;
20429 	dst = ipha->ipha_dst;
20430 
20431 	if (connp->conn_nofailover_ill != NULL) {
20432 		attach_ill = conn_get_held_ill(connp,
20433 		    &connp->conn_nofailover_ill, &err);
20434 		if (err == ILL_LOOKUP_FAILED) {
20435 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20436 			if (need_decref)
20437 				CONN_DEC_REF(connp);
20438 			freemsg(first_mp);
20439 			return;
20440 		}
20441 	}
20442 
20443 
20444 	/* is packet multicast? */
20445 	if (CLASSD(dst))
20446 		goto multicast;
20447 
20448 	/*
20449 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20450 	 * takes precedence over conn_dontroute and conn_nexthop_set
20451 	 */
20452 	if (xmit_ill != NULL) {
20453 		goto send_from_ill;
20454 	}
20455 
20456 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20457 	    (connp->conn_nexthop_set)) {
20458 		/*
20459 		 * If the destination is a broadcast or a loopback
20460 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20461 		 * through the standard path. But in the case of local
20462 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20463 		 * the standard path not IP_XMIT_IF.
20464 		 */
20465 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20466 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20467 		    (ire->ire_type != IRE_LOOPBACK))) {
20468 			if ((connp->conn_dontroute ||
20469 			    connp->conn_nexthop_set) && (ire != NULL) &&
20470 			    (ire->ire_type == IRE_LOCAL))
20471 				goto standard_path;
20472 
20473 			if (ire != NULL) {
20474 				ire_refrele(ire);
20475 				/* No more access to ire */
20476 				ire = NULL;
20477 			}
20478 			/*
20479 			 * bypass routing checks and go directly to
20480 			 * interface.
20481 			 */
20482 			if (connp->conn_dontroute) {
20483 				goto dontroute;
20484 			} else if (connp->conn_nexthop_set) {
20485 				ip_nexthop = B_TRUE;
20486 				nexthop_addr = connp->conn_nexthop_v4;
20487 				goto send_from_ill;
20488 			}
20489 
20490 			/*
20491 			 * If IP_XMIT_IF socket option is set,
20492 			 * then we allow unicast and multicast
20493 			 * packets to go through the ill. It is
20494 			 * quite possible that the destination
20495 			 * is not in the ire cache table and we
20496 			 * do not want to go to ip_newroute()
20497 			 * instead we call ip_newroute_ipif.
20498 			 */
20499 			xmit_ill = conn_get_held_ill(connp,
20500 			    &connp->conn_xmit_if_ill, &err);
20501 			if (err == ILL_LOOKUP_FAILED) {
20502 				BUMP_MIB(&ipst->ips_ip_mib,
20503 				    ipIfStatsOutDiscards);
20504 				if (attach_ill != NULL)
20505 					ill_refrele(attach_ill);
20506 				if (need_decref)
20507 					CONN_DEC_REF(connp);
20508 				freemsg(first_mp);
20509 				return;
20510 			}
20511 			goto send_from_ill;
20512 		}
20513 standard_path:
20514 		/* Must be a broadcast, a loopback or a local ire */
20515 		if (ire != NULL) {
20516 			ire_refrele(ire);
20517 			/* No more access to ire */
20518 			ire = NULL;
20519 		}
20520 	}
20521 
20522 	if (attach_ill != NULL)
20523 		goto send_from_ill;
20524 
20525 	/*
20526 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20527 	 * this for the tcp global queue and listen end point
20528 	 * as it does not really have a real destination to
20529 	 * talk to.  This is also true for SCTP.
20530 	 */
20531 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20532 	    !connp->conn_fully_bound) {
20533 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20534 		if (ire == NULL)
20535 			goto noirefound;
20536 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20537 		    "ip_wput_end: q %p (%S)", q, "end");
20538 
20539 		/*
20540 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20541 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20542 		 */
20543 		if (ire->ire_flags & RTF_MULTIRT) {
20544 
20545 			/*
20546 			 * Force the TTL of multirouted packets if required.
20547 			 * The TTL of such packets is bounded by the
20548 			 * ip_multirt_ttl ndd variable.
20549 			 */
20550 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20551 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20552 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20553 				    "(was %d), dst 0x%08x\n",
20554 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20555 				    ntohl(ire->ire_addr)));
20556 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20557 			}
20558 			/*
20559 			 * We look at this point if there are pending
20560 			 * unresolved routes. ire_multirt_resolvable()
20561 			 * checks in O(n) that all IRE_OFFSUBNET ire
20562 			 * entries for the packet's destination and
20563 			 * flagged RTF_MULTIRT are currently resolved.
20564 			 * If some remain unresolved, we make a copy
20565 			 * of the current message. It will be used
20566 			 * to initiate additional route resolutions.
20567 			 */
20568 			multirt_need_resolve =
20569 			    ire_multirt_need_resolve(ire->ire_addr,
20570 			    MBLK_GETLABEL(first_mp), ipst);
20571 			ip2dbg(("ip_wput[TCP]: ire %p, "
20572 			    "multirt_need_resolve %d, first_mp %p\n",
20573 			    (void *)ire, multirt_need_resolve,
20574 			    (void *)first_mp));
20575 			if (multirt_need_resolve) {
20576 				copy_mp = copymsg(first_mp);
20577 				if (copy_mp != NULL) {
20578 					MULTIRT_DEBUG_TAG(copy_mp);
20579 				}
20580 			}
20581 		}
20582 
20583 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20584 
20585 		/*
20586 		 * Try to resolve another multiroute if
20587 		 * ire_multirt_need_resolve() deemed it necessary.
20588 		 */
20589 		if (copy_mp != NULL) {
20590 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20591 		}
20592 		if (need_decref)
20593 			CONN_DEC_REF(connp);
20594 		return;
20595 	}
20596 
20597 	/*
20598 	 * Access to conn_ire_cache. (protected by conn_lock)
20599 	 *
20600 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20601 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20602 	 * send a packet or two with the IRE_CACHE that is going away.
20603 	 * Access to the ire requires an ire refhold on the ire prior to
20604 	 * its use since an interface unplumb thread may delete the cached
20605 	 * ire and release the refhold at any time.
20606 	 *
20607 	 * Caching an ire in the conn_ire_cache
20608 	 *
20609 	 * o Caching an ire pointer in the conn requires a strict check for
20610 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20611 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20612 	 * in the conn is done after making sure under the bucket lock that the
20613 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20614 	 * caching an ire after the unplumb thread has cleaned up the conn.
20615 	 * If the conn does not send a packet subsequently the unplumb thread
20616 	 * will be hanging waiting for the ire count to drop to zero.
20617 	 *
20618 	 * o We also need to atomically test for a null conn_ire_cache and
20619 	 * set the conn_ire_cache under the the protection of the conn_lock
20620 	 * to avoid races among concurrent threads trying to simultaneously
20621 	 * cache an ire in the conn_ire_cache.
20622 	 */
20623 	mutex_enter(&connp->conn_lock);
20624 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20625 
20626 	if (ire != NULL && ire->ire_addr == dst &&
20627 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20628 
20629 		IRE_REFHOLD(ire);
20630 		mutex_exit(&connp->conn_lock);
20631 
20632 	} else {
20633 		boolean_t cached = B_FALSE;
20634 		connp->conn_ire_cache = NULL;
20635 		mutex_exit(&connp->conn_lock);
20636 		/* Release the old ire */
20637 		if (ire != NULL && sctp_ire == NULL)
20638 			IRE_REFRELE_NOTR(ire);
20639 
20640 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20641 		if (ire == NULL)
20642 			goto noirefound;
20643 		IRE_REFHOLD_NOTR(ire);
20644 
20645 		mutex_enter(&connp->conn_lock);
20646 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20647 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20648 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20649 				if (connp->conn_ulp == IPPROTO_TCP)
20650 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20651 				connp->conn_ire_cache = ire;
20652 				cached = B_TRUE;
20653 			}
20654 			rw_exit(&ire->ire_bucket->irb_lock);
20655 		}
20656 		mutex_exit(&connp->conn_lock);
20657 
20658 		/*
20659 		 * We can continue to use the ire but since it was
20660 		 * not cached, we should drop the extra reference.
20661 		 */
20662 		if (!cached)
20663 			IRE_REFRELE_NOTR(ire);
20664 	}
20665 
20666 
20667 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20668 	    "ip_wput_end: q %p (%S)", q, "end");
20669 
20670 	/*
20671 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20672 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20673 	 */
20674 	if (ire->ire_flags & RTF_MULTIRT) {
20675 
20676 		/*
20677 		 * Force the TTL of multirouted packets if required.
20678 		 * The TTL of such packets is bounded by the
20679 		 * ip_multirt_ttl ndd variable.
20680 		 */
20681 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20682 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20683 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20684 			    "(was %d), dst 0x%08x\n",
20685 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20686 			    ntohl(ire->ire_addr)));
20687 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20688 		}
20689 
20690 		/*
20691 		 * At this point, we check to see if there are any pending
20692 		 * unresolved routes. ire_multirt_resolvable()
20693 		 * checks in O(n) that all IRE_OFFSUBNET ire
20694 		 * entries for the packet's destination and
20695 		 * flagged RTF_MULTIRT are currently resolved.
20696 		 * If some remain unresolved, we make a copy
20697 		 * of the current message. It will be used
20698 		 * to initiate additional route resolutions.
20699 		 */
20700 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20701 		    MBLK_GETLABEL(first_mp), ipst);
20702 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20703 		    "multirt_need_resolve %d, first_mp %p\n",
20704 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20705 		if (multirt_need_resolve) {
20706 			copy_mp = copymsg(first_mp);
20707 			if (copy_mp != NULL) {
20708 				MULTIRT_DEBUG_TAG(copy_mp);
20709 			}
20710 		}
20711 	}
20712 
20713 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20714 
20715 	/*
20716 	 * Try to resolve another multiroute if
20717 	 * ire_multirt_resolvable() deemed it necessary
20718 	 */
20719 	if (copy_mp != NULL) {
20720 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20721 	}
20722 	if (need_decref)
20723 		CONN_DEC_REF(connp);
20724 	return;
20725 
20726 qnext:
20727 	/*
20728 	 * Upper Level Protocols pass down complete IP datagrams
20729 	 * as M_DATA messages.	Everything else is a sideshow.
20730 	 *
20731 	 * 1) We could be re-entering ip_wput because of ip_neworute
20732 	 *    in which case we could have a IPSEC_OUT message. We
20733 	 *    need to pass through ip_wput like other datagrams and
20734 	 *    hence cannot branch to ip_wput_nondata.
20735 	 *
20736 	 * 2) ARP, AH, ESP, and other clients who are on the module
20737 	 *    instance of IP stream, give us something to deal with.
20738 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20739 	 *
20740 	 * 3) ICMP replies also could come here.
20741 	 */
20742 	ipst = ILLQ_TO_IPST(q);
20743 
20744 	if (DB_TYPE(mp) != M_DATA) {
20745 	    notdata:
20746 		if (DB_TYPE(mp) == M_CTL) {
20747 			/*
20748 			 * M_CTL messages are used by ARP, AH and ESP to
20749 			 * communicate with IP. We deal with IPSEC_IN and
20750 			 * IPSEC_OUT here. ip_wput_nondata handles other
20751 			 * cases.
20752 			 */
20753 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20754 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20755 				first_mp = mp->b_cont;
20756 				first_mp->b_flag &= ~MSGHASREF;
20757 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20758 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20759 				CONN_DEC_REF(connp);
20760 				connp = NULL;
20761 			}
20762 			if (ii->ipsec_info_type == IPSEC_IN) {
20763 				/*
20764 				 * Either this message goes back to
20765 				 * IPSEC for further processing or to
20766 				 * ULP after policy checks.
20767 				 */
20768 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20769 				return;
20770 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20771 				io = (ipsec_out_t *)ii;
20772 				if (io->ipsec_out_proc_begin) {
20773 					/*
20774 					 * IPSEC processing has already started.
20775 					 * Complete it.
20776 					 * IPQoS notes: We don't care what is
20777 					 * in ipsec_out_ill_index since this
20778 					 * won't be processed for IPQoS policies
20779 					 * in ipsec_out_process.
20780 					 */
20781 					ipsec_out_process(q, mp, NULL,
20782 					    io->ipsec_out_ill_index);
20783 					return;
20784 				} else {
20785 					connp = (q->q_next != NULL) ?
20786 					    NULL : Q_TO_CONN(q);
20787 					first_mp = mp;
20788 					mp = mp->b_cont;
20789 					mctl_present = B_TRUE;
20790 				}
20791 				zoneid = io->ipsec_out_zoneid;
20792 				ASSERT(zoneid != ALL_ZONES);
20793 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20794 				/*
20795 				 * It's an IPsec control message requesting
20796 				 * an SADB update to be sent to the IPsec
20797 				 * hardware acceleration capable ills.
20798 				 */
20799 				ipsec_ctl_t *ipsec_ctl =
20800 				    (ipsec_ctl_t *)mp->b_rptr;
20801 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20802 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20803 				mblk_t *cmp = mp->b_cont;
20804 
20805 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20806 				ASSERT(cmp != NULL);
20807 
20808 				freeb(mp);
20809 				ill_ipsec_capab_send_all(satype, cmp, sa,
20810 				    ipst->ips_netstack);
20811 				return;
20812 			} else {
20813 				/*
20814 				 * This must be ARP or special TSOL signaling.
20815 				 */
20816 				ip_wput_nondata(NULL, q, mp, NULL);
20817 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20818 				    "ip_wput_end: q %p (%S)", q, "nondata");
20819 				return;
20820 			}
20821 		} else {
20822 			/*
20823 			 * This must be non-(ARP/AH/ESP) messages.
20824 			 */
20825 			ASSERT(!need_decref);
20826 			ip_wput_nondata(NULL, q, mp, NULL);
20827 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20828 			    "ip_wput_end: q %p (%S)", q, "nondata");
20829 			return;
20830 		}
20831 	} else {
20832 		first_mp = mp;
20833 		mctl_present = B_FALSE;
20834 	}
20835 
20836 	ASSERT(first_mp != NULL);
20837 	/*
20838 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20839 	 * to make sure that this packet goes out on the same interface it
20840 	 * came in. We handle that here.
20841 	 */
20842 	if (mctl_present) {
20843 		uint_t ifindex;
20844 
20845 		io = (ipsec_out_t *)first_mp->b_rptr;
20846 		if (io->ipsec_out_attach_if ||
20847 		    io->ipsec_out_xmit_if ||
20848 		    io->ipsec_out_ip_nexthop) {
20849 			ill_t	*ill;
20850 
20851 			/*
20852 			 * We may have lost the conn context if we are
20853 			 * coming here from ip_newroute(). Copy the
20854 			 * nexthop information.
20855 			 */
20856 			if (io->ipsec_out_ip_nexthop) {
20857 				ip_nexthop = B_TRUE;
20858 				nexthop_addr = io->ipsec_out_nexthop_addr;
20859 
20860 				ipha = (ipha_t *)mp->b_rptr;
20861 				dst = ipha->ipha_dst;
20862 				goto send_from_ill;
20863 			} else {
20864 				ASSERT(io->ipsec_out_ill_index != 0);
20865 				ifindex = io->ipsec_out_ill_index;
20866 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20867 				    NULL, NULL, NULL, NULL, ipst);
20868 				/*
20869 				 * ipsec_out_xmit_if bit is used to tell
20870 				 * ip_wput to use the ill to send outgoing data
20871 				 * as we have no conn when data comes from ICMP
20872 				 * error msg routines. Currently this feature is
20873 				 * only used by ip_mrtun_forward routine.
20874 				 */
20875 				if (io->ipsec_out_xmit_if) {
20876 					xmit_ill = ill;
20877 					if (xmit_ill == NULL) {
20878 						ip1dbg(("ip_output:bad ifindex "
20879 						    "for xmit_ill %d\n",
20880 						    ifindex));
20881 						freemsg(first_mp);
20882 						BUMP_MIB(&ipst->ips_ip_mib,
20883 						    ipIfStatsOutDiscards);
20884 						ASSERT(!need_decref);
20885 						return;
20886 					}
20887 					/* Free up the ipsec_out_t mblk */
20888 					ASSERT(first_mp->b_cont == mp);
20889 					first_mp->b_cont = NULL;
20890 					freeb(first_mp);
20891 					/* Just send the IP header+ICMP+data */
20892 					first_mp = mp;
20893 					ipha = (ipha_t *)mp->b_rptr;
20894 					dst = ipha->ipha_dst;
20895 					goto send_from_ill;
20896 				} else {
20897 					attach_ill = ill;
20898 				}
20899 
20900 				if (attach_ill == NULL) {
20901 					ASSERT(xmit_ill == NULL);
20902 					ip1dbg(("ip_output: bad ifindex for "
20903 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20904 					    ifindex));
20905 					freemsg(first_mp);
20906 					BUMP_MIB(&ipst->ips_ip_mib,
20907 					    ipIfStatsOutDiscards);
20908 					ASSERT(!need_decref);
20909 					return;
20910 				}
20911 			}
20912 		}
20913 	}
20914 
20915 	ASSERT(xmit_ill == NULL);
20916 
20917 	/* We have a complete IP datagram heading outbound. */
20918 	ipha = (ipha_t *)mp->b_rptr;
20919 
20920 #ifndef SPEED_BEFORE_SAFETY
20921 	/*
20922 	 * Make sure we have a full-word aligned message and that at least
20923 	 * a simple IP header is accessible in the first message.  If not,
20924 	 * try a pullup.
20925 	 */
20926 	if (!OK_32PTR(rptr) ||
20927 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20928 	    hdrtoosmall:
20929 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20930 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20931 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20932 			if (first_mp == NULL)
20933 				first_mp = mp;
20934 			goto discard_pkt;
20935 		}
20936 
20937 		/* This function assumes that mp points to an IPv4 packet. */
20938 		if (is_system_labeled() && q->q_next == NULL &&
20939 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20940 		    !connp->conn_ulp_labeled) {
20941 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20942 			    &adjust, connp->conn_mac_exempt, ipst);
20943 			ipha = (ipha_t *)mp->b_rptr;
20944 			if (first_mp != NULL)
20945 				first_mp->b_cont = mp;
20946 			if (err != 0) {
20947 				if (first_mp == NULL)
20948 					first_mp = mp;
20949 				if (err == EINVAL)
20950 					goto icmp_parameter_problem;
20951 				ip2dbg(("ip_wput: label check failed (%d)\n",
20952 				    err));
20953 				goto discard_pkt;
20954 			}
20955 			iplen = ntohs(ipha->ipha_length) + adjust;
20956 			ipha->ipha_length = htons(iplen);
20957 		}
20958 
20959 		ipha = (ipha_t *)mp->b_rptr;
20960 		if (first_mp == NULL) {
20961 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20962 			/*
20963 			 * If we got here because of "goto hdrtoosmall"
20964 			 * We need to attach a IPSEC_OUT.
20965 			 */
20966 			if (connp->conn_out_enforce_policy) {
20967 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20968 				    NULL, ipha->ipha_protocol,
20969 				    ipst->ips_netstack)) == NULL)) {
20970 					BUMP_MIB(&ipst->ips_ip_mib,
20971 					    ipIfStatsOutDiscards);
20972 					if (need_decref)
20973 						CONN_DEC_REF(connp);
20974 					return;
20975 				} else {
20976 					ASSERT(mp->b_datap->db_type == M_CTL);
20977 					first_mp = mp;
20978 					mp = mp->b_cont;
20979 					mctl_present = B_TRUE;
20980 				}
20981 			} else {
20982 				first_mp = mp;
20983 				mctl_present = B_FALSE;
20984 			}
20985 		}
20986 	}
20987 #endif
20988 
20989 	/* Most of the code below is written for speed, not readability */
20990 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20991 
20992 	/*
20993 	 * If ip_newroute() fails, we're going to need a full
20994 	 * header for the icmp wraparound.
20995 	 */
20996 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20997 		uint_t	v_hlen;
20998 	    version_hdrlen_check:
20999 		ASSERT(first_mp != NULL);
21000 		v_hlen = V_HLEN;
21001 		/*
21002 		 * siphon off IPv6 packets coming down from transport
21003 		 * layer modules here.
21004 		 * Note: high-order bit carries NUD reachability confirmation
21005 		 */
21006 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21007 			/*
21008 			 * XXX implement a IPv4 and IPv6 packet counter per
21009 			 * conn and switch when ratio exceeds e.g. 10:1
21010 			 */
21011 #ifdef notyet
21012 			if (q->q_next == NULL) /* Avoid ill queue */
21013 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21014 #endif
21015 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21016 			ASSERT(xmit_ill == NULL);
21017 			if (attach_ill != NULL)
21018 				ill_refrele(attach_ill);
21019 			if (need_decref)
21020 				mp->b_flag |= MSGHASREF;
21021 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21022 			return;
21023 		}
21024 
21025 		if ((v_hlen >> 4) != IP_VERSION) {
21026 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21027 			    "ip_wput_end: q %p (%S)", q, "badvers");
21028 			goto discard_pkt;
21029 		}
21030 		/*
21031 		 * Is the header length at least 20 bytes?
21032 		 *
21033 		 * Are there enough bytes accessible in the header?  If
21034 		 * not, try a pullup.
21035 		 */
21036 		v_hlen &= 0xF;
21037 		v_hlen <<= 2;
21038 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21039 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21040 			    "ip_wput_end: q %p (%S)", q, "badlen");
21041 			goto discard_pkt;
21042 		}
21043 		if (v_hlen > (mp->b_wptr - rptr)) {
21044 			if (!pullupmsg(mp, v_hlen)) {
21045 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21046 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21047 				goto discard_pkt;
21048 			}
21049 			ipha = (ipha_t *)mp->b_rptr;
21050 		}
21051 		/*
21052 		 * Move first entry from any source route into ipha_dst and
21053 		 * verify the options
21054 		 */
21055 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21056 			zoneid, ipst)) {
21057 			ASSERT(xmit_ill == NULL);
21058 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21059 			if (attach_ill != NULL)
21060 				ill_refrele(attach_ill);
21061 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21062 			    "ip_wput_end: q %p (%S)", q, "badopts");
21063 			if (need_decref)
21064 				CONN_DEC_REF(connp);
21065 			return;
21066 		}
21067 	}
21068 	dst = ipha->ipha_dst;
21069 
21070 	/*
21071 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21072 	 * we have to run the packet through ip_newroute which will take
21073 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21074 	 * a resolver, or assigning a default gateway, etc.
21075 	 */
21076 	if (CLASSD(dst)) {
21077 		ipif_t	*ipif;
21078 		uint32_t setsrc = 0;
21079 
21080 	    multicast:
21081 		ASSERT(first_mp != NULL);
21082 		ip2dbg(("ip_wput: CLASSD\n"));
21083 		if (connp == NULL) {
21084 			/*
21085 			 * Use the first good ipif on the ill.
21086 			 * XXX Should this ever happen? (Appears
21087 			 * to show up with just ppp and no ethernet due
21088 			 * to in.rdisc.)
21089 			 * However, ire_send should be able to
21090 			 * call ip_wput_ire directly.
21091 			 *
21092 			 * XXX Also, this can happen for ICMP and other packets
21093 			 * with multicast source addresses.  Perhaps we should
21094 			 * fix things so that we drop the packet in question,
21095 			 * but for now, just run with it.
21096 			 */
21097 			ill_t *ill = (ill_t *)q->q_ptr;
21098 
21099 			/*
21100 			 * Don't honor attach_if for this case. If ill
21101 			 * is part of the group, ipif could belong to
21102 			 * any ill and we cannot maintain attach_ill
21103 			 * and ipif_ill same anymore and the assert
21104 			 * below would fail.
21105 			 */
21106 			if (mctl_present && io->ipsec_out_attach_if) {
21107 				io->ipsec_out_ill_index = 0;
21108 				io->ipsec_out_attach_if = B_FALSE;
21109 				ASSERT(attach_ill != NULL);
21110 				ill_refrele(attach_ill);
21111 				attach_ill = NULL;
21112 			}
21113 
21114 			ASSERT(attach_ill == NULL);
21115 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21116 			if (ipif == NULL) {
21117 				if (need_decref)
21118 					CONN_DEC_REF(connp);
21119 				freemsg(first_mp);
21120 				return;
21121 			}
21122 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21123 			    ntohl(dst), ill->ill_name));
21124 		} else {
21125 			/*
21126 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21127 			 * and IP_MULTICAST_IF.
21128 			 * Block comment above this function explains the
21129 			 * locking mechanism used here
21130 			 */
21131 			if (xmit_ill == NULL) {
21132 				xmit_ill = conn_get_held_ill(connp,
21133 				    &connp->conn_xmit_if_ill, &err);
21134 				if (err == ILL_LOOKUP_FAILED) {
21135 					ip1dbg(("ip_wput: No ill for "
21136 					    "IP_XMIT_IF\n"));
21137 					BUMP_MIB(&ipst->ips_ip_mib,
21138 					    ipIfStatsOutNoRoutes);
21139 					goto drop_pkt;
21140 				}
21141 			}
21142 
21143 			if (xmit_ill == NULL) {
21144 				ipif = conn_get_held_ipif(connp,
21145 				    &connp->conn_multicast_ipif, &err);
21146 				if (err == IPIF_LOOKUP_FAILED) {
21147 					ip1dbg(("ip_wput: No ipif for "
21148 					    "multicast\n"));
21149 					BUMP_MIB(&ipst->ips_ip_mib,
21150 					    ipIfStatsOutNoRoutes);
21151 					goto drop_pkt;
21152 				}
21153 			}
21154 			if (xmit_ill != NULL) {
21155 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21156 				if (ipif == NULL) {
21157 					ip1dbg(("ip_wput: No ipif for "
21158 					    "IP_XMIT_IF\n"));
21159 					BUMP_MIB(&ipst->ips_ip_mib,
21160 					    ipIfStatsOutNoRoutes);
21161 					goto drop_pkt;
21162 				}
21163 			} else if (ipif == NULL || ipif->ipif_isv6) {
21164 				/*
21165 				 * We must do this ipif determination here
21166 				 * else we could pass through ip_newroute
21167 				 * and come back here without the conn context.
21168 				 *
21169 				 * Note: we do late binding i.e. we bind to
21170 				 * the interface when the first packet is sent.
21171 				 * For performance reasons we do not rebind on
21172 				 * each packet but keep the binding until the
21173 				 * next IP_MULTICAST_IF option.
21174 				 *
21175 				 * conn_multicast_{ipif,ill} are shared between
21176 				 * IPv4 and IPv6 and AF_INET6 sockets can
21177 				 * send both IPv4 and IPv6 packets. Hence
21178 				 * we have to check that "isv6" matches above.
21179 				 */
21180 				if (ipif != NULL)
21181 					ipif_refrele(ipif);
21182 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21183 				if (ipif == NULL) {
21184 					ip1dbg(("ip_wput: No ipif for "
21185 					    "multicast\n"));
21186 					BUMP_MIB(&ipst->ips_ip_mib,
21187 					    ipIfStatsOutNoRoutes);
21188 					goto drop_pkt;
21189 				}
21190 				err = conn_set_held_ipif(connp,
21191 				    &connp->conn_multicast_ipif, ipif);
21192 				if (err == IPIF_LOOKUP_FAILED) {
21193 					ipif_refrele(ipif);
21194 					ip1dbg(("ip_wput: No ipif for "
21195 					    "multicast\n"));
21196 					BUMP_MIB(&ipst->ips_ip_mib,
21197 					    ipIfStatsOutNoRoutes);
21198 					goto drop_pkt;
21199 				}
21200 			}
21201 		}
21202 		ASSERT(!ipif->ipif_isv6);
21203 		/*
21204 		 * As we may lose the conn by the time we reach ip_wput_ire,
21205 		 * we copy conn_multicast_loop and conn_dontroute on to an
21206 		 * ipsec_out. In case if this datagram goes out secure,
21207 		 * we need the ill_index also. Copy that also into the
21208 		 * ipsec_out.
21209 		 */
21210 		if (mctl_present) {
21211 			io = (ipsec_out_t *)first_mp->b_rptr;
21212 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21213 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21214 		} else {
21215 			ASSERT(mp == first_mp);
21216 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21217 			    BPRI_HI)) == NULL) {
21218 				ipif_refrele(ipif);
21219 				first_mp = mp;
21220 				goto discard_pkt;
21221 			}
21222 			first_mp->b_datap->db_type = M_CTL;
21223 			first_mp->b_wptr += sizeof (ipsec_info_t);
21224 			/* ipsec_out_secure is B_FALSE now */
21225 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21226 			io = (ipsec_out_t *)first_mp->b_rptr;
21227 			io->ipsec_out_type = IPSEC_OUT;
21228 			io->ipsec_out_len = sizeof (ipsec_out_t);
21229 			io->ipsec_out_use_global_policy = B_TRUE;
21230 			io->ipsec_out_ns = ipst->ips_netstack;
21231 			first_mp->b_cont = mp;
21232 			mctl_present = B_TRUE;
21233 		}
21234 		if (attach_ill != NULL) {
21235 			ASSERT(attach_ill == ipif->ipif_ill);
21236 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21237 
21238 			/*
21239 			 * Check if we need an ire that will not be
21240 			 * looked up by anybody else i.e. HIDDEN.
21241 			 */
21242 			if (ill_is_probeonly(attach_ill)) {
21243 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21244 			}
21245 			io->ipsec_out_ill_index =
21246 			    attach_ill->ill_phyint->phyint_ifindex;
21247 			io->ipsec_out_attach_if = B_TRUE;
21248 		} else {
21249 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21250 			io->ipsec_out_ill_index =
21251 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21252 		}
21253 		if (connp != NULL) {
21254 			io->ipsec_out_multicast_loop =
21255 			    connp->conn_multicast_loop;
21256 			io->ipsec_out_dontroute = connp->conn_dontroute;
21257 			io->ipsec_out_zoneid = connp->conn_zoneid;
21258 		}
21259 		/*
21260 		 * If the application uses IP_MULTICAST_IF with
21261 		 * different logical addresses of the same ILL, we
21262 		 * need to make sure that the soruce address of
21263 		 * the packet matches the logical IP address used
21264 		 * in the option. We do it by initializing ipha_src
21265 		 * here. This should keep IPSEC also happy as
21266 		 * when we return from IPSEC processing, we don't
21267 		 * have to worry about getting the right address on
21268 		 * the packet. Thus it is sufficient to look for
21269 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21270 		 * MATCH_IRE_IPIF.
21271 		 *
21272 		 * NOTE : We need to do it for non-secure case also as
21273 		 * this might go out secure if there is a global policy
21274 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21275 		 * address, the source should be initialized already and
21276 		 * hence we won't be initializing here.
21277 		 *
21278 		 * As we do not have the ire yet, it is possible that
21279 		 * we set the source address here and then later discover
21280 		 * that the ire implies the source address to be assigned
21281 		 * through the RTF_SETSRC flag.
21282 		 * In that case, the setsrc variable will remind us
21283 		 * that overwritting the source address by the one
21284 		 * of the RTF_SETSRC-flagged ire is allowed.
21285 		 */
21286 		if (ipha->ipha_src == INADDR_ANY &&
21287 		    (connp == NULL || !connp->conn_unspec_src)) {
21288 			ipha->ipha_src = ipif->ipif_src_addr;
21289 			setsrc = RTF_SETSRC;
21290 		}
21291 		/*
21292 		 * Find an IRE which matches the destination and the outgoing
21293 		 * queue (i.e. the outgoing interface.)
21294 		 * For loopback use a unicast IP address for
21295 		 * the ire lookup.
21296 		 */
21297 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
21298 		    PHYI_LOOPBACK) {
21299 			dst = ipif->ipif_lcl_addr;
21300 		}
21301 		/*
21302 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21303 		 * We don't need to lookup ire in ctable as the packet
21304 		 * needs to be sent to the destination through the specified
21305 		 * ill irrespective of ires in the cache table.
21306 		 */
21307 		ire = NULL;
21308 		if (xmit_ill == NULL) {
21309 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21310 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21311 		}
21312 
21313 		/*
21314 		 * refrele attach_ill as its not needed anymore.
21315 		 */
21316 		if (attach_ill != NULL) {
21317 			ill_refrele(attach_ill);
21318 			attach_ill = NULL;
21319 		}
21320 
21321 		if (ire == NULL) {
21322 			/*
21323 			 * Multicast loopback and multicast forwarding is
21324 			 * done in ip_wput_ire.
21325 			 *
21326 			 * Mark this packet to make it be delivered to
21327 			 * ip_wput_ire after the new ire has been
21328 			 * created.
21329 			 *
21330 			 * The call to ip_newroute_ipif takes into account
21331 			 * the setsrc reminder. In any case, we take care
21332 			 * of the RTF_MULTIRT flag.
21333 			 */
21334 			mp->b_prev = mp->b_next = NULL;
21335 			if (xmit_ill == NULL ||
21336 			    xmit_ill->ill_ipif_up_count > 0) {
21337 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21338 				    setsrc | RTF_MULTIRT, zoneid, infop);
21339 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21340 				    "ip_wput_end: q %p (%S)", q, "noire");
21341 			} else {
21342 				freemsg(first_mp);
21343 			}
21344 			ipif_refrele(ipif);
21345 			if (xmit_ill != NULL)
21346 				ill_refrele(xmit_ill);
21347 			if (need_decref)
21348 				CONN_DEC_REF(connp);
21349 			return;
21350 		}
21351 
21352 		ipif_refrele(ipif);
21353 		ipif = NULL;
21354 		ASSERT(xmit_ill == NULL);
21355 
21356 		/*
21357 		 * Honor the RTF_SETSRC flag for multicast packets,
21358 		 * if allowed by the setsrc reminder.
21359 		 */
21360 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21361 			ipha->ipha_src = ire->ire_src_addr;
21362 		}
21363 
21364 		/*
21365 		 * Unconditionally force the TTL to 1 for
21366 		 * multirouted multicast packets:
21367 		 * multirouted multicast should not cross
21368 		 * multicast routers.
21369 		 */
21370 		if (ire->ire_flags & RTF_MULTIRT) {
21371 			if (ipha->ipha_ttl > 1) {
21372 				ip2dbg(("ip_wput: forcing multicast "
21373 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21374 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21375 				ipha->ipha_ttl = 1;
21376 			}
21377 		}
21378 	} else {
21379 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21380 		if ((ire != NULL) && (ire->ire_type &
21381 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21382 			ignore_dontroute = B_TRUE;
21383 			ignore_nexthop = B_TRUE;
21384 		}
21385 		if (ire != NULL) {
21386 			ire_refrele(ire);
21387 			ire = NULL;
21388 		}
21389 		/*
21390 		 * Guard against coming in from arp in which case conn is NULL.
21391 		 * Also guard against non M_DATA with dontroute set but
21392 		 * destined to local, loopback or broadcast addresses.
21393 		 */
21394 		if (connp != NULL && connp->conn_dontroute &&
21395 		    !ignore_dontroute) {
21396 dontroute:
21397 			/*
21398 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21399 			 * routing protocols from seeing false direct
21400 			 * connectivity.
21401 			 */
21402 			ipha->ipha_ttl = 1;
21403 			/*
21404 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21405 			 * along with SO_DONTROUTE, higher precedence is
21406 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21407 			 */
21408 			if (connp->conn_xmit_if_ill == NULL) {
21409 				/* If suitable ipif not found, drop packet */
21410 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21411 				    ipst);
21412 				if (dst_ipif == NULL) {
21413 					ip1dbg(("ip_wput: no route for "
21414 					    "dst using SO_DONTROUTE\n"));
21415 					BUMP_MIB(&ipst->ips_ip_mib,
21416 					    ipIfStatsOutNoRoutes);
21417 					mp->b_prev = mp->b_next = NULL;
21418 					if (first_mp == NULL)
21419 						first_mp = mp;
21420 					goto drop_pkt;
21421 				} else {
21422 					/*
21423 					 * If suitable ipif has been found, set
21424 					 * xmit_ill to the corresponding
21425 					 * ipif_ill because we'll be following
21426 					 * the IP_XMIT_IF logic.
21427 					 */
21428 					ASSERT(xmit_ill == NULL);
21429 					xmit_ill = dst_ipif->ipif_ill;
21430 					mutex_enter(&xmit_ill->ill_lock);
21431 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21432 						mutex_exit(&xmit_ill->ill_lock);
21433 						xmit_ill = NULL;
21434 						ipif_refrele(dst_ipif);
21435 						ip1dbg(("ip_wput: no route for"
21436 						    " dst using"
21437 						    " SO_DONTROUTE\n"));
21438 						BUMP_MIB(&ipst->ips_ip_mib,
21439 						    ipIfStatsOutNoRoutes);
21440 						mp->b_prev = mp->b_next = NULL;
21441 						if (first_mp == NULL)
21442 							first_mp = mp;
21443 						goto drop_pkt;
21444 					}
21445 					ill_refhold_locked(xmit_ill);
21446 					mutex_exit(&xmit_ill->ill_lock);
21447 					ipif_refrele(dst_ipif);
21448 				}
21449 			}
21450 
21451 		}
21452 		/*
21453 		 * If we are bound to IPIF_NOFAILOVER address, look for
21454 		 * an IRE_CACHE matching the ill.
21455 		 */
21456 send_from_ill:
21457 		if (attach_ill != NULL) {
21458 			ipif_t	*attach_ipif;
21459 
21460 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21461 
21462 			/*
21463 			 * Check if we need an ire that will not be
21464 			 * looked up by anybody else i.e. HIDDEN.
21465 			 */
21466 			if (ill_is_probeonly(attach_ill)) {
21467 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21468 			}
21469 
21470 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21471 			if (attach_ipif == NULL) {
21472 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21473 				goto discard_pkt;
21474 			}
21475 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21476 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21477 			ipif_refrele(attach_ipif);
21478 		} else if (xmit_ill != NULL || (connp != NULL &&
21479 			    connp->conn_xmit_if_ill != NULL)) {
21480 			/*
21481 			 * Mark this packet as originated locally
21482 			 */
21483 			mp->b_prev = mp->b_next = NULL;
21484 			/*
21485 			 * xmit_ill could be NULL if SO_DONTROUTE
21486 			 * is also set.
21487 			 */
21488 			if (xmit_ill == NULL) {
21489 				xmit_ill = conn_get_held_ill(connp,
21490 				    &connp->conn_xmit_if_ill, &err);
21491 				if (err == ILL_LOOKUP_FAILED) {
21492 					BUMP_MIB(&ipst->ips_ip_mib,
21493 					    ipIfStatsOutDiscards);
21494 					if (need_decref)
21495 						CONN_DEC_REF(connp);
21496 					freemsg(first_mp);
21497 					return;
21498 				}
21499 				if (xmit_ill == NULL) {
21500 					if (connp->conn_dontroute)
21501 						goto dontroute;
21502 					goto send_from_ill;
21503 				}
21504 			}
21505 			/*
21506 			 * Could be SO_DONTROUTE case also.
21507 			 * check at least one interface is UP as
21508 			 * specified by this ILL
21509 			 */
21510 			if (xmit_ill->ill_ipif_up_count > 0) {
21511 				ipif_t *ipif;
21512 
21513 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21514 				if (ipif == NULL) {
21515 					ip1dbg(("ip_output: "
21516 					    "xmit_ill NULL ipif\n"));
21517 					goto drop_pkt;
21518 				}
21519 				/*
21520 				 * Look for a ire that is part of the group,
21521 				 * if found use it else call ip_newroute_ipif.
21522 				 * IPCL_ZONEID is not used for matching because
21523 				 * IP_ALLZONES option is valid only when the
21524 				 * ill is accessible from all zones i.e has a
21525 				 * valid ipif in all zones.
21526 				 */
21527 				match_flags = MATCH_IRE_ILL_GROUP |
21528 				    MATCH_IRE_SECATTR;
21529 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21530 				    MBLK_GETLABEL(mp), match_flags, ipst);
21531 				/*
21532 				 * If an ire exists use it or else create
21533 				 * an ire but don't add it to the cache.
21534 				 * Adding an ire may cause issues with
21535 				 * asymmetric routing.
21536 				 * In case of multiroute always act as if
21537 				 * ire does not exist.
21538 				 */
21539 				if (ire == NULL ||
21540 				    ire->ire_flags & RTF_MULTIRT) {
21541 					if (ire != NULL)
21542 						ire_refrele(ire);
21543 					ip_newroute_ipif(q, first_mp, ipif,
21544 					    dst, connp, 0, zoneid, infop);
21545 					ipif_refrele(ipif);
21546 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21547 					ill_refrele(xmit_ill);
21548 					if (need_decref)
21549 						CONN_DEC_REF(connp);
21550 					return;
21551 				}
21552 				ipif_refrele(ipif);
21553 			} else {
21554 				goto drop_pkt;
21555 			}
21556 		} else if (ip_nexthop || (connp != NULL &&
21557 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21558 			if (!ip_nexthop) {
21559 				ip_nexthop = B_TRUE;
21560 				nexthop_addr = connp->conn_nexthop_v4;
21561 			}
21562 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21563 			    MATCH_IRE_GW;
21564 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21565 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21566 		} else {
21567 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21568 			    ipst);
21569 		}
21570 		if (!ire) {
21571 			/*
21572 			 * Make sure we don't load spread if this
21573 			 * is IPIF_NOFAILOVER case.
21574 			 */
21575 			if ((attach_ill != NULL) ||
21576 			    (ip_nexthop && !ignore_nexthop)) {
21577 				if (mctl_present) {
21578 					io = (ipsec_out_t *)first_mp->b_rptr;
21579 					ASSERT(first_mp->b_datap->db_type ==
21580 					    M_CTL);
21581 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21582 				} else {
21583 					ASSERT(mp == first_mp);
21584 					first_mp = allocb(
21585 					    sizeof (ipsec_info_t), BPRI_HI);
21586 					if (first_mp == NULL) {
21587 						first_mp = mp;
21588 						goto discard_pkt;
21589 					}
21590 					first_mp->b_datap->db_type = M_CTL;
21591 					first_mp->b_wptr +=
21592 					    sizeof (ipsec_info_t);
21593 					/* ipsec_out_secure is B_FALSE now */
21594 					bzero(first_mp->b_rptr,
21595 					    sizeof (ipsec_info_t));
21596 					io = (ipsec_out_t *)first_mp->b_rptr;
21597 					io->ipsec_out_type = IPSEC_OUT;
21598 					io->ipsec_out_len =
21599 					    sizeof (ipsec_out_t);
21600 					io->ipsec_out_use_global_policy =
21601 					    B_TRUE;
21602 					io->ipsec_out_ns = ipst->ips_netstack;
21603 					first_mp->b_cont = mp;
21604 					mctl_present = B_TRUE;
21605 				}
21606 				if (attach_ill != NULL) {
21607 					io->ipsec_out_ill_index = attach_ill->
21608 					    ill_phyint->phyint_ifindex;
21609 					io->ipsec_out_attach_if = B_TRUE;
21610 				} else {
21611 					io->ipsec_out_ip_nexthop = ip_nexthop;
21612 					io->ipsec_out_nexthop_addr =
21613 					    nexthop_addr;
21614 				}
21615 			}
21616 noirefound:
21617 			/*
21618 			 * Mark this packet as having originated on
21619 			 * this machine.  This will be noted in
21620 			 * ire_add_then_send, which needs to know
21621 			 * whether to run it back through ip_wput or
21622 			 * ip_rput following successful resolution.
21623 			 */
21624 			mp->b_prev = NULL;
21625 			mp->b_next = NULL;
21626 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21627 			    ipst);
21628 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21629 			    "ip_wput_end: q %p (%S)", q, "newroute");
21630 			if (attach_ill != NULL)
21631 				ill_refrele(attach_ill);
21632 			if (xmit_ill != NULL)
21633 				ill_refrele(xmit_ill);
21634 			if (need_decref)
21635 				CONN_DEC_REF(connp);
21636 			return;
21637 		}
21638 	}
21639 
21640 	/* We now know where we are going with it. */
21641 
21642 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21643 	    "ip_wput_end: q %p (%S)", q, "end");
21644 
21645 	/*
21646 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21647 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21648 	 */
21649 	if (ire->ire_flags & RTF_MULTIRT) {
21650 		/*
21651 		 * Force the TTL of multirouted packets if required.
21652 		 * The TTL of such packets is bounded by the
21653 		 * ip_multirt_ttl ndd variable.
21654 		 */
21655 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21656 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21657 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21658 			    "(was %d), dst 0x%08x\n",
21659 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21660 			    ntohl(ire->ire_addr)));
21661 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21662 		}
21663 		/*
21664 		 * At this point, we check to see if there are any pending
21665 		 * unresolved routes. ire_multirt_resolvable()
21666 		 * checks in O(n) that all IRE_OFFSUBNET ire
21667 		 * entries for the packet's destination and
21668 		 * flagged RTF_MULTIRT are currently resolved.
21669 		 * If some remain unresolved, we make a copy
21670 		 * of the current message. It will be used
21671 		 * to initiate additional route resolutions.
21672 		 */
21673 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21674 		    MBLK_GETLABEL(first_mp), ipst);
21675 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21676 		    "multirt_need_resolve %d, first_mp %p\n",
21677 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21678 		if (multirt_need_resolve) {
21679 			copy_mp = copymsg(first_mp);
21680 			if (copy_mp != NULL) {
21681 				MULTIRT_DEBUG_TAG(copy_mp);
21682 			}
21683 		}
21684 	}
21685 
21686 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21687 	/*
21688 	 * Try to resolve another multiroute if
21689 	 * ire_multirt_resolvable() deemed it necessary.
21690 	 * At this point, we need to distinguish
21691 	 * multicasts from other packets. For multicasts,
21692 	 * we call ip_newroute_ipif() and request that both
21693 	 * multirouting and setsrc flags are checked.
21694 	 */
21695 	if (copy_mp != NULL) {
21696 		if (CLASSD(dst)) {
21697 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21698 			if (ipif) {
21699 				ASSERT(infop->ip_opt_ill_index == 0);
21700 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21701 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21702 				ipif_refrele(ipif);
21703 			} else {
21704 				MULTIRT_DEBUG_UNTAG(copy_mp);
21705 				freemsg(copy_mp);
21706 				copy_mp = NULL;
21707 			}
21708 		} else {
21709 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21710 		}
21711 	}
21712 	if (attach_ill != NULL)
21713 		ill_refrele(attach_ill);
21714 	if (xmit_ill != NULL)
21715 		ill_refrele(xmit_ill);
21716 	if (need_decref)
21717 		CONN_DEC_REF(connp);
21718 	return;
21719 
21720 icmp_parameter_problem:
21721 	/* could not have originated externally */
21722 	ASSERT(mp->b_prev == NULL);
21723 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21724 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21725 		/* it's the IP header length that's in trouble */
21726 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21727 		first_mp = NULL;
21728 	}
21729 
21730 discard_pkt:
21731 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21732 drop_pkt:
21733 	ip1dbg(("ip_wput: dropped packet\n"));
21734 	if (ire != NULL)
21735 		ire_refrele(ire);
21736 	if (need_decref)
21737 		CONN_DEC_REF(connp);
21738 	freemsg(first_mp);
21739 	if (attach_ill != NULL)
21740 		ill_refrele(attach_ill);
21741 	if (xmit_ill != NULL)
21742 		ill_refrele(xmit_ill);
21743 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21744 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21745 }
21746 
21747 /*
21748  * If this is a conn_t queue, then we pass in the conn. This includes the
21749  * zoneid.
21750  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21751  * in which case we use the global zoneid since those are all part of
21752  * the global zone.
21753  */
21754 void
21755 ip_wput(queue_t *q, mblk_t *mp)
21756 {
21757 	if (CONN_Q(q))
21758 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21759 	else
21760 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21761 }
21762 
21763 /*
21764  *
21765  * The following rules must be observed when accessing any ipif or ill
21766  * that has been cached in the conn. Typically conn_nofailover_ill,
21767  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21768  *
21769  * Access: The ipif or ill pointed to from the conn can be accessed under
21770  * the protection of the conn_lock or after it has been refheld under the
21771  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21772  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21773  * The reason for this is that a concurrent unplumb could actually be
21774  * cleaning up these cached pointers by walking the conns and might have
21775  * finished cleaning up the conn in question. The macros check that an
21776  * unplumb has not yet started on the ipif or ill.
21777  *
21778  * Caching: An ipif or ill pointer may be cached in the conn only after
21779  * making sure that an unplumb has not started. So the caching is done
21780  * while holding both the conn_lock and the ill_lock and after using the
21781  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21782  * flag before starting the cleanup of conns.
21783  *
21784  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21785  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21786  * or a reference to the ipif or a reference to an ire that references the
21787  * ipif. An ipif does not change its ill except for failover/failback. Since
21788  * failover/failback happens only after bringing down the ipif and making sure
21789  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21790  * the above holds.
21791  */
21792 ipif_t *
21793 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21794 {
21795 	ipif_t	*ipif;
21796 	ill_t	*ill;
21797 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21798 
21799 	*err = 0;
21800 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21801 	mutex_enter(&connp->conn_lock);
21802 	ipif = *ipifp;
21803 	if (ipif != NULL) {
21804 		ill = ipif->ipif_ill;
21805 		mutex_enter(&ill->ill_lock);
21806 		if (IPIF_CAN_LOOKUP(ipif)) {
21807 			ipif_refhold_locked(ipif);
21808 			mutex_exit(&ill->ill_lock);
21809 			mutex_exit(&connp->conn_lock);
21810 			rw_exit(&ipst->ips_ill_g_lock);
21811 			return (ipif);
21812 		} else {
21813 			*err = IPIF_LOOKUP_FAILED;
21814 		}
21815 		mutex_exit(&ill->ill_lock);
21816 	}
21817 	mutex_exit(&connp->conn_lock);
21818 	rw_exit(&ipst->ips_ill_g_lock);
21819 	return (NULL);
21820 }
21821 
21822 ill_t *
21823 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21824 {
21825 	ill_t	*ill;
21826 
21827 	*err = 0;
21828 	mutex_enter(&connp->conn_lock);
21829 	ill = *illp;
21830 	if (ill != NULL) {
21831 		mutex_enter(&ill->ill_lock);
21832 		if (ILL_CAN_LOOKUP(ill)) {
21833 			ill_refhold_locked(ill);
21834 			mutex_exit(&ill->ill_lock);
21835 			mutex_exit(&connp->conn_lock);
21836 			return (ill);
21837 		} else {
21838 			*err = ILL_LOOKUP_FAILED;
21839 		}
21840 		mutex_exit(&ill->ill_lock);
21841 	}
21842 	mutex_exit(&connp->conn_lock);
21843 	return (NULL);
21844 }
21845 
21846 static int
21847 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21848 {
21849 	ill_t	*ill;
21850 
21851 	ill = ipif->ipif_ill;
21852 	mutex_enter(&connp->conn_lock);
21853 	mutex_enter(&ill->ill_lock);
21854 	if (IPIF_CAN_LOOKUP(ipif)) {
21855 		*ipifp = ipif;
21856 		mutex_exit(&ill->ill_lock);
21857 		mutex_exit(&connp->conn_lock);
21858 		return (0);
21859 	}
21860 	mutex_exit(&ill->ill_lock);
21861 	mutex_exit(&connp->conn_lock);
21862 	return (IPIF_LOOKUP_FAILED);
21863 }
21864 
21865 /*
21866  * This is called if the outbound datagram needs fragmentation.
21867  *
21868  * NOTE : This function does not ire_refrele the ire argument passed in.
21869  */
21870 static void
21871 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21872     ip_stack_t *ipst)
21873 {
21874 	ipha_t		*ipha;
21875 	mblk_t		*mp;
21876 	uint32_t	v_hlen_tos_len;
21877 	uint32_t	max_frag;
21878 	uint32_t	frag_flag;
21879 	boolean_t	dont_use;
21880 
21881 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21882 		mp = ipsec_mp->b_cont;
21883 	} else {
21884 		mp = ipsec_mp;
21885 	}
21886 
21887 	ipha = (ipha_t *)mp->b_rptr;
21888 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21889 
21890 #ifdef	_BIG_ENDIAN
21891 #define	V_HLEN	(v_hlen_tos_len >> 24)
21892 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21893 #else
21894 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21895 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21896 #endif
21897 
21898 #ifndef SPEED_BEFORE_SAFETY
21899 	/*
21900 	 * Check that ipha_length is consistent with
21901 	 * the mblk length
21902 	 */
21903 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21904 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21905 		    LENGTH, msgdsize(mp)));
21906 		freemsg(ipsec_mp);
21907 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21908 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21909 		    "packet length mismatch");
21910 		return;
21911 	}
21912 #endif
21913 	/*
21914 	 * Don't use frag_flag if pre-built packet or source
21915 	 * routed or if multicast (since multicast packets do not solicit
21916 	 * ICMP "packet too big" messages). Get the values of
21917 	 * max_frag and frag_flag atomically by acquiring the
21918 	 * ire_lock.
21919 	 */
21920 	mutex_enter(&ire->ire_lock);
21921 	max_frag = ire->ire_max_frag;
21922 	frag_flag = ire->ire_frag_flag;
21923 	mutex_exit(&ire->ire_lock);
21924 
21925 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21926 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21927 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21928 
21929 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21930 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21931 }
21932 
21933 /*
21934  * Used for deciding the MSS size for the upper layer. Thus
21935  * we need to check the outbound policy values in the conn.
21936  */
21937 int
21938 conn_ipsec_length(conn_t *connp)
21939 {
21940 	ipsec_latch_t *ipl;
21941 
21942 	ipl = connp->conn_latch;
21943 	if (ipl == NULL)
21944 		return (0);
21945 
21946 	if (ipl->ipl_out_policy == NULL)
21947 		return (0);
21948 
21949 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21950 }
21951 
21952 /*
21953  * Returns an estimate of the IPSEC headers size. This is used if
21954  * we don't want to call into IPSEC to get the exact size.
21955  */
21956 int
21957 ipsec_out_extra_length(mblk_t *ipsec_mp)
21958 {
21959 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21960 	ipsec_action_t *a;
21961 
21962 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21963 	if (!io->ipsec_out_secure)
21964 		return (0);
21965 
21966 	a = io->ipsec_out_act;
21967 
21968 	if (a == NULL) {
21969 		ASSERT(io->ipsec_out_policy != NULL);
21970 		a = io->ipsec_out_policy->ipsp_act;
21971 	}
21972 	ASSERT(a != NULL);
21973 
21974 	return (a->ipa_ovhd);
21975 }
21976 
21977 /*
21978  * Returns an estimate of the IPSEC headers size. This is used if
21979  * we don't want to call into IPSEC to get the exact size.
21980  */
21981 int
21982 ipsec_in_extra_length(mblk_t *ipsec_mp)
21983 {
21984 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21985 	ipsec_action_t *a;
21986 
21987 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21988 
21989 	a = ii->ipsec_in_action;
21990 	return (a == NULL ? 0 : a->ipa_ovhd);
21991 }
21992 
21993 /*
21994  * If there are any source route options, return the true final
21995  * destination. Otherwise, return the destination.
21996  */
21997 ipaddr_t
21998 ip_get_dst(ipha_t *ipha)
21999 {
22000 	ipoptp_t	opts;
22001 	uchar_t		*opt;
22002 	uint8_t		optval;
22003 	uint8_t		optlen;
22004 	ipaddr_t	dst;
22005 	uint32_t off;
22006 
22007 	dst = ipha->ipha_dst;
22008 
22009 	if (IS_SIMPLE_IPH(ipha))
22010 		return (dst);
22011 
22012 	for (optval = ipoptp_first(&opts, ipha);
22013 	    optval != IPOPT_EOL;
22014 	    optval = ipoptp_next(&opts)) {
22015 		opt = opts.ipoptp_cur;
22016 		optlen = opts.ipoptp_len;
22017 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22018 		switch (optval) {
22019 		case IPOPT_SSRR:
22020 		case IPOPT_LSRR:
22021 			off = opt[IPOPT_OFFSET];
22022 			/*
22023 			 * If one of the conditions is true, it means
22024 			 * end of options and dst already has the right
22025 			 * value.
22026 			 */
22027 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22028 				off = optlen - IP_ADDR_LEN;
22029 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22030 			}
22031 			return (dst);
22032 		default:
22033 			break;
22034 		}
22035 	}
22036 
22037 	return (dst);
22038 }
22039 
22040 mblk_t *
22041 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22042     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22043 {
22044 	ipsec_out_t	*io;
22045 	mblk_t		*first_mp;
22046 	boolean_t policy_present;
22047 	ip_stack_t	*ipst;
22048 	ipsec_stack_t	*ipss;
22049 
22050 	ASSERT(ire != NULL);
22051 	ipst = ire->ire_ipst;
22052 	ipss = ipst->ips_netstack->netstack_ipsec;
22053 
22054 	first_mp = mp;
22055 	if (mp->b_datap->db_type == M_CTL) {
22056 		io = (ipsec_out_t *)first_mp->b_rptr;
22057 		/*
22058 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22059 		 *
22060 		 * 1) There is per-socket policy (including cached global
22061 		 *    policy) or a policy on the IP-in-IP tunnel.
22062 		 * 2) There is no per-socket policy, but it is
22063 		 *    a multicast packet that needs to go out
22064 		 *    on a specific interface. This is the case
22065 		 *    where (ip_wput and ip_wput_multicast) attaches
22066 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22067 		 *
22068 		 * In case (2) we check with global policy to
22069 		 * see if there is a match and set the ill_index
22070 		 * appropriately so that we can lookup the ire
22071 		 * properly in ip_wput_ipsec_out.
22072 		 */
22073 
22074 		/*
22075 		 * ipsec_out_use_global_policy is set to B_FALSE
22076 		 * in ipsec_in_to_out(). Refer to that function for
22077 		 * details.
22078 		 */
22079 		if ((io->ipsec_out_latch == NULL) &&
22080 		    (io->ipsec_out_use_global_policy)) {
22081 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22082 				    ire, connp, unspec_src, zoneid));
22083 		}
22084 		if (!io->ipsec_out_secure) {
22085 			/*
22086 			 * If this is not a secure packet, drop
22087 			 * the IPSEC_OUT mp and treat it as a clear
22088 			 * packet. This happens when we are sending
22089 			 * a ICMP reply back to a clear packet. See
22090 			 * ipsec_in_to_out() for details.
22091 			 */
22092 			mp = first_mp->b_cont;
22093 			freeb(first_mp);
22094 		}
22095 		return (mp);
22096 	}
22097 	/*
22098 	 * See whether we need to attach a global policy here. We
22099 	 * don't depend on the conn (as it could be null) for deciding
22100 	 * what policy this datagram should go through because it
22101 	 * should have happened in ip_wput if there was some
22102 	 * policy. This normally happens for connections which are not
22103 	 * fully bound preventing us from caching policies in
22104 	 * ip_bind. Packets coming from the TCP listener/global queue
22105 	 * - which are non-hard_bound - could also be affected by
22106 	 * applying policy here.
22107 	 *
22108 	 * If this packet is coming from tcp global queue or listener,
22109 	 * we will be applying policy here.  This may not be *right*
22110 	 * if these packets are coming from the detached connection as
22111 	 * it could have gone in clear before. This happens only if a
22112 	 * TCP connection started when there is no policy and somebody
22113 	 * added policy before it became detached. Thus packets of the
22114 	 * detached connection could go out secure and the other end
22115 	 * would drop it because it will be expecting in clear. The
22116 	 * converse is not true i.e if somebody starts a TCP
22117 	 * connection and deletes the policy, all the packets will
22118 	 * still go out with the policy that existed before deleting
22119 	 * because ip_unbind sends up policy information which is used
22120 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22121 	 * TCP to attach a dummy IPSEC_OUT and set
22122 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22123 	 * affect performance for normal cases, we are not doing it.
22124 	 * Thus, set policy before starting any TCP connections.
22125 	 *
22126 	 * NOTE - We might apply policy even for a hard bound connection
22127 	 * - for which we cached policy in ip_bind - if somebody added
22128 	 * global policy after we inherited the policy in ip_bind.
22129 	 * This means that the packets that were going out in clear
22130 	 * previously would start going secure and hence get dropped
22131 	 * on the other side. To fix this, TCP attaches a dummy
22132 	 * ipsec_out and make sure that we don't apply global policy.
22133 	 */
22134 	if (ipha != NULL)
22135 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22136 	else
22137 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22138 	if (!policy_present)
22139 		return (mp);
22140 
22141 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22142 		    zoneid));
22143 }
22144 
22145 ire_t *
22146 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22147 {
22148 	ipaddr_t addr;
22149 	ire_t *save_ire;
22150 	irb_t *irb;
22151 	ill_group_t *illgrp;
22152 	int	err;
22153 
22154 	save_ire = ire;
22155 	addr = ire->ire_addr;
22156 
22157 	ASSERT(ire->ire_type == IRE_BROADCAST);
22158 
22159 	illgrp = connp->conn_outgoing_ill->ill_group;
22160 	if (illgrp == NULL) {
22161 		*conn_outgoing_ill = conn_get_held_ill(connp,
22162 		    &connp->conn_outgoing_ill, &err);
22163 		if (err == ILL_LOOKUP_FAILED) {
22164 			ire_refrele(save_ire);
22165 			return (NULL);
22166 		}
22167 		return (save_ire);
22168 	}
22169 	/*
22170 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22171 	 * If it is part of the group, we need to send on the ire
22172 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22173 	 * to this group. This is okay as IP_BOUND_IF really means
22174 	 * any ill in the group. We depend on the fact that the
22175 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22176 	 * if such an ire exists. This is possible only if you have
22177 	 * at least one ill in the group that has not failed.
22178 	 *
22179 	 * First get to the ire that matches the address and group.
22180 	 *
22181 	 * We don't look for an ire with a matching zoneid because a given zone
22182 	 * won't always have broadcast ires on all ills in the group.
22183 	 */
22184 	irb = ire->ire_bucket;
22185 	rw_enter(&irb->irb_lock, RW_READER);
22186 	if (ire->ire_marks & IRE_MARK_NORECV) {
22187 		/*
22188 		 * If the current zone only has an ire broadcast for this
22189 		 * address marked NORECV, the ire we want is ahead in the
22190 		 * bucket, so we look it up deliberately ignoring the zoneid.
22191 		 */
22192 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22193 			if (ire->ire_addr != addr)
22194 				continue;
22195 			/* skip over deleted ires */
22196 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22197 				continue;
22198 		}
22199 	}
22200 	while (ire != NULL) {
22201 		/*
22202 		 * If a new interface is coming up, we could end up
22203 		 * seeing the loopback ire and the non-loopback ire
22204 		 * may not have been added yet. So check for ire_stq
22205 		 */
22206 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22207 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22208 			break;
22209 		}
22210 		ire = ire->ire_next;
22211 	}
22212 	if (ire != NULL && ire->ire_addr == addr &&
22213 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22214 		IRE_REFHOLD(ire);
22215 		rw_exit(&irb->irb_lock);
22216 		ire_refrele(save_ire);
22217 		*conn_outgoing_ill = ire_to_ill(ire);
22218 		/*
22219 		 * Refhold the ill to make the conn_outgoing_ill
22220 		 * independent of the ire. ip_wput_ire goes in a loop
22221 		 * and may refrele the ire. Since we have an ire at this
22222 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22223 		 */
22224 		ill_refhold(*conn_outgoing_ill);
22225 		return (ire);
22226 	}
22227 	rw_exit(&irb->irb_lock);
22228 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22229 	/*
22230 	 * If we can't find a suitable ire, return the original ire.
22231 	 */
22232 	return (save_ire);
22233 }
22234 
22235 /*
22236  * This function does the ire_refrele of the ire passed in as the
22237  * argument. As this function looks up more ires i.e broadcast ires,
22238  * it needs to REFRELE them. Currently, for simplicity we don't
22239  * differentiate the one passed in and looked up here. We always
22240  * REFRELE.
22241  * IPQoS Notes:
22242  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22243  * IPSec packets are done in ipsec_out_process.
22244  *
22245  */
22246 void
22247 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22248     zoneid_t zoneid)
22249 {
22250 	ipha_t		*ipha;
22251 #define	rptr	((uchar_t *)ipha)
22252 	queue_t		*stq;
22253 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22254 	uint32_t	v_hlen_tos_len;
22255 	uint32_t	ttl_protocol;
22256 	ipaddr_t	src;
22257 	ipaddr_t	dst;
22258 	uint32_t	cksum;
22259 	ipaddr_t	orig_src;
22260 	ire_t		*ire1;
22261 	mblk_t		*next_mp;
22262 	uint_t		hlen;
22263 	uint16_t	*up;
22264 	uint32_t	max_frag = ire->ire_max_frag;
22265 	ill_t		*ill = ire_to_ill(ire);
22266 	int		clusterwide;
22267 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22268 	int		ipsec_len;
22269 	mblk_t		*first_mp;
22270 	ipsec_out_t	*io;
22271 	boolean_t	conn_dontroute;		/* conn value for multicast */
22272 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22273 	boolean_t	multicast_forward;	/* Should we forward ? */
22274 	boolean_t	unspec_src;
22275 	ill_t		*conn_outgoing_ill = NULL;
22276 	ill_t		*ire_ill;
22277 	ill_t		*ire1_ill;
22278 	ill_t		*out_ill;
22279 	uint32_t 	ill_index = 0;
22280 	boolean_t	multirt_send = B_FALSE;
22281 	int		err;
22282 	ipxmit_state_t	pktxmit_state;
22283 	ip_stack_t	*ipst = ire->ire_ipst;
22284 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22285 
22286 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22287 	    "ip_wput_ire_start: q %p", q);
22288 
22289 	multicast_forward = B_FALSE;
22290 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22291 
22292 	if (ire->ire_flags & RTF_MULTIRT) {
22293 		/*
22294 		 * Multirouting case. The bucket where ire is stored
22295 		 * probably holds other RTF_MULTIRT flagged ire
22296 		 * to the destination. In this call to ip_wput_ire,
22297 		 * we attempt to send the packet through all
22298 		 * those ires. Thus, we first ensure that ire is the
22299 		 * first RTF_MULTIRT ire in the bucket,
22300 		 * before walking the ire list.
22301 		 */
22302 		ire_t *first_ire;
22303 		irb_t *irb = ire->ire_bucket;
22304 		ASSERT(irb != NULL);
22305 
22306 		/* Make sure we do not omit any multiroute ire. */
22307 		IRB_REFHOLD(irb);
22308 		for (first_ire = irb->irb_ire;
22309 		    first_ire != NULL;
22310 		    first_ire = first_ire->ire_next) {
22311 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22312 			    (first_ire->ire_addr == ire->ire_addr) &&
22313 			    !(first_ire->ire_marks &
22314 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22315 				break;
22316 		}
22317 
22318 		if ((first_ire != NULL) && (first_ire != ire)) {
22319 			IRE_REFHOLD(first_ire);
22320 			ire_refrele(ire);
22321 			ire = first_ire;
22322 			ill = ire_to_ill(ire);
22323 		}
22324 		IRB_REFRELE(irb);
22325 	}
22326 
22327 	/*
22328 	 * conn_outgoing_ill is used only in the broadcast loop.
22329 	 * for performance we don't grab the mutexs in the fastpath
22330 	 */
22331 	if ((connp != NULL) &&
22332 	    (connp->conn_xmit_if_ill == NULL) &&
22333 	    (ire->ire_type == IRE_BROADCAST) &&
22334 	    ((connp->conn_nofailover_ill != NULL) ||
22335 	    (connp->conn_outgoing_ill != NULL))) {
22336 		/*
22337 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22338 		 * option. So, see if this endpoint is bound to a
22339 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22340 		 * that if the interface is failed, we will still send
22341 		 * the packet on the same ill which is what we want.
22342 		 */
22343 		conn_outgoing_ill = conn_get_held_ill(connp,
22344 		    &connp->conn_nofailover_ill, &err);
22345 		if (err == ILL_LOOKUP_FAILED) {
22346 			ire_refrele(ire);
22347 			freemsg(mp);
22348 			return;
22349 		}
22350 		if (conn_outgoing_ill == NULL) {
22351 			/*
22352 			 * Choose a good ill in the group to send the
22353 			 * packets on.
22354 			 */
22355 			ire = conn_set_outgoing_ill(connp, ire,
22356 			    &conn_outgoing_ill);
22357 			if (ire == NULL) {
22358 				freemsg(mp);
22359 				return;
22360 			}
22361 		}
22362 	}
22363 
22364 	if (mp->b_datap->db_type != M_CTL) {
22365 		ipha = (ipha_t *)mp->b_rptr;
22366 	} else {
22367 		io = (ipsec_out_t *)mp->b_rptr;
22368 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22369 		ASSERT(zoneid == io->ipsec_out_zoneid);
22370 		ASSERT(zoneid != ALL_ZONES);
22371 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22372 		dst = ipha->ipha_dst;
22373 		/*
22374 		 * For the multicast case, ipsec_out carries conn_dontroute and
22375 		 * conn_multicast_loop as conn may not be available here. We
22376 		 * need this for multicast loopback and forwarding which is done
22377 		 * later in the code.
22378 		 */
22379 		if (CLASSD(dst)) {
22380 			conn_dontroute = io->ipsec_out_dontroute;
22381 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22382 			/*
22383 			 * If conn_dontroute is not set or conn_multicast_loop
22384 			 * is set, we need to do forwarding/loopback. For
22385 			 * datagrams from ip_wput_multicast, conn_dontroute is
22386 			 * set to B_TRUE and conn_multicast_loop is set to
22387 			 * B_FALSE so that we neither do forwarding nor
22388 			 * loopback.
22389 			 */
22390 			if (!conn_dontroute || conn_multicast_loop)
22391 				multicast_forward = B_TRUE;
22392 		}
22393 	}
22394 
22395 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22396 	    ire->ire_zoneid != ALL_ZONES) {
22397 		/*
22398 		 * When a zone sends a packet to another zone, we try to deliver
22399 		 * the packet under the same conditions as if the destination
22400 		 * was a real node on the network. To do so, we look for a
22401 		 * matching route in the forwarding table.
22402 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22403 		 * ip_newroute() does.
22404 		 * Note that IRE_LOCAL are special, since they are used
22405 		 * when the zoneid doesn't match in some cases. This means that
22406 		 * we need to handle ipha_src differently since ire_src_addr
22407 		 * belongs to the receiving zone instead of the sending zone.
22408 		 * When ip_restrict_interzone_loopback is set, then
22409 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22410 		 * for loopback between zones when the logical "Ethernet" would
22411 		 * have looped them back.
22412 		 */
22413 		ire_t *src_ire;
22414 
22415 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22416 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22417 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22418 		if (src_ire != NULL &&
22419 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22420 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22421 		    ire_local_same_ill_group(ire, src_ire))) {
22422 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22423 				ipha->ipha_src = src_ire->ire_src_addr;
22424 			ire_refrele(src_ire);
22425 		} else {
22426 			ire_refrele(ire);
22427 			if (conn_outgoing_ill != NULL)
22428 				ill_refrele(conn_outgoing_ill);
22429 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22430 			if (src_ire != NULL) {
22431 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22432 					ire_refrele(src_ire);
22433 					freemsg(mp);
22434 					return;
22435 				}
22436 				ire_refrele(src_ire);
22437 			}
22438 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22439 				/* Failed */
22440 				freemsg(mp);
22441 				return;
22442 			}
22443 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22444 			    ipst);
22445 			return;
22446 		}
22447 	}
22448 
22449 	if (mp->b_datap->db_type == M_CTL ||
22450 	    ipss->ipsec_outbound_v4_policy_present) {
22451 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22452 		    unspec_src, zoneid);
22453 		if (mp == NULL) {
22454 			ire_refrele(ire);
22455 			if (conn_outgoing_ill != NULL)
22456 				ill_refrele(conn_outgoing_ill);
22457 			return;
22458 		}
22459 	}
22460 
22461 	first_mp = mp;
22462 	ipsec_len = 0;
22463 
22464 	if (first_mp->b_datap->db_type == M_CTL) {
22465 		io = (ipsec_out_t *)first_mp->b_rptr;
22466 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22467 		mp = first_mp->b_cont;
22468 		ipsec_len = ipsec_out_extra_length(first_mp);
22469 		ASSERT(ipsec_len >= 0);
22470 		/* We already picked up the zoneid from the M_CTL above */
22471 		ASSERT(zoneid == io->ipsec_out_zoneid);
22472 		ASSERT(zoneid != ALL_ZONES);
22473 
22474 		/*
22475 		 * Drop M_CTL here if IPsec processing is not needed.
22476 		 * (Non-IPsec use of M_CTL extracted any information it
22477 		 * needed above).
22478 		 */
22479 		if (ipsec_len == 0) {
22480 			freeb(first_mp);
22481 			first_mp = mp;
22482 		}
22483 	}
22484 
22485 	/*
22486 	 * Fast path for ip_wput_ire
22487 	 */
22488 
22489 	ipha = (ipha_t *)mp->b_rptr;
22490 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22491 	dst = ipha->ipha_dst;
22492 
22493 	/*
22494 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22495 	 * if the socket is a SOCK_RAW type. The transport checksum should
22496 	 * be provided in the pre-built packet, so we don't need to compute it.
22497 	 * Also, other application set flags, like DF, should not be altered.
22498 	 * Other transport MUST pass down zero.
22499 	 */
22500 	ip_hdr_included = ipha->ipha_ident;
22501 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22502 
22503 	if (CLASSD(dst)) {
22504 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22505 		    ntohl(dst),
22506 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22507 		    ntohl(ire->ire_addr)));
22508 	}
22509 
22510 /* Macros to extract header fields from data already in registers */
22511 #ifdef	_BIG_ENDIAN
22512 #define	V_HLEN	(v_hlen_tos_len >> 24)
22513 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22514 #define	PROTO	(ttl_protocol & 0xFF)
22515 #else
22516 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22517 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22518 #define	PROTO	(ttl_protocol >> 8)
22519 #endif
22520 
22521 
22522 	orig_src = src = ipha->ipha_src;
22523 	/* (The loop back to "another" is explained down below.) */
22524 another:;
22525 	/*
22526 	 * Assign an ident value for this packet.  We assign idents on
22527 	 * a per destination basis out of the IRE.  There could be
22528 	 * other threads targeting the same destination, so we have to
22529 	 * arrange for a atomic increment.  Note that we use a 32-bit
22530 	 * atomic add because it has better performance than its
22531 	 * 16-bit sibling.
22532 	 *
22533 	 * If running in cluster mode and if the source address
22534 	 * belongs to a replicated service then vector through
22535 	 * cl_inet_ipident vector to allocate ip identifier
22536 	 * NOTE: This is a contract private interface with the
22537 	 * clustering group.
22538 	 */
22539 	clusterwide = 0;
22540 	if (cl_inet_ipident) {
22541 		ASSERT(cl_inet_isclusterwide);
22542 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22543 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22544 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22545 			    AF_INET, (uint8_t *)(uintptr_t)src,
22546 			    (uint8_t *)(uintptr_t)dst);
22547 			clusterwide = 1;
22548 		}
22549 	}
22550 	if (!clusterwide) {
22551 		ipha->ipha_ident =
22552 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22553 	}
22554 
22555 #ifndef _BIG_ENDIAN
22556 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22557 #endif
22558 
22559 	/*
22560 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22561 	 * This is needed to obey conn_unspec_src when packets go through
22562 	 * ip_newroute + arp.
22563 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22564 	 */
22565 	if (src == INADDR_ANY && !unspec_src) {
22566 		/*
22567 		 * Assign the appropriate source address from the IRE if none
22568 		 * was specified.
22569 		 */
22570 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22571 
22572 		/*
22573 		 * With IP multipathing, broadcast packets are sent on the ire
22574 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22575 		 * the group. However, this ire might not be in the same zone so
22576 		 * we can't always use its source address. We look for a
22577 		 * broadcast ire in the same group and in the right zone.
22578 		 */
22579 		if (ire->ire_type == IRE_BROADCAST &&
22580 		    ire->ire_zoneid != zoneid) {
22581 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22582 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22583 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22584 			if (src_ire != NULL) {
22585 				src = src_ire->ire_src_addr;
22586 				ire_refrele(src_ire);
22587 			} else {
22588 				ire_refrele(ire);
22589 				if (conn_outgoing_ill != NULL)
22590 					ill_refrele(conn_outgoing_ill);
22591 				freemsg(first_mp);
22592 				if (ill != NULL) {
22593 					BUMP_MIB(ill->ill_ip_mib,
22594 					    ipIfStatsOutDiscards);
22595 				} else {
22596 					BUMP_MIB(&ipst->ips_ip_mib,
22597 					    ipIfStatsOutDiscards);
22598 				}
22599 				return;
22600 			}
22601 		} else {
22602 			src = ire->ire_src_addr;
22603 		}
22604 
22605 		if (connp == NULL) {
22606 			ip1dbg(("ip_wput_ire: no connp and no src "
22607 			    "address for dst 0x%x, using src 0x%x\n",
22608 			    ntohl(dst),
22609 			    ntohl(src)));
22610 		}
22611 		ipha->ipha_src = src;
22612 	}
22613 	stq = ire->ire_stq;
22614 
22615 	/*
22616 	 * We only allow ire chains for broadcasts since there will
22617 	 * be multiple IRE_CACHE entries for the same multicast
22618 	 * address (one per ipif).
22619 	 */
22620 	next_mp = NULL;
22621 
22622 	/* broadcast packet */
22623 	if (ire->ire_type == IRE_BROADCAST)
22624 		goto broadcast;
22625 
22626 	/* loopback ? */
22627 	if (stq == NULL)
22628 		goto nullstq;
22629 
22630 	/* The ill_index for outbound ILL */
22631 	ill_index = Q_TO_INDEX(stq);
22632 
22633 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22634 	ttl_protocol = ((uint16_t *)ipha)[4];
22635 
22636 	/* pseudo checksum (do it in parts for IP header checksum) */
22637 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22638 
22639 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22640 		queue_t *dev_q = stq->q_next;
22641 
22642 		/* flow controlled */
22643 		if ((dev_q->q_next || dev_q->q_first) &&
22644 		    !canput(dev_q))
22645 			goto blocked;
22646 		if ((PROTO == IPPROTO_UDP) &&
22647 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22648 			hlen = (V_HLEN & 0xF) << 2;
22649 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22650 			if (*up != 0) {
22651 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22652 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22653 				/* Software checksum? */
22654 				if (DB_CKSUMFLAGS(mp) == 0) {
22655 					IP_STAT(ipst, ip_out_sw_cksum);
22656 					IP_STAT_UPDATE(ipst,
22657 					    ip_udp_out_sw_cksum_bytes,
22658 					    LENGTH - hlen);
22659 				}
22660 			}
22661 		}
22662 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22663 		hlen = (V_HLEN & 0xF) << 2;
22664 		if (PROTO == IPPROTO_TCP) {
22665 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22666 			/*
22667 			 * The packet header is processed once and for all, even
22668 			 * in the multirouting case. We disable hardware
22669 			 * checksum if the packet is multirouted, as it will be
22670 			 * replicated via several interfaces, and not all of
22671 			 * them may have this capability.
22672 			 */
22673 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22674 			    LENGTH, max_frag, ipsec_len, cksum);
22675 			/* Software checksum? */
22676 			if (DB_CKSUMFLAGS(mp) == 0) {
22677 				IP_STAT(ipst, ip_out_sw_cksum);
22678 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22679 				    LENGTH - hlen);
22680 			}
22681 		} else {
22682 			sctp_hdr_t	*sctph;
22683 
22684 			ASSERT(PROTO == IPPROTO_SCTP);
22685 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22686 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22687 			/*
22688 			 * Zero out the checksum field to ensure proper
22689 			 * checksum calculation.
22690 			 */
22691 			sctph->sh_chksum = 0;
22692 #ifdef	DEBUG
22693 			if (!skip_sctp_cksum)
22694 #endif
22695 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22696 		}
22697 	}
22698 
22699 	/*
22700 	 * If this is a multicast packet and originated from ip_wput
22701 	 * we need to do loopback and forwarding checks. If it comes
22702 	 * from ip_wput_multicast, we SHOULD not do this.
22703 	 */
22704 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22705 
22706 	/* checksum */
22707 	cksum += ttl_protocol;
22708 
22709 	/* fragment the packet */
22710 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22711 		goto fragmentit;
22712 	/*
22713 	 * Don't use frag_flag if packet is pre-built or source
22714 	 * routed or if multicast (since multicast packets do
22715 	 * not solicit ICMP "packet too big" messages).
22716 	 */
22717 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22718 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22719 	    !ip_source_route_included(ipha)) &&
22720 	    !CLASSD(ipha->ipha_dst))
22721 		ipha->ipha_fragment_offset_and_flags |=
22722 		    htons(ire->ire_frag_flag);
22723 
22724 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22725 		/* calculate IP header checksum */
22726 		cksum += ipha->ipha_ident;
22727 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22728 		cksum += ipha->ipha_fragment_offset_and_flags;
22729 
22730 		/* IP options present */
22731 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22732 		if (hlen)
22733 			goto checksumoptions;
22734 
22735 		/* calculate hdr checksum */
22736 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22737 		cksum = ~(cksum + (cksum >> 16));
22738 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22739 	}
22740 	if (ipsec_len != 0) {
22741 		/*
22742 		 * We will do the rest of the processing after
22743 		 * we come back from IPSEC in ip_wput_ipsec_out().
22744 		 */
22745 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22746 
22747 		io = (ipsec_out_t *)first_mp->b_rptr;
22748 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22749 				ill_phyint->phyint_ifindex;
22750 
22751 		ipsec_out_process(q, first_mp, ire, ill_index);
22752 		ire_refrele(ire);
22753 		if (conn_outgoing_ill != NULL)
22754 			ill_refrele(conn_outgoing_ill);
22755 		return;
22756 	}
22757 
22758 	/*
22759 	 * In most cases, the emission loop below is entered only
22760 	 * once. Only in the case where the ire holds the
22761 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22762 	 * flagged ires in the bucket, and send the packet
22763 	 * through all crossed RTF_MULTIRT routes.
22764 	 */
22765 	if (ire->ire_flags & RTF_MULTIRT) {
22766 		multirt_send = B_TRUE;
22767 	}
22768 	do {
22769 		if (multirt_send) {
22770 			irb_t *irb;
22771 			/*
22772 			 * We are in a multiple send case, need to get
22773 			 * the next ire and make a duplicate of the packet.
22774 			 * ire1 holds here the next ire to process in the
22775 			 * bucket. If multirouting is expected,
22776 			 * any non-RTF_MULTIRT ire that has the
22777 			 * right destination address is ignored.
22778 			 */
22779 			irb = ire->ire_bucket;
22780 			ASSERT(irb != NULL);
22781 
22782 			IRB_REFHOLD(irb);
22783 			for (ire1 = ire->ire_next;
22784 			    ire1 != NULL;
22785 			    ire1 = ire1->ire_next) {
22786 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22787 					continue;
22788 				if (ire1->ire_addr != ire->ire_addr)
22789 					continue;
22790 				if (ire1->ire_marks &
22791 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22792 					continue;
22793 
22794 				/* Got one */
22795 				IRE_REFHOLD(ire1);
22796 				break;
22797 			}
22798 			IRB_REFRELE(irb);
22799 
22800 			if (ire1 != NULL) {
22801 				next_mp = copyb(mp);
22802 				if ((next_mp == NULL) ||
22803 				    ((mp->b_cont != NULL) &&
22804 				    ((next_mp->b_cont =
22805 				    dupmsg(mp->b_cont)) == NULL))) {
22806 					freemsg(next_mp);
22807 					next_mp = NULL;
22808 					ire_refrele(ire1);
22809 					ire1 = NULL;
22810 				}
22811 			}
22812 
22813 			/* Last multiroute ire; don't loop anymore. */
22814 			if (ire1 == NULL) {
22815 				multirt_send = B_FALSE;
22816 			}
22817 		}
22818 
22819 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22820 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22821 		    mblk_t *, mp);
22822 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22823 		    ipst->ips_ipv4firewall_physical_out,
22824 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22825 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22826 		if (mp == NULL)
22827 			goto release_ire_and_ill;
22828 
22829 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22830 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22831 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22832 		if ((pktxmit_state == SEND_FAILED) ||
22833 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22834 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22835 			    "- packet dropped\n"));
22836 release_ire_and_ill:
22837 			ire_refrele(ire);
22838 			if (next_mp != NULL) {
22839 				freemsg(next_mp);
22840 				ire_refrele(ire1);
22841 			}
22842 			if (conn_outgoing_ill != NULL)
22843 				ill_refrele(conn_outgoing_ill);
22844 			return;
22845 		}
22846 
22847 		if (CLASSD(dst)) {
22848 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22849 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22850 			    LENGTH);
22851 		}
22852 
22853 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22854 		    "ip_wput_ire_end: q %p (%S)",
22855 		    q, "last copy out");
22856 		IRE_REFRELE(ire);
22857 
22858 		if (multirt_send) {
22859 			ASSERT(ire1);
22860 			/*
22861 			 * Proceed with the next RTF_MULTIRT ire,
22862 			 * Also set up the send-to queue accordingly.
22863 			 */
22864 			ire = ire1;
22865 			ire1 = NULL;
22866 			stq = ire->ire_stq;
22867 			mp = next_mp;
22868 			next_mp = NULL;
22869 			ipha = (ipha_t *)mp->b_rptr;
22870 			ill_index = Q_TO_INDEX(stq);
22871 			ill = (ill_t *)stq->q_ptr;
22872 		}
22873 	} while (multirt_send);
22874 	if (conn_outgoing_ill != NULL)
22875 		ill_refrele(conn_outgoing_ill);
22876 	return;
22877 
22878 	/*
22879 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22880 	 */
22881 broadcast:
22882 	{
22883 		/*
22884 		 * Avoid broadcast storms by setting the ttl to 1
22885 		 * for broadcasts. This parameter can be set
22886 		 * via ndd, so make sure that for the SO_DONTROUTE
22887 		 * case that ipha_ttl is always set to 1.
22888 		 * In the event that we are replying to incoming
22889 		 * ICMP packets, conn could be NULL.
22890 		 */
22891 		if ((connp != NULL) && connp->conn_dontroute)
22892 			ipha->ipha_ttl = 1;
22893 		else
22894 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22895 
22896 		/*
22897 		 * Note that we are not doing a IRB_REFHOLD here.
22898 		 * Actually we don't care if the list changes i.e
22899 		 * if somebody deletes an IRE from the list while
22900 		 * we drop the lock, the next time we come around
22901 		 * ire_next will be NULL and hence we won't send
22902 		 * out multiple copies which is fine.
22903 		 */
22904 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22905 		ire1 = ire->ire_next;
22906 		if (conn_outgoing_ill != NULL) {
22907 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22908 				ASSERT(ire1 == ire->ire_next);
22909 				if (ire1 != NULL && ire1->ire_addr == dst) {
22910 					ire_refrele(ire);
22911 					ire = ire1;
22912 					IRE_REFHOLD(ire);
22913 					ire1 = ire->ire_next;
22914 					continue;
22915 				}
22916 				rw_exit(&ire->ire_bucket->irb_lock);
22917 				/* Did not find a matching ill */
22918 				ip1dbg(("ip_wput_ire: broadcast with no "
22919 				    "matching IP_BOUND_IF ill %s\n",
22920 				    conn_outgoing_ill->ill_name));
22921 				freemsg(first_mp);
22922 				if (ire != NULL)
22923 					ire_refrele(ire);
22924 				ill_refrele(conn_outgoing_ill);
22925 				return;
22926 			}
22927 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22928 			/*
22929 			 * If the next IRE has the same address and is not one
22930 			 * of the two copies that we need to send, try to see
22931 			 * whether this copy should be sent at all. This
22932 			 * assumes that we insert loopbacks first and then
22933 			 * non-loopbacks. This is acheived by inserting the
22934 			 * loopback always before non-loopback.
22935 			 * This is used to send a single copy of a broadcast
22936 			 * packet out all physical interfaces that have an
22937 			 * matching IRE_BROADCAST while also looping
22938 			 * back one copy (to ip_wput_local) for each
22939 			 * matching physical interface. However, we avoid
22940 			 * sending packets out different logical that match by
22941 			 * having ipif_up/ipif_down supress duplicate
22942 			 * IRE_BROADCASTS.
22943 			 *
22944 			 * This feature is currently used to get broadcasts
22945 			 * sent to multiple interfaces, when the broadcast
22946 			 * address being used applies to multiple interfaces.
22947 			 * For example, a whole net broadcast will be
22948 			 * replicated on every connected subnet of
22949 			 * the target net.
22950 			 *
22951 			 * Each zone has its own set of IRE_BROADCASTs, so that
22952 			 * we're able to distribute inbound packets to multiple
22953 			 * zones who share a broadcast address. We avoid looping
22954 			 * back outbound packets in different zones but on the
22955 			 * same ill, as the application would see duplicates.
22956 			 *
22957 			 * If the interfaces are part of the same group,
22958 			 * we would want to send only one copy out for
22959 			 * whole group.
22960 			 *
22961 			 * This logic assumes that ire_add_v4() groups the
22962 			 * IRE_BROADCAST entries so that those with the same
22963 			 * ire_addr and ill_group are kept together.
22964 			 */
22965 			ire_ill = ire->ire_ipif->ipif_ill;
22966 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22967 				if (ire_ill->ill_group != NULL &&
22968 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22969 					/*
22970 					 * If the current zone only has an ire
22971 					 * broadcast for this address marked
22972 					 * NORECV, the ire we want is ahead in
22973 					 * the bucket, so we look it up
22974 					 * deliberately ignoring the zoneid.
22975 					 */
22976 					for (ire1 = ire->ire_bucket->irb_ire;
22977 					    ire1 != NULL;
22978 					    ire1 = ire1->ire_next) {
22979 						ire1_ill =
22980 						    ire1->ire_ipif->ipif_ill;
22981 						if (ire1->ire_addr != dst)
22982 							continue;
22983 						/* skip over the current ire */
22984 						if (ire1 == ire)
22985 							continue;
22986 						/* skip over deleted ires */
22987 						if (ire1->ire_marks &
22988 						    IRE_MARK_CONDEMNED)
22989 							continue;
22990 						/*
22991 						 * non-loopback ire in our
22992 						 * group: use it for the next
22993 						 * pass in the loop
22994 						 */
22995 						if (ire1->ire_stq != NULL &&
22996 						    ire1_ill->ill_group ==
22997 						    ire_ill->ill_group)
22998 							break;
22999 					}
23000 				}
23001 			} else {
23002 				while (ire1 != NULL && ire1->ire_addr == dst) {
23003 					ire1_ill = ire1->ire_ipif->ipif_ill;
23004 					/*
23005 					 * We can have two broadcast ires on the
23006 					 * same ill in different zones; here
23007 					 * we'll send a copy of the packet on
23008 					 * each ill and the fanout code will
23009 					 * call conn_wantpacket() to check that
23010 					 * the zone has the broadcast address
23011 					 * configured on the ill. If the two
23012 					 * ires are in the same group we only
23013 					 * send one copy up.
23014 					 */
23015 					if (ire1_ill != ire_ill &&
23016 					    (ire1_ill->ill_group == NULL ||
23017 					    ire_ill->ill_group == NULL ||
23018 					    ire1_ill->ill_group !=
23019 					    ire_ill->ill_group)) {
23020 						break;
23021 					}
23022 					ire1 = ire1->ire_next;
23023 				}
23024 			}
23025 		}
23026 		ASSERT(multirt_send == B_FALSE);
23027 		if (ire1 != NULL && ire1->ire_addr == dst) {
23028 			if ((ire->ire_flags & RTF_MULTIRT) &&
23029 			    (ire1->ire_flags & RTF_MULTIRT)) {
23030 				/*
23031 				 * We are in the multirouting case.
23032 				 * The message must be sent at least
23033 				 * on both ires. These ires have been
23034 				 * inserted AFTER the standard ones
23035 				 * in ip_rt_add(). There are thus no
23036 				 * other ire entries for the destination
23037 				 * address in the rest of the bucket
23038 				 * that do not have the RTF_MULTIRT
23039 				 * flag. We don't process a copy
23040 				 * of the message here. This will be
23041 				 * done in the final sending loop.
23042 				 */
23043 				multirt_send = B_TRUE;
23044 			} else {
23045 				next_mp = ip_copymsg(first_mp);
23046 				if (next_mp != NULL)
23047 					IRE_REFHOLD(ire1);
23048 			}
23049 		}
23050 		rw_exit(&ire->ire_bucket->irb_lock);
23051 	}
23052 
23053 	if (stq) {
23054 		/*
23055 		 * A non-NULL send-to queue means this packet is going
23056 		 * out of this machine.
23057 		 */
23058 		out_ill = (ill_t *)stq->q_ptr;
23059 
23060 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23061 		ttl_protocol = ((uint16_t *)ipha)[4];
23062 		/*
23063 		 * We accumulate the pseudo header checksum in cksum.
23064 		 * This is pretty hairy code, so watch close.  One
23065 		 * thing to keep in mind is that UDP and TCP have
23066 		 * stored their respective datagram lengths in their
23067 		 * checksum fields.  This lines things up real nice.
23068 		 */
23069 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23070 		    (src >> 16) + (src & 0xFFFF);
23071 		/*
23072 		 * We assume the udp checksum field contains the
23073 		 * length, so to compute the pseudo header checksum,
23074 		 * all we need is the protocol number and src/dst.
23075 		 */
23076 		/* Provide the checksums for UDP and TCP. */
23077 		if ((PROTO == IPPROTO_TCP) &&
23078 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23079 			/* hlen gets the number of uchar_ts in the IP header */
23080 			hlen = (V_HLEN & 0xF) << 2;
23081 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23082 			IP_STAT(ipst, ip_out_sw_cksum);
23083 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23084 			    LENGTH - hlen);
23085 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23086 		} else if (PROTO == IPPROTO_SCTP &&
23087 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23088 			sctp_hdr_t	*sctph;
23089 
23090 			hlen = (V_HLEN & 0xF) << 2;
23091 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23092 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23093 			sctph->sh_chksum = 0;
23094 #ifdef	DEBUG
23095 			if (!skip_sctp_cksum)
23096 #endif
23097 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23098 		} else {
23099 			queue_t *dev_q = stq->q_next;
23100 
23101 			if ((dev_q->q_next || dev_q->q_first) &&
23102 			    !canput(dev_q)) {
23103 			    blocked:
23104 				ipha->ipha_ident = ip_hdr_included;
23105 				/*
23106 				 * If we don't have a conn to apply
23107 				 * backpressure, free the message.
23108 				 * In the ire_send path, we don't know
23109 				 * the position to requeue the packet. Rather
23110 				 * than reorder packets, we just drop this
23111 				 * packet.
23112 				 */
23113 				if (ipst->ips_ip_output_queue &&
23114 				    connp != NULL &&
23115 				    caller != IRE_SEND) {
23116 					if (caller == IP_WSRV) {
23117 						connp->conn_did_putbq = 1;
23118 						(void) putbq(connp->conn_wq,
23119 						    first_mp);
23120 						conn_drain_insert(connp);
23121 						/*
23122 						 * This is the service thread,
23123 						 * and the queue is already
23124 						 * noenabled. The check for
23125 						 * canput and the putbq is not
23126 						 * atomic. So we need to check
23127 						 * again.
23128 						 */
23129 						if (canput(stq->q_next))
23130 							connp->conn_did_putbq
23131 							    = 0;
23132 						IP_STAT(ipst, ip_conn_flputbq);
23133 					} else {
23134 						/*
23135 						 * We are not the service proc.
23136 						 * ip_wsrv will be scheduled or
23137 						 * is already running.
23138 						 */
23139 						(void) putq(connp->conn_wq,
23140 						    first_mp);
23141 					}
23142 				} else {
23143 					out_ill = (ill_t *)stq->q_ptr;
23144 					BUMP_MIB(out_ill->ill_ip_mib,
23145 					    ipIfStatsOutDiscards);
23146 					freemsg(first_mp);
23147 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23148 					    "ip_wput_ire_end: q %p (%S)",
23149 					    q, "discard");
23150 				}
23151 				ire_refrele(ire);
23152 				if (next_mp) {
23153 					ire_refrele(ire1);
23154 					freemsg(next_mp);
23155 				}
23156 				if (conn_outgoing_ill != NULL)
23157 					ill_refrele(conn_outgoing_ill);
23158 				return;
23159 			}
23160 			if ((PROTO == IPPROTO_UDP) &&
23161 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23162 				/*
23163 				 * hlen gets the number of uchar_ts in the
23164 				 * IP header
23165 				 */
23166 				hlen = (V_HLEN & 0xF) << 2;
23167 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23168 				max_frag = ire->ire_max_frag;
23169 				if (*up != 0) {
23170 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23171 					    up, PROTO, hlen, LENGTH, max_frag,
23172 					    ipsec_len, cksum);
23173 					/* Software checksum? */
23174 					if (DB_CKSUMFLAGS(mp) == 0) {
23175 						IP_STAT(ipst, ip_out_sw_cksum);
23176 						IP_STAT_UPDATE(ipst,
23177 						    ip_udp_out_sw_cksum_bytes,
23178 						    LENGTH - hlen);
23179 					}
23180 				}
23181 			}
23182 		}
23183 		/*
23184 		 * Need to do this even when fragmenting. The local
23185 		 * loopback can be done without computing checksums
23186 		 * but forwarding out other interface must be done
23187 		 * after the IP checksum (and ULP checksums) have been
23188 		 * computed.
23189 		 *
23190 		 * NOTE : multicast_forward is set only if this packet
23191 		 * originated from ip_wput. For packets originating from
23192 		 * ip_wput_multicast, it is not set.
23193 		 */
23194 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23195 		    multi_loopback:
23196 			ip2dbg(("ip_wput: multicast, loop %d\n",
23197 			    conn_multicast_loop));
23198 
23199 			/*  Forget header checksum offload */
23200 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23201 
23202 			/*
23203 			 * Local loopback of multicasts?  Check the
23204 			 * ill.
23205 			 *
23206 			 * Note that the loopback function will not come
23207 			 * in through ip_rput - it will only do the
23208 			 * client fanout thus we need to do an mforward
23209 			 * as well.  The is different from the BSD
23210 			 * logic.
23211 			 */
23212 			if (ill != NULL) {
23213 				ilm_t	*ilm;
23214 
23215 				ILM_WALKER_HOLD(ill);
23216 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23217 				    ALL_ZONES);
23218 				ILM_WALKER_RELE(ill);
23219 				if (ilm != NULL) {
23220 					/*
23221 					 * Pass along the virtual output q.
23222 					 * ip_wput_local() will distribute the
23223 					 * packet to all the matching zones,
23224 					 * except the sending zone when
23225 					 * IP_MULTICAST_LOOP is false.
23226 					 */
23227 					ip_multicast_loopback(q, ill, first_mp,
23228 					    conn_multicast_loop ? 0 :
23229 					    IP_FF_NO_MCAST_LOOP, zoneid);
23230 				}
23231 			}
23232 			if (ipha->ipha_ttl == 0) {
23233 				/*
23234 				 * 0 => only to this host i.e. we are
23235 				 * done. We are also done if this was the
23236 				 * loopback interface since it is sufficient
23237 				 * to loopback one copy of a multicast packet.
23238 				 */
23239 				freemsg(first_mp);
23240 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23241 				    "ip_wput_ire_end: q %p (%S)",
23242 				    q, "loopback");
23243 				ire_refrele(ire);
23244 				if (conn_outgoing_ill != NULL)
23245 					ill_refrele(conn_outgoing_ill);
23246 				return;
23247 			}
23248 			/*
23249 			 * ILLF_MULTICAST is checked in ip_newroute
23250 			 * i.e. we don't need to check it here since
23251 			 * all IRE_CACHEs come from ip_newroute.
23252 			 * For multicast traffic, SO_DONTROUTE is interpreted
23253 			 * to mean only send the packet out the interface
23254 			 * (optionally specified with IP_MULTICAST_IF)
23255 			 * and do not forward it out additional interfaces.
23256 			 * RSVP and the rsvp daemon is an example of a
23257 			 * protocol and user level process that
23258 			 * handles it's own routing. Hence, it uses the
23259 			 * SO_DONTROUTE option to accomplish this.
23260 			 */
23261 
23262 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23263 			    ill != NULL) {
23264 				/* Unconditionally redo the checksum */
23265 				ipha->ipha_hdr_checksum = 0;
23266 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23267 
23268 				/*
23269 				 * If this needs to go out secure, we need
23270 				 * to wait till we finish the IPSEC
23271 				 * processing.
23272 				 */
23273 				if (ipsec_len == 0 &&
23274 				    ip_mforward(ill, ipha, mp)) {
23275 					freemsg(first_mp);
23276 					ip1dbg(("ip_wput: mforward failed\n"));
23277 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23278 					    "ip_wput_ire_end: q %p (%S)",
23279 					    q, "mforward failed");
23280 					ire_refrele(ire);
23281 					if (conn_outgoing_ill != NULL)
23282 						ill_refrele(conn_outgoing_ill);
23283 					return;
23284 				}
23285 			}
23286 		}
23287 		max_frag = ire->ire_max_frag;
23288 		cksum += ttl_protocol;
23289 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23290 			/* No fragmentation required for this one. */
23291 			/*
23292 			 * Don't use frag_flag if packet is pre-built or source
23293 			 * routed or if multicast (since multicast packets do
23294 			 * not solicit ICMP "packet too big" messages).
23295 			 */
23296 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23297 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23298 			    !ip_source_route_included(ipha)) &&
23299 			    !CLASSD(ipha->ipha_dst))
23300 				ipha->ipha_fragment_offset_and_flags |=
23301 				    htons(ire->ire_frag_flag);
23302 
23303 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23304 				/* Complete the IP header checksum. */
23305 				cksum += ipha->ipha_ident;
23306 				cksum += (v_hlen_tos_len >> 16)+
23307 				    (v_hlen_tos_len & 0xFFFF);
23308 				cksum += ipha->ipha_fragment_offset_and_flags;
23309 				hlen = (V_HLEN & 0xF) -
23310 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23311 				if (hlen) {
23312 				    checksumoptions:
23313 					/*
23314 					 * Account for the IP Options in the IP
23315 					 * header checksum.
23316 					 */
23317 					up = (uint16_t *)(rptr+
23318 					    IP_SIMPLE_HDR_LENGTH);
23319 					do {
23320 						cksum += up[0];
23321 						cksum += up[1];
23322 						up += 2;
23323 					} while (--hlen);
23324 				}
23325 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23326 				cksum = ~(cksum + (cksum >> 16));
23327 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23328 			}
23329 			if (ipsec_len != 0) {
23330 				ipsec_out_process(q, first_mp, ire, ill_index);
23331 				if (!next_mp) {
23332 					ire_refrele(ire);
23333 					if (conn_outgoing_ill != NULL)
23334 						ill_refrele(conn_outgoing_ill);
23335 					return;
23336 				}
23337 				goto next;
23338 			}
23339 
23340 			/*
23341 			 * multirt_send has already been handled
23342 			 * for broadcast, but not yet for multicast
23343 			 * or IP options.
23344 			 */
23345 			if (next_mp == NULL) {
23346 				if (ire->ire_flags & RTF_MULTIRT) {
23347 					multirt_send = B_TRUE;
23348 				}
23349 			}
23350 
23351 			/*
23352 			 * In most cases, the emission loop below is
23353 			 * entered only once. Only in the case where
23354 			 * the ire holds the RTF_MULTIRT flag, do we loop
23355 			 * to process all RTF_MULTIRT ires in the bucket,
23356 			 * and send the packet through all crossed
23357 			 * RTF_MULTIRT routes.
23358 			 */
23359 			do {
23360 				if (multirt_send) {
23361 					irb_t *irb;
23362 
23363 					irb = ire->ire_bucket;
23364 					ASSERT(irb != NULL);
23365 					/*
23366 					 * We are in a multiple send case,
23367 					 * need to get the next IRE and make
23368 					 * a duplicate of the packet.
23369 					 */
23370 					IRB_REFHOLD(irb);
23371 					for (ire1 = ire->ire_next;
23372 					    ire1 != NULL;
23373 					    ire1 = ire1->ire_next) {
23374 						if (!(ire1->ire_flags &
23375 						    RTF_MULTIRT))
23376 							continue;
23377 						if (ire1->ire_addr !=
23378 						    ire->ire_addr)
23379 							continue;
23380 						if (ire1->ire_marks &
23381 						    (IRE_MARK_CONDEMNED|
23382 							IRE_MARK_HIDDEN))
23383 							continue;
23384 
23385 						/* Got one */
23386 						IRE_REFHOLD(ire1);
23387 						break;
23388 					}
23389 					IRB_REFRELE(irb);
23390 
23391 					if (ire1 != NULL) {
23392 						next_mp = copyb(mp);
23393 						if ((next_mp == NULL) ||
23394 						    ((mp->b_cont != NULL) &&
23395 						    ((next_mp->b_cont =
23396 						    dupmsg(mp->b_cont))
23397 						    == NULL))) {
23398 							freemsg(next_mp);
23399 							next_mp = NULL;
23400 							ire_refrele(ire1);
23401 							ire1 = NULL;
23402 						}
23403 					}
23404 
23405 					/*
23406 					 * Last multiroute ire; don't loop
23407 					 * anymore. The emission is over
23408 					 * and next_mp is NULL.
23409 					 */
23410 					if (ire1 == NULL) {
23411 						multirt_send = B_FALSE;
23412 					}
23413 				}
23414 
23415 				out_ill = ire->ire_ipif->ipif_ill;
23416 				DTRACE_PROBE4(ip4__physical__out__start,
23417 				    ill_t *, NULL,
23418 				    ill_t *, out_ill,
23419 				    ipha_t *, ipha, mblk_t *, mp);
23420 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23421 				    ipst->ips_ipv4firewall_physical_out,
23422 				    NULL, out_ill, ipha, mp, mp, ipst);
23423 				DTRACE_PROBE1(ip4__physical__out__end,
23424 				    mblk_t *, mp);
23425 				if (mp == NULL)
23426 					goto release_ire_and_ill_2;
23427 
23428 				ASSERT(ipsec_len == 0);
23429 				mp->b_prev =
23430 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23431 				DTRACE_PROBE2(ip__xmit__2,
23432 				    mblk_t *, mp, ire_t *, ire);
23433 				pktxmit_state = ip_xmit_v4(mp, ire,
23434 				    NULL, B_TRUE);
23435 				if ((pktxmit_state == SEND_FAILED) ||
23436 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23437 release_ire_and_ill_2:
23438 					if (next_mp) {
23439 						freemsg(next_mp);
23440 						ire_refrele(ire1);
23441 					}
23442 					ire_refrele(ire);
23443 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23444 					    "ip_wput_ire_end: q %p (%S)",
23445 					    q, "discard MDATA");
23446 					if (conn_outgoing_ill != NULL)
23447 						ill_refrele(conn_outgoing_ill);
23448 					return;
23449 				}
23450 
23451 				if (CLASSD(dst)) {
23452 					BUMP_MIB(out_ill->ill_ip_mib,
23453 					    ipIfStatsHCOutMcastPkts);
23454 					UPDATE_MIB(out_ill->ill_ip_mib,
23455 					    ipIfStatsHCOutMcastOctets,
23456 					    LENGTH);
23457 				} else if (ire->ire_type == IRE_BROADCAST) {
23458 					BUMP_MIB(out_ill->ill_ip_mib,
23459 					    ipIfStatsHCOutBcastPkts);
23460 				}
23461 
23462 				if (multirt_send) {
23463 					/*
23464 					 * We are in a multiple send case,
23465 					 * need to re-enter the sending loop
23466 					 * using the next ire.
23467 					 */
23468 					ire_refrele(ire);
23469 					ire = ire1;
23470 					stq = ire->ire_stq;
23471 					mp = next_mp;
23472 					next_mp = NULL;
23473 					ipha = (ipha_t *)mp->b_rptr;
23474 					ill_index = Q_TO_INDEX(stq);
23475 				}
23476 			} while (multirt_send);
23477 
23478 			if (!next_mp) {
23479 				/*
23480 				 * Last copy going out (the ultra-common
23481 				 * case).  Note that we intentionally replicate
23482 				 * the putnext rather than calling it before
23483 				 * the next_mp check in hopes of a little
23484 				 * tail-call action out of the compiler.
23485 				 */
23486 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23487 				    "ip_wput_ire_end: q %p (%S)",
23488 				    q, "last copy out(1)");
23489 				ire_refrele(ire);
23490 				if (conn_outgoing_ill != NULL)
23491 					ill_refrele(conn_outgoing_ill);
23492 				return;
23493 			}
23494 			/* More copies going out below. */
23495 		} else {
23496 			int offset;
23497 		    fragmentit:
23498 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23499 			/*
23500 			 * If this would generate a icmp_frag_needed message,
23501 			 * we need to handle it before we do the IPSEC
23502 			 * processing. Otherwise, we need to strip the IPSEC
23503 			 * headers before we send up the message to the ULPs
23504 			 * which becomes messy and difficult.
23505 			 */
23506 			if (ipsec_len != 0) {
23507 				if ((max_frag < (unsigned int)(LENGTH +
23508 				    ipsec_len)) && (offset & IPH_DF)) {
23509 					out_ill = (ill_t *)stq->q_ptr;
23510 					BUMP_MIB(out_ill->ill_ip_mib,
23511 					    ipIfStatsOutFragFails);
23512 					BUMP_MIB(out_ill->ill_ip_mib,
23513 					    ipIfStatsOutFragReqds);
23514 					ipha->ipha_hdr_checksum = 0;
23515 					ipha->ipha_hdr_checksum =
23516 					    (uint16_t)ip_csum_hdr(ipha);
23517 					icmp_frag_needed(ire->ire_stq, first_mp,
23518 					    max_frag, zoneid, ipst);
23519 					if (!next_mp) {
23520 						ire_refrele(ire);
23521 						if (conn_outgoing_ill != NULL) {
23522 							ill_refrele(
23523 							    conn_outgoing_ill);
23524 						}
23525 						return;
23526 					}
23527 				} else {
23528 					/*
23529 					 * This won't cause a icmp_frag_needed
23530 					 * message. to be generated. Send it on
23531 					 * the wire. Note that this could still
23532 					 * cause fragmentation and all we
23533 					 * do is the generation of the message
23534 					 * to the ULP if needed before IPSEC.
23535 					 */
23536 					if (!next_mp) {
23537 						ipsec_out_process(q, first_mp,
23538 						    ire, ill_index);
23539 						TRACE_2(TR_FAC_IP,
23540 						    TR_IP_WPUT_IRE_END,
23541 						    "ip_wput_ire_end: q %p "
23542 						    "(%S)", q,
23543 						    "last ipsec_out_process");
23544 						ire_refrele(ire);
23545 						if (conn_outgoing_ill != NULL) {
23546 							ill_refrele(
23547 							    conn_outgoing_ill);
23548 						}
23549 						return;
23550 					}
23551 					ipsec_out_process(q, first_mp,
23552 					    ire, ill_index);
23553 				}
23554 			} else {
23555 				/*
23556 				 * Initiate IPPF processing. For
23557 				 * fragmentable packets we finish
23558 				 * all QOS packet processing before
23559 				 * calling:
23560 				 * ip_wput_ire_fragmentit->ip_wput_frag
23561 				 */
23562 
23563 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23564 					ip_process(IPP_LOCAL_OUT, &mp,
23565 					    ill_index);
23566 					if (mp == NULL) {
23567 						out_ill = (ill_t *)stq->q_ptr;
23568 						BUMP_MIB(out_ill->ill_ip_mib,
23569 						    ipIfStatsOutDiscards);
23570 						if (next_mp != NULL) {
23571 							freemsg(next_mp);
23572 							ire_refrele(ire1);
23573 						}
23574 						ire_refrele(ire);
23575 						TRACE_2(TR_FAC_IP,
23576 						    TR_IP_WPUT_IRE_END,
23577 						    "ip_wput_ire: q %p (%S)",
23578 						    q, "discard MDATA");
23579 						if (conn_outgoing_ill != NULL) {
23580 							ill_refrele(
23581 							    conn_outgoing_ill);
23582 						}
23583 						return;
23584 					}
23585 				}
23586 				if (!next_mp) {
23587 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23588 					    "ip_wput_ire_end: q %p (%S)",
23589 					    q, "last fragmentation");
23590 					ip_wput_ire_fragmentit(mp, ire,
23591 					    zoneid, ipst);
23592 					ire_refrele(ire);
23593 					if (conn_outgoing_ill != NULL)
23594 						ill_refrele(conn_outgoing_ill);
23595 					return;
23596 				}
23597 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23598 			}
23599 		}
23600 	} else {
23601 	    nullstq:
23602 		/* A NULL stq means the destination address is local. */
23603 		UPDATE_OB_PKT_COUNT(ire);
23604 		ire->ire_last_used_time = lbolt;
23605 		ASSERT(ire->ire_ipif != NULL);
23606 		if (!next_mp) {
23607 			/*
23608 			 * Is there an "in" and "out" for traffic local
23609 			 * to a host (loopback)?  The code in Solaris doesn't
23610 			 * explicitly draw a line in its code for in vs out,
23611 			 * so we've had to draw a line in the sand: ip_wput_ire
23612 			 * is considered to be the "output" side and
23613 			 * ip_wput_local to be the "input" side.
23614 			 */
23615 			out_ill = ire->ire_ipif->ipif_ill;
23616 
23617 			DTRACE_PROBE4(ip4__loopback__out__start,
23618 			    ill_t *, NULL, ill_t *, out_ill,
23619 			    ipha_t *, ipha, mblk_t *, first_mp);
23620 
23621 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23622 			    ipst->ips_ipv4firewall_loopback_out,
23623 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23624 
23625 			DTRACE_PROBE1(ip4__loopback__out_end,
23626 			    mblk_t *, first_mp);
23627 
23628 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23629 			    "ip_wput_ire_end: q %p (%S)",
23630 			    q, "local address");
23631 
23632 			if (first_mp != NULL)
23633 				ip_wput_local(q, out_ill, ipha,
23634 				    first_mp, ire, 0, ire->ire_zoneid);
23635 			ire_refrele(ire);
23636 			if (conn_outgoing_ill != NULL)
23637 				ill_refrele(conn_outgoing_ill);
23638 			return;
23639 		}
23640 
23641 		out_ill = ire->ire_ipif->ipif_ill;
23642 
23643 		DTRACE_PROBE4(ip4__loopback__out__start,
23644 		    ill_t *, NULL, ill_t *, out_ill,
23645 		    ipha_t *, ipha, mblk_t *, first_mp);
23646 
23647 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23648 		    ipst->ips_ipv4firewall_loopback_out,
23649 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23650 
23651 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23652 
23653 		if (first_mp != NULL)
23654 			ip_wput_local(q, out_ill, ipha,
23655 			    first_mp, ire, 0, ire->ire_zoneid);
23656 	}
23657 next:
23658 	/*
23659 	 * More copies going out to additional interfaces.
23660 	 * ire1 has already been held. We don't need the
23661 	 * "ire" anymore.
23662 	 */
23663 	ire_refrele(ire);
23664 	ire = ire1;
23665 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23666 	mp = next_mp;
23667 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23668 	ill = ire_to_ill(ire);
23669 	first_mp = mp;
23670 	if (ipsec_len != 0) {
23671 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23672 		mp = mp->b_cont;
23673 	}
23674 	dst = ire->ire_addr;
23675 	ipha = (ipha_t *)mp->b_rptr;
23676 	/*
23677 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23678 	 * Restore ipha_ident "no checksum" flag.
23679 	 */
23680 	src = orig_src;
23681 	ipha->ipha_ident = ip_hdr_included;
23682 	goto another;
23683 
23684 #undef	rptr
23685 #undef	Q_TO_INDEX
23686 }
23687 
23688 /*
23689  * Routine to allocate a message that is used to notify the ULP about MDT.
23690  * The caller may provide a pointer to the link-layer MDT capabilities,
23691  * or NULL if MDT is to be disabled on the stream.
23692  */
23693 mblk_t *
23694 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23695 {
23696 	mblk_t *mp;
23697 	ip_mdt_info_t *mdti;
23698 	ill_mdt_capab_t *idst;
23699 
23700 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23701 		DB_TYPE(mp) = M_CTL;
23702 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23703 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23704 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23705 		idst = &(mdti->mdt_capab);
23706 
23707 		/*
23708 		 * If the caller provides us with the capability, copy
23709 		 * it over into our notification message; otherwise
23710 		 * we zero out the capability portion.
23711 		 */
23712 		if (isrc != NULL)
23713 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23714 		else
23715 			bzero((caddr_t)idst, sizeof (*idst));
23716 	}
23717 	return (mp);
23718 }
23719 
23720 /*
23721  * Routine which determines whether MDT can be enabled on the destination
23722  * IRE and IPC combination, and if so, allocates and returns the MDT
23723  * notification mblk that may be used by ULP.  We also check if we need to
23724  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23725  * MDT usage in the past have been lifted.  This gets called during IP
23726  * and ULP binding.
23727  */
23728 mblk_t *
23729 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23730     ill_mdt_capab_t *mdt_cap)
23731 {
23732 	mblk_t *mp;
23733 	boolean_t rc = B_FALSE;
23734 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23735 
23736 	ASSERT(dst_ire != NULL);
23737 	ASSERT(connp != NULL);
23738 	ASSERT(mdt_cap != NULL);
23739 
23740 	/*
23741 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23742 	 * Multidata, which is handled in tcp_multisend().  This
23743 	 * is the reason why we do all these checks here, to ensure
23744 	 * that we don't enable Multidata for the cases which we
23745 	 * can't handle at the moment.
23746 	 */
23747 	do {
23748 		/* Only do TCP at the moment */
23749 		if (connp->conn_ulp != IPPROTO_TCP)
23750 			break;
23751 
23752 		/*
23753 		 * IPSEC outbound policy present?  Note that we get here
23754 		 * after calling ipsec_conn_cache_policy() where the global
23755 		 * policy checking is performed.  conn_latch will be
23756 		 * non-NULL as long as there's a policy defined,
23757 		 * i.e. conn_out_enforce_policy may be NULL in such case
23758 		 * when the connection is non-secure, and hence we check
23759 		 * further if the latch refers to an outbound policy.
23760 		 */
23761 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23762 			break;
23763 
23764 		/* CGTP (multiroute) is enabled? */
23765 		if (dst_ire->ire_flags & RTF_MULTIRT)
23766 			break;
23767 
23768 		/* Outbound IPQoS enabled? */
23769 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23770 			/*
23771 			 * In this case, we disable MDT for this and all
23772 			 * future connections going over the interface.
23773 			 */
23774 			mdt_cap->ill_mdt_on = 0;
23775 			break;
23776 		}
23777 
23778 		/* socket option(s) present? */
23779 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23780 			break;
23781 
23782 		rc = B_TRUE;
23783 	/* CONSTCOND */
23784 	} while (0);
23785 
23786 	/* Remember the result */
23787 	connp->conn_mdt_ok = rc;
23788 
23789 	if (!rc)
23790 		return (NULL);
23791 	else if (!mdt_cap->ill_mdt_on) {
23792 		/*
23793 		 * If MDT has been previously turned off in the past, and we
23794 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23795 		 * then enable it for this interface.
23796 		 */
23797 		mdt_cap->ill_mdt_on = 1;
23798 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23799 		    "interface %s\n", ill_name));
23800 	}
23801 
23802 	/* Allocate the MDT info mblk */
23803 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23804 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23805 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23806 		return (NULL);
23807 	}
23808 	return (mp);
23809 }
23810 
23811 /*
23812  * Routine to allocate a message that is used to notify the ULP about LSO.
23813  * The caller may provide a pointer to the link-layer LSO capabilities,
23814  * or NULL if LSO is to be disabled on the stream.
23815  */
23816 mblk_t *
23817 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23818 {
23819 	mblk_t *mp;
23820 	ip_lso_info_t *lsoi;
23821 	ill_lso_capab_t *idst;
23822 
23823 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23824 		DB_TYPE(mp) = M_CTL;
23825 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23826 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23827 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23828 		idst = &(lsoi->lso_capab);
23829 
23830 		/*
23831 		 * If the caller provides us with the capability, copy
23832 		 * it over into our notification message; otherwise
23833 		 * we zero out the capability portion.
23834 		 */
23835 		if (isrc != NULL)
23836 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23837 		else
23838 			bzero((caddr_t)idst, sizeof (*idst));
23839 	}
23840 	return (mp);
23841 }
23842 
23843 /*
23844  * Routine which determines whether LSO can be enabled on the destination
23845  * IRE and IPC combination, and if so, allocates and returns the LSO
23846  * notification mblk that may be used by ULP.  We also check if we need to
23847  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23848  * LSO usage in the past have been lifted.  This gets called during IP
23849  * and ULP binding.
23850  */
23851 mblk_t *
23852 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23853     ill_lso_capab_t *lso_cap)
23854 {
23855 	mblk_t *mp;
23856 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23857 
23858 	ASSERT(dst_ire != NULL);
23859 	ASSERT(connp != NULL);
23860 	ASSERT(lso_cap != NULL);
23861 
23862 	connp->conn_lso_ok = B_TRUE;
23863 
23864 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23865 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23866 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23867 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23868 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23869 		connp->conn_lso_ok = B_FALSE;
23870 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23871 			/*
23872 			 * Disable LSO for this and all future connections going
23873 			 * over the interface.
23874 			 */
23875 			lso_cap->ill_lso_on = 0;
23876 		}
23877 	}
23878 
23879 	if (!connp->conn_lso_ok)
23880 		return (NULL);
23881 	else if (!lso_cap->ill_lso_on) {
23882 		/*
23883 		 * If LSO has been previously turned off in the past, and we
23884 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23885 		 * then enable it for this interface.
23886 		 */
23887 		lso_cap->ill_lso_on = 1;
23888 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23889 		    ill_name));
23890 	}
23891 
23892 	/* Allocate the LSO info mblk */
23893 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23894 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23895 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23896 
23897 	return (mp);
23898 }
23899 
23900 /*
23901  * Create destination address attribute, and fill it with the physical
23902  * destination address and SAP taken from the template DL_UNITDATA_REQ
23903  * message block.
23904  */
23905 boolean_t
23906 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23907 {
23908 	dl_unitdata_req_t *dlurp;
23909 	pattr_t *pa;
23910 	pattrinfo_t pa_info;
23911 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23912 	uint_t das_len, das_off;
23913 
23914 	ASSERT(dlmp != NULL);
23915 
23916 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23917 	das_len = dlurp->dl_dest_addr_length;
23918 	das_off = dlurp->dl_dest_addr_offset;
23919 
23920 	pa_info.type = PATTR_DSTADDRSAP;
23921 	pa_info.len = sizeof (**das) + das_len - 1;
23922 
23923 	/* create and associate the attribute */
23924 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23925 	if (pa != NULL) {
23926 		ASSERT(*das != NULL);
23927 		(*das)->addr_is_group = 0;
23928 		(*das)->addr_len = (uint8_t)das_len;
23929 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23930 	}
23931 
23932 	return (pa != NULL);
23933 }
23934 
23935 /*
23936  * Create hardware checksum attribute and fill it with the values passed.
23937  */
23938 boolean_t
23939 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23940     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23941 {
23942 	pattr_t *pa;
23943 	pattrinfo_t pa_info;
23944 
23945 	ASSERT(mmd != NULL);
23946 
23947 	pa_info.type = PATTR_HCKSUM;
23948 	pa_info.len = sizeof (pattr_hcksum_t);
23949 
23950 	/* create and associate the attribute */
23951 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23952 	if (pa != NULL) {
23953 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23954 
23955 		hck->hcksum_start_offset = start_offset;
23956 		hck->hcksum_stuff_offset = stuff_offset;
23957 		hck->hcksum_end_offset = end_offset;
23958 		hck->hcksum_flags = flags;
23959 	}
23960 	return (pa != NULL);
23961 }
23962 
23963 /*
23964  * Create zerocopy attribute and fill it with the specified flags
23965  */
23966 boolean_t
23967 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23968 {
23969 	pattr_t *pa;
23970 	pattrinfo_t pa_info;
23971 
23972 	ASSERT(mmd != NULL);
23973 	pa_info.type = PATTR_ZCOPY;
23974 	pa_info.len = sizeof (pattr_zcopy_t);
23975 
23976 	/* create and associate the attribute */
23977 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23978 	if (pa != NULL) {
23979 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23980 
23981 		zcopy->zcopy_flags = flags;
23982 	}
23983 	return (pa != NULL);
23984 }
23985 
23986 /*
23987  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23988  * block chain. We could rewrite to handle arbitrary message block chains but
23989  * that would make the code complicated and slow. Right now there three
23990  * restrictions:
23991  *
23992  *   1. The first message block must contain the complete IP header and
23993  *	at least 1 byte of payload data.
23994  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23995  *	so that we can use a single Multidata message.
23996  *   3. No frag must be distributed over two or more message blocks so
23997  *	that we don't need more than two packet descriptors per frag.
23998  *
23999  * The above restrictions allow us to support userland applications (which
24000  * will send down a single message block) and NFS over UDP (which will
24001  * send down a chain of at most three message blocks).
24002  *
24003  * We also don't use MDT for payloads with less than or equal to
24004  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24005  */
24006 boolean_t
24007 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24008 {
24009 	int	blocks;
24010 	ssize_t	total, missing, size;
24011 
24012 	ASSERT(mp != NULL);
24013 	ASSERT(hdr_len > 0);
24014 
24015 	size = MBLKL(mp) - hdr_len;
24016 	if (size <= 0)
24017 		return (B_FALSE);
24018 
24019 	/* The first mblk contains the header and some payload. */
24020 	blocks = 1;
24021 	total = size;
24022 	size %= len;
24023 	missing = (size == 0) ? 0 : (len - size);
24024 	mp = mp->b_cont;
24025 
24026 	while (mp != NULL) {
24027 		/*
24028 		 * Give up if we encounter a zero length message block.
24029 		 * In practice, this should rarely happen and therefore
24030 		 * not worth the trouble of freeing and re-linking the
24031 		 * mblk from the chain to handle such case.
24032 		 */
24033 		if ((size = MBLKL(mp)) == 0)
24034 			return (B_FALSE);
24035 
24036 		/* Too many payload buffers for a single Multidata message? */
24037 		if (++blocks > MULTIDATA_MAX_PBUFS)
24038 			return (B_FALSE);
24039 
24040 		total += size;
24041 		/* Is a frag distributed over two or more message blocks? */
24042 		if (missing > size)
24043 			return (B_FALSE);
24044 		size -= missing;
24045 
24046 		size %= len;
24047 		missing = (size == 0) ? 0 : (len - size);
24048 
24049 		mp = mp->b_cont;
24050 	}
24051 
24052 	return (total > ip_wput_frag_mdt_min);
24053 }
24054 
24055 /*
24056  * Outbound IPv4 fragmentation routine using MDT.
24057  */
24058 static void
24059 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24060     uint32_t frag_flag, int offset)
24061 {
24062 	ipha_t		*ipha_orig;
24063 	int		i1, ip_data_end;
24064 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24065 	mblk_t		*hdr_mp, *md_mp = NULL;
24066 	unsigned char	*hdr_ptr, *pld_ptr;
24067 	multidata_t	*mmd;
24068 	ip_pdescinfo_t	pdi;
24069 	ill_t		*ill;
24070 	ip_stack_t	*ipst = ire->ire_ipst;
24071 
24072 	ASSERT(DB_TYPE(mp) == M_DATA);
24073 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24074 
24075 	ill = ire_to_ill(ire);
24076 	ASSERT(ill != NULL);
24077 
24078 	ipha_orig = (ipha_t *)mp->b_rptr;
24079 	mp->b_rptr += sizeof (ipha_t);
24080 
24081 	/* Calculate how many packets we will send out */
24082 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24083 	pkts = (i1 + len - 1) / len;
24084 	ASSERT(pkts > 1);
24085 
24086 	/* Allocate a message block which will hold all the IP Headers. */
24087 	wroff = ipst->ips_ip_wroff_extra;
24088 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24089 
24090 	i1 = pkts * hdr_chunk_len;
24091 	/*
24092 	 * Create the header buffer, Multidata and destination address
24093 	 * and SAP attribute that should be associated with it.
24094 	 */
24095 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24096 	    ((hdr_mp->b_wptr += i1),
24097 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24098 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24099 		freemsg(mp);
24100 		if (md_mp == NULL) {
24101 			freemsg(hdr_mp);
24102 		} else {
24103 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24104 			freemsg(md_mp);
24105 		}
24106 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24107 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24108 		return;
24109 	}
24110 	IP_STAT(ipst, ip_frag_mdt_allocd);
24111 
24112 	/*
24113 	 * Add a payload buffer to the Multidata; this operation must not
24114 	 * fail, or otherwise our logic in this routine is broken.  There
24115 	 * is no memory allocation done by the routine, so any returned
24116 	 * failure simply tells us that we've done something wrong.
24117 	 *
24118 	 * A failure tells us that either we're adding the same payload
24119 	 * buffer more than once, or we're trying to add more buffers than
24120 	 * allowed.  None of the above cases should happen, and we panic
24121 	 * because either there's horrible heap corruption, and/or
24122 	 * programming mistake.
24123 	 */
24124 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24125 		goto pbuf_panic;
24126 
24127 	hdr_ptr = hdr_mp->b_rptr;
24128 	pld_ptr = mp->b_rptr;
24129 
24130 	/* Establish the ending byte offset, based on the starting offset. */
24131 	offset <<= 3;
24132 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24133 	    IP_SIMPLE_HDR_LENGTH;
24134 
24135 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24136 
24137 	while (pld_ptr < mp->b_wptr) {
24138 		ipha_t		*ipha;
24139 		uint16_t	offset_and_flags;
24140 		uint16_t	ip_len;
24141 		int		error;
24142 
24143 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24144 		ipha = (ipha_t *)(hdr_ptr + wroff);
24145 		ASSERT(OK_32PTR(ipha));
24146 		*ipha = *ipha_orig;
24147 
24148 		if (ip_data_end - offset > len) {
24149 			offset_and_flags = IPH_MF;
24150 		} else {
24151 			/*
24152 			 * Last frag. Set len to the length of this last piece.
24153 			 */
24154 			len = ip_data_end - offset;
24155 			/* A frag of a frag might have IPH_MF non-zero */
24156 			offset_and_flags =
24157 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24158 			    IPH_MF;
24159 		}
24160 		offset_and_flags |= (uint16_t)(offset >> 3);
24161 		offset_and_flags |= (uint16_t)frag_flag;
24162 		/* Store the offset and flags in the IP header. */
24163 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24164 
24165 		/* Store the length in the IP header. */
24166 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24167 		ipha->ipha_length = htons(ip_len);
24168 
24169 		/*
24170 		 * Set the IP header checksum.  Note that mp is just
24171 		 * the header, so this is easy to pass to ip_csum.
24172 		 */
24173 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24174 
24175 		/*
24176 		 * Record offset and size of header and data of the next packet
24177 		 * in the multidata message.
24178 		 */
24179 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24180 		PDESC_PLD_INIT(&pdi);
24181 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24182 		ASSERT(i1 > 0);
24183 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24184 		if (i1 == len) {
24185 			pld_ptr += len;
24186 		} else {
24187 			i1 = len - i1;
24188 			mp = mp->b_cont;
24189 			ASSERT(mp != NULL);
24190 			ASSERT(MBLKL(mp) >= i1);
24191 			/*
24192 			 * Attach the next payload message block to the
24193 			 * multidata message.
24194 			 */
24195 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24196 				goto pbuf_panic;
24197 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24198 			pld_ptr = mp->b_rptr + i1;
24199 		}
24200 
24201 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24202 		    KM_NOSLEEP)) == NULL) {
24203 			/*
24204 			 * Any failure other than ENOMEM indicates that we
24205 			 * have passed in invalid pdesc info or parameters
24206 			 * to mmd_addpdesc, which must not happen.
24207 			 *
24208 			 * EINVAL is a result of failure on boundary checks
24209 			 * against the pdesc info contents.  It should not
24210 			 * happen, and we panic because either there's
24211 			 * horrible heap corruption, and/or programming
24212 			 * mistake.
24213 			 */
24214 			if (error != ENOMEM) {
24215 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24216 				    "pdesc logic error detected for "
24217 				    "mmd %p pinfo %p (%d)\n",
24218 				    (void *)mmd, (void *)&pdi, error);
24219 				/* NOTREACHED */
24220 			}
24221 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24222 			/* Free unattached payload message blocks as well */
24223 			md_mp->b_cont = mp->b_cont;
24224 			goto free_mmd;
24225 		}
24226 
24227 		/* Advance fragment offset. */
24228 		offset += len;
24229 
24230 		/* Advance to location for next header in the buffer. */
24231 		hdr_ptr += hdr_chunk_len;
24232 
24233 		/* Did we reach the next payload message block? */
24234 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24235 			mp = mp->b_cont;
24236 			/*
24237 			 * Attach the next message block with payload
24238 			 * data to the multidata message.
24239 			 */
24240 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24241 				goto pbuf_panic;
24242 			pld_ptr = mp->b_rptr;
24243 		}
24244 	}
24245 
24246 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24247 	ASSERT(mp->b_wptr == pld_ptr);
24248 
24249 	/* Update IP statistics */
24250 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24251 
24252 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24253 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24254 
24255 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24256 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24257 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24258 
24259 	if (pkt_type == OB_PKT) {
24260 		ire->ire_ob_pkt_count += pkts;
24261 		if (ire->ire_ipif != NULL)
24262 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24263 	} else {
24264 		/*
24265 		 * The type is IB_PKT in the forwarding path and in
24266 		 * the mobile IP case when the packet is being reverse-
24267 		 * tunneled to the home agent.
24268 		 */
24269 		ire->ire_ib_pkt_count += pkts;
24270 		ASSERT(!IRE_IS_LOCAL(ire));
24271 		if (ire->ire_type & IRE_BROADCAST) {
24272 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24273 		} else {
24274 			UPDATE_MIB(ill->ill_ip_mib,
24275 			    ipIfStatsHCOutForwDatagrams, pkts);
24276 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24277 		}
24278 	}
24279 	ire->ire_last_used_time = lbolt;
24280 	/* Send it down */
24281 	putnext(ire->ire_stq, md_mp);
24282 	return;
24283 
24284 pbuf_panic:
24285 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24286 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24287 	    pbuf_idx);
24288 	/* NOTREACHED */
24289 }
24290 
24291 /*
24292  * Outbound IP fragmentation routine.
24293  *
24294  * NOTE : This routine does not ire_refrele the ire that is passed in
24295  * as the argument.
24296  */
24297 static void
24298 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24299     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24300 {
24301 	int		i1;
24302 	mblk_t		*ll_hdr_mp;
24303 	int 		ll_hdr_len;
24304 	int		hdr_len;
24305 	mblk_t		*hdr_mp;
24306 	ipha_t		*ipha;
24307 	int		ip_data_end;
24308 	int		len;
24309 	mblk_t		*mp = mp_orig, *mp1;
24310 	int		offset;
24311 	queue_t		*q;
24312 	uint32_t	v_hlen_tos_len;
24313 	mblk_t		*first_mp;
24314 	boolean_t	mctl_present;
24315 	ill_t		*ill;
24316 	ill_t		*out_ill;
24317 	mblk_t		*xmit_mp;
24318 	mblk_t		*carve_mp;
24319 	ire_t		*ire1 = NULL;
24320 	ire_t		*save_ire = NULL;
24321 	mblk_t  	*next_mp = NULL;
24322 	boolean_t	last_frag = B_FALSE;
24323 	boolean_t	multirt_send = B_FALSE;
24324 	ire_t		*first_ire = NULL;
24325 	irb_t		*irb = NULL;
24326 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24327 
24328 	ill = ire_to_ill(ire);
24329 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24330 
24331 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24332 
24333 	if (max_frag == 0) {
24334 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24335 		    " -  dropping packet\n"));
24336 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24337 		freemsg(mp);
24338 		return;
24339 	}
24340 
24341 	/*
24342 	 * IPSEC does not allow hw accelerated packets to be fragmented
24343 	 * This check is made in ip_wput_ipsec_out prior to coming here
24344 	 * via ip_wput_ire_fragmentit.
24345 	 *
24346 	 * If at this point we have an ire whose ARP request has not
24347 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24348 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24349 	 * This packet and all fragmentable packets for this ire will
24350 	 * continue to get dropped while ire_nce->nce_state remains in
24351 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24352 	 * ND_REACHABLE, all subsquent large packets for this ire will
24353 	 * get fragemented and sent out by this function.
24354 	 */
24355 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24356 		/* If nce_state is ND_INITIAL, trigger ARP query */
24357 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24358 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24359 		    " -  dropping packet\n"));
24360 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24361 		freemsg(mp);
24362 		return;
24363 	}
24364 
24365 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24366 	    "ip_wput_frag_start:");
24367 
24368 	if (mp->b_datap->db_type == M_CTL) {
24369 		first_mp = mp;
24370 		mp_orig = mp = mp->b_cont;
24371 		mctl_present = B_TRUE;
24372 	} else {
24373 		first_mp = mp;
24374 		mctl_present = B_FALSE;
24375 	}
24376 
24377 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24378 	ipha = (ipha_t *)mp->b_rptr;
24379 
24380 	/*
24381 	 * If the Don't Fragment flag is on, generate an ICMP destination
24382 	 * unreachable, fragmentation needed.
24383 	 */
24384 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24385 	if (offset & IPH_DF) {
24386 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24387 		/*
24388 		 * Need to compute hdr checksum if called from ip_wput_ire.
24389 		 * Note that ip_rput_forward verifies the checksum before
24390 		 * calling this routine so in that case this is a noop.
24391 		 */
24392 		ipha->ipha_hdr_checksum = 0;
24393 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24394 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24395 		    ipst);
24396 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24397 		    "ip_wput_frag_end:(%S)",
24398 		    "don't fragment");
24399 		return;
24400 	}
24401 	if (mctl_present)
24402 		freeb(first_mp);
24403 	/*
24404 	 * Establish the starting offset.  May not be zero if we are fragging
24405 	 * a fragment that is being forwarded.
24406 	 */
24407 	offset = offset & IPH_OFFSET;
24408 
24409 	/* TODO why is this test needed? */
24410 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24411 	if (((max_frag - LENGTH) & ~7) < 8) {
24412 		/* TODO: notify ulp somehow */
24413 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24414 		freemsg(mp);
24415 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24416 		    "ip_wput_frag_end:(%S)",
24417 		    "len < 8");
24418 		return;
24419 	}
24420 
24421 	hdr_len = (V_HLEN & 0xF) << 2;
24422 
24423 	ipha->ipha_hdr_checksum = 0;
24424 
24425 	/*
24426 	 * Establish the number of bytes maximum per frag, after putting
24427 	 * in the header.
24428 	 */
24429 	len = (max_frag - hdr_len) & ~7;
24430 
24431 	/* Check if we can use MDT to send out the frags. */
24432 	ASSERT(!IRE_IS_LOCAL(ire));
24433 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24434 	    ipst->ips_ip_multidata_outbound &&
24435 	    !(ire->ire_flags & RTF_MULTIRT) &&
24436 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24437 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24438 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24439 		ASSERT(ill->ill_mdt_capab != NULL);
24440 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24441 			/*
24442 			 * If MDT has been previously turned off in the past,
24443 			 * and we currently can do MDT (due to IPQoS policy
24444 			 * removal, etc.) then enable it for this interface.
24445 			 */
24446 			ill->ill_mdt_capab->ill_mdt_on = 1;
24447 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24448 			    ill->ill_name));
24449 		}
24450 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24451 		    offset);
24452 		return;
24453 	}
24454 
24455 	/* Get a copy of the header for the trailing frags */
24456 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24457 	if (!hdr_mp) {
24458 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24459 		freemsg(mp);
24460 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24461 		    "ip_wput_frag_end:(%S)",
24462 		    "couldn't copy hdr");
24463 		return;
24464 	}
24465 	if (DB_CRED(mp) != NULL)
24466 		mblk_setcred(hdr_mp, DB_CRED(mp));
24467 
24468 	/* Store the starting offset, with the MoreFrags flag. */
24469 	i1 = offset | IPH_MF | frag_flag;
24470 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24471 
24472 	/* Establish the ending byte offset, based on the starting offset. */
24473 	offset <<= 3;
24474 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24475 
24476 	/* Store the length of the first fragment in the IP header. */
24477 	i1 = len + hdr_len;
24478 	ASSERT(i1 <= IP_MAXPACKET);
24479 	ipha->ipha_length = htons((uint16_t)i1);
24480 
24481 	/*
24482 	 * Compute the IP header checksum for the first frag.  We have to
24483 	 * watch out that we stop at the end of the header.
24484 	 */
24485 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24486 
24487 	/*
24488 	 * Now carve off the first frag.  Note that this will include the
24489 	 * original IP header.
24490 	 */
24491 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24492 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24493 		freeb(hdr_mp);
24494 		freemsg(mp_orig);
24495 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24496 		    "ip_wput_frag_end:(%S)",
24497 		    "couldn't carve first");
24498 		return;
24499 	}
24500 
24501 	/*
24502 	 * Multirouting case. Each fragment is replicated
24503 	 * via all non-condemned RTF_MULTIRT routes
24504 	 * currently resolved.
24505 	 * We ensure that first_ire is the first RTF_MULTIRT
24506 	 * ire in the bucket.
24507 	 */
24508 	if (ire->ire_flags & RTF_MULTIRT) {
24509 		irb = ire->ire_bucket;
24510 		ASSERT(irb != NULL);
24511 
24512 		multirt_send = B_TRUE;
24513 
24514 		/* Make sure we do not omit any multiroute ire. */
24515 		IRB_REFHOLD(irb);
24516 		for (first_ire = irb->irb_ire;
24517 		    first_ire != NULL;
24518 		    first_ire = first_ire->ire_next) {
24519 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24520 			    (first_ire->ire_addr == ire->ire_addr) &&
24521 			    !(first_ire->ire_marks &
24522 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24523 				break;
24524 		}
24525 
24526 		if (first_ire != NULL) {
24527 			if (first_ire != ire) {
24528 				IRE_REFHOLD(first_ire);
24529 				/*
24530 				 * Do not release the ire passed in
24531 				 * as the argument.
24532 				 */
24533 				ire = first_ire;
24534 			} else {
24535 				first_ire = NULL;
24536 			}
24537 		}
24538 		IRB_REFRELE(irb);
24539 
24540 		/*
24541 		 * Save the first ire; we will need to restore it
24542 		 * for the trailing frags.
24543 		 * We REFHOLD save_ire, as each iterated ire will be
24544 		 * REFRELEd.
24545 		 */
24546 		save_ire = ire;
24547 		IRE_REFHOLD(save_ire);
24548 	}
24549 
24550 	/*
24551 	 * First fragment emission loop.
24552 	 * In most cases, the emission loop below is entered only
24553 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24554 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24555 	 * bucket, and send the fragment through all crossed
24556 	 * RTF_MULTIRT routes.
24557 	 */
24558 	do {
24559 		if (ire->ire_flags & RTF_MULTIRT) {
24560 			/*
24561 			 * We are in a multiple send case, need to get
24562 			 * the next ire and make a copy of the packet.
24563 			 * ire1 holds here the next ire to process in the
24564 			 * bucket. If multirouting is expected,
24565 			 * any non-RTF_MULTIRT ire that has the
24566 			 * right destination address is ignored.
24567 			 *
24568 			 * We have to take into account the MTU of
24569 			 * each walked ire. max_frag is set by the
24570 			 * the caller and generally refers to
24571 			 * the primary ire entry. Here we ensure that
24572 			 * no route with a lower MTU will be used, as
24573 			 * fragments are carved once for all ires,
24574 			 * then replicated.
24575 			 */
24576 			ASSERT(irb != NULL);
24577 			IRB_REFHOLD(irb);
24578 			for (ire1 = ire->ire_next;
24579 			    ire1 != NULL;
24580 			    ire1 = ire1->ire_next) {
24581 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24582 					continue;
24583 				if (ire1->ire_addr != ire->ire_addr)
24584 					continue;
24585 				if (ire1->ire_marks &
24586 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24587 					continue;
24588 				/*
24589 				 * Ensure we do not exceed the MTU
24590 				 * of the next route.
24591 				 */
24592 				if (ire1->ire_max_frag < max_frag) {
24593 					ip_multirt_bad_mtu(ire1, max_frag);
24594 					continue;
24595 				}
24596 
24597 				/* Got one. */
24598 				IRE_REFHOLD(ire1);
24599 				break;
24600 			}
24601 			IRB_REFRELE(irb);
24602 
24603 			if (ire1 != NULL) {
24604 				next_mp = copyb(mp);
24605 				if ((next_mp == NULL) ||
24606 				    ((mp->b_cont != NULL) &&
24607 				    ((next_mp->b_cont =
24608 				    dupmsg(mp->b_cont)) == NULL))) {
24609 					freemsg(next_mp);
24610 					next_mp = NULL;
24611 					ire_refrele(ire1);
24612 					ire1 = NULL;
24613 				}
24614 			}
24615 
24616 			/* Last multiroute ire; don't loop anymore. */
24617 			if (ire1 == NULL) {
24618 				multirt_send = B_FALSE;
24619 			}
24620 		}
24621 
24622 		ll_hdr_len = 0;
24623 		LOCK_IRE_FP_MP(ire);
24624 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24625 		if (ll_hdr_mp != NULL) {
24626 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24627 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24628 		} else {
24629 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24630 		}
24631 
24632 		/* If there is a transmit header, get a copy for this frag. */
24633 		/*
24634 		 * TODO: should check db_ref before calling ip_carve_mp since
24635 		 * it might give us a dup.
24636 		 */
24637 		if (!ll_hdr_mp) {
24638 			/* No xmit header. */
24639 			xmit_mp = mp;
24640 
24641 		/* We have a link-layer header that can fit in our mblk. */
24642 		} else if (mp->b_datap->db_ref == 1 &&
24643 		    ll_hdr_len != 0 &&
24644 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24645 			/* M_DATA fastpath */
24646 			mp->b_rptr -= ll_hdr_len;
24647 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24648 			xmit_mp = mp;
24649 
24650 		/* Corner case if copyb has failed */
24651 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24652 			UNLOCK_IRE_FP_MP(ire);
24653 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24654 			freeb(hdr_mp);
24655 			freemsg(mp);
24656 			freemsg(mp_orig);
24657 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24658 			    "ip_wput_frag_end:(%S)",
24659 			    "discard");
24660 
24661 			if (multirt_send) {
24662 				ASSERT(ire1);
24663 				ASSERT(next_mp);
24664 
24665 				freemsg(next_mp);
24666 				ire_refrele(ire1);
24667 			}
24668 			if (save_ire != NULL)
24669 				IRE_REFRELE(save_ire);
24670 
24671 			if (first_ire != NULL)
24672 				ire_refrele(first_ire);
24673 			return;
24674 
24675 		/*
24676 		 * Case of res_mp OR the fastpath mp can't fit
24677 		 * in the mblk
24678 		 */
24679 		} else {
24680 			xmit_mp->b_cont = mp;
24681 			if (DB_CRED(mp) != NULL)
24682 				mblk_setcred(xmit_mp, DB_CRED(mp));
24683 			/*
24684 			 * Get priority marking, if any.
24685 			 * We propagate the CoS marking from the
24686 			 * original packet that went to QoS processing
24687 			 * in ip_wput_ire to the newly carved mp.
24688 			 */
24689 			if (DB_TYPE(xmit_mp) == M_DATA)
24690 				xmit_mp->b_band = mp->b_band;
24691 		}
24692 		UNLOCK_IRE_FP_MP(ire);
24693 
24694 		q = ire->ire_stq;
24695 		out_ill = (ill_t *)q->q_ptr;
24696 
24697 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24698 
24699 		DTRACE_PROBE4(ip4__physical__out__start,
24700 		    ill_t *, NULL, ill_t *, out_ill,
24701 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24702 
24703 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24704 		    ipst->ips_ipv4firewall_physical_out,
24705 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24706 
24707 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24708 
24709 		if (xmit_mp != NULL) {
24710 			putnext(q, xmit_mp);
24711 
24712 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24713 			UPDATE_MIB(out_ill->ill_ip_mib,
24714 			    ipIfStatsHCOutOctets, i1);
24715 
24716 			if (pkt_type != OB_PKT) {
24717 				/*
24718 				 * Update the packet count and MIB stats
24719 				 * of trailing RTF_MULTIRT ires.
24720 				 */
24721 				UPDATE_OB_PKT_COUNT(ire);
24722 				BUMP_MIB(out_ill->ill_ip_mib,
24723 				    ipIfStatsOutFragReqds);
24724 			}
24725 		}
24726 
24727 		if (multirt_send) {
24728 			/*
24729 			 * We are in a multiple send case; look for
24730 			 * the next ire and re-enter the loop.
24731 			 */
24732 			ASSERT(ire1);
24733 			ASSERT(next_mp);
24734 			/* REFRELE the current ire before looping */
24735 			ire_refrele(ire);
24736 			ire = ire1;
24737 			ire1 = NULL;
24738 			mp = next_mp;
24739 			next_mp = NULL;
24740 		}
24741 	} while (multirt_send);
24742 
24743 	ASSERT(ire1 == NULL);
24744 
24745 	/* Restore the original ire; we need it for the trailing frags */
24746 	if (save_ire != NULL) {
24747 		/* REFRELE the last iterated ire */
24748 		ire_refrele(ire);
24749 		/* save_ire has been REFHOLDed */
24750 		ire = save_ire;
24751 		save_ire = NULL;
24752 		q = ire->ire_stq;
24753 	}
24754 
24755 	if (pkt_type == OB_PKT) {
24756 		UPDATE_OB_PKT_COUNT(ire);
24757 	} else {
24758 		out_ill = (ill_t *)q->q_ptr;
24759 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24760 		UPDATE_IB_PKT_COUNT(ire);
24761 	}
24762 
24763 	/* Advance the offset to the second frag starting point. */
24764 	offset += len;
24765 	/*
24766 	 * Update hdr_len from the copied header - there might be less options
24767 	 * in the later fragments.
24768 	 */
24769 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24770 	/* Loop until done. */
24771 	for (;;) {
24772 		uint16_t	offset_and_flags;
24773 		uint16_t	ip_len;
24774 
24775 		if (ip_data_end - offset > len) {
24776 			/*
24777 			 * Carve off the appropriate amount from the original
24778 			 * datagram.
24779 			 */
24780 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24781 				mp = NULL;
24782 				break;
24783 			}
24784 			/*
24785 			 * More frags after this one.  Get another copy
24786 			 * of the header.
24787 			 */
24788 			if (carve_mp->b_datap->db_ref == 1 &&
24789 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24790 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24791 				/* Inline IP header */
24792 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24793 				    hdr_mp->b_rptr;
24794 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24795 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24796 				mp = carve_mp;
24797 			} else {
24798 				if (!(mp = copyb(hdr_mp))) {
24799 					freemsg(carve_mp);
24800 					break;
24801 				}
24802 				/* Get priority marking, if any. */
24803 				mp->b_band = carve_mp->b_band;
24804 				mp->b_cont = carve_mp;
24805 			}
24806 			ipha = (ipha_t *)mp->b_rptr;
24807 			offset_and_flags = IPH_MF;
24808 		} else {
24809 			/*
24810 			 * Last frag.  Consume the header. Set len to
24811 			 * the length of this last piece.
24812 			 */
24813 			len = ip_data_end - offset;
24814 
24815 			/*
24816 			 * Carve off the appropriate amount from the original
24817 			 * datagram.
24818 			 */
24819 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24820 				mp = NULL;
24821 				break;
24822 			}
24823 			if (carve_mp->b_datap->db_ref == 1 &&
24824 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24825 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24826 				/* Inline IP header */
24827 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24828 				    hdr_mp->b_rptr;
24829 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24830 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24831 				mp = carve_mp;
24832 				freeb(hdr_mp);
24833 				hdr_mp = mp;
24834 			} else {
24835 				mp = hdr_mp;
24836 				/* Get priority marking, if any. */
24837 				mp->b_band = carve_mp->b_band;
24838 				mp->b_cont = carve_mp;
24839 			}
24840 			ipha = (ipha_t *)mp->b_rptr;
24841 			/* A frag of a frag might have IPH_MF non-zero */
24842 			offset_and_flags =
24843 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24844 			    IPH_MF;
24845 		}
24846 		offset_and_flags |= (uint16_t)(offset >> 3);
24847 		offset_and_flags |= (uint16_t)frag_flag;
24848 		/* Store the offset and flags in the IP header. */
24849 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24850 
24851 		/* Store the length in the IP header. */
24852 		ip_len = (uint16_t)(len + hdr_len);
24853 		ipha->ipha_length = htons(ip_len);
24854 
24855 		/*
24856 		 * Set the IP header checksum.	Note that mp is just
24857 		 * the header, so this is easy to pass to ip_csum.
24858 		 */
24859 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24860 
24861 		/* Attach a transmit header, if any, and ship it. */
24862 		if (pkt_type == OB_PKT) {
24863 			UPDATE_OB_PKT_COUNT(ire);
24864 		} else {
24865 			out_ill = (ill_t *)q->q_ptr;
24866 			BUMP_MIB(out_ill->ill_ip_mib,
24867 			    ipIfStatsHCOutForwDatagrams);
24868 			UPDATE_IB_PKT_COUNT(ire);
24869 		}
24870 
24871 		if (ire->ire_flags & RTF_MULTIRT) {
24872 			irb = ire->ire_bucket;
24873 			ASSERT(irb != NULL);
24874 
24875 			multirt_send = B_TRUE;
24876 
24877 			/*
24878 			 * Save the original ire; we will need to restore it
24879 			 * for the tailing frags.
24880 			 */
24881 			save_ire = ire;
24882 			IRE_REFHOLD(save_ire);
24883 		}
24884 		/*
24885 		 * Emission loop for this fragment, similar
24886 		 * to what is done for the first fragment.
24887 		 */
24888 		do {
24889 			if (multirt_send) {
24890 				/*
24891 				 * We are in a multiple send case, need to get
24892 				 * the next ire and make a copy of the packet.
24893 				 */
24894 				ASSERT(irb != NULL);
24895 				IRB_REFHOLD(irb);
24896 				for (ire1 = ire->ire_next;
24897 				    ire1 != NULL;
24898 				    ire1 = ire1->ire_next) {
24899 					if (!(ire1->ire_flags & RTF_MULTIRT))
24900 						continue;
24901 					if (ire1->ire_addr != ire->ire_addr)
24902 						continue;
24903 					if (ire1->ire_marks &
24904 					    (IRE_MARK_CONDEMNED|
24905 						IRE_MARK_HIDDEN))
24906 						continue;
24907 					/*
24908 					 * Ensure we do not exceed the MTU
24909 					 * of the next route.
24910 					 */
24911 					if (ire1->ire_max_frag < max_frag) {
24912 						ip_multirt_bad_mtu(ire1,
24913 						    max_frag);
24914 						continue;
24915 					}
24916 
24917 					/* Got one. */
24918 					IRE_REFHOLD(ire1);
24919 					break;
24920 				}
24921 				IRB_REFRELE(irb);
24922 
24923 				if (ire1 != NULL) {
24924 					next_mp = copyb(mp);
24925 					if ((next_mp == NULL) ||
24926 					    ((mp->b_cont != NULL) &&
24927 					    ((next_mp->b_cont =
24928 					    dupmsg(mp->b_cont)) == NULL))) {
24929 						freemsg(next_mp);
24930 						next_mp = NULL;
24931 						ire_refrele(ire1);
24932 						ire1 = NULL;
24933 					}
24934 				}
24935 
24936 				/* Last multiroute ire; don't loop anymore. */
24937 				if (ire1 == NULL) {
24938 					multirt_send = B_FALSE;
24939 				}
24940 			}
24941 
24942 			/* Update transmit header */
24943 			ll_hdr_len = 0;
24944 			LOCK_IRE_FP_MP(ire);
24945 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24946 			if (ll_hdr_mp != NULL) {
24947 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24948 				ll_hdr_len = MBLKL(ll_hdr_mp);
24949 			} else {
24950 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24951 			}
24952 
24953 			if (!ll_hdr_mp) {
24954 				xmit_mp = mp;
24955 
24956 			/*
24957 			 * We have link-layer header that can fit in
24958 			 * our mblk.
24959 			 */
24960 			} else if (mp->b_datap->db_ref == 1 &&
24961 			    ll_hdr_len != 0 &&
24962 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24963 				/* M_DATA fastpath */
24964 				mp->b_rptr -= ll_hdr_len;
24965 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24966 				    ll_hdr_len);
24967 				xmit_mp = mp;
24968 
24969 			/*
24970 			 * Case of res_mp OR the fastpath mp can't fit
24971 			 * in the mblk
24972 			 */
24973 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24974 				xmit_mp->b_cont = mp;
24975 				if (DB_CRED(mp) != NULL)
24976 					mblk_setcred(xmit_mp, DB_CRED(mp));
24977 				/* Get priority marking, if any. */
24978 				if (DB_TYPE(xmit_mp) == M_DATA)
24979 					xmit_mp->b_band = mp->b_band;
24980 
24981 			/* Corner case if copyb failed */
24982 			} else {
24983 				/*
24984 				 * Exit both the replication and
24985 				 * fragmentation loops.
24986 				 */
24987 				UNLOCK_IRE_FP_MP(ire);
24988 				goto drop_pkt;
24989 			}
24990 			UNLOCK_IRE_FP_MP(ire);
24991 
24992 			mp1 = mp;
24993 			out_ill = (ill_t *)q->q_ptr;
24994 
24995 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24996 
24997 			DTRACE_PROBE4(ip4__physical__out__start,
24998 			    ill_t *, NULL, ill_t *, out_ill,
24999 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25000 
25001 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25002 			    ipst->ips_ipv4firewall_physical_out,
25003 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25004 
25005 			DTRACE_PROBE1(ip4__physical__out__end,
25006 			    mblk_t *, xmit_mp);
25007 
25008 			if (mp != mp1 && hdr_mp == mp1)
25009 				hdr_mp = mp;
25010 			if (mp != mp1 && mp_orig == mp1)
25011 				mp_orig = mp;
25012 
25013 			if (xmit_mp != NULL) {
25014 				putnext(q, xmit_mp);
25015 
25016 				BUMP_MIB(out_ill->ill_ip_mib,
25017 				    ipIfStatsHCOutTransmits);
25018 				UPDATE_MIB(out_ill->ill_ip_mib,
25019 				    ipIfStatsHCOutOctets, ip_len);
25020 
25021 				if (pkt_type != OB_PKT) {
25022 					/*
25023 					 * Update the packet count of trailing
25024 					 * RTF_MULTIRT ires.
25025 					 */
25026 					UPDATE_OB_PKT_COUNT(ire);
25027 				}
25028 			}
25029 
25030 			/* All done if we just consumed the hdr_mp. */
25031 			if (mp == hdr_mp) {
25032 				last_frag = B_TRUE;
25033 				BUMP_MIB(out_ill->ill_ip_mib,
25034 				    ipIfStatsOutFragOKs);
25035 			}
25036 
25037 			if (multirt_send) {
25038 				/*
25039 				 * We are in a multiple send case; look for
25040 				 * the next ire and re-enter the loop.
25041 				 */
25042 				ASSERT(ire1);
25043 				ASSERT(next_mp);
25044 				/* REFRELE the current ire before looping */
25045 				ire_refrele(ire);
25046 				ire = ire1;
25047 				ire1 = NULL;
25048 				q = ire->ire_stq;
25049 				mp = next_mp;
25050 				next_mp = NULL;
25051 			}
25052 		} while (multirt_send);
25053 		/*
25054 		 * Restore the original ire; we need it for the
25055 		 * trailing frags
25056 		 */
25057 		if (save_ire != NULL) {
25058 			ASSERT(ire1 == NULL);
25059 			/* REFRELE the last iterated ire */
25060 			ire_refrele(ire);
25061 			/* save_ire has been REFHOLDed */
25062 			ire = save_ire;
25063 			q = ire->ire_stq;
25064 			save_ire = NULL;
25065 		}
25066 
25067 		if (last_frag) {
25068 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25069 			    "ip_wput_frag_end:(%S)",
25070 			    "consumed hdr_mp");
25071 
25072 			if (first_ire != NULL)
25073 				ire_refrele(first_ire);
25074 			return;
25075 		}
25076 		/* Otherwise, advance and loop. */
25077 		offset += len;
25078 	}
25079 
25080 drop_pkt:
25081 	/* Clean up following allocation failure. */
25082 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25083 	freemsg(mp);
25084 	if (mp != hdr_mp)
25085 		freeb(hdr_mp);
25086 	if (mp != mp_orig)
25087 		freemsg(mp_orig);
25088 
25089 	if (save_ire != NULL)
25090 		IRE_REFRELE(save_ire);
25091 	if (first_ire != NULL)
25092 		ire_refrele(first_ire);
25093 
25094 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25095 	    "ip_wput_frag_end:(%S)",
25096 	    "end--alloc failure");
25097 }
25098 
25099 /*
25100  * Copy the header plus those options which have the copy bit set
25101  */
25102 static mblk_t *
25103 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25104 {
25105 	mblk_t	*mp;
25106 	uchar_t	*up;
25107 
25108 	/*
25109 	 * Quick check if we need to look for options without the copy bit
25110 	 * set
25111 	 */
25112 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25113 	if (!mp)
25114 		return (mp);
25115 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25116 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25117 		bcopy(rptr, mp->b_rptr, hdr_len);
25118 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25119 		return (mp);
25120 	}
25121 	up  = mp->b_rptr;
25122 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25123 	up += IP_SIMPLE_HDR_LENGTH;
25124 	rptr += IP_SIMPLE_HDR_LENGTH;
25125 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25126 	while (hdr_len > 0) {
25127 		uint32_t optval;
25128 		uint32_t optlen;
25129 
25130 		optval = *rptr;
25131 		if (optval == IPOPT_EOL)
25132 			break;
25133 		if (optval == IPOPT_NOP)
25134 			optlen = 1;
25135 		else
25136 			optlen = rptr[1];
25137 		if (optval & IPOPT_COPY) {
25138 			bcopy(rptr, up, optlen);
25139 			up += optlen;
25140 		}
25141 		rptr += optlen;
25142 		hdr_len -= optlen;
25143 	}
25144 	/*
25145 	 * Make sure that we drop an even number of words by filling
25146 	 * with EOL to the next word boundary.
25147 	 */
25148 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25149 	    hdr_len & 0x3; hdr_len++)
25150 		*up++ = IPOPT_EOL;
25151 	mp->b_wptr = up;
25152 	/* Update header length */
25153 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25154 	return (mp);
25155 }
25156 
25157 /*
25158  * Delivery to local recipients including fanout to multiple recipients.
25159  * Does not do checksumming of UDP/TCP.
25160  * Note: q should be the read side queue for either the ill or conn.
25161  * Note: rq should be the read side q for the lower (ill) stream.
25162  * We don't send packets to IPPF processing, thus the last argument
25163  * to all the fanout calls are B_FALSE.
25164  */
25165 void
25166 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25167     int fanout_flags, zoneid_t zoneid)
25168 {
25169 	uint32_t	protocol;
25170 	mblk_t		*first_mp;
25171 	boolean_t	mctl_present;
25172 	int		ire_type;
25173 #define	rptr	((uchar_t *)ipha)
25174 	ip_stack_t	*ipst = ill->ill_ipst;
25175 
25176 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25177 	    "ip_wput_local_start: q %p", q);
25178 
25179 	if (ire != NULL) {
25180 		ire_type = ire->ire_type;
25181 	} else {
25182 		/*
25183 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25184 		 * packet is not multicast, we can't tell the ire type.
25185 		 */
25186 		ASSERT(CLASSD(ipha->ipha_dst));
25187 		ire_type = IRE_BROADCAST;
25188 	}
25189 
25190 	first_mp = mp;
25191 	if (first_mp->b_datap->db_type == M_CTL) {
25192 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25193 		if (!io->ipsec_out_secure) {
25194 			/*
25195 			 * This ipsec_out_t was allocated in ip_wput
25196 			 * for multicast packets to store the ill_index.
25197 			 * As this is being delivered locally, we don't
25198 			 * need this anymore.
25199 			 */
25200 			mp = first_mp->b_cont;
25201 			freeb(first_mp);
25202 			first_mp = mp;
25203 			mctl_present = B_FALSE;
25204 		} else {
25205 			/*
25206 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25207 			 * security properties for the looped-back packet.
25208 			 */
25209 			mctl_present = B_TRUE;
25210 			mp = first_mp->b_cont;
25211 			ASSERT(mp != NULL);
25212 			ipsec_out_to_in(first_mp);
25213 		}
25214 	} else {
25215 		mctl_present = B_FALSE;
25216 	}
25217 
25218 	DTRACE_PROBE4(ip4__loopback__in__start,
25219 	    ill_t *, ill, ill_t *, NULL,
25220 	    ipha_t *, ipha, mblk_t *, first_mp);
25221 
25222 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25223 	    ipst->ips_ipv4firewall_loopback_in,
25224 	    ill, NULL, ipha, first_mp, mp, ipst);
25225 
25226 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25227 
25228 	if (first_mp == NULL)
25229 		return;
25230 
25231 	ipst->ips_loopback_packets++;
25232 
25233 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25234 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25235 	if (!IS_SIMPLE_IPH(ipha)) {
25236 		ip_wput_local_options(ipha, ipst);
25237 	}
25238 
25239 	protocol = ipha->ipha_protocol;
25240 	switch (protocol) {
25241 	case IPPROTO_ICMP: {
25242 		ire_t		*ire_zone;
25243 		ilm_t		*ilm;
25244 		mblk_t		*mp1;
25245 		zoneid_t	last_zoneid;
25246 
25247 		if (CLASSD(ipha->ipha_dst) &&
25248 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
25249 			ASSERT(ire_type == IRE_BROADCAST);
25250 			/*
25251 			 * In the multicast case, applications may have joined
25252 			 * the group from different zones, so we need to deliver
25253 			 * the packet to each of them. Loop through the
25254 			 * multicast memberships structures (ilm) on the receive
25255 			 * ill and send a copy of the packet up each matching
25256 			 * one. However, we don't do this for multicasts sent on
25257 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25258 			 * they must stay in the sender's zone.
25259 			 *
25260 			 * ilm_add_v6() ensures that ilms in the same zone are
25261 			 * contiguous in the ill_ilm list. We use this property
25262 			 * to avoid sending duplicates needed when two
25263 			 * applications in the same zone join the same group on
25264 			 * different logical interfaces: we ignore the ilm if
25265 			 * it's zoneid is the same as the last matching one.
25266 			 * In addition, the sending of the packet for
25267 			 * ire_zoneid is delayed until all of the other ilms
25268 			 * have been exhausted.
25269 			 */
25270 			last_zoneid = -1;
25271 			ILM_WALKER_HOLD(ill);
25272 			for (ilm = ill->ill_ilm; ilm != NULL;
25273 			    ilm = ilm->ilm_next) {
25274 				if ((ilm->ilm_flags & ILM_DELETED) ||
25275 				    ipha->ipha_dst != ilm->ilm_addr ||
25276 				    ilm->ilm_zoneid == last_zoneid ||
25277 				    ilm->ilm_zoneid == zoneid ||
25278 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25279 					continue;
25280 				mp1 = ip_copymsg(first_mp);
25281 				if (mp1 == NULL)
25282 					continue;
25283 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25284 				    mctl_present, B_FALSE, ill,
25285 				    ilm->ilm_zoneid);
25286 				last_zoneid = ilm->ilm_zoneid;
25287 			}
25288 			ILM_WALKER_RELE(ill);
25289 			/*
25290 			 * Loopback case: the sending endpoint has
25291 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25292 			 * dispatch the multicast packet to the sending zone.
25293 			 */
25294 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25295 				freemsg(first_mp);
25296 				return;
25297 			}
25298 		} else if (ire_type == IRE_BROADCAST) {
25299 			/*
25300 			 * In the broadcast case, there may be many zones
25301 			 * which need a copy of the packet delivered to them.
25302 			 * There is one IRE_BROADCAST per broadcast address
25303 			 * and per zone; we walk those using a helper function.
25304 			 * In addition, the sending of the packet for zoneid is
25305 			 * delayed until all of the other ires have been
25306 			 * processed.
25307 			 */
25308 			IRB_REFHOLD(ire->ire_bucket);
25309 			ire_zone = NULL;
25310 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25311 			    ire)) != NULL) {
25312 				mp1 = ip_copymsg(first_mp);
25313 				if (mp1 == NULL)
25314 					continue;
25315 
25316 				UPDATE_IB_PKT_COUNT(ire_zone);
25317 				ire_zone->ire_last_used_time = lbolt;
25318 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25319 				    mctl_present, B_FALSE, ill,
25320 				    ire_zone->ire_zoneid);
25321 			}
25322 			IRB_REFRELE(ire->ire_bucket);
25323 		}
25324 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25325 		    0, mctl_present, B_FALSE, ill, zoneid);
25326 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25327 		    "ip_wput_local_end: q %p (%S)",
25328 		    q, "icmp");
25329 		return;
25330 	}
25331 	case IPPROTO_IGMP:
25332 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25333 			/* Bad packet - discarded by igmp_input */
25334 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25335 			    "ip_wput_local_end: q %p (%S)",
25336 			    q, "igmp_input--bad packet");
25337 			if (mctl_present)
25338 				freeb(first_mp);
25339 			return;
25340 		}
25341 		/*
25342 		 * igmp_input() may have returned the pulled up message.
25343 		 * So first_mp and ipha need to be reinitialized.
25344 		 */
25345 		ipha = (ipha_t *)mp->b_rptr;
25346 		if (mctl_present)
25347 			first_mp->b_cont = mp;
25348 		else
25349 			first_mp = mp;
25350 		/* deliver to local raw users */
25351 		break;
25352 	case IPPROTO_ENCAP:
25353 		/*
25354 		 * This case is covered by either ip_fanout_proto, or by
25355 		 * the above security processing for self-tunneled packets.
25356 		 */
25357 		break;
25358 	case IPPROTO_UDP: {
25359 		uint16_t	*up;
25360 		uint32_t	ports;
25361 
25362 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25363 		    UDP_PORTS_OFFSET);
25364 		/* Force a 'valid' checksum. */
25365 		up[3] = 0;
25366 
25367 		ports = *(uint32_t *)up;
25368 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25369 		    (ire_type == IRE_BROADCAST),
25370 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25371 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25372 		    ill, zoneid);
25373 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25374 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25375 		return;
25376 	}
25377 	case IPPROTO_TCP: {
25378 
25379 		/*
25380 		 * For TCP, discard broadcast packets.
25381 		 */
25382 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25383 			freemsg(first_mp);
25384 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25385 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25386 			return;
25387 		}
25388 
25389 		if (mp->b_datap->db_type == M_DATA) {
25390 			/*
25391 			 * M_DATA mblk, so init mblk (chain) for no struio().
25392 			 */
25393 			mblk_t	*mp1 = mp;
25394 
25395 			do
25396 				mp1->b_datap->db_struioflag = 0;
25397 			while ((mp1 = mp1->b_cont) != NULL);
25398 		}
25399 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25400 		    <= mp->b_wptr);
25401 		ip_fanout_tcp(q, first_mp, ill, ipha,
25402 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25403 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25404 		    mctl_present, B_FALSE, zoneid);
25405 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25406 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25407 		return;
25408 	}
25409 	case IPPROTO_SCTP:
25410 	{
25411 		uint32_t	ports;
25412 
25413 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25414 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25415 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25416 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25417 		return;
25418 	}
25419 
25420 	default:
25421 		break;
25422 	}
25423 	/*
25424 	 * Find a client for some other protocol.  We give
25425 	 * copies to multiple clients, if more than one is
25426 	 * bound.
25427 	 */
25428 	ip_fanout_proto(q, first_mp, ill, ipha,
25429 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25430 	    mctl_present, B_FALSE, ill, zoneid);
25431 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25432 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25433 #undef	rptr
25434 }
25435 
25436 /*
25437  * Update any source route, record route, or timestamp options.
25438  * Check that we are at end of strict source route.
25439  * The options have been sanity checked by ip_wput_options().
25440  */
25441 static void
25442 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25443 {
25444 	ipoptp_t	opts;
25445 	uchar_t		*opt;
25446 	uint8_t		optval;
25447 	uint8_t		optlen;
25448 	ipaddr_t	dst;
25449 	uint32_t	ts;
25450 	ire_t		*ire;
25451 	timestruc_t	now;
25452 
25453 	ip2dbg(("ip_wput_local_options\n"));
25454 	for (optval = ipoptp_first(&opts, ipha);
25455 	    optval != IPOPT_EOL;
25456 	    optval = ipoptp_next(&opts)) {
25457 		opt = opts.ipoptp_cur;
25458 		optlen = opts.ipoptp_len;
25459 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25460 		switch (optval) {
25461 			uint32_t off;
25462 		case IPOPT_SSRR:
25463 		case IPOPT_LSRR:
25464 			off = opt[IPOPT_OFFSET];
25465 			off--;
25466 			if (optlen < IP_ADDR_LEN ||
25467 			    off > optlen - IP_ADDR_LEN) {
25468 				/* End of source route */
25469 				break;
25470 			}
25471 			/*
25472 			 * This will only happen if two consecutive entries
25473 			 * in the source route contains our address or if
25474 			 * it is a packet with a loose source route which
25475 			 * reaches us before consuming the whole source route
25476 			 */
25477 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25478 			if (optval == IPOPT_SSRR) {
25479 				return;
25480 			}
25481 			/*
25482 			 * Hack: instead of dropping the packet truncate the
25483 			 * source route to what has been used by filling the
25484 			 * rest with IPOPT_NOP.
25485 			 */
25486 			opt[IPOPT_OLEN] = (uint8_t)off;
25487 			while (off < optlen) {
25488 				opt[off++] = IPOPT_NOP;
25489 			}
25490 			break;
25491 		case IPOPT_RR:
25492 			off = opt[IPOPT_OFFSET];
25493 			off--;
25494 			if (optlen < IP_ADDR_LEN ||
25495 			    off > optlen - IP_ADDR_LEN) {
25496 				/* No more room - ignore */
25497 				ip1dbg((
25498 				    "ip_wput_forward_options: end of RR\n"));
25499 				break;
25500 			}
25501 			dst = htonl(INADDR_LOOPBACK);
25502 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25503 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25504 			break;
25505 		case IPOPT_TS:
25506 			/* Insert timestamp if there is romm */
25507 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25508 			case IPOPT_TS_TSONLY:
25509 				off = IPOPT_TS_TIMELEN;
25510 				break;
25511 			case IPOPT_TS_PRESPEC:
25512 			case IPOPT_TS_PRESPEC_RFC791:
25513 				/* Verify that the address matched */
25514 				off = opt[IPOPT_OFFSET] - 1;
25515 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25516 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25517 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25518 				    ipst);
25519 				if (ire == NULL) {
25520 					/* Not for us */
25521 					break;
25522 				}
25523 				ire_refrele(ire);
25524 				/* FALLTHRU */
25525 			case IPOPT_TS_TSANDADDR:
25526 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25527 				break;
25528 			default:
25529 				/*
25530 				 * ip_*put_options should have already
25531 				 * dropped this packet.
25532 				 */
25533 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25534 				    "unknown IT - bug in ip_wput_options?\n");
25535 				return;	/* Keep "lint" happy */
25536 			}
25537 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25538 				/* Increase overflow counter */
25539 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25540 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25541 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25542 				    (off << 4);
25543 				break;
25544 			}
25545 			off = opt[IPOPT_OFFSET] - 1;
25546 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25547 			case IPOPT_TS_PRESPEC:
25548 			case IPOPT_TS_PRESPEC_RFC791:
25549 			case IPOPT_TS_TSANDADDR:
25550 				dst = htonl(INADDR_LOOPBACK);
25551 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25552 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25553 				/* FALLTHRU */
25554 			case IPOPT_TS_TSONLY:
25555 				off = opt[IPOPT_OFFSET] - 1;
25556 				/* Compute # of milliseconds since midnight */
25557 				gethrestime(&now);
25558 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25559 				    now.tv_nsec / (NANOSEC / MILLISEC);
25560 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25561 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25562 				break;
25563 			}
25564 			break;
25565 		}
25566 	}
25567 }
25568 
25569 /*
25570  * Send out a multicast packet on interface ipif.
25571  * The sender does not have an conn.
25572  * Caller verifies that this isn't a PHYI_LOOPBACK.
25573  */
25574 void
25575 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25576 {
25577 	ipha_t	*ipha;
25578 	ire_t	*ire;
25579 	ipaddr_t	dst;
25580 	mblk_t		*first_mp;
25581 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25582 
25583 	/* igmp_sendpkt always allocates a ipsec_out_t */
25584 	ASSERT(mp->b_datap->db_type == M_CTL);
25585 	ASSERT(!ipif->ipif_isv6);
25586 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25587 
25588 	first_mp = mp;
25589 	mp = first_mp->b_cont;
25590 	ASSERT(mp->b_datap->db_type == M_DATA);
25591 	ipha = (ipha_t *)mp->b_rptr;
25592 
25593 	/*
25594 	 * Find an IRE which matches the destination and the outgoing
25595 	 * queue (i.e. the outgoing interface.)
25596 	 */
25597 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25598 		dst = ipif->ipif_pp_dst_addr;
25599 	else
25600 		dst = ipha->ipha_dst;
25601 	/*
25602 	 * The source address has already been initialized by the
25603 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25604 	 * be sufficient rather than MATCH_IRE_IPIF.
25605 	 *
25606 	 * This function is used for sending IGMP packets. We need
25607 	 * to make sure that we send the packet out of the interface
25608 	 * (ipif->ipif_ill) where we joined the group. This is to
25609 	 * prevent from switches doing IGMP snooping to send us multicast
25610 	 * packets for a given group on the interface we have joined.
25611 	 * If we can't find an ire, igmp_sendpkt has already initialized
25612 	 * ipsec_out_attach_if so that this will not be load spread in
25613 	 * ip_newroute_ipif.
25614 	 */
25615 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25616 	    MATCH_IRE_ILL, ipst);
25617 	if (!ire) {
25618 		/*
25619 		 * Mark this packet to make it be delivered to
25620 		 * ip_wput_ire after the new ire has been
25621 		 * created.
25622 		 */
25623 		mp->b_prev = NULL;
25624 		mp->b_next = NULL;
25625 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25626 		    zoneid, &zero_info);
25627 		return;
25628 	}
25629 
25630 	/*
25631 	 * Honor the RTF_SETSRC flag; this is the only case
25632 	 * where we force this addr whatever the current src addr is,
25633 	 * because this address is set by igmp_sendpkt(), and
25634 	 * cannot be specified by any user.
25635 	 */
25636 	if (ire->ire_flags & RTF_SETSRC) {
25637 		ipha->ipha_src = ire->ire_src_addr;
25638 	}
25639 
25640 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25641 }
25642 
25643 /*
25644  * NOTE : This function does not ire_refrele the ire argument passed in.
25645  *
25646  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25647  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25648  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25649  * the ire_lock to access the nce_fp_mp in this case.
25650  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25651  * prepending a fastpath message IPQoS processing must precede it, we also set
25652  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25653  * (IPQoS might have set the b_band for CoS marking).
25654  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25655  * must follow it so that IPQoS can mark the dl_priority field for CoS
25656  * marking, if needed.
25657  */
25658 static mblk_t *
25659 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25660 {
25661 	uint_t	hlen;
25662 	ipha_t *ipha;
25663 	mblk_t *mp1;
25664 	boolean_t qos_done = B_FALSE;
25665 	uchar_t	*ll_hdr;
25666 	ip_stack_t	*ipst = ire->ire_ipst;
25667 
25668 #define	rptr	((uchar_t *)ipha)
25669 
25670 	ipha = (ipha_t *)mp->b_rptr;
25671 	hlen = 0;
25672 	LOCK_IRE_FP_MP(ire);
25673 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25674 		ASSERT(DB_TYPE(mp1) == M_DATA);
25675 		/* Initiate IPPF processing */
25676 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25677 			UNLOCK_IRE_FP_MP(ire);
25678 			ip_process(proc, &mp, ill_index);
25679 			if (mp == NULL)
25680 				return (NULL);
25681 
25682 			ipha = (ipha_t *)mp->b_rptr;
25683 			LOCK_IRE_FP_MP(ire);
25684 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25685 				qos_done = B_TRUE;
25686 				goto no_fp_mp;
25687 			}
25688 			ASSERT(DB_TYPE(mp1) == M_DATA);
25689 		}
25690 		hlen = MBLKL(mp1);
25691 		/*
25692 		 * Check if we have enough room to prepend fastpath
25693 		 * header
25694 		 */
25695 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25696 			ll_hdr = rptr - hlen;
25697 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25698 			/*
25699 			 * Set the b_rptr to the start of the link layer
25700 			 * header
25701 			 */
25702 			mp->b_rptr = ll_hdr;
25703 			mp1 = mp;
25704 		} else {
25705 			mp1 = copyb(mp1);
25706 			if (mp1 == NULL)
25707 				goto unlock_err;
25708 			mp1->b_band = mp->b_band;
25709 			mp1->b_cont = mp;
25710 			/*
25711 			 * certain system generated traffic may not
25712 			 * have cred/label in ip header block. This
25713 			 * is true even for a labeled system. But for
25714 			 * labeled traffic, inherit the label in the
25715 			 * new header.
25716 			 */
25717 			if (DB_CRED(mp) != NULL)
25718 				mblk_setcred(mp1, DB_CRED(mp));
25719 			/*
25720 			 * XXX disable ICK_VALID and compute checksum
25721 			 * here; can happen if nce_fp_mp changes and
25722 			 * it can't be copied now due to insufficient
25723 			 * space. (unlikely, fp mp can change, but it
25724 			 * does not increase in length)
25725 			 */
25726 		}
25727 		UNLOCK_IRE_FP_MP(ire);
25728 	} else {
25729 no_fp_mp:
25730 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25731 		if (mp1 == NULL) {
25732 unlock_err:
25733 			UNLOCK_IRE_FP_MP(ire);
25734 			freemsg(mp);
25735 			return (NULL);
25736 		}
25737 		UNLOCK_IRE_FP_MP(ire);
25738 		mp1->b_cont = mp;
25739 		/*
25740 		 * certain system generated traffic may not
25741 		 * have cred/label in ip header block. This
25742 		 * is true even for a labeled system. But for
25743 		 * labeled traffic, inherit the label in the
25744 		 * new header.
25745 		 */
25746 		if (DB_CRED(mp) != NULL)
25747 			mblk_setcred(mp1, DB_CRED(mp));
25748 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25749 			ip_process(proc, &mp1, ill_index);
25750 			if (mp1 == NULL)
25751 				return (NULL);
25752 		}
25753 	}
25754 	return (mp1);
25755 #undef rptr
25756 }
25757 
25758 /*
25759  * Finish the outbound IPsec processing for an IPv6 packet. This function
25760  * is called from ipsec_out_process() if the IPsec packet was processed
25761  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25762  * asynchronously.
25763  */
25764 void
25765 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25766     ire_t *ire_arg)
25767 {
25768 	in6_addr_t *v6dstp;
25769 	ire_t *ire;
25770 	mblk_t *mp;
25771 	ip6_t *ip6h1;
25772 	uint_t	ill_index;
25773 	ipsec_out_t *io;
25774 	boolean_t attach_if, hwaccel;
25775 	uint32_t flags = IP6_NO_IPPOLICY;
25776 	int match_flags;
25777 	zoneid_t zoneid;
25778 	boolean_t ill_need_rele = B_FALSE;
25779 	boolean_t ire_need_rele = B_FALSE;
25780 	ip_stack_t	*ipst;
25781 
25782 	mp = ipsec_mp->b_cont;
25783 	ip6h1 = (ip6_t *)mp->b_rptr;
25784 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25785 	ASSERT(io->ipsec_out_ns != NULL);
25786 	ipst = io->ipsec_out_ns->netstack_ip;
25787 	ill_index = io->ipsec_out_ill_index;
25788 	if (io->ipsec_out_reachable) {
25789 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25790 	}
25791 	attach_if = io->ipsec_out_attach_if;
25792 	hwaccel = io->ipsec_out_accelerated;
25793 	zoneid = io->ipsec_out_zoneid;
25794 	ASSERT(zoneid != ALL_ZONES);
25795 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25796 	/* Multicast addresses should have non-zero ill_index. */
25797 	v6dstp = &ip6h->ip6_dst;
25798 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25799 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25800 	ASSERT(!attach_if || ill_index != 0);
25801 	if (ill_index != 0) {
25802 		if (ill == NULL) {
25803 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25804 			    B_TRUE, ipst);
25805 
25806 			/* Failure case frees things for us. */
25807 			if (ill == NULL)
25808 				return;
25809 
25810 			ill_need_rele = B_TRUE;
25811 		}
25812 		/*
25813 		 * If this packet needs to go out on a particular interface
25814 		 * honor it.
25815 		 */
25816 		if (attach_if) {
25817 			match_flags = MATCH_IRE_ILL;
25818 
25819 			/*
25820 			 * Check if we need an ire that will not be
25821 			 * looked up by anybody else i.e. HIDDEN.
25822 			 */
25823 			if (ill_is_probeonly(ill)) {
25824 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25825 			}
25826 		}
25827 	}
25828 	ASSERT(mp != NULL);
25829 
25830 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25831 		boolean_t unspec_src;
25832 		ipif_t	*ipif;
25833 
25834 		/*
25835 		 * Use the ill_index to get the right ill.
25836 		 */
25837 		unspec_src = io->ipsec_out_unspec_src;
25838 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25839 		if (ipif == NULL) {
25840 			if (ill_need_rele)
25841 				ill_refrele(ill);
25842 			freemsg(ipsec_mp);
25843 			return;
25844 		}
25845 
25846 		if (ire_arg != NULL) {
25847 			ire = ire_arg;
25848 		} else {
25849 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25850 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25851 			ire_need_rele = B_TRUE;
25852 		}
25853 		if (ire != NULL) {
25854 			ipif_refrele(ipif);
25855 			/*
25856 			 * XXX Do the multicast forwarding now, as the IPSEC
25857 			 * processing has been done.
25858 			 */
25859 			goto send;
25860 		}
25861 
25862 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: 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_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25878 		    unspec_src, zoneid);
25879 		ipif_refrele(ipif);
25880 	} else {
25881 		if (attach_if) {
25882 			ipif_t	*ipif;
25883 
25884 			ipif = ipif_get_next_ipif(NULL, ill);
25885 			if (ipif == NULL) {
25886 				if (ill_need_rele)
25887 					ill_refrele(ill);
25888 				freemsg(ipsec_mp);
25889 				return;
25890 			}
25891 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25892 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25893 			ire_need_rele = B_TRUE;
25894 			ipif_refrele(ipif);
25895 		} else {
25896 			if (ire_arg != NULL) {
25897 				ire = ire_arg;
25898 			} else {
25899 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25900 				    ipst);
25901 				ire_need_rele = B_TRUE;
25902 			}
25903 		}
25904 		if (ire != NULL)
25905 			goto send;
25906 		/*
25907 		 * ire disappeared underneath.
25908 		 *
25909 		 * What we need to do here is the ip_newroute
25910 		 * logic to get the ire without doing the IPSEC
25911 		 * processing. Follow the same old path. But this
25912 		 * time, ip_wput or ire_add_then_send will call us
25913 		 * directly as all the IPSEC operations are done.
25914 		 */
25915 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25916 		mp->b_prev = NULL;
25917 		mp->b_next = NULL;
25918 
25919 		/*
25920 		 * If the IPsec packet was processed asynchronously,
25921 		 * drop it now.
25922 		 */
25923 		if (q == NULL) {
25924 			if (ill_need_rele)
25925 				ill_refrele(ill);
25926 			freemsg(ipsec_mp);
25927 			return;
25928 		}
25929 
25930 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25931 		    zoneid, ipst);
25932 	}
25933 	if (ill != NULL && ill_need_rele)
25934 		ill_refrele(ill);
25935 	return;
25936 send:
25937 	if (ill != NULL && ill_need_rele)
25938 		ill_refrele(ill);
25939 
25940 	/* Local delivery */
25941 	if (ire->ire_stq == NULL) {
25942 		ill_t	*out_ill;
25943 		ASSERT(q != NULL);
25944 
25945 		/* PFHooks: LOOPBACK_OUT */
25946 		out_ill = ire->ire_ipif->ipif_ill;
25947 
25948 		DTRACE_PROBE4(ip6__loopback__out__start,
25949 		    ill_t *, NULL, ill_t *, out_ill,
25950 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25951 
25952 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25953 		    ipst->ips_ipv6firewall_loopback_out,
25954 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25955 
25956 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25957 
25958 		if (ipsec_mp != NULL)
25959 			ip_wput_local_v6(RD(q), out_ill,
25960 			    ip6h, ipsec_mp, ire, 0);
25961 		if (ire_need_rele)
25962 			ire_refrele(ire);
25963 		return;
25964 	}
25965 	/*
25966 	 * Everything is done. Send it out on the wire.
25967 	 * We force the insertion of a fragment header using the
25968 	 * IPH_FRAG_HDR flag in two cases:
25969 	 * - after reception of an ICMPv6 "packet too big" message
25970 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25971 	 * - for multirouted IPv6 packets, so that the receiver can
25972 	 *   discard duplicates according to their fragment identifier
25973 	 */
25974 	/* XXX fix flow control problems. */
25975 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25976 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25977 		if (hwaccel) {
25978 			/*
25979 			 * hardware acceleration does not handle these
25980 			 * "slow path" cases.
25981 			 */
25982 			/* IPsec KSTATS: should bump bean counter here. */
25983 			if (ire_need_rele)
25984 				ire_refrele(ire);
25985 			freemsg(ipsec_mp);
25986 			return;
25987 		}
25988 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25989 		    (mp->b_cont ? msgdsize(mp) :
25990 		    mp->b_wptr - (uchar_t *)ip6h)) {
25991 			/* IPsec KSTATS: should bump bean counter here. */
25992 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25993 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25994 			    msgdsize(mp)));
25995 			if (ire_need_rele)
25996 				ire_refrele(ire);
25997 			freemsg(ipsec_mp);
25998 			return;
25999 		}
26000 		ASSERT(mp->b_prev == NULL);
26001 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26002 		    ntohs(ip6h->ip6_plen) +
26003 		    IPV6_HDR_LEN, ire->ire_max_frag));
26004 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26005 		    ire->ire_max_frag);
26006 	} else {
26007 		UPDATE_OB_PKT_COUNT(ire);
26008 		ire->ire_last_used_time = lbolt;
26009 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26010 	}
26011 	if (ire_need_rele)
26012 		ire_refrele(ire);
26013 	freeb(ipsec_mp);
26014 }
26015 
26016 void
26017 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26018 {
26019 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26020 	da_ipsec_t *hada;	/* data attributes */
26021 	ill_t *ill = (ill_t *)q->q_ptr;
26022 
26023 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26024 
26025 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26026 		/* IPsec KSTATS: Bump lose counter here! */
26027 		freemsg(mp);
26028 		return;
26029 	}
26030 
26031 	/*
26032 	 * It's an IPsec packet that must be
26033 	 * accelerated by the Provider, and the
26034 	 * outbound ill is IPsec acceleration capable.
26035 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26036 	 * to the ill.
26037 	 * IPsec KSTATS: should bump packet counter here.
26038 	 */
26039 
26040 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26041 	if (hada_mp == NULL) {
26042 		/* IPsec KSTATS: should bump packet counter here. */
26043 		freemsg(mp);
26044 		return;
26045 	}
26046 
26047 	hada_mp->b_datap->db_type = M_CTL;
26048 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26049 	hada_mp->b_cont = mp;
26050 
26051 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26052 	bzero(hada, sizeof (da_ipsec_t));
26053 	hada->da_type = IPHADA_M_CTL;
26054 
26055 	putnext(q, hada_mp);
26056 }
26057 
26058 /*
26059  * Finish the outbound IPsec processing. This function is called from
26060  * ipsec_out_process() if the IPsec packet was processed
26061  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26062  * asynchronously.
26063  */
26064 void
26065 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26066     ire_t *ire_arg)
26067 {
26068 	uint32_t v_hlen_tos_len;
26069 	ipaddr_t	dst;
26070 	ipif_t	*ipif = NULL;
26071 	ire_t *ire;
26072 	ire_t *ire1 = NULL;
26073 	mblk_t *next_mp = NULL;
26074 	uint32_t max_frag;
26075 	boolean_t multirt_send = B_FALSE;
26076 	mblk_t *mp;
26077 	mblk_t *mp1;
26078 	ipha_t *ipha1;
26079 	uint_t	ill_index;
26080 	ipsec_out_t *io;
26081 	boolean_t attach_if;
26082 	int match_flags, offset;
26083 	irb_t *irb = NULL;
26084 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26085 	zoneid_t zoneid;
26086 	uint32_t cksum;
26087 	uint16_t *up;
26088 	ipxmit_state_t	pktxmit_state;
26089 	ip_stack_t	*ipst;
26090 
26091 #ifdef	_BIG_ENDIAN
26092 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26093 #else
26094 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26095 #endif
26096 
26097 	mp = ipsec_mp->b_cont;
26098 	ipha1 = (ipha_t *)mp->b_rptr;
26099 	ASSERT(mp != NULL);
26100 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26101 	dst = ipha->ipha_dst;
26102 
26103 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26104 	ill_index = io->ipsec_out_ill_index;
26105 	attach_if = io->ipsec_out_attach_if;
26106 	zoneid = io->ipsec_out_zoneid;
26107 	ASSERT(zoneid != ALL_ZONES);
26108 	ipst = io->ipsec_out_ns->netstack_ip;
26109 	ASSERT(io->ipsec_out_ns != NULL);
26110 
26111 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26112 	if (ill_index != 0) {
26113 		if (ill == NULL) {
26114 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26115 			    ill_index, B_FALSE, ipst);
26116 
26117 			/* Failure case frees things for us. */
26118 			if (ill == NULL)
26119 				return;
26120 
26121 			ill_need_rele = B_TRUE;
26122 		}
26123 		/*
26124 		 * If this packet needs to go out on a particular interface
26125 		 * honor it.
26126 		 */
26127 		if (attach_if) {
26128 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26129 
26130 			/*
26131 			 * Check if we need an ire that will not be
26132 			 * looked up by anybody else i.e. HIDDEN.
26133 			 */
26134 			if (ill_is_probeonly(ill)) {
26135 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26136 			}
26137 		}
26138 	}
26139 
26140 	if (CLASSD(dst)) {
26141 		boolean_t conn_dontroute;
26142 		/*
26143 		 * Use the ill_index to get the right ipif.
26144 		 */
26145 		conn_dontroute = io->ipsec_out_dontroute;
26146 		if (ill_index == 0)
26147 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26148 		else
26149 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26150 		if (ipif == NULL) {
26151 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26152 			    " multicast\n"));
26153 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26154 			freemsg(ipsec_mp);
26155 			goto done;
26156 		}
26157 		/*
26158 		 * ipha_src has already been intialized with the
26159 		 * value of the ipif in ip_wput. All we need now is
26160 		 * an ire to send this downstream.
26161 		 */
26162 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26163 		    MBLK_GETLABEL(mp), match_flags, ipst);
26164 		if (ire != NULL) {
26165 			ill_t *ill1;
26166 			/*
26167 			 * Do the multicast forwarding now, as the IPSEC
26168 			 * processing has been done.
26169 			 */
26170 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26171 			    (ill1 = ire_to_ill(ire))) {
26172 				if (ip_mforward(ill1, ipha, mp)) {
26173 					freemsg(ipsec_mp);
26174 					ip1dbg(("ip_wput_ipsec_out: mforward "
26175 					    "failed\n"));
26176 					ire_refrele(ire);
26177 					goto done;
26178 				}
26179 			}
26180 			goto send;
26181 		}
26182 
26183 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26184 		mp->b_prev = NULL;
26185 		mp->b_next = NULL;
26186 
26187 		/*
26188 		 * If the IPsec packet was processed asynchronously,
26189 		 * drop it now.
26190 		 */
26191 		if (q == NULL) {
26192 			freemsg(ipsec_mp);
26193 			goto done;
26194 		}
26195 
26196 		/*
26197 		 * We may be using a wrong ipif to create the ire.
26198 		 * But it is okay as the source address is assigned
26199 		 * for the packet already. Next outbound packet would
26200 		 * create the IRE with the right IPIF in ip_wput.
26201 		 *
26202 		 * Also handle RTF_MULTIRT routes.
26203 		 */
26204 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26205 		    zoneid, &zero_info);
26206 	} else {
26207 		if (attach_if) {
26208 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26209 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26210 		} else {
26211 			if (ire_arg != NULL) {
26212 				ire = ire_arg;
26213 				ire_need_rele = B_FALSE;
26214 			} else {
26215 				ire = ire_cache_lookup(dst, zoneid,
26216 				    MBLK_GETLABEL(mp), ipst);
26217 			}
26218 		}
26219 		if (ire != NULL) {
26220 			goto send;
26221 		}
26222 
26223 		/*
26224 		 * ire disappeared underneath.
26225 		 *
26226 		 * What we need to do here is the ip_newroute
26227 		 * logic to get the ire without doing the IPSEC
26228 		 * processing. Follow the same old path. But this
26229 		 * time, ip_wput or ire_add_then_put will call us
26230 		 * directly as all the IPSEC operations are done.
26231 		 */
26232 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26233 		mp->b_prev = NULL;
26234 		mp->b_next = NULL;
26235 
26236 		/*
26237 		 * If the IPsec packet was processed asynchronously,
26238 		 * drop it now.
26239 		 */
26240 		if (q == NULL) {
26241 			freemsg(ipsec_mp);
26242 			goto done;
26243 		}
26244 
26245 		/*
26246 		 * Since we're going through ip_newroute() again, we
26247 		 * need to make sure we don't:
26248 		 *
26249 		 *	1.) Trigger the ASSERT() with the ipha_ident
26250 		 *	    overloading.
26251 		 *	2.) Redo transport-layer checksumming, since we've
26252 		 *	    already done all that to get this far.
26253 		 *
26254 		 * The easiest way not do either of the above is to set
26255 		 * the ipha_ident field to IP_HDR_INCLUDED.
26256 		 */
26257 		ipha->ipha_ident = IP_HDR_INCLUDED;
26258 		ip_newroute(q, ipsec_mp, dst, NULL,
26259 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26260 	}
26261 	goto done;
26262 send:
26263 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26264 	    udp_compute_checksum(ipst->ips_netstack)) {
26265 		/*
26266 		 * ESP NAT-Traversal packet.
26267 		 *
26268 		 * Just do software checksum for now.
26269 		 */
26270 
26271 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26272 		IP_STAT(ipst, ip_out_sw_cksum);
26273 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26274 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26275 #define	iphs	((uint16_t *)ipha)
26276 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26277 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26278 		    IP_SIMPLE_HDR_LENGTH);
26279 #undef iphs
26280 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
26281 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26282 			if (mp1->b_wptr - mp1->b_rptr >=
26283 			    offset + sizeof (uint16_t)) {
26284 				up = (uint16_t *)(mp1->b_rptr + offset);
26285 				*up = cksum;
26286 				break;	/* out of for loop */
26287 			} else {
26288 				offset -= (mp->b_wptr - mp->b_rptr);
26289 			}
26290 	} /* Otherwise, just keep the all-zero checksum. */
26291 
26292 	if (ire->ire_stq == NULL) {
26293 		ill_t	*out_ill;
26294 		/*
26295 		 * Loopbacks go through ip_wput_local except for one case.
26296 		 * We come here if we generate a icmp_frag_needed message
26297 		 * after IPSEC processing is over. When this function calls
26298 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26299 		 * icmp_frag_needed. The message generated comes back here
26300 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26301 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26302 		 * source address as it is usually set in ip_wput_ire. As
26303 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26304 		 * and we end up here. We can't enter ip_wput_ire once the
26305 		 * IPSEC processing is over and hence we need to do it here.
26306 		 */
26307 		ASSERT(q != NULL);
26308 		UPDATE_OB_PKT_COUNT(ire);
26309 		ire->ire_last_used_time = lbolt;
26310 		if (ipha->ipha_src == 0)
26311 			ipha->ipha_src = ire->ire_src_addr;
26312 
26313 		/* PFHooks: LOOPBACK_OUT */
26314 		out_ill = ire->ire_ipif->ipif_ill;
26315 
26316 		DTRACE_PROBE4(ip4__loopback__out__start,
26317 		    ill_t *, NULL, ill_t *, out_ill,
26318 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26319 
26320 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26321 		    ipst->ips_ipv4firewall_loopback_out,
26322 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26323 
26324 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26325 
26326 		if (ipsec_mp != NULL)
26327 			ip_wput_local(RD(q), out_ill,
26328 			    ipha, ipsec_mp, ire, 0, zoneid);
26329 		if (ire_need_rele)
26330 			ire_refrele(ire);
26331 		goto done;
26332 	}
26333 
26334 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26335 		/*
26336 		 * We are through with IPSEC processing.
26337 		 * Fragment this and send it on the wire.
26338 		 */
26339 		if (io->ipsec_out_accelerated) {
26340 			/*
26341 			 * The packet has been accelerated but must
26342 			 * be fragmented. This should not happen
26343 			 * since AH and ESP must not accelerate
26344 			 * packets that need fragmentation, however
26345 			 * the configuration could have changed
26346 			 * since the AH or ESP processing.
26347 			 * Drop packet.
26348 			 * IPsec KSTATS: bump bean counter here.
26349 			 */
26350 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26351 			    "fragmented accelerated packet!\n"));
26352 			freemsg(ipsec_mp);
26353 		} else {
26354 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26355 		}
26356 		if (ire_need_rele)
26357 			ire_refrele(ire);
26358 		goto done;
26359 	}
26360 
26361 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26362 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26363 	    (void *)ire->ire_ipif, (void *)ipif));
26364 
26365 	/*
26366 	 * Multiroute the secured packet, unless IPsec really
26367 	 * requires the packet to go out only through a particular
26368 	 * interface.
26369 	 */
26370 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26371 		ire_t *first_ire;
26372 		irb = ire->ire_bucket;
26373 		ASSERT(irb != NULL);
26374 		/*
26375 		 * This ire has been looked up as the one that
26376 		 * goes through the given ipif;
26377 		 * make sure we do not omit any other multiroute ire
26378 		 * that may be present in the bucket before this one.
26379 		 */
26380 		IRB_REFHOLD(irb);
26381 		for (first_ire = irb->irb_ire;
26382 		    first_ire != NULL;
26383 		    first_ire = first_ire->ire_next) {
26384 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26385 			    (first_ire->ire_addr == ire->ire_addr) &&
26386 			    !(first_ire->ire_marks &
26387 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
26388 				break;
26389 		}
26390 
26391 		if ((first_ire != NULL) && (first_ire != ire)) {
26392 			/*
26393 			 * Don't change the ire if the packet must
26394 			 * be fragmented if sent via this new one.
26395 			 */
26396 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26397 				IRE_REFHOLD(first_ire);
26398 				if (ire_need_rele)
26399 					ire_refrele(ire);
26400 				else
26401 					ire_need_rele = B_TRUE;
26402 				ire = first_ire;
26403 			}
26404 		}
26405 		IRB_REFRELE(irb);
26406 
26407 		multirt_send = B_TRUE;
26408 		max_frag = ire->ire_max_frag;
26409 	} else {
26410 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26411 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26412 			    "flag, attach_if %d\n", attach_if));
26413 		}
26414 	}
26415 
26416 	/*
26417 	 * In most cases, the emission loop below is entered only once.
26418 	 * Only in the case where the ire holds the RTF_MULTIRT
26419 	 * flag, we loop to process all RTF_MULTIRT ires in the
26420 	 * bucket, and send the packet through all crossed
26421 	 * RTF_MULTIRT routes.
26422 	 */
26423 	do {
26424 		if (multirt_send) {
26425 			/*
26426 			 * ire1 holds here the next ire to process in the
26427 			 * bucket. If multirouting is expected,
26428 			 * any non-RTF_MULTIRT ire that has the
26429 			 * right destination address is ignored.
26430 			 */
26431 			ASSERT(irb != NULL);
26432 			IRB_REFHOLD(irb);
26433 			for (ire1 = ire->ire_next;
26434 			    ire1 != NULL;
26435 			    ire1 = ire1->ire_next) {
26436 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26437 					continue;
26438 				if (ire1->ire_addr != ire->ire_addr)
26439 					continue;
26440 				if (ire1->ire_marks &
26441 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26442 					continue;
26443 				/* No loopback here */
26444 				if (ire1->ire_stq == NULL)
26445 					continue;
26446 				/*
26447 				 * Ensure we do not exceed the MTU
26448 				 * of the next route.
26449 				 */
26450 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26451 					ip_multirt_bad_mtu(ire1, max_frag);
26452 					continue;
26453 				}
26454 
26455 				IRE_REFHOLD(ire1);
26456 				break;
26457 			}
26458 			IRB_REFRELE(irb);
26459 			if (ire1 != NULL) {
26460 				/*
26461 				 * We are in a multiple send case, need to
26462 				 * make a copy of the packet.
26463 				 */
26464 				next_mp = copymsg(ipsec_mp);
26465 				if (next_mp == NULL) {
26466 					ire_refrele(ire1);
26467 					ire1 = NULL;
26468 				}
26469 			}
26470 		}
26471 		/*
26472 		 * Everything is done. Send it out on the wire
26473 		 *
26474 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26475 		 * either send it on the wire or, in the case of
26476 		 * HW acceleration, call ipsec_hw_putnext.
26477 		 */
26478 		if (ire->ire_nce &&
26479 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26480 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26481 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26482 			/*
26483 			 * If ire's link-layer is unresolved (this
26484 			 * would only happen if the incomplete ire
26485 			 * was added to cachetable via forwarding path)
26486 			 * don't bother going to ip_xmit_v4. Just drop the
26487 			 * packet.
26488 			 * There is a slight risk here, in that, if we
26489 			 * have the forwarding path create an incomplete
26490 			 * IRE, then until the IRE is completed, any
26491 			 * transmitted IPSEC packets will be dropped
26492 			 * instead of being queued waiting for resolution.
26493 			 *
26494 			 * But the likelihood of a forwarding packet and a wput
26495 			 * packet sending to the same dst at the same time
26496 			 * and there not yet be an ARP entry for it is small.
26497 			 * Furthermore, if this actually happens, it might
26498 			 * be likely that wput would generate multiple
26499 			 * packets (and forwarding would also have a train
26500 			 * of packets) for that destination. If this is
26501 			 * the case, some of them would have been dropped
26502 			 * anyway, since ARP only queues a few packets while
26503 			 * waiting for resolution
26504 			 *
26505 			 * NOTE: We should really call ip_xmit_v4,
26506 			 * and let it queue the packet and send the
26507 			 * ARP query and have ARP come back thus:
26508 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26509 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26510 			 * hw accel work. But it's too complex to get
26511 			 * the IPsec hw  acceleration approach to fit
26512 			 * well with ip_xmit_v4 doing ARP without
26513 			 * doing IPSEC simplification. For now, we just
26514 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26515 			 * that we can continue with the send on the next
26516 			 * attempt.
26517 			 *
26518 			 * XXX THis should be revisited, when
26519 			 * the IPsec/IP interaction is cleaned up
26520 			 */
26521 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26522 			    " - dropping packet\n"));
26523 			freemsg(ipsec_mp);
26524 			/*
26525 			 * Call ip_xmit_v4() to trigger ARP query
26526 			 * in case the nce_state is ND_INITIAL
26527 			 */
26528 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26529 			goto drop_pkt;
26530 		}
26531 
26532 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26533 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26534 		    mblk_t *, mp);
26535 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26536 		    ipst->ips_ipv4firewall_physical_out,
26537 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp, ipst);
26538 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26539 		if (mp == NULL)
26540 			goto drop_pkt;
26541 
26542 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26543 		pktxmit_state = ip_xmit_v4(mp, ire,
26544 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26545 
26546 		if ((pktxmit_state ==  SEND_FAILED) ||
26547 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26548 
26549 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26550 drop_pkt:
26551 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26552 			    ipIfStatsOutDiscards);
26553 			if (ire_need_rele)
26554 				ire_refrele(ire);
26555 			if (ire1 != NULL) {
26556 				ire_refrele(ire1);
26557 				freemsg(next_mp);
26558 			}
26559 			goto done;
26560 		}
26561 
26562 		freeb(ipsec_mp);
26563 		if (ire_need_rele)
26564 			ire_refrele(ire);
26565 
26566 		if (ire1 != NULL) {
26567 			ire = ire1;
26568 			ire_need_rele = B_TRUE;
26569 			ASSERT(next_mp);
26570 			ipsec_mp = next_mp;
26571 			mp = ipsec_mp->b_cont;
26572 			ire1 = NULL;
26573 			next_mp = NULL;
26574 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26575 		} else {
26576 			multirt_send = B_FALSE;
26577 		}
26578 	} while (multirt_send);
26579 done:
26580 	if (ill != NULL && ill_need_rele)
26581 		ill_refrele(ill);
26582 	if (ipif != NULL)
26583 		ipif_refrele(ipif);
26584 }
26585 
26586 /*
26587  * Get the ill corresponding to the specified ire, and compare its
26588  * capabilities with the protocol and algorithms specified by the
26589  * the SA obtained from ipsec_out. If they match, annotate the
26590  * ipsec_out structure to indicate that the packet needs acceleration.
26591  *
26592  *
26593  * A packet is eligible for outbound hardware acceleration if the
26594  * following conditions are satisfied:
26595  *
26596  * 1. the packet will not be fragmented
26597  * 2. the provider supports the algorithm
26598  * 3. there is no pending control message being exchanged
26599  * 4. snoop is not attached
26600  * 5. the destination address is not a broadcast or multicast address.
26601  *
26602  * Rationale:
26603  *	- Hardware drivers do not support fragmentation with
26604  *	  the current interface.
26605  *	- snoop, multicast, and broadcast may result in exposure of
26606  *	  a cleartext datagram.
26607  * We check all five of these conditions here.
26608  *
26609  * XXX would like to nuke "ire_t *" parameter here; problem is that
26610  * IRE is only way to figure out if a v4 address is a broadcast and
26611  * thus ineligible for acceleration...
26612  */
26613 static void
26614 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26615 {
26616 	ipsec_out_t *io;
26617 	mblk_t *data_mp;
26618 	uint_t plen, overhead;
26619 	ip_stack_t	*ipst;
26620 
26621 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26622 		return;
26623 
26624 	if (ill == NULL)
26625 		return;
26626 	ipst = ill->ill_ipst;
26627 	/*
26628 	 * Destination address is a broadcast or multicast.  Punt.
26629 	 */
26630 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26631 	    IRE_LOCAL)))
26632 		return;
26633 
26634 	data_mp = ipsec_mp->b_cont;
26635 
26636 	if (ill->ill_isv6) {
26637 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26638 
26639 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26640 			return;
26641 
26642 		plen = ip6h->ip6_plen;
26643 	} else {
26644 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26645 
26646 		if (CLASSD(ipha->ipha_dst))
26647 			return;
26648 
26649 		plen = ipha->ipha_length;
26650 	}
26651 	/*
26652 	 * Is there a pending DLPI control message being exchanged
26653 	 * between IP/IPsec and the DLS Provider? If there is, it
26654 	 * could be a SADB update, and the state of the DLS Provider
26655 	 * SADB might not be in sync with the SADB maintained by
26656 	 * IPsec. To avoid dropping packets or using the wrong keying
26657 	 * material, we do not accelerate this packet.
26658 	 */
26659 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26660 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26661 		    "ill_dlpi_pending! don't accelerate packet\n"));
26662 		return;
26663 	}
26664 
26665 	/*
26666 	 * Is the Provider in promiscous mode? If it does, we don't
26667 	 * accelerate the packet since it will bounce back up to the
26668 	 * listeners in the clear.
26669 	 */
26670 	if (ill->ill_promisc_on_phys) {
26671 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26672 		    "ill in promiscous mode, don't accelerate packet\n"));
26673 		return;
26674 	}
26675 
26676 	/*
26677 	 * Will the packet require fragmentation?
26678 	 */
26679 
26680 	/*
26681 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26682 	 * as is used elsewhere.
26683 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26684 	 *	+ 2-byte trailer
26685 	 */
26686 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26687 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26688 
26689 	if ((plen + overhead) > ill->ill_max_mtu)
26690 		return;
26691 
26692 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26693 
26694 	/*
26695 	 * Can the ill accelerate this IPsec protocol and algorithm
26696 	 * specified by the SA?
26697 	 */
26698 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26699 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26700 		return;
26701 	}
26702 
26703 	/*
26704 	 * Tell AH or ESP that the outbound ill is capable of
26705 	 * accelerating this packet.
26706 	 */
26707 	io->ipsec_out_is_capab_ill = B_TRUE;
26708 }
26709 
26710 /*
26711  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26712  *
26713  * If this function returns B_TRUE, the requested SA's have been filled
26714  * into the ipsec_out_*_sa pointers.
26715  *
26716  * If the function returns B_FALSE, the packet has been "consumed", most
26717  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26718  *
26719  * The SA references created by the protocol-specific "select"
26720  * function will be released when the ipsec_mp is freed, thanks to the
26721  * ipsec_out_free destructor -- see spd.c.
26722  */
26723 static boolean_t
26724 ipsec_out_select_sa(mblk_t *ipsec_mp)
26725 {
26726 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26727 	ipsec_out_t *io;
26728 	ipsec_policy_t *pp;
26729 	ipsec_action_t *ap;
26730 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26731 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26732 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26733 
26734 	if (!io->ipsec_out_secure) {
26735 		/*
26736 		 * We came here by mistake.
26737 		 * Don't bother with ipsec processing
26738 		 * We should "discourage" this path in the future.
26739 		 */
26740 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26741 		return (B_FALSE);
26742 	}
26743 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26744 	ASSERT((io->ipsec_out_policy != NULL) ||
26745 	    (io->ipsec_out_act != NULL));
26746 
26747 	ASSERT(io->ipsec_out_failed == B_FALSE);
26748 
26749 	/*
26750 	 * IPSEC processing has started.
26751 	 */
26752 	io->ipsec_out_proc_begin = B_TRUE;
26753 	ap = io->ipsec_out_act;
26754 	if (ap == NULL) {
26755 		pp = io->ipsec_out_policy;
26756 		ASSERT(pp != NULL);
26757 		ap = pp->ipsp_act;
26758 		ASSERT(ap != NULL);
26759 	}
26760 
26761 	/*
26762 	 * We have an action.  now, let's select SA's.
26763 	 * (In the future, we can cache this in the conn_t..)
26764 	 */
26765 	if (ap->ipa_want_esp) {
26766 		if (io->ipsec_out_esp_sa == NULL) {
26767 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26768 			    IPPROTO_ESP);
26769 		}
26770 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26771 	}
26772 
26773 	if (ap->ipa_want_ah) {
26774 		if (io->ipsec_out_ah_sa == NULL) {
26775 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26776 			    IPPROTO_AH);
26777 		}
26778 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26779 		/*
26780 		 * The ESP and AH processing order needs to be preserved
26781 		 * when both protocols are required (ESP should be applied
26782 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26783 		 * when both ESP and AH are required, and an AH ACQUIRE
26784 		 * is needed.
26785 		 */
26786 		if (ap->ipa_want_esp && need_ah_acquire)
26787 			need_esp_acquire = B_TRUE;
26788 	}
26789 
26790 	/*
26791 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26792 	 * Release SAs that got referenced, but will not be used until we
26793 	 * acquire _all_ of the SAs we need.
26794 	 */
26795 	if (need_ah_acquire || need_esp_acquire) {
26796 		if (io->ipsec_out_ah_sa != NULL) {
26797 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26798 			io->ipsec_out_ah_sa = NULL;
26799 		}
26800 		if (io->ipsec_out_esp_sa != NULL) {
26801 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26802 			io->ipsec_out_esp_sa = NULL;
26803 		}
26804 
26805 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26806 		return (B_FALSE);
26807 	}
26808 
26809 	return (B_TRUE);
26810 }
26811 
26812 /*
26813  * Process an IPSEC_OUT message and see what you can
26814  * do with it.
26815  * IPQoS Notes:
26816  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26817  * IPSec.
26818  * XXX would like to nuke ire_t.
26819  * XXX ill_index better be "real"
26820  */
26821 void
26822 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26823 {
26824 	ipsec_out_t *io;
26825 	ipsec_policy_t *pp;
26826 	ipsec_action_t *ap;
26827 	ipha_t *ipha;
26828 	ip6_t *ip6h;
26829 	mblk_t *mp;
26830 	ill_t *ill;
26831 	zoneid_t zoneid;
26832 	ipsec_status_t ipsec_rc;
26833 	boolean_t ill_need_rele = B_FALSE;
26834 	ip_stack_t	*ipst;
26835 	ipsec_stack_t	*ipss;
26836 
26837 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26838 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26839 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26840 	ipst = io->ipsec_out_ns->netstack_ip;
26841 	mp = ipsec_mp->b_cont;
26842 
26843 	/*
26844 	 * Initiate IPPF processing. We do it here to account for packets
26845 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26846 	 * We can check for ipsec_out_proc_begin even for such packets, as
26847 	 * they will always be false (asserted below).
26848 	 */
26849 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26850 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26851 		    io->ipsec_out_ill_index : ill_index);
26852 		if (mp == NULL) {
26853 			ip2dbg(("ipsec_out_process: packet dropped "\
26854 			    "during IPPF processing\n"));
26855 			freeb(ipsec_mp);
26856 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26857 			return;
26858 		}
26859 	}
26860 
26861 	if (!io->ipsec_out_secure) {
26862 		/*
26863 		 * We came here by mistake.
26864 		 * Don't bother with ipsec processing
26865 		 * Should "discourage" this path in the future.
26866 		 */
26867 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26868 		goto done;
26869 	}
26870 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26871 	ASSERT((io->ipsec_out_policy != NULL) ||
26872 	    (io->ipsec_out_act != NULL));
26873 	ASSERT(io->ipsec_out_failed == B_FALSE);
26874 
26875 	ipss = ipst->ips_netstack->netstack_ipsec;
26876 	if (!ipsec_loaded(ipss)) {
26877 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26878 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26879 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26880 		} else {
26881 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26882 		}
26883 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26884 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26885 		    &ipss->ipsec_dropper);
26886 		return;
26887 	}
26888 
26889 	/*
26890 	 * IPSEC processing has started.
26891 	 */
26892 	io->ipsec_out_proc_begin = B_TRUE;
26893 	ap = io->ipsec_out_act;
26894 	if (ap == NULL) {
26895 		pp = io->ipsec_out_policy;
26896 		ASSERT(pp != NULL);
26897 		ap = pp->ipsp_act;
26898 		ASSERT(ap != NULL);
26899 	}
26900 
26901 	/*
26902 	 * Save the outbound ill index. When the packet comes back
26903 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26904 	 * before sending it the accelerated packet.
26905 	 */
26906 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26907 		int ifindex;
26908 		ill = ire_to_ill(ire);
26909 		ifindex = ill->ill_phyint->phyint_ifindex;
26910 		io->ipsec_out_capab_ill_index = ifindex;
26911 	}
26912 
26913 	/*
26914 	 * The order of processing is first insert a IP header if needed.
26915 	 * Then insert the ESP header and then the AH header.
26916 	 */
26917 	if ((io->ipsec_out_se_done == B_FALSE) &&
26918 	    (ap->ipa_want_se)) {
26919 		/*
26920 		 * First get the outer IP header before sending
26921 		 * it to ESP.
26922 		 */
26923 		ipha_t *oipha, *iipha;
26924 		mblk_t *outer_mp, *inner_mp;
26925 
26926 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26927 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26928 			    "ipsec_out_process: "
26929 			    "Self-Encapsulation failed: Out of memory\n");
26930 			freemsg(ipsec_mp);
26931 			if (ill != NULL) {
26932 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26933 			} else {
26934 				BUMP_MIB(&ipst->ips_ip_mib,
26935 				    ipIfStatsOutDiscards);
26936 			}
26937 			return;
26938 		}
26939 		inner_mp = ipsec_mp->b_cont;
26940 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26941 		oipha = (ipha_t *)outer_mp->b_rptr;
26942 		iipha = (ipha_t *)inner_mp->b_rptr;
26943 		*oipha = *iipha;
26944 		outer_mp->b_wptr += sizeof (ipha_t);
26945 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26946 		    sizeof (ipha_t));
26947 		oipha->ipha_protocol = IPPROTO_ENCAP;
26948 		oipha->ipha_version_and_hdr_length =
26949 		    IP_SIMPLE_HDR_VERSION;
26950 		oipha->ipha_hdr_checksum = 0;
26951 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26952 		outer_mp->b_cont = inner_mp;
26953 		ipsec_mp->b_cont = outer_mp;
26954 
26955 		io->ipsec_out_se_done = B_TRUE;
26956 		io->ipsec_out_tunnel = B_TRUE;
26957 	}
26958 
26959 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26960 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26961 	    !ipsec_out_select_sa(ipsec_mp))
26962 		return;
26963 
26964 	/*
26965 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26966 	 * to do the heavy lifting.
26967 	 */
26968 	zoneid = io->ipsec_out_zoneid;
26969 	ASSERT(zoneid != ALL_ZONES);
26970 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26971 		ASSERT(io->ipsec_out_esp_sa != NULL);
26972 		io->ipsec_out_esp_done = B_TRUE;
26973 		/*
26974 		 * Note that since hw accel can only apply one transform,
26975 		 * not two, we skip hw accel for ESP if we also have AH
26976 		 * This is an design limitation of the interface
26977 		 * which should be revisited.
26978 		 */
26979 		ASSERT(ire != NULL);
26980 		if (io->ipsec_out_ah_sa == NULL) {
26981 			ill = (ill_t *)ire->ire_stq->q_ptr;
26982 			ipsec_out_is_accelerated(ipsec_mp,
26983 			    io->ipsec_out_esp_sa, ill, ire);
26984 		}
26985 
26986 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26987 		switch (ipsec_rc) {
26988 		case IPSEC_STATUS_SUCCESS:
26989 			break;
26990 		case IPSEC_STATUS_FAILED:
26991 			if (ill != NULL) {
26992 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26993 			} else {
26994 				BUMP_MIB(&ipst->ips_ip_mib,
26995 				    ipIfStatsOutDiscards);
26996 			}
26997 			/* FALLTHRU */
26998 		case IPSEC_STATUS_PENDING:
26999 			return;
27000 		}
27001 	}
27002 
27003 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27004 		ASSERT(io->ipsec_out_ah_sa != NULL);
27005 		io->ipsec_out_ah_done = B_TRUE;
27006 		if (ire == NULL) {
27007 			int idx = io->ipsec_out_capab_ill_index;
27008 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27009 			    NULL, NULL, NULL, NULL, ipst);
27010 			ill_need_rele = B_TRUE;
27011 		} else {
27012 			ill = (ill_t *)ire->ire_stq->q_ptr;
27013 		}
27014 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27015 		    ire);
27016 
27017 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27018 		switch (ipsec_rc) {
27019 		case IPSEC_STATUS_SUCCESS:
27020 			break;
27021 		case IPSEC_STATUS_FAILED:
27022 			if (ill != NULL) {
27023 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27024 			} else {
27025 				BUMP_MIB(&ipst->ips_ip_mib,
27026 				    ipIfStatsOutDiscards);
27027 			}
27028 			/* FALLTHRU */
27029 		case IPSEC_STATUS_PENDING:
27030 			if (ill != NULL && ill_need_rele)
27031 				ill_refrele(ill);
27032 			return;
27033 		}
27034 	}
27035 	/*
27036 	 * We are done with IPSEC processing. Send it over
27037 	 * the wire.
27038 	 */
27039 done:
27040 	mp = ipsec_mp->b_cont;
27041 	ipha = (ipha_t *)mp->b_rptr;
27042 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27043 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27044 	} else {
27045 		ip6h = (ip6_t *)ipha;
27046 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27047 	}
27048 	if (ill != NULL && ill_need_rele)
27049 		ill_refrele(ill);
27050 }
27051 
27052 /* ARGSUSED */
27053 void
27054 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27055 {
27056 	opt_restart_t	*or;
27057 	int	err;
27058 	conn_t	*connp;
27059 
27060 	ASSERT(CONN_Q(q));
27061 	connp = Q_TO_CONN(q);
27062 
27063 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27064 	or = (opt_restart_t *)first_mp->b_rptr;
27065 	/*
27066 	 * We don't need to pass any credentials here since this is just
27067 	 * a restart. The credentials are passed in when svr4_optcom_req
27068 	 * is called the first time (from ip_wput_nondata).
27069 	 */
27070 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27071 		err = svr4_optcom_req(q, first_mp, NULL,
27072 		    &ip_opt_obj);
27073 	} else {
27074 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27075 		err = tpi_optcom_req(q, first_mp, NULL,
27076 		    &ip_opt_obj);
27077 	}
27078 	if (err != EINPROGRESS) {
27079 		/* operation is done */
27080 		CONN_OPER_PENDING_DONE(connp);
27081 	}
27082 }
27083 
27084 /*
27085  * ioctls that go through a down/up sequence may need to wait for the down
27086  * to complete. This involves waiting for the ire and ipif refcnts to go down
27087  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27088  */
27089 /* ARGSUSED */
27090 void
27091 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27092 {
27093 	struct iocblk *iocp;
27094 	mblk_t *mp1;
27095 	ip_ioctl_cmd_t *ipip;
27096 	int err;
27097 	sin_t	*sin;
27098 	struct lifreq *lifr;
27099 	struct ifreq *ifr;
27100 
27101 	iocp = (struct iocblk *)mp->b_rptr;
27102 	ASSERT(ipsq != NULL);
27103 	/* Existence of mp1 verified in ip_wput_nondata */
27104 	mp1 = mp->b_cont->b_cont;
27105 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27106 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27107 		/*
27108 		 * Special case where ipsq_current_ipif is not set:
27109 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27110 		 * ill could also have become part of a ipmp group in the
27111 		 * process, we are here as were not able to complete the
27112 		 * operation in ipif_set_values because we could not become
27113 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27114 		 * will not be set so we need to set it.
27115 		 */
27116 		ill_t *ill = q->q_ptr;
27117 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27118 	}
27119 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27120 
27121 	if (ipip->ipi_cmd_type == IF_CMD) {
27122 		/* This a old style SIOC[GS]IF* command */
27123 		ifr = (struct ifreq *)mp1->b_rptr;
27124 		sin = (sin_t *)&ifr->ifr_addr;
27125 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27126 		/* This a new style SIOC[GS]LIF* command */
27127 		lifr = (struct lifreq *)mp1->b_rptr;
27128 		sin = (sin_t *)&lifr->lifr_addr;
27129 	} else {
27130 		sin = NULL;
27131 	}
27132 
27133 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27134 	    ipip, mp1->b_rptr);
27135 
27136 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27137 }
27138 
27139 /*
27140  * ioctl processing
27141  *
27142  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27143  * the ioctl command in the ioctl tables and determines the copyin data size
27144  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27145  * size.
27146  *
27147  * ioctl processing then continues when the M_IOCDATA makes its way down.
27148  * Now the ioctl is looked up again in the ioctl table, and its properties are
27149  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27150  * and the general ioctl processing function ip_process_ioctl is called.
27151  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27152  * so goes thru the serialization primitive ipsq_try_enter. Then the
27153  * appropriate function to handle the ioctl is called based on the entry in
27154  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27155  * which also refreleases the 'conn' that was refheld at the start of the
27156  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27157  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27158  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27159  *
27160  * Many exclusive ioctls go thru an internal down up sequence as part of
27161  * the operation. For example an attempt to change the IP address of an
27162  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27163  * does all the cleanup such as deleting all ires that use this address.
27164  * Then we need to wait till all references to the interface go away.
27165  */
27166 void
27167 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27168 {
27169 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27170 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27171 	cmd_info_t ci;
27172 	int err;
27173 	boolean_t entered_ipsq = B_FALSE;
27174 
27175 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27176 
27177 	if (ipip == NULL)
27178 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27179 
27180 	/*
27181 	 * SIOCLIFADDIF needs to go thru a special path since the
27182 	 * ill may not exist yet. This happens in the case of lo0
27183 	 * which is created using this ioctl.
27184 	 */
27185 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27186 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27187 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27188 		return;
27189 	}
27190 
27191 	ci.ci_ipif = NULL;
27192 	switch (ipip->ipi_cmd_type) {
27193 	case IF_CMD:
27194 	case LIF_CMD:
27195 		/*
27196 		 * ioctls that pass in a [l]ifreq appear here.
27197 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27198 		 * ci.ci_ipif
27199 		 */
27200 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27201 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27202 		if (err != 0) {
27203 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27204 			return;
27205 		}
27206 		ASSERT(ci.ci_ipif != NULL);
27207 		break;
27208 
27209 	case TUN_CMD:
27210 		/*
27211 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27212 		 * a refheld ipif in ci.ci_ipif
27213 		 */
27214 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27215 		if (err != 0) {
27216 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27217 			return;
27218 		}
27219 		ASSERT(ci.ci_ipif != NULL);
27220 		break;
27221 
27222 	case MISC_CMD:
27223 		/*
27224 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27225 		 * For eg. SIOCGLIFCONF will appear here.
27226 		 */
27227 		switch (ipip->ipi_cmd) {
27228 		case IF_UNITSEL:
27229 			/* ioctl comes down the ill */
27230 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27231 			ipif_refhold(ci.ci_ipif);
27232 			break;
27233 		case SIOCGMSFILTER:
27234 		case SIOCSMSFILTER:
27235 		case SIOCGIPMSFILTER:
27236 		case SIOCSIPMSFILTER:
27237 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27238 			    ip_process_ioctl);
27239 			if (err != 0) {
27240 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27241 				    NULL);
27242 			}
27243 			break;
27244 		}
27245 		err = 0;
27246 		ci.ci_sin = NULL;
27247 		ci.ci_sin6 = NULL;
27248 		ci.ci_lifr = NULL;
27249 		break;
27250 	}
27251 
27252 	/*
27253 	 * If ipsq is non-null, we are already being called exclusively
27254 	 */
27255 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27256 	if (!(ipip->ipi_flags & IPI_WR)) {
27257 		/*
27258 		 * A return value of EINPROGRESS means the ioctl is
27259 		 * either queued and waiting for some reason or has
27260 		 * already completed.
27261 		 */
27262 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27263 		    ci.ci_lifr);
27264 		if (ci.ci_ipif != NULL)
27265 			ipif_refrele(ci.ci_ipif);
27266 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27267 		return;
27268 	}
27269 
27270 	ASSERT(ci.ci_ipif != NULL);
27271 
27272 	if (ipsq == NULL) {
27273 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27274 		    ip_process_ioctl, NEW_OP, B_TRUE);
27275 		entered_ipsq = B_TRUE;
27276 	}
27277 	/*
27278 	 * Release the ipif so that ipif_down and friends that wait for
27279 	 * references to go away are not misled about the current ipif_refcnt
27280 	 * values. We are writer so we can access the ipif even after releasing
27281 	 * the ipif.
27282 	 */
27283 	ipif_refrele(ci.ci_ipif);
27284 	if (ipsq == NULL)
27285 		return;
27286 
27287 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27288 
27289 	/*
27290 	 * For most set ioctls that come here, this serves as a single point
27291 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27292 	 * be any new references to the ipif. This helps functions that go
27293 	 * through this path and end up trying to wait for the refcnts
27294 	 * associated with the ipif to go down to zero. Some exceptions are
27295 	 * Failover, Failback, and Groupname commands that operate on more than
27296 	 * just the ci.ci_ipif. These commands internally determine the
27297 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27298 	 * flags on that set. Another exception is the Removeif command that
27299 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27300 	 * ipif to operate on.
27301 	 */
27302 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27303 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27304 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27305 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27306 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27307 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27308 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27309 
27310 	/*
27311 	 * A return value of EINPROGRESS means the ioctl is
27312 	 * either queued and waiting for some reason or has
27313 	 * already completed.
27314 	 */
27315 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27316 
27317 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27318 
27319 	if (entered_ipsq)
27320 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27321 }
27322 
27323 /*
27324  * Complete the ioctl. Typically ioctls use the mi package and need to
27325  * do mi_copyout/mi_copy_done.
27326  */
27327 void
27328 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27329 {
27330 	conn_t	*connp = NULL;
27331 
27332 	if (err == EINPROGRESS)
27333 		return;
27334 
27335 	if (CONN_Q(q)) {
27336 		connp = Q_TO_CONN(q);
27337 		ASSERT(connp->conn_ref >= 2);
27338 	}
27339 
27340 	switch (mode) {
27341 	case COPYOUT:
27342 		if (err == 0)
27343 			mi_copyout(q, mp);
27344 		else
27345 			mi_copy_done(q, mp, err);
27346 		break;
27347 
27348 	case NO_COPYOUT:
27349 		mi_copy_done(q, mp, err);
27350 		break;
27351 
27352 	default:
27353 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27354 		break;
27355 	}
27356 
27357 	/*
27358 	 * The refhold placed at the start of the ioctl is released here.
27359 	 */
27360 	if (connp != NULL)
27361 		CONN_OPER_PENDING_DONE(connp);
27362 
27363 	if (ipsq != NULL)
27364 		ipsq_current_finish(ipsq);
27365 }
27366 
27367 /*
27368  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27369  */
27370 /* ARGSUSED */
27371 void
27372 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27373 {
27374 	conn_t *connp = arg;
27375 	tcp_t	*tcp;
27376 
27377 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27378 	tcp = connp->conn_tcp;
27379 
27380 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27381 		freemsg(mp);
27382 	else
27383 		tcp_rput_other(tcp, mp);
27384 	CONN_OPER_PENDING_DONE(connp);
27385 }
27386 
27387 /* Called from ip_wput for all non data messages */
27388 /* ARGSUSED */
27389 void
27390 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27391 {
27392 	mblk_t		*mp1;
27393 	ire_t		*ire, *fake_ire;
27394 	ill_t		*ill;
27395 	struct iocblk	*iocp;
27396 	ip_ioctl_cmd_t	*ipip;
27397 	cred_t		*cr;
27398 	conn_t		*connp;
27399 	int		cmd, err;
27400 	nce_t		*nce;
27401 	ipif_t		*ipif;
27402 	ip_stack_t	*ipst;
27403 	char		*proto_str;
27404 
27405 	if (CONN_Q(q)) {
27406 		connp = Q_TO_CONN(q);
27407 		ipst = connp->conn_netstack->netstack_ip;
27408 	} else {
27409 		connp = NULL;
27410 		ipst = ILLQ_TO_IPST(q);
27411 	}
27412 
27413 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27414 
27415 	/* Check if it is a queue to /dev/sctp. */
27416 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27417 	    connp->conn_rq == NULL) {
27418 		sctp_wput(q, mp);
27419 		return;
27420 	}
27421 
27422 	switch (DB_TYPE(mp)) {
27423 	case M_IOCTL:
27424 		/*
27425 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27426 		 * will arrange to copy in associated control structures.
27427 		 */
27428 		ip_sioctl_copyin_setup(q, mp);
27429 		return;
27430 	case M_IOCDATA:
27431 		/*
27432 		 * Ensure that this is associated with one of our trans-
27433 		 * parent ioctls.  If it's not ours, discard it if we're
27434 		 * running as a driver, or pass it on if we're a module.
27435 		 */
27436 		iocp = (struct iocblk *)mp->b_rptr;
27437 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27438 		if (ipip == NULL) {
27439 			if (q->q_next == NULL) {
27440 				goto nak;
27441 			} else {
27442 				putnext(q, mp);
27443 			}
27444 			return;
27445 		} else if ((q->q_next != NULL) &&
27446 		    !(ipip->ipi_flags & IPI_MODOK)) {
27447 			/*
27448 			 * the ioctl is one we recognise, but is not
27449 			 * consumed by IP as a module, pass M_IOCDATA
27450 			 * for processing downstream, but only for
27451 			 * common Streams ioctls.
27452 			 */
27453 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27454 				putnext(q, mp);
27455 				return;
27456 			} else {
27457 				goto nak;
27458 			}
27459 		}
27460 
27461 		/* IOCTL continuation following copyin or copyout. */
27462 		if (mi_copy_state(q, mp, NULL) == -1) {
27463 			/*
27464 			 * The copy operation failed.  mi_copy_state already
27465 			 * cleaned up, so we're out of here.
27466 			 */
27467 			return;
27468 		}
27469 		/*
27470 		 * If we just completed a copy in, we become writer and
27471 		 * continue processing in ip_sioctl_copyin_done.  If it
27472 		 * was a copy out, we call mi_copyout again.  If there is
27473 		 * nothing more to copy out, it will complete the IOCTL.
27474 		 */
27475 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27476 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27477 				mi_copy_done(q, mp, EPROTO);
27478 				return;
27479 			}
27480 			/*
27481 			 * Check for cases that need more copying.  A return
27482 			 * value of 0 means a second copyin has been started,
27483 			 * so we return; a return value of 1 means no more
27484 			 * copying is needed, so we continue.
27485 			 */
27486 			cmd = iocp->ioc_cmd;
27487 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27488 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27489 			    MI_COPY_COUNT(mp) == 1) {
27490 				if (ip_copyin_msfilter(q, mp) == 0)
27491 					return;
27492 			}
27493 			/*
27494 			 * Refhold the conn, till the ioctl completes. This is
27495 			 * needed in case the ioctl ends up in the pending mp
27496 			 * list. Every mp in the ill_pending_mp list and
27497 			 * the ipsq_pending_mp must have a refhold on the conn
27498 			 * to resume processing. The refhold is released when
27499 			 * the ioctl completes. (normally or abnormally)
27500 			 * In all cases ip_ioctl_finish is called to finish
27501 			 * the ioctl.
27502 			 */
27503 			if (connp != NULL) {
27504 				/* This is not a reentry */
27505 				ASSERT(ipsq == NULL);
27506 				CONN_INC_REF(connp);
27507 			} else {
27508 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27509 					mi_copy_done(q, mp, EINVAL);
27510 					return;
27511 				}
27512 			}
27513 
27514 			ip_process_ioctl(ipsq, q, mp, ipip);
27515 
27516 		} else {
27517 			mi_copyout(q, mp);
27518 		}
27519 		return;
27520 nak:
27521 		iocp->ioc_error = EINVAL;
27522 		mp->b_datap->db_type = M_IOCNAK;
27523 		iocp->ioc_count = 0;
27524 		qreply(q, mp);
27525 		return;
27526 
27527 	case M_IOCNAK:
27528 		/*
27529 		 * The only way we could get here is if a resolver didn't like
27530 		 * an IOCTL we sent it.	 This shouldn't happen.
27531 		 */
27532 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27533 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27534 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27535 		freemsg(mp);
27536 		return;
27537 	case M_IOCACK:
27538 		/* /dev/ip shouldn't see this */
27539 		if (CONN_Q(q))
27540 			goto nak;
27541 
27542 		/* Finish socket ioctls passed through to ARP. */
27543 		ip_sioctl_iocack(q, mp);
27544 		return;
27545 	case M_FLUSH:
27546 		if (*mp->b_rptr & FLUSHW)
27547 			flushq(q, FLUSHALL);
27548 		if (q->q_next) {
27549 			putnext(q, mp);
27550 			return;
27551 		}
27552 		if (*mp->b_rptr & FLUSHR) {
27553 			*mp->b_rptr &= ~FLUSHW;
27554 			qreply(q, mp);
27555 			return;
27556 		}
27557 		freemsg(mp);
27558 		return;
27559 	case IRE_DB_REQ_TYPE:
27560 		if (connp == NULL) {
27561 			proto_str = "IRE_DB_REQ_TYPE";
27562 			goto protonak;
27563 		}
27564 		/* An Upper Level Protocol wants a copy of an IRE. */
27565 		ip_ire_req(q, mp);
27566 		return;
27567 	case M_CTL:
27568 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27569 			break;
27570 
27571 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27572 		    TUN_HELLO) {
27573 			ASSERT(connp != NULL);
27574 			connp->conn_flags |= IPCL_IPTUN;
27575 			freeb(mp);
27576 			return;
27577 		}
27578 
27579 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27580 		    IP_ULP_OUT_LABELED) {
27581 			out_labeled_t *olp;
27582 
27583 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27584 				break;
27585 			olp = (out_labeled_t *)mp->b_rptr;
27586 			connp->conn_ulp_labeled = olp->out_qnext == q;
27587 			freemsg(mp);
27588 			return;
27589 		}
27590 
27591 		/* M_CTL messages are used by ARP to tell us things. */
27592 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27593 			break;
27594 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27595 		case AR_ENTRY_SQUERY:
27596 			ip_wput_ctl(q, mp);
27597 			return;
27598 		case AR_CLIENT_NOTIFY:
27599 			ip_arp_news(q, mp);
27600 			return;
27601 		case AR_DLPIOP_DONE:
27602 			ASSERT(q->q_next != NULL);
27603 			ill = (ill_t *)q->q_ptr;
27604 			/* qwriter_ip releases the refhold */
27605 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27606 			ill_refhold(ill);
27607 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27608 			return;
27609 		case AR_ARP_CLOSING:
27610 			/*
27611 			 * ARP (above us) is closing. If no ARP bringup is
27612 			 * currently pending, ack the message so that ARP
27613 			 * can complete its close. Also mark ill_arp_closing
27614 			 * so that new ARP bringups will fail. If any
27615 			 * ARP bringup is currently in progress, we will
27616 			 * ack this when the current ARP bringup completes.
27617 			 */
27618 			ASSERT(q->q_next != NULL);
27619 			ill = (ill_t *)q->q_ptr;
27620 			mutex_enter(&ill->ill_lock);
27621 			ill->ill_arp_closing = 1;
27622 			if (!ill->ill_arp_bringup_pending) {
27623 				mutex_exit(&ill->ill_lock);
27624 				qreply(q, mp);
27625 			} else {
27626 				mutex_exit(&ill->ill_lock);
27627 				freemsg(mp);
27628 			}
27629 			return;
27630 		case AR_ARP_EXTEND:
27631 			/*
27632 			 * The ARP module above us is capable of duplicate
27633 			 * address detection.  Old ATM drivers will not send
27634 			 * this message.
27635 			 */
27636 			ASSERT(q->q_next != NULL);
27637 			ill = (ill_t *)q->q_ptr;
27638 			ill->ill_arp_extend = B_TRUE;
27639 			freemsg(mp);
27640 			return;
27641 		default:
27642 			break;
27643 		}
27644 		break;
27645 	case M_PROTO:
27646 	case M_PCPROTO:
27647 		/*
27648 		 * The only PROTO messages we expect are ULP binds and
27649 		 * copies of option negotiation acknowledgements.
27650 		 */
27651 		switch (((union T_primitives *)mp->b_rptr)->type) {
27652 		case O_T_BIND_REQ:
27653 		case T_BIND_REQ: {
27654 			/* Request can get queued in bind */
27655 			if (connp == NULL) {
27656 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27657 				goto protonak;
27658 			}
27659 			/*
27660 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27661 			 * instead of going through this path.  We only get
27662 			 * here in the following cases:
27663 			 *
27664 			 * a. Bind retries, where ipsq is non-NULL.
27665 			 * b. T_BIND_REQ is issued from non TCP/UDP
27666 			 *    transport, e.g. icmp for raw socket,
27667 			 *    in which case ipsq will be NULL.
27668 			 */
27669 			ASSERT(ipsq != NULL ||
27670 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27671 
27672 			/* Don't increment refcnt if this is a re-entry */
27673 			if (ipsq == NULL)
27674 				CONN_INC_REF(connp);
27675 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27676 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27677 			if (mp == NULL)
27678 				return;
27679 			if (IPCL_IS_TCP(connp)) {
27680 				/*
27681 				 * In the case of TCP endpoint we
27682 				 * come here only for bind retries
27683 				 */
27684 				ASSERT(ipsq != NULL);
27685 				CONN_INC_REF(connp);
27686 				squeue_fill(connp->conn_sqp, mp,
27687 				    ip_resume_tcp_bind, connp,
27688 				    SQTAG_BIND_RETRY);
27689 				return;
27690 			} else if (IPCL_IS_UDP(connp)) {
27691 				/*
27692 				 * In the case of UDP endpoint we
27693 				 * come here only for bind retries
27694 				 */
27695 				ASSERT(ipsq != NULL);
27696 				udp_resume_bind(connp, mp);
27697 				return;
27698 			}
27699 			qreply(q, mp);
27700 			CONN_OPER_PENDING_DONE(connp);
27701 			return;
27702 		}
27703 		case T_SVR4_OPTMGMT_REQ:
27704 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27705 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27706 
27707 			if (connp == NULL) {
27708 				proto_str = "T_SVR4_OPTMGMT_REQ";
27709 				goto protonak;
27710 			}
27711 
27712 			if (!snmpcom_req(q, mp, ip_snmp_set,
27713 			    ip_snmp_get, cr)) {
27714 				/*
27715 				 * Call svr4_optcom_req so that it can
27716 				 * generate the ack. We don't come here
27717 				 * if this operation is being restarted.
27718 				 * ip_restart_optmgmt will drop the conn ref.
27719 				 * In the case of ipsec option after the ipsec
27720 				 * load is complete conn_restart_ipsec_waiter
27721 				 * drops the conn ref.
27722 				 */
27723 				ASSERT(ipsq == NULL);
27724 				CONN_INC_REF(connp);
27725 				if (ip_check_for_ipsec_opt(q, mp))
27726 					return;
27727 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27728 				if (err != EINPROGRESS) {
27729 					/* Operation is done */
27730 					CONN_OPER_PENDING_DONE(connp);
27731 				}
27732 			}
27733 			return;
27734 		case T_OPTMGMT_REQ:
27735 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27736 			/*
27737 			 * Note: No snmpcom_req support through new
27738 			 * T_OPTMGMT_REQ.
27739 			 * Call tpi_optcom_req so that it can
27740 			 * generate the ack.
27741 			 */
27742 			if (connp == NULL) {
27743 				proto_str = "T_OPTMGMT_REQ";
27744 				goto protonak;
27745 			}
27746 
27747 			ASSERT(ipsq == NULL);
27748 			/*
27749 			 * We don't come here for restart. ip_restart_optmgmt
27750 			 * will drop the conn ref. In the case of ipsec option
27751 			 * after the ipsec load is complete
27752 			 * conn_restart_ipsec_waiter drops the conn ref.
27753 			 */
27754 			CONN_INC_REF(connp);
27755 			if (ip_check_for_ipsec_opt(q, mp))
27756 				return;
27757 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27758 			if (err != EINPROGRESS) {
27759 				/* Operation is done */
27760 				CONN_OPER_PENDING_DONE(connp);
27761 			}
27762 			return;
27763 		case T_UNBIND_REQ:
27764 			if (connp == NULL) {
27765 				proto_str = "T_UNBIND_REQ";
27766 				goto protonak;
27767 			}
27768 			mp = ip_unbind(q, mp);
27769 			qreply(q, mp);
27770 			return;
27771 		default:
27772 			/*
27773 			 * Have to drop any DLPI messages coming down from
27774 			 * arp (such as an info_req which would cause ip
27775 			 * to receive an extra info_ack if it was passed
27776 			 * through.
27777 			 */
27778 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27779 			    (int)*(uint_t *)mp->b_rptr));
27780 			freemsg(mp);
27781 			return;
27782 		}
27783 		/* NOTREACHED */
27784 	case IRE_DB_TYPE: {
27785 		nce_t		*nce;
27786 		ill_t		*ill;
27787 		in6_addr_t	gw_addr_v6;
27788 
27789 
27790 		/*
27791 		 * This is a response back from a resolver.  It
27792 		 * consists of a message chain containing:
27793 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27794 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27795 		 * The LL_HDR_MBLK is the DLPI header to use to get
27796 		 * the attached packet, and subsequent ones for the
27797 		 * same destination, transmitted.
27798 		 */
27799 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27800 			break;
27801 		/*
27802 		 * First, check to make sure the resolution succeeded.
27803 		 * If it failed, the second mblk will be empty.
27804 		 * If it is, free the chain, dropping the packet.
27805 		 * (We must ire_delete the ire; that frees the ire mblk)
27806 		 * We're doing this now to support PVCs for ATM; it's
27807 		 * a partial xresolv implementation. When we fully implement
27808 		 * xresolv interfaces, instead of freeing everything here
27809 		 * we'll initiate neighbor discovery.
27810 		 *
27811 		 * For v4 (ARP and other external resolvers) the resolver
27812 		 * frees the message, so no check is needed. This check
27813 		 * is required, though, for a full xresolve implementation.
27814 		 * Including this code here now both shows how external
27815 		 * resolvers can NACK a resolution request using an
27816 		 * existing design that has no specific provisions for NACKs,
27817 		 * and also takes into account that the current non-ARP
27818 		 * external resolver has been coded to use this method of
27819 		 * NACKing for all IPv6 (xresolv) cases,
27820 		 * whether our xresolv implementation is complete or not.
27821 		 *
27822 		 */
27823 		ire = (ire_t *)mp->b_rptr;
27824 		ill = ire_to_ill(ire);
27825 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27826 		if (mp1->b_rptr == mp1->b_wptr) {
27827 			if (ire->ire_ipversion == IPV6_VERSION) {
27828 				/*
27829 				 * XRESOLV interface.
27830 				 */
27831 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27832 				mutex_enter(&ire->ire_lock);
27833 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27834 				mutex_exit(&ire->ire_lock);
27835 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27836 					nce = ndp_lookup_v6(ill,
27837 					    &ire->ire_addr_v6, B_FALSE);
27838 				} else {
27839 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27840 					    B_FALSE);
27841 				}
27842 				if (nce != NULL) {
27843 					nce_resolv_failed(nce);
27844 					ndp_delete(nce);
27845 					NCE_REFRELE(nce);
27846 				}
27847 			}
27848 			mp->b_cont = NULL;
27849 			freemsg(mp1);		/* frees the pkt as well */
27850 			ASSERT(ire->ire_nce == NULL);
27851 			ire_delete((ire_t *)mp->b_rptr);
27852 			return;
27853 		}
27854 
27855 		/*
27856 		 * Split them into IRE_MBLK and pkt and feed it into
27857 		 * ire_add_then_send. Then in ire_add_then_send
27858 		 * the IRE will be added, and then the packet will be
27859 		 * run back through ip_wput. This time it will make
27860 		 * it to the wire.
27861 		 */
27862 		mp->b_cont = NULL;
27863 		mp = mp1->b_cont;		/* now, mp points to pkt */
27864 		mp1->b_cont = NULL;
27865 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27866 		if (ire->ire_ipversion == IPV6_VERSION) {
27867 			/*
27868 			 * XRESOLV interface. Find the nce and put a copy
27869 			 * of the dl_unitdata_req in nce_res_mp
27870 			 */
27871 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27872 			mutex_enter(&ire->ire_lock);
27873 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27874 			mutex_exit(&ire->ire_lock);
27875 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27876 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27877 				    B_FALSE);
27878 			} else {
27879 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27880 			}
27881 			if (nce != NULL) {
27882 				/*
27883 				 * We have to protect nce_res_mp here
27884 				 * from being accessed by other threads
27885 				 * while we change the mblk pointer.
27886 				 * Other functions will also lock the nce when
27887 				 * accessing nce_res_mp.
27888 				 *
27889 				 * The reason we change the mblk pointer
27890 				 * here rather than copying the resolved address
27891 				 * into the template is that, unlike with
27892 				 * ethernet, we have no guarantee that the
27893 				 * resolved address length will be
27894 				 * smaller than or equal to the lla length
27895 				 * with which the template was allocated,
27896 				 * (for ethernet, they're equal)
27897 				 * so we have to use the actual resolved
27898 				 * address mblk - which holds the real
27899 				 * dl_unitdata_req with the resolved address.
27900 				 *
27901 				 * Doing this is the same behavior as was
27902 				 * previously used in the v4 ARP case.
27903 				 */
27904 				mutex_enter(&nce->nce_lock);
27905 				if (nce->nce_res_mp != NULL)
27906 					freemsg(nce->nce_res_mp);
27907 				nce->nce_res_mp = mp1;
27908 				mutex_exit(&nce->nce_lock);
27909 				/*
27910 				 * We do a fastpath probe here because
27911 				 * we have resolved the address without
27912 				 * using Neighbor Discovery.
27913 				 * In the non-XRESOLV v6 case, the fastpath
27914 				 * probe is done right after neighbor
27915 				 * discovery completes.
27916 				 */
27917 				if (nce->nce_res_mp != NULL) {
27918 					int res;
27919 					nce_fastpath_list_add(nce);
27920 					res = ill_fastpath_probe(ill,
27921 					    nce->nce_res_mp);
27922 					if (res != 0 && res != EAGAIN)
27923 						nce_fastpath_list_delete(nce);
27924 				}
27925 
27926 				ire_add_then_send(q, ire, mp);
27927 				/*
27928 				 * Now we have to clean out any packets
27929 				 * that may have been queued on the nce
27930 				 * while it was waiting for address resolution
27931 				 * to complete.
27932 				 */
27933 				mutex_enter(&nce->nce_lock);
27934 				mp1 = nce->nce_qd_mp;
27935 				nce->nce_qd_mp = NULL;
27936 				mutex_exit(&nce->nce_lock);
27937 				while (mp1 != NULL) {
27938 					mblk_t *nxt_mp;
27939 					queue_t *fwdq = NULL;
27940 					ill_t   *inbound_ill;
27941 					uint_t ifindex;
27942 
27943 					nxt_mp = mp1->b_next;
27944 					mp1->b_next = NULL;
27945 					/*
27946 					 * Retrieve ifindex stored in
27947 					 * ip_rput_data_v6()
27948 					 */
27949 					ifindex =
27950 					    (uint_t)(uintptr_t)mp1->b_prev;
27951 					inbound_ill =
27952 						ill_lookup_on_ifindex(ifindex,
27953 						    B_TRUE, NULL, NULL, NULL,
27954 						    NULL, ipst);
27955 					mp1->b_prev = NULL;
27956 					if (inbound_ill != NULL)
27957 						fwdq = inbound_ill->ill_rq;
27958 
27959 					if (fwdq != NULL) {
27960 						put(fwdq, mp1);
27961 						ill_refrele(inbound_ill);
27962 					} else
27963 						put(WR(ill->ill_rq), mp1);
27964 					mp1 = nxt_mp;
27965 				}
27966 				NCE_REFRELE(nce);
27967 			} else {	/* nce is NULL; clean up */
27968 				ire_delete(ire);
27969 				freemsg(mp);
27970 				freemsg(mp1);
27971 				return;
27972 			}
27973 		} else {
27974 			nce_t *arpce;
27975 			/*
27976 			 * Link layer resolution succeeded. Recompute the
27977 			 * ire_nce.
27978 			 */
27979 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27980 			if ((arpce = ndp_lookup_v4(ill,
27981 			    (ire->ire_gateway_addr != INADDR_ANY ?
27982 			    &ire->ire_gateway_addr : &ire->ire_addr),
27983 			    B_FALSE)) == NULL) {
27984 				freeb(ire->ire_mp);
27985 				freeb(mp1);
27986 				freemsg(mp);
27987 				return;
27988 			}
27989 			mutex_enter(&arpce->nce_lock);
27990 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27991 			if (arpce->nce_state == ND_REACHABLE) {
27992 				/*
27993 				 * Someone resolved this before us;
27994 				 * cleanup the res_mp. Since ire has
27995 				 * not been added yet, the call to ire_add_v4
27996 				 * from ire_add_then_send (when a dup is
27997 				 * detected) will clean up the ire.
27998 				 */
27999 				freeb(mp1);
28000 			} else {
28001 				if (arpce->nce_res_mp != NULL)
28002 					freemsg(arpce->nce_res_mp);
28003 				arpce->nce_res_mp = mp1;
28004 				arpce->nce_state = ND_REACHABLE;
28005 			}
28006 			mutex_exit(&arpce->nce_lock);
28007 			if (ire->ire_marks & IRE_MARK_NOADD) {
28008 				/*
28009 				 * this ire will not be added to the ire
28010 				 * cache table, so we can set the ire_nce
28011 				 * here, as there are no atomicity constraints.
28012 				 */
28013 				ire->ire_nce = arpce;
28014 				/*
28015 				 * We are associating this nce with the ire
28016 				 * so change the nce ref taken in
28017 				 * ndp_lookup_v4() from
28018 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28019 				 */
28020 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28021 			} else {
28022 				NCE_REFRELE(arpce);
28023 			}
28024 			ire_add_then_send(q, ire, mp);
28025 		}
28026 		return;	/* All is well, the packet has been sent. */
28027 	}
28028 	case IRE_ARPRESOLVE_TYPE: {
28029 
28030 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28031 			break;
28032 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28033 		mp->b_cont = NULL;
28034 		/*
28035 		 * First, check to make sure the resolution succeeded.
28036 		 * If it failed, the second mblk will be empty.
28037 		 */
28038 		if (mp1->b_rptr == mp1->b_wptr) {
28039 			/* cleanup  the incomplete ire, free queued packets */
28040 			freemsg(mp); /* fake ire */
28041 			freeb(mp1);  /* dl_unitdata response */
28042 			return;
28043 		}
28044 
28045 		/*
28046 		 * update any incomplete nce_t found. we lookup the ctable
28047 		 * and find the nce from the ire->ire_nce because we need
28048 		 * to pass the ire to ip_xmit_v4 later, and can find both
28049 		 * ire and nce in one lookup from the ctable.
28050 		 */
28051 		fake_ire = (ire_t *)mp->b_rptr;
28052 		/*
28053 		 * By the time we come back here from ARP
28054 		 * the logical outgoing interface  of the incomplete ire
28055 		 * we added in ire_forward could have disappeared,
28056 		 * causing the incomplete ire to also have
28057 		 * dissapeared. So we need to retreive the
28058 		 * proper ipif for the ire  before looking
28059 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28060 		 */
28061 		ill = q->q_ptr;
28062 
28063 		/* Get the outgoing ipif */
28064 		mutex_enter(&ill->ill_lock);
28065 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28066 			mutex_exit(&ill->ill_lock);
28067 			freemsg(mp); /* fake ire */
28068 			freeb(mp1);  /* dl_unitdata response */
28069 			return;
28070 		}
28071 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28072 
28073 		if (ipif == NULL) {
28074 			mutex_exit(&ill->ill_lock);
28075 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28076 			freemsg(mp);
28077 			freeb(mp1);
28078 			return;
28079 		}
28080 		ipif_refhold_locked(ipif);
28081 		mutex_exit(&ill->ill_lock);
28082 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28083 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28084 		    ipif, fake_ire->ire_zoneid, NULL,
28085 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28086 		ipif_refrele(ipif);
28087 		if (ire == NULL) {
28088 			/*
28089 			 * no ire was found; check if there is an nce
28090 			 * for this lookup; if it has no ire's pointing at it
28091 			 * cleanup.
28092 			 */
28093 			if ((nce = ndp_lookup_v4(ill,
28094 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28095 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28096 			    B_FALSE)) != NULL) {
28097 				/*
28098 				 * cleanup:
28099 				 * We check for refcnt 2 (one for the nce
28100 				 * hash list + 1 for the ref taken by
28101 				 * ndp_lookup_v4) to check that there are
28102 				 * no ire's pointing at the nce.
28103 				 */
28104 				if (nce->nce_refcnt == 2)
28105 					ndp_delete(nce);
28106 				NCE_REFRELE(nce);
28107 			}
28108 			freeb(mp1);  /* dl_unitdata response */
28109 			freemsg(mp); /* fake ire */
28110 			return;
28111 		}
28112 		nce = ire->ire_nce;
28113 		DTRACE_PROBE2(ire__arpresolve__type,
28114 		    ire_t *, ire, nce_t *, nce);
28115 		ASSERT(nce->nce_state != ND_INITIAL);
28116 		mutex_enter(&nce->nce_lock);
28117 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28118 		if (nce->nce_state == ND_REACHABLE) {
28119 			/*
28120 			 * Someone resolved this before us;
28121 			 * our response is not needed any more.
28122 			 */
28123 			mutex_exit(&nce->nce_lock);
28124 			freeb(mp1);  /* dl_unitdata response */
28125 		} else {
28126 			if (nce->nce_res_mp != NULL) {
28127 				freemsg(nce->nce_res_mp);
28128 				/* existing dl_unitdata template */
28129 			}
28130 			nce->nce_res_mp = mp1;
28131 			nce->nce_state = ND_REACHABLE;
28132 			mutex_exit(&nce->nce_lock);
28133 			nce_fastpath(nce);
28134 		}
28135 		/*
28136 		 * The cached nce_t has been updated to be reachable;
28137 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28138 		 */
28139 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28140 		freemsg(mp);
28141 		/*
28142 		 * send out queued packets.
28143 		 */
28144 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28145 
28146 		IRE_REFRELE(ire);
28147 		return;
28148 	}
28149 	default:
28150 		break;
28151 	}
28152 	if (q->q_next) {
28153 		putnext(q, mp);
28154 	} else
28155 		freemsg(mp);
28156 	return;
28157 
28158 protonak:
28159 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28160 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28161 		qreply(q, mp);
28162 }
28163 
28164 /*
28165  * Process IP options in an outbound packet.  Modify the destination if there
28166  * is a source route option.
28167  * Returns non-zero if something fails in which case an ICMP error has been
28168  * sent and mp freed.
28169  */
28170 static int
28171 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28172     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28173 {
28174 	ipoptp_t	opts;
28175 	uchar_t		*opt;
28176 	uint8_t		optval;
28177 	uint8_t		optlen;
28178 	ipaddr_t	dst;
28179 	intptr_t	code = 0;
28180 	mblk_t		*mp;
28181 	ire_t		*ire = NULL;
28182 
28183 	ip2dbg(("ip_wput_options\n"));
28184 	mp = ipsec_mp;
28185 	if (mctl_present) {
28186 		mp = ipsec_mp->b_cont;
28187 	}
28188 
28189 	dst = ipha->ipha_dst;
28190 	for (optval = ipoptp_first(&opts, ipha);
28191 	    optval != IPOPT_EOL;
28192 	    optval = ipoptp_next(&opts)) {
28193 		opt = opts.ipoptp_cur;
28194 		optlen = opts.ipoptp_len;
28195 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28196 		    optval, optlen));
28197 		switch (optval) {
28198 			uint32_t off;
28199 		case IPOPT_SSRR:
28200 		case IPOPT_LSRR:
28201 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28202 				ip1dbg((
28203 				    "ip_wput_options: bad option offset\n"));
28204 				code = (char *)&opt[IPOPT_OLEN] -
28205 				    (char *)ipha;
28206 				goto param_prob;
28207 			}
28208 			off = opt[IPOPT_OFFSET];
28209 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28210 			    ntohl(dst)));
28211 			/*
28212 			 * For strict: verify that dst is directly
28213 			 * reachable.
28214 			 */
28215 			if (optval == IPOPT_SSRR) {
28216 				ire = ire_ftable_lookup(dst, 0, 0,
28217 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28218 				    MBLK_GETLABEL(mp),
28219 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28220 				if (ire == NULL) {
28221 					ip1dbg(("ip_wput_options: SSRR not"
28222 					    " directly reachable: 0x%x\n",
28223 					    ntohl(dst)));
28224 					goto bad_src_route;
28225 				}
28226 				ire_refrele(ire);
28227 			}
28228 			break;
28229 		case IPOPT_RR:
28230 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28231 				ip1dbg((
28232 				    "ip_wput_options: bad option offset\n"));
28233 				code = (char *)&opt[IPOPT_OLEN] -
28234 				    (char *)ipha;
28235 				goto param_prob;
28236 			}
28237 			break;
28238 		case IPOPT_TS:
28239 			/*
28240 			 * Verify that length >=5 and that there is either
28241 			 * room for another timestamp or that the overflow
28242 			 * counter is not maxed out.
28243 			 */
28244 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28245 			if (optlen < IPOPT_MINLEN_IT) {
28246 				goto param_prob;
28247 			}
28248 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28249 				ip1dbg((
28250 				    "ip_wput_options: bad option offset\n"));
28251 				code = (char *)&opt[IPOPT_OFFSET] -
28252 				    (char *)ipha;
28253 				goto param_prob;
28254 			}
28255 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28256 			case IPOPT_TS_TSONLY:
28257 				off = IPOPT_TS_TIMELEN;
28258 				break;
28259 			case IPOPT_TS_TSANDADDR:
28260 			case IPOPT_TS_PRESPEC:
28261 			case IPOPT_TS_PRESPEC_RFC791:
28262 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28263 				break;
28264 			default:
28265 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28266 				    (char *)ipha;
28267 				goto param_prob;
28268 			}
28269 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28270 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28271 				/*
28272 				 * No room and the overflow counter is 15
28273 				 * already.
28274 				 */
28275 				goto param_prob;
28276 			}
28277 			break;
28278 		}
28279 	}
28280 
28281 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28282 		return (0);
28283 
28284 	ip1dbg(("ip_wput_options: error processing IP options."));
28285 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28286 
28287 param_prob:
28288 	/*
28289 	 * Since ip_wput() isn't close to finished, we fill
28290 	 * in enough of the header for credible error reporting.
28291 	 */
28292 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28293 		/* Failed */
28294 		freemsg(ipsec_mp);
28295 		return (-1);
28296 	}
28297 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28298 	return (-1);
28299 
28300 bad_src_route:
28301 	/*
28302 	 * Since ip_wput() isn't close to finished, we fill
28303 	 * in enough of the header for credible error reporting.
28304 	 */
28305 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28306 		/* Failed */
28307 		freemsg(ipsec_mp);
28308 		return (-1);
28309 	}
28310 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28311 	return (-1);
28312 }
28313 
28314 /*
28315  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28316  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28317  * thru /etc/system.
28318  */
28319 #define	CONN_MAXDRAINCNT	64
28320 
28321 static void
28322 conn_drain_init(ip_stack_t *ipst)
28323 {
28324 	int i;
28325 
28326 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28327 
28328 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28329 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28330 		/*
28331 		 * Default value of the number of drainers is the
28332 		 * number of cpus, subject to maximum of 8 drainers.
28333 		 */
28334 		if (boot_max_ncpus != -1)
28335 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28336 		else
28337 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28338 	}
28339 
28340 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28341 	    sizeof (idl_t), KM_SLEEP);
28342 
28343 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28344 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28345 		    MUTEX_DEFAULT, NULL);
28346 	}
28347 }
28348 
28349 static void
28350 conn_drain_fini(ip_stack_t *ipst)
28351 {
28352 	int i;
28353 
28354 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28355 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28356 	kmem_free(ipst->ips_conn_drain_list,
28357 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28358 	ipst->ips_conn_drain_list = NULL;
28359 }
28360 
28361 /*
28362  * Note: For an overview of how flowcontrol is handled in IP please see the
28363  * IP Flowcontrol notes at the top of this file.
28364  *
28365  * Flow control has blocked us from proceeding. Insert the given conn in one
28366  * of the conn drain lists. These conn wq's will be qenabled later on when
28367  * STREAMS flow control does a backenable. conn_walk_drain will enable
28368  * the first conn in each of these drain lists. Each of these qenabled conns
28369  * in turn enables the next in the list, after it runs, or when it closes,
28370  * thus sustaining the drain process.
28371  *
28372  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28373  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28374  * running at any time, on a given conn, since there can be only 1 service proc
28375  * running on a queue at any time.
28376  */
28377 void
28378 conn_drain_insert(conn_t *connp)
28379 {
28380 	idl_t	*idl;
28381 	uint_t	index;
28382 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28383 
28384 	mutex_enter(&connp->conn_lock);
28385 	if (connp->conn_state_flags & CONN_CLOSING) {
28386 		/*
28387 		 * The conn is closing as a result of which CONN_CLOSING
28388 		 * is set. Return.
28389 		 */
28390 		mutex_exit(&connp->conn_lock);
28391 		return;
28392 	} else if (connp->conn_idl == NULL) {
28393 		/*
28394 		 * Assign the next drain list round robin. We dont' use
28395 		 * a lock, and thus it may not be strictly round robin.
28396 		 * Atomicity of load/stores is enough to make sure that
28397 		 * conn_drain_list_index is always within bounds.
28398 		 */
28399 		index = ipst->ips_conn_drain_list_index;
28400 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28401 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28402 		index++;
28403 		if (index == ipst->ips_conn_drain_list_cnt)
28404 			index = 0;
28405 		ipst->ips_conn_drain_list_index = index;
28406 	}
28407 	mutex_exit(&connp->conn_lock);
28408 
28409 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28410 	if ((connp->conn_drain_prev != NULL) ||
28411 	    (connp->conn_state_flags & CONN_CLOSING)) {
28412 		/*
28413 		 * The conn is already in the drain list, OR
28414 		 * the conn is closing. We need to check again for
28415 		 * the closing case again since close can happen
28416 		 * after we drop the conn_lock, and before we
28417 		 * acquire the CONN_DRAIN_LIST_LOCK.
28418 		 */
28419 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28420 		return;
28421 	} else {
28422 		idl = connp->conn_idl;
28423 	}
28424 
28425 	/*
28426 	 * The conn is not in the drain list. Insert it at the
28427 	 * tail of the drain list. The drain list is circular
28428 	 * and doubly linked. idl_conn points to the 1st element
28429 	 * in the list.
28430 	 */
28431 	if (idl->idl_conn == NULL) {
28432 		idl->idl_conn = connp;
28433 		connp->conn_drain_next = connp;
28434 		connp->conn_drain_prev = connp;
28435 	} else {
28436 		conn_t *head = idl->idl_conn;
28437 
28438 		connp->conn_drain_next = head;
28439 		connp->conn_drain_prev = head->conn_drain_prev;
28440 		head->conn_drain_prev->conn_drain_next = connp;
28441 		head->conn_drain_prev = connp;
28442 	}
28443 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28444 }
28445 
28446 /*
28447  * This conn is closing, and we are called from ip_close. OR
28448  * This conn has been serviced by ip_wsrv, and we need to do the tail
28449  * processing.
28450  * If this conn is part of the drain list, we may need to sustain the drain
28451  * process by qenabling the next conn in the drain list. We may also need to
28452  * remove this conn from the list, if it is done.
28453  */
28454 static void
28455 conn_drain_tail(conn_t *connp, boolean_t closing)
28456 {
28457 	idl_t *idl;
28458 
28459 	/*
28460 	 * connp->conn_idl is stable at this point, and no lock is needed
28461 	 * to check it. If we are called from ip_close, close has already
28462 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28463 	 * called us only because conn_idl is non-null. If we are called thru
28464 	 * service, conn_idl could be null, but it cannot change because
28465 	 * service is single-threaded per queue, and there cannot be another
28466 	 * instance of service trying to call conn_drain_insert on this conn
28467 	 * now.
28468 	 */
28469 	ASSERT(!closing || (connp->conn_idl != NULL));
28470 
28471 	/*
28472 	 * If connp->conn_idl is null, the conn has not been inserted into any
28473 	 * drain list even once since creation of the conn. Just return.
28474 	 */
28475 	if (connp->conn_idl == NULL)
28476 		return;
28477 
28478 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28479 
28480 	if (connp->conn_drain_prev == NULL) {
28481 		/* This conn is currently not in the drain list.  */
28482 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28483 		return;
28484 	}
28485 	idl = connp->conn_idl;
28486 	if (idl->idl_conn_draining == connp) {
28487 		/*
28488 		 * This conn is the current drainer. If this is the last conn
28489 		 * in the drain list, we need to do more checks, in the 'if'
28490 		 * below. Otherwwise we need to just qenable the next conn,
28491 		 * to sustain the draining, and is handled in the 'else'
28492 		 * below.
28493 		 */
28494 		if (connp->conn_drain_next == idl->idl_conn) {
28495 			/*
28496 			 * This conn is the last in this list. This round
28497 			 * of draining is complete. If idl_repeat is set,
28498 			 * it means another flow enabling has happened from
28499 			 * the driver/streams and we need to another round
28500 			 * of draining.
28501 			 * If there are more than 2 conns in the drain list,
28502 			 * do a left rotate by 1, so that all conns except the
28503 			 * conn at the head move towards the head by 1, and the
28504 			 * the conn at the head goes to the tail. This attempts
28505 			 * a more even share for all queues that are being
28506 			 * drained.
28507 			 */
28508 			if ((connp->conn_drain_next != connp) &&
28509 			    (idl->idl_conn->conn_drain_next != connp)) {
28510 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28511 			}
28512 			if (idl->idl_repeat) {
28513 				qenable(idl->idl_conn->conn_wq);
28514 				idl->idl_conn_draining = idl->idl_conn;
28515 				idl->idl_repeat = 0;
28516 			} else {
28517 				idl->idl_conn_draining = NULL;
28518 			}
28519 		} else {
28520 			/*
28521 			 * If the next queue that we are now qenable'ing,
28522 			 * is closing, it will remove itself from this list
28523 			 * and qenable the subsequent queue in ip_close().
28524 			 * Serialization is acheived thru idl_lock.
28525 			 */
28526 			qenable(connp->conn_drain_next->conn_wq);
28527 			idl->idl_conn_draining = connp->conn_drain_next;
28528 		}
28529 	}
28530 	if (!connp->conn_did_putbq || closing) {
28531 		/*
28532 		 * Remove ourself from the drain list, if we did not do
28533 		 * a putbq, or if the conn is closing.
28534 		 * Note: It is possible that q->q_first is non-null. It means
28535 		 * that these messages landed after we did a enableok() in
28536 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28537 		 * service them.
28538 		 */
28539 		if (connp->conn_drain_next == connp) {
28540 			/* Singleton in the list */
28541 			ASSERT(connp->conn_drain_prev == connp);
28542 			idl->idl_conn = NULL;
28543 			idl->idl_conn_draining = NULL;
28544 		} else {
28545 			connp->conn_drain_prev->conn_drain_next =
28546 			    connp->conn_drain_next;
28547 			connp->conn_drain_next->conn_drain_prev =
28548 			    connp->conn_drain_prev;
28549 			if (idl->idl_conn == connp)
28550 				idl->idl_conn = connp->conn_drain_next;
28551 			ASSERT(idl->idl_conn_draining != connp);
28552 
28553 		}
28554 		connp->conn_drain_next = NULL;
28555 		connp->conn_drain_prev = NULL;
28556 	}
28557 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28558 }
28559 
28560 /*
28561  * Write service routine. Shared perimeter entry point.
28562  * ip_wsrv can be called in any of the following ways.
28563  * 1. The device queue's messages has fallen below the low water mark
28564  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28565  *    the drain lists and backenable the first conn in each list.
28566  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28567  *    qenabled non-tcp upper layers. We start dequeing messages and call
28568  *    ip_wput for each message.
28569  */
28570 
28571 void
28572 ip_wsrv(queue_t *q)
28573 {
28574 	conn_t	*connp;
28575 	ill_t	*ill;
28576 	mblk_t	*mp;
28577 
28578 	if (q->q_next) {
28579 		ill = (ill_t *)q->q_ptr;
28580 		if (ill->ill_state_flags == 0) {
28581 			/*
28582 			 * The device flow control has opened up.
28583 			 * Walk through conn drain lists and qenable the
28584 			 * first conn in each list. This makes sense only
28585 			 * if the stream is fully plumbed and setup.
28586 			 * Hence the if check above.
28587 			 */
28588 			ip1dbg(("ip_wsrv: walking\n"));
28589 			conn_walk_drain(ill->ill_ipst);
28590 		}
28591 		return;
28592 	}
28593 
28594 	connp = Q_TO_CONN(q);
28595 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28596 
28597 	/*
28598 	 * 1. Set conn_draining flag to signal that service is active.
28599 	 *
28600 	 * 2. ip_output determines whether it has been called from service,
28601 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28602 	 *    has been called from service.
28603 	 *
28604 	 * 3. Message ordering is preserved by the following logic.
28605 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28606 	 *    the message at the tail, if conn_draining is set (i.e. service
28607 	 *    is running) or if q->q_first is non-null.
28608 	 *
28609 	 *    ii. If ip_output is called from service, and if ip_output cannot
28610 	 *    putnext due to flow control, it does a putbq.
28611 	 *
28612 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28613 	 *    (causing an infinite loop).
28614 	 */
28615 	ASSERT(!connp->conn_did_putbq);
28616 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28617 		connp->conn_draining = 1;
28618 		noenable(q);
28619 		while ((mp = getq(q)) != NULL) {
28620 			ASSERT(CONN_Q(q));
28621 
28622 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28623 			if (connp->conn_did_putbq) {
28624 				/* ip_wput did a putbq */
28625 				break;
28626 			}
28627 		}
28628 		/*
28629 		 * At this point, a thread coming down from top, calling
28630 		 * ip_wput, may end up queueing the message. We have not yet
28631 		 * enabled the queue, so ip_wsrv won't be called again.
28632 		 * To avoid this race, check q->q_first again (in the loop)
28633 		 * If the other thread queued the message before we call
28634 		 * enableok(), we will catch it in the q->q_first check.
28635 		 * If the other thread queues the message after we call
28636 		 * enableok(), ip_wsrv will be called again by STREAMS.
28637 		 */
28638 		connp->conn_draining = 0;
28639 		enableok(q);
28640 	}
28641 
28642 	/* Enable the next conn for draining */
28643 	conn_drain_tail(connp, B_FALSE);
28644 
28645 	connp->conn_did_putbq = 0;
28646 }
28647 
28648 /*
28649  * Walk the list of all conn's calling the function provided with the
28650  * specified argument for each.	 Note that this only walks conn's that
28651  * have been bound.
28652  * Applies to both IPv4 and IPv6.
28653  */
28654 static void
28655 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28656 {
28657 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28658 	    ipst->ips_ipcl_udp_fanout_size,
28659 	    func, arg, zoneid);
28660 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28661 	    ipst->ips_ipcl_conn_fanout_size,
28662 	    func, arg, zoneid);
28663 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28664 	    ipst->ips_ipcl_bind_fanout_size,
28665 	    func, arg, zoneid);
28666 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28667 	    IPPROTO_MAX, func, arg, zoneid);
28668 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28669 	    IPPROTO_MAX, func, arg, zoneid);
28670 }
28671 
28672 /*
28673  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28674  * of conns that need to be drained, check if drain is already in progress.
28675  * If so set the idl_repeat bit, indicating that the last conn in the list
28676  * needs to reinitiate the drain once again, for the list. If drain is not
28677  * in progress for the list, initiate the draining, by qenabling the 1st
28678  * conn in the list. The drain is self-sustaining, each qenabled conn will
28679  * in turn qenable the next conn, when it is done/blocked/closing.
28680  */
28681 static void
28682 conn_walk_drain(ip_stack_t *ipst)
28683 {
28684 	int i;
28685 	idl_t *idl;
28686 
28687 	IP_STAT(ipst, ip_conn_walk_drain);
28688 
28689 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28690 		idl = &ipst->ips_conn_drain_list[i];
28691 		mutex_enter(&idl->idl_lock);
28692 		if (idl->idl_conn == NULL) {
28693 			mutex_exit(&idl->idl_lock);
28694 			continue;
28695 		}
28696 		/*
28697 		 * If this list is not being drained currently by
28698 		 * an ip_wsrv thread, start the process.
28699 		 */
28700 		if (idl->idl_conn_draining == NULL) {
28701 			ASSERT(idl->idl_repeat == 0);
28702 			qenable(idl->idl_conn->conn_wq);
28703 			idl->idl_conn_draining = idl->idl_conn;
28704 		} else {
28705 			idl->idl_repeat = 1;
28706 		}
28707 		mutex_exit(&idl->idl_lock);
28708 	}
28709 }
28710 
28711 /*
28712  * Walk an conn hash table of `count' buckets, calling func for each entry.
28713  */
28714 static void
28715 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28716     zoneid_t zoneid)
28717 {
28718 	conn_t	*connp;
28719 
28720 	while (count-- > 0) {
28721 		mutex_enter(&connfp->connf_lock);
28722 		for (connp = connfp->connf_head; connp != NULL;
28723 		    connp = connp->conn_next) {
28724 			if (zoneid == GLOBAL_ZONEID ||
28725 			    zoneid == connp->conn_zoneid) {
28726 				CONN_INC_REF(connp);
28727 				mutex_exit(&connfp->connf_lock);
28728 				(*func)(connp, arg);
28729 				mutex_enter(&connfp->connf_lock);
28730 				CONN_DEC_REF(connp);
28731 			}
28732 		}
28733 		mutex_exit(&connfp->connf_lock);
28734 		connfp++;
28735 	}
28736 }
28737 
28738 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28739 static void
28740 conn_report1(conn_t *connp, void *mp)
28741 {
28742 	char	buf1[INET6_ADDRSTRLEN];
28743 	char	buf2[INET6_ADDRSTRLEN];
28744 	uint_t	print_len, buf_len;
28745 
28746 	ASSERT(connp != NULL);
28747 
28748 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28749 	if (buf_len <= 0)
28750 		return;
28751 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28752 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28753 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28754 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28755 	    "%5d %s/%05d %s/%05d\n",
28756 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28757 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28758 	    buf1, connp->conn_lport,
28759 	    buf2, connp->conn_fport);
28760 	if (print_len < buf_len) {
28761 		((mblk_t *)mp)->b_wptr += print_len;
28762 	} else {
28763 		((mblk_t *)mp)->b_wptr += buf_len;
28764 	}
28765 }
28766 
28767 /*
28768  * Named Dispatch routine to produce a formatted report on all conns
28769  * that are listed in one of the fanout tables.
28770  * This report is accessed by using the ndd utility to "get" ND variable
28771  * "ip_conn_status".
28772  */
28773 /* ARGSUSED */
28774 static int
28775 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28776 {
28777 	conn_t *connp = Q_TO_CONN(q);
28778 
28779 	(void) mi_mpprintf(mp,
28780 	    "CONN      " MI_COL_HDRPAD_STR
28781 	    "rfq      " MI_COL_HDRPAD_STR
28782 	    "stq      " MI_COL_HDRPAD_STR
28783 	    " zone local                 remote");
28784 
28785 	/*
28786 	 * Because of the ndd constraint, at most we can have 64K buffer
28787 	 * to put in all conn info.  So to be more efficient, just
28788 	 * allocate a 64K buffer here, assuming we need that large buffer.
28789 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28790 	 */
28791 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28792 		/* The following may work even if we cannot get a large buf. */
28793 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28794 		return (0);
28795 	}
28796 
28797 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28798 	    connp->conn_netstack->netstack_ip);
28799 	return (0);
28800 }
28801 
28802 /*
28803  * Determine if the ill and multicast aspects of that packets
28804  * "matches" the conn.
28805  */
28806 boolean_t
28807 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28808     zoneid_t zoneid)
28809 {
28810 	ill_t *in_ill;
28811 	boolean_t found;
28812 	ipif_t *ipif;
28813 	ire_t *ire;
28814 	ipaddr_t dst, src;
28815 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28816 
28817 	dst = ipha->ipha_dst;
28818 	src = ipha->ipha_src;
28819 
28820 	/*
28821 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28822 	 * unicast, broadcast and multicast reception to
28823 	 * conn_incoming_ill. conn_wantpacket itself is called
28824 	 * only for BROADCAST and multicast.
28825 	 *
28826 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28827 	 *    is part of a group. Hence, we should be receiving
28828 	 *    just one copy of broadcast for the whole group.
28829 	 *    Thus, if it is part of the group the packet could
28830 	 *    come on any ill of the group and hence we need a
28831 	 *    match on the group. Otherwise, match on ill should
28832 	 *    be sufficient.
28833 	 *
28834 	 * 2) ip_rput does not suppress duplicate multicast packets.
28835 	 *    If there are two interfaces in a ill group and we have
28836 	 *    2 applications (conns) joined a multicast group G on
28837 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28838 	 *    will give us two packets because we join G on both the
28839 	 *    interfaces rather than nominating just one interface
28840 	 *    for receiving multicast like broadcast above. So,
28841 	 *    we have to call ilg_lookup_ill to filter out duplicate
28842 	 *    copies, if ill is part of a group.
28843 	 */
28844 	in_ill = connp->conn_incoming_ill;
28845 	if (in_ill != NULL) {
28846 		if (in_ill->ill_group == NULL) {
28847 			if (in_ill != ill)
28848 				return (B_FALSE);
28849 		} else if (in_ill->ill_group != ill->ill_group) {
28850 			return (B_FALSE);
28851 		}
28852 	}
28853 
28854 	if (!CLASSD(dst)) {
28855 		if (IPCL_ZONE_MATCH(connp, zoneid))
28856 			return (B_TRUE);
28857 		/*
28858 		 * The conn is in a different zone; we need to check that this
28859 		 * broadcast address is configured in the application's zone and
28860 		 * on one ill in the group.
28861 		 */
28862 		ipif = ipif_get_next_ipif(NULL, ill);
28863 		if (ipif == NULL)
28864 			return (B_FALSE);
28865 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28866 		    connp->conn_zoneid, NULL,
28867 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28868 		ipif_refrele(ipif);
28869 		if (ire != NULL) {
28870 			ire_refrele(ire);
28871 			return (B_TRUE);
28872 		} else {
28873 			return (B_FALSE);
28874 		}
28875 	}
28876 
28877 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28878 	    connp->conn_zoneid == zoneid) {
28879 		/*
28880 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28881 		 * disabled, therefore we don't dispatch the multicast packet to
28882 		 * the sending zone.
28883 		 */
28884 		return (B_FALSE);
28885 	}
28886 
28887 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28888 	    connp->conn_zoneid != zoneid) {
28889 		/*
28890 		 * Multicast packet on the loopback interface: we only match
28891 		 * conns who joined the group in the specified zone.
28892 		 */
28893 		return (B_FALSE);
28894 	}
28895 
28896 	if (connp->conn_multi_router) {
28897 		/* multicast packet and multicast router socket: send up */
28898 		return (B_TRUE);
28899 	}
28900 
28901 	mutex_enter(&connp->conn_lock);
28902 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28903 	mutex_exit(&connp->conn_lock);
28904 	return (found);
28905 }
28906 
28907 /*
28908  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28909  */
28910 /* ARGSUSED */
28911 static void
28912 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28913 {
28914 	ill_t *ill = (ill_t *)q->q_ptr;
28915 	mblk_t	*mp1, *mp2;
28916 	ipif_t  *ipif;
28917 	int err = 0;
28918 	conn_t *connp = NULL;
28919 	ipsq_t	*ipsq;
28920 	arc_t	*arc;
28921 
28922 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28923 
28924 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28925 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28926 
28927 	ASSERT(IAM_WRITER_ILL(ill));
28928 	mp2 = mp->b_cont;
28929 	mp->b_cont = NULL;
28930 
28931 	/*
28932 	 * We have now received the arp bringup completion message
28933 	 * from ARP. Mark the arp bringup as done. Also if the arp
28934 	 * stream has already started closing, send up the AR_ARP_CLOSING
28935 	 * ack now since ARP is waiting in close for this ack.
28936 	 */
28937 	mutex_enter(&ill->ill_lock);
28938 	ill->ill_arp_bringup_pending = 0;
28939 	if (ill->ill_arp_closing) {
28940 		mutex_exit(&ill->ill_lock);
28941 		/* Let's reuse the mp for sending the ack */
28942 		arc = (arc_t *)mp->b_rptr;
28943 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28944 		arc->arc_cmd = AR_ARP_CLOSING;
28945 		qreply(q, mp);
28946 	} else {
28947 		mutex_exit(&ill->ill_lock);
28948 		freeb(mp);
28949 	}
28950 
28951 	ipsq = ill->ill_phyint->phyint_ipsq;
28952 	ipif = ipsq->ipsq_pending_ipif;
28953 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28954 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28955 	if (mp1 == NULL) {
28956 		/* bringup was aborted by the user */
28957 		freemsg(mp2);
28958 		return;
28959 	}
28960 
28961 	/*
28962 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28963 	 * must have an associated conn_t.  Otherwise, we're bringing this
28964 	 * interface back up as part of handling an asynchronous event (e.g.,
28965 	 * physical address change).
28966 	 */
28967 	if (ipsq->ipsq_current_ioctl != 0) {
28968 		ASSERT(connp != NULL);
28969 		q = CONNP_TO_WQ(connp);
28970 	} else {
28971 		ASSERT(connp == NULL);
28972 		q = ill->ill_rq;
28973 	}
28974 
28975 	/*
28976 	 * If the DL_BIND_REQ fails, it is noted
28977 	 * in arc_name_offset.
28978 	 */
28979 	err = *((int *)mp2->b_rptr);
28980 	if (err == 0) {
28981 		if (ipif->ipif_isv6) {
28982 			if ((err = ipif_up_done_v6(ipif)) != 0)
28983 				ip0dbg(("ip_arp_done: init failed\n"));
28984 		} else {
28985 			if ((err = ipif_up_done(ipif)) != 0)
28986 				ip0dbg(("ip_arp_done: init failed\n"));
28987 		}
28988 	} else {
28989 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28990 	}
28991 
28992 	freemsg(mp2);
28993 
28994 	if ((err == 0) && (ill->ill_up_ipifs)) {
28995 		err = ill_up_ipifs(ill, q, mp1);
28996 		if (err == EINPROGRESS)
28997 			return;
28998 	}
28999 
29000 	if (ill->ill_up_ipifs)
29001 		ill_group_cleanup(ill);
29002 
29003 	/*
29004 	 * The operation must complete without EINPROGRESS since
29005 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29006 	 * Otherwise, the operation will be stuck forever in the ipsq.
29007 	 */
29008 	ASSERT(err != EINPROGRESS);
29009 	if (ipsq->ipsq_current_ioctl != 0)
29010 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29011 	else
29012 		ipsq_current_finish(ipsq);
29013 }
29014 
29015 /* Allocate the private structure */
29016 static int
29017 ip_priv_alloc(void **bufp)
29018 {
29019 	void	*buf;
29020 
29021 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29022 		return (ENOMEM);
29023 
29024 	*bufp = buf;
29025 	return (0);
29026 }
29027 
29028 /* Function to delete the private structure */
29029 void
29030 ip_priv_free(void *buf)
29031 {
29032 	ASSERT(buf != NULL);
29033 	kmem_free(buf, sizeof (ip_priv_t));
29034 }
29035 
29036 /*
29037  * The entry point for IPPF processing.
29038  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29039  * routine just returns.
29040  *
29041  * When called, ip_process generates an ipp_packet_t structure
29042  * which holds the state information for this packet and invokes the
29043  * the classifier (via ipp_packet_process). The classification, depending on
29044  * configured filters, results in a list of actions for this packet. Invoking
29045  * an action may cause the packet to be dropped, in which case the resulting
29046  * mblk (*mpp) is NULL. proc indicates the callout position for
29047  * this packet and ill_index is the interface this packet on or will leave
29048  * on (inbound and outbound resp.).
29049  */
29050 void
29051 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29052 {
29053 	mblk_t		*mp;
29054 	ip_priv_t	*priv;
29055 	ipp_action_id_t	aid;
29056 	int		rc = 0;
29057 	ipp_packet_t	*pp;
29058 #define	IP_CLASS	"ip"
29059 
29060 	/* If the classifier is not loaded, return  */
29061 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29062 		return;
29063 	}
29064 
29065 	mp = *mpp;
29066 	ASSERT(mp != NULL);
29067 
29068 	/* Allocate the packet structure */
29069 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29070 	if (rc != 0) {
29071 		*mpp = NULL;
29072 		freemsg(mp);
29073 		return;
29074 	}
29075 
29076 	/* Allocate the private structure */
29077 	rc = ip_priv_alloc((void **)&priv);
29078 	if (rc != 0) {
29079 		*mpp = NULL;
29080 		freemsg(mp);
29081 		ipp_packet_free(pp);
29082 		return;
29083 	}
29084 	priv->proc = proc;
29085 	priv->ill_index = ill_index;
29086 	ipp_packet_set_private(pp, priv, ip_priv_free);
29087 	ipp_packet_set_data(pp, mp);
29088 
29089 	/* Invoke the classifier */
29090 	rc = ipp_packet_process(&pp);
29091 	if (pp != NULL) {
29092 		mp = ipp_packet_get_data(pp);
29093 		ipp_packet_free(pp);
29094 		if (rc != 0) {
29095 			freemsg(mp);
29096 			*mpp = NULL;
29097 		}
29098 	} else {
29099 		*mpp = NULL;
29100 	}
29101 #undef	IP_CLASS
29102 }
29103 
29104 /*
29105  * Propagate a multicast group membership operation (add/drop) on
29106  * all the interfaces crossed by the related multirt routes.
29107  * The call is considered successful if the operation succeeds
29108  * on at least one interface.
29109  */
29110 static int
29111 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29112     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29113     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29114     mblk_t *first_mp)
29115 {
29116 	ire_t		*ire_gw;
29117 	irb_t		*irb;
29118 	int		error = 0;
29119 	opt_restart_t	*or;
29120 	ip_stack_t	*ipst = ire->ire_ipst;
29121 
29122 	irb = ire->ire_bucket;
29123 	ASSERT(irb != NULL);
29124 
29125 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29126 
29127 	or = (opt_restart_t *)first_mp->b_rptr;
29128 	IRB_REFHOLD(irb);
29129 	for (; ire != NULL; ire = ire->ire_next) {
29130 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29131 			continue;
29132 		if (ire->ire_addr != group)
29133 			continue;
29134 
29135 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29136 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29137 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29138 		/* No resolver exists for the gateway; skip this ire. */
29139 		if (ire_gw == NULL)
29140 			continue;
29141 
29142 		/*
29143 		 * This function can return EINPROGRESS. If so the operation
29144 		 * will be restarted from ip_restart_optmgmt which will
29145 		 * call ip_opt_set and option processing will restart for
29146 		 * this option. So we may end up calling 'fn' more than once.
29147 		 * This requires that 'fn' is idempotent except for the
29148 		 * return value. The operation is considered a success if
29149 		 * it succeeds at least once on any one interface.
29150 		 */
29151 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29152 		    NULL, fmode, src, first_mp);
29153 		if (error == 0)
29154 			or->or_private = CGTP_MCAST_SUCCESS;
29155 
29156 		if (ip_debug > 0) {
29157 			ulong_t	off;
29158 			char	*ksym;
29159 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29160 			ip2dbg(("ip_multirt_apply_membership: "
29161 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29162 			    "error %d [success %u]\n",
29163 			    ksym ? ksym : "?",
29164 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29165 			    error, or->or_private));
29166 		}
29167 
29168 		ire_refrele(ire_gw);
29169 		if (error == EINPROGRESS) {
29170 			IRB_REFRELE(irb);
29171 			return (error);
29172 		}
29173 	}
29174 	IRB_REFRELE(irb);
29175 	/*
29176 	 * Consider the call as successful if we succeeded on at least
29177 	 * one interface. Otherwise, return the last encountered error.
29178 	 */
29179 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29180 }
29181 
29182 
29183 /*
29184  * Issue a warning regarding a route crossing an interface with an
29185  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29186  * amount of time is logged.
29187  */
29188 static void
29189 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29190 {
29191 	hrtime_t	current = gethrtime();
29192 	char		buf[INET_ADDRSTRLEN];
29193 	ip_stack_t	*ipst = ire->ire_ipst;
29194 
29195 	/* Convert interval in ms to hrtime in ns */
29196 	if (ipst->ips_multirt_bad_mtu_last_time +
29197 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29198 	    current) {
29199 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29200 		    "to %s, incorrect MTU %u (expected %u)\n",
29201 		    ip_dot_addr(ire->ire_addr, buf),
29202 		    ire->ire_max_frag, max_frag);
29203 
29204 		ipst->ips_multirt_bad_mtu_last_time = current;
29205 	}
29206 }
29207 
29208 
29209 /*
29210  * Get the CGTP (multirouting) filtering status.
29211  * If 0, the CGTP hooks are transparent.
29212  */
29213 /* ARGSUSED */
29214 static int
29215 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29216 {
29217 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29218 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29219 
29220 	/*
29221 	 * Only applies to the shared stack since the filter_ops
29222 	 * do not carry an ip_stack_t or zoneid.
29223 	 */
29224 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29225 		return (ENOTSUP);
29226 
29227 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29228 	return (0);
29229 }
29230 
29231 
29232 /*
29233  * Set the CGTP (multirouting) filtering status.
29234  * If the status is changed from active to transparent
29235  * or from transparent to active, forward the new status
29236  * to the filtering module (if loaded).
29237  */
29238 /* ARGSUSED */
29239 static int
29240 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29241     cred_t *ioc_cr)
29242 {
29243 	long		new_value;
29244 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29245 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29246 
29247 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29248 		return (EPERM);
29249 
29250 	/*
29251 	 * Only applies to the shared stack since the filter_ops
29252 	 * do not carry an ip_stack_t or zoneid.
29253 	 */
29254 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29255 		return (ENOTSUP);
29256 
29257 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29258 	    new_value < 0 || new_value > 1) {
29259 		return (EINVAL);
29260 	}
29261 
29262 	/*
29263 	 * Do not enable CGTP filtering - thus preventing the hooks
29264 	 * from being invoked - if the version number of the
29265 	 * filtering module hooks does not match.
29266 	 */
29267 	if ((ip_cgtp_filter_ops != NULL) &&
29268 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29269 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29270 		    "(module hooks version %d, expecting %d)\n",
29271 		    ip_cgtp_filter_ops->cfo_filter_rev,
29272 		    CGTP_FILTER_REV);
29273 		return (ENOTSUP);
29274 	}
29275 
29276 	if ((!*ip_cgtp_filter_value) && new_value) {
29277 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29278 		    ip_cgtp_filter_ops == NULL ?
29279 		    " (module not loaded)" : "");
29280 	}
29281 	if (*ip_cgtp_filter_value && (!new_value)) {
29282 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29283 		    ip_cgtp_filter_ops == NULL ?
29284 		    " (module not loaded)" : "");
29285 	}
29286 
29287 	if (ip_cgtp_filter_ops != NULL) {
29288 		int	res;
29289 
29290 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29291 		if (res)
29292 			return (res);
29293 	}
29294 
29295 	*ip_cgtp_filter_value = (boolean_t)new_value;
29296 
29297 	return (0);
29298 }
29299 
29300 
29301 /*
29302  * Return the expected CGTP hooks version number.
29303  */
29304 int
29305 ip_cgtp_filter_supported(void)
29306 {
29307 	ip_stack_t *ipst;
29308 	int ret;
29309 
29310 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29311 	if (ipst == NULL)
29312 		return (-1);
29313 	ret = ip_cgtp_filter_rev;
29314 	netstack_rele(ipst->ips_netstack);
29315 	return (ret);
29316 }
29317 
29318 
29319 /*
29320  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29321  * or by invoking this function. In the first case, the version number
29322  * of the registered structure is checked at hooks activation time
29323  * in ip_cgtp_filter_set().
29324  *
29325  * Only applies to the shared stack since the filter_ops
29326  * do not carry an ip_stack_t or zoneid.
29327  */
29328 int
29329 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29330 {
29331 	ip_stack_t *ipst;
29332 
29333 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29334 		return (ENOTSUP);
29335 
29336 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29337 	if (ipst == NULL)
29338 		return (EINVAL);
29339 
29340 	ip_cgtp_filter_ops = ops;
29341 	netstack_rele(ipst->ips_netstack);
29342 	return (0);
29343 }
29344 
29345 static squeue_func_t
29346 ip_squeue_switch(int val)
29347 {
29348 	squeue_func_t rval = squeue_fill;
29349 
29350 	switch (val) {
29351 	case IP_SQUEUE_ENTER_NODRAIN:
29352 		rval = squeue_enter_nodrain;
29353 		break;
29354 	case IP_SQUEUE_ENTER:
29355 		rval = squeue_enter;
29356 		break;
29357 	default:
29358 		break;
29359 	}
29360 	return (rval);
29361 }
29362 
29363 /* ARGSUSED */
29364 static int
29365 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29366     caddr_t addr, cred_t *cr)
29367 {
29368 	int *v = (int *)addr;
29369 	long new_value;
29370 
29371 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29372 		return (EPERM);
29373 
29374 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29375 		return (EINVAL);
29376 
29377 	ip_input_proc = ip_squeue_switch(new_value);
29378 	*v = new_value;
29379 	return (0);
29380 }
29381 
29382 /* ARGSUSED */
29383 static int
29384 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29385     caddr_t addr, cred_t *cr)
29386 {
29387 	int *v = (int *)addr;
29388 	long new_value;
29389 
29390 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29391 		return (EPERM);
29392 
29393 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29394 		return (EINVAL);
29395 
29396 	*v = new_value;
29397 	return (0);
29398 }
29399 
29400 /*
29401  * Handle changes to ipmp_hook_emulation ndd variable.
29402  * Need to update phyint_hook_ifindex.
29403  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29404  */
29405 static void
29406 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29407 {
29408 	phyint_t *phyi;
29409 	phyint_t *phyi_tmp;
29410 	char *groupname;
29411 	int namelen;
29412 	ill_t	*ill;
29413 	boolean_t new_group;
29414 
29415 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29416 	/*
29417 	 * Group indicies are stored in the phyint - a common structure
29418 	 * to both IPv4 and IPv6.
29419 	 */
29420 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29421 	for (; phyi != NULL;
29422 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29423 	    phyi, AVL_AFTER)) {
29424 		/* Ignore the ones that do not have a group */
29425 		if (phyi->phyint_groupname_len == 0)
29426 			continue;
29427 
29428 		/*
29429 		 * Look for other phyint in group.
29430 		 * Clear name/namelen so the lookup doesn't find ourselves.
29431 		 */
29432 		namelen = phyi->phyint_groupname_len;
29433 		groupname = phyi->phyint_groupname;
29434 		phyi->phyint_groupname_len = 0;
29435 		phyi->phyint_groupname = NULL;
29436 
29437 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29438 		/* Restore */
29439 		phyi->phyint_groupname_len = namelen;
29440 		phyi->phyint_groupname = groupname;
29441 
29442 		new_group = B_FALSE;
29443 		if (ipst->ips_ipmp_hook_emulation) {
29444 			/*
29445 			 * If the group already exists and has already
29446 			 * been assigned a group ifindex, we use the existing
29447 			 * group_ifindex, otherwise we pick a new group_ifindex
29448 			 * here.
29449 			 */
29450 			if (phyi_tmp != NULL &&
29451 			    phyi_tmp->phyint_group_ifindex != 0) {
29452 				phyi->phyint_group_ifindex =
29453 				    phyi_tmp->phyint_group_ifindex;
29454 			} else {
29455 				/* XXX We need a recovery strategy here. */
29456 				if (!ip_assign_ifindex(
29457 				    &phyi->phyint_group_ifindex, ipst))
29458 					cmn_err(CE_PANIC,
29459 					    "ip_assign_ifindex() failed");
29460 				new_group = B_TRUE;
29461 			}
29462 		} else {
29463 			phyi->phyint_group_ifindex = 0;
29464 		}
29465 		if (ipst->ips_ipmp_hook_emulation)
29466 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29467 		else
29468 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29469 
29470 		/*
29471 		 * For IP Filter to find out the relationship between
29472 		 * names and interface indicies, we need to generate
29473 		 * a NE_PLUMB event when a new group can appear.
29474 		 * We always generate events when a new interface appears
29475 		 * (even when ipmp_hook_emulation is set) so there
29476 		 * is no need to generate NE_PLUMB events when
29477 		 * ipmp_hook_emulation is turned off.
29478 		 * And since it isn't critical for IP Filter to get
29479 		 * the NE_UNPLUMB events we skip those here.
29480 		 */
29481 		if (new_group) {
29482 			/*
29483 			 * First phyint in group - generate group PLUMB event.
29484 			 * Since we are not running inside the ipsq we do
29485 			 * the dispatch immediately.
29486 			 */
29487 			if (phyi->phyint_illv4 != NULL)
29488 				ill = phyi->phyint_illv4;
29489 			else
29490 				ill = phyi->phyint_illv6;
29491 
29492 			if (ill != NULL) {
29493 				mutex_enter(&ill->ill_lock);
29494 				ill_nic_info_plumb(ill, B_TRUE);
29495 				ill_nic_info_dispatch(ill);
29496 				mutex_exit(&ill->ill_lock);
29497 			}
29498 		}
29499 	}
29500 	rw_exit(&ipst->ips_ill_g_lock);
29501 }
29502 
29503 /* ARGSUSED */
29504 static int
29505 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29506     caddr_t addr, cred_t *cr)
29507 {
29508 	int *v = (int *)addr;
29509 	long new_value;
29510 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29511 
29512 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29513 		return (EINVAL);
29514 
29515 	if (*v != new_value) {
29516 		*v = new_value;
29517 		ipmp_hook_emulation_changed(ipst);
29518 	}
29519 	return (0);
29520 }
29521 
29522 static void *
29523 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29524 {
29525 	kstat_t *ksp;
29526 
29527 	ip_stat_t template = {
29528 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29529 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29530 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29531 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29532 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29533 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29534 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29535 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29536 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29537 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29538 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29539 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29540 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29541 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29542 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29543 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29544 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29545 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29546 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29547 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29548 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29549 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29550 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29551 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29552 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29553 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29554 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29555 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29556 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29557 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29558 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29559 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29560 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29561 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29562 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29563 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29564 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29565 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29566 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29567 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29568 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29569 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29570 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29571 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29572 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29573 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29574 	};
29575 
29576 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29577 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29578 	    KSTAT_FLAG_VIRTUAL, stackid);
29579 
29580 	if (ksp == NULL)
29581 		return (NULL);
29582 
29583 	bcopy(&template, ip_statisticsp, sizeof (template));
29584 	ksp->ks_data = (void *)ip_statisticsp;
29585 	ksp->ks_private = (void *)(uintptr_t)stackid;
29586 
29587 	kstat_install(ksp);
29588 	return (ksp);
29589 }
29590 
29591 static void
29592 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29593 {
29594 	if (ksp != NULL) {
29595 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29596 		kstat_delete_netstack(ksp, stackid);
29597 	}
29598 }
29599 
29600 static void *
29601 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29602 {
29603 	kstat_t	*ksp;
29604 
29605 	ip_named_kstat_t template = {
29606 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29607 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29608 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29609 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29610 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29611 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29612 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29613 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29614 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29615 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29616 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29617 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29618 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29619 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29620 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29621 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29622 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29623 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29624 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29625 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29626 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29627 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29628 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29629 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29630 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29631 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29632 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29633 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29634 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29635 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29636 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29637 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29638 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29639 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29640 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29641 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29642 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29643 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29644 	};
29645 
29646 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29647 					NUM_OF_FIELDS(ip_named_kstat_t),
29648 					0, stackid);
29649 	if (ksp == NULL || ksp->ks_data == NULL)
29650 		return (NULL);
29651 
29652 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29653 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29654 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29655 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29656 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29657 
29658 	template.netToMediaEntrySize.value.i32 =
29659 		sizeof (mib2_ipNetToMediaEntry_t);
29660 
29661 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29662 
29663 	bcopy(&template, ksp->ks_data, sizeof (template));
29664 	ksp->ks_update = ip_kstat_update;
29665 	ksp->ks_private = (void *)(uintptr_t)stackid;
29666 
29667 	kstat_install(ksp);
29668 	return (ksp);
29669 }
29670 
29671 static void
29672 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29673 {
29674 	if (ksp != NULL) {
29675 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29676 		kstat_delete_netstack(ksp, stackid);
29677 	}
29678 }
29679 
29680 static int
29681 ip_kstat_update(kstat_t *kp, int rw)
29682 {
29683 	ip_named_kstat_t *ipkp;
29684 	mib2_ipIfStatsEntry_t ipmib;
29685 	ill_walk_context_t ctx;
29686 	ill_t *ill;
29687 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29688 	netstack_t	*ns;
29689 	ip_stack_t	*ipst;
29690 
29691 	if (kp == NULL || kp->ks_data == NULL)
29692 		return (EIO);
29693 
29694 	if (rw == KSTAT_WRITE)
29695 		return (EACCES);
29696 
29697 	ns = netstack_find_by_stackid(stackid);
29698 	if (ns == NULL)
29699 		return (-1);
29700 	ipst = ns->netstack_ip;
29701 	if (ipst == NULL) {
29702 		netstack_rele(ns);
29703 		return (-1);
29704 	}
29705 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29706 
29707 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29708 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29709 	ill = ILL_START_WALK_V4(&ctx, ipst);
29710 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29711 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29712 	rw_exit(&ipst->ips_ill_g_lock);
29713 
29714 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29715 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29716 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29717 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29718 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29719 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29720 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29721 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29722 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29723 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29724 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29725 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29726 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29727 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29728 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29729 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29730 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29731 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29732 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29733 
29734 	ipkp->routingDiscards.value.ui32 =	0;
29735 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29736 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29737 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29738 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29739 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29740 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29741 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29742 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29743 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29744 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29745 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29746 
29747 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29748 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29749 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29750 
29751 	netstack_rele(ns);
29752 
29753 	return (0);
29754 }
29755 
29756 static void *
29757 icmp_kstat_init(netstackid_t stackid)
29758 {
29759 	kstat_t	*ksp;
29760 
29761 	icmp_named_kstat_t template = {
29762 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29763 		{ "inErrors",		KSTAT_DATA_UINT32 },
29764 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29765 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29766 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29767 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29768 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29769 		{ "inEchos",		KSTAT_DATA_UINT32 },
29770 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29771 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29772 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29773 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29774 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29775 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29776 		{ "outErrors",		KSTAT_DATA_UINT32 },
29777 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29778 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29779 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29780 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29781 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29782 		{ "outEchos",		KSTAT_DATA_UINT32 },
29783 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29784 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29785 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29786 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29787 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29788 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29789 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29790 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29791 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29792 		{ "outDrops",		KSTAT_DATA_UINT32 },
29793 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29794 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29795 	};
29796 
29797 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29798 					NUM_OF_FIELDS(icmp_named_kstat_t),
29799 					0, stackid);
29800 	if (ksp == NULL || ksp->ks_data == NULL)
29801 		return (NULL);
29802 
29803 	bcopy(&template, ksp->ks_data, sizeof (template));
29804 
29805 	ksp->ks_update = icmp_kstat_update;
29806 	ksp->ks_private = (void *)(uintptr_t)stackid;
29807 
29808 	kstat_install(ksp);
29809 	return (ksp);
29810 }
29811 
29812 static void
29813 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29814 {
29815 	if (ksp != NULL) {
29816 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29817 		kstat_delete_netstack(ksp, stackid);
29818 	}
29819 }
29820 
29821 static int
29822 icmp_kstat_update(kstat_t *kp, int rw)
29823 {
29824 	icmp_named_kstat_t *icmpkp;
29825 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29826 	netstack_t	*ns;
29827 	ip_stack_t	*ipst;
29828 
29829 	if ((kp == NULL) || (kp->ks_data == NULL))
29830 		return (EIO);
29831 
29832 	if (rw == KSTAT_WRITE)
29833 		return (EACCES);
29834 
29835 	ns = netstack_find_by_stackid(stackid);
29836 	if (ns == NULL)
29837 		return (-1);
29838 	ipst = ns->netstack_ip;
29839 	if (ipst == NULL) {
29840 		netstack_rele(ns);
29841 		return (-1);
29842 	}
29843 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29844 
29845 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29846 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29847 	icmpkp->inDestUnreachs.value.ui32 =
29848 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29849 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29850 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29851 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29852 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29853 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29854 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29855 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29856 	icmpkp->inTimestampReps.value.ui32 =
29857 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29858 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29859 	icmpkp->inAddrMaskReps.value.ui32 =
29860 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29861 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29862 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29863 	icmpkp->outDestUnreachs.value.ui32 =
29864 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29865 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29866 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29867 	icmpkp->outSrcQuenchs.value.ui32 =
29868 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29869 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29870 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29871 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29872 	icmpkp->outTimestamps.value.ui32 =
29873 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29874 	icmpkp->outTimestampReps.value.ui32 =
29875 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29876 	icmpkp->outAddrMasks.value.ui32 =
29877 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29878 	icmpkp->outAddrMaskReps.value.ui32 =
29879 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29880 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29881 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29882 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29883 	icmpkp->outFragNeeded.value.ui32 =
29884 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29885 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29886 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29887 	icmpkp->inBadRedirects.value.ui32 =
29888 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29889 
29890 	netstack_rele(ns);
29891 	return (0);
29892 }
29893 
29894 /*
29895  * This is the fanout function for raw socket opened for SCTP.  Note
29896  * that it is called after SCTP checks that there is no socket which
29897  * wants a packet.  Then before SCTP handles this out of the blue packet,
29898  * this function is called to see if there is any raw socket for SCTP.
29899  * If there is and it is bound to the correct address, the packet will
29900  * be sent to that socket.  Note that only one raw socket can be bound to
29901  * a port.  This is assured in ipcl_sctp_hash_insert();
29902  */
29903 void
29904 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29905     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29906     zoneid_t zoneid)
29907 {
29908 	conn_t		*connp;
29909 	queue_t		*rq;
29910 	mblk_t		*first_mp;
29911 	boolean_t	secure;
29912 	ip6_t		*ip6h;
29913 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29914 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29915 
29916 	first_mp = mp;
29917 	if (mctl_present) {
29918 		mp = first_mp->b_cont;
29919 		secure = ipsec_in_is_secure(first_mp);
29920 		ASSERT(mp != NULL);
29921 	} else {
29922 		secure = B_FALSE;
29923 	}
29924 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29925 
29926 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29927 	if (connp == NULL) {
29928 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29929 		return;
29930 	}
29931 	rq = connp->conn_rq;
29932 	if (!canputnext(rq)) {
29933 		CONN_DEC_REF(connp);
29934 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29935 		freemsg(first_mp);
29936 		return;
29937 	}
29938 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29939 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29940 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29941 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29942 		if (first_mp == NULL) {
29943 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29944 			CONN_DEC_REF(connp);
29945 			return;
29946 		}
29947 	}
29948 	/*
29949 	 * We probably should not send M_CTL message up to
29950 	 * raw socket.
29951 	 */
29952 	if (mctl_present)
29953 		freeb(first_mp);
29954 
29955 	/* Initiate IPPF processing here if needed. */
29956 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29957 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29958 		ip_process(IPP_LOCAL_IN, &mp,
29959 		    recv_ill->ill_phyint->phyint_ifindex);
29960 		if (mp == NULL) {
29961 			CONN_DEC_REF(connp);
29962 			return;
29963 		}
29964 	}
29965 
29966 	if (connp->conn_recvif || connp->conn_recvslla ||
29967 	    ((connp->conn_ip_recvpktinfo ||
29968 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29969 	    (flags & IP_FF_IPINFO))) {
29970 		int in_flags = 0;
29971 
29972 		/*
29973 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29974 		 * IPF_RECVIF.
29975 		 */
29976 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29977 			in_flags = IPF_RECVIF;
29978 		}
29979 		if (connp->conn_recvslla) {
29980 			in_flags |= IPF_RECVSLLA;
29981 		}
29982 		if (isv4) {
29983 			mp = ip_add_info(mp, recv_ill, in_flags,
29984 			    IPCL_ZONEID(connp), ipst);
29985 		} else {
29986 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29987 			if (mp == NULL) {
29988 				BUMP_MIB(recv_ill->ill_ip_mib,
29989 				    ipIfStatsInDiscards);
29990 				CONN_DEC_REF(connp);
29991 				return;
29992 			}
29993 		}
29994 	}
29995 
29996 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29997 	/*
29998 	 * We are sending the IPSEC_IN message also up. Refer
29999 	 * to comments above this function.
30000 	 */
30001 	putnext(rq, mp);
30002 	CONN_DEC_REF(connp);
30003 }
30004 
30005 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30006 {									\
30007 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30008 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30009 }
30010 /*
30011  * This function should be called only if all packet processing
30012  * including fragmentation is complete. Callers of this function
30013  * must set mp->b_prev to one of these values:
30014  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30015  * prior to handing over the mp as first argument to this function.
30016  *
30017  * If the ire passed by caller is incomplete, this function
30018  * queues the packet and if necessary, sends ARP request and bails.
30019  * If the ire passed is fully resolved, we simply prepend
30020  * the link-layer header to the packet, do ipsec hw acceleration
30021  * work if necessary, and send the packet out on the wire.
30022  *
30023  * NOTE: IPSEC will only call this function with fully resolved
30024  * ires if hw acceleration is involved.
30025  * TODO list :
30026  * 	a Handle M_MULTIDATA so that
30027  *	  tcp_multisend->tcp_multisend_data can
30028  *	  call ip_xmit_v4 directly
30029  *	b Handle post-ARP work for fragments so that
30030  *	  ip_wput_frag can call this function.
30031  */
30032 ipxmit_state_t
30033 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30034 {
30035 	nce_t		*arpce;
30036 	queue_t		*q;
30037 	int		ill_index;
30038 	mblk_t		*nxt_mp, *first_mp;
30039 	boolean_t	xmit_drop = B_FALSE;
30040 	ip_proc_t	proc;
30041 	ill_t		*out_ill;
30042 	int		pkt_len;
30043 
30044 	arpce = ire->ire_nce;
30045 	ASSERT(arpce != NULL);
30046 
30047 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30048 
30049 	mutex_enter(&arpce->nce_lock);
30050 	switch (arpce->nce_state) {
30051 	case ND_REACHABLE:
30052 		/* If there are other queued packets, queue this packet */
30053 		if (arpce->nce_qd_mp != NULL) {
30054 			if (mp != NULL)
30055 				nce_queue_mp_common(arpce, mp, B_FALSE);
30056 			mp = arpce->nce_qd_mp;
30057 		}
30058 		arpce->nce_qd_mp = NULL;
30059 		mutex_exit(&arpce->nce_lock);
30060 
30061 		/*
30062 		 * Flush the queue.  In the common case, where the
30063 		 * ARP is already resolved,  it will go through the
30064 		 * while loop only once.
30065 		 */
30066 		while (mp != NULL) {
30067 
30068 			nxt_mp = mp->b_next;
30069 			mp->b_next = NULL;
30070 			ASSERT(mp->b_datap->db_type != M_CTL);
30071 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30072 			/*
30073 			 * This info is needed for IPQOS to do COS marking
30074 			 * in ip_wput_attach_llhdr->ip_process.
30075 			 */
30076 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30077 			mp->b_prev = NULL;
30078 
30079 			/* set up ill index for outbound qos processing */
30080 			out_ill = ire->ire_ipif->ipif_ill;
30081 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30082 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30083 			    ill_index);
30084 			if (first_mp == NULL) {
30085 				xmit_drop = B_TRUE;
30086 				BUMP_MIB(out_ill->ill_ip_mib,
30087 				    ipIfStatsOutDiscards);
30088 				goto next_mp;
30089 			}
30090 			/* non-ipsec hw accel case */
30091 			if (io == NULL || !io->ipsec_out_accelerated) {
30092 				/* send it */
30093 				q = ire->ire_stq;
30094 				if (proc == IPP_FWD_OUT) {
30095 					UPDATE_IB_PKT_COUNT(ire);
30096 				} else {
30097 					UPDATE_OB_PKT_COUNT(ire);
30098 				}
30099 				ire->ire_last_used_time = lbolt;
30100 
30101 				if (flow_ctl_enabled || canputnext(q))  {
30102 					if (proc == IPP_FWD_OUT) {
30103 						BUMP_MIB(out_ill->ill_ip_mib,
30104 						ipIfStatsHCOutForwDatagrams);
30105 					}
30106 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30107 					    pkt_len);
30108 
30109 					putnext(q, first_mp);
30110 				} else {
30111 					BUMP_MIB(out_ill->ill_ip_mib,
30112 					    ipIfStatsOutDiscards);
30113 					xmit_drop = B_TRUE;
30114 					freemsg(first_mp);
30115 				}
30116 			} else {
30117 				/*
30118 				 * Safety Pup says: make sure this
30119 				 *  is going to the right interface!
30120 				 */
30121 				ill_t *ill1 =
30122 				    (ill_t *)ire->ire_stq->q_ptr;
30123 				int ifindex =
30124 				    ill1->ill_phyint->phyint_ifindex;
30125 				if (ifindex !=
30126 				    io->ipsec_out_capab_ill_index) {
30127 					xmit_drop = B_TRUE;
30128 					freemsg(mp);
30129 				} else {
30130 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30131 					    pkt_len);
30132 					ipsec_hw_putnext(ire->ire_stq, mp);
30133 				}
30134 			}
30135 next_mp:
30136 			mp = nxt_mp;
30137 		} /* while (mp != NULL) */
30138 		if (xmit_drop)
30139 			return (SEND_FAILED);
30140 		else
30141 			return (SEND_PASSED);
30142 
30143 	case ND_INITIAL:
30144 	case ND_INCOMPLETE:
30145 
30146 		/*
30147 		 * While we do send off packets to dests that
30148 		 * use fully-resolved CGTP routes, we do not
30149 		 * handle unresolved CGTP routes.
30150 		 */
30151 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30152 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30153 
30154 		if (mp != NULL) {
30155 			/* queue the packet */
30156 			nce_queue_mp_common(arpce, mp, B_FALSE);
30157 		}
30158 
30159 		if (arpce->nce_state == ND_INCOMPLETE) {
30160 			mutex_exit(&arpce->nce_lock);
30161 			DTRACE_PROBE3(ip__xmit__incomplete,
30162 			    (ire_t *), ire, (mblk_t *), mp,
30163 			    (ipsec_out_t *), io);
30164 			return (LOOKUP_IN_PROGRESS);
30165 		}
30166 
30167 		arpce->nce_state = ND_INCOMPLETE;
30168 		mutex_exit(&arpce->nce_lock);
30169 		/*
30170 		 * Note that ire_add() (called from ire_forward())
30171 		 * holds a ref on the ire until ARP is completed.
30172 		 */
30173 
30174 		ire_arpresolve(ire, ire_to_ill(ire));
30175 		return (LOOKUP_IN_PROGRESS);
30176 	default:
30177 		ASSERT(0);
30178 		mutex_exit(&arpce->nce_lock);
30179 		return (LLHDR_RESLV_FAILED);
30180 	}
30181 }
30182 
30183 #undef	UPDATE_IP_MIB_OB_COUNTERS
30184 
30185 /*
30186  * Return B_TRUE if the buffers differ in length or content.
30187  * This is used for comparing extension header buffers.
30188  * Note that an extension header would be declared different
30189  * even if all that changed was the next header value in that header i.e.
30190  * what really changed is the next extension header.
30191  */
30192 boolean_t
30193 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30194     uint_t blen)
30195 {
30196 	if (!b_valid)
30197 		blen = 0;
30198 
30199 	if (alen != blen)
30200 		return (B_TRUE);
30201 	if (alen == 0)
30202 		return (B_FALSE);	/* Both zero length */
30203 	return (bcmp(abuf, bbuf, alen));
30204 }
30205 
30206 /*
30207  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30208  * Return B_FALSE if memory allocation fails - don't change any state!
30209  */
30210 boolean_t
30211 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30212     const void *src, uint_t srclen)
30213 {
30214 	void *dst;
30215 
30216 	if (!src_valid)
30217 		srclen = 0;
30218 
30219 	ASSERT(*dstlenp == 0);
30220 	if (src != NULL && srclen != 0) {
30221 		dst = mi_alloc(srclen, BPRI_MED);
30222 		if (dst == NULL)
30223 			return (B_FALSE);
30224 	} else {
30225 		dst = NULL;
30226 	}
30227 	if (*dstp != NULL)
30228 		mi_free(*dstp);
30229 	*dstp = dst;
30230 	*dstlenp = dst == NULL ? 0 : srclen;
30231 	return (B_TRUE);
30232 }
30233 
30234 /*
30235  * Replace what is in *dst, *dstlen with the source.
30236  * Assumes ip_allocbuf has already been called.
30237  */
30238 void
30239 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30240     const void *src, uint_t srclen)
30241 {
30242 	if (!src_valid)
30243 		srclen = 0;
30244 
30245 	ASSERT(*dstlenp == srclen);
30246 	if (src != NULL && srclen != 0)
30247 		bcopy(src, *dstp, srclen);
30248 }
30249 
30250 /*
30251  * Free the storage pointed to by the members of an ip6_pkt_t.
30252  */
30253 void
30254 ip6_pkt_free(ip6_pkt_t *ipp)
30255 {
30256 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30257 
30258 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30259 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30260 		ipp->ipp_hopopts = NULL;
30261 		ipp->ipp_hopoptslen = 0;
30262 	}
30263 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30264 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30265 		ipp->ipp_rtdstopts = NULL;
30266 		ipp->ipp_rtdstoptslen = 0;
30267 	}
30268 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30269 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30270 		ipp->ipp_dstopts = NULL;
30271 		ipp->ipp_dstoptslen = 0;
30272 	}
30273 	if (ipp->ipp_fields & IPPF_RTHDR) {
30274 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30275 		ipp->ipp_rthdr = NULL;
30276 		ipp->ipp_rthdrlen = 0;
30277 	}
30278 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30279 	    IPPF_RTHDR);
30280 }
30281