xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision d39fefdf3aeec16d43d13967fd24e698a60d8e94)
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 				(void) qwriter_ip(NULL, ill, q, mp,
4061 				    ip_arp_excl, CUR_OP, 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 					(void) qwriter_ip(NULL, ill, q, mp,
4074 					    ip_arp_defend, CUR_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 				(void) qwriter_ip(NULL, ill, q, mp,
4147 				    ip_arp_excl, CUR_OP, 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 		(void) qwriter_ip(NULL, ill, q, mp, ip_arp_excl, CUR_OP,
4176 		    B_FALSE);
4177 		return;
4178 	}
4179 	freemsg(mp);
4180 }
4181 
4182 /*
4183  * Create a mblk suitable for carrying the interface index and/or source link
4184  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4185  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4186  * application.
4187  */
4188 mblk_t *
4189 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4190     ip_stack_t *ipst)
4191 {
4192 	mblk_t		*mp;
4193 	ip_pktinfo_t	*pinfo;
4194 	ipha_t *ipha;
4195 	struct ether_header *pether;
4196 
4197 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4198 	if (mp == NULL) {
4199 		ip1dbg(("ip_add_info: allocation failure.\n"));
4200 		return (data_mp);
4201 	}
4202 
4203 	ipha	= (ipha_t *)data_mp->b_rptr;
4204 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4205 	bzero(pinfo, sizeof (ip_pktinfo_t));
4206 	pinfo->ip_pkt_flags = (uchar_t)flags;
4207 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4208 
4209 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4210 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4211 	if (flags & IPF_RECVADDR) {
4212 		ipif_t	*ipif;
4213 		ire_t	*ire;
4214 
4215 		/*
4216 		 * Only valid for V4
4217 		 */
4218 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4219 		    (IPV4_VERSION << 4));
4220 
4221 		ipif = ipif_get_next_ipif(NULL, ill);
4222 		if (ipif != NULL) {
4223 			/*
4224 			 * Since a decision has already been made to deliver the
4225 			 * packet, there is no need to test for SECATTR and
4226 			 * ZONEONLY.
4227 			 */
4228 			ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0, ipif,
4229 			    zoneid, NULL, MATCH_IRE_ILL_GROUP, ipst);
4230 			if (ire == NULL) {
4231 				/*
4232 				 * packet must have come on a different
4233 				 * interface.
4234 				 * Since a decision has already been made to
4235 				 * deliver the packet, there is no need to test
4236 				 * for SECATTR and ZONEONLY.
4237 				 */
4238 				ire = ire_ctable_lookup(ipha->ipha_dst, 0, 0,
4239 				    ipif, zoneid, NULL, NULL, ipst);
4240 			}
4241 
4242 			if (ire == NULL) {
4243 				/*
4244 				 * This is either a multicast packet or
4245 				 * the address has been removed since
4246 				 * the packet was received.
4247 				 * Return INADDR_ANY so that normal source
4248 				 * selection occurs for the response.
4249 				 */
4250 
4251 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4252 			} else {
4253 				ASSERT(ire->ire_type != IRE_CACHE);
4254 				pinfo->ip_pkt_match_addr.s_addr =
4255 				    ire->ire_src_addr;
4256 				ire_refrele(ire);
4257 			}
4258 			ipif_refrele(ipif);
4259 		} else {
4260 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4261 		}
4262 	}
4263 
4264 	pether = (struct ether_header *)((char *)ipha
4265 	    - sizeof (struct ether_header));
4266 	/*
4267 	 * Make sure the interface is an ethernet type, since this option
4268 	 * is currently supported only on this type of interface. Also make
4269 	 * sure we are pointing correctly above db_base.
4270 	 */
4271 
4272 	if ((flags & IPF_RECVSLLA) &&
4273 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4274 	    (ill->ill_type == IFT_ETHER) &&
4275 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4276 
4277 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4278 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4279 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4280 	} else {
4281 		/*
4282 		 * Clear the bit. Indicate to upper layer that IP is not
4283 		 * sending this ancillary info.
4284 		 */
4285 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4286 	}
4287 
4288 	mp->b_datap->db_type = M_CTL;
4289 	mp->b_wptr += sizeof (ip_pktinfo_t);
4290 	mp->b_cont = data_mp;
4291 
4292 	return (mp);
4293 }
4294 
4295 /*
4296  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4297  * part of the bind request.
4298  */
4299 
4300 boolean_t
4301 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4302 {
4303 	ipsec_in_t *ii;
4304 
4305 	ASSERT(policy_mp != NULL);
4306 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4307 
4308 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4309 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4310 
4311 	connp->conn_policy = ii->ipsec_in_policy;
4312 	ii->ipsec_in_policy = NULL;
4313 
4314 	if (ii->ipsec_in_action != NULL) {
4315 		if (connp->conn_latch == NULL) {
4316 			connp->conn_latch = iplatch_create();
4317 			if (connp->conn_latch == NULL)
4318 				return (B_FALSE);
4319 		}
4320 		ipsec_latch_inbound(connp->conn_latch, ii);
4321 	}
4322 	return (B_TRUE);
4323 }
4324 
4325 /*
4326  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4327  * and to arrange for power-fanout assist.  The ULP is identified by
4328  * adding a single byte at the end of the original bind message.
4329  * A ULP other than UDP or TCP that wishes to be recognized passes
4330  * down a bind with a zero length address.
4331  *
4332  * The binding works as follows:
4333  * - A zero byte address means just bind to the protocol.
4334  * - A four byte address is treated as a request to validate
4335  *   that the address is a valid local address, appropriate for
4336  *   an application to bind to. This does not affect any fanout
4337  *   information in IP.
4338  * - A sizeof sin_t byte address is used to bind to only the local address
4339  *   and port.
4340  * - A sizeof ipa_conn_t byte address contains complete fanout information
4341  *   consisting of local and remote addresses and ports.  In
4342  *   this case, the addresses are both validated as appropriate
4343  *   for this operation, and, if so, the information is retained
4344  *   for use in the inbound fanout.
4345  *
4346  * The ULP (except in the zero-length bind) can append an
4347  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4348  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4349  * a copy of the source or destination IRE (source for local bind;
4350  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4351  * policy information contained should be copied on to the conn.
4352  *
4353  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4354  */
4355 mblk_t *
4356 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4357 {
4358 	ssize_t		len;
4359 	struct T_bind_req	*tbr;
4360 	sin_t		*sin;
4361 	ipa_conn_t	*ac;
4362 	uchar_t		*ucp;
4363 	mblk_t		*mp1;
4364 	boolean_t	ire_requested;
4365 	boolean_t	ipsec_policy_set = B_FALSE;
4366 	int		error = 0;
4367 	int		protocol;
4368 	ipa_conn_x_t	*acx;
4369 
4370 	ASSERT(!connp->conn_af_isv6);
4371 	connp->conn_pkt_isv6 = B_FALSE;
4372 
4373 	len = MBLKL(mp);
4374 	if (len < (sizeof (*tbr) + 1)) {
4375 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4376 		    "ip_bind: bogus msg, len %ld", len);
4377 		/* XXX: Need to return something better */
4378 		goto bad_addr;
4379 	}
4380 	/* Back up and extract the protocol identifier. */
4381 	mp->b_wptr--;
4382 	protocol = *mp->b_wptr & 0xFF;
4383 	tbr = (struct T_bind_req *)mp->b_rptr;
4384 	/* Reset the message type in preparation for shipping it back. */
4385 	DB_TYPE(mp) = M_PCPROTO;
4386 
4387 	connp->conn_ulp = (uint8_t)protocol;
4388 
4389 	/*
4390 	 * Check for a zero length address.  This is from a protocol that
4391 	 * wants to register to receive all packets of its type.
4392 	 */
4393 	if (tbr->ADDR_length == 0) {
4394 		/*
4395 		 * These protocols are now intercepted in ip_bind_v6().
4396 		 * Reject protocol-level binds here for now.
4397 		 *
4398 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4399 		 * so that the protocol type cannot be SCTP.
4400 		 */
4401 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4402 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4403 			goto bad_addr;
4404 		}
4405 
4406 		/*
4407 		 *
4408 		 * The udp module never sends down a zero-length address,
4409 		 * and allowing this on a labeled system will break MLP
4410 		 * functionality.
4411 		 */
4412 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4413 			goto bad_addr;
4414 
4415 		if (connp->conn_mac_exempt)
4416 			goto bad_addr;
4417 
4418 		/* No hash here really.  The table is big enough. */
4419 		connp->conn_srcv6 = ipv6_all_zeros;
4420 
4421 		ipcl_proto_insert(connp, protocol);
4422 
4423 		tbr->PRIM_type = T_BIND_ACK;
4424 		return (mp);
4425 	}
4426 
4427 	/* Extract the address pointer from the message. */
4428 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4429 	    tbr->ADDR_length);
4430 	if (ucp == NULL) {
4431 		ip1dbg(("ip_bind: no address\n"));
4432 		goto bad_addr;
4433 	}
4434 	if (!OK_32PTR(ucp)) {
4435 		ip1dbg(("ip_bind: unaligned address\n"));
4436 		goto bad_addr;
4437 	}
4438 	/*
4439 	 * Check for trailing mps.
4440 	 */
4441 
4442 	mp1 = mp->b_cont;
4443 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4444 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4445 
4446 	switch (tbr->ADDR_length) {
4447 	default:
4448 		ip1dbg(("ip_bind: bad address length %d\n",
4449 		    (int)tbr->ADDR_length));
4450 		goto bad_addr;
4451 
4452 	case IP_ADDR_LEN:
4453 		/* Verification of local address only */
4454 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4455 		    ire_requested, ipsec_policy_set, B_FALSE);
4456 		break;
4457 
4458 	case sizeof (sin_t):
4459 		sin = (sin_t *)ucp;
4460 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4461 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4462 		break;
4463 
4464 	case sizeof (ipa_conn_t):
4465 		ac = (ipa_conn_t *)ucp;
4466 		/* For raw socket, the local port is not set. */
4467 		if (ac->ac_lport == 0)
4468 			ac->ac_lport = connp->conn_lport;
4469 		/* Always verify destination reachability. */
4470 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4471 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4472 		    ipsec_policy_set, B_TRUE, B_TRUE);
4473 		break;
4474 
4475 	case sizeof (ipa_conn_x_t):
4476 		acx = (ipa_conn_x_t *)ucp;
4477 		/*
4478 		 * Whether or not to verify destination reachability depends
4479 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4480 		 */
4481 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4482 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4483 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4484 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4485 		break;
4486 	}
4487 	if (error == EINPROGRESS)
4488 		return (NULL);
4489 	else if (error != 0)
4490 		goto bad_addr;
4491 	/*
4492 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4493 	 * We can't do this in ip_bind_insert_ire because the policy
4494 	 * may not have been inherited at that point in time and hence
4495 	 * conn_out_enforce_policy may not be set.
4496 	 */
4497 	mp1 = mp->b_cont;
4498 	if (ire_requested && connp->conn_out_enforce_policy &&
4499 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4500 		ire_t *ire = (ire_t *)mp1->b_rptr;
4501 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4502 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4503 	}
4504 
4505 	/* Send it home. */
4506 	mp->b_datap->db_type = M_PCPROTO;
4507 	tbr->PRIM_type = T_BIND_ACK;
4508 	return (mp);
4509 
4510 bad_addr:
4511 	/*
4512 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4513 	 * a unix errno.
4514 	 */
4515 	if (error > 0)
4516 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4517 	else
4518 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4519 	return (mp);
4520 }
4521 
4522 /*
4523  * Here address is verified to be a valid local address.
4524  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4525  * address is also considered a valid local address.
4526  * In the case of a broadcast/multicast address, however, the
4527  * upper protocol is expected to reset the src address
4528  * to 0 if it sees a IRE_BROADCAST type returned so that
4529  * no packets are emitted with broadcast/multicast address as
4530  * source address (that violates hosts requirements RFC1122)
4531  * The addresses valid for bind are:
4532  *	(1) - INADDR_ANY (0)
4533  *	(2) - IP address of an UP interface
4534  *	(3) - IP address of a DOWN interface
4535  *	(4) - valid local IP broadcast addresses. In this case
4536  *	the conn will only receive packets destined to
4537  *	the specified broadcast address.
4538  *	(5) - a multicast address. In this case
4539  *	the conn will only receive packets destined to
4540  *	the specified multicast address. Note: the
4541  *	application still has to issue an
4542  *	IP_ADD_MEMBERSHIP socket option.
4543  *
4544  * On error, return -1 for TBADADDR otherwise pass the
4545  * errno with TSYSERR reply.
4546  *
4547  * In all the above cases, the bound address must be valid in the current zone.
4548  * When the address is loopback, multicast or broadcast, there might be many
4549  * matching IREs so bind has to look up based on the zone.
4550  *
4551  * Note: lport is in network byte order.
4552  */
4553 int
4554 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4555     boolean_t ire_requested, boolean_t ipsec_policy_set,
4556     boolean_t fanout_insert)
4557 {
4558 	int		error = 0;
4559 	ire_t		*src_ire;
4560 	mblk_t		*policy_mp;
4561 	ipif_t		*ipif;
4562 	zoneid_t	zoneid;
4563 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4564 
4565 	if (ipsec_policy_set) {
4566 		policy_mp = mp->b_cont;
4567 	}
4568 
4569 	/*
4570 	 * If it was previously connected, conn_fully_bound would have
4571 	 * been set.
4572 	 */
4573 	connp->conn_fully_bound = B_FALSE;
4574 
4575 	src_ire = NULL;
4576 	ipif = NULL;
4577 
4578 	zoneid = IPCL_ZONEID(connp);
4579 
4580 	if (src_addr) {
4581 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4582 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4583 		/*
4584 		 * If an address other than 0.0.0.0 is requested,
4585 		 * we verify that it is a valid address for bind
4586 		 * Note: Following code is in if-else-if form for
4587 		 * readability compared to a condition check.
4588 		 */
4589 		/* LINTED - statement has no consequent */
4590 		if (IRE_IS_LOCAL(src_ire)) {
4591 			/*
4592 			 * (2) Bind to address of local UP interface
4593 			 */
4594 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4595 			/*
4596 			 * (4) Bind to broadcast address
4597 			 * Note: permitted only from transports that
4598 			 * request IRE
4599 			 */
4600 			if (!ire_requested)
4601 				error = EADDRNOTAVAIL;
4602 		} else {
4603 			/*
4604 			 * (3) Bind to address of local DOWN interface
4605 			 * (ipif_lookup_addr() looks up all interfaces
4606 			 * but we do not get here for UP interfaces
4607 			 * - case (2) above)
4608 			 * We put the protocol byte back into the mblk
4609 			 * since we may come back via ip_wput_nondata()
4610 			 * later with this mblk if ipif_lookup_addr chooses
4611 			 * to defer processing.
4612 			 */
4613 			*mp->b_wptr++ = (char)connp->conn_ulp;
4614 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4615 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4616 			    &error, ipst)) != NULL) {
4617 				ipif_refrele(ipif);
4618 			} else if (error == EINPROGRESS) {
4619 				if (src_ire != NULL)
4620 					ire_refrele(src_ire);
4621 				return (EINPROGRESS);
4622 			} else if (CLASSD(src_addr)) {
4623 				error = 0;
4624 				if (src_ire != NULL)
4625 					ire_refrele(src_ire);
4626 				/*
4627 				 * (5) bind to multicast address.
4628 				 * Fake out the IRE returned to upper
4629 				 * layer to be a broadcast IRE.
4630 				 */
4631 				src_ire = ire_ctable_lookup(
4632 				    INADDR_BROADCAST, INADDR_ANY,
4633 				    IRE_BROADCAST, NULL, zoneid, NULL,
4634 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4635 				    ipst);
4636 				if (src_ire == NULL || !ire_requested)
4637 					error = EADDRNOTAVAIL;
4638 			} else {
4639 				/*
4640 				 * Not a valid address for bind
4641 				 */
4642 				error = EADDRNOTAVAIL;
4643 			}
4644 			/*
4645 			 * Just to keep it consistent with the processing in
4646 			 * ip_bind_v4()
4647 			 */
4648 			mp->b_wptr--;
4649 		}
4650 		if (error) {
4651 			/* Red Alert!  Attempting to be a bogon! */
4652 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4653 			    ntohl(src_addr)));
4654 			goto bad_addr;
4655 		}
4656 	}
4657 
4658 	/*
4659 	 * Allow setting new policies. For example, disconnects come
4660 	 * down as ipa_t bind. As we would have set conn_policy_cached
4661 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4662 	 * can change after the disconnect.
4663 	 */
4664 	connp->conn_policy_cached = B_FALSE;
4665 
4666 	/*
4667 	 * If not fanout_insert this was just an address verification
4668 	 */
4669 	if (fanout_insert) {
4670 		/*
4671 		 * The addresses have been verified. Time to insert in
4672 		 * the correct fanout list.
4673 		 */
4674 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4675 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4676 		connp->conn_lport = lport;
4677 		connp->conn_fport = 0;
4678 		/*
4679 		 * Do we need to add a check to reject Multicast packets
4680 		 *
4681 		 * We need to make sure that the conn_recv is set to a non-null
4682 		 * value before we insert the conn into the classifier table.
4683 		 * This is to avoid a race with an incoming packet which does an
4684 		 * ipcl_classify().
4685 		 */
4686 		if (*mp->b_wptr == IPPROTO_TCP)
4687 			connp->conn_recv = tcp_conn_request;
4688 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4689 	}
4690 
4691 	if (error == 0) {
4692 		if (ire_requested) {
4693 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4694 				error = -1;
4695 				/* Falls through to bad_addr */
4696 			}
4697 		} else if (ipsec_policy_set) {
4698 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4699 				error = -1;
4700 				/* Falls through to bad_addr */
4701 			}
4702 		}
4703 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4704 		connp->conn_recv = tcp_input;
4705 	}
4706 bad_addr:
4707 	if (error != 0) {
4708 		if (connp->conn_anon_port) {
4709 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4710 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4711 			    B_FALSE);
4712 		}
4713 		connp->conn_mlp_type = mlptSingle;
4714 	}
4715 	if (src_ire != NULL)
4716 		IRE_REFRELE(src_ire);
4717 	if (ipsec_policy_set) {
4718 		ASSERT(policy_mp == mp->b_cont);
4719 		ASSERT(policy_mp != NULL);
4720 		freeb(policy_mp);
4721 		/*
4722 		 * As of now assume that nothing else accompanies
4723 		 * IPSEC_POLICY_SET.
4724 		 */
4725 		mp->b_cont = NULL;
4726 	}
4727 	return (error);
4728 }
4729 
4730 /*
4731  * Verify that both the source and destination addresses
4732  * are valid.  If verify_dst is false, then the destination address may be
4733  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4734  * destination reachability, while tunnels do not.
4735  * Note that we allow connect to broadcast and multicast
4736  * addresses when ire_requested is set. Thus the ULP
4737  * has to check for IRE_BROADCAST and multicast.
4738  *
4739  * Returns zero if ok.
4740  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4741  * (for use with TSYSERR reply).
4742  *
4743  * Note: lport and fport are in network byte order.
4744  */
4745 int
4746 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4747     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4748     boolean_t ire_requested, boolean_t ipsec_policy_set,
4749     boolean_t fanout_insert, boolean_t verify_dst)
4750 {
4751 	ire_t		*src_ire;
4752 	ire_t		*dst_ire;
4753 	int		error = 0;
4754 	int 		protocol;
4755 	mblk_t		*policy_mp;
4756 	ire_t		*sire = NULL;
4757 	ire_t		*md_dst_ire = NULL;
4758 	ire_t		*lso_dst_ire = NULL;
4759 	ill_t		*ill = NULL;
4760 	zoneid_t	zoneid;
4761 	ipaddr_t	src_addr = *src_addrp;
4762 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4763 
4764 	src_ire = dst_ire = NULL;
4765 	protocol = *mp->b_wptr & 0xFF;
4766 
4767 	/*
4768 	 * If we never got a disconnect before, clear it now.
4769 	 */
4770 	connp->conn_fully_bound = B_FALSE;
4771 
4772 	if (ipsec_policy_set) {
4773 		policy_mp = mp->b_cont;
4774 	}
4775 
4776 	zoneid = IPCL_ZONEID(connp);
4777 
4778 	if (CLASSD(dst_addr)) {
4779 		/* Pick up an IRE_BROADCAST */
4780 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4781 		    NULL, zoneid, MBLK_GETLABEL(mp),
4782 		    (MATCH_IRE_RECURSIVE |
4783 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4784 		    MATCH_IRE_SECATTR), ipst);
4785 	} else {
4786 		/*
4787 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4788 		 * and onlink ipif is not found set ENETUNREACH error.
4789 		 */
4790 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4791 			ipif_t *ipif;
4792 
4793 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4794 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4795 			if (ipif == NULL) {
4796 				error = ENETUNREACH;
4797 				goto bad_addr;
4798 			}
4799 			ipif_refrele(ipif);
4800 		}
4801 
4802 		if (connp->conn_nexthop_set) {
4803 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4804 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4805 			    MATCH_IRE_SECATTR, ipst);
4806 		} else {
4807 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4808 			    &sire, zoneid, MBLK_GETLABEL(mp),
4809 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4810 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4811 			    MATCH_IRE_SECATTR), ipst);
4812 		}
4813 	}
4814 	/*
4815 	 * dst_ire can't be a broadcast when not ire_requested.
4816 	 * We also prevent ire's with src address INADDR_ANY to
4817 	 * be used, which are created temporarily for
4818 	 * sending out packets from endpoints that have
4819 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4820 	 * reachable.  If verify_dst is false, the destination needn't be
4821 	 * reachable.
4822 	 *
4823 	 * If we match on a reject or black hole, then we've got a
4824 	 * local failure.  May as well fail out the connect() attempt,
4825 	 * since it's never going to succeed.
4826 	 */
4827 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4828 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4829 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4830 		/*
4831 		 * If we're verifying destination reachability, we always want
4832 		 * to complain here.
4833 		 *
4834 		 * If we're not verifying destination reachability but the
4835 		 * destination has a route, we still want to fail on the
4836 		 * temporary address and broadcast address tests.
4837 		 */
4838 		if (verify_dst || (dst_ire != NULL)) {
4839 			if (ip_debug > 2) {
4840 				pr_addr_dbg("ip_bind_connected: bad connected "
4841 				    "dst %s\n", AF_INET, &dst_addr);
4842 			}
4843 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4844 				error = ENETUNREACH;
4845 			else
4846 				error = EHOSTUNREACH;
4847 			goto bad_addr;
4848 		}
4849 	}
4850 
4851 	/*
4852 	 * We now know that routing will allow us to reach the destination.
4853 	 * Check whether Trusted Solaris policy allows communication with this
4854 	 * host, and pretend that the destination is unreachable if not.
4855 	 *
4856 	 * This is never a problem for TCP, since that transport is known to
4857 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4858 	 * handling.  If the remote is unreachable, it will be detected at that
4859 	 * point, so there's no reason to check it here.
4860 	 *
4861 	 * Note that for sendto (and other datagram-oriented friends), this
4862 	 * check is done as part of the data path label computation instead.
4863 	 * The check here is just to make non-TCP connect() report the right
4864 	 * error.
4865 	 */
4866 	if (dst_ire != NULL && is_system_labeled() &&
4867 	    !IPCL_IS_TCP(connp) &&
4868 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4869 	    connp->conn_mac_exempt, ipst) != 0) {
4870 		error = EHOSTUNREACH;
4871 		if (ip_debug > 2) {
4872 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4873 			    AF_INET, &dst_addr);
4874 		}
4875 		goto bad_addr;
4876 	}
4877 
4878 	/*
4879 	 * If the app does a connect(), it means that it will most likely
4880 	 * send more than 1 packet to the destination.  It makes sense
4881 	 * to clear the temporary flag.
4882 	 */
4883 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4884 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4885 		irb_t *irb = dst_ire->ire_bucket;
4886 
4887 		rw_enter(&irb->irb_lock, RW_WRITER);
4888 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4889 		irb->irb_tmp_ire_cnt--;
4890 		rw_exit(&irb->irb_lock);
4891 	}
4892 
4893 	/*
4894 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4895 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4896 	 * eligibility tests for passive connects are handled separately
4897 	 * through tcp_adapt_ire().  We do this before the source address
4898 	 * selection, because dst_ire may change after a call to
4899 	 * ipif_select_source().  This is a best-effort check, as the
4900 	 * packet for this connection may not actually go through
4901 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4902 	 * calling ip_newroute().  This is why we further check on the
4903 	 * IRE during LSO/Multidata packet transmission in
4904 	 * tcp_lsosend()/tcp_multisend().
4905 	 */
4906 	if (!ipsec_policy_set && dst_ire != NULL &&
4907 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4908 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4909 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4910 			lso_dst_ire = dst_ire;
4911 			IRE_REFHOLD(lso_dst_ire);
4912 		} else if (ipst->ips_ip_multidata_outbound &&
4913 		    ILL_MDT_CAPABLE(ill)) {
4914 			md_dst_ire = dst_ire;
4915 			IRE_REFHOLD(md_dst_ire);
4916 		}
4917 	}
4918 
4919 	if (dst_ire != NULL &&
4920 	    dst_ire->ire_type == IRE_LOCAL &&
4921 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4922 		/*
4923 		 * If the IRE belongs to a different zone, look for a matching
4924 		 * route in the forwarding table and use the source address from
4925 		 * that route.
4926 		 */
4927 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4928 		    zoneid, 0, NULL,
4929 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4930 		    MATCH_IRE_RJ_BHOLE, ipst);
4931 		if (src_ire == NULL) {
4932 			error = EHOSTUNREACH;
4933 			goto bad_addr;
4934 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4935 			if (!(src_ire->ire_type & IRE_HOST))
4936 				error = ENETUNREACH;
4937 			else
4938 				error = EHOSTUNREACH;
4939 			goto bad_addr;
4940 		}
4941 		if (src_addr == INADDR_ANY)
4942 			src_addr = src_ire->ire_src_addr;
4943 		ire_refrele(src_ire);
4944 		src_ire = NULL;
4945 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4946 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4947 			src_addr = sire->ire_src_addr;
4948 			ire_refrele(dst_ire);
4949 			dst_ire = sire;
4950 			sire = NULL;
4951 		} else {
4952 			/*
4953 			 * Pick a source address so that a proper inbound
4954 			 * load spreading would happen.
4955 			 */
4956 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4957 			ipif_t *src_ipif = NULL;
4958 			ire_t *ipif_ire;
4959 
4960 			/*
4961 			 * Supply a local source address such that inbound
4962 			 * load spreading happens.
4963 			 *
4964 			 * Determine the best source address on this ill for
4965 			 * the destination.
4966 			 *
4967 			 * 1) For broadcast, we should return a broadcast ire
4968 			 *    found above so that upper layers know that the
4969 			 *    destination address is a broadcast address.
4970 			 *
4971 			 * 2) If this is part of a group, select a better
4972 			 *    source address so that better inbound load
4973 			 *    balancing happens. Do the same if the ipif
4974 			 *    is DEPRECATED.
4975 			 *
4976 			 * 3) If the outgoing interface is part of a usesrc
4977 			 *    group, then try selecting a source address from
4978 			 *    the usesrc ILL.
4979 			 */
4980 			if ((dst_ire->ire_zoneid != zoneid &&
4981 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4982 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4983 			    ((dst_ill->ill_group != NULL) ||
4984 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4985 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4986 				/*
4987 				 * If the destination is reachable via a
4988 				 * given gateway, the selected source address
4989 				 * should be in the same subnet as the gateway.
4990 				 * Otherwise, the destination is not reachable.
4991 				 *
4992 				 * If there are no interfaces on the same subnet
4993 				 * as the destination, ipif_select_source gives
4994 				 * first non-deprecated interface which might be
4995 				 * on a different subnet than the gateway.
4996 				 * This is not desirable. Hence pass the dst_ire
4997 				 * source address to ipif_select_source.
4998 				 * It is sure that the destination is reachable
4999 				 * with the dst_ire source address subnet.
5000 				 * So passing dst_ire source address to
5001 				 * ipif_select_source will make sure that the
5002 				 * selected source will be on the same subnet
5003 				 * as dst_ire source address.
5004 				 */
5005 				ipaddr_t saddr =
5006 				    dst_ire->ire_ipif->ipif_src_addr;
5007 				src_ipif = ipif_select_source(dst_ill,
5008 				    saddr, zoneid);
5009 				if (src_ipif != NULL) {
5010 					if (IS_VNI(src_ipif->ipif_ill)) {
5011 						/*
5012 						 * For VNI there is no
5013 						 * interface route
5014 						 */
5015 						src_addr =
5016 						    src_ipif->ipif_src_addr;
5017 					} else {
5018 						ipif_ire =
5019 						    ipif_to_ire(src_ipif);
5020 						if (ipif_ire != NULL) {
5021 							IRE_REFRELE(dst_ire);
5022 							dst_ire = ipif_ire;
5023 						}
5024 						src_addr =
5025 						    dst_ire->ire_src_addr;
5026 					}
5027 					ipif_refrele(src_ipif);
5028 				} else {
5029 					src_addr = dst_ire->ire_src_addr;
5030 				}
5031 			} else {
5032 				src_addr = dst_ire->ire_src_addr;
5033 			}
5034 		}
5035 	}
5036 
5037 	/*
5038 	 * We do ire_route_lookup() here (and not
5039 	 * interface lookup as we assert that
5040 	 * src_addr should only come from an
5041 	 * UP interface for hard binding.
5042 	 */
5043 	ASSERT(src_ire == NULL);
5044 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5045 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5046 	/* src_ire must be a local|loopback */
5047 	if (!IRE_IS_LOCAL(src_ire)) {
5048 		if (ip_debug > 2) {
5049 			pr_addr_dbg("ip_bind_connected: bad connected "
5050 			    "src %s\n", AF_INET, &src_addr);
5051 		}
5052 		error = EADDRNOTAVAIL;
5053 		goto bad_addr;
5054 	}
5055 
5056 	/*
5057 	 * If the source address is a loopback address, the
5058 	 * destination had best be local or multicast.
5059 	 * The transports that can't handle multicast will reject
5060 	 * those addresses.
5061 	 */
5062 	if (src_ire->ire_type == IRE_LOOPBACK &&
5063 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5064 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5065 		error = -1;
5066 		goto bad_addr;
5067 	}
5068 
5069 	/*
5070 	 * Allow setting new policies. For example, disconnects come
5071 	 * down as ipa_t bind. As we would have set conn_policy_cached
5072 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5073 	 * can change after the disconnect.
5074 	 */
5075 	connp->conn_policy_cached = B_FALSE;
5076 
5077 	/*
5078 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5079 	 * can handle their passed-in conn's.
5080 	 */
5081 
5082 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5083 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5084 	connp->conn_lport = lport;
5085 	connp->conn_fport = fport;
5086 	*src_addrp = src_addr;
5087 
5088 	ASSERT(!(ipsec_policy_set && ire_requested));
5089 	if (ire_requested) {
5090 		iulp_t *ulp_info = NULL;
5091 
5092 		/*
5093 		 * Note that sire will not be NULL if this is an off-link
5094 		 * connection and there is not cache for that dest yet.
5095 		 *
5096 		 * XXX Because of an existing bug, if there are multiple
5097 		 * default routes, the IRE returned now may not be the actual
5098 		 * default route used (default routes are chosen in a
5099 		 * round robin fashion).  So if the metrics for different
5100 		 * default routes are different, we may return the wrong
5101 		 * metrics.  This will not be a problem if the existing
5102 		 * bug is fixed.
5103 		 */
5104 		if (sire != NULL) {
5105 			ulp_info = &(sire->ire_uinfo);
5106 		}
5107 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5108 			error = -1;
5109 			goto bad_addr;
5110 		}
5111 	} else if (ipsec_policy_set) {
5112 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5113 			error = -1;
5114 			goto bad_addr;
5115 		}
5116 	}
5117 
5118 	/*
5119 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5120 	 * we'll cache that.  If we don't, we'll inherit global policy.
5121 	 *
5122 	 * We can't insert until the conn reflects the policy. Note that
5123 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5124 	 * connections where we don't have a policy. This is to prevent
5125 	 * global policy lookups in the inbound path.
5126 	 *
5127 	 * If we insert before we set conn_policy_cached,
5128 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5129 	 * because global policy cound be non-empty. We normally call
5130 	 * ipsec_check_policy() for conn_policy_cached connections only if
5131 	 * ipc_in_enforce_policy is set. But in this case,
5132 	 * conn_policy_cached can get set anytime since we made the
5133 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5134 	 * called, which will make the above assumption false.  Thus, we
5135 	 * need to insert after we set conn_policy_cached.
5136 	 */
5137 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5138 		goto bad_addr;
5139 
5140 	if (fanout_insert) {
5141 		/*
5142 		 * The addresses have been verified. Time to insert in
5143 		 * the correct fanout list.
5144 		 * We need to make sure that the conn_recv is set to a non-null
5145 		 * value before we insert into the classifier table to avoid a
5146 		 * race with an incoming packet which does an ipcl_classify().
5147 		 */
5148 		if (protocol == IPPROTO_TCP)
5149 			connp->conn_recv = tcp_input;
5150 		error = ipcl_conn_insert(connp, protocol, src_addr,
5151 		    dst_addr, connp->conn_ports);
5152 	}
5153 
5154 	if (error == 0) {
5155 		connp->conn_fully_bound = B_TRUE;
5156 		/*
5157 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5158 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5159 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5160 		 * ip_xxinfo_return(), which performs further checks
5161 		 * against them and upon success, returns the LSO/MDT info
5162 		 * mblk which we will attach to the bind acknowledgment.
5163 		 */
5164 		if (lso_dst_ire != NULL) {
5165 			mblk_t *lsoinfo_mp;
5166 
5167 			ASSERT(ill->ill_lso_capab != NULL);
5168 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5169 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5170 				linkb(mp, lsoinfo_mp);
5171 		} else if (md_dst_ire != NULL) {
5172 			mblk_t *mdinfo_mp;
5173 
5174 			ASSERT(ill->ill_mdt_capab != NULL);
5175 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5176 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5177 				linkb(mp, mdinfo_mp);
5178 		}
5179 	}
5180 bad_addr:
5181 	if (ipsec_policy_set) {
5182 		ASSERT(policy_mp == mp->b_cont);
5183 		ASSERT(policy_mp != NULL);
5184 		freeb(policy_mp);
5185 		/*
5186 		 * As of now assume that nothing else accompanies
5187 		 * IPSEC_POLICY_SET.
5188 		 */
5189 		mp->b_cont = NULL;
5190 	}
5191 	if (src_ire != NULL)
5192 		IRE_REFRELE(src_ire);
5193 	if (dst_ire != NULL)
5194 		IRE_REFRELE(dst_ire);
5195 	if (sire != NULL)
5196 		IRE_REFRELE(sire);
5197 	if (md_dst_ire != NULL)
5198 		IRE_REFRELE(md_dst_ire);
5199 	if (lso_dst_ire != NULL)
5200 		IRE_REFRELE(lso_dst_ire);
5201 	return (error);
5202 }
5203 
5204 /*
5205  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5206  * Prefers dst_ire over src_ire.
5207  */
5208 static boolean_t
5209 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5210 {
5211 	mblk_t	*mp1;
5212 	ire_t *ret_ire = NULL;
5213 
5214 	mp1 = mp->b_cont;
5215 	ASSERT(mp1 != NULL);
5216 
5217 	if (ire != NULL) {
5218 		/*
5219 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5220 		 * appended mblk. Its <upper protocol>'s
5221 		 * job to make sure there is room.
5222 		 */
5223 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5224 			return (0);
5225 
5226 		mp1->b_datap->db_type = IRE_DB_TYPE;
5227 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5228 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5229 		ret_ire = (ire_t *)mp1->b_rptr;
5230 		/*
5231 		 * Pass the latest setting of the ip_path_mtu_discovery and
5232 		 * copy the ulp info if any.
5233 		 */
5234 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5235 		    IPH_DF : 0;
5236 		if (ulp_info != NULL) {
5237 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5238 			    sizeof (iulp_t));
5239 		}
5240 		ret_ire->ire_mp = mp1;
5241 	} else {
5242 		/*
5243 		 * No IRE was found. Remove IRE mblk.
5244 		 */
5245 		mp->b_cont = mp1->b_cont;
5246 		freeb(mp1);
5247 	}
5248 
5249 	return (1);
5250 }
5251 
5252 /*
5253  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5254  * the final piece where we don't.  Return a pointer to the first mblk in the
5255  * result, and update the pointer to the next mblk to chew on.  If anything
5256  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5257  * NULL pointer.
5258  */
5259 mblk_t *
5260 ip_carve_mp(mblk_t **mpp, ssize_t len)
5261 {
5262 	mblk_t	*mp0;
5263 	mblk_t	*mp1;
5264 	mblk_t	*mp2;
5265 
5266 	if (!len || !mpp || !(mp0 = *mpp))
5267 		return (NULL);
5268 	/* If we aren't going to consume the first mblk, we need a dup. */
5269 	if (mp0->b_wptr - mp0->b_rptr > len) {
5270 		mp1 = dupb(mp0);
5271 		if (mp1) {
5272 			/* Partition the data between the two mblks. */
5273 			mp1->b_wptr = mp1->b_rptr + len;
5274 			mp0->b_rptr = mp1->b_wptr;
5275 			/*
5276 			 * after adjustments if mblk not consumed is now
5277 			 * unaligned, try to align it. If this fails free
5278 			 * all messages and let upper layer recover.
5279 			 */
5280 			if (!OK_32PTR(mp0->b_rptr)) {
5281 				if (!pullupmsg(mp0, -1)) {
5282 					freemsg(mp0);
5283 					freemsg(mp1);
5284 					*mpp = NULL;
5285 					return (NULL);
5286 				}
5287 			}
5288 		}
5289 		return (mp1);
5290 	}
5291 	/* Eat through as many mblks as we need to get len bytes. */
5292 	len -= mp0->b_wptr - mp0->b_rptr;
5293 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5294 		if (mp2->b_wptr - mp2->b_rptr > len) {
5295 			/*
5296 			 * We won't consume the entire last mblk.  Like
5297 			 * above, dup and partition it.
5298 			 */
5299 			mp1->b_cont = dupb(mp2);
5300 			mp1 = mp1->b_cont;
5301 			if (!mp1) {
5302 				/*
5303 				 * Trouble.  Rather than go to a lot of
5304 				 * trouble to clean up, we free the messages.
5305 				 * This won't be any worse than losing it on
5306 				 * the wire.
5307 				 */
5308 				freemsg(mp0);
5309 				freemsg(mp2);
5310 				*mpp = NULL;
5311 				return (NULL);
5312 			}
5313 			mp1->b_wptr = mp1->b_rptr + len;
5314 			mp2->b_rptr = mp1->b_wptr;
5315 			/*
5316 			 * after adjustments if mblk not consumed is now
5317 			 * unaligned, try to align it. If this fails free
5318 			 * all messages and let upper layer recover.
5319 			 */
5320 			if (!OK_32PTR(mp2->b_rptr)) {
5321 				if (!pullupmsg(mp2, -1)) {
5322 					freemsg(mp0);
5323 					freemsg(mp2);
5324 					*mpp = NULL;
5325 					return (NULL);
5326 				}
5327 			}
5328 			*mpp = mp2;
5329 			return (mp0);
5330 		}
5331 		/* Decrement len by the amount we just got. */
5332 		len -= mp2->b_wptr - mp2->b_rptr;
5333 	}
5334 	/*
5335 	 * len should be reduced to zero now.  If not our caller has
5336 	 * screwed up.
5337 	 */
5338 	if (len) {
5339 		/* Shouldn't happen! */
5340 		freemsg(mp0);
5341 		*mpp = NULL;
5342 		return (NULL);
5343 	}
5344 	/*
5345 	 * We consumed up to exactly the end of an mblk.  Detach the part
5346 	 * we are returning from the rest of the chain.
5347 	 */
5348 	mp1->b_cont = NULL;
5349 	*mpp = mp2;
5350 	return (mp0);
5351 }
5352 
5353 /* The ill stream is being unplumbed. Called from ip_close */
5354 int
5355 ip_modclose(ill_t *ill)
5356 {
5357 
5358 	boolean_t success;
5359 	ipsq_t	*ipsq;
5360 	ipif_t	*ipif;
5361 	queue_t	*q = ill->ill_rq;
5362 	ip_stack_t	*ipst = ill->ill_ipst;
5363 	clock_t timeout;
5364 
5365 	/*
5366 	 * Wait for the ACKs of all deferred control messages to be processed.
5367 	 * In particular, we wait for a potential capability reset initiated
5368 	 * in ip_sioctl_plink() to complete before proceeding.
5369 	 *
5370 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5371 	 * in case the driver never replies.
5372 	 */
5373 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5374 	mutex_enter(&ill->ill_lock);
5375 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5376 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5377 			/* Timeout */
5378 			break;
5379 		}
5380 	}
5381 	mutex_exit(&ill->ill_lock);
5382 
5383 	/*
5384 	 * Forcibly enter the ipsq after some delay. This is to take
5385 	 * care of the case when some ioctl does not complete because
5386 	 * we sent a control message to the driver and it did not
5387 	 * send us a reply. We want to be able to at least unplumb
5388 	 * and replumb rather than force the user to reboot the system.
5389 	 */
5390 	success = ipsq_enter(ill, B_FALSE);
5391 
5392 	/*
5393 	 * Open/close/push/pop is guaranteed to be single threaded
5394 	 * per stream by STREAMS. FS guarantees that all references
5395 	 * from top are gone before close is called. So there can't
5396 	 * be another close thread that has set CONDEMNED on this ill.
5397 	 * and cause ipsq_enter to return failure.
5398 	 */
5399 	ASSERT(success);
5400 	ipsq = ill->ill_phyint->phyint_ipsq;
5401 
5402 	/*
5403 	 * Mark it condemned. No new reference will be made to this ill.
5404 	 * Lookup functions will return an error. Threads that try to
5405 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5406 	 * that the refcnt will drop down to zero.
5407 	 */
5408 	mutex_enter(&ill->ill_lock);
5409 	ill->ill_state_flags |= ILL_CONDEMNED;
5410 	for (ipif = ill->ill_ipif; ipif != NULL;
5411 	    ipif = ipif->ipif_next) {
5412 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5413 	}
5414 	/*
5415 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5416 	 * returns  error if ILL_CONDEMNED is set
5417 	 */
5418 	cv_broadcast(&ill->ill_cv);
5419 	mutex_exit(&ill->ill_lock);
5420 
5421 	/*
5422 	 * Send all the deferred control messages downstream which came in
5423 	 * during the small window right before ipsq_enter(). We do this
5424 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5425 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5426 	 */
5427 	ill_send_all_deferred_mp(ill);
5428 
5429 	/*
5430 	 * Shut down fragmentation reassembly.
5431 	 * ill_frag_timer won't start a timer again.
5432 	 * Now cancel any existing timer
5433 	 */
5434 	(void) untimeout(ill->ill_frag_timer_id);
5435 	(void) ill_frag_timeout(ill, 0);
5436 
5437 	/*
5438 	 * If MOVE was in progress, clear the
5439 	 * move_in_progress fields also.
5440 	 */
5441 	if (ill->ill_move_in_progress) {
5442 		ILL_CLEAR_MOVE(ill);
5443 	}
5444 
5445 	/*
5446 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5447 	 * this ill. Then wait for the refcnts to drop to zero.
5448 	 * ill_is_quiescent checks whether the ill is really quiescent.
5449 	 * Then make sure that threads that are waiting to enter the
5450 	 * ipsq have seen the error returned by ipsq_enter and have
5451 	 * gone away. Then we call ill_delete_tail which does the
5452 	 * DL_UNBIND and DL_DETACH with the driver and then qprocsoff.
5453 	 */
5454 	ill_delete(ill);
5455 	mutex_enter(&ill->ill_lock);
5456 	while (!ill_is_quiescent(ill))
5457 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5458 	while (ill->ill_waiters)
5459 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5460 
5461 	mutex_exit(&ill->ill_lock);
5462 
5463 	/*
5464 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5465 	 * it held until the end of the function since the cleanup
5466 	 * below needs to be able to use the ip_stack_t.
5467 	 */
5468 	netstack_hold(ipst->ips_netstack);
5469 
5470 	/* qprocsoff is called in ill_delete_tail */
5471 	ill_delete_tail(ill);
5472 	ASSERT(ill->ill_ipst == NULL);
5473 
5474 	/*
5475 	 * Walk through all upper (conn) streams and qenable
5476 	 * those that have queued data.
5477 	 * close synchronization needs this to
5478 	 * be done to ensure that all upper layers blocked
5479 	 * due to flow control to the closing device
5480 	 * get unblocked.
5481 	 */
5482 	ip1dbg(("ip_wsrv: walking\n"));
5483 	conn_walk_drain(ipst);
5484 
5485 	mutex_enter(&ipst->ips_ip_mi_lock);
5486 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5487 	mutex_exit(&ipst->ips_ip_mi_lock);
5488 
5489 	/*
5490 	 * credp could be null if the open didn't succeed and ip_modopen
5491 	 * itself calls ip_close.
5492 	 */
5493 	if (ill->ill_credp != NULL)
5494 		crfree(ill->ill_credp);
5495 
5496 	mutex_enter(&ill->ill_lock);
5497 	ill_nic_info_dispatch(ill);
5498 	mutex_exit(&ill->ill_lock);
5499 
5500 	/*
5501 	 * Now we are done with the module close pieces that
5502 	 * need the netstack_t.
5503 	 */
5504 	netstack_rele(ipst->ips_netstack);
5505 
5506 	mi_close_free((IDP)ill);
5507 	q->q_ptr = WR(q)->q_ptr = NULL;
5508 
5509 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5510 
5511 	return (0);
5512 }
5513 
5514 /*
5515  * This is called as part of close() for both IP and UDP
5516  * in order to quiesce the conn.
5517  */
5518 void
5519 ip_quiesce_conn(conn_t *connp)
5520 {
5521 	boolean_t	drain_cleanup_reqd = B_FALSE;
5522 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5523 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5524 	ip_stack_t	*ipst;
5525 
5526 	ASSERT(!IPCL_IS_TCP(connp));
5527 	ipst = connp->conn_netstack->netstack_ip;
5528 
5529 	/*
5530 	 * Mark the conn as closing, and this conn must not be
5531 	 * inserted in future into any list. Eg. conn_drain_insert(),
5532 	 * won't insert this conn into the conn_drain_list.
5533 	 * Similarly ill_pending_mp_add() will not add any mp to
5534 	 * the pending mp list, after this conn has started closing.
5535 	 *
5536 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5537 	 * cannot get set henceforth.
5538 	 */
5539 	mutex_enter(&connp->conn_lock);
5540 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5541 	connp->conn_state_flags |= CONN_CLOSING;
5542 	if (connp->conn_idl != NULL)
5543 		drain_cleanup_reqd = B_TRUE;
5544 	if (connp->conn_oper_pending_ill != NULL)
5545 		conn_ioctl_cleanup_reqd = B_TRUE;
5546 	if (connp->conn_ilg_inuse != 0)
5547 		ilg_cleanup_reqd = B_TRUE;
5548 	mutex_exit(&connp->conn_lock);
5549 
5550 	if (IPCL_IS_UDP(connp))
5551 		udp_quiesce_conn(connp);
5552 
5553 	if (conn_ioctl_cleanup_reqd)
5554 		conn_ioctl_cleanup(connp);
5555 
5556 	if (is_system_labeled() && connp->conn_anon_port) {
5557 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5558 		    connp->conn_mlp_type, connp->conn_ulp,
5559 		    ntohs(connp->conn_lport), B_FALSE);
5560 		connp->conn_anon_port = 0;
5561 	}
5562 	connp->conn_mlp_type = mlptSingle;
5563 
5564 	/*
5565 	 * Remove this conn from any fanout list it is on.
5566 	 * and then wait for any threads currently operating
5567 	 * on this endpoint to finish
5568 	 */
5569 	ipcl_hash_remove(connp);
5570 
5571 	/*
5572 	 * Remove this conn from the drain list, and do
5573 	 * any other cleanup that may be required.
5574 	 * (Only non-tcp streams may have a non-null conn_idl.
5575 	 * TCP streams are never flow controlled, and
5576 	 * conn_idl will be null)
5577 	 */
5578 	if (drain_cleanup_reqd)
5579 		conn_drain_tail(connp, B_TRUE);
5580 
5581 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5582 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5583 		(void) ip_mrouter_done(NULL, ipst);
5584 
5585 	if (ilg_cleanup_reqd)
5586 		ilg_delete_all(connp);
5587 
5588 	conn_delete_ire(connp, NULL);
5589 
5590 	/*
5591 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5592 	 * callers from write side can't be there now because close
5593 	 * is in progress. The only other caller is ipcl_walk
5594 	 * which checks for the condemned flag.
5595 	 */
5596 	mutex_enter(&connp->conn_lock);
5597 	connp->conn_state_flags |= CONN_CONDEMNED;
5598 	while (connp->conn_ref != 1)
5599 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5600 	connp->conn_state_flags |= CONN_QUIESCED;
5601 	mutex_exit(&connp->conn_lock);
5602 }
5603 
5604 /* ARGSUSED */
5605 int
5606 ip_close(queue_t *q, int flags)
5607 {
5608 	conn_t		*connp;
5609 
5610 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5611 
5612 	/*
5613 	 * Call the appropriate delete routine depending on whether this is
5614 	 * a module or device.
5615 	 */
5616 	if (WR(q)->q_next != NULL) {
5617 		/* This is a module close */
5618 		return (ip_modclose((ill_t *)q->q_ptr));
5619 	}
5620 
5621 	connp = q->q_ptr;
5622 	ip_quiesce_conn(connp);
5623 
5624 	qprocsoff(q);
5625 
5626 	/*
5627 	 * Now we are truly single threaded on this stream, and can
5628 	 * delete the things hanging off the connp, and finally the connp.
5629 	 * We removed this connp from the fanout list, it cannot be
5630 	 * accessed thru the fanouts, and we already waited for the
5631 	 * conn_ref to drop to 0. We are already in close, so
5632 	 * there cannot be any other thread from the top. qprocsoff
5633 	 * has completed, and service has completed or won't run in
5634 	 * future.
5635 	 */
5636 	ASSERT(connp->conn_ref == 1);
5637 
5638 	/*
5639 	 * A conn which was previously marked as IPCL_UDP cannot
5640 	 * retain the flag because it would have been cleared by
5641 	 * udp_close().
5642 	 */
5643 	ASSERT(!IPCL_IS_UDP(connp));
5644 
5645 	if (connp->conn_latch != NULL) {
5646 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5647 		connp->conn_latch = NULL;
5648 	}
5649 	if (connp->conn_policy != NULL) {
5650 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5651 		connp->conn_policy = NULL;
5652 	}
5653 	if (connp->conn_ipsec_opt_mp != NULL) {
5654 		freemsg(connp->conn_ipsec_opt_mp);
5655 		connp->conn_ipsec_opt_mp = NULL;
5656 	}
5657 
5658 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5659 
5660 	connp->conn_ref--;
5661 	ipcl_conn_destroy(connp);
5662 
5663 	q->q_ptr = WR(q)->q_ptr = NULL;
5664 	return (0);
5665 }
5666 
5667 int
5668 ip_snmpmod_close(queue_t *q)
5669 {
5670 	conn_t *connp = Q_TO_CONN(q);
5671 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5672 
5673 	qprocsoff(q);
5674 
5675 	if (connp->conn_flags & IPCL_UDPMOD)
5676 		udp_close_free(connp);
5677 
5678 	if (connp->conn_cred != NULL) {
5679 		crfree(connp->conn_cred);
5680 		connp->conn_cred = NULL;
5681 	}
5682 	CONN_DEC_REF(connp);
5683 	q->q_ptr = WR(q)->q_ptr = NULL;
5684 	return (0);
5685 }
5686 
5687 /*
5688  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5689  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5690  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5691  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5692  * queues as we never enqueue messages there and we don't handle any ioctls.
5693  * Everything else is freed.
5694  */
5695 void
5696 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5697 {
5698 	conn_t	*connp = q->q_ptr;
5699 	pfi_t	setfn;
5700 	pfi_t	getfn;
5701 
5702 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5703 
5704 	switch (DB_TYPE(mp)) {
5705 	case M_PROTO:
5706 	case M_PCPROTO:
5707 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5708 		    ((((union T_primitives *)mp->b_rptr)->type ==
5709 			T_SVR4_OPTMGMT_REQ) ||
5710 		    (((union T_primitives *)mp->b_rptr)->type ==
5711 			T_OPTMGMT_REQ))) {
5712 			/*
5713 			 * This is the only TPI primitive supported. Its
5714 			 * handling does not require tcp_t, but it does require
5715 			 * conn_t to check permissions.
5716 			 */
5717 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5718 
5719 			if (connp->conn_flags & IPCL_TCPMOD) {
5720 				setfn = tcp_snmp_set;
5721 				getfn = tcp_snmp_get;
5722 			} else {
5723 				setfn = udp_snmp_set;
5724 				getfn = udp_snmp_get;
5725 			}
5726 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5727 				freemsg(mp);
5728 				return;
5729 			}
5730 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5731 		    != NULL)
5732 			qreply(q, mp);
5733 		break;
5734 	case M_FLUSH:
5735 	case M_IOCTL:
5736 		putnext(q, mp);
5737 		break;
5738 	default:
5739 		freemsg(mp);
5740 		break;
5741 	}
5742 }
5743 
5744 /* Return the IP checksum for the IP header at "iph". */
5745 uint16_t
5746 ip_csum_hdr(ipha_t *ipha)
5747 {
5748 	uint16_t	*uph;
5749 	uint32_t	sum;
5750 	int		opt_len;
5751 
5752 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5753 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5754 	uph = (uint16_t *)ipha;
5755 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5756 		uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5757 	if (opt_len > 0) {
5758 		do {
5759 			sum += uph[10];
5760 			sum += uph[11];
5761 			uph += 2;
5762 		} while (--opt_len);
5763 	}
5764 	sum = (sum & 0xFFFF) + (sum >> 16);
5765 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5766 	if (sum == 0xffff)
5767 		sum = 0;
5768 	return ((uint16_t)sum);
5769 }
5770 
5771 /*
5772  * Called when the module is about to be unloaded
5773  */
5774 void
5775 ip_ddi_destroy(void)
5776 {
5777 	tnet_fini();
5778 
5779 	sctp_ddi_g_destroy();
5780 	tcp_ddi_g_destroy();
5781 	ipsec_policy_g_destroy();
5782 	ipcl_g_destroy();
5783 	ip_net_g_destroy();
5784 	ip_ire_g_fini();
5785 	inet_minor_destroy(ip_minor_arena);
5786 
5787 	netstack_unregister(NS_IP);
5788 }
5789 
5790 /*
5791  * First step in cleanup.
5792  */
5793 /* ARGSUSED */
5794 static void
5795 ip_stack_shutdown(netstackid_t stackid, void *arg)
5796 {
5797 	ip_stack_t *ipst = (ip_stack_t *)arg;
5798 
5799 #ifdef NS_DEBUG
5800 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5801 #endif
5802 
5803 	/* Get rid of loopback interfaces and their IREs */
5804 	ip_loopback_cleanup(ipst);
5805 }
5806 
5807 /*
5808  * Free the IP stack instance.
5809  */
5810 static void
5811 ip_stack_fini(netstackid_t stackid, void *arg)
5812 {
5813 	ip_stack_t *ipst = (ip_stack_t *)arg;
5814 	int ret;
5815 
5816 #ifdef NS_DEBUG
5817 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5818 #endif
5819 	ipv4_hook_destroy(ipst);
5820 	ipv6_hook_destroy(ipst);
5821 	ip_net_destroy(ipst);
5822 
5823 	rw_destroy(&ipst->ips_srcid_lock);
5824 
5825 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5826 	ipst->ips_ip_mibkp = NULL;
5827 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5828 	ipst->ips_icmp_mibkp = NULL;
5829 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5830 	ipst->ips_ip_kstat = NULL;
5831 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5832 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5833 	ipst->ips_ip6_kstat = NULL;
5834 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5835 
5836 	nd_free(&ipst->ips_ip_g_nd);
5837 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5838 	ipst->ips_param_arr = NULL;
5839 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5840 	ipst->ips_ndp_arr = NULL;
5841 
5842 	ip_mrouter_stack_destroy(ipst);
5843 
5844 	mutex_destroy(&ipst->ips_ip_mi_lock);
5845 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5846 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5847 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5848 
5849 	ret = untimeout(ipst->ips_igmp_timeout_id);
5850 	if (ret == -1) {
5851 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5852 	} else {
5853 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5854 		ipst->ips_igmp_timeout_id = 0;
5855 	}
5856 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5857 	if (ret == -1) {
5858 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5859 	} else {
5860 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5861 		ipst->ips_igmp_slowtimeout_id = 0;
5862 	}
5863 	ret = untimeout(ipst->ips_mld_timeout_id);
5864 	if (ret == -1) {
5865 		ASSERT(ipst->ips_mld_timeout_id == 0);
5866 	} else {
5867 		ASSERT(ipst->ips_mld_timeout_id != 0);
5868 		ipst->ips_mld_timeout_id = 0;
5869 	}
5870 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5871 	if (ret == -1) {
5872 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5873 	} else {
5874 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5875 		ipst->ips_mld_slowtimeout_id = 0;
5876 	}
5877 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5878 	if (ret == -1) {
5879 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5880 	} else {
5881 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5882 		ipst->ips_ip_ire_expire_id = 0;
5883 	}
5884 
5885 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5886 	mutex_destroy(&ipst->ips_mld_timer_lock);
5887 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5888 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5889 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5890 	rw_destroy(&ipst->ips_ill_g_lock);
5891 
5892 	ip_ire_fini(ipst);
5893 	ip6_asp_free(ipst);
5894 	conn_drain_fini(ipst);
5895 	ipcl_destroy(ipst);
5896 
5897 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5898 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5899 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5900 	ipst->ips_ndp4 = NULL;
5901 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5902 	ipst->ips_ndp6 = NULL;
5903 
5904 	if (ipst->ips_loopback_ksp != NULL) {
5905 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5906 		ipst->ips_loopback_ksp = NULL;
5907 	}
5908 
5909 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5910 	ipst->ips_phyint_g_list = NULL;
5911 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5912 	ipst->ips_ill_g_heads = NULL;
5913 
5914 	kmem_free(ipst, sizeof (*ipst));
5915 }
5916 
5917 /*
5918  * Called when the IP kernel module is loaded into the kernel
5919  */
5920 void
5921 ip_ddi_init(void)
5922 {
5923 	TCP6_MAJ = ddi_name_to_major(TCP6);
5924 	TCP_MAJ	= ddi_name_to_major(TCP);
5925 	SCTP_MAJ = ddi_name_to_major(SCTP);
5926 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5927 
5928 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5929 
5930 	/*
5931 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5932 	 * initial devices: ip, ip6, tcp, tcp6.
5933 	 */
5934 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5935 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5936 		cmn_err(CE_PANIC,
5937 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5938 	}
5939 
5940 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5941 
5942 	ipcl_g_init();
5943 	ip_ire_g_init();
5944 	ip_net_g_init();
5945 
5946 #ifdef ILL_DEBUG
5947 	/* Default cleanup function */
5948 	ip_cleanup_func = ip_thread_exit;
5949 #endif
5950 
5951 	/*
5952 	 * We want to be informed each time a stack is created or
5953 	 * destroyed in the kernel, so we can maintain the
5954 	 * set of udp_stack_t's.
5955 	 */
5956 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5957 	    ip_stack_fini);
5958 
5959 	ipsec_policy_g_init();
5960 	tcp_ddi_g_init();
5961 	sctp_ddi_g_init();
5962 
5963 	tnet_init();
5964 }
5965 
5966 /*
5967  * Initialize the IP stack instance.
5968  */
5969 static void *
5970 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5971 {
5972 	ip_stack_t	*ipst;
5973 	ipparam_t	*pa;
5974 	ipndp_t		*na;
5975 
5976 #ifdef NS_DEBUG
5977 	printf("ip_stack_init(stack %d)\n", stackid);
5978 #endif
5979 
5980 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5981 	ipst->ips_netstack = ns;
5982 
5983 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5984 	    KM_SLEEP);
5985 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5986 	    KM_SLEEP);
5987 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5988 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5989 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5990 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5991 
5992 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5993 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5994 	ipst->ips_igmp_deferred_next = INFINITY;
5995 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5996 	ipst->ips_mld_deferred_next = INFINITY;
5997 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5998 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5999 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6000 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6001 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6002 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6003 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6004 
6005 	ipcl_init(ipst);
6006 	ip_ire_init(ipst);
6007 	ip6_asp_init(ipst);
6008 	ipif_init(ipst);
6009 	conn_drain_init(ipst);
6010 	ip_mrouter_stack_init(ipst);
6011 
6012 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6013 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6014 
6015 	ipst->ips_ip_multirt_log_interval = 1000;
6016 
6017 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6018 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6019 	ipst->ips_ill_index = 1;
6020 
6021 	ipst->ips_saved_ip_g_forward = -1;
6022 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6023 
6024 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6025 	ipst->ips_param_arr = pa;
6026 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6027 
6028 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6029 	ipst->ips_ndp_arr = na;
6030 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6031 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6032 	    (caddr_t)&ipst->ips_ip_g_forward;
6033 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6034 	    (caddr_t)&ipst->ips_ipv6_forward;
6035 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6036 		"ip_cgtp_filter") == 0);
6037 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6038 	    (caddr_t)&ip_cgtp_filter;
6039 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6040 		"ipmp_hook_emulation") == 0);
6041 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6042 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6043 
6044 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6045 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6046 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6047 
6048 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6049 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6050 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6051 	ipst->ips_ip6_kstat =
6052 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6053 
6054 	ipst->ips_ipmp_enable_failback = B_TRUE;
6055 
6056 	ipst->ips_ip_src_id = 1;
6057 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6058 
6059 	ip_net_init(ipst, ns);
6060 	ipv4_hook_init(ipst);
6061 	ipv6_hook_init(ipst);
6062 
6063 	return (ipst);
6064 }
6065 
6066 /*
6067  * Allocate and initialize a DLPI template of the specified length.  (May be
6068  * called as writer.)
6069  */
6070 mblk_t *
6071 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6072 {
6073 	mblk_t	*mp;
6074 
6075 	mp = allocb(len, BPRI_MED);
6076 	if (!mp)
6077 		return (NULL);
6078 
6079 	/*
6080 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6081 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6082 	 * that other DLPI are M_PROTO.
6083 	 */
6084 	if (prim == DL_INFO_REQ) {
6085 		mp->b_datap->db_type = M_PCPROTO;
6086 	} else {
6087 		mp->b_datap->db_type = M_PROTO;
6088 	}
6089 
6090 	mp->b_wptr = mp->b_rptr + len;
6091 	bzero(mp->b_rptr, len);
6092 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6093 	return (mp);
6094 }
6095 
6096 const char *
6097 dlpi_prim_str(int prim)
6098 {
6099 	switch (prim) {
6100 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6101 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6102 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6103 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6104 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6105 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6106 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6107 	case DL_OK_ACK:		return ("DL_OK_ACK");
6108 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6109 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6110 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6111 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6112 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6113 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6114 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6115 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6116 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6117 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6118 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6119 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6120 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6121 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6122 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6123 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6124 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6125 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6126 	default:		return ("<unknown primitive>");
6127 	}
6128 }
6129 
6130 const char *
6131 dlpi_err_str(int err)
6132 {
6133 	switch (err) {
6134 	case DL_ACCESS:		return ("DL_ACCESS");
6135 	case DL_BADADDR:	return ("DL_BADADDR");
6136 	case DL_BADCORR:	return ("DL_BADCORR");
6137 	case DL_BADDATA:	return ("DL_BADDATA");
6138 	case DL_BADPPA:		return ("DL_BADPPA");
6139 	case DL_BADPRIM:	return ("DL_BADPRIM");
6140 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6141 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6142 	case DL_BADSAP:		return ("DL_BADSAP");
6143 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6144 	case DL_BOUND:		return ("DL_BOUND");
6145 	case DL_INITFAILED:	return ("DL_INITFAILED");
6146 	case DL_NOADDR:		return ("DL_NOADDR");
6147 	case DL_NOTINIT:	return ("DL_NOTINIT");
6148 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6149 	case DL_SYSERR:		return ("DL_SYSERR");
6150 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6151 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6152 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6153 	case DL_TOOMANY:	return ("DL_TOOMANY");
6154 	case DL_NOTENAB:	return ("DL_NOTENAB");
6155 	case DL_BUSY:		return ("DL_BUSY");
6156 	case DL_NOAUTO:		return ("DL_NOAUTO");
6157 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6158 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6159 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6160 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6161 	case DL_PENDING:	return ("DL_PENDING");
6162 	default:		return ("<unknown error>");
6163 	}
6164 }
6165 
6166 /*
6167  * Debug formatting routine.  Returns a character string representation of the
6168  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6169  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6170  *
6171  * Once the ndd table-printing interfaces are removed, this can be changed to
6172  * standard dotted-decimal form.
6173  */
6174 char *
6175 ip_dot_addr(ipaddr_t addr, char *buf)
6176 {
6177 	uint8_t *ap = (uint8_t *)&addr;
6178 
6179 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6180 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6181 	return (buf);
6182 }
6183 
6184 /*
6185  * Write the given MAC address as a printable string in the usual colon-
6186  * separated format.
6187  */
6188 const char *
6189 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6190 {
6191 	char *bp;
6192 
6193 	if (alen == 0 || buflen < 4)
6194 		return ("?");
6195 	bp = buf;
6196 	for (;;) {
6197 		/*
6198 		 * If there are more MAC address bytes available, but we won't
6199 		 * have any room to print them, then add "..." to the string
6200 		 * instead.  See below for the 'magic number' explanation.
6201 		 */
6202 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6203 			(void) strcpy(bp, "...");
6204 			break;
6205 		}
6206 		(void) sprintf(bp, "%02x", *addr++);
6207 		bp += 2;
6208 		if (--alen == 0)
6209 			break;
6210 		*bp++ = ':';
6211 		buflen -= 3;
6212 		/*
6213 		 * At this point, based on the first 'if' statement above,
6214 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6215 		 * buflen >= 4.  The first case leaves room for the final "xx"
6216 		 * number and trailing NUL byte.  The second leaves room for at
6217 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6218 		 * that statement.
6219 		 */
6220 	}
6221 	return (buf);
6222 }
6223 
6224 /*
6225  * Send an ICMP error after patching up the packet appropriately.  Returns
6226  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6227  */
6228 static boolean_t
6229 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6230     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6231     zoneid_t zoneid, ip_stack_t *ipst)
6232 {
6233 	ipha_t *ipha;
6234 	mblk_t *first_mp;
6235 	boolean_t secure;
6236 	unsigned char db_type;
6237 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6238 
6239 	first_mp = mp;
6240 	if (mctl_present) {
6241 		mp = mp->b_cont;
6242 		secure = ipsec_in_is_secure(first_mp);
6243 		ASSERT(mp != NULL);
6244 	} else {
6245 		/*
6246 		 * If this is an ICMP error being reported - which goes
6247 		 * up as M_CTLs, we need to convert them to M_DATA till
6248 		 * we finish checking with global policy because
6249 		 * ipsec_check_global_policy() assumes M_DATA as clear
6250 		 * and M_CTL as secure.
6251 		 */
6252 		db_type = DB_TYPE(mp);
6253 		DB_TYPE(mp) = M_DATA;
6254 		secure = B_FALSE;
6255 	}
6256 	/*
6257 	 * We are generating an icmp error for some inbound packet.
6258 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6259 	 * Before we generate an error, check with global policy
6260 	 * to see whether this is allowed to enter the system. As
6261 	 * there is no "conn", we are checking with global policy.
6262 	 */
6263 	ipha = (ipha_t *)mp->b_rptr;
6264 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6265 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6266 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6267 		if (first_mp == NULL)
6268 			return (B_FALSE);
6269 	}
6270 
6271 	if (!mctl_present)
6272 		DB_TYPE(mp) = db_type;
6273 
6274 	if (flags & IP_FF_SEND_ICMP) {
6275 		if (flags & IP_FF_HDR_COMPLETE) {
6276 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6277 				freemsg(first_mp);
6278 				return (B_TRUE);
6279 			}
6280 		}
6281 		if (flags & IP_FF_CKSUM) {
6282 			/*
6283 			 * Have to correct checksum since
6284 			 * the packet might have been
6285 			 * fragmented and the reassembly code in ip_rput
6286 			 * does not restore the IP checksum.
6287 			 */
6288 			ipha->ipha_hdr_checksum = 0;
6289 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6290 		}
6291 		switch (icmp_type) {
6292 		case ICMP_DEST_UNREACHABLE:
6293 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6294 			    ipst);
6295 			break;
6296 		default:
6297 			freemsg(first_mp);
6298 			break;
6299 		}
6300 	} else {
6301 		freemsg(first_mp);
6302 		return (B_FALSE);
6303 	}
6304 
6305 	return (B_TRUE);
6306 }
6307 
6308 /*
6309  * Used to send an ICMP error message when a packet is received for
6310  * a protocol that is not supported. The mblk passed as argument
6311  * is consumed by this function.
6312  */
6313 void
6314 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6315     ip_stack_t *ipst)
6316 {
6317 	mblk_t *mp;
6318 	ipha_t *ipha;
6319 	ill_t *ill;
6320 	ipsec_in_t *ii;
6321 
6322 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6323 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6324 
6325 	mp = ipsec_mp->b_cont;
6326 	ipsec_mp->b_cont = NULL;
6327 	ipha = (ipha_t *)mp->b_rptr;
6328 	/* Get ill from index in ipsec_in_t. */
6329 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6330 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6331 	    ipst);
6332 	if (ill != NULL) {
6333 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6334 			if (ip_fanout_send_icmp(q, mp, flags,
6335 			    ICMP_DEST_UNREACHABLE,
6336 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6337 				BUMP_MIB(ill->ill_ip_mib,
6338 				    ipIfStatsInUnknownProtos);
6339 			}
6340 		} else {
6341 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6342 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6343 			    0, B_FALSE, zoneid, ipst)) {
6344 				BUMP_MIB(ill->ill_ip_mib,
6345 				    ipIfStatsInUnknownProtos);
6346 			}
6347 		}
6348 		ill_refrele(ill);
6349 	} else { /* re-link for the freemsg() below. */
6350 		ipsec_mp->b_cont = mp;
6351 	}
6352 
6353 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6354 	freemsg(ipsec_mp);
6355 }
6356 
6357 /*
6358  * See if the inbound datagram has had IPsec processing applied to it.
6359  */
6360 boolean_t
6361 ipsec_in_is_secure(mblk_t *ipsec_mp)
6362 {
6363 	ipsec_in_t *ii;
6364 
6365 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6366 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6367 
6368 	if (ii->ipsec_in_loopback) {
6369 		return (ii->ipsec_in_secure);
6370 	} else {
6371 		return (ii->ipsec_in_ah_sa != NULL ||
6372 		    ii->ipsec_in_esp_sa != NULL ||
6373 		    ii->ipsec_in_decaps);
6374 	}
6375 }
6376 
6377 /*
6378  * Handle protocols with which IP is less intimate.  There
6379  * can be more than one stream bound to a particular
6380  * protocol.  When this is the case, normally each one gets a copy
6381  * of any incoming packets.
6382  *
6383  * IPSEC NOTE :
6384  *
6385  * Don't allow a secure packet going up a non-secure connection.
6386  * We don't allow this because
6387  *
6388  * 1) Reply might go out in clear which will be dropped at
6389  *    the sending side.
6390  * 2) If the reply goes out in clear it will give the
6391  *    adversary enough information for getting the key in
6392  *    most of the cases.
6393  *
6394  * Moreover getting a secure packet when we expect clear
6395  * implies that SA's were added without checking for
6396  * policy on both ends. This should not happen once ISAKMP
6397  * is used to negotiate SAs as SAs will be added only after
6398  * verifying the policy.
6399  *
6400  * NOTE : If the packet was tunneled and not multicast we only send
6401  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6402  * back to delivering packets to AF_INET6 raw sockets.
6403  *
6404  * IPQoS Notes:
6405  * Once we have determined the client, invoke IPPF processing.
6406  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6407  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6408  * ip_policy will be false.
6409  *
6410  * Zones notes:
6411  * Currently only applications in the global zone can create raw sockets for
6412  * protocols other than ICMP. So unlike the broadcast / multicast case of
6413  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6414  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6415  */
6416 static void
6417 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6418     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6419     zoneid_t zoneid)
6420 {
6421 	queue_t	*rq;
6422 	mblk_t	*mp1, *first_mp1;
6423 	uint_t	protocol = ipha->ipha_protocol;
6424 	ipaddr_t dst;
6425 	boolean_t one_only;
6426 	mblk_t *first_mp = mp;
6427 	boolean_t secure;
6428 	uint32_t ill_index;
6429 	conn_t	*connp, *first_connp, *next_connp;
6430 	connf_t	*connfp;
6431 	boolean_t shared_addr;
6432 	mib2_ipIfStatsEntry_t *mibptr;
6433 	ip_stack_t *ipst = recv_ill->ill_ipst;
6434 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6435 
6436 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6437 	if (mctl_present) {
6438 		mp = first_mp->b_cont;
6439 		secure = ipsec_in_is_secure(first_mp);
6440 		ASSERT(mp != NULL);
6441 	} else {
6442 		secure = B_FALSE;
6443 	}
6444 	dst = ipha->ipha_dst;
6445 	/*
6446 	 * If the packet was tunneled and not multicast we only send to it
6447 	 * the first match.
6448 	 */
6449 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6450 	    !CLASSD(dst));
6451 
6452 	shared_addr = (zoneid == ALL_ZONES);
6453 	if (shared_addr) {
6454 		/*
6455 		 * We don't allow multilevel ports for raw IP, so no need to
6456 		 * check for that here.
6457 		 */
6458 		zoneid = tsol_packet_to_zoneid(mp);
6459 	}
6460 
6461 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6462 	mutex_enter(&connfp->connf_lock);
6463 	connp = connfp->connf_head;
6464 	for (connp = connfp->connf_head; connp != NULL;
6465 		connp = connp->conn_next) {
6466 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6467 		    zoneid) &&
6468 		    (!is_system_labeled() ||
6469 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6470 		    connp)))
6471 			break;
6472 	}
6473 
6474 	if (connp == NULL || connp->conn_upq == NULL) {
6475 		/*
6476 		 * No one bound to these addresses.  Is
6477 		 * there a client that wants all
6478 		 * unclaimed datagrams?
6479 		 */
6480 		mutex_exit(&connfp->connf_lock);
6481 		/*
6482 		 * Check for IPPROTO_ENCAP...
6483 		 */
6484 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6485 			/*
6486 			 * If an IPsec mblk is here on a multicast
6487 			 * tunnel (using ip_mroute stuff), check policy here,
6488 			 * THEN ship off to ip_mroute_decap().
6489 			 *
6490 			 * BTW,  If I match a configured IP-in-IP
6491 			 * tunnel, this path will not be reached, and
6492 			 * ip_mroute_decap will never be called.
6493 			 */
6494 			first_mp = ipsec_check_global_policy(first_mp, connp,
6495 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6496 			if (first_mp != NULL) {
6497 				if (mctl_present)
6498 					freeb(first_mp);
6499 				ip_mroute_decap(q, mp, ill);
6500 			} /* Else we already freed everything! */
6501 		} else {
6502 			/*
6503 			 * Otherwise send an ICMP protocol unreachable.
6504 			 */
6505 			if (ip_fanout_send_icmp(q, first_mp, flags,
6506 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6507 			    mctl_present, zoneid, ipst)) {
6508 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6509 			}
6510 		}
6511 		return;
6512 	}
6513 	CONN_INC_REF(connp);
6514 	first_connp = connp;
6515 
6516 	/*
6517 	 * Only send message to one tunnel driver by immediately
6518 	 * terminating the loop.
6519 	 */
6520 	connp = one_only ? NULL : connp->conn_next;
6521 
6522 	for (;;) {
6523 		while (connp != NULL) {
6524 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6525 			    flags, zoneid) &&
6526 			    (!is_system_labeled() ||
6527 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6528 			    shared_addr, connp)))
6529 				break;
6530 			connp = connp->conn_next;
6531 		}
6532 
6533 		/*
6534 		 * Copy the packet.
6535 		 */
6536 		if (connp == NULL || connp->conn_upq == NULL ||
6537 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6538 			((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6539 			/*
6540 			 * No more interested clients or memory
6541 			 * allocation failed
6542 			 */
6543 			connp = first_connp;
6544 			break;
6545 		}
6546 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6547 		CONN_INC_REF(connp);
6548 		mutex_exit(&connfp->connf_lock);
6549 		rq = connp->conn_rq;
6550 		if (!canputnext(rq)) {
6551 			if (flags & IP_FF_RAWIP) {
6552 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6553 			} else {
6554 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6555 			}
6556 
6557 			freemsg(first_mp1);
6558 		} else {
6559 			/*
6560 			 * Don't enforce here if we're an actual tunnel -
6561 			 * let "tun" do it instead.
6562 			 */
6563 			if (!IPCL_IS_IPTUN(connp) &&
6564 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6565 			    secure)) {
6566 				first_mp1 = ipsec_check_inbound_policy
6567 				    (first_mp1, connp, ipha, NULL,
6568 				    mctl_present);
6569 			}
6570 			if (first_mp1 != NULL) {
6571 				int in_flags = 0;
6572 				/*
6573 				 * ip_fanout_proto also gets called from
6574 				 * icmp_inbound_error_fanout, in which case
6575 				 * the msg type is M_CTL.  Don't add info
6576 				 * in this case for the time being. In future
6577 				 * when there is a need for knowing the
6578 				 * inbound iface index for ICMP error msgs,
6579 				 * then this can be changed.
6580 				 */
6581 				if (connp->conn_recvif)
6582 					in_flags = IPF_RECVIF;
6583 				/*
6584 				 * The ULP may support IP_RECVPKTINFO for both
6585 				 * IP v4 and v6 so pass the appropriate argument
6586 				 * based on conn IP version.
6587 				 */
6588 				if (connp->conn_ip_recvpktinfo) {
6589 					if (connp->conn_af_isv6) {
6590 						/*
6591 						 * V6 only needs index
6592 						 */
6593 						in_flags |= IPF_RECVIF;
6594 					} else {
6595 						/*
6596 						 * V4 needs index +
6597 						 * matching address.
6598 						 */
6599 						in_flags |= IPF_RECVADDR;
6600 					}
6601 				}
6602 				if ((in_flags != 0) &&
6603 				    (mp->b_datap->db_type != M_CTL)) {
6604 					/*
6605 					 * the actual data will be
6606 					 * contained in b_cont upon
6607 					 * successful return of the
6608 					 * following call else
6609 					 * original mblk is returned
6610 					 */
6611 					ASSERT(recv_ill != NULL);
6612 					mp1 = ip_add_info(mp1, recv_ill,
6613 					    in_flags, IPCL_ZONEID(connp), ipst);
6614 				}
6615 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6616 				if (mctl_present)
6617 					freeb(first_mp1);
6618 				putnext(rq, mp1);
6619 			}
6620 		}
6621 		mutex_enter(&connfp->connf_lock);
6622 		/* Follow the next pointer before releasing the conn. */
6623 		next_connp = connp->conn_next;
6624 		CONN_DEC_REF(connp);
6625 		connp = next_connp;
6626 	}
6627 
6628 	/* Last one.  Send it upstream. */
6629 	mutex_exit(&connfp->connf_lock);
6630 
6631 	/*
6632 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6633 	 * will be set to false.
6634 	 */
6635 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6636 		ill_index = ill->ill_phyint->phyint_ifindex;
6637 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6638 		if (mp == NULL) {
6639 			CONN_DEC_REF(connp);
6640 			if (mctl_present) {
6641 				freeb(first_mp);
6642 			}
6643 			return;
6644 		}
6645 	}
6646 
6647 	rq = connp->conn_rq;
6648 	if (!canputnext(rq)) {
6649 		if (flags & IP_FF_RAWIP) {
6650 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6651 		} else {
6652 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6653 		}
6654 
6655 		freemsg(first_mp);
6656 	} else {
6657 		if (IPCL_IS_IPTUN(connp)) {
6658 			/*
6659 			 * Tunneled packet.  We enforce policy in the tunnel
6660 			 * module itself.
6661 			 *
6662 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6663 			 * a policy check.
6664 			 */
6665 			putnext(rq, first_mp);
6666 			CONN_DEC_REF(connp);
6667 			return;
6668 		}
6669 
6670 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6671 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6672 			    ipha, NULL, mctl_present);
6673 		}
6674 
6675 		if (first_mp != NULL) {
6676 			int in_flags = 0;
6677 
6678 			/*
6679 			 * ip_fanout_proto also gets called
6680 			 * from icmp_inbound_error_fanout, in
6681 			 * which case the msg type is M_CTL.
6682 			 * Don't add info in this case for time
6683 			 * being. In future when there is a
6684 			 * need for knowing the inbound iface
6685 			 * index for ICMP error msgs, then this
6686 			 * can be changed
6687 			 */
6688 			if (connp->conn_recvif)
6689 				in_flags = IPF_RECVIF;
6690 			if (connp->conn_ip_recvpktinfo) {
6691 				if (connp->conn_af_isv6) {
6692 					/*
6693 					 * V6 only needs index
6694 					 */
6695 					in_flags |= IPF_RECVIF;
6696 				} else {
6697 					/*
6698 					 * V4 needs index +
6699 					 * matching address.
6700 					 */
6701 					in_flags |= IPF_RECVADDR;
6702 				}
6703 			}
6704 			if ((in_flags != 0) &&
6705 			    (mp->b_datap->db_type != M_CTL)) {
6706 
6707 				/*
6708 				 * the actual data will be contained in
6709 				 * b_cont upon successful return
6710 				 * of the following call else original
6711 				 * mblk is returned
6712 				 */
6713 				ASSERT(recv_ill != NULL);
6714 				mp = ip_add_info(mp, recv_ill,
6715 				    in_flags, IPCL_ZONEID(connp), ipst);
6716 			}
6717 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6718 			putnext(rq, mp);
6719 			if (mctl_present)
6720 				freeb(first_mp);
6721 		}
6722 	}
6723 	CONN_DEC_REF(connp);
6724 }
6725 
6726 /*
6727  * Fanout for TCP packets
6728  * The caller puts <fport, lport> in the ports parameter.
6729  *
6730  * IPQoS Notes
6731  * Before sending it to the client, invoke IPPF processing.
6732  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6733  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6734  * ip_policy is false.
6735  */
6736 static void
6737 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6738     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6739 {
6740 	mblk_t  *first_mp;
6741 	boolean_t secure;
6742 	uint32_t ill_index;
6743 	int	ip_hdr_len;
6744 	tcph_t	*tcph;
6745 	boolean_t syn_present = B_FALSE;
6746 	conn_t	*connp;
6747 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6748 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6749 
6750 	ASSERT(recv_ill != NULL);
6751 
6752 	first_mp = mp;
6753 	if (mctl_present) {
6754 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6755 		mp = first_mp->b_cont;
6756 		secure = ipsec_in_is_secure(first_mp);
6757 		ASSERT(mp != NULL);
6758 	} else {
6759 		secure = B_FALSE;
6760 	}
6761 
6762 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6763 
6764 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6765 		    zoneid, ipst)) == NULL) {
6766 		/*
6767 		 * No connected connection or listener. Send a
6768 		 * TH_RST via tcp_xmit_listeners_reset.
6769 		 */
6770 
6771 		/* Initiate IPPf processing, if needed. */
6772 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6773 			uint32_t ill_index;
6774 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6775 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6776 			if (first_mp == NULL)
6777 				return;
6778 		}
6779 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6780 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6781 		    zoneid));
6782 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6783 		    ipst->ips_netstack->netstack_tcp);
6784 		return;
6785 	}
6786 
6787 	/*
6788 	 * Allocate the SYN for the TCP connection here itself
6789 	 */
6790 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6791 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6792 		if (IPCL_IS_TCP(connp)) {
6793 			squeue_t *sqp;
6794 
6795 			/*
6796 			 * For fused tcp loopback, assign the eager's
6797 			 * squeue to be that of the active connect's.
6798 			 * Note that we don't check for IP_FF_LOOPBACK
6799 			 * here since this routine gets called only
6800 			 * for loopback (unlike the IPv6 counterpart).
6801 			 */
6802 			ASSERT(Q_TO_CONN(q) != NULL);
6803 			if (do_tcp_fusion &&
6804 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6805 			    !secure &&
6806 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6807 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6808 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6809 				sqp = Q_TO_CONN(q)->conn_sqp;
6810 			} else {
6811 				sqp = IP_SQUEUE_GET(lbolt);
6812 			}
6813 
6814 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6815 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6816 			syn_present = B_TRUE;
6817 		}
6818 	}
6819 
6820 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6821 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6822 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6823 		if ((flags & TH_RST) || (flags & TH_URG)) {
6824 			CONN_DEC_REF(connp);
6825 			freemsg(first_mp);
6826 			return;
6827 		}
6828 		if (flags & TH_ACK) {
6829 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6830 			    ipst->ips_netstack->netstack_tcp);
6831 			CONN_DEC_REF(connp);
6832 			return;
6833 		}
6834 
6835 		CONN_DEC_REF(connp);
6836 		freemsg(first_mp);
6837 		return;
6838 	}
6839 
6840 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6841 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6842 		    NULL, mctl_present);
6843 		if (first_mp == NULL) {
6844 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6845 			CONN_DEC_REF(connp);
6846 			return;
6847 		}
6848 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6849 			ASSERT(syn_present);
6850 			if (mctl_present) {
6851 				ASSERT(first_mp != mp);
6852 				first_mp->b_datap->db_struioflag |=
6853 				    STRUIO_POLICY;
6854 			} else {
6855 				ASSERT(first_mp == mp);
6856 				mp->b_datap->db_struioflag &=
6857 				    ~STRUIO_EAGER;
6858 				mp->b_datap->db_struioflag |=
6859 				    STRUIO_POLICY;
6860 			}
6861 		} else {
6862 			/*
6863 			 * Discard first_mp early since we're dealing with a
6864 			 * fully-connected conn_t and tcp doesn't do policy in
6865 			 * this case.
6866 			 */
6867 			if (mctl_present) {
6868 				freeb(first_mp);
6869 				mctl_present = B_FALSE;
6870 			}
6871 			first_mp = mp;
6872 		}
6873 	}
6874 
6875 	/*
6876 	 * Initiate policy processing here if needed. If we get here from
6877 	 * icmp_inbound_error_fanout, ip_policy is false.
6878 	 */
6879 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6880 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6881 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6882 		if (mp == NULL) {
6883 			CONN_DEC_REF(connp);
6884 			if (mctl_present)
6885 				freeb(first_mp);
6886 			return;
6887 		} else if (mctl_present) {
6888 			ASSERT(first_mp != mp);
6889 			first_mp->b_cont = mp;
6890 		} else {
6891 			first_mp = mp;
6892 		}
6893 	}
6894 
6895 
6896 
6897 	/* Handle socket options. */
6898 	if (!syn_present &&
6899 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6900 		/* Add header */
6901 		ASSERT(recv_ill != NULL);
6902 		/*
6903 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6904 		 * IPF_RECVIF.
6905 		 */
6906 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6907 		    ipst);
6908 		if (mp == NULL) {
6909 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6910 			CONN_DEC_REF(connp);
6911 			if (mctl_present)
6912 				freeb(first_mp);
6913 			return;
6914 		} else if (mctl_present) {
6915 			/*
6916 			 * ip_add_info might return a new mp.
6917 			 */
6918 			ASSERT(first_mp != mp);
6919 			first_mp->b_cont = mp;
6920 		} else {
6921 			first_mp = mp;
6922 		}
6923 	}
6924 
6925 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6926 	if (IPCL_IS_TCP(connp)) {
6927 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6928 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6929 	} else {
6930 		putnext(connp->conn_rq, first_mp);
6931 		CONN_DEC_REF(connp);
6932 	}
6933 }
6934 
6935 /*
6936  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6937  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6938  * Caller is responsible for dropping references to the conn, and freeing
6939  * first_mp.
6940  *
6941  * IPQoS Notes
6942  * Before sending it to the client, invoke IPPF processing. Policy processing
6943  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6944  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6945  * ip_wput_local, ip_policy is false.
6946  */
6947 static void
6948 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6949     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6950     boolean_t ip_policy)
6951 {
6952 	boolean_t	mctl_present = (first_mp != NULL);
6953 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6954 	uint32_t	ill_index;
6955 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6956 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6957 
6958 	ASSERT(ill != NULL);
6959 
6960 	if (mctl_present)
6961 		first_mp->b_cont = mp;
6962 	else
6963 		first_mp = mp;
6964 
6965 	if (CONN_UDP_FLOWCTLD(connp)) {
6966 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6967 		freemsg(first_mp);
6968 		return;
6969 	}
6970 
6971 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6972 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6973 		    NULL, mctl_present);
6974 		if (first_mp == NULL) {
6975 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6976 			return;	/* Freed by ipsec_check_inbound_policy(). */
6977 		}
6978 	}
6979 	if (mctl_present)
6980 		freeb(first_mp);
6981 
6982 	/* Handle options. */
6983 	if (connp->conn_recvif)
6984 		in_flags = IPF_RECVIF;
6985 	/*
6986 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6987 	 * passed to ip_add_info is based on IP version of connp.
6988 	 */
6989 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6990 		if (connp->conn_af_isv6) {
6991 			/*
6992 			 * V6 only needs index
6993 			 */
6994 			in_flags |= IPF_RECVIF;
6995 		} else {
6996 			/*
6997 			 * V4 needs index + matching address.
6998 			 */
6999 			in_flags |= IPF_RECVADDR;
7000 		}
7001 	}
7002 
7003 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7004 		in_flags |= IPF_RECVSLLA;
7005 
7006 	/*
7007 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7008 	 * freed if the packet is dropped. The caller will do so.
7009 	 */
7010 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7011 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7012 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7013 		if (mp == NULL) {
7014 			return;
7015 		}
7016 	}
7017 	if ((in_flags != 0) &&
7018 	    (mp->b_datap->db_type != M_CTL)) {
7019 		/*
7020 		 * The actual data will be contained in b_cont
7021 		 * upon successful return of the following call
7022 		 * else original mblk is returned
7023 		 */
7024 		ASSERT(recv_ill != NULL);
7025 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7026 		    ipst);
7027 	}
7028 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7029 	/* Send it upstream */
7030 	CONN_UDP_RECV(connp, mp);
7031 }
7032 
7033 /*
7034  * Fanout for UDP packets.
7035  * The caller puts <fport, lport> in the ports parameter.
7036  *
7037  * If SO_REUSEADDR is set all multicast and broadcast packets
7038  * will be delivered to all streams bound to the same port.
7039  *
7040  * Zones notes:
7041  * Multicast and broadcast packets will be distributed to streams in all zones.
7042  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7043  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7044  * packets. To maintain this behavior with multiple zones, the conns are grouped
7045  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7046  * each zone. If unset, all the following conns in the same zone are skipped.
7047  */
7048 static void
7049 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7050     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7051     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7052 {
7053 	uint32_t	dstport, srcport;
7054 	ipaddr_t	dst;
7055 	mblk_t		*first_mp;
7056 	boolean_t	secure;
7057 	in6_addr_t	v6src;
7058 	conn_t		*connp;
7059 	connf_t		*connfp;
7060 	conn_t		*first_connp;
7061 	conn_t		*next_connp;
7062 	mblk_t		*mp1, *first_mp1;
7063 	ipaddr_t	src;
7064 	zoneid_t	last_zoneid;
7065 	boolean_t	reuseaddr;
7066 	boolean_t	shared_addr;
7067 	ip_stack_t	*ipst;
7068 
7069 	ASSERT(recv_ill != NULL);
7070 	ipst = recv_ill->ill_ipst;
7071 
7072 	first_mp = mp;
7073 	if (mctl_present) {
7074 		mp = first_mp->b_cont;
7075 		first_mp->b_cont = NULL;
7076 		secure = ipsec_in_is_secure(first_mp);
7077 		ASSERT(mp != NULL);
7078 	} else {
7079 		first_mp = NULL;
7080 		secure = B_FALSE;
7081 	}
7082 
7083 	/* Extract ports in net byte order */
7084 	dstport = htons(ntohl(ports) & 0xFFFF);
7085 	srcport = htons(ntohl(ports) >> 16);
7086 	dst = ipha->ipha_dst;
7087 	src = ipha->ipha_src;
7088 
7089 	shared_addr = (zoneid == ALL_ZONES);
7090 	if (shared_addr) {
7091 		/*
7092 		 * No need to handle exclusive-stack zones since ALL_ZONES
7093 		 * only applies to the shared stack.
7094 		 */
7095 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7096 		if (zoneid == ALL_ZONES)
7097 			zoneid = tsol_packet_to_zoneid(mp);
7098 	}
7099 
7100 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7101 	mutex_enter(&connfp->connf_lock);
7102 	connp = connfp->connf_head;
7103 	if (!broadcast && !CLASSD(dst)) {
7104 		/*
7105 		 * Not broadcast or multicast. Send to the one (first)
7106 		 * client we find. No need to check conn_wantpacket()
7107 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7108 		 * IPv4 unicast packets.
7109 		 */
7110 		while ((connp != NULL) &&
7111 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7112 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7113 			connp = connp->conn_next;
7114 		}
7115 
7116 		if (connp == NULL || connp->conn_upq == NULL)
7117 			goto notfound;
7118 
7119 		if (is_system_labeled() &&
7120 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7121 		    connp))
7122 			goto notfound;
7123 
7124 		CONN_INC_REF(connp);
7125 		mutex_exit(&connfp->connf_lock);
7126 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7127 		    flags, recv_ill, ip_policy);
7128 		IP_STAT(ipst, ip_udp_fannorm);
7129 		CONN_DEC_REF(connp);
7130 		return;
7131 	}
7132 
7133 	/*
7134 	 * Broadcast and multicast case
7135 	 *
7136 	 * Need to check conn_wantpacket().
7137 	 * If SO_REUSEADDR has been set on the first we send the
7138 	 * packet to all clients that have joined the group and
7139 	 * match the port.
7140 	 */
7141 
7142 	while (connp != NULL) {
7143 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7144 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7145 		    (!is_system_labeled() ||
7146 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7147 		    connp)))
7148 			break;
7149 		connp = connp->conn_next;
7150 	}
7151 
7152 	if (connp == NULL || connp->conn_upq == NULL)
7153 		goto notfound;
7154 
7155 	first_connp = connp;
7156 	/*
7157 	 * When SO_REUSEADDR is not set, send the packet only to the first
7158 	 * matching connection in its zone by keeping track of the zoneid.
7159 	 */
7160 	reuseaddr = first_connp->conn_reuseaddr;
7161 	last_zoneid = first_connp->conn_zoneid;
7162 
7163 	CONN_INC_REF(connp);
7164 	connp = connp->conn_next;
7165 	for (;;) {
7166 		while (connp != NULL) {
7167 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7168 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7169 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7170 			    (!is_system_labeled() ||
7171 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7172 			    shared_addr, connp)))
7173 				break;
7174 			connp = connp->conn_next;
7175 		}
7176 		/*
7177 		 * Just copy the data part alone. The mctl part is
7178 		 * needed just for verifying policy and it is never
7179 		 * sent up.
7180 		 */
7181 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7182 		    ((mp1 = copymsg(mp)) == NULL))) {
7183 			/*
7184 			 * No more interested clients or memory
7185 			 * allocation failed
7186 			 */
7187 			connp = first_connp;
7188 			break;
7189 		}
7190 		if (connp->conn_zoneid != last_zoneid) {
7191 			/*
7192 			 * Update the zoneid so that the packet isn't sent to
7193 			 * any more conns in the same zone unless SO_REUSEADDR
7194 			 * is set.
7195 			 */
7196 			reuseaddr = connp->conn_reuseaddr;
7197 			last_zoneid = connp->conn_zoneid;
7198 		}
7199 		if (first_mp != NULL) {
7200 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7201 			    ipsec_info_type == IPSEC_IN);
7202 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7203 			    ipst->ips_netstack);
7204 			if (first_mp1 == NULL) {
7205 				freemsg(mp1);
7206 				connp = first_connp;
7207 				break;
7208 			}
7209 		} else {
7210 			first_mp1 = NULL;
7211 		}
7212 		CONN_INC_REF(connp);
7213 		mutex_exit(&connfp->connf_lock);
7214 		/*
7215 		 * IPQoS notes: We don't send the packet for policy
7216 		 * processing here, will do it for the last one (below).
7217 		 * i.e. we do it per-packet now, but if we do policy
7218 		 * processing per-conn, then we would need to do it
7219 		 * here too.
7220 		 */
7221 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7222 		    ipha, flags, recv_ill, B_FALSE);
7223 		mutex_enter(&connfp->connf_lock);
7224 		/* Follow the next pointer before releasing the conn. */
7225 		next_connp = connp->conn_next;
7226 		IP_STAT(ipst, ip_udp_fanmb);
7227 		CONN_DEC_REF(connp);
7228 		connp = next_connp;
7229 	}
7230 
7231 	/* Last one.  Send it upstream. */
7232 	mutex_exit(&connfp->connf_lock);
7233 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7234 	    recv_ill, ip_policy);
7235 	IP_STAT(ipst, ip_udp_fanmb);
7236 	CONN_DEC_REF(connp);
7237 	return;
7238 
7239 notfound:
7240 
7241 	mutex_exit(&connfp->connf_lock);
7242 	IP_STAT(ipst, ip_udp_fanothers);
7243 	/*
7244 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7245 	 * have already been matched above, since they live in the IPv4
7246 	 * fanout tables. This implies we only need to
7247 	 * check for IPv6 in6addr_any endpoints here.
7248 	 * Thus we compare using ipv6_all_zeros instead of the destination
7249 	 * address, except for the multicast group membership lookup which
7250 	 * uses the IPv4 destination.
7251 	 */
7252 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7253 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7254 	mutex_enter(&connfp->connf_lock);
7255 	connp = connfp->connf_head;
7256 	if (!broadcast && !CLASSD(dst)) {
7257 		while (connp != NULL) {
7258 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7259 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7260 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7261 			    !connp->conn_ipv6_v6only)
7262 				break;
7263 			connp = connp->conn_next;
7264 		}
7265 
7266 		if (connp != NULL && is_system_labeled() &&
7267 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7268 		    connp))
7269 			connp = NULL;
7270 
7271 		if (connp == NULL || connp->conn_upq == NULL) {
7272 			/*
7273 			 * No one bound to this port.  Is
7274 			 * there a client that wants all
7275 			 * unclaimed datagrams?
7276 			 */
7277 			mutex_exit(&connfp->connf_lock);
7278 
7279 			if (mctl_present)
7280 				first_mp->b_cont = mp;
7281 			else
7282 				first_mp = mp;
7283 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7284 			    connf_head != NULL) {
7285 				ip_fanout_proto(q, first_mp, ill, ipha,
7286 				    flags | IP_FF_RAWIP, mctl_present,
7287 				    ip_policy, recv_ill, zoneid);
7288 			} else {
7289 				if (ip_fanout_send_icmp(q, first_mp, flags,
7290 				    ICMP_DEST_UNREACHABLE,
7291 				    ICMP_PORT_UNREACHABLE,
7292 				    mctl_present, zoneid, ipst)) {
7293 					BUMP_MIB(ill->ill_ip_mib,
7294 					    udpIfStatsNoPorts);
7295 				}
7296 			}
7297 			return;
7298 		}
7299 
7300 		CONN_INC_REF(connp);
7301 		mutex_exit(&connfp->connf_lock);
7302 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7303 		    flags, recv_ill, ip_policy);
7304 		CONN_DEC_REF(connp);
7305 		return;
7306 	}
7307 	/*
7308 	 * IPv4 multicast packet being delivered to an AF_INET6
7309 	 * in6addr_any endpoint.
7310 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7311 	 * and not conn_wantpacket_v6() since any multicast membership is
7312 	 * for an IPv4-mapped multicast address.
7313 	 * The packet is sent to all clients in all zones that have joined the
7314 	 * group and match the port.
7315 	 */
7316 	while (connp != NULL) {
7317 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7318 		    srcport, v6src) &&
7319 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7320 		    (!is_system_labeled() ||
7321 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7322 		    connp)))
7323 			break;
7324 		connp = connp->conn_next;
7325 	}
7326 
7327 	if (connp == NULL || connp->conn_upq == NULL) {
7328 		/*
7329 		 * No one bound to this port.  Is
7330 		 * there a client that wants all
7331 		 * unclaimed datagrams?
7332 		 */
7333 		mutex_exit(&connfp->connf_lock);
7334 
7335 		if (mctl_present)
7336 			first_mp->b_cont = mp;
7337 		else
7338 			first_mp = mp;
7339 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7340 		    NULL) {
7341 			ip_fanout_proto(q, first_mp, ill, ipha,
7342 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7343 			    recv_ill, zoneid);
7344 		} else {
7345 			/*
7346 			 * We used to attempt to send an icmp error here, but
7347 			 * since this is known to be a multicast packet
7348 			 * and we don't send icmp errors in response to
7349 			 * multicast, just drop the packet and give up sooner.
7350 			 */
7351 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7352 			freemsg(first_mp);
7353 		}
7354 		return;
7355 	}
7356 
7357 	first_connp = connp;
7358 
7359 	CONN_INC_REF(connp);
7360 	connp = connp->conn_next;
7361 	for (;;) {
7362 		while (connp != NULL) {
7363 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7364 			    ipv6_all_zeros, srcport, v6src) &&
7365 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7366 			    (!is_system_labeled() ||
7367 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7368 			    shared_addr, connp)))
7369 				break;
7370 			connp = connp->conn_next;
7371 		}
7372 		/*
7373 		 * Just copy the data part alone. The mctl part is
7374 		 * needed just for verifying policy and it is never
7375 		 * sent up.
7376 		 */
7377 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7378 		    ((mp1 = copymsg(mp)) == NULL))) {
7379 			/*
7380 			 * No more intested clients or memory
7381 			 * allocation failed
7382 			 */
7383 			connp = first_connp;
7384 			break;
7385 		}
7386 		if (first_mp != NULL) {
7387 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7388 			    ipsec_info_type == IPSEC_IN);
7389 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7390 			    ipst->ips_netstack);
7391 			if (first_mp1 == NULL) {
7392 				freemsg(mp1);
7393 				connp = first_connp;
7394 				break;
7395 			}
7396 		} else {
7397 			first_mp1 = NULL;
7398 		}
7399 		CONN_INC_REF(connp);
7400 		mutex_exit(&connfp->connf_lock);
7401 		/*
7402 		 * IPQoS notes: We don't send the packet for policy
7403 		 * processing here, will do it for the last one (below).
7404 		 * i.e. we do it per-packet now, but if we do policy
7405 		 * processing per-conn, then we would need to do it
7406 		 * here too.
7407 		 */
7408 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7409 		    ipha, flags, recv_ill, B_FALSE);
7410 		mutex_enter(&connfp->connf_lock);
7411 		/* Follow the next pointer before releasing the conn. */
7412 		next_connp = connp->conn_next;
7413 		CONN_DEC_REF(connp);
7414 		connp = next_connp;
7415 	}
7416 
7417 	/* Last one.  Send it upstream. */
7418 	mutex_exit(&connfp->connf_lock);
7419 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7420 	    recv_ill, ip_policy);
7421 	CONN_DEC_REF(connp);
7422 }
7423 
7424 /*
7425  * Complete the ip_wput header so that it
7426  * is possible to generate ICMP
7427  * errors.
7428  */
7429 int
7430 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7431 {
7432 	ire_t *ire;
7433 
7434 	if (ipha->ipha_src == INADDR_ANY) {
7435 		ire = ire_lookup_local(zoneid, ipst);
7436 		if (ire == NULL) {
7437 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7438 			return (1);
7439 		}
7440 		ipha->ipha_src = ire->ire_addr;
7441 		ire_refrele(ire);
7442 	}
7443 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7444 	ipha->ipha_hdr_checksum = 0;
7445 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7446 	return (0);
7447 }
7448 
7449 /*
7450  * Nobody should be sending
7451  * packets up this stream
7452  */
7453 static void
7454 ip_lrput(queue_t *q, mblk_t *mp)
7455 {
7456 	mblk_t *mp1;
7457 
7458 	switch (mp->b_datap->db_type) {
7459 	case M_FLUSH:
7460 		/* Turn around */
7461 		if (*mp->b_rptr & FLUSHW) {
7462 			*mp->b_rptr &= ~FLUSHR;
7463 			qreply(q, mp);
7464 			return;
7465 		}
7466 		break;
7467 	}
7468 	/* Could receive messages that passed through ar_rput */
7469 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7470 		mp1->b_prev = mp1->b_next = NULL;
7471 	freemsg(mp);
7472 }
7473 
7474 /* Nobody should be sending packets down this stream */
7475 /* ARGSUSED */
7476 void
7477 ip_lwput(queue_t *q, mblk_t *mp)
7478 {
7479 	freemsg(mp);
7480 }
7481 
7482 /*
7483  * Move the first hop in any source route to ipha_dst and remove that part of
7484  * the source route.  Called by other protocols.  Errors in option formatting
7485  * are ignored - will be handled by ip_wput_options Return the final
7486  * destination (either ipha_dst or the last entry in a source route.)
7487  */
7488 ipaddr_t
7489 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7490 {
7491 	ipoptp_t	opts;
7492 	uchar_t		*opt;
7493 	uint8_t		optval;
7494 	uint8_t		optlen;
7495 	ipaddr_t	dst;
7496 	int		i;
7497 	ire_t		*ire;
7498 	ip_stack_t	*ipst = ns->netstack_ip;
7499 
7500 	ip2dbg(("ip_massage_options\n"));
7501 	dst = ipha->ipha_dst;
7502 	for (optval = ipoptp_first(&opts, ipha);
7503 	    optval != IPOPT_EOL;
7504 	    optval = ipoptp_next(&opts)) {
7505 		opt = opts.ipoptp_cur;
7506 		switch (optval) {
7507 			uint8_t off;
7508 		case IPOPT_SSRR:
7509 		case IPOPT_LSRR:
7510 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7511 				ip1dbg(("ip_massage_options: bad src route\n"));
7512 				break;
7513 			}
7514 			optlen = opts.ipoptp_len;
7515 			off = opt[IPOPT_OFFSET];
7516 			off--;
7517 		redo_srr:
7518 			if (optlen < IP_ADDR_LEN ||
7519 			    off > optlen - IP_ADDR_LEN) {
7520 				/* End of source route */
7521 				ip1dbg(("ip_massage_options: end of SR\n"));
7522 				break;
7523 			}
7524 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7525 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7526 			    ntohl(dst)));
7527 			/*
7528 			 * Check if our address is present more than
7529 			 * once as consecutive hops in source route.
7530 			 * XXX verify per-interface ip_forwarding
7531 			 * for source route?
7532 			 */
7533 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7534 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7535 			if (ire != NULL) {
7536 				ire_refrele(ire);
7537 				off += IP_ADDR_LEN;
7538 				goto redo_srr;
7539 			}
7540 			if (dst == htonl(INADDR_LOOPBACK)) {
7541 				ip1dbg(("ip_massage_options: loopback addr in "
7542 				    "source route!\n"));
7543 				break;
7544 			}
7545 			/*
7546 			 * Update ipha_dst to be the first hop and remove the
7547 			 * first hop from the source route (by overwriting
7548 			 * part of the option with NOP options).
7549 			 */
7550 			ipha->ipha_dst = dst;
7551 			/* Put the last entry in dst */
7552 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7553 			    3;
7554 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7555 
7556 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7557 			    ntohl(dst)));
7558 			/* Move down and overwrite */
7559 			opt[IP_ADDR_LEN] = opt[0];
7560 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7561 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7562 			for (i = 0; i < IP_ADDR_LEN; i++)
7563 				opt[i] = IPOPT_NOP;
7564 			break;
7565 		}
7566 	}
7567 	return (dst);
7568 }
7569 
7570 /*
7571  * This function's job is to forward data to the reverse tunnel (FA->HA)
7572  * after doing a few checks. It is assumed that the incoming interface
7573  * of the packet is always different than the outgoing interface and the
7574  * ire_type of the found ire has to be a non-resolver type.
7575  *
7576  * IPQoS notes
7577  * IP policy is invoked twice for a forwarded packet, once on the read side
7578  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7579  * enabled.
7580  */
7581 static void
7582 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7583 {
7584 	ipha_t		*ipha;
7585 	queue_t		*q;
7586 	uint32_t 	pkt_len;
7587 #define	rptr    ((uchar_t *)ipha)
7588 	uint32_t 	sum;
7589 	uint32_t 	max_frag;
7590 	mblk_t		*first_mp;
7591 	uint32_t	ill_index;
7592 	ipxmit_state_t	pktxmit_state;
7593 	ill_t		*out_ill;
7594 	ip_stack_t	*ipst = in_ill->ill_ipst;
7595 
7596 	ASSERT(ire != NULL);
7597 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7598 	ASSERT(ire->ire_stq != NULL);
7599 
7600 	/* Initiate read side IPPF processing */
7601 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7602 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7603 		ip_process(IPP_FWD_IN, &mp, ill_index);
7604 		if (mp == NULL) {
7605 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7606 			    "dropped during IPPF processing\n"));
7607 			return;
7608 		}
7609 	}
7610 
7611 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7612 		ILLF_ROUTER) == 0) ||
7613 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7614 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7615 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7616 		    "forwarding is not turned on\n"));
7617 		goto drop_pkt;
7618 	}
7619 
7620 	/*
7621 	 * Don't forward if the interface is down
7622 	 */
7623 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7624 		goto discard_pkt;
7625 	}
7626 
7627 	ipha = (ipha_t *)mp->b_rptr;
7628 	pkt_len = ntohs(ipha->ipha_length);
7629 	/* Adjust the checksum to reflect the ttl decrement. */
7630 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7631 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7632 	if (ipha->ipha_ttl-- <= 1) {
7633 		if (ip_csum_hdr(ipha)) {
7634 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7635 			goto drop_pkt;
7636 		}
7637 		q = ire->ire_stq;
7638 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7639 		    BPRI_HI)) == NULL) {
7640 			goto discard_pkt;
7641 		}
7642 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7643 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7644 		/* Sent by forwarding path, and router is global zone */
7645 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7646 		    GLOBAL_ZONEID, ipst);
7647 		return;
7648 	}
7649 
7650 	/* Get the ill_index of the ILL */
7651 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7652 
7653 	/*
7654 	 * This location is chosen for the placement of the forwarding hook
7655 	 * because at this point we know that we have a path out for the
7656 	 * packet but haven't yet applied any logic (such as fragmenting)
7657 	 * that happen as part of transmitting the packet out.
7658 	 */
7659 	out_ill = ire->ire_ipif->ipif_ill;
7660 
7661 	DTRACE_PROBE4(ip4__forwarding__start,
7662 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7663 
7664 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7665 	    ipst->ips_ipv4firewall_forwarding,
7666 	    in_ill, out_ill, ipha, mp, mp, ipst);
7667 
7668 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7669 
7670 	if (mp == NULL)
7671 		return;
7672 	pkt_len = ntohs(ipha->ipha_length);
7673 
7674 	/*
7675 	 * ip_mrtun_forward is only used by foreign agent to reverse
7676 	 * tunnel the incoming packet. So it does not do any option
7677 	 * processing for source routing.
7678 	 */
7679 	max_frag = ire->ire_max_frag;
7680 	if (pkt_len > max_frag) {
7681 		/*
7682 		 * It needs fragging on its way out.  We haven't
7683 		 * verified the header checksum yet.  Since we
7684 		 * are going to put a surely good checksum in the
7685 		 * outgoing header, we have to make sure that it
7686 		 * was good coming in.
7687 		 */
7688 		if (ip_csum_hdr(ipha)) {
7689 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7690 			goto drop_pkt;
7691 		}
7692 
7693 		/* Initiate write side IPPF processing */
7694 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7695 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7696 			if (mp == NULL) {
7697 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7698 				    "dropped/deferred during ip policy "\
7699 				    "processing\n"));
7700 				return;
7701 			}
7702 		}
7703 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7704 		    BPRI_HI)) == NULL) {
7705 			goto discard_pkt;
7706 		}
7707 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7708 		mp = first_mp;
7709 
7710 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7711 		return;
7712 	}
7713 
7714 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7715 
7716 	ASSERT(ire->ire_ipif != NULL);
7717 
7718 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7719 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7720 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7721 	    ipst->ips_ipv4firewall_physical_out,
7722 	    NULL, out_ill, ipha, mp, mp, ipst);
7723 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7724 	if (mp == NULL)
7725 		return;
7726 
7727 	/* Now send the packet to the tunnel interface */
7728 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7729 	q = ire->ire_stq;
7730 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7731 	if ((pktxmit_state == SEND_FAILED) ||
7732 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7733 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7734 		    q->q_ptr));
7735 	}
7736 
7737 	return;
7738 discard_pkt:
7739 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7740 drop_pkt:;
7741 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7742 	freemsg(mp);
7743 #undef	rptr
7744 }
7745 
7746 /*
7747  * Fills the ipsec_out_t data structure with appropriate fields and
7748  * prepends it to mp which contains the IP hdr + data that was meant
7749  * to be forwarded. Please note that ipsec_out_info data structure
7750  * is used here to communicate the outgoing ill path at ip_wput()
7751  * for the ICMP error packet. This has nothing to do with ipsec IP
7752  * security. ipsec_out_t is really used to pass the info to the module
7753  * IP where this information cannot be extracted from conn.
7754  * This functions is called by ip_mrtun_forward().
7755  */
7756 void
7757 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7758 {
7759 	ipsec_out_t	*io;
7760 
7761 	ASSERT(xmit_ill != NULL);
7762 	first_mp->b_datap->db_type = M_CTL;
7763 	first_mp->b_wptr += sizeof (ipsec_info_t);
7764 	/*
7765 	 * This is to pass info to ip_wput in absence of conn.
7766 	 * ipsec_out_secure will be B_FALSE because of this.
7767 	 * Thus ipsec_out_secure being B_FALSE indicates that
7768 	 * this is not IPSEC security related information.
7769 	 */
7770 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7771 	io = (ipsec_out_t *)first_mp->b_rptr;
7772 	io->ipsec_out_type = IPSEC_OUT;
7773 	io->ipsec_out_len = sizeof (ipsec_out_t);
7774 	first_mp->b_cont = mp;
7775 	io->ipsec_out_ill_index =
7776 	    xmit_ill->ill_phyint->phyint_ifindex;
7777 	io->ipsec_out_xmit_if = B_TRUE;
7778 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7779 }
7780 
7781 /*
7782  * Return the network mask
7783  * associated with the specified address.
7784  */
7785 ipaddr_t
7786 ip_net_mask(ipaddr_t addr)
7787 {
7788 	uchar_t	*up = (uchar_t *)&addr;
7789 	ipaddr_t mask = 0;
7790 	uchar_t	*maskp = (uchar_t *)&mask;
7791 
7792 #if defined(__i386) || defined(__amd64)
7793 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7794 #endif
7795 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7796 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7797 #endif
7798 	if (CLASSD(addr)) {
7799 		maskp[0] = 0xF0;
7800 		return (mask);
7801 	}
7802 	if (addr == 0)
7803 		return (0);
7804 	maskp[0] = 0xFF;
7805 	if ((up[0] & 0x80) == 0)
7806 		return (mask);
7807 
7808 	maskp[1] = 0xFF;
7809 	if ((up[0] & 0xC0) == 0x80)
7810 		return (mask);
7811 
7812 	maskp[2] = 0xFF;
7813 	if ((up[0] & 0xE0) == 0xC0)
7814 		return (mask);
7815 
7816 	/* Must be experimental or multicast, indicate as much */
7817 	return ((ipaddr_t)0);
7818 }
7819 
7820 /*
7821  * Select an ill for the packet by considering load spreading across
7822  * a different ill in the group if dst_ill is part of some group.
7823  */
7824 ill_t *
7825 ip_newroute_get_dst_ill(ill_t *dst_ill)
7826 {
7827 	ill_t *ill;
7828 
7829 	/*
7830 	 * We schedule irrespective of whether the source address is
7831 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7832 	 */
7833 	ill = illgrp_scheduler(dst_ill);
7834 	if (ill == NULL)
7835 		return (NULL);
7836 
7837 	/*
7838 	 * For groups with names ip_sioctl_groupname ensures that all
7839 	 * ills are of same type. For groups without names, ifgrp_insert
7840 	 * ensures this.
7841 	 */
7842 	ASSERT(dst_ill->ill_type == ill->ill_type);
7843 
7844 	return (ill);
7845 }
7846 
7847 /*
7848  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7849  */
7850 ill_t *
7851 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7852     ip_stack_t *ipst)
7853 {
7854 	ill_t *ret_ill;
7855 
7856 	ASSERT(ifindex != 0);
7857 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7858 	    ipst);
7859 	if (ret_ill == NULL ||
7860 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7861 		if (isv6) {
7862 			if (ill != NULL) {
7863 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7864 			} else {
7865 				BUMP_MIB(&ipst->ips_ip6_mib,
7866 				    ipIfStatsOutDiscards);
7867 			}
7868 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7869 			    "bad ifindex %d.\n", ifindex));
7870 		} else {
7871 			if (ill != NULL) {
7872 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7873 			} else {
7874 				BUMP_MIB(&ipst->ips_ip_mib,
7875 				    ipIfStatsOutDiscards);
7876 			}
7877 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7878 			    "bad ifindex %d.\n", ifindex));
7879 		}
7880 		if (ret_ill != NULL)
7881 			ill_refrele(ret_ill);
7882 		freemsg(first_mp);
7883 		return (NULL);
7884 	}
7885 
7886 	return (ret_ill);
7887 }
7888 
7889 /*
7890  * IPv4 -
7891  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7892  * out a packet to a destination address for which we do not have specific
7893  * (or sufficient) routing information.
7894  *
7895  * NOTE : These are the scopes of some of the variables that point at IRE,
7896  *	  which needs to be followed while making any future modifications
7897  *	  to avoid memory leaks.
7898  *
7899  *	- ire and sire are the entries looked up initially by
7900  *	  ire_ftable_lookup.
7901  *	- ipif_ire is used to hold the interface ire associated with
7902  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7903  *	  it before branching out to error paths.
7904  *	- save_ire is initialized before ire_create, so that ire returned
7905  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7906  *	  before breaking out of the switch.
7907  *
7908  *	Thus on failures, we have to REFRELE only ire and sire, if they
7909  *	are not NULL.
7910  */
7911 void
7912 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7913     zoneid_t zoneid, ip_stack_t *ipst)
7914 {
7915 	areq_t	*areq;
7916 	ipaddr_t gw = 0;
7917 	ire_t	*ire = NULL;
7918 	mblk_t	*res_mp;
7919 	ipaddr_t *addrp;
7920 	ipaddr_t nexthop_addr;
7921 	ipif_t  *src_ipif = NULL;
7922 	ill_t	*dst_ill = NULL;
7923 	ipha_t  *ipha;
7924 	ire_t	*sire = NULL;
7925 	mblk_t	*first_mp;
7926 	ire_t	*save_ire;
7927 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7928 	ushort_t ire_marks = 0;
7929 	boolean_t mctl_present;
7930 	ipsec_out_t *io;
7931 	mblk_t	*saved_mp;
7932 	ire_t	*first_sire = NULL;
7933 	mblk_t	*copy_mp = NULL;
7934 	mblk_t	*xmit_mp = NULL;
7935 	ipaddr_t save_dst;
7936 	uint32_t multirt_flags =
7937 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7938 	boolean_t multirt_is_resolvable;
7939 	boolean_t multirt_resolve_next;
7940 	boolean_t do_attach_ill = B_FALSE;
7941 	boolean_t ip_nexthop = B_FALSE;
7942 	tsol_ire_gw_secattr_t *attrp = NULL;
7943 	tsol_gcgrp_t *gcgrp = NULL;
7944 	tsol_gcgrp_addr_t ga;
7945 
7946 	if (ip_debug > 2) {
7947 		/* ip1dbg */
7948 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7949 	}
7950 
7951 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7952 	if (mctl_present) {
7953 		io = (ipsec_out_t *)first_mp->b_rptr;
7954 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7955 		ASSERT(zoneid == io->ipsec_out_zoneid);
7956 		ASSERT(zoneid != ALL_ZONES);
7957 	}
7958 
7959 	ipha = (ipha_t *)mp->b_rptr;
7960 
7961 	/* All multicast lookups come through ip_newroute_ipif() */
7962 	if (CLASSD(dst)) {
7963 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7964 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7965 		freemsg(first_mp);
7966 		return;
7967 	}
7968 
7969 	if (mctl_present && io->ipsec_out_attach_if) {
7970 		/* ip_grab_attach_ill returns a held ill */
7971 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7972 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7973 
7974 		/* Failure case frees things for us. */
7975 		if (attach_ill == NULL)
7976 			return;
7977 
7978 		/*
7979 		 * Check if we need an ire that will not be
7980 		 * looked up by anybody else i.e. HIDDEN.
7981 		 */
7982 		if (ill_is_probeonly(attach_ill))
7983 			ire_marks = IRE_MARK_HIDDEN;
7984 	}
7985 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7986 		ip_nexthop = B_TRUE;
7987 		nexthop_addr = io->ipsec_out_nexthop_addr;
7988 	}
7989 	/*
7990 	 * If this IRE is created for forwarding or it is not for
7991 	 * traffic for congestion controlled protocols, mark it as temporary.
7992 	 */
7993 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7994 		ire_marks |= IRE_MARK_TEMPORARY;
7995 
7996 	/*
7997 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7998 	 * chain until it gets the most specific information available.
7999 	 * For example, we know that there is no IRE_CACHE for this dest,
8000 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
8001 	 * ire_ftable_lookup will look up the gateway, etc.
8002 	 * Check if in_ill != NULL. If it is true, the packet must be
8003 	 * from an incoming interface where RTA_SRCIFP is set.
8004 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8005 	 * to the destination, of equal netmask length in the forward table,
8006 	 * will be recursively explored. If no information is available
8007 	 * for the final gateway of that route, we force the returned ire
8008 	 * to be equal to sire using MATCH_IRE_PARENT.
8009 	 * At least, in this case we have a starting point (in the buckets)
8010 	 * to look for other routes to the destination in the forward table.
8011 	 * This is actually used only for multirouting, where a list
8012 	 * of routes has to be processed in sequence.
8013 	 *
8014 	 * In the process of coming up with the most specific information,
8015 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8016 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8017 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8018 	 * Two caveats when handling incomplete ire's in ip_newroute:
8019 	 * - we should be careful when accessing its ire_nce (specifically
8020 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8021 	 * - not all legacy code path callers are prepared to handle
8022 	 *   incomplete ire's, so we should not create/add incomplete
8023 	 *   ire_cache entries here. (See discussion about temporary solution
8024 	 *   further below).
8025 	 *
8026 	 * In order to minimize packet dropping, and to preserve existing
8027 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8028 	 * gateway, and instead use the IF_RESOLVER ire to send out
8029 	 * another request to ARP (this is achieved by passing the
8030 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8031 	 * arp response comes back in ip_wput_nondata, we will create
8032 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8033 	 *
8034 	 * Note that this is a temporary solution; the correct solution is
8035 	 * to create an incomplete  per-dst ire_cache entry, and send the
8036 	 * packet out when the gw's nce is resolved. In order to achieve this,
8037 	 * all packet processing must have been completed prior to calling
8038 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8039 	 * to be modified to accomodate this solution.
8040 	 */
8041 	if (in_ill != NULL) {
8042 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8043 		    in_ill, MATCH_IRE_TYPE);
8044 	} else if (ip_nexthop) {
8045 		/*
8046 		 * The first time we come here, we look for an IRE_INTERFACE
8047 		 * entry for the specified nexthop, set the dst to be the
8048 		 * nexthop address and create an IRE_CACHE entry for the
8049 		 * nexthop. The next time around, we are able to find an
8050 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8051 		 * nexthop address and create an IRE_CACHE entry for the
8052 		 * destination address via the specified nexthop.
8053 		 */
8054 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8055 		    MBLK_GETLABEL(mp), ipst);
8056 		if (ire != NULL) {
8057 			gw = nexthop_addr;
8058 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8059 		} else {
8060 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8061 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8062 			    MBLK_GETLABEL(mp),
8063 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8064 			    ipst);
8065 			if (ire != NULL) {
8066 				dst = nexthop_addr;
8067 			}
8068 		}
8069 	} else if (attach_ill == NULL) {
8070 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8071 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8072 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8073 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8074 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8075 		    ipst);
8076 	} else {
8077 		/*
8078 		 * attach_ill is set only for communicating with
8079 		 * on-link hosts. So, don't look for DEFAULT.
8080 		 */
8081 		ipif_t	*attach_ipif;
8082 
8083 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8084 		if (attach_ipif == NULL) {
8085 			ill_refrele(attach_ill);
8086 			goto icmp_err_ret;
8087 		}
8088 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8089 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8090 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8091 		    MATCH_IRE_SECATTR, ipst);
8092 		ipif_refrele(attach_ipif);
8093 	}
8094 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8095 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8096 
8097 	/*
8098 	 * This loop is run only once in most cases.
8099 	 * We loop to resolve further routes only when the destination
8100 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8101 	 */
8102 	do {
8103 		/* Clear the previous iteration's values */
8104 		if (src_ipif != NULL) {
8105 			ipif_refrele(src_ipif);
8106 			src_ipif = NULL;
8107 		}
8108 		if (dst_ill != NULL) {
8109 			ill_refrele(dst_ill);
8110 			dst_ill = NULL;
8111 		}
8112 
8113 		multirt_resolve_next = B_FALSE;
8114 		/*
8115 		 * We check if packets have to be multirouted.
8116 		 * In this case, given the current <ire, sire> couple,
8117 		 * we look for the next suitable <ire, sire>.
8118 		 * This check is done in ire_multirt_lookup(),
8119 		 * which applies various criteria to find the next route
8120 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8121 		 * unchanged if it detects it has not been tried yet.
8122 		 */
8123 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8124 			ip3dbg(("ip_newroute: starting next_resolution "
8125 			    "with first_mp %p, tag %d\n",
8126 			    (void *)first_mp,
8127 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8128 
8129 			ASSERT(sire != NULL);
8130 			multirt_is_resolvable =
8131 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8132 				MBLK_GETLABEL(mp), ipst);
8133 
8134 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8135 			    "ire %p, sire %p\n",
8136 			    multirt_is_resolvable,
8137 			    (void *)ire, (void *)sire));
8138 
8139 			if (!multirt_is_resolvable) {
8140 				/*
8141 				 * No more multirt route to resolve; give up
8142 				 * (all routes resolved or no more
8143 				 * resolvable routes).
8144 				 */
8145 				if (ire != NULL) {
8146 					ire_refrele(ire);
8147 					ire = NULL;
8148 				}
8149 			} else {
8150 				ASSERT(sire != NULL);
8151 				ASSERT(ire != NULL);
8152 				/*
8153 				 * We simply use first_sire as a flag that
8154 				 * indicates if a resolvable multirt route
8155 				 * has already been found.
8156 				 * If it is not the case, we may have to send
8157 				 * an ICMP error to report that the
8158 				 * destination is unreachable.
8159 				 * We do not IRE_REFHOLD first_sire.
8160 				 */
8161 				if (first_sire == NULL) {
8162 					first_sire = sire;
8163 				}
8164 			}
8165 		}
8166 		if (ire == NULL) {
8167 			if (ip_debug > 3) {
8168 				/* ip2dbg */
8169 				pr_addr_dbg("ip_newroute: "
8170 				    "can't resolve %s\n", AF_INET, &dst);
8171 			}
8172 			ip3dbg(("ip_newroute: "
8173 			    "ire %p, sire %p, first_sire %p\n",
8174 			    (void *)ire, (void *)sire, (void *)first_sire));
8175 
8176 			if (sire != NULL) {
8177 				ire_refrele(sire);
8178 				sire = NULL;
8179 			}
8180 
8181 			if (first_sire != NULL) {
8182 				/*
8183 				 * At least one multirt route has been found
8184 				 * in the same call to ip_newroute();
8185 				 * there is no need to report an ICMP error.
8186 				 * first_sire was not IRE_REFHOLDed.
8187 				 */
8188 				MULTIRT_DEBUG_UNTAG(first_mp);
8189 				freemsg(first_mp);
8190 				return;
8191 			}
8192 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8193 			    RTA_DST, ipst);
8194 			if (attach_ill != NULL)
8195 				ill_refrele(attach_ill);
8196 			goto icmp_err_ret;
8197 		}
8198 
8199 		/*
8200 		 * When RTA_SRCIFP is used to add a route, then an interface
8201 		 * route is added in the source interface's routing table.
8202 		 * If the outgoing interface of this route is of type
8203 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8204 		 * ire_nce->nce_res_mp is set to NULL.
8205 		 * Later, when this route is first used for forwarding
8206 		 * a packet, ip_newroute() is called
8207 		 * to resolve the hardware address of the outgoing ipif.
8208 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8209 		 * source interface based table. We only come here if the
8210 		 * outgoing interface is a resolver interface and we don't
8211 		 * have the ire_nce->nce_res_mp information yet.
8212 		 * If in_ill is not null that means it is called from
8213 		 * ip_rput.
8214 		 */
8215 
8216 		ASSERT(ire->ire_in_ill == NULL ||
8217 		    (ire->ire_type == IRE_IF_RESOLVER &&
8218 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8219 
8220 		/*
8221 		 * Verify that the returned IRE does not have either
8222 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8223 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8224 		 */
8225 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8226 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8227 			if (attach_ill != NULL)
8228 				ill_refrele(attach_ill);
8229 			goto icmp_err_ret;
8230 		}
8231 		/*
8232 		 * Increment the ire_ob_pkt_count field for ire if it is an
8233 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8234 		 * increment the same for the parent IRE, sire, if it is some
8235 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, HOST
8236 		 * and HOST_REDIRECT).
8237 		 */
8238 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8239 			UPDATE_OB_PKT_COUNT(ire);
8240 			ire->ire_last_used_time = lbolt;
8241 		}
8242 
8243 		if (sire != NULL) {
8244 			gw = sire->ire_gateway_addr;
8245 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8246 			    IRE_INTERFACE)) == 0);
8247 			UPDATE_OB_PKT_COUNT(sire);
8248 			sire->ire_last_used_time = lbolt;
8249 		}
8250 		/*
8251 		 * We have a route to reach the destination.
8252 		 *
8253 		 * 1) If the interface is part of ill group, try to get a new
8254 		 *    ill taking load spreading into account.
8255 		 *
8256 		 * 2) After selecting the ill, get a source address that
8257 		 *    might create good inbound load spreading.
8258 		 *    ipif_select_source does this for us.
8259 		 *
8260 		 * If the application specified the ill (ifindex), we still
8261 		 * load spread. Only if the packets needs to go out
8262 		 * specifically on a given ill e.g. binding to
8263 		 * IPIF_NOFAILOVER address, then we don't try to use a
8264 		 * different ill for load spreading.
8265 		 */
8266 		if (attach_ill == NULL) {
8267 			/*
8268 			 * Don't perform outbound load spreading in the
8269 			 * case of an RTF_MULTIRT route, as we actually
8270 			 * typically want to replicate outgoing packets
8271 			 * through particular interfaces.
8272 			 */
8273 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8274 				dst_ill = ire->ire_ipif->ipif_ill;
8275 				/* for uniformity */
8276 				ill_refhold(dst_ill);
8277 			} else {
8278 				/*
8279 				 * If we are here trying to create an IRE_CACHE
8280 				 * for an offlink destination and have the
8281 				 * IRE_CACHE for the next hop and the latter is
8282 				 * using virtual IP source address selection i.e
8283 				 * it's ire->ire_ipif is pointing to a virtual
8284 				 * network interface (vni) then
8285 				 * ip_newroute_get_dst_ll() will return the vni
8286 				 * interface as the dst_ill. Since the vni is
8287 				 * virtual i.e not associated with any physical
8288 				 * interface, it cannot be the dst_ill, hence
8289 				 * in such a case call ip_newroute_get_dst_ll()
8290 				 * with the stq_ill instead of the ire_ipif ILL.
8291 				 * The function returns a refheld ill.
8292 				 */
8293 				if ((ire->ire_type == IRE_CACHE) &&
8294 				    IS_VNI(ire->ire_ipif->ipif_ill))
8295 					dst_ill = ip_newroute_get_dst_ill(
8296 						ire->ire_stq->q_ptr);
8297 				else
8298 					dst_ill = ip_newroute_get_dst_ill(
8299 						ire->ire_ipif->ipif_ill);
8300 			}
8301 			if (dst_ill == NULL) {
8302 				if (ip_debug > 2) {
8303 					pr_addr_dbg("ip_newroute: "
8304 					    "no dst ill for dst"
8305 					    " %s\n", AF_INET, &dst);
8306 				}
8307 				goto icmp_err_ret;
8308 			}
8309 		} else {
8310 			dst_ill = ire->ire_ipif->ipif_ill;
8311 			/* for uniformity */
8312 			ill_refhold(dst_ill);
8313 			/*
8314 			 * We should have found a route matching ill as we
8315 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8316 			 * Rather than asserting, when there is a mismatch,
8317 			 * we just drop the packet.
8318 			 */
8319 			if (dst_ill != attach_ill) {
8320 				ip0dbg(("ip_newroute: Packet dropped as "
8321 				    "IPIF_NOFAILOVER ill is %s, "
8322 				    "ire->ire_ipif->ipif_ill is %s\n",
8323 				    attach_ill->ill_name,
8324 				    dst_ill->ill_name));
8325 				ill_refrele(attach_ill);
8326 				goto icmp_err_ret;
8327 			}
8328 		}
8329 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8330 		if (attach_ill != NULL) {
8331 			ill_refrele(attach_ill);
8332 			attach_ill = NULL;
8333 			do_attach_ill = B_TRUE;
8334 		}
8335 		ASSERT(dst_ill != NULL);
8336 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8337 
8338 		/*
8339 		 * Pick the best source address from dst_ill.
8340 		 *
8341 		 * 1) If it is part of a multipathing group, we would
8342 		 *    like to spread the inbound packets across different
8343 		 *    interfaces. ipif_select_source picks a random source
8344 		 *    across the different ills in the group.
8345 		 *
8346 		 * 2) If it is not part of a multipathing group, we try
8347 		 *    to pick the source address from the destination
8348 		 *    route. Clustering assumes that when we have multiple
8349 		 *    prefixes hosted on an interface, the prefix of the
8350 		 *    source address matches the prefix of the destination
8351 		 *    route. We do this only if the address is not
8352 		 *    DEPRECATED.
8353 		 *
8354 		 * 3) If the conn is in a different zone than the ire, we
8355 		 *    need to pick a source address from the right zone.
8356 		 *
8357 		 * NOTE : If we hit case (1) above, the prefix of the source
8358 		 *	  address picked may not match the prefix of the
8359 		 *	  destination routes prefix as ipif_select_source
8360 		 *	  does not look at "dst" while picking a source
8361 		 *	  address.
8362 		 *	  If we want the same behavior as (2), we will need
8363 		 *	  to change the behavior of ipif_select_source.
8364 		 */
8365 		ASSERT(src_ipif == NULL);
8366 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8367 			/*
8368 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8369 			 * Check that the ipif matching the requested source
8370 			 * address still exists.
8371 			 */
8372 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8373 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8374 		}
8375 		if (src_ipif == NULL) {
8376 			ire_marks |= IRE_MARK_USESRC_CHECK;
8377 			if ((dst_ill->ill_group != NULL) ||
8378 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8379 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8380 			    ire->ire_zoneid != ALL_ZONES) ||
8381 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8382 				/*
8383 				 * If the destination is reachable via a
8384 				 * given gateway, the selected source address
8385 				 * should be in the same subnet as the gateway.
8386 				 * Otherwise, the destination is not reachable.
8387 				 *
8388 				 * If there are no interfaces on the same subnet
8389 				 * as the destination, ipif_select_source gives
8390 				 * first non-deprecated interface which might be
8391 				 * on a different subnet than the gateway.
8392 				 * This is not desirable. Hence pass the dst_ire
8393 				 * source address to ipif_select_source.
8394 				 * It is sure that the destination is reachable
8395 				 * with the dst_ire source address subnet.
8396 				 * So passing dst_ire source address to
8397 				 * ipif_select_source will make sure that the
8398 				 * selected source will be on the same subnet
8399 				 * as dst_ire source address.
8400 				 */
8401 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8402 				src_ipif = ipif_select_source(dst_ill, saddr,
8403 				    zoneid);
8404 				if (src_ipif == NULL) {
8405 					if (ip_debug > 2) {
8406 						pr_addr_dbg("ip_newroute: "
8407 						    "no src for dst %s ",
8408 						    AF_INET, &dst);
8409 						printf("through interface %s\n",
8410 						    dst_ill->ill_name);
8411 					}
8412 					goto icmp_err_ret;
8413 				}
8414 			} else {
8415 				src_ipif = ire->ire_ipif;
8416 				ASSERT(src_ipif != NULL);
8417 				/* hold src_ipif for uniformity */
8418 				ipif_refhold(src_ipif);
8419 			}
8420 		}
8421 
8422 		/*
8423 		 * Assign a source address while we have the conn.
8424 		 * We can't have ip_wput_ire pick a source address when the
8425 		 * packet returns from arp since we need to look at
8426 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8427 		 * going through arp.
8428 		 *
8429 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8430 		 *	  it uses ip6i to store this information.
8431 		 */
8432 		if (ipha->ipha_src == INADDR_ANY &&
8433 		    (connp == NULL || !connp->conn_unspec_src)) {
8434 			ipha->ipha_src = src_ipif->ipif_src_addr;
8435 		}
8436 		if (ip_debug > 3) {
8437 			/* ip2dbg */
8438 			pr_addr_dbg("ip_newroute: first hop %s\n",
8439 			    AF_INET, &gw);
8440 		}
8441 		ip2dbg(("\tire type %s (%d)\n",
8442 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8443 
8444 		/*
8445 		 * The TTL of multirouted packets is bounded by the
8446 		 * ip_multirt_ttl ndd variable.
8447 		 */
8448 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8449 			/* Force TTL of multirouted packets */
8450 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8451 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8452 				ip2dbg(("ip_newroute: forcing multirt TTL "
8453 				    "to %d (was %d), dst 0x%08x\n",
8454 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8455 				    ntohl(sire->ire_addr)));
8456 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8457 			}
8458 		}
8459 		/*
8460 		 * At this point in ip_newroute(), ire is either the
8461 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8462 		 * destination or an IRE_INTERFACE type that should be used
8463 		 * to resolve an on-subnet destination or an on-subnet
8464 		 * next-hop gateway.
8465 		 *
8466 		 * In the IRE_CACHE case, we have the following :
8467 		 *
8468 		 * 1) src_ipif - used for getting a source address.
8469 		 *
8470 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8471 		 *    means packets using this IRE_CACHE will go out on
8472 		 *    dst_ill.
8473 		 *
8474 		 * 3) The IRE sire will point to the prefix that is the
8475 		 *    longest  matching route for the destination. These
8476 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8477 		 *
8478 		 *    The newly created IRE_CACHE entry for the off-subnet
8479 		 *    destination is tied to both the prefix route and the
8480 		 *    interface route used to resolve the next-hop gateway
8481 		 *    via the ire_phandle and ire_ihandle fields,
8482 		 *    respectively.
8483 		 *
8484 		 * In the IRE_INTERFACE case, we have the following :
8485 		 *
8486 		 * 1) src_ipif - used for getting a source address.
8487 		 *
8488 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8489 		 *    means packets using the IRE_CACHE that we will build
8490 		 *    here will go out on dst_ill.
8491 		 *
8492 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8493 		 *    to be created will only be tied to the IRE_INTERFACE
8494 		 *    that was derived from the ire_ihandle field.
8495 		 *
8496 		 *    If sire is non-NULL, it means the destination is
8497 		 *    off-link and we will first create the IRE_CACHE for the
8498 		 *    gateway. Next time through ip_newroute, we will create
8499 		 *    the IRE_CACHE for the final destination as described
8500 		 *    above.
8501 		 *
8502 		 * In both cases, after the current resolution has been
8503 		 * completed (or possibly initialised, in the IRE_INTERFACE
8504 		 * case), the loop may be re-entered to attempt the resolution
8505 		 * of another RTF_MULTIRT route.
8506 		 *
8507 		 * When an IRE_CACHE entry for the off-subnet destination is
8508 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8509 		 * for further processing in emission loops.
8510 		 */
8511 		save_ire = ire;
8512 		switch (ire->ire_type) {
8513 		case IRE_CACHE: {
8514 			ire_t	*ipif_ire;
8515 			mblk_t	*ire_fp_mp;
8516 
8517 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8518 			if (gw == 0)
8519 				gw = ire->ire_gateway_addr;
8520 			/*
8521 			 * We need 3 ire's to create a new cache ire for an
8522 			 * off-link destination from the cache ire of the
8523 			 * gateway.
8524 			 *
8525 			 *	1. The prefix ire 'sire' (Note that this does
8526 			 *	   not apply to the conn_nexthop_set case)
8527 			 *	2. The cache ire of the gateway 'ire'
8528 			 *	3. The interface ire 'ipif_ire'
8529 			 *
8530 			 * We have (1) and (2). We lookup (3) below.
8531 			 *
8532 			 * If there is no interface route to the gateway,
8533 			 * it is a race condition, where we found the cache
8534 			 * but the interface route has been deleted.
8535 			 */
8536 			if (ip_nexthop) {
8537 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8538 			} else {
8539 				ipif_ire =
8540 				    ire_ihandle_lookup_offlink(ire, sire);
8541 			}
8542 			if (ipif_ire == NULL) {
8543 				ip1dbg(("ip_newroute: "
8544 				    "ire_ihandle_lookup_offlink failed\n"));
8545 				goto icmp_err_ret;
8546 			}
8547 			/*
8548 			 * XXX We are using the same res_mp
8549 			 * (DL_UNITDATA_REQ) though the save_ire is not
8550 			 * pointing at the same ill.
8551 			 * This is incorrect. We need to send it up to the
8552 			 * resolver to get the right res_mp. For ethernets
8553 			 * this may be okay (ill_type == DL_ETHER).
8554 			 */
8555 			res_mp = save_ire->ire_nce->nce_res_mp;
8556 			ire_fp_mp = NULL;
8557 
8558 			/*
8559 			 * Check cached gateway IRE for any security
8560 			 * attributes; if found, associate the gateway
8561 			 * credentials group to the destination IRE.
8562 			 */
8563 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8564 				mutex_enter(&attrp->igsa_lock);
8565 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8566 					GCGRP_REFHOLD(gcgrp);
8567 				mutex_exit(&attrp->igsa_lock);
8568 			}
8569 
8570 			ire = ire_create(
8571 			    (uchar_t *)&dst,		/* dest address */
8572 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8573 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8574 			    (uchar_t *)&gw,		/* gateway address */
8575 			    NULL,
8576 			    &save_ire->ire_max_frag,
8577 			    ire_fp_mp,			/* Fast Path header */
8578 			    dst_ill->ill_rq,		/* recv-from queue */
8579 			    dst_ill->ill_wq,		/* send-to queue */
8580 			    IRE_CACHE,			/* IRE type */
8581 			    res_mp,
8582 			    src_ipif,
8583 			    in_ill,			/* incoming ill */
8584 			    (sire != NULL) ?
8585 				sire->ire_mask : 0, 	/* Parent mask */
8586 			    (sire != NULL) ?
8587 				sire->ire_phandle : 0,  /* Parent handle */
8588 			    ipif_ire->ire_ihandle,	/* Interface handle */
8589 			    (sire != NULL) ? (sire->ire_flags &
8590 				(RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8591 			    (sire != NULL) ?
8592 				&(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8593 			    NULL,
8594 			    gcgrp,
8595 			    ipst);
8596 
8597 			if (ire == NULL) {
8598 				if (gcgrp != NULL) {
8599 					GCGRP_REFRELE(gcgrp);
8600 					gcgrp = NULL;
8601 				}
8602 				ire_refrele(ipif_ire);
8603 				ire_refrele(save_ire);
8604 				break;
8605 			}
8606 
8607 			/* reference now held by IRE */
8608 			gcgrp = NULL;
8609 
8610 			ire->ire_marks |= ire_marks;
8611 
8612 			/*
8613 			 * Prevent sire and ipif_ire from getting deleted.
8614 			 * The newly created ire is tied to both of them via
8615 			 * the phandle and ihandle respectively.
8616 			 */
8617 			if (sire != NULL) {
8618 				IRB_REFHOLD(sire->ire_bucket);
8619 				/* Has it been removed already ? */
8620 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8621 					IRB_REFRELE(sire->ire_bucket);
8622 					ire_refrele(ipif_ire);
8623 					ire_refrele(save_ire);
8624 					break;
8625 				}
8626 			}
8627 
8628 			IRB_REFHOLD(ipif_ire->ire_bucket);
8629 			/* Has it been removed already ? */
8630 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8631 				IRB_REFRELE(ipif_ire->ire_bucket);
8632 				if (sire != NULL)
8633 					IRB_REFRELE(sire->ire_bucket);
8634 				ire_refrele(ipif_ire);
8635 				ire_refrele(save_ire);
8636 				break;
8637 			}
8638 
8639 			xmit_mp = first_mp;
8640 			/*
8641 			 * In the case of multirouting, a copy
8642 			 * of the packet is done before its sending.
8643 			 * The copy is used to attempt another
8644 			 * route resolution, in a next loop.
8645 			 */
8646 			if (ire->ire_flags & RTF_MULTIRT) {
8647 				copy_mp = copymsg(first_mp);
8648 				if (copy_mp != NULL) {
8649 					xmit_mp = copy_mp;
8650 					MULTIRT_DEBUG_TAG(first_mp);
8651 				}
8652 			}
8653 			ire_add_then_send(q, ire, xmit_mp);
8654 			ire_refrele(save_ire);
8655 
8656 			/* Assert that sire is not deleted yet. */
8657 			if (sire != NULL) {
8658 				ASSERT(sire->ire_ptpn != NULL);
8659 				IRB_REFRELE(sire->ire_bucket);
8660 			}
8661 
8662 			/* Assert that ipif_ire is not deleted yet. */
8663 			ASSERT(ipif_ire->ire_ptpn != NULL);
8664 			IRB_REFRELE(ipif_ire->ire_bucket);
8665 			ire_refrele(ipif_ire);
8666 
8667 			/*
8668 			 * If copy_mp is not NULL, multirouting was
8669 			 * requested. We loop to initiate a next
8670 			 * route resolution attempt, starting from sire.
8671 			 */
8672 			if (copy_mp != NULL) {
8673 				/*
8674 				 * Search for the next unresolved
8675 				 * multirt route.
8676 				 */
8677 				copy_mp = NULL;
8678 				ipif_ire = NULL;
8679 				ire = NULL;
8680 				multirt_resolve_next = B_TRUE;
8681 				continue;
8682 			}
8683 			if (sire != NULL)
8684 				ire_refrele(sire);
8685 			ipif_refrele(src_ipif);
8686 			ill_refrele(dst_ill);
8687 			return;
8688 		}
8689 		case IRE_IF_NORESOLVER: {
8690 			/*
8691 			 * We have what we need to build an IRE_CACHE.
8692 			 *
8693 			 * Create a new res_mp with the IP gateway address
8694 			 * in destination address in the DLPI hdr if the
8695 			 * physical length is exactly 4 bytes.
8696 			 */
8697 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8698 				uchar_t *addr;
8699 
8700 				if (gw)
8701 					addr = (uchar_t *)&gw;
8702 				else
8703 					addr = (uchar_t *)&dst;
8704 
8705 				res_mp = ill_dlur_gen(addr,
8706 				    dst_ill->ill_phys_addr_length,
8707 				    dst_ill->ill_sap,
8708 				    dst_ill->ill_sap_length);
8709 
8710 				if (res_mp == NULL) {
8711 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8712 					break;
8713 				}
8714 			} else if (dst_ill->ill_resolver_mp == NULL) {
8715 				ip1dbg(("ip_newroute: dst_ill %p "
8716 				    "for IF_NORESOLV ire %p has "
8717 				    "no ill_resolver_mp\n",
8718 				    (void *)dst_ill, (void *)ire));
8719 				break;
8720 			} else {
8721 				res_mp = NULL;
8722 			}
8723 
8724 			/*
8725 			 * TSol note: We are creating the ire cache for the
8726 			 * destination 'dst'. If 'dst' is offlink, going
8727 			 * through the first hop 'gw', the security attributes
8728 			 * of 'dst' must be set to point to the gateway
8729 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8730 			 * is possible that 'dst' is a potential gateway that is
8731 			 * referenced by some route that has some security
8732 			 * attributes. Thus in the former case, we need to do a
8733 			 * gcgrp_lookup of 'gw' while in the latter case we
8734 			 * need to do gcgrp_lookup of 'dst' itself.
8735 			 */
8736 			ga.ga_af = AF_INET;
8737 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8738 			    &ga.ga_addr);
8739 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8740 
8741 			ire = ire_create(
8742 			    (uchar_t *)&dst,		/* dest address */
8743 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8744 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8745 			    (uchar_t *)&gw,		/* gateway address */
8746 			    NULL,
8747 			    &save_ire->ire_max_frag,
8748 			    NULL,			/* Fast Path header */
8749 			    dst_ill->ill_rq,		/* recv-from queue */
8750 			    dst_ill->ill_wq,		/* send-to queue */
8751 			    IRE_CACHE,
8752 			    res_mp,
8753 			    src_ipif,
8754 			    in_ill,			/* Incoming ill */
8755 			    save_ire->ire_mask,		/* Parent mask */
8756 			    (sire != NULL) ?		/* Parent handle */
8757 				sire->ire_phandle : 0,
8758 			    save_ire->ire_ihandle,	/* Interface handle */
8759 			    (sire != NULL) ? sire->ire_flags &
8760 				(RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8761 			    &(save_ire->ire_uinfo),
8762 			    NULL,
8763 			    gcgrp,
8764 			    ipst);
8765 
8766 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8767 				freeb(res_mp);
8768 
8769 			if (ire == NULL) {
8770 				if (gcgrp != NULL) {
8771 					GCGRP_REFRELE(gcgrp);
8772 					gcgrp = NULL;
8773 				}
8774 				ire_refrele(save_ire);
8775 				break;
8776 			}
8777 
8778 			/* reference now held by IRE */
8779 			gcgrp = NULL;
8780 
8781 			ire->ire_marks |= ire_marks;
8782 
8783 			/* Prevent save_ire from getting deleted */
8784 			IRB_REFHOLD(save_ire->ire_bucket);
8785 			/* Has it been removed already ? */
8786 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8787 				IRB_REFRELE(save_ire->ire_bucket);
8788 				ire_refrele(save_ire);
8789 				break;
8790 			}
8791 
8792 			/*
8793 			 * In the case of multirouting, a copy
8794 			 * of the packet is made before it is sent.
8795 			 * The copy is used in the next
8796 			 * loop to attempt another resolution.
8797 			 */
8798 			xmit_mp = first_mp;
8799 			if ((sire != NULL) &&
8800 			    (sire->ire_flags & RTF_MULTIRT)) {
8801 				copy_mp = copymsg(first_mp);
8802 				if (copy_mp != NULL) {
8803 					xmit_mp = copy_mp;
8804 					MULTIRT_DEBUG_TAG(first_mp);
8805 				}
8806 			}
8807 			ire_add_then_send(q, ire, xmit_mp);
8808 
8809 			/* Assert that it is not deleted yet. */
8810 			ASSERT(save_ire->ire_ptpn != NULL);
8811 			IRB_REFRELE(save_ire->ire_bucket);
8812 			ire_refrele(save_ire);
8813 
8814 			if (copy_mp != NULL) {
8815 				/*
8816 				 * If we found a (no)resolver, we ignore any
8817 				 * trailing top priority IRE_CACHE in further
8818 				 * loops. This ensures that we do not omit any
8819 				 * (no)resolver.
8820 				 * This IRE_CACHE, if any, will be processed
8821 				 * by another thread entering ip_newroute().
8822 				 * IRE_CACHE entries, if any, will be processed
8823 				 * by another thread entering ip_newroute(),
8824 				 * (upon resolver response, for instance).
8825 				 * This aims to force parallel multirt
8826 				 * resolutions as soon as a packet must be sent.
8827 				 * In the best case, after the tx of only one
8828 				 * packet, all reachable routes are resolved.
8829 				 * Otherwise, the resolution of all RTF_MULTIRT
8830 				 * routes would require several emissions.
8831 				 */
8832 				multirt_flags &= ~MULTIRT_CACHEGW;
8833 
8834 				/*
8835 				 * Search for the next unresolved multirt
8836 				 * route.
8837 				 */
8838 				copy_mp = NULL;
8839 				save_ire = NULL;
8840 				ire = NULL;
8841 				multirt_resolve_next = B_TRUE;
8842 				continue;
8843 			}
8844 
8845 			/*
8846 			 * Don't need sire anymore
8847 			 */
8848 			if (sire != NULL)
8849 				ire_refrele(sire);
8850 
8851 			ipif_refrele(src_ipif);
8852 			ill_refrele(dst_ill);
8853 			return;
8854 		}
8855 		case IRE_IF_RESOLVER:
8856 			/*
8857 			 * We can't build an IRE_CACHE yet, but at least we
8858 			 * found a resolver that can help.
8859 			 */
8860 			res_mp = dst_ill->ill_resolver_mp;
8861 			if (!OK_RESOLVER_MP(res_mp))
8862 				break;
8863 
8864 			/*
8865 			 * To be at this point in the code with a non-zero gw
8866 			 * means that dst is reachable through a gateway that
8867 			 * we have never resolved.  By changing dst to the gw
8868 			 * addr we resolve the gateway first.
8869 			 * When ire_add_then_send() tries to put the IP dg
8870 			 * to dst, it will reenter ip_newroute() at which
8871 			 * time we will find the IRE_CACHE for the gw and
8872 			 * create another IRE_CACHE in case IRE_CACHE above.
8873 			 */
8874 			if (gw != INADDR_ANY) {
8875 				/*
8876 				 * The source ipif that was determined above was
8877 				 * relative to the destination address, not the
8878 				 * gateway's. If src_ipif was not taken out of
8879 				 * the IRE_IF_RESOLVER entry, we'll need to call
8880 				 * ipif_select_source() again.
8881 				 */
8882 				if (src_ipif != ire->ire_ipif) {
8883 					ipif_refrele(src_ipif);
8884 					src_ipif = ipif_select_source(dst_ill,
8885 					    gw, zoneid);
8886 					if (src_ipif == NULL) {
8887 						if (ip_debug > 2) {
8888 							pr_addr_dbg(
8889 							    "ip_newroute: no "
8890 							    "src for gw %s ",
8891 							    AF_INET, &gw);
8892 							printf("through "
8893 							    "interface %s\n",
8894 							    dst_ill->ill_name);
8895 						}
8896 						goto icmp_err_ret;
8897 					}
8898 				}
8899 				save_dst = dst;
8900 				dst = gw;
8901 				gw = INADDR_ANY;
8902 			}
8903 
8904 			/*
8905 			 * We obtain a partial IRE_CACHE which we will pass
8906 			 * along with the resolver query.  When the response
8907 			 * comes back it will be there ready for us to add.
8908 			 * The ire_max_frag is atomically set under the
8909 			 * irebucket lock in ire_add_v[46].
8910 			 */
8911 
8912 			ire = ire_create_mp(
8913 			    (uchar_t *)&dst,		/* dest address */
8914 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8915 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8916 			    (uchar_t *)&gw,		/* gateway address */
8917 			    NULL,			/* no in_src_addr */
8918 			    NULL,			/* ire_max_frag */
8919 			    NULL,			/* Fast Path header */
8920 			    dst_ill->ill_rq,		/* recv-from queue */
8921 			    dst_ill->ill_wq,		/* send-to queue */
8922 			    IRE_CACHE,
8923 			    NULL,
8924 			    src_ipif,			/* Interface ipif */
8925 			    in_ill,			/* Incoming ILL */
8926 			    save_ire->ire_mask,		/* Parent mask */
8927 			    0,
8928 			    save_ire->ire_ihandle,	/* Interface handle */
8929 			    0,				/* flags if any */
8930 			    &(save_ire->ire_uinfo),
8931 			    NULL,
8932 			    NULL,
8933 			    ipst);
8934 
8935 			if (ire == NULL) {
8936 				ire_refrele(save_ire);
8937 				break;
8938 			}
8939 
8940 			if ((sire != NULL) &&
8941 			    (sire->ire_flags & RTF_MULTIRT)) {
8942 				copy_mp = copymsg(first_mp);
8943 				if (copy_mp != NULL)
8944 					MULTIRT_DEBUG_TAG(copy_mp);
8945 			}
8946 
8947 			ire->ire_marks |= ire_marks;
8948 
8949 			/*
8950 			 * Construct message chain for the resolver
8951 			 * of the form:
8952 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8953 			 * Packet could contain a IPSEC_OUT mp.
8954 			 *
8955 			 * NOTE : ire will be added later when the response
8956 			 * comes back from ARP. If the response does not
8957 			 * come back, ARP frees the packet. For this reason,
8958 			 * we can't REFHOLD the bucket of save_ire to prevent
8959 			 * deletions. We may not be able to REFRELE the bucket
8960 			 * if the response never comes back. Thus, before
8961 			 * adding the ire, ire_add_v4 will make sure that the
8962 			 * interface route does not get deleted. This is the
8963 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8964 			 * where we can always prevent deletions because of
8965 			 * the synchronous nature of adding IRES i.e
8966 			 * ire_add_then_send is called after creating the IRE.
8967 			 */
8968 			ASSERT(ire->ire_mp != NULL);
8969 			ire->ire_mp->b_cont = first_mp;
8970 			/* Have saved_mp handy, for cleanup if canput fails */
8971 			saved_mp = mp;
8972 			mp = copyb(res_mp);
8973 			if (mp == NULL) {
8974 				/* Prepare for cleanup */
8975 				mp = saved_mp; /* pkt */
8976 				ire_delete(ire); /* ire_mp */
8977 				ire = NULL;
8978 				ire_refrele(save_ire);
8979 				if (copy_mp != NULL) {
8980 					MULTIRT_DEBUG_UNTAG(copy_mp);
8981 					freemsg(copy_mp);
8982 					copy_mp = NULL;
8983 				}
8984 				break;
8985 			}
8986 			linkb(mp, ire->ire_mp);
8987 
8988 			/*
8989 			 * Fill in the source and dest addrs for the resolver.
8990 			 * NOTE: this depends on memory layouts imposed by
8991 			 * ill_init().
8992 			 */
8993 			areq = (areq_t *)mp->b_rptr;
8994 			addrp = (ipaddr_t *)((char *)areq +
8995 			    areq->areq_sender_addr_offset);
8996 			if (do_attach_ill) {
8997 				/*
8998 				 * This is bind to no failover case.
8999 				 * arp packet also must go out on attach_ill.
9000 				 */
9001 				ASSERT(ipha->ipha_src != NULL);
9002 				*addrp = ipha->ipha_src;
9003 			} else {
9004 				*addrp = save_ire->ire_src_addr;
9005 			}
9006 
9007 			ire_refrele(save_ire);
9008 			addrp = (ipaddr_t *)((char *)areq +
9009 			    areq->areq_target_addr_offset);
9010 			*addrp = dst;
9011 			/* Up to the resolver. */
9012 			if (canputnext(dst_ill->ill_rq) &&
9013 			    !(dst_ill->ill_arp_closing)) {
9014 				putnext(dst_ill->ill_rq, mp);
9015 				ire = NULL;
9016 				if (copy_mp != NULL) {
9017 					/*
9018 					 * If we found a resolver, we ignore
9019 					 * any trailing top priority IRE_CACHE
9020 					 * in the further loops. This ensures
9021 					 * that we do not omit any resolver.
9022 					 * IRE_CACHE entries, if any, will be
9023 					 * processed next time we enter
9024 					 * ip_newroute().
9025 					 */
9026 					multirt_flags &= ~MULTIRT_CACHEGW;
9027 					/*
9028 					 * Search for the next unresolved
9029 					 * multirt route.
9030 					 */
9031 					first_mp = copy_mp;
9032 					copy_mp = NULL;
9033 					/* Prepare the next resolution loop. */
9034 					mp = first_mp;
9035 					EXTRACT_PKT_MP(mp, first_mp,
9036 					    mctl_present);
9037 					if (mctl_present)
9038 						io = (ipsec_out_t *)
9039 						    first_mp->b_rptr;
9040 					ipha = (ipha_t *)mp->b_rptr;
9041 
9042 					ASSERT(sire != NULL);
9043 
9044 					dst = save_dst;
9045 					multirt_resolve_next = B_TRUE;
9046 					continue;
9047 				}
9048 
9049 				if (sire != NULL)
9050 					ire_refrele(sire);
9051 
9052 				/*
9053 				 * The response will come back in ip_wput
9054 				 * with db_type IRE_DB_TYPE.
9055 				 */
9056 				ipif_refrele(src_ipif);
9057 				ill_refrele(dst_ill);
9058 				return;
9059 			} else {
9060 				/* Prepare for cleanup */
9061 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9062 				    mp);
9063 				mp->b_cont = NULL;
9064 				freeb(mp); /* areq */
9065 				/*
9066 				 * this is an ire that is not added to the
9067 				 * cache. ire_freemblk will handle the release
9068 				 * of any resources associated with the ire.
9069 				 */
9070 				ire_delete(ire); /* ire_mp */
9071 				mp = saved_mp; /* pkt */
9072 				ire = NULL;
9073 				if (copy_mp != NULL) {
9074 					MULTIRT_DEBUG_UNTAG(copy_mp);
9075 					freemsg(copy_mp);
9076 					copy_mp = NULL;
9077 				}
9078 				break;
9079 			}
9080 		default:
9081 			break;
9082 		}
9083 	} while (multirt_resolve_next);
9084 
9085 	ip1dbg(("ip_newroute: dropped\n"));
9086 	/* Did this packet originate externally? */
9087 	if (mp->b_prev) {
9088 		mp->b_next = NULL;
9089 		mp->b_prev = NULL;
9090 		if (in_ill != NULL) {
9091 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9092 		} else {
9093 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9094 		}
9095 	} else {
9096 		if (dst_ill != NULL) {
9097 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9098 		} else {
9099 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9100 		}
9101 	}
9102 	ASSERT(copy_mp == NULL);
9103 	MULTIRT_DEBUG_UNTAG(first_mp);
9104 	freemsg(first_mp);
9105 	if (ire != NULL)
9106 		ire_refrele(ire);
9107 	if (sire != NULL)
9108 		ire_refrele(sire);
9109 	if (src_ipif != NULL)
9110 		ipif_refrele(src_ipif);
9111 	if (dst_ill != NULL)
9112 		ill_refrele(dst_ill);
9113 	return;
9114 
9115 icmp_err_ret:
9116 	ip1dbg(("ip_newroute: no route\n"));
9117 	if (src_ipif != NULL)
9118 		ipif_refrele(src_ipif);
9119 	if (dst_ill != NULL)
9120 		ill_refrele(dst_ill);
9121 	if (sire != NULL)
9122 		ire_refrele(sire);
9123 	/* Did this packet originate externally? */
9124 	if (mp->b_prev) {
9125 		mp->b_next = NULL;
9126 		mp->b_prev = NULL;
9127 		if (in_ill != NULL) {
9128 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9129 		} else {
9130 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9131 		}
9132 		q = WR(q);
9133 	} else {
9134 		/*
9135 		 * There is no outgoing ill, so just increment the
9136 		 * system MIB.
9137 		 */
9138 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9139 		/*
9140 		 * Since ip_wput() isn't close to finished, we fill
9141 		 * in enough of the header for credible error reporting.
9142 		 */
9143 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9144 			/* Failed */
9145 			MULTIRT_DEBUG_UNTAG(first_mp);
9146 			freemsg(first_mp);
9147 			if (ire != NULL)
9148 				ire_refrele(ire);
9149 			return;
9150 		}
9151 	}
9152 
9153 	/*
9154 	 * At this point we will have ire only if RTF_BLACKHOLE
9155 	 * or RTF_REJECT flags are set on the IRE. It will not
9156 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9157 	 */
9158 	if (ire != NULL) {
9159 		if (ire->ire_flags & RTF_BLACKHOLE) {
9160 			ire_refrele(ire);
9161 			MULTIRT_DEBUG_UNTAG(first_mp);
9162 			freemsg(first_mp);
9163 			return;
9164 		}
9165 		ire_refrele(ire);
9166 	}
9167 	if (ip_source_routed(ipha, ipst)) {
9168 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9169 		    zoneid, ipst);
9170 		return;
9171 	}
9172 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9173 }
9174 
9175 ip_opt_info_t zero_info;
9176 
9177 /*
9178  * IPv4 -
9179  * ip_newroute_ipif is called by ip_wput_multicast and
9180  * ip_rput_forward_multicast whenever we need to send
9181  * out a packet to a destination address for which we do not have specific
9182  * routing information. It is used when the packet will be sent out
9183  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9184  * socket option is set or icmp error message wants to go out on a particular
9185  * interface for a unicast packet.
9186  *
9187  * In most cases, the destination address is resolved thanks to the ipif
9188  * intrinsic resolver. However, there are some cases where the call to
9189  * ip_newroute_ipif must take into account the potential presence of
9190  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9191  * that uses the interface. This is specified through flags,
9192  * which can be a combination of:
9193  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9194  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9195  *   and flags. Additionally, the packet source address has to be set to
9196  *   the specified address. The caller is thus expected to set this flag
9197  *   if the packet has no specific source address yet.
9198  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9199  *   flag, the resulting ire will inherit the flag. All unresolved routes
9200  *   to the destination must be explored in the same call to
9201  *   ip_newroute_ipif().
9202  */
9203 static void
9204 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9205     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9206 {
9207 	areq_t	*areq;
9208 	ire_t	*ire = NULL;
9209 	mblk_t	*res_mp;
9210 	ipaddr_t *addrp;
9211 	mblk_t *first_mp;
9212 	ire_t	*save_ire = NULL;
9213 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9214 	ipif_t	*src_ipif = NULL;
9215 	ushort_t ire_marks = 0;
9216 	ill_t	*dst_ill = NULL;
9217 	boolean_t mctl_present;
9218 	ipsec_out_t *io;
9219 	ipha_t *ipha;
9220 	int	ihandle = 0;
9221 	mblk_t	*saved_mp;
9222 	ire_t   *fire = NULL;
9223 	mblk_t  *copy_mp = NULL;
9224 	boolean_t multirt_resolve_next;
9225 	ipaddr_t ipha_dst;
9226 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9227 
9228 	/*
9229 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9230 	 * here for uniformity
9231 	 */
9232 	ipif_refhold(ipif);
9233 
9234 	/*
9235 	 * This loop is run only once in most cases.
9236 	 * We loop to resolve further routes only when the destination
9237 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9238 	 */
9239 	do {
9240 		if (dst_ill != NULL) {
9241 			ill_refrele(dst_ill);
9242 			dst_ill = NULL;
9243 		}
9244 		if (src_ipif != NULL) {
9245 			ipif_refrele(src_ipif);
9246 			src_ipif = NULL;
9247 		}
9248 		multirt_resolve_next = B_FALSE;
9249 
9250 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9251 		    ipif->ipif_ill->ill_name));
9252 
9253 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9254 		if (mctl_present)
9255 			io = (ipsec_out_t *)first_mp->b_rptr;
9256 
9257 		ipha = (ipha_t *)mp->b_rptr;
9258 
9259 		/*
9260 		 * Save the packet destination address, we may need it after
9261 		 * the packet has been consumed.
9262 		 */
9263 		ipha_dst = ipha->ipha_dst;
9264 
9265 		/*
9266 		 * If the interface is a pt-pt interface we look for an
9267 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9268 		 * local_address and the pt-pt destination address. Otherwise
9269 		 * we just match the local address.
9270 		 * NOTE: dst could be different than ipha->ipha_dst in case
9271 		 * of sending igmp multicast packets over a point-to-point
9272 		 * connection.
9273 		 * Thus we must be careful enough to check ipha_dst to be a
9274 		 * multicast address, otherwise it will take xmit_if path for
9275 		 * multicast packets resulting into kernel stack overflow by
9276 		 * repeated calls to ip_newroute_ipif from ire_send().
9277 		 */
9278 		if (CLASSD(ipha_dst) &&
9279 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9280 			goto err_ret;
9281 		}
9282 
9283 		/*
9284 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9285 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9286 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9287 		 * propagate its flags to the new ire.
9288 		 */
9289 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9290 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9291 			ip2dbg(("ip_newroute_ipif: "
9292 			    "ipif_lookup_multi_ire("
9293 			    "ipif %p, dst %08x) = fire %p\n",
9294 			    (void *)ipif, ntohl(dst), (void *)fire));
9295 		}
9296 
9297 		if (mctl_present && io->ipsec_out_attach_if) {
9298 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9299 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9300 
9301 			/* Failure case frees things for us. */
9302 			if (attach_ill == NULL) {
9303 				ipif_refrele(ipif);
9304 				if (fire != NULL)
9305 					ire_refrele(fire);
9306 				return;
9307 			}
9308 
9309 			/*
9310 			 * Check if we need an ire that will not be
9311 			 * looked up by anybody else i.e. HIDDEN.
9312 			 */
9313 			if (ill_is_probeonly(attach_ill)) {
9314 				ire_marks = IRE_MARK_HIDDEN;
9315 			}
9316 			/*
9317 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9318 			 * case.
9319 			 */
9320 			dst_ill = ipif->ipif_ill;
9321 			/* attach_ill has been refheld by ip_grab_attach_ill */
9322 			ASSERT(dst_ill == attach_ill);
9323 		} else {
9324 			/*
9325 			 * If this is set by IP_XMIT_IF, then make sure that
9326 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9327 			 * specified ill.
9328 			 */
9329 			ASSERT((connp == NULL) ||
9330 			    (connp->conn_xmit_if_ill == NULL) ||
9331 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9332 			/*
9333 			 * If the interface belongs to an interface group,
9334 			 * make sure the next possible interface in the group
9335 			 * is used.  This encourages load spreading among
9336 			 * peers in an interface group.
9337 			 * Note: load spreading is disabled for RTF_MULTIRT
9338 			 * routes.
9339 			 */
9340 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9341 			    (fire->ire_flags & RTF_MULTIRT)) {
9342 				/*
9343 				 * Don't perform outbound load spreading
9344 				 * in the case of an RTF_MULTIRT issued route,
9345 				 * we actually typically want to replicate
9346 				 * outgoing packets through particular
9347 				 * interfaces.
9348 				 */
9349 				dst_ill = ipif->ipif_ill;
9350 				ill_refhold(dst_ill);
9351 			} else {
9352 				dst_ill = ip_newroute_get_dst_ill(
9353 				    ipif->ipif_ill);
9354 			}
9355 			if (dst_ill == NULL) {
9356 				if (ip_debug > 2) {
9357 					pr_addr_dbg("ip_newroute_ipif: "
9358 					    "no dst ill for dst %s\n",
9359 					    AF_INET, &dst);
9360 				}
9361 				goto err_ret;
9362 			}
9363 		}
9364 
9365 		/*
9366 		 * Pick a source address preferring non-deprecated ones.
9367 		 * Unlike ip_newroute, we don't do any source address
9368 		 * selection here since for multicast it really does not help
9369 		 * in inbound load spreading as in the unicast case.
9370 		 */
9371 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9372 		    (fire->ire_flags & RTF_SETSRC)) {
9373 			/*
9374 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9375 			 * on that interface. This ire has RTF_SETSRC flag, so
9376 			 * the source address of the packet must be changed.
9377 			 * Check that the ipif matching the requested source
9378 			 * address still exists.
9379 			 */
9380 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9381 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9382 		}
9383 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9384 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9385 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9386 		    (src_ipif == NULL)) {
9387 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9388 			if (src_ipif == NULL) {
9389 				if (ip_debug > 2) {
9390 					/* ip1dbg */
9391 					pr_addr_dbg("ip_newroute_ipif: "
9392 					    "no src for dst %s",
9393 					    AF_INET, &dst);
9394 				}
9395 				ip1dbg((" through interface %s\n",
9396 				    dst_ill->ill_name));
9397 				goto err_ret;
9398 			}
9399 			ipif_refrele(ipif);
9400 			ipif = src_ipif;
9401 			ipif_refhold(ipif);
9402 		}
9403 		if (src_ipif == NULL) {
9404 			src_ipif = ipif;
9405 			ipif_refhold(src_ipif);
9406 		}
9407 
9408 		/*
9409 		 * Assign a source address while we have the conn.
9410 		 * We can't have ip_wput_ire pick a source address when the
9411 		 * packet returns from arp since conn_unspec_src might be set
9412 		 * and we loose the conn when going through arp.
9413 		 */
9414 		if (ipha->ipha_src == INADDR_ANY &&
9415 		    (connp == NULL || !connp->conn_unspec_src)) {
9416 			ipha->ipha_src = src_ipif->ipif_src_addr;
9417 		}
9418 
9419 		/*
9420 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9421 		 * interface does not have an interface ire.
9422 		 * Example: Thousands of mobileip PPP interfaces to mobile
9423 		 * nodes. We don't want to create interface ires because
9424 		 * packets from other mobile nodes must not take the route
9425 		 * via interface ires to the visiting mobile node without
9426 		 * going through the home agent, in absence of mobileip
9427 		 * route optimization.
9428 		 */
9429 		if (CLASSD(ipha_dst) && (connp == NULL ||
9430 		    connp->conn_xmit_if_ill == NULL) &&
9431 		    infop->ip_opt_ill_index == 0) {
9432 			/* ipif_to_ire returns an held ire */
9433 			ire = ipif_to_ire(ipif);
9434 			if (ire == NULL)
9435 				goto err_ret;
9436 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9437 				goto err_ret;
9438 			/*
9439 			 * ihandle is needed when the ire is added to
9440 			 * cache table.
9441 			 */
9442 			save_ire = ire;
9443 			ihandle = save_ire->ire_ihandle;
9444 
9445 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9446 			    "flags %04x\n",
9447 			    (void *)ire, (void *)ipif, flags));
9448 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9449 			    (fire->ire_flags & RTF_MULTIRT)) {
9450 				/*
9451 				 * As requested by flags, an IRE_OFFSUBNET was
9452 				 * looked up on that interface. This ire has
9453 				 * RTF_MULTIRT flag, so the resolution loop will
9454 				 * be re-entered to resolve additional routes on
9455 				 * other interfaces. For that purpose, a copy of
9456 				 * the packet is performed at this point.
9457 				 */
9458 				fire->ire_last_used_time = lbolt;
9459 				copy_mp = copymsg(first_mp);
9460 				if (copy_mp) {
9461 					MULTIRT_DEBUG_TAG(copy_mp);
9462 				}
9463 			}
9464 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9465 			    (fire->ire_flags & RTF_SETSRC)) {
9466 				/*
9467 				 * As requested by flags, an IRE_OFFSUBET was
9468 				 * looked up on that interface. This ire has
9469 				 * RTF_SETSRC flag, so the source address of the
9470 				 * packet must be changed.
9471 				 */
9472 				ipha->ipha_src = fire->ire_src_addr;
9473 			}
9474 		} else {
9475 			ASSERT((connp == NULL) ||
9476 			    (connp->conn_xmit_if_ill != NULL) ||
9477 			    (connp->conn_dontroute) ||
9478 			    infop->ip_opt_ill_index != 0);
9479 			/*
9480 			 * The only ways we can come here are:
9481 			 * 1) IP_XMIT_IF socket option is set
9482 			 * 2) ICMP error message generated from
9483 			 *    ip_mrtun_forward() routine and it needs
9484 			 *    to go through the specified ill.
9485 			 * 3) SO_DONTROUTE socket option is set
9486 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9487 			 * In all cases, the new ire will not be added
9488 			 * into cache table.
9489 			 */
9490 			ire_marks |= IRE_MARK_NOADD;
9491 		}
9492 
9493 		switch (ipif->ipif_net_type) {
9494 		case IRE_IF_NORESOLVER: {
9495 			/* We have what we need to build an IRE_CACHE. */
9496 			mblk_t	*res_mp;
9497 
9498 			/*
9499 			 * Create a new res_mp with the
9500 			 * IP gateway address as destination address in the
9501 			 * DLPI hdr if the physical length is exactly 4 bytes.
9502 			 */
9503 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9504 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9505 				    dst_ill->ill_phys_addr_length,
9506 				    dst_ill->ill_sap,
9507 				    dst_ill->ill_sap_length);
9508 			} else if (dst_ill->ill_resolver_mp == NULL) {
9509 				ip1dbg(("ip_newroute: dst_ill %p "
9510 				    "for IF_NORESOLV ire %p has "
9511 				    "no ill_resolver_mp\n",
9512 				    (void *)dst_ill, (void *)ire));
9513 				break;
9514 			} else {
9515 				/* use the value set in ip_ll_subnet_defaults */
9516 				res_mp = ill_dlur_gen(NULL,
9517 				    dst_ill->ill_phys_addr_length,
9518 				    dst_ill->ill_sap,
9519 				    dst_ill->ill_sap_length);
9520 			}
9521 
9522 			if (res_mp == NULL)
9523 				break;
9524 			/*
9525 			 * The new ire inherits the IRE_OFFSUBNET flags
9526 			 * and source address, if this was requested.
9527 			 */
9528 			ire = ire_create(
9529 			    (uchar_t *)&dst,		/* dest address */
9530 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9531 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9532 			    NULL,			/* gateway address */
9533 			    NULL,
9534 			    &ipif->ipif_mtu,
9535 			    NULL,			/* Fast Path header */
9536 			    dst_ill->ill_rq,		/* recv-from queue */
9537 			    dst_ill->ill_wq,		/* send-to queue */
9538 			    IRE_CACHE,
9539 			    res_mp,
9540 			    src_ipif,
9541 			    NULL,
9542 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9543 			    (fire != NULL) ?		/* Parent handle */
9544 				fire->ire_phandle : 0,
9545 			    ihandle,			/* Interface handle */
9546 			    (fire != NULL) ?
9547 				(fire->ire_flags &
9548 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9549 			    (save_ire == NULL ? &ire_uinfo_null :
9550 				&save_ire->ire_uinfo),
9551 			    NULL,
9552 			    NULL,
9553 			    ipst);
9554 
9555 			freeb(res_mp);
9556 
9557 			if (ire == NULL) {
9558 				if (save_ire != NULL)
9559 					ire_refrele(save_ire);
9560 				break;
9561 			}
9562 
9563 			ire->ire_marks |= ire_marks;
9564 
9565 			/*
9566 			 * If IRE_MARK_NOADD is set then we need to convert
9567 			 * the max_fragp to a useable value now. This is
9568 			 * normally done in ire_add_v[46]. We also need to
9569 			 * associate the ire with an nce (normally would be
9570 			 * done in ip_wput_nondata()).
9571 			 *
9572 			 * Note that IRE_MARK_NOADD packets created here
9573 			 * do not have a non-null ire_mp pointer. The null
9574 			 * value of ire_bucket indicates that they were
9575 			 * never added.
9576 			 */
9577 			if (ire->ire_marks & IRE_MARK_NOADD) {
9578 				uint_t  max_frag;
9579 
9580 				max_frag = *ire->ire_max_fragp;
9581 				ire->ire_max_fragp = NULL;
9582 				ire->ire_max_frag = max_frag;
9583 
9584 				if ((ire->ire_nce = ndp_lookup_v4(
9585 				    ire_to_ill(ire),
9586 				    (ire->ire_gateway_addr != INADDR_ANY ?
9587 				    &ire->ire_gateway_addr : &ire->ire_addr),
9588 				    B_FALSE)) == NULL) {
9589 					if (save_ire != NULL)
9590 						ire_refrele(save_ire);
9591 					break;
9592 				}
9593 				ASSERT(ire->ire_nce->nce_state ==
9594 				    ND_REACHABLE);
9595 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9596 			}
9597 
9598 			/* Prevent save_ire from getting deleted */
9599 			if (save_ire != NULL) {
9600 				IRB_REFHOLD(save_ire->ire_bucket);
9601 				/* Has it been removed already ? */
9602 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9603 					IRB_REFRELE(save_ire->ire_bucket);
9604 					ire_refrele(save_ire);
9605 					break;
9606 				}
9607 			}
9608 
9609 			ire_add_then_send(q, ire, first_mp);
9610 
9611 			/* Assert that save_ire is not deleted yet. */
9612 			if (save_ire != NULL) {
9613 				ASSERT(save_ire->ire_ptpn != NULL);
9614 				IRB_REFRELE(save_ire->ire_bucket);
9615 				ire_refrele(save_ire);
9616 				save_ire = NULL;
9617 			}
9618 			if (fire != NULL) {
9619 				ire_refrele(fire);
9620 				fire = NULL;
9621 			}
9622 
9623 			/*
9624 			 * the resolution loop is re-entered if this
9625 			 * was requested through flags and if we
9626 			 * actually are in a multirouting case.
9627 			 */
9628 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9629 				boolean_t need_resolve =
9630 				    ire_multirt_need_resolve(ipha_dst,
9631 					MBLK_GETLABEL(copy_mp), ipst);
9632 				if (!need_resolve) {
9633 					MULTIRT_DEBUG_UNTAG(copy_mp);
9634 					freemsg(copy_mp);
9635 					copy_mp = NULL;
9636 				} else {
9637 					/*
9638 					 * ipif_lookup_group() calls
9639 					 * ire_lookup_multi() that uses
9640 					 * ire_ftable_lookup() to find
9641 					 * an IRE_INTERFACE for the group.
9642 					 * In the multirt case,
9643 					 * ire_lookup_multi() then invokes
9644 					 * ire_multirt_lookup() to find
9645 					 * the next resolvable ire.
9646 					 * As a result, we obtain an new
9647 					 * interface, derived from the
9648 					 * next ire.
9649 					 */
9650 					ipif_refrele(ipif);
9651 					ipif = ipif_lookup_group(ipha_dst,
9652 					    zoneid, ipst);
9653 					ip2dbg(("ip_newroute_ipif: "
9654 					    "multirt dst %08x, ipif %p\n",
9655 					    htonl(dst), (void *)ipif));
9656 					if (ipif != NULL) {
9657 						mp = copy_mp;
9658 						copy_mp = NULL;
9659 						multirt_resolve_next = B_TRUE;
9660 						continue;
9661 					} else {
9662 						freemsg(copy_mp);
9663 					}
9664 				}
9665 			}
9666 			if (ipif != NULL)
9667 				ipif_refrele(ipif);
9668 			ill_refrele(dst_ill);
9669 			ipif_refrele(src_ipif);
9670 			return;
9671 		}
9672 		case IRE_IF_RESOLVER:
9673 			/*
9674 			 * We can't build an IRE_CACHE yet, but at least
9675 			 * we found a resolver that can help.
9676 			 */
9677 			res_mp = dst_ill->ill_resolver_mp;
9678 			if (!OK_RESOLVER_MP(res_mp))
9679 				break;
9680 
9681 			/*
9682 			 * We obtain a partial IRE_CACHE which we will pass
9683 			 * along with the resolver query.  When the response
9684 			 * comes back it will be there ready for us to add.
9685 			 * The new ire inherits the IRE_OFFSUBNET flags
9686 			 * and source address, if this was requested.
9687 			 * The ire_max_frag is atomically set under the
9688 			 * irebucket lock in ire_add_v[46]. Only in the
9689 			 * case of IRE_MARK_NOADD, we set it here itself.
9690 			 */
9691 			ire = ire_create_mp(
9692 			    (uchar_t *)&dst,		/* dest address */
9693 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9694 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9695 			    NULL,			/* gateway address */
9696 			    NULL,			/* no in_src_addr */
9697 			    (ire_marks & IRE_MARK_NOADD) ?
9698 				ipif->ipif_mtu : 0,	/* max_frag */
9699 			    NULL,			/* Fast path header */
9700 			    dst_ill->ill_rq,		/* recv-from queue */
9701 			    dst_ill->ill_wq,		/* send-to queue */
9702 			    IRE_CACHE,
9703 			    NULL,	/* let ire_nce_init figure res_mp out */
9704 			    src_ipif,
9705 			    NULL,
9706 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9707 			    (fire != NULL) ?		/* Parent handle */
9708 				fire->ire_phandle : 0,
9709 			    ihandle,			/* Interface handle */
9710 			    (fire != NULL) ?		/* flags if any */
9711 				(fire->ire_flags &
9712 				(RTF_SETSRC | RTF_MULTIRT)) : 0,
9713 			    (save_ire == NULL ? &ire_uinfo_null :
9714 				&save_ire->ire_uinfo),
9715 			    NULL,
9716 			    NULL,
9717 			    ipst);
9718 
9719 			if (save_ire != NULL) {
9720 				ire_refrele(save_ire);
9721 				save_ire = NULL;
9722 			}
9723 			if (ire == NULL)
9724 				break;
9725 
9726 			ire->ire_marks |= ire_marks;
9727 			/*
9728 			 * Construct message chain for the resolver of the
9729 			 * form:
9730 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9731 			 *
9732 			 * NOTE : ire will be added later when the response
9733 			 * comes back from ARP. If the response does not
9734 			 * come back, ARP frees the packet. For this reason,
9735 			 * we can't REFHOLD the bucket of save_ire to prevent
9736 			 * deletions. We may not be able to REFRELE the
9737 			 * bucket if the response never comes back.
9738 			 * Thus, before adding the ire, ire_add_v4 will make
9739 			 * sure that the interface route does not get deleted.
9740 			 * This is the only case unlike ip_newroute_v6,
9741 			 * ip_newroute_ipif_v6 where we can always prevent
9742 			 * deletions because ire_add_then_send is called after
9743 			 * creating the IRE.
9744 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9745 			 * does not add this IRE into the IRE CACHE.
9746 			 */
9747 			ASSERT(ire->ire_mp != NULL);
9748 			ire->ire_mp->b_cont = first_mp;
9749 			/* Have saved_mp handy, for cleanup if canput fails */
9750 			saved_mp = mp;
9751 			mp = copyb(res_mp);
9752 			if (mp == NULL) {
9753 				/* Prepare for cleanup */
9754 				mp = saved_mp; /* pkt */
9755 				ire_delete(ire); /* ire_mp */
9756 				ire = NULL;
9757 				if (copy_mp != NULL) {
9758 					MULTIRT_DEBUG_UNTAG(copy_mp);
9759 					freemsg(copy_mp);
9760 					copy_mp = NULL;
9761 				}
9762 				break;
9763 			}
9764 			linkb(mp, ire->ire_mp);
9765 
9766 			/*
9767 			 * Fill in the source and dest addrs for the resolver.
9768 			 * NOTE: this depends on memory layouts imposed by
9769 			 * ill_init().
9770 			 */
9771 			areq = (areq_t *)mp->b_rptr;
9772 			addrp = (ipaddr_t *)((char *)areq +
9773 			    areq->areq_sender_addr_offset);
9774 			*addrp = ire->ire_src_addr;
9775 			addrp = (ipaddr_t *)((char *)areq +
9776 			    areq->areq_target_addr_offset);
9777 			*addrp = dst;
9778 			/* Up to the resolver. */
9779 			if (canputnext(dst_ill->ill_rq) &&
9780 			    !(dst_ill->ill_arp_closing)) {
9781 				putnext(dst_ill->ill_rq, mp);
9782 				/*
9783 				 * The response will come back in ip_wput
9784 				 * with db_type IRE_DB_TYPE.
9785 				 */
9786 			} else {
9787 				mp->b_cont = NULL;
9788 				freeb(mp); /* areq */
9789 				ire_delete(ire); /* ire_mp */
9790 				saved_mp->b_next = NULL;
9791 				saved_mp->b_prev = NULL;
9792 				freemsg(first_mp); /* pkt */
9793 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9794 			}
9795 
9796 			if (fire != NULL) {
9797 				ire_refrele(fire);
9798 				fire = NULL;
9799 			}
9800 
9801 
9802 			/*
9803 			 * The resolution loop is re-entered if this was
9804 			 * requested through flags and we actually are
9805 			 * in a multirouting case.
9806 			 */
9807 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9808 				boolean_t need_resolve =
9809 				    ire_multirt_need_resolve(ipha_dst,
9810 					MBLK_GETLABEL(copy_mp), ipst);
9811 				if (!need_resolve) {
9812 					MULTIRT_DEBUG_UNTAG(copy_mp);
9813 					freemsg(copy_mp);
9814 					copy_mp = NULL;
9815 				} else {
9816 					/*
9817 					 * ipif_lookup_group() calls
9818 					 * ire_lookup_multi() that uses
9819 					 * ire_ftable_lookup() to find
9820 					 * an IRE_INTERFACE for the group.
9821 					 * In the multirt case,
9822 					 * ire_lookup_multi() then invokes
9823 					 * ire_multirt_lookup() to find
9824 					 * the next resolvable ire.
9825 					 * As a result, we obtain an new
9826 					 * interface, derived from the
9827 					 * next ire.
9828 					 */
9829 					ipif_refrele(ipif);
9830 					ipif = ipif_lookup_group(ipha_dst,
9831 					    zoneid, ipst);
9832 					if (ipif != NULL) {
9833 						mp = copy_mp;
9834 						copy_mp = NULL;
9835 						multirt_resolve_next = B_TRUE;
9836 						continue;
9837 					} else {
9838 						freemsg(copy_mp);
9839 					}
9840 				}
9841 			}
9842 			if (ipif != NULL)
9843 				ipif_refrele(ipif);
9844 			ill_refrele(dst_ill);
9845 			ipif_refrele(src_ipif);
9846 			return;
9847 		default:
9848 			break;
9849 		}
9850 	} while (multirt_resolve_next);
9851 
9852 err_ret:
9853 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9854 	if (fire != NULL)
9855 		ire_refrele(fire);
9856 	ipif_refrele(ipif);
9857 	/* Did this packet originate externally? */
9858 	if (dst_ill != NULL)
9859 		ill_refrele(dst_ill);
9860 	if (src_ipif != NULL)
9861 		ipif_refrele(src_ipif);
9862 	if (mp->b_prev || mp->b_next) {
9863 		mp->b_next = NULL;
9864 		mp->b_prev = NULL;
9865 	} else {
9866 		/*
9867 		 * Since ip_wput() isn't close to finished, we fill
9868 		 * in enough of the header for credible error reporting.
9869 		 */
9870 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9871 			/* Failed */
9872 			freemsg(first_mp);
9873 			if (ire != NULL)
9874 				ire_refrele(ire);
9875 			return;
9876 		}
9877 	}
9878 	/*
9879 	 * At this point we will have ire only if RTF_BLACKHOLE
9880 	 * or RTF_REJECT flags are set on the IRE. It will not
9881 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9882 	 */
9883 	if (ire != NULL) {
9884 		if (ire->ire_flags & RTF_BLACKHOLE) {
9885 			ire_refrele(ire);
9886 			freemsg(first_mp);
9887 			return;
9888 		}
9889 		ire_refrele(ire);
9890 	}
9891 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9892 }
9893 
9894 /* Name/Value Table Lookup Routine */
9895 char *
9896 ip_nv_lookup(nv_t *nv, int value)
9897 {
9898 	if (!nv)
9899 		return (NULL);
9900 	for (; nv->nv_name; nv++) {
9901 		if (nv->nv_value == value)
9902 			return (nv->nv_name);
9903 	}
9904 	return ("unknown");
9905 }
9906 
9907 /*
9908  * This is a module open, i.e. this is a control stream for access
9909  * to a DLPI device.  We allocate an ill_t as the instance data in
9910  * this case.
9911  */
9912 int
9913 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9914 {
9915 	ill_t	*ill;
9916 	int	err;
9917 	zoneid_t zoneid;
9918 	netstack_t *ns;
9919 	ip_stack_t *ipst;
9920 
9921 	/*
9922 	 * Prevent unprivileged processes from pushing IP so that
9923 	 * they can't send raw IP.
9924 	 */
9925 	if (secpolicy_net_rawaccess(credp) != 0)
9926 		return (EPERM);
9927 
9928 	ns = netstack_find_by_cred(credp);
9929 	ASSERT(ns != NULL);
9930 	ipst = ns->netstack_ip;
9931 	ASSERT(ipst != NULL);
9932 
9933 	/*
9934 	 * For exclusive stacks we set the zoneid to zero
9935 	 * to make IP operate as if in the global zone.
9936 	 */
9937 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9938 		zoneid = GLOBAL_ZONEID;
9939 	else
9940 		zoneid = crgetzoneid(credp);
9941 
9942 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9943 	q->q_ptr = WR(q)->q_ptr = ill;
9944 	ill->ill_ipst = ipst;
9945 	ill->ill_zoneid = zoneid;
9946 
9947 	/*
9948 	 * ill_init initializes the ill fields and then sends down
9949 	 * down a DL_INFO_REQ after calling qprocson.
9950 	 */
9951 	err = ill_init(q, ill);
9952 	if (err != 0) {
9953 		mi_free(ill);
9954 		netstack_rele(ipst->ips_netstack);
9955 		q->q_ptr = NULL;
9956 		WR(q)->q_ptr = NULL;
9957 		return (err);
9958 	}
9959 
9960 	/* ill_init initializes the ipsq marking this thread as writer */
9961 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9962 	/* Wait for the DL_INFO_ACK */
9963 	mutex_enter(&ill->ill_lock);
9964 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9965 		/*
9966 		 * Return value of 0 indicates a pending signal.
9967 		 */
9968 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9969 		if (err == 0) {
9970 			mutex_exit(&ill->ill_lock);
9971 			(void) ip_close(q, 0);
9972 			return (EINTR);
9973 		}
9974 	}
9975 	mutex_exit(&ill->ill_lock);
9976 
9977 	/*
9978 	 * ip_rput_other could have set an error  in ill_error on
9979 	 * receipt of M_ERROR.
9980 	 */
9981 
9982 	err = ill->ill_error;
9983 	if (err != 0) {
9984 		(void) ip_close(q, 0);
9985 		return (err);
9986 	}
9987 
9988 	ill->ill_credp = credp;
9989 	crhold(credp);
9990 
9991 	mutex_enter(&ipst->ips_ip_mi_lock);
9992 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9993 	    credp);
9994 	mutex_exit(&ipst->ips_ip_mi_lock);
9995 	if (err) {
9996 		(void) ip_close(q, 0);
9997 		return (err);
9998 	}
9999 	return (0);
10000 }
10001 
10002 /* IP open routine. */
10003 int
10004 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
10005 {
10006 	conn_t 		*connp;
10007 	major_t		maj;
10008 	zoneid_t	zoneid;
10009 	netstack_t	*ns;
10010 	ip_stack_t	*ipst;
10011 
10012 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
10013 
10014 	/* Allow reopen. */
10015 	if (q->q_ptr != NULL)
10016 		return (0);
10017 
10018 	if (sflag & MODOPEN) {
10019 		/* This is a module open */
10020 		return (ip_modopen(q, devp, flag, sflag, credp));
10021 	}
10022 
10023 	ns = netstack_find_by_cred(credp);
10024 	ASSERT(ns != NULL);
10025 	ipst = ns->netstack_ip;
10026 	ASSERT(ipst != NULL);
10027 
10028 	/*
10029 	 * For exclusive stacks we set the zoneid to zero
10030 	 * to make IP operate as if in the global zone.
10031 	 */
10032 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10033 		zoneid = GLOBAL_ZONEID;
10034 	else
10035 		zoneid = crgetzoneid(credp);
10036 
10037 	/*
10038 	 * We are opening as a device. This is an IP client stream, and we
10039 	 * allocate an conn_t as the instance data.
10040 	 */
10041 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10042 
10043 	/*
10044 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10045 	 * done by netstack_find_by_cred()
10046 	 */
10047 	netstack_rele(ipst->ips_netstack);
10048 
10049 	connp->conn_zoneid = zoneid;
10050 
10051 	connp->conn_upq = q;
10052 	q->q_ptr = WR(q)->q_ptr = connp;
10053 
10054 	if (flag & SO_SOCKSTR)
10055 		connp->conn_flags |= IPCL_SOCKET;
10056 
10057 	/* Minor tells us which /dev entry was opened */
10058 	if (geteminor(*devp) == IPV6_MINOR) {
10059 		connp->conn_flags |= IPCL_ISV6;
10060 		connp->conn_af_isv6 = B_TRUE;
10061 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10062 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10063 	} else {
10064 		connp->conn_af_isv6 = B_FALSE;
10065 		connp->conn_pkt_isv6 = B_FALSE;
10066 	}
10067 
10068 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10069 		/* CONN_DEC_REF takes care of netstack_rele() */
10070 		q->q_ptr = WR(q)->q_ptr = NULL;
10071 		CONN_DEC_REF(connp);
10072 		return (EBUSY);
10073 	}
10074 
10075 	maj = getemajor(*devp);
10076 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10077 
10078 	/*
10079 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10080 	 */
10081 	connp->conn_cred = credp;
10082 	crhold(connp->conn_cred);
10083 
10084 	/*
10085 	 * If the caller has the process-wide flag set, then default to MAC
10086 	 * exempt mode.  This allows read-down to unlabeled hosts.
10087 	 */
10088 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10089 		connp->conn_mac_exempt = B_TRUE;
10090 
10091 	/*
10092 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10093 	 * administrative ops.  In these cases, we just need a normal conn_t
10094 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10095 	 * an error will be returned.
10096 	 */
10097 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10098 		connp->conn_rq = q;
10099 		connp->conn_wq = WR(q);
10100 	} else {
10101 		connp->conn_ulp = IPPROTO_SCTP;
10102 		connp->conn_rq = connp->conn_wq = NULL;
10103 	}
10104 	/* Non-zero default values */
10105 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10106 
10107 	/*
10108 	 * Make the conn globally visible to walkers
10109 	 */
10110 	mutex_enter(&connp->conn_lock);
10111 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10112 	mutex_exit(&connp->conn_lock);
10113 	ASSERT(connp->conn_ref == 1);
10114 
10115 	qprocson(q);
10116 
10117 	return (0);
10118 }
10119 
10120 /*
10121  * Change q_qinfo based on the value of isv6.
10122  * This can not called on an ill queue.
10123  * Note that there is no race since either q_qinfo works for conn queues - it
10124  * is just an optimization to enter the best wput routine directly.
10125  */
10126 void
10127 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10128 {
10129 	ASSERT(q->q_flag & QREADR);
10130 	ASSERT(WR(q)->q_next == NULL);
10131 	ASSERT(q->q_ptr != NULL);
10132 
10133 	if (minor == IPV6_MINOR)  {
10134 		if (bump_mib) {
10135 			BUMP_MIB(&ipst->ips_ip6_mib,
10136 			    ipIfStatsOutSwitchIPVersion);
10137 		}
10138 		q->q_qinfo = &rinit_ipv6;
10139 		WR(q)->q_qinfo = &winit_ipv6;
10140 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10141 	} else {
10142 		if (bump_mib) {
10143 			BUMP_MIB(&ipst->ips_ip_mib,
10144 			    ipIfStatsOutSwitchIPVersion);
10145 		}
10146 		q->q_qinfo = &iprinit;
10147 		WR(q)->q_qinfo = &ipwinit;
10148 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10149 	}
10150 
10151 }
10152 
10153 /*
10154  * See if IPsec needs loading because of the options in mp.
10155  */
10156 static boolean_t
10157 ipsec_opt_present(mblk_t *mp)
10158 {
10159 	uint8_t *optcp, *next_optcp, *opt_endcp;
10160 	struct opthdr *opt;
10161 	struct T_opthdr *topt;
10162 	int opthdr_len;
10163 	t_uscalar_t optname, optlevel;
10164 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10165 	ipsec_req_t *ipsr;
10166 
10167 	/*
10168 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10169 	 * return TRUE.
10170 	 */
10171 
10172 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10173 	opt_endcp = optcp + tor->OPT_length;
10174 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10175 		opthdr_len = sizeof (struct T_opthdr);
10176 	} else {		/* O_OPTMGMT_REQ */
10177 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10178 		opthdr_len = sizeof (struct opthdr);
10179 	}
10180 	for (; optcp < opt_endcp; optcp = next_optcp) {
10181 		if (optcp + opthdr_len > opt_endcp)
10182 			return (B_FALSE);	/* Not enough option header. */
10183 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10184 			topt = (struct T_opthdr *)optcp;
10185 			optlevel = topt->level;
10186 			optname = topt->name;
10187 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10188 		} else {
10189 			opt = (struct opthdr *)optcp;
10190 			optlevel = opt->level;
10191 			optname = opt->name;
10192 			next_optcp = optcp + opthdr_len +
10193 			    _TPI_ALIGN_OPT(opt->len);
10194 		}
10195 		if ((next_optcp < optcp) || /* wraparound pointer space */
10196 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10197 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10198 			return (B_FALSE); /* bad option buffer */
10199 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10200 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10201 			/*
10202 			 * Check to see if it's an all-bypass or all-zeroes
10203 			 * IPsec request.  Don't bother loading IPsec if
10204 			 * the socket doesn't want to use it.  (A good example
10205 			 * is a bypass request.)
10206 			 *
10207 			 * Basically, if any of the non-NEVER bits are set,
10208 			 * load IPsec.
10209 			 */
10210 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10211 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10212 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10213 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10214 			    != 0)
10215 				return (B_TRUE);
10216 		}
10217 	}
10218 	return (B_FALSE);
10219 }
10220 
10221 /*
10222  * If conn is is waiting for ipsec to finish loading, kick it.
10223  */
10224 /* ARGSUSED */
10225 static void
10226 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10227 {
10228 	t_scalar_t	optreq_prim;
10229 	mblk_t		*mp;
10230 	cred_t		*cr;
10231 	int		err = 0;
10232 
10233 	/*
10234 	 * This function is called, after ipsec loading is complete.
10235 	 * Since IP checks exclusively and atomically (i.e it prevents
10236 	 * ipsec load from completing until ip_optcom_req completes)
10237 	 * whether ipsec load is complete, there cannot be a race with IP
10238 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10239 	 */
10240 	mutex_enter(&connp->conn_lock);
10241 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10242 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10243 		mp = connp->conn_ipsec_opt_mp;
10244 		connp->conn_ipsec_opt_mp = NULL;
10245 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10246 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10247 		mutex_exit(&connp->conn_lock);
10248 
10249 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10250 
10251 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10252 		if (optreq_prim == T_OPTMGMT_REQ) {
10253 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10254 			    &ip_opt_obj);
10255 		} else {
10256 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10257 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10258 			    &ip_opt_obj);
10259 		}
10260 		if (err != EINPROGRESS)
10261 			CONN_OPER_PENDING_DONE(connp);
10262 		return;
10263 	}
10264 	mutex_exit(&connp->conn_lock);
10265 }
10266 
10267 /*
10268  * Called from the ipsec_loader thread, outside any perimeter, to tell
10269  * ip qenable any of the queues waiting for the ipsec loader to
10270  * complete.
10271  */
10272 void
10273 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10274 {
10275 	netstack_t *ns = ipss->ipsec_netstack;
10276 
10277 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10278 }
10279 
10280 /*
10281  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10282  * determines the grp on which it has to become exclusive, queues the mp
10283  * and sq draining restarts the optmgmt
10284  */
10285 static boolean_t
10286 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10287 {
10288 	conn_t *connp = Q_TO_CONN(q);
10289 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10290 
10291 	/*
10292 	 * Take IPsec requests and treat them special.
10293 	 */
10294 	if (ipsec_opt_present(mp)) {
10295 		/* First check if IPsec is loaded. */
10296 		mutex_enter(&ipss->ipsec_loader_lock);
10297 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10298 			mutex_exit(&ipss->ipsec_loader_lock);
10299 			return (B_FALSE);
10300 		}
10301 		mutex_enter(&connp->conn_lock);
10302 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10303 
10304 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10305 		connp->conn_ipsec_opt_mp = mp;
10306 		mutex_exit(&connp->conn_lock);
10307 		mutex_exit(&ipss->ipsec_loader_lock);
10308 
10309 		ipsec_loader_loadnow(ipss);
10310 		return (B_TRUE);
10311 	}
10312 	return (B_FALSE);
10313 }
10314 
10315 /*
10316  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10317  * all of them are copied to the conn_t. If the req is "zero", the policy is
10318  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10319  * fields.
10320  * We keep only the latest setting of the policy and thus policy setting
10321  * is not incremental/cumulative.
10322  *
10323  * Requests to set policies with multiple alternative actions will
10324  * go through a different API.
10325  */
10326 int
10327 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10328 {
10329 	uint_t ah_req = 0;
10330 	uint_t esp_req = 0;
10331 	uint_t se_req = 0;
10332 	ipsec_selkey_t sel;
10333 	ipsec_act_t *actp = NULL;
10334 	uint_t nact;
10335 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10336 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10337 	ipsec_policy_root_t *pr;
10338 	ipsec_policy_head_t *ph;
10339 	int fam;
10340 	boolean_t is_pol_reset;
10341 	int error = 0;
10342 	netstack_t	*ns = connp->conn_netstack;
10343 	ip_stack_t	*ipst = ns->netstack_ip;
10344 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10345 
10346 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10347 
10348 	/*
10349 	 * The IP_SEC_OPT option does not allow variable length parameters,
10350 	 * hence a request cannot be NULL.
10351 	 */
10352 	if (req == NULL)
10353 		return (EINVAL);
10354 
10355 	ah_req = req->ipsr_ah_req;
10356 	esp_req = req->ipsr_esp_req;
10357 	se_req = req->ipsr_self_encap_req;
10358 
10359 	/*
10360 	 * Are we dealing with a request to reset the policy (i.e.
10361 	 * zero requests).
10362 	 */
10363 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10364 	    (esp_req & REQ_MASK) == 0 &&
10365 	    (se_req & REQ_MASK) == 0);
10366 
10367 	if (!is_pol_reset) {
10368 		/*
10369 		 * If we couldn't load IPsec, fail with "protocol
10370 		 * not supported".
10371 		 * IPsec may not have been loaded for a request with zero
10372 		 * policies, so we don't fail in this case.
10373 		 */
10374 		mutex_enter(&ipss->ipsec_loader_lock);
10375 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10376 			mutex_exit(&ipss->ipsec_loader_lock);
10377 			return (EPROTONOSUPPORT);
10378 		}
10379 		mutex_exit(&ipss->ipsec_loader_lock);
10380 
10381 		/*
10382 		 * Test for valid requests. Invalid algorithms
10383 		 * need to be tested by IPSEC code because new
10384 		 * algorithms can be added dynamically.
10385 		 */
10386 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10387 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10388 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10389 			return (EINVAL);
10390 		}
10391 
10392 		/*
10393 		 * Only privileged users can issue these
10394 		 * requests.
10395 		 */
10396 		if (((ah_req & IPSEC_PREF_NEVER) ||
10397 		    (esp_req & IPSEC_PREF_NEVER) ||
10398 		    (se_req & IPSEC_PREF_NEVER)) &&
10399 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10400 			return (EPERM);
10401 		}
10402 
10403 		/*
10404 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10405 		 * are mutually exclusive.
10406 		 */
10407 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10408 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10409 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10410 			/* Both of them are set */
10411 			return (EINVAL);
10412 		}
10413 	}
10414 
10415 	mutex_enter(&connp->conn_lock);
10416 
10417 	/*
10418 	 * If we have already cached policies in ip_bind_connected*(), don't
10419 	 * let them change now. We cache policies for connections
10420 	 * whose src,dst [addr, port] is known.
10421 	 */
10422 	if (connp->conn_policy_cached) {
10423 		mutex_exit(&connp->conn_lock);
10424 		return (EINVAL);
10425 	}
10426 
10427 	/*
10428 	 * We have a zero policies, reset the connection policy if already
10429 	 * set. This will cause the connection to inherit the
10430 	 * global policy, if any.
10431 	 */
10432 	if (is_pol_reset) {
10433 		if (connp->conn_policy != NULL) {
10434 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10435 			connp->conn_policy = NULL;
10436 		}
10437 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10438 		connp->conn_in_enforce_policy = B_FALSE;
10439 		connp->conn_out_enforce_policy = B_FALSE;
10440 		mutex_exit(&connp->conn_lock);
10441 		return (0);
10442 	}
10443 
10444 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10445 	    ipst->ips_netstack);
10446 	if (ph == NULL)
10447 		goto enomem;
10448 
10449 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10450 	if (actp == NULL)
10451 		goto enomem;
10452 
10453 	/*
10454 	 * Always allocate IPv4 policy entries, since they can also
10455 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10456 	 */
10457 	bzero(&sel, sizeof (sel));
10458 	sel.ipsl_valid = IPSL_IPV4;
10459 
10460 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10461 	    ipst->ips_netstack);
10462 	if (pin4 == NULL)
10463 		goto enomem;
10464 
10465 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10466 	    ipst->ips_netstack);
10467 	if (pout4 == NULL)
10468 		goto enomem;
10469 
10470 	if (connp->conn_pkt_isv6) {
10471 		/*
10472 		 * We're looking at a v6 socket, also allocate the
10473 		 * v6-specific entries...
10474 		 */
10475 		sel.ipsl_valid = IPSL_IPV6;
10476 		pin6 = ipsec_policy_create(&sel, actp, nact,
10477 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10478 		if (pin6 == NULL)
10479 			goto enomem;
10480 
10481 		pout6 = ipsec_policy_create(&sel, actp, nact,
10482 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10483 		if (pout6 == NULL)
10484 			goto enomem;
10485 
10486 		/*
10487 		 * .. and file them away in the right place.
10488 		 */
10489 		fam = IPSEC_AF_V6;
10490 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10491 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10492 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10493 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10494 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10495 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10496 	}
10497 
10498 	ipsec_actvec_free(actp, nact);
10499 
10500 	/*
10501 	 * File the v4 policies.
10502 	 */
10503 	fam = IPSEC_AF_V4;
10504 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10505 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10506 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10507 
10508 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10509 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10510 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10511 
10512 	/*
10513 	 * If the requests need security, set enforce_policy.
10514 	 * If the requests are IPSEC_PREF_NEVER, one should
10515 	 * still set conn_out_enforce_policy so that an ipsec_out
10516 	 * gets attached in ip_wput. This is needed so that
10517 	 * for connections that we don't cache policy in ip_bind,
10518 	 * if global policy matches in ip_wput_attach_policy, we
10519 	 * don't wrongly inherit global policy. Similarly, we need
10520 	 * to set conn_in_enforce_policy also so that we don't verify
10521 	 * policy wrongly.
10522 	 */
10523 	if ((ah_req & REQ_MASK) != 0 ||
10524 	    (esp_req & REQ_MASK) != 0 ||
10525 	    (se_req & REQ_MASK) != 0) {
10526 		connp->conn_in_enforce_policy = B_TRUE;
10527 		connp->conn_out_enforce_policy = B_TRUE;
10528 		connp->conn_flags |= IPCL_CHECK_POLICY;
10529 	}
10530 
10531 	mutex_exit(&connp->conn_lock);
10532 	return (error);
10533 #undef REQ_MASK
10534 
10535 	/*
10536 	 * Common memory-allocation-failure exit path.
10537 	 */
10538 enomem:
10539 	mutex_exit(&connp->conn_lock);
10540 	if (actp != NULL)
10541 		ipsec_actvec_free(actp, nact);
10542 	if (pin4 != NULL)
10543 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10544 	if (pout4 != NULL)
10545 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10546 	if (pin6 != NULL)
10547 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10548 	if (pout6 != NULL)
10549 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10550 	return (ENOMEM);
10551 }
10552 
10553 /*
10554  * Only for options that pass in an IP addr. Currently only V4 options
10555  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10556  * So this function assumes level is IPPROTO_IP
10557  */
10558 int
10559 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10560     mblk_t *first_mp)
10561 {
10562 	ipif_t *ipif = NULL;
10563 	int error;
10564 	ill_t *ill;
10565 	int zoneid;
10566 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10567 
10568 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10569 
10570 	if (addr != INADDR_ANY || checkonly) {
10571 		ASSERT(connp != NULL);
10572 		zoneid = IPCL_ZONEID(connp);
10573 		if (option == IP_NEXTHOP) {
10574 			ipif = ipif_lookup_onlink_addr(addr,
10575 			    connp->conn_zoneid, ipst);
10576 		} else {
10577 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10578 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10579 			    &error, ipst);
10580 		}
10581 		if (ipif == NULL) {
10582 			if (error == EINPROGRESS)
10583 				return (error);
10584 			else if ((option == IP_MULTICAST_IF) ||
10585 			    (option == IP_NEXTHOP))
10586 				return (EHOSTUNREACH);
10587 			else
10588 				return (EINVAL);
10589 		} else if (checkonly) {
10590 			if (option == IP_MULTICAST_IF) {
10591 				ill = ipif->ipif_ill;
10592 				/* not supported by the virtual network iface */
10593 				if (IS_VNI(ill)) {
10594 					ipif_refrele(ipif);
10595 					return (EINVAL);
10596 				}
10597 			}
10598 			ipif_refrele(ipif);
10599 			return (0);
10600 		}
10601 		ill = ipif->ipif_ill;
10602 		mutex_enter(&connp->conn_lock);
10603 		mutex_enter(&ill->ill_lock);
10604 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10605 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10606 			mutex_exit(&ill->ill_lock);
10607 			mutex_exit(&connp->conn_lock);
10608 			ipif_refrele(ipif);
10609 			return (option == IP_MULTICAST_IF ?
10610 			    EHOSTUNREACH : EINVAL);
10611 		}
10612 	} else {
10613 		mutex_enter(&connp->conn_lock);
10614 	}
10615 
10616 	/* None of the options below are supported on the VNI */
10617 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10618 		mutex_exit(&ill->ill_lock);
10619 		mutex_exit(&connp->conn_lock);
10620 		ipif_refrele(ipif);
10621 		return (EINVAL);
10622 	}
10623 
10624 	switch (option) {
10625 	case IP_DONTFAILOVER_IF:
10626 		/*
10627 		 * This option is used by in.mpathd to ensure
10628 		 * that IPMP probe packets only go out on the
10629 		 * test interfaces. in.mpathd sets this option
10630 		 * on the non-failover interfaces.
10631 		 * For backward compatibility, this option
10632 		 * implicitly sets IP_MULTICAST_IF, as used
10633 		 * be done in bind(), so that ip_wput gets
10634 		 * this ipif to send mcast packets.
10635 		 */
10636 		if (ipif != NULL) {
10637 			ASSERT(addr != INADDR_ANY);
10638 			connp->conn_nofailover_ill = ipif->ipif_ill;
10639 			connp->conn_multicast_ipif = ipif;
10640 		} else {
10641 			ASSERT(addr == INADDR_ANY);
10642 			connp->conn_nofailover_ill = NULL;
10643 			connp->conn_multicast_ipif = NULL;
10644 		}
10645 		break;
10646 
10647 	case IP_MULTICAST_IF:
10648 		connp->conn_multicast_ipif = ipif;
10649 		break;
10650 	case IP_NEXTHOP:
10651 		connp->conn_nexthop_v4 = addr;
10652 		connp->conn_nexthop_set = B_TRUE;
10653 		break;
10654 	}
10655 
10656 	if (ipif != NULL) {
10657 		mutex_exit(&ill->ill_lock);
10658 		mutex_exit(&connp->conn_lock);
10659 		ipif_refrele(ipif);
10660 		return (0);
10661 	}
10662 	mutex_exit(&connp->conn_lock);
10663 	/* We succeded in cleared the option */
10664 	return (0);
10665 }
10666 
10667 /*
10668  * For options that pass in an ifindex specifying the ill. V6 options always
10669  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10670  */
10671 int
10672 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10673     int level, int option, mblk_t *first_mp)
10674 {
10675 	ill_t *ill = NULL;
10676 	int error = 0;
10677 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10678 
10679 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10680 	if (ifindex != 0) {
10681 		ASSERT(connp != NULL);
10682 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10683 		    first_mp, ip_restart_optmgmt, &error, ipst);
10684 		if (ill != NULL) {
10685 			if (checkonly) {
10686 				/* not supported by the virtual network iface */
10687 				if (IS_VNI(ill)) {
10688 					ill_refrele(ill);
10689 					return (EINVAL);
10690 				}
10691 				ill_refrele(ill);
10692 				return (0);
10693 			}
10694 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10695 			    0, NULL)) {
10696 				ill_refrele(ill);
10697 				ill = NULL;
10698 				mutex_enter(&connp->conn_lock);
10699 				goto setit;
10700 			}
10701 			mutex_enter(&connp->conn_lock);
10702 			mutex_enter(&ill->ill_lock);
10703 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10704 				mutex_exit(&ill->ill_lock);
10705 				mutex_exit(&connp->conn_lock);
10706 				ill_refrele(ill);
10707 				ill = NULL;
10708 				mutex_enter(&connp->conn_lock);
10709 			}
10710 			goto setit;
10711 		} else if (error == EINPROGRESS) {
10712 			return (error);
10713 		} else {
10714 			error = 0;
10715 		}
10716 	}
10717 	mutex_enter(&connp->conn_lock);
10718 setit:
10719 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10720 
10721 	/*
10722 	 * The options below assume that the ILL (if any) transmits and/or
10723 	 * receives traffic. Neither of which is true for the virtual network
10724 	 * interface, so fail setting these on a VNI.
10725 	 */
10726 	if (IS_VNI(ill)) {
10727 		ASSERT(ill != NULL);
10728 		mutex_exit(&ill->ill_lock);
10729 		mutex_exit(&connp->conn_lock);
10730 		ill_refrele(ill);
10731 		return (EINVAL);
10732 	}
10733 
10734 	if (level == IPPROTO_IP) {
10735 		switch (option) {
10736 		case IP_BOUND_IF:
10737 			connp->conn_incoming_ill = ill;
10738 			connp->conn_outgoing_ill = ill;
10739 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10740 			    0 : ifindex;
10741 			break;
10742 
10743 		case IP_XMIT_IF:
10744 			/*
10745 			 * Similar to IP_BOUND_IF, but this only
10746 			 * determines the outgoing interface for
10747 			 * unicast packets. Also no IRE_CACHE entry
10748 			 * is added for the destination of the
10749 			 * outgoing packets. This feature is needed
10750 			 * for mobile IP.
10751 			 */
10752 			connp->conn_xmit_if_ill = ill;
10753 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10754 			    0 : ifindex;
10755 			break;
10756 
10757 		case IP_MULTICAST_IF:
10758 			/*
10759 			 * This option is an internal special. The socket
10760 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10761 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10762 			 * specifies an ifindex and we try first on V6 ill's.
10763 			 * If we don't find one, we they try using on v4 ill's
10764 			 * intenally and we come here.
10765 			 */
10766 			if (!checkonly && ill != NULL) {
10767 				ipif_t	*ipif;
10768 				ipif = ill->ill_ipif;
10769 
10770 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10771 					mutex_exit(&ill->ill_lock);
10772 					mutex_exit(&connp->conn_lock);
10773 					ill_refrele(ill);
10774 					ill = NULL;
10775 					mutex_enter(&connp->conn_lock);
10776 				} else {
10777 					connp->conn_multicast_ipif = ipif;
10778 				}
10779 			}
10780 			break;
10781 		}
10782 	} else {
10783 		switch (option) {
10784 		case IPV6_BOUND_IF:
10785 			connp->conn_incoming_ill = ill;
10786 			connp->conn_outgoing_ill = ill;
10787 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10788 			    0 : ifindex;
10789 			break;
10790 
10791 		case IPV6_BOUND_PIF:
10792 			/*
10793 			 * Limit all transmit to this ill.
10794 			 * Unlike IPV6_BOUND_IF, using this option
10795 			 * prevents load spreading and failover from
10796 			 * happening when the interface is part of the
10797 			 * group. That's why we don't need to remember
10798 			 * the ifindex in orig_bound_ifindex as in
10799 			 * IPV6_BOUND_IF.
10800 			 */
10801 			connp->conn_outgoing_pill = ill;
10802 			break;
10803 
10804 		case IPV6_DONTFAILOVER_IF:
10805 			/*
10806 			 * This option is used by in.mpathd to ensure
10807 			 * that IPMP probe packets only go out on the
10808 			 * test interfaces. in.mpathd sets this option
10809 			 * on the non-failover interfaces.
10810 			 */
10811 			connp->conn_nofailover_ill = ill;
10812 			/*
10813 			 * For backward compatibility, this option
10814 			 * implicitly sets ip_multicast_ill as used in
10815 			 * IP_MULTICAST_IF so that ip_wput gets
10816 			 * this ipif to send mcast packets.
10817 			 */
10818 			connp->conn_multicast_ill = ill;
10819 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10820 			    0 : ifindex;
10821 			break;
10822 
10823 		case IPV6_MULTICAST_IF:
10824 			/*
10825 			 * Set conn_multicast_ill to be the IPv6 ill.
10826 			 * Set conn_multicast_ipif to be an IPv4 ipif
10827 			 * for ifindex to make IPv4 mapped addresses
10828 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10829 			 * Even if no IPv6 ill exists for the ifindex
10830 			 * we need to check for an IPv4 ifindex in order
10831 			 * for this to work with mapped addresses. In that
10832 			 * case only set conn_multicast_ipif.
10833 			 */
10834 			if (!checkonly) {
10835 				if (ifindex == 0) {
10836 					connp->conn_multicast_ill = NULL;
10837 					connp->conn_orig_multicast_ifindex = 0;
10838 					connp->conn_multicast_ipif = NULL;
10839 				} else if (ill != NULL) {
10840 					connp->conn_multicast_ill = ill;
10841 					connp->conn_orig_multicast_ifindex =
10842 					    ifindex;
10843 				}
10844 			}
10845 			break;
10846 		}
10847 	}
10848 
10849 	if (ill != NULL) {
10850 		mutex_exit(&ill->ill_lock);
10851 		mutex_exit(&connp->conn_lock);
10852 		ill_refrele(ill);
10853 		return (0);
10854 	}
10855 	mutex_exit(&connp->conn_lock);
10856 	/*
10857 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10858 	 * locate the ill and could not set the option (ifindex != 0)
10859 	 */
10860 	return (ifindex == 0 ? 0 : EINVAL);
10861 }
10862 
10863 /* This routine sets socket options. */
10864 /* ARGSUSED */
10865 int
10866 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10867     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10868     void *dummy, cred_t *cr, mblk_t *first_mp)
10869 {
10870 	int		*i1 = (int *)invalp;
10871 	conn_t		*connp = Q_TO_CONN(q);
10872 	int		error = 0;
10873 	boolean_t	checkonly;
10874 	ire_t		*ire;
10875 	boolean_t	found;
10876 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10877 
10878 	switch (optset_context) {
10879 
10880 	case SETFN_OPTCOM_CHECKONLY:
10881 		checkonly = B_TRUE;
10882 		/*
10883 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10884 		 * inlen != 0 implies value supplied and
10885 		 * 	we have to "pretend" to set it.
10886 		 * inlen == 0 implies that there is no
10887 		 * 	value part in T_CHECK request and just validation
10888 		 * done elsewhere should be enough, we just return here.
10889 		 */
10890 		if (inlen == 0) {
10891 			*outlenp = 0;
10892 			return (0);
10893 		}
10894 		break;
10895 	case SETFN_OPTCOM_NEGOTIATE:
10896 	case SETFN_UD_NEGOTIATE:
10897 	case SETFN_CONN_NEGOTIATE:
10898 		checkonly = B_FALSE;
10899 		break;
10900 	default:
10901 		/*
10902 		 * We should never get here
10903 		 */
10904 		*outlenp = 0;
10905 		return (EINVAL);
10906 	}
10907 
10908 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10909 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10910 
10911 	/*
10912 	 * For fixed length options, no sanity check
10913 	 * of passed in length is done. It is assumed *_optcom_req()
10914 	 * routines do the right thing.
10915 	 */
10916 
10917 	switch (level) {
10918 	case SOL_SOCKET:
10919 		/*
10920 		 * conn_lock protects the bitfields, and is used to
10921 		 * set the fields atomically.
10922 		 */
10923 		switch (name) {
10924 		case SO_BROADCAST:
10925 			if (!checkonly) {
10926 				/* TODO: use value someplace? */
10927 				mutex_enter(&connp->conn_lock);
10928 				connp->conn_broadcast = *i1 ? 1 : 0;
10929 				mutex_exit(&connp->conn_lock);
10930 			}
10931 			break;	/* goto sizeof (int) option return */
10932 		case SO_USELOOPBACK:
10933 			if (!checkonly) {
10934 				/* TODO: use value someplace? */
10935 				mutex_enter(&connp->conn_lock);
10936 				connp->conn_loopback = *i1 ? 1 : 0;
10937 				mutex_exit(&connp->conn_lock);
10938 			}
10939 			break;	/* goto sizeof (int) option return */
10940 		case SO_DONTROUTE:
10941 			if (!checkonly) {
10942 				mutex_enter(&connp->conn_lock);
10943 				connp->conn_dontroute = *i1 ? 1 : 0;
10944 				mutex_exit(&connp->conn_lock);
10945 			}
10946 			break;	/* goto sizeof (int) option return */
10947 		case SO_REUSEADDR:
10948 			if (!checkonly) {
10949 				mutex_enter(&connp->conn_lock);
10950 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10951 				mutex_exit(&connp->conn_lock);
10952 			}
10953 			break;	/* goto sizeof (int) option return */
10954 		case SO_PROTOTYPE:
10955 			if (!checkonly) {
10956 				mutex_enter(&connp->conn_lock);
10957 				connp->conn_proto = *i1;
10958 				mutex_exit(&connp->conn_lock);
10959 			}
10960 			break;	/* goto sizeof (int) option return */
10961 		case SO_ALLZONES:
10962 			if (!checkonly) {
10963 				mutex_enter(&connp->conn_lock);
10964 				if (IPCL_IS_BOUND(connp)) {
10965 					mutex_exit(&connp->conn_lock);
10966 					return (EINVAL);
10967 				}
10968 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10969 				mutex_exit(&connp->conn_lock);
10970 			}
10971 			break;	/* goto sizeof (int) option return */
10972 		case SO_ANON_MLP:
10973 			if (!checkonly) {
10974 				mutex_enter(&connp->conn_lock);
10975 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10976 				mutex_exit(&connp->conn_lock);
10977 			}
10978 			break;	/* goto sizeof (int) option return */
10979 		case SO_MAC_EXEMPT:
10980 			if (secpolicy_net_mac_aware(cr) != 0 ||
10981 			    IPCL_IS_BOUND(connp))
10982 				return (EACCES);
10983 			if (!checkonly) {
10984 				mutex_enter(&connp->conn_lock);
10985 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10986 				mutex_exit(&connp->conn_lock);
10987 			}
10988 			break;	/* goto sizeof (int) option return */
10989 		default:
10990 			/*
10991 			 * "soft" error (negative)
10992 			 * option not handled at this level
10993 			 * Note: Do not modify *outlenp
10994 			 */
10995 			return (-EINVAL);
10996 		}
10997 		break;
10998 	case IPPROTO_IP:
10999 		switch (name) {
11000 		case IP_NEXTHOP:
11001 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
11002 				return (EPERM);
11003 			/* FALLTHRU */
11004 		case IP_MULTICAST_IF:
11005 		case IP_DONTFAILOVER_IF: {
11006 			ipaddr_t addr = *i1;
11007 
11008 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
11009 			    first_mp);
11010 			if (error != 0)
11011 				return (error);
11012 			break;	/* goto sizeof (int) option return */
11013 		}
11014 
11015 		case IP_MULTICAST_TTL:
11016 			/* Recorded in transport above IP */
11017 			*outvalp = *invalp;
11018 			*outlenp = sizeof (uchar_t);
11019 			return (0);
11020 		case IP_MULTICAST_LOOP:
11021 			if (!checkonly) {
11022 				mutex_enter(&connp->conn_lock);
11023 				connp->conn_multicast_loop = *invalp ? 1 : 0;
11024 				mutex_exit(&connp->conn_lock);
11025 			}
11026 			*outvalp = *invalp;
11027 			*outlenp = sizeof (uchar_t);
11028 			return (0);
11029 		case IP_ADD_MEMBERSHIP:
11030 		case MCAST_JOIN_GROUP:
11031 		case IP_DROP_MEMBERSHIP:
11032 		case MCAST_LEAVE_GROUP: {
11033 			struct ip_mreq *mreqp;
11034 			struct group_req *greqp;
11035 			ire_t *ire;
11036 			boolean_t done = B_FALSE;
11037 			ipaddr_t group, ifaddr;
11038 			struct sockaddr_in *sin;
11039 			uint32_t *ifindexp;
11040 			boolean_t mcast_opt = B_TRUE;
11041 			mcast_record_t fmode;
11042 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11043 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11044 
11045 			switch (name) {
11046 			case IP_ADD_MEMBERSHIP:
11047 				mcast_opt = B_FALSE;
11048 				/* FALLTHRU */
11049 			case MCAST_JOIN_GROUP:
11050 				fmode = MODE_IS_EXCLUDE;
11051 				optfn = ip_opt_add_group;
11052 				break;
11053 
11054 			case IP_DROP_MEMBERSHIP:
11055 				mcast_opt = B_FALSE;
11056 				/* FALLTHRU */
11057 			case MCAST_LEAVE_GROUP:
11058 				fmode = MODE_IS_INCLUDE;
11059 				optfn = ip_opt_delete_group;
11060 				break;
11061 			}
11062 
11063 			if (mcast_opt) {
11064 				greqp = (struct group_req *)i1;
11065 				sin = (struct sockaddr_in *)&greqp->gr_group;
11066 				if (sin->sin_family != AF_INET) {
11067 					*outlenp = 0;
11068 					return (ENOPROTOOPT);
11069 				}
11070 				group = (ipaddr_t)sin->sin_addr.s_addr;
11071 				ifaddr = INADDR_ANY;
11072 				ifindexp = &greqp->gr_interface;
11073 			} else {
11074 				mreqp = (struct ip_mreq *)i1;
11075 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11076 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11077 				ifindexp = NULL;
11078 			}
11079 
11080 			/*
11081 			 * In the multirouting case, we need to replicate
11082 			 * the request on all interfaces that will take part
11083 			 * in replication.  We do so because multirouting is
11084 			 * reflective, thus we will probably receive multi-
11085 			 * casts on those interfaces.
11086 			 * The ip_multirt_apply_membership() succeeds if the
11087 			 * operation succeeds on at least one interface.
11088 			 */
11089 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11090 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11091 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11092 			if (ire != NULL) {
11093 				if (ire->ire_flags & RTF_MULTIRT) {
11094 					error = ip_multirt_apply_membership(
11095 					    optfn, ire, connp, checkonly, group,
11096 					    fmode, INADDR_ANY, first_mp);
11097 					done = B_TRUE;
11098 				}
11099 				ire_refrele(ire);
11100 			}
11101 			if (!done) {
11102 				error = optfn(connp, checkonly, group, ifaddr,
11103 				    ifindexp, fmode, INADDR_ANY, first_mp);
11104 			}
11105 			if (error) {
11106 				/*
11107 				 * EINPROGRESS is a soft error, needs retry
11108 				 * so don't make *outlenp zero.
11109 				 */
11110 				if (error != EINPROGRESS)
11111 					*outlenp = 0;
11112 				return (error);
11113 			}
11114 			/* OK return - copy input buffer into output buffer */
11115 			if (invalp != outvalp) {
11116 				/* don't trust bcopy for identical src/dst */
11117 				bcopy(invalp, outvalp, inlen);
11118 			}
11119 			*outlenp = inlen;
11120 			return (0);
11121 		}
11122 		case IP_BLOCK_SOURCE:
11123 		case IP_UNBLOCK_SOURCE:
11124 		case IP_ADD_SOURCE_MEMBERSHIP:
11125 		case IP_DROP_SOURCE_MEMBERSHIP:
11126 		case MCAST_BLOCK_SOURCE:
11127 		case MCAST_UNBLOCK_SOURCE:
11128 		case MCAST_JOIN_SOURCE_GROUP:
11129 		case MCAST_LEAVE_SOURCE_GROUP: {
11130 			struct ip_mreq_source *imreqp;
11131 			struct group_source_req *gsreqp;
11132 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11133 			uint32_t ifindex = 0;
11134 			mcast_record_t fmode;
11135 			struct sockaddr_in *sin;
11136 			ire_t *ire;
11137 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11138 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11139 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11140 
11141 			switch (name) {
11142 			case IP_BLOCK_SOURCE:
11143 				mcast_opt = B_FALSE;
11144 				/* FALLTHRU */
11145 			case MCAST_BLOCK_SOURCE:
11146 				fmode = MODE_IS_EXCLUDE;
11147 				optfn = ip_opt_add_group;
11148 				break;
11149 
11150 			case IP_UNBLOCK_SOURCE:
11151 				mcast_opt = B_FALSE;
11152 				/* FALLTHRU */
11153 			case MCAST_UNBLOCK_SOURCE:
11154 				fmode = MODE_IS_EXCLUDE;
11155 				optfn = ip_opt_delete_group;
11156 				break;
11157 
11158 			case IP_ADD_SOURCE_MEMBERSHIP:
11159 				mcast_opt = B_FALSE;
11160 				/* FALLTHRU */
11161 			case MCAST_JOIN_SOURCE_GROUP:
11162 				fmode = MODE_IS_INCLUDE;
11163 				optfn = ip_opt_add_group;
11164 				break;
11165 
11166 			case IP_DROP_SOURCE_MEMBERSHIP:
11167 				mcast_opt = B_FALSE;
11168 				/* FALLTHRU */
11169 			case MCAST_LEAVE_SOURCE_GROUP:
11170 				fmode = MODE_IS_INCLUDE;
11171 				optfn = ip_opt_delete_group;
11172 				break;
11173 			}
11174 
11175 			if (mcast_opt) {
11176 				gsreqp = (struct group_source_req *)i1;
11177 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11178 					*outlenp = 0;
11179 					return (ENOPROTOOPT);
11180 				}
11181 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11182 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11183 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11184 				src = (ipaddr_t)sin->sin_addr.s_addr;
11185 				ifindex = gsreqp->gsr_interface;
11186 			} else {
11187 				imreqp = (struct ip_mreq_source *)i1;
11188 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11189 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11190 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11191 			}
11192 
11193 			/*
11194 			 * In the multirouting case, we need to replicate
11195 			 * the request as noted in the mcast cases above.
11196 			 */
11197 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11198 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11199 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11200 			if (ire != NULL) {
11201 				if (ire->ire_flags & RTF_MULTIRT) {
11202 					error = ip_multirt_apply_membership(
11203 					    optfn, ire, connp, checkonly, grp,
11204 					    fmode, src, first_mp);
11205 					done = B_TRUE;
11206 				}
11207 				ire_refrele(ire);
11208 			}
11209 			if (!done) {
11210 				error = optfn(connp, checkonly, grp, ifaddr,
11211 				    &ifindex, fmode, src, first_mp);
11212 			}
11213 			if (error != 0) {
11214 				/*
11215 				 * EINPROGRESS is a soft error, needs retry
11216 				 * so don't make *outlenp zero.
11217 				 */
11218 				if (error != EINPROGRESS)
11219 					*outlenp = 0;
11220 				return (error);
11221 			}
11222 			/* OK return - copy input buffer into output buffer */
11223 			if (invalp != outvalp) {
11224 				bcopy(invalp, outvalp, inlen);
11225 			}
11226 			*outlenp = inlen;
11227 			return (0);
11228 		}
11229 		case IP_SEC_OPT:
11230 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11231 			if (error != 0) {
11232 				*outlenp = 0;
11233 				return (error);
11234 			}
11235 			break;
11236 		case IP_HDRINCL:
11237 		case IP_OPTIONS:
11238 		case T_IP_OPTIONS:
11239 		case IP_TOS:
11240 		case T_IP_TOS:
11241 		case IP_TTL:
11242 		case IP_RECVDSTADDR:
11243 		case IP_RECVOPTS:
11244 			/* OK return - copy input buffer into output buffer */
11245 			if (invalp != outvalp) {
11246 				/* don't trust bcopy for identical src/dst */
11247 				bcopy(invalp, outvalp, inlen);
11248 			}
11249 			*outlenp = inlen;
11250 			return (0);
11251 		case IP_RECVIF:
11252 			/* Retrieve the inbound interface index */
11253 			if (!checkonly) {
11254 				mutex_enter(&connp->conn_lock);
11255 				connp->conn_recvif = *i1 ? 1 : 0;
11256 				mutex_exit(&connp->conn_lock);
11257 			}
11258 			break;	/* goto sizeof (int) option return */
11259 		case IP_RECVPKTINFO:
11260 			if (!checkonly) {
11261 				mutex_enter(&connp->conn_lock);
11262 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11263 				mutex_exit(&connp->conn_lock);
11264 			}
11265 			break;	/* goto sizeof (int) option return */
11266 		case IP_RECVSLLA:
11267 			/* Retrieve the source link layer address */
11268 			if (!checkonly) {
11269 				mutex_enter(&connp->conn_lock);
11270 				connp->conn_recvslla = *i1 ? 1 : 0;
11271 				mutex_exit(&connp->conn_lock);
11272 			}
11273 			break;	/* goto sizeof (int) option return */
11274 		case MRT_INIT:
11275 		case MRT_DONE:
11276 		case MRT_ADD_VIF:
11277 		case MRT_DEL_VIF:
11278 		case MRT_ADD_MFC:
11279 		case MRT_DEL_MFC:
11280 		case MRT_ASSERT:
11281 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11282 				*outlenp = 0;
11283 				return (error);
11284 			}
11285 			error = ip_mrouter_set((int)name, q, checkonly,
11286 			    (uchar_t *)invalp, inlen, first_mp);
11287 			if (error) {
11288 				*outlenp = 0;
11289 				return (error);
11290 			}
11291 			/* OK return - copy input buffer into output buffer */
11292 			if (invalp != outvalp) {
11293 				/* don't trust bcopy for identical src/dst */
11294 				bcopy(invalp, outvalp, inlen);
11295 			}
11296 			*outlenp = inlen;
11297 			return (0);
11298 		case IP_BOUND_IF:
11299 		case IP_XMIT_IF:
11300 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11301 			    level, name, first_mp);
11302 			if (error != 0)
11303 				return (error);
11304 			break; 		/* goto sizeof (int) option return */
11305 
11306 		case IP_UNSPEC_SRC:
11307 			/* Allow sending with a zero source address */
11308 			if (!checkonly) {
11309 				mutex_enter(&connp->conn_lock);
11310 				connp->conn_unspec_src = *i1 ? 1 : 0;
11311 				mutex_exit(&connp->conn_lock);
11312 			}
11313 			break;	/* goto sizeof (int) option return */
11314 		default:
11315 			/*
11316 			 * "soft" error (negative)
11317 			 * option not handled at this level
11318 			 * Note: Do not modify *outlenp
11319 			 */
11320 			return (-EINVAL);
11321 		}
11322 		break;
11323 	case IPPROTO_IPV6:
11324 		switch (name) {
11325 		case IPV6_BOUND_IF:
11326 		case IPV6_BOUND_PIF:
11327 		case IPV6_DONTFAILOVER_IF:
11328 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11329 			    level, name, first_mp);
11330 			if (error != 0)
11331 				return (error);
11332 			break; 		/* goto sizeof (int) option return */
11333 
11334 		case IPV6_MULTICAST_IF:
11335 			/*
11336 			 * The only possible errors are EINPROGRESS and
11337 			 * EINVAL. EINPROGRESS will be restarted and is not
11338 			 * a hard error. We call this option on both V4 and V6
11339 			 * If both return EINVAL, then this call returns
11340 			 * EINVAL. If at least one of them succeeds we
11341 			 * return success.
11342 			 */
11343 			found = B_FALSE;
11344 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11345 			    level, name, first_mp);
11346 			if (error == EINPROGRESS)
11347 				return (error);
11348 			if (error == 0)
11349 				found = B_TRUE;
11350 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11351 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11352 			if (error == 0)
11353 				found = B_TRUE;
11354 			if (!found)
11355 				return (error);
11356 			break; 		/* goto sizeof (int) option return */
11357 
11358 		case IPV6_MULTICAST_HOPS:
11359 			/* Recorded in transport above IP */
11360 			break;	/* goto sizeof (int) option return */
11361 		case IPV6_MULTICAST_LOOP:
11362 			if (!checkonly) {
11363 				mutex_enter(&connp->conn_lock);
11364 				connp->conn_multicast_loop = *i1;
11365 				mutex_exit(&connp->conn_lock);
11366 			}
11367 			break;	/* goto sizeof (int) option return */
11368 		case IPV6_JOIN_GROUP:
11369 		case MCAST_JOIN_GROUP:
11370 		case IPV6_LEAVE_GROUP:
11371 		case MCAST_LEAVE_GROUP: {
11372 			struct ipv6_mreq *ip_mreqp;
11373 			struct group_req *greqp;
11374 			ire_t *ire;
11375 			boolean_t done = B_FALSE;
11376 			in6_addr_t groupv6;
11377 			uint32_t ifindex;
11378 			boolean_t mcast_opt = B_TRUE;
11379 			mcast_record_t fmode;
11380 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11381 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11382 
11383 			switch (name) {
11384 			case IPV6_JOIN_GROUP:
11385 				mcast_opt = B_FALSE;
11386 				/* FALLTHRU */
11387 			case MCAST_JOIN_GROUP:
11388 				fmode = MODE_IS_EXCLUDE;
11389 				optfn = ip_opt_add_group_v6;
11390 				break;
11391 
11392 			case IPV6_LEAVE_GROUP:
11393 				mcast_opt = B_FALSE;
11394 				/* FALLTHRU */
11395 			case MCAST_LEAVE_GROUP:
11396 				fmode = MODE_IS_INCLUDE;
11397 				optfn = ip_opt_delete_group_v6;
11398 				break;
11399 			}
11400 
11401 			if (mcast_opt) {
11402 				struct sockaddr_in *sin;
11403 				struct sockaddr_in6 *sin6;
11404 				greqp = (struct group_req *)i1;
11405 				if (greqp->gr_group.ss_family == AF_INET) {
11406 					sin = (struct sockaddr_in *)
11407 					    &(greqp->gr_group);
11408 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11409 					    &groupv6);
11410 				} else {
11411 					sin6 = (struct sockaddr_in6 *)
11412 					    &(greqp->gr_group);
11413 					groupv6 = sin6->sin6_addr;
11414 				}
11415 				ifindex = greqp->gr_interface;
11416 			} else {
11417 				ip_mreqp = (struct ipv6_mreq *)i1;
11418 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11419 				ifindex = ip_mreqp->ipv6mr_interface;
11420 			}
11421 			/*
11422 			 * In the multirouting case, we need to replicate
11423 			 * the request on all interfaces that will take part
11424 			 * in replication.  We do so because multirouting is
11425 			 * reflective, thus we will probably receive multi-
11426 			 * casts on those interfaces.
11427 			 * The ip_multirt_apply_membership_v6() succeeds if
11428 			 * the operation succeeds on at least one interface.
11429 			 */
11430 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11431 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11432 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11433 			if (ire != NULL) {
11434 				if (ire->ire_flags & RTF_MULTIRT) {
11435 					error = ip_multirt_apply_membership_v6(
11436 					    optfn, ire, connp, checkonly,
11437 					    &groupv6, fmode, &ipv6_all_zeros,
11438 					    first_mp);
11439 					done = B_TRUE;
11440 				}
11441 				ire_refrele(ire);
11442 			}
11443 			if (!done) {
11444 				error = optfn(connp, checkonly, &groupv6,
11445 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11446 			}
11447 			if (error) {
11448 				/*
11449 				 * EINPROGRESS is a soft error, needs retry
11450 				 * so don't make *outlenp zero.
11451 				 */
11452 				if (error != EINPROGRESS)
11453 					*outlenp = 0;
11454 				return (error);
11455 			}
11456 			/* OK return - copy input buffer into output buffer */
11457 			if (invalp != outvalp) {
11458 				/* don't trust bcopy for identical src/dst */
11459 				bcopy(invalp, outvalp, inlen);
11460 			}
11461 			*outlenp = inlen;
11462 			return (0);
11463 		}
11464 		case MCAST_BLOCK_SOURCE:
11465 		case MCAST_UNBLOCK_SOURCE:
11466 		case MCAST_JOIN_SOURCE_GROUP:
11467 		case MCAST_LEAVE_SOURCE_GROUP: {
11468 			struct group_source_req *gsreqp;
11469 			in6_addr_t v6grp, v6src;
11470 			uint32_t ifindex;
11471 			mcast_record_t fmode;
11472 			ire_t *ire;
11473 			boolean_t done = B_FALSE;
11474 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11475 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11476 
11477 			switch (name) {
11478 			case MCAST_BLOCK_SOURCE:
11479 				fmode = MODE_IS_EXCLUDE;
11480 				optfn = ip_opt_add_group_v6;
11481 				break;
11482 			case MCAST_UNBLOCK_SOURCE:
11483 				fmode = MODE_IS_EXCLUDE;
11484 				optfn = ip_opt_delete_group_v6;
11485 				break;
11486 			case MCAST_JOIN_SOURCE_GROUP:
11487 				fmode = MODE_IS_INCLUDE;
11488 				optfn = ip_opt_add_group_v6;
11489 				break;
11490 			case MCAST_LEAVE_SOURCE_GROUP:
11491 				fmode = MODE_IS_INCLUDE;
11492 				optfn = ip_opt_delete_group_v6;
11493 				break;
11494 			}
11495 
11496 			gsreqp = (struct group_source_req *)i1;
11497 			ifindex = gsreqp->gsr_interface;
11498 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11499 				struct sockaddr_in *s;
11500 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11501 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11502 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11503 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11504 			} else {
11505 				struct sockaddr_in6 *s6;
11506 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11507 				v6grp = s6->sin6_addr;
11508 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11509 				v6src = s6->sin6_addr;
11510 			}
11511 
11512 			/*
11513 			 * In the multirouting case, we need to replicate
11514 			 * the request as noted in the mcast cases above.
11515 			 */
11516 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11517 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11518 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11519 			if (ire != NULL) {
11520 				if (ire->ire_flags & RTF_MULTIRT) {
11521 					error = ip_multirt_apply_membership_v6(
11522 					    optfn, ire, connp, checkonly,
11523 					    &v6grp, fmode, &v6src, first_mp);
11524 					done = B_TRUE;
11525 				}
11526 				ire_refrele(ire);
11527 			}
11528 			if (!done) {
11529 				error = optfn(connp, checkonly, &v6grp,
11530 				    ifindex, fmode, &v6src, first_mp);
11531 			}
11532 			if (error != 0) {
11533 				/*
11534 				 * EINPROGRESS is a soft error, needs retry
11535 				 * so don't make *outlenp zero.
11536 				 */
11537 				if (error != EINPROGRESS)
11538 					*outlenp = 0;
11539 				return (error);
11540 			}
11541 			/* OK return - copy input buffer into output buffer */
11542 			if (invalp != outvalp) {
11543 				bcopy(invalp, outvalp, inlen);
11544 			}
11545 			*outlenp = inlen;
11546 			return (0);
11547 		}
11548 		case IPV6_UNICAST_HOPS:
11549 			/* Recorded in transport above IP */
11550 			break;	/* goto sizeof (int) option return */
11551 		case IPV6_UNSPEC_SRC:
11552 			/* Allow sending with a zero source address */
11553 			if (!checkonly) {
11554 				mutex_enter(&connp->conn_lock);
11555 				connp->conn_unspec_src = *i1 ? 1 : 0;
11556 				mutex_exit(&connp->conn_lock);
11557 			}
11558 			break;	/* goto sizeof (int) option return */
11559 		case IPV6_RECVPKTINFO:
11560 			if (!checkonly) {
11561 				mutex_enter(&connp->conn_lock);
11562 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11563 				mutex_exit(&connp->conn_lock);
11564 			}
11565 			break;	/* goto sizeof (int) option return */
11566 		case IPV6_RECVTCLASS:
11567 			if (!checkonly) {
11568 				if (*i1 < 0 || *i1 > 1) {
11569 					return (EINVAL);
11570 				}
11571 				mutex_enter(&connp->conn_lock);
11572 				connp->conn_ipv6_recvtclass = *i1;
11573 				mutex_exit(&connp->conn_lock);
11574 			}
11575 			break;
11576 		case IPV6_RECVPATHMTU:
11577 			if (!checkonly) {
11578 				if (*i1 < 0 || *i1 > 1) {
11579 					return (EINVAL);
11580 				}
11581 				mutex_enter(&connp->conn_lock);
11582 				connp->conn_ipv6_recvpathmtu = *i1;
11583 				mutex_exit(&connp->conn_lock);
11584 			}
11585 			break;
11586 		case IPV6_RECVHOPLIMIT:
11587 			if (!checkonly) {
11588 				mutex_enter(&connp->conn_lock);
11589 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11590 				mutex_exit(&connp->conn_lock);
11591 			}
11592 			break;	/* goto sizeof (int) option return */
11593 		case IPV6_RECVHOPOPTS:
11594 			if (!checkonly) {
11595 				mutex_enter(&connp->conn_lock);
11596 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11597 				mutex_exit(&connp->conn_lock);
11598 			}
11599 			break;	/* goto sizeof (int) option return */
11600 		case IPV6_RECVDSTOPTS:
11601 			if (!checkonly) {
11602 				mutex_enter(&connp->conn_lock);
11603 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11604 				mutex_exit(&connp->conn_lock);
11605 			}
11606 			break;	/* goto sizeof (int) option return */
11607 		case IPV6_RECVRTHDR:
11608 			if (!checkonly) {
11609 				mutex_enter(&connp->conn_lock);
11610 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11611 				mutex_exit(&connp->conn_lock);
11612 			}
11613 			break;	/* goto sizeof (int) option return */
11614 		case IPV6_RECVRTHDRDSTOPTS:
11615 			if (!checkonly) {
11616 				mutex_enter(&connp->conn_lock);
11617 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11618 				mutex_exit(&connp->conn_lock);
11619 			}
11620 			break;	/* goto sizeof (int) option return */
11621 		case IPV6_PKTINFO:
11622 			if (inlen == 0)
11623 				return (-EINVAL);	/* clearing option */
11624 			error = ip6_set_pktinfo(cr, connp,
11625 			    (struct in6_pktinfo *)invalp, first_mp);
11626 			if (error != 0)
11627 				*outlenp = 0;
11628 			else
11629 				*outlenp = inlen;
11630 			return (error);
11631 		case IPV6_NEXTHOP: {
11632 			struct sockaddr_in6 *sin6;
11633 
11634 			/* Verify that the nexthop is reachable */
11635 			if (inlen == 0)
11636 				return (-EINVAL);	/* clearing option */
11637 
11638 			sin6 = (struct sockaddr_in6 *)invalp;
11639 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11640 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11641 			    NULL, MATCH_IRE_DEFAULT, ipst);
11642 
11643 			if (ire == NULL) {
11644 				*outlenp = 0;
11645 				return (EHOSTUNREACH);
11646 			}
11647 			ire_refrele(ire);
11648 			return (-EINVAL);
11649 		}
11650 		case IPV6_SEC_OPT:
11651 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11652 			if (error != 0) {
11653 				*outlenp = 0;
11654 				return (error);
11655 			}
11656 			break;
11657 		case IPV6_SRC_PREFERENCES: {
11658 			/*
11659 			 * This is implemented strictly in the ip module
11660 			 * (here and in tcp_opt_*() to accomodate tcp
11661 			 * sockets).  Modules above ip pass this option
11662 			 * down here since ip is the only one that needs to
11663 			 * be aware of source address preferences.
11664 			 *
11665 			 * This socket option only affects connected
11666 			 * sockets that haven't already bound to a specific
11667 			 * IPv6 address.  In other words, sockets that
11668 			 * don't call bind() with an address other than the
11669 			 * unspecified address and that call connect().
11670 			 * ip_bind_connected_v6() passes these preferences
11671 			 * to the ipif_select_source_v6() function.
11672 			 */
11673 			if (inlen != sizeof (uint32_t))
11674 				return (EINVAL);
11675 			error = ip6_set_src_preferences(connp,
11676 			    *(uint32_t *)invalp);
11677 			if (error != 0) {
11678 				*outlenp = 0;
11679 				return (error);
11680 			} else {
11681 				*outlenp = sizeof (uint32_t);
11682 			}
11683 			break;
11684 		}
11685 		case IPV6_V6ONLY:
11686 			if (*i1 < 0 || *i1 > 1) {
11687 				return (EINVAL);
11688 			}
11689 			mutex_enter(&connp->conn_lock);
11690 			connp->conn_ipv6_v6only = *i1;
11691 			mutex_exit(&connp->conn_lock);
11692 			break;
11693 		default:
11694 			return (-EINVAL);
11695 		}
11696 		break;
11697 	default:
11698 		/*
11699 		 * "soft" error (negative)
11700 		 * option not handled at this level
11701 		 * Note: Do not modify *outlenp
11702 		 */
11703 		return (-EINVAL);
11704 	}
11705 	/*
11706 	 * Common case of return from an option that is sizeof (int)
11707 	 */
11708 	*(int *)outvalp = *i1;
11709 	*outlenp = sizeof (int);
11710 	return (0);
11711 }
11712 
11713 /*
11714  * This routine gets default values of certain options whose default
11715  * values are maintained by protocol specific code
11716  */
11717 /* ARGSUSED */
11718 int
11719 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11720 {
11721 	int *i1 = (int *)ptr;
11722 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11723 
11724 	switch (level) {
11725 	case IPPROTO_IP:
11726 		switch (name) {
11727 		case IP_MULTICAST_TTL:
11728 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11729 			return (sizeof (uchar_t));
11730 		case IP_MULTICAST_LOOP:
11731 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11732 			return (sizeof (uchar_t));
11733 		default:
11734 			return (-1);
11735 		}
11736 	case IPPROTO_IPV6:
11737 		switch (name) {
11738 		case IPV6_UNICAST_HOPS:
11739 			*i1 = ipst->ips_ipv6_def_hops;
11740 			return (sizeof (int));
11741 		case IPV6_MULTICAST_HOPS:
11742 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11743 			return (sizeof (int));
11744 		case IPV6_MULTICAST_LOOP:
11745 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11746 			return (sizeof (int));
11747 		case IPV6_V6ONLY:
11748 			*i1 = 1;
11749 			return (sizeof (int));
11750 		default:
11751 			return (-1);
11752 		}
11753 	default:
11754 		return (-1);
11755 	}
11756 	/* NOTREACHED */
11757 }
11758 
11759 /*
11760  * Given a destination address and a pointer to where to put the information
11761  * this routine fills in the mtuinfo.
11762  */
11763 int
11764 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11765     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11766 {
11767 	ire_t *ire;
11768 	ip_stack_t	*ipst = ns->netstack_ip;
11769 
11770 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11771 		return (-1);
11772 
11773 	bzero(mtuinfo, sizeof (*mtuinfo));
11774 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11775 	mtuinfo->ip6m_addr.sin6_port = port;
11776 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11777 
11778 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11779 	if (ire != NULL) {
11780 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11781 		ire_refrele(ire);
11782 	} else {
11783 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11784 	}
11785 	return (sizeof (struct ip6_mtuinfo));
11786 }
11787 
11788 /*
11789  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11790  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11791  * isn't.  This doesn't matter as the error checking is done properly for the
11792  * other MRT options coming in through ip_opt_set.
11793  */
11794 int
11795 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11796 {
11797 	conn_t		*connp = Q_TO_CONN(q);
11798 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11799 
11800 	switch (level) {
11801 	case IPPROTO_IP:
11802 		switch (name) {
11803 		case MRT_VERSION:
11804 		case MRT_ASSERT:
11805 			(void) ip_mrouter_get(name, q, ptr);
11806 			return (sizeof (int));
11807 		case IP_SEC_OPT:
11808 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11809 		case IP_NEXTHOP:
11810 			if (connp->conn_nexthop_set) {
11811 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11812 				return (sizeof (ipaddr_t));
11813 			} else
11814 				return (0);
11815 		case IP_RECVPKTINFO:
11816 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11817 			return (sizeof (int));
11818 		default:
11819 			break;
11820 		}
11821 		break;
11822 	case IPPROTO_IPV6:
11823 		switch (name) {
11824 		case IPV6_SEC_OPT:
11825 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11826 		case IPV6_SRC_PREFERENCES: {
11827 			return (ip6_get_src_preferences(connp,
11828 			    (uint32_t *)ptr));
11829 		}
11830 		case IPV6_V6ONLY:
11831 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11832 			return (sizeof (int));
11833 		case IPV6_PATHMTU:
11834 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11835 				(struct ip6_mtuinfo *)ptr,
11836 				connp->conn_netstack));
11837 		default:
11838 			break;
11839 		}
11840 		break;
11841 	default:
11842 		break;
11843 	}
11844 	return (-1);
11845 }
11846 
11847 /* Named Dispatch routine to get a current value out of our parameter table. */
11848 /* ARGSUSED */
11849 static int
11850 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11851 {
11852 	ipparam_t *ippa = (ipparam_t *)cp;
11853 
11854 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11855 	return (0);
11856 }
11857 
11858 /* ARGSUSED */
11859 static int
11860 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11861 {
11862 
11863 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11864 	return (0);
11865 }
11866 
11867 /*
11868  * Set ip{,6}_forwarding values.  This means walking through all of the
11869  * ill's and toggling their forwarding values.
11870  */
11871 /* ARGSUSED */
11872 static int
11873 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11874 {
11875 	long new_value;
11876 	int *forwarding_value = (int *)cp;
11877 	ill_t *walker;
11878 	boolean_t isv6;
11879 	ill_walk_context_t ctx;
11880 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11881 
11882 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11883 
11884 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11885 	    new_value < 0 || new_value > 1) {
11886 		return (EINVAL);
11887 	}
11888 
11889 	*forwarding_value = new_value;
11890 
11891 	/*
11892 	 * Regardless of the current value of ip_forwarding, set all per-ill
11893 	 * values of ip_forwarding to the value being set.
11894 	 *
11895 	 * Bring all the ill's up to date with the new global value.
11896 	 */
11897 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11898 
11899 	if (isv6)
11900 		walker = ILL_START_WALK_V6(&ctx, ipst);
11901 	else
11902 		walker = ILL_START_WALK_V4(&ctx, ipst);
11903 	for (; walker != NULL; walker = ill_next(&ctx, walker)) {
11904 		(void) ill_forward_set(q, mp, (new_value != 0),
11905 		    (caddr_t)walker);
11906 	}
11907 	rw_exit(&ipst->ips_ill_g_lock);
11908 
11909 	return (0);
11910 }
11911 
11912 /*
11913  * Walk through the param array specified registering each element with the
11914  * Named Dispatch handler. This is called only during init. So it is ok
11915  * not to acquire any locks
11916  */
11917 static boolean_t
11918 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11919     ipndp_t *ipnd, size_t ipnd_cnt)
11920 {
11921 	for (; ippa_cnt-- > 0; ippa++) {
11922 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11923 			if (!nd_load(ndp, ippa->ip_param_name,
11924 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11925 				nd_free(ndp);
11926 				return (B_FALSE);
11927 			}
11928 		}
11929 	}
11930 
11931 	for (; ipnd_cnt-- > 0; ipnd++) {
11932 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11933 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11934 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11935 			    ipnd->ip_ndp_data)) {
11936 				nd_free(ndp);
11937 				return (B_FALSE);
11938 			}
11939 		}
11940 	}
11941 
11942 	return (B_TRUE);
11943 }
11944 
11945 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11946 /* ARGSUSED */
11947 static int
11948 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11949 {
11950 	long		new_value;
11951 	ipparam_t	*ippa = (ipparam_t *)cp;
11952 
11953 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11954 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11955 		return (EINVAL);
11956 	}
11957 	ippa->ip_param_value = new_value;
11958 	return (0);
11959 }
11960 
11961 /*
11962  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11963  * When an ipf is passed here for the first time, if
11964  * we already have in-order fragments on the queue, we convert from the fast-
11965  * path reassembly scheme to the hard-case scheme.  From then on, additional
11966  * fragments are reassembled here.  We keep track of the start and end offsets
11967  * of each piece, and the number of holes in the chain.  When the hole count
11968  * goes to zero, we are done!
11969  *
11970  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11971  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11972  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11973  * after the call to ip_reassemble().
11974  */
11975 int
11976 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11977     size_t msg_len)
11978 {
11979 	uint_t	end;
11980 	mblk_t	*next_mp;
11981 	mblk_t	*mp1;
11982 	uint_t	offset;
11983 	boolean_t incr_dups = B_TRUE;
11984 	boolean_t offset_zero_seen = B_FALSE;
11985 	boolean_t pkt_boundary_checked = B_FALSE;
11986 
11987 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11988 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11989 
11990 	/* Add in byte count */
11991 	ipf->ipf_count += msg_len;
11992 	if (ipf->ipf_end) {
11993 		/*
11994 		 * We were part way through in-order reassembly, but now there
11995 		 * is a hole.  We walk through messages already queued, and
11996 		 * mark them for hard case reassembly.  We know that up till
11997 		 * now they were in order starting from offset zero.
11998 		 */
11999 		offset = 0;
12000 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12001 			IP_REASS_SET_START(mp1, offset);
12002 			if (offset == 0) {
12003 				ASSERT(ipf->ipf_nf_hdr_len != 0);
12004 				offset = -ipf->ipf_nf_hdr_len;
12005 			}
12006 			offset += mp1->b_wptr - mp1->b_rptr;
12007 			IP_REASS_SET_END(mp1, offset);
12008 		}
12009 		/* One hole at the end. */
12010 		ipf->ipf_hole_cnt = 1;
12011 		/* Brand it as a hard case, forever. */
12012 		ipf->ipf_end = 0;
12013 	}
12014 	/* Walk through all the new pieces. */
12015 	do {
12016 		end = start + (mp->b_wptr - mp->b_rptr);
12017 		/*
12018 		 * If start is 0, decrease 'end' only for the first mblk of
12019 		 * the fragment. Otherwise 'end' can get wrong value in the
12020 		 * second pass of the loop if first mblk is exactly the
12021 		 * size of ipf_nf_hdr_len.
12022 		 */
12023 		if (start == 0 && !offset_zero_seen) {
12024 			/* First segment */
12025 			ASSERT(ipf->ipf_nf_hdr_len != 0);
12026 			end -= ipf->ipf_nf_hdr_len;
12027 			offset_zero_seen = B_TRUE;
12028 		}
12029 		next_mp = mp->b_cont;
12030 		/*
12031 		 * We are checking to see if there is any interesing data
12032 		 * to process.  If there isn't and the mblk isn't the
12033 		 * one which carries the unfragmentable header then we
12034 		 * drop it.  It's possible to have just the unfragmentable
12035 		 * header come through without any data.  That needs to be
12036 		 * saved.
12037 		 *
12038 		 * If the assert at the top of this function holds then the
12039 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12040 		 * is infrequently traveled enough that the test is left in
12041 		 * to protect against future code changes which break that
12042 		 * invariant.
12043 		 */
12044 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12045 			/* Empty.  Blast it. */
12046 			IP_REASS_SET_START(mp, 0);
12047 			IP_REASS_SET_END(mp, 0);
12048 			/*
12049 			 * If the ipf points to the mblk we are about to free,
12050 			 * update ipf to point to the next mblk (or NULL
12051 			 * if none).
12052 			 */
12053 			if (ipf->ipf_mp->b_cont == mp)
12054 				ipf->ipf_mp->b_cont = next_mp;
12055 			freeb(mp);
12056 			continue;
12057 		}
12058 		mp->b_cont = NULL;
12059 		IP_REASS_SET_START(mp, start);
12060 		IP_REASS_SET_END(mp, end);
12061 		if (!ipf->ipf_tail_mp) {
12062 			ipf->ipf_tail_mp = mp;
12063 			ipf->ipf_mp->b_cont = mp;
12064 			if (start == 0 || !more) {
12065 				ipf->ipf_hole_cnt = 1;
12066 				/*
12067 				 * if the first fragment comes in more than one
12068 				 * mblk, this loop will be executed for each
12069 				 * mblk. Need to adjust hole count so exiting
12070 				 * this routine will leave hole count at 1.
12071 				 */
12072 				if (next_mp)
12073 					ipf->ipf_hole_cnt++;
12074 			} else
12075 				ipf->ipf_hole_cnt = 2;
12076 			continue;
12077 		} else if (ipf->ipf_last_frag_seen && !more &&
12078 			    !pkt_boundary_checked) {
12079 			/*
12080 			 * We check datagram boundary only if this fragment
12081 			 * claims to be the last fragment and we have seen a
12082 			 * last fragment in the past too. We do this only
12083 			 * once for a given fragment.
12084 			 *
12085 			 * start cannot be 0 here as fragments with start=0
12086 			 * and MF=0 gets handled as a complete packet. These
12087 			 * fragments should not reach here.
12088 			 */
12089 
12090 			if (start + msgdsize(mp) !=
12091 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12092 				/*
12093 				 * We have two fragments both of which claim
12094 				 * to be the last fragment but gives conflicting
12095 				 * information about the whole datagram size.
12096 				 * Something fishy is going on. Drop the
12097 				 * fragment and free up the reassembly list.
12098 				 */
12099 				return (IP_REASS_FAILED);
12100 			}
12101 
12102 			/*
12103 			 * We shouldn't come to this code block again for this
12104 			 * particular fragment.
12105 			 */
12106 			pkt_boundary_checked = B_TRUE;
12107 		}
12108 
12109 		/* New stuff at or beyond tail? */
12110 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12111 		if (start >= offset) {
12112 			if (ipf->ipf_last_frag_seen) {
12113 				/* current fragment is beyond last fragment */
12114 				return (IP_REASS_FAILED);
12115 			}
12116 			/* Link it on end. */
12117 			ipf->ipf_tail_mp->b_cont = mp;
12118 			ipf->ipf_tail_mp = mp;
12119 			if (more) {
12120 				if (start != offset)
12121 					ipf->ipf_hole_cnt++;
12122 			} else if (start == offset && next_mp == NULL)
12123 					ipf->ipf_hole_cnt--;
12124 			continue;
12125 		}
12126 		mp1 = ipf->ipf_mp->b_cont;
12127 		offset = IP_REASS_START(mp1);
12128 		/* New stuff at the front? */
12129 		if (start < offset) {
12130 			if (start == 0) {
12131 				if (end >= offset) {
12132 					/* Nailed the hole at the begining. */
12133 					ipf->ipf_hole_cnt--;
12134 				}
12135 			} else if (end < offset) {
12136 				/*
12137 				 * A hole, stuff, and a hole where there used
12138 				 * to be just a hole.
12139 				 */
12140 				ipf->ipf_hole_cnt++;
12141 			}
12142 			mp->b_cont = mp1;
12143 			/* Check for overlap. */
12144 			while (end > offset) {
12145 				if (end < IP_REASS_END(mp1)) {
12146 					mp->b_wptr -= end - offset;
12147 					IP_REASS_SET_END(mp, offset);
12148 					BUMP_MIB(ill->ill_ip_mib,
12149 					    ipIfStatsReasmPartDups);
12150 					break;
12151 				}
12152 				/* Did we cover another hole? */
12153 				if ((mp1->b_cont &&
12154 				    IP_REASS_END(mp1) !=
12155 				    IP_REASS_START(mp1->b_cont) &&
12156 				    end >= IP_REASS_START(mp1->b_cont)) ||
12157 				    (!ipf->ipf_last_frag_seen && !more)) {
12158 					ipf->ipf_hole_cnt--;
12159 				}
12160 				/* Clip out mp1. */
12161 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12162 					/*
12163 					 * After clipping out mp1, this guy
12164 					 * is now hanging off the end.
12165 					 */
12166 					ipf->ipf_tail_mp = mp;
12167 				}
12168 				IP_REASS_SET_START(mp1, 0);
12169 				IP_REASS_SET_END(mp1, 0);
12170 				/* Subtract byte count */
12171 				ipf->ipf_count -= mp1->b_datap->db_lim -
12172 				    mp1->b_datap->db_base;
12173 				freeb(mp1);
12174 				BUMP_MIB(ill->ill_ip_mib,
12175 				    ipIfStatsReasmPartDups);
12176 				mp1 = mp->b_cont;
12177 				if (!mp1)
12178 					break;
12179 				offset = IP_REASS_START(mp1);
12180 			}
12181 			ipf->ipf_mp->b_cont = mp;
12182 			continue;
12183 		}
12184 		/*
12185 		 * The new piece starts somewhere between the start of the head
12186 		 * and before the end of the tail.
12187 		 */
12188 		for (; mp1; mp1 = mp1->b_cont) {
12189 			offset = IP_REASS_END(mp1);
12190 			if (start < offset) {
12191 				if (end <= offset) {
12192 					/* Nothing new. */
12193 					IP_REASS_SET_START(mp, 0);
12194 					IP_REASS_SET_END(mp, 0);
12195 					/* Subtract byte count */
12196 					ipf->ipf_count -= mp->b_datap->db_lim -
12197 					    mp->b_datap->db_base;
12198 					if (incr_dups) {
12199 						ipf->ipf_num_dups++;
12200 						incr_dups = B_FALSE;
12201 					}
12202 					freeb(mp);
12203 					BUMP_MIB(ill->ill_ip_mib,
12204 					    ipIfStatsReasmDuplicates);
12205 					break;
12206 				}
12207 				/*
12208 				 * Trim redundant stuff off beginning of new
12209 				 * piece.
12210 				 */
12211 				IP_REASS_SET_START(mp, offset);
12212 				mp->b_rptr += offset - start;
12213 				BUMP_MIB(ill->ill_ip_mib,
12214 				    ipIfStatsReasmPartDups);
12215 				start = offset;
12216 				if (!mp1->b_cont) {
12217 					/*
12218 					 * After trimming, this guy is now
12219 					 * hanging off the end.
12220 					 */
12221 					mp1->b_cont = mp;
12222 					ipf->ipf_tail_mp = mp;
12223 					if (!more) {
12224 						ipf->ipf_hole_cnt--;
12225 					}
12226 					break;
12227 				}
12228 			}
12229 			if (start >= IP_REASS_START(mp1->b_cont))
12230 				continue;
12231 			/* Fill a hole */
12232 			if (start > offset)
12233 				ipf->ipf_hole_cnt++;
12234 			mp->b_cont = mp1->b_cont;
12235 			mp1->b_cont = mp;
12236 			mp1 = mp->b_cont;
12237 			offset = IP_REASS_START(mp1);
12238 			if (end >= offset) {
12239 				ipf->ipf_hole_cnt--;
12240 				/* Check for overlap. */
12241 				while (end > offset) {
12242 					if (end < IP_REASS_END(mp1)) {
12243 						mp->b_wptr -= end - offset;
12244 						IP_REASS_SET_END(mp, offset);
12245 						/*
12246 						 * TODO we might bump
12247 						 * this up twice if there is
12248 						 * overlap at both ends.
12249 						 */
12250 						BUMP_MIB(ill->ill_ip_mib,
12251 						    ipIfStatsReasmPartDups);
12252 						break;
12253 					}
12254 					/* Did we cover another hole? */
12255 					if ((mp1->b_cont &&
12256 					    IP_REASS_END(mp1)
12257 					    != IP_REASS_START(mp1->b_cont) &&
12258 					    end >=
12259 					    IP_REASS_START(mp1->b_cont)) ||
12260 					    (!ipf->ipf_last_frag_seen &&
12261 					    !more)) {
12262 						ipf->ipf_hole_cnt--;
12263 					}
12264 					/* Clip out mp1. */
12265 					if ((mp->b_cont = mp1->b_cont) ==
12266 					    NULL) {
12267 						/*
12268 						 * After clipping out mp1,
12269 						 * this guy is now hanging
12270 						 * off the end.
12271 						 */
12272 						ipf->ipf_tail_mp = mp;
12273 					}
12274 					IP_REASS_SET_START(mp1, 0);
12275 					IP_REASS_SET_END(mp1, 0);
12276 					/* Subtract byte count */
12277 					ipf->ipf_count -=
12278 					    mp1->b_datap->db_lim -
12279 					    mp1->b_datap->db_base;
12280 					freeb(mp1);
12281 					BUMP_MIB(ill->ill_ip_mib,
12282 					    ipIfStatsReasmPartDups);
12283 					mp1 = mp->b_cont;
12284 					if (!mp1)
12285 						break;
12286 					offset = IP_REASS_START(mp1);
12287 				}
12288 			}
12289 			break;
12290 		}
12291 	} while (start = end, mp = next_mp);
12292 
12293 	/* Fragment just processed could be the last one. Remember this fact */
12294 	if (!more)
12295 		ipf->ipf_last_frag_seen = B_TRUE;
12296 
12297 	/* Still got holes? */
12298 	if (ipf->ipf_hole_cnt)
12299 		return (IP_REASS_PARTIAL);
12300 	/* Clean up overloaded fields to avoid upstream disasters. */
12301 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12302 		IP_REASS_SET_START(mp1, 0);
12303 		IP_REASS_SET_END(mp1, 0);
12304 	}
12305 	return (IP_REASS_COMPLETE);
12306 }
12307 
12308 /*
12309  * ipsec processing for the fast path, used for input UDP Packets
12310  */
12311 static boolean_t
12312 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12313     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12314 {
12315 	uint32_t	ill_index;
12316 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12317 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12318 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12319 
12320 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12321 	/* The ill_index of the incoming ILL */
12322 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12323 
12324 	/* pass packet up to the transport */
12325 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12326 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12327 		    NULL, mctl_present);
12328 		if (*first_mpp == NULL) {
12329 			return (B_FALSE);
12330 		}
12331 	}
12332 
12333 	/* Initiate IPPF processing for fastpath UDP */
12334 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12335 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12336 		if (*mpp == NULL) {
12337 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12338 			    "deferred/dropped during IPPF processing\n"));
12339 			return (B_FALSE);
12340 		}
12341 	}
12342 	/*
12343 	 * We make the checks as below since we are in the fast path
12344 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12345 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12346 	 */
12347 	if (connp->conn_recvif || connp->conn_recvslla ||
12348 	    connp->conn_ip_recvpktinfo) {
12349 		if (connp->conn_recvif) {
12350 			in_flags = IPF_RECVIF;
12351 		}
12352 		/*
12353 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12354 		 * so the flag passed to ip_add_info is based on IP version
12355 		 * of connp.
12356 		 */
12357 		if (connp->conn_ip_recvpktinfo) {
12358 			if (connp->conn_af_isv6) {
12359 				/*
12360 				 * V6 only needs index
12361 				 */
12362 				in_flags |= IPF_RECVIF;
12363 			} else {
12364 				/*
12365 				 * V4 needs index + matching address.
12366 				 */
12367 				in_flags |= IPF_RECVADDR;
12368 			}
12369 		}
12370 		if (connp->conn_recvslla) {
12371 			in_flags |= IPF_RECVSLLA;
12372 		}
12373 		/*
12374 		 * since in_flags are being set ill will be
12375 		 * referenced in ip_add_info, so it better not
12376 		 * be NULL.
12377 		 */
12378 		/*
12379 		 * the actual data will be contained in b_cont
12380 		 * upon successful return of the following call.
12381 		 * If the call fails then the original mblk is
12382 		 * returned.
12383 		 */
12384 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12385 		    ipst);
12386 	}
12387 
12388 	return (B_TRUE);
12389 }
12390 
12391 /*
12392  * Fragmentation reassembly.  Each ILL has a hash table for
12393  * queuing packets undergoing reassembly for all IPIFs
12394  * associated with the ILL.  The hash is based on the packet
12395  * IP ident field.  The ILL frag hash table was allocated
12396  * as a timer block at the time the ILL was created.  Whenever
12397  * there is anything on the reassembly queue, the timer will
12398  * be running.  Returns B_TRUE if successful else B_FALSE;
12399  * frees mp on failure.
12400  */
12401 static boolean_t
12402 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12403     uint32_t *cksum_val, uint16_t *cksum_flags)
12404 {
12405 	uint32_t	frag_offset_flags;
12406 	ill_t		*ill = (ill_t *)q->q_ptr;
12407 	mblk_t		*mp = *mpp;
12408 	mblk_t		*t_mp;
12409 	ipaddr_t	dst;
12410 	uint8_t		proto = ipha->ipha_protocol;
12411 	uint32_t	sum_val;
12412 	uint16_t	sum_flags;
12413 	ipf_t		*ipf;
12414 	ipf_t		**ipfp;
12415 	ipfb_t		*ipfb;
12416 	uint16_t	ident;
12417 	uint32_t	offset;
12418 	ipaddr_t	src;
12419 	uint_t		hdr_length;
12420 	uint32_t	end;
12421 	mblk_t		*mp1;
12422 	mblk_t		*tail_mp;
12423 	size_t		count;
12424 	size_t		msg_len;
12425 	uint8_t		ecn_info = 0;
12426 	uint32_t	packet_size;
12427 	boolean_t	pruned = B_FALSE;
12428 	ip_stack_t *ipst = ill->ill_ipst;
12429 
12430 	if (cksum_val != NULL)
12431 		*cksum_val = 0;
12432 	if (cksum_flags != NULL)
12433 		*cksum_flags = 0;
12434 
12435 	/*
12436 	 * Drop the fragmented as early as possible, if
12437 	 * we don't have resource(s) to re-assemble.
12438 	 */
12439 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12440 		freemsg(mp);
12441 		return (B_FALSE);
12442 	}
12443 
12444 	/* Check for fragmentation offset; return if there's none */
12445 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12446 	    (IPH_MF | IPH_OFFSET)) == 0)
12447 		return (B_TRUE);
12448 
12449 	/*
12450 	 * We utilize hardware computed checksum info only for UDP since
12451 	 * IP fragmentation is a normal occurence for the protocol.  In
12452 	 * addition, checksum offload support for IP fragments carrying
12453 	 * UDP payload is commonly implemented across network adapters.
12454 	 */
12455 	ASSERT(ill != NULL);
12456 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12457 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12458 		mblk_t *mp1 = mp->b_cont;
12459 		int32_t len;
12460 
12461 		/* Record checksum information from the packet */
12462 		sum_val = (uint32_t)DB_CKSUM16(mp);
12463 		sum_flags = DB_CKSUMFLAGS(mp);
12464 
12465 		/* IP payload offset from beginning of mblk */
12466 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12467 
12468 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12469 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12470 		    offset >= DB_CKSUMSTART(mp) &&
12471 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12472 			uint32_t adj;
12473 			/*
12474 			 * Partial checksum has been calculated by hardware
12475 			 * and attached to the packet; in addition, any
12476 			 * prepended extraneous data is even byte aligned.
12477 			 * If any such data exists, we adjust the checksum;
12478 			 * this would also handle any postpended data.
12479 			 */
12480 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12481 			    mp, mp1, len, adj);
12482 
12483 			/* One's complement subtract extraneous checksum */
12484 			if (adj >= sum_val)
12485 				sum_val = ~(adj - sum_val) & 0xFFFF;
12486 			else
12487 				sum_val -= adj;
12488 		}
12489 	} else {
12490 		sum_val = 0;
12491 		sum_flags = 0;
12492 	}
12493 
12494 	/* Clear hardware checksumming flag */
12495 	DB_CKSUMFLAGS(mp) = 0;
12496 
12497 	ident = ipha->ipha_ident;
12498 	offset = (frag_offset_flags << 3) & 0xFFFF;
12499 	src = ipha->ipha_src;
12500 	dst = ipha->ipha_dst;
12501 	hdr_length = IPH_HDR_LENGTH(ipha);
12502 	end = ntohs(ipha->ipha_length) - hdr_length;
12503 
12504 	/* If end == 0 then we have a packet with no data, so just free it */
12505 	if (end == 0) {
12506 		freemsg(mp);
12507 		return (B_FALSE);
12508 	}
12509 
12510 	/* Record the ECN field info. */
12511 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12512 	if (offset != 0) {
12513 		/*
12514 		 * If this isn't the first piece, strip the header, and
12515 		 * add the offset to the end value.
12516 		 */
12517 		mp->b_rptr += hdr_length;
12518 		end += offset;
12519 	}
12520 
12521 	msg_len = MBLKSIZE(mp);
12522 	tail_mp = mp;
12523 	while (tail_mp->b_cont != NULL) {
12524 		tail_mp = tail_mp->b_cont;
12525 		msg_len += MBLKSIZE(tail_mp);
12526 	}
12527 
12528 	/* If the reassembly list for this ILL will get too big, prune it */
12529 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12530 	    ipst->ips_ip_reass_queue_bytes) {
12531 		ill_frag_prune(ill,
12532 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12533 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12534 		pruned = B_TRUE;
12535 	}
12536 
12537 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12538 	mutex_enter(&ipfb->ipfb_lock);
12539 
12540 	ipfp = &ipfb->ipfb_ipf;
12541 	/* Try to find an existing fragment queue for this packet. */
12542 	for (;;) {
12543 		ipf = ipfp[0];
12544 		if (ipf != NULL) {
12545 			/*
12546 			 * It has to match on ident and src/dst address.
12547 			 */
12548 			if (ipf->ipf_ident == ident &&
12549 			    ipf->ipf_src == src &&
12550 			    ipf->ipf_dst == dst &&
12551 			    ipf->ipf_protocol == proto) {
12552 				/*
12553 				 * If we have received too many
12554 				 * duplicate fragments for this packet
12555 				 * free it.
12556 				 */
12557 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12558 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12559 					freemsg(mp);
12560 					mutex_exit(&ipfb->ipfb_lock);
12561 					return (B_FALSE);
12562 				}
12563 				/* Found it. */
12564 				break;
12565 			}
12566 			ipfp = &ipf->ipf_hash_next;
12567 			continue;
12568 		}
12569 
12570 		/*
12571 		 * If we pruned the list, do we want to store this new
12572 		 * fragment?. We apply an optimization here based on the
12573 		 * fact that most fragments will be received in order.
12574 		 * So if the offset of this incoming fragment is zero,
12575 		 * it is the first fragment of a new packet. We will
12576 		 * keep it.  Otherwise drop the fragment, as we have
12577 		 * probably pruned the packet already (since the
12578 		 * packet cannot be found).
12579 		 */
12580 		if (pruned && offset != 0) {
12581 			mutex_exit(&ipfb->ipfb_lock);
12582 			freemsg(mp);
12583 			return (B_FALSE);
12584 		}
12585 
12586 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12587 			/*
12588 			 * Too many fragmented packets in this hash
12589 			 * bucket. Free the oldest.
12590 			 */
12591 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12592 		}
12593 
12594 		/* New guy.  Allocate a frag message. */
12595 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12596 		if (mp1 == NULL) {
12597 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12598 			freemsg(mp);
12599 reass_done:
12600 			mutex_exit(&ipfb->ipfb_lock);
12601 			return (B_FALSE);
12602 		}
12603 
12604 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12605 		mp1->b_cont = mp;
12606 
12607 		/* Initialize the fragment header. */
12608 		ipf = (ipf_t *)mp1->b_rptr;
12609 		ipf->ipf_mp = mp1;
12610 		ipf->ipf_ptphn = ipfp;
12611 		ipfp[0] = ipf;
12612 		ipf->ipf_hash_next = NULL;
12613 		ipf->ipf_ident = ident;
12614 		ipf->ipf_protocol = proto;
12615 		ipf->ipf_src = src;
12616 		ipf->ipf_dst = dst;
12617 		ipf->ipf_nf_hdr_len = 0;
12618 		/* Record reassembly start time. */
12619 		ipf->ipf_timestamp = gethrestime_sec();
12620 		/* Record ipf generation and account for frag header */
12621 		ipf->ipf_gen = ill->ill_ipf_gen++;
12622 		ipf->ipf_count = MBLKSIZE(mp1);
12623 		ipf->ipf_last_frag_seen = B_FALSE;
12624 		ipf->ipf_ecn = ecn_info;
12625 		ipf->ipf_num_dups = 0;
12626 		ipfb->ipfb_frag_pkts++;
12627 		ipf->ipf_checksum = 0;
12628 		ipf->ipf_checksum_flags = 0;
12629 
12630 		/* Store checksum value in fragment header */
12631 		if (sum_flags != 0) {
12632 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12633 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12634 			ipf->ipf_checksum = sum_val;
12635 			ipf->ipf_checksum_flags = sum_flags;
12636 		}
12637 
12638 		/*
12639 		 * We handle reassembly two ways.  In the easy case,
12640 		 * where all the fragments show up in order, we do
12641 		 * minimal bookkeeping, and just clip new pieces on
12642 		 * the end.  If we ever see a hole, then we go off
12643 		 * to ip_reassemble which has to mark the pieces and
12644 		 * keep track of the number of holes, etc.  Obviously,
12645 		 * the point of having both mechanisms is so we can
12646 		 * handle the easy case as efficiently as possible.
12647 		 */
12648 		if (offset == 0) {
12649 			/* Easy case, in-order reassembly so far. */
12650 			ipf->ipf_count += msg_len;
12651 			ipf->ipf_tail_mp = tail_mp;
12652 			/*
12653 			 * Keep track of next expected offset in
12654 			 * ipf_end.
12655 			 */
12656 			ipf->ipf_end = end;
12657 			ipf->ipf_nf_hdr_len = hdr_length;
12658 		} else {
12659 			/* Hard case, hole at the beginning. */
12660 			ipf->ipf_tail_mp = NULL;
12661 			/*
12662 			 * ipf_end == 0 means that we have given up
12663 			 * on easy reassembly.
12664 			 */
12665 			ipf->ipf_end = 0;
12666 
12667 			/* Forget checksum offload from now on */
12668 			ipf->ipf_checksum_flags = 0;
12669 
12670 			/*
12671 			 * ipf_hole_cnt is set by ip_reassemble.
12672 			 * ipf_count is updated by ip_reassemble.
12673 			 * No need to check for return value here
12674 			 * as we don't expect reassembly to complete
12675 			 * or fail for the first fragment itself.
12676 			 */
12677 			(void) ip_reassemble(mp, ipf,
12678 			    (frag_offset_flags & IPH_OFFSET) << 3,
12679 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12680 		}
12681 		/* Update per ipfb and ill byte counts */
12682 		ipfb->ipfb_count += ipf->ipf_count;
12683 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12684 		ill->ill_frag_count += ipf->ipf_count;
12685 		/* If the frag timer wasn't already going, start it. */
12686 		mutex_enter(&ill->ill_lock);
12687 		ill_frag_timer_start(ill);
12688 		mutex_exit(&ill->ill_lock);
12689 		goto reass_done;
12690 	}
12691 
12692 	/*
12693 	 * If the packet's flag has changed (it could be coming up
12694 	 * from an interface different than the previous, therefore
12695 	 * possibly different checksum capability), then forget about
12696 	 * any stored checksum states.  Otherwise add the value to
12697 	 * the existing one stored in the fragment header.
12698 	 */
12699 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12700 		sum_val += ipf->ipf_checksum;
12701 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12702 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12703 		ipf->ipf_checksum = sum_val;
12704 	} else if (ipf->ipf_checksum_flags != 0) {
12705 		/* Forget checksum offload from now on */
12706 		ipf->ipf_checksum_flags = 0;
12707 	}
12708 
12709 	/*
12710 	 * We have a new piece of a datagram which is already being
12711 	 * reassembled.  Update the ECN info if all IP fragments
12712 	 * are ECN capable.  If there is one which is not, clear
12713 	 * all the info.  If there is at least one which has CE
12714 	 * code point, IP needs to report that up to transport.
12715 	 */
12716 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12717 		if (ecn_info == IPH_ECN_CE)
12718 			ipf->ipf_ecn = IPH_ECN_CE;
12719 	} else {
12720 		ipf->ipf_ecn = IPH_ECN_NECT;
12721 	}
12722 	if (offset && ipf->ipf_end == offset) {
12723 		/* The new fragment fits at the end */
12724 		ipf->ipf_tail_mp->b_cont = mp;
12725 		/* Update the byte count */
12726 		ipf->ipf_count += msg_len;
12727 		/* Update per ipfb and ill byte counts */
12728 		ipfb->ipfb_count += msg_len;
12729 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12730 		ill->ill_frag_count += msg_len;
12731 		if (frag_offset_flags & IPH_MF) {
12732 			/* More to come. */
12733 			ipf->ipf_end = end;
12734 			ipf->ipf_tail_mp = tail_mp;
12735 			goto reass_done;
12736 		}
12737 	} else {
12738 		/* Go do the hard cases. */
12739 		int ret;
12740 
12741 		if (offset == 0)
12742 			ipf->ipf_nf_hdr_len = hdr_length;
12743 
12744 		/* Save current byte count */
12745 		count = ipf->ipf_count;
12746 		ret = ip_reassemble(mp, ipf,
12747 		    (frag_offset_flags & IPH_OFFSET) << 3,
12748 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12749 		/* Count of bytes added and subtracted (freeb()ed) */
12750 		count = ipf->ipf_count - count;
12751 		if (count) {
12752 			/* Update per ipfb and ill byte counts */
12753 			ipfb->ipfb_count += count;
12754 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12755 			ill->ill_frag_count += count;
12756 		}
12757 		if (ret == IP_REASS_PARTIAL) {
12758 			goto reass_done;
12759 		} else if (ret == IP_REASS_FAILED) {
12760 			/* Reassembly failed. Free up all resources */
12761 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12762 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12763 				IP_REASS_SET_START(t_mp, 0);
12764 				IP_REASS_SET_END(t_mp, 0);
12765 			}
12766 			freemsg(mp);
12767 			goto reass_done;
12768 		}
12769 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12770 	}
12771 	/*
12772 	 * We have completed reassembly.  Unhook the frag header from
12773 	 * the reassembly list.
12774 	 *
12775 	 * Before we free the frag header, record the ECN info
12776 	 * to report back to the transport.
12777 	 */
12778 	ecn_info = ipf->ipf_ecn;
12779 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12780 	ipfp = ipf->ipf_ptphn;
12781 
12782 	/* We need to supply these to caller */
12783 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12784 		sum_val = ipf->ipf_checksum;
12785 	else
12786 		sum_val = 0;
12787 
12788 	mp1 = ipf->ipf_mp;
12789 	count = ipf->ipf_count;
12790 	ipf = ipf->ipf_hash_next;
12791 	if (ipf != NULL)
12792 		ipf->ipf_ptphn = ipfp;
12793 	ipfp[0] = ipf;
12794 	ill->ill_frag_count -= count;
12795 	ASSERT(ipfb->ipfb_count >= count);
12796 	ipfb->ipfb_count -= count;
12797 	ipfb->ipfb_frag_pkts--;
12798 	mutex_exit(&ipfb->ipfb_lock);
12799 	/* Ditch the frag header. */
12800 	mp = mp1->b_cont;
12801 
12802 	freeb(mp1);
12803 
12804 	/* Restore original IP length in header. */
12805 	packet_size = (uint32_t)msgdsize(mp);
12806 	if (packet_size > IP_MAXPACKET) {
12807 		freemsg(mp);
12808 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12809 		return (B_FALSE);
12810 	}
12811 
12812 	if (DB_REF(mp) > 1) {
12813 		mblk_t *mp2 = copymsg(mp);
12814 
12815 		freemsg(mp);
12816 		if (mp2 == NULL) {
12817 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12818 			return (B_FALSE);
12819 		}
12820 		mp = mp2;
12821 	}
12822 	ipha = (ipha_t *)mp->b_rptr;
12823 
12824 	ipha->ipha_length = htons((uint16_t)packet_size);
12825 	/* We're now complete, zip the frag state */
12826 	ipha->ipha_fragment_offset_and_flags = 0;
12827 	/* Record the ECN info. */
12828 	ipha->ipha_type_of_service &= 0xFC;
12829 	ipha->ipha_type_of_service |= ecn_info;
12830 	*mpp = mp;
12831 
12832 	/* Reassembly is successful; return checksum information if needed */
12833 	if (cksum_val != NULL)
12834 		*cksum_val = sum_val;
12835 	if (cksum_flags != NULL)
12836 		*cksum_flags = sum_flags;
12837 
12838 	return (B_TRUE);
12839 }
12840 
12841 /*
12842  * Perform ip header check sum update local options.
12843  * return B_TRUE if all is well, else return B_FALSE and release
12844  * the mp. caller is responsible for decrementing ire ref cnt.
12845  */
12846 static boolean_t
12847 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12848     ip_stack_t *ipst)
12849 {
12850 	mblk_t		*first_mp;
12851 	boolean_t	mctl_present;
12852 	uint16_t	sum;
12853 
12854 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12855 	/*
12856 	 * Don't do the checksum if it has gone through AH/ESP
12857 	 * processing.
12858 	 */
12859 	if (!mctl_present) {
12860 		sum = ip_csum_hdr(ipha);
12861 		if (sum != 0) {
12862 			if (ill != NULL) {
12863 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12864 			} else {
12865 				BUMP_MIB(&ipst->ips_ip_mib,
12866 				    ipIfStatsInCksumErrs);
12867 			}
12868 			freemsg(first_mp);
12869 			return (B_FALSE);
12870 		}
12871 	}
12872 
12873 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12874 		if (mctl_present)
12875 			freeb(first_mp);
12876 		return (B_FALSE);
12877 	}
12878 
12879 	return (B_TRUE);
12880 }
12881 
12882 /*
12883  * All udp packet are delivered to the local host via this routine.
12884  */
12885 void
12886 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12887     ill_t *recv_ill)
12888 {
12889 	uint32_t	sum;
12890 	uint32_t	u1;
12891 	boolean_t	mctl_present;
12892 	conn_t		*connp;
12893 	mblk_t		*first_mp;
12894 	uint16_t	*up;
12895 	ill_t		*ill = (ill_t *)q->q_ptr;
12896 	uint16_t	reass_hck_flags = 0;
12897 	ip_stack_t	*ipst;
12898 
12899 	ASSERT(recv_ill != NULL);
12900 	ipst = recv_ill->ill_ipst;
12901 
12902 #define	rptr    ((uchar_t *)ipha)
12903 
12904 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12905 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12906 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12907 	ASSERT(ill != NULL);
12908 
12909 	/*
12910 	 * FAST PATH for udp packets
12911 	 */
12912 
12913 	/* u1 is # words of IP options */
12914 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12915 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12916 
12917 	/* IP options present */
12918 	if (u1 != 0)
12919 		goto ipoptions;
12920 
12921 	/* Check the IP header checksum.  */
12922 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12923 		/* Clear the IP header h/w cksum flag */
12924 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12925 	} else {
12926 #define	uph	((uint16_t *)ipha)
12927 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12928 		    uph[6] + uph[7] + uph[8] + uph[9];
12929 #undef	uph
12930 		/* finish doing IP checksum */
12931 		sum = (sum & 0xFFFF) + (sum >> 16);
12932 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12933 		/*
12934 		 * Don't verify header checksum if this packet is coming
12935 		 * back from AH/ESP as we already did it.
12936 		 */
12937 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12938 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12939 			freemsg(first_mp);
12940 			return;
12941 		}
12942 	}
12943 
12944 	/*
12945 	 * Count for SNMP of inbound packets for ire.
12946 	 * if mctl is present this might be a secure packet and
12947 	 * has already been counted for in ip_proto_input().
12948 	 */
12949 	if (!mctl_present) {
12950 		UPDATE_IB_PKT_COUNT(ire);
12951 		ire->ire_last_used_time = lbolt;
12952 	}
12953 
12954 	/* packet part of fragmented IP packet? */
12955 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12956 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12957 		goto fragmented;
12958 	}
12959 
12960 	/* u1 = IP header length (20 bytes) */
12961 	u1 = IP_SIMPLE_HDR_LENGTH;
12962 
12963 	/* packet does not contain complete IP & UDP headers */
12964 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12965 		goto udppullup;
12966 
12967 	/* up points to UDP header */
12968 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12969 #define	iphs    ((uint16_t *)ipha)
12970 
12971 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12972 	if (up[3] != 0) {
12973 		mblk_t *mp1 = mp->b_cont;
12974 		boolean_t cksum_err;
12975 		uint16_t hck_flags = 0;
12976 
12977 		/* Pseudo-header checksum */
12978 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12979 		    iphs[9] + up[2];
12980 
12981 		/*
12982 		 * Revert to software checksum calculation if the interface
12983 		 * isn't capable of checksum offload or if IPsec is present.
12984 		 */
12985 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12986 			hck_flags = DB_CKSUMFLAGS(mp);
12987 
12988 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12989 			IP_STAT(ipst, ip_in_sw_cksum);
12990 
12991 		IP_CKSUM_RECV(hck_flags, u1,
12992 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12993 		    (int32_t)((uchar_t *)up - rptr),
12994 		    mp, mp1, cksum_err);
12995 
12996 		if (cksum_err) {
12997 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12998 			if (hck_flags & HCK_FULLCKSUM)
12999 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13000 			else if (hck_flags & HCK_PARTIALCKSUM)
13001 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13002 			else
13003 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13004 
13005 			freemsg(first_mp);
13006 			return;
13007 		}
13008 	}
13009 
13010 	/* Non-fragmented broadcast or multicast packet? */
13011 	if (ire->ire_type == IRE_BROADCAST)
13012 		goto udpslowpath;
13013 
13014 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
13015 	    ire->ire_zoneid, ipst)) != NULL) {
13016 		ASSERT(connp->conn_upq != NULL);
13017 		IP_STAT(ipst, ip_udp_fast_path);
13018 
13019 		if (CONN_UDP_FLOWCTLD(connp)) {
13020 			freemsg(mp);
13021 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
13022 		} else {
13023 			if (!mctl_present) {
13024 				BUMP_MIB(ill->ill_ip_mib,
13025 				    ipIfStatsHCInDelivers);
13026 			}
13027 			/*
13028 			 * mp and first_mp can change.
13029 			 */
13030 			if (ip_udp_check(q, connp, recv_ill,
13031 			    ipha, &mp, &first_mp, mctl_present)) {
13032 				/* Send it upstream */
13033 				CONN_UDP_RECV(connp, mp);
13034 			}
13035 		}
13036 		/*
13037 		 * freeb() cannot deal with null mblk being passed
13038 		 * in and first_mp can be set to null in the call
13039 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13040 		 */
13041 		if (mctl_present && first_mp != NULL) {
13042 			freeb(first_mp);
13043 		}
13044 		CONN_DEC_REF(connp);
13045 		return;
13046 	}
13047 
13048 	/*
13049 	 * if we got here we know the packet is not fragmented and
13050 	 * has no options. The classifier could not find a conn_t and
13051 	 * most likely its an icmp packet so send it through slow path.
13052 	 */
13053 
13054 	goto udpslowpath;
13055 
13056 ipoptions:
13057 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13058 		goto slow_done;
13059 	}
13060 
13061 	UPDATE_IB_PKT_COUNT(ire);
13062 	ire->ire_last_used_time = lbolt;
13063 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13064 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13065 fragmented:
13066 		/*
13067 		 * "sum" and "reass_hck_flags" are non-zero if the
13068 		 * reassembled packet has a valid hardware computed
13069 		 * checksum information associated with it.
13070 		 */
13071 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13072 			goto slow_done;
13073 		/*
13074 		 * Make sure that first_mp points back to mp as
13075 		 * the mp we came in with could have changed in
13076 		 * ip_rput_fragment().
13077 		 */
13078 		ASSERT(!mctl_present);
13079 		ipha = (ipha_t *)mp->b_rptr;
13080 		first_mp = mp;
13081 	}
13082 
13083 	/* Now we have a complete datagram, destined for this machine. */
13084 	u1 = IPH_HDR_LENGTH(ipha);
13085 	/* Pull up the UDP header, if necessary. */
13086 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13087 udppullup:
13088 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13089 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13090 			freemsg(first_mp);
13091 			goto slow_done;
13092 		}
13093 		ipha = (ipha_t *)mp->b_rptr;
13094 	}
13095 
13096 	/*
13097 	 * Validate the checksum for the reassembled packet; for the
13098 	 * pullup case we calculate the payload checksum in software.
13099 	 */
13100 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13101 	if (up[3] != 0) {
13102 		boolean_t cksum_err;
13103 
13104 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13105 			IP_STAT(ipst, ip_in_sw_cksum);
13106 
13107 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13108 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13109 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13110 		    iphs[9] + up[2], sum, cksum_err);
13111 
13112 		if (cksum_err) {
13113 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13114 
13115 			if (reass_hck_flags & HCK_FULLCKSUM)
13116 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13117 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13118 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13119 			else
13120 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13121 
13122 			freemsg(first_mp);
13123 			goto slow_done;
13124 		}
13125 	}
13126 udpslowpath:
13127 
13128 	/* Clear hardware checksum flag to be safe */
13129 	DB_CKSUMFLAGS(mp) = 0;
13130 
13131 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13132 	    (ire->ire_type == IRE_BROADCAST),
13133 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13134 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13135 
13136 slow_done:
13137 	IP_STAT(ipst, ip_udp_slow_path);
13138 	return;
13139 
13140 #undef  iphs
13141 #undef  rptr
13142 }
13143 
13144 /* ARGSUSED */
13145 static mblk_t *
13146 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13147     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13148     ill_rx_ring_t *ill_ring)
13149 {
13150 	conn_t		*connp;
13151 	uint32_t	sum;
13152 	uint32_t	u1;
13153 	uint16_t	*up;
13154 	int		offset;
13155 	ssize_t		len;
13156 	mblk_t		*mp1;
13157 	boolean_t	syn_present = B_FALSE;
13158 	tcph_t		*tcph;
13159 	uint_t		ip_hdr_len;
13160 	ill_t		*ill = (ill_t *)q->q_ptr;
13161 	zoneid_t	zoneid = ire->ire_zoneid;
13162 	boolean_t	cksum_err;
13163 	uint16_t	hck_flags = 0;
13164 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13165 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13166 
13167 #define	rptr	((uchar_t *)ipha)
13168 
13169 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13170 	ASSERT(ill != NULL);
13171 
13172 	/*
13173 	 * FAST PATH for tcp packets
13174 	 */
13175 
13176 	/* u1 is # words of IP options */
13177 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13178 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13179 
13180 	/* IP options present */
13181 	if (u1) {
13182 		goto ipoptions;
13183 	} else {
13184 		/* Check the IP header checksum.  */
13185 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13186 			/* Clear the IP header h/w cksum flag */
13187 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13188 		} else {
13189 #define	uph	((uint16_t *)ipha)
13190 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13191 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13192 #undef	uph
13193 			/* finish doing IP checksum */
13194 			sum = (sum & 0xFFFF) + (sum >> 16);
13195 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13196 			/*
13197 			 * Don't verify header checksum if this packet
13198 			 * is coming back from AH/ESP as we already did it.
13199 			 */
13200 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13201 				BUMP_MIB(ill->ill_ip_mib,
13202 				    ipIfStatsInCksumErrs);
13203 				goto error;
13204 			}
13205 		}
13206 	}
13207 
13208 	if (!mctl_present) {
13209 		UPDATE_IB_PKT_COUNT(ire);
13210 		ire->ire_last_used_time = lbolt;
13211 	}
13212 
13213 	/* packet part of fragmented IP packet? */
13214 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13215 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13216 		goto fragmented;
13217 	}
13218 
13219 	/* u1 = IP header length (20 bytes) */
13220 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13221 
13222 	/* does packet contain IP+TCP headers? */
13223 	len = mp->b_wptr - rptr;
13224 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13225 		IP_STAT(ipst, ip_tcppullup);
13226 		goto tcppullup;
13227 	}
13228 
13229 	/* TCP options present? */
13230 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13231 
13232 	/*
13233 	 * If options need to be pulled up, then goto tcpoptions.
13234 	 * otherwise we are still in the fast path
13235 	 */
13236 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13237 		IP_STAT(ipst, ip_tcpoptions);
13238 		goto tcpoptions;
13239 	}
13240 
13241 	/* multiple mblks of tcp data? */
13242 	if ((mp1 = mp->b_cont) != NULL) {
13243 		/* more then two? */
13244 		if (mp1->b_cont != NULL) {
13245 			IP_STAT(ipst, ip_multipkttcp);
13246 			goto multipkttcp;
13247 		}
13248 		len += mp1->b_wptr - mp1->b_rptr;
13249 	}
13250 
13251 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13252 
13253 	/* part of pseudo checksum */
13254 
13255 	/* TCP datagram length */
13256 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13257 
13258 #define	iphs    ((uint16_t *)ipha)
13259 
13260 #ifdef	_BIG_ENDIAN
13261 	u1 += IPPROTO_TCP;
13262 #else
13263 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13264 #endif
13265 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13266 
13267 	/*
13268 	 * Revert to software checksum calculation if the interface
13269 	 * isn't capable of checksum offload or if IPsec is present.
13270 	 */
13271 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13272 		hck_flags = DB_CKSUMFLAGS(mp);
13273 
13274 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13275 		IP_STAT(ipst, ip_in_sw_cksum);
13276 
13277 	IP_CKSUM_RECV(hck_flags, u1,
13278 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13279 	    (int32_t)((uchar_t *)up - rptr),
13280 	    mp, mp1, cksum_err);
13281 
13282 	if (cksum_err) {
13283 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13284 
13285 		if (hck_flags & HCK_FULLCKSUM)
13286 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13287 		else if (hck_flags & HCK_PARTIALCKSUM)
13288 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13289 		else
13290 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13291 
13292 		goto error;
13293 	}
13294 
13295 try_again:
13296 
13297 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13298 		    zoneid, ipst)) == NULL) {
13299 		/* Send the TH_RST */
13300 		goto no_conn;
13301 	}
13302 
13303 	/*
13304 	 * TCP FAST PATH for AF_INET socket.
13305 	 *
13306 	 * TCP fast path to avoid extra work. An AF_INET socket type
13307 	 * does not have facility to receive extra information via
13308 	 * ip_process or ip_add_info. Also, when the connection was
13309 	 * established, we made a check if this connection is impacted
13310 	 * by any global IPSec policy or per connection policy (a
13311 	 * policy that comes in effect later will not apply to this
13312 	 * connection). Since all this can be determined at the
13313 	 * connection establishment time, a quick check of flags
13314 	 * can avoid extra work.
13315 	 */
13316 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13317 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13318 		ASSERT(first_mp == mp);
13319 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13320 		SET_SQUEUE(mp, tcp_rput_data, connp);
13321 		return (mp);
13322 	}
13323 
13324 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13325 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13326 		if (IPCL_IS_TCP(connp)) {
13327 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13328 			DB_CKSUMSTART(mp) =
13329 			    (intptr_t)ip_squeue_get(ill_ring);
13330 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13331 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13332 				BUMP_MIB(ill->ill_ip_mib,
13333 				    ipIfStatsHCInDelivers);
13334 				SET_SQUEUE(mp, connp->conn_recv, connp);
13335 				return (mp);
13336 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13337 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13338 				BUMP_MIB(ill->ill_ip_mib,
13339 				    ipIfStatsHCInDelivers);
13340 				ip_squeue_enter_unbound++;
13341 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13342 				    connp);
13343 				return (mp);
13344 			}
13345 			syn_present = B_TRUE;
13346 		}
13347 
13348 	}
13349 
13350 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13351 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13352 
13353 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13354 		/* No need to send this packet to TCP */
13355 		if ((flags & TH_RST) || (flags & TH_URG)) {
13356 			CONN_DEC_REF(connp);
13357 			freemsg(first_mp);
13358 			return (NULL);
13359 		}
13360 		if (flags & TH_ACK) {
13361 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13362 			    ipst->ips_netstack->netstack_tcp);
13363 			CONN_DEC_REF(connp);
13364 			return (NULL);
13365 		}
13366 
13367 		CONN_DEC_REF(connp);
13368 		freemsg(first_mp);
13369 		return (NULL);
13370 	}
13371 
13372 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13373 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13374 		    ipha, NULL, mctl_present);
13375 		if (first_mp == NULL) {
13376 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13377 			CONN_DEC_REF(connp);
13378 			return (NULL);
13379 		}
13380 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13381 			ASSERT(syn_present);
13382 			if (mctl_present) {
13383 				ASSERT(first_mp != mp);
13384 				first_mp->b_datap->db_struioflag |=
13385 				    STRUIO_POLICY;
13386 			} else {
13387 				ASSERT(first_mp == mp);
13388 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13389 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13390 			}
13391 		} else {
13392 			/*
13393 			 * Discard first_mp early since we're dealing with a
13394 			 * fully-connected conn_t and tcp doesn't do policy in
13395 			 * this case.
13396 			 */
13397 			if (mctl_present) {
13398 				freeb(first_mp);
13399 				mctl_present = B_FALSE;
13400 			}
13401 			first_mp = mp;
13402 		}
13403 	}
13404 
13405 	/* Initiate IPPF processing for fastpath */
13406 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13407 		uint32_t	ill_index;
13408 
13409 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13410 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13411 		if (mp == NULL) {
13412 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13413 			    "deferred/dropped during IPPF processing\n"));
13414 			CONN_DEC_REF(connp);
13415 			if (mctl_present)
13416 				freeb(first_mp);
13417 			return (NULL);
13418 		} else if (mctl_present) {
13419 			/*
13420 			 * ip_process might return a new mp.
13421 			 */
13422 			ASSERT(first_mp != mp);
13423 			first_mp->b_cont = mp;
13424 		} else {
13425 			first_mp = mp;
13426 		}
13427 
13428 	}
13429 
13430 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13431 		/*
13432 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13433 		 * make sure IPF_RECVIF is passed to ip_add_info.
13434 		 */
13435 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13436 		    IPCL_ZONEID(connp), ipst);
13437 		if (mp == NULL) {
13438 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13439 			CONN_DEC_REF(connp);
13440 			if (mctl_present)
13441 				freeb(first_mp);
13442 			return (NULL);
13443 		} else if (mctl_present) {
13444 			/*
13445 			 * ip_add_info might return a new mp.
13446 			 */
13447 			ASSERT(first_mp != mp);
13448 			first_mp->b_cont = mp;
13449 		} else {
13450 			first_mp = mp;
13451 		}
13452 	}
13453 
13454 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13455 	if (IPCL_IS_TCP(connp)) {
13456 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13457 		return (first_mp);
13458 	} else {
13459 		putnext(connp->conn_rq, first_mp);
13460 		CONN_DEC_REF(connp);
13461 		return (NULL);
13462 	}
13463 
13464 no_conn:
13465 	/* Initiate IPPf processing, if needed. */
13466 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13467 		uint32_t ill_index;
13468 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13469 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13470 		if (first_mp == NULL) {
13471 			return (NULL);
13472 		}
13473 	}
13474 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13475 
13476 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13477 	    ipst->ips_netstack->netstack_tcp);
13478 	return (NULL);
13479 ipoptions:
13480 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13481 		goto slow_done;
13482 	}
13483 
13484 	UPDATE_IB_PKT_COUNT(ire);
13485 	ire->ire_last_used_time = lbolt;
13486 
13487 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13488 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13489 fragmented:
13490 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13491 			if (mctl_present)
13492 				freeb(first_mp);
13493 			goto slow_done;
13494 		}
13495 		/*
13496 		 * Make sure that first_mp points back to mp as
13497 		 * the mp we came in with could have changed in
13498 		 * ip_rput_fragment().
13499 		 */
13500 		ASSERT(!mctl_present);
13501 		ipha = (ipha_t *)mp->b_rptr;
13502 		first_mp = mp;
13503 	}
13504 
13505 	/* Now we have a complete datagram, destined for this machine. */
13506 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13507 
13508 	len = mp->b_wptr - mp->b_rptr;
13509 	/* Pull up a minimal TCP header, if necessary. */
13510 	if (len < (u1 + 20)) {
13511 tcppullup:
13512 		if (!pullupmsg(mp, u1 + 20)) {
13513 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13514 			goto error;
13515 		}
13516 		ipha = (ipha_t *)mp->b_rptr;
13517 		len = mp->b_wptr - mp->b_rptr;
13518 	}
13519 
13520 	/*
13521 	 * Extract the offset field from the TCP header.  As usual, we
13522 	 * try to help the compiler more than the reader.
13523 	 */
13524 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13525 	if (offset != 5) {
13526 tcpoptions:
13527 		if (offset < 5) {
13528 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13529 			goto error;
13530 		}
13531 		/*
13532 		 * There must be TCP options.
13533 		 * Make sure we can grab them.
13534 		 */
13535 		offset <<= 2;
13536 		offset += u1;
13537 		if (len < offset) {
13538 			if (!pullupmsg(mp, offset)) {
13539 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13540 				goto error;
13541 			}
13542 			ipha = (ipha_t *)mp->b_rptr;
13543 			len = mp->b_wptr - rptr;
13544 		}
13545 	}
13546 
13547 	/* Get the total packet length in len, including headers. */
13548 	if (mp->b_cont) {
13549 multipkttcp:
13550 		len = msgdsize(mp);
13551 	}
13552 
13553 	/*
13554 	 * Check the TCP checksum by pulling together the pseudo-
13555 	 * header checksum, and passing it to ip_csum to be added in
13556 	 * with the TCP datagram.
13557 	 *
13558 	 * Since we are not using the hwcksum if available we must
13559 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13560 	 * If either of these fails along the way the mblk is freed.
13561 	 * If this logic ever changes and mblk is reused to say send
13562 	 * ICMP's back, then this flag may need to be cleared in
13563 	 * other places as well.
13564 	 */
13565 	DB_CKSUMFLAGS(mp) = 0;
13566 
13567 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13568 
13569 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13570 #ifdef	_BIG_ENDIAN
13571 	u1 += IPPROTO_TCP;
13572 #else
13573 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13574 #endif
13575 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13576 	/*
13577 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13578 	 */
13579 	IP_STAT(ipst, ip_in_sw_cksum);
13580 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13581 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13582 		goto error;
13583 	}
13584 
13585 	IP_STAT(ipst, ip_tcp_slow_path);
13586 	goto try_again;
13587 #undef  iphs
13588 #undef  rptr
13589 
13590 error:
13591 	freemsg(first_mp);
13592 slow_done:
13593 	return (NULL);
13594 }
13595 
13596 /* ARGSUSED */
13597 static void
13598 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13599     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13600 {
13601 	conn_t		*connp;
13602 	uint32_t	sum;
13603 	uint32_t	u1;
13604 	ssize_t		len;
13605 	sctp_hdr_t	*sctph;
13606 	zoneid_t	zoneid = ire->ire_zoneid;
13607 	uint32_t	pktsum;
13608 	uint32_t	calcsum;
13609 	uint32_t	ports;
13610 	in6_addr_t	map_src, map_dst;
13611 	ill_t		*ill = (ill_t *)q->q_ptr;
13612 	ip_stack_t	*ipst;
13613 	sctp_stack_t	*sctps;
13614 
13615 	ASSERT(recv_ill != NULL);
13616 	ipst = recv_ill->ill_ipst;
13617 	sctps = ipst->ips_netstack->netstack_sctp;
13618 
13619 #define	rptr	((uchar_t *)ipha)
13620 
13621 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13622 	ASSERT(ill != NULL);
13623 
13624 	/* u1 is # words of IP options */
13625 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13626 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13627 
13628 	/* IP options present */
13629 	if (u1 > 0) {
13630 		goto ipoptions;
13631 	} else {
13632 		/* Check the IP header checksum.  */
13633 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13634 #define	uph	((uint16_t *)ipha)
13635 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13636 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13637 #undef	uph
13638 			/* finish doing IP checksum */
13639 			sum = (sum & 0xFFFF) + (sum >> 16);
13640 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13641 			/*
13642 			 * Don't verify header checksum if this packet
13643 			 * is coming back from AH/ESP as we already did it.
13644 			 */
13645 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13646 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13647 				goto error;
13648 			}
13649 		}
13650 		/*
13651 		 * Since there is no SCTP h/w cksum support yet, just
13652 		 * clear the flag.
13653 		 */
13654 		DB_CKSUMFLAGS(mp) = 0;
13655 	}
13656 
13657 	/*
13658 	 * Don't verify header checksum if this packet is coming
13659 	 * back from AH/ESP as we already did it.
13660 	 */
13661 	if (!mctl_present) {
13662 		UPDATE_IB_PKT_COUNT(ire);
13663 		ire->ire_last_used_time = lbolt;
13664 	}
13665 
13666 	/* packet part of fragmented IP packet? */
13667 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13668 	if (u1 & (IPH_MF | IPH_OFFSET))
13669 		goto fragmented;
13670 
13671 	/* u1 = IP header length (20 bytes) */
13672 	u1 = IP_SIMPLE_HDR_LENGTH;
13673 
13674 find_sctp_client:
13675 	/* Pullup if we don't have the sctp common header. */
13676 	len = MBLKL(mp);
13677 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13678 		if (mp->b_cont == NULL ||
13679 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13680 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13681 			goto error;
13682 		}
13683 		ipha = (ipha_t *)mp->b_rptr;
13684 		len = MBLKL(mp);
13685 	}
13686 
13687 	sctph = (sctp_hdr_t *)(rptr + u1);
13688 #ifdef	DEBUG
13689 	if (!skip_sctp_cksum) {
13690 #endif
13691 		pktsum = sctph->sh_chksum;
13692 		sctph->sh_chksum = 0;
13693 		calcsum = sctp_cksum(mp, u1);
13694 		if (calcsum != pktsum) {
13695 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13696 			goto error;
13697 		}
13698 		sctph->sh_chksum = pktsum;
13699 #ifdef	DEBUG	/* skip_sctp_cksum */
13700 	}
13701 #endif
13702 	/* get the ports */
13703 	ports = *(uint32_t *)&sctph->sh_sport;
13704 
13705 	IRE_REFRELE(ire);
13706 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13707 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13708 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13709 	    sctps)) == NULL) {
13710 		/* Check for raw socket or OOTB handling */
13711 		goto no_conn;
13712 	}
13713 
13714 	/* Found a client; up it goes */
13715 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13716 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13717 	return;
13718 
13719 no_conn:
13720 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13721 	    ports, mctl_present, flags, B_TRUE, zoneid);
13722 	return;
13723 
13724 ipoptions:
13725 	DB_CKSUMFLAGS(mp) = 0;
13726 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13727 		goto slow_done;
13728 
13729 	UPDATE_IB_PKT_COUNT(ire);
13730 	ire->ire_last_used_time = lbolt;
13731 
13732 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13733 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13734 fragmented:
13735 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13736 			goto slow_done;
13737 		/*
13738 		 * Make sure that first_mp points back to mp as
13739 		 * the mp we came in with could have changed in
13740 		 * ip_rput_fragment().
13741 		 */
13742 		ASSERT(!mctl_present);
13743 		ipha = (ipha_t *)mp->b_rptr;
13744 		first_mp = mp;
13745 	}
13746 
13747 	/* Now we have a complete datagram, destined for this machine. */
13748 	u1 = IPH_HDR_LENGTH(ipha);
13749 	goto find_sctp_client;
13750 #undef  iphs
13751 #undef  rptr
13752 
13753 error:
13754 	freemsg(first_mp);
13755 slow_done:
13756 	IRE_REFRELE(ire);
13757 }
13758 
13759 #define	VER_BITS	0xF0
13760 #define	VERSION_6	0x60
13761 
13762 static boolean_t
13763 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13764     ipaddr_t *dstp, ip_stack_t *ipst)
13765 {
13766 	uint_t	opt_len;
13767 	ipha_t *ipha;
13768 	ssize_t len;
13769 	uint_t	pkt_len;
13770 
13771 	ASSERT(ill != NULL);
13772 	IP_STAT(ipst, ip_ipoptions);
13773 	ipha = *iphapp;
13774 
13775 #define	rptr    ((uchar_t *)ipha)
13776 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13777 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13778 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13779 		freemsg(mp);
13780 		return (B_FALSE);
13781 	}
13782 
13783 	/* multiple mblk or too short */
13784 	pkt_len = ntohs(ipha->ipha_length);
13785 
13786 	/* Get the number of words of IP options in the IP header. */
13787 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13788 	if (opt_len) {
13789 		/* IP Options present!  Validate and process. */
13790 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13791 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13792 			goto done;
13793 		}
13794 		/*
13795 		 * Recompute complete header length and make sure we
13796 		 * have access to all of it.
13797 		 */
13798 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13799 		if (len > (mp->b_wptr - rptr)) {
13800 			if (len > pkt_len) {
13801 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13802 				goto done;
13803 			}
13804 			if (!pullupmsg(mp, len)) {
13805 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13806 				goto done;
13807 			}
13808 			ipha = (ipha_t *)mp->b_rptr;
13809 		}
13810 		/*
13811 		 * Go off to ip_rput_options which returns the next hop
13812 		 * destination address, which may have been affected
13813 		 * by source routing.
13814 		 */
13815 		IP_STAT(ipst, ip_opt);
13816 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13817 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13818 			return (B_FALSE);
13819 		}
13820 	}
13821 	*iphapp = ipha;
13822 	return (B_TRUE);
13823 done:
13824 	/* clear b_prev - used by ip_mroute_decap */
13825 	mp->b_prev = NULL;
13826 	freemsg(mp);
13827 	return (B_FALSE);
13828 #undef  rptr
13829 }
13830 
13831 /*
13832  * Deal with the fact that there is no ire for the destination.
13833  * The incoming ill (in_ill) is passed in to ip_newroute only
13834  * in the case of packets coming from mobile ip forward tunnel.
13835  * It must be null otherwise.
13836  */
13837 static ire_t *
13838 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13839     ipaddr_t dst)
13840 {
13841 	ipha_t	*ipha;
13842 	ill_t	*ill;
13843 	ire_t	*ire;
13844 	boolean_t	check_multirt = B_FALSE;
13845 	ip_stack_t *ipst;
13846 
13847 	ipha = (ipha_t *)mp->b_rptr;
13848 	ill = (ill_t *)q->q_ptr;
13849 
13850 	ASSERT(ill != NULL);
13851 	ipst = ill->ill_ipst;
13852 
13853 	/*
13854 	 * No IRE for this destination, so it can't be for us.
13855 	 * Unless we are forwarding, drop the packet.
13856 	 * We have to let source routed packets through
13857 	 * since we don't yet know if they are 'ping -l'
13858 	 * packets i.e. if they will go out over the
13859 	 * same interface as they came in on.
13860 	 */
13861 	if (ll_multicast) {
13862 		freemsg(mp);
13863 		return (NULL);
13864 	}
13865 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13866 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13867 		freemsg(mp);
13868 		return (NULL);
13869 	}
13870 
13871 	/*
13872 	 * Mark this packet as having originated externally.
13873 	 *
13874 	 * For non-forwarding code path, ire_send later double
13875 	 * checks this interface to see if it is still exists
13876 	 * post-ARP resolution.
13877 	 *
13878 	 * Also, IPQOS uses this to differentiate between
13879 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13880 	 * QOS packet processing in ip_wput_attach_llhdr().
13881 	 * The QoS module can mark the b_band for a fastpath message
13882 	 * or the dl_priority field in a unitdata_req header for
13883 	 * CoS marking. This info can only be found in
13884 	 * ip_wput_attach_llhdr().
13885 	 */
13886 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13887 	/*
13888 	 * Clear the indication that this may have a hardware checksum
13889 	 * as we are not using it
13890 	 */
13891 	DB_CKSUMFLAGS(mp) = 0;
13892 
13893 	if (in_ill != NULL) {
13894 		/*
13895 		 * Now hand the packet to ip_newroute.
13896 		 */
13897 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13898 		return (NULL);
13899 	}
13900 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13901 	    MBLK_GETLABEL(mp), ipst);
13902 
13903 	if (ire == NULL && check_multirt) {
13904 		/* Let ip_newroute handle CGTP  */
13905 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13906 		return (NULL);
13907 	}
13908 
13909 	if (ire != NULL)
13910 		return (ire);
13911 
13912 	mp->b_prev = mp->b_next = 0;
13913 	/* send icmp unreachable */
13914 	q = WR(q);
13915 	/* Sent by forwarding path, and router is global zone */
13916 	if (ip_source_routed(ipha, ipst)) {
13917 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13918 		    GLOBAL_ZONEID, ipst);
13919 	} else {
13920 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13921 		    ipst);
13922 	}
13923 
13924 	return (NULL);
13925 
13926 }
13927 
13928 /*
13929  * check ip header length and align it.
13930  */
13931 static boolean_t
13932 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13933 {
13934 	ssize_t len;
13935 	ill_t *ill;
13936 	ipha_t	*ipha;
13937 
13938 	len = MBLKL(mp);
13939 
13940 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13941 		ill = (ill_t *)q->q_ptr;
13942 
13943 		if (!OK_32PTR(mp->b_rptr))
13944 			IP_STAT(ipst, ip_notaligned1);
13945 		else
13946 			IP_STAT(ipst, ip_notaligned2);
13947 		/* Guard against bogus device drivers */
13948 		if (len < 0) {
13949 			/* clear b_prev - used by ip_mroute_decap */
13950 			mp->b_prev = NULL;
13951 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13952 			freemsg(mp);
13953 			return (B_FALSE);
13954 		}
13955 
13956 		if (ip_rput_pullups++ == 0) {
13957 			ipha = (ipha_t *)mp->b_rptr;
13958 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13959 			    "ip_check_and_align_header: %s forced us to "
13960 			    " pullup pkt, hdr len %ld, hdr addr %p",
13961 			    ill->ill_name, len, ipha);
13962 		}
13963 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13964 			/* clear b_prev - used by ip_mroute_decap */
13965 			mp->b_prev = NULL;
13966 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13967 			freemsg(mp);
13968 			return (B_FALSE);
13969 		}
13970 	}
13971 	return (B_TRUE);
13972 }
13973 
13974 ire_t *
13975 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13976 {
13977 	ire_t		*new_ire;
13978 	ill_t		*ire_ill;
13979 	uint_t		ifindex;
13980 	ip_stack_t	*ipst = ill->ill_ipst;
13981 	boolean_t	strict_check = B_FALSE;
13982 
13983 	/*
13984 	 * This packet came in on an interface other than the one associated
13985 	 * with the first ire we found for the destination address. We do
13986 	 * another ire lookup here, using the ingress ill, to see if the
13987 	 * interface is in an interface group.
13988 	 * As long as the ills belong to the same group, we don't consider
13989 	 * them to be arriving on the wrong interface. Thus, if the switch
13990 	 * is doing inbound load spreading, we won't drop packets when the
13991 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13992 	 * for 'usesrc groups' where the destination address may belong to
13993 	 * another interface to allow multipathing to happen.
13994 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13995 	 * where the local address may not be unique. In this case we were
13996 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13997 	 * actually returned. The new lookup, which is more specific, should
13998 	 * only find the IRE_LOCAL associated with the ingress ill if one
13999 	 * exists.
14000 	 */
14001 
14002 	if (ire->ire_ipversion == IPV4_VERSION) {
14003 		if (ipst->ips_ip_strict_dst_multihoming)
14004 			strict_check = B_TRUE;
14005 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
14006 		    ill->ill_ipif, ALL_ZONES, NULL,
14007 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14008 	} else {
14009 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
14010 		if (ipst->ips_ipv6_strict_dst_multihoming)
14011 			strict_check = B_TRUE;
14012 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
14013 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
14014 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14015 	}
14016 	/*
14017 	 * If the same ire that was returned in ip_input() is found then this
14018 	 * is an indication that interface groups are in use. The packet
14019 	 * arrived on a different ill in the group than the one associated with
14020 	 * the destination address.  If a different ire was found then the same
14021 	 * IP address must be hosted on multiple ills. This is possible with
14022 	 * unnumbered point2point interfaces. We switch to use this new ire in
14023 	 * order to have accurate interface statistics.
14024 	 */
14025 	if (new_ire != NULL) {
14026 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
14027 			ire_refrele(ire);
14028 			ire = new_ire;
14029 		} else {
14030 			ire_refrele(new_ire);
14031 		}
14032 		return (ire);
14033 	} else if ((ire->ire_rfq == NULL) &&
14034 		    (ire->ire_ipversion == IPV4_VERSION)) {
14035 		/*
14036 		 * The best match could have been the original ire which
14037 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14038 		 * the strict multihoming checks are irrelevant as we consider
14039 		 * local addresses hosted on lo0 to be interface agnostic. We
14040 		 * only expect a null ire_rfq on IREs which are associated with
14041 		 * lo0 hence we can return now.
14042 		 */
14043 		return (ire);
14044 	}
14045 
14046 	/*
14047 	 * Chase pointers once and store locally.
14048 	 */
14049 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14050 	    (ill_t *)(ire->ire_rfq->q_ptr);
14051 	ifindex = ill->ill_usesrc_ifindex;
14052 
14053 	/*
14054 	 * Check if it's a legal address on the 'usesrc' interface.
14055 	 */
14056 	if ((ifindex != 0) && (ire_ill != NULL) &&
14057 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14058 		return (ire);
14059 	}
14060 
14061 	/*
14062 	 * If the ip*_strict_dst_multihoming switch is on then we can
14063 	 * only accept this packet if the interface is marked as routing.
14064 	 */
14065 	if (!(strict_check))
14066 		return (ire);
14067 
14068 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14069 	    ILLF_ROUTER) != 0) {
14070 		return (ire);
14071 	}
14072 
14073 	ire_refrele(ire);
14074 	return (NULL);
14075 }
14076 
14077 ire_t *
14078 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14079 {
14080 	ipha_t	*ipha;
14081 	ipaddr_t ip_dst, ip_src;
14082 	ire_t	*src_ire = NULL;
14083 	ill_t	*stq_ill;
14084 	uint_t	hlen;
14085 	uint_t	pkt_len;
14086 	uint32_t sum;
14087 	queue_t	*dev_q;
14088 	boolean_t check_multirt = B_FALSE;
14089 	ip_stack_t *ipst = ill->ill_ipst;
14090 
14091 	ipha = (ipha_t *)mp->b_rptr;
14092 
14093 	/*
14094 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14095 	 * The loopback address check for both src and dst has already
14096 	 * been checked in ip_input
14097 	 */
14098 	ip_dst = ntohl(dst);
14099 	ip_src = ntohl(ipha->ipha_src);
14100 
14101 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14102 	    IN_CLASSD(ip_src)) {
14103 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14104 		goto drop;
14105 	}
14106 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14107 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14108 
14109 	if (src_ire != NULL) {
14110 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14111 		goto drop;
14112 	}
14113 
14114 
14115 	/* No ire cache of nexthop. So first create one  */
14116 	if (ire == NULL) {
14117 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14118 		/*
14119 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14120 		 * is not set. So upon return from ire_forward
14121 		 * check_multirt should remain as false.
14122 		 */
14123 		ASSERT(!check_multirt);
14124 		if (ire == NULL) {
14125 			/* An attempt was made to forward the packet */
14126 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14127 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14128 			mp->b_prev = mp->b_next = 0;
14129 			/* send icmp unreachable */
14130 			/* Sent by forwarding path, and router is global zone */
14131 			if (ip_source_routed(ipha, ipst)) {
14132 				icmp_unreachable(ill->ill_wq, mp,
14133 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14134 				    ipst);
14135 			} else {
14136 				icmp_unreachable(ill->ill_wq, mp,
14137 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14138 				    ipst);
14139 			}
14140 			return (ire);
14141 		}
14142 	}
14143 
14144 	/*
14145 	 * Forwarding fastpath exception case:
14146 	 * If either of the follwoing case is true, we take
14147 	 * the slowpath
14148 	 *	o forwarding is not enabled
14149 	 *	o incoming and outgoing interface are the same, or the same
14150 	 *	  IPMP group
14151 	 *	o corresponding ire is in incomplete state
14152 	 *	o packet needs fragmentation
14153 	 *
14154 	 * The codeflow from here on is thus:
14155 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14156 	 */
14157 	pkt_len = ntohs(ipha->ipha_length);
14158 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14159 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14160 	    !(ill->ill_flags & ILLF_ROUTER) ||
14161 	    (ill == stq_ill) ||
14162 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14163 	    (ire->ire_nce == NULL) ||
14164 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14165 	    (pkt_len > ire->ire_max_frag) ||
14166 	    ipha->ipha_ttl <= 1) {
14167 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14168 		    ipha, ill, B_FALSE);
14169 		return (ire);
14170 	}
14171 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14172 
14173 	DTRACE_PROBE4(ip4__forwarding__start,
14174 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14175 
14176 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14177 	    ipst->ips_ipv4firewall_forwarding,
14178 	    ill, stq_ill, ipha, mp, mp, ipst);
14179 
14180 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14181 
14182 	if (mp == NULL)
14183 		goto drop;
14184 
14185 	mp->b_datap->db_struioun.cksum.flags = 0;
14186 	/* Adjust the checksum to reflect the ttl decrement. */
14187 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14188 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14189 	ipha->ipha_ttl--;
14190 
14191 	dev_q = ire->ire_stq->q_next;
14192 	if ((dev_q->q_next != NULL ||
14193 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14194 		goto indiscard;
14195 	}
14196 
14197 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14198 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14199 
14200 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14201 		mblk_t *mpip = mp;
14202 
14203 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14204 		if (mp != NULL) {
14205 			DTRACE_PROBE4(ip4__physical__out__start,
14206 			    ill_t *, NULL, ill_t *, stq_ill,
14207 			    ipha_t *, ipha, mblk_t *, mp);
14208 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14209 			    ipst->ips_ipv4firewall_physical_out,
14210 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14211 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14212 			    mp);
14213 			if (mp == NULL)
14214 				goto drop;
14215 
14216 			UPDATE_IB_PKT_COUNT(ire);
14217 			ire->ire_last_used_time = lbolt;
14218 			BUMP_MIB(stq_ill->ill_ip_mib,
14219 			    ipIfStatsHCOutForwDatagrams);
14220 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14221 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14222 			    pkt_len);
14223 			putnext(ire->ire_stq, mp);
14224 			return (ire);
14225 		}
14226 	}
14227 
14228 indiscard:
14229 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14230 drop:
14231 	if (mp != NULL)
14232 		freemsg(mp);
14233 	if (src_ire != NULL)
14234 		ire_refrele(src_ire);
14235 	return (ire);
14236 
14237 }
14238 
14239 /*
14240  * This function is called in the forwarding slowpath, when
14241  * either the ire lacks the link-layer address, or the packet needs
14242  * further processing(eg. fragmentation), before transmission.
14243  */
14244 
14245 static void
14246 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14247     ill_t *ill, boolean_t ll_multicast)
14248 {
14249 	ill_group_t	*ill_group;
14250 	ill_group_t	*ire_group;
14251 	queue_t		*dev_q;
14252 	ire_t		*src_ire;
14253 	ip_stack_t	*ipst = ill->ill_ipst;
14254 
14255 	ASSERT(ire->ire_stq != NULL);
14256 
14257 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14258 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14259 
14260 	if (ll_multicast != 0) {
14261 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14262 		goto drop_pkt;
14263 	}
14264 
14265 	/*
14266 	 * check if ipha_src is a broadcast address. Note that this
14267 	 * check is redundant when we get here from ip_fast_forward()
14268 	 * which has already done this check. However, since we can
14269 	 * also get here from ip_rput_process_broadcast() or, for
14270 	 * for the slow path through ip_fast_forward(), we perform
14271 	 * the check again for code-reusability
14272 	 */
14273 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14274 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14275 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14276 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14277 		if (src_ire != NULL)
14278 			ire_refrele(src_ire);
14279 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14280 		ip2dbg(("ip_rput_process_forward: Received packet with"
14281 		    " bad src/dst address on %s\n", ill->ill_name));
14282 		goto drop_pkt;
14283 	}
14284 
14285 	ill_group = ill->ill_group;
14286 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14287 	/*
14288 	 * Check if we want to forward this one at this time.
14289 	 * We allow source routed packets on a host provided that
14290 	 * they go out the same interface or same interface group
14291 	 * as they came in on.
14292 	 *
14293 	 * XXX To be quicker, we may wish to not chase pointers to
14294 	 * get the ILLF_ROUTER flag and instead store the
14295 	 * forwarding policy in the ire.  An unfortunate
14296 	 * side-effect of that would be requiring an ire flush
14297 	 * whenever the ILLF_ROUTER flag changes.
14298 	 */
14299 	if (((ill->ill_flags &
14300 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14301 	    ILLF_ROUTER) == 0) &&
14302 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14303 	    (ill_group != NULL && ill_group == ire_group)))) {
14304 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14305 		if (ip_source_routed(ipha, ipst)) {
14306 			q = WR(q);
14307 			/*
14308 			 * Clear the indication that this may have
14309 			 * hardware checksum as we are not using it.
14310 			 */
14311 			DB_CKSUMFLAGS(mp) = 0;
14312 			/* Sent by forwarding path, and router is global zone */
14313 			icmp_unreachable(q, mp,
14314 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14315 			return;
14316 		}
14317 		goto drop_pkt;
14318 	}
14319 
14320 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14321 
14322 	/* Packet is being forwarded. Turning off hwcksum flag. */
14323 	DB_CKSUMFLAGS(mp) = 0;
14324 	if (ipst->ips_ip_g_send_redirects) {
14325 		/*
14326 		 * Check whether the incoming interface and outgoing
14327 		 * interface is part of the same group. If so,
14328 		 * send redirects.
14329 		 *
14330 		 * Check the source address to see if it originated
14331 		 * on the same logical subnet it is going back out on.
14332 		 * If so, we should be able to send it a redirect.
14333 		 * Avoid sending a redirect if the destination
14334 		 * is directly connected (i.e., ipha_dst is the same
14335 		 * as ire_gateway_addr or the ire_addr of the
14336 		 * nexthop IRE_CACHE ), or if the packet was source
14337 		 * routed out this interface.
14338 		 */
14339 		ipaddr_t src, nhop;
14340 		mblk_t	*mp1;
14341 		ire_t	*nhop_ire = NULL;
14342 
14343 		/*
14344 		 * Check whether ire_rfq and q are from the same ill
14345 		 * or if they are not same, they at least belong
14346 		 * to the same group. If so, send redirects.
14347 		 */
14348 		if ((ire->ire_rfq == q ||
14349 		    (ill_group != NULL && ill_group == ire_group)) &&
14350 		    !ip_source_routed(ipha, ipst)) {
14351 
14352 			nhop = (ire->ire_gateway_addr != 0 ?
14353 			    ire->ire_gateway_addr : ire->ire_addr);
14354 
14355 			if (ipha->ipha_dst == nhop) {
14356 				/*
14357 				 * We avoid sending a redirect if the
14358 				 * destination is directly connected
14359 				 * because it is possible that multiple
14360 				 * IP subnets may have been configured on
14361 				 * the link, and the source may not
14362 				 * be on the same subnet as ip destination,
14363 				 * even though they are on the same
14364 				 * physical link.
14365 				 */
14366 				goto sendit;
14367 			}
14368 
14369 			src = ipha->ipha_src;
14370 
14371 			/*
14372 			 * We look up the interface ire for the nexthop,
14373 			 * to see if ipha_src is in the same subnet
14374 			 * as the nexthop.
14375 			 *
14376 			 * Note that, if, in the future, IRE_CACHE entries
14377 			 * are obsoleted,  this lookup will not be needed,
14378 			 * as the ire passed to this function will be the
14379 			 * same as the nhop_ire computed below.
14380 			 */
14381 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14382 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14383 			    0, NULL, MATCH_IRE_TYPE, ipst);
14384 
14385 			if (nhop_ire != NULL) {
14386 				if ((src & nhop_ire->ire_mask) ==
14387 				    (nhop & nhop_ire->ire_mask)) {
14388 					/*
14389 					 * The source is directly connected.
14390 					 * Just copy the ip header (which is
14391 					 * in the first mblk)
14392 					 */
14393 					mp1 = copyb(mp);
14394 					if (mp1 != NULL) {
14395 						icmp_send_redirect(WR(q), mp1,
14396 						    nhop, ipst);
14397 					}
14398 				}
14399 				ire_refrele(nhop_ire);
14400 			}
14401 		}
14402 	}
14403 sendit:
14404 	dev_q = ire->ire_stq->q_next;
14405 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14406 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14407 		freemsg(mp);
14408 		return;
14409 	}
14410 
14411 	ip_rput_forward(ire, ipha, mp, ill);
14412 	return;
14413 
14414 drop_pkt:
14415 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14416 	freemsg(mp);
14417 }
14418 
14419 ire_t *
14420 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14421     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14422 {
14423 	queue_t		*q;
14424 	uint16_t	hcksumflags;
14425 	ip_stack_t	*ipst = ill->ill_ipst;
14426 
14427 	q = *qp;
14428 
14429 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14430 
14431 	/*
14432 	 * Clear the indication that this may have hardware
14433 	 * checksum as we are not using it for forwarding.
14434 	 */
14435 	hcksumflags = DB_CKSUMFLAGS(mp);
14436 	DB_CKSUMFLAGS(mp) = 0;
14437 
14438 	/*
14439 	 * Directed broadcast forwarding: if the packet came in over a
14440 	 * different interface then it is routed out over we can forward it.
14441 	 */
14442 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14443 		ire_refrele(ire);
14444 		freemsg(mp);
14445 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14446 		return (NULL);
14447 	}
14448 	/*
14449 	 * For multicast we have set dst to be INADDR_BROADCAST
14450 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14451 	 * only for broadcast packets.
14452 	 */
14453 	if (!CLASSD(ipha->ipha_dst)) {
14454 		ire_t *new_ire;
14455 		ipif_t *ipif;
14456 		/*
14457 		 * For ill groups, as the switch duplicates broadcasts
14458 		 * across all the ports, we need to filter out and
14459 		 * send up only one copy. There is one copy for every
14460 		 * broadcast address on each ill. Thus, we look for a
14461 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14462 		 * later to see whether this ill is eligible to receive
14463 		 * them or not. ill_nominate_bcast_rcv() nominates only
14464 		 * one set of IREs for receiving.
14465 		 */
14466 
14467 		ipif = ipif_get_next_ipif(NULL, ill);
14468 		if (ipif == NULL) {
14469 			ire_refrele(ire);
14470 			freemsg(mp);
14471 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14472 			return (NULL);
14473 		}
14474 		new_ire = ire_ctable_lookup(dst, 0, 0,
14475 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14476 		ipif_refrele(ipif);
14477 
14478 		if (new_ire != NULL) {
14479 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14480 				ire_refrele(ire);
14481 				ire_refrele(new_ire);
14482 				freemsg(mp);
14483 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14484 				return (NULL);
14485 			}
14486 			/*
14487 			 * In the special case of multirouted broadcast
14488 			 * packets, we unconditionally need to "gateway"
14489 			 * them to the appropriate interface here.
14490 			 * In the normal case, this cannot happen, because
14491 			 * there is no broadcast IRE tagged with the
14492 			 * RTF_MULTIRT flag.
14493 			 */
14494 			if (new_ire->ire_flags & RTF_MULTIRT) {
14495 				ire_refrele(new_ire);
14496 				if (ire->ire_rfq != NULL) {
14497 					q = ire->ire_rfq;
14498 					*qp = q;
14499 				}
14500 			} else {
14501 				ire_refrele(ire);
14502 				ire = new_ire;
14503 			}
14504 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14505 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14506 				/*
14507 				 * Free the message if
14508 				 * ip_g_forward_directed_bcast is turned
14509 				 * off for non-local broadcast.
14510 				 */
14511 				ire_refrele(ire);
14512 				freemsg(mp);
14513 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14514 				return (NULL);
14515 			}
14516 		} else {
14517 			/*
14518 			 * This CGTP packet successfully passed the
14519 			 * CGTP filter, but the related CGTP
14520 			 * broadcast IRE has not been found,
14521 			 * meaning that the redundant ipif is
14522 			 * probably down. However, if we discarded
14523 			 * this packet, its duplicate would be
14524 			 * filtered out by the CGTP filter so none
14525 			 * of them would get through. So we keep
14526 			 * going with this one.
14527 			 */
14528 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14529 			if (ire->ire_rfq != NULL) {
14530 				q = ire->ire_rfq;
14531 				*qp = q;
14532 			}
14533 		}
14534 	}
14535 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14536 		/*
14537 		 * Verify that there are not more then one
14538 		 * IRE_BROADCAST with this broadcast address which
14539 		 * has ire_stq set.
14540 		 * TODO: simplify, loop over all IRE's
14541 		 */
14542 		ire_t	*ire1;
14543 		int	num_stq = 0;
14544 		mblk_t	*mp1;
14545 
14546 		/* Find the first one with ire_stq set */
14547 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14548 		for (ire1 = ire; ire1 &&
14549 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14550 		    ire1 = ire1->ire_next)
14551 			;
14552 		if (ire1) {
14553 			ire_refrele(ire);
14554 			ire = ire1;
14555 			IRE_REFHOLD(ire);
14556 		}
14557 
14558 		/* Check if there are additional ones with stq set */
14559 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14560 			if (ire->ire_addr != ire1->ire_addr)
14561 				break;
14562 			if (ire1->ire_stq) {
14563 				num_stq++;
14564 				break;
14565 			}
14566 		}
14567 		rw_exit(&ire->ire_bucket->irb_lock);
14568 		if (num_stq == 1 && ire->ire_stq != NULL) {
14569 			ip1dbg(("ip_rput_process_broadcast: directed "
14570 			    "broadcast to 0x%x\n",
14571 			    ntohl(ire->ire_addr)));
14572 			mp1 = copymsg(mp);
14573 			if (mp1) {
14574 				switch (ipha->ipha_protocol) {
14575 				case IPPROTO_UDP:
14576 					ip_udp_input(q, mp1, ipha, ire, ill);
14577 					break;
14578 				default:
14579 					ip_proto_input(q, mp1, ipha, ire, ill);
14580 					break;
14581 				}
14582 			}
14583 			/*
14584 			 * Adjust ttl to 2 (1+1 - the forward engine
14585 			 * will decrement it by one.
14586 			 */
14587 			if (ip_csum_hdr(ipha)) {
14588 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14589 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14590 				freemsg(mp);
14591 				ire_refrele(ire);
14592 				return (NULL);
14593 			}
14594 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14595 			ipha->ipha_hdr_checksum = 0;
14596 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14597 			ip_rput_process_forward(q, mp, ire, ipha,
14598 			    ill, ll_multicast);
14599 			ire_refrele(ire);
14600 			return (NULL);
14601 		}
14602 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14603 		    ntohl(ire->ire_addr)));
14604 	}
14605 
14606 
14607 	/* Restore any hardware checksum flags */
14608 	DB_CKSUMFLAGS(mp) = hcksumflags;
14609 	return (ire);
14610 }
14611 
14612 /* ARGSUSED */
14613 static boolean_t
14614 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14615     int *ll_multicast, ipaddr_t *dstp)
14616 {
14617 	ip_stack_t	*ipst = ill->ill_ipst;
14618 
14619 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14620 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14621 	    ntohs(ipha->ipha_length));
14622 
14623 	/*
14624 	 * Forward packets only if we have joined the allmulti
14625 	 * group on this interface.
14626 	 */
14627 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14628 		int retval;
14629 
14630 		/*
14631 		 * Clear the indication that this may have hardware
14632 		 * checksum as we are not using it.
14633 		 */
14634 		DB_CKSUMFLAGS(mp) = 0;
14635 		retval = ip_mforward(ill, ipha, mp);
14636 		/* ip_mforward updates mib variables if needed */
14637 		/* clear b_prev - used by ip_mroute_decap */
14638 		mp->b_prev = NULL;
14639 
14640 		switch (retval) {
14641 		case 0:
14642 			/*
14643 			 * pkt is okay and arrived on phyint.
14644 			 *
14645 			 * If we are running as a multicast router
14646 			 * we need to see all IGMP and/or PIM packets.
14647 			 */
14648 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14649 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14650 				goto done;
14651 			}
14652 			break;
14653 		case -1:
14654 			/* pkt is mal-formed, toss it */
14655 			goto drop_pkt;
14656 		case 1:
14657 			/* pkt is okay and arrived on a tunnel */
14658 			/*
14659 			 * If we are running a multicast router
14660 			 *  we need to see all igmp packets.
14661 			 */
14662 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14663 				*dstp = INADDR_BROADCAST;
14664 				*ll_multicast = 1;
14665 				return (B_FALSE);
14666 			}
14667 
14668 			goto drop_pkt;
14669 		}
14670 	}
14671 
14672 	ILM_WALKER_HOLD(ill);
14673 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14674 		/*
14675 		 * This might just be caused by the fact that
14676 		 * multiple IP Multicast addresses map to the same
14677 		 * link layer multicast - no need to increment counter!
14678 		 */
14679 		ILM_WALKER_RELE(ill);
14680 		freemsg(mp);
14681 		return (B_TRUE);
14682 	}
14683 	ILM_WALKER_RELE(ill);
14684 done:
14685 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14686 	/*
14687 	 * This assumes the we deliver to all streams for multicast
14688 	 * and broadcast packets.
14689 	 */
14690 	*dstp = INADDR_BROADCAST;
14691 	*ll_multicast = 1;
14692 	return (B_FALSE);
14693 drop_pkt:
14694 	ip2dbg(("ip_rput: drop pkt\n"));
14695 	freemsg(mp);
14696 	return (B_TRUE);
14697 }
14698 
14699 static boolean_t
14700 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14701     int *ll_multicast, mblk_t **mpp)
14702 {
14703 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14704 	boolean_t must_copy = B_FALSE;
14705 	struct iocblk   *iocp;
14706 	ipha_t		*ipha;
14707 	ip_stack_t	*ipst = ill->ill_ipst;
14708 
14709 #define	rptr    ((uchar_t *)ipha)
14710 
14711 	first_mp = *first_mpp;
14712 	mp = *mpp;
14713 
14714 	ASSERT(first_mp == mp);
14715 
14716 	/*
14717 	 * if db_ref > 1 then copymsg and free original. Packet may be
14718 	 * changed and do not want other entity who has a reference to this
14719 	 * message to trip over the changes. This is a blind change because
14720 	 * trying to catch all places that might change packet is too
14721 	 * difficult (since it may be a module above this one)
14722 	 *
14723 	 * This corresponds to the non-fast path case. We walk down the full
14724 	 * chain in this case, and check the db_ref count of all the dblks,
14725 	 * and do a copymsg if required. It is possible that the db_ref counts
14726 	 * of the data blocks in the mblk chain can be different.
14727 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14728 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14729 	 * 'snoop' is running.
14730 	 */
14731 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14732 		if (mp1->b_datap->db_ref > 1) {
14733 			must_copy = B_TRUE;
14734 			break;
14735 		}
14736 	}
14737 
14738 	if (must_copy) {
14739 		mp1 = copymsg(mp);
14740 		if (mp1 == NULL) {
14741 			for (mp1 = mp; mp1 != NULL;
14742 			    mp1 = mp1->b_cont) {
14743 				mp1->b_next = NULL;
14744 				mp1->b_prev = NULL;
14745 			}
14746 			freemsg(mp);
14747 			if (ill != NULL) {
14748 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14749 			} else {
14750 				BUMP_MIB(&ipst->ips_ip_mib,
14751 				    ipIfStatsInDiscards);
14752 			}
14753 			return (B_TRUE);
14754 		}
14755 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14756 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14757 			/* Copy b_prev - used by ip_mroute_decap */
14758 			to_mp->b_prev = from_mp->b_prev;
14759 			from_mp->b_prev = NULL;
14760 		}
14761 		*first_mpp = first_mp = mp1;
14762 		freemsg(mp);
14763 		mp = mp1;
14764 		*mpp = mp1;
14765 	}
14766 
14767 	ipha = (ipha_t *)mp->b_rptr;
14768 
14769 	/*
14770 	 * previous code has a case for M_DATA.
14771 	 * We want to check how that happens.
14772 	 */
14773 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14774 	switch (first_mp->b_datap->db_type) {
14775 	case M_PROTO:
14776 	case M_PCPROTO:
14777 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14778 		    DL_UNITDATA_IND) {
14779 			/* Go handle anything other than data elsewhere. */
14780 			ip_rput_dlpi(q, mp);
14781 			return (B_TRUE);
14782 		}
14783 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14784 		/* Ditch the DLPI header. */
14785 		mp1 = mp->b_cont;
14786 		ASSERT(first_mp == mp);
14787 		*first_mpp = mp1;
14788 		freeb(mp);
14789 		*mpp = mp1;
14790 		return (B_FALSE);
14791 	case M_IOCACK:
14792 		ip1dbg(("got iocack "));
14793 		iocp = (struct iocblk *)mp->b_rptr;
14794 		switch (iocp->ioc_cmd) {
14795 		case DL_IOC_HDR_INFO:
14796 			ill = (ill_t *)q->q_ptr;
14797 			ill_fastpath_ack(ill, mp);
14798 			return (B_TRUE);
14799 		case SIOCSTUNPARAM:
14800 		case OSIOCSTUNPARAM:
14801 			/* Go through qwriter_ip */
14802 			break;
14803 		case SIOCGTUNPARAM:
14804 		case OSIOCGTUNPARAM:
14805 			ip_rput_other(NULL, q, mp, NULL);
14806 			return (B_TRUE);
14807 		default:
14808 			putnext(q, mp);
14809 			return (B_TRUE);
14810 		}
14811 		/* FALLTHRU */
14812 	case M_ERROR:
14813 	case M_HANGUP:
14814 		/*
14815 		 * Since this is on the ill stream we unconditionally
14816 		 * bump up the refcount
14817 		 */
14818 		ill_refhold(ill);
14819 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other, CUR_OP,
14820 		    B_FALSE);
14821 		return (B_TRUE);
14822 	case M_CTL:
14823 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14824 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14825 			IPHADA_M_CTL)) {
14826 			/*
14827 			 * It's an IPsec accelerated packet.
14828 			 * Make sure that the ill from which we received the
14829 			 * packet has enabled IPsec hardware acceleration.
14830 			 */
14831 			if (!(ill->ill_capabilities &
14832 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14833 				/* IPsec kstats: bean counter */
14834 				freemsg(mp);
14835 				return (B_TRUE);
14836 			}
14837 
14838 			/*
14839 			 * Make mp point to the mblk following the M_CTL,
14840 			 * then process according to type of mp.
14841 			 * After this processing, first_mp will point to
14842 			 * the data-attributes and mp to the pkt following
14843 			 * the M_CTL.
14844 			 */
14845 			mp = first_mp->b_cont;
14846 			if (mp == NULL) {
14847 				freemsg(first_mp);
14848 				return (B_TRUE);
14849 			}
14850 			/*
14851 			 * A Hardware Accelerated packet can only be M_DATA
14852 			 * ESP or AH packet.
14853 			 */
14854 			if (mp->b_datap->db_type != M_DATA) {
14855 				/* non-M_DATA IPsec accelerated packet */
14856 				IPSECHW_DEBUG(IPSECHW_PKT,
14857 				    ("non-M_DATA IPsec accelerated pkt\n"));
14858 				freemsg(first_mp);
14859 				return (B_TRUE);
14860 			}
14861 			ipha = (ipha_t *)mp->b_rptr;
14862 			if (ipha->ipha_protocol != IPPROTO_AH &&
14863 			    ipha->ipha_protocol != IPPROTO_ESP) {
14864 				IPSECHW_DEBUG(IPSECHW_PKT,
14865 				    ("non-M_DATA IPsec accelerated pkt\n"));
14866 				freemsg(first_mp);
14867 				return (B_TRUE);
14868 			}
14869 			*mpp = mp;
14870 			return (B_FALSE);
14871 		}
14872 		putnext(q, mp);
14873 		return (B_TRUE);
14874 	case M_FLUSH:
14875 		if (*mp->b_rptr & FLUSHW) {
14876 			*mp->b_rptr &= ~FLUSHR;
14877 			qreply(q, mp);
14878 			return (B_TRUE);
14879 		}
14880 		freemsg(mp);
14881 		return (B_TRUE);
14882 	case M_IOCNAK:
14883 		ip1dbg(("got iocnak "));
14884 		iocp = (struct iocblk *)mp->b_rptr;
14885 		switch (iocp->ioc_cmd) {
14886 		case DL_IOC_HDR_INFO:
14887 		case SIOCSTUNPARAM:
14888 		case OSIOCSTUNPARAM:
14889 			/*
14890 			 * Since this is on the ill stream we unconditionally
14891 			 * bump up the refcount
14892 			 */
14893 			ill_refhold(ill);
14894 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_other,
14895 			    CUR_OP, B_FALSE);
14896 			return (B_TRUE);
14897 		case SIOCGTUNPARAM:
14898 		case OSIOCGTUNPARAM:
14899 			ip_rput_other(NULL, q, mp, NULL);
14900 			return (B_TRUE);
14901 		default:
14902 			break;
14903 		}
14904 		/* FALLTHRU */
14905 	default:
14906 		putnext(q, mp);
14907 		return (B_TRUE);
14908 	}
14909 }
14910 
14911 /* Read side put procedure.  Packets coming from the wire arrive here. */
14912 void
14913 ip_rput(queue_t *q, mblk_t *mp)
14914 {
14915 	ill_t	*ill;
14916 	ip_stack_t	*ipst;
14917 
14918 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14919 
14920 	ill = (ill_t *)q->q_ptr;
14921 	ipst = ill->ill_ipst;
14922 
14923 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14924 		union DL_primitives *dl;
14925 
14926 		/*
14927 		 * Things are opening or closing. Only accept DLPI control
14928 		 * messages. In the open case, the ill->ill_ipif has not yet
14929 		 * been created. In the close case, things hanging off the
14930 		 * ill could have been freed already. In either case it
14931 		 * may not be safe to proceed further.
14932 		 */
14933 
14934 		dl = (union DL_primitives *)mp->b_rptr;
14935 		if ((mp->b_datap->db_type != M_PCPROTO) ||
14936 		    (dl->dl_primitive == DL_UNITDATA_IND)) {
14937 			/*
14938 			 * Also SIOC[GS]TUN* ioctls can come here.
14939 			 */
14940 			inet_freemsg(mp);
14941 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14942 			    "ip_input_end: q %p (%S)", q, "uninit");
14943 			return;
14944 		}
14945 	}
14946 
14947 	/*
14948 	 * if db_ref > 1 then copymsg and free original. Packet may be
14949 	 * changed and we do not want the other entity who has a reference to
14950 	 * this message to trip over the changes. This is a blind change because
14951 	 * trying to catch all places that might change the packet is too
14952 	 * difficult.
14953 	 *
14954 	 * This corresponds to the fast path case, where we have a chain of
14955 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14956 	 * in the mblk chain. There doesn't seem to be a reason why a device
14957 	 * driver would send up data with varying db_ref counts in the mblk
14958 	 * chain. In any case the Fast path is a private interface, and our
14959 	 * drivers don't do such a thing. Given the above assumption, there is
14960 	 * no need to walk down the entire mblk chain (which could have a
14961 	 * potential performance problem)
14962 	 */
14963 	if (mp->b_datap->db_ref > 1) {
14964 		mblk_t  *mp1;
14965 		boolean_t adjusted = B_FALSE;
14966 		IP_STAT(ipst, ip_db_ref);
14967 
14968 		/*
14969 		 * The IP_RECVSLLA option depends on having the link layer
14970 		 * header. First check that:
14971 		 * a> the underlying device is of type ether, since this
14972 		 * option is currently supported only over ethernet.
14973 		 * b> there is enough room to copy over the link layer header.
14974 		 *
14975 		 * Once the checks are done, adjust rptr so that the link layer
14976 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14977 		 * be returned by some non-ethernet drivers but in this case the
14978 		 * second check will fail.
14979 		 */
14980 		if (ill->ill_type == IFT_ETHER &&
14981 		    (mp->b_rptr - mp->b_datap->db_base) >=
14982 		    sizeof (struct ether_header)) {
14983 			mp->b_rptr -= sizeof (struct ether_header);
14984 			adjusted = B_TRUE;
14985 		}
14986 		mp1 = copymsg(mp);
14987 		if (mp1 == NULL) {
14988 			mp->b_next = NULL;
14989 			/* clear b_prev - used by ip_mroute_decap */
14990 			mp->b_prev = NULL;
14991 			freemsg(mp);
14992 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14993 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14994 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14995 			return;
14996 		}
14997 		if (adjusted) {
14998 			/*
14999 			 * Copy is done. Restore the pointer in the _new_ mblk
15000 			 */
15001 			mp1->b_rptr += sizeof (struct ether_header);
15002 		}
15003 		/* Copy b_prev - used by ip_mroute_decap */
15004 		mp1->b_prev = mp->b_prev;
15005 		mp->b_prev = NULL;
15006 		freemsg(mp);
15007 		mp = mp1;
15008 	}
15009 
15010 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15011 	    "ip_rput_end: q %p (%S)", q, "end");
15012 
15013 	ip_input(ill, NULL, mp, NULL);
15014 }
15015 
15016 /*
15017  * Direct read side procedure capable of dealing with chains. GLDv3 based
15018  * drivers call this function directly with mblk chains while STREAMS
15019  * read side procedure ip_rput() calls this for single packet with ip_ring
15020  * set to NULL to process one packet at a time.
15021  *
15022  * The ill will always be valid if this function is called directly from
15023  * the driver.
15024  *
15025  * If ip_input() is called from GLDv3:
15026  *
15027  *   - This must be a non-VLAN IP stream.
15028  *   - 'mp' is either an untagged or a special priority-tagged packet.
15029  *   - Any VLAN tag that was in the MAC header has been stripped.
15030  *
15031  * If the IP header in packet is not 32-bit aligned, every message in the
15032  * chain will be aligned before further operations. This is required on SPARC
15033  * platform.
15034  */
15035 /* ARGSUSED */
15036 void
15037 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15038     struct mac_header_info_s *mhip)
15039 {
15040 	ipaddr_t		dst = NULL;
15041 	ipaddr_t		prev_dst;
15042 	ire_t			*ire = NULL;
15043 	ipha_t			*ipha;
15044 	uint_t			pkt_len;
15045 	ssize_t			len;
15046 	uint_t			opt_len;
15047 	int			ll_multicast;
15048 	int			cgtp_flt_pkt;
15049 	queue_t			*q = ill->ill_rq;
15050 	squeue_t		*curr_sqp = NULL;
15051 	mblk_t 			*head = NULL;
15052 	mblk_t			*tail = NULL;
15053 	mblk_t			*first_mp;
15054 	mblk_t 			*mp;
15055 	mblk_t			*dmp;
15056 	int			cnt = 0;
15057 	ip_stack_t		*ipst = ill->ill_ipst;
15058 
15059 	ASSERT(mp_chain != NULL);
15060 	ASSERT(ill != NULL);
15061 
15062 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15063 
15064 #define	rptr	((uchar_t *)ipha)
15065 
15066 	while (mp_chain != NULL) {
15067 		first_mp = mp = mp_chain;
15068 		mp_chain = mp_chain->b_next;
15069 		mp->b_next = NULL;
15070 		ll_multicast = 0;
15071 
15072 		/*
15073 		 * We do ire caching from one iteration to
15074 		 * another. In the event the packet chain contains
15075 		 * all packets from the same dst, this caching saves
15076 		 * an ire_cache_lookup for each of the succeeding
15077 		 * packets in a packet chain.
15078 		 */
15079 		prev_dst = dst;
15080 
15081 		/*
15082 		 * Check and align the IP header.
15083 		 */
15084 		if (DB_TYPE(mp) == M_DATA) {
15085 			dmp = mp;
15086 		} else if (DB_TYPE(mp) == M_PROTO &&
15087 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15088 			dmp = mp->b_cont;
15089 		} else {
15090 			dmp = NULL;
15091 		}
15092 		if (dmp != NULL) {
15093 			/*
15094 			 * IP header ptr not aligned?
15095 			 * OR IP header not complete in first mblk
15096 			 */
15097 			if (!OK_32PTR(dmp->b_rptr) ||
15098 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15099 				if (!ip_check_and_align_header(q, dmp, ipst))
15100 					continue;
15101 			}
15102 		}
15103 
15104 		/*
15105 		 * ip_input fast path
15106 		 */
15107 
15108 		/* mblk type is not M_DATA */
15109 		if (DB_TYPE(mp) != M_DATA) {
15110 			if (ip_rput_process_notdata(q, &first_mp, ill,
15111 			    &ll_multicast, &mp))
15112 				continue;
15113 		}
15114 
15115 		/* Make sure its an M_DATA and that its aligned */
15116 		ASSERT(DB_TYPE(mp) == M_DATA);
15117 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15118 
15119 		ipha = (ipha_t *)mp->b_rptr;
15120 		len = mp->b_wptr - rptr;
15121 		pkt_len = ntohs(ipha->ipha_length);
15122 
15123 		/*
15124 		 * We must count all incoming packets, even if they end
15125 		 * up being dropped later on.
15126 		 */
15127 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15128 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15129 
15130 		/* multiple mblk or too short */
15131 		len -= pkt_len;
15132 		if (len != 0) {
15133 			/*
15134 			 * Make sure we have data length consistent
15135 			 * with the IP header.
15136 			 */
15137 			if (mp->b_cont == NULL) {
15138 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15139 					BUMP_MIB(ill->ill_ip_mib,
15140 					    ipIfStatsInHdrErrors);
15141 					ip2dbg(("ip_input: drop pkt\n"));
15142 					freemsg(mp);
15143 					continue;
15144 				}
15145 				mp->b_wptr = rptr + pkt_len;
15146 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15147 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15148 					BUMP_MIB(ill->ill_ip_mib,
15149 					    ipIfStatsInHdrErrors);
15150 					ip2dbg(("ip_input: drop pkt\n"));
15151 					freemsg(mp);
15152 					continue;
15153 				}
15154 				(void) adjmsg(mp, -len);
15155 				IP_STAT(ipst, ip_multimblk3);
15156 			}
15157 		}
15158 
15159 		/* Obtain the dst of the current packet */
15160 		dst = ipha->ipha_dst;
15161 
15162 		if (IP_LOOPBACK_ADDR(dst) ||
15163 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15164 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15165 			cmn_err(CE_CONT, "dst %X src %X\n",
15166 			    dst, ipha->ipha_src);
15167 			freemsg(mp);
15168 			continue;
15169 		}
15170 
15171 		/*
15172 		 * The event for packets being received from a 'physical'
15173 		 * interface is placed after validation of the source and/or
15174 		 * destination address as being local so that packets can be
15175 		 * redirected to loopback addresses using ipnat.
15176 		 */
15177 		DTRACE_PROBE4(ip4__physical__in__start,
15178 		    ill_t *, ill, ill_t *, NULL,
15179 		    ipha_t *, ipha, mblk_t *, first_mp);
15180 
15181 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15182 		    ipst->ips_ipv4firewall_physical_in,
15183 		    ill, NULL, ipha, first_mp, mp, ipst);
15184 
15185 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15186 
15187 		if (first_mp == NULL) {
15188 			continue;
15189 		}
15190 		dst = ipha->ipha_dst;
15191 
15192 		/*
15193 		 * Attach any necessary label information to
15194 		 * this packet
15195 		 */
15196 		if (is_system_labeled() &&
15197 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15198 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15199 			freemsg(mp);
15200 			continue;
15201 		}
15202 
15203 		/*
15204 		 * Reuse the cached ire only if the ipha_dst of the previous
15205 		 * packet is the same as the current packet AND it is not
15206 		 * INADDR_ANY.
15207 		 */
15208 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15209 		    (ire != NULL)) {
15210 			ire_refrele(ire);
15211 			ire = NULL;
15212 		}
15213 		opt_len = ipha->ipha_version_and_hdr_length -
15214 		    IP_SIMPLE_HDR_VERSION;
15215 
15216 		/*
15217 		 * Check to see if we can take the fastpath.
15218 		 * That is possible if the following conditions are met
15219 		 *	o Tsol disabled
15220 		 *	o CGTP disabled
15221 		 *	o ipp_action_count is 0
15222 		 *	o Mobile IP not running
15223 		 *	o no options in the packet
15224 		 *	o not a RSVP packet
15225 		 * 	o not a multicast packet
15226 		 */
15227 		if (!is_system_labeled() &&
15228 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15229 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15230 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15231 		    !ll_multicast && !CLASSD(dst)) {
15232 			if (ire == NULL)
15233 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15234 				    ipst);
15235 
15236 			/* incoming packet is for forwarding */
15237 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15238 				ire = ip_fast_forward(ire, dst, ill, mp);
15239 				continue;
15240 			}
15241 			/* incoming packet is for local consumption */
15242 			if (ire->ire_type & IRE_LOCAL)
15243 				goto local;
15244 		}
15245 
15246 		/*
15247 		 * Disable ire caching for anything more complex
15248 		 * than the simple fast path case we checked for above.
15249 		 */
15250 		if (ire != NULL) {
15251 			ire_refrele(ire);
15252 			ire = NULL;
15253 		}
15254 
15255 		/* Full-blown slow path */
15256 		if (opt_len != 0) {
15257 			if (len != 0)
15258 				IP_STAT(ipst, ip_multimblk4);
15259 			else
15260 				IP_STAT(ipst, ip_ipoptions);
15261 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15262 			    &dst, ipst))
15263 				continue;
15264 		}
15265 
15266 		/*
15267 		 * Invoke the CGTP (multirouting) filtering module to process
15268 		 * the incoming packet. Packets identified as duplicates
15269 		 * must be discarded. Filtering is active only if the
15270 		 * the ip_cgtp_filter ndd variable is non-zero.
15271 		 *
15272 		 * Only applies to the shared stack since the filter_ops
15273 		 * do not carry an ip_stack_t or zoneid.
15274 		 */
15275 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15276 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15277 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15278 			cgtp_flt_pkt =
15279 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15280 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15281 				freemsg(first_mp);
15282 				continue;
15283 			}
15284 		}
15285 
15286 		/*
15287 		 * If rsvpd is running, let RSVP daemon handle its processing
15288 		 * and forwarding of RSVP multicast/unicast packets.
15289 		 * If rsvpd is not running but mrouted is running, RSVP
15290 		 * multicast packets are forwarded as multicast traffic
15291 		 * and RSVP unicast packets are forwarded by unicast router.
15292 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15293 		 * packets are not forwarded, but the unicast packets are
15294 		 * forwarded like unicast traffic.
15295 		 */
15296 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15297 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15298 		    NULL) {
15299 			/* RSVP packet and rsvpd running. Treat as ours */
15300 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15301 			/*
15302 			 * This assumes that we deliver to all streams for
15303 			 * multicast and broadcast packets.
15304 			 * We have to force ll_multicast to 1 to handle the
15305 			 * M_DATA messages passed in from ip_mroute_decap.
15306 			 */
15307 			dst = INADDR_BROADCAST;
15308 			ll_multicast = 1;
15309 		} else if (CLASSD(dst)) {
15310 			/* packet is multicast */
15311 			mp->b_next = NULL;
15312 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15313 			    &ll_multicast, &dst))
15314 				continue;
15315 		}
15316 
15317 
15318 		/*
15319 		 * Check if the packet is coming from the Mobile IP
15320 		 * forward tunnel interface
15321 		 */
15322 		if (ill->ill_srcif_refcnt > 0) {
15323 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15324 			    NULL, ill, MATCH_IRE_TYPE);
15325 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15326 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15327 
15328 				/* We need to resolve the link layer info */
15329 				ire_refrele(ire);
15330 				ire = NULL;
15331 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15332 				    ll_multicast, dst);
15333 				continue;
15334 			}
15335 		}
15336 
15337 		if (ire == NULL) {
15338 			ire = ire_cache_lookup(dst, ALL_ZONES,
15339 			    MBLK_GETLABEL(mp), ipst);
15340 		}
15341 
15342 		/*
15343 		 * If mipagent is running and reverse tunnel is created as per
15344 		 * mobile node request, then any packet coming through the
15345 		 * incoming interface from the mobile-node, should be reverse
15346 		 * tunneled to it's home agent except those that are destined
15347 		 * to foreign agent only.
15348 		 * This needs source address based ire lookup. The routing
15349 		 * entries for source address based lookup are only created by
15350 		 * mipagent program only when a reverse tunnel is created.
15351 		 * Reference : RFC2002, RFC2344
15352 		 */
15353 		if (ill->ill_mrtun_refcnt > 0) {
15354 			ipaddr_t	srcaddr;
15355 			ire_t		*tmp_ire;
15356 
15357 			tmp_ire = ire;	/* Save, we might need it later */
15358 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15359 			    ire->ire_type != IRE_BROADCAST)) {
15360 				srcaddr = ipha->ipha_src;
15361 				ire = ire_mrtun_lookup(srcaddr, ill);
15362 				if (ire != NULL) {
15363 					/*
15364 					 * Should not be getting iphada packet
15365 					 * here. we should only get those for
15366 					 * IRE_LOCAL traffic, excluded above.
15367 					 * Fail-safe (drop packet) in the event
15368 					 * hardware is misbehaving.
15369 					 */
15370 					if (first_mp != mp) {
15371 						/* IPsec KSTATS: beancount me */
15372 						freemsg(first_mp);
15373 					} else {
15374 						/*
15375 						 * This packet must be forwarded
15376 						 * to Reverse Tunnel
15377 						 */
15378 						ip_mrtun_forward(ire, ill, mp);
15379 					}
15380 					ire_refrele(ire);
15381 					ire = NULL;
15382 					if (tmp_ire != NULL) {
15383 						ire_refrele(tmp_ire);
15384 						tmp_ire = NULL;
15385 					}
15386 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15387 					    "ip_input_end: q %p (%S)",
15388 					    q, "uninit");
15389 					continue;
15390 				}
15391 			}
15392 			/*
15393 			 * If this packet is from a non-mobilenode  or a
15394 			 * mobile-node which does not request reverse
15395 			 * tunnel service
15396 			 */
15397 			ire = tmp_ire;
15398 		}
15399 
15400 
15401 		/*
15402 		 * If we reach here that means the incoming packet satisfies
15403 		 * one of the following conditions:
15404 		 *   - packet is from a mobile node which does not request
15405 		 *	reverse tunnel
15406 		 *   - packet is from a non-mobile node, which is the most
15407 		 *	common case
15408 		 *   - packet is from a reverse tunnel enabled mobile node
15409 		 *	and destined to foreign agent only
15410 		 */
15411 
15412 		if (ire == NULL) {
15413 			/*
15414 			 * No IRE for this destination, so it can't be for us.
15415 			 * Unless we are forwarding, drop the packet.
15416 			 * We have to let source routed packets through
15417 			 * since we don't yet know if they are 'ping -l'
15418 			 * packets i.e. if they will go out over the
15419 			 * same interface as they came in on.
15420 			 */
15421 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15422 			if (ire == NULL)
15423 				continue;
15424 		}
15425 
15426 		/*
15427 		 * Broadcast IRE may indicate either broadcast or
15428 		 * multicast packet
15429 		 */
15430 		if (ire->ire_type == IRE_BROADCAST) {
15431 			/*
15432 			 * Skip broadcast checks if packet is UDP multicast;
15433 			 * we'd rather not enter ip_rput_process_broadcast()
15434 			 * unless the packet is broadcast for real, since
15435 			 * that routine is a no-op for multicast.
15436 			 */
15437 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15438 			    !CLASSD(ipha->ipha_dst)) {
15439 				ire = ip_rput_process_broadcast(&q, mp,
15440 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15441 				    ll_multicast);
15442 				if (ire == NULL)
15443 					continue;
15444 			}
15445 		} else if (ire->ire_stq != NULL) {
15446 			/* fowarding? */
15447 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15448 			    ll_multicast);
15449 			/* ip_rput_process_forward consumed the packet */
15450 			continue;
15451 		}
15452 
15453 local:
15454 		/*
15455 		 * If the queue in the ire is different to the ingress queue
15456 		 * then we need to check to see if we can accept the packet.
15457 		 * Note that for multicast packets and broadcast packets sent
15458 		 * to a broadcast address which is shared between multiple
15459 		 * interfaces we should not do this since we just got a random
15460 		 * broadcast ire.
15461 		 */
15462 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15463 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15464 			    ill)) == NULL) {
15465 				/* Drop packet */
15466 				BUMP_MIB(ill->ill_ip_mib,
15467 				    ipIfStatsForwProhibits);
15468 				freemsg(mp);
15469 				continue;
15470 			}
15471 			if (ire->ire_rfq != NULL)
15472 				q = ire->ire_rfq;
15473 		}
15474 
15475 		switch (ipha->ipha_protocol) {
15476 		case IPPROTO_TCP:
15477 			ASSERT(first_mp == mp);
15478 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15479 				mp, 0, q, ip_ring)) != NULL) {
15480 				if (curr_sqp == NULL) {
15481 					curr_sqp = GET_SQUEUE(mp);
15482 					ASSERT(cnt == 0);
15483 					cnt++;
15484 					head = tail = mp;
15485 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15486 					ASSERT(tail != NULL);
15487 					cnt++;
15488 					tail->b_next = mp;
15489 					tail = mp;
15490 				} else {
15491 					/*
15492 					 * A different squeue. Send the
15493 					 * chain for the previous squeue on
15494 					 * its way. This shouldn't happen
15495 					 * often unless interrupt binding
15496 					 * changes.
15497 					 */
15498 					IP_STAT(ipst, ip_input_multi_squeue);
15499 					squeue_enter_chain(curr_sqp, head,
15500 					    tail, cnt, SQTAG_IP_INPUT);
15501 					curr_sqp = GET_SQUEUE(mp);
15502 					head = mp;
15503 					tail = mp;
15504 					cnt = 1;
15505 				}
15506 			}
15507 			continue;
15508 		case IPPROTO_UDP:
15509 			ASSERT(first_mp == mp);
15510 			ip_udp_input(q, mp, ipha, ire, ill);
15511 			continue;
15512 		case IPPROTO_SCTP:
15513 			ASSERT(first_mp == mp);
15514 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15515 			    q, dst);
15516 			/* ire has been released by ip_sctp_input */
15517 			ire = NULL;
15518 			continue;
15519 		default:
15520 			ip_proto_input(q, first_mp, ipha, ire, ill);
15521 			continue;
15522 		}
15523 	}
15524 
15525 	if (ire != NULL)
15526 		ire_refrele(ire);
15527 
15528 	if (head != NULL)
15529 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15530 
15531 	/*
15532 	 * This code is there just to make netperf/ttcp look good.
15533 	 *
15534 	 * Its possible that after being in polling mode (and having cleared
15535 	 * the backlog), squeues have turned the interrupt frequency higher
15536 	 * to improve latency at the expense of more CPU utilization (less
15537 	 * packets per interrupts or more number of interrupts). Workloads
15538 	 * like ttcp/netperf do manage to tickle polling once in a while
15539 	 * but for the remaining time, stay in higher interrupt mode since
15540 	 * their packet arrival rate is pretty uniform and this shows up
15541 	 * as higher CPU utilization. Since people care about CPU utilization
15542 	 * while running netperf/ttcp, turn the interrupt frequency back to
15543 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15544 	 */
15545 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15546 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15547 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15548 			ip_ring->rr_blank(ip_ring->rr_handle,
15549 			    ip_ring->rr_normal_blank_time,
15550 			    ip_ring->rr_normal_pkt_cnt);
15551 		}
15552 		}
15553 
15554 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15555 	    "ip_input_end: q %p (%S)", q, "end");
15556 #undef  rptr
15557 }
15558 
15559 static void
15560 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15561     t_uscalar_t err)
15562 {
15563 	if (dl_err == DL_SYSERR) {
15564 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15565 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15566 		    ill->ill_name, dlpi_prim_str(prim), err);
15567 		return;
15568 	}
15569 
15570 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15571 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15572 	    dlpi_err_str(dl_err));
15573 }
15574 
15575 /*
15576  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15577  * than DL_UNITDATA_IND messages. If we need to process this message
15578  * exclusively, we call qwriter_ip, in which case we also need to call
15579  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15580  */
15581 void
15582 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15583 {
15584 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15585 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15586 	ill_t		*ill;
15587 
15588 	ip1dbg(("ip_rput_dlpi"));
15589 	ill = (ill_t *)q->q_ptr;
15590 	switch (dloa->dl_primitive) {
15591 	case DL_ERROR_ACK:
15592 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15593 		    "%s (0x%x), unix %u\n", ill->ill_name,
15594 		    dlpi_prim_str(dlea->dl_error_primitive),
15595 		    dlea->dl_error_primitive,
15596 		    dlpi_err_str(dlea->dl_errno),
15597 		    dlea->dl_errno,
15598 		    dlea->dl_unix_errno));
15599 		switch (dlea->dl_error_primitive) {
15600 		case DL_UNBIND_REQ:
15601 			mutex_enter(&ill->ill_lock);
15602 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15603 			cv_signal(&ill->ill_cv);
15604 			mutex_exit(&ill->ill_lock);
15605 			/* FALLTHRU */
15606 		case DL_NOTIFY_REQ:
15607 		case DL_ATTACH_REQ:
15608 		case DL_DETACH_REQ:
15609 		case DL_INFO_REQ:
15610 		case DL_BIND_REQ:
15611 		case DL_ENABMULTI_REQ:
15612 		case DL_PHYS_ADDR_REQ:
15613 		case DL_CAPABILITY_REQ:
15614 		case DL_CONTROL_REQ:
15615 			/*
15616 			 * Refhold the ill to match qwriter_ip which does a
15617 			 * refrele. Since this is on the ill stream we
15618 			 * unconditionally bump up the refcount without
15619 			 * checking for ILL_CAN_LOOKUP
15620 			 */
15621 			ill_refhold(ill);
15622 			(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15623 			    CUR_OP, B_FALSE);
15624 			return;
15625 		case DL_DISABMULTI_REQ:
15626 			freemsg(mp);	/* Don't want to pass this up */
15627 			return;
15628 		default:
15629 			break;
15630 		}
15631 		ip_dlpi_error(ill, dlea->dl_error_primitive,
15632 		    dlea->dl_errno, dlea->dl_unix_errno);
15633 		freemsg(mp);
15634 		return;
15635 	case DL_INFO_ACK:
15636 	case DL_BIND_ACK:
15637 	case DL_PHYS_ADDR_ACK:
15638 	case DL_NOTIFY_ACK:
15639 	case DL_CAPABILITY_ACK:
15640 	case DL_CONTROL_ACK:
15641 		/*
15642 		 * Refhold the ill to match qwriter_ip which does a refrele
15643 		 * Since this is on the ill stream we unconditionally
15644 		 * bump up the refcount without doing ILL_CAN_LOOKUP.
15645 		 */
15646 		ill_refhold(ill);
15647 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15648 		    CUR_OP, B_FALSE);
15649 		return;
15650 	case DL_NOTIFY_IND:
15651 		ill_refhold(ill);
15652 		/*
15653 		 * The DL_NOTIFY_IND is an asynchronous message that has no
15654 		 * relation to the current ioctl in progress (if any). Hence we
15655 		 * pass in NEW_OP in this case.
15656 		 */
15657 		(void) qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15658 		    NEW_OP, B_FALSE);
15659 		return;
15660 	case DL_OK_ACK:
15661 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15662 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15663 		switch (dloa->dl_correct_primitive) {
15664 		case DL_UNBIND_REQ:
15665 			mutex_enter(&ill->ill_lock);
15666 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15667 			cv_signal(&ill->ill_cv);
15668 			mutex_exit(&ill->ill_lock);
15669 			/* FALLTHRU */
15670 		case DL_ATTACH_REQ:
15671 		case DL_DETACH_REQ:
15672 			/*
15673 			 * Refhold the ill to match qwriter_ip which does a
15674 			 * refrele. Since this is on the ill stream we
15675 			 * unconditionally bump up the refcount
15676 			 */
15677 			ill_refhold(ill);
15678 			qwriter_ip(NULL, ill, q, mp, ip_rput_dlpi_writer,
15679 			    CUR_OP, B_FALSE);
15680 			return;
15681 		case DL_ENABMULTI_REQ:
15682 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15683 				ill->ill_dlpi_multicast_state = IDS_OK;
15684 			break;
15685 
15686 		}
15687 		break;
15688 	default:
15689 		break;
15690 	}
15691 	freemsg(mp);
15692 }
15693 
15694 /*
15695  * Handling of DLPI messages that require exclusive access to the ipsq.
15696  *
15697  * Need to do ill_pending_mp_release on ioctl completion, which could
15698  * happen here. (along with mi_copy_done)
15699  */
15700 /* ARGSUSED */
15701 static void
15702 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15703 {
15704 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15705 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15706 	int		err = 0;
15707 	ill_t		*ill;
15708 	ipif_t		*ipif = NULL;
15709 	mblk_t		*mp1 = NULL;
15710 	conn_t		*connp = NULL;
15711 	t_uscalar_t	paddrreq;
15712 	mblk_t		*mp_hw;
15713 	boolean_t	success;
15714 	boolean_t	ioctl_aborted = B_FALSE;
15715 	boolean_t	log = B_TRUE;
15716 	hook_nic_event_t	*info;
15717 	ip_stack_t		*ipst;
15718 
15719 	ip1dbg(("ip_rput_dlpi_writer .."));
15720 	ill = (ill_t *)q->q_ptr;
15721 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15722 
15723 	ASSERT(IAM_WRITER_ILL(ill));
15724 
15725 	ipst = ill->ill_ipst;
15726 
15727 	/*
15728 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15729 	 * both are null or non-null. However we can assert that only
15730 	 * after grabbing the ipsq_lock. So we don't make any assertion
15731 	 * here and in other places in the code.
15732 	 */
15733 	ipif = ipsq->ipsq_pending_ipif;
15734 	/*
15735 	 * The current ioctl could have been aborted by the user and a new
15736 	 * ioctl to bring up another ill could have started. We could still
15737 	 * get a response from the driver later.
15738 	 */
15739 	if (ipif != NULL && ipif->ipif_ill != ill)
15740 		ioctl_aborted = B_TRUE;
15741 
15742 	switch (dloa->dl_primitive) {
15743 	case DL_ERROR_ACK:
15744 		switch (dlea->dl_error_primitive) {
15745 		case DL_UNBIND_REQ:
15746 		case DL_ATTACH_REQ:
15747 		case DL_DETACH_REQ:
15748 		case DL_INFO_REQ:
15749 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15750 			break;
15751 		case DL_NOTIFY_REQ:
15752 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15753 			log = B_FALSE;
15754 			break;
15755 		case DL_PHYS_ADDR_REQ:
15756 			/*
15757 			 * For IPv6 only, there are two additional
15758 			 * phys_addr_req's sent to the driver to get the
15759 			 * IPv6 token and lla. This allows IP to acquire
15760 			 * the hardware address format for a given interface
15761 			 * without having built in knowledge of the hardware
15762 			 * address. ill_phys_addr_pend keeps track of the last
15763 			 * DL_PAR sent so we know which response we are
15764 			 * dealing with. ill_dlpi_done will update
15765 			 * ill_phys_addr_pend when it sends the next req.
15766 			 * We don't complete the IOCTL until all three DL_PARs
15767 			 * have been attempted, so set *_len to 0 and break.
15768 			 */
15769 			paddrreq = ill->ill_phys_addr_pend;
15770 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15771 			if (paddrreq == DL_IPV6_TOKEN) {
15772 				ill->ill_token_length = 0;
15773 				log = B_FALSE;
15774 				break;
15775 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15776 				ill->ill_nd_lla_len = 0;
15777 				log = B_FALSE;
15778 				break;
15779 			}
15780 			/*
15781 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15782 			 * We presumably have an IOCTL hanging out waiting
15783 			 * for completion. Find it and complete the IOCTL
15784 			 * with the error noted.
15785 			 * However, ill_dl_phys was called on an ill queue
15786 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15787 			 * set. But the ioctl is known to be pending on ill_wq.
15788 			 */
15789 			if (!ill->ill_ifname_pending)
15790 				break;
15791 			ill->ill_ifname_pending = 0;
15792 			if (!ioctl_aborted)
15793 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15794 			if (mp1 != NULL) {
15795 				/*
15796 				 * This operation (SIOCSLIFNAME) must have
15797 				 * happened on the ill. Assert there is no conn
15798 				 */
15799 				ASSERT(connp == NULL);
15800 				q = ill->ill_wq;
15801 			}
15802 			break;
15803 		case DL_BIND_REQ:
15804 			ill_dlpi_done(ill, DL_BIND_REQ);
15805 			if (ill->ill_ifname_pending)
15806 				break;
15807 			/*
15808 			 * Something went wrong with the bind.  We presumably
15809 			 * have an IOCTL hanging out waiting for completion.
15810 			 * Find it, take down the interface that was coming
15811 			 * up, and complete the IOCTL with the error noted.
15812 			 */
15813 			if (!ioctl_aborted)
15814 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15815 			if (mp1 != NULL) {
15816 				/*
15817 				 * This operation (SIOCSLIFFLAGS) must have
15818 				 * happened from a conn.
15819 				 */
15820 				ASSERT(connp != NULL);
15821 				q = CONNP_TO_WQ(connp);
15822 				if (ill->ill_move_in_progress) {
15823 					ILL_CLEAR_MOVE(ill);
15824 				}
15825 				(void) ipif_down(ipif, NULL, NULL);
15826 				/* error is set below the switch */
15827 			}
15828 			break;
15829 		case DL_ENABMULTI_REQ:
15830 			ip1dbg(("DL_ERROR_ACK to enabmulti\n"));
15831 
15832 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15833 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15834 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15835 				ipif_t *ipif;
15836 
15837 				log = B_FALSE;
15838 				printf("ip: joining multicasts failed (%d)"
15839 				    " on %s - will use link layer "
15840 				    "broadcasts for multicast\n",
15841 				    dlea->dl_errno, ill->ill_name);
15842 
15843 				/*
15844 				 * Set up the multicast mapping alone.
15845 				 * writer, so ok to access ill->ill_ipif
15846 				 * without any lock.
15847 				 */
15848 				ipif = ill->ill_ipif;
15849 				mutex_enter(&ill->ill_phyint->phyint_lock);
15850 				ill->ill_phyint->phyint_flags |=
15851 				    PHYI_MULTI_BCAST;
15852 				mutex_exit(&ill->ill_phyint->phyint_lock);
15853 
15854 				if (!ill->ill_isv6) {
15855 					(void) ipif_arp_setup_multicast(ipif,
15856 					    NULL);
15857 				} else {
15858 					(void) ipif_ndp_setup_multicast(ipif,
15859 					    NULL);
15860 				}
15861 			}
15862 			freemsg(mp);	/* Don't want to pass this up */
15863 			return;
15864 		case DL_CAPABILITY_REQ:
15865 		case DL_CONTROL_REQ:
15866 			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
15867 			    "DL_CAPABILITY/CONTROL REQ\n"));
15868 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15869 			ill->ill_dlpi_capab_state = IDS_FAILED;
15870 			freemsg(mp);
15871 			return;
15872 		}
15873 		/*
15874 		 * Note the error for IOCTL completion (mp1 is set when
15875 		 * ready to complete ioctl). If ill_ifname_pending_err is
15876 		 * set, an error occured during plumbing (ill_ifname_pending),
15877 		 * so we want to report that error.
15878 		 *
15879 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15880 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15881 		 * expected to get errack'd if the driver doesn't support
15882 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15883 		 * if these error conditions are encountered.
15884 		 */
15885 		if (mp1 != NULL) {
15886 			if (ill->ill_ifname_pending_err != 0)  {
15887 				err = ill->ill_ifname_pending_err;
15888 				ill->ill_ifname_pending_err = 0;
15889 			} else {
15890 				err = dlea->dl_unix_errno ?
15891 				    dlea->dl_unix_errno : ENXIO;
15892 			}
15893 		/*
15894 		 * If we're plumbing an interface and an error hasn't already
15895 		 * been saved, set ill_ifname_pending_err to the error passed
15896 		 * up. Ignore the error if log is B_FALSE (see comment above).
15897 		 */
15898 		} else if (log && ill->ill_ifname_pending &&
15899 		    ill->ill_ifname_pending_err == 0) {
15900 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15901 			dlea->dl_unix_errno : ENXIO;
15902 		}
15903 
15904 		if (log)
15905 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15906 			    dlea->dl_errno, dlea->dl_unix_errno);
15907 		break;
15908 	case DL_CAPABILITY_ACK: {
15909 		boolean_t reneg_flag = B_FALSE;
15910 		/* Call a routine to handle this one. */
15911 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15912 		/*
15913 		 * Check if the ACK is due to renegotiation case since we
15914 		 * will need to send a new CAPABILITY_REQ later.
15915 		 */
15916 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15917 			/* This is the ack for a renogiation case */
15918 			reneg_flag = B_TRUE;
15919 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15920 		}
15921 		ill_capability_ack(ill, mp);
15922 		if (reneg_flag)
15923 			ill_capability_probe(ill);
15924 		break;
15925 	}
15926 	case DL_CONTROL_ACK:
15927 		/* We treat all of these as "fire and forget" */
15928 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15929 		break;
15930 	case DL_INFO_ACK:
15931 		/* Call a routine to handle this one. */
15932 		ill_dlpi_done(ill, DL_INFO_REQ);
15933 		ip_ll_subnet_defaults(ill, mp);
15934 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15935 		return;
15936 	case DL_BIND_ACK:
15937 		/*
15938 		 * We should have an IOCTL waiting on this unless
15939 		 * sent by ill_dl_phys, in which case just return
15940 		 */
15941 		ill_dlpi_done(ill, DL_BIND_REQ);
15942 		if (ill->ill_ifname_pending)
15943 			break;
15944 
15945 		if (!ioctl_aborted)
15946 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15947 		if (mp1 == NULL)
15948 			break;
15949 		/*
15950 		 * Because mp1 was added by ill_dl_up(), and it always
15951 		 * passes a valid connp, connp must be valid here.
15952 		 */
15953 		ASSERT(connp != NULL);
15954 		q = CONNP_TO_WQ(connp);
15955 
15956 		/*
15957 		 * We are exclusive. So nothing can change even after
15958 		 * we get the pending mp. If need be we can put it back
15959 		 * and restart, as in calling ipif_arp_up()  below.
15960 		 */
15961 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15962 
15963 		mutex_enter(&ill->ill_lock);
15964 
15965 		ill->ill_dl_up = 1;
15966 
15967 		if ((info = ill->ill_nic_event_info) != NULL) {
15968 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15969 			    "attached for %s\n", info->hne_event,
15970 			    ill->ill_name));
15971 			if (info->hne_data != NULL)
15972 				kmem_free(info->hne_data, info->hne_datalen);
15973 			kmem_free(info, sizeof (hook_nic_event_t));
15974 		}
15975 
15976 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15977 		if (info != NULL) {
15978 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15979 			info->hne_lif = 0;
15980 			info->hne_event = NE_UP;
15981 			info->hne_data = NULL;
15982 			info->hne_datalen = 0;
15983 			info->hne_family = ill->ill_isv6 ?
15984 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15985 		} else
15986 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15987 			    "event information for %s (ENOMEM)\n",
15988 			    ill->ill_name));
15989 
15990 		ill->ill_nic_event_info = info;
15991 
15992 		mutex_exit(&ill->ill_lock);
15993 
15994 		/*
15995 		 * Now bring up the resolver; when that is complete, we'll
15996 		 * create IREs.  Note that we intentionally mirror what
15997 		 * ipif_up() would have done, because we got here by way of
15998 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15999 		 */
16000 		if (ill->ill_isv6) {
16001 			/*
16002 			 * v6 interfaces.
16003 			 * Unlike ARP which has to do another bind
16004 			 * and attach, once we get here we are
16005 			 * done with NDP. Except in the case of
16006 			 * ILLF_XRESOLV, in which case we send an
16007 			 * AR_INTERFACE_UP to the external resolver.
16008 			 * If all goes well, the ioctl will complete
16009 			 * in ip_rput(). If there's an error, we
16010 			 * complete it here.
16011 			 */
16012 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
16013 			if (err == 0) {
16014 				if (ill->ill_flags & ILLF_XRESOLV) {
16015 					mutex_enter(&connp->conn_lock);
16016 					mutex_enter(&ill->ill_lock);
16017 					success = ipsq_pending_mp_add(
16018 					    connp, ipif, q, mp1, 0);
16019 					mutex_exit(&ill->ill_lock);
16020 					mutex_exit(&connp->conn_lock);
16021 					if (success) {
16022 						err = ipif_resolver_up(ipif,
16023 						    Res_act_initial);
16024 						if (err == EINPROGRESS) {
16025 							freemsg(mp);
16026 							return;
16027 						}
16028 						ASSERT(err != 0);
16029 						mp1 = ipsq_pending_mp_get(ipsq,
16030 						    &connp);
16031 						ASSERT(mp1 != NULL);
16032 					} else {
16033 						/* conn has started closing */
16034 						err = EINTR;
16035 					}
16036 				} else { /* Non XRESOLV interface */
16037 					(void) ipif_resolver_up(ipif,
16038 					    Res_act_initial);
16039 					err = ipif_up_done_v6(ipif);
16040 				}
16041 			}
16042 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16043 			/*
16044 			 * ARP and other v4 external resolvers.
16045 			 * Leave the pending mblk intact so that
16046 			 * the ioctl completes in ip_rput().
16047 			 */
16048 			mutex_enter(&connp->conn_lock);
16049 			mutex_enter(&ill->ill_lock);
16050 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16051 			mutex_exit(&ill->ill_lock);
16052 			mutex_exit(&connp->conn_lock);
16053 			if (success) {
16054 				err = ipif_resolver_up(ipif, Res_act_initial);
16055 				if (err == EINPROGRESS) {
16056 					freemsg(mp);
16057 					return;
16058 				}
16059 				ASSERT(err != 0);
16060 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16061 			} else {
16062 				/* The conn has started closing */
16063 				err = EINTR;
16064 			}
16065 		} else {
16066 			/*
16067 			 * This one is complete. Reply to pending ioctl.
16068 			 */
16069 			(void) ipif_resolver_up(ipif, Res_act_initial);
16070 			err = ipif_up_done(ipif);
16071 		}
16072 
16073 		if ((err == 0) && (ill->ill_up_ipifs)) {
16074 			err = ill_up_ipifs(ill, q, mp1);
16075 			if (err == EINPROGRESS) {
16076 				freemsg(mp);
16077 				return;
16078 			}
16079 		}
16080 
16081 		if (ill->ill_up_ipifs) {
16082 			ill_group_cleanup(ill);
16083 		}
16084 
16085 		break;
16086 	case DL_NOTIFY_IND: {
16087 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16088 		ire_t *ire;
16089 		boolean_t need_ire_walk_v4 = B_FALSE;
16090 		boolean_t need_ire_walk_v6 = B_FALSE;
16091 
16092 		switch (notify->dl_notification) {
16093 		case DL_NOTE_PHYS_ADDR:
16094 			err = ill_set_phys_addr(ill, mp);
16095 			break;
16096 
16097 		case DL_NOTE_FASTPATH_FLUSH:
16098 			ill_fastpath_flush(ill);
16099 			break;
16100 
16101 		case DL_NOTE_SDU_SIZE:
16102 			/*
16103 			 * Change the MTU size of the interface, of all
16104 			 * attached ipif's, and of all relevant ire's.  The
16105 			 * new value's a uint32_t at notify->dl_data.
16106 			 * Mtu change Vs. new ire creation - protocol below.
16107 			 *
16108 			 * a Mark the ipif as IPIF_CHANGING.
16109 			 * b Set the new mtu in the ipif.
16110 			 * c Change the ire_max_frag on all affected ires
16111 			 * d Unmark the IPIF_CHANGING
16112 			 *
16113 			 * To see how the protocol works, assume an interface
16114 			 * route is also being added simultaneously by
16115 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16116 			 * the ire. If the ire is created before step a,
16117 			 * it will be cleaned up by step c. If the ire is
16118 			 * created after step d, it will see the new value of
16119 			 * ipif_mtu. Any attempt to create the ire between
16120 			 * steps a to d will fail because of the IPIF_CHANGING
16121 			 * flag. Note that ire_create() is passed a pointer to
16122 			 * the ipif_mtu, and not the value. During ire_add
16123 			 * under the bucket lock, the ire_max_frag of the
16124 			 * new ire being created is set from the ipif/ire from
16125 			 * which it is being derived.
16126 			 */
16127 			mutex_enter(&ill->ill_lock);
16128 			ill->ill_max_frag = (uint_t)notify->dl_data;
16129 
16130 			/*
16131 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16132 			 * leave it alone
16133 			 */
16134 			if (ill->ill_mtu_userspecified) {
16135 				mutex_exit(&ill->ill_lock);
16136 				break;
16137 			}
16138 			ill->ill_max_mtu = ill->ill_max_frag;
16139 			if (ill->ill_isv6) {
16140 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16141 					ill->ill_max_mtu = IPV6_MIN_MTU;
16142 			} else {
16143 				if (ill->ill_max_mtu < IP_MIN_MTU)
16144 					ill->ill_max_mtu = IP_MIN_MTU;
16145 			}
16146 			for (ipif = ill->ill_ipif; ipif != NULL;
16147 			    ipif = ipif->ipif_next) {
16148 				/*
16149 				 * Don't override the mtu if the user
16150 				 * has explicitly set it.
16151 				 */
16152 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16153 					continue;
16154 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16155 				if (ipif->ipif_isv6)
16156 					ire = ipif_to_ire_v6(ipif);
16157 				else
16158 					ire = ipif_to_ire(ipif);
16159 				if (ire != NULL) {
16160 					ire->ire_max_frag = ipif->ipif_mtu;
16161 					ire_refrele(ire);
16162 				}
16163 				if (ipif->ipif_flags & IPIF_UP) {
16164 					if (ill->ill_isv6)
16165 						need_ire_walk_v6 = B_TRUE;
16166 					else
16167 						need_ire_walk_v4 = B_TRUE;
16168 				}
16169 			}
16170 			mutex_exit(&ill->ill_lock);
16171 			if (need_ire_walk_v4)
16172 				ire_walk_v4(ill_mtu_change, (char *)ill,
16173 				    ALL_ZONES, ipst);
16174 			if (need_ire_walk_v6)
16175 				ire_walk_v6(ill_mtu_change, (char *)ill,
16176 				    ALL_ZONES, ipst);
16177 			break;
16178 		case DL_NOTE_LINK_UP:
16179 		case DL_NOTE_LINK_DOWN: {
16180 			/*
16181 			 * We are writer. ill / phyint / ipsq assocs stable.
16182 			 * The RUNNING flag reflects the state of the link.
16183 			 */
16184 			phyint_t *phyint = ill->ill_phyint;
16185 			uint64_t new_phyint_flags;
16186 			boolean_t changed = B_FALSE;
16187 			boolean_t went_up;
16188 
16189 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16190 			mutex_enter(&phyint->phyint_lock);
16191 			new_phyint_flags = went_up ?
16192 			    phyint->phyint_flags | PHYI_RUNNING :
16193 			    phyint->phyint_flags & ~PHYI_RUNNING;
16194 			if (new_phyint_flags != phyint->phyint_flags) {
16195 				phyint->phyint_flags = new_phyint_flags;
16196 				changed = B_TRUE;
16197 			}
16198 			mutex_exit(&phyint->phyint_lock);
16199 			/*
16200 			 * ill_restart_dad handles the DAD restart and routing
16201 			 * socket notification logic.
16202 			 */
16203 			if (changed) {
16204 				ill_restart_dad(phyint->phyint_illv4, went_up);
16205 				ill_restart_dad(phyint->phyint_illv6, went_up);
16206 			}
16207 			break;
16208 		}
16209 		case DL_NOTE_PROMISC_ON_PHYS:
16210 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16211 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16212 			mutex_enter(&ill->ill_lock);
16213 			ill->ill_promisc_on_phys = B_TRUE;
16214 			mutex_exit(&ill->ill_lock);
16215 			break;
16216 		case DL_NOTE_PROMISC_OFF_PHYS:
16217 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16218 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16219 			mutex_enter(&ill->ill_lock);
16220 			ill->ill_promisc_on_phys = B_FALSE;
16221 			mutex_exit(&ill->ill_lock);
16222 			break;
16223 		case DL_NOTE_CAPAB_RENEG:
16224 			/*
16225 			 * Something changed on the driver side.
16226 			 * It wants us to renegotiate the capabilities
16227 			 * on this ill. The most likely cause is the
16228 			 * aggregation interface under us where a
16229 			 * port got added or went away.
16230 			 *
16231 			 * We reset the capabilities and set the
16232 			 * state to IDS_RENG so that when the ack
16233 			 * comes back, we can start the
16234 			 * renegotiation process.
16235 			 */
16236 			ill_capability_reset(ill);
16237 			ill->ill_dlpi_capab_state = IDS_RENEG;
16238 			break;
16239 		default:
16240 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16241 			    "type 0x%x for DL_NOTIFY_IND\n",
16242 			    notify->dl_notification));
16243 			break;
16244 		}
16245 
16246 		/*
16247 		 * As this is an asynchronous operation, we
16248 		 * should not call ill_dlpi_done
16249 		 */
16250 		break;
16251 	}
16252 	case DL_NOTIFY_ACK: {
16253 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16254 
16255 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16256 			ill->ill_note_link = 1;
16257 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16258 		break;
16259 	}
16260 	case DL_PHYS_ADDR_ACK: {
16261 		/*
16262 		 * As part of plumbing the interface via SIOCSLIFNAME,
16263 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16264 		 * whose answers we receive here.  As each answer is received,
16265 		 * we call ill_dlpi_done() to dispatch the next request as
16266 		 * we're processing the current one.  Once all answers have
16267 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16268 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16269 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16270 		 * available, but we know the ioctl is pending on ill_wq.)
16271 		 */
16272 		uint_t paddrlen, paddroff;
16273 
16274 		paddrreq = ill->ill_phys_addr_pend;
16275 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16276 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16277 
16278 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16279 		if (paddrreq == DL_IPV6_TOKEN) {
16280 			/*
16281 			 * bcopy to low-order bits of ill_token
16282 			 *
16283 			 * XXX Temporary hack - currently, all known tokens
16284 			 * are 64 bits, so I'll cheat for the moment.
16285 			 */
16286 			bcopy(mp->b_rptr + paddroff,
16287 			    &ill->ill_token.s6_addr32[2], paddrlen);
16288 			ill->ill_token_length = paddrlen;
16289 			break;
16290 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16291 			ASSERT(ill->ill_nd_lla_mp == NULL);
16292 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16293 			mp = NULL;
16294 			break;
16295 		}
16296 
16297 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16298 		ASSERT(ill->ill_phys_addr_mp == NULL);
16299 		if (!ill->ill_ifname_pending)
16300 			break;
16301 		ill->ill_ifname_pending = 0;
16302 		if (!ioctl_aborted)
16303 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16304 		if (mp1 != NULL) {
16305 			ASSERT(connp == NULL);
16306 			q = ill->ill_wq;
16307 		}
16308 		/*
16309 		 * If any error acks received during the plumbing sequence,
16310 		 * ill_ifname_pending_err will be set. Break out and send up
16311 		 * the error to the pending ioctl.
16312 		 */
16313 		if (ill->ill_ifname_pending_err != 0) {
16314 			err = ill->ill_ifname_pending_err;
16315 			ill->ill_ifname_pending_err = 0;
16316 			break;
16317 		}
16318 
16319 		ill->ill_phys_addr_mp = mp;
16320 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16321 		mp = NULL;
16322 
16323 		/*
16324 		 * If paddrlen is zero, the DLPI provider doesn't support
16325 		 * physical addresses.  The other two tests were historical
16326 		 * workarounds for bugs in our former PPP implementation, but
16327 		 * now other things have grown dependencies on them -- e.g.,
16328 		 * the tun module specifies a dl_addr_length of zero in its
16329 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16330 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16331 		 * but only after careful testing ensures that all dependent
16332 		 * broken DLPI providers have been fixed.
16333 		 */
16334 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16335 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16336 			ill->ill_phys_addr = NULL;
16337 		} else if (paddrlen != ill->ill_phys_addr_length) {
16338 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16339 			    paddrlen, ill->ill_phys_addr_length));
16340 			err = EINVAL;
16341 			break;
16342 		}
16343 
16344 		if (ill->ill_nd_lla_mp == NULL) {
16345 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16346 				err = ENOMEM;
16347 				break;
16348 			}
16349 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16350 		}
16351 
16352 		/*
16353 		 * Set the interface token.  If the zeroth interface address
16354 		 * is unspecified, then set it to the link local address.
16355 		 */
16356 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16357 			(void) ill_setdefaulttoken(ill);
16358 
16359 		ASSERT(ill->ill_ipif->ipif_id == 0);
16360 		if (ipif != NULL &&
16361 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16362 			(void) ipif_setlinklocal(ipif);
16363 		}
16364 		break;
16365 	}
16366 	case DL_OK_ACK:
16367 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16368 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16369 		    dloa->dl_correct_primitive));
16370 		switch (dloa->dl_correct_primitive) {
16371 		case DL_UNBIND_REQ:
16372 		case DL_ATTACH_REQ:
16373 		case DL_DETACH_REQ:
16374 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16375 			break;
16376 		}
16377 		break;
16378 	default:
16379 		break;
16380 	}
16381 
16382 	freemsg(mp);
16383 	if (mp1 != NULL) {
16384 		/*
16385 		 * The operation must complete without EINPROGRESS
16386 		 * since ipsq_pending_mp_get() has removed the mblk
16387 		 * from ipsq_pending_mp.  Otherwise, the operation
16388 		 * will be stuck forever in the ipsq.
16389 		 */
16390 		ASSERT(err != EINPROGRESS);
16391 
16392 		switch (ipsq->ipsq_current_ioctl) {
16393 		case 0:
16394 			ipsq_current_finish(ipsq);
16395 			break;
16396 
16397 		case SIOCLIFADDIF:
16398 		case SIOCSLIFNAME:
16399 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16400 			break;
16401 
16402 		default:
16403 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16404 			break;
16405 		}
16406 	}
16407 }
16408 
16409 /*
16410  * ip_rput_other is called by ip_rput to handle messages modifying the global
16411  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16412  */
16413 /* ARGSUSED */
16414 void
16415 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16416 {
16417 	ill_t		*ill;
16418 	struct iocblk	*iocp;
16419 	mblk_t		*mp1;
16420 	conn_t		*connp = NULL;
16421 
16422 	ip1dbg(("ip_rput_other "));
16423 	ill = (ill_t *)q->q_ptr;
16424 	/*
16425 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16426 	 * in which case ipsq is NULL.
16427 	 */
16428 	if (ipsq != NULL) {
16429 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16430 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16431 	}
16432 
16433 	switch (mp->b_datap->db_type) {
16434 	case M_ERROR:
16435 	case M_HANGUP:
16436 		/*
16437 		 * The device has a problem.  We force the ILL down.  It can
16438 		 * be brought up again manually using SIOCSIFFLAGS (via
16439 		 * ifconfig or equivalent).
16440 		 */
16441 		ASSERT(ipsq != NULL);
16442 		if (mp->b_rptr < mp->b_wptr)
16443 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16444 		if (ill->ill_error == 0)
16445 			ill->ill_error = ENXIO;
16446 		if (!ill_down_start(q, mp))
16447 			return;
16448 		ipif_all_down_tail(ipsq, q, mp, NULL);
16449 		break;
16450 	case M_IOCACK:
16451 		iocp = (struct iocblk *)mp->b_rptr;
16452 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16453 		switch (iocp->ioc_cmd) {
16454 		case SIOCSTUNPARAM:
16455 		case OSIOCSTUNPARAM:
16456 			ASSERT(ipsq != NULL);
16457 			/*
16458 			 * Finish socket ioctl passed through to tun.
16459 			 * We should have an IOCTL waiting on this.
16460 			 */
16461 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16462 			if (ill->ill_isv6) {
16463 				struct iftun_req *ta;
16464 
16465 				/*
16466 				 * if a source or destination is
16467 				 * being set, try and set the link
16468 				 * local address for the tunnel
16469 				 */
16470 				ta = (struct iftun_req *)mp->b_cont->
16471 				    b_cont->b_rptr;
16472 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16473 					ipif_set_tun_llink(ill, ta);
16474 				}
16475 
16476 			}
16477 			if (mp1 != NULL) {
16478 				/*
16479 				 * Now copy back the b_next/b_prev used by
16480 				 * mi code for the mi_copy* functions.
16481 				 * See ip_sioctl_tunparam() for the reason.
16482 				 * Also protect against missing b_cont.
16483 				 */
16484 				if (mp->b_cont != NULL) {
16485 					mp->b_cont->b_next =
16486 					    mp1->b_cont->b_next;
16487 					mp->b_cont->b_prev =
16488 					    mp1->b_cont->b_prev;
16489 				}
16490 				inet_freemsg(mp1);
16491 				ASSERT(connp != NULL);
16492 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16493 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16494 			} else {
16495 				ASSERT(connp == NULL);
16496 				putnext(q, mp);
16497 			}
16498 			break;
16499 		case SIOCGTUNPARAM:
16500 		case OSIOCGTUNPARAM:
16501 			/*
16502 			 * This is really M_IOCDATA from the tunnel driver.
16503 			 * convert back and complete the ioctl.
16504 			 * We should have an IOCTL waiting on this.
16505 			 */
16506 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16507 			if (mp1) {
16508 				/*
16509 				 * Now copy back the b_next/b_prev used by
16510 				 * mi code for the mi_copy* functions.
16511 				 * See ip_sioctl_tunparam() for the reason.
16512 				 * Also protect against missing b_cont.
16513 				 */
16514 				if (mp->b_cont != NULL) {
16515 					mp->b_cont->b_next =
16516 					    mp1->b_cont->b_next;
16517 					mp->b_cont->b_prev =
16518 					    mp1->b_cont->b_prev;
16519 				}
16520 				inet_freemsg(mp1);
16521 				if (iocp->ioc_error == 0)
16522 					mp->b_datap->db_type = M_IOCDATA;
16523 				ASSERT(connp != NULL);
16524 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16525 				    iocp->ioc_error, COPYOUT, NULL);
16526 			} else {
16527 				ASSERT(connp == NULL);
16528 				putnext(q, mp);
16529 			}
16530 			break;
16531 		default:
16532 			break;
16533 		}
16534 		break;
16535 	case M_IOCNAK:
16536 		iocp = (struct iocblk *)mp->b_rptr;
16537 
16538 		switch (iocp->ioc_cmd) {
16539 		int mode;
16540 
16541 		case DL_IOC_HDR_INFO:
16542 			/*
16543 			 * If this was the first attempt turn of the
16544 			 * fastpath probing.
16545 			 */
16546 			mutex_enter(&ill->ill_lock);
16547 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16548 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16549 				mutex_exit(&ill->ill_lock);
16550 				ill_fastpath_nack(ill);
16551 				ip1dbg(("ip_rput: DLPI fastpath off on "
16552 				    "interface %s\n",
16553 				    ill->ill_name));
16554 			} else {
16555 				mutex_exit(&ill->ill_lock);
16556 			}
16557 			freemsg(mp);
16558 			break;
16559 		case SIOCSTUNPARAM:
16560 		case OSIOCSTUNPARAM:
16561 			ASSERT(ipsq != NULL);
16562 			/*
16563 			 * Finish socket ioctl passed through to tun
16564 			 * We should have an IOCTL waiting on this.
16565 			 */
16566 			/* FALLTHRU */
16567 		case SIOCGTUNPARAM:
16568 		case OSIOCGTUNPARAM:
16569 			/*
16570 			 * This is really M_IOCDATA from the tunnel driver.
16571 			 * convert back and complete the ioctl.
16572 			 * We should have an IOCTL waiting on this.
16573 			 */
16574 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16575 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16576 				mp1 = ill_pending_mp_get(ill, &connp,
16577 				    iocp->ioc_id);
16578 				mode = COPYOUT;
16579 				ipsq = NULL;
16580 			} else {
16581 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16582 				mode = NO_COPYOUT;
16583 			}
16584 			if (mp1 != NULL) {
16585 				/*
16586 				 * Now copy back the b_next/b_prev used by
16587 				 * mi code for the mi_copy* functions.
16588 				 * See ip_sioctl_tunparam() for the reason.
16589 				 * Also protect against missing b_cont.
16590 				 */
16591 				if (mp->b_cont != NULL) {
16592 					mp->b_cont->b_next =
16593 					    mp1->b_cont->b_next;
16594 					mp->b_cont->b_prev =
16595 					    mp1->b_cont->b_prev;
16596 				}
16597 				inet_freemsg(mp1);
16598 				if (iocp->ioc_error == 0)
16599 					iocp->ioc_error = EINVAL;
16600 				ASSERT(connp != NULL);
16601 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16602 				    iocp->ioc_error, mode, ipsq);
16603 			} else {
16604 				ASSERT(connp == NULL);
16605 				putnext(q, mp);
16606 			}
16607 			break;
16608 		default:
16609 			break;
16610 		}
16611 	default:
16612 		break;
16613 	}
16614 }
16615 
16616 /*
16617  * NOTE : This function does not ire_refrele the ire argument passed in.
16618  *
16619  * IPQoS notes
16620  * IP policy is invoked twice for a forwarded packet, once on the read side
16621  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16622  * enabled. An additional parameter, in_ill, has been added for this purpose.
16623  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16624  * because ip_mroute drops this information.
16625  *
16626  */
16627 void
16628 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16629 {
16630 	uint32_t	pkt_len;
16631 	queue_t	*q;
16632 	uint32_t	sum;
16633 #define	rptr	((uchar_t *)ipha)
16634 	uint32_t	max_frag;
16635 	uint32_t	ill_index;
16636 	ill_t		*out_ill;
16637 	mib2_ipIfStatsEntry_t *mibptr;
16638 	ip_stack_t	*ipst = in_ill->ill_ipst;
16639 
16640 	/* Get the ill_index of the incoming ILL */
16641 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16642 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16643 
16644 	/* Initiate Read side IPPF processing */
16645 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16646 		ip_process(IPP_FWD_IN, &mp, ill_index);
16647 		if (mp == NULL) {
16648 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16649 			    "during IPPF processing\n"));
16650 			return;
16651 		}
16652 	}
16653 
16654 	pkt_len = ntohs(ipha->ipha_length);
16655 
16656 	/* Adjust the checksum to reflect the ttl decrement. */
16657 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16658 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16659 
16660 	if (ipha->ipha_ttl-- <= 1) {
16661 		if (ip_csum_hdr(ipha)) {
16662 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16663 			goto drop_pkt;
16664 		}
16665 		/*
16666 		 * Note: ire_stq this will be NULL for multicast
16667 		 * datagrams using the long path through arp (the IRE
16668 		 * is not an IRE_CACHE). This should not cause
16669 		 * problems since we don't generate ICMP errors for
16670 		 * multicast packets.
16671 		 */
16672 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16673 		q = ire->ire_stq;
16674 		if (q != NULL) {
16675 			/* Sent by forwarding path, and router is global zone */
16676 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16677 			    GLOBAL_ZONEID, ipst);
16678 		} else
16679 			freemsg(mp);
16680 		return;
16681 	}
16682 
16683 	/*
16684 	 * Don't forward if the interface is down
16685 	 */
16686 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16687 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16688 		ip2dbg(("ip_rput_forward:interface is down\n"));
16689 		goto drop_pkt;
16690 	}
16691 
16692 	/* Get the ill_index of the outgoing ILL */
16693 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16694 
16695 	out_ill = ire->ire_ipif->ipif_ill;
16696 
16697 	DTRACE_PROBE4(ip4__forwarding__start,
16698 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16699 
16700 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16701 	    ipst->ips_ipv4firewall_forwarding,
16702 	    in_ill, out_ill, ipha, mp, mp, ipst);
16703 
16704 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16705 
16706 	if (mp == NULL)
16707 		return;
16708 	pkt_len = ntohs(ipha->ipha_length);
16709 
16710 	if (is_system_labeled()) {
16711 		mblk_t *mp1;
16712 
16713 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16714 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16715 			goto drop_pkt;
16716 		}
16717 		/* Size may have changed */
16718 		mp = mp1;
16719 		ipha = (ipha_t *)mp->b_rptr;
16720 		pkt_len = ntohs(ipha->ipha_length);
16721 	}
16722 
16723 	/* Check if there are options to update */
16724 	if (!IS_SIMPLE_IPH(ipha)) {
16725 		if (ip_csum_hdr(ipha)) {
16726 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16727 			goto drop_pkt;
16728 		}
16729 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16730 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16731 			return;
16732 		}
16733 
16734 		ipha->ipha_hdr_checksum = 0;
16735 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16736 	}
16737 	max_frag = ire->ire_max_frag;
16738 	if (pkt_len > max_frag) {
16739 		/*
16740 		 * It needs fragging on its way out.  We haven't
16741 		 * verified the header checksum yet.  Since we
16742 		 * are going to put a surely good checksum in the
16743 		 * outgoing header, we have to make sure that it
16744 		 * was good coming in.
16745 		 */
16746 		if (ip_csum_hdr(ipha)) {
16747 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16748 			goto drop_pkt;
16749 		}
16750 		/* Initiate Write side IPPF processing */
16751 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16752 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16753 			if (mp == NULL) {
16754 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16755 				    " during IPPF processing\n"));
16756 				return;
16757 			}
16758 		}
16759 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16760 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16761 		return;
16762 	}
16763 
16764 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16765 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16766 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16767 	    ipst->ips_ipv4firewall_physical_out,
16768 	    NULL, out_ill, ipha, mp, mp, ipst);
16769 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16770 	if (mp == NULL)
16771 		return;
16772 
16773 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16774 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16775 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16776 	/* ip_xmit_v4 always consumes the packet */
16777 	return;
16778 
16779 drop_pkt:;
16780 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16781 	freemsg(mp);
16782 #undef	rptr
16783 }
16784 
16785 void
16786 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16787 {
16788 	ire_t	*ire;
16789 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16790 
16791 	ASSERT(!ipif->ipif_isv6);
16792 	/*
16793 	 * Find an IRE which matches the destination and the outgoing
16794 	 * queue in the cache table. All we need is an IRE_CACHE which
16795 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16796 	 * then it is enough to have some IRE_CACHE in the group.
16797 	 */
16798 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16799 		dst = ipif->ipif_pp_dst_addr;
16800 
16801 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16802 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16803 	if (ire == NULL) {
16804 		/*
16805 		 * Mark this packet to make it be delivered to
16806 		 * ip_rput_forward after the new ire has been
16807 		 * created.
16808 		 */
16809 		mp->b_prev = NULL;
16810 		mp->b_next = mp;
16811 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16812 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16813 	} else {
16814 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16815 		IRE_REFRELE(ire);
16816 	}
16817 }
16818 
16819 /* Update any source route, record route or timestamp options */
16820 static int
16821 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16822 {
16823 	ipoptp_t	opts;
16824 	uchar_t		*opt;
16825 	uint8_t		optval;
16826 	uint8_t		optlen;
16827 	ipaddr_t	dst;
16828 	uint32_t	ts;
16829 	ire_t		*dst_ire = NULL;
16830 	ire_t		*tmp_ire = NULL;
16831 	timestruc_t	now;
16832 
16833 	ip2dbg(("ip_rput_forward_options\n"));
16834 	dst = ipha->ipha_dst;
16835 	for (optval = ipoptp_first(&opts, ipha);
16836 	    optval != IPOPT_EOL;
16837 	    optval = ipoptp_next(&opts)) {
16838 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16839 		opt = opts.ipoptp_cur;
16840 		optlen = opts.ipoptp_len;
16841 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16842 		    optval, opts.ipoptp_len));
16843 		switch (optval) {
16844 			uint32_t off;
16845 		case IPOPT_SSRR:
16846 		case IPOPT_LSRR:
16847 			/* Check if adminstratively disabled */
16848 			if (!ipst->ips_ip_forward_src_routed) {
16849 				if (ire->ire_stq != NULL) {
16850 					/*
16851 					 * Sent by forwarding path, and router
16852 					 * is global zone
16853 					 */
16854 					icmp_unreachable(ire->ire_stq, mp,
16855 					    ICMP_SOURCE_ROUTE_FAILED,
16856 					    GLOBAL_ZONEID, ipst);
16857 				} else {
16858 					ip0dbg(("ip_rput_forward_options: "
16859 					    "unable to send unreach\n"));
16860 					freemsg(mp);
16861 				}
16862 				return (-1);
16863 			}
16864 
16865 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16866 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16867 			if (dst_ire == NULL) {
16868 				/*
16869 				 * Must be partial since ip_rput_options
16870 				 * checked for strict.
16871 				 */
16872 				break;
16873 			}
16874 			off = opt[IPOPT_OFFSET];
16875 			off--;
16876 		redo_srr:
16877 			if (optlen < IP_ADDR_LEN ||
16878 			    off > optlen - IP_ADDR_LEN) {
16879 				/* End of source route */
16880 				ip1dbg((
16881 				    "ip_rput_forward_options: end of SR\n"));
16882 				ire_refrele(dst_ire);
16883 				break;
16884 			}
16885 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16886 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16887 			    IP_ADDR_LEN);
16888 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16889 			    ntohl(dst)));
16890 
16891 			/*
16892 			 * Check if our address is present more than
16893 			 * once as consecutive hops in source route.
16894 			 */
16895 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16896 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16897 			if (tmp_ire != NULL) {
16898 				ire_refrele(tmp_ire);
16899 				off += IP_ADDR_LEN;
16900 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16901 				goto redo_srr;
16902 			}
16903 			ipha->ipha_dst = dst;
16904 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16905 			ire_refrele(dst_ire);
16906 			break;
16907 		case IPOPT_RR:
16908 			off = opt[IPOPT_OFFSET];
16909 			off--;
16910 			if (optlen < IP_ADDR_LEN ||
16911 			    off > optlen - IP_ADDR_LEN) {
16912 				/* No more room - ignore */
16913 				ip1dbg((
16914 				    "ip_rput_forward_options: end of RR\n"));
16915 				break;
16916 			}
16917 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16918 			    IP_ADDR_LEN);
16919 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16920 			break;
16921 		case IPOPT_TS:
16922 			/* Insert timestamp if there is room */
16923 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16924 			case IPOPT_TS_TSONLY:
16925 				off = IPOPT_TS_TIMELEN;
16926 				break;
16927 			case IPOPT_TS_PRESPEC:
16928 			case IPOPT_TS_PRESPEC_RFC791:
16929 				/* Verify that the address matched */
16930 				off = opt[IPOPT_OFFSET] - 1;
16931 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16932 				dst_ire = ire_ctable_lookup(dst, 0,
16933 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16934 				    MATCH_IRE_TYPE, ipst);
16935 				if (dst_ire == NULL) {
16936 					/* Not for us */
16937 					break;
16938 				}
16939 				ire_refrele(dst_ire);
16940 				/* FALLTHRU */
16941 			case IPOPT_TS_TSANDADDR:
16942 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16943 				break;
16944 			default:
16945 				/*
16946 				 * ip_*put_options should have already
16947 				 * dropped this packet.
16948 				 */
16949 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16950 				    "unknown IT - bug in ip_rput_options?\n");
16951 				return (0);	/* Keep "lint" happy */
16952 			}
16953 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16954 				/* Increase overflow counter */
16955 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16956 				opt[IPOPT_POS_OV_FLG] =
16957 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16958 				    (off << 4));
16959 				break;
16960 			}
16961 			off = opt[IPOPT_OFFSET] - 1;
16962 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16963 			case IPOPT_TS_PRESPEC:
16964 			case IPOPT_TS_PRESPEC_RFC791:
16965 			case IPOPT_TS_TSANDADDR:
16966 				bcopy(&ire->ire_src_addr,
16967 				    (char *)opt + off, IP_ADDR_LEN);
16968 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16969 				/* FALLTHRU */
16970 			case IPOPT_TS_TSONLY:
16971 				off = opt[IPOPT_OFFSET] - 1;
16972 				/* Compute # of milliseconds since midnight */
16973 				gethrestime(&now);
16974 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16975 				    now.tv_nsec / (NANOSEC / MILLISEC);
16976 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16977 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16978 				break;
16979 			}
16980 			break;
16981 		}
16982 	}
16983 	return (0);
16984 }
16985 
16986 /*
16987  * This is called after processing at least one of AH/ESP headers.
16988  *
16989  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16990  * the actual, physical interface on which the packet was received,
16991  * but, when ip_strict_dst_multihoming is set to 1, could be the
16992  * interface which had the ipha_dst configured when the packet went
16993  * through ip_rput. The ill_index corresponding to the recv_ill
16994  * is saved in ipsec_in_rill_index
16995  *
16996  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16997  * cannot assume "ire" points to valid data for any IPv6 cases.
16998  */
16999 void
17000 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17001 {
17002 	mblk_t *mp;
17003 	ipaddr_t dst;
17004 	in6_addr_t *v6dstp;
17005 	ipha_t *ipha;
17006 	ip6_t *ip6h;
17007 	ipsec_in_t *ii;
17008 	boolean_t ill_need_rele = B_FALSE;
17009 	boolean_t rill_need_rele = B_FALSE;
17010 	boolean_t ire_need_rele = B_FALSE;
17011 	netstack_t	*ns;
17012 	ip_stack_t	*ipst;
17013 
17014 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17015 	ASSERT(ii->ipsec_in_ill_index != 0);
17016 	ns = ii->ipsec_in_ns;
17017 	ASSERT(ii->ipsec_in_ns != NULL);
17018 	ipst = ns->netstack_ip;
17019 
17020 	mp = ipsec_mp->b_cont;
17021 	ASSERT(mp != NULL);
17022 
17023 
17024 	if (ill == NULL) {
17025 		ASSERT(recv_ill == NULL);
17026 		/*
17027 		 * We need to get the original queue on which ip_rput_local
17028 		 * or ip_rput_data_v6 was called.
17029 		 */
17030 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17031 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17032 		ill_need_rele = B_TRUE;
17033 
17034 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17035 			recv_ill = ill_lookup_on_ifindex(
17036 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17037 			    NULL, NULL, NULL, NULL, ipst);
17038 			rill_need_rele = B_TRUE;
17039 		} else {
17040 			recv_ill = ill;
17041 		}
17042 
17043 		if ((ill == NULL) || (recv_ill == NULL)) {
17044 			ip0dbg(("ip_fanout_proto_again: interface "
17045 			    "disappeared\n"));
17046 			if (ill != NULL)
17047 				ill_refrele(ill);
17048 			if (recv_ill != NULL)
17049 				ill_refrele(recv_ill);
17050 			freemsg(ipsec_mp);
17051 			return;
17052 		}
17053 	}
17054 
17055 	ASSERT(ill != NULL && recv_ill != NULL);
17056 
17057 	if (mp->b_datap->db_type == M_CTL) {
17058 		/*
17059 		 * AH/ESP is returning the ICMP message after
17060 		 * removing their headers. Fanout again till
17061 		 * it gets to the right protocol.
17062 		 */
17063 		if (ii->ipsec_in_v4) {
17064 			icmph_t *icmph;
17065 			int iph_hdr_length;
17066 			int hdr_length;
17067 
17068 			ipha = (ipha_t *)mp->b_rptr;
17069 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17070 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17071 			ipha = (ipha_t *)&icmph[1];
17072 			hdr_length = IPH_HDR_LENGTH(ipha);
17073 			/*
17074 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17075 			 * Reset the type to M_DATA.
17076 			 */
17077 			mp->b_datap->db_type = M_DATA;
17078 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17079 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17080 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17081 		} else {
17082 			icmp6_t *icmp6;
17083 			int hdr_length;
17084 
17085 			ip6h = (ip6_t *)mp->b_rptr;
17086 			/* Don't call hdr_length_v6() unless you have to. */
17087 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17088 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17089 			else
17090 				hdr_length = IPV6_HDR_LEN;
17091 
17092 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17093 			/*
17094 			 * icmp_inbound_error_fanout_v6 may need to do
17095 			 * pullupmsg.  Reset the type to M_DATA.
17096 			 */
17097 			mp->b_datap->db_type = M_DATA;
17098 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17099 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17100 		}
17101 		if (ill_need_rele)
17102 			ill_refrele(ill);
17103 		if (rill_need_rele)
17104 			ill_refrele(recv_ill);
17105 		return;
17106 	}
17107 
17108 	if (ii->ipsec_in_v4) {
17109 		ipha = (ipha_t *)mp->b_rptr;
17110 		dst = ipha->ipha_dst;
17111 		if (CLASSD(dst)) {
17112 			/*
17113 			 * Multicast has to be delivered to all streams.
17114 			 */
17115 			dst = INADDR_BROADCAST;
17116 		}
17117 
17118 		if (ire == NULL) {
17119 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17120 			    MBLK_GETLABEL(mp), ipst);
17121 			if (ire == NULL) {
17122 				if (ill_need_rele)
17123 					ill_refrele(ill);
17124 				if (rill_need_rele)
17125 					ill_refrele(recv_ill);
17126 				ip1dbg(("ip_fanout_proto_again: "
17127 				    "IRE not found"));
17128 				freemsg(ipsec_mp);
17129 				return;
17130 			}
17131 			ire_need_rele = B_TRUE;
17132 		}
17133 
17134 		switch (ipha->ipha_protocol) {
17135 			case IPPROTO_UDP:
17136 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17137 				    recv_ill);
17138 				if (ire_need_rele)
17139 					ire_refrele(ire);
17140 				break;
17141 			case IPPROTO_TCP:
17142 				if (!ire_need_rele)
17143 					IRE_REFHOLD(ire);
17144 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17145 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17146 				IRE_REFRELE(ire);
17147 				if (mp != NULL)
17148 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17149 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17150 				break;
17151 			case IPPROTO_SCTP:
17152 				if (!ire_need_rele)
17153 					IRE_REFHOLD(ire);
17154 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17155 				    ipsec_mp, 0, ill->ill_rq, dst);
17156 				break;
17157 			default:
17158 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17159 				    recv_ill);
17160 				if (ire_need_rele)
17161 					ire_refrele(ire);
17162 				break;
17163 		}
17164 	} else {
17165 		uint32_t rput_flags = 0;
17166 
17167 		ip6h = (ip6_t *)mp->b_rptr;
17168 		v6dstp = &ip6h->ip6_dst;
17169 		/*
17170 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17171 		 * address.
17172 		 *
17173 		 * Currently, we don't store that state in the IPSEC_IN
17174 		 * message, and we may need to.
17175 		 */
17176 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17177 		    IP6_IN_LLMCAST : 0);
17178 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17179 		    NULL, NULL);
17180 	}
17181 	if (ill_need_rele)
17182 		ill_refrele(ill);
17183 	if (rill_need_rele)
17184 		ill_refrele(recv_ill);
17185 }
17186 
17187 /*
17188  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17189  * returns 'true' if there are still fragments left on the queue, in
17190  * which case we restart the timer.
17191  */
17192 void
17193 ill_frag_timer(void *arg)
17194 {
17195 	ill_t	*ill = (ill_t *)arg;
17196 	boolean_t frag_pending;
17197 	ip_stack_t	*ipst = ill->ill_ipst;
17198 
17199 	mutex_enter(&ill->ill_lock);
17200 	ASSERT(!ill->ill_fragtimer_executing);
17201 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17202 		ill->ill_frag_timer_id = 0;
17203 		mutex_exit(&ill->ill_lock);
17204 		return;
17205 	}
17206 	ill->ill_fragtimer_executing = 1;
17207 	mutex_exit(&ill->ill_lock);
17208 
17209 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17210 
17211 	/*
17212 	 * Restart the timer, if we have fragments pending or if someone
17213 	 * wanted us to be scheduled again.
17214 	 */
17215 	mutex_enter(&ill->ill_lock);
17216 	ill->ill_fragtimer_executing = 0;
17217 	ill->ill_frag_timer_id = 0;
17218 	if (frag_pending || ill->ill_fragtimer_needrestart)
17219 		ill_frag_timer_start(ill);
17220 	mutex_exit(&ill->ill_lock);
17221 }
17222 
17223 void
17224 ill_frag_timer_start(ill_t *ill)
17225 {
17226 	ip_stack_t	*ipst = ill->ill_ipst;
17227 
17228 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17229 
17230 	/* If the ill is closing or opening don't proceed */
17231 	if (ill->ill_state_flags & ILL_CONDEMNED)
17232 		return;
17233 
17234 	if (ill->ill_fragtimer_executing) {
17235 		/*
17236 		 * ill_frag_timer is currently executing. Just record the
17237 		 * the fact that we want the timer to be restarted.
17238 		 * ill_frag_timer will post a timeout before it returns,
17239 		 * ensuring it will be called again.
17240 		 */
17241 		ill->ill_fragtimer_needrestart = 1;
17242 		return;
17243 	}
17244 
17245 	if (ill->ill_frag_timer_id == 0) {
17246 		/*
17247 		 * The timer is neither running nor is the timeout handler
17248 		 * executing. Post a timeout so that ill_frag_timer will be
17249 		 * called
17250 		 */
17251 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17252 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17253 		ill->ill_fragtimer_needrestart = 0;
17254 	}
17255 }
17256 
17257 /*
17258  * This routine is needed for loopback when forwarding multicasts.
17259  *
17260  * IPQoS Notes:
17261  * IPPF processing is done in fanout routines.
17262  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17263  * processing for IPSec packets is done when it comes back in clear.
17264  * NOTE : The callers of this function need to do the ire_refrele for the
17265  *	  ire that is being passed in.
17266  */
17267 void
17268 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17269     ill_t *recv_ill)
17270 {
17271 	ill_t	*ill = (ill_t *)q->q_ptr;
17272 	uint32_t	sum;
17273 	uint32_t	u1;
17274 	uint32_t	u2;
17275 	int		hdr_length;
17276 	boolean_t	mctl_present;
17277 	mblk_t		*first_mp = mp;
17278 	mblk_t		*hada_mp = NULL;
17279 	ipha_t		*inner_ipha;
17280 	ip_stack_t	*ipst;
17281 
17282 	ASSERT(recv_ill != NULL);
17283 	ipst = recv_ill->ill_ipst;
17284 
17285 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17286 	    "ip_rput_locl_start: q %p", q);
17287 
17288 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17289 	ASSERT(ill != NULL);
17290 
17291 
17292 #define	rptr	((uchar_t *)ipha)
17293 #define	iphs	((uint16_t *)ipha)
17294 
17295 	/*
17296 	 * no UDP or TCP packet should come here anymore.
17297 	 */
17298 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17299 	    (ipha->ipha_protocol != IPPROTO_UDP));
17300 
17301 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17302 	if (mctl_present &&
17303 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17304 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17305 
17306 		/*
17307 		 * It's an IPsec accelerated packet.
17308 		 * Keep a pointer to the data attributes around until
17309 		 * we allocate the ipsec_info_t.
17310 		 */
17311 		IPSECHW_DEBUG(IPSECHW_PKT,
17312 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17313 		hada_mp = first_mp;
17314 		hada_mp->b_cont = NULL;
17315 		/*
17316 		 * Since it is accelerated, it comes directly from
17317 		 * the ill and the data attributes is followed by
17318 		 * the packet data.
17319 		 */
17320 		ASSERT(mp->b_datap->db_type != M_CTL);
17321 		first_mp = mp;
17322 		mctl_present = B_FALSE;
17323 	}
17324 
17325 	/*
17326 	 * IF M_CTL is not present, then ipsec_in_is_secure
17327 	 * should return B_TRUE. There is a case where loopback
17328 	 * packets has an M_CTL in the front with all the
17329 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17330 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17331 	 * packets never comes here, it is safe to ASSERT the
17332 	 * following.
17333 	 */
17334 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17335 
17336 
17337 	/* u1 is # words of IP options */
17338 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17339 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17340 
17341 	if (u1) {
17342 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17343 			if (hada_mp != NULL)
17344 				freemsg(hada_mp);
17345 			return;
17346 		}
17347 	} else {
17348 		/* Check the IP header checksum.  */
17349 #define	uph	((uint16_t *)ipha)
17350 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17351 		    uph[6] + uph[7] + uph[8] + uph[9];
17352 #undef  uph
17353 		/* finish doing IP checksum */
17354 		sum = (sum & 0xFFFF) + (sum >> 16);
17355 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17356 		/*
17357 		 * Don't verify header checksum if this packet is coming
17358 		 * back from AH/ESP as we already did it.
17359 		 */
17360 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17361 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17362 			goto drop_pkt;
17363 		}
17364 	}
17365 
17366 	/*
17367 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17368 	 * might be called more than once for secure packets, count only
17369 	 * the first time.
17370 	 */
17371 	if (!mctl_present) {
17372 		UPDATE_IB_PKT_COUNT(ire);
17373 		ire->ire_last_used_time = lbolt;
17374 	}
17375 
17376 	/* Check for fragmentation offset. */
17377 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17378 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17379 	if (u1) {
17380 		/*
17381 		 * We re-assemble fragments before we do the AH/ESP
17382 		 * processing. Thus, M_CTL should not be present
17383 		 * while we are re-assembling.
17384 		 */
17385 		ASSERT(!mctl_present);
17386 		ASSERT(first_mp == mp);
17387 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17388 			return;
17389 		}
17390 		/*
17391 		 * Make sure that first_mp points back to mp as
17392 		 * the mp we came in with could have changed in
17393 		 * ip_rput_fragment().
17394 		 */
17395 		ipha = (ipha_t *)mp->b_rptr;
17396 		first_mp = mp;
17397 	}
17398 
17399 	/*
17400 	 * Clear hardware checksumming flag as it is currently only
17401 	 * used by TCP and UDP.
17402 	 */
17403 	DB_CKSUMFLAGS(mp) = 0;
17404 
17405 	/* Now we have a complete datagram, destined for this machine. */
17406 	u1 = IPH_HDR_LENGTH(ipha);
17407 	switch (ipha->ipha_protocol) {
17408 	case IPPROTO_ICMP: {
17409 		ire_t		*ire_zone;
17410 		ilm_t		*ilm;
17411 		mblk_t		*mp1;
17412 		zoneid_t	last_zoneid;
17413 
17414 		if (CLASSD(ipha->ipha_dst) &&
17415 		    !(recv_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
17416 			ASSERT(ire->ire_type == IRE_BROADCAST);
17417 			/*
17418 			 * In the multicast case, applications may have joined
17419 			 * the group from different zones, so we need to deliver
17420 			 * the packet to each of them. Loop through the
17421 			 * multicast memberships structures (ilm) on the receive
17422 			 * ill and send a copy of the packet up each matching
17423 			 * one. However, we don't do this for multicasts sent on
17424 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17425 			 * they must stay in the sender's zone.
17426 			 *
17427 			 * ilm_add_v6() ensures that ilms in the same zone are
17428 			 * contiguous in the ill_ilm list. We use this property
17429 			 * to avoid sending duplicates needed when two
17430 			 * applications in the same zone join the same group on
17431 			 * different logical interfaces: we ignore the ilm if
17432 			 * its zoneid is the same as the last matching one.
17433 			 * In addition, the sending of the packet for
17434 			 * ire_zoneid is delayed until all of the other ilms
17435 			 * have been exhausted.
17436 			 */
17437 			last_zoneid = -1;
17438 			ILM_WALKER_HOLD(recv_ill);
17439 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17440 			    ilm = ilm->ilm_next) {
17441 				if ((ilm->ilm_flags & ILM_DELETED) ||
17442 				    ipha->ipha_dst != ilm->ilm_addr ||
17443 				    ilm->ilm_zoneid == last_zoneid ||
17444 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17445 				    ilm->ilm_zoneid == ALL_ZONES ||
17446 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17447 					continue;
17448 				mp1 = ip_copymsg(first_mp);
17449 				if (mp1 == NULL)
17450 					continue;
17451 				icmp_inbound(q, mp1, B_TRUE, ill,
17452 				    0, sum, mctl_present, B_TRUE,
17453 				    recv_ill, ilm->ilm_zoneid);
17454 				last_zoneid = ilm->ilm_zoneid;
17455 			}
17456 			ILM_WALKER_RELE(recv_ill);
17457 		} else if (ire->ire_type == IRE_BROADCAST) {
17458 			/*
17459 			 * In the broadcast case, there may be many zones
17460 			 * which need a copy of the packet delivered to them.
17461 			 * There is one IRE_BROADCAST per broadcast address
17462 			 * and per zone; we walk those using a helper function.
17463 			 * In addition, the sending of the packet for ire is
17464 			 * delayed until all of the other ires have been
17465 			 * processed.
17466 			 */
17467 			IRB_REFHOLD(ire->ire_bucket);
17468 			ire_zone = NULL;
17469 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17470 			    ire)) != NULL) {
17471 				mp1 = ip_copymsg(first_mp);
17472 				if (mp1 == NULL)
17473 					continue;
17474 
17475 				UPDATE_IB_PKT_COUNT(ire_zone);
17476 				ire_zone->ire_last_used_time = lbolt;
17477 				icmp_inbound(q, mp1, B_TRUE, ill,
17478 				    0, sum, mctl_present, B_TRUE,
17479 				    recv_ill, ire_zone->ire_zoneid);
17480 			}
17481 			IRB_REFRELE(ire->ire_bucket);
17482 		}
17483 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17484 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17485 		    ire->ire_zoneid);
17486 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17487 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17488 		return;
17489 	}
17490 	case IPPROTO_IGMP:
17491 		/*
17492 		 * If we are not willing to accept IGMP packets in clear,
17493 		 * then check with global policy.
17494 		 */
17495 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17496 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17497 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17498 			if (first_mp == NULL)
17499 				return;
17500 		}
17501 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17502 			freemsg(first_mp);
17503 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17504 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17505 			return;
17506 		}
17507 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17508 			/* Bad packet - discarded by igmp_input */
17509 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17510 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17511 			if (mctl_present)
17512 				freeb(first_mp);
17513 			return;
17514 		}
17515 		/*
17516 		 * igmp_input() may have returned the pulled up message.
17517 		 * So first_mp and ipha need to be reinitialized.
17518 		 */
17519 		ipha = (ipha_t *)mp->b_rptr;
17520 		if (mctl_present)
17521 			first_mp->b_cont = mp;
17522 		else
17523 			first_mp = mp;
17524 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17525 		    connf_head != NULL) {
17526 			/* No user-level listener for IGMP packets */
17527 			goto drop_pkt;
17528 		}
17529 		/* deliver to local raw users */
17530 		break;
17531 	case IPPROTO_PIM:
17532 		/*
17533 		 * If we are not willing to accept PIM packets in clear,
17534 		 * then check with global policy.
17535 		 */
17536 		if (ipst->ips_pim_accept_clear_messages == 0) {
17537 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17538 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17539 			if (first_mp == NULL)
17540 				return;
17541 		}
17542 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17543 			freemsg(first_mp);
17544 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17545 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17546 			return;
17547 		}
17548 		if (pim_input(q, mp, ill) != 0) {
17549 			/* Bad packet - discarded by pim_input */
17550 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17551 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17552 			if (mctl_present)
17553 				freeb(first_mp);
17554 			return;
17555 		}
17556 
17557 		/*
17558 		 * pim_input() may have pulled up the message so ipha needs to
17559 		 * be reinitialized.
17560 		 */
17561 		ipha = (ipha_t *)mp->b_rptr;
17562 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17563 		    connf_head != NULL) {
17564 			/* No user-level listener for PIM packets */
17565 			goto drop_pkt;
17566 		}
17567 		/* deliver to local raw users */
17568 		break;
17569 	case IPPROTO_ENCAP:
17570 		/*
17571 		 * Handle self-encapsulated packets (IP-in-IP where
17572 		 * the inner addresses == the outer addresses).
17573 		 */
17574 		hdr_length = IPH_HDR_LENGTH(ipha);
17575 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17576 		    mp->b_wptr) {
17577 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17578 			    sizeof (ipha_t) - mp->b_rptr)) {
17579 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17580 				freemsg(first_mp);
17581 				return;
17582 			}
17583 			ipha = (ipha_t *)mp->b_rptr;
17584 		}
17585 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17586 		/*
17587 		 * Check the sanity of the inner IP header.
17588 		 */
17589 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17591 			freemsg(first_mp);
17592 			return;
17593 		}
17594 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17595 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17596 			freemsg(first_mp);
17597 			return;
17598 		}
17599 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17600 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17601 			ipsec_in_t *ii;
17602 
17603 			/*
17604 			 * Self-encapsulated tunnel packet. Remove
17605 			 * the outer IP header and fanout again.
17606 			 * We also need to make sure that the inner
17607 			 * header is pulled up until options.
17608 			 */
17609 			mp->b_rptr = (uchar_t *)inner_ipha;
17610 			ipha = inner_ipha;
17611 			hdr_length = IPH_HDR_LENGTH(ipha);
17612 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17613 				if (!pullupmsg(mp, (uchar_t *)ipha +
17614 				    + hdr_length - mp->b_rptr)) {
17615 					freemsg(first_mp);
17616 					return;
17617 				}
17618 				ipha = (ipha_t *)mp->b_rptr;
17619 			}
17620 			if (!mctl_present) {
17621 				ASSERT(first_mp == mp);
17622 				/*
17623 				 * This means that somebody is sending
17624 				 * Self-encapsualted packets without AH/ESP.
17625 				 * If AH/ESP was present, we would have already
17626 				 * allocated the first_mp.
17627 				 */
17628 				first_mp = ipsec_in_alloc(B_TRUE,
17629 				    ipst->ips_netstack);
17630 				if (first_mp == NULL) {
17631 					ip1dbg(("ip_proto_input: IPSEC_IN "
17632 					    "allocation failure.\n"));
17633 					BUMP_MIB(ill->ill_ip_mib,
17634 					    ipIfStatsInDiscards);
17635 					freemsg(mp);
17636 					return;
17637 				}
17638 				first_mp->b_cont = mp;
17639 			}
17640 			/*
17641 			 * We generally store the ill_index if we need to
17642 			 * do IPSEC processing as we lose the ill queue when
17643 			 * we come back. But in this case, we never should
17644 			 * have to store the ill_index here as it should have
17645 			 * been stored previously when we processed the
17646 			 * AH/ESP header in this routine or for non-ipsec
17647 			 * cases, we still have the queue. But for some bad
17648 			 * packets from the wire, we can get to IPSEC after
17649 			 * this and we better store the index for that case.
17650 			 */
17651 			ill = (ill_t *)q->q_ptr;
17652 			ii = (ipsec_in_t *)first_mp->b_rptr;
17653 			ii->ipsec_in_ill_index =
17654 			    ill->ill_phyint->phyint_ifindex;
17655 			ii->ipsec_in_rill_index =
17656 			    recv_ill->ill_phyint->phyint_ifindex;
17657 			if (ii->ipsec_in_decaps) {
17658 				/*
17659 				 * This packet is self-encapsulated multiple
17660 				 * times. We don't want to recurse infinitely.
17661 				 * To keep it simple, drop the packet.
17662 				 */
17663 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17664 				freemsg(first_mp);
17665 				return;
17666 			}
17667 			ii->ipsec_in_decaps = B_TRUE;
17668 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17669 			    ire);
17670 			return;
17671 		}
17672 		break;
17673 	case IPPROTO_AH:
17674 	case IPPROTO_ESP: {
17675 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17676 
17677 		/*
17678 		 * Fast path for AH/ESP. If this is the first time
17679 		 * we are sending a datagram to AH/ESP, allocate
17680 		 * a IPSEC_IN message and prepend it. Otherwise,
17681 		 * just fanout.
17682 		 */
17683 
17684 		int ipsec_rc;
17685 		ipsec_in_t *ii;
17686 		netstack_t *ns = ipst->ips_netstack;
17687 
17688 		IP_STAT(ipst, ipsec_proto_ahesp);
17689 		if (!mctl_present) {
17690 			ASSERT(first_mp == mp);
17691 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17692 			if (first_mp == NULL) {
17693 				ip1dbg(("ip_proto_input: IPSEC_IN "
17694 				    "allocation failure.\n"));
17695 				freemsg(hada_mp); /* okay ifnull */
17696 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17697 				freemsg(mp);
17698 				return;
17699 			}
17700 			/*
17701 			 * Store the ill_index so that when we come back
17702 			 * from IPSEC we ride on the same queue.
17703 			 */
17704 			ill = (ill_t *)q->q_ptr;
17705 			ii = (ipsec_in_t *)first_mp->b_rptr;
17706 			ii->ipsec_in_ill_index =
17707 			    ill->ill_phyint->phyint_ifindex;
17708 			ii->ipsec_in_rill_index =
17709 			    recv_ill->ill_phyint->phyint_ifindex;
17710 			first_mp->b_cont = mp;
17711 			/*
17712 			 * Cache hardware acceleration info.
17713 			 */
17714 			if (hada_mp != NULL) {
17715 				IPSECHW_DEBUG(IPSECHW_PKT,
17716 				    ("ip_rput_local: caching data attr.\n"));
17717 				ii->ipsec_in_accelerated = B_TRUE;
17718 				ii->ipsec_in_da = hada_mp;
17719 				hada_mp = NULL;
17720 			}
17721 		} else {
17722 			ii = (ipsec_in_t *)first_mp->b_rptr;
17723 		}
17724 
17725 		if (!ipsec_loaded(ipss)) {
17726 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17727 			    ire->ire_zoneid, ipst);
17728 			return;
17729 		}
17730 
17731 		ns = ipst->ips_netstack;
17732 		/* select inbound SA and have IPsec process the pkt */
17733 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17734 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17735 			if (esph == NULL)
17736 				return;
17737 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17738 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17739 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17740 			    first_mp, esph);
17741 		} else {
17742 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17743 			if (ah == NULL)
17744 				return;
17745 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17746 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17747 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17748 			    first_mp, ah);
17749 		}
17750 
17751 		switch (ipsec_rc) {
17752 		case IPSEC_STATUS_SUCCESS:
17753 			break;
17754 		case IPSEC_STATUS_FAILED:
17755 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17756 			/* FALLTHRU */
17757 		case IPSEC_STATUS_PENDING:
17758 			return;
17759 		}
17760 		/* we're done with IPsec processing, send it up */
17761 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17762 		return;
17763 	}
17764 	default:
17765 		break;
17766 	}
17767 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17768 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17769 		    ire->ire_zoneid));
17770 		goto drop_pkt;
17771 	}
17772 	/*
17773 	 * Handle protocols with which IP is less intimate.  There
17774 	 * can be more than one stream bound to a particular
17775 	 * protocol.  When this is the case, each one gets a copy
17776 	 * of any incoming packets.
17777 	 */
17778 	ip_fanout_proto(q, first_mp, ill, ipha,
17779 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17780 	    B_TRUE, recv_ill, ire->ire_zoneid);
17781 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17782 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17783 	return;
17784 
17785 drop_pkt:
17786 	freemsg(first_mp);
17787 	if (hada_mp != NULL)
17788 		freeb(hada_mp);
17789 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17790 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17791 #undef	rptr
17792 #undef  iphs
17793 
17794 }
17795 
17796 /*
17797  * Update any source route, record route or timestamp options.
17798  * Check that we are at end of strict source route.
17799  * The options have already been checked for sanity in ip_rput_options().
17800  */
17801 static boolean_t
17802 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17803     ip_stack_t *ipst)
17804 {
17805 	ipoptp_t	opts;
17806 	uchar_t		*opt;
17807 	uint8_t		optval;
17808 	uint8_t		optlen;
17809 	ipaddr_t	dst;
17810 	uint32_t	ts;
17811 	ire_t		*dst_ire;
17812 	timestruc_t	now;
17813 	zoneid_t	zoneid;
17814 	ill_t		*ill;
17815 
17816 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17817 
17818 	ip2dbg(("ip_rput_local_options\n"));
17819 
17820 	for (optval = ipoptp_first(&opts, ipha);
17821 	    optval != IPOPT_EOL;
17822 	    optval = ipoptp_next(&opts)) {
17823 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17824 		opt = opts.ipoptp_cur;
17825 		optlen = opts.ipoptp_len;
17826 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17827 		    optval, optlen));
17828 		switch (optval) {
17829 			uint32_t off;
17830 		case IPOPT_SSRR:
17831 		case IPOPT_LSRR:
17832 			off = opt[IPOPT_OFFSET];
17833 			off--;
17834 			if (optlen < IP_ADDR_LEN ||
17835 			    off > optlen - IP_ADDR_LEN) {
17836 				/* End of source route */
17837 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17838 				break;
17839 			}
17840 			/*
17841 			 * This will only happen if two consecutive entries
17842 			 * in the source route contains our address or if
17843 			 * it is a packet with a loose source route which
17844 			 * reaches us before consuming the whole source route
17845 			 */
17846 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17847 			if (optval == IPOPT_SSRR) {
17848 				goto bad_src_route;
17849 			}
17850 			/*
17851 			 * Hack: instead of dropping the packet truncate the
17852 			 * source route to what has been used by filling the
17853 			 * rest with IPOPT_NOP.
17854 			 */
17855 			opt[IPOPT_OLEN] = (uint8_t)off;
17856 			while (off < optlen) {
17857 				opt[off++] = IPOPT_NOP;
17858 			}
17859 			break;
17860 		case IPOPT_RR:
17861 			off = opt[IPOPT_OFFSET];
17862 			off--;
17863 			if (optlen < IP_ADDR_LEN ||
17864 			    off > optlen - IP_ADDR_LEN) {
17865 				/* No more room - ignore */
17866 				ip1dbg((
17867 				    "ip_rput_local_options: end of RR\n"));
17868 				break;
17869 			}
17870 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17871 			    IP_ADDR_LEN);
17872 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17873 			break;
17874 		case IPOPT_TS:
17875 			/* Insert timestamp if there is romm */
17876 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17877 			case IPOPT_TS_TSONLY:
17878 				off = IPOPT_TS_TIMELEN;
17879 				break;
17880 			case IPOPT_TS_PRESPEC:
17881 			case IPOPT_TS_PRESPEC_RFC791:
17882 				/* Verify that the address matched */
17883 				off = opt[IPOPT_OFFSET] - 1;
17884 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17885 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17886 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17887 				    ipst);
17888 				if (dst_ire == NULL) {
17889 					/* Not for us */
17890 					break;
17891 				}
17892 				ire_refrele(dst_ire);
17893 				/* FALLTHRU */
17894 			case IPOPT_TS_TSANDADDR:
17895 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17896 				break;
17897 			default:
17898 				/*
17899 				 * ip_*put_options should have already
17900 				 * dropped this packet.
17901 				 */
17902 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17903 				    "unknown IT - bug in ip_rput_options?\n");
17904 				return (B_TRUE);	/* Keep "lint" happy */
17905 			}
17906 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17907 				/* Increase overflow counter */
17908 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17909 				opt[IPOPT_POS_OV_FLG] =
17910 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17911 				    (off << 4));
17912 				break;
17913 			}
17914 			off = opt[IPOPT_OFFSET] - 1;
17915 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17916 			case IPOPT_TS_PRESPEC:
17917 			case IPOPT_TS_PRESPEC_RFC791:
17918 			case IPOPT_TS_TSANDADDR:
17919 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17920 				    IP_ADDR_LEN);
17921 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17922 				/* FALLTHRU */
17923 			case IPOPT_TS_TSONLY:
17924 				off = opt[IPOPT_OFFSET] - 1;
17925 				/* Compute # of milliseconds since midnight */
17926 				gethrestime(&now);
17927 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17928 				    now.tv_nsec / (NANOSEC / MILLISEC);
17929 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17930 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17931 				break;
17932 			}
17933 			break;
17934 		}
17935 	}
17936 	return (B_TRUE);
17937 
17938 bad_src_route:
17939 	q = WR(q);
17940 	if (q->q_next != NULL)
17941 		ill = q->q_ptr;
17942 	else
17943 		ill = NULL;
17944 
17945 	/* make sure we clear any indication of a hardware checksum */
17946 	DB_CKSUMFLAGS(mp) = 0;
17947 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17948 	if (zoneid == ALL_ZONES)
17949 		freemsg(mp);
17950 	else
17951 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17952 	return (B_FALSE);
17953 
17954 }
17955 
17956 /*
17957  * Process IP options in an inbound packet.  If an option affects the
17958  * effective destination address, return the next hop address via dstp.
17959  * Returns -1 if something fails in which case an ICMP error has been sent
17960  * and mp freed.
17961  */
17962 static int
17963 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17964     ip_stack_t *ipst)
17965 {
17966 	ipoptp_t	opts;
17967 	uchar_t		*opt;
17968 	uint8_t		optval;
17969 	uint8_t		optlen;
17970 	ipaddr_t	dst;
17971 	intptr_t	code = 0;
17972 	ire_t		*ire = NULL;
17973 	zoneid_t	zoneid;
17974 	ill_t		*ill;
17975 
17976 	ip2dbg(("ip_rput_options\n"));
17977 	dst = ipha->ipha_dst;
17978 	for (optval = ipoptp_first(&opts, ipha);
17979 	    optval != IPOPT_EOL;
17980 	    optval = ipoptp_next(&opts)) {
17981 		opt = opts.ipoptp_cur;
17982 		optlen = opts.ipoptp_len;
17983 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17984 		    optval, optlen));
17985 		/*
17986 		 * Note: we need to verify the checksum before we
17987 		 * modify anything thus this routine only extracts the next
17988 		 * hop dst from any source route.
17989 		 */
17990 		switch (optval) {
17991 			uint32_t off;
17992 		case IPOPT_SSRR:
17993 		case IPOPT_LSRR:
17994 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17995 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17996 			if (ire == NULL) {
17997 				if (optval == IPOPT_SSRR) {
17998 					ip1dbg(("ip_rput_options: not next"
17999 					    " strict source route 0x%x\n",
18000 					    ntohl(dst)));
18001 					code = (char *)&ipha->ipha_dst -
18002 					    (char *)ipha;
18003 					goto param_prob; /* RouterReq's */
18004 				}
18005 				ip2dbg(("ip_rput_options: "
18006 				    "not next source route 0x%x\n",
18007 				    ntohl(dst)));
18008 				break;
18009 			}
18010 			ire_refrele(ire);
18011 
18012 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18013 				ip1dbg((
18014 				    "ip_rput_options: bad option offset\n"));
18015 				code = (char *)&opt[IPOPT_OLEN] -
18016 				    (char *)ipha;
18017 				goto param_prob;
18018 			}
18019 			off = opt[IPOPT_OFFSET];
18020 			off--;
18021 		redo_srr:
18022 			if (optlen < IP_ADDR_LEN ||
18023 			    off > optlen - IP_ADDR_LEN) {
18024 				/* End of source route */
18025 				ip1dbg(("ip_rput_options: end of SR\n"));
18026 				break;
18027 			}
18028 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18029 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18030 			    ntohl(dst)));
18031 
18032 			/*
18033 			 * Check if our address is present more than
18034 			 * once as consecutive hops in source route.
18035 			 * XXX verify per-interface ip_forwarding
18036 			 * for source route?
18037 			 */
18038 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18039 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18040 
18041 			if (ire != NULL) {
18042 				ire_refrele(ire);
18043 				off += IP_ADDR_LEN;
18044 				goto redo_srr;
18045 			}
18046 
18047 			if (dst == htonl(INADDR_LOOPBACK)) {
18048 				ip1dbg(("ip_rput_options: loopback addr in "
18049 				    "source route!\n"));
18050 				goto bad_src_route;
18051 			}
18052 			/*
18053 			 * For strict: verify that dst is directly
18054 			 * reachable.
18055 			 */
18056 			if (optval == IPOPT_SSRR) {
18057 				ire = ire_ftable_lookup(dst, 0, 0,
18058 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18059 				    MBLK_GETLABEL(mp),
18060 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18061 				if (ire == NULL) {
18062 					ip1dbg(("ip_rput_options: SSRR not "
18063 					    "directly reachable: 0x%x\n",
18064 					    ntohl(dst)));
18065 					goto bad_src_route;
18066 				}
18067 				ire_refrele(ire);
18068 			}
18069 			/*
18070 			 * Defer update of the offset and the record route
18071 			 * until the packet is forwarded.
18072 			 */
18073 			break;
18074 		case IPOPT_RR:
18075 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18076 				ip1dbg((
18077 				    "ip_rput_options: bad option offset\n"));
18078 				code = (char *)&opt[IPOPT_OLEN] -
18079 				    (char *)ipha;
18080 				goto param_prob;
18081 			}
18082 			break;
18083 		case IPOPT_TS:
18084 			/*
18085 			 * Verify that length >= 5 and that there is either
18086 			 * room for another timestamp or that the overflow
18087 			 * counter is not maxed out.
18088 			 */
18089 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18090 			if (optlen < IPOPT_MINLEN_IT) {
18091 				goto param_prob;
18092 			}
18093 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18094 				ip1dbg((
18095 				    "ip_rput_options: bad option offset\n"));
18096 				code = (char *)&opt[IPOPT_OFFSET] -
18097 				    (char *)ipha;
18098 				goto param_prob;
18099 			}
18100 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18101 			case IPOPT_TS_TSONLY:
18102 				off = IPOPT_TS_TIMELEN;
18103 				break;
18104 			case IPOPT_TS_TSANDADDR:
18105 			case IPOPT_TS_PRESPEC:
18106 			case IPOPT_TS_PRESPEC_RFC791:
18107 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18108 				break;
18109 			default:
18110 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18111 				    (char *)ipha;
18112 				goto param_prob;
18113 			}
18114 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18115 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18116 				/*
18117 				 * No room and the overflow counter is 15
18118 				 * already.
18119 				 */
18120 				goto param_prob;
18121 			}
18122 			break;
18123 		}
18124 	}
18125 
18126 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18127 		*dstp = dst;
18128 		return (0);
18129 	}
18130 
18131 	ip1dbg(("ip_rput_options: error processing IP options."));
18132 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18133 
18134 param_prob:
18135 	q = WR(q);
18136 	if (q->q_next != NULL)
18137 		ill = q->q_ptr;
18138 	else
18139 		ill = NULL;
18140 
18141 	/* make sure we clear any indication of a hardware checksum */
18142 	DB_CKSUMFLAGS(mp) = 0;
18143 	/* Don't know whether this is for non-global or global/forwarding */
18144 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18145 	if (zoneid == ALL_ZONES)
18146 		freemsg(mp);
18147 	else
18148 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18149 	return (-1);
18150 
18151 bad_src_route:
18152 	q = WR(q);
18153 	if (q->q_next != NULL)
18154 		ill = q->q_ptr;
18155 	else
18156 		ill = NULL;
18157 
18158 	/* make sure we clear any indication of a hardware checksum */
18159 	DB_CKSUMFLAGS(mp) = 0;
18160 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18161 	if (zoneid == ALL_ZONES)
18162 		freemsg(mp);
18163 	else
18164 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18165 	return (-1);
18166 }
18167 
18168 /*
18169  * IP & ICMP info in >=14 msg's ...
18170  *  - ip fixed part (mib2_ip_t)
18171  *  - icmp fixed part (mib2_icmp_t)
18172  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18173  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18174  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18175  *  - ipRouteAttributeTable (ip 102)	labeled routes
18176  *  - ip multicast membership (ip_member_t)
18177  *  - ip multicast source filtering (ip_grpsrc_t)
18178  *  - igmp fixed part (struct igmpstat)
18179  *  - multicast routing stats (struct mrtstat)
18180  *  - multicast routing vifs (array of struct vifctl)
18181  *  - multicast routing routes (array of struct mfcctl)
18182  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18183  *					One per ill plus one generic
18184  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18185  *					One per ill plus one generic
18186  *  - ipv6RouteEntry			all IPv6 IREs
18187  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18188  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18189  *  - ipv6AddrEntry			all IPv6 ipifs
18190  *  - ipv6 multicast membership (ipv6_member_t)
18191  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18192  *
18193  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18194  *
18195  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18196  * already filled in by the caller.
18197  * Return value of 0 indicates that no messages were sent and caller
18198  * should free mpctl.
18199  */
18200 int
18201 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18202 {
18203 	ip_stack_t *ipst;
18204 	sctp_stack_t *sctps;
18205 
18206 
18207 	if (q->q_next != NULL) {
18208 		ipst = ILLQ_TO_IPST(q);
18209 	} else {
18210 		ipst = CONNQ_TO_IPST(q);
18211 	}
18212 	ASSERT(ipst != NULL);
18213 	sctps = ipst->ips_netstack->netstack_sctp;
18214 
18215 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18216 		return (0);
18217 	}
18218 
18219 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18220 	    ipst)) == NULL) {
18221 		return (1);
18222 	}
18223 
18224 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18225 		return (1);
18226 	}
18227 
18228 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18229 		return (1);
18230 	}
18231 
18232 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18233 		return (1);
18234 	}
18235 
18236 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18237 		return (1);
18238 	}
18239 
18240 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18241 		return (1);
18242 	}
18243 
18244 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18245 		return (1);
18246 	}
18247 
18248 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18249 		return (1);
18250 	}
18251 
18252 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18253 		return (1);
18254 	}
18255 
18256 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18257 		return (1);
18258 	}
18259 
18260 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18261 		return (1);
18262 	}
18263 
18264 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18265 		return (1);
18266 	}
18267 
18268 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18269 		return (1);
18270 	}
18271 
18272 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18273 		return (1);
18274 	}
18275 
18276 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18277 		return (1);
18278 	}
18279 
18280 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18281 	if (mpctl == NULL) {
18282 		return (1);
18283 	}
18284 
18285 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18286 		return (1);
18287 	}
18288 	freemsg(mpctl);
18289 	return (1);
18290 }
18291 
18292 
18293 /* Get global (legacy) IPv4 statistics */
18294 static mblk_t *
18295 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18296     ip_stack_t *ipst)
18297 {
18298 	mib2_ip_t		old_ip_mib;
18299 	struct opthdr		*optp;
18300 	mblk_t			*mp2ctl;
18301 
18302 	/*
18303 	 * make a copy of the original message
18304 	 */
18305 	mp2ctl = copymsg(mpctl);
18306 
18307 	/* fixed length IP structure... */
18308 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18309 	optp->level = MIB2_IP;
18310 	optp->name = 0;
18311 	SET_MIB(old_ip_mib.ipForwarding,
18312 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18313 	SET_MIB(old_ip_mib.ipDefaultTTL,
18314 	    (uint32_t)ipst->ips_ip_def_ttl);
18315 	SET_MIB(old_ip_mib.ipReasmTimeout,
18316 	    ipst->ips_ip_g_frag_timeout);
18317 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18318 	    sizeof (mib2_ipAddrEntry_t));
18319 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18320 	    sizeof (mib2_ipRouteEntry_t));
18321 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18322 	    sizeof (mib2_ipNetToMediaEntry_t));
18323 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18324 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18325 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18326 	    sizeof (mib2_ipAttributeEntry_t));
18327 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18328 
18329 	/*
18330 	 * Grab the statistics from the new IP MIB
18331 	 */
18332 	SET_MIB(old_ip_mib.ipInReceives,
18333 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18334 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18335 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18336 	SET_MIB(old_ip_mib.ipForwDatagrams,
18337 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18338 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18339 	    ipmib->ipIfStatsInUnknownProtos);
18340 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18341 	SET_MIB(old_ip_mib.ipInDelivers,
18342 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18343 	SET_MIB(old_ip_mib.ipOutRequests,
18344 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18345 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18346 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18347 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18348 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18349 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18350 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18351 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18352 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18353 
18354 	/* ipRoutingDiscards is not being used */
18355 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18356 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18357 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18358 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18359 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18360 	    ipmib->ipIfStatsReasmDuplicates);
18361 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18362 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18363 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18364 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18365 	SET_MIB(old_ip_mib.rawipInOverflows,
18366 	    ipmib->rawipIfStatsInOverflows);
18367 
18368 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18369 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18370 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18371 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18372 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18373 	    ipmib->ipIfStatsOutSwitchIPVersion);
18374 
18375 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18376 	    (int)sizeof (old_ip_mib))) {
18377 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18378 		    (uint_t)sizeof (old_ip_mib)));
18379 	}
18380 
18381 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18382 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18383 	    (int)optp->level, (int)optp->name, (int)optp->len));
18384 	qreply(q, mpctl);
18385 	return (mp2ctl);
18386 }
18387 
18388 /* Per interface IPv4 statistics */
18389 static mblk_t *
18390 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18391 {
18392 	struct opthdr		*optp;
18393 	mblk_t			*mp2ctl;
18394 	ill_t			*ill;
18395 	ill_walk_context_t	ctx;
18396 	mblk_t			*mp_tail = NULL;
18397 	mib2_ipIfStatsEntry_t	global_ip_mib;
18398 
18399 	/*
18400 	 * Make a copy of the original message
18401 	 */
18402 	mp2ctl = copymsg(mpctl);
18403 
18404 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18405 	optp->level = MIB2_IP;
18406 	optp->name = MIB2_IP_TRAFFIC_STATS;
18407 	/* Include "unknown interface" ip_mib */
18408 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18409 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18410 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18411 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18412 	    (ipst->ips_ip_g_forward ? 1 : 2));
18413 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18414 	    (uint32_t)ipst->ips_ip_def_ttl);
18415 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18416 	    sizeof (mib2_ipIfStatsEntry_t));
18417 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18418 	    sizeof (mib2_ipAddrEntry_t));
18419 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18420 	    sizeof (mib2_ipRouteEntry_t));
18421 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18422 	    sizeof (mib2_ipNetToMediaEntry_t));
18423 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18424 	    sizeof (ip_member_t));
18425 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18426 	    sizeof (ip_grpsrc_t));
18427 
18428 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18429 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18430 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18431 		    "failed to allocate %u bytes\n",
18432 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18433 	}
18434 
18435 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18436 
18437 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18438 	ill = ILL_START_WALK_V4(&ctx, ipst);
18439 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18440 		ill->ill_ip_mib->ipIfStatsIfIndex =
18441 		    ill->ill_phyint->phyint_ifindex;
18442 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18443 		    (ipst->ips_ip_g_forward ? 1 : 2));
18444 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18445 		    (uint32_t)ipst->ips_ip_def_ttl);
18446 
18447 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18448 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18449 		    (char *)ill->ill_ip_mib,
18450 		    (int)sizeof (*ill->ill_ip_mib))) {
18451 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18452 			    "failed to allocate %u bytes\n",
18453 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18454 		}
18455 	}
18456 	rw_exit(&ipst->ips_ill_g_lock);
18457 
18458 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18459 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18460 	    "level %d, name %d, len %d\n",
18461 	    (int)optp->level, (int)optp->name, (int)optp->len));
18462 	qreply(q, mpctl);
18463 
18464 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18465 }
18466 
18467 /* Global IPv4 ICMP statistics */
18468 static mblk_t *
18469 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18470 {
18471 	struct opthdr		*optp;
18472 	mblk_t			*mp2ctl;
18473 
18474 	/*
18475 	 * Make a copy of the original message
18476 	 */
18477 	mp2ctl = copymsg(mpctl);
18478 
18479 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18480 	optp->level = MIB2_ICMP;
18481 	optp->name = 0;
18482 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18483 	    (int)sizeof (ipst->ips_icmp_mib))) {
18484 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18485 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18486 	}
18487 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18488 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18489 	    (int)optp->level, (int)optp->name, (int)optp->len));
18490 	qreply(q, mpctl);
18491 	return (mp2ctl);
18492 }
18493 
18494 /* Global IPv4 IGMP statistics */
18495 static mblk_t *
18496 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18497 {
18498 	struct opthdr		*optp;
18499 	mblk_t			*mp2ctl;
18500 
18501 	/*
18502 	 * make a copy of the original message
18503 	 */
18504 	mp2ctl = copymsg(mpctl);
18505 
18506 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18507 	optp->level = EXPER_IGMP;
18508 	optp->name = 0;
18509 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18510 	    (int)sizeof (ipst->ips_igmpstat))) {
18511 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18512 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18513 	}
18514 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18515 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18516 	    (int)optp->level, (int)optp->name, (int)optp->len));
18517 	qreply(q, mpctl);
18518 	return (mp2ctl);
18519 }
18520 
18521 /* Global IPv4 Multicast Routing statistics */
18522 static mblk_t *
18523 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18524 {
18525 	struct opthdr		*optp;
18526 	mblk_t			*mp2ctl;
18527 
18528 	/*
18529 	 * make a copy of the original message
18530 	 */
18531 	mp2ctl = copymsg(mpctl);
18532 
18533 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18534 	optp->level = EXPER_DVMRP;
18535 	optp->name = 0;
18536 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18537 		ip0dbg(("ip_mroute_stats: failed\n"));
18538 	}
18539 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18540 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18541 	    (int)optp->level, (int)optp->name, (int)optp->len));
18542 	qreply(q, mpctl);
18543 	return (mp2ctl);
18544 }
18545 
18546 /* IPv4 address information */
18547 static mblk_t *
18548 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18549 {
18550 	struct opthdr		*optp;
18551 	mblk_t			*mp2ctl;
18552 	mblk_t			*mp_tail = NULL;
18553 	ill_t			*ill;
18554 	ipif_t			*ipif;
18555 	uint_t			bitval;
18556 	mib2_ipAddrEntry_t	mae;
18557 	zoneid_t		zoneid;
18558 	ill_walk_context_t ctx;
18559 
18560 	/*
18561 	 * make a copy of the original message
18562 	 */
18563 	mp2ctl = copymsg(mpctl);
18564 
18565 	/* ipAddrEntryTable */
18566 
18567 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18568 	optp->level = MIB2_IP;
18569 	optp->name = MIB2_IP_ADDR;
18570 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18571 
18572 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18573 	ill = ILL_START_WALK_V4(&ctx, ipst);
18574 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18575 		for (ipif = ill->ill_ipif; ipif != NULL;
18576 		    ipif = ipif->ipif_next) {
18577 			if (ipif->ipif_zoneid != zoneid &&
18578 			    ipif->ipif_zoneid != ALL_ZONES)
18579 				continue;
18580 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18581 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18582 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18583 
18584 			(void) ipif_get_name(ipif,
18585 			    mae.ipAdEntIfIndex.o_bytes,
18586 			    OCTET_LENGTH);
18587 			mae.ipAdEntIfIndex.o_length =
18588 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18589 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18590 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18591 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18592 			mae.ipAdEntInfo.ae_subnet_len =
18593 			    ip_mask_to_plen(ipif->ipif_net_mask);
18594 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18595 			for (bitval = 1;
18596 			    bitval &&
18597 			    !(bitval & ipif->ipif_brd_addr);
18598 			    bitval <<= 1)
18599 				noop;
18600 			mae.ipAdEntBcastAddr = bitval;
18601 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18602 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18603 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18604 			mae.ipAdEntInfo.ae_broadcast_addr =
18605 			    ipif->ipif_brd_addr;
18606 			mae.ipAdEntInfo.ae_pp_dst_addr =
18607 			    ipif->ipif_pp_dst_addr;
18608 			    mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18609 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18610 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18611 
18612 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18613 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18614 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18615 				    "allocate %u bytes\n",
18616 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18617 			}
18618 		}
18619 	}
18620 	rw_exit(&ipst->ips_ill_g_lock);
18621 
18622 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18623 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18624 	    (int)optp->level, (int)optp->name, (int)optp->len));
18625 	qreply(q, mpctl);
18626 	return (mp2ctl);
18627 }
18628 
18629 /* IPv6 address information */
18630 static mblk_t *
18631 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18632 {
18633 	struct opthdr		*optp;
18634 	mblk_t			*mp2ctl;
18635 	mblk_t			*mp_tail = NULL;
18636 	ill_t			*ill;
18637 	ipif_t			*ipif;
18638 	mib2_ipv6AddrEntry_t	mae6;
18639 	zoneid_t		zoneid;
18640 	ill_walk_context_t	ctx;
18641 
18642 	/*
18643 	 * make a copy of the original message
18644 	 */
18645 	mp2ctl = copymsg(mpctl);
18646 
18647 	/* ipv6AddrEntryTable */
18648 
18649 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18650 	optp->level = MIB2_IP6;
18651 	optp->name = MIB2_IP6_ADDR;
18652 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18653 
18654 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18655 	ill = ILL_START_WALK_V6(&ctx, ipst);
18656 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18657 		for (ipif = ill->ill_ipif; ipif != NULL;
18658 		    ipif = ipif->ipif_next) {
18659 			if (ipif->ipif_zoneid != zoneid &&
18660 			    ipif->ipif_zoneid != ALL_ZONES)
18661 				continue;
18662 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18663 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18664 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18665 
18666 			(void) ipif_get_name(ipif,
18667 			    mae6.ipv6AddrIfIndex.o_bytes,
18668 			    OCTET_LENGTH);
18669 			mae6.ipv6AddrIfIndex.o_length =
18670 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18671 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18672 			mae6.ipv6AddrPfxLength =
18673 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18674 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18675 			mae6.ipv6AddrInfo.ae_subnet_len =
18676 			    mae6.ipv6AddrPfxLength;
18677 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18678 
18679 			/* Type: stateless(1), stateful(2), unknown(3) */
18680 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18681 				mae6.ipv6AddrType = 1;
18682 			else
18683 				mae6.ipv6AddrType = 2;
18684 			/* Anycast: true(1), false(2) */
18685 			if (ipif->ipif_flags & IPIF_ANYCAST)
18686 				mae6.ipv6AddrAnycastFlag = 1;
18687 			else
18688 				mae6.ipv6AddrAnycastFlag = 2;
18689 
18690 			/*
18691 			 * Address status: preferred(1), deprecated(2),
18692 			 * invalid(3), inaccessible(4), unknown(5)
18693 			 */
18694 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18695 				mae6.ipv6AddrStatus = 3;
18696 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18697 				mae6.ipv6AddrStatus = 2;
18698 			else
18699 				mae6.ipv6AddrStatus = 1;
18700 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18701 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18702 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18703 						ipif->ipif_v6pp_dst_addr;
18704 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18705 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18706 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18707 			mae6.ipv6AddrIdentifier = ill->ill_token;
18708 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18709 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18710 			mae6.ipv6AddrRetransmitTime =
18711 			    ill->ill_reachable_retrans_time;
18712 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18713 				(char *)&mae6,
18714 				(int)sizeof (mib2_ipv6AddrEntry_t))) {
18715 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18716 				    "allocate %u bytes\n",
18717 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18718 			}
18719 		}
18720 	}
18721 	rw_exit(&ipst->ips_ill_g_lock);
18722 
18723 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18724 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18725 	    (int)optp->level, (int)optp->name, (int)optp->len));
18726 	qreply(q, mpctl);
18727 	return (mp2ctl);
18728 }
18729 
18730 /* IPv4 multicast group membership. */
18731 static mblk_t *
18732 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18733 {
18734 	struct opthdr		*optp;
18735 	mblk_t			*mp2ctl;
18736 	ill_t			*ill;
18737 	ipif_t			*ipif;
18738 	ilm_t			*ilm;
18739 	ip_member_t		ipm;
18740 	mblk_t			*mp_tail = NULL;
18741 	ill_walk_context_t	ctx;
18742 	zoneid_t		zoneid;
18743 
18744 	/*
18745 	 * make a copy of the original message
18746 	 */
18747 	mp2ctl = copymsg(mpctl);
18748 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18749 
18750 	/* ipGroupMember table */
18751 	optp = (struct opthdr *)&mpctl->b_rptr[
18752 	    sizeof (struct T_optmgmt_ack)];
18753 	optp->level = MIB2_IP;
18754 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18755 
18756 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18757 	ill = ILL_START_WALK_V4(&ctx, ipst);
18758 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18759 		ILM_WALKER_HOLD(ill);
18760 		for (ipif = ill->ill_ipif; ipif != NULL;
18761 		    ipif = ipif->ipif_next) {
18762 			if (ipif->ipif_zoneid != zoneid &&
18763 			    ipif->ipif_zoneid != ALL_ZONES)
18764 				continue;	/* not this zone */
18765 			(void) ipif_get_name(ipif,
18766 			    ipm.ipGroupMemberIfIndex.o_bytes,
18767 			    OCTET_LENGTH);
18768 			ipm.ipGroupMemberIfIndex.o_length =
18769 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18770 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18771 				ASSERT(ilm->ilm_ipif != NULL);
18772 				ASSERT(ilm->ilm_ill == NULL);
18773 				if (ilm->ilm_ipif != ipif)
18774 					continue;
18775 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18776 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18777 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18778 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18779 				    (char *)&ipm, (int)sizeof (ipm))) {
18780 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18781 					    "failed to allocate %u bytes\n",
18782 						(uint_t)sizeof (ipm)));
18783 				}
18784 			}
18785 		}
18786 		ILM_WALKER_RELE(ill);
18787 	}
18788 	rw_exit(&ipst->ips_ill_g_lock);
18789 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18790 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18791 	    (int)optp->level, (int)optp->name, (int)optp->len));
18792 	qreply(q, mpctl);
18793 	return (mp2ctl);
18794 }
18795 
18796 /* IPv6 multicast group membership. */
18797 static mblk_t *
18798 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18799 {
18800 	struct opthdr		*optp;
18801 	mblk_t			*mp2ctl;
18802 	ill_t			*ill;
18803 	ilm_t			*ilm;
18804 	ipv6_member_t		ipm6;
18805 	mblk_t			*mp_tail = NULL;
18806 	ill_walk_context_t	ctx;
18807 	zoneid_t		zoneid;
18808 
18809 	/*
18810 	 * make a copy of the original message
18811 	 */
18812 	mp2ctl = copymsg(mpctl);
18813 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18814 
18815 	/* ip6GroupMember table */
18816 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18817 	optp->level = MIB2_IP6;
18818 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18819 
18820 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18821 	ill = ILL_START_WALK_V6(&ctx, ipst);
18822 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18823 		ILM_WALKER_HOLD(ill);
18824 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18825 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18826 			ASSERT(ilm->ilm_ipif == NULL);
18827 			ASSERT(ilm->ilm_ill != NULL);
18828 			if (ilm->ilm_zoneid != zoneid)
18829 				continue;	/* not this zone */
18830 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18831 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18832 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18833 			if (!snmp_append_data2(mpctl->b_cont,
18834 			    &mp_tail,
18835 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18836 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18837 				    "failed to allocate %u bytes\n",
18838 				    (uint_t)sizeof (ipm6)));
18839 			}
18840 		}
18841 		ILM_WALKER_RELE(ill);
18842 	}
18843 	rw_exit(&ipst->ips_ill_g_lock);
18844 
18845 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18846 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18847 	    (int)optp->level, (int)optp->name, (int)optp->len));
18848 	qreply(q, mpctl);
18849 	return (mp2ctl);
18850 }
18851 
18852 /* IP multicast filtered sources */
18853 static mblk_t *
18854 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18855 {
18856 	struct opthdr		*optp;
18857 	mblk_t			*mp2ctl;
18858 	ill_t			*ill;
18859 	ipif_t			*ipif;
18860 	ilm_t			*ilm;
18861 	ip_grpsrc_t		ips;
18862 	mblk_t			*mp_tail = NULL;
18863 	ill_walk_context_t	ctx;
18864 	zoneid_t		zoneid;
18865 	int			i;
18866 	slist_t			*sl;
18867 
18868 	/*
18869 	 * make a copy of the original message
18870 	 */
18871 	mp2ctl = copymsg(mpctl);
18872 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18873 
18874 	/* ipGroupSource table */
18875 	optp = (struct opthdr *)&mpctl->b_rptr[
18876 	    sizeof (struct T_optmgmt_ack)];
18877 	optp->level = MIB2_IP;
18878 	optp->name = EXPER_IP_GROUP_SOURCES;
18879 
18880 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18881 	ill = ILL_START_WALK_V4(&ctx, ipst);
18882 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18883 		ILM_WALKER_HOLD(ill);
18884 		for (ipif = ill->ill_ipif; ipif != NULL;
18885 		    ipif = ipif->ipif_next) {
18886 			if (ipif->ipif_zoneid != zoneid)
18887 				continue;	/* not this zone */
18888 			(void) ipif_get_name(ipif,
18889 			    ips.ipGroupSourceIfIndex.o_bytes,
18890 			    OCTET_LENGTH);
18891 			ips.ipGroupSourceIfIndex.o_length =
18892 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18893 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18894 				ASSERT(ilm->ilm_ipif != NULL);
18895 				ASSERT(ilm->ilm_ill == NULL);
18896 				sl = ilm->ilm_filter;
18897 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18898 					continue;
18899 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18900 				for (i = 0; i < sl->sl_numsrc; i++) {
18901 					if (!IN6_IS_ADDR_V4MAPPED(
18902 					    &sl->sl_addr[i]))
18903 						continue;
18904 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18905 					    ips.ipGroupSourceAddress);
18906 					if (snmp_append_data2(mpctl->b_cont,
18907 					    &mp_tail, (char *)&ips,
18908 					    (int)sizeof (ips)) == 0) {
18909 						ip1dbg(("ip_snmp_get_mib2_"
18910 						    "ip_group_src: failed to "
18911 						    "allocate %u bytes\n",
18912 						    (uint_t)sizeof (ips)));
18913 					}
18914 				}
18915 			}
18916 		}
18917 		ILM_WALKER_RELE(ill);
18918 	}
18919 	rw_exit(&ipst->ips_ill_g_lock);
18920 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18921 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18922 	    (int)optp->level, (int)optp->name, (int)optp->len));
18923 	qreply(q, mpctl);
18924 	return (mp2ctl);
18925 }
18926 
18927 /* IPv6 multicast filtered sources. */
18928 static mblk_t *
18929 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18930 {
18931 	struct opthdr		*optp;
18932 	mblk_t			*mp2ctl;
18933 	ill_t			*ill;
18934 	ilm_t			*ilm;
18935 	ipv6_grpsrc_t		ips6;
18936 	mblk_t			*mp_tail = NULL;
18937 	ill_walk_context_t	ctx;
18938 	zoneid_t		zoneid;
18939 	int			i;
18940 	slist_t			*sl;
18941 
18942 	/*
18943 	 * make a copy of the original message
18944 	 */
18945 	mp2ctl = copymsg(mpctl);
18946 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18947 
18948 	/* ip6GroupMember table */
18949 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18950 	optp->level = MIB2_IP6;
18951 	optp->name = EXPER_IP6_GROUP_SOURCES;
18952 
18953 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18954 	ill = ILL_START_WALK_V6(&ctx, ipst);
18955 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18956 		ILM_WALKER_HOLD(ill);
18957 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18958 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18959 			ASSERT(ilm->ilm_ipif == NULL);
18960 			ASSERT(ilm->ilm_ill != NULL);
18961 			sl = ilm->ilm_filter;
18962 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18963 				continue;
18964 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18965 			for (i = 0; i < sl->sl_numsrc; i++) {
18966 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18967 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18968 				    (char *)&ips6, (int)sizeof (ips6))) {
18969 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18970 					    "group_src: failed to allocate "
18971 					    "%u bytes\n",
18972 					    (uint_t)sizeof (ips6)));
18973 				}
18974 			}
18975 		}
18976 		ILM_WALKER_RELE(ill);
18977 	}
18978 	rw_exit(&ipst->ips_ill_g_lock);
18979 
18980 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18981 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18982 	    (int)optp->level, (int)optp->name, (int)optp->len));
18983 	qreply(q, mpctl);
18984 	return (mp2ctl);
18985 }
18986 
18987 /* Multicast routing virtual interface table. */
18988 static mblk_t *
18989 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18990 {
18991 	struct opthdr		*optp;
18992 	mblk_t			*mp2ctl;
18993 
18994 	/*
18995 	 * make a copy of the original message
18996 	 */
18997 	mp2ctl = copymsg(mpctl);
18998 
18999 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19000 	optp->level = EXPER_DVMRP;
19001 	optp->name = EXPER_DVMRP_VIF;
19002 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19003 		ip0dbg(("ip_mroute_vif: failed\n"));
19004 	}
19005 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19006 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19007 	    (int)optp->level, (int)optp->name, (int)optp->len));
19008 	qreply(q, mpctl);
19009 	return (mp2ctl);
19010 }
19011 
19012 /* Multicast routing table. */
19013 static mblk_t *
19014 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19015 {
19016 	struct opthdr		*optp;
19017 	mblk_t			*mp2ctl;
19018 
19019 	/*
19020 	 * make a copy of the original message
19021 	 */
19022 	mp2ctl = copymsg(mpctl);
19023 
19024 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19025 	optp->level = EXPER_DVMRP;
19026 	optp->name = EXPER_DVMRP_MRT;
19027 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19028 		ip0dbg(("ip_mroute_mrt: failed\n"));
19029 	}
19030 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19031 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19032 	    (int)optp->level, (int)optp->name, (int)optp->len));
19033 	qreply(q, mpctl);
19034 	return (mp2ctl);
19035 }
19036 
19037 /*
19038  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19039  * in one IRE walk.
19040  */
19041 static mblk_t *
19042 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19043 {
19044 	struct opthdr	*optp;
19045 	mblk_t		*mp2ctl;	/* Returned */
19046 	mblk_t		*mp3ctl;	/* nettomedia */
19047 	mblk_t		*mp4ctl;	/* routeattrs */
19048 	iproutedata_t	ird;
19049 	zoneid_t	zoneid;
19050 
19051 	/*
19052 	 * make copies of the original message
19053 	 *	- mp2ctl is returned unchanged to the caller for his use
19054 	 *	- mpctl is sent upstream as ipRouteEntryTable
19055 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19056 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19057 	 */
19058 	mp2ctl = copymsg(mpctl);
19059 	mp3ctl = copymsg(mpctl);
19060 	mp4ctl = copymsg(mpctl);
19061 	if (mp3ctl == NULL || mp4ctl == NULL) {
19062 		freemsg(mp4ctl);
19063 		freemsg(mp3ctl);
19064 		freemsg(mp2ctl);
19065 		freemsg(mpctl);
19066 		return (NULL);
19067 	}
19068 
19069 	bzero(&ird, sizeof (ird));
19070 
19071 	ird.ird_route.lp_head = mpctl->b_cont;
19072 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19073 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19074 
19075 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19076 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19077 	if (zoneid == GLOBAL_ZONEID) {
19078 		/*
19079 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19080 		 * requires the sys_net_config or sys_ip_config privilege,
19081 		 * it can only run in the global zone or an exclusive-IP zone,
19082 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19083 		 */
19084 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19085 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19086 	}
19087 
19088 	/* ipRouteEntryTable in mpctl */
19089 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19090 	optp->level = MIB2_IP;
19091 	optp->name = MIB2_IP_ROUTE;
19092 	optp->len = msgdsize(ird.ird_route.lp_head);
19093 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19094 	    (int)optp->level, (int)optp->name, (int)optp->len));
19095 	qreply(q, mpctl);
19096 
19097 	/* ipNetToMediaEntryTable in mp3ctl */
19098 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19099 	optp->level = MIB2_IP;
19100 	optp->name = MIB2_IP_MEDIA;
19101 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19102 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19103 	    (int)optp->level, (int)optp->name, (int)optp->len));
19104 	qreply(q, mp3ctl);
19105 
19106 	/* ipRouteAttributeTable in mp4ctl */
19107 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19108 	optp->level = MIB2_IP;
19109 	optp->name = EXPER_IP_RTATTR;
19110 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19111 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19112 	    (int)optp->level, (int)optp->name, (int)optp->len));
19113 	if (optp->len == 0)
19114 		freemsg(mp4ctl);
19115 	else
19116 		qreply(q, mp4ctl);
19117 
19118 	return (mp2ctl);
19119 }
19120 
19121 /*
19122  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19123  * ipv6NetToMediaEntryTable in an NDP walk.
19124  */
19125 static mblk_t *
19126 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19127 {
19128 	struct opthdr	*optp;
19129 	mblk_t		*mp2ctl;	/* Returned */
19130 	mblk_t		*mp3ctl;	/* nettomedia */
19131 	mblk_t		*mp4ctl;	/* routeattrs */
19132 	iproutedata_t	ird;
19133 	zoneid_t	zoneid;
19134 
19135 	/*
19136 	 * make copies of the original message
19137 	 *	- mp2ctl is returned unchanged to the caller for his use
19138 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19139 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19140 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19141 	 */
19142 	mp2ctl = copymsg(mpctl);
19143 	mp3ctl = copymsg(mpctl);
19144 	mp4ctl = copymsg(mpctl);
19145 	if (mp3ctl == NULL || mp4ctl == NULL) {
19146 		freemsg(mp4ctl);
19147 		freemsg(mp3ctl);
19148 		freemsg(mp2ctl);
19149 		freemsg(mpctl);
19150 		return (NULL);
19151 	}
19152 
19153 	bzero(&ird, sizeof (ird));
19154 
19155 	ird.ird_route.lp_head = mpctl->b_cont;
19156 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19157 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19158 
19159 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19160 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19161 
19162 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19163 	optp->level = MIB2_IP6;
19164 	optp->name = MIB2_IP6_ROUTE;
19165 	optp->len = msgdsize(ird.ird_route.lp_head);
19166 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19167 	    (int)optp->level, (int)optp->name, (int)optp->len));
19168 	qreply(q, mpctl);
19169 
19170 	/* ipv6NetToMediaEntryTable in mp3ctl */
19171 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19172 
19173 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19174 	optp->level = MIB2_IP6;
19175 	optp->name = MIB2_IP6_MEDIA;
19176 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19177 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19178 	    (int)optp->level, (int)optp->name, (int)optp->len));
19179 	qreply(q, mp3ctl);
19180 
19181 	/* ipv6RouteAttributeTable in mp4ctl */
19182 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19183 	optp->level = MIB2_IP6;
19184 	optp->name = EXPER_IP_RTATTR;
19185 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19186 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19187 	    (int)optp->level, (int)optp->name, (int)optp->len));
19188 	if (optp->len == 0)
19189 		freemsg(mp4ctl);
19190 	else
19191 		qreply(q, mp4ctl);
19192 
19193 	return (mp2ctl);
19194 }
19195 
19196 /*
19197  * IPv6 mib: One per ill
19198  */
19199 static mblk_t *
19200 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19201 {
19202 	struct opthdr		*optp;
19203 	mblk_t			*mp2ctl;
19204 	ill_t			*ill;
19205 	ill_walk_context_t	ctx;
19206 	mblk_t			*mp_tail = NULL;
19207 
19208 	/*
19209 	 * Make a copy of the original message
19210 	 */
19211 	mp2ctl = copymsg(mpctl);
19212 
19213 	/* fixed length IPv6 structure ... */
19214 
19215 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19216 	optp->level = MIB2_IP6;
19217 	optp->name = 0;
19218 	/* Include "unknown interface" ip6_mib */
19219 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19220 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19221 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19222 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19223 	    ipst->ips_ipv6_forward ? 1 : 2);
19224 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19225 	    ipst->ips_ipv6_def_hops);
19226 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19227 	    sizeof (mib2_ipIfStatsEntry_t));
19228 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19229 	    sizeof (mib2_ipv6AddrEntry_t));
19230 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19231 	    sizeof (mib2_ipv6RouteEntry_t));
19232 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19233 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19234 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19235 	    sizeof (ipv6_member_t));
19236 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19237 	    sizeof (ipv6_grpsrc_t));
19238 
19239 	/*
19240 	 * Synchronize 64- and 32-bit counters
19241 	 */
19242 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19243 	    ipIfStatsHCInReceives);
19244 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19245 	    ipIfStatsHCInDelivers);
19246 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19247 	    ipIfStatsHCOutRequests);
19248 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19249 	    ipIfStatsHCOutForwDatagrams);
19250 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19251 	    ipIfStatsHCOutMcastPkts);
19252 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19253 	    ipIfStatsHCInMcastPkts);
19254 
19255 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19256 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19257 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19258 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19259 	}
19260 
19261 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19262 	ill = ILL_START_WALK_V6(&ctx, ipst);
19263 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19264 		ill->ill_ip_mib->ipIfStatsIfIndex =
19265 		    ill->ill_phyint->phyint_ifindex;
19266 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19267 		    ipst->ips_ipv6_forward ? 1 : 2);
19268 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19269 		    ill->ill_max_hops);
19270 
19271 		/*
19272 		 * Synchronize 64- and 32-bit counters
19273 		 */
19274 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19275 		    ipIfStatsHCInReceives);
19276 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19277 		    ipIfStatsHCInDelivers);
19278 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19279 		    ipIfStatsHCOutRequests);
19280 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19281 		    ipIfStatsHCOutForwDatagrams);
19282 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19283 		    ipIfStatsHCOutMcastPkts);
19284 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19285 		    ipIfStatsHCInMcastPkts);
19286 
19287 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19288 		    (char *)ill->ill_ip_mib,
19289 		    (int)sizeof (*ill->ill_ip_mib))) {
19290 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19291 				"%u bytes\n",
19292 				(uint_t)sizeof (*ill->ill_ip_mib)));
19293 		}
19294 	}
19295 	rw_exit(&ipst->ips_ill_g_lock);
19296 
19297 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19298 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19299 	    (int)optp->level, (int)optp->name, (int)optp->len));
19300 	qreply(q, mpctl);
19301 	return (mp2ctl);
19302 }
19303 
19304 /*
19305  * ICMPv6 mib: One per ill
19306  */
19307 static mblk_t *
19308 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19309 {
19310 	struct opthdr		*optp;
19311 	mblk_t			*mp2ctl;
19312 	ill_t			*ill;
19313 	ill_walk_context_t	ctx;
19314 	mblk_t			*mp_tail = NULL;
19315 	/*
19316 	 * Make a copy of the original message
19317 	 */
19318 	mp2ctl = copymsg(mpctl);
19319 
19320 	/* fixed length ICMPv6 structure ... */
19321 
19322 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19323 	optp->level = MIB2_ICMP6;
19324 	optp->name = 0;
19325 	/* Include "unknown interface" icmp6_mib */
19326 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19327 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19328 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19329 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19330 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19331 	    (char *)&ipst->ips_icmp6_mib,
19332 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19333 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19334 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19335 	}
19336 
19337 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19338 	ill = ILL_START_WALK_V6(&ctx, ipst);
19339 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19340 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19341 		    ill->ill_phyint->phyint_ifindex;
19342 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19343 		    (char *)ill->ill_icmp6_mib,
19344 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19345 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19346 			    "%u bytes\n",
19347 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19348 		}
19349 	}
19350 	rw_exit(&ipst->ips_ill_g_lock);
19351 
19352 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19353 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19354 	    (int)optp->level, (int)optp->name, (int)optp->len));
19355 	qreply(q, mpctl);
19356 	return (mp2ctl);
19357 }
19358 
19359 /*
19360  * ire_walk routine to create both ipRouteEntryTable and
19361  * ipRouteAttributeTable in one IRE walk
19362  */
19363 static void
19364 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19365 {
19366 	ill_t				*ill;
19367 	ipif_t				*ipif;
19368 	mib2_ipRouteEntry_t		*re;
19369 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19370 	ipaddr_t			gw_addr;
19371 	tsol_ire_gw_secattr_t		*attrp;
19372 	tsol_gc_t			*gc = NULL;
19373 	tsol_gcgrp_t			*gcgrp = NULL;
19374 	uint_t				sacnt = 0;
19375 	int				i;
19376 
19377 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19378 
19379 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19380 		return;
19381 
19382 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19383 		mutex_enter(&attrp->igsa_lock);
19384 		if ((gc = attrp->igsa_gc) != NULL) {
19385 			gcgrp = gc->gc_grp;
19386 			ASSERT(gcgrp != NULL);
19387 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19388 			sacnt = 1;
19389 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19390 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19391 			gc = gcgrp->gcgrp_head;
19392 			sacnt = gcgrp->gcgrp_count;
19393 		}
19394 		mutex_exit(&attrp->igsa_lock);
19395 
19396 		/* do nothing if there's no gc to report */
19397 		if (gc == NULL) {
19398 			ASSERT(sacnt == 0);
19399 			if (gcgrp != NULL) {
19400 				/* we might as well drop the lock now */
19401 				rw_exit(&gcgrp->gcgrp_rwlock);
19402 				gcgrp = NULL;
19403 			}
19404 			attrp = NULL;
19405 		}
19406 
19407 		ASSERT(gc == NULL || (gcgrp != NULL &&
19408 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19409 	}
19410 	ASSERT(sacnt == 0 || gc != NULL);
19411 
19412 	if (sacnt != 0 &&
19413 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19414 		kmem_free(re, sizeof (*re));
19415 		rw_exit(&gcgrp->gcgrp_rwlock);
19416 		return;
19417 	}
19418 
19419 	/*
19420 	 * Return all IRE types for route table... let caller pick and choose
19421 	 */
19422 	re->ipRouteDest = ire->ire_addr;
19423 	ipif = ire->ire_ipif;
19424 	re->ipRouteIfIndex.o_length = 0;
19425 	if (ire->ire_type == IRE_CACHE) {
19426 		ill = (ill_t *)ire->ire_stq->q_ptr;
19427 		re->ipRouteIfIndex.o_length =
19428 		    ill->ill_name_length == 0 ? 0 :
19429 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19430 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19431 		    re->ipRouteIfIndex.o_length);
19432 	} else if (ipif != NULL) {
19433 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19434 		    OCTET_LENGTH);
19435 		re->ipRouteIfIndex.o_length =
19436 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19437 	}
19438 	re->ipRouteMetric1 = -1;
19439 	re->ipRouteMetric2 = -1;
19440 	re->ipRouteMetric3 = -1;
19441 	re->ipRouteMetric4 = -1;
19442 
19443 	gw_addr = ire->ire_gateway_addr;
19444 
19445 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19446 		re->ipRouteNextHop = ire->ire_src_addr;
19447 	else
19448 		re->ipRouteNextHop = gw_addr;
19449 	/* indirect(4), direct(3), or invalid(2) */
19450 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19451 		re->ipRouteType = 2;
19452 	else
19453 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19454 	re->ipRouteProto = -1;
19455 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19456 	re->ipRouteMask = ire->ire_mask;
19457 	re->ipRouteMetric5 = -1;
19458 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19459 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19460 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19461 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19462 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19463 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19464 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19465 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19466 	re->ipRouteInfo.re_in_ill.o_length = 0;
19467 
19468 	if (ire->ire_flags & RTF_DYNAMIC) {
19469 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19470 	} else {
19471 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19472 	}
19473 
19474 	if (ire->ire_in_ill != NULL) {
19475 		re->ipRouteInfo.re_in_ill.o_length =
19476 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19477 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19478 		bcopy(ire->ire_in_ill->ill_name,
19479 		    re->ipRouteInfo.re_in_ill.o_bytes,
19480 		    re->ipRouteInfo.re_in_ill.o_length);
19481 	}
19482 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19483 
19484 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19485 	    (char *)re, (int)sizeof (*re))) {
19486 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19487 		    (uint_t)sizeof (*re)));
19488 	}
19489 
19490 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19491 		iaeptr->iae_routeidx = ird->ird_idx;
19492 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19493 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19494 	}
19495 
19496 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19497 	    (char *)iae, sacnt * sizeof (*iae))) {
19498 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19499 		    (unsigned)(sacnt * sizeof (*iae))));
19500 	}
19501 
19502 	/* bump route index for next pass */
19503 	ird->ird_idx++;
19504 
19505 	kmem_free(re, sizeof (*re));
19506 	if (sacnt != 0)
19507 		kmem_free(iae, sacnt * sizeof (*iae));
19508 
19509 	if (gcgrp != NULL)
19510 		rw_exit(&gcgrp->gcgrp_rwlock);
19511 }
19512 
19513 /*
19514  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19515  */
19516 static void
19517 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19518 {
19519 	ill_t				*ill;
19520 	ipif_t				*ipif;
19521 	mib2_ipv6RouteEntry_t		*re;
19522 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19523 	in6_addr_t			gw_addr_v6;
19524 	tsol_ire_gw_secattr_t		*attrp;
19525 	tsol_gc_t			*gc = NULL;
19526 	tsol_gcgrp_t			*gcgrp = NULL;
19527 	uint_t				sacnt = 0;
19528 	int				i;
19529 
19530 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19531 
19532 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19533 		return;
19534 
19535 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19536 		mutex_enter(&attrp->igsa_lock);
19537 		if ((gc = attrp->igsa_gc) != NULL) {
19538 			gcgrp = gc->gc_grp;
19539 			ASSERT(gcgrp != NULL);
19540 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19541 			sacnt = 1;
19542 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19543 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19544 			gc = gcgrp->gcgrp_head;
19545 			sacnt = gcgrp->gcgrp_count;
19546 		}
19547 		mutex_exit(&attrp->igsa_lock);
19548 
19549 		/* do nothing if there's no gc to report */
19550 		if (gc == NULL) {
19551 			ASSERT(sacnt == 0);
19552 			if (gcgrp != NULL) {
19553 				/* we might as well drop the lock now */
19554 				rw_exit(&gcgrp->gcgrp_rwlock);
19555 				gcgrp = NULL;
19556 			}
19557 			attrp = NULL;
19558 		}
19559 
19560 		ASSERT(gc == NULL || (gcgrp != NULL &&
19561 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19562 	}
19563 	ASSERT(sacnt == 0 || gc != NULL);
19564 
19565 	if (sacnt != 0 &&
19566 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19567 		kmem_free(re, sizeof (*re));
19568 		rw_exit(&gcgrp->gcgrp_rwlock);
19569 		return;
19570 	}
19571 
19572 	/*
19573 	 * Return all IRE types for route table... let caller pick and choose
19574 	 */
19575 	re->ipv6RouteDest = ire->ire_addr_v6;
19576 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19577 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19578 	re->ipv6RouteIfIndex.o_length = 0;
19579 	ipif = ire->ire_ipif;
19580 	if (ire->ire_type == IRE_CACHE) {
19581 		ill = (ill_t *)ire->ire_stq->q_ptr;
19582 		re->ipv6RouteIfIndex.o_length =
19583 		    ill->ill_name_length == 0 ? 0 :
19584 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19585 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19586 		    re->ipv6RouteIfIndex.o_length);
19587 	} else if (ipif != NULL) {
19588 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19589 		    OCTET_LENGTH);
19590 		re->ipv6RouteIfIndex.o_length =
19591 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19592 	}
19593 
19594 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19595 
19596 	mutex_enter(&ire->ire_lock);
19597 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19598 	mutex_exit(&ire->ire_lock);
19599 
19600 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19601 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19602 	else
19603 		re->ipv6RouteNextHop = gw_addr_v6;
19604 
19605 	/* remote(4), local(3), or discard(2) */
19606 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19607 		re->ipv6RouteType = 2;
19608 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19609 		re->ipv6RouteType = 3;
19610 	else
19611 		re->ipv6RouteType = 4;
19612 
19613 	re->ipv6RouteProtocol	= -1;
19614 	re->ipv6RoutePolicy	= 0;
19615 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19616 	re->ipv6RouteNextHopRDI	= 0;
19617 	re->ipv6RouteWeight	= 0;
19618 	re->ipv6RouteMetric	= 0;
19619 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19620 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19621 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19622 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19623 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19624 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19625 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19626 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19627 
19628 	if (ire->ire_flags & RTF_DYNAMIC) {
19629 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19630 	} else {
19631 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19632 	}
19633 
19634 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19635 	    (char *)re, (int)sizeof (*re))) {
19636 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19637 		    (uint_t)sizeof (*re)));
19638 	}
19639 
19640 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19641 		iaeptr->iae_routeidx = ird->ird_idx;
19642 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19643 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19644 	}
19645 
19646 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19647 	    (char *)iae, sacnt * sizeof (*iae))) {
19648 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19649 		    (unsigned)(sacnt * sizeof (*iae))));
19650 	}
19651 
19652 	/* bump route index for next pass */
19653 	ird->ird_idx++;
19654 
19655 	kmem_free(re, sizeof (*re));
19656 	if (sacnt != 0)
19657 		kmem_free(iae, sacnt * sizeof (*iae));
19658 
19659 	if (gcgrp != NULL)
19660 		rw_exit(&gcgrp->gcgrp_rwlock);
19661 }
19662 
19663 /*
19664  * ndp_walk routine to create ipv6NetToMediaEntryTable
19665  */
19666 static int
19667 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19668 {
19669 	ill_t				*ill;
19670 	mib2_ipv6NetToMediaEntry_t	ntme;
19671 	dl_unitdata_req_t		*dl;
19672 
19673 	ill = nce->nce_ill;
19674 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19675 		return (0);
19676 
19677 	/*
19678 	 * Neighbor cache entry attached to IRE with on-link
19679 	 * destination.
19680 	 */
19681 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19682 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19683 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19684 	    (nce->nce_res_mp != NULL)) {
19685 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19686 		ntme.ipv6NetToMediaPhysAddress.o_length =
19687 		    dl->dl_dest_addr_length;
19688 	} else {
19689 		ntme.ipv6NetToMediaPhysAddress.o_length =
19690 		    ill->ill_phys_addr_length;
19691 	}
19692 	if (nce->nce_res_mp != NULL) {
19693 		bcopy((char *)nce->nce_res_mp->b_rptr +
19694 		    NCE_LL_ADDR_OFFSET(ill),
19695 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19696 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19697 	} else {
19698 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19699 		    ill->ill_phys_addr_length);
19700 	}
19701 	/*
19702 	 * Note: Returns ND_* states. Should be:
19703 	 * reachable(1), stale(2), delay(3), probe(4),
19704 	 * invalid(5), unknown(6)
19705 	 */
19706 	ntme.ipv6NetToMediaState = nce->nce_state;
19707 	ntme.ipv6NetToMediaLastUpdated = 0;
19708 
19709 	/* other(1), dynamic(2), static(3), local(4) */
19710 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19711 		ntme.ipv6NetToMediaType = 4;
19712 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19713 		ntme.ipv6NetToMediaType = 1;
19714 	} else {
19715 		ntme.ipv6NetToMediaType = 2;
19716 	}
19717 
19718 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19719 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19720 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19721 		    (uint_t)sizeof (ntme)));
19722 	}
19723 	return (0);
19724 }
19725 
19726 /*
19727  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19728  */
19729 /* ARGSUSED */
19730 int
19731 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19732 {
19733 	switch (level) {
19734 	case MIB2_IP:
19735 	case MIB2_ICMP:
19736 		switch (name) {
19737 		default:
19738 			break;
19739 		}
19740 		return (1);
19741 	default:
19742 		return (1);
19743 	}
19744 }
19745 
19746 /*
19747  * When there exists both a 64- and 32-bit counter of a particular type
19748  * (i.e., InReceives), only the 64-bit counters are added.
19749  */
19750 void
19751 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19752 {
19753 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19754 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19755 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19756 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19757 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19758 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19759 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19760 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19761 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19762 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19763 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19764 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19765 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19766 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19767 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19768 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19769 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19770 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19771 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19772 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19773 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19774 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19775 	    o2->ipIfStatsInWrongIPVersion);
19776 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19777 	    o2->ipIfStatsInWrongIPVersion);
19778 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19779 	    o2->ipIfStatsOutSwitchIPVersion);
19780 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19781 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19782 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19783 	    o2->ipIfStatsHCInForwDatagrams);
19784 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19785 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19786 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19787 	    o2->ipIfStatsHCOutForwDatagrams);
19788 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19789 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19790 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19791 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19792 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19793 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19794 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19795 	    o2->ipIfStatsHCOutMcastOctets);
19796 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19797 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19798 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19799 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19800 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19801 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19802 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19803 }
19804 
19805 void
19806 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19807 {
19808 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19809 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19810 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19811 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19812 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19813 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19814 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19815 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19816 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19817 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19818 	    o2->ipv6IfIcmpInRouterSolicits);
19819 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19820 	    o2->ipv6IfIcmpInRouterAdvertisements);
19821 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19822 	    o2->ipv6IfIcmpInNeighborSolicits);
19823 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19824 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19825 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19826 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19827 	    o2->ipv6IfIcmpInGroupMembQueries);
19828 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19829 	    o2->ipv6IfIcmpInGroupMembResponses);
19830 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19831 	    o2->ipv6IfIcmpInGroupMembReductions);
19832 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19833 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19834 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19835 	    o2->ipv6IfIcmpOutDestUnreachs);
19836 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19837 	    o2->ipv6IfIcmpOutAdminProhibs);
19838 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19839 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19840 	    o2->ipv6IfIcmpOutParmProblems);
19841 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19842 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19843 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19844 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19845 	    o2->ipv6IfIcmpOutRouterSolicits);
19846 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19847 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19848 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19849 	    o2->ipv6IfIcmpOutNeighborSolicits);
19850 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19851 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19852 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19853 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19854 	    o2->ipv6IfIcmpOutGroupMembQueries);
19855 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19856 	    o2->ipv6IfIcmpOutGroupMembResponses);
19857 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19858 	    o2->ipv6IfIcmpOutGroupMembReductions);
19859 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19860 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19861 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19862 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19863 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19864 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19865 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19866 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19867 	    o2->ipv6IfIcmpInGroupMembTotal);
19868 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19869 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19870 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19871 	    o2->ipv6IfIcmpInGroupMembBadReports);
19872 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19873 	    o2->ipv6IfIcmpInGroupMembOurReports);
19874 }
19875 
19876 /*
19877  * Called before the options are updated to check if this packet will
19878  * be source routed from here.
19879  * This routine assumes that the options are well formed i.e. that they
19880  * have already been checked.
19881  */
19882 static boolean_t
19883 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19884 {
19885 	ipoptp_t	opts;
19886 	uchar_t		*opt;
19887 	uint8_t		optval;
19888 	uint8_t		optlen;
19889 	ipaddr_t	dst;
19890 	ire_t		*ire;
19891 
19892 	if (IS_SIMPLE_IPH(ipha)) {
19893 		ip2dbg(("not source routed\n"));
19894 		return (B_FALSE);
19895 	}
19896 	dst = ipha->ipha_dst;
19897 	for (optval = ipoptp_first(&opts, ipha);
19898 	    optval != IPOPT_EOL;
19899 	    optval = ipoptp_next(&opts)) {
19900 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19901 		opt = opts.ipoptp_cur;
19902 		optlen = opts.ipoptp_len;
19903 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19904 		    optval, optlen));
19905 		switch (optval) {
19906 			uint32_t off;
19907 		case IPOPT_SSRR:
19908 		case IPOPT_LSRR:
19909 			/*
19910 			 * If dst is one of our addresses and there are some
19911 			 * entries left in the source route return (true).
19912 			 */
19913 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19914 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19915 			if (ire == NULL) {
19916 				ip2dbg(("ip_source_routed: not next"
19917 				    " source route 0x%x\n",
19918 				    ntohl(dst)));
19919 				return (B_FALSE);
19920 			}
19921 			ire_refrele(ire);
19922 			off = opt[IPOPT_OFFSET];
19923 			off--;
19924 			if (optlen < IP_ADDR_LEN ||
19925 			    off > optlen - IP_ADDR_LEN) {
19926 				/* End of source route */
19927 				ip1dbg(("ip_source_routed: end of SR\n"));
19928 				return (B_FALSE);
19929 			}
19930 			return (B_TRUE);
19931 		}
19932 	}
19933 	ip2dbg(("not source routed\n"));
19934 	return (B_FALSE);
19935 }
19936 
19937 /*
19938  * Check if the packet contains any source route.
19939  */
19940 static boolean_t
19941 ip_source_route_included(ipha_t *ipha)
19942 {
19943 	ipoptp_t	opts;
19944 	uint8_t		optval;
19945 
19946 	if (IS_SIMPLE_IPH(ipha))
19947 		return (B_FALSE);
19948 	for (optval = ipoptp_first(&opts, ipha);
19949 	    optval != IPOPT_EOL;
19950 	    optval = ipoptp_next(&opts)) {
19951 		switch (optval) {
19952 		case IPOPT_SSRR:
19953 		case IPOPT_LSRR:
19954 			return (B_TRUE);
19955 		}
19956 	}
19957 	return (B_FALSE);
19958 }
19959 
19960 /*
19961  * Called when the IRE expiration timer fires.
19962  */
19963 void
19964 ip_trash_timer_expire(void *args)
19965 {
19966 	int			flush_flag = 0;
19967 	ire_expire_arg_t	iea;
19968 	ip_stack_t		*ipst = (ip_stack_t *)args;
19969 
19970 	iea.iea_ipst = ipst;	/* No netstack_hold */
19971 
19972 	/*
19973 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19974 	 * This lock makes sure that a new invocation of this function
19975 	 * that occurs due to an almost immediate timer firing will not
19976 	 * progress beyond this point until the current invocation is done
19977 	 */
19978 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19979 	ipst->ips_ip_ire_expire_id = 0;
19980 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19981 
19982 	/* Periodic timer */
19983 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19984 	    ipst->ips_ip_ire_arp_interval) {
19985 		/*
19986 		 * Remove all IRE_CACHE entries since they might
19987 		 * contain arp information.
19988 		 */
19989 		flush_flag |= FLUSH_ARP_TIME;
19990 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19991 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19992 	}
19993 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19994 	    ipst->ips_ip_ire_redir_interval) {
19995 		/* Remove all redirects */
19996 		flush_flag |= FLUSH_REDIRECT_TIME;
19997 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19998 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19999 	}
20000 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
20001 	    ipst->ips_ip_ire_pathmtu_interval) {
20002 		/* Increase path mtu */
20003 		flush_flag |= FLUSH_MTU_TIME;
20004 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20005 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20006 	}
20007 
20008 	/*
20009 	 * Optimize for the case when there are no redirects in the
20010 	 * ftable, that is, no need to walk the ftable in that case.
20011 	 */
20012 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20013 		iea.iea_flush_flag = flush_flag;
20014 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20015 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20016 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20017 		    NULL, ALL_ZONES, ipst);
20018 	}
20019 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20020 	    ipst->ips_ip_redirect_cnt > 0) {
20021 		iea.iea_flush_flag = flush_flag;
20022 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20023 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20024 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20025 	}
20026 	if (flush_flag & FLUSH_MTU_TIME) {
20027 		/*
20028 		 * Walk all IPv6 IRE's and update them
20029 		 * Note that ARP and redirect timers are not
20030 		 * needed since NUD handles stale entries.
20031 		 */
20032 		flush_flag = FLUSH_MTU_TIME;
20033 		iea.iea_flush_flag = flush_flag;
20034 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20035 		    ALL_ZONES, ipst);
20036 	}
20037 
20038 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20039 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20040 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20041 
20042 	/*
20043 	 * Hold the lock to serialize timeout calls and prevent
20044 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20045 	 * for the timer to fire and a new invocation of this function
20046 	 * to start before the return value of timeout has been stored
20047 	 * in ip_ire_expire_id by the current invocation.
20048 	 */
20049 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20050 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20051 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20052 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20053 }
20054 
20055 /*
20056  * Called by the memory allocator subsystem directly, when the system
20057  * is running low on memory.
20058  */
20059 /* ARGSUSED */
20060 void
20061 ip_trash_ire_reclaim(void *args)
20062 {
20063 	netstack_handle_t nh;
20064 	netstack_t *ns;
20065 
20066 	netstack_next_init(&nh);
20067 	while ((ns = netstack_next(&nh)) != NULL) {
20068 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20069 		netstack_rele(ns);
20070 	}
20071 	netstack_next_fini(&nh);
20072 }
20073 
20074 static void
20075 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20076 {
20077 	ire_cache_count_t icc;
20078 	ire_cache_reclaim_t icr;
20079 	ncc_cache_count_t ncc;
20080 	nce_cache_reclaim_t ncr;
20081 	uint_t delete_cnt;
20082 	/*
20083 	 * Memory reclaim call back.
20084 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20085 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20086 	 * entries, determine what fraction to free for
20087 	 * each category of IRE_CACHE entries giving absolute priority
20088 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20089 	 * entry will be freed unless all offlink entries are freed).
20090 	 */
20091 	icc.icc_total = 0;
20092 	icc.icc_unused = 0;
20093 	icc.icc_offlink = 0;
20094 	icc.icc_pmtu = 0;
20095 	icc.icc_onlink = 0;
20096 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20097 
20098 	/*
20099 	 * Free NCEs for IPv6 like the onlink ires.
20100 	 */
20101 	ncc.ncc_total = 0;
20102 	ncc.ncc_host = 0;
20103 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20104 
20105 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20106 	    icc.icc_pmtu + icc.icc_onlink);
20107 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20108 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20109 	if (delete_cnt == 0)
20110 		return;
20111 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20112 	/* Always delete all unused offlink entries */
20113 	icr.icr_ipst = ipst;
20114 	icr.icr_unused = 1;
20115 	if (delete_cnt <= icc.icc_unused) {
20116 		/*
20117 		 * Only need to free unused entries.  In other words,
20118 		 * there are enough unused entries to free to meet our
20119 		 * target number of freed ire cache entries.
20120 		 */
20121 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20122 		ncr.ncr_host = 0;
20123 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20124 		/*
20125 		 * Only need to free unused entries, plus a fraction of offlink
20126 		 * entries.  It follows from the first if statement that
20127 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20128 		 */
20129 		delete_cnt -= icc.icc_unused;
20130 		/* Round up # deleted by truncating fraction */
20131 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20132 		icr.icr_pmtu = icr.icr_onlink = 0;
20133 		ncr.ncr_host = 0;
20134 	} else if (delete_cnt <=
20135 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20136 		/*
20137 		 * Free all unused and offlink entries, plus a fraction of
20138 		 * pmtu entries.  It follows from the previous if statement
20139 		 * that icc_pmtu is non-zero, and that
20140 		 * delete_cnt != icc_unused + icc_offlink.
20141 		 */
20142 		icr.icr_offlink = 1;
20143 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20144 		/* Round up # deleted by truncating fraction */
20145 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20146 		icr.icr_onlink = 0;
20147 		ncr.ncr_host = 0;
20148 	} else {
20149 		/*
20150 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20151 		 * of onlink entries.  If we're here, then we know that
20152 		 * icc_onlink is non-zero, and that
20153 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20154 		 */
20155 		icr.icr_offlink = icr.icr_pmtu = 1;
20156 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20157 		    icc.icc_pmtu;
20158 		/* Round up # deleted by truncating fraction */
20159 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20160 		/* Using the same delete fraction as for onlink IREs */
20161 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20162 	}
20163 #ifdef DEBUG
20164 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20165 	    "fractions %d/%d/%d/%d\n",
20166 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20167 	    icc.icc_unused, icc.icc_offlink,
20168 	    icc.icc_pmtu, icc.icc_onlink,
20169 	    icr.icr_unused, icr.icr_offlink,
20170 	    icr.icr_pmtu, icr.icr_onlink));
20171 #endif
20172 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20173 	if (ncr.ncr_host != 0)
20174 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20175 		    (uchar_t *)&ncr, ipst);
20176 #ifdef DEBUG
20177 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20178 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20179 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20180 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20181 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20182 	    icc.icc_pmtu, icc.icc_onlink));
20183 #endif
20184 }
20185 
20186 /*
20187  * ip_unbind is called when a copy of an unbind request is received from the
20188  * upper level protocol.  We remove this conn from any fanout hash list it is
20189  * on, and zero out the bind information.  No reply is expected up above.
20190  */
20191 mblk_t *
20192 ip_unbind(queue_t *q, mblk_t *mp)
20193 {
20194 	conn_t	*connp = Q_TO_CONN(q);
20195 
20196 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20197 
20198 	if (is_system_labeled() && connp->conn_anon_port) {
20199 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20200 		    connp->conn_mlp_type, connp->conn_ulp,
20201 		    ntohs(connp->conn_lport), B_FALSE);
20202 		connp->conn_anon_port = 0;
20203 	}
20204 	connp->conn_mlp_type = mlptSingle;
20205 
20206 	ipcl_hash_remove(connp);
20207 
20208 	ASSERT(mp->b_cont == NULL);
20209 	/*
20210 	 * Convert mp into a T_OK_ACK
20211 	 */
20212 	mp = mi_tpi_ok_ack_alloc(mp);
20213 
20214 	/*
20215 	 * should not happen in practice... T_OK_ACK is smaller than the
20216 	 * original message.
20217 	 */
20218 	if (mp == NULL)
20219 		return (NULL);
20220 
20221 	/*
20222 	 * Don't bzero the ports if its TCP since TCP still needs the
20223 	 * lport to remove it from its own bind hash. TCP will do the
20224 	 * cleanup.
20225 	 */
20226 	if (!IPCL_IS_TCP(connp))
20227 		bzero(&connp->u_port, sizeof (connp->u_port));
20228 
20229 	return (mp);
20230 }
20231 
20232 /*
20233  * Write side put procedure.  Outbound data, IOCTLs, responses from
20234  * resolvers, etc, come down through here.
20235  *
20236  * arg2 is always a queue_t *.
20237  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20238  * the zoneid.
20239  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20240  */
20241 void
20242 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20243 {
20244 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20245 }
20246 
20247 void
20248 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20249     ip_opt_info_t *infop)
20250 {
20251 	conn_t		*connp = NULL;
20252 	queue_t		*q = (queue_t *)arg2;
20253 	ipha_t		*ipha;
20254 #define	rptr	((uchar_t *)ipha)
20255 	ire_t		*ire = NULL;
20256 	ire_t		*sctp_ire = NULL;
20257 	uint32_t	v_hlen_tos_len;
20258 	ipaddr_t	dst;
20259 	mblk_t		*first_mp = NULL;
20260 	boolean_t	mctl_present;
20261 	ipsec_out_t	*io;
20262 	int		match_flags;
20263 	ill_t		*attach_ill = NULL;
20264 					/* Bind to IPIF_NOFAILOVER ill etc. */
20265 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20266 	ipif_t		*dst_ipif;
20267 	boolean_t	multirt_need_resolve = B_FALSE;
20268 	mblk_t		*copy_mp = NULL;
20269 	int		err;
20270 	zoneid_t	zoneid;
20271 	int	adjust;
20272 	uint16_t iplen;
20273 	boolean_t	need_decref = B_FALSE;
20274 	boolean_t	ignore_dontroute = B_FALSE;
20275 	boolean_t	ignore_nexthop = B_FALSE;
20276 	boolean_t	ip_nexthop = B_FALSE;
20277 	ipaddr_t	nexthop_addr;
20278 	ip_stack_t	*ipst;
20279 
20280 #ifdef	_BIG_ENDIAN
20281 #define	V_HLEN	(v_hlen_tos_len >> 24)
20282 #else
20283 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20284 #endif
20285 
20286 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20287 	    "ip_wput_start: q %p", q);
20288 
20289 	/*
20290 	 * ip_wput fast path
20291 	 */
20292 
20293 	/* is packet from ARP ? */
20294 	if (q->q_next != NULL) {
20295 		zoneid = (zoneid_t)(uintptr_t)arg;
20296 		goto qnext;
20297 	}
20298 
20299 	connp = (conn_t *)arg;
20300 	ASSERT(connp != NULL);
20301 	zoneid = connp->conn_zoneid;
20302 	ipst = connp->conn_netstack->netstack_ip;
20303 
20304 	/* is queue flow controlled? */
20305 	if ((q->q_first != NULL || connp->conn_draining) &&
20306 	    (caller == IP_WPUT)) {
20307 		ASSERT(!need_decref);
20308 		(void) putq(q, mp);
20309 		return;
20310 	}
20311 
20312 	/* Multidata transmit? */
20313 	if (DB_TYPE(mp) == M_MULTIDATA) {
20314 		/*
20315 		 * We should never get here, since all Multidata messages
20316 		 * originating from tcp should have been directed over to
20317 		 * tcp_multisend() in the first place.
20318 		 */
20319 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20320 		freemsg(mp);
20321 		return;
20322 	} else if (DB_TYPE(mp) != M_DATA)
20323 		goto notdata;
20324 
20325 	if (mp->b_flag & MSGHASREF) {
20326 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20327 		mp->b_flag &= ~MSGHASREF;
20328 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20329 		need_decref = B_TRUE;
20330 	}
20331 	ipha = (ipha_t *)mp->b_rptr;
20332 
20333 	/* is IP header non-aligned or mblk smaller than basic IP header */
20334 #ifndef SAFETY_BEFORE_SPEED
20335 	if (!OK_32PTR(rptr) ||
20336 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20337 		goto hdrtoosmall;
20338 #endif
20339 
20340 	ASSERT(OK_32PTR(ipha));
20341 
20342 	/*
20343 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20344 	 * wrong version, we'll catch it again in ip_output_v6.
20345 	 *
20346 	 * Note that this is *only* locally-generated output here, and never
20347 	 * forwarded data, and that we need to deal only with transports that
20348 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20349 	 * label.)
20350 	 */
20351 	if (is_system_labeled() &&
20352 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20353 	    !connp->conn_ulp_labeled) {
20354 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20355 		    connp->conn_mac_exempt, ipst);
20356 		ipha = (ipha_t *)mp->b_rptr;
20357 		if (err != 0) {
20358 			first_mp = mp;
20359 			if (err == EINVAL)
20360 				goto icmp_parameter_problem;
20361 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20362 			goto discard_pkt;
20363 		}
20364 		iplen = ntohs(ipha->ipha_length) + adjust;
20365 		ipha->ipha_length = htons(iplen);
20366 	}
20367 
20368 	ASSERT(infop != NULL);
20369 
20370 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20371 		/*
20372 		 * IP_PKTINFO ancillary option is present.
20373 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20374 		 * allows using address of any zone as the source address.
20375 		 */
20376 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20377 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20378 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20379 		if (ire == NULL)
20380 			goto drop_pkt;
20381 		ire_refrele(ire);
20382 		ire = NULL;
20383 	}
20384 
20385 	/*
20386 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20387 	 * ill index passed in IP_PKTINFO.
20388 	 */
20389 	if (infop->ip_opt_ill_index != 0 &&
20390 	    connp->conn_xmit_if_ill == NULL &&
20391 	    connp->conn_nofailover_ill == NULL) {
20392 
20393 		xmit_ill = ill_lookup_on_ifindex(
20394 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20395 		    ipst);
20396 
20397 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20398 			goto drop_pkt;
20399 		/*
20400 		 * check that there is an ipif belonging
20401 		 * to our zone. IPCL_ZONEID is not used because
20402 		 * IP_ALLZONES option is valid only when the ill is
20403 		 * accessible from all zones i.e has a valid ipif in
20404 		 * all zones.
20405 		 */
20406 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20407 			goto drop_pkt;
20408 		}
20409 	}
20410 
20411 	/*
20412 	 * If there is a policy, try to attach an ipsec_out in
20413 	 * the front. At the end, first_mp either points to a
20414 	 * M_DATA message or IPSEC_OUT message linked to a
20415 	 * M_DATA message. We have to do it now as we might
20416 	 * lose the "conn" if we go through ip_newroute.
20417 	 */
20418 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20419 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20420 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20421 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20422 			if (need_decref)
20423 				CONN_DEC_REF(connp);
20424 			return;
20425 		} else {
20426 			ASSERT(mp->b_datap->db_type == M_CTL);
20427 			first_mp = mp;
20428 			mp = mp->b_cont;
20429 			mctl_present = B_TRUE;
20430 		}
20431 	} else {
20432 		first_mp = mp;
20433 		mctl_present = B_FALSE;
20434 	}
20435 
20436 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20437 
20438 	/* is wrong version or IP options present */
20439 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20440 		goto version_hdrlen_check;
20441 	dst = ipha->ipha_dst;
20442 
20443 	if (connp->conn_nofailover_ill != NULL) {
20444 		attach_ill = conn_get_held_ill(connp,
20445 		    &connp->conn_nofailover_ill, &err);
20446 		if (err == ILL_LOOKUP_FAILED) {
20447 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20448 			if (need_decref)
20449 				CONN_DEC_REF(connp);
20450 			freemsg(first_mp);
20451 			return;
20452 		}
20453 	}
20454 
20455 
20456 	/* is packet multicast? */
20457 	if (CLASSD(dst))
20458 		goto multicast;
20459 
20460 	/*
20461 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20462 	 * takes precedence over conn_dontroute and conn_nexthop_set
20463 	 */
20464 	if (xmit_ill != NULL) {
20465 		goto send_from_ill;
20466 	}
20467 
20468 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20469 	    (connp->conn_nexthop_set)) {
20470 		/*
20471 		 * If the destination is a broadcast or a loopback
20472 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20473 		 * through the standard path. But in the case of local
20474 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20475 		 * the standard path not IP_XMIT_IF.
20476 		 */
20477 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20478 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20479 		    (ire->ire_type != IRE_LOOPBACK))) {
20480 			if ((connp->conn_dontroute ||
20481 			    connp->conn_nexthop_set) && (ire != NULL) &&
20482 			    (ire->ire_type == IRE_LOCAL))
20483 				goto standard_path;
20484 
20485 			if (ire != NULL) {
20486 				ire_refrele(ire);
20487 				/* No more access to ire */
20488 				ire = NULL;
20489 			}
20490 			/*
20491 			 * bypass routing checks and go directly to
20492 			 * interface.
20493 			 */
20494 			if (connp->conn_dontroute) {
20495 				goto dontroute;
20496 			} else if (connp->conn_nexthop_set) {
20497 				ip_nexthop = B_TRUE;
20498 				nexthop_addr = connp->conn_nexthop_v4;
20499 				goto send_from_ill;
20500 			}
20501 
20502 			/*
20503 			 * If IP_XMIT_IF socket option is set,
20504 			 * then we allow unicast and multicast
20505 			 * packets to go through the ill. It is
20506 			 * quite possible that the destination
20507 			 * is not in the ire cache table and we
20508 			 * do not want to go to ip_newroute()
20509 			 * instead we call ip_newroute_ipif.
20510 			 */
20511 			xmit_ill = conn_get_held_ill(connp,
20512 			    &connp->conn_xmit_if_ill, &err);
20513 			if (err == ILL_LOOKUP_FAILED) {
20514 				BUMP_MIB(&ipst->ips_ip_mib,
20515 				    ipIfStatsOutDiscards);
20516 				if (attach_ill != NULL)
20517 					ill_refrele(attach_ill);
20518 				if (need_decref)
20519 					CONN_DEC_REF(connp);
20520 				freemsg(first_mp);
20521 				return;
20522 			}
20523 			goto send_from_ill;
20524 		}
20525 standard_path:
20526 		/* Must be a broadcast, a loopback or a local ire */
20527 		if (ire != NULL) {
20528 			ire_refrele(ire);
20529 			/* No more access to ire */
20530 			ire = NULL;
20531 		}
20532 	}
20533 
20534 	if (attach_ill != NULL)
20535 		goto send_from_ill;
20536 
20537 	/*
20538 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20539 	 * this for the tcp global queue and listen end point
20540 	 * as it does not really have a real destination to
20541 	 * talk to.  This is also true for SCTP.
20542 	 */
20543 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20544 	    !connp->conn_fully_bound) {
20545 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20546 		if (ire == NULL)
20547 			goto noirefound;
20548 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20549 		    "ip_wput_end: q %p (%S)", q, "end");
20550 
20551 		/*
20552 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20553 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20554 		 */
20555 		if (ire->ire_flags & RTF_MULTIRT) {
20556 
20557 			/*
20558 			 * Force the TTL of multirouted packets if required.
20559 			 * The TTL of such packets is bounded by the
20560 			 * ip_multirt_ttl ndd variable.
20561 			 */
20562 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20563 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20564 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20565 				    "(was %d), dst 0x%08x\n",
20566 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20567 				    ntohl(ire->ire_addr)));
20568 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20569 			}
20570 			/*
20571 			 * We look at this point if there are pending
20572 			 * unresolved routes. ire_multirt_resolvable()
20573 			 * checks in O(n) that all IRE_OFFSUBNET ire
20574 			 * entries for the packet's destination and
20575 			 * flagged RTF_MULTIRT are currently resolved.
20576 			 * If some remain unresolved, we make a copy
20577 			 * of the current message. It will be used
20578 			 * to initiate additional route resolutions.
20579 			 */
20580 			multirt_need_resolve =
20581 			    ire_multirt_need_resolve(ire->ire_addr,
20582 			    MBLK_GETLABEL(first_mp), ipst);
20583 			ip2dbg(("ip_wput[TCP]: ire %p, "
20584 			    "multirt_need_resolve %d, first_mp %p\n",
20585 			    (void *)ire, multirt_need_resolve,
20586 			    (void *)first_mp));
20587 			if (multirt_need_resolve) {
20588 				copy_mp = copymsg(first_mp);
20589 				if (copy_mp != NULL) {
20590 					MULTIRT_DEBUG_TAG(copy_mp);
20591 				}
20592 			}
20593 		}
20594 
20595 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20596 
20597 		/*
20598 		 * Try to resolve another multiroute if
20599 		 * ire_multirt_need_resolve() deemed it necessary.
20600 		 */
20601 		if (copy_mp != NULL) {
20602 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20603 		}
20604 		if (need_decref)
20605 			CONN_DEC_REF(connp);
20606 		return;
20607 	}
20608 
20609 	/*
20610 	 * Access to conn_ire_cache. (protected by conn_lock)
20611 	 *
20612 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20613 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20614 	 * send a packet or two with the IRE_CACHE that is going away.
20615 	 * Access to the ire requires an ire refhold on the ire prior to
20616 	 * its use since an interface unplumb thread may delete the cached
20617 	 * ire and release the refhold at any time.
20618 	 *
20619 	 * Caching an ire in the conn_ire_cache
20620 	 *
20621 	 * o Caching an ire pointer in the conn requires a strict check for
20622 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20623 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20624 	 * in the conn is done after making sure under the bucket lock that the
20625 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20626 	 * caching an ire after the unplumb thread has cleaned up the conn.
20627 	 * If the conn does not send a packet subsequently the unplumb thread
20628 	 * will be hanging waiting for the ire count to drop to zero.
20629 	 *
20630 	 * o We also need to atomically test for a null conn_ire_cache and
20631 	 * set the conn_ire_cache under the the protection of the conn_lock
20632 	 * to avoid races among concurrent threads trying to simultaneously
20633 	 * cache an ire in the conn_ire_cache.
20634 	 */
20635 	mutex_enter(&connp->conn_lock);
20636 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20637 
20638 	if (ire != NULL && ire->ire_addr == dst &&
20639 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20640 
20641 		IRE_REFHOLD(ire);
20642 		mutex_exit(&connp->conn_lock);
20643 
20644 	} else {
20645 		boolean_t cached = B_FALSE;
20646 		connp->conn_ire_cache = NULL;
20647 		mutex_exit(&connp->conn_lock);
20648 		/* Release the old ire */
20649 		if (ire != NULL && sctp_ire == NULL)
20650 			IRE_REFRELE_NOTR(ire);
20651 
20652 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20653 		if (ire == NULL)
20654 			goto noirefound;
20655 		IRE_REFHOLD_NOTR(ire);
20656 
20657 		mutex_enter(&connp->conn_lock);
20658 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20659 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20660 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20661 				if (connp->conn_ulp == IPPROTO_TCP)
20662 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20663 				connp->conn_ire_cache = ire;
20664 				cached = B_TRUE;
20665 			}
20666 			rw_exit(&ire->ire_bucket->irb_lock);
20667 		}
20668 		mutex_exit(&connp->conn_lock);
20669 
20670 		/*
20671 		 * We can continue to use the ire but since it was
20672 		 * not cached, we should drop the extra reference.
20673 		 */
20674 		if (!cached)
20675 			IRE_REFRELE_NOTR(ire);
20676 	}
20677 
20678 
20679 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20680 	    "ip_wput_end: q %p (%S)", q, "end");
20681 
20682 	/*
20683 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20684 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20685 	 */
20686 	if (ire->ire_flags & RTF_MULTIRT) {
20687 
20688 		/*
20689 		 * Force the TTL of multirouted packets if required.
20690 		 * The TTL of such packets is bounded by the
20691 		 * ip_multirt_ttl ndd variable.
20692 		 */
20693 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20694 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20695 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20696 			    "(was %d), dst 0x%08x\n",
20697 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20698 			    ntohl(ire->ire_addr)));
20699 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20700 		}
20701 
20702 		/*
20703 		 * At this point, we check to see if there are any pending
20704 		 * unresolved routes. ire_multirt_resolvable()
20705 		 * checks in O(n) that all IRE_OFFSUBNET ire
20706 		 * entries for the packet's destination and
20707 		 * flagged RTF_MULTIRT are currently resolved.
20708 		 * If some remain unresolved, we make a copy
20709 		 * of the current message. It will be used
20710 		 * to initiate additional route resolutions.
20711 		 */
20712 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20713 		    MBLK_GETLABEL(first_mp), ipst);
20714 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20715 		    "multirt_need_resolve %d, first_mp %p\n",
20716 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20717 		if (multirt_need_resolve) {
20718 			copy_mp = copymsg(first_mp);
20719 			if (copy_mp != NULL) {
20720 				MULTIRT_DEBUG_TAG(copy_mp);
20721 			}
20722 		}
20723 	}
20724 
20725 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20726 
20727 	/*
20728 	 * Try to resolve another multiroute if
20729 	 * ire_multirt_resolvable() deemed it necessary
20730 	 */
20731 	if (copy_mp != NULL) {
20732 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20733 	}
20734 	if (need_decref)
20735 		CONN_DEC_REF(connp);
20736 	return;
20737 
20738 qnext:
20739 	/*
20740 	 * Upper Level Protocols pass down complete IP datagrams
20741 	 * as M_DATA messages.	Everything else is a sideshow.
20742 	 *
20743 	 * 1) We could be re-entering ip_wput because of ip_neworute
20744 	 *    in which case we could have a IPSEC_OUT message. We
20745 	 *    need to pass through ip_wput like other datagrams and
20746 	 *    hence cannot branch to ip_wput_nondata.
20747 	 *
20748 	 * 2) ARP, AH, ESP, and other clients who are on the module
20749 	 *    instance of IP stream, give us something to deal with.
20750 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20751 	 *
20752 	 * 3) ICMP replies also could come here.
20753 	 */
20754 	ipst = ILLQ_TO_IPST(q);
20755 
20756 	if (DB_TYPE(mp) != M_DATA) {
20757 	    notdata:
20758 		if (DB_TYPE(mp) == M_CTL) {
20759 			/*
20760 			 * M_CTL messages are used by ARP, AH and ESP to
20761 			 * communicate with IP. We deal with IPSEC_IN and
20762 			 * IPSEC_OUT here. ip_wput_nondata handles other
20763 			 * cases.
20764 			 */
20765 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20766 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20767 				first_mp = mp->b_cont;
20768 				first_mp->b_flag &= ~MSGHASREF;
20769 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20770 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20771 				CONN_DEC_REF(connp);
20772 				connp = NULL;
20773 			}
20774 			if (ii->ipsec_info_type == IPSEC_IN) {
20775 				/*
20776 				 * Either this message goes back to
20777 				 * IPSEC for further processing or to
20778 				 * ULP after policy checks.
20779 				 */
20780 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20781 				return;
20782 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20783 				io = (ipsec_out_t *)ii;
20784 				if (io->ipsec_out_proc_begin) {
20785 					/*
20786 					 * IPSEC processing has already started.
20787 					 * Complete it.
20788 					 * IPQoS notes: We don't care what is
20789 					 * in ipsec_out_ill_index since this
20790 					 * won't be processed for IPQoS policies
20791 					 * in ipsec_out_process.
20792 					 */
20793 					ipsec_out_process(q, mp, NULL,
20794 					    io->ipsec_out_ill_index);
20795 					return;
20796 				} else {
20797 					connp = (q->q_next != NULL) ?
20798 					    NULL : Q_TO_CONN(q);
20799 					first_mp = mp;
20800 					mp = mp->b_cont;
20801 					mctl_present = B_TRUE;
20802 				}
20803 				zoneid = io->ipsec_out_zoneid;
20804 				ASSERT(zoneid != ALL_ZONES);
20805 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20806 				/*
20807 				 * It's an IPsec control message requesting
20808 				 * an SADB update to be sent to the IPsec
20809 				 * hardware acceleration capable ills.
20810 				 */
20811 				ipsec_ctl_t *ipsec_ctl =
20812 				    (ipsec_ctl_t *)mp->b_rptr;
20813 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20814 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20815 				mblk_t *cmp = mp->b_cont;
20816 
20817 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20818 				ASSERT(cmp != NULL);
20819 
20820 				freeb(mp);
20821 				ill_ipsec_capab_send_all(satype, cmp, sa,
20822 				    ipst->ips_netstack);
20823 				return;
20824 			} else {
20825 				/*
20826 				 * This must be ARP or special TSOL signaling.
20827 				 */
20828 				ip_wput_nondata(NULL, q, mp, NULL);
20829 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20830 				    "ip_wput_end: q %p (%S)", q, "nondata");
20831 				return;
20832 			}
20833 		} else {
20834 			/*
20835 			 * This must be non-(ARP/AH/ESP) messages.
20836 			 */
20837 			ASSERT(!need_decref);
20838 			ip_wput_nondata(NULL, q, mp, NULL);
20839 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20840 			    "ip_wput_end: q %p (%S)", q, "nondata");
20841 			return;
20842 		}
20843 	} else {
20844 		first_mp = mp;
20845 		mctl_present = B_FALSE;
20846 	}
20847 
20848 	ASSERT(first_mp != NULL);
20849 	/*
20850 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20851 	 * to make sure that this packet goes out on the same interface it
20852 	 * came in. We handle that here.
20853 	 */
20854 	if (mctl_present) {
20855 		uint_t ifindex;
20856 
20857 		io = (ipsec_out_t *)first_mp->b_rptr;
20858 		if (io->ipsec_out_attach_if ||
20859 		    io->ipsec_out_xmit_if ||
20860 		    io->ipsec_out_ip_nexthop) {
20861 			ill_t	*ill;
20862 
20863 			/*
20864 			 * We may have lost the conn context if we are
20865 			 * coming here from ip_newroute(). Copy the
20866 			 * nexthop information.
20867 			 */
20868 			if (io->ipsec_out_ip_nexthop) {
20869 				ip_nexthop = B_TRUE;
20870 				nexthop_addr = io->ipsec_out_nexthop_addr;
20871 
20872 				ipha = (ipha_t *)mp->b_rptr;
20873 				dst = ipha->ipha_dst;
20874 				goto send_from_ill;
20875 			} else {
20876 				ASSERT(io->ipsec_out_ill_index != 0);
20877 				ifindex = io->ipsec_out_ill_index;
20878 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20879 				    NULL, NULL, NULL, NULL, ipst);
20880 				/*
20881 				 * ipsec_out_xmit_if bit is used to tell
20882 				 * ip_wput to use the ill to send outgoing data
20883 				 * as we have no conn when data comes from ICMP
20884 				 * error msg routines. Currently this feature is
20885 				 * only used by ip_mrtun_forward routine.
20886 				 */
20887 				if (io->ipsec_out_xmit_if) {
20888 					xmit_ill = ill;
20889 					if (xmit_ill == NULL) {
20890 						ip1dbg(("ip_output:bad ifindex "
20891 						    "for xmit_ill %d\n",
20892 						    ifindex));
20893 						freemsg(first_mp);
20894 						BUMP_MIB(&ipst->ips_ip_mib,
20895 						    ipIfStatsOutDiscards);
20896 						ASSERT(!need_decref);
20897 						return;
20898 					}
20899 					/* Free up the ipsec_out_t mblk */
20900 					ASSERT(first_mp->b_cont == mp);
20901 					first_mp->b_cont = NULL;
20902 					freeb(first_mp);
20903 					/* Just send the IP header+ICMP+data */
20904 					first_mp = mp;
20905 					ipha = (ipha_t *)mp->b_rptr;
20906 					dst = ipha->ipha_dst;
20907 					goto send_from_ill;
20908 				} else {
20909 					attach_ill = ill;
20910 				}
20911 
20912 				if (attach_ill == NULL) {
20913 					ASSERT(xmit_ill == NULL);
20914 					ip1dbg(("ip_output: bad ifindex for "
20915 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20916 					    ifindex));
20917 					freemsg(first_mp);
20918 					BUMP_MIB(&ipst->ips_ip_mib,
20919 					    ipIfStatsOutDiscards);
20920 					ASSERT(!need_decref);
20921 					return;
20922 				}
20923 			}
20924 		}
20925 	}
20926 
20927 	ASSERT(xmit_ill == NULL);
20928 
20929 	/* We have a complete IP datagram heading outbound. */
20930 	ipha = (ipha_t *)mp->b_rptr;
20931 
20932 #ifndef SPEED_BEFORE_SAFETY
20933 	/*
20934 	 * Make sure we have a full-word aligned message and that at least
20935 	 * a simple IP header is accessible in the first message.  If not,
20936 	 * try a pullup.
20937 	 */
20938 	if (!OK_32PTR(rptr) ||
20939 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20940 	    hdrtoosmall:
20941 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20942 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20943 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20944 			if (first_mp == NULL)
20945 				first_mp = mp;
20946 			goto discard_pkt;
20947 		}
20948 
20949 		/* This function assumes that mp points to an IPv4 packet. */
20950 		if (is_system_labeled() && q->q_next == NULL &&
20951 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20952 		    !connp->conn_ulp_labeled) {
20953 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20954 			    &adjust, connp->conn_mac_exempt, ipst);
20955 			ipha = (ipha_t *)mp->b_rptr;
20956 			if (first_mp != NULL)
20957 				first_mp->b_cont = mp;
20958 			if (err != 0) {
20959 				if (first_mp == NULL)
20960 					first_mp = mp;
20961 				if (err == EINVAL)
20962 					goto icmp_parameter_problem;
20963 				ip2dbg(("ip_wput: label check failed (%d)\n",
20964 				    err));
20965 				goto discard_pkt;
20966 			}
20967 			iplen = ntohs(ipha->ipha_length) + adjust;
20968 			ipha->ipha_length = htons(iplen);
20969 		}
20970 
20971 		ipha = (ipha_t *)mp->b_rptr;
20972 		if (first_mp == NULL) {
20973 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20974 			/*
20975 			 * If we got here because of "goto hdrtoosmall"
20976 			 * We need to attach a IPSEC_OUT.
20977 			 */
20978 			if (connp->conn_out_enforce_policy) {
20979 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20980 				    NULL, ipha->ipha_protocol,
20981 				    ipst->ips_netstack)) == NULL)) {
20982 					BUMP_MIB(&ipst->ips_ip_mib,
20983 					    ipIfStatsOutDiscards);
20984 					if (need_decref)
20985 						CONN_DEC_REF(connp);
20986 					return;
20987 				} else {
20988 					ASSERT(mp->b_datap->db_type == M_CTL);
20989 					first_mp = mp;
20990 					mp = mp->b_cont;
20991 					mctl_present = B_TRUE;
20992 				}
20993 			} else {
20994 				first_mp = mp;
20995 				mctl_present = B_FALSE;
20996 			}
20997 		}
20998 	}
20999 #endif
21000 
21001 	/* Most of the code below is written for speed, not readability */
21002 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21003 
21004 	/*
21005 	 * If ip_newroute() fails, we're going to need a full
21006 	 * header for the icmp wraparound.
21007 	 */
21008 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21009 		uint_t	v_hlen;
21010 	    version_hdrlen_check:
21011 		ASSERT(first_mp != NULL);
21012 		v_hlen = V_HLEN;
21013 		/*
21014 		 * siphon off IPv6 packets coming down from transport
21015 		 * layer modules here.
21016 		 * Note: high-order bit carries NUD reachability confirmation
21017 		 */
21018 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21019 			/*
21020 			 * XXX implement a IPv4 and IPv6 packet counter per
21021 			 * conn and switch when ratio exceeds e.g. 10:1
21022 			 */
21023 #ifdef notyet
21024 			if (q->q_next == NULL) /* Avoid ill queue */
21025 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21026 #endif
21027 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21028 			ASSERT(xmit_ill == NULL);
21029 			if (attach_ill != NULL)
21030 				ill_refrele(attach_ill);
21031 			if (need_decref)
21032 				mp->b_flag |= MSGHASREF;
21033 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21034 			return;
21035 		}
21036 
21037 		if ((v_hlen >> 4) != IP_VERSION) {
21038 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21039 			    "ip_wput_end: q %p (%S)", q, "badvers");
21040 			goto discard_pkt;
21041 		}
21042 		/*
21043 		 * Is the header length at least 20 bytes?
21044 		 *
21045 		 * Are there enough bytes accessible in the header?  If
21046 		 * not, try a pullup.
21047 		 */
21048 		v_hlen &= 0xF;
21049 		v_hlen <<= 2;
21050 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21051 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21052 			    "ip_wput_end: q %p (%S)", q, "badlen");
21053 			goto discard_pkt;
21054 		}
21055 		if (v_hlen > (mp->b_wptr - rptr)) {
21056 			if (!pullupmsg(mp, v_hlen)) {
21057 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21058 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21059 				goto discard_pkt;
21060 			}
21061 			ipha = (ipha_t *)mp->b_rptr;
21062 		}
21063 		/*
21064 		 * Move first entry from any source route into ipha_dst and
21065 		 * verify the options
21066 		 */
21067 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21068 			zoneid, ipst)) {
21069 			ASSERT(xmit_ill == NULL);
21070 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21071 			if (attach_ill != NULL)
21072 				ill_refrele(attach_ill);
21073 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21074 			    "ip_wput_end: q %p (%S)", q, "badopts");
21075 			if (need_decref)
21076 				CONN_DEC_REF(connp);
21077 			return;
21078 		}
21079 	}
21080 	dst = ipha->ipha_dst;
21081 
21082 	/*
21083 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21084 	 * we have to run the packet through ip_newroute which will take
21085 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21086 	 * a resolver, or assigning a default gateway, etc.
21087 	 */
21088 	if (CLASSD(dst)) {
21089 		ipif_t	*ipif;
21090 		uint32_t setsrc = 0;
21091 
21092 	    multicast:
21093 		ASSERT(first_mp != NULL);
21094 		ip2dbg(("ip_wput: CLASSD\n"));
21095 		if (connp == NULL) {
21096 			/*
21097 			 * Use the first good ipif on the ill.
21098 			 * XXX Should this ever happen? (Appears
21099 			 * to show up with just ppp and no ethernet due
21100 			 * to in.rdisc.)
21101 			 * However, ire_send should be able to
21102 			 * call ip_wput_ire directly.
21103 			 *
21104 			 * XXX Also, this can happen for ICMP and other packets
21105 			 * with multicast source addresses.  Perhaps we should
21106 			 * fix things so that we drop the packet in question,
21107 			 * but for now, just run with it.
21108 			 */
21109 			ill_t *ill = (ill_t *)q->q_ptr;
21110 
21111 			/*
21112 			 * Don't honor attach_if for this case. If ill
21113 			 * is part of the group, ipif could belong to
21114 			 * any ill and we cannot maintain attach_ill
21115 			 * and ipif_ill same anymore and the assert
21116 			 * below would fail.
21117 			 */
21118 			if (mctl_present && io->ipsec_out_attach_if) {
21119 				io->ipsec_out_ill_index = 0;
21120 				io->ipsec_out_attach_if = B_FALSE;
21121 				ASSERT(attach_ill != NULL);
21122 				ill_refrele(attach_ill);
21123 				attach_ill = NULL;
21124 			}
21125 
21126 			ASSERT(attach_ill == NULL);
21127 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21128 			if (ipif == NULL) {
21129 				if (need_decref)
21130 					CONN_DEC_REF(connp);
21131 				freemsg(first_mp);
21132 				return;
21133 			}
21134 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21135 			    ntohl(dst), ill->ill_name));
21136 		} else {
21137 			/*
21138 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21139 			 * and IP_MULTICAST_IF.
21140 			 * Block comment above this function explains the
21141 			 * locking mechanism used here
21142 			 */
21143 			if (xmit_ill == NULL) {
21144 				xmit_ill = conn_get_held_ill(connp,
21145 				    &connp->conn_xmit_if_ill, &err);
21146 				if (err == ILL_LOOKUP_FAILED) {
21147 					ip1dbg(("ip_wput: No ill for "
21148 					    "IP_XMIT_IF\n"));
21149 					BUMP_MIB(&ipst->ips_ip_mib,
21150 					    ipIfStatsOutNoRoutes);
21151 					goto drop_pkt;
21152 				}
21153 			}
21154 
21155 			if (xmit_ill == NULL) {
21156 				ipif = conn_get_held_ipif(connp,
21157 				    &connp->conn_multicast_ipif, &err);
21158 				if (err == IPIF_LOOKUP_FAILED) {
21159 					ip1dbg(("ip_wput: No ipif for "
21160 					    "multicast\n"));
21161 					BUMP_MIB(&ipst->ips_ip_mib,
21162 					    ipIfStatsOutNoRoutes);
21163 					goto drop_pkt;
21164 				}
21165 			}
21166 			if (xmit_ill != NULL) {
21167 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21168 				if (ipif == NULL) {
21169 					ip1dbg(("ip_wput: No ipif for "
21170 					    "IP_XMIT_IF\n"));
21171 					BUMP_MIB(&ipst->ips_ip_mib,
21172 					    ipIfStatsOutNoRoutes);
21173 					goto drop_pkt;
21174 				}
21175 			} else if (ipif == NULL || ipif->ipif_isv6) {
21176 				/*
21177 				 * We must do this ipif determination here
21178 				 * else we could pass through ip_newroute
21179 				 * and come back here without the conn context.
21180 				 *
21181 				 * Note: we do late binding i.e. we bind to
21182 				 * the interface when the first packet is sent.
21183 				 * For performance reasons we do not rebind on
21184 				 * each packet but keep the binding until the
21185 				 * next IP_MULTICAST_IF option.
21186 				 *
21187 				 * conn_multicast_{ipif,ill} are shared between
21188 				 * IPv4 and IPv6 and AF_INET6 sockets can
21189 				 * send both IPv4 and IPv6 packets. Hence
21190 				 * we have to check that "isv6" matches above.
21191 				 */
21192 				if (ipif != NULL)
21193 					ipif_refrele(ipif);
21194 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21195 				if (ipif == NULL) {
21196 					ip1dbg(("ip_wput: No ipif for "
21197 					    "multicast\n"));
21198 					BUMP_MIB(&ipst->ips_ip_mib,
21199 					    ipIfStatsOutNoRoutes);
21200 					goto drop_pkt;
21201 				}
21202 				err = conn_set_held_ipif(connp,
21203 				    &connp->conn_multicast_ipif, ipif);
21204 				if (err == IPIF_LOOKUP_FAILED) {
21205 					ipif_refrele(ipif);
21206 					ip1dbg(("ip_wput: No ipif for "
21207 					    "multicast\n"));
21208 					BUMP_MIB(&ipst->ips_ip_mib,
21209 					    ipIfStatsOutNoRoutes);
21210 					goto drop_pkt;
21211 				}
21212 			}
21213 		}
21214 		ASSERT(!ipif->ipif_isv6);
21215 		/*
21216 		 * As we may lose the conn by the time we reach ip_wput_ire,
21217 		 * we copy conn_multicast_loop and conn_dontroute on to an
21218 		 * ipsec_out. In case if this datagram goes out secure,
21219 		 * we need the ill_index also. Copy that also into the
21220 		 * ipsec_out.
21221 		 */
21222 		if (mctl_present) {
21223 			io = (ipsec_out_t *)first_mp->b_rptr;
21224 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21225 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21226 		} else {
21227 			ASSERT(mp == first_mp);
21228 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21229 			    BPRI_HI)) == NULL) {
21230 				ipif_refrele(ipif);
21231 				first_mp = mp;
21232 				goto discard_pkt;
21233 			}
21234 			first_mp->b_datap->db_type = M_CTL;
21235 			first_mp->b_wptr += sizeof (ipsec_info_t);
21236 			/* ipsec_out_secure is B_FALSE now */
21237 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21238 			io = (ipsec_out_t *)first_mp->b_rptr;
21239 			io->ipsec_out_type = IPSEC_OUT;
21240 			io->ipsec_out_len = sizeof (ipsec_out_t);
21241 			io->ipsec_out_use_global_policy = B_TRUE;
21242 			io->ipsec_out_ns = ipst->ips_netstack;
21243 			first_mp->b_cont = mp;
21244 			mctl_present = B_TRUE;
21245 		}
21246 		if (attach_ill != NULL) {
21247 			ASSERT(attach_ill == ipif->ipif_ill);
21248 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21249 
21250 			/*
21251 			 * Check if we need an ire that will not be
21252 			 * looked up by anybody else i.e. HIDDEN.
21253 			 */
21254 			if (ill_is_probeonly(attach_ill)) {
21255 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21256 			}
21257 			io->ipsec_out_ill_index =
21258 			    attach_ill->ill_phyint->phyint_ifindex;
21259 			io->ipsec_out_attach_if = B_TRUE;
21260 		} else {
21261 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21262 			io->ipsec_out_ill_index =
21263 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21264 		}
21265 		if (connp != NULL) {
21266 			io->ipsec_out_multicast_loop =
21267 			    connp->conn_multicast_loop;
21268 			io->ipsec_out_dontroute = connp->conn_dontroute;
21269 			io->ipsec_out_zoneid = connp->conn_zoneid;
21270 		}
21271 		/*
21272 		 * If the application uses IP_MULTICAST_IF with
21273 		 * different logical addresses of the same ILL, we
21274 		 * need to make sure that the soruce address of
21275 		 * the packet matches the logical IP address used
21276 		 * in the option. We do it by initializing ipha_src
21277 		 * here. This should keep IPSEC also happy as
21278 		 * when we return from IPSEC processing, we don't
21279 		 * have to worry about getting the right address on
21280 		 * the packet. Thus it is sufficient to look for
21281 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21282 		 * MATCH_IRE_IPIF.
21283 		 *
21284 		 * NOTE : We need to do it for non-secure case also as
21285 		 * this might go out secure if there is a global policy
21286 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21287 		 * address, the source should be initialized already and
21288 		 * hence we won't be initializing here.
21289 		 *
21290 		 * As we do not have the ire yet, it is possible that
21291 		 * we set the source address here and then later discover
21292 		 * that the ire implies the source address to be assigned
21293 		 * through the RTF_SETSRC flag.
21294 		 * In that case, the setsrc variable will remind us
21295 		 * that overwritting the source address by the one
21296 		 * of the RTF_SETSRC-flagged ire is allowed.
21297 		 */
21298 		if (ipha->ipha_src == INADDR_ANY &&
21299 		    (connp == NULL || !connp->conn_unspec_src)) {
21300 			ipha->ipha_src = ipif->ipif_src_addr;
21301 			setsrc = RTF_SETSRC;
21302 		}
21303 		/*
21304 		 * Find an IRE which matches the destination and the outgoing
21305 		 * queue (i.e. the outgoing interface.)
21306 		 * For loopback use a unicast IP address for
21307 		 * the ire lookup.
21308 		 */
21309 		if (ipif->ipif_ill->ill_phyint->phyint_flags &
21310 		    PHYI_LOOPBACK) {
21311 			dst = ipif->ipif_lcl_addr;
21312 		}
21313 		/*
21314 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21315 		 * We don't need to lookup ire in ctable as the packet
21316 		 * needs to be sent to the destination through the specified
21317 		 * ill irrespective of ires in the cache table.
21318 		 */
21319 		ire = NULL;
21320 		if (xmit_ill == NULL) {
21321 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21322 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21323 		}
21324 
21325 		/*
21326 		 * refrele attach_ill as its not needed anymore.
21327 		 */
21328 		if (attach_ill != NULL) {
21329 			ill_refrele(attach_ill);
21330 			attach_ill = NULL;
21331 		}
21332 
21333 		if (ire == NULL) {
21334 			/*
21335 			 * Multicast loopback and multicast forwarding is
21336 			 * done in ip_wput_ire.
21337 			 *
21338 			 * Mark this packet to make it be delivered to
21339 			 * ip_wput_ire after the new ire has been
21340 			 * created.
21341 			 *
21342 			 * The call to ip_newroute_ipif takes into account
21343 			 * the setsrc reminder. In any case, we take care
21344 			 * of the RTF_MULTIRT flag.
21345 			 */
21346 			mp->b_prev = mp->b_next = NULL;
21347 			if (xmit_ill == NULL ||
21348 			    xmit_ill->ill_ipif_up_count > 0) {
21349 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21350 				    setsrc | RTF_MULTIRT, zoneid, infop);
21351 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21352 				    "ip_wput_end: q %p (%S)", q, "noire");
21353 			} else {
21354 				freemsg(first_mp);
21355 			}
21356 			ipif_refrele(ipif);
21357 			if (xmit_ill != NULL)
21358 				ill_refrele(xmit_ill);
21359 			if (need_decref)
21360 				CONN_DEC_REF(connp);
21361 			return;
21362 		}
21363 
21364 		ipif_refrele(ipif);
21365 		ipif = NULL;
21366 		ASSERT(xmit_ill == NULL);
21367 
21368 		/*
21369 		 * Honor the RTF_SETSRC flag for multicast packets,
21370 		 * if allowed by the setsrc reminder.
21371 		 */
21372 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21373 			ipha->ipha_src = ire->ire_src_addr;
21374 		}
21375 
21376 		/*
21377 		 * Unconditionally force the TTL to 1 for
21378 		 * multirouted multicast packets:
21379 		 * multirouted multicast should not cross
21380 		 * multicast routers.
21381 		 */
21382 		if (ire->ire_flags & RTF_MULTIRT) {
21383 			if (ipha->ipha_ttl > 1) {
21384 				ip2dbg(("ip_wput: forcing multicast "
21385 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21386 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21387 				ipha->ipha_ttl = 1;
21388 			}
21389 		}
21390 	} else {
21391 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21392 		if ((ire != NULL) && (ire->ire_type &
21393 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21394 			ignore_dontroute = B_TRUE;
21395 			ignore_nexthop = B_TRUE;
21396 		}
21397 		if (ire != NULL) {
21398 			ire_refrele(ire);
21399 			ire = NULL;
21400 		}
21401 		/*
21402 		 * Guard against coming in from arp in which case conn is NULL.
21403 		 * Also guard against non M_DATA with dontroute set but
21404 		 * destined to local, loopback or broadcast addresses.
21405 		 */
21406 		if (connp != NULL && connp->conn_dontroute &&
21407 		    !ignore_dontroute) {
21408 dontroute:
21409 			/*
21410 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21411 			 * routing protocols from seeing false direct
21412 			 * connectivity.
21413 			 */
21414 			ipha->ipha_ttl = 1;
21415 			/*
21416 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21417 			 * along with SO_DONTROUTE, higher precedence is
21418 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21419 			 */
21420 			if (connp->conn_xmit_if_ill == NULL) {
21421 				/* If suitable ipif not found, drop packet */
21422 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21423 				    ipst);
21424 				if (dst_ipif == NULL) {
21425 					ip1dbg(("ip_wput: no route for "
21426 					    "dst using SO_DONTROUTE\n"));
21427 					BUMP_MIB(&ipst->ips_ip_mib,
21428 					    ipIfStatsOutNoRoutes);
21429 					mp->b_prev = mp->b_next = NULL;
21430 					if (first_mp == NULL)
21431 						first_mp = mp;
21432 					goto drop_pkt;
21433 				} else {
21434 					/*
21435 					 * If suitable ipif has been found, set
21436 					 * xmit_ill to the corresponding
21437 					 * ipif_ill because we'll be following
21438 					 * the IP_XMIT_IF logic.
21439 					 */
21440 					ASSERT(xmit_ill == NULL);
21441 					xmit_ill = dst_ipif->ipif_ill;
21442 					mutex_enter(&xmit_ill->ill_lock);
21443 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21444 						mutex_exit(&xmit_ill->ill_lock);
21445 						xmit_ill = NULL;
21446 						ipif_refrele(dst_ipif);
21447 						ip1dbg(("ip_wput: no route for"
21448 						    " dst using"
21449 						    " SO_DONTROUTE\n"));
21450 						BUMP_MIB(&ipst->ips_ip_mib,
21451 						    ipIfStatsOutNoRoutes);
21452 						mp->b_prev = mp->b_next = NULL;
21453 						if (first_mp == NULL)
21454 							first_mp = mp;
21455 						goto drop_pkt;
21456 					}
21457 					ill_refhold_locked(xmit_ill);
21458 					mutex_exit(&xmit_ill->ill_lock);
21459 					ipif_refrele(dst_ipif);
21460 				}
21461 			}
21462 
21463 		}
21464 		/*
21465 		 * If we are bound to IPIF_NOFAILOVER address, look for
21466 		 * an IRE_CACHE matching the ill.
21467 		 */
21468 send_from_ill:
21469 		if (attach_ill != NULL) {
21470 			ipif_t	*attach_ipif;
21471 
21472 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21473 
21474 			/*
21475 			 * Check if we need an ire that will not be
21476 			 * looked up by anybody else i.e. HIDDEN.
21477 			 */
21478 			if (ill_is_probeonly(attach_ill)) {
21479 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21480 			}
21481 
21482 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21483 			if (attach_ipif == NULL) {
21484 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21485 				goto discard_pkt;
21486 			}
21487 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21488 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21489 			ipif_refrele(attach_ipif);
21490 		} else if (xmit_ill != NULL || (connp != NULL &&
21491 			    connp->conn_xmit_if_ill != NULL)) {
21492 			/*
21493 			 * Mark this packet as originated locally
21494 			 */
21495 			mp->b_prev = mp->b_next = NULL;
21496 			/*
21497 			 * xmit_ill could be NULL if SO_DONTROUTE
21498 			 * is also set.
21499 			 */
21500 			if (xmit_ill == NULL) {
21501 				xmit_ill = conn_get_held_ill(connp,
21502 				    &connp->conn_xmit_if_ill, &err);
21503 				if (err == ILL_LOOKUP_FAILED) {
21504 					BUMP_MIB(&ipst->ips_ip_mib,
21505 					    ipIfStatsOutDiscards);
21506 					if (need_decref)
21507 						CONN_DEC_REF(connp);
21508 					freemsg(first_mp);
21509 					return;
21510 				}
21511 				if (xmit_ill == NULL) {
21512 					if (connp->conn_dontroute)
21513 						goto dontroute;
21514 					goto send_from_ill;
21515 				}
21516 			}
21517 			/*
21518 			 * Could be SO_DONTROUTE case also.
21519 			 * check at least one interface is UP as
21520 			 * specified by this ILL
21521 			 */
21522 			if (xmit_ill->ill_ipif_up_count > 0) {
21523 				ipif_t *ipif;
21524 
21525 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21526 				if (ipif == NULL) {
21527 					ip1dbg(("ip_output: "
21528 					    "xmit_ill NULL ipif\n"));
21529 					goto drop_pkt;
21530 				}
21531 				/*
21532 				 * Look for a ire that is part of the group,
21533 				 * if found use it else call ip_newroute_ipif.
21534 				 * IPCL_ZONEID is not used for matching because
21535 				 * IP_ALLZONES option is valid only when the
21536 				 * ill is accessible from all zones i.e has a
21537 				 * valid ipif in all zones.
21538 				 */
21539 				match_flags = MATCH_IRE_ILL_GROUP |
21540 				    MATCH_IRE_SECATTR;
21541 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21542 				    MBLK_GETLABEL(mp), match_flags, ipst);
21543 				/*
21544 				 * If an ire exists use it or else create
21545 				 * an ire but don't add it to the cache.
21546 				 * Adding an ire may cause issues with
21547 				 * asymmetric routing.
21548 				 * In case of multiroute always act as if
21549 				 * ire does not exist.
21550 				 */
21551 				if (ire == NULL ||
21552 				    ire->ire_flags & RTF_MULTIRT) {
21553 					if (ire != NULL)
21554 						ire_refrele(ire);
21555 					ip_newroute_ipif(q, first_mp, ipif,
21556 					    dst, connp, 0, zoneid, infop);
21557 					ipif_refrele(ipif);
21558 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21559 					ill_refrele(xmit_ill);
21560 					if (need_decref)
21561 						CONN_DEC_REF(connp);
21562 					return;
21563 				}
21564 				ipif_refrele(ipif);
21565 			} else {
21566 				goto drop_pkt;
21567 			}
21568 		} else if (ip_nexthop || (connp != NULL &&
21569 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21570 			if (!ip_nexthop) {
21571 				ip_nexthop = B_TRUE;
21572 				nexthop_addr = connp->conn_nexthop_v4;
21573 			}
21574 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21575 			    MATCH_IRE_GW;
21576 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21577 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21578 		} else {
21579 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21580 			    ipst);
21581 		}
21582 		if (!ire) {
21583 			/*
21584 			 * Make sure we don't load spread if this
21585 			 * is IPIF_NOFAILOVER case.
21586 			 */
21587 			if ((attach_ill != NULL) ||
21588 			    (ip_nexthop && !ignore_nexthop)) {
21589 				if (mctl_present) {
21590 					io = (ipsec_out_t *)first_mp->b_rptr;
21591 					ASSERT(first_mp->b_datap->db_type ==
21592 					    M_CTL);
21593 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21594 				} else {
21595 					ASSERT(mp == first_mp);
21596 					first_mp = allocb(
21597 					    sizeof (ipsec_info_t), BPRI_HI);
21598 					if (first_mp == NULL) {
21599 						first_mp = mp;
21600 						goto discard_pkt;
21601 					}
21602 					first_mp->b_datap->db_type = M_CTL;
21603 					first_mp->b_wptr +=
21604 					    sizeof (ipsec_info_t);
21605 					/* ipsec_out_secure is B_FALSE now */
21606 					bzero(first_mp->b_rptr,
21607 					    sizeof (ipsec_info_t));
21608 					io = (ipsec_out_t *)first_mp->b_rptr;
21609 					io->ipsec_out_type = IPSEC_OUT;
21610 					io->ipsec_out_len =
21611 					    sizeof (ipsec_out_t);
21612 					io->ipsec_out_use_global_policy =
21613 					    B_TRUE;
21614 					io->ipsec_out_ns = ipst->ips_netstack;
21615 					first_mp->b_cont = mp;
21616 					mctl_present = B_TRUE;
21617 				}
21618 				if (attach_ill != NULL) {
21619 					io->ipsec_out_ill_index = attach_ill->
21620 					    ill_phyint->phyint_ifindex;
21621 					io->ipsec_out_attach_if = B_TRUE;
21622 				} else {
21623 					io->ipsec_out_ip_nexthop = ip_nexthop;
21624 					io->ipsec_out_nexthop_addr =
21625 					    nexthop_addr;
21626 				}
21627 			}
21628 noirefound:
21629 			/*
21630 			 * Mark this packet as having originated on
21631 			 * this machine.  This will be noted in
21632 			 * ire_add_then_send, which needs to know
21633 			 * whether to run it back through ip_wput or
21634 			 * ip_rput following successful resolution.
21635 			 */
21636 			mp->b_prev = NULL;
21637 			mp->b_next = NULL;
21638 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21639 			    ipst);
21640 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21641 			    "ip_wput_end: q %p (%S)", q, "newroute");
21642 			if (attach_ill != NULL)
21643 				ill_refrele(attach_ill);
21644 			if (xmit_ill != NULL)
21645 				ill_refrele(xmit_ill);
21646 			if (need_decref)
21647 				CONN_DEC_REF(connp);
21648 			return;
21649 		}
21650 	}
21651 
21652 	/* We now know where we are going with it. */
21653 
21654 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21655 	    "ip_wput_end: q %p (%S)", q, "end");
21656 
21657 	/*
21658 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21659 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21660 	 */
21661 	if (ire->ire_flags & RTF_MULTIRT) {
21662 		/*
21663 		 * Force the TTL of multirouted packets if required.
21664 		 * The TTL of such packets is bounded by the
21665 		 * ip_multirt_ttl ndd variable.
21666 		 */
21667 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21668 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21669 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21670 			    "(was %d), dst 0x%08x\n",
21671 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21672 			    ntohl(ire->ire_addr)));
21673 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21674 		}
21675 		/*
21676 		 * At this point, we check to see if there are any pending
21677 		 * unresolved routes. ire_multirt_resolvable()
21678 		 * checks in O(n) that all IRE_OFFSUBNET ire
21679 		 * entries for the packet's destination and
21680 		 * flagged RTF_MULTIRT are currently resolved.
21681 		 * If some remain unresolved, we make a copy
21682 		 * of the current message. It will be used
21683 		 * to initiate additional route resolutions.
21684 		 */
21685 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21686 		    MBLK_GETLABEL(first_mp), ipst);
21687 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21688 		    "multirt_need_resolve %d, first_mp %p\n",
21689 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21690 		if (multirt_need_resolve) {
21691 			copy_mp = copymsg(first_mp);
21692 			if (copy_mp != NULL) {
21693 				MULTIRT_DEBUG_TAG(copy_mp);
21694 			}
21695 		}
21696 	}
21697 
21698 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21699 	/*
21700 	 * Try to resolve another multiroute if
21701 	 * ire_multirt_resolvable() deemed it necessary.
21702 	 * At this point, we need to distinguish
21703 	 * multicasts from other packets. For multicasts,
21704 	 * we call ip_newroute_ipif() and request that both
21705 	 * multirouting and setsrc flags are checked.
21706 	 */
21707 	if (copy_mp != NULL) {
21708 		if (CLASSD(dst)) {
21709 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21710 			if (ipif) {
21711 				ASSERT(infop->ip_opt_ill_index == 0);
21712 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21713 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21714 				ipif_refrele(ipif);
21715 			} else {
21716 				MULTIRT_DEBUG_UNTAG(copy_mp);
21717 				freemsg(copy_mp);
21718 				copy_mp = NULL;
21719 			}
21720 		} else {
21721 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21722 		}
21723 	}
21724 	if (attach_ill != NULL)
21725 		ill_refrele(attach_ill);
21726 	if (xmit_ill != NULL)
21727 		ill_refrele(xmit_ill);
21728 	if (need_decref)
21729 		CONN_DEC_REF(connp);
21730 	return;
21731 
21732 icmp_parameter_problem:
21733 	/* could not have originated externally */
21734 	ASSERT(mp->b_prev == NULL);
21735 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21736 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21737 		/* it's the IP header length that's in trouble */
21738 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21739 		first_mp = NULL;
21740 	}
21741 
21742 discard_pkt:
21743 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21744 drop_pkt:
21745 	ip1dbg(("ip_wput: dropped packet\n"));
21746 	if (ire != NULL)
21747 		ire_refrele(ire);
21748 	if (need_decref)
21749 		CONN_DEC_REF(connp);
21750 	freemsg(first_mp);
21751 	if (attach_ill != NULL)
21752 		ill_refrele(attach_ill);
21753 	if (xmit_ill != NULL)
21754 		ill_refrele(xmit_ill);
21755 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21756 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21757 }
21758 
21759 /*
21760  * If this is a conn_t queue, then we pass in the conn. This includes the
21761  * zoneid.
21762  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21763  * in which case we use the global zoneid since those are all part of
21764  * the global zone.
21765  */
21766 void
21767 ip_wput(queue_t *q, mblk_t *mp)
21768 {
21769 	if (CONN_Q(q))
21770 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21771 	else
21772 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21773 }
21774 
21775 /*
21776  *
21777  * The following rules must be observed when accessing any ipif or ill
21778  * that has been cached in the conn. Typically conn_nofailover_ill,
21779  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21780  *
21781  * Access: The ipif or ill pointed to from the conn can be accessed under
21782  * the protection of the conn_lock or after it has been refheld under the
21783  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21784  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21785  * The reason for this is that a concurrent unplumb could actually be
21786  * cleaning up these cached pointers by walking the conns and might have
21787  * finished cleaning up the conn in question. The macros check that an
21788  * unplumb has not yet started on the ipif or ill.
21789  *
21790  * Caching: An ipif or ill pointer may be cached in the conn only after
21791  * making sure that an unplumb has not started. So the caching is done
21792  * while holding both the conn_lock and the ill_lock and after using the
21793  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21794  * flag before starting the cleanup of conns.
21795  *
21796  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21797  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21798  * or a reference to the ipif or a reference to an ire that references the
21799  * ipif. An ipif does not change its ill except for failover/failback. Since
21800  * failover/failback happens only after bringing down the ipif and making sure
21801  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21802  * the above holds.
21803  */
21804 ipif_t *
21805 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21806 {
21807 	ipif_t	*ipif;
21808 	ill_t	*ill;
21809 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21810 
21811 	*err = 0;
21812 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21813 	mutex_enter(&connp->conn_lock);
21814 	ipif = *ipifp;
21815 	if (ipif != NULL) {
21816 		ill = ipif->ipif_ill;
21817 		mutex_enter(&ill->ill_lock);
21818 		if (IPIF_CAN_LOOKUP(ipif)) {
21819 			ipif_refhold_locked(ipif);
21820 			mutex_exit(&ill->ill_lock);
21821 			mutex_exit(&connp->conn_lock);
21822 			rw_exit(&ipst->ips_ill_g_lock);
21823 			return (ipif);
21824 		} else {
21825 			*err = IPIF_LOOKUP_FAILED;
21826 		}
21827 		mutex_exit(&ill->ill_lock);
21828 	}
21829 	mutex_exit(&connp->conn_lock);
21830 	rw_exit(&ipst->ips_ill_g_lock);
21831 	return (NULL);
21832 }
21833 
21834 ill_t *
21835 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21836 {
21837 	ill_t	*ill;
21838 
21839 	*err = 0;
21840 	mutex_enter(&connp->conn_lock);
21841 	ill = *illp;
21842 	if (ill != NULL) {
21843 		mutex_enter(&ill->ill_lock);
21844 		if (ILL_CAN_LOOKUP(ill)) {
21845 			ill_refhold_locked(ill);
21846 			mutex_exit(&ill->ill_lock);
21847 			mutex_exit(&connp->conn_lock);
21848 			return (ill);
21849 		} else {
21850 			*err = ILL_LOOKUP_FAILED;
21851 		}
21852 		mutex_exit(&ill->ill_lock);
21853 	}
21854 	mutex_exit(&connp->conn_lock);
21855 	return (NULL);
21856 }
21857 
21858 static int
21859 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21860 {
21861 	ill_t	*ill;
21862 
21863 	ill = ipif->ipif_ill;
21864 	mutex_enter(&connp->conn_lock);
21865 	mutex_enter(&ill->ill_lock);
21866 	if (IPIF_CAN_LOOKUP(ipif)) {
21867 		*ipifp = ipif;
21868 		mutex_exit(&ill->ill_lock);
21869 		mutex_exit(&connp->conn_lock);
21870 		return (0);
21871 	}
21872 	mutex_exit(&ill->ill_lock);
21873 	mutex_exit(&connp->conn_lock);
21874 	return (IPIF_LOOKUP_FAILED);
21875 }
21876 
21877 /*
21878  * This is called if the outbound datagram needs fragmentation.
21879  *
21880  * NOTE : This function does not ire_refrele the ire argument passed in.
21881  */
21882 static void
21883 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21884     ip_stack_t *ipst)
21885 {
21886 	ipha_t		*ipha;
21887 	mblk_t		*mp;
21888 	uint32_t	v_hlen_tos_len;
21889 	uint32_t	max_frag;
21890 	uint32_t	frag_flag;
21891 	boolean_t	dont_use;
21892 
21893 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21894 		mp = ipsec_mp->b_cont;
21895 	} else {
21896 		mp = ipsec_mp;
21897 	}
21898 
21899 	ipha = (ipha_t *)mp->b_rptr;
21900 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21901 
21902 #ifdef	_BIG_ENDIAN
21903 #define	V_HLEN	(v_hlen_tos_len >> 24)
21904 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21905 #else
21906 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21907 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21908 #endif
21909 
21910 #ifndef SPEED_BEFORE_SAFETY
21911 	/*
21912 	 * Check that ipha_length is consistent with
21913 	 * the mblk length
21914 	 */
21915 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21916 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21917 		    LENGTH, msgdsize(mp)));
21918 		freemsg(ipsec_mp);
21919 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21920 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21921 		    "packet length mismatch");
21922 		return;
21923 	}
21924 #endif
21925 	/*
21926 	 * Don't use frag_flag if pre-built packet or source
21927 	 * routed or if multicast (since multicast packets do not solicit
21928 	 * ICMP "packet too big" messages). Get the values of
21929 	 * max_frag and frag_flag atomically by acquiring the
21930 	 * ire_lock.
21931 	 */
21932 	mutex_enter(&ire->ire_lock);
21933 	max_frag = ire->ire_max_frag;
21934 	frag_flag = ire->ire_frag_flag;
21935 	mutex_exit(&ire->ire_lock);
21936 
21937 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21938 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21939 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21940 
21941 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21942 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21943 }
21944 
21945 /*
21946  * Used for deciding the MSS size for the upper layer. Thus
21947  * we need to check the outbound policy values in the conn.
21948  */
21949 int
21950 conn_ipsec_length(conn_t *connp)
21951 {
21952 	ipsec_latch_t *ipl;
21953 
21954 	ipl = connp->conn_latch;
21955 	if (ipl == NULL)
21956 		return (0);
21957 
21958 	if (ipl->ipl_out_policy == NULL)
21959 		return (0);
21960 
21961 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21962 }
21963 
21964 /*
21965  * Returns an estimate of the IPSEC headers size. This is used if
21966  * we don't want to call into IPSEC to get the exact size.
21967  */
21968 int
21969 ipsec_out_extra_length(mblk_t *ipsec_mp)
21970 {
21971 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21972 	ipsec_action_t *a;
21973 
21974 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21975 	if (!io->ipsec_out_secure)
21976 		return (0);
21977 
21978 	a = io->ipsec_out_act;
21979 
21980 	if (a == NULL) {
21981 		ASSERT(io->ipsec_out_policy != NULL);
21982 		a = io->ipsec_out_policy->ipsp_act;
21983 	}
21984 	ASSERT(a != NULL);
21985 
21986 	return (a->ipa_ovhd);
21987 }
21988 
21989 /*
21990  * Returns an estimate of the IPSEC headers size. This is used if
21991  * we don't want to call into IPSEC to get the exact size.
21992  */
21993 int
21994 ipsec_in_extra_length(mblk_t *ipsec_mp)
21995 {
21996 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21997 	ipsec_action_t *a;
21998 
21999 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
22000 
22001 	a = ii->ipsec_in_action;
22002 	return (a == NULL ? 0 : a->ipa_ovhd);
22003 }
22004 
22005 /*
22006  * If there are any source route options, return the true final
22007  * destination. Otherwise, return the destination.
22008  */
22009 ipaddr_t
22010 ip_get_dst(ipha_t *ipha)
22011 {
22012 	ipoptp_t	opts;
22013 	uchar_t		*opt;
22014 	uint8_t		optval;
22015 	uint8_t		optlen;
22016 	ipaddr_t	dst;
22017 	uint32_t off;
22018 
22019 	dst = ipha->ipha_dst;
22020 
22021 	if (IS_SIMPLE_IPH(ipha))
22022 		return (dst);
22023 
22024 	for (optval = ipoptp_first(&opts, ipha);
22025 	    optval != IPOPT_EOL;
22026 	    optval = ipoptp_next(&opts)) {
22027 		opt = opts.ipoptp_cur;
22028 		optlen = opts.ipoptp_len;
22029 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22030 		switch (optval) {
22031 		case IPOPT_SSRR:
22032 		case IPOPT_LSRR:
22033 			off = opt[IPOPT_OFFSET];
22034 			/*
22035 			 * If one of the conditions is true, it means
22036 			 * end of options and dst already has the right
22037 			 * value.
22038 			 */
22039 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22040 				off = optlen - IP_ADDR_LEN;
22041 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22042 			}
22043 			return (dst);
22044 		default:
22045 			break;
22046 		}
22047 	}
22048 
22049 	return (dst);
22050 }
22051 
22052 mblk_t *
22053 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22054     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22055 {
22056 	ipsec_out_t	*io;
22057 	mblk_t		*first_mp;
22058 	boolean_t policy_present;
22059 	ip_stack_t	*ipst;
22060 	ipsec_stack_t	*ipss;
22061 
22062 	ASSERT(ire != NULL);
22063 	ipst = ire->ire_ipst;
22064 	ipss = ipst->ips_netstack->netstack_ipsec;
22065 
22066 	first_mp = mp;
22067 	if (mp->b_datap->db_type == M_CTL) {
22068 		io = (ipsec_out_t *)first_mp->b_rptr;
22069 		/*
22070 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22071 		 *
22072 		 * 1) There is per-socket policy (including cached global
22073 		 *    policy) or a policy on the IP-in-IP tunnel.
22074 		 * 2) There is no per-socket policy, but it is
22075 		 *    a multicast packet that needs to go out
22076 		 *    on a specific interface. This is the case
22077 		 *    where (ip_wput and ip_wput_multicast) attaches
22078 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22079 		 *
22080 		 * In case (2) we check with global policy to
22081 		 * see if there is a match and set the ill_index
22082 		 * appropriately so that we can lookup the ire
22083 		 * properly in ip_wput_ipsec_out.
22084 		 */
22085 
22086 		/*
22087 		 * ipsec_out_use_global_policy is set to B_FALSE
22088 		 * in ipsec_in_to_out(). Refer to that function for
22089 		 * details.
22090 		 */
22091 		if ((io->ipsec_out_latch == NULL) &&
22092 		    (io->ipsec_out_use_global_policy)) {
22093 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22094 				    ire, connp, unspec_src, zoneid));
22095 		}
22096 		if (!io->ipsec_out_secure) {
22097 			/*
22098 			 * If this is not a secure packet, drop
22099 			 * the IPSEC_OUT mp and treat it as a clear
22100 			 * packet. This happens when we are sending
22101 			 * a ICMP reply back to a clear packet. See
22102 			 * ipsec_in_to_out() for details.
22103 			 */
22104 			mp = first_mp->b_cont;
22105 			freeb(first_mp);
22106 		}
22107 		return (mp);
22108 	}
22109 	/*
22110 	 * See whether we need to attach a global policy here. We
22111 	 * don't depend on the conn (as it could be null) for deciding
22112 	 * what policy this datagram should go through because it
22113 	 * should have happened in ip_wput if there was some
22114 	 * policy. This normally happens for connections which are not
22115 	 * fully bound preventing us from caching policies in
22116 	 * ip_bind. Packets coming from the TCP listener/global queue
22117 	 * - which are non-hard_bound - could also be affected by
22118 	 * applying policy here.
22119 	 *
22120 	 * If this packet is coming from tcp global queue or listener,
22121 	 * we will be applying policy here.  This may not be *right*
22122 	 * if these packets are coming from the detached connection as
22123 	 * it could have gone in clear before. This happens only if a
22124 	 * TCP connection started when there is no policy and somebody
22125 	 * added policy before it became detached. Thus packets of the
22126 	 * detached connection could go out secure and the other end
22127 	 * would drop it because it will be expecting in clear. The
22128 	 * converse is not true i.e if somebody starts a TCP
22129 	 * connection and deletes the policy, all the packets will
22130 	 * still go out with the policy that existed before deleting
22131 	 * because ip_unbind sends up policy information which is used
22132 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22133 	 * TCP to attach a dummy IPSEC_OUT and set
22134 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22135 	 * affect performance for normal cases, we are not doing it.
22136 	 * Thus, set policy before starting any TCP connections.
22137 	 *
22138 	 * NOTE - We might apply policy even for a hard bound connection
22139 	 * - for which we cached policy in ip_bind - if somebody added
22140 	 * global policy after we inherited the policy in ip_bind.
22141 	 * This means that the packets that were going out in clear
22142 	 * previously would start going secure and hence get dropped
22143 	 * on the other side. To fix this, TCP attaches a dummy
22144 	 * ipsec_out and make sure that we don't apply global policy.
22145 	 */
22146 	if (ipha != NULL)
22147 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22148 	else
22149 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22150 	if (!policy_present)
22151 		return (mp);
22152 
22153 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22154 		    zoneid));
22155 }
22156 
22157 ire_t *
22158 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22159 {
22160 	ipaddr_t addr;
22161 	ire_t *save_ire;
22162 	irb_t *irb;
22163 	ill_group_t *illgrp;
22164 	int	err;
22165 
22166 	save_ire = ire;
22167 	addr = ire->ire_addr;
22168 
22169 	ASSERT(ire->ire_type == IRE_BROADCAST);
22170 
22171 	illgrp = connp->conn_outgoing_ill->ill_group;
22172 	if (illgrp == NULL) {
22173 		*conn_outgoing_ill = conn_get_held_ill(connp,
22174 		    &connp->conn_outgoing_ill, &err);
22175 		if (err == ILL_LOOKUP_FAILED) {
22176 			ire_refrele(save_ire);
22177 			return (NULL);
22178 		}
22179 		return (save_ire);
22180 	}
22181 	/*
22182 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22183 	 * If it is part of the group, we need to send on the ire
22184 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22185 	 * to this group. This is okay as IP_BOUND_IF really means
22186 	 * any ill in the group. We depend on the fact that the
22187 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22188 	 * if such an ire exists. This is possible only if you have
22189 	 * at least one ill in the group that has not failed.
22190 	 *
22191 	 * First get to the ire that matches the address and group.
22192 	 *
22193 	 * We don't look for an ire with a matching zoneid because a given zone
22194 	 * won't always have broadcast ires on all ills in the group.
22195 	 */
22196 	irb = ire->ire_bucket;
22197 	rw_enter(&irb->irb_lock, RW_READER);
22198 	if (ire->ire_marks & IRE_MARK_NORECV) {
22199 		/*
22200 		 * If the current zone only has an ire broadcast for this
22201 		 * address marked NORECV, the ire we want is ahead in the
22202 		 * bucket, so we look it up deliberately ignoring the zoneid.
22203 		 */
22204 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22205 			if (ire->ire_addr != addr)
22206 				continue;
22207 			/* skip over deleted ires */
22208 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22209 				continue;
22210 		}
22211 	}
22212 	while (ire != NULL) {
22213 		/*
22214 		 * If a new interface is coming up, we could end up
22215 		 * seeing the loopback ire and the non-loopback ire
22216 		 * may not have been added yet. So check for ire_stq
22217 		 */
22218 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22219 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22220 			break;
22221 		}
22222 		ire = ire->ire_next;
22223 	}
22224 	if (ire != NULL && ire->ire_addr == addr &&
22225 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22226 		IRE_REFHOLD(ire);
22227 		rw_exit(&irb->irb_lock);
22228 		ire_refrele(save_ire);
22229 		*conn_outgoing_ill = ire_to_ill(ire);
22230 		/*
22231 		 * Refhold the ill to make the conn_outgoing_ill
22232 		 * independent of the ire. ip_wput_ire goes in a loop
22233 		 * and may refrele the ire. Since we have an ire at this
22234 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22235 		 */
22236 		ill_refhold(*conn_outgoing_ill);
22237 		return (ire);
22238 	}
22239 	rw_exit(&irb->irb_lock);
22240 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22241 	/*
22242 	 * If we can't find a suitable ire, return the original ire.
22243 	 */
22244 	return (save_ire);
22245 }
22246 
22247 /*
22248  * This function does the ire_refrele of the ire passed in as the
22249  * argument. As this function looks up more ires i.e broadcast ires,
22250  * it needs to REFRELE them. Currently, for simplicity we don't
22251  * differentiate the one passed in and looked up here. We always
22252  * REFRELE.
22253  * IPQoS Notes:
22254  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22255  * IPSec packets are done in ipsec_out_process.
22256  *
22257  */
22258 void
22259 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22260     zoneid_t zoneid)
22261 {
22262 	ipha_t		*ipha;
22263 #define	rptr	((uchar_t *)ipha)
22264 	queue_t		*stq;
22265 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22266 	uint32_t	v_hlen_tos_len;
22267 	uint32_t	ttl_protocol;
22268 	ipaddr_t	src;
22269 	ipaddr_t	dst;
22270 	uint32_t	cksum;
22271 	ipaddr_t	orig_src;
22272 	ire_t		*ire1;
22273 	mblk_t		*next_mp;
22274 	uint_t		hlen;
22275 	uint16_t	*up;
22276 	uint32_t	max_frag = ire->ire_max_frag;
22277 	ill_t		*ill = ire_to_ill(ire);
22278 	int		clusterwide;
22279 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22280 	int		ipsec_len;
22281 	mblk_t		*first_mp;
22282 	ipsec_out_t	*io;
22283 	boolean_t	conn_dontroute;		/* conn value for multicast */
22284 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22285 	boolean_t	multicast_forward;	/* Should we forward ? */
22286 	boolean_t	unspec_src;
22287 	ill_t		*conn_outgoing_ill = NULL;
22288 	ill_t		*ire_ill;
22289 	ill_t		*ire1_ill;
22290 	ill_t		*out_ill;
22291 	uint32_t 	ill_index = 0;
22292 	boolean_t	multirt_send = B_FALSE;
22293 	int		err;
22294 	ipxmit_state_t	pktxmit_state;
22295 	ip_stack_t	*ipst = ire->ire_ipst;
22296 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22297 
22298 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22299 	    "ip_wput_ire_start: q %p", q);
22300 
22301 	multicast_forward = B_FALSE;
22302 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22303 
22304 	if (ire->ire_flags & RTF_MULTIRT) {
22305 		/*
22306 		 * Multirouting case. The bucket where ire is stored
22307 		 * probably holds other RTF_MULTIRT flagged ire
22308 		 * to the destination. In this call to ip_wput_ire,
22309 		 * we attempt to send the packet through all
22310 		 * those ires. Thus, we first ensure that ire is the
22311 		 * first RTF_MULTIRT ire in the bucket,
22312 		 * before walking the ire list.
22313 		 */
22314 		ire_t *first_ire;
22315 		irb_t *irb = ire->ire_bucket;
22316 		ASSERT(irb != NULL);
22317 
22318 		/* Make sure we do not omit any multiroute ire. */
22319 		IRB_REFHOLD(irb);
22320 		for (first_ire = irb->irb_ire;
22321 		    first_ire != NULL;
22322 		    first_ire = first_ire->ire_next) {
22323 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22324 			    (first_ire->ire_addr == ire->ire_addr) &&
22325 			    !(first_ire->ire_marks &
22326 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
22327 				break;
22328 		}
22329 
22330 		if ((first_ire != NULL) && (first_ire != ire)) {
22331 			IRE_REFHOLD(first_ire);
22332 			ire_refrele(ire);
22333 			ire = first_ire;
22334 			ill = ire_to_ill(ire);
22335 		}
22336 		IRB_REFRELE(irb);
22337 	}
22338 
22339 	/*
22340 	 * conn_outgoing_ill is used only in the broadcast loop.
22341 	 * for performance we don't grab the mutexs in the fastpath
22342 	 */
22343 	if ((connp != NULL) &&
22344 	    (connp->conn_xmit_if_ill == NULL) &&
22345 	    (ire->ire_type == IRE_BROADCAST) &&
22346 	    ((connp->conn_nofailover_ill != NULL) ||
22347 	    (connp->conn_outgoing_ill != NULL))) {
22348 		/*
22349 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22350 		 * option. So, see if this endpoint is bound to a
22351 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22352 		 * that if the interface is failed, we will still send
22353 		 * the packet on the same ill which is what we want.
22354 		 */
22355 		conn_outgoing_ill = conn_get_held_ill(connp,
22356 		    &connp->conn_nofailover_ill, &err);
22357 		if (err == ILL_LOOKUP_FAILED) {
22358 			ire_refrele(ire);
22359 			freemsg(mp);
22360 			return;
22361 		}
22362 		if (conn_outgoing_ill == NULL) {
22363 			/*
22364 			 * Choose a good ill in the group to send the
22365 			 * packets on.
22366 			 */
22367 			ire = conn_set_outgoing_ill(connp, ire,
22368 			    &conn_outgoing_ill);
22369 			if (ire == NULL) {
22370 				freemsg(mp);
22371 				return;
22372 			}
22373 		}
22374 	}
22375 
22376 	if (mp->b_datap->db_type != M_CTL) {
22377 		ipha = (ipha_t *)mp->b_rptr;
22378 	} else {
22379 		io = (ipsec_out_t *)mp->b_rptr;
22380 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22381 		ASSERT(zoneid == io->ipsec_out_zoneid);
22382 		ASSERT(zoneid != ALL_ZONES);
22383 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22384 		dst = ipha->ipha_dst;
22385 		/*
22386 		 * For the multicast case, ipsec_out carries conn_dontroute and
22387 		 * conn_multicast_loop as conn may not be available here. We
22388 		 * need this for multicast loopback and forwarding which is done
22389 		 * later in the code.
22390 		 */
22391 		if (CLASSD(dst)) {
22392 			conn_dontroute = io->ipsec_out_dontroute;
22393 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22394 			/*
22395 			 * If conn_dontroute is not set or conn_multicast_loop
22396 			 * is set, we need to do forwarding/loopback. For
22397 			 * datagrams from ip_wput_multicast, conn_dontroute is
22398 			 * set to B_TRUE and conn_multicast_loop is set to
22399 			 * B_FALSE so that we neither do forwarding nor
22400 			 * loopback.
22401 			 */
22402 			if (!conn_dontroute || conn_multicast_loop)
22403 				multicast_forward = B_TRUE;
22404 		}
22405 	}
22406 
22407 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22408 	    ire->ire_zoneid != ALL_ZONES) {
22409 		/*
22410 		 * When a zone sends a packet to another zone, we try to deliver
22411 		 * the packet under the same conditions as if the destination
22412 		 * was a real node on the network. To do so, we look for a
22413 		 * matching route in the forwarding table.
22414 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22415 		 * ip_newroute() does.
22416 		 * Note that IRE_LOCAL are special, since they are used
22417 		 * when the zoneid doesn't match in some cases. This means that
22418 		 * we need to handle ipha_src differently since ire_src_addr
22419 		 * belongs to the receiving zone instead of the sending zone.
22420 		 * When ip_restrict_interzone_loopback is set, then
22421 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22422 		 * for loopback between zones when the logical "Ethernet" would
22423 		 * have looped them back.
22424 		 */
22425 		ire_t *src_ire;
22426 
22427 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22428 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22429 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22430 		if (src_ire != NULL &&
22431 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22432 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22433 		    ire_local_same_ill_group(ire, src_ire))) {
22434 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22435 				ipha->ipha_src = src_ire->ire_src_addr;
22436 			ire_refrele(src_ire);
22437 		} else {
22438 			ire_refrele(ire);
22439 			if (conn_outgoing_ill != NULL)
22440 				ill_refrele(conn_outgoing_ill);
22441 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22442 			if (src_ire != NULL) {
22443 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22444 					ire_refrele(src_ire);
22445 					freemsg(mp);
22446 					return;
22447 				}
22448 				ire_refrele(src_ire);
22449 			}
22450 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22451 				/* Failed */
22452 				freemsg(mp);
22453 				return;
22454 			}
22455 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22456 			    ipst);
22457 			return;
22458 		}
22459 	}
22460 
22461 	if (mp->b_datap->db_type == M_CTL ||
22462 	    ipss->ipsec_outbound_v4_policy_present) {
22463 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22464 		    unspec_src, zoneid);
22465 		if (mp == NULL) {
22466 			ire_refrele(ire);
22467 			if (conn_outgoing_ill != NULL)
22468 				ill_refrele(conn_outgoing_ill);
22469 			return;
22470 		}
22471 	}
22472 
22473 	first_mp = mp;
22474 	ipsec_len = 0;
22475 
22476 	if (first_mp->b_datap->db_type == M_CTL) {
22477 		io = (ipsec_out_t *)first_mp->b_rptr;
22478 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22479 		mp = first_mp->b_cont;
22480 		ipsec_len = ipsec_out_extra_length(first_mp);
22481 		ASSERT(ipsec_len >= 0);
22482 		/* We already picked up the zoneid from the M_CTL above */
22483 		ASSERT(zoneid == io->ipsec_out_zoneid);
22484 		ASSERT(zoneid != ALL_ZONES);
22485 
22486 		/*
22487 		 * Drop M_CTL here if IPsec processing is not needed.
22488 		 * (Non-IPsec use of M_CTL extracted any information it
22489 		 * needed above).
22490 		 */
22491 		if (ipsec_len == 0) {
22492 			freeb(first_mp);
22493 			first_mp = mp;
22494 		}
22495 	}
22496 
22497 	/*
22498 	 * Fast path for ip_wput_ire
22499 	 */
22500 
22501 	ipha = (ipha_t *)mp->b_rptr;
22502 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22503 	dst = ipha->ipha_dst;
22504 
22505 	/*
22506 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22507 	 * if the socket is a SOCK_RAW type. The transport checksum should
22508 	 * be provided in the pre-built packet, so we don't need to compute it.
22509 	 * Also, other application set flags, like DF, should not be altered.
22510 	 * Other transport MUST pass down zero.
22511 	 */
22512 	ip_hdr_included = ipha->ipha_ident;
22513 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22514 
22515 	if (CLASSD(dst)) {
22516 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22517 		    ntohl(dst),
22518 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22519 		    ntohl(ire->ire_addr)));
22520 	}
22521 
22522 /* Macros to extract header fields from data already in registers */
22523 #ifdef	_BIG_ENDIAN
22524 #define	V_HLEN	(v_hlen_tos_len >> 24)
22525 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22526 #define	PROTO	(ttl_protocol & 0xFF)
22527 #else
22528 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22529 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22530 #define	PROTO	(ttl_protocol >> 8)
22531 #endif
22532 
22533 
22534 	orig_src = src = ipha->ipha_src;
22535 	/* (The loop back to "another" is explained down below.) */
22536 another:;
22537 	/*
22538 	 * Assign an ident value for this packet.  We assign idents on
22539 	 * a per destination basis out of the IRE.  There could be
22540 	 * other threads targeting the same destination, so we have to
22541 	 * arrange for a atomic increment.  Note that we use a 32-bit
22542 	 * atomic add because it has better performance than its
22543 	 * 16-bit sibling.
22544 	 *
22545 	 * If running in cluster mode and if the source address
22546 	 * belongs to a replicated service then vector through
22547 	 * cl_inet_ipident vector to allocate ip identifier
22548 	 * NOTE: This is a contract private interface with the
22549 	 * clustering group.
22550 	 */
22551 	clusterwide = 0;
22552 	if (cl_inet_ipident) {
22553 		ASSERT(cl_inet_isclusterwide);
22554 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22555 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22556 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22557 			    AF_INET, (uint8_t *)(uintptr_t)src,
22558 			    (uint8_t *)(uintptr_t)dst);
22559 			clusterwide = 1;
22560 		}
22561 	}
22562 	if (!clusterwide) {
22563 		ipha->ipha_ident =
22564 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22565 	}
22566 
22567 #ifndef _BIG_ENDIAN
22568 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22569 #endif
22570 
22571 	/*
22572 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22573 	 * This is needed to obey conn_unspec_src when packets go through
22574 	 * ip_newroute + arp.
22575 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22576 	 */
22577 	if (src == INADDR_ANY && !unspec_src) {
22578 		/*
22579 		 * Assign the appropriate source address from the IRE if none
22580 		 * was specified.
22581 		 */
22582 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22583 
22584 		/*
22585 		 * With IP multipathing, broadcast packets are sent on the ire
22586 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22587 		 * the group. However, this ire might not be in the same zone so
22588 		 * we can't always use its source address. We look for a
22589 		 * broadcast ire in the same group and in the right zone.
22590 		 */
22591 		if (ire->ire_type == IRE_BROADCAST &&
22592 		    ire->ire_zoneid != zoneid) {
22593 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22594 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22595 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22596 			if (src_ire != NULL) {
22597 				src = src_ire->ire_src_addr;
22598 				ire_refrele(src_ire);
22599 			} else {
22600 				ire_refrele(ire);
22601 				if (conn_outgoing_ill != NULL)
22602 					ill_refrele(conn_outgoing_ill);
22603 				freemsg(first_mp);
22604 				if (ill != NULL) {
22605 					BUMP_MIB(ill->ill_ip_mib,
22606 					    ipIfStatsOutDiscards);
22607 				} else {
22608 					BUMP_MIB(&ipst->ips_ip_mib,
22609 					    ipIfStatsOutDiscards);
22610 				}
22611 				return;
22612 			}
22613 		} else {
22614 			src = ire->ire_src_addr;
22615 		}
22616 
22617 		if (connp == NULL) {
22618 			ip1dbg(("ip_wput_ire: no connp and no src "
22619 			    "address for dst 0x%x, using src 0x%x\n",
22620 			    ntohl(dst),
22621 			    ntohl(src)));
22622 		}
22623 		ipha->ipha_src = src;
22624 	}
22625 	stq = ire->ire_stq;
22626 
22627 	/*
22628 	 * We only allow ire chains for broadcasts since there will
22629 	 * be multiple IRE_CACHE entries for the same multicast
22630 	 * address (one per ipif).
22631 	 */
22632 	next_mp = NULL;
22633 
22634 	/* broadcast packet */
22635 	if (ire->ire_type == IRE_BROADCAST)
22636 		goto broadcast;
22637 
22638 	/* loopback ? */
22639 	if (stq == NULL)
22640 		goto nullstq;
22641 
22642 	/* The ill_index for outbound ILL */
22643 	ill_index = Q_TO_INDEX(stq);
22644 
22645 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22646 	ttl_protocol = ((uint16_t *)ipha)[4];
22647 
22648 	/* pseudo checksum (do it in parts for IP header checksum) */
22649 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22650 
22651 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22652 		queue_t *dev_q = stq->q_next;
22653 
22654 		/* flow controlled */
22655 		if ((dev_q->q_next || dev_q->q_first) &&
22656 		    !canput(dev_q))
22657 			goto blocked;
22658 		if ((PROTO == IPPROTO_UDP) &&
22659 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22660 			hlen = (V_HLEN & 0xF) << 2;
22661 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22662 			if (*up != 0) {
22663 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22664 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22665 				/* Software checksum? */
22666 				if (DB_CKSUMFLAGS(mp) == 0) {
22667 					IP_STAT(ipst, ip_out_sw_cksum);
22668 					IP_STAT_UPDATE(ipst,
22669 					    ip_udp_out_sw_cksum_bytes,
22670 					    LENGTH - hlen);
22671 				}
22672 			}
22673 		}
22674 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22675 		hlen = (V_HLEN & 0xF) << 2;
22676 		if (PROTO == IPPROTO_TCP) {
22677 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22678 			/*
22679 			 * The packet header is processed once and for all, even
22680 			 * in the multirouting case. We disable hardware
22681 			 * checksum if the packet is multirouted, as it will be
22682 			 * replicated via several interfaces, and not all of
22683 			 * them may have this capability.
22684 			 */
22685 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22686 			    LENGTH, max_frag, ipsec_len, cksum);
22687 			/* Software checksum? */
22688 			if (DB_CKSUMFLAGS(mp) == 0) {
22689 				IP_STAT(ipst, ip_out_sw_cksum);
22690 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22691 				    LENGTH - hlen);
22692 			}
22693 		} else {
22694 			sctp_hdr_t	*sctph;
22695 
22696 			ASSERT(PROTO == IPPROTO_SCTP);
22697 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22698 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22699 			/*
22700 			 * Zero out the checksum field to ensure proper
22701 			 * checksum calculation.
22702 			 */
22703 			sctph->sh_chksum = 0;
22704 #ifdef	DEBUG
22705 			if (!skip_sctp_cksum)
22706 #endif
22707 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22708 		}
22709 	}
22710 
22711 	/*
22712 	 * If this is a multicast packet and originated from ip_wput
22713 	 * we need to do loopback and forwarding checks. If it comes
22714 	 * from ip_wput_multicast, we SHOULD not do this.
22715 	 */
22716 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22717 
22718 	/* checksum */
22719 	cksum += ttl_protocol;
22720 
22721 	/* fragment the packet */
22722 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22723 		goto fragmentit;
22724 	/*
22725 	 * Don't use frag_flag if packet is pre-built or source
22726 	 * routed or if multicast (since multicast packets do
22727 	 * not solicit ICMP "packet too big" messages).
22728 	 */
22729 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22730 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22731 	    !ip_source_route_included(ipha)) &&
22732 	    !CLASSD(ipha->ipha_dst))
22733 		ipha->ipha_fragment_offset_and_flags |=
22734 		    htons(ire->ire_frag_flag);
22735 
22736 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22737 		/* calculate IP header checksum */
22738 		cksum += ipha->ipha_ident;
22739 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22740 		cksum += ipha->ipha_fragment_offset_and_flags;
22741 
22742 		/* IP options present */
22743 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22744 		if (hlen)
22745 			goto checksumoptions;
22746 
22747 		/* calculate hdr checksum */
22748 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22749 		cksum = ~(cksum + (cksum >> 16));
22750 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22751 	}
22752 	if (ipsec_len != 0) {
22753 		/*
22754 		 * We will do the rest of the processing after
22755 		 * we come back from IPSEC in ip_wput_ipsec_out().
22756 		 */
22757 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22758 
22759 		io = (ipsec_out_t *)first_mp->b_rptr;
22760 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22761 				ill_phyint->phyint_ifindex;
22762 
22763 		ipsec_out_process(q, first_mp, ire, ill_index);
22764 		ire_refrele(ire);
22765 		if (conn_outgoing_ill != NULL)
22766 			ill_refrele(conn_outgoing_ill);
22767 		return;
22768 	}
22769 
22770 	/*
22771 	 * In most cases, the emission loop below is entered only
22772 	 * once. Only in the case where the ire holds the
22773 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22774 	 * flagged ires in the bucket, and send the packet
22775 	 * through all crossed RTF_MULTIRT routes.
22776 	 */
22777 	if (ire->ire_flags & RTF_MULTIRT) {
22778 		multirt_send = B_TRUE;
22779 	}
22780 	do {
22781 		if (multirt_send) {
22782 			irb_t *irb;
22783 			/*
22784 			 * We are in a multiple send case, need to get
22785 			 * the next ire and make a duplicate of the packet.
22786 			 * ire1 holds here the next ire to process in the
22787 			 * bucket. If multirouting is expected,
22788 			 * any non-RTF_MULTIRT ire that has the
22789 			 * right destination address is ignored.
22790 			 */
22791 			irb = ire->ire_bucket;
22792 			ASSERT(irb != NULL);
22793 
22794 			IRB_REFHOLD(irb);
22795 			for (ire1 = ire->ire_next;
22796 			    ire1 != NULL;
22797 			    ire1 = ire1->ire_next) {
22798 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22799 					continue;
22800 				if (ire1->ire_addr != ire->ire_addr)
22801 					continue;
22802 				if (ire1->ire_marks &
22803 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22804 					continue;
22805 
22806 				/* Got one */
22807 				IRE_REFHOLD(ire1);
22808 				break;
22809 			}
22810 			IRB_REFRELE(irb);
22811 
22812 			if (ire1 != NULL) {
22813 				next_mp = copyb(mp);
22814 				if ((next_mp == NULL) ||
22815 				    ((mp->b_cont != NULL) &&
22816 				    ((next_mp->b_cont =
22817 				    dupmsg(mp->b_cont)) == NULL))) {
22818 					freemsg(next_mp);
22819 					next_mp = NULL;
22820 					ire_refrele(ire1);
22821 					ire1 = NULL;
22822 				}
22823 			}
22824 
22825 			/* Last multiroute ire; don't loop anymore. */
22826 			if (ire1 == NULL) {
22827 				multirt_send = B_FALSE;
22828 			}
22829 		}
22830 
22831 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22832 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22833 		    mblk_t *, mp);
22834 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22835 		    ipst->ips_ipv4firewall_physical_out,
22836 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22837 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22838 		if (mp == NULL)
22839 			goto release_ire_and_ill;
22840 
22841 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22842 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22843 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22844 		if ((pktxmit_state == SEND_FAILED) ||
22845 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22846 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22847 			    "- packet dropped\n"));
22848 release_ire_and_ill:
22849 			ire_refrele(ire);
22850 			if (next_mp != NULL) {
22851 				freemsg(next_mp);
22852 				ire_refrele(ire1);
22853 			}
22854 			if (conn_outgoing_ill != NULL)
22855 				ill_refrele(conn_outgoing_ill);
22856 			return;
22857 		}
22858 
22859 		if (CLASSD(dst)) {
22860 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22861 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22862 			    LENGTH);
22863 		}
22864 
22865 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22866 		    "ip_wput_ire_end: q %p (%S)",
22867 		    q, "last copy out");
22868 		IRE_REFRELE(ire);
22869 
22870 		if (multirt_send) {
22871 			ASSERT(ire1);
22872 			/*
22873 			 * Proceed with the next RTF_MULTIRT ire,
22874 			 * Also set up the send-to queue accordingly.
22875 			 */
22876 			ire = ire1;
22877 			ire1 = NULL;
22878 			stq = ire->ire_stq;
22879 			mp = next_mp;
22880 			next_mp = NULL;
22881 			ipha = (ipha_t *)mp->b_rptr;
22882 			ill_index = Q_TO_INDEX(stq);
22883 			ill = (ill_t *)stq->q_ptr;
22884 		}
22885 	} while (multirt_send);
22886 	if (conn_outgoing_ill != NULL)
22887 		ill_refrele(conn_outgoing_ill);
22888 	return;
22889 
22890 	/*
22891 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22892 	 */
22893 broadcast:
22894 	{
22895 		/*
22896 		 * Avoid broadcast storms by setting the ttl to 1
22897 		 * for broadcasts. This parameter can be set
22898 		 * via ndd, so make sure that for the SO_DONTROUTE
22899 		 * case that ipha_ttl is always set to 1.
22900 		 * In the event that we are replying to incoming
22901 		 * ICMP packets, conn could be NULL.
22902 		 */
22903 		if ((connp != NULL) && connp->conn_dontroute)
22904 			ipha->ipha_ttl = 1;
22905 		else
22906 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22907 
22908 		/*
22909 		 * Note that we are not doing a IRB_REFHOLD here.
22910 		 * Actually we don't care if the list changes i.e
22911 		 * if somebody deletes an IRE from the list while
22912 		 * we drop the lock, the next time we come around
22913 		 * ire_next will be NULL and hence we won't send
22914 		 * out multiple copies which is fine.
22915 		 */
22916 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22917 		ire1 = ire->ire_next;
22918 		if (conn_outgoing_ill != NULL) {
22919 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22920 				ASSERT(ire1 == ire->ire_next);
22921 				if (ire1 != NULL && ire1->ire_addr == dst) {
22922 					ire_refrele(ire);
22923 					ire = ire1;
22924 					IRE_REFHOLD(ire);
22925 					ire1 = ire->ire_next;
22926 					continue;
22927 				}
22928 				rw_exit(&ire->ire_bucket->irb_lock);
22929 				/* Did not find a matching ill */
22930 				ip1dbg(("ip_wput_ire: broadcast with no "
22931 				    "matching IP_BOUND_IF ill %s\n",
22932 				    conn_outgoing_ill->ill_name));
22933 				freemsg(first_mp);
22934 				if (ire != NULL)
22935 					ire_refrele(ire);
22936 				ill_refrele(conn_outgoing_ill);
22937 				return;
22938 			}
22939 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22940 			/*
22941 			 * If the next IRE has the same address and is not one
22942 			 * of the two copies that we need to send, try to see
22943 			 * whether this copy should be sent at all. This
22944 			 * assumes that we insert loopbacks first and then
22945 			 * non-loopbacks. This is acheived by inserting the
22946 			 * loopback always before non-loopback.
22947 			 * This is used to send a single copy of a broadcast
22948 			 * packet out all physical interfaces that have an
22949 			 * matching IRE_BROADCAST while also looping
22950 			 * back one copy (to ip_wput_local) for each
22951 			 * matching physical interface. However, we avoid
22952 			 * sending packets out different logical that match by
22953 			 * having ipif_up/ipif_down supress duplicate
22954 			 * IRE_BROADCASTS.
22955 			 *
22956 			 * This feature is currently used to get broadcasts
22957 			 * sent to multiple interfaces, when the broadcast
22958 			 * address being used applies to multiple interfaces.
22959 			 * For example, a whole net broadcast will be
22960 			 * replicated on every connected subnet of
22961 			 * the target net.
22962 			 *
22963 			 * Each zone has its own set of IRE_BROADCASTs, so that
22964 			 * we're able to distribute inbound packets to multiple
22965 			 * zones who share a broadcast address. We avoid looping
22966 			 * back outbound packets in different zones but on the
22967 			 * same ill, as the application would see duplicates.
22968 			 *
22969 			 * If the interfaces are part of the same group,
22970 			 * we would want to send only one copy out for
22971 			 * whole group.
22972 			 *
22973 			 * This logic assumes that ire_add_v4() groups the
22974 			 * IRE_BROADCAST entries so that those with the same
22975 			 * ire_addr and ill_group are kept together.
22976 			 */
22977 			ire_ill = ire->ire_ipif->ipif_ill;
22978 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22979 				if (ire_ill->ill_group != NULL &&
22980 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22981 					/*
22982 					 * If the current zone only has an ire
22983 					 * broadcast for this address marked
22984 					 * NORECV, the ire we want is ahead in
22985 					 * the bucket, so we look it up
22986 					 * deliberately ignoring the zoneid.
22987 					 */
22988 					for (ire1 = ire->ire_bucket->irb_ire;
22989 					    ire1 != NULL;
22990 					    ire1 = ire1->ire_next) {
22991 						ire1_ill =
22992 						    ire1->ire_ipif->ipif_ill;
22993 						if (ire1->ire_addr != dst)
22994 							continue;
22995 						/* skip over the current ire */
22996 						if (ire1 == ire)
22997 							continue;
22998 						/* skip over deleted ires */
22999 						if (ire1->ire_marks &
23000 						    IRE_MARK_CONDEMNED)
23001 							continue;
23002 						/*
23003 						 * non-loopback ire in our
23004 						 * group: use it for the next
23005 						 * pass in the loop
23006 						 */
23007 						if (ire1->ire_stq != NULL &&
23008 						    ire1_ill->ill_group ==
23009 						    ire_ill->ill_group)
23010 							break;
23011 					}
23012 				}
23013 			} else {
23014 				while (ire1 != NULL && ire1->ire_addr == dst) {
23015 					ire1_ill = ire1->ire_ipif->ipif_ill;
23016 					/*
23017 					 * We can have two broadcast ires on the
23018 					 * same ill in different zones; here
23019 					 * we'll send a copy of the packet on
23020 					 * each ill and the fanout code will
23021 					 * call conn_wantpacket() to check that
23022 					 * the zone has the broadcast address
23023 					 * configured on the ill. If the two
23024 					 * ires are in the same group we only
23025 					 * send one copy up.
23026 					 */
23027 					if (ire1_ill != ire_ill &&
23028 					    (ire1_ill->ill_group == NULL ||
23029 					    ire_ill->ill_group == NULL ||
23030 					    ire1_ill->ill_group !=
23031 					    ire_ill->ill_group)) {
23032 						break;
23033 					}
23034 					ire1 = ire1->ire_next;
23035 				}
23036 			}
23037 		}
23038 		ASSERT(multirt_send == B_FALSE);
23039 		if (ire1 != NULL && ire1->ire_addr == dst) {
23040 			if ((ire->ire_flags & RTF_MULTIRT) &&
23041 			    (ire1->ire_flags & RTF_MULTIRT)) {
23042 				/*
23043 				 * We are in the multirouting case.
23044 				 * The message must be sent at least
23045 				 * on both ires. These ires have been
23046 				 * inserted AFTER the standard ones
23047 				 * in ip_rt_add(). There are thus no
23048 				 * other ire entries for the destination
23049 				 * address in the rest of the bucket
23050 				 * that do not have the RTF_MULTIRT
23051 				 * flag. We don't process a copy
23052 				 * of the message here. This will be
23053 				 * done in the final sending loop.
23054 				 */
23055 				multirt_send = B_TRUE;
23056 			} else {
23057 				next_mp = ip_copymsg(first_mp);
23058 				if (next_mp != NULL)
23059 					IRE_REFHOLD(ire1);
23060 			}
23061 		}
23062 		rw_exit(&ire->ire_bucket->irb_lock);
23063 	}
23064 
23065 	if (stq) {
23066 		/*
23067 		 * A non-NULL send-to queue means this packet is going
23068 		 * out of this machine.
23069 		 */
23070 		out_ill = (ill_t *)stq->q_ptr;
23071 
23072 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23073 		ttl_protocol = ((uint16_t *)ipha)[4];
23074 		/*
23075 		 * We accumulate the pseudo header checksum in cksum.
23076 		 * This is pretty hairy code, so watch close.  One
23077 		 * thing to keep in mind is that UDP and TCP have
23078 		 * stored their respective datagram lengths in their
23079 		 * checksum fields.  This lines things up real nice.
23080 		 */
23081 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23082 		    (src >> 16) + (src & 0xFFFF);
23083 		/*
23084 		 * We assume the udp checksum field contains the
23085 		 * length, so to compute the pseudo header checksum,
23086 		 * all we need is the protocol number and src/dst.
23087 		 */
23088 		/* Provide the checksums for UDP and TCP. */
23089 		if ((PROTO == IPPROTO_TCP) &&
23090 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23091 			/* hlen gets the number of uchar_ts in the IP header */
23092 			hlen = (V_HLEN & 0xF) << 2;
23093 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23094 			IP_STAT(ipst, ip_out_sw_cksum);
23095 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23096 			    LENGTH - hlen);
23097 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23098 		} else if (PROTO == IPPROTO_SCTP &&
23099 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23100 			sctp_hdr_t	*sctph;
23101 
23102 			hlen = (V_HLEN & 0xF) << 2;
23103 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23104 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23105 			sctph->sh_chksum = 0;
23106 #ifdef	DEBUG
23107 			if (!skip_sctp_cksum)
23108 #endif
23109 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23110 		} else {
23111 			queue_t *dev_q = stq->q_next;
23112 
23113 			if ((dev_q->q_next || dev_q->q_first) &&
23114 			    !canput(dev_q)) {
23115 			    blocked:
23116 				ipha->ipha_ident = ip_hdr_included;
23117 				/*
23118 				 * If we don't have a conn to apply
23119 				 * backpressure, free the message.
23120 				 * In the ire_send path, we don't know
23121 				 * the position to requeue the packet. Rather
23122 				 * than reorder packets, we just drop this
23123 				 * packet.
23124 				 */
23125 				if (ipst->ips_ip_output_queue &&
23126 				    connp != NULL &&
23127 				    caller != IRE_SEND) {
23128 					if (caller == IP_WSRV) {
23129 						connp->conn_did_putbq = 1;
23130 						(void) putbq(connp->conn_wq,
23131 						    first_mp);
23132 						conn_drain_insert(connp);
23133 						/*
23134 						 * This is the service thread,
23135 						 * and the queue is already
23136 						 * noenabled. The check for
23137 						 * canput and the putbq is not
23138 						 * atomic. So we need to check
23139 						 * again.
23140 						 */
23141 						if (canput(stq->q_next))
23142 							connp->conn_did_putbq
23143 							    = 0;
23144 						IP_STAT(ipst, ip_conn_flputbq);
23145 					} else {
23146 						/*
23147 						 * We are not the service proc.
23148 						 * ip_wsrv will be scheduled or
23149 						 * is already running.
23150 						 */
23151 						(void) putq(connp->conn_wq,
23152 						    first_mp);
23153 					}
23154 				} else {
23155 					out_ill = (ill_t *)stq->q_ptr;
23156 					BUMP_MIB(out_ill->ill_ip_mib,
23157 					    ipIfStatsOutDiscards);
23158 					freemsg(first_mp);
23159 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23160 					    "ip_wput_ire_end: q %p (%S)",
23161 					    q, "discard");
23162 				}
23163 				ire_refrele(ire);
23164 				if (next_mp) {
23165 					ire_refrele(ire1);
23166 					freemsg(next_mp);
23167 				}
23168 				if (conn_outgoing_ill != NULL)
23169 					ill_refrele(conn_outgoing_ill);
23170 				return;
23171 			}
23172 			if ((PROTO == IPPROTO_UDP) &&
23173 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23174 				/*
23175 				 * hlen gets the number of uchar_ts in the
23176 				 * IP header
23177 				 */
23178 				hlen = (V_HLEN & 0xF) << 2;
23179 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23180 				max_frag = ire->ire_max_frag;
23181 				if (*up != 0) {
23182 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23183 					    up, PROTO, hlen, LENGTH, max_frag,
23184 					    ipsec_len, cksum);
23185 					/* Software checksum? */
23186 					if (DB_CKSUMFLAGS(mp) == 0) {
23187 						IP_STAT(ipst, ip_out_sw_cksum);
23188 						IP_STAT_UPDATE(ipst,
23189 						    ip_udp_out_sw_cksum_bytes,
23190 						    LENGTH - hlen);
23191 					}
23192 				}
23193 			}
23194 		}
23195 		/*
23196 		 * Need to do this even when fragmenting. The local
23197 		 * loopback can be done without computing checksums
23198 		 * but forwarding out other interface must be done
23199 		 * after the IP checksum (and ULP checksums) have been
23200 		 * computed.
23201 		 *
23202 		 * NOTE : multicast_forward is set only if this packet
23203 		 * originated from ip_wput. For packets originating from
23204 		 * ip_wput_multicast, it is not set.
23205 		 */
23206 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23207 		    multi_loopback:
23208 			ip2dbg(("ip_wput: multicast, loop %d\n",
23209 			    conn_multicast_loop));
23210 
23211 			/*  Forget header checksum offload */
23212 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23213 
23214 			/*
23215 			 * Local loopback of multicasts?  Check the
23216 			 * ill.
23217 			 *
23218 			 * Note that the loopback function will not come
23219 			 * in through ip_rput - it will only do the
23220 			 * client fanout thus we need to do an mforward
23221 			 * as well.  The is different from the BSD
23222 			 * logic.
23223 			 */
23224 			if (ill != NULL) {
23225 				ilm_t	*ilm;
23226 
23227 				ILM_WALKER_HOLD(ill);
23228 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23229 				    ALL_ZONES);
23230 				ILM_WALKER_RELE(ill);
23231 				if (ilm != NULL) {
23232 					/*
23233 					 * Pass along the virtual output q.
23234 					 * ip_wput_local() will distribute the
23235 					 * packet to all the matching zones,
23236 					 * except the sending zone when
23237 					 * IP_MULTICAST_LOOP is false.
23238 					 */
23239 					ip_multicast_loopback(q, ill, first_mp,
23240 					    conn_multicast_loop ? 0 :
23241 					    IP_FF_NO_MCAST_LOOP, zoneid);
23242 				}
23243 			}
23244 			if (ipha->ipha_ttl == 0) {
23245 				/*
23246 				 * 0 => only to this host i.e. we are
23247 				 * done. We are also done if this was the
23248 				 * loopback interface since it is sufficient
23249 				 * to loopback one copy of a multicast packet.
23250 				 */
23251 				freemsg(first_mp);
23252 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23253 				    "ip_wput_ire_end: q %p (%S)",
23254 				    q, "loopback");
23255 				ire_refrele(ire);
23256 				if (conn_outgoing_ill != NULL)
23257 					ill_refrele(conn_outgoing_ill);
23258 				return;
23259 			}
23260 			/*
23261 			 * ILLF_MULTICAST is checked in ip_newroute
23262 			 * i.e. we don't need to check it here since
23263 			 * all IRE_CACHEs come from ip_newroute.
23264 			 * For multicast traffic, SO_DONTROUTE is interpreted
23265 			 * to mean only send the packet out the interface
23266 			 * (optionally specified with IP_MULTICAST_IF)
23267 			 * and do not forward it out additional interfaces.
23268 			 * RSVP and the rsvp daemon is an example of a
23269 			 * protocol and user level process that
23270 			 * handles it's own routing. Hence, it uses the
23271 			 * SO_DONTROUTE option to accomplish this.
23272 			 */
23273 
23274 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23275 			    ill != NULL) {
23276 				/* Unconditionally redo the checksum */
23277 				ipha->ipha_hdr_checksum = 0;
23278 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23279 
23280 				/*
23281 				 * If this needs to go out secure, we need
23282 				 * to wait till we finish the IPSEC
23283 				 * processing.
23284 				 */
23285 				if (ipsec_len == 0 &&
23286 				    ip_mforward(ill, ipha, mp)) {
23287 					freemsg(first_mp);
23288 					ip1dbg(("ip_wput: mforward failed\n"));
23289 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23290 					    "ip_wput_ire_end: q %p (%S)",
23291 					    q, "mforward failed");
23292 					ire_refrele(ire);
23293 					if (conn_outgoing_ill != NULL)
23294 						ill_refrele(conn_outgoing_ill);
23295 					return;
23296 				}
23297 			}
23298 		}
23299 		max_frag = ire->ire_max_frag;
23300 		cksum += ttl_protocol;
23301 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23302 			/* No fragmentation required for this one. */
23303 			/*
23304 			 * Don't use frag_flag if packet is pre-built or source
23305 			 * routed or if multicast (since multicast packets do
23306 			 * not solicit ICMP "packet too big" messages).
23307 			 */
23308 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23309 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23310 			    !ip_source_route_included(ipha)) &&
23311 			    !CLASSD(ipha->ipha_dst))
23312 				ipha->ipha_fragment_offset_and_flags |=
23313 				    htons(ire->ire_frag_flag);
23314 
23315 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23316 				/* Complete the IP header checksum. */
23317 				cksum += ipha->ipha_ident;
23318 				cksum += (v_hlen_tos_len >> 16)+
23319 				    (v_hlen_tos_len & 0xFFFF);
23320 				cksum += ipha->ipha_fragment_offset_and_flags;
23321 				hlen = (V_HLEN & 0xF) -
23322 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23323 				if (hlen) {
23324 				    checksumoptions:
23325 					/*
23326 					 * Account for the IP Options in the IP
23327 					 * header checksum.
23328 					 */
23329 					up = (uint16_t *)(rptr+
23330 					    IP_SIMPLE_HDR_LENGTH);
23331 					do {
23332 						cksum += up[0];
23333 						cksum += up[1];
23334 						up += 2;
23335 					} while (--hlen);
23336 				}
23337 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23338 				cksum = ~(cksum + (cksum >> 16));
23339 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23340 			}
23341 			if (ipsec_len != 0) {
23342 				ipsec_out_process(q, first_mp, ire, ill_index);
23343 				if (!next_mp) {
23344 					ire_refrele(ire);
23345 					if (conn_outgoing_ill != NULL)
23346 						ill_refrele(conn_outgoing_ill);
23347 					return;
23348 				}
23349 				goto next;
23350 			}
23351 
23352 			/*
23353 			 * multirt_send has already been handled
23354 			 * for broadcast, but not yet for multicast
23355 			 * or IP options.
23356 			 */
23357 			if (next_mp == NULL) {
23358 				if (ire->ire_flags & RTF_MULTIRT) {
23359 					multirt_send = B_TRUE;
23360 				}
23361 			}
23362 
23363 			/*
23364 			 * In most cases, the emission loop below is
23365 			 * entered only once. Only in the case where
23366 			 * the ire holds the RTF_MULTIRT flag, do we loop
23367 			 * to process all RTF_MULTIRT ires in the bucket,
23368 			 * and send the packet through all crossed
23369 			 * RTF_MULTIRT routes.
23370 			 */
23371 			do {
23372 				if (multirt_send) {
23373 					irb_t *irb;
23374 
23375 					irb = ire->ire_bucket;
23376 					ASSERT(irb != NULL);
23377 					/*
23378 					 * We are in a multiple send case,
23379 					 * need to get the next IRE and make
23380 					 * a duplicate of the packet.
23381 					 */
23382 					IRB_REFHOLD(irb);
23383 					for (ire1 = ire->ire_next;
23384 					    ire1 != NULL;
23385 					    ire1 = ire1->ire_next) {
23386 						if (!(ire1->ire_flags &
23387 						    RTF_MULTIRT))
23388 							continue;
23389 						if (ire1->ire_addr !=
23390 						    ire->ire_addr)
23391 							continue;
23392 						if (ire1->ire_marks &
23393 						    (IRE_MARK_CONDEMNED|
23394 							IRE_MARK_HIDDEN))
23395 							continue;
23396 
23397 						/* Got one */
23398 						IRE_REFHOLD(ire1);
23399 						break;
23400 					}
23401 					IRB_REFRELE(irb);
23402 
23403 					if (ire1 != NULL) {
23404 						next_mp = copyb(mp);
23405 						if ((next_mp == NULL) ||
23406 						    ((mp->b_cont != NULL) &&
23407 						    ((next_mp->b_cont =
23408 						    dupmsg(mp->b_cont))
23409 						    == NULL))) {
23410 							freemsg(next_mp);
23411 							next_mp = NULL;
23412 							ire_refrele(ire1);
23413 							ire1 = NULL;
23414 						}
23415 					}
23416 
23417 					/*
23418 					 * Last multiroute ire; don't loop
23419 					 * anymore. The emission is over
23420 					 * and next_mp is NULL.
23421 					 */
23422 					if (ire1 == NULL) {
23423 						multirt_send = B_FALSE;
23424 					}
23425 				}
23426 
23427 				out_ill = ire->ire_ipif->ipif_ill;
23428 				DTRACE_PROBE4(ip4__physical__out__start,
23429 				    ill_t *, NULL,
23430 				    ill_t *, out_ill,
23431 				    ipha_t *, ipha, mblk_t *, mp);
23432 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23433 				    ipst->ips_ipv4firewall_physical_out,
23434 				    NULL, out_ill, ipha, mp, mp, ipst);
23435 				DTRACE_PROBE1(ip4__physical__out__end,
23436 				    mblk_t *, mp);
23437 				if (mp == NULL)
23438 					goto release_ire_and_ill_2;
23439 
23440 				ASSERT(ipsec_len == 0);
23441 				mp->b_prev =
23442 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23443 				DTRACE_PROBE2(ip__xmit__2,
23444 				    mblk_t *, mp, ire_t *, ire);
23445 				pktxmit_state = ip_xmit_v4(mp, ire,
23446 				    NULL, B_TRUE);
23447 				if ((pktxmit_state == SEND_FAILED) ||
23448 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23449 release_ire_and_ill_2:
23450 					if (next_mp) {
23451 						freemsg(next_mp);
23452 						ire_refrele(ire1);
23453 					}
23454 					ire_refrele(ire);
23455 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23456 					    "ip_wput_ire_end: q %p (%S)",
23457 					    q, "discard MDATA");
23458 					if (conn_outgoing_ill != NULL)
23459 						ill_refrele(conn_outgoing_ill);
23460 					return;
23461 				}
23462 
23463 				if (CLASSD(dst)) {
23464 					BUMP_MIB(out_ill->ill_ip_mib,
23465 					    ipIfStatsHCOutMcastPkts);
23466 					UPDATE_MIB(out_ill->ill_ip_mib,
23467 					    ipIfStatsHCOutMcastOctets,
23468 					    LENGTH);
23469 				} else if (ire->ire_type == IRE_BROADCAST) {
23470 					BUMP_MIB(out_ill->ill_ip_mib,
23471 					    ipIfStatsHCOutBcastPkts);
23472 				}
23473 
23474 				if (multirt_send) {
23475 					/*
23476 					 * We are in a multiple send case,
23477 					 * need to re-enter the sending loop
23478 					 * using the next ire.
23479 					 */
23480 					ire_refrele(ire);
23481 					ire = ire1;
23482 					stq = ire->ire_stq;
23483 					mp = next_mp;
23484 					next_mp = NULL;
23485 					ipha = (ipha_t *)mp->b_rptr;
23486 					ill_index = Q_TO_INDEX(stq);
23487 				}
23488 			} while (multirt_send);
23489 
23490 			if (!next_mp) {
23491 				/*
23492 				 * Last copy going out (the ultra-common
23493 				 * case).  Note that we intentionally replicate
23494 				 * the putnext rather than calling it before
23495 				 * the next_mp check in hopes of a little
23496 				 * tail-call action out of the compiler.
23497 				 */
23498 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23499 				    "ip_wput_ire_end: q %p (%S)",
23500 				    q, "last copy out(1)");
23501 				ire_refrele(ire);
23502 				if (conn_outgoing_ill != NULL)
23503 					ill_refrele(conn_outgoing_ill);
23504 				return;
23505 			}
23506 			/* More copies going out below. */
23507 		} else {
23508 			int offset;
23509 		    fragmentit:
23510 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23511 			/*
23512 			 * If this would generate a icmp_frag_needed message,
23513 			 * we need to handle it before we do the IPSEC
23514 			 * processing. Otherwise, we need to strip the IPSEC
23515 			 * headers before we send up the message to the ULPs
23516 			 * which becomes messy and difficult.
23517 			 */
23518 			if (ipsec_len != 0) {
23519 				if ((max_frag < (unsigned int)(LENGTH +
23520 				    ipsec_len)) && (offset & IPH_DF)) {
23521 					out_ill = (ill_t *)stq->q_ptr;
23522 					BUMP_MIB(out_ill->ill_ip_mib,
23523 					    ipIfStatsOutFragFails);
23524 					BUMP_MIB(out_ill->ill_ip_mib,
23525 					    ipIfStatsOutFragReqds);
23526 					ipha->ipha_hdr_checksum = 0;
23527 					ipha->ipha_hdr_checksum =
23528 					    (uint16_t)ip_csum_hdr(ipha);
23529 					icmp_frag_needed(ire->ire_stq, first_mp,
23530 					    max_frag, zoneid, ipst);
23531 					if (!next_mp) {
23532 						ire_refrele(ire);
23533 						if (conn_outgoing_ill != NULL) {
23534 							ill_refrele(
23535 							    conn_outgoing_ill);
23536 						}
23537 						return;
23538 					}
23539 				} else {
23540 					/*
23541 					 * This won't cause a icmp_frag_needed
23542 					 * message. to be generated. Send it on
23543 					 * the wire. Note that this could still
23544 					 * cause fragmentation and all we
23545 					 * do is the generation of the message
23546 					 * to the ULP if needed before IPSEC.
23547 					 */
23548 					if (!next_mp) {
23549 						ipsec_out_process(q, first_mp,
23550 						    ire, ill_index);
23551 						TRACE_2(TR_FAC_IP,
23552 						    TR_IP_WPUT_IRE_END,
23553 						    "ip_wput_ire_end: q %p "
23554 						    "(%S)", q,
23555 						    "last ipsec_out_process");
23556 						ire_refrele(ire);
23557 						if (conn_outgoing_ill != NULL) {
23558 							ill_refrele(
23559 							    conn_outgoing_ill);
23560 						}
23561 						return;
23562 					}
23563 					ipsec_out_process(q, first_mp,
23564 					    ire, ill_index);
23565 				}
23566 			} else {
23567 				/*
23568 				 * Initiate IPPF processing. For
23569 				 * fragmentable packets we finish
23570 				 * all QOS packet processing before
23571 				 * calling:
23572 				 * ip_wput_ire_fragmentit->ip_wput_frag
23573 				 */
23574 
23575 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23576 					ip_process(IPP_LOCAL_OUT, &mp,
23577 					    ill_index);
23578 					if (mp == NULL) {
23579 						out_ill = (ill_t *)stq->q_ptr;
23580 						BUMP_MIB(out_ill->ill_ip_mib,
23581 						    ipIfStatsOutDiscards);
23582 						if (next_mp != NULL) {
23583 							freemsg(next_mp);
23584 							ire_refrele(ire1);
23585 						}
23586 						ire_refrele(ire);
23587 						TRACE_2(TR_FAC_IP,
23588 						    TR_IP_WPUT_IRE_END,
23589 						    "ip_wput_ire: q %p (%S)",
23590 						    q, "discard MDATA");
23591 						if (conn_outgoing_ill != NULL) {
23592 							ill_refrele(
23593 							    conn_outgoing_ill);
23594 						}
23595 						return;
23596 					}
23597 				}
23598 				if (!next_mp) {
23599 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23600 					    "ip_wput_ire_end: q %p (%S)",
23601 					    q, "last fragmentation");
23602 					ip_wput_ire_fragmentit(mp, ire,
23603 					    zoneid, ipst);
23604 					ire_refrele(ire);
23605 					if (conn_outgoing_ill != NULL)
23606 						ill_refrele(conn_outgoing_ill);
23607 					return;
23608 				}
23609 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23610 			}
23611 		}
23612 	} else {
23613 	    nullstq:
23614 		/* A NULL stq means the destination address is local. */
23615 		UPDATE_OB_PKT_COUNT(ire);
23616 		ire->ire_last_used_time = lbolt;
23617 		ASSERT(ire->ire_ipif != NULL);
23618 		if (!next_mp) {
23619 			/*
23620 			 * Is there an "in" and "out" for traffic local
23621 			 * to a host (loopback)?  The code in Solaris doesn't
23622 			 * explicitly draw a line in its code for in vs out,
23623 			 * so we've had to draw a line in the sand: ip_wput_ire
23624 			 * is considered to be the "output" side and
23625 			 * ip_wput_local to be the "input" side.
23626 			 */
23627 			out_ill = ire->ire_ipif->ipif_ill;
23628 
23629 			DTRACE_PROBE4(ip4__loopback__out__start,
23630 			    ill_t *, NULL, ill_t *, out_ill,
23631 			    ipha_t *, ipha, mblk_t *, first_mp);
23632 
23633 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23634 			    ipst->ips_ipv4firewall_loopback_out,
23635 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23636 
23637 			DTRACE_PROBE1(ip4__loopback__out_end,
23638 			    mblk_t *, first_mp);
23639 
23640 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23641 			    "ip_wput_ire_end: q %p (%S)",
23642 			    q, "local address");
23643 
23644 			if (first_mp != NULL)
23645 				ip_wput_local(q, out_ill, ipha,
23646 				    first_mp, ire, 0, ire->ire_zoneid);
23647 			ire_refrele(ire);
23648 			if (conn_outgoing_ill != NULL)
23649 				ill_refrele(conn_outgoing_ill);
23650 			return;
23651 		}
23652 
23653 		out_ill = ire->ire_ipif->ipif_ill;
23654 
23655 		DTRACE_PROBE4(ip4__loopback__out__start,
23656 		    ill_t *, NULL, ill_t *, out_ill,
23657 		    ipha_t *, ipha, mblk_t *, first_mp);
23658 
23659 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23660 		    ipst->ips_ipv4firewall_loopback_out,
23661 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23662 
23663 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23664 
23665 		if (first_mp != NULL)
23666 			ip_wput_local(q, out_ill, ipha,
23667 			    first_mp, ire, 0, ire->ire_zoneid);
23668 	}
23669 next:
23670 	/*
23671 	 * More copies going out to additional interfaces.
23672 	 * ire1 has already been held. We don't need the
23673 	 * "ire" anymore.
23674 	 */
23675 	ire_refrele(ire);
23676 	ire = ire1;
23677 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23678 	mp = next_mp;
23679 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23680 	ill = ire_to_ill(ire);
23681 	first_mp = mp;
23682 	if (ipsec_len != 0) {
23683 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23684 		mp = mp->b_cont;
23685 	}
23686 	dst = ire->ire_addr;
23687 	ipha = (ipha_t *)mp->b_rptr;
23688 	/*
23689 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23690 	 * Restore ipha_ident "no checksum" flag.
23691 	 */
23692 	src = orig_src;
23693 	ipha->ipha_ident = ip_hdr_included;
23694 	goto another;
23695 
23696 #undef	rptr
23697 #undef	Q_TO_INDEX
23698 }
23699 
23700 /*
23701  * Routine to allocate a message that is used to notify the ULP about MDT.
23702  * The caller may provide a pointer to the link-layer MDT capabilities,
23703  * or NULL if MDT is to be disabled on the stream.
23704  */
23705 mblk_t *
23706 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23707 {
23708 	mblk_t *mp;
23709 	ip_mdt_info_t *mdti;
23710 	ill_mdt_capab_t *idst;
23711 
23712 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23713 		DB_TYPE(mp) = M_CTL;
23714 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23715 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23716 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23717 		idst = &(mdti->mdt_capab);
23718 
23719 		/*
23720 		 * If the caller provides us with the capability, copy
23721 		 * it over into our notification message; otherwise
23722 		 * we zero out the capability portion.
23723 		 */
23724 		if (isrc != NULL)
23725 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23726 		else
23727 			bzero((caddr_t)idst, sizeof (*idst));
23728 	}
23729 	return (mp);
23730 }
23731 
23732 /*
23733  * Routine which determines whether MDT can be enabled on the destination
23734  * IRE and IPC combination, and if so, allocates and returns the MDT
23735  * notification mblk that may be used by ULP.  We also check if we need to
23736  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23737  * MDT usage in the past have been lifted.  This gets called during IP
23738  * and ULP binding.
23739  */
23740 mblk_t *
23741 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23742     ill_mdt_capab_t *mdt_cap)
23743 {
23744 	mblk_t *mp;
23745 	boolean_t rc = B_FALSE;
23746 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23747 
23748 	ASSERT(dst_ire != NULL);
23749 	ASSERT(connp != NULL);
23750 	ASSERT(mdt_cap != NULL);
23751 
23752 	/*
23753 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23754 	 * Multidata, which is handled in tcp_multisend().  This
23755 	 * is the reason why we do all these checks here, to ensure
23756 	 * that we don't enable Multidata for the cases which we
23757 	 * can't handle at the moment.
23758 	 */
23759 	do {
23760 		/* Only do TCP at the moment */
23761 		if (connp->conn_ulp != IPPROTO_TCP)
23762 			break;
23763 
23764 		/*
23765 		 * IPSEC outbound policy present?  Note that we get here
23766 		 * after calling ipsec_conn_cache_policy() where the global
23767 		 * policy checking is performed.  conn_latch will be
23768 		 * non-NULL as long as there's a policy defined,
23769 		 * i.e. conn_out_enforce_policy may be NULL in such case
23770 		 * when the connection is non-secure, and hence we check
23771 		 * further if the latch refers to an outbound policy.
23772 		 */
23773 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23774 			break;
23775 
23776 		/* CGTP (multiroute) is enabled? */
23777 		if (dst_ire->ire_flags & RTF_MULTIRT)
23778 			break;
23779 
23780 		/* Outbound IPQoS enabled? */
23781 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23782 			/*
23783 			 * In this case, we disable MDT for this and all
23784 			 * future connections going over the interface.
23785 			 */
23786 			mdt_cap->ill_mdt_on = 0;
23787 			break;
23788 		}
23789 
23790 		/* socket option(s) present? */
23791 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23792 			break;
23793 
23794 		rc = B_TRUE;
23795 	/* CONSTCOND */
23796 	} while (0);
23797 
23798 	/* Remember the result */
23799 	connp->conn_mdt_ok = rc;
23800 
23801 	if (!rc)
23802 		return (NULL);
23803 	else if (!mdt_cap->ill_mdt_on) {
23804 		/*
23805 		 * If MDT has been previously turned off in the past, and we
23806 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23807 		 * then enable it for this interface.
23808 		 */
23809 		mdt_cap->ill_mdt_on = 1;
23810 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23811 		    "interface %s\n", ill_name));
23812 	}
23813 
23814 	/* Allocate the MDT info mblk */
23815 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23816 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23817 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23818 		return (NULL);
23819 	}
23820 	return (mp);
23821 }
23822 
23823 /*
23824  * Routine to allocate a message that is used to notify the ULP about LSO.
23825  * The caller may provide a pointer to the link-layer LSO capabilities,
23826  * or NULL if LSO is to be disabled on the stream.
23827  */
23828 mblk_t *
23829 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23830 {
23831 	mblk_t *mp;
23832 	ip_lso_info_t *lsoi;
23833 	ill_lso_capab_t *idst;
23834 
23835 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23836 		DB_TYPE(mp) = M_CTL;
23837 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23838 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23839 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23840 		idst = &(lsoi->lso_capab);
23841 
23842 		/*
23843 		 * If the caller provides us with the capability, copy
23844 		 * it over into our notification message; otherwise
23845 		 * we zero out the capability portion.
23846 		 */
23847 		if (isrc != NULL)
23848 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23849 		else
23850 			bzero((caddr_t)idst, sizeof (*idst));
23851 	}
23852 	return (mp);
23853 }
23854 
23855 /*
23856  * Routine which determines whether LSO can be enabled on the destination
23857  * IRE and IPC combination, and if so, allocates and returns the LSO
23858  * notification mblk that may be used by ULP.  We also check if we need to
23859  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23860  * LSO usage in the past have been lifted.  This gets called during IP
23861  * and ULP binding.
23862  */
23863 mblk_t *
23864 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23865     ill_lso_capab_t *lso_cap)
23866 {
23867 	mblk_t *mp;
23868 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23869 
23870 	ASSERT(dst_ire != NULL);
23871 	ASSERT(connp != NULL);
23872 	ASSERT(lso_cap != NULL);
23873 
23874 	connp->conn_lso_ok = B_TRUE;
23875 
23876 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23877 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23878 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23879 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23880 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23881 		connp->conn_lso_ok = B_FALSE;
23882 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23883 			/*
23884 			 * Disable LSO for this and all future connections going
23885 			 * over the interface.
23886 			 */
23887 			lso_cap->ill_lso_on = 0;
23888 		}
23889 	}
23890 
23891 	if (!connp->conn_lso_ok)
23892 		return (NULL);
23893 	else if (!lso_cap->ill_lso_on) {
23894 		/*
23895 		 * If LSO has been previously turned off in the past, and we
23896 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23897 		 * then enable it for this interface.
23898 		 */
23899 		lso_cap->ill_lso_on = 1;
23900 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23901 		    ill_name));
23902 	}
23903 
23904 	/* Allocate the LSO info mblk */
23905 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23906 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23907 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23908 
23909 	return (mp);
23910 }
23911 
23912 /*
23913  * Create destination address attribute, and fill it with the physical
23914  * destination address and SAP taken from the template DL_UNITDATA_REQ
23915  * message block.
23916  */
23917 boolean_t
23918 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23919 {
23920 	dl_unitdata_req_t *dlurp;
23921 	pattr_t *pa;
23922 	pattrinfo_t pa_info;
23923 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23924 	uint_t das_len, das_off;
23925 
23926 	ASSERT(dlmp != NULL);
23927 
23928 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23929 	das_len = dlurp->dl_dest_addr_length;
23930 	das_off = dlurp->dl_dest_addr_offset;
23931 
23932 	pa_info.type = PATTR_DSTADDRSAP;
23933 	pa_info.len = sizeof (**das) + das_len - 1;
23934 
23935 	/* create and associate the attribute */
23936 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23937 	if (pa != NULL) {
23938 		ASSERT(*das != NULL);
23939 		(*das)->addr_is_group = 0;
23940 		(*das)->addr_len = (uint8_t)das_len;
23941 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23942 	}
23943 
23944 	return (pa != NULL);
23945 }
23946 
23947 /*
23948  * Create hardware checksum attribute and fill it with the values passed.
23949  */
23950 boolean_t
23951 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23952     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23953 {
23954 	pattr_t *pa;
23955 	pattrinfo_t pa_info;
23956 
23957 	ASSERT(mmd != NULL);
23958 
23959 	pa_info.type = PATTR_HCKSUM;
23960 	pa_info.len = sizeof (pattr_hcksum_t);
23961 
23962 	/* create and associate the attribute */
23963 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23964 	if (pa != NULL) {
23965 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23966 
23967 		hck->hcksum_start_offset = start_offset;
23968 		hck->hcksum_stuff_offset = stuff_offset;
23969 		hck->hcksum_end_offset = end_offset;
23970 		hck->hcksum_flags = flags;
23971 	}
23972 	return (pa != NULL);
23973 }
23974 
23975 /*
23976  * Create zerocopy attribute and fill it with the specified flags
23977  */
23978 boolean_t
23979 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23980 {
23981 	pattr_t *pa;
23982 	pattrinfo_t pa_info;
23983 
23984 	ASSERT(mmd != NULL);
23985 	pa_info.type = PATTR_ZCOPY;
23986 	pa_info.len = sizeof (pattr_zcopy_t);
23987 
23988 	/* create and associate the attribute */
23989 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23990 	if (pa != NULL) {
23991 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23992 
23993 		zcopy->zcopy_flags = flags;
23994 	}
23995 	return (pa != NULL);
23996 }
23997 
23998 /*
23999  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
24000  * block chain. We could rewrite to handle arbitrary message block chains but
24001  * that would make the code complicated and slow. Right now there three
24002  * restrictions:
24003  *
24004  *   1. The first message block must contain the complete IP header and
24005  *	at least 1 byte of payload data.
24006  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
24007  *	so that we can use a single Multidata message.
24008  *   3. No frag must be distributed over two or more message blocks so
24009  *	that we don't need more than two packet descriptors per frag.
24010  *
24011  * The above restrictions allow us to support userland applications (which
24012  * will send down a single message block) and NFS over UDP (which will
24013  * send down a chain of at most three message blocks).
24014  *
24015  * We also don't use MDT for payloads with less than or equal to
24016  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
24017  */
24018 boolean_t
24019 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
24020 {
24021 	int	blocks;
24022 	ssize_t	total, missing, size;
24023 
24024 	ASSERT(mp != NULL);
24025 	ASSERT(hdr_len > 0);
24026 
24027 	size = MBLKL(mp) - hdr_len;
24028 	if (size <= 0)
24029 		return (B_FALSE);
24030 
24031 	/* The first mblk contains the header and some payload. */
24032 	blocks = 1;
24033 	total = size;
24034 	size %= len;
24035 	missing = (size == 0) ? 0 : (len - size);
24036 	mp = mp->b_cont;
24037 
24038 	while (mp != NULL) {
24039 		/*
24040 		 * Give up if we encounter a zero length message block.
24041 		 * In practice, this should rarely happen and therefore
24042 		 * not worth the trouble of freeing and re-linking the
24043 		 * mblk from the chain to handle such case.
24044 		 */
24045 		if ((size = MBLKL(mp)) == 0)
24046 			return (B_FALSE);
24047 
24048 		/* Too many payload buffers for a single Multidata message? */
24049 		if (++blocks > MULTIDATA_MAX_PBUFS)
24050 			return (B_FALSE);
24051 
24052 		total += size;
24053 		/* Is a frag distributed over two or more message blocks? */
24054 		if (missing > size)
24055 			return (B_FALSE);
24056 		size -= missing;
24057 
24058 		size %= len;
24059 		missing = (size == 0) ? 0 : (len - size);
24060 
24061 		mp = mp->b_cont;
24062 	}
24063 
24064 	return (total > ip_wput_frag_mdt_min);
24065 }
24066 
24067 /*
24068  * Outbound IPv4 fragmentation routine using MDT.
24069  */
24070 static void
24071 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24072     uint32_t frag_flag, int offset)
24073 {
24074 	ipha_t		*ipha_orig;
24075 	int		i1, ip_data_end;
24076 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24077 	mblk_t		*hdr_mp, *md_mp = NULL;
24078 	unsigned char	*hdr_ptr, *pld_ptr;
24079 	multidata_t	*mmd;
24080 	ip_pdescinfo_t	pdi;
24081 	ill_t		*ill;
24082 	ip_stack_t	*ipst = ire->ire_ipst;
24083 
24084 	ASSERT(DB_TYPE(mp) == M_DATA);
24085 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24086 
24087 	ill = ire_to_ill(ire);
24088 	ASSERT(ill != NULL);
24089 
24090 	ipha_orig = (ipha_t *)mp->b_rptr;
24091 	mp->b_rptr += sizeof (ipha_t);
24092 
24093 	/* Calculate how many packets we will send out */
24094 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24095 	pkts = (i1 + len - 1) / len;
24096 	ASSERT(pkts > 1);
24097 
24098 	/* Allocate a message block which will hold all the IP Headers. */
24099 	wroff = ipst->ips_ip_wroff_extra;
24100 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24101 
24102 	i1 = pkts * hdr_chunk_len;
24103 	/*
24104 	 * Create the header buffer, Multidata and destination address
24105 	 * and SAP attribute that should be associated with it.
24106 	 */
24107 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24108 	    ((hdr_mp->b_wptr += i1),
24109 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24110 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24111 		freemsg(mp);
24112 		if (md_mp == NULL) {
24113 			freemsg(hdr_mp);
24114 		} else {
24115 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24116 			freemsg(md_mp);
24117 		}
24118 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24119 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24120 		return;
24121 	}
24122 	IP_STAT(ipst, ip_frag_mdt_allocd);
24123 
24124 	/*
24125 	 * Add a payload buffer to the Multidata; this operation must not
24126 	 * fail, or otherwise our logic in this routine is broken.  There
24127 	 * is no memory allocation done by the routine, so any returned
24128 	 * failure simply tells us that we've done something wrong.
24129 	 *
24130 	 * A failure tells us that either we're adding the same payload
24131 	 * buffer more than once, or we're trying to add more buffers than
24132 	 * allowed.  None of the above cases should happen, and we panic
24133 	 * because either there's horrible heap corruption, and/or
24134 	 * programming mistake.
24135 	 */
24136 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24137 		goto pbuf_panic;
24138 
24139 	hdr_ptr = hdr_mp->b_rptr;
24140 	pld_ptr = mp->b_rptr;
24141 
24142 	/* Establish the ending byte offset, based on the starting offset. */
24143 	offset <<= 3;
24144 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24145 	    IP_SIMPLE_HDR_LENGTH;
24146 
24147 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24148 
24149 	while (pld_ptr < mp->b_wptr) {
24150 		ipha_t		*ipha;
24151 		uint16_t	offset_and_flags;
24152 		uint16_t	ip_len;
24153 		int		error;
24154 
24155 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24156 		ipha = (ipha_t *)(hdr_ptr + wroff);
24157 		ASSERT(OK_32PTR(ipha));
24158 		*ipha = *ipha_orig;
24159 
24160 		if (ip_data_end - offset > len) {
24161 			offset_and_flags = IPH_MF;
24162 		} else {
24163 			/*
24164 			 * Last frag. Set len to the length of this last piece.
24165 			 */
24166 			len = ip_data_end - offset;
24167 			/* A frag of a frag might have IPH_MF non-zero */
24168 			offset_and_flags =
24169 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24170 			    IPH_MF;
24171 		}
24172 		offset_and_flags |= (uint16_t)(offset >> 3);
24173 		offset_and_flags |= (uint16_t)frag_flag;
24174 		/* Store the offset and flags in the IP header. */
24175 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24176 
24177 		/* Store the length in the IP header. */
24178 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24179 		ipha->ipha_length = htons(ip_len);
24180 
24181 		/*
24182 		 * Set the IP header checksum.  Note that mp is just
24183 		 * the header, so this is easy to pass to ip_csum.
24184 		 */
24185 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24186 
24187 		/*
24188 		 * Record offset and size of header and data of the next packet
24189 		 * in the multidata message.
24190 		 */
24191 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24192 		PDESC_PLD_INIT(&pdi);
24193 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24194 		ASSERT(i1 > 0);
24195 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24196 		if (i1 == len) {
24197 			pld_ptr += len;
24198 		} else {
24199 			i1 = len - i1;
24200 			mp = mp->b_cont;
24201 			ASSERT(mp != NULL);
24202 			ASSERT(MBLKL(mp) >= i1);
24203 			/*
24204 			 * Attach the next payload message block to the
24205 			 * multidata message.
24206 			 */
24207 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24208 				goto pbuf_panic;
24209 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24210 			pld_ptr = mp->b_rptr + i1;
24211 		}
24212 
24213 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24214 		    KM_NOSLEEP)) == NULL) {
24215 			/*
24216 			 * Any failure other than ENOMEM indicates that we
24217 			 * have passed in invalid pdesc info or parameters
24218 			 * to mmd_addpdesc, which must not happen.
24219 			 *
24220 			 * EINVAL is a result of failure on boundary checks
24221 			 * against the pdesc info contents.  It should not
24222 			 * happen, and we panic because either there's
24223 			 * horrible heap corruption, and/or programming
24224 			 * mistake.
24225 			 */
24226 			if (error != ENOMEM) {
24227 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24228 				    "pdesc logic error detected for "
24229 				    "mmd %p pinfo %p (%d)\n",
24230 				    (void *)mmd, (void *)&pdi, error);
24231 				/* NOTREACHED */
24232 			}
24233 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24234 			/* Free unattached payload message blocks as well */
24235 			md_mp->b_cont = mp->b_cont;
24236 			goto free_mmd;
24237 		}
24238 
24239 		/* Advance fragment offset. */
24240 		offset += len;
24241 
24242 		/* Advance to location for next header in the buffer. */
24243 		hdr_ptr += hdr_chunk_len;
24244 
24245 		/* Did we reach the next payload message block? */
24246 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24247 			mp = mp->b_cont;
24248 			/*
24249 			 * Attach the next message block with payload
24250 			 * data to the multidata message.
24251 			 */
24252 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24253 				goto pbuf_panic;
24254 			pld_ptr = mp->b_rptr;
24255 		}
24256 	}
24257 
24258 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24259 	ASSERT(mp->b_wptr == pld_ptr);
24260 
24261 	/* Update IP statistics */
24262 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24263 
24264 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24265 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24266 
24267 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24268 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24269 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24270 
24271 	if (pkt_type == OB_PKT) {
24272 		ire->ire_ob_pkt_count += pkts;
24273 		if (ire->ire_ipif != NULL)
24274 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24275 	} else {
24276 		/*
24277 		 * The type is IB_PKT in the forwarding path and in
24278 		 * the mobile IP case when the packet is being reverse-
24279 		 * tunneled to the home agent.
24280 		 */
24281 		ire->ire_ib_pkt_count += pkts;
24282 		ASSERT(!IRE_IS_LOCAL(ire));
24283 		if (ire->ire_type & IRE_BROADCAST) {
24284 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24285 		} else {
24286 			UPDATE_MIB(ill->ill_ip_mib,
24287 			    ipIfStatsHCOutForwDatagrams, pkts);
24288 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24289 		}
24290 	}
24291 	ire->ire_last_used_time = lbolt;
24292 	/* Send it down */
24293 	putnext(ire->ire_stq, md_mp);
24294 	return;
24295 
24296 pbuf_panic:
24297 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24298 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24299 	    pbuf_idx);
24300 	/* NOTREACHED */
24301 }
24302 
24303 /*
24304  * Outbound IP fragmentation routine.
24305  *
24306  * NOTE : This routine does not ire_refrele the ire that is passed in
24307  * as the argument.
24308  */
24309 static void
24310 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24311     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24312 {
24313 	int		i1;
24314 	mblk_t		*ll_hdr_mp;
24315 	int 		ll_hdr_len;
24316 	int		hdr_len;
24317 	mblk_t		*hdr_mp;
24318 	ipha_t		*ipha;
24319 	int		ip_data_end;
24320 	int		len;
24321 	mblk_t		*mp = mp_orig, *mp1;
24322 	int		offset;
24323 	queue_t		*q;
24324 	uint32_t	v_hlen_tos_len;
24325 	mblk_t		*first_mp;
24326 	boolean_t	mctl_present;
24327 	ill_t		*ill;
24328 	ill_t		*out_ill;
24329 	mblk_t		*xmit_mp;
24330 	mblk_t		*carve_mp;
24331 	ire_t		*ire1 = NULL;
24332 	ire_t		*save_ire = NULL;
24333 	mblk_t  	*next_mp = NULL;
24334 	boolean_t	last_frag = B_FALSE;
24335 	boolean_t	multirt_send = B_FALSE;
24336 	ire_t		*first_ire = NULL;
24337 	irb_t		*irb = NULL;
24338 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24339 
24340 	ill = ire_to_ill(ire);
24341 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24342 
24343 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24344 
24345 	/*
24346 	 * IPSEC does not allow hw accelerated packets to be fragmented
24347 	 * This check is made in ip_wput_ipsec_out prior to coming here
24348 	 * via ip_wput_ire_fragmentit.
24349 	 *
24350 	 * If at this point we have an ire whose ARP request has not
24351 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24352 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24353 	 * This packet and all fragmentable packets for this ire will
24354 	 * continue to get dropped while ire_nce->nce_state remains in
24355 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24356 	 * ND_REACHABLE, all subsquent large packets for this ire will
24357 	 * get fragemented and sent out by this function.
24358 	 */
24359 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24360 		/* If nce_state is ND_INITIAL, trigger ARP query */
24361 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24362 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24363 		    " -  dropping packet\n"));
24364 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24365 		freemsg(mp);
24366 		return;
24367 	}
24368 
24369 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24370 	    "ip_wput_frag_start:");
24371 
24372 	if (mp->b_datap->db_type == M_CTL) {
24373 		first_mp = mp;
24374 		mp_orig = mp = mp->b_cont;
24375 		mctl_present = B_TRUE;
24376 	} else {
24377 		first_mp = mp;
24378 		mctl_present = B_FALSE;
24379 	}
24380 
24381 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24382 	ipha = (ipha_t *)mp->b_rptr;
24383 
24384 	/*
24385 	 * If the Don't Fragment flag is on, generate an ICMP destination
24386 	 * unreachable, fragmentation needed.
24387 	 */
24388 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24389 	if (offset & IPH_DF) {
24390 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24391 		/*
24392 		 * Need to compute hdr checksum if called from ip_wput_ire.
24393 		 * Note that ip_rput_forward verifies the checksum before
24394 		 * calling this routine so in that case this is a noop.
24395 		 */
24396 		ipha->ipha_hdr_checksum = 0;
24397 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24398 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24399 		    ipst);
24400 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24401 		    "ip_wput_frag_end:(%S)",
24402 		    "don't fragment");
24403 		return;
24404 	}
24405 	if (mctl_present)
24406 		freeb(first_mp);
24407 	/*
24408 	 * Establish the starting offset.  May not be zero if we are fragging
24409 	 * a fragment that is being forwarded.
24410 	 */
24411 	offset = offset & IPH_OFFSET;
24412 
24413 	/* TODO why is this test needed? */
24414 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24415 	if (((max_frag - LENGTH) & ~7) < 8) {
24416 		/* TODO: notify ulp somehow */
24417 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24418 		freemsg(mp);
24419 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24420 		    "ip_wput_frag_end:(%S)",
24421 		    "len < 8");
24422 		return;
24423 	}
24424 
24425 	hdr_len = (V_HLEN & 0xF) << 2;
24426 
24427 	ipha->ipha_hdr_checksum = 0;
24428 
24429 	/*
24430 	 * Establish the number of bytes maximum per frag, after putting
24431 	 * in the header.
24432 	 */
24433 	len = (max_frag - hdr_len) & ~7;
24434 
24435 	/* Check if we can use MDT to send out the frags. */
24436 	ASSERT(!IRE_IS_LOCAL(ire));
24437 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24438 	    ipst->ips_ip_multidata_outbound &&
24439 	    !(ire->ire_flags & RTF_MULTIRT) &&
24440 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24441 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24442 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24443 		ASSERT(ill->ill_mdt_capab != NULL);
24444 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24445 			/*
24446 			 * If MDT has been previously turned off in the past,
24447 			 * and we currently can do MDT (due to IPQoS policy
24448 			 * removal, etc.) then enable it for this interface.
24449 			 */
24450 			ill->ill_mdt_capab->ill_mdt_on = 1;
24451 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24452 			    ill->ill_name));
24453 		}
24454 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24455 		    offset);
24456 		return;
24457 	}
24458 
24459 	/* Get a copy of the header for the trailing frags */
24460 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24461 	if (!hdr_mp) {
24462 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24463 		freemsg(mp);
24464 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24465 		    "ip_wput_frag_end:(%S)",
24466 		    "couldn't copy hdr");
24467 		return;
24468 	}
24469 	if (DB_CRED(mp) != NULL)
24470 		mblk_setcred(hdr_mp, DB_CRED(mp));
24471 
24472 	/* Store the starting offset, with the MoreFrags flag. */
24473 	i1 = offset | IPH_MF | frag_flag;
24474 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24475 
24476 	/* Establish the ending byte offset, based on the starting offset. */
24477 	offset <<= 3;
24478 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24479 
24480 	/* Store the length of the first fragment in the IP header. */
24481 	i1 = len + hdr_len;
24482 	ASSERT(i1 <= IP_MAXPACKET);
24483 	ipha->ipha_length = htons((uint16_t)i1);
24484 
24485 	/*
24486 	 * Compute the IP header checksum for the first frag.  We have to
24487 	 * watch out that we stop at the end of the header.
24488 	 */
24489 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24490 
24491 	/*
24492 	 * Now carve off the first frag.  Note that this will include the
24493 	 * original IP header.
24494 	 */
24495 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24496 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24497 		freeb(hdr_mp);
24498 		freemsg(mp_orig);
24499 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24500 		    "ip_wput_frag_end:(%S)",
24501 		    "couldn't carve first");
24502 		return;
24503 	}
24504 
24505 	/*
24506 	 * Multirouting case. Each fragment is replicated
24507 	 * via all non-condemned RTF_MULTIRT routes
24508 	 * currently resolved.
24509 	 * We ensure that first_ire is the first RTF_MULTIRT
24510 	 * ire in the bucket.
24511 	 */
24512 	if (ire->ire_flags & RTF_MULTIRT) {
24513 		irb = ire->ire_bucket;
24514 		ASSERT(irb != NULL);
24515 
24516 		multirt_send = B_TRUE;
24517 
24518 		/* Make sure we do not omit any multiroute ire. */
24519 		IRB_REFHOLD(irb);
24520 		for (first_ire = irb->irb_ire;
24521 		    first_ire != NULL;
24522 		    first_ire = first_ire->ire_next) {
24523 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24524 			    (first_ire->ire_addr == ire->ire_addr) &&
24525 			    !(first_ire->ire_marks &
24526 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
24527 				break;
24528 		}
24529 
24530 		if (first_ire != NULL) {
24531 			if (first_ire != ire) {
24532 				IRE_REFHOLD(first_ire);
24533 				/*
24534 				 * Do not release the ire passed in
24535 				 * as the argument.
24536 				 */
24537 				ire = first_ire;
24538 			} else {
24539 				first_ire = NULL;
24540 			}
24541 		}
24542 		IRB_REFRELE(irb);
24543 
24544 		/*
24545 		 * Save the first ire; we will need to restore it
24546 		 * for the trailing frags.
24547 		 * We REFHOLD save_ire, as each iterated ire will be
24548 		 * REFRELEd.
24549 		 */
24550 		save_ire = ire;
24551 		IRE_REFHOLD(save_ire);
24552 	}
24553 
24554 	/*
24555 	 * First fragment emission loop.
24556 	 * In most cases, the emission loop below is entered only
24557 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24558 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24559 	 * bucket, and send the fragment through all crossed
24560 	 * RTF_MULTIRT routes.
24561 	 */
24562 	do {
24563 		if (ire->ire_flags & RTF_MULTIRT) {
24564 			/*
24565 			 * We are in a multiple send case, need to get
24566 			 * the next ire and make a copy of the packet.
24567 			 * ire1 holds here the next ire to process in the
24568 			 * bucket. If multirouting is expected,
24569 			 * any non-RTF_MULTIRT ire that has the
24570 			 * right destination address is ignored.
24571 			 *
24572 			 * We have to take into account the MTU of
24573 			 * each walked ire. max_frag is set by the
24574 			 * the caller and generally refers to
24575 			 * the primary ire entry. Here we ensure that
24576 			 * no route with a lower MTU will be used, as
24577 			 * fragments are carved once for all ires,
24578 			 * then replicated.
24579 			 */
24580 			ASSERT(irb != NULL);
24581 			IRB_REFHOLD(irb);
24582 			for (ire1 = ire->ire_next;
24583 			    ire1 != NULL;
24584 			    ire1 = ire1->ire_next) {
24585 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24586 					continue;
24587 				if (ire1->ire_addr != ire->ire_addr)
24588 					continue;
24589 				if (ire1->ire_marks &
24590 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24591 					continue;
24592 				/*
24593 				 * Ensure we do not exceed the MTU
24594 				 * of the next route.
24595 				 */
24596 				if (ire1->ire_max_frag < max_frag) {
24597 					ip_multirt_bad_mtu(ire1, max_frag);
24598 					continue;
24599 				}
24600 
24601 				/* Got one. */
24602 				IRE_REFHOLD(ire1);
24603 				break;
24604 			}
24605 			IRB_REFRELE(irb);
24606 
24607 			if (ire1 != NULL) {
24608 				next_mp = copyb(mp);
24609 				if ((next_mp == NULL) ||
24610 				    ((mp->b_cont != NULL) &&
24611 				    ((next_mp->b_cont =
24612 				    dupmsg(mp->b_cont)) == NULL))) {
24613 					freemsg(next_mp);
24614 					next_mp = NULL;
24615 					ire_refrele(ire1);
24616 					ire1 = NULL;
24617 				}
24618 			}
24619 
24620 			/* Last multiroute ire; don't loop anymore. */
24621 			if (ire1 == NULL) {
24622 				multirt_send = B_FALSE;
24623 			}
24624 		}
24625 
24626 		ll_hdr_len = 0;
24627 		LOCK_IRE_FP_MP(ire);
24628 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24629 		if (ll_hdr_mp != NULL) {
24630 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24631 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24632 		} else {
24633 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24634 		}
24635 
24636 		/* If there is a transmit header, get a copy for this frag. */
24637 		/*
24638 		 * TODO: should check db_ref before calling ip_carve_mp since
24639 		 * it might give us a dup.
24640 		 */
24641 		if (!ll_hdr_mp) {
24642 			/* No xmit header. */
24643 			xmit_mp = mp;
24644 
24645 		/* We have a link-layer header that can fit in our mblk. */
24646 		} else if (mp->b_datap->db_ref == 1 &&
24647 		    ll_hdr_len != 0 &&
24648 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24649 			/* M_DATA fastpath */
24650 			mp->b_rptr -= ll_hdr_len;
24651 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24652 			xmit_mp = mp;
24653 
24654 		/* Corner case if copyb has failed */
24655 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24656 			UNLOCK_IRE_FP_MP(ire);
24657 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24658 			freeb(hdr_mp);
24659 			freemsg(mp);
24660 			freemsg(mp_orig);
24661 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24662 			    "ip_wput_frag_end:(%S)",
24663 			    "discard");
24664 
24665 			if (multirt_send) {
24666 				ASSERT(ire1);
24667 				ASSERT(next_mp);
24668 
24669 				freemsg(next_mp);
24670 				ire_refrele(ire1);
24671 			}
24672 			if (save_ire != NULL)
24673 				IRE_REFRELE(save_ire);
24674 
24675 			if (first_ire != NULL)
24676 				ire_refrele(first_ire);
24677 			return;
24678 
24679 		/*
24680 		 * Case of res_mp OR the fastpath mp can't fit
24681 		 * in the mblk
24682 		 */
24683 		} else {
24684 			xmit_mp->b_cont = mp;
24685 			if (DB_CRED(mp) != NULL)
24686 				mblk_setcred(xmit_mp, DB_CRED(mp));
24687 			/*
24688 			 * Get priority marking, if any.
24689 			 * We propagate the CoS marking from the
24690 			 * original packet that went to QoS processing
24691 			 * in ip_wput_ire to the newly carved mp.
24692 			 */
24693 			if (DB_TYPE(xmit_mp) == M_DATA)
24694 				xmit_mp->b_band = mp->b_band;
24695 		}
24696 		UNLOCK_IRE_FP_MP(ire);
24697 
24698 		q = ire->ire_stq;
24699 		out_ill = (ill_t *)q->q_ptr;
24700 
24701 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24702 
24703 		DTRACE_PROBE4(ip4__physical__out__start,
24704 		    ill_t *, NULL, ill_t *, out_ill,
24705 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24706 
24707 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24708 		    ipst->ips_ipv4firewall_physical_out,
24709 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24710 
24711 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24712 
24713 		if (xmit_mp != NULL) {
24714 			putnext(q, xmit_mp);
24715 
24716 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24717 			UPDATE_MIB(out_ill->ill_ip_mib,
24718 			    ipIfStatsHCOutOctets, i1);
24719 
24720 			if (pkt_type != OB_PKT) {
24721 				/*
24722 				 * Update the packet count and MIB stats
24723 				 * of trailing RTF_MULTIRT ires.
24724 				 */
24725 				UPDATE_OB_PKT_COUNT(ire);
24726 				BUMP_MIB(out_ill->ill_ip_mib,
24727 				    ipIfStatsOutFragReqds);
24728 			}
24729 		}
24730 
24731 		if (multirt_send) {
24732 			/*
24733 			 * We are in a multiple send case; look for
24734 			 * the next ire and re-enter the loop.
24735 			 */
24736 			ASSERT(ire1);
24737 			ASSERT(next_mp);
24738 			/* REFRELE the current ire before looping */
24739 			ire_refrele(ire);
24740 			ire = ire1;
24741 			ire1 = NULL;
24742 			mp = next_mp;
24743 			next_mp = NULL;
24744 		}
24745 	} while (multirt_send);
24746 
24747 	ASSERT(ire1 == NULL);
24748 
24749 	/* Restore the original ire; we need it for the trailing frags */
24750 	if (save_ire != NULL) {
24751 		/* REFRELE the last iterated ire */
24752 		ire_refrele(ire);
24753 		/* save_ire has been REFHOLDed */
24754 		ire = save_ire;
24755 		save_ire = NULL;
24756 		q = ire->ire_stq;
24757 	}
24758 
24759 	if (pkt_type == OB_PKT) {
24760 		UPDATE_OB_PKT_COUNT(ire);
24761 	} else {
24762 		out_ill = (ill_t *)q->q_ptr;
24763 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24764 		UPDATE_IB_PKT_COUNT(ire);
24765 	}
24766 
24767 	/* Advance the offset to the second frag starting point. */
24768 	offset += len;
24769 	/*
24770 	 * Update hdr_len from the copied header - there might be less options
24771 	 * in the later fragments.
24772 	 */
24773 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24774 	/* Loop until done. */
24775 	for (;;) {
24776 		uint16_t	offset_and_flags;
24777 		uint16_t	ip_len;
24778 
24779 		if (ip_data_end - offset > len) {
24780 			/*
24781 			 * Carve off the appropriate amount from the original
24782 			 * datagram.
24783 			 */
24784 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24785 				mp = NULL;
24786 				break;
24787 			}
24788 			/*
24789 			 * More frags after this one.  Get another copy
24790 			 * of the header.
24791 			 */
24792 			if (carve_mp->b_datap->db_ref == 1 &&
24793 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24794 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24795 				/* Inline IP header */
24796 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24797 				    hdr_mp->b_rptr;
24798 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24799 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24800 				mp = carve_mp;
24801 			} else {
24802 				if (!(mp = copyb(hdr_mp))) {
24803 					freemsg(carve_mp);
24804 					break;
24805 				}
24806 				/* Get priority marking, if any. */
24807 				mp->b_band = carve_mp->b_band;
24808 				mp->b_cont = carve_mp;
24809 			}
24810 			ipha = (ipha_t *)mp->b_rptr;
24811 			offset_and_flags = IPH_MF;
24812 		} else {
24813 			/*
24814 			 * Last frag.  Consume the header. Set len to
24815 			 * the length of this last piece.
24816 			 */
24817 			len = ip_data_end - offset;
24818 
24819 			/*
24820 			 * Carve off the appropriate amount from the original
24821 			 * datagram.
24822 			 */
24823 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24824 				mp = NULL;
24825 				break;
24826 			}
24827 			if (carve_mp->b_datap->db_ref == 1 &&
24828 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24829 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24830 				/* Inline IP header */
24831 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24832 				    hdr_mp->b_rptr;
24833 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24834 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24835 				mp = carve_mp;
24836 				freeb(hdr_mp);
24837 				hdr_mp = mp;
24838 			} else {
24839 				mp = hdr_mp;
24840 				/* Get priority marking, if any. */
24841 				mp->b_band = carve_mp->b_band;
24842 				mp->b_cont = carve_mp;
24843 			}
24844 			ipha = (ipha_t *)mp->b_rptr;
24845 			/* A frag of a frag might have IPH_MF non-zero */
24846 			offset_and_flags =
24847 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24848 			    IPH_MF;
24849 		}
24850 		offset_and_flags |= (uint16_t)(offset >> 3);
24851 		offset_and_flags |= (uint16_t)frag_flag;
24852 		/* Store the offset and flags in the IP header. */
24853 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24854 
24855 		/* Store the length in the IP header. */
24856 		ip_len = (uint16_t)(len + hdr_len);
24857 		ipha->ipha_length = htons(ip_len);
24858 
24859 		/*
24860 		 * Set the IP header checksum.	Note that mp is just
24861 		 * the header, so this is easy to pass to ip_csum.
24862 		 */
24863 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24864 
24865 		/* Attach a transmit header, if any, and ship it. */
24866 		if (pkt_type == OB_PKT) {
24867 			UPDATE_OB_PKT_COUNT(ire);
24868 		} else {
24869 			out_ill = (ill_t *)q->q_ptr;
24870 			BUMP_MIB(out_ill->ill_ip_mib,
24871 			    ipIfStatsHCOutForwDatagrams);
24872 			UPDATE_IB_PKT_COUNT(ire);
24873 		}
24874 
24875 		if (ire->ire_flags & RTF_MULTIRT) {
24876 			irb = ire->ire_bucket;
24877 			ASSERT(irb != NULL);
24878 
24879 			multirt_send = B_TRUE;
24880 
24881 			/*
24882 			 * Save the original ire; we will need to restore it
24883 			 * for the tailing frags.
24884 			 */
24885 			save_ire = ire;
24886 			IRE_REFHOLD(save_ire);
24887 		}
24888 		/*
24889 		 * Emission loop for this fragment, similar
24890 		 * to what is done for the first fragment.
24891 		 */
24892 		do {
24893 			if (multirt_send) {
24894 				/*
24895 				 * We are in a multiple send case, need to get
24896 				 * the next ire and make a copy of the packet.
24897 				 */
24898 				ASSERT(irb != NULL);
24899 				IRB_REFHOLD(irb);
24900 				for (ire1 = ire->ire_next;
24901 				    ire1 != NULL;
24902 				    ire1 = ire1->ire_next) {
24903 					if (!(ire1->ire_flags & RTF_MULTIRT))
24904 						continue;
24905 					if (ire1->ire_addr != ire->ire_addr)
24906 						continue;
24907 					if (ire1->ire_marks &
24908 					    (IRE_MARK_CONDEMNED|
24909 						IRE_MARK_HIDDEN))
24910 						continue;
24911 					/*
24912 					 * Ensure we do not exceed the MTU
24913 					 * of the next route.
24914 					 */
24915 					if (ire1->ire_max_frag < max_frag) {
24916 						ip_multirt_bad_mtu(ire1,
24917 						    max_frag);
24918 						continue;
24919 					}
24920 
24921 					/* Got one. */
24922 					IRE_REFHOLD(ire1);
24923 					break;
24924 				}
24925 				IRB_REFRELE(irb);
24926 
24927 				if (ire1 != NULL) {
24928 					next_mp = copyb(mp);
24929 					if ((next_mp == NULL) ||
24930 					    ((mp->b_cont != NULL) &&
24931 					    ((next_mp->b_cont =
24932 					    dupmsg(mp->b_cont)) == NULL))) {
24933 						freemsg(next_mp);
24934 						next_mp = NULL;
24935 						ire_refrele(ire1);
24936 						ire1 = NULL;
24937 					}
24938 				}
24939 
24940 				/* Last multiroute ire; don't loop anymore. */
24941 				if (ire1 == NULL) {
24942 					multirt_send = B_FALSE;
24943 				}
24944 			}
24945 
24946 			/* Update transmit header */
24947 			ll_hdr_len = 0;
24948 			LOCK_IRE_FP_MP(ire);
24949 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24950 			if (ll_hdr_mp != NULL) {
24951 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24952 				ll_hdr_len = MBLKL(ll_hdr_mp);
24953 			} else {
24954 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24955 			}
24956 
24957 			if (!ll_hdr_mp) {
24958 				xmit_mp = mp;
24959 
24960 			/*
24961 			 * We have link-layer header that can fit in
24962 			 * our mblk.
24963 			 */
24964 			} else if (mp->b_datap->db_ref == 1 &&
24965 			    ll_hdr_len != 0 &&
24966 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24967 				/* M_DATA fastpath */
24968 				mp->b_rptr -= ll_hdr_len;
24969 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24970 				    ll_hdr_len);
24971 				xmit_mp = mp;
24972 
24973 			/*
24974 			 * Case of res_mp OR the fastpath mp can't fit
24975 			 * in the mblk
24976 			 */
24977 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24978 				xmit_mp->b_cont = mp;
24979 				if (DB_CRED(mp) != NULL)
24980 					mblk_setcred(xmit_mp, DB_CRED(mp));
24981 				/* Get priority marking, if any. */
24982 				if (DB_TYPE(xmit_mp) == M_DATA)
24983 					xmit_mp->b_band = mp->b_band;
24984 
24985 			/* Corner case if copyb failed */
24986 			} else {
24987 				/*
24988 				 * Exit both the replication and
24989 				 * fragmentation loops.
24990 				 */
24991 				UNLOCK_IRE_FP_MP(ire);
24992 				goto drop_pkt;
24993 			}
24994 			UNLOCK_IRE_FP_MP(ire);
24995 
24996 			mp1 = mp;
24997 			out_ill = (ill_t *)q->q_ptr;
24998 
24999 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25000 
25001 			DTRACE_PROBE4(ip4__physical__out__start,
25002 			    ill_t *, NULL, ill_t *, out_ill,
25003 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25004 
25005 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25006 			    ipst->ips_ipv4firewall_physical_out,
25007 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25008 
25009 			DTRACE_PROBE1(ip4__physical__out__end,
25010 			    mblk_t *, xmit_mp);
25011 
25012 			if (mp != mp1 && hdr_mp == mp1)
25013 				hdr_mp = mp;
25014 			if (mp != mp1 && mp_orig == mp1)
25015 				mp_orig = mp;
25016 
25017 			if (xmit_mp != NULL) {
25018 				putnext(q, xmit_mp);
25019 
25020 				BUMP_MIB(out_ill->ill_ip_mib,
25021 				    ipIfStatsHCOutTransmits);
25022 				UPDATE_MIB(out_ill->ill_ip_mib,
25023 				    ipIfStatsHCOutOctets, ip_len);
25024 
25025 				if (pkt_type != OB_PKT) {
25026 					/*
25027 					 * Update the packet count of trailing
25028 					 * RTF_MULTIRT ires.
25029 					 */
25030 					UPDATE_OB_PKT_COUNT(ire);
25031 				}
25032 			}
25033 
25034 			/* All done if we just consumed the hdr_mp. */
25035 			if (mp == hdr_mp) {
25036 				last_frag = B_TRUE;
25037 				BUMP_MIB(out_ill->ill_ip_mib,
25038 				    ipIfStatsOutFragOKs);
25039 			}
25040 
25041 			if (multirt_send) {
25042 				/*
25043 				 * We are in a multiple send case; look for
25044 				 * the next ire and re-enter the loop.
25045 				 */
25046 				ASSERT(ire1);
25047 				ASSERT(next_mp);
25048 				/* REFRELE the current ire before looping */
25049 				ire_refrele(ire);
25050 				ire = ire1;
25051 				ire1 = NULL;
25052 				q = ire->ire_stq;
25053 				mp = next_mp;
25054 				next_mp = NULL;
25055 			}
25056 		} while (multirt_send);
25057 		/*
25058 		 * Restore the original ire; we need it for the
25059 		 * trailing frags
25060 		 */
25061 		if (save_ire != NULL) {
25062 			ASSERT(ire1 == NULL);
25063 			/* REFRELE the last iterated ire */
25064 			ire_refrele(ire);
25065 			/* save_ire has been REFHOLDed */
25066 			ire = save_ire;
25067 			q = ire->ire_stq;
25068 			save_ire = NULL;
25069 		}
25070 
25071 		if (last_frag) {
25072 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25073 			    "ip_wput_frag_end:(%S)",
25074 			    "consumed hdr_mp");
25075 
25076 			if (first_ire != NULL)
25077 				ire_refrele(first_ire);
25078 			return;
25079 		}
25080 		/* Otherwise, advance and loop. */
25081 		offset += len;
25082 	}
25083 
25084 drop_pkt:
25085 	/* Clean up following allocation failure. */
25086 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25087 	freemsg(mp);
25088 	if (mp != hdr_mp)
25089 		freeb(hdr_mp);
25090 	if (mp != mp_orig)
25091 		freemsg(mp_orig);
25092 
25093 	if (save_ire != NULL)
25094 		IRE_REFRELE(save_ire);
25095 	if (first_ire != NULL)
25096 		ire_refrele(first_ire);
25097 
25098 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25099 	    "ip_wput_frag_end:(%S)",
25100 	    "end--alloc failure");
25101 }
25102 
25103 /*
25104  * Copy the header plus those options which have the copy bit set
25105  */
25106 static mblk_t *
25107 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25108 {
25109 	mblk_t	*mp;
25110 	uchar_t	*up;
25111 
25112 	/*
25113 	 * Quick check if we need to look for options without the copy bit
25114 	 * set
25115 	 */
25116 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25117 	if (!mp)
25118 		return (mp);
25119 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25120 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25121 		bcopy(rptr, mp->b_rptr, hdr_len);
25122 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25123 		return (mp);
25124 	}
25125 	up  = mp->b_rptr;
25126 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25127 	up += IP_SIMPLE_HDR_LENGTH;
25128 	rptr += IP_SIMPLE_HDR_LENGTH;
25129 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25130 	while (hdr_len > 0) {
25131 		uint32_t optval;
25132 		uint32_t optlen;
25133 
25134 		optval = *rptr;
25135 		if (optval == IPOPT_EOL)
25136 			break;
25137 		if (optval == IPOPT_NOP)
25138 			optlen = 1;
25139 		else
25140 			optlen = rptr[1];
25141 		if (optval & IPOPT_COPY) {
25142 			bcopy(rptr, up, optlen);
25143 			up += optlen;
25144 		}
25145 		rptr += optlen;
25146 		hdr_len -= optlen;
25147 	}
25148 	/*
25149 	 * Make sure that we drop an even number of words by filling
25150 	 * with EOL to the next word boundary.
25151 	 */
25152 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25153 	    hdr_len & 0x3; hdr_len++)
25154 		*up++ = IPOPT_EOL;
25155 	mp->b_wptr = up;
25156 	/* Update header length */
25157 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25158 	return (mp);
25159 }
25160 
25161 /*
25162  * Delivery to local recipients including fanout to multiple recipients.
25163  * Does not do checksumming of UDP/TCP.
25164  * Note: q should be the read side queue for either the ill or conn.
25165  * Note: rq should be the read side q for the lower (ill) stream.
25166  * We don't send packets to IPPF processing, thus the last argument
25167  * to all the fanout calls are B_FALSE.
25168  */
25169 void
25170 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25171     int fanout_flags, zoneid_t zoneid)
25172 {
25173 	uint32_t	protocol;
25174 	mblk_t		*first_mp;
25175 	boolean_t	mctl_present;
25176 	int		ire_type;
25177 #define	rptr	((uchar_t *)ipha)
25178 	ip_stack_t	*ipst = ill->ill_ipst;
25179 
25180 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25181 	    "ip_wput_local_start: q %p", q);
25182 
25183 	if (ire != NULL) {
25184 		ire_type = ire->ire_type;
25185 	} else {
25186 		/*
25187 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25188 		 * packet is not multicast, we can't tell the ire type.
25189 		 */
25190 		ASSERT(CLASSD(ipha->ipha_dst));
25191 		ire_type = IRE_BROADCAST;
25192 	}
25193 
25194 	first_mp = mp;
25195 	if (first_mp->b_datap->db_type == M_CTL) {
25196 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25197 		if (!io->ipsec_out_secure) {
25198 			/*
25199 			 * This ipsec_out_t was allocated in ip_wput
25200 			 * for multicast packets to store the ill_index.
25201 			 * As this is being delivered locally, we don't
25202 			 * need this anymore.
25203 			 */
25204 			mp = first_mp->b_cont;
25205 			freeb(first_mp);
25206 			first_mp = mp;
25207 			mctl_present = B_FALSE;
25208 		} else {
25209 			/*
25210 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25211 			 * security properties for the looped-back packet.
25212 			 */
25213 			mctl_present = B_TRUE;
25214 			mp = first_mp->b_cont;
25215 			ASSERT(mp != NULL);
25216 			ipsec_out_to_in(first_mp);
25217 		}
25218 	} else {
25219 		mctl_present = B_FALSE;
25220 	}
25221 
25222 	DTRACE_PROBE4(ip4__loopback__in__start,
25223 	    ill_t *, ill, ill_t *, NULL,
25224 	    ipha_t *, ipha, mblk_t *, first_mp);
25225 
25226 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25227 	    ipst->ips_ipv4firewall_loopback_in,
25228 	    ill, NULL, ipha, first_mp, mp, ipst);
25229 
25230 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25231 
25232 	if (first_mp == NULL)
25233 		return;
25234 
25235 	ipst->ips_loopback_packets++;
25236 
25237 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25238 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25239 	if (!IS_SIMPLE_IPH(ipha)) {
25240 		ip_wput_local_options(ipha, ipst);
25241 	}
25242 
25243 	protocol = ipha->ipha_protocol;
25244 	switch (protocol) {
25245 	case IPPROTO_ICMP: {
25246 		ire_t		*ire_zone;
25247 		ilm_t		*ilm;
25248 		mblk_t		*mp1;
25249 		zoneid_t	last_zoneid;
25250 
25251 		if (CLASSD(ipha->ipha_dst) &&
25252 		    !(ill->ill_phyint->phyint_flags & PHYI_LOOPBACK)) {
25253 			ASSERT(ire_type == IRE_BROADCAST);
25254 			/*
25255 			 * In the multicast case, applications may have joined
25256 			 * the group from different zones, so we need to deliver
25257 			 * the packet to each of them. Loop through the
25258 			 * multicast memberships structures (ilm) on the receive
25259 			 * ill and send a copy of the packet up each matching
25260 			 * one. However, we don't do this for multicasts sent on
25261 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25262 			 * they must stay in the sender's zone.
25263 			 *
25264 			 * ilm_add_v6() ensures that ilms in the same zone are
25265 			 * contiguous in the ill_ilm list. We use this property
25266 			 * to avoid sending duplicates needed when two
25267 			 * applications in the same zone join the same group on
25268 			 * different logical interfaces: we ignore the ilm if
25269 			 * it's zoneid is the same as the last matching one.
25270 			 * In addition, the sending of the packet for
25271 			 * ire_zoneid is delayed until all of the other ilms
25272 			 * have been exhausted.
25273 			 */
25274 			last_zoneid = -1;
25275 			ILM_WALKER_HOLD(ill);
25276 			for (ilm = ill->ill_ilm; ilm != NULL;
25277 			    ilm = ilm->ilm_next) {
25278 				if ((ilm->ilm_flags & ILM_DELETED) ||
25279 				    ipha->ipha_dst != ilm->ilm_addr ||
25280 				    ilm->ilm_zoneid == last_zoneid ||
25281 				    ilm->ilm_zoneid == zoneid ||
25282 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25283 					continue;
25284 				mp1 = ip_copymsg(first_mp);
25285 				if (mp1 == NULL)
25286 					continue;
25287 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25288 				    mctl_present, B_FALSE, ill,
25289 				    ilm->ilm_zoneid);
25290 				last_zoneid = ilm->ilm_zoneid;
25291 			}
25292 			ILM_WALKER_RELE(ill);
25293 			/*
25294 			 * Loopback case: the sending endpoint has
25295 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25296 			 * dispatch the multicast packet to the sending zone.
25297 			 */
25298 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25299 				freemsg(first_mp);
25300 				return;
25301 			}
25302 		} else if (ire_type == IRE_BROADCAST) {
25303 			/*
25304 			 * In the broadcast case, there may be many zones
25305 			 * which need a copy of the packet delivered to them.
25306 			 * There is one IRE_BROADCAST per broadcast address
25307 			 * and per zone; we walk those using a helper function.
25308 			 * In addition, the sending of the packet for zoneid is
25309 			 * delayed until all of the other ires have been
25310 			 * processed.
25311 			 */
25312 			IRB_REFHOLD(ire->ire_bucket);
25313 			ire_zone = NULL;
25314 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25315 			    ire)) != NULL) {
25316 				mp1 = ip_copymsg(first_mp);
25317 				if (mp1 == NULL)
25318 					continue;
25319 
25320 				UPDATE_IB_PKT_COUNT(ire_zone);
25321 				ire_zone->ire_last_used_time = lbolt;
25322 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25323 				    mctl_present, B_FALSE, ill,
25324 				    ire_zone->ire_zoneid);
25325 			}
25326 			IRB_REFRELE(ire->ire_bucket);
25327 		}
25328 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25329 		    0, mctl_present, B_FALSE, ill, zoneid);
25330 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25331 		    "ip_wput_local_end: q %p (%S)",
25332 		    q, "icmp");
25333 		return;
25334 	}
25335 	case IPPROTO_IGMP:
25336 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25337 			/* Bad packet - discarded by igmp_input */
25338 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25339 			    "ip_wput_local_end: q %p (%S)",
25340 			    q, "igmp_input--bad packet");
25341 			if (mctl_present)
25342 				freeb(first_mp);
25343 			return;
25344 		}
25345 		/*
25346 		 * igmp_input() may have returned the pulled up message.
25347 		 * So first_mp and ipha need to be reinitialized.
25348 		 */
25349 		ipha = (ipha_t *)mp->b_rptr;
25350 		if (mctl_present)
25351 			first_mp->b_cont = mp;
25352 		else
25353 			first_mp = mp;
25354 		/* deliver to local raw users */
25355 		break;
25356 	case IPPROTO_ENCAP:
25357 		/*
25358 		 * This case is covered by either ip_fanout_proto, or by
25359 		 * the above security processing for self-tunneled packets.
25360 		 */
25361 		break;
25362 	case IPPROTO_UDP: {
25363 		uint16_t	*up;
25364 		uint32_t	ports;
25365 
25366 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25367 		    UDP_PORTS_OFFSET);
25368 		/* Force a 'valid' checksum. */
25369 		up[3] = 0;
25370 
25371 		ports = *(uint32_t *)up;
25372 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25373 		    (ire_type == IRE_BROADCAST),
25374 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25375 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25376 		    ill, zoneid);
25377 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25378 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25379 		return;
25380 	}
25381 	case IPPROTO_TCP: {
25382 
25383 		/*
25384 		 * For TCP, discard broadcast packets.
25385 		 */
25386 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25387 			freemsg(first_mp);
25388 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25389 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25390 			return;
25391 		}
25392 
25393 		if (mp->b_datap->db_type == M_DATA) {
25394 			/*
25395 			 * M_DATA mblk, so init mblk (chain) for no struio().
25396 			 */
25397 			mblk_t	*mp1 = mp;
25398 
25399 			do
25400 				mp1->b_datap->db_struioflag = 0;
25401 			while ((mp1 = mp1->b_cont) != NULL);
25402 		}
25403 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25404 		    <= mp->b_wptr);
25405 		ip_fanout_tcp(q, first_mp, ill, ipha,
25406 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25407 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25408 		    mctl_present, B_FALSE, zoneid);
25409 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25410 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25411 		return;
25412 	}
25413 	case IPPROTO_SCTP:
25414 	{
25415 		uint32_t	ports;
25416 
25417 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25418 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25419 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25420 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25421 		return;
25422 	}
25423 
25424 	default:
25425 		break;
25426 	}
25427 	/*
25428 	 * Find a client for some other protocol.  We give
25429 	 * copies to multiple clients, if more than one is
25430 	 * bound.
25431 	 */
25432 	ip_fanout_proto(q, first_mp, ill, ipha,
25433 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25434 	    mctl_present, B_FALSE, ill, zoneid);
25435 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25436 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25437 #undef	rptr
25438 }
25439 
25440 /*
25441  * Update any source route, record route, or timestamp options.
25442  * Check that we are at end of strict source route.
25443  * The options have been sanity checked by ip_wput_options().
25444  */
25445 static void
25446 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25447 {
25448 	ipoptp_t	opts;
25449 	uchar_t		*opt;
25450 	uint8_t		optval;
25451 	uint8_t		optlen;
25452 	ipaddr_t	dst;
25453 	uint32_t	ts;
25454 	ire_t		*ire;
25455 	timestruc_t	now;
25456 
25457 	ip2dbg(("ip_wput_local_options\n"));
25458 	for (optval = ipoptp_first(&opts, ipha);
25459 	    optval != IPOPT_EOL;
25460 	    optval = ipoptp_next(&opts)) {
25461 		opt = opts.ipoptp_cur;
25462 		optlen = opts.ipoptp_len;
25463 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25464 		switch (optval) {
25465 			uint32_t off;
25466 		case IPOPT_SSRR:
25467 		case IPOPT_LSRR:
25468 			off = opt[IPOPT_OFFSET];
25469 			off--;
25470 			if (optlen < IP_ADDR_LEN ||
25471 			    off > optlen - IP_ADDR_LEN) {
25472 				/* End of source route */
25473 				break;
25474 			}
25475 			/*
25476 			 * This will only happen if two consecutive entries
25477 			 * in the source route contains our address or if
25478 			 * it is a packet with a loose source route which
25479 			 * reaches us before consuming the whole source route
25480 			 */
25481 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25482 			if (optval == IPOPT_SSRR) {
25483 				return;
25484 			}
25485 			/*
25486 			 * Hack: instead of dropping the packet truncate the
25487 			 * source route to what has been used by filling the
25488 			 * rest with IPOPT_NOP.
25489 			 */
25490 			opt[IPOPT_OLEN] = (uint8_t)off;
25491 			while (off < optlen) {
25492 				opt[off++] = IPOPT_NOP;
25493 			}
25494 			break;
25495 		case IPOPT_RR:
25496 			off = opt[IPOPT_OFFSET];
25497 			off--;
25498 			if (optlen < IP_ADDR_LEN ||
25499 			    off > optlen - IP_ADDR_LEN) {
25500 				/* No more room - ignore */
25501 				ip1dbg((
25502 				    "ip_wput_forward_options: end of RR\n"));
25503 				break;
25504 			}
25505 			dst = htonl(INADDR_LOOPBACK);
25506 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25507 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25508 			break;
25509 		case IPOPT_TS:
25510 			/* Insert timestamp if there is romm */
25511 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25512 			case IPOPT_TS_TSONLY:
25513 				off = IPOPT_TS_TIMELEN;
25514 				break;
25515 			case IPOPT_TS_PRESPEC:
25516 			case IPOPT_TS_PRESPEC_RFC791:
25517 				/* Verify that the address matched */
25518 				off = opt[IPOPT_OFFSET] - 1;
25519 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25520 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25521 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25522 				    ipst);
25523 				if (ire == NULL) {
25524 					/* Not for us */
25525 					break;
25526 				}
25527 				ire_refrele(ire);
25528 				/* FALLTHRU */
25529 			case IPOPT_TS_TSANDADDR:
25530 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25531 				break;
25532 			default:
25533 				/*
25534 				 * ip_*put_options should have already
25535 				 * dropped this packet.
25536 				 */
25537 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25538 				    "unknown IT - bug in ip_wput_options?\n");
25539 				return;	/* Keep "lint" happy */
25540 			}
25541 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25542 				/* Increase overflow counter */
25543 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25544 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25545 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25546 				    (off << 4);
25547 				break;
25548 			}
25549 			off = opt[IPOPT_OFFSET] - 1;
25550 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25551 			case IPOPT_TS_PRESPEC:
25552 			case IPOPT_TS_PRESPEC_RFC791:
25553 			case IPOPT_TS_TSANDADDR:
25554 				dst = htonl(INADDR_LOOPBACK);
25555 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25556 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25557 				/* FALLTHRU */
25558 			case IPOPT_TS_TSONLY:
25559 				off = opt[IPOPT_OFFSET] - 1;
25560 				/* Compute # of milliseconds since midnight */
25561 				gethrestime(&now);
25562 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25563 				    now.tv_nsec / (NANOSEC / MILLISEC);
25564 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25565 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25566 				break;
25567 			}
25568 			break;
25569 		}
25570 	}
25571 }
25572 
25573 /*
25574  * Send out a multicast packet on interface ipif.
25575  * The sender does not have an conn.
25576  * Caller verifies that this isn't a PHYI_LOOPBACK.
25577  */
25578 void
25579 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25580 {
25581 	ipha_t	*ipha;
25582 	ire_t	*ire;
25583 	ipaddr_t	dst;
25584 	mblk_t		*first_mp;
25585 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25586 
25587 	/* igmp_sendpkt always allocates a ipsec_out_t */
25588 	ASSERT(mp->b_datap->db_type == M_CTL);
25589 	ASSERT(!ipif->ipif_isv6);
25590 	ASSERT(!(ipif->ipif_ill->ill_phyint->phyint_flags & PHYI_LOOPBACK));
25591 
25592 	first_mp = mp;
25593 	mp = first_mp->b_cont;
25594 	ASSERT(mp->b_datap->db_type == M_DATA);
25595 	ipha = (ipha_t *)mp->b_rptr;
25596 
25597 	/*
25598 	 * Find an IRE which matches the destination and the outgoing
25599 	 * queue (i.e. the outgoing interface.)
25600 	 */
25601 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25602 		dst = ipif->ipif_pp_dst_addr;
25603 	else
25604 		dst = ipha->ipha_dst;
25605 	/*
25606 	 * The source address has already been initialized by the
25607 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25608 	 * be sufficient rather than MATCH_IRE_IPIF.
25609 	 *
25610 	 * This function is used for sending IGMP packets. We need
25611 	 * to make sure that we send the packet out of the interface
25612 	 * (ipif->ipif_ill) where we joined the group. This is to
25613 	 * prevent from switches doing IGMP snooping to send us multicast
25614 	 * packets for a given group on the interface we have joined.
25615 	 * If we can't find an ire, igmp_sendpkt has already initialized
25616 	 * ipsec_out_attach_if so that this will not be load spread in
25617 	 * ip_newroute_ipif.
25618 	 */
25619 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25620 	    MATCH_IRE_ILL, ipst);
25621 	if (!ire) {
25622 		/*
25623 		 * Mark this packet to make it be delivered to
25624 		 * ip_wput_ire after the new ire has been
25625 		 * created.
25626 		 */
25627 		mp->b_prev = NULL;
25628 		mp->b_next = NULL;
25629 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25630 		    zoneid, &zero_info);
25631 		return;
25632 	}
25633 
25634 	/*
25635 	 * Honor the RTF_SETSRC flag; this is the only case
25636 	 * where we force this addr whatever the current src addr is,
25637 	 * because this address is set by igmp_sendpkt(), and
25638 	 * cannot be specified by any user.
25639 	 */
25640 	if (ire->ire_flags & RTF_SETSRC) {
25641 		ipha->ipha_src = ire->ire_src_addr;
25642 	}
25643 
25644 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25645 }
25646 
25647 /*
25648  * NOTE : This function does not ire_refrele the ire argument passed in.
25649  *
25650  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25651  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25652  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25653  * the ire_lock to access the nce_fp_mp in this case.
25654  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25655  * prepending a fastpath message IPQoS processing must precede it, we also set
25656  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25657  * (IPQoS might have set the b_band for CoS marking).
25658  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25659  * must follow it so that IPQoS can mark the dl_priority field for CoS
25660  * marking, if needed.
25661  */
25662 static mblk_t *
25663 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25664 {
25665 	uint_t	hlen;
25666 	ipha_t *ipha;
25667 	mblk_t *mp1;
25668 	boolean_t qos_done = B_FALSE;
25669 	uchar_t	*ll_hdr;
25670 	ip_stack_t	*ipst = ire->ire_ipst;
25671 
25672 #define	rptr	((uchar_t *)ipha)
25673 
25674 	ipha = (ipha_t *)mp->b_rptr;
25675 	hlen = 0;
25676 	LOCK_IRE_FP_MP(ire);
25677 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25678 		ASSERT(DB_TYPE(mp1) == M_DATA);
25679 		/* Initiate IPPF processing */
25680 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25681 			UNLOCK_IRE_FP_MP(ire);
25682 			ip_process(proc, &mp, ill_index);
25683 			if (mp == NULL)
25684 				return (NULL);
25685 
25686 			ipha = (ipha_t *)mp->b_rptr;
25687 			LOCK_IRE_FP_MP(ire);
25688 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25689 				qos_done = B_TRUE;
25690 				goto no_fp_mp;
25691 			}
25692 			ASSERT(DB_TYPE(mp1) == M_DATA);
25693 		}
25694 		hlen = MBLKL(mp1);
25695 		/*
25696 		 * Check if we have enough room to prepend fastpath
25697 		 * header
25698 		 */
25699 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25700 			ll_hdr = rptr - hlen;
25701 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25702 			/*
25703 			 * Set the b_rptr to the start of the link layer
25704 			 * header
25705 			 */
25706 			mp->b_rptr = ll_hdr;
25707 			mp1 = mp;
25708 		} else {
25709 			mp1 = copyb(mp1);
25710 			if (mp1 == NULL)
25711 				goto unlock_err;
25712 			mp1->b_band = mp->b_band;
25713 			mp1->b_cont = mp;
25714 			/*
25715 			 * certain system generated traffic may not
25716 			 * have cred/label in ip header block. This
25717 			 * is true even for a labeled system. But for
25718 			 * labeled traffic, inherit the label in the
25719 			 * new header.
25720 			 */
25721 			if (DB_CRED(mp) != NULL)
25722 				mblk_setcred(mp1, DB_CRED(mp));
25723 			/*
25724 			 * XXX disable ICK_VALID and compute checksum
25725 			 * here; can happen if nce_fp_mp changes and
25726 			 * it can't be copied now due to insufficient
25727 			 * space. (unlikely, fp mp can change, but it
25728 			 * does not increase in length)
25729 			 */
25730 		}
25731 		UNLOCK_IRE_FP_MP(ire);
25732 	} else {
25733 no_fp_mp:
25734 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25735 		if (mp1 == NULL) {
25736 unlock_err:
25737 			UNLOCK_IRE_FP_MP(ire);
25738 			freemsg(mp);
25739 			return (NULL);
25740 		}
25741 		UNLOCK_IRE_FP_MP(ire);
25742 		mp1->b_cont = mp;
25743 		/*
25744 		 * certain system generated traffic may not
25745 		 * have cred/label in ip header block. This
25746 		 * is true even for a labeled system. But for
25747 		 * labeled traffic, inherit the label in the
25748 		 * new header.
25749 		 */
25750 		if (DB_CRED(mp) != NULL)
25751 			mblk_setcred(mp1, DB_CRED(mp));
25752 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25753 			ip_process(proc, &mp1, ill_index);
25754 			if (mp1 == NULL)
25755 				return (NULL);
25756 		}
25757 	}
25758 	return (mp1);
25759 #undef rptr
25760 }
25761 
25762 /*
25763  * Finish the outbound IPsec processing for an IPv6 packet. This function
25764  * is called from ipsec_out_process() if the IPsec packet was processed
25765  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25766  * asynchronously.
25767  */
25768 void
25769 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25770     ire_t *ire_arg)
25771 {
25772 	in6_addr_t *v6dstp;
25773 	ire_t *ire;
25774 	mblk_t *mp;
25775 	ip6_t *ip6h1;
25776 	uint_t	ill_index;
25777 	ipsec_out_t *io;
25778 	boolean_t attach_if, hwaccel;
25779 	uint32_t flags = IP6_NO_IPPOLICY;
25780 	int match_flags;
25781 	zoneid_t zoneid;
25782 	boolean_t ill_need_rele = B_FALSE;
25783 	boolean_t ire_need_rele = B_FALSE;
25784 	ip_stack_t	*ipst;
25785 
25786 	mp = ipsec_mp->b_cont;
25787 	ip6h1 = (ip6_t *)mp->b_rptr;
25788 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25789 	ASSERT(io->ipsec_out_ns != NULL);
25790 	ipst = io->ipsec_out_ns->netstack_ip;
25791 	ill_index = io->ipsec_out_ill_index;
25792 	if (io->ipsec_out_reachable) {
25793 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25794 	}
25795 	attach_if = io->ipsec_out_attach_if;
25796 	hwaccel = io->ipsec_out_accelerated;
25797 	zoneid = io->ipsec_out_zoneid;
25798 	ASSERT(zoneid != ALL_ZONES);
25799 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25800 	/* Multicast addresses should have non-zero ill_index. */
25801 	v6dstp = &ip6h->ip6_dst;
25802 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25803 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25804 	ASSERT(!attach_if || ill_index != 0);
25805 	if (ill_index != 0) {
25806 		if (ill == NULL) {
25807 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25808 			    B_TRUE, ipst);
25809 
25810 			/* Failure case frees things for us. */
25811 			if (ill == NULL)
25812 				return;
25813 
25814 			ill_need_rele = B_TRUE;
25815 		}
25816 		/*
25817 		 * If this packet needs to go out on a particular interface
25818 		 * honor it.
25819 		 */
25820 		if (attach_if) {
25821 			match_flags = MATCH_IRE_ILL;
25822 
25823 			/*
25824 			 * Check if we need an ire that will not be
25825 			 * looked up by anybody else i.e. HIDDEN.
25826 			 */
25827 			if (ill_is_probeonly(ill)) {
25828 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25829 			}
25830 		}
25831 	}
25832 	ASSERT(mp != NULL);
25833 
25834 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25835 		boolean_t unspec_src;
25836 		ipif_t	*ipif;
25837 
25838 		/*
25839 		 * Use the ill_index to get the right ill.
25840 		 */
25841 		unspec_src = io->ipsec_out_unspec_src;
25842 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25843 		if (ipif == NULL) {
25844 			if (ill_need_rele)
25845 				ill_refrele(ill);
25846 			freemsg(ipsec_mp);
25847 			return;
25848 		}
25849 
25850 		if (ire_arg != NULL) {
25851 			ire = ire_arg;
25852 		} else {
25853 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25854 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25855 			ire_need_rele = B_TRUE;
25856 		}
25857 		if (ire != NULL) {
25858 			ipif_refrele(ipif);
25859 			/*
25860 			 * XXX Do the multicast forwarding now, as the IPSEC
25861 			 * processing has been done.
25862 			 */
25863 			goto send;
25864 		}
25865 
25866 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25867 		mp->b_prev = NULL;
25868 		mp->b_next = NULL;
25869 
25870 		/*
25871 		 * If the IPsec packet was processed asynchronously,
25872 		 * drop it now.
25873 		 */
25874 		if (q == NULL) {
25875 			if (ill_need_rele)
25876 				ill_refrele(ill);
25877 			freemsg(ipsec_mp);
25878 			return;
25879 		}
25880 
25881 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25882 		    unspec_src, zoneid);
25883 		ipif_refrele(ipif);
25884 	} else {
25885 		if (attach_if) {
25886 			ipif_t	*ipif;
25887 
25888 			ipif = ipif_get_next_ipif(NULL, ill);
25889 			if (ipif == NULL) {
25890 				if (ill_need_rele)
25891 					ill_refrele(ill);
25892 				freemsg(ipsec_mp);
25893 				return;
25894 			}
25895 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25896 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25897 			ire_need_rele = B_TRUE;
25898 			ipif_refrele(ipif);
25899 		} else {
25900 			if (ire_arg != NULL) {
25901 				ire = ire_arg;
25902 			} else {
25903 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25904 				    ipst);
25905 				ire_need_rele = B_TRUE;
25906 			}
25907 		}
25908 		if (ire != NULL)
25909 			goto send;
25910 		/*
25911 		 * ire disappeared underneath.
25912 		 *
25913 		 * What we need to do here is the ip_newroute
25914 		 * logic to get the ire without doing the IPSEC
25915 		 * processing. Follow the same old path. But this
25916 		 * time, ip_wput or ire_add_then_send will call us
25917 		 * directly as all the IPSEC operations are done.
25918 		 */
25919 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25920 		mp->b_prev = NULL;
25921 		mp->b_next = NULL;
25922 
25923 		/*
25924 		 * If the IPsec packet was processed asynchronously,
25925 		 * drop it now.
25926 		 */
25927 		if (q == NULL) {
25928 			if (ill_need_rele)
25929 				ill_refrele(ill);
25930 			freemsg(ipsec_mp);
25931 			return;
25932 		}
25933 
25934 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25935 		    zoneid, ipst);
25936 	}
25937 	if (ill != NULL && ill_need_rele)
25938 		ill_refrele(ill);
25939 	return;
25940 send:
25941 	if (ill != NULL && ill_need_rele)
25942 		ill_refrele(ill);
25943 
25944 	/* Local delivery */
25945 	if (ire->ire_stq == NULL) {
25946 		ill_t	*out_ill;
25947 		ASSERT(q != NULL);
25948 
25949 		/* PFHooks: LOOPBACK_OUT */
25950 		out_ill = ire->ire_ipif->ipif_ill;
25951 
25952 		DTRACE_PROBE4(ip6__loopback__out__start,
25953 		    ill_t *, NULL, ill_t *, out_ill,
25954 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25955 
25956 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25957 		    ipst->ips_ipv6firewall_loopback_out,
25958 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25959 
25960 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25961 
25962 		if (ipsec_mp != NULL)
25963 			ip_wput_local_v6(RD(q), out_ill,
25964 			    ip6h, ipsec_mp, ire, 0);
25965 		if (ire_need_rele)
25966 			ire_refrele(ire);
25967 		return;
25968 	}
25969 	/*
25970 	 * Everything is done. Send it out on the wire.
25971 	 * We force the insertion of a fragment header using the
25972 	 * IPH_FRAG_HDR flag in two cases:
25973 	 * - after reception of an ICMPv6 "packet too big" message
25974 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25975 	 * - for multirouted IPv6 packets, so that the receiver can
25976 	 *   discard duplicates according to their fragment identifier
25977 	 */
25978 	/* XXX fix flow control problems. */
25979 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25980 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25981 		if (hwaccel) {
25982 			/*
25983 			 * hardware acceleration does not handle these
25984 			 * "slow path" cases.
25985 			 */
25986 			/* IPsec KSTATS: should bump bean counter here. */
25987 			if (ire_need_rele)
25988 				ire_refrele(ire);
25989 			freemsg(ipsec_mp);
25990 			return;
25991 		}
25992 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25993 		    (mp->b_cont ? msgdsize(mp) :
25994 		    mp->b_wptr - (uchar_t *)ip6h)) {
25995 			/* IPsec KSTATS: should bump bean counter here. */
25996 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25997 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25998 			    msgdsize(mp)));
25999 			if (ire_need_rele)
26000 				ire_refrele(ire);
26001 			freemsg(ipsec_mp);
26002 			return;
26003 		}
26004 		ASSERT(mp->b_prev == NULL);
26005 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26006 		    ntohs(ip6h->ip6_plen) +
26007 		    IPV6_HDR_LEN, ire->ire_max_frag));
26008 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26009 		    ire->ire_max_frag);
26010 	} else {
26011 		UPDATE_OB_PKT_COUNT(ire);
26012 		ire->ire_last_used_time = lbolt;
26013 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26014 	}
26015 	if (ire_need_rele)
26016 		ire_refrele(ire);
26017 	freeb(ipsec_mp);
26018 }
26019 
26020 void
26021 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26022 {
26023 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26024 	da_ipsec_t *hada;	/* data attributes */
26025 	ill_t *ill = (ill_t *)q->q_ptr;
26026 
26027 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26028 
26029 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26030 		/* IPsec KSTATS: Bump lose counter here! */
26031 		freemsg(mp);
26032 		return;
26033 	}
26034 
26035 	/*
26036 	 * It's an IPsec packet that must be
26037 	 * accelerated by the Provider, and the
26038 	 * outbound ill is IPsec acceleration capable.
26039 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26040 	 * to the ill.
26041 	 * IPsec KSTATS: should bump packet counter here.
26042 	 */
26043 
26044 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26045 	if (hada_mp == NULL) {
26046 		/* IPsec KSTATS: should bump packet counter here. */
26047 		freemsg(mp);
26048 		return;
26049 	}
26050 
26051 	hada_mp->b_datap->db_type = M_CTL;
26052 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26053 	hada_mp->b_cont = mp;
26054 
26055 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26056 	bzero(hada, sizeof (da_ipsec_t));
26057 	hada->da_type = IPHADA_M_CTL;
26058 
26059 	putnext(q, hada_mp);
26060 }
26061 
26062 /*
26063  * Finish the outbound IPsec processing. This function is called from
26064  * ipsec_out_process() if the IPsec packet was processed
26065  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26066  * asynchronously.
26067  */
26068 void
26069 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26070     ire_t *ire_arg)
26071 {
26072 	uint32_t v_hlen_tos_len;
26073 	ipaddr_t	dst;
26074 	ipif_t	*ipif = NULL;
26075 	ire_t *ire;
26076 	ire_t *ire1 = NULL;
26077 	mblk_t *next_mp = NULL;
26078 	uint32_t max_frag;
26079 	boolean_t multirt_send = B_FALSE;
26080 	mblk_t *mp;
26081 	mblk_t *mp1;
26082 	ipha_t *ipha1;
26083 	uint_t	ill_index;
26084 	ipsec_out_t *io;
26085 	boolean_t attach_if;
26086 	int match_flags, offset;
26087 	irb_t *irb = NULL;
26088 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26089 	zoneid_t zoneid;
26090 	uint32_t cksum;
26091 	uint16_t *up;
26092 	ipxmit_state_t	pktxmit_state;
26093 	ip_stack_t	*ipst;
26094 
26095 #ifdef	_BIG_ENDIAN
26096 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26097 #else
26098 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26099 #endif
26100 
26101 	mp = ipsec_mp->b_cont;
26102 	ipha1 = (ipha_t *)mp->b_rptr;
26103 	ASSERT(mp != NULL);
26104 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26105 	dst = ipha->ipha_dst;
26106 
26107 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26108 	ill_index = io->ipsec_out_ill_index;
26109 	attach_if = io->ipsec_out_attach_if;
26110 	zoneid = io->ipsec_out_zoneid;
26111 	ASSERT(zoneid != ALL_ZONES);
26112 	ipst = io->ipsec_out_ns->netstack_ip;
26113 	ASSERT(io->ipsec_out_ns != NULL);
26114 
26115 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26116 	if (ill_index != 0) {
26117 		if (ill == NULL) {
26118 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26119 			    ill_index, B_FALSE, ipst);
26120 
26121 			/* Failure case frees things for us. */
26122 			if (ill == NULL)
26123 				return;
26124 
26125 			ill_need_rele = B_TRUE;
26126 		}
26127 		/*
26128 		 * If this packet needs to go out on a particular interface
26129 		 * honor it.
26130 		 */
26131 		if (attach_if) {
26132 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26133 
26134 			/*
26135 			 * Check if we need an ire that will not be
26136 			 * looked up by anybody else i.e. HIDDEN.
26137 			 */
26138 			if (ill_is_probeonly(ill)) {
26139 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26140 			}
26141 		}
26142 	}
26143 
26144 	if (CLASSD(dst)) {
26145 		boolean_t conn_dontroute;
26146 		/*
26147 		 * Use the ill_index to get the right ipif.
26148 		 */
26149 		conn_dontroute = io->ipsec_out_dontroute;
26150 		if (ill_index == 0)
26151 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26152 		else
26153 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26154 		if (ipif == NULL) {
26155 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26156 			    " multicast\n"));
26157 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26158 			freemsg(ipsec_mp);
26159 			goto done;
26160 		}
26161 		/*
26162 		 * ipha_src has already been intialized with the
26163 		 * value of the ipif in ip_wput. All we need now is
26164 		 * an ire to send this downstream.
26165 		 */
26166 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26167 		    MBLK_GETLABEL(mp), match_flags, ipst);
26168 		if (ire != NULL) {
26169 			ill_t *ill1;
26170 			/*
26171 			 * Do the multicast forwarding now, as the IPSEC
26172 			 * processing has been done.
26173 			 */
26174 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26175 			    (ill1 = ire_to_ill(ire))) {
26176 				if (ip_mforward(ill1, ipha, mp)) {
26177 					freemsg(ipsec_mp);
26178 					ip1dbg(("ip_wput_ipsec_out: mforward "
26179 					    "failed\n"));
26180 					ire_refrele(ire);
26181 					goto done;
26182 				}
26183 			}
26184 			goto send;
26185 		}
26186 
26187 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26188 		mp->b_prev = NULL;
26189 		mp->b_next = NULL;
26190 
26191 		/*
26192 		 * If the IPsec packet was processed asynchronously,
26193 		 * drop it now.
26194 		 */
26195 		if (q == NULL) {
26196 			freemsg(ipsec_mp);
26197 			goto done;
26198 		}
26199 
26200 		/*
26201 		 * We may be using a wrong ipif to create the ire.
26202 		 * But it is okay as the source address is assigned
26203 		 * for the packet already. Next outbound packet would
26204 		 * create the IRE with the right IPIF in ip_wput.
26205 		 *
26206 		 * Also handle RTF_MULTIRT routes.
26207 		 */
26208 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26209 		    zoneid, &zero_info);
26210 	} else {
26211 		if (attach_if) {
26212 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26213 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26214 		} else {
26215 			if (ire_arg != NULL) {
26216 				ire = ire_arg;
26217 				ire_need_rele = B_FALSE;
26218 			} else {
26219 				ire = ire_cache_lookup(dst, zoneid,
26220 				    MBLK_GETLABEL(mp), ipst);
26221 			}
26222 		}
26223 		if (ire != NULL) {
26224 			goto send;
26225 		}
26226 
26227 		/*
26228 		 * ire disappeared underneath.
26229 		 *
26230 		 * What we need to do here is the ip_newroute
26231 		 * logic to get the ire without doing the IPSEC
26232 		 * processing. Follow the same old path. But this
26233 		 * time, ip_wput or ire_add_then_put will call us
26234 		 * directly as all the IPSEC operations are done.
26235 		 */
26236 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26237 		mp->b_prev = NULL;
26238 		mp->b_next = NULL;
26239 
26240 		/*
26241 		 * If the IPsec packet was processed asynchronously,
26242 		 * drop it now.
26243 		 */
26244 		if (q == NULL) {
26245 			freemsg(ipsec_mp);
26246 			goto done;
26247 		}
26248 
26249 		/*
26250 		 * Since we're going through ip_newroute() again, we
26251 		 * need to make sure we don't:
26252 		 *
26253 		 *	1.) Trigger the ASSERT() with the ipha_ident
26254 		 *	    overloading.
26255 		 *	2.) Redo transport-layer checksumming, since we've
26256 		 *	    already done all that to get this far.
26257 		 *
26258 		 * The easiest way not do either of the above is to set
26259 		 * the ipha_ident field to IP_HDR_INCLUDED.
26260 		 */
26261 		ipha->ipha_ident = IP_HDR_INCLUDED;
26262 		ip_newroute(q, ipsec_mp, dst, NULL,
26263 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26264 	}
26265 	goto done;
26266 send:
26267 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26268 	    udp_compute_checksum(ipst->ips_netstack)) {
26269 		/*
26270 		 * ESP NAT-Traversal packet.
26271 		 *
26272 		 * Just do software checksum for now.
26273 		 */
26274 
26275 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26276 		IP_STAT(ipst, ip_out_sw_cksum);
26277 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26278 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26279 #define	iphs	((uint16_t *)ipha)
26280 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26281 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26282 		    IP_SIMPLE_HDR_LENGTH);
26283 #undef iphs
26284 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
26285 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26286 			if (mp1->b_wptr - mp1->b_rptr >=
26287 			    offset + sizeof (uint16_t)) {
26288 				up = (uint16_t *)(mp1->b_rptr + offset);
26289 				*up = cksum;
26290 				break;	/* out of for loop */
26291 			} else {
26292 				offset -= (mp->b_wptr - mp->b_rptr);
26293 			}
26294 	} /* Otherwise, just keep the all-zero checksum. */
26295 
26296 	if (ire->ire_stq == NULL) {
26297 		ill_t	*out_ill;
26298 		/*
26299 		 * Loopbacks go through ip_wput_local except for one case.
26300 		 * We come here if we generate a icmp_frag_needed message
26301 		 * after IPSEC processing is over. When this function calls
26302 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26303 		 * icmp_frag_needed. The message generated comes back here
26304 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26305 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26306 		 * source address as it is usually set in ip_wput_ire. As
26307 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26308 		 * and we end up here. We can't enter ip_wput_ire once the
26309 		 * IPSEC processing is over and hence we need to do it here.
26310 		 */
26311 		ASSERT(q != NULL);
26312 		UPDATE_OB_PKT_COUNT(ire);
26313 		ire->ire_last_used_time = lbolt;
26314 		if (ipha->ipha_src == 0)
26315 			ipha->ipha_src = ire->ire_src_addr;
26316 
26317 		/* PFHooks: LOOPBACK_OUT */
26318 		out_ill = ire->ire_ipif->ipif_ill;
26319 
26320 		DTRACE_PROBE4(ip4__loopback__out__start,
26321 		    ill_t *, NULL, ill_t *, out_ill,
26322 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26323 
26324 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26325 		    ipst->ips_ipv4firewall_loopback_out,
26326 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26327 
26328 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26329 
26330 		if (ipsec_mp != NULL)
26331 			ip_wput_local(RD(q), out_ill,
26332 			    ipha, ipsec_mp, ire, 0, zoneid);
26333 		if (ire_need_rele)
26334 			ire_refrele(ire);
26335 		goto done;
26336 	}
26337 
26338 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26339 		/*
26340 		 * We are through with IPSEC processing.
26341 		 * Fragment this and send it on the wire.
26342 		 */
26343 		if (io->ipsec_out_accelerated) {
26344 			/*
26345 			 * The packet has been accelerated but must
26346 			 * be fragmented. This should not happen
26347 			 * since AH and ESP must not accelerate
26348 			 * packets that need fragmentation, however
26349 			 * the configuration could have changed
26350 			 * since the AH or ESP processing.
26351 			 * Drop packet.
26352 			 * IPsec KSTATS: bump bean counter here.
26353 			 */
26354 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26355 			    "fragmented accelerated packet!\n"));
26356 			freemsg(ipsec_mp);
26357 		} else {
26358 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26359 		}
26360 		if (ire_need_rele)
26361 			ire_refrele(ire);
26362 		goto done;
26363 	}
26364 
26365 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26366 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26367 	    (void *)ire->ire_ipif, (void *)ipif));
26368 
26369 	/*
26370 	 * Multiroute the secured packet, unless IPsec really
26371 	 * requires the packet to go out only through a particular
26372 	 * interface.
26373 	 */
26374 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26375 		ire_t *first_ire;
26376 		irb = ire->ire_bucket;
26377 		ASSERT(irb != NULL);
26378 		/*
26379 		 * This ire has been looked up as the one that
26380 		 * goes through the given ipif;
26381 		 * make sure we do not omit any other multiroute ire
26382 		 * that may be present in the bucket before this one.
26383 		 */
26384 		IRB_REFHOLD(irb);
26385 		for (first_ire = irb->irb_ire;
26386 		    first_ire != NULL;
26387 		    first_ire = first_ire->ire_next) {
26388 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26389 			    (first_ire->ire_addr == ire->ire_addr) &&
26390 			    !(first_ire->ire_marks &
26391 				(IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN)))
26392 				break;
26393 		}
26394 
26395 		if ((first_ire != NULL) && (first_ire != ire)) {
26396 			/*
26397 			 * Don't change the ire if the packet must
26398 			 * be fragmented if sent via this new one.
26399 			 */
26400 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26401 				IRE_REFHOLD(first_ire);
26402 				if (ire_need_rele)
26403 					ire_refrele(ire);
26404 				else
26405 					ire_need_rele = B_TRUE;
26406 				ire = first_ire;
26407 			}
26408 		}
26409 		IRB_REFRELE(irb);
26410 
26411 		multirt_send = B_TRUE;
26412 		max_frag = ire->ire_max_frag;
26413 	} else {
26414 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26415 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26416 			    "flag, attach_if %d\n", attach_if));
26417 		}
26418 	}
26419 
26420 	/*
26421 	 * In most cases, the emission loop below is entered only once.
26422 	 * Only in the case where the ire holds the RTF_MULTIRT
26423 	 * flag, we loop to process all RTF_MULTIRT ires in the
26424 	 * bucket, and send the packet through all crossed
26425 	 * RTF_MULTIRT routes.
26426 	 */
26427 	do {
26428 		if (multirt_send) {
26429 			/*
26430 			 * ire1 holds here the next ire to process in the
26431 			 * bucket. If multirouting is expected,
26432 			 * any non-RTF_MULTIRT ire that has the
26433 			 * right destination address is ignored.
26434 			 */
26435 			ASSERT(irb != NULL);
26436 			IRB_REFHOLD(irb);
26437 			for (ire1 = ire->ire_next;
26438 			    ire1 != NULL;
26439 			    ire1 = ire1->ire_next) {
26440 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26441 					continue;
26442 				if (ire1->ire_addr != ire->ire_addr)
26443 					continue;
26444 				if (ire1->ire_marks &
26445 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26446 					continue;
26447 				/* No loopback here */
26448 				if (ire1->ire_stq == NULL)
26449 					continue;
26450 				/*
26451 				 * Ensure we do not exceed the MTU
26452 				 * of the next route.
26453 				 */
26454 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26455 					ip_multirt_bad_mtu(ire1, max_frag);
26456 					continue;
26457 				}
26458 
26459 				IRE_REFHOLD(ire1);
26460 				break;
26461 			}
26462 			IRB_REFRELE(irb);
26463 			if (ire1 != NULL) {
26464 				/*
26465 				 * We are in a multiple send case, need to
26466 				 * make a copy of the packet.
26467 				 */
26468 				next_mp = copymsg(ipsec_mp);
26469 				if (next_mp == NULL) {
26470 					ire_refrele(ire1);
26471 					ire1 = NULL;
26472 				}
26473 			}
26474 		}
26475 		/*
26476 		 * Everything is done. Send it out on the wire
26477 		 *
26478 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26479 		 * either send it on the wire or, in the case of
26480 		 * HW acceleration, call ipsec_hw_putnext.
26481 		 */
26482 		if (ire->ire_nce &&
26483 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26484 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26485 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26486 			/*
26487 			 * If ire's link-layer is unresolved (this
26488 			 * would only happen if the incomplete ire
26489 			 * was added to cachetable via forwarding path)
26490 			 * don't bother going to ip_xmit_v4. Just drop the
26491 			 * packet.
26492 			 * There is a slight risk here, in that, if we
26493 			 * have the forwarding path create an incomplete
26494 			 * IRE, then until the IRE is completed, any
26495 			 * transmitted IPSEC packets will be dropped
26496 			 * instead of being queued waiting for resolution.
26497 			 *
26498 			 * But the likelihood of a forwarding packet and a wput
26499 			 * packet sending to the same dst at the same time
26500 			 * and there not yet be an ARP entry for it is small.
26501 			 * Furthermore, if this actually happens, it might
26502 			 * be likely that wput would generate multiple
26503 			 * packets (and forwarding would also have a train
26504 			 * of packets) for that destination. If this is
26505 			 * the case, some of them would have been dropped
26506 			 * anyway, since ARP only queues a few packets while
26507 			 * waiting for resolution
26508 			 *
26509 			 * NOTE: We should really call ip_xmit_v4,
26510 			 * and let it queue the packet and send the
26511 			 * ARP query and have ARP come back thus:
26512 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26513 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26514 			 * hw accel work. But it's too complex to get
26515 			 * the IPsec hw  acceleration approach to fit
26516 			 * well with ip_xmit_v4 doing ARP without
26517 			 * doing IPSEC simplification. For now, we just
26518 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26519 			 * that we can continue with the send on the next
26520 			 * attempt.
26521 			 *
26522 			 * XXX THis should be revisited, when
26523 			 * the IPsec/IP interaction is cleaned up
26524 			 */
26525 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26526 			    " - dropping packet\n"));
26527 			freemsg(ipsec_mp);
26528 			/*
26529 			 * Call ip_xmit_v4() to trigger ARP query
26530 			 * in case the nce_state is ND_INITIAL
26531 			 */
26532 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26533 			goto drop_pkt;
26534 		}
26535 
26536 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26537 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26538 		    mblk_t *, mp);
26539 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26540 		    ipst->ips_ipv4firewall_physical_out,
26541 		    NULL, ire->ire_ipif->ipif_ill, ipha1, mp, mp, ipst);
26542 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
26543 		if (mp == NULL)
26544 			goto drop_pkt;
26545 
26546 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26547 		pktxmit_state = ip_xmit_v4(mp, ire,
26548 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26549 
26550 		if ((pktxmit_state ==  SEND_FAILED) ||
26551 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26552 
26553 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26554 drop_pkt:
26555 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26556 			    ipIfStatsOutDiscards);
26557 			if (ire_need_rele)
26558 				ire_refrele(ire);
26559 			if (ire1 != NULL) {
26560 				ire_refrele(ire1);
26561 				freemsg(next_mp);
26562 			}
26563 			goto done;
26564 		}
26565 
26566 		freeb(ipsec_mp);
26567 		if (ire_need_rele)
26568 			ire_refrele(ire);
26569 
26570 		if (ire1 != NULL) {
26571 			ire = ire1;
26572 			ire_need_rele = B_TRUE;
26573 			ASSERT(next_mp);
26574 			ipsec_mp = next_mp;
26575 			mp = ipsec_mp->b_cont;
26576 			ire1 = NULL;
26577 			next_mp = NULL;
26578 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26579 		} else {
26580 			multirt_send = B_FALSE;
26581 		}
26582 	} while (multirt_send);
26583 done:
26584 	if (ill != NULL && ill_need_rele)
26585 		ill_refrele(ill);
26586 	if (ipif != NULL)
26587 		ipif_refrele(ipif);
26588 }
26589 
26590 /*
26591  * Get the ill corresponding to the specified ire, and compare its
26592  * capabilities with the protocol and algorithms specified by the
26593  * the SA obtained from ipsec_out. If they match, annotate the
26594  * ipsec_out structure to indicate that the packet needs acceleration.
26595  *
26596  *
26597  * A packet is eligible for outbound hardware acceleration if the
26598  * following conditions are satisfied:
26599  *
26600  * 1. the packet will not be fragmented
26601  * 2. the provider supports the algorithm
26602  * 3. there is no pending control message being exchanged
26603  * 4. snoop is not attached
26604  * 5. the destination address is not a broadcast or multicast address.
26605  *
26606  * Rationale:
26607  *	- Hardware drivers do not support fragmentation with
26608  *	  the current interface.
26609  *	- snoop, multicast, and broadcast may result in exposure of
26610  *	  a cleartext datagram.
26611  * We check all five of these conditions here.
26612  *
26613  * XXX would like to nuke "ire_t *" parameter here; problem is that
26614  * IRE is only way to figure out if a v4 address is a broadcast and
26615  * thus ineligible for acceleration...
26616  */
26617 static void
26618 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26619 {
26620 	ipsec_out_t *io;
26621 	mblk_t *data_mp;
26622 	uint_t plen, overhead;
26623 	ip_stack_t	*ipst;
26624 
26625 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26626 		return;
26627 
26628 	if (ill == NULL)
26629 		return;
26630 	ipst = ill->ill_ipst;
26631 	/*
26632 	 * Destination address is a broadcast or multicast.  Punt.
26633 	 */
26634 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26635 	    IRE_LOCAL)))
26636 		return;
26637 
26638 	data_mp = ipsec_mp->b_cont;
26639 
26640 	if (ill->ill_isv6) {
26641 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26642 
26643 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26644 			return;
26645 
26646 		plen = ip6h->ip6_plen;
26647 	} else {
26648 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26649 
26650 		if (CLASSD(ipha->ipha_dst))
26651 			return;
26652 
26653 		plen = ipha->ipha_length;
26654 	}
26655 	/*
26656 	 * Is there a pending DLPI control message being exchanged
26657 	 * between IP/IPsec and the DLS Provider? If there is, it
26658 	 * could be a SADB update, and the state of the DLS Provider
26659 	 * SADB might not be in sync with the SADB maintained by
26660 	 * IPsec. To avoid dropping packets or using the wrong keying
26661 	 * material, we do not accelerate this packet.
26662 	 */
26663 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26664 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26665 		    "ill_dlpi_pending! don't accelerate packet\n"));
26666 		return;
26667 	}
26668 
26669 	/*
26670 	 * Is the Provider in promiscous mode? If it does, we don't
26671 	 * accelerate the packet since it will bounce back up to the
26672 	 * listeners in the clear.
26673 	 */
26674 	if (ill->ill_promisc_on_phys) {
26675 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26676 		    "ill in promiscous mode, don't accelerate packet\n"));
26677 		return;
26678 	}
26679 
26680 	/*
26681 	 * Will the packet require fragmentation?
26682 	 */
26683 
26684 	/*
26685 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26686 	 * as is used elsewhere.
26687 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26688 	 *	+ 2-byte trailer
26689 	 */
26690 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26691 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26692 
26693 	if ((plen + overhead) > ill->ill_max_mtu)
26694 		return;
26695 
26696 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26697 
26698 	/*
26699 	 * Can the ill accelerate this IPsec protocol and algorithm
26700 	 * specified by the SA?
26701 	 */
26702 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26703 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26704 		return;
26705 	}
26706 
26707 	/*
26708 	 * Tell AH or ESP that the outbound ill is capable of
26709 	 * accelerating this packet.
26710 	 */
26711 	io->ipsec_out_is_capab_ill = B_TRUE;
26712 }
26713 
26714 /*
26715  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26716  *
26717  * If this function returns B_TRUE, the requested SA's have been filled
26718  * into the ipsec_out_*_sa pointers.
26719  *
26720  * If the function returns B_FALSE, the packet has been "consumed", most
26721  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26722  *
26723  * The SA references created by the protocol-specific "select"
26724  * function will be released when the ipsec_mp is freed, thanks to the
26725  * ipsec_out_free destructor -- see spd.c.
26726  */
26727 static boolean_t
26728 ipsec_out_select_sa(mblk_t *ipsec_mp)
26729 {
26730 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26731 	ipsec_out_t *io;
26732 	ipsec_policy_t *pp;
26733 	ipsec_action_t *ap;
26734 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26735 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26736 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26737 
26738 	if (!io->ipsec_out_secure) {
26739 		/*
26740 		 * We came here by mistake.
26741 		 * Don't bother with ipsec processing
26742 		 * We should "discourage" this path in the future.
26743 		 */
26744 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26745 		return (B_FALSE);
26746 	}
26747 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26748 	ASSERT((io->ipsec_out_policy != NULL) ||
26749 	    (io->ipsec_out_act != NULL));
26750 
26751 	ASSERT(io->ipsec_out_failed == B_FALSE);
26752 
26753 	/*
26754 	 * IPSEC processing has started.
26755 	 */
26756 	io->ipsec_out_proc_begin = B_TRUE;
26757 	ap = io->ipsec_out_act;
26758 	if (ap == NULL) {
26759 		pp = io->ipsec_out_policy;
26760 		ASSERT(pp != NULL);
26761 		ap = pp->ipsp_act;
26762 		ASSERT(ap != NULL);
26763 	}
26764 
26765 	/*
26766 	 * We have an action.  now, let's select SA's.
26767 	 * (In the future, we can cache this in the conn_t..)
26768 	 */
26769 	if (ap->ipa_want_esp) {
26770 		if (io->ipsec_out_esp_sa == NULL) {
26771 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26772 			    IPPROTO_ESP);
26773 		}
26774 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26775 	}
26776 
26777 	if (ap->ipa_want_ah) {
26778 		if (io->ipsec_out_ah_sa == NULL) {
26779 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26780 			    IPPROTO_AH);
26781 		}
26782 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26783 		/*
26784 		 * The ESP and AH processing order needs to be preserved
26785 		 * when both protocols are required (ESP should be applied
26786 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26787 		 * when both ESP and AH are required, and an AH ACQUIRE
26788 		 * is needed.
26789 		 */
26790 		if (ap->ipa_want_esp && need_ah_acquire)
26791 			need_esp_acquire = B_TRUE;
26792 	}
26793 
26794 	/*
26795 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26796 	 * Release SAs that got referenced, but will not be used until we
26797 	 * acquire _all_ of the SAs we need.
26798 	 */
26799 	if (need_ah_acquire || need_esp_acquire) {
26800 		if (io->ipsec_out_ah_sa != NULL) {
26801 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26802 			io->ipsec_out_ah_sa = NULL;
26803 		}
26804 		if (io->ipsec_out_esp_sa != NULL) {
26805 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26806 			io->ipsec_out_esp_sa = NULL;
26807 		}
26808 
26809 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26810 		return (B_FALSE);
26811 	}
26812 
26813 	return (B_TRUE);
26814 }
26815 
26816 /*
26817  * Process an IPSEC_OUT message and see what you can
26818  * do with it.
26819  * IPQoS Notes:
26820  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26821  * IPSec.
26822  * XXX would like to nuke ire_t.
26823  * XXX ill_index better be "real"
26824  */
26825 void
26826 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26827 {
26828 	ipsec_out_t *io;
26829 	ipsec_policy_t *pp;
26830 	ipsec_action_t *ap;
26831 	ipha_t *ipha;
26832 	ip6_t *ip6h;
26833 	mblk_t *mp;
26834 	ill_t *ill;
26835 	zoneid_t zoneid;
26836 	ipsec_status_t ipsec_rc;
26837 	boolean_t ill_need_rele = B_FALSE;
26838 	ip_stack_t	*ipst;
26839 	ipsec_stack_t	*ipss;
26840 
26841 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26842 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26843 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26844 	ipst = io->ipsec_out_ns->netstack_ip;
26845 	mp = ipsec_mp->b_cont;
26846 
26847 	/*
26848 	 * Initiate IPPF processing. We do it here to account for packets
26849 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26850 	 * We can check for ipsec_out_proc_begin even for such packets, as
26851 	 * they will always be false (asserted below).
26852 	 */
26853 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26854 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26855 		    io->ipsec_out_ill_index : ill_index);
26856 		if (mp == NULL) {
26857 			ip2dbg(("ipsec_out_process: packet dropped "\
26858 			    "during IPPF processing\n"));
26859 			freeb(ipsec_mp);
26860 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26861 			return;
26862 		}
26863 	}
26864 
26865 	if (!io->ipsec_out_secure) {
26866 		/*
26867 		 * We came here by mistake.
26868 		 * Don't bother with ipsec processing
26869 		 * Should "discourage" this path in the future.
26870 		 */
26871 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26872 		goto done;
26873 	}
26874 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26875 	ASSERT((io->ipsec_out_policy != NULL) ||
26876 	    (io->ipsec_out_act != NULL));
26877 	ASSERT(io->ipsec_out_failed == B_FALSE);
26878 
26879 	ipss = ipst->ips_netstack->netstack_ipsec;
26880 	if (!ipsec_loaded(ipss)) {
26881 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26882 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26883 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26884 		} else {
26885 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26886 		}
26887 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26888 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26889 		    &ipss->ipsec_dropper);
26890 		return;
26891 	}
26892 
26893 	/*
26894 	 * IPSEC processing has started.
26895 	 */
26896 	io->ipsec_out_proc_begin = B_TRUE;
26897 	ap = io->ipsec_out_act;
26898 	if (ap == NULL) {
26899 		pp = io->ipsec_out_policy;
26900 		ASSERT(pp != NULL);
26901 		ap = pp->ipsp_act;
26902 		ASSERT(ap != NULL);
26903 	}
26904 
26905 	/*
26906 	 * Save the outbound ill index. When the packet comes back
26907 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26908 	 * before sending it the accelerated packet.
26909 	 */
26910 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26911 		int ifindex;
26912 		ill = ire_to_ill(ire);
26913 		ifindex = ill->ill_phyint->phyint_ifindex;
26914 		io->ipsec_out_capab_ill_index = ifindex;
26915 	}
26916 
26917 	/*
26918 	 * The order of processing is first insert a IP header if needed.
26919 	 * Then insert the ESP header and then the AH header.
26920 	 */
26921 	if ((io->ipsec_out_se_done == B_FALSE) &&
26922 	    (ap->ipa_want_se)) {
26923 		/*
26924 		 * First get the outer IP header before sending
26925 		 * it to ESP.
26926 		 */
26927 		ipha_t *oipha, *iipha;
26928 		mblk_t *outer_mp, *inner_mp;
26929 
26930 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26931 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26932 			    "ipsec_out_process: "
26933 			    "Self-Encapsulation failed: Out of memory\n");
26934 			freemsg(ipsec_mp);
26935 			if (ill != NULL) {
26936 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26937 			} else {
26938 				BUMP_MIB(&ipst->ips_ip_mib,
26939 				    ipIfStatsOutDiscards);
26940 			}
26941 			return;
26942 		}
26943 		inner_mp = ipsec_mp->b_cont;
26944 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26945 		oipha = (ipha_t *)outer_mp->b_rptr;
26946 		iipha = (ipha_t *)inner_mp->b_rptr;
26947 		*oipha = *iipha;
26948 		outer_mp->b_wptr += sizeof (ipha_t);
26949 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26950 		    sizeof (ipha_t));
26951 		oipha->ipha_protocol = IPPROTO_ENCAP;
26952 		oipha->ipha_version_and_hdr_length =
26953 		    IP_SIMPLE_HDR_VERSION;
26954 		oipha->ipha_hdr_checksum = 0;
26955 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26956 		outer_mp->b_cont = inner_mp;
26957 		ipsec_mp->b_cont = outer_mp;
26958 
26959 		io->ipsec_out_se_done = B_TRUE;
26960 		io->ipsec_out_tunnel = B_TRUE;
26961 	}
26962 
26963 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26964 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26965 	    !ipsec_out_select_sa(ipsec_mp))
26966 		return;
26967 
26968 	/*
26969 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26970 	 * to do the heavy lifting.
26971 	 */
26972 	zoneid = io->ipsec_out_zoneid;
26973 	ASSERT(zoneid != ALL_ZONES);
26974 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26975 		ASSERT(io->ipsec_out_esp_sa != NULL);
26976 		io->ipsec_out_esp_done = B_TRUE;
26977 		/*
26978 		 * Note that since hw accel can only apply one transform,
26979 		 * not two, we skip hw accel for ESP if we also have AH
26980 		 * This is an design limitation of the interface
26981 		 * which should be revisited.
26982 		 */
26983 		ASSERT(ire != NULL);
26984 		if (io->ipsec_out_ah_sa == NULL) {
26985 			ill = (ill_t *)ire->ire_stq->q_ptr;
26986 			ipsec_out_is_accelerated(ipsec_mp,
26987 			    io->ipsec_out_esp_sa, ill, ire);
26988 		}
26989 
26990 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26991 		switch (ipsec_rc) {
26992 		case IPSEC_STATUS_SUCCESS:
26993 			break;
26994 		case IPSEC_STATUS_FAILED:
26995 			if (ill != NULL) {
26996 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26997 			} else {
26998 				BUMP_MIB(&ipst->ips_ip_mib,
26999 				    ipIfStatsOutDiscards);
27000 			}
27001 			/* FALLTHRU */
27002 		case IPSEC_STATUS_PENDING:
27003 			return;
27004 		}
27005 	}
27006 
27007 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27008 		ASSERT(io->ipsec_out_ah_sa != NULL);
27009 		io->ipsec_out_ah_done = B_TRUE;
27010 		if (ire == NULL) {
27011 			int idx = io->ipsec_out_capab_ill_index;
27012 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27013 			    NULL, NULL, NULL, NULL, ipst);
27014 			ill_need_rele = B_TRUE;
27015 		} else {
27016 			ill = (ill_t *)ire->ire_stq->q_ptr;
27017 		}
27018 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27019 		    ire);
27020 
27021 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27022 		switch (ipsec_rc) {
27023 		case IPSEC_STATUS_SUCCESS:
27024 			break;
27025 		case IPSEC_STATUS_FAILED:
27026 			if (ill != NULL) {
27027 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27028 			} else {
27029 				BUMP_MIB(&ipst->ips_ip_mib,
27030 				    ipIfStatsOutDiscards);
27031 			}
27032 			/* FALLTHRU */
27033 		case IPSEC_STATUS_PENDING:
27034 			if (ill != NULL && ill_need_rele)
27035 				ill_refrele(ill);
27036 			return;
27037 		}
27038 	}
27039 	/*
27040 	 * We are done with IPSEC processing. Send it over
27041 	 * the wire.
27042 	 */
27043 done:
27044 	mp = ipsec_mp->b_cont;
27045 	ipha = (ipha_t *)mp->b_rptr;
27046 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27047 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27048 	} else {
27049 		ip6h = (ip6_t *)ipha;
27050 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27051 	}
27052 	if (ill != NULL && ill_need_rele)
27053 		ill_refrele(ill);
27054 }
27055 
27056 /* ARGSUSED */
27057 void
27058 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27059 {
27060 	opt_restart_t	*or;
27061 	int	err;
27062 	conn_t	*connp;
27063 
27064 	ASSERT(CONN_Q(q));
27065 	connp = Q_TO_CONN(q);
27066 
27067 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27068 	or = (opt_restart_t *)first_mp->b_rptr;
27069 	/*
27070 	 * We don't need to pass any credentials here since this is just
27071 	 * a restart. The credentials are passed in when svr4_optcom_req
27072 	 * is called the first time (from ip_wput_nondata).
27073 	 */
27074 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27075 		err = svr4_optcom_req(q, first_mp, NULL,
27076 		    &ip_opt_obj);
27077 	} else {
27078 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27079 		err = tpi_optcom_req(q, first_mp, NULL,
27080 		    &ip_opt_obj);
27081 	}
27082 	if (err != EINPROGRESS) {
27083 		/* operation is done */
27084 		CONN_OPER_PENDING_DONE(connp);
27085 	}
27086 }
27087 
27088 /*
27089  * ioctls that go through a down/up sequence may need to wait for the down
27090  * to complete. This involves waiting for the ire and ipif refcnts to go down
27091  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27092  */
27093 /* ARGSUSED */
27094 void
27095 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27096 {
27097 	struct iocblk *iocp;
27098 	mblk_t *mp1;
27099 	ip_ioctl_cmd_t *ipip;
27100 	int err;
27101 	sin_t	*sin;
27102 	struct lifreq *lifr;
27103 	struct ifreq *ifr;
27104 
27105 	iocp = (struct iocblk *)mp->b_rptr;
27106 	ASSERT(ipsq != NULL);
27107 	/* Existence of mp1 verified in ip_wput_nondata */
27108 	mp1 = mp->b_cont->b_cont;
27109 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27110 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27111 		/*
27112 		 * Special case where ipsq_current_ipif is not set:
27113 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27114 		 * ill could also have become part of a ipmp group in the
27115 		 * process, we are here as were not able to complete the
27116 		 * operation in ipif_set_values because we could not become
27117 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27118 		 * will not be set so we need to set it.
27119 		 */
27120 		ill_t *ill = q->q_ptr;
27121 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27122 	}
27123 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27124 
27125 	if (ipip->ipi_cmd_type == IF_CMD) {
27126 		/* This a old style SIOC[GS]IF* command */
27127 		ifr = (struct ifreq *)mp1->b_rptr;
27128 		sin = (sin_t *)&ifr->ifr_addr;
27129 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27130 		/* This a new style SIOC[GS]LIF* command */
27131 		lifr = (struct lifreq *)mp1->b_rptr;
27132 		sin = (sin_t *)&lifr->lifr_addr;
27133 	} else {
27134 		sin = NULL;
27135 	}
27136 
27137 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27138 	    ipip, mp1->b_rptr);
27139 
27140 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27141 }
27142 
27143 /*
27144  * ioctl processing
27145  *
27146  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27147  * the ioctl command in the ioctl tables and determines the copyin data size
27148  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27149  * size.
27150  *
27151  * ioctl processing then continues when the M_IOCDATA makes its way down.
27152  * Now the ioctl is looked up again in the ioctl table, and its properties are
27153  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27154  * and the general ioctl processing function ip_process_ioctl is called.
27155  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27156  * so goes thru the serialization primitive ipsq_try_enter. Then the
27157  * appropriate function to handle the ioctl is called based on the entry in
27158  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27159  * which also refreleases the 'conn' that was refheld at the start of the
27160  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27161  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27162  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27163  *
27164  * Many exclusive ioctls go thru an internal down up sequence as part of
27165  * the operation. For example an attempt to change the IP address of an
27166  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27167  * does all the cleanup such as deleting all ires that use this address.
27168  * Then we need to wait till all references to the interface go away.
27169  */
27170 void
27171 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27172 {
27173 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27174 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27175 	cmd_info_t ci;
27176 	int err;
27177 	boolean_t entered_ipsq = B_FALSE;
27178 
27179 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27180 
27181 	if (ipip == NULL)
27182 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27183 
27184 	/*
27185 	 * SIOCLIFADDIF needs to go thru a special path since the
27186 	 * ill may not exist yet. This happens in the case of lo0
27187 	 * which is created using this ioctl.
27188 	 */
27189 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27190 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27191 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27192 		return;
27193 	}
27194 
27195 	ci.ci_ipif = NULL;
27196 	switch (ipip->ipi_cmd_type) {
27197 	case IF_CMD:
27198 	case LIF_CMD:
27199 		/*
27200 		 * ioctls that pass in a [l]ifreq appear here.
27201 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27202 		 * ci.ci_ipif
27203 		 */
27204 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27205 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27206 		if (err != 0) {
27207 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27208 			return;
27209 		}
27210 		ASSERT(ci.ci_ipif != NULL);
27211 		break;
27212 
27213 	case TUN_CMD:
27214 		/*
27215 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27216 		 * a refheld ipif in ci.ci_ipif
27217 		 */
27218 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27219 		if (err != 0) {
27220 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27221 			return;
27222 		}
27223 		ASSERT(ci.ci_ipif != NULL);
27224 		break;
27225 
27226 	case MISC_CMD:
27227 		/*
27228 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27229 		 * For eg. SIOCGLIFCONF will appear here.
27230 		 */
27231 		switch (ipip->ipi_cmd) {
27232 		case IF_UNITSEL:
27233 			/* ioctl comes down the ill */
27234 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27235 			ipif_refhold(ci.ci_ipif);
27236 			break;
27237 		case SIOCGMSFILTER:
27238 		case SIOCSMSFILTER:
27239 		case SIOCGIPMSFILTER:
27240 		case SIOCSIPMSFILTER:
27241 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27242 			    ip_process_ioctl);
27243 			if (err != 0) {
27244 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27245 				    NULL);
27246 			}
27247 			break;
27248 		}
27249 		err = 0;
27250 		ci.ci_sin = NULL;
27251 		ci.ci_sin6 = NULL;
27252 		ci.ci_lifr = NULL;
27253 		break;
27254 	}
27255 
27256 	/*
27257 	 * If ipsq is non-null, we are already being called exclusively
27258 	 */
27259 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27260 	if (!(ipip->ipi_flags & IPI_WR)) {
27261 		/*
27262 		 * A return value of EINPROGRESS means the ioctl is
27263 		 * either queued and waiting for some reason or has
27264 		 * already completed.
27265 		 */
27266 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27267 		    ci.ci_lifr);
27268 		if (ci.ci_ipif != NULL)
27269 			ipif_refrele(ci.ci_ipif);
27270 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27271 		return;
27272 	}
27273 
27274 	ASSERT(ci.ci_ipif != NULL);
27275 
27276 	if (ipsq == NULL) {
27277 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27278 		    ip_process_ioctl, NEW_OP, B_TRUE);
27279 		entered_ipsq = B_TRUE;
27280 	}
27281 	/*
27282 	 * Release the ipif so that ipif_down and friends that wait for
27283 	 * references to go away are not misled about the current ipif_refcnt
27284 	 * values. We are writer so we can access the ipif even after releasing
27285 	 * the ipif.
27286 	 */
27287 	ipif_refrele(ci.ci_ipif);
27288 	if (ipsq == NULL)
27289 		return;
27290 
27291 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27292 
27293 	/*
27294 	 * For most set ioctls that come here, this serves as a single point
27295 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27296 	 * be any new references to the ipif. This helps functions that go
27297 	 * through this path and end up trying to wait for the refcnts
27298 	 * associated with the ipif to go down to zero. Some exceptions are
27299 	 * Failover, Failback, and Groupname commands that operate on more than
27300 	 * just the ci.ci_ipif. These commands internally determine the
27301 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27302 	 * flags on that set. Another exception is the Removeif command that
27303 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27304 	 * ipif to operate on.
27305 	 */
27306 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27307 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27308 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27309 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27310 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27311 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27312 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27313 
27314 	/*
27315 	 * A return value of EINPROGRESS means the ioctl is
27316 	 * either queued and waiting for some reason or has
27317 	 * already completed.
27318 	 */
27319 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27320 
27321 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27322 
27323 	if (entered_ipsq)
27324 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27325 }
27326 
27327 /*
27328  * Complete the ioctl. Typically ioctls use the mi package and need to
27329  * do mi_copyout/mi_copy_done.
27330  */
27331 void
27332 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27333 {
27334 	conn_t	*connp = NULL;
27335 
27336 	if (err == EINPROGRESS)
27337 		return;
27338 
27339 	if (CONN_Q(q)) {
27340 		connp = Q_TO_CONN(q);
27341 		ASSERT(connp->conn_ref >= 2);
27342 	}
27343 
27344 	switch (mode) {
27345 	case COPYOUT:
27346 		if (err == 0)
27347 			mi_copyout(q, mp);
27348 		else
27349 			mi_copy_done(q, mp, err);
27350 		break;
27351 
27352 	case NO_COPYOUT:
27353 		mi_copy_done(q, mp, err);
27354 		break;
27355 
27356 	default:
27357 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27358 		break;
27359 	}
27360 
27361 	/*
27362 	 * The refhold placed at the start of the ioctl is released here.
27363 	 */
27364 	if (connp != NULL)
27365 		CONN_OPER_PENDING_DONE(connp);
27366 
27367 	if (ipsq != NULL)
27368 		ipsq_current_finish(ipsq);
27369 }
27370 
27371 /*
27372  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27373  */
27374 /* ARGSUSED */
27375 void
27376 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27377 {
27378 	conn_t *connp = arg;
27379 	tcp_t	*tcp;
27380 
27381 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27382 	tcp = connp->conn_tcp;
27383 
27384 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27385 		freemsg(mp);
27386 	else
27387 		tcp_rput_other(tcp, mp);
27388 	CONN_OPER_PENDING_DONE(connp);
27389 }
27390 
27391 /* Called from ip_wput for all non data messages */
27392 /* ARGSUSED */
27393 void
27394 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27395 {
27396 	mblk_t		*mp1;
27397 	ire_t		*ire, *fake_ire;
27398 	ill_t		*ill;
27399 	struct iocblk	*iocp;
27400 	ip_ioctl_cmd_t	*ipip;
27401 	cred_t		*cr;
27402 	conn_t		*connp;
27403 	int		cmd, err;
27404 	nce_t		*nce;
27405 	ipif_t		*ipif;
27406 	ip_stack_t	*ipst;
27407 	char		*proto_str;
27408 
27409 	if (CONN_Q(q)) {
27410 		connp = Q_TO_CONN(q);
27411 		ipst = connp->conn_netstack->netstack_ip;
27412 	} else {
27413 		connp = NULL;
27414 		ipst = ILLQ_TO_IPST(q);
27415 	}
27416 
27417 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27418 
27419 	/* Check if it is a queue to /dev/sctp. */
27420 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27421 	    connp->conn_rq == NULL) {
27422 		sctp_wput(q, mp);
27423 		return;
27424 	}
27425 
27426 	switch (DB_TYPE(mp)) {
27427 	case M_IOCTL:
27428 		/*
27429 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27430 		 * will arrange to copy in associated control structures.
27431 		 */
27432 		ip_sioctl_copyin_setup(q, mp);
27433 		return;
27434 	case M_IOCDATA:
27435 		/*
27436 		 * Ensure that this is associated with one of our trans-
27437 		 * parent ioctls.  If it's not ours, discard it if we're
27438 		 * running as a driver, or pass it on if we're a module.
27439 		 */
27440 		iocp = (struct iocblk *)mp->b_rptr;
27441 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27442 		if (ipip == NULL) {
27443 			if (q->q_next == NULL) {
27444 				goto nak;
27445 			} else {
27446 				putnext(q, mp);
27447 			}
27448 			return;
27449 		} else if ((q->q_next != NULL) &&
27450 		    !(ipip->ipi_flags & IPI_MODOK)) {
27451 			/*
27452 			 * the ioctl is one we recognise, but is not
27453 			 * consumed by IP as a module, pass M_IOCDATA
27454 			 * for processing downstream, but only for
27455 			 * common Streams ioctls.
27456 			 */
27457 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27458 				putnext(q, mp);
27459 				return;
27460 			} else {
27461 				goto nak;
27462 			}
27463 		}
27464 
27465 		/* IOCTL continuation following copyin or copyout. */
27466 		if (mi_copy_state(q, mp, NULL) == -1) {
27467 			/*
27468 			 * The copy operation failed.  mi_copy_state already
27469 			 * cleaned up, so we're out of here.
27470 			 */
27471 			return;
27472 		}
27473 		/*
27474 		 * If we just completed a copy in, we become writer and
27475 		 * continue processing in ip_sioctl_copyin_done.  If it
27476 		 * was a copy out, we call mi_copyout again.  If there is
27477 		 * nothing more to copy out, it will complete the IOCTL.
27478 		 */
27479 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27480 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27481 				mi_copy_done(q, mp, EPROTO);
27482 				return;
27483 			}
27484 			/*
27485 			 * Check for cases that need more copying.  A return
27486 			 * value of 0 means a second copyin has been started,
27487 			 * so we return; a return value of 1 means no more
27488 			 * copying is needed, so we continue.
27489 			 */
27490 			cmd = iocp->ioc_cmd;
27491 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27492 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27493 			    MI_COPY_COUNT(mp) == 1) {
27494 				if (ip_copyin_msfilter(q, mp) == 0)
27495 					return;
27496 			}
27497 			/*
27498 			 * Refhold the conn, till the ioctl completes. This is
27499 			 * needed in case the ioctl ends up in the pending mp
27500 			 * list. Every mp in the ill_pending_mp list and
27501 			 * the ipsq_pending_mp must have a refhold on the conn
27502 			 * to resume processing. The refhold is released when
27503 			 * the ioctl completes. (normally or abnormally)
27504 			 * In all cases ip_ioctl_finish is called to finish
27505 			 * the ioctl.
27506 			 */
27507 			if (connp != NULL) {
27508 				/* This is not a reentry */
27509 				ASSERT(ipsq == NULL);
27510 				CONN_INC_REF(connp);
27511 			} else {
27512 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27513 					mi_copy_done(q, mp, EINVAL);
27514 					return;
27515 				}
27516 			}
27517 
27518 			ip_process_ioctl(ipsq, q, mp, ipip);
27519 
27520 		} else {
27521 			mi_copyout(q, mp);
27522 		}
27523 		return;
27524 nak:
27525 		iocp->ioc_error = EINVAL;
27526 		mp->b_datap->db_type = M_IOCNAK;
27527 		iocp->ioc_count = 0;
27528 		qreply(q, mp);
27529 		return;
27530 
27531 	case M_IOCNAK:
27532 		/*
27533 		 * The only way we could get here is if a resolver didn't like
27534 		 * an IOCTL we sent it.	 This shouldn't happen.
27535 		 */
27536 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27537 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27538 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27539 		freemsg(mp);
27540 		return;
27541 	case M_IOCACK:
27542 		/* /dev/ip shouldn't see this */
27543 		if (CONN_Q(q))
27544 			goto nak;
27545 
27546 		/* Finish socket ioctls passed through to ARP. */
27547 		ip_sioctl_iocack(q, mp);
27548 		return;
27549 	case M_FLUSH:
27550 		if (*mp->b_rptr & FLUSHW)
27551 			flushq(q, FLUSHALL);
27552 		if (q->q_next) {
27553 			/*
27554 			 * M_FLUSH is sent up to IP by some drivers during
27555 			 * unbind. ip_rput has already replied to it. We are
27556 			 * here for the M_FLUSH that we originated in IP
27557 			 * before sending the unbind request to the driver.
27558 			 * Just free it as we don't queue packets in IP
27559 			 * on the write side of the device instance.
27560 			 */
27561 			freemsg(mp);
27562 			return;
27563 		}
27564 		if (*mp->b_rptr & FLUSHR) {
27565 			*mp->b_rptr &= ~FLUSHW;
27566 			qreply(q, mp);
27567 			return;
27568 		}
27569 		freemsg(mp);
27570 		return;
27571 	case IRE_DB_REQ_TYPE:
27572 		if (connp == NULL) {
27573 			proto_str = "IRE_DB_REQ_TYPE";
27574 			goto protonak;
27575 		}
27576 		/* An Upper Level Protocol wants a copy of an IRE. */
27577 		ip_ire_req(q, mp);
27578 		return;
27579 	case M_CTL:
27580 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27581 			break;
27582 
27583 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27584 		    TUN_HELLO) {
27585 			ASSERT(connp != NULL);
27586 			connp->conn_flags |= IPCL_IPTUN;
27587 			freeb(mp);
27588 			return;
27589 		}
27590 
27591 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27592 		    IP_ULP_OUT_LABELED) {
27593 			out_labeled_t *olp;
27594 
27595 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27596 				break;
27597 			olp = (out_labeled_t *)mp->b_rptr;
27598 			connp->conn_ulp_labeled = olp->out_qnext == q;
27599 			freemsg(mp);
27600 			return;
27601 		}
27602 
27603 		/* M_CTL messages are used by ARP to tell us things. */
27604 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27605 			break;
27606 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27607 		case AR_ENTRY_SQUERY:
27608 			ip_wput_ctl(q, mp);
27609 			return;
27610 		case AR_CLIENT_NOTIFY:
27611 			ip_arp_news(q, mp);
27612 			return;
27613 		case AR_DLPIOP_DONE:
27614 			ASSERT(q->q_next != NULL);
27615 			ill = (ill_t *)q->q_ptr;
27616 			/* qwriter_ip releases the refhold */
27617 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27618 			ill_refhold(ill);
27619 			(void) qwriter_ip(NULL, ill, q, mp, ip_arp_done,
27620 			    CUR_OP, B_FALSE);
27621 			return;
27622 		case AR_ARP_CLOSING:
27623 			/*
27624 			 * ARP (above us) is closing. If no ARP bringup is
27625 			 * currently pending, ack the message so that ARP
27626 			 * can complete its close. Also mark ill_arp_closing
27627 			 * so that new ARP bringups will fail. If any
27628 			 * ARP bringup is currently in progress, we will
27629 			 * ack this when the current ARP bringup completes.
27630 			 */
27631 			ASSERT(q->q_next != NULL);
27632 			ill = (ill_t *)q->q_ptr;
27633 			mutex_enter(&ill->ill_lock);
27634 			ill->ill_arp_closing = 1;
27635 			if (!ill->ill_arp_bringup_pending) {
27636 				mutex_exit(&ill->ill_lock);
27637 				qreply(q, mp);
27638 			} else {
27639 				mutex_exit(&ill->ill_lock);
27640 				freemsg(mp);
27641 			}
27642 			return;
27643 		case AR_ARP_EXTEND:
27644 			/*
27645 			 * The ARP module above us is capable of duplicate
27646 			 * address detection.  Old ATM drivers will not send
27647 			 * this message.
27648 			 */
27649 			ASSERT(q->q_next != NULL);
27650 			ill = (ill_t *)q->q_ptr;
27651 			ill->ill_arp_extend = B_TRUE;
27652 			freemsg(mp);
27653 			return;
27654 		default:
27655 			break;
27656 		}
27657 		break;
27658 	case M_PROTO:
27659 	case M_PCPROTO:
27660 		/*
27661 		 * The only PROTO messages we expect are ULP binds and
27662 		 * copies of option negotiation acknowledgements.
27663 		 */
27664 		switch (((union T_primitives *)mp->b_rptr)->type) {
27665 		case O_T_BIND_REQ:
27666 		case T_BIND_REQ: {
27667 			/* Request can get queued in bind */
27668 			if (connp == NULL) {
27669 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27670 				goto protonak;
27671 			}
27672 			/*
27673 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27674 			 * instead of going through this path.  We only get
27675 			 * here in the following cases:
27676 			 *
27677 			 * a. Bind retries, where ipsq is non-NULL.
27678 			 * b. T_BIND_REQ is issued from non TCP/UDP
27679 			 *    transport, e.g. icmp for raw socket,
27680 			 *    in which case ipsq will be NULL.
27681 			 */
27682 			ASSERT(ipsq != NULL ||
27683 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27684 
27685 			/* Don't increment refcnt if this is a re-entry */
27686 			if (ipsq == NULL)
27687 				CONN_INC_REF(connp);
27688 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27689 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27690 			if (mp == NULL)
27691 				return;
27692 			if (IPCL_IS_TCP(connp)) {
27693 				/*
27694 				 * In the case of TCP endpoint we
27695 				 * come here only for bind retries
27696 				 */
27697 				ASSERT(ipsq != NULL);
27698 				CONN_INC_REF(connp);
27699 				squeue_fill(connp->conn_sqp, mp,
27700 				    ip_resume_tcp_bind, connp,
27701 				    SQTAG_BIND_RETRY);
27702 				return;
27703 			} else if (IPCL_IS_UDP(connp)) {
27704 				/*
27705 				 * In the case of UDP endpoint we
27706 				 * come here only for bind retries
27707 				 */
27708 				ASSERT(ipsq != NULL);
27709 				udp_resume_bind(connp, mp);
27710 				return;
27711 			}
27712 			qreply(q, mp);
27713 			CONN_OPER_PENDING_DONE(connp);
27714 			return;
27715 		}
27716 		case T_SVR4_OPTMGMT_REQ:
27717 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27718 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27719 
27720 			if (connp == NULL) {
27721 				proto_str = "T_SVR4_OPTMGMT_REQ";
27722 				goto protonak;
27723 			}
27724 
27725 			if (!snmpcom_req(q, mp, ip_snmp_set,
27726 			    ip_snmp_get, cr)) {
27727 				/*
27728 				 * Call svr4_optcom_req so that it can
27729 				 * generate the ack. We don't come here
27730 				 * if this operation is being restarted.
27731 				 * ip_restart_optmgmt will drop the conn ref.
27732 				 * In the case of ipsec option after the ipsec
27733 				 * load is complete conn_restart_ipsec_waiter
27734 				 * drops the conn ref.
27735 				 */
27736 				ASSERT(ipsq == NULL);
27737 				CONN_INC_REF(connp);
27738 				if (ip_check_for_ipsec_opt(q, mp))
27739 					return;
27740 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27741 				if (err != EINPROGRESS) {
27742 					/* Operation is done */
27743 					CONN_OPER_PENDING_DONE(connp);
27744 				}
27745 			}
27746 			return;
27747 		case T_OPTMGMT_REQ:
27748 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27749 			/*
27750 			 * Note: No snmpcom_req support through new
27751 			 * T_OPTMGMT_REQ.
27752 			 * Call tpi_optcom_req so that it can
27753 			 * generate the ack.
27754 			 */
27755 			if (connp == NULL) {
27756 				proto_str = "T_OPTMGMT_REQ";
27757 				goto protonak;
27758 			}
27759 
27760 			ASSERT(ipsq == NULL);
27761 			/*
27762 			 * We don't come here for restart. ip_restart_optmgmt
27763 			 * will drop the conn ref. In the case of ipsec option
27764 			 * after the ipsec load is complete
27765 			 * conn_restart_ipsec_waiter drops the conn ref.
27766 			 */
27767 			CONN_INC_REF(connp);
27768 			if (ip_check_for_ipsec_opt(q, mp))
27769 				return;
27770 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27771 			if (err != EINPROGRESS) {
27772 				/* Operation is done */
27773 				CONN_OPER_PENDING_DONE(connp);
27774 			}
27775 			return;
27776 		case T_UNBIND_REQ:
27777 			if (connp == NULL) {
27778 				proto_str = "T_UNBIND_REQ";
27779 				goto protonak;
27780 			}
27781 			mp = ip_unbind(q, mp);
27782 			qreply(q, mp);
27783 			return;
27784 		default:
27785 			/*
27786 			 * Have to drop any DLPI messages coming down from
27787 			 * arp (such as an info_req which would cause ip
27788 			 * to receive an extra info_ack if it was passed
27789 			 * through.
27790 			 */
27791 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27792 			    (int)*(uint_t *)mp->b_rptr));
27793 			freemsg(mp);
27794 			return;
27795 		}
27796 		/* NOTREACHED */
27797 	case IRE_DB_TYPE: {
27798 		nce_t		*nce;
27799 		ill_t		*ill;
27800 		in6_addr_t	gw_addr_v6;
27801 
27802 
27803 		/*
27804 		 * This is a response back from a resolver.  It
27805 		 * consists of a message chain containing:
27806 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27807 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27808 		 * The LL_HDR_MBLK is the DLPI header to use to get
27809 		 * the attached packet, and subsequent ones for the
27810 		 * same destination, transmitted.
27811 		 */
27812 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27813 			break;
27814 		/*
27815 		 * First, check to make sure the resolution succeeded.
27816 		 * If it failed, the second mblk will be empty.
27817 		 * If it is, free the chain, dropping the packet.
27818 		 * (We must ire_delete the ire; that frees the ire mblk)
27819 		 * We're doing this now to support PVCs for ATM; it's
27820 		 * a partial xresolv implementation. When we fully implement
27821 		 * xresolv interfaces, instead of freeing everything here
27822 		 * we'll initiate neighbor discovery.
27823 		 *
27824 		 * For v4 (ARP and other external resolvers) the resolver
27825 		 * frees the message, so no check is needed. This check
27826 		 * is required, though, for a full xresolve implementation.
27827 		 * Including this code here now both shows how external
27828 		 * resolvers can NACK a resolution request using an
27829 		 * existing design that has no specific provisions for NACKs,
27830 		 * and also takes into account that the current non-ARP
27831 		 * external resolver has been coded to use this method of
27832 		 * NACKing for all IPv6 (xresolv) cases,
27833 		 * whether our xresolv implementation is complete or not.
27834 		 *
27835 		 */
27836 		ire = (ire_t *)mp->b_rptr;
27837 		ill = ire_to_ill(ire);
27838 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27839 		if (mp1->b_rptr == mp1->b_wptr) {
27840 			if (ire->ire_ipversion == IPV6_VERSION) {
27841 				/*
27842 				 * XRESOLV interface.
27843 				 */
27844 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27845 				mutex_enter(&ire->ire_lock);
27846 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27847 				mutex_exit(&ire->ire_lock);
27848 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27849 					nce = ndp_lookup_v6(ill,
27850 					    &ire->ire_addr_v6, B_FALSE);
27851 				} else {
27852 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27853 					    B_FALSE);
27854 				}
27855 				if (nce != NULL) {
27856 					nce_resolv_failed(nce);
27857 					ndp_delete(nce);
27858 					NCE_REFRELE(nce);
27859 				}
27860 			}
27861 			mp->b_cont = NULL;
27862 			freemsg(mp1);		/* frees the pkt as well */
27863 			ASSERT(ire->ire_nce == NULL);
27864 			ire_delete((ire_t *)mp->b_rptr);
27865 			return;
27866 		}
27867 
27868 		/*
27869 		 * Split them into IRE_MBLK and pkt and feed it into
27870 		 * ire_add_then_send. Then in ire_add_then_send
27871 		 * the IRE will be added, and then the packet will be
27872 		 * run back through ip_wput. This time it will make
27873 		 * it to the wire.
27874 		 */
27875 		mp->b_cont = NULL;
27876 		mp = mp1->b_cont;		/* now, mp points to pkt */
27877 		mp1->b_cont = NULL;
27878 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27879 		if (ire->ire_ipversion == IPV6_VERSION) {
27880 			/*
27881 			 * XRESOLV interface. Find the nce and put a copy
27882 			 * of the dl_unitdata_req in nce_res_mp
27883 			 */
27884 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27885 			mutex_enter(&ire->ire_lock);
27886 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27887 			mutex_exit(&ire->ire_lock);
27888 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27889 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27890 				    B_FALSE);
27891 			} else {
27892 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27893 			}
27894 			if (nce != NULL) {
27895 				/*
27896 				 * We have to protect nce_res_mp here
27897 				 * from being accessed by other threads
27898 				 * while we change the mblk pointer.
27899 				 * Other functions will also lock the nce when
27900 				 * accessing nce_res_mp.
27901 				 *
27902 				 * The reason we change the mblk pointer
27903 				 * here rather than copying the resolved address
27904 				 * into the template is that, unlike with
27905 				 * ethernet, we have no guarantee that the
27906 				 * resolved address length will be
27907 				 * smaller than or equal to the lla length
27908 				 * with which the template was allocated,
27909 				 * (for ethernet, they're equal)
27910 				 * so we have to use the actual resolved
27911 				 * address mblk - which holds the real
27912 				 * dl_unitdata_req with the resolved address.
27913 				 *
27914 				 * Doing this is the same behavior as was
27915 				 * previously used in the v4 ARP case.
27916 				 */
27917 				mutex_enter(&nce->nce_lock);
27918 				if (nce->nce_res_mp != NULL)
27919 					freemsg(nce->nce_res_mp);
27920 				nce->nce_res_mp = mp1;
27921 				mutex_exit(&nce->nce_lock);
27922 				/*
27923 				 * We do a fastpath probe here because
27924 				 * we have resolved the address without
27925 				 * using Neighbor Discovery.
27926 				 * In the non-XRESOLV v6 case, the fastpath
27927 				 * probe is done right after neighbor
27928 				 * discovery completes.
27929 				 */
27930 				if (nce->nce_res_mp != NULL) {
27931 					int res;
27932 					nce_fastpath_list_add(nce);
27933 					res = ill_fastpath_probe(ill,
27934 					    nce->nce_res_mp);
27935 					if (res != 0 && res != EAGAIN)
27936 						nce_fastpath_list_delete(nce);
27937 				}
27938 
27939 				ire_add_then_send(q, ire, mp);
27940 				/*
27941 				 * Now we have to clean out any packets
27942 				 * that may have been queued on the nce
27943 				 * while it was waiting for address resolution
27944 				 * to complete.
27945 				 */
27946 				mutex_enter(&nce->nce_lock);
27947 				mp1 = nce->nce_qd_mp;
27948 				nce->nce_qd_mp = NULL;
27949 				mutex_exit(&nce->nce_lock);
27950 				while (mp1 != NULL) {
27951 					mblk_t *nxt_mp;
27952 					queue_t *fwdq = NULL;
27953 					ill_t   *inbound_ill;
27954 					uint_t ifindex;
27955 
27956 					nxt_mp = mp1->b_next;
27957 					mp1->b_next = NULL;
27958 					/*
27959 					 * Retrieve ifindex stored in
27960 					 * ip_rput_data_v6()
27961 					 */
27962 					ifindex =
27963 					    (uint_t)(uintptr_t)mp1->b_prev;
27964 					inbound_ill =
27965 						ill_lookup_on_ifindex(ifindex,
27966 						    B_TRUE, NULL, NULL, NULL,
27967 						    NULL, ipst);
27968 					mp1->b_prev = NULL;
27969 					if (inbound_ill != NULL)
27970 						fwdq = inbound_ill->ill_rq;
27971 
27972 					if (fwdq != NULL) {
27973 						put(fwdq, mp1);
27974 						ill_refrele(inbound_ill);
27975 					} else
27976 						put(WR(ill->ill_rq), mp1);
27977 					mp1 = nxt_mp;
27978 				}
27979 				NCE_REFRELE(nce);
27980 			} else {	/* nce is NULL; clean up */
27981 				ire_delete(ire);
27982 				freemsg(mp);
27983 				freemsg(mp1);
27984 				return;
27985 			}
27986 		} else {
27987 			nce_t *arpce;
27988 			/*
27989 			 * Link layer resolution succeeded. Recompute the
27990 			 * ire_nce.
27991 			 */
27992 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27993 			if ((arpce = ndp_lookup_v4(ill,
27994 			    (ire->ire_gateway_addr != INADDR_ANY ?
27995 			    &ire->ire_gateway_addr : &ire->ire_addr),
27996 			    B_FALSE)) == NULL) {
27997 				freeb(ire->ire_mp);
27998 				freeb(mp1);
27999 				freemsg(mp);
28000 				return;
28001 			}
28002 			mutex_enter(&arpce->nce_lock);
28003 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28004 			if (arpce->nce_state == ND_REACHABLE) {
28005 				/*
28006 				 * Someone resolved this before us;
28007 				 * cleanup the res_mp. Since ire has
28008 				 * not been added yet, the call to ire_add_v4
28009 				 * from ire_add_then_send (when a dup is
28010 				 * detected) will clean up the ire.
28011 				 */
28012 				freeb(mp1);
28013 			} else {
28014 				if (arpce->nce_res_mp != NULL)
28015 					freemsg(arpce->nce_res_mp);
28016 				arpce->nce_res_mp = mp1;
28017 				arpce->nce_state = ND_REACHABLE;
28018 			}
28019 			mutex_exit(&arpce->nce_lock);
28020 			if (ire->ire_marks & IRE_MARK_NOADD) {
28021 				/*
28022 				 * this ire will not be added to the ire
28023 				 * cache table, so we can set the ire_nce
28024 				 * here, as there are no atomicity constraints.
28025 				 */
28026 				ire->ire_nce = arpce;
28027 				/*
28028 				 * We are associating this nce with the ire
28029 				 * so change the nce ref taken in
28030 				 * ndp_lookup_v4() from
28031 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28032 				 */
28033 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28034 			} else {
28035 				NCE_REFRELE(arpce);
28036 			}
28037 			ire_add_then_send(q, ire, mp);
28038 		}
28039 		return;	/* All is well, the packet has been sent. */
28040 	}
28041 	case IRE_ARPRESOLVE_TYPE: {
28042 
28043 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28044 			break;
28045 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28046 		mp->b_cont = NULL;
28047 		/*
28048 		 * First, check to make sure the resolution succeeded.
28049 		 * If it failed, the second mblk will be empty.
28050 		 */
28051 		if (mp1->b_rptr == mp1->b_wptr) {
28052 			/* cleanup  the incomplete ire, free queued packets */
28053 			freemsg(mp); /* fake ire */
28054 			freeb(mp1);  /* dl_unitdata response */
28055 			return;
28056 		}
28057 
28058 		/*
28059 		 * update any incomplete nce_t found. we lookup the ctable
28060 		 * and find the nce from the ire->ire_nce because we need
28061 		 * to pass the ire to ip_xmit_v4 later, and can find both
28062 		 * ire and nce in one lookup from the ctable.
28063 		 */
28064 		fake_ire = (ire_t *)mp->b_rptr;
28065 		/*
28066 		 * By the time we come back here from ARP
28067 		 * the logical outgoing interface  of the incomplete ire
28068 		 * we added in ire_forward could have disappeared,
28069 		 * causing the incomplete ire to also have
28070 		 * dissapeared. So we need to retreive the
28071 		 * proper ipif for the ire  before looking
28072 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28073 		 */
28074 		ill = q->q_ptr;
28075 
28076 		/* Get the outgoing ipif */
28077 		mutex_enter(&ill->ill_lock);
28078 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28079 			mutex_exit(&ill->ill_lock);
28080 			freemsg(mp); /* fake ire */
28081 			freeb(mp1);  /* dl_unitdata response */
28082 			return;
28083 		}
28084 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28085 
28086 		if (ipif == NULL) {
28087 			mutex_exit(&ill->ill_lock);
28088 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28089 			freemsg(mp);
28090 			freeb(mp1);
28091 			return;
28092 		}
28093 		ipif_refhold_locked(ipif);
28094 		mutex_exit(&ill->ill_lock);
28095 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28096 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28097 		    ipif, fake_ire->ire_zoneid, NULL,
28098 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28099 		ipif_refrele(ipif);
28100 		if (ire == NULL) {
28101 			/*
28102 			 * no ire was found; check if there is an nce
28103 			 * for this lookup; if it has no ire's pointing at it
28104 			 * cleanup.
28105 			 */
28106 			if ((nce = ndp_lookup_v4(ill,
28107 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28108 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28109 			    B_FALSE)) != NULL) {
28110 				/*
28111 				 * cleanup:
28112 				 * We check for refcnt 2 (one for the nce
28113 				 * hash list + 1 for the ref taken by
28114 				 * ndp_lookup_v4) to check that there are
28115 				 * no ire's pointing at the nce.
28116 				 */
28117 				if (nce->nce_refcnt == 2)
28118 					ndp_delete(nce);
28119 				NCE_REFRELE(nce);
28120 			}
28121 			freeb(mp1);  /* dl_unitdata response */
28122 			freemsg(mp); /* fake ire */
28123 			return;
28124 		}
28125 		nce = ire->ire_nce;
28126 		DTRACE_PROBE2(ire__arpresolve__type,
28127 		    ire_t *, ire, nce_t *, nce);
28128 		ASSERT(nce->nce_state != ND_INITIAL);
28129 		mutex_enter(&nce->nce_lock);
28130 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28131 		if (nce->nce_state == ND_REACHABLE) {
28132 			/*
28133 			 * Someone resolved this before us;
28134 			 * our response is not needed any more.
28135 			 */
28136 			mutex_exit(&nce->nce_lock);
28137 			freeb(mp1);  /* dl_unitdata response */
28138 		} else {
28139 			if (nce->nce_res_mp != NULL) {
28140 				freemsg(nce->nce_res_mp);
28141 				/* existing dl_unitdata template */
28142 			}
28143 			nce->nce_res_mp = mp1;
28144 			nce->nce_state = ND_REACHABLE;
28145 			mutex_exit(&nce->nce_lock);
28146 			nce_fastpath(nce);
28147 		}
28148 		/*
28149 		 * The cached nce_t has been updated to be reachable;
28150 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28151 		 */
28152 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28153 		freemsg(mp);
28154 		/*
28155 		 * send out queued packets.
28156 		 */
28157 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28158 
28159 		IRE_REFRELE(ire);
28160 		return;
28161 	}
28162 	default:
28163 		break;
28164 	}
28165 	if (q->q_next) {
28166 		putnext(q, mp);
28167 	} else
28168 		freemsg(mp);
28169 	return;
28170 
28171 protonak:
28172 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28173 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28174 		qreply(q, mp);
28175 }
28176 
28177 /*
28178  * Process IP options in an outbound packet.  Modify the destination if there
28179  * is a source route option.
28180  * Returns non-zero if something fails in which case an ICMP error has been
28181  * sent and mp freed.
28182  */
28183 static int
28184 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28185     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28186 {
28187 	ipoptp_t	opts;
28188 	uchar_t		*opt;
28189 	uint8_t		optval;
28190 	uint8_t		optlen;
28191 	ipaddr_t	dst;
28192 	intptr_t	code = 0;
28193 	mblk_t		*mp;
28194 	ire_t		*ire = NULL;
28195 
28196 	ip2dbg(("ip_wput_options\n"));
28197 	mp = ipsec_mp;
28198 	if (mctl_present) {
28199 		mp = ipsec_mp->b_cont;
28200 	}
28201 
28202 	dst = ipha->ipha_dst;
28203 	for (optval = ipoptp_first(&opts, ipha);
28204 	    optval != IPOPT_EOL;
28205 	    optval = ipoptp_next(&opts)) {
28206 		opt = opts.ipoptp_cur;
28207 		optlen = opts.ipoptp_len;
28208 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28209 		    optval, optlen));
28210 		switch (optval) {
28211 			uint32_t off;
28212 		case IPOPT_SSRR:
28213 		case IPOPT_LSRR:
28214 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28215 				ip1dbg((
28216 				    "ip_wput_options: bad option offset\n"));
28217 				code = (char *)&opt[IPOPT_OLEN] -
28218 				    (char *)ipha;
28219 				goto param_prob;
28220 			}
28221 			off = opt[IPOPT_OFFSET];
28222 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28223 			    ntohl(dst)));
28224 			/*
28225 			 * For strict: verify that dst is directly
28226 			 * reachable.
28227 			 */
28228 			if (optval == IPOPT_SSRR) {
28229 				ire = ire_ftable_lookup(dst, 0, 0,
28230 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28231 				    MBLK_GETLABEL(mp),
28232 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28233 				if (ire == NULL) {
28234 					ip1dbg(("ip_wput_options: SSRR not"
28235 					    " directly reachable: 0x%x\n",
28236 					    ntohl(dst)));
28237 					goto bad_src_route;
28238 				}
28239 				ire_refrele(ire);
28240 			}
28241 			break;
28242 		case IPOPT_RR:
28243 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28244 				ip1dbg((
28245 				    "ip_wput_options: bad option offset\n"));
28246 				code = (char *)&opt[IPOPT_OLEN] -
28247 				    (char *)ipha;
28248 				goto param_prob;
28249 			}
28250 			break;
28251 		case IPOPT_TS:
28252 			/*
28253 			 * Verify that length >=5 and that there is either
28254 			 * room for another timestamp or that the overflow
28255 			 * counter is not maxed out.
28256 			 */
28257 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28258 			if (optlen < IPOPT_MINLEN_IT) {
28259 				goto param_prob;
28260 			}
28261 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28262 				ip1dbg((
28263 				    "ip_wput_options: bad option offset\n"));
28264 				code = (char *)&opt[IPOPT_OFFSET] -
28265 				    (char *)ipha;
28266 				goto param_prob;
28267 			}
28268 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28269 			case IPOPT_TS_TSONLY:
28270 				off = IPOPT_TS_TIMELEN;
28271 				break;
28272 			case IPOPT_TS_TSANDADDR:
28273 			case IPOPT_TS_PRESPEC:
28274 			case IPOPT_TS_PRESPEC_RFC791:
28275 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28276 				break;
28277 			default:
28278 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28279 				    (char *)ipha;
28280 				goto param_prob;
28281 			}
28282 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28283 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28284 				/*
28285 				 * No room and the overflow counter is 15
28286 				 * already.
28287 				 */
28288 				goto param_prob;
28289 			}
28290 			break;
28291 		}
28292 	}
28293 
28294 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28295 		return (0);
28296 
28297 	ip1dbg(("ip_wput_options: error processing IP options."));
28298 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28299 
28300 param_prob:
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_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28311 	return (-1);
28312 
28313 bad_src_route:
28314 	/*
28315 	 * Since ip_wput() isn't close to finished, we fill
28316 	 * in enough of the header for credible error reporting.
28317 	 */
28318 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28319 		/* Failed */
28320 		freemsg(ipsec_mp);
28321 		return (-1);
28322 	}
28323 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28324 	return (-1);
28325 }
28326 
28327 /*
28328  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28329  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28330  * thru /etc/system.
28331  */
28332 #define	CONN_MAXDRAINCNT	64
28333 
28334 static void
28335 conn_drain_init(ip_stack_t *ipst)
28336 {
28337 	int i;
28338 
28339 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28340 
28341 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28342 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28343 		/*
28344 		 * Default value of the number of drainers is the
28345 		 * number of cpus, subject to maximum of 8 drainers.
28346 		 */
28347 		if (boot_max_ncpus != -1)
28348 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28349 		else
28350 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28351 	}
28352 
28353 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28354 	    sizeof (idl_t), KM_SLEEP);
28355 
28356 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28357 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28358 		    MUTEX_DEFAULT, NULL);
28359 	}
28360 }
28361 
28362 static void
28363 conn_drain_fini(ip_stack_t *ipst)
28364 {
28365 	int i;
28366 
28367 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28368 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28369 	kmem_free(ipst->ips_conn_drain_list,
28370 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28371 	ipst->ips_conn_drain_list = NULL;
28372 }
28373 
28374 /*
28375  * Note: For an overview of how flowcontrol is handled in IP please see the
28376  * IP Flowcontrol notes at the top of this file.
28377  *
28378  * Flow control has blocked us from proceeding. Insert the given conn in one
28379  * of the conn drain lists. These conn wq's will be qenabled later on when
28380  * STREAMS flow control does a backenable. conn_walk_drain will enable
28381  * the first conn in each of these drain lists. Each of these qenabled conns
28382  * in turn enables the next in the list, after it runs, or when it closes,
28383  * thus sustaining the drain process.
28384  *
28385  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28386  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28387  * running at any time, on a given conn, since there can be only 1 service proc
28388  * running on a queue at any time.
28389  */
28390 void
28391 conn_drain_insert(conn_t *connp)
28392 {
28393 	idl_t	*idl;
28394 	uint_t	index;
28395 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28396 
28397 	mutex_enter(&connp->conn_lock);
28398 	if (connp->conn_state_flags & CONN_CLOSING) {
28399 		/*
28400 		 * The conn is closing as a result of which CONN_CLOSING
28401 		 * is set. Return.
28402 		 */
28403 		mutex_exit(&connp->conn_lock);
28404 		return;
28405 	} else if (connp->conn_idl == NULL) {
28406 		/*
28407 		 * Assign the next drain list round robin. We dont' use
28408 		 * a lock, and thus it may not be strictly round robin.
28409 		 * Atomicity of load/stores is enough to make sure that
28410 		 * conn_drain_list_index is always within bounds.
28411 		 */
28412 		index = ipst->ips_conn_drain_list_index;
28413 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28414 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28415 		index++;
28416 		if (index == ipst->ips_conn_drain_list_cnt)
28417 			index = 0;
28418 		ipst->ips_conn_drain_list_index = index;
28419 	}
28420 	mutex_exit(&connp->conn_lock);
28421 
28422 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28423 	if ((connp->conn_drain_prev != NULL) ||
28424 	    (connp->conn_state_flags & CONN_CLOSING)) {
28425 		/*
28426 		 * The conn is already in the drain list, OR
28427 		 * the conn is closing. We need to check again for
28428 		 * the closing case again since close can happen
28429 		 * after we drop the conn_lock, and before we
28430 		 * acquire the CONN_DRAIN_LIST_LOCK.
28431 		 */
28432 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28433 		return;
28434 	} else {
28435 		idl = connp->conn_idl;
28436 	}
28437 
28438 	/*
28439 	 * The conn is not in the drain list. Insert it at the
28440 	 * tail of the drain list. The drain list is circular
28441 	 * and doubly linked. idl_conn points to the 1st element
28442 	 * in the list.
28443 	 */
28444 	if (idl->idl_conn == NULL) {
28445 		idl->idl_conn = connp;
28446 		connp->conn_drain_next = connp;
28447 		connp->conn_drain_prev = connp;
28448 	} else {
28449 		conn_t *head = idl->idl_conn;
28450 
28451 		connp->conn_drain_next = head;
28452 		connp->conn_drain_prev = head->conn_drain_prev;
28453 		head->conn_drain_prev->conn_drain_next = connp;
28454 		head->conn_drain_prev = connp;
28455 	}
28456 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28457 }
28458 
28459 /*
28460  * This conn is closing, and we are called from ip_close. OR
28461  * This conn has been serviced by ip_wsrv, and we need to do the tail
28462  * processing.
28463  * If this conn is part of the drain list, we may need to sustain the drain
28464  * process by qenabling the next conn in the drain list. We may also need to
28465  * remove this conn from the list, if it is done.
28466  */
28467 static void
28468 conn_drain_tail(conn_t *connp, boolean_t closing)
28469 {
28470 	idl_t *idl;
28471 
28472 	/*
28473 	 * connp->conn_idl is stable at this point, and no lock is needed
28474 	 * to check it. If we are called from ip_close, close has already
28475 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28476 	 * called us only because conn_idl is non-null. If we are called thru
28477 	 * service, conn_idl could be null, but it cannot change because
28478 	 * service is single-threaded per queue, and there cannot be another
28479 	 * instance of service trying to call conn_drain_insert on this conn
28480 	 * now.
28481 	 */
28482 	ASSERT(!closing || (connp->conn_idl != NULL));
28483 
28484 	/*
28485 	 * If connp->conn_idl is null, the conn has not been inserted into any
28486 	 * drain list even once since creation of the conn. Just return.
28487 	 */
28488 	if (connp->conn_idl == NULL)
28489 		return;
28490 
28491 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28492 
28493 	if (connp->conn_drain_prev == NULL) {
28494 		/* This conn is currently not in the drain list.  */
28495 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28496 		return;
28497 	}
28498 	idl = connp->conn_idl;
28499 	if (idl->idl_conn_draining == connp) {
28500 		/*
28501 		 * This conn is the current drainer. If this is the last conn
28502 		 * in the drain list, we need to do more checks, in the 'if'
28503 		 * below. Otherwwise we need to just qenable the next conn,
28504 		 * to sustain the draining, and is handled in the 'else'
28505 		 * below.
28506 		 */
28507 		if (connp->conn_drain_next == idl->idl_conn) {
28508 			/*
28509 			 * This conn is the last in this list. This round
28510 			 * of draining is complete. If idl_repeat is set,
28511 			 * it means another flow enabling has happened from
28512 			 * the driver/streams and we need to another round
28513 			 * of draining.
28514 			 * If there are more than 2 conns in the drain list,
28515 			 * do a left rotate by 1, so that all conns except the
28516 			 * conn at the head move towards the head by 1, and the
28517 			 * the conn at the head goes to the tail. This attempts
28518 			 * a more even share for all queues that are being
28519 			 * drained.
28520 			 */
28521 			if ((connp->conn_drain_next != connp) &&
28522 			    (idl->idl_conn->conn_drain_next != connp)) {
28523 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28524 			}
28525 			if (idl->idl_repeat) {
28526 				qenable(idl->idl_conn->conn_wq);
28527 				idl->idl_conn_draining = idl->idl_conn;
28528 				idl->idl_repeat = 0;
28529 			} else {
28530 				idl->idl_conn_draining = NULL;
28531 			}
28532 		} else {
28533 			/*
28534 			 * If the next queue that we are now qenable'ing,
28535 			 * is closing, it will remove itself from this list
28536 			 * and qenable the subsequent queue in ip_close().
28537 			 * Serialization is acheived thru idl_lock.
28538 			 */
28539 			qenable(connp->conn_drain_next->conn_wq);
28540 			idl->idl_conn_draining = connp->conn_drain_next;
28541 		}
28542 	}
28543 	if (!connp->conn_did_putbq || closing) {
28544 		/*
28545 		 * Remove ourself from the drain list, if we did not do
28546 		 * a putbq, or if the conn is closing.
28547 		 * Note: It is possible that q->q_first is non-null. It means
28548 		 * that these messages landed after we did a enableok() in
28549 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28550 		 * service them.
28551 		 */
28552 		if (connp->conn_drain_next == connp) {
28553 			/* Singleton in the list */
28554 			ASSERT(connp->conn_drain_prev == connp);
28555 			idl->idl_conn = NULL;
28556 			idl->idl_conn_draining = NULL;
28557 		} else {
28558 			connp->conn_drain_prev->conn_drain_next =
28559 			    connp->conn_drain_next;
28560 			connp->conn_drain_next->conn_drain_prev =
28561 			    connp->conn_drain_prev;
28562 			if (idl->idl_conn == connp)
28563 				idl->idl_conn = connp->conn_drain_next;
28564 			ASSERT(idl->idl_conn_draining != connp);
28565 
28566 		}
28567 		connp->conn_drain_next = NULL;
28568 		connp->conn_drain_prev = NULL;
28569 	}
28570 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28571 }
28572 
28573 /*
28574  * Write service routine. Shared perimeter entry point.
28575  * ip_wsrv can be called in any of the following ways.
28576  * 1. The device queue's messages has fallen below the low water mark
28577  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28578  *    the drain lists and backenable the first conn in each list.
28579  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28580  *    qenabled non-tcp upper layers. We start dequeing messages and call
28581  *    ip_wput for each message.
28582  */
28583 
28584 void
28585 ip_wsrv(queue_t *q)
28586 {
28587 	conn_t	*connp;
28588 	ill_t	*ill;
28589 	mblk_t	*mp;
28590 
28591 	if (q->q_next) {
28592 		ill = (ill_t *)q->q_ptr;
28593 		if (ill->ill_state_flags == 0) {
28594 			/*
28595 			 * The device flow control has opened up.
28596 			 * Walk through conn drain lists and qenable the
28597 			 * first conn in each list. This makes sense only
28598 			 * if the stream is fully plumbed and setup.
28599 			 * Hence the if check above.
28600 			 */
28601 			ip1dbg(("ip_wsrv: walking\n"));
28602 			conn_walk_drain(ill->ill_ipst);
28603 		}
28604 		return;
28605 	}
28606 
28607 	connp = Q_TO_CONN(q);
28608 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28609 
28610 	/*
28611 	 * 1. Set conn_draining flag to signal that service is active.
28612 	 *
28613 	 * 2. ip_output determines whether it has been called from service,
28614 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28615 	 *    has been called from service.
28616 	 *
28617 	 * 3. Message ordering is preserved by the following logic.
28618 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28619 	 *    the message at the tail, if conn_draining is set (i.e. service
28620 	 *    is running) or if q->q_first is non-null.
28621 	 *
28622 	 *    ii. If ip_output is called from service, and if ip_output cannot
28623 	 *    putnext due to flow control, it does a putbq.
28624 	 *
28625 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28626 	 *    (causing an infinite loop).
28627 	 */
28628 	ASSERT(!connp->conn_did_putbq);
28629 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28630 		connp->conn_draining = 1;
28631 		noenable(q);
28632 		while ((mp = getq(q)) != NULL) {
28633 			ASSERT(CONN_Q(q));
28634 
28635 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28636 			if (connp->conn_did_putbq) {
28637 				/* ip_wput did a putbq */
28638 				break;
28639 			}
28640 		}
28641 		/*
28642 		 * At this point, a thread coming down from top, calling
28643 		 * ip_wput, may end up queueing the message. We have not yet
28644 		 * enabled the queue, so ip_wsrv won't be called again.
28645 		 * To avoid this race, check q->q_first again (in the loop)
28646 		 * If the other thread queued the message before we call
28647 		 * enableok(), we will catch it in the q->q_first check.
28648 		 * If the other thread queues the message after we call
28649 		 * enableok(), ip_wsrv will be called again by STREAMS.
28650 		 */
28651 		connp->conn_draining = 0;
28652 		enableok(q);
28653 	}
28654 
28655 	/* Enable the next conn for draining */
28656 	conn_drain_tail(connp, B_FALSE);
28657 
28658 	connp->conn_did_putbq = 0;
28659 }
28660 
28661 /*
28662  * Walk the list of all conn's calling the function provided with the
28663  * specified argument for each.	 Note that this only walks conn's that
28664  * have been bound.
28665  * Applies to both IPv4 and IPv6.
28666  */
28667 static void
28668 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28669 {
28670 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28671 	    ipst->ips_ipcl_udp_fanout_size,
28672 	    func, arg, zoneid);
28673 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28674 	    ipst->ips_ipcl_conn_fanout_size,
28675 	    func, arg, zoneid);
28676 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28677 	    ipst->ips_ipcl_bind_fanout_size,
28678 	    func, arg, zoneid);
28679 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28680 	    IPPROTO_MAX, func, arg, zoneid);
28681 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28682 	    IPPROTO_MAX, func, arg, zoneid);
28683 }
28684 
28685 /*
28686  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28687  * of conns that need to be drained, check if drain is already in progress.
28688  * If so set the idl_repeat bit, indicating that the last conn in the list
28689  * needs to reinitiate the drain once again, for the list. If drain is not
28690  * in progress for the list, initiate the draining, by qenabling the 1st
28691  * conn in the list. The drain is self-sustaining, each qenabled conn will
28692  * in turn qenable the next conn, when it is done/blocked/closing.
28693  */
28694 static void
28695 conn_walk_drain(ip_stack_t *ipst)
28696 {
28697 	int i;
28698 	idl_t *idl;
28699 
28700 	IP_STAT(ipst, ip_conn_walk_drain);
28701 
28702 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28703 		idl = &ipst->ips_conn_drain_list[i];
28704 		mutex_enter(&idl->idl_lock);
28705 		if (idl->idl_conn == NULL) {
28706 			mutex_exit(&idl->idl_lock);
28707 			continue;
28708 		}
28709 		/*
28710 		 * If this list is not being drained currently by
28711 		 * an ip_wsrv thread, start the process.
28712 		 */
28713 		if (idl->idl_conn_draining == NULL) {
28714 			ASSERT(idl->idl_repeat == 0);
28715 			qenable(idl->idl_conn->conn_wq);
28716 			idl->idl_conn_draining = idl->idl_conn;
28717 		} else {
28718 			idl->idl_repeat = 1;
28719 		}
28720 		mutex_exit(&idl->idl_lock);
28721 	}
28722 }
28723 
28724 /*
28725  * Walk an conn hash table of `count' buckets, calling func for each entry.
28726  */
28727 static void
28728 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28729     zoneid_t zoneid)
28730 {
28731 	conn_t	*connp;
28732 
28733 	while (count-- > 0) {
28734 		mutex_enter(&connfp->connf_lock);
28735 		for (connp = connfp->connf_head; connp != NULL;
28736 		    connp = connp->conn_next) {
28737 			if (zoneid == GLOBAL_ZONEID ||
28738 			    zoneid == connp->conn_zoneid) {
28739 				CONN_INC_REF(connp);
28740 				mutex_exit(&connfp->connf_lock);
28741 				(*func)(connp, arg);
28742 				mutex_enter(&connfp->connf_lock);
28743 				CONN_DEC_REF(connp);
28744 			}
28745 		}
28746 		mutex_exit(&connfp->connf_lock);
28747 		connfp++;
28748 	}
28749 }
28750 
28751 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28752 static void
28753 conn_report1(conn_t *connp, void *mp)
28754 {
28755 	char	buf1[INET6_ADDRSTRLEN];
28756 	char	buf2[INET6_ADDRSTRLEN];
28757 	uint_t	print_len, buf_len;
28758 
28759 	ASSERT(connp != NULL);
28760 
28761 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28762 	if (buf_len <= 0)
28763 		return;
28764 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1)),
28765 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2)),
28766 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28767 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28768 	    "%5d %s/%05d %s/%05d\n",
28769 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28770 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28771 	    buf1, connp->conn_lport,
28772 	    buf2, connp->conn_fport);
28773 	if (print_len < buf_len) {
28774 		((mblk_t *)mp)->b_wptr += print_len;
28775 	} else {
28776 		((mblk_t *)mp)->b_wptr += buf_len;
28777 	}
28778 }
28779 
28780 /*
28781  * Named Dispatch routine to produce a formatted report on all conns
28782  * that are listed in one of the fanout tables.
28783  * This report is accessed by using the ndd utility to "get" ND variable
28784  * "ip_conn_status".
28785  */
28786 /* ARGSUSED */
28787 static int
28788 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28789 {
28790 	conn_t *connp = Q_TO_CONN(q);
28791 
28792 	(void) mi_mpprintf(mp,
28793 	    "CONN      " MI_COL_HDRPAD_STR
28794 	    "rfq      " MI_COL_HDRPAD_STR
28795 	    "stq      " MI_COL_HDRPAD_STR
28796 	    " zone local                 remote");
28797 
28798 	/*
28799 	 * Because of the ndd constraint, at most we can have 64K buffer
28800 	 * to put in all conn info.  So to be more efficient, just
28801 	 * allocate a 64K buffer here, assuming we need that large buffer.
28802 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28803 	 */
28804 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28805 		/* The following may work even if we cannot get a large buf. */
28806 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28807 		return (0);
28808 	}
28809 
28810 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28811 	    connp->conn_netstack->netstack_ip);
28812 	return (0);
28813 }
28814 
28815 /*
28816  * Determine if the ill and multicast aspects of that packets
28817  * "matches" the conn.
28818  */
28819 boolean_t
28820 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28821     zoneid_t zoneid)
28822 {
28823 	ill_t *in_ill;
28824 	boolean_t found;
28825 	ipif_t *ipif;
28826 	ire_t *ire;
28827 	ipaddr_t dst, src;
28828 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28829 
28830 	dst = ipha->ipha_dst;
28831 	src = ipha->ipha_src;
28832 
28833 	/*
28834 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28835 	 * unicast, broadcast and multicast reception to
28836 	 * conn_incoming_ill. conn_wantpacket itself is called
28837 	 * only for BROADCAST and multicast.
28838 	 *
28839 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28840 	 *    is part of a group. Hence, we should be receiving
28841 	 *    just one copy of broadcast for the whole group.
28842 	 *    Thus, if it is part of the group the packet could
28843 	 *    come on any ill of the group and hence we need a
28844 	 *    match on the group. Otherwise, match on ill should
28845 	 *    be sufficient.
28846 	 *
28847 	 * 2) ip_rput does not suppress duplicate multicast packets.
28848 	 *    If there are two interfaces in a ill group and we have
28849 	 *    2 applications (conns) joined a multicast group G on
28850 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28851 	 *    will give us two packets because we join G on both the
28852 	 *    interfaces rather than nominating just one interface
28853 	 *    for receiving multicast like broadcast above. So,
28854 	 *    we have to call ilg_lookup_ill to filter out duplicate
28855 	 *    copies, if ill is part of a group.
28856 	 */
28857 	in_ill = connp->conn_incoming_ill;
28858 	if (in_ill != NULL) {
28859 		if (in_ill->ill_group == NULL) {
28860 			if (in_ill != ill)
28861 				return (B_FALSE);
28862 		} else if (in_ill->ill_group != ill->ill_group) {
28863 			return (B_FALSE);
28864 		}
28865 	}
28866 
28867 	if (!CLASSD(dst)) {
28868 		if (IPCL_ZONE_MATCH(connp, zoneid))
28869 			return (B_TRUE);
28870 		/*
28871 		 * The conn is in a different zone; we need to check that this
28872 		 * broadcast address is configured in the application's zone and
28873 		 * on one ill in the group.
28874 		 */
28875 		ipif = ipif_get_next_ipif(NULL, ill);
28876 		if (ipif == NULL)
28877 			return (B_FALSE);
28878 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28879 		    connp->conn_zoneid, NULL,
28880 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28881 		ipif_refrele(ipif);
28882 		if (ire != NULL) {
28883 			ire_refrele(ire);
28884 			return (B_TRUE);
28885 		} else {
28886 			return (B_FALSE);
28887 		}
28888 	}
28889 
28890 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28891 	    connp->conn_zoneid == zoneid) {
28892 		/*
28893 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28894 		 * disabled, therefore we don't dispatch the multicast packet to
28895 		 * the sending zone.
28896 		 */
28897 		return (B_FALSE);
28898 	}
28899 
28900 	if ((ill->ill_phyint->phyint_flags & PHYI_LOOPBACK) &&
28901 	    connp->conn_zoneid != zoneid) {
28902 		/*
28903 		 * Multicast packet on the loopback interface: we only match
28904 		 * conns who joined the group in the specified zone.
28905 		 */
28906 		return (B_FALSE);
28907 	}
28908 
28909 	if (connp->conn_multi_router) {
28910 		/* multicast packet and multicast router socket: send up */
28911 		return (B_TRUE);
28912 	}
28913 
28914 	mutex_enter(&connp->conn_lock);
28915 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28916 	mutex_exit(&connp->conn_lock);
28917 	return (found);
28918 }
28919 
28920 /*
28921  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28922  */
28923 /* ARGSUSED */
28924 static void
28925 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28926 {
28927 	ill_t *ill = (ill_t *)q->q_ptr;
28928 	mblk_t	*mp1, *mp2;
28929 	ipif_t  *ipif;
28930 	int err = 0;
28931 	conn_t *connp = NULL;
28932 	ipsq_t	*ipsq;
28933 	arc_t	*arc;
28934 
28935 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28936 
28937 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28938 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28939 
28940 	ASSERT(IAM_WRITER_ILL(ill));
28941 	mp2 = mp->b_cont;
28942 	mp->b_cont = NULL;
28943 
28944 	/*
28945 	 * We have now received the arp bringup completion message
28946 	 * from ARP. Mark the arp bringup as done. Also if the arp
28947 	 * stream has already started closing, send up the AR_ARP_CLOSING
28948 	 * ack now since ARP is waiting in close for this ack.
28949 	 */
28950 	mutex_enter(&ill->ill_lock);
28951 	ill->ill_arp_bringup_pending = 0;
28952 	if (ill->ill_arp_closing) {
28953 		mutex_exit(&ill->ill_lock);
28954 		/* Let's reuse the mp for sending the ack */
28955 		arc = (arc_t *)mp->b_rptr;
28956 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28957 		arc->arc_cmd = AR_ARP_CLOSING;
28958 		qreply(q, mp);
28959 	} else {
28960 		mutex_exit(&ill->ill_lock);
28961 		freeb(mp);
28962 	}
28963 
28964 	ipsq = ill->ill_phyint->phyint_ipsq;
28965 	ipif = ipsq->ipsq_pending_ipif;
28966 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28967 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28968 	if (mp1 == NULL) {
28969 		/* bringup was aborted by the user */
28970 		freemsg(mp2);
28971 		return;
28972 	}
28973 
28974 	/*
28975 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28976 	 * must have an associated conn_t.  Otherwise, we're bringing this
28977 	 * interface back up as part of handling an asynchronous event (e.g.,
28978 	 * physical address change).
28979 	 */
28980 	if (ipsq->ipsq_current_ioctl != 0) {
28981 		ASSERT(connp != NULL);
28982 		q = CONNP_TO_WQ(connp);
28983 	} else {
28984 		ASSERT(connp == NULL);
28985 		q = ill->ill_rq;
28986 	}
28987 
28988 	/*
28989 	 * If the DL_BIND_REQ fails, it is noted
28990 	 * in arc_name_offset.
28991 	 */
28992 	err = *((int *)mp2->b_rptr);
28993 	if (err == 0) {
28994 		if (ipif->ipif_isv6) {
28995 			if ((err = ipif_up_done_v6(ipif)) != 0)
28996 				ip0dbg(("ip_arp_done: init failed\n"));
28997 		} else {
28998 			if ((err = ipif_up_done(ipif)) != 0)
28999 				ip0dbg(("ip_arp_done: init failed\n"));
29000 		}
29001 	} else {
29002 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
29003 	}
29004 
29005 	freemsg(mp2);
29006 
29007 	if ((err == 0) && (ill->ill_up_ipifs)) {
29008 		err = ill_up_ipifs(ill, q, mp1);
29009 		if (err == EINPROGRESS)
29010 			return;
29011 	}
29012 
29013 	if (ill->ill_up_ipifs)
29014 		ill_group_cleanup(ill);
29015 
29016 	/*
29017 	 * The operation must complete without EINPROGRESS since
29018 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29019 	 * Otherwise, the operation will be stuck forever in the ipsq.
29020 	 */
29021 	ASSERT(err != EINPROGRESS);
29022 	if (ipsq->ipsq_current_ioctl != 0)
29023 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29024 	else
29025 		ipsq_current_finish(ipsq);
29026 }
29027 
29028 /* Allocate the private structure */
29029 static int
29030 ip_priv_alloc(void **bufp)
29031 {
29032 	void	*buf;
29033 
29034 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29035 		return (ENOMEM);
29036 
29037 	*bufp = buf;
29038 	return (0);
29039 }
29040 
29041 /* Function to delete the private structure */
29042 void
29043 ip_priv_free(void *buf)
29044 {
29045 	ASSERT(buf != NULL);
29046 	kmem_free(buf, sizeof (ip_priv_t));
29047 }
29048 
29049 /*
29050  * The entry point for IPPF processing.
29051  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29052  * routine just returns.
29053  *
29054  * When called, ip_process generates an ipp_packet_t structure
29055  * which holds the state information for this packet and invokes the
29056  * the classifier (via ipp_packet_process). The classification, depending on
29057  * configured filters, results in a list of actions for this packet. Invoking
29058  * an action may cause the packet to be dropped, in which case the resulting
29059  * mblk (*mpp) is NULL. proc indicates the callout position for
29060  * this packet and ill_index is the interface this packet on or will leave
29061  * on (inbound and outbound resp.).
29062  */
29063 void
29064 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29065 {
29066 	mblk_t		*mp;
29067 	ip_priv_t	*priv;
29068 	ipp_action_id_t	aid;
29069 	int		rc = 0;
29070 	ipp_packet_t	*pp;
29071 #define	IP_CLASS	"ip"
29072 
29073 	/* If the classifier is not loaded, return  */
29074 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29075 		return;
29076 	}
29077 
29078 	mp = *mpp;
29079 	ASSERT(mp != NULL);
29080 
29081 	/* Allocate the packet structure */
29082 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29083 	if (rc != 0) {
29084 		*mpp = NULL;
29085 		freemsg(mp);
29086 		return;
29087 	}
29088 
29089 	/* Allocate the private structure */
29090 	rc = ip_priv_alloc((void **)&priv);
29091 	if (rc != 0) {
29092 		*mpp = NULL;
29093 		freemsg(mp);
29094 		ipp_packet_free(pp);
29095 		return;
29096 	}
29097 	priv->proc = proc;
29098 	priv->ill_index = ill_index;
29099 	ipp_packet_set_private(pp, priv, ip_priv_free);
29100 	ipp_packet_set_data(pp, mp);
29101 
29102 	/* Invoke the classifier */
29103 	rc = ipp_packet_process(&pp);
29104 	if (pp != NULL) {
29105 		mp = ipp_packet_get_data(pp);
29106 		ipp_packet_free(pp);
29107 		if (rc != 0) {
29108 			freemsg(mp);
29109 			*mpp = NULL;
29110 		}
29111 	} else {
29112 		*mpp = NULL;
29113 	}
29114 #undef	IP_CLASS
29115 }
29116 
29117 /*
29118  * Propagate a multicast group membership operation (add/drop) on
29119  * all the interfaces crossed by the related multirt routes.
29120  * The call is considered successful if the operation succeeds
29121  * on at least one interface.
29122  */
29123 static int
29124 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29125     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29126     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29127     mblk_t *first_mp)
29128 {
29129 	ire_t		*ire_gw;
29130 	irb_t		*irb;
29131 	int		error = 0;
29132 	opt_restart_t	*or;
29133 	ip_stack_t	*ipst = ire->ire_ipst;
29134 
29135 	irb = ire->ire_bucket;
29136 	ASSERT(irb != NULL);
29137 
29138 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29139 
29140 	or = (opt_restart_t *)first_mp->b_rptr;
29141 	IRB_REFHOLD(irb);
29142 	for (; ire != NULL; ire = ire->ire_next) {
29143 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29144 			continue;
29145 		if (ire->ire_addr != group)
29146 			continue;
29147 
29148 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29149 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29150 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29151 		/* No resolver exists for the gateway; skip this ire. */
29152 		if (ire_gw == NULL)
29153 			continue;
29154 
29155 		/*
29156 		 * This function can return EINPROGRESS. If so the operation
29157 		 * will be restarted from ip_restart_optmgmt which will
29158 		 * call ip_opt_set and option processing will restart for
29159 		 * this option. So we may end up calling 'fn' more than once.
29160 		 * This requires that 'fn' is idempotent except for the
29161 		 * return value. The operation is considered a success if
29162 		 * it succeeds at least once on any one interface.
29163 		 */
29164 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29165 		    NULL, fmode, src, first_mp);
29166 		if (error == 0)
29167 			or->or_private = CGTP_MCAST_SUCCESS;
29168 
29169 		if (ip_debug > 0) {
29170 			ulong_t	off;
29171 			char	*ksym;
29172 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29173 			ip2dbg(("ip_multirt_apply_membership: "
29174 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29175 			    "error %d [success %u]\n",
29176 			    ksym ? ksym : "?",
29177 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29178 			    error, or->or_private));
29179 		}
29180 
29181 		ire_refrele(ire_gw);
29182 		if (error == EINPROGRESS) {
29183 			IRB_REFRELE(irb);
29184 			return (error);
29185 		}
29186 	}
29187 	IRB_REFRELE(irb);
29188 	/*
29189 	 * Consider the call as successful if we succeeded on at least
29190 	 * one interface. Otherwise, return the last encountered error.
29191 	 */
29192 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29193 }
29194 
29195 
29196 /*
29197  * Issue a warning regarding a route crossing an interface with an
29198  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29199  * amount of time is logged.
29200  */
29201 static void
29202 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29203 {
29204 	hrtime_t	current = gethrtime();
29205 	char		buf[INET_ADDRSTRLEN];
29206 	ip_stack_t	*ipst = ire->ire_ipst;
29207 
29208 	/* Convert interval in ms to hrtime in ns */
29209 	if (ipst->ips_multirt_bad_mtu_last_time +
29210 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29211 	    current) {
29212 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29213 		    "to %s, incorrect MTU %u (expected %u)\n",
29214 		    ip_dot_addr(ire->ire_addr, buf),
29215 		    ire->ire_max_frag, max_frag);
29216 
29217 		ipst->ips_multirt_bad_mtu_last_time = current;
29218 	}
29219 }
29220 
29221 
29222 /*
29223  * Get the CGTP (multirouting) filtering status.
29224  * If 0, the CGTP hooks are transparent.
29225  */
29226 /* ARGSUSED */
29227 static int
29228 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29229 {
29230 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29231 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29232 
29233 	/*
29234 	 * Only applies to the shared stack since the filter_ops
29235 	 * do not carry an ip_stack_t or zoneid.
29236 	 */
29237 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29238 		return (ENOTSUP);
29239 
29240 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29241 	return (0);
29242 }
29243 
29244 
29245 /*
29246  * Set the CGTP (multirouting) filtering status.
29247  * If the status is changed from active to transparent
29248  * or from transparent to active, forward the new status
29249  * to the filtering module (if loaded).
29250  */
29251 /* ARGSUSED */
29252 static int
29253 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29254     cred_t *ioc_cr)
29255 {
29256 	long		new_value;
29257 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29258 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29259 
29260 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29261 		return (EPERM);
29262 
29263 	/*
29264 	 * Only applies to the shared stack since the filter_ops
29265 	 * do not carry an ip_stack_t or zoneid.
29266 	 */
29267 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29268 		return (ENOTSUP);
29269 
29270 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29271 	    new_value < 0 || new_value > 1) {
29272 		return (EINVAL);
29273 	}
29274 
29275 	/*
29276 	 * Do not enable CGTP filtering - thus preventing the hooks
29277 	 * from being invoked - if the version number of the
29278 	 * filtering module hooks does not match.
29279 	 */
29280 	if ((ip_cgtp_filter_ops != NULL) &&
29281 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29282 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29283 		    "(module hooks version %d, expecting %d)\n",
29284 		    ip_cgtp_filter_ops->cfo_filter_rev,
29285 		    CGTP_FILTER_REV);
29286 		return (ENOTSUP);
29287 	}
29288 
29289 	if ((!*ip_cgtp_filter_value) && new_value) {
29290 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29291 		    ip_cgtp_filter_ops == NULL ?
29292 		    " (module not loaded)" : "");
29293 	}
29294 	if (*ip_cgtp_filter_value && (!new_value)) {
29295 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29296 		    ip_cgtp_filter_ops == NULL ?
29297 		    " (module not loaded)" : "");
29298 	}
29299 
29300 	if (ip_cgtp_filter_ops != NULL) {
29301 		int	res;
29302 
29303 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29304 		if (res)
29305 			return (res);
29306 	}
29307 
29308 	*ip_cgtp_filter_value = (boolean_t)new_value;
29309 
29310 	return (0);
29311 }
29312 
29313 
29314 /*
29315  * Return the expected CGTP hooks version number.
29316  */
29317 int
29318 ip_cgtp_filter_supported(void)
29319 {
29320 	ip_stack_t *ipst;
29321 	int ret;
29322 
29323 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29324 	if (ipst == NULL)
29325 		return (-1);
29326 	ret = ip_cgtp_filter_rev;
29327 	netstack_rele(ipst->ips_netstack);
29328 	return (ret);
29329 }
29330 
29331 
29332 /*
29333  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29334  * or by invoking this function. In the first case, the version number
29335  * of the registered structure is checked at hooks activation time
29336  * in ip_cgtp_filter_set().
29337  *
29338  * Only applies to the shared stack since the filter_ops
29339  * do not carry an ip_stack_t or zoneid.
29340  */
29341 int
29342 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29343 {
29344 	ip_stack_t *ipst;
29345 
29346 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29347 		return (ENOTSUP);
29348 
29349 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29350 	if (ipst == NULL)
29351 		return (EINVAL);
29352 
29353 	ip_cgtp_filter_ops = ops;
29354 	netstack_rele(ipst->ips_netstack);
29355 	return (0);
29356 }
29357 
29358 static squeue_func_t
29359 ip_squeue_switch(int val)
29360 {
29361 	squeue_func_t rval = squeue_fill;
29362 
29363 	switch (val) {
29364 	case IP_SQUEUE_ENTER_NODRAIN:
29365 		rval = squeue_enter_nodrain;
29366 		break;
29367 	case IP_SQUEUE_ENTER:
29368 		rval = squeue_enter;
29369 		break;
29370 	default:
29371 		break;
29372 	}
29373 	return (rval);
29374 }
29375 
29376 /* ARGSUSED */
29377 static int
29378 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29379     caddr_t addr, cred_t *cr)
29380 {
29381 	int *v = (int *)addr;
29382 	long new_value;
29383 
29384 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29385 		return (EPERM);
29386 
29387 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29388 		return (EINVAL);
29389 
29390 	ip_input_proc = ip_squeue_switch(new_value);
29391 	*v = new_value;
29392 	return (0);
29393 }
29394 
29395 /* ARGSUSED */
29396 static int
29397 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29398     caddr_t addr, cred_t *cr)
29399 {
29400 	int *v = (int *)addr;
29401 	long new_value;
29402 
29403 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29404 		return (EPERM);
29405 
29406 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29407 		return (EINVAL);
29408 
29409 	*v = new_value;
29410 	return (0);
29411 }
29412 
29413 /*
29414  * Handle changes to ipmp_hook_emulation ndd variable.
29415  * Need to update phyint_hook_ifindex.
29416  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29417  */
29418 static void
29419 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29420 {
29421 	phyint_t *phyi;
29422 	phyint_t *phyi_tmp;
29423 	char *groupname;
29424 	int namelen;
29425 	ill_t	*ill;
29426 	boolean_t new_group;
29427 
29428 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29429 	/*
29430 	 * Group indicies are stored in the phyint - a common structure
29431 	 * to both IPv4 and IPv6.
29432 	 */
29433 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29434 	for (; phyi != NULL;
29435 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29436 	    phyi, AVL_AFTER)) {
29437 		/* Ignore the ones that do not have a group */
29438 		if (phyi->phyint_groupname_len == 0)
29439 			continue;
29440 
29441 		/*
29442 		 * Look for other phyint in group.
29443 		 * Clear name/namelen so the lookup doesn't find ourselves.
29444 		 */
29445 		namelen = phyi->phyint_groupname_len;
29446 		groupname = phyi->phyint_groupname;
29447 		phyi->phyint_groupname_len = 0;
29448 		phyi->phyint_groupname = NULL;
29449 
29450 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29451 		/* Restore */
29452 		phyi->phyint_groupname_len = namelen;
29453 		phyi->phyint_groupname = groupname;
29454 
29455 		new_group = B_FALSE;
29456 		if (ipst->ips_ipmp_hook_emulation) {
29457 			/*
29458 			 * If the group already exists and has already
29459 			 * been assigned a group ifindex, we use the existing
29460 			 * group_ifindex, otherwise we pick a new group_ifindex
29461 			 * here.
29462 			 */
29463 			if (phyi_tmp != NULL &&
29464 			    phyi_tmp->phyint_group_ifindex != 0) {
29465 				phyi->phyint_group_ifindex =
29466 				    phyi_tmp->phyint_group_ifindex;
29467 			} else {
29468 				/* XXX We need a recovery strategy here. */
29469 				if (!ip_assign_ifindex(
29470 				    &phyi->phyint_group_ifindex, ipst))
29471 					cmn_err(CE_PANIC,
29472 					    "ip_assign_ifindex() failed");
29473 				new_group = B_TRUE;
29474 			}
29475 		} else {
29476 			phyi->phyint_group_ifindex = 0;
29477 		}
29478 		if (ipst->ips_ipmp_hook_emulation)
29479 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29480 		else
29481 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29482 
29483 		/*
29484 		 * For IP Filter to find out the relationship between
29485 		 * names and interface indicies, we need to generate
29486 		 * a NE_PLUMB event when a new group can appear.
29487 		 * We always generate events when a new interface appears
29488 		 * (even when ipmp_hook_emulation is set) so there
29489 		 * is no need to generate NE_PLUMB events when
29490 		 * ipmp_hook_emulation is turned off.
29491 		 * And since it isn't critical for IP Filter to get
29492 		 * the NE_UNPLUMB events we skip those here.
29493 		 */
29494 		if (new_group) {
29495 			/*
29496 			 * First phyint in group - generate group PLUMB event.
29497 			 * Since we are not running inside the ipsq we do
29498 			 * the dispatch immediately.
29499 			 */
29500 			if (phyi->phyint_illv4 != NULL)
29501 				ill = phyi->phyint_illv4;
29502 			else
29503 				ill = phyi->phyint_illv6;
29504 
29505 			if (ill != NULL) {
29506 				mutex_enter(&ill->ill_lock);
29507 				ill_nic_info_plumb(ill, B_TRUE);
29508 				ill_nic_info_dispatch(ill);
29509 				mutex_exit(&ill->ill_lock);
29510 			}
29511 		}
29512 	}
29513 	rw_exit(&ipst->ips_ill_g_lock);
29514 }
29515 
29516 /* ARGSUSED */
29517 static int
29518 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29519     caddr_t addr, cred_t *cr)
29520 {
29521 	int *v = (int *)addr;
29522 	long new_value;
29523 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29524 
29525 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29526 		return (EINVAL);
29527 
29528 	if (*v != new_value) {
29529 		*v = new_value;
29530 		ipmp_hook_emulation_changed(ipst);
29531 	}
29532 	return (0);
29533 }
29534 
29535 static void *
29536 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29537 {
29538 	kstat_t *ksp;
29539 
29540 	ip_stat_t template = {
29541 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29542 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29543 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29544 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29545 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29546 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29547 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29548 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29549 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29550 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29551 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29552 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29553 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29554 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29555 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29556 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29557 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29558 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29559 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29560 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29561 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29562 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29563 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29564 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29565 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29566 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29567 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29568 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29569 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29570 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29571 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29572 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29573 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29574 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29575 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29576 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29577 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29578 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29579 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29580 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29581 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29582 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29583 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29584 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29585 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29586 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29587 	};
29588 
29589 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29590 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29591 	    KSTAT_FLAG_VIRTUAL, stackid);
29592 
29593 	if (ksp == NULL)
29594 		return (NULL);
29595 
29596 	bcopy(&template, ip_statisticsp, sizeof (template));
29597 	ksp->ks_data = (void *)ip_statisticsp;
29598 	ksp->ks_private = (void *)(uintptr_t)stackid;
29599 
29600 	kstat_install(ksp);
29601 	return (ksp);
29602 }
29603 
29604 static void
29605 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29606 {
29607 	if (ksp != NULL) {
29608 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29609 		kstat_delete_netstack(ksp, stackid);
29610 	}
29611 }
29612 
29613 static void *
29614 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29615 {
29616 	kstat_t	*ksp;
29617 
29618 	ip_named_kstat_t template = {
29619 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29620 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29621 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29622 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29623 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29624 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29625 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29626 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29627 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29628 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29629 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29630 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29631 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29632 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29633 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29634 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29635 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29636 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29637 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29638 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29639 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29640 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29641 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29642 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29643 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29644 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29645 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29646 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29647 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29648 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29649 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29650 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29651 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29652 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29653 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29654 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29655 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29656 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29657 	};
29658 
29659 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29660 					NUM_OF_FIELDS(ip_named_kstat_t),
29661 					0, stackid);
29662 	if (ksp == NULL || ksp->ks_data == NULL)
29663 		return (NULL);
29664 
29665 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29666 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29667 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29668 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29669 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29670 
29671 	template.netToMediaEntrySize.value.i32 =
29672 		sizeof (mib2_ipNetToMediaEntry_t);
29673 
29674 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29675 
29676 	bcopy(&template, ksp->ks_data, sizeof (template));
29677 	ksp->ks_update = ip_kstat_update;
29678 	ksp->ks_private = (void *)(uintptr_t)stackid;
29679 
29680 	kstat_install(ksp);
29681 	return (ksp);
29682 }
29683 
29684 static void
29685 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29686 {
29687 	if (ksp != NULL) {
29688 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29689 		kstat_delete_netstack(ksp, stackid);
29690 	}
29691 }
29692 
29693 static int
29694 ip_kstat_update(kstat_t *kp, int rw)
29695 {
29696 	ip_named_kstat_t *ipkp;
29697 	mib2_ipIfStatsEntry_t ipmib;
29698 	ill_walk_context_t ctx;
29699 	ill_t *ill;
29700 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29701 	netstack_t	*ns;
29702 	ip_stack_t	*ipst;
29703 
29704 	if (kp == NULL || kp->ks_data == NULL)
29705 		return (EIO);
29706 
29707 	if (rw == KSTAT_WRITE)
29708 		return (EACCES);
29709 
29710 	ns = netstack_find_by_stackid(stackid);
29711 	if (ns == NULL)
29712 		return (-1);
29713 	ipst = ns->netstack_ip;
29714 	if (ipst == NULL) {
29715 		netstack_rele(ns);
29716 		return (-1);
29717 	}
29718 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29719 
29720 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29721 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29722 	ill = ILL_START_WALK_V4(&ctx, ipst);
29723 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29724 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29725 	rw_exit(&ipst->ips_ill_g_lock);
29726 
29727 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29728 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29729 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29730 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29731 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29732 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29733 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29734 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29735 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29736 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29737 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29738 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29739 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29740 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29741 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29742 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29743 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29744 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29745 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29746 
29747 	ipkp->routingDiscards.value.ui32 =	0;
29748 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29749 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29750 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29751 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29752 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29753 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29754 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29755 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29756 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29757 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29758 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29759 
29760 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29761 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29762 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29763 
29764 	netstack_rele(ns);
29765 
29766 	return (0);
29767 }
29768 
29769 static void *
29770 icmp_kstat_init(netstackid_t stackid)
29771 {
29772 	kstat_t	*ksp;
29773 
29774 	icmp_named_kstat_t template = {
29775 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29776 		{ "inErrors",		KSTAT_DATA_UINT32 },
29777 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29778 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29779 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29780 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29781 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29782 		{ "inEchos",		KSTAT_DATA_UINT32 },
29783 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29784 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29785 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29786 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29787 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29788 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29789 		{ "outErrors",		KSTAT_DATA_UINT32 },
29790 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29791 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29792 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29793 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29794 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29795 		{ "outEchos",		KSTAT_DATA_UINT32 },
29796 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29797 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29798 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29799 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29800 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29801 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29802 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29803 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29804 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29805 		{ "outDrops",		KSTAT_DATA_UINT32 },
29806 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29807 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29808 	};
29809 
29810 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29811 					NUM_OF_FIELDS(icmp_named_kstat_t),
29812 					0, stackid);
29813 	if (ksp == NULL || ksp->ks_data == NULL)
29814 		return (NULL);
29815 
29816 	bcopy(&template, ksp->ks_data, sizeof (template));
29817 
29818 	ksp->ks_update = icmp_kstat_update;
29819 	ksp->ks_private = (void *)(uintptr_t)stackid;
29820 
29821 	kstat_install(ksp);
29822 	return (ksp);
29823 }
29824 
29825 static void
29826 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29827 {
29828 	if (ksp != NULL) {
29829 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29830 		kstat_delete_netstack(ksp, stackid);
29831 	}
29832 }
29833 
29834 static int
29835 icmp_kstat_update(kstat_t *kp, int rw)
29836 {
29837 	icmp_named_kstat_t *icmpkp;
29838 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29839 	netstack_t	*ns;
29840 	ip_stack_t	*ipst;
29841 
29842 	if ((kp == NULL) || (kp->ks_data == NULL))
29843 		return (EIO);
29844 
29845 	if (rw == KSTAT_WRITE)
29846 		return (EACCES);
29847 
29848 	ns = netstack_find_by_stackid(stackid);
29849 	if (ns == NULL)
29850 		return (-1);
29851 	ipst = ns->netstack_ip;
29852 	if (ipst == NULL) {
29853 		netstack_rele(ns);
29854 		return (-1);
29855 	}
29856 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29857 
29858 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29859 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29860 	icmpkp->inDestUnreachs.value.ui32 =
29861 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29862 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29863 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29864 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29865 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29866 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29867 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29868 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29869 	icmpkp->inTimestampReps.value.ui32 =
29870 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29871 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29872 	icmpkp->inAddrMaskReps.value.ui32 =
29873 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29874 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29875 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29876 	icmpkp->outDestUnreachs.value.ui32 =
29877 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29878 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29879 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29880 	icmpkp->outSrcQuenchs.value.ui32 =
29881 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29882 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29883 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29884 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29885 	icmpkp->outTimestamps.value.ui32 =
29886 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29887 	icmpkp->outTimestampReps.value.ui32 =
29888 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29889 	icmpkp->outAddrMasks.value.ui32 =
29890 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29891 	icmpkp->outAddrMaskReps.value.ui32 =
29892 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29893 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29894 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29895 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29896 	icmpkp->outFragNeeded.value.ui32 =
29897 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29898 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29899 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29900 	icmpkp->inBadRedirects.value.ui32 =
29901 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29902 
29903 	netstack_rele(ns);
29904 	return (0);
29905 }
29906 
29907 /*
29908  * This is the fanout function for raw socket opened for SCTP.  Note
29909  * that it is called after SCTP checks that there is no socket which
29910  * wants a packet.  Then before SCTP handles this out of the blue packet,
29911  * this function is called to see if there is any raw socket for SCTP.
29912  * If there is and it is bound to the correct address, the packet will
29913  * be sent to that socket.  Note that only one raw socket can be bound to
29914  * a port.  This is assured in ipcl_sctp_hash_insert();
29915  */
29916 void
29917 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29918     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29919     zoneid_t zoneid)
29920 {
29921 	conn_t		*connp;
29922 	queue_t		*rq;
29923 	mblk_t		*first_mp;
29924 	boolean_t	secure;
29925 	ip6_t		*ip6h;
29926 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29927 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29928 
29929 	first_mp = mp;
29930 	if (mctl_present) {
29931 		mp = first_mp->b_cont;
29932 		secure = ipsec_in_is_secure(first_mp);
29933 		ASSERT(mp != NULL);
29934 	} else {
29935 		secure = B_FALSE;
29936 	}
29937 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29938 
29939 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29940 	if (connp == NULL) {
29941 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29942 		return;
29943 	}
29944 	rq = connp->conn_rq;
29945 	if (!canputnext(rq)) {
29946 		CONN_DEC_REF(connp);
29947 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29948 		freemsg(first_mp);
29949 		return;
29950 	}
29951 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29952 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29953 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29954 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29955 		if (first_mp == NULL) {
29956 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29957 			CONN_DEC_REF(connp);
29958 			return;
29959 		}
29960 	}
29961 	/*
29962 	 * We probably should not send M_CTL message up to
29963 	 * raw socket.
29964 	 */
29965 	if (mctl_present)
29966 		freeb(first_mp);
29967 
29968 	/* Initiate IPPF processing here if needed. */
29969 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29970 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29971 		ip_process(IPP_LOCAL_IN, &mp,
29972 		    recv_ill->ill_phyint->phyint_ifindex);
29973 		if (mp == NULL) {
29974 			CONN_DEC_REF(connp);
29975 			return;
29976 		}
29977 	}
29978 
29979 	if (connp->conn_recvif || connp->conn_recvslla ||
29980 	    ((connp->conn_ip_recvpktinfo ||
29981 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29982 	    (flags & IP_FF_IPINFO))) {
29983 		int in_flags = 0;
29984 
29985 		/*
29986 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29987 		 * IPF_RECVIF.
29988 		 */
29989 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29990 			in_flags = IPF_RECVIF;
29991 		}
29992 		if (connp->conn_recvslla) {
29993 			in_flags |= IPF_RECVSLLA;
29994 		}
29995 		if (isv4) {
29996 			mp = ip_add_info(mp, recv_ill, in_flags,
29997 			    IPCL_ZONEID(connp), ipst);
29998 		} else {
29999 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
30000 			if (mp == NULL) {
30001 				BUMP_MIB(recv_ill->ill_ip_mib,
30002 				    ipIfStatsInDiscards);
30003 				CONN_DEC_REF(connp);
30004 				return;
30005 			}
30006 		}
30007 	}
30008 
30009 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30010 	/*
30011 	 * We are sending the IPSEC_IN message also up. Refer
30012 	 * to comments above this function.
30013 	 */
30014 	putnext(rq, mp);
30015 	CONN_DEC_REF(connp);
30016 }
30017 
30018 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30019 {									\
30020 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30021 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30022 }
30023 /*
30024  * This function should be called only if all packet processing
30025  * including fragmentation is complete. Callers of this function
30026  * must set mp->b_prev to one of these values:
30027  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30028  * prior to handing over the mp as first argument to this function.
30029  *
30030  * If the ire passed by caller is incomplete, this function
30031  * queues the packet and if necessary, sends ARP request and bails.
30032  * If the ire passed is fully resolved, we simply prepend
30033  * the link-layer header to the packet, do ipsec hw acceleration
30034  * work if necessary, and send the packet out on the wire.
30035  *
30036  * NOTE: IPSEC will only call this function with fully resolved
30037  * ires if hw acceleration is involved.
30038  * TODO list :
30039  * 	a Handle M_MULTIDATA so that
30040  *	  tcp_multisend->tcp_multisend_data can
30041  *	  call ip_xmit_v4 directly
30042  *	b Handle post-ARP work for fragments so that
30043  *	  ip_wput_frag can call this function.
30044  */
30045 ipxmit_state_t
30046 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30047 {
30048 	nce_t		*arpce;
30049 	queue_t		*q;
30050 	int		ill_index;
30051 	mblk_t		*nxt_mp, *first_mp;
30052 	boolean_t	xmit_drop = B_FALSE;
30053 	ip_proc_t	proc;
30054 	ill_t		*out_ill;
30055 	int		pkt_len;
30056 
30057 	arpce = ire->ire_nce;
30058 	ASSERT(arpce != NULL);
30059 
30060 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30061 
30062 	mutex_enter(&arpce->nce_lock);
30063 	switch (arpce->nce_state) {
30064 	case ND_REACHABLE:
30065 		/* If there are other queued packets, queue this packet */
30066 		if (arpce->nce_qd_mp != NULL) {
30067 			if (mp != NULL)
30068 				nce_queue_mp_common(arpce, mp, B_FALSE);
30069 			mp = arpce->nce_qd_mp;
30070 		}
30071 		arpce->nce_qd_mp = NULL;
30072 		mutex_exit(&arpce->nce_lock);
30073 
30074 		/*
30075 		 * Flush the queue.  In the common case, where the
30076 		 * ARP is already resolved,  it will go through the
30077 		 * while loop only once.
30078 		 */
30079 		while (mp != NULL) {
30080 
30081 			nxt_mp = mp->b_next;
30082 			mp->b_next = NULL;
30083 			ASSERT(mp->b_datap->db_type != M_CTL);
30084 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30085 			/*
30086 			 * This info is needed for IPQOS to do COS marking
30087 			 * in ip_wput_attach_llhdr->ip_process.
30088 			 */
30089 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30090 			mp->b_prev = NULL;
30091 
30092 			/* set up ill index for outbound qos processing */
30093 			out_ill = ire->ire_ipif->ipif_ill;
30094 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30095 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30096 			    ill_index);
30097 			if (first_mp == NULL) {
30098 				xmit_drop = B_TRUE;
30099 				BUMP_MIB(out_ill->ill_ip_mib,
30100 				    ipIfStatsOutDiscards);
30101 				goto next_mp;
30102 			}
30103 			/* non-ipsec hw accel case */
30104 			if (io == NULL || !io->ipsec_out_accelerated) {
30105 				/* send it */
30106 				q = ire->ire_stq;
30107 				if (proc == IPP_FWD_OUT) {
30108 					UPDATE_IB_PKT_COUNT(ire);
30109 				} else {
30110 					UPDATE_OB_PKT_COUNT(ire);
30111 				}
30112 				ire->ire_last_used_time = lbolt;
30113 
30114 				if (flow_ctl_enabled || canputnext(q))  {
30115 					if (proc == IPP_FWD_OUT) {
30116 						BUMP_MIB(out_ill->ill_ip_mib,
30117 						ipIfStatsHCOutForwDatagrams);
30118 					}
30119 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30120 					    pkt_len);
30121 
30122 					putnext(q, first_mp);
30123 				} else {
30124 					BUMP_MIB(out_ill->ill_ip_mib,
30125 					    ipIfStatsOutDiscards);
30126 					xmit_drop = B_TRUE;
30127 					freemsg(first_mp);
30128 				}
30129 			} else {
30130 				/*
30131 				 * Safety Pup says: make sure this
30132 				 *  is going to the right interface!
30133 				 */
30134 				ill_t *ill1 =
30135 				    (ill_t *)ire->ire_stq->q_ptr;
30136 				int ifindex =
30137 				    ill1->ill_phyint->phyint_ifindex;
30138 				if (ifindex !=
30139 				    io->ipsec_out_capab_ill_index) {
30140 					xmit_drop = B_TRUE;
30141 					freemsg(mp);
30142 				} else {
30143 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30144 					    pkt_len);
30145 					ipsec_hw_putnext(ire->ire_stq, mp);
30146 				}
30147 			}
30148 next_mp:
30149 			mp = nxt_mp;
30150 		} /* while (mp != NULL) */
30151 		if (xmit_drop)
30152 			return (SEND_FAILED);
30153 		else
30154 			return (SEND_PASSED);
30155 
30156 	case ND_INITIAL:
30157 	case ND_INCOMPLETE:
30158 
30159 		/*
30160 		 * While we do send off packets to dests that
30161 		 * use fully-resolved CGTP routes, we do not
30162 		 * handle unresolved CGTP routes.
30163 		 */
30164 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30165 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30166 
30167 		if (mp != NULL) {
30168 			/* queue the packet */
30169 			nce_queue_mp_common(arpce, mp, B_FALSE);
30170 		}
30171 
30172 		if (arpce->nce_state == ND_INCOMPLETE) {
30173 			mutex_exit(&arpce->nce_lock);
30174 			DTRACE_PROBE3(ip__xmit__incomplete,
30175 			    (ire_t *), ire, (mblk_t *), mp,
30176 			    (ipsec_out_t *), io);
30177 			return (LOOKUP_IN_PROGRESS);
30178 		}
30179 
30180 		arpce->nce_state = ND_INCOMPLETE;
30181 		mutex_exit(&arpce->nce_lock);
30182 		/*
30183 		 * Note that ire_add() (called from ire_forward())
30184 		 * holds a ref on the ire until ARP is completed.
30185 		 */
30186 
30187 		ire_arpresolve(ire, ire_to_ill(ire));
30188 		return (LOOKUP_IN_PROGRESS);
30189 	default:
30190 		ASSERT(0);
30191 		mutex_exit(&arpce->nce_lock);
30192 		return (LLHDR_RESLV_FAILED);
30193 	}
30194 }
30195 
30196 #undef	UPDATE_IP_MIB_OB_COUNTERS
30197 
30198 /*
30199  * Return B_TRUE if the buffers differ in length or content.
30200  * This is used for comparing extension header buffers.
30201  * Note that an extension header would be declared different
30202  * even if all that changed was the next header value in that header i.e.
30203  * what really changed is the next extension header.
30204  */
30205 boolean_t
30206 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30207     uint_t blen)
30208 {
30209 	if (!b_valid)
30210 		blen = 0;
30211 
30212 	if (alen != blen)
30213 		return (B_TRUE);
30214 	if (alen == 0)
30215 		return (B_FALSE);	/* Both zero length */
30216 	return (bcmp(abuf, bbuf, alen));
30217 }
30218 
30219 /*
30220  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30221  * Return B_FALSE if memory allocation fails - don't change any state!
30222  */
30223 boolean_t
30224 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30225     const void *src, uint_t srclen)
30226 {
30227 	void *dst;
30228 
30229 	if (!src_valid)
30230 		srclen = 0;
30231 
30232 	ASSERT(*dstlenp == 0);
30233 	if (src != NULL && srclen != 0) {
30234 		dst = mi_alloc(srclen, BPRI_MED);
30235 		if (dst == NULL)
30236 			return (B_FALSE);
30237 	} else {
30238 		dst = NULL;
30239 	}
30240 	if (*dstp != NULL)
30241 		mi_free(*dstp);
30242 	*dstp = dst;
30243 	*dstlenp = dst == NULL ? 0 : srclen;
30244 	return (B_TRUE);
30245 }
30246 
30247 /*
30248  * Replace what is in *dst, *dstlen with the source.
30249  * Assumes ip_allocbuf has already been called.
30250  */
30251 void
30252 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30253     const void *src, uint_t srclen)
30254 {
30255 	if (!src_valid)
30256 		srclen = 0;
30257 
30258 	ASSERT(*dstlenp == srclen);
30259 	if (src != NULL && srclen != 0)
30260 		bcopy(src, *dstp, srclen);
30261 }
30262 
30263 /*
30264  * Free the storage pointed to by the members of an ip6_pkt_t.
30265  */
30266 void
30267 ip6_pkt_free(ip6_pkt_t *ipp)
30268 {
30269 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30270 
30271 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30272 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30273 		ipp->ipp_hopopts = NULL;
30274 		ipp->ipp_hopoptslen = 0;
30275 	}
30276 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30277 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30278 		ipp->ipp_rtdstopts = NULL;
30279 		ipp->ipp_rtdstoptslen = 0;
30280 	}
30281 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30282 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30283 		ipp->ipp_dstopts = NULL;
30284 		ipp->ipp_dstoptslen = 0;
30285 	}
30286 	if (ipp->ipp_fields & IPPF_RTHDR) {
30287 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30288 		ipp->ipp_rthdr = NULL;
30289 		ipp->ipp_rthdrlen = 0;
30290 	}
30291 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30292 	    IPPF_RTHDR);
30293 }
30294