xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 700682b83aee7f7b038d7f1d7f262ff4bff575d5)
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 		}
1757 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1758 		break;
1759 	case ICMP_ADDRESS_MASK_REPLY:
1760 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1761 		break;
1762 	default:
1763 		interested = B_TRUE;	/* Pass up to transport */
1764 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1765 		break;
1766 	}
1767 	/* See if there is an ICMP client. */
1768 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1769 		/* If there is an ICMP client and we want one too, copy it. */
1770 		mblk_t *first_mp1;
1771 
1772 		if (!interested) {
1773 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1774 			    ip_policy, recv_ill, zoneid);
1775 			return;
1776 		}
1777 		first_mp1 = ip_copymsg(first_mp);
1778 		if (first_mp1 != NULL) {
1779 			ip_fanout_proto(q, first_mp1, ill, ipha,
1780 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1781 		}
1782 	} else if (!interested) {
1783 		freemsg(first_mp);
1784 		return;
1785 	} else {
1786 		/*
1787 		 * Initiate policy processing for this packet if ip_policy
1788 		 * is true.
1789 		 */
1790 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1791 			ill_index = ill->ill_phyint->phyint_ifindex;
1792 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1793 			if (mp == NULL) {
1794 				if (mctl_present) {
1795 					freeb(first_mp);
1796 				}
1797 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1798 				return;
1799 			}
1800 		}
1801 	}
1802 	/* We want to do something with it. */
1803 	/* Check db_ref to make sure we can modify the packet. */
1804 	if (mp->b_datap->db_ref > 1) {
1805 		mblk_t	*first_mp1;
1806 
1807 		first_mp1 = ip_copymsg(first_mp);
1808 		freemsg(first_mp);
1809 		if (!first_mp1) {
1810 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1811 			return;
1812 		}
1813 		first_mp = first_mp1;
1814 		if (mctl_present) {
1815 			mp = first_mp->b_cont;
1816 			ASSERT(mp != NULL);
1817 		} else {
1818 			mp = first_mp;
1819 		}
1820 		ipha = (ipha_t *)mp->b_rptr;
1821 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1822 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1823 	}
1824 	switch (icmph->icmph_type) {
1825 	case ICMP_ADDRESS_MASK_REQUEST:
1826 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1827 		if (ipif == NULL) {
1828 			freemsg(first_mp);
1829 			return;
1830 		}
1831 		/*
1832 		 * outging interface must be IPv4
1833 		 */
1834 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1835 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1836 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1837 		ipif_refrele(ipif);
1838 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1839 		break;
1840 	case ICMP_ECHO_REQUEST:
1841 		icmph->icmph_type = ICMP_ECHO_REPLY;
1842 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1843 		break;
1844 	case ICMP_TIME_STAMP_REQUEST: {
1845 		uint32_t *tsp;
1846 
1847 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1848 		tsp = (uint32_t *)wptr;
1849 		tsp++;		/* Skip past 'originate time' */
1850 		/* Compute # of milliseconds since midnight */
1851 		gethrestime(&now);
1852 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1853 		    now.tv_nsec / (NANOSEC / MILLISEC);
1854 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1855 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1856 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1857 		break;
1858 	}
1859 	default:
1860 		ipha = (ipha_t *)&icmph[1];
1861 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1862 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1863 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1864 				freemsg(first_mp);
1865 				return;
1866 			}
1867 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1868 			ipha = (ipha_t *)&icmph[1];
1869 		}
1870 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1871 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1872 			freemsg(first_mp);
1873 			return;
1874 		}
1875 		hdr_length = IPH_HDR_LENGTH(ipha);
1876 		if (hdr_length < sizeof (ipha_t)) {
1877 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1878 			freemsg(first_mp);
1879 			return;
1880 		}
1881 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1882 			if (!pullupmsg(mp,
1883 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1884 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1885 				freemsg(first_mp);
1886 				return;
1887 			}
1888 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1889 			ipha = (ipha_t *)&icmph[1];
1890 		}
1891 		switch (icmph->icmph_type) {
1892 		case ICMP_REDIRECT:
1893 			/*
1894 			 * As there is no upper client to deliver, we don't
1895 			 * need the first_mp any more.
1896 			 */
1897 			if (mctl_present) {
1898 				freeb(first_mp);
1899 			}
1900 			icmp_redirect(ill, mp);
1901 			return;
1902 		case ICMP_DEST_UNREACHABLE:
1903 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1904 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1905 				    zoneid, mp, iph_hdr_length, ipst)) {
1906 					freemsg(first_mp);
1907 					return;
1908 				}
1909 				/*
1910 				 * icmp_inbound_too_big() may alter mp.
1911 				 * Resynch ipha and icmph accordingly.
1912 				 */
1913 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1914 				ipha = (ipha_t *)&icmph[1];
1915 			}
1916 			/* FALLTHRU */
1917 		default :
1918 			/*
1919 			 * IPQoS notes: Since we have already done IPQoS
1920 			 * processing we don't want to do it again in
1921 			 * the fanout routines called by
1922 			 * icmp_inbound_error_fanout, hence the last
1923 			 * argument, ip_policy, is B_FALSE.
1924 			 */
1925 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1926 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1927 			    B_FALSE, recv_ill, zoneid);
1928 		}
1929 		return;
1930 	}
1931 	/* Send out an ICMP packet */
1932 	icmph->icmph_checksum = 0;
1933 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1934 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1935 		ipif_t	*ipif_chosen;
1936 		/*
1937 		 * Make it look like it was directed to us, so we don't look
1938 		 * like a fool with a broadcast or multicast source address.
1939 		 */
1940 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1941 		/*
1942 		 * Make sure that we haven't grabbed an interface that's DOWN.
1943 		 */
1944 		if (ipif != NULL) {
1945 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1946 			    ipha->ipha_src, zoneid);
1947 			if (ipif_chosen != NULL) {
1948 				ipif_refrele(ipif);
1949 				ipif = ipif_chosen;
1950 			}
1951 		}
1952 		if (ipif == NULL) {
1953 			ip0dbg(("icmp_inbound: "
1954 			    "No source for broadcast/multicast:\n"
1955 			    "\tsrc 0x%x dst 0x%x ill %p "
1956 			    "ipif_lcl_addr 0x%x\n",
1957 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1958 			    (void *)ill,
1959 			    ill->ill_ipif->ipif_lcl_addr));
1960 			freemsg(first_mp);
1961 			return;
1962 		}
1963 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1964 		ipha->ipha_dst = ipif->ipif_src_addr;
1965 		ipif_refrele(ipif);
1966 	}
1967 	/* Reset time to live. */
1968 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1969 	{
1970 		/* Swap source and destination addresses */
1971 		ipaddr_t tmp;
1972 
1973 		tmp = ipha->ipha_src;
1974 		ipha->ipha_src = ipha->ipha_dst;
1975 		ipha->ipha_dst = tmp;
1976 	}
1977 	ipha->ipha_ident = 0;
1978 	if (!IS_SIMPLE_IPH(ipha))
1979 		icmp_options_update(ipha);
1980 
1981 	/*
1982 	 * ICMP echo replies should go out on the same interface
1983 	 * the request came on as probes used by in.mpathd for detecting
1984 	 * NIC failures are ECHO packets. We turn-off load spreading
1985 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1986 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1987 	 * function. This is in turn handled by ip_wput and ip_newroute
1988 	 * to make sure that the packet goes out on the interface it came
1989 	 * in on. If we don't turnoff load spreading, the packets might get
1990 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1991 	 * to go out and in.mpathd would wrongly detect a failure or
1992 	 * mis-detect a NIC failure for link failure. As load spreading
1993 	 * can happen only if ill_group is not NULL, we do only for
1994 	 * that case and this does not affect the normal case.
1995 	 *
1996 	 * We turn off load spreading only on echo packets that came from
1997 	 * on-link hosts. If the interface route has been deleted, this will
1998 	 * not be enforced as we can't do much. For off-link hosts, as the
1999 	 * default routes in IPv4 does not typically have an ire_ipif
2000 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2001 	 * Moreover, expecting a default route through this interface may
2002 	 * not be correct. We use ipha_dst because of the swap above.
2003 	 */
2004 	onlink = B_FALSE;
2005 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2006 		/*
2007 		 * First, we need to make sure that it is not one of our
2008 		 * local addresses. If we set onlink when it is one of
2009 		 * our local addresses, we will end up creating IRE_CACHES
2010 		 * for one of our local addresses. Then, we will never
2011 		 * accept packets for them afterwards.
2012 		 */
2013 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2014 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2015 		if (src_ire == NULL) {
2016 			ipif = ipif_get_next_ipif(NULL, ill);
2017 			if (ipif == NULL) {
2018 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2019 				freemsg(mp);
2020 				return;
2021 			}
2022 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2023 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2024 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2025 			ipif_refrele(ipif);
2026 			if (src_ire != NULL) {
2027 				onlink = B_TRUE;
2028 				ire_refrele(src_ire);
2029 			}
2030 		} else {
2031 			ire_refrele(src_ire);
2032 		}
2033 	}
2034 	if (!mctl_present) {
2035 		/*
2036 		 * This packet should go out the same way as it
2037 		 * came in i.e in clear. To make sure that global
2038 		 * policy will not be applied to this in ip_wput_ire,
2039 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2040 		 */
2041 		ASSERT(first_mp == mp);
2042 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2043 		if (first_mp == NULL) {
2044 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2045 			freemsg(mp);
2046 			return;
2047 		}
2048 		ii = (ipsec_in_t *)first_mp->b_rptr;
2049 
2050 		/* This is not a secure packet */
2051 		ii->ipsec_in_secure = B_FALSE;
2052 		if (onlink) {
2053 			ii->ipsec_in_attach_if = B_TRUE;
2054 			ii->ipsec_in_ill_index =
2055 			    ill->ill_phyint->phyint_ifindex;
2056 			ii->ipsec_in_rill_index =
2057 			    recv_ill->ill_phyint->phyint_ifindex;
2058 		}
2059 		first_mp->b_cont = mp;
2060 	} else if (onlink) {
2061 		ii = (ipsec_in_t *)first_mp->b_rptr;
2062 		ii->ipsec_in_attach_if = B_TRUE;
2063 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2064 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2065 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2066 	} else {
2067 		ii = (ipsec_in_t *)first_mp->b_rptr;
2068 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2069 	}
2070 	ii->ipsec_in_zoneid = zoneid;
2071 	ASSERT(zoneid != ALL_ZONES);
2072 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2073 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2074 		return;
2075 	}
2076 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2077 	put(WR(q), first_mp);
2078 }
2079 
2080 static ipaddr_t
2081 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2082 {
2083 	conn_t *connp;
2084 	connf_t *connfp;
2085 	ipaddr_t nexthop_addr = INADDR_ANY;
2086 	int hdr_length = IPH_HDR_LENGTH(ipha);
2087 	uint16_t *up;
2088 	uint32_t ports;
2089 	ip_stack_t *ipst = ill->ill_ipst;
2090 
2091 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2092 	switch (ipha->ipha_protocol) {
2093 		case IPPROTO_TCP:
2094 		{
2095 			tcph_t *tcph;
2096 
2097 			/* do a reverse lookup */
2098 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2099 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2100 			    TCPS_LISTEN, ipst);
2101 			break;
2102 		}
2103 		case IPPROTO_UDP:
2104 		{
2105 			uint32_t dstport, srcport;
2106 
2107 			((uint16_t *)&ports)[0] = up[1];
2108 			((uint16_t *)&ports)[1] = up[0];
2109 
2110 			/* Extract ports in net byte order */
2111 			dstport = htons(ntohl(ports) & 0xFFFF);
2112 			srcport = htons(ntohl(ports) >> 16);
2113 
2114 			connfp = &ipst->ips_ipcl_udp_fanout[
2115 			    IPCL_UDP_HASH(dstport, ipst)];
2116 			mutex_enter(&connfp->connf_lock);
2117 			connp = connfp->connf_head;
2118 
2119 			/* do a reverse lookup */
2120 			while ((connp != NULL) &&
2121 			    (!IPCL_UDP_MATCH(connp, dstport,
2122 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2123 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2124 				connp = connp->conn_next;
2125 			}
2126 			if (connp != NULL)
2127 				CONN_INC_REF(connp);
2128 			mutex_exit(&connfp->connf_lock);
2129 			break;
2130 		}
2131 		case IPPROTO_SCTP:
2132 		{
2133 			in6_addr_t map_src, map_dst;
2134 
2135 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2136 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2137 			((uint16_t *)&ports)[0] = up[1];
2138 			((uint16_t *)&ports)[1] = up[0];
2139 
2140 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2141 			    zoneid, ipst->ips_netstack->netstack_sctp);
2142 			if (connp == NULL) {
2143 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2144 				    zoneid, ports, ipha, ipst);
2145 			} else {
2146 				CONN_INC_REF(connp);
2147 				SCTP_REFRELE(CONN2SCTP(connp));
2148 			}
2149 			break;
2150 		}
2151 		default:
2152 		{
2153 			ipha_t ripha;
2154 
2155 			ripha.ipha_src = ipha->ipha_dst;
2156 			ripha.ipha_dst = ipha->ipha_src;
2157 			ripha.ipha_protocol = ipha->ipha_protocol;
2158 
2159 			connfp = &ipst->ips_ipcl_proto_fanout[
2160 			    ipha->ipha_protocol];
2161 			mutex_enter(&connfp->connf_lock);
2162 			connp = connfp->connf_head;
2163 			for (connp = connfp->connf_head; connp != NULL;
2164 			    connp = connp->conn_next) {
2165 				if (IPCL_PROTO_MATCH(connp,
2166 				    ipha->ipha_protocol, &ripha, ill,
2167 				    0, zoneid)) {
2168 					CONN_INC_REF(connp);
2169 					break;
2170 				}
2171 			}
2172 			mutex_exit(&connfp->connf_lock);
2173 		}
2174 	}
2175 	if (connp != NULL) {
2176 		if (connp->conn_nexthop_set)
2177 			nexthop_addr = connp->conn_nexthop_v4;
2178 		CONN_DEC_REF(connp);
2179 	}
2180 	return (nexthop_addr);
2181 }
2182 
2183 /* Table from RFC 1191 */
2184 static int icmp_frag_size_table[] =
2185 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2186 
2187 /*
2188  * Process received ICMP Packet too big.
2189  * After updating any IRE it does the fanout to any matching transport streams.
2190  * Assumes the message has been pulled up till the IP header that caused
2191  * the error.
2192  *
2193  * Returns B_FALSE on failure and B_TRUE on success.
2194  */
2195 static boolean_t
2196 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2197     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2198     ip_stack_t *ipst)
2199 {
2200 	ire_t	*ire, *first_ire;
2201 	int	mtu;
2202 	int	hdr_length;
2203 	ipaddr_t nexthop_addr;
2204 
2205 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2206 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2207 	ASSERT(ill != NULL);
2208 
2209 	hdr_length = IPH_HDR_LENGTH(ipha);
2210 
2211 	/* Drop if the original packet contained a source route */
2212 	if (ip_source_route_included(ipha)) {
2213 		return (B_FALSE);
2214 	}
2215 	/*
2216 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2217 	 * header.
2218 	 */
2219 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2220 	    mp->b_wptr) {
2221 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2222 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2223 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2224 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2225 			return (B_FALSE);
2226 		}
2227 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2228 		ipha = (ipha_t *)&icmph[1];
2229 	}
2230 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2231 	if (nexthop_addr != INADDR_ANY) {
2232 		/* nexthop set */
2233 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2234 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2235 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2236 	} else {
2237 		/* nexthop not set */
2238 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2239 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2240 	}
2241 
2242 	if (!first_ire) {
2243 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2244 		    ntohl(ipha->ipha_dst)));
2245 		return (B_FALSE);
2246 	}
2247 	/* Check for MTU discovery advice as described in RFC 1191 */
2248 	mtu = ntohs(icmph->icmph_du_mtu);
2249 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2250 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2251 	    ire = ire->ire_next) {
2252 		/*
2253 		 * Look for the connection to which this ICMP message is
2254 		 * directed. If it has the IP_NEXTHOP option set, then the
2255 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2256 		 * option. Else the search is limited to regular IREs.
2257 		 */
2258 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2259 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2260 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != INADDR_ANY)))
2262 			continue;
2263 
2264 		mutex_enter(&ire->ire_lock);
2265 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2266 			/* Reduce the IRE max frag value as advised. */
2267 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2268 			    mtu, ire->ire_max_frag));
2269 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2270 		} else {
2271 			uint32_t length;
2272 			int	i;
2273 
2274 			/*
2275 			 * Use the table from RFC 1191 to figure out
2276 			 * the next "plateau" based on the length in
2277 			 * the original IP packet.
2278 			 */
2279 			length = ntohs(ipha->ipha_length);
2280 			if (ire->ire_max_frag <= length &&
2281 			    ire->ire_max_frag >= length - hdr_length) {
2282 				/*
2283 				 * Handle broken BSD 4.2 systems that
2284 				 * return the wrong iph_length in ICMP
2285 				 * errors.
2286 				 */
2287 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2288 				    length, ire->ire_max_frag));
2289 				length -= hdr_length;
2290 			}
2291 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2292 				if (length > icmp_frag_size_table[i])
2293 					break;
2294 			}
2295 			if (i == A_CNT(icmp_frag_size_table)) {
2296 				/* Smaller than 68! */
2297 				ip1dbg(("Too big for packet size %d\n",
2298 				    length));
2299 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2300 				ire->ire_frag_flag = 0;
2301 			} else {
2302 				mtu = icmp_frag_size_table[i];
2303 				ip1dbg(("Calculated mtu %d, packet size %d, "
2304 				    "before %d", mtu, length,
2305 				    ire->ire_max_frag));
2306 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2307 				ip1dbg((", after %d\n", ire->ire_max_frag));
2308 			}
2309 			/* Record the new max frag size for the ULP. */
2310 			icmph->icmph_du_zero = 0;
2311 			icmph->icmph_du_mtu =
2312 			    htons((uint16_t)ire->ire_max_frag);
2313 		}
2314 		mutex_exit(&ire->ire_lock);
2315 	}
2316 	rw_exit(&first_ire->ire_bucket->irb_lock);
2317 	ire_refrele(first_ire);
2318 	return (B_TRUE);
2319 }
2320 
2321 /*
2322  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2323  * calls this function.
2324  */
2325 static mblk_t *
2326 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2327 {
2328 	ipha_t *ipha;
2329 	icmph_t *icmph;
2330 	ipha_t *in_ipha;
2331 	int length;
2332 
2333 	ASSERT(mp->b_datap->db_type == M_DATA);
2334 
2335 	/*
2336 	 * For Self-encapsulated packets, we added an extra IP header
2337 	 * without the options. Inner IP header is the one from which
2338 	 * the outer IP header was formed. Thus, we need to remove the
2339 	 * outer IP header. To do this, we pullup the whole message
2340 	 * and overlay whatever follows the outer IP header over the
2341 	 * outer IP header.
2342 	 */
2343 
2344 	if (!pullupmsg(mp, -1))
2345 		return (NULL);
2346 
2347 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2348 	ipha = (ipha_t *)&icmph[1];
2349 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2350 
2351 	/*
2352 	 * The length that we want to overlay is following the inner
2353 	 * IP header. Subtracting the IP header + icmp header + outer
2354 	 * IP header's length should give us the length that we want to
2355 	 * overlay.
2356 	 */
2357 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2358 	    hdr_length;
2359 	/*
2360 	 * Overlay whatever follows the inner header over the
2361 	 * outer header.
2362 	 */
2363 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2364 
2365 	/* Set the wptr to account for the outer header */
2366 	mp->b_wptr -= hdr_length;
2367 	return (mp);
2368 }
2369 
2370 /*
2371  * Try to pass the ICMP message upstream in case the ULP cares.
2372  *
2373  * If the packet that caused the ICMP error is secure, we send
2374  * it to AH/ESP to make sure that the attached packet has a
2375  * valid association. ipha in the code below points to the
2376  * IP header of the packet that caused the error.
2377  *
2378  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2379  * in the context of IPSEC. Normally we tell the upper layer
2380  * whenever we send the ire (including ip_bind), the IPSEC header
2381  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2382  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2383  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2384  * same thing. As TCP has the IPSEC options size that needs to be
2385  * adjusted, we just pass the MTU unchanged.
2386  *
2387  * IFN could have been generated locally or by some router.
2388  *
2389  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2390  *	    This happens because IP adjusted its value of MTU on an
2391  *	    earlier IFN message and could not tell the upper layer,
2392  *	    the new adjusted value of MTU e.g. Packet was encrypted
2393  *	    or there was not enough information to fanout to upper
2394  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2395  *	    generates the IFN, where IPSEC processing has *not* been
2396  *	    done.
2397  *
2398  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2399  *	    could have generated this. This happens because ire_max_frag
2400  *	    value in IP was set to a new value, while the IPSEC processing
2401  *	    was being done and after we made the fragmentation check in
2402  *	    ip_wput_ire. Thus on return from IPSEC processing,
2403  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2404  *	    and generates the IFN. As IPSEC processing is over, we fanout
2405  *	    to AH/ESP to remove the header.
2406  *
2407  *	    In both these cases, ipsec_in_loopback will be set indicating
2408  *	    that IFN was generated locally.
2409  *
2410  * ROUTER : IFN could be secure or non-secure.
2411  *
2412  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2413  *	      packet in error has AH/ESP headers to validate the AH/ESP
2414  *	      headers. AH/ESP will verify whether there is a valid SA or
2415  *	      not and send it back. We will fanout again if we have more
2416  *	      data in the packet.
2417  *
2418  *	      If the packet in error does not have AH/ESP, we handle it
2419  *	      like any other case.
2420  *
2421  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2422  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2423  *	      for validation. AH/ESP will verify whether there is a
2424  *	      valid SA or not and send it back. We will fanout again if
2425  *	      we have more data in the packet.
2426  *
2427  *	      If the packet in error does not have AH/ESP, we handle it
2428  *	      like any other case.
2429  */
2430 static void
2431 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2432     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2433     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2434     zoneid_t zoneid)
2435 {
2436 	uint16_t *up;	/* Pointer to ports in ULP header */
2437 	uint32_t ports;	/* reversed ports for fanout */
2438 	ipha_t ripha;	/* With reversed addresses */
2439 	mblk_t *first_mp;
2440 	ipsec_in_t *ii;
2441 	tcph_t	*tcph;
2442 	conn_t	*connp;
2443 	ip_stack_t *ipst;
2444 
2445 	ASSERT(ill != NULL);
2446 
2447 	ASSERT(recv_ill != NULL);
2448 	ipst = recv_ill->ill_ipst;
2449 
2450 	first_mp = mp;
2451 	if (mctl_present) {
2452 		mp = first_mp->b_cont;
2453 		ASSERT(mp != NULL);
2454 
2455 		ii = (ipsec_in_t *)first_mp->b_rptr;
2456 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2457 	} else {
2458 		ii = NULL;
2459 	}
2460 
2461 	switch (ipha->ipha_protocol) {
2462 	case IPPROTO_UDP:
2463 		/*
2464 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2465 		 * transport header.
2466 		 */
2467 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2468 		    mp->b_wptr) {
2469 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2470 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2471 				goto discard_pkt;
2472 			}
2473 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2474 			ipha = (ipha_t *)&icmph[1];
2475 		}
2476 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2477 
2478 		/*
2479 		 * Attempt to find a client stream based on port.
2480 		 * Note that we do a reverse lookup since the header is
2481 		 * in the form we sent it out.
2482 		 * The ripha header is only used for the IP_UDP_MATCH and we
2483 		 * only set the src and dst addresses and protocol.
2484 		 */
2485 		ripha.ipha_src = ipha->ipha_dst;
2486 		ripha.ipha_dst = ipha->ipha_src;
2487 		ripha.ipha_protocol = ipha->ipha_protocol;
2488 		((uint16_t *)&ports)[0] = up[1];
2489 		((uint16_t *)&ports)[1] = up[0];
2490 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2491 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2492 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2493 		    icmph->icmph_type, icmph->icmph_code));
2494 
2495 		/* Have to change db_type after any pullupmsg */
2496 		DB_TYPE(mp) = M_CTL;
2497 
2498 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2499 		    mctl_present, ip_policy, recv_ill, zoneid);
2500 		return;
2501 
2502 	case IPPROTO_TCP:
2503 		/*
2504 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2505 		 * transport header.
2506 		 */
2507 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2508 		    mp->b_wptr) {
2509 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2510 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2511 				goto discard_pkt;
2512 			}
2513 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2514 			ipha = (ipha_t *)&icmph[1];
2515 		}
2516 		/*
2517 		 * Find a TCP client stream for this packet.
2518 		 * Note that we do a reverse lookup since the header is
2519 		 * in the form we sent it out.
2520 		 */
2521 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2522 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2523 		    ipst);
2524 		if (connp == NULL)
2525 			goto discard_pkt;
2526 
2527 		/* Have to change db_type after any pullupmsg */
2528 		DB_TYPE(mp) = M_CTL;
2529 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2530 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2531 		return;
2532 
2533 	case IPPROTO_SCTP:
2534 		/*
2535 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2536 		 * transport header.
2537 		 */
2538 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2539 		    mp->b_wptr) {
2540 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2541 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2542 				goto discard_pkt;
2543 			}
2544 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2545 			ipha = (ipha_t *)&icmph[1];
2546 		}
2547 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2548 		/*
2549 		 * Find a SCTP client stream for this packet.
2550 		 * Note that we do a reverse lookup since the header is
2551 		 * in the form we sent it out.
2552 		 * The ripha header is only used for the matching and we
2553 		 * only set the src and dst addresses, protocol, and version.
2554 		 */
2555 		ripha.ipha_src = ipha->ipha_dst;
2556 		ripha.ipha_dst = ipha->ipha_src;
2557 		ripha.ipha_protocol = ipha->ipha_protocol;
2558 		ripha.ipha_version_and_hdr_length =
2559 		    ipha->ipha_version_and_hdr_length;
2560 		((uint16_t *)&ports)[0] = up[1];
2561 		((uint16_t *)&ports)[1] = up[0];
2562 
2563 		/* Have to change db_type after any pullupmsg */
2564 		DB_TYPE(mp) = M_CTL;
2565 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2566 		    mctl_present, ip_policy, zoneid);
2567 		return;
2568 
2569 	case IPPROTO_ESP:
2570 	case IPPROTO_AH: {
2571 		int ipsec_rc;
2572 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2573 
2574 		/*
2575 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2576 		 * We will re-use the IPSEC_IN if it is already present as
2577 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2578 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2579 		 * one and attach it in the front.
2580 		 */
2581 		if (ii != NULL) {
2582 			/*
2583 			 * ip_fanout_proto_again converts the ICMP errors
2584 			 * that come back from AH/ESP to M_DATA so that
2585 			 * if it is non-AH/ESP and we do a pullupmsg in
2586 			 * this function, it would work. Convert it back
2587 			 * to M_CTL before we send up as this is a ICMP
2588 			 * error. This could have been generated locally or
2589 			 * by some router. Validate the inner IPSEC
2590 			 * headers.
2591 			 *
2592 			 * NOTE : ill_index is used by ip_fanout_proto_again
2593 			 * to locate the ill.
2594 			 */
2595 			ASSERT(ill != NULL);
2596 			ii->ipsec_in_ill_index =
2597 			    ill->ill_phyint->phyint_ifindex;
2598 			ii->ipsec_in_rill_index =
2599 			    recv_ill->ill_phyint->phyint_ifindex;
2600 			DB_TYPE(first_mp->b_cont) = M_CTL;
2601 		} else {
2602 			/*
2603 			 * IPSEC_IN is not present. We attach a ipsec_in
2604 			 * message and send up to IPSEC for validating
2605 			 * and removing the IPSEC headers. Clear
2606 			 * ipsec_in_secure so that when we return
2607 			 * from IPSEC, we don't mistakenly think that this
2608 			 * is a secure packet came from the network.
2609 			 *
2610 			 * NOTE : ill_index is used by ip_fanout_proto_again
2611 			 * to locate the ill.
2612 			 */
2613 			ASSERT(first_mp == mp);
2614 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2615 			if (first_mp == NULL) {
2616 				freemsg(mp);
2617 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2618 				return;
2619 			}
2620 			ii = (ipsec_in_t *)first_mp->b_rptr;
2621 
2622 			/* This is not a secure packet */
2623 			ii->ipsec_in_secure = B_FALSE;
2624 			first_mp->b_cont = mp;
2625 			DB_TYPE(mp) = M_CTL;
2626 			ASSERT(ill != NULL);
2627 			ii->ipsec_in_ill_index =
2628 			    ill->ill_phyint->phyint_ifindex;
2629 			ii->ipsec_in_rill_index =
2630 			    recv_ill->ill_phyint->phyint_ifindex;
2631 		}
2632 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2633 
2634 		if (!ipsec_loaded(ipss)) {
2635 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2636 			return;
2637 		}
2638 
2639 		if (ipha->ipha_protocol == IPPROTO_ESP)
2640 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2641 		else
2642 			ipsec_rc = ipsecah_icmp_error(first_mp);
2643 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2644 			return;
2645 
2646 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2647 		return;
2648 	}
2649 	default:
2650 		/*
2651 		 * The ripha header is only used for the lookup and we
2652 		 * only set the src and dst addresses and protocol.
2653 		 */
2654 		ripha.ipha_src = ipha->ipha_dst;
2655 		ripha.ipha_dst = ipha->ipha_src;
2656 		ripha.ipha_protocol = ipha->ipha_protocol;
2657 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2658 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2659 		    ntohl(ipha->ipha_dst),
2660 		    icmph->icmph_type, icmph->icmph_code));
2661 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2662 			ipha_t *in_ipha;
2663 
2664 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2665 			    mp->b_wptr) {
2666 				if (!pullupmsg(mp, (uchar_t *)ipha +
2667 				    hdr_length + sizeof (ipha_t) -
2668 				    mp->b_rptr)) {
2669 					goto discard_pkt;
2670 				}
2671 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2672 				ipha = (ipha_t *)&icmph[1];
2673 			}
2674 			/*
2675 			 * Caller has verified that length has to be
2676 			 * at least the size of IP header.
2677 			 */
2678 			ASSERT(hdr_length >= sizeof (ipha_t));
2679 			/*
2680 			 * Check the sanity of the inner IP header like
2681 			 * we did for the outer header.
2682 			 */
2683 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2684 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2685 				goto discard_pkt;
2686 			}
2687 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2688 				goto discard_pkt;
2689 			}
2690 			/* Check for Self-encapsulated tunnels */
2691 			if (in_ipha->ipha_src == ipha->ipha_src &&
2692 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2693 
2694 				mp = icmp_inbound_self_encap_error(mp,
2695 				    iph_hdr_length, hdr_length);
2696 				if (mp == NULL)
2697 					goto discard_pkt;
2698 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2699 				ipha = (ipha_t *)&icmph[1];
2700 				hdr_length = IPH_HDR_LENGTH(ipha);
2701 				/*
2702 				 * The packet in error is self-encapsualted.
2703 				 * And we are finding it further encapsulated
2704 				 * which we could not have possibly generated.
2705 				 */
2706 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2707 					goto discard_pkt;
2708 				}
2709 				icmp_inbound_error_fanout(q, ill, first_mp,
2710 				    icmph, ipha, iph_hdr_length, hdr_length,
2711 				    mctl_present, ip_policy, recv_ill, zoneid);
2712 				return;
2713 			}
2714 		}
2715 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2716 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2717 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2718 		    ii != NULL &&
2719 		    ii->ipsec_in_loopback &&
2720 		    ii->ipsec_in_secure) {
2721 			/*
2722 			 * For IP tunnels that get a looped-back
2723 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2724 			 * reported new MTU to take into account the IPsec
2725 			 * headers protecting this configured tunnel.
2726 			 *
2727 			 * This allows the tunnel module (tun.c) to blindly
2728 			 * accept the MTU reported in an ICMP "too big"
2729 			 * message.
2730 			 *
2731 			 * Non-looped back ICMP messages will just be
2732 			 * handled by the security protocols (if needed),
2733 			 * and the first subsequent packet will hit this
2734 			 * path.
2735 			 */
2736 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2737 			    ipsec_in_extra_length(first_mp));
2738 		}
2739 		/* Have to change db_type after any pullupmsg */
2740 		DB_TYPE(mp) = M_CTL;
2741 
2742 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2743 		    ip_policy, recv_ill, zoneid);
2744 		return;
2745 	}
2746 	/* NOTREACHED */
2747 discard_pkt:
2748 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2749 drop_pkt:;
2750 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2751 	freemsg(first_mp);
2752 }
2753 
2754 /*
2755  * Common IP options parser.
2756  *
2757  * Setup routine: fill in *optp with options-parsing state, then
2758  * tail-call ipoptp_next to return the first option.
2759  */
2760 uint8_t
2761 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2762 {
2763 	uint32_t totallen; /* total length of all options */
2764 
2765 	totallen = ipha->ipha_version_and_hdr_length -
2766 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2767 	totallen <<= 2;
2768 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2769 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2770 	optp->ipoptp_flags = 0;
2771 	return (ipoptp_next(optp));
2772 }
2773 
2774 /*
2775  * Common IP options parser: extract next option.
2776  */
2777 uint8_t
2778 ipoptp_next(ipoptp_t *optp)
2779 {
2780 	uint8_t *end = optp->ipoptp_end;
2781 	uint8_t *cur = optp->ipoptp_next;
2782 	uint8_t opt, len, pointer;
2783 
2784 	/*
2785 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2786 	 * has been corrupted.
2787 	 */
2788 	ASSERT(cur <= end);
2789 
2790 	if (cur == end)
2791 		return (IPOPT_EOL);
2792 
2793 	opt = cur[IPOPT_OPTVAL];
2794 
2795 	/*
2796 	 * Skip any NOP options.
2797 	 */
2798 	while (opt == IPOPT_NOP) {
2799 		cur++;
2800 		if (cur == end)
2801 			return (IPOPT_EOL);
2802 		opt = cur[IPOPT_OPTVAL];
2803 	}
2804 
2805 	if (opt == IPOPT_EOL)
2806 		return (IPOPT_EOL);
2807 
2808 	/*
2809 	 * Option requiring a length.
2810 	 */
2811 	if ((cur + 1) >= end) {
2812 		optp->ipoptp_flags |= IPOPTP_ERROR;
2813 		return (IPOPT_EOL);
2814 	}
2815 	len = cur[IPOPT_OLEN];
2816 	if (len < 2) {
2817 		optp->ipoptp_flags |= IPOPTP_ERROR;
2818 		return (IPOPT_EOL);
2819 	}
2820 	optp->ipoptp_cur = cur;
2821 	optp->ipoptp_len = len;
2822 	optp->ipoptp_next = cur + len;
2823 	if (cur + len > end) {
2824 		optp->ipoptp_flags |= IPOPTP_ERROR;
2825 		return (IPOPT_EOL);
2826 	}
2827 
2828 	/*
2829 	 * For the options which require a pointer field, make sure
2830 	 * its there, and make sure it points to either something
2831 	 * inside this option, or the end of the option.
2832 	 */
2833 	switch (opt) {
2834 	case IPOPT_RR:
2835 	case IPOPT_TS:
2836 	case IPOPT_LSRR:
2837 	case IPOPT_SSRR:
2838 		if (len <= IPOPT_OFFSET) {
2839 			optp->ipoptp_flags |= IPOPTP_ERROR;
2840 			return (opt);
2841 		}
2842 		pointer = cur[IPOPT_OFFSET];
2843 		if (pointer - 1 > len) {
2844 			optp->ipoptp_flags |= IPOPTP_ERROR;
2845 			return (opt);
2846 		}
2847 		break;
2848 	}
2849 
2850 	/*
2851 	 * Sanity check the pointer field based on the type of the
2852 	 * option.
2853 	 */
2854 	switch (opt) {
2855 	case IPOPT_RR:
2856 	case IPOPT_SSRR:
2857 	case IPOPT_LSRR:
2858 		if (pointer < IPOPT_MINOFF_SR)
2859 			optp->ipoptp_flags |= IPOPTP_ERROR;
2860 		break;
2861 	case IPOPT_TS:
2862 		if (pointer < IPOPT_MINOFF_IT)
2863 			optp->ipoptp_flags |= IPOPTP_ERROR;
2864 		/*
2865 		 * Note that the Internet Timestamp option also
2866 		 * contains two four bit fields (the Overflow field,
2867 		 * and the Flag field), which follow the pointer
2868 		 * field.  We don't need to check that these fields
2869 		 * fall within the length of the option because this
2870 		 * was implicitely done above.  We've checked that the
2871 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2872 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2873 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2874 		 */
2875 		ASSERT(len > IPOPT_POS_OV_FLG);
2876 		break;
2877 	}
2878 
2879 	return (opt);
2880 }
2881 
2882 /*
2883  * Use the outgoing IP header to create an IP_OPTIONS option the way
2884  * it was passed down from the application.
2885  */
2886 int
2887 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2888 {
2889 	ipoptp_t	opts;
2890 	const uchar_t	*opt;
2891 	uint8_t		optval;
2892 	uint8_t		optlen;
2893 	uint32_t	len = 0;
2894 	uchar_t	*buf1 = buf;
2895 
2896 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2897 	len += IP_ADDR_LEN;
2898 	bzero(buf1, IP_ADDR_LEN);
2899 
2900 	/*
2901 	 * OK to cast away const here, as we don't store through the returned
2902 	 * opts.ipoptp_cur pointer.
2903 	 */
2904 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2905 	    optval != IPOPT_EOL;
2906 	    optval = ipoptp_next(&opts)) {
2907 		int	off;
2908 
2909 		opt = opts.ipoptp_cur;
2910 		optlen = opts.ipoptp_len;
2911 		switch (optval) {
2912 		case IPOPT_SSRR:
2913 		case IPOPT_LSRR:
2914 
2915 			/*
2916 			 * Insert ipha_dst as the first entry in the source
2917 			 * route and move down the entries on step.
2918 			 * The last entry gets placed at buf1.
2919 			 */
2920 			buf[IPOPT_OPTVAL] = optval;
2921 			buf[IPOPT_OLEN] = optlen;
2922 			buf[IPOPT_OFFSET] = optlen;
2923 
2924 			off = optlen - IP_ADDR_LEN;
2925 			if (off < 0) {
2926 				/* No entries in source route */
2927 				break;
2928 			}
2929 			/* Last entry in source route */
2930 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2931 			off -= IP_ADDR_LEN;
2932 
2933 			while (off > 0) {
2934 				bcopy(opt + off,
2935 				    buf + off + IP_ADDR_LEN,
2936 				    IP_ADDR_LEN);
2937 				off -= IP_ADDR_LEN;
2938 			}
2939 			/* ipha_dst into first slot */
2940 			bcopy(&ipha->ipha_dst,
2941 			    buf + off + IP_ADDR_LEN,
2942 			    IP_ADDR_LEN);
2943 			buf += optlen;
2944 			len += optlen;
2945 			break;
2946 
2947 		case IPOPT_COMSEC:
2948 		case IPOPT_SECURITY:
2949 			/* if passing up a label is not ok, then remove */
2950 			if (is_system_labeled())
2951 				break;
2952 			/* FALLTHROUGH */
2953 		default:
2954 			bcopy(opt, buf, optlen);
2955 			buf += optlen;
2956 			len += optlen;
2957 			break;
2958 		}
2959 	}
2960 done:
2961 	/* Pad the resulting options */
2962 	while (len & 0x3) {
2963 		*buf++ = IPOPT_EOL;
2964 		len++;
2965 	}
2966 	return (len);
2967 }
2968 
2969 /*
2970  * Update any record route or timestamp options to include this host.
2971  * Reverse any source route option.
2972  * This routine assumes that the options are well formed i.e. that they
2973  * have already been checked.
2974  */
2975 static void
2976 icmp_options_update(ipha_t *ipha)
2977 {
2978 	ipoptp_t	opts;
2979 	uchar_t		*opt;
2980 	uint8_t		optval;
2981 	ipaddr_t	src;		/* Our local address */
2982 	ipaddr_t	dst;
2983 
2984 	ip2dbg(("icmp_options_update\n"));
2985 	src = ipha->ipha_src;
2986 	dst = ipha->ipha_dst;
2987 
2988 	for (optval = ipoptp_first(&opts, ipha);
2989 	    optval != IPOPT_EOL;
2990 	    optval = ipoptp_next(&opts)) {
2991 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2992 		opt = opts.ipoptp_cur;
2993 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2994 		    optval, opts.ipoptp_len));
2995 		switch (optval) {
2996 			int off1, off2;
2997 		case IPOPT_SSRR:
2998 		case IPOPT_LSRR:
2999 			/*
3000 			 * Reverse the source route.  The first entry
3001 			 * should be the next to last one in the current
3002 			 * source route (the last entry is our address).
3003 			 * The last entry should be the final destination.
3004 			 */
3005 			off1 = IPOPT_MINOFF_SR - 1;
3006 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3007 			if (off2 < 0) {
3008 				/* No entries in source route */
3009 				ip1dbg((
3010 				    "icmp_options_update: bad src route\n"));
3011 				break;
3012 			}
3013 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3014 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3015 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3016 			off2 -= IP_ADDR_LEN;
3017 
3018 			while (off1 < off2) {
3019 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3020 				bcopy((char *)opt + off2, (char *)opt + off1,
3021 				    IP_ADDR_LEN);
3022 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3023 				off1 += IP_ADDR_LEN;
3024 				off2 -= IP_ADDR_LEN;
3025 			}
3026 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3027 			break;
3028 		}
3029 	}
3030 }
3031 
3032 /*
3033  * Process received ICMP Redirect messages.
3034  */
3035 static void
3036 icmp_redirect(ill_t *ill, mblk_t *mp)
3037 {
3038 	ipha_t	*ipha;
3039 	int	iph_hdr_length;
3040 	icmph_t	*icmph;
3041 	ipha_t	*ipha_err;
3042 	ire_t	*ire;
3043 	ire_t	*prev_ire;
3044 	ire_t	*save_ire;
3045 	ipaddr_t  src, dst, gateway;
3046 	iulp_t	ulp_info = { 0 };
3047 	int	error;
3048 	ip_stack_t *ipst;
3049 
3050 	ASSERT(ill != NULL);
3051 	ipst = ill->ill_ipst;
3052 
3053 	ipha = (ipha_t *)mp->b_rptr;
3054 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3055 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3056 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3057 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3058 		freemsg(mp);
3059 		return;
3060 	}
3061 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3062 	ipha_err = (ipha_t *)&icmph[1];
3063 	src = ipha->ipha_src;
3064 	dst = ipha_err->ipha_dst;
3065 	gateway = icmph->icmph_rd_gateway;
3066 	/* Make sure the new gateway is reachable somehow. */
3067 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3068 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3069 	/*
3070 	 * Make sure we had a route for the dest in question and that
3071 	 * that route was pointing to the old gateway (the source of the
3072 	 * redirect packet.)
3073 	 */
3074 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3075 	    NULL, MATCH_IRE_GW, ipst);
3076 	/*
3077 	 * Check that
3078 	 *	the redirect was not from ourselves
3079 	 *	the new gateway and the old gateway are directly reachable
3080 	 */
3081 	if (!prev_ire ||
3082 	    !ire ||
3083 	    ire->ire_type == IRE_LOCAL) {
3084 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3085 		freemsg(mp);
3086 		if (ire != NULL)
3087 			ire_refrele(ire);
3088 		if (prev_ire != NULL)
3089 			ire_refrele(prev_ire);
3090 		return;
3091 	}
3092 
3093 	/*
3094 	 * Should we use the old ULP info to create the new gateway?  From
3095 	 * a user's perspective, we should inherit the info so that it
3096 	 * is a "smooth" transition.  If we do not do that, then new
3097 	 * connections going thru the new gateway will have no route metrics,
3098 	 * which is counter-intuitive to user.  From a network point of
3099 	 * view, this may or may not make sense even though the new gateway
3100 	 * is still directly connected to us so the route metrics should not
3101 	 * change much.
3102 	 *
3103 	 * But if the old ire_uinfo is not initialized, we do another
3104 	 * recursive lookup on the dest using the new gateway.  There may
3105 	 * be a route to that.  If so, use it to initialize the redirect
3106 	 * route.
3107 	 */
3108 	if (prev_ire->ire_uinfo.iulp_set) {
3109 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3110 	} else {
3111 		ire_t *tmp_ire;
3112 		ire_t *sire;
3113 
3114 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3115 		    ALL_ZONES, 0, NULL,
3116 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3117 		    ipst);
3118 		if (sire != NULL) {
3119 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3120 			/*
3121 			 * If sire != NULL, ire_ftable_lookup() should not
3122 			 * return a NULL value.
3123 			 */
3124 			ASSERT(tmp_ire != NULL);
3125 			ire_refrele(tmp_ire);
3126 			ire_refrele(sire);
3127 		} else if (tmp_ire != NULL) {
3128 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3129 			    sizeof (iulp_t));
3130 			ire_refrele(tmp_ire);
3131 		}
3132 	}
3133 	if (prev_ire->ire_type == IRE_CACHE)
3134 		ire_delete(prev_ire);
3135 	ire_refrele(prev_ire);
3136 	/*
3137 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3138 	 * require TOS routing
3139 	 */
3140 	switch (icmph->icmph_code) {
3141 	case 0:
3142 	case 1:
3143 		/* TODO: TOS specificity for cases 2 and 3 */
3144 	case 2:
3145 	case 3:
3146 		break;
3147 	default:
3148 		freemsg(mp);
3149 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3150 		ire_refrele(ire);
3151 		return;
3152 	}
3153 	/*
3154 	 * Create a Route Association.  This will allow us to remember that
3155 	 * someone we believe told us to use the particular gateway.
3156 	 */
3157 	save_ire = ire;
3158 	ire = ire_create(
3159 	    (uchar_t *)&dst,			/* dest addr */
3160 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3161 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3162 	    (uchar_t *)&gateway,		/* gateway addr */
3163 	    NULL,				/* no in_srcaddr */
3164 	    &save_ire->ire_max_frag,		/* max frag */
3165 	    NULL,				/* Fast Path header */
3166 	    NULL,				/* no rfq */
3167 	    NULL,				/* no stq */
3168 	    IRE_HOST,
3169 	    NULL,
3170 	    NULL,
3171 	    NULL,
3172 	    0,
3173 	    0,
3174 	    0,
3175 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3176 	    &ulp_info,
3177 	    NULL,
3178 	    NULL,
3179 	    ipst);
3180 
3181 	if (ire == NULL) {
3182 		freemsg(mp);
3183 		ire_refrele(save_ire);
3184 		return;
3185 	}
3186 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3187 	ire_refrele(save_ire);
3188 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3189 
3190 	if (error == 0) {
3191 		ire_refrele(ire);		/* Held in ire_add_v4 */
3192 		/* tell routing sockets that we received a redirect */
3193 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3194 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3195 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3196 	}
3197 
3198 	/*
3199 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3200 	 * This together with the added IRE has the effect of
3201 	 * modifying an existing redirect.
3202 	 */
3203 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3204 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3205 	if (prev_ire != NULL) {
3206 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3207 			ire_delete(prev_ire);
3208 		ire_refrele(prev_ire);
3209 	}
3210 
3211 	freemsg(mp);
3212 }
3213 
3214 /*
3215  * Generate an ICMP parameter problem message.
3216  */
3217 static void
3218 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3219 	ip_stack_t *ipst)
3220 {
3221 	icmph_t	icmph;
3222 	boolean_t mctl_present;
3223 	mblk_t *first_mp;
3224 
3225 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3226 
3227 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3228 		if (mctl_present)
3229 			freeb(first_mp);
3230 		return;
3231 	}
3232 
3233 	bzero(&icmph, sizeof (icmph_t));
3234 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3235 	icmph.icmph_pp_ptr = ptr;
3236 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3237 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3238 	    ipst);
3239 }
3240 
3241 /*
3242  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3243  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3244  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3245  * an icmp error packet can be sent.
3246  * Assigns an appropriate source address to the packet. If ipha_dst is
3247  * one of our addresses use it for source. Otherwise pick a source based
3248  * on a route lookup back to ipha_src.
3249  * Note that ipha_src must be set here since the
3250  * packet is likely to arrive on an ill queue in ip_wput() which will
3251  * not set a source address.
3252  */
3253 static void
3254 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3255     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3256 {
3257 	ipaddr_t dst;
3258 	icmph_t	*icmph;
3259 	ipha_t	*ipha;
3260 	uint_t	len_needed;
3261 	size_t	msg_len;
3262 	mblk_t	*mp1;
3263 	ipaddr_t src;
3264 	ire_t	*ire;
3265 	mblk_t *ipsec_mp;
3266 	ipsec_out_t	*io = NULL;
3267 	boolean_t xmit_if_on = B_FALSE;
3268 
3269 	if (mctl_present) {
3270 		/*
3271 		 * If it is :
3272 		 *
3273 		 * 1) a IPSEC_OUT, then this is caused by outbound
3274 		 *    datagram originating on this host. IPSEC processing
3275 		 *    may or may not have been done. Refer to comments above
3276 		 *    icmp_inbound_error_fanout for details.
3277 		 *
3278 		 * 2) a IPSEC_IN if we are generating a icmp_message
3279 		 *    for an incoming datagram destined for us i.e called
3280 		 *    from ip_fanout_send_icmp.
3281 		 */
3282 		ipsec_info_t *in;
3283 		ipsec_mp = mp;
3284 		mp = ipsec_mp->b_cont;
3285 
3286 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3287 		ipha = (ipha_t *)mp->b_rptr;
3288 
3289 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3290 		    in->ipsec_info_type == IPSEC_IN);
3291 
3292 		if (in->ipsec_info_type == IPSEC_IN) {
3293 			/*
3294 			 * Convert the IPSEC_IN to IPSEC_OUT.
3295 			 */
3296 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3297 				BUMP_MIB(&ipst->ips_ip_mib,
3298 				    ipIfStatsOutDiscards);
3299 				return;
3300 			}
3301 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3302 		} else {
3303 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3304 			io = (ipsec_out_t *)in;
3305 			if (io->ipsec_out_xmit_if)
3306 				xmit_if_on = B_TRUE;
3307 			/*
3308 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3309 			 * ire lookup.
3310 			 */
3311 			io->ipsec_out_proc_begin = B_FALSE;
3312 		}
3313 		ASSERT(zoneid == io->ipsec_out_zoneid);
3314 		ASSERT(zoneid != ALL_ZONES);
3315 	} else {
3316 		/*
3317 		 * This is in clear. The icmp message we are building
3318 		 * here should go out in clear.
3319 		 *
3320 		 * Pardon the convolution of it all, but it's easier to
3321 		 * allocate a "use cleartext" IPSEC_IN message and convert
3322 		 * it than it is to allocate a new one.
3323 		 */
3324 		ipsec_in_t *ii;
3325 		ASSERT(DB_TYPE(mp) == M_DATA);
3326 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3327 		if (ipsec_mp == NULL) {
3328 			freemsg(mp);
3329 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3330 			return;
3331 		}
3332 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3333 
3334 		/* This is not a secure packet */
3335 		ii->ipsec_in_secure = B_FALSE;
3336 		/*
3337 		 * For trusted extensions using a shared IP address we can
3338 		 * send using any zoneid.
3339 		 */
3340 		if (zoneid == ALL_ZONES)
3341 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3342 		else
3343 			ii->ipsec_in_zoneid = zoneid;
3344 		ipsec_mp->b_cont = mp;
3345 		ipha = (ipha_t *)mp->b_rptr;
3346 		/*
3347 		 * Convert the IPSEC_IN to IPSEC_OUT.
3348 		 */
3349 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3350 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3351 			return;
3352 		}
3353 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3354 	}
3355 
3356 	/* Remember our eventual destination */
3357 	dst = ipha->ipha_src;
3358 
3359 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3360 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3361 	if (ire != NULL &&
3362 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3363 		src = ipha->ipha_dst;
3364 	} else if (!xmit_if_on) {
3365 		if (ire != NULL)
3366 			ire_refrele(ire);
3367 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3368 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3369 		    ipst);
3370 		if (ire == NULL) {
3371 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3372 			freemsg(ipsec_mp);
3373 			return;
3374 		}
3375 		src = ire->ire_src_addr;
3376 	} else {
3377 		ipif_t	*ipif = NULL;
3378 		ill_t	*ill;
3379 		/*
3380 		 * This must be an ICMP error coming from
3381 		 * ip_mrtun_forward(). The src addr should
3382 		 * be equal to the IP-addr of the outgoing
3383 		 * interface.
3384 		 */
3385 		if (io == NULL) {
3386 			/* This is not a IPSEC_OUT type control msg */
3387 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3388 			freemsg(ipsec_mp);
3389 			return;
3390 		}
3391 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3392 		    NULL, NULL, NULL, NULL, ipst);
3393 		if (ill != NULL) {
3394 			ipif = ipif_get_next_ipif(NULL, ill);
3395 			ill_refrele(ill);
3396 		}
3397 		if (ipif == NULL) {
3398 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3399 			freemsg(ipsec_mp);
3400 			return;
3401 		}
3402 		src = ipif->ipif_src_addr;
3403 		ipif_refrele(ipif);
3404 	}
3405 
3406 	if (ire != NULL)
3407 		ire_refrele(ire);
3408 
3409 	/*
3410 	 * Check if we can send back more then 8 bytes in addition
3411 	 * to the IP header. We will include as much as 64 bytes.
3412 	 */
3413 	len_needed = IPH_HDR_LENGTH(ipha);
3414 	if (ipha->ipha_protocol == IPPROTO_ENCAP &&
3415 	    (uchar_t *)ipha + len_needed + 1 <= mp->b_wptr) {
3416 		len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha + len_needed));
3417 	}
3418 	len_needed += ipst->ips_ip_icmp_return;
3419 	msg_len = msgdsize(mp);
3420 	if (msg_len > len_needed) {
3421 		(void) adjmsg(mp, len_needed - msg_len);
3422 		msg_len = len_needed;
3423 	}
3424 	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_HI);
3425 	if (mp1 == NULL) {
3426 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3427 		freemsg(ipsec_mp);
3428 		return;
3429 	}
3430 	/*
3431 	 * On an unlabeled system, dblks don't necessarily have creds.
3432 	 */
3433 	ASSERT(!is_system_labeled() || DB_CRED(mp) != NULL);
3434 	if (DB_CRED(mp) != NULL)
3435 		mblk_setcred(mp1, DB_CRED(mp));
3436 	mp1->b_cont = mp;
3437 	mp = mp1;
3438 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3439 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3440 	    io->ipsec_out_type == IPSEC_OUT);
3441 	ipsec_mp->b_cont = mp;
3442 
3443 	/*
3444 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3445 	 * node generates be accepted in peace by all on-host destinations.
3446 	 * If we do NOT assume that all on-host destinations trust
3447 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3448 	 * (Look for ipsec_out_icmp_loopback).
3449 	 */
3450 	io->ipsec_out_icmp_loopback = B_TRUE;
3451 
3452 	ipha = (ipha_t *)mp->b_rptr;
3453 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3454 	*ipha = icmp_ipha;
3455 	ipha->ipha_src = src;
3456 	ipha->ipha_dst = dst;
3457 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3458 	msg_len += sizeof (icmp_ipha) + len;
3459 	if (msg_len > IP_MAXPACKET) {
3460 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3461 		msg_len = IP_MAXPACKET;
3462 	}
3463 	ipha->ipha_length = htons((uint16_t)msg_len);
3464 	icmph = (icmph_t *)&ipha[1];
3465 	bcopy(stuff, icmph, len);
3466 	icmph->icmph_checksum = 0;
3467 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3468 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3469 	put(q, ipsec_mp);
3470 }
3471 
3472 /*
3473  * Determine if an ICMP error packet can be sent given the rate limit.
3474  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3475  * in milliseconds) and a burst size. Burst size number of packets can
3476  * be sent arbitrarely closely spaced.
3477  * The state is tracked using two variables to implement an approximate
3478  * token bucket filter:
3479  *	icmp_pkt_err_last - lbolt value when the last burst started
3480  *	icmp_pkt_err_sent - number of packets sent in current burst
3481  */
3482 boolean_t
3483 icmp_err_rate_limit(ip_stack_t *ipst)
3484 {
3485 	clock_t now = TICK_TO_MSEC(lbolt);
3486 	uint_t refilled; /* Number of packets refilled in tbf since last */
3487 	/* Guard against changes by loading into local variable */
3488 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3489 
3490 	if (err_interval == 0)
3491 		return (B_FALSE);
3492 
3493 	if (ipst->ips_icmp_pkt_err_last > now) {
3494 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3495 		ipst->ips_icmp_pkt_err_last = 0;
3496 		ipst->ips_icmp_pkt_err_sent = 0;
3497 	}
3498 	/*
3499 	 * If we are in a burst update the token bucket filter.
3500 	 * Update the "last" time to be close to "now" but make sure
3501 	 * we don't loose precision.
3502 	 */
3503 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3504 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3505 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3506 			ipst->ips_icmp_pkt_err_sent = 0;
3507 		} else {
3508 			ipst->ips_icmp_pkt_err_sent -= refilled;
3509 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3510 		}
3511 	}
3512 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3513 		/* Start of new burst */
3514 		ipst->ips_icmp_pkt_err_last = now;
3515 	}
3516 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3517 		ipst->ips_icmp_pkt_err_sent++;
3518 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3519 		    ipst->ips_icmp_pkt_err_sent));
3520 		return (B_FALSE);
3521 	}
3522 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3523 	return (B_TRUE);
3524 }
3525 
3526 /*
3527  * Check if it is ok to send an IPv4 ICMP error packet in
3528  * response to the IPv4 packet in mp.
3529  * Free the message and return null if no
3530  * ICMP error packet should be sent.
3531  */
3532 static mblk_t *
3533 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3534 {
3535 	icmph_t	*icmph;
3536 	ipha_t	*ipha;
3537 	uint_t	len_needed;
3538 	ire_t	*src_ire;
3539 	ire_t	*dst_ire;
3540 
3541 	if (!mp)
3542 		return (NULL);
3543 	ipha = (ipha_t *)mp->b_rptr;
3544 	if (ip_csum_hdr(ipha)) {
3545 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3546 		freemsg(mp);
3547 		return (NULL);
3548 	}
3549 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3550 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3551 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3552 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3553 	if (src_ire != NULL || dst_ire != NULL ||
3554 	    CLASSD(ipha->ipha_dst) ||
3555 	    CLASSD(ipha->ipha_src) ||
3556 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3557 		/* Note: only errors to the fragment with offset 0 */
3558 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3559 		freemsg(mp);
3560 		if (src_ire != NULL)
3561 			ire_refrele(src_ire);
3562 		if (dst_ire != NULL)
3563 			ire_refrele(dst_ire);
3564 		return (NULL);
3565 	}
3566 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3567 		/*
3568 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3569 		 * errors in response to any ICMP errors.
3570 		 */
3571 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3572 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3573 			if (!pullupmsg(mp, len_needed)) {
3574 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3575 				freemsg(mp);
3576 				return (NULL);
3577 			}
3578 			ipha = (ipha_t *)mp->b_rptr;
3579 		}
3580 		icmph = (icmph_t *)
3581 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3582 		switch (icmph->icmph_type) {
3583 		case ICMP_DEST_UNREACHABLE:
3584 		case ICMP_SOURCE_QUENCH:
3585 		case ICMP_TIME_EXCEEDED:
3586 		case ICMP_PARAM_PROBLEM:
3587 		case ICMP_REDIRECT:
3588 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3589 			freemsg(mp);
3590 			return (NULL);
3591 		default:
3592 			break;
3593 		}
3594 	}
3595 	/*
3596 	 * If this is a labeled system, then check to see if we're allowed to
3597 	 * send a response to this particular sender.  If not, then just drop.
3598 	 */
3599 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3600 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3601 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3602 		freemsg(mp);
3603 		return (NULL);
3604 	}
3605 	if (icmp_err_rate_limit(ipst)) {
3606 		/*
3607 		 * Only send ICMP error packets every so often.
3608 		 * This should be done on a per port/source basis,
3609 		 * but for now this will suffice.
3610 		 */
3611 		freemsg(mp);
3612 		return (NULL);
3613 	}
3614 	return (mp);
3615 }
3616 
3617 /*
3618  * Generate an ICMP redirect message.
3619  */
3620 static void
3621 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3622 {
3623 	icmph_t	icmph;
3624 
3625 	/*
3626 	 * We are called from ip_rput where we could
3627 	 * not have attached an IPSEC_IN.
3628 	 */
3629 	ASSERT(mp->b_datap->db_type == M_DATA);
3630 
3631 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3632 		return;
3633 	}
3634 
3635 	bzero(&icmph, sizeof (icmph_t));
3636 	icmph.icmph_type = ICMP_REDIRECT;
3637 	icmph.icmph_code = 1;
3638 	icmph.icmph_rd_gateway = gateway;
3639 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3640 	/* Redirects sent by router, and router is global zone */
3641 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3642 }
3643 
3644 /*
3645  * Generate an ICMP time exceeded message.
3646  */
3647 void
3648 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3649     ip_stack_t *ipst)
3650 {
3651 	icmph_t	icmph;
3652 	boolean_t mctl_present;
3653 	mblk_t *first_mp;
3654 
3655 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3656 
3657 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3658 		if (mctl_present)
3659 			freeb(first_mp);
3660 		return;
3661 	}
3662 
3663 	bzero(&icmph, sizeof (icmph_t));
3664 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3665 	icmph.icmph_code = code;
3666 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3667 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3668 	    ipst);
3669 }
3670 
3671 /*
3672  * Generate an ICMP unreachable message.
3673  */
3674 void
3675 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3676     ip_stack_t *ipst)
3677 {
3678 	icmph_t	icmph;
3679 	mblk_t *first_mp;
3680 	boolean_t mctl_present;
3681 
3682 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3683 
3684 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3685 		if (mctl_present)
3686 			freeb(first_mp);
3687 		return;
3688 	}
3689 
3690 	bzero(&icmph, sizeof (icmph_t));
3691 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3692 	icmph.icmph_code = code;
3693 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3694 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3695 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3696 	    zoneid, ipst);
3697 }
3698 
3699 /*
3700  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3701  * duplicate.  As long as someone else holds the address, the interface will
3702  * stay down.  When that conflict goes away, the interface is brought back up.
3703  * This is done so that accidental shutdowns of addresses aren't made
3704  * permanent.  Your server will recover from a failure.
3705  *
3706  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3707  * user space process (dhcpagent).
3708  *
3709  * Recovery completes if ARP reports that the address is now ours (via
3710  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3711  *
3712  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3713  */
3714 static void
3715 ipif_dup_recovery(void *arg)
3716 {
3717 	ipif_t *ipif = arg;
3718 	ill_t *ill = ipif->ipif_ill;
3719 	mblk_t *arp_add_mp;
3720 	mblk_t *arp_del_mp;
3721 	area_t *area;
3722 	ip_stack_t *ipst = ill->ill_ipst;
3723 
3724 	ipif->ipif_recovery_id = 0;
3725 
3726 	/*
3727 	 * No lock needed for moving or condemned check, as this is just an
3728 	 * optimization.
3729 	 */
3730 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3731 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3732 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3733 		/* No reason to try to bring this address back. */
3734 		return;
3735 	}
3736 
3737 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3738 		goto alloc_fail;
3739 
3740 	if (ipif->ipif_arp_del_mp == NULL) {
3741 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3742 			goto alloc_fail;
3743 		ipif->ipif_arp_del_mp = arp_del_mp;
3744 	}
3745 
3746 	/* Setting the 'unverified' flag restarts DAD */
3747 	area = (area_t *)arp_add_mp->b_rptr;
3748 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3749 	    ACE_F_UNVERIFIED;
3750 	putnext(ill->ill_rq, arp_add_mp);
3751 	return;
3752 
3753 alloc_fail:
3754 	/*
3755 	 * On allocation failure, just restart the timer.  Note that the ipif
3756 	 * is down here, so no other thread could be trying to start a recovery
3757 	 * timer.  The ill_lock protects the condemned flag and the recovery
3758 	 * timer ID.
3759 	 */
3760 	freemsg(arp_add_mp);
3761 	mutex_enter(&ill->ill_lock);
3762 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3763 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3764 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3765 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3766 	}
3767 	mutex_exit(&ill->ill_lock);
3768 }
3769 
3770 /*
3771  * This is for exclusive changes due to ARP.  Either tear down an interface due
3772  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3773  */
3774 /* ARGSUSED */
3775 static void
3776 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3777 {
3778 	ill_t	*ill = rq->q_ptr;
3779 	arh_t *arh;
3780 	ipaddr_t src;
3781 	ipif_t	*ipif;
3782 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3783 	char hbuf[MAC_STR_LEN];
3784 	char sbuf[INET_ADDRSTRLEN];
3785 	const char *failtype;
3786 	boolean_t bring_up;
3787 	ip_stack_t *ipst = ill->ill_ipst;
3788 
3789 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3790 	case AR_CN_READY:
3791 		failtype = NULL;
3792 		bring_up = B_TRUE;
3793 		break;
3794 	case AR_CN_FAILED:
3795 		failtype = "in use";
3796 		bring_up = B_FALSE;
3797 		break;
3798 	default:
3799 		failtype = "claimed";
3800 		bring_up = B_FALSE;
3801 		break;
3802 	}
3803 
3804 	arh = (arh_t *)mp->b_cont->b_rptr;
3805 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3806 
3807 	/* Handle failures due to probes */
3808 	if (src == 0) {
3809 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3810 		    IP_ADDR_LEN);
3811 	}
3812 
3813 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3814 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3815 	    sizeof (hbuf));
3816 	(void) ip_dot_addr(src, sbuf);
3817 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3818 
3819 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3820 		    ipif->ipif_lcl_addr != src) {
3821 			continue;
3822 		}
3823 
3824 		/*
3825 		 * If we failed on a recovery probe, then restart the timer to
3826 		 * try again later.
3827 		 */
3828 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3829 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3830 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3831 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3832 		    ipst->ips_ip_dup_recovery > 0 &&
3833 		    ipif->ipif_recovery_id == 0) {
3834 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3835 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3836 			continue;
3837 		}
3838 
3839 		/*
3840 		 * If what we're trying to do has already been done, then do
3841 		 * nothing.
3842 		 */
3843 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3844 			continue;
3845 
3846 		if (ipif->ipif_id != 0) {
3847 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3848 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3849 			    ipif->ipif_id);
3850 		}
3851 		if (failtype == NULL) {
3852 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3853 			    ibuf);
3854 		} else {
3855 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3856 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3857 		}
3858 
3859 		if (bring_up) {
3860 			ASSERT(ill->ill_dl_up);
3861 			/*
3862 			 * Free up the ARP delete message so we can allocate
3863 			 * a fresh one through the normal path.
3864 			 */
3865 			freemsg(ipif->ipif_arp_del_mp);
3866 			ipif->ipif_arp_del_mp = NULL;
3867 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3868 			    EINPROGRESS) {
3869 				ipif->ipif_addr_ready = 1;
3870 				(void) ipif_up_done(ipif);
3871 			}
3872 			continue;
3873 		}
3874 
3875 		mutex_enter(&ill->ill_lock);
3876 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3877 		ipif->ipif_flags |= IPIF_DUPLICATE;
3878 		ill->ill_ipif_dup_count++;
3879 		mutex_exit(&ill->ill_lock);
3880 		/*
3881 		 * Already exclusive on the ill; no need to handle deferred
3882 		 * processing here.
3883 		 */
3884 		(void) ipif_down(ipif, NULL, NULL);
3885 		ipif_down_tail(ipif);
3886 		mutex_enter(&ill->ill_lock);
3887 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3888 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3889 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3890 		    ipst->ips_ip_dup_recovery > 0) {
3891 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3892 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3893 		}
3894 		mutex_exit(&ill->ill_lock);
3895 	}
3896 	freemsg(mp);
3897 }
3898 
3899 /* ARGSUSED */
3900 static void
3901 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3902 {
3903 	ill_t	*ill = rq->q_ptr;
3904 	arh_t *arh;
3905 	ipaddr_t src;
3906 	ipif_t	*ipif;
3907 
3908 	arh = (arh_t *)mp->b_cont->b_rptr;
3909 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3910 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3911 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3912 			(void) ipif_resolver_up(ipif, Res_act_defend);
3913 	}
3914 	freemsg(mp);
3915 }
3916 
3917 /*
3918  * News from ARP.  ARP sends notification of interesting events down
3919  * to its clients using M_CTL messages with the interesting ARP packet
3920  * attached via b_cont.
3921  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3922  * queue as opposed to ARP sending the message to all the clients, i.e. all
3923  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3924  * table if a cache IRE is found to delete all the entries for the address in
3925  * the packet.
3926  */
3927 static void
3928 ip_arp_news(queue_t *q, mblk_t *mp)
3929 {
3930 	arcn_t		*arcn;
3931 	arh_t		*arh;
3932 	ire_t		*ire = NULL;
3933 	char		hbuf[MAC_STR_LEN];
3934 	char		sbuf[INET_ADDRSTRLEN];
3935 	ipaddr_t	src;
3936 	in6_addr_t	v6src;
3937 	boolean_t	isv6 = B_FALSE;
3938 	ipif_t		*ipif;
3939 	ill_t		*ill;
3940 	ip_stack_t	*ipst;
3941 
3942 	if (CONN_Q(q)) {
3943 		conn_t *connp = Q_TO_CONN(q);
3944 
3945 		ipst = connp->conn_netstack->netstack_ip;
3946 	} else {
3947 		ill_t *ill = (ill_t *)q->q_ptr;
3948 
3949 		ipst = ill->ill_ipst;
3950 	}
3951 
3952 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3953 		if (q->q_next) {
3954 			putnext(q, mp);
3955 		} else
3956 			freemsg(mp);
3957 		return;
3958 	}
3959 	arh = (arh_t *)mp->b_cont->b_rptr;
3960 	/* Is it one we are interested in? */
3961 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3962 		isv6 = B_TRUE;
3963 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3964 		    IPV6_ADDR_LEN);
3965 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3966 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3967 		    IP_ADDR_LEN);
3968 	} else {
3969 		freemsg(mp);
3970 		return;
3971 	}
3972 
3973 	ill = q->q_ptr;
3974 
3975 	arcn = (arcn_t *)mp->b_rptr;
3976 	switch (arcn->arcn_code) {
3977 	case AR_CN_BOGON:
3978 		/*
3979 		 * Someone is sending ARP packets with a source protocol
3980 		 * address that we have published and for which we believe our
3981 		 * entry is authoritative and (when ill_arp_extend is set)
3982 		 * verified to be unique on the network.
3983 		 *
3984 		 * The ARP module internally handles the cases where the sender
3985 		 * is just probing (for DAD) and where the hardware address of
3986 		 * a non-authoritative entry has changed.  Thus, these are the
3987 		 * real conflicts, and we have to do resolution.
3988 		 *
3989 		 * We back away quickly from the address if it's from DHCP or
3990 		 * otherwise temporary and hasn't been used recently (or at
3991 		 * all).  We'd like to include "deprecated" addresses here as
3992 		 * well (as there's no real reason to defend something we're
3993 		 * discarding), but IPMP "reuses" this flag to mean something
3994 		 * other than the standard meaning.
3995 		 *
3996 		 * If the ARP module above is not extended (meaning that it
3997 		 * doesn't know how to defend the address), then we just log
3998 		 * the problem as we always did and continue on.  It's not
3999 		 * right, but there's little else we can do, and those old ATM
4000 		 * users are going away anyway.
4001 		 */
4002 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4003 		    hbuf, sizeof (hbuf));
4004 		(void) ip_dot_addr(src, sbuf);
4005 		if (isv6) {
4006 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4007 			    ipst);
4008 		} else {
4009 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4010 		}
4011 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4012 			uint32_t now;
4013 			uint32_t maxage;
4014 			clock_t lused;
4015 			uint_t maxdefense;
4016 			uint_t defs;
4017 
4018 			/*
4019 			 * First, figure out if this address hasn't been used
4020 			 * in a while.  If it hasn't, then it's a better
4021 			 * candidate for abandoning.
4022 			 */
4023 			ipif = ire->ire_ipif;
4024 			ASSERT(ipif != NULL);
4025 			now = gethrestime_sec();
4026 			maxage = now - ire->ire_create_time;
4027 			if (maxage > ipst->ips_ip_max_temp_idle)
4028 				maxage = ipst->ips_ip_max_temp_idle;
4029 			lused = drv_hztousec(ddi_get_lbolt() -
4030 			    ire->ire_last_used_time) / MICROSEC + 1;
4031 			if (lused >= maxage && (ipif->ipif_flags &
4032 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4033 				maxdefense = ipst->ips_ip_max_temp_defend;
4034 			else
4035 				maxdefense = ipst->ips_ip_max_defend;
4036 
4037 			/*
4038 			 * Now figure out how many times we've defended
4039 			 * ourselves.  Ignore defenses that happened long in
4040 			 * the past.
4041 			 */
4042 			mutex_enter(&ire->ire_lock);
4043 			if ((defs = ire->ire_defense_count) > 0 &&
4044 			    now - ire->ire_defense_time >
4045 			    ipst->ips_ip_defend_interval) {
4046 				ire->ire_defense_count = defs = 0;
4047 			}
4048 			ire->ire_defense_count++;
4049 			ire->ire_defense_time = now;
4050 			mutex_exit(&ire->ire_lock);
4051 			ill_refhold(ill);
4052 			ire_refrele(ire);
4053 
4054 			/*
4055 			 * If we've defended ourselves too many times already,
4056 			 * then give up and tear down the interface(s) using
4057 			 * this address.  Otherwise, defend by sending out a
4058 			 * gratuitous ARP.
4059 			 */
4060 			if (defs >= maxdefense && ill->ill_arp_extend) {
4061 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4062 				    B_FALSE);
4063 			} else {
4064 				cmn_err(CE_WARN,
4065 				    "node %s is using our IP address %s on %s",
4066 				    hbuf, sbuf, ill->ill_name);
4067 				/*
4068 				 * If this is an old (ATM) ARP module, then
4069 				 * don't try to defend the address.  Remain
4070 				 * compatible with the old behavior.  Defend
4071 				 * only with new ARP.
4072 				 */
4073 				if (ill->ill_arp_extend) {
4074 					qwriter_ip(ill, q, mp, ip_arp_defend,
4075 					    NEW_OP, B_FALSE);
4076 				} else {
4077 					ill_refrele(ill);
4078 				}
4079 			}
4080 			return;
4081 		}
4082 		cmn_err(CE_WARN,
4083 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4084 		    hbuf, sbuf, ill->ill_name);
4085 		if (ire != NULL)
4086 			ire_refrele(ire);
4087 		break;
4088 	case AR_CN_ANNOUNCE:
4089 		if (isv6) {
4090 			/*
4091 			 * For XRESOLV interfaces.
4092 			 * Delete the IRE cache entry and NCE for this
4093 			 * v6 address
4094 			 */
4095 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4096 			/*
4097 			 * If v6src is a non-zero, it's a router address
4098 			 * as below. Do the same sort of thing to clean
4099 			 * out off-net IRE_CACHE entries that go through
4100 			 * the router.
4101 			 */
4102 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4103 				ire_walk_v6(ire_delete_cache_gw_v6,
4104 				    (char *)&v6src, ALL_ZONES, ipst);
4105 			}
4106 		} else {
4107 			nce_hw_map_t hwm;
4108 
4109 			/*
4110 			 * ARP gives us a copy of any packet where it thinks
4111 			 * the address has changed, so that we can update our
4112 			 * caches.  We're responsible for caching known answers
4113 			 * in the current design.  We check whether the
4114 			 * hardware address really has changed in all of our
4115 			 * entries that have cached this mapping, and if so, we
4116 			 * blow them away.  This way we will immediately pick
4117 			 * up the rare case of a host changing hardware
4118 			 * address.
4119 			 */
4120 			if (src == 0)
4121 				break;
4122 			hwm.hwm_addr = src;
4123 			hwm.hwm_hwlen = arh->arh_hlen;
4124 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4125 			ndp_walk_common(ipst->ips_ndp4, NULL,
4126 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4127 		}
4128 		break;
4129 	case AR_CN_READY:
4130 		/* No external v6 resolver has a contract to use this */
4131 		if (isv6)
4132 			break;
4133 		/* If the link is down, we'll retry this later */
4134 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4135 			break;
4136 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4137 		    NULL, NULL, ipst);
4138 		if (ipif != NULL) {
4139 			/*
4140 			 * If this is a duplicate recovery, then we now need to
4141 			 * go exclusive to bring this thing back up.
4142 			 */
4143 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4144 			    IPIF_DUPLICATE) {
4145 				ipif_refrele(ipif);
4146 				ill_refhold(ill);
4147 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4148 				    B_FALSE);
4149 				return;
4150 			}
4151 			/*
4152 			 * If this is the first notice that this address is
4153 			 * ready, then let the user know now.
4154 			 */
4155 			if ((ipif->ipif_flags & IPIF_UP) &&
4156 			    !ipif->ipif_addr_ready) {
4157 				ipif_mask_reply(ipif);
4158 				ip_rts_ifmsg(ipif);
4159 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4160 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4161 			}
4162 			ipif->ipif_addr_ready = 1;
4163 			ipif_refrele(ipif);
4164 		}
4165 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4166 		if (ire != NULL) {
4167 			ire->ire_defense_count = 0;
4168 			ire_refrele(ire);
4169 		}
4170 		break;
4171 	case AR_CN_FAILED:
4172 		/* No external v6 resolver has a contract to use this */
4173 		if (isv6)
4174 			break;
4175 		ill_refhold(ill);
4176 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, 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 			 * When a multicast packet is transmitted
4228 			 * a cache entry is created for the multicast address.
4229 			 * When delivering a copy of the packet or when new
4230 			 * packets are received we do not want to match on the
4231 			 * cached entry so explicitly match on
4232 			 * IRE_LOCAL and IRE_LOOPBACK
4233 			 */
4234 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4235 			    IRE_LOCAL | IRE_LOOPBACK,
4236 			    ipif, zoneid, NULL,
4237 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4238 			if (ire == NULL) {
4239 				/*
4240 				 * packet must have come on a different
4241 				 * interface.
4242 				 * Since a decision has already been made to
4243 				 * deliver the packet, there is no need to test
4244 				 * for SECATTR and ZONEONLY.
4245 				 * Only match on local and broadcast ire's.
4246 				 * See detailed comment above.
4247 				 */
4248 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4249 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4250 				    NULL, MATCH_IRE_TYPE, ipst);
4251 			}
4252 
4253 			if (ire == NULL) {
4254 				/*
4255 				 * This is either a multicast packet or
4256 				 * the address has been removed since
4257 				 * the packet was received.
4258 				 * Return INADDR_ANY so that normal source
4259 				 * selection occurs for the response.
4260 				 */
4261 
4262 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4263 			} else {
4264 				pinfo->ip_pkt_match_addr.s_addr =
4265 				    ire->ire_src_addr;
4266 				ire_refrele(ire);
4267 			}
4268 			ipif_refrele(ipif);
4269 		} else {
4270 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4271 		}
4272 	}
4273 
4274 	pether = (struct ether_header *)((char *)ipha
4275 	    - sizeof (struct ether_header));
4276 	/*
4277 	 * Make sure the interface is an ethernet type, since this option
4278 	 * is currently supported only on this type of interface. Also make
4279 	 * sure we are pointing correctly above db_base.
4280 	 */
4281 
4282 	if ((flags & IPF_RECVSLLA) &&
4283 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4284 	    (ill->ill_type == IFT_ETHER) &&
4285 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4286 
4287 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4288 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4289 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4290 	} else {
4291 		/*
4292 		 * Clear the bit. Indicate to upper layer that IP is not
4293 		 * sending this ancillary info.
4294 		 */
4295 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4296 	}
4297 
4298 	mp->b_datap->db_type = M_CTL;
4299 	mp->b_wptr += sizeof (ip_pktinfo_t);
4300 	mp->b_cont = data_mp;
4301 
4302 	return (mp);
4303 }
4304 
4305 /*
4306  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4307  * part of the bind request.
4308  */
4309 
4310 boolean_t
4311 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4312 {
4313 	ipsec_in_t *ii;
4314 
4315 	ASSERT(policy_mp != NULL);
4316 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4317 
4318 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4319 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4320 
4321 	connp->conn_policy = ii->ipsec_in_policy;
4322 	ii->ipsec_in_policy = NULL;
4323 
4324 	if (ii->ipsec_in_action != NULL) {
4325 		if (connp->conn_latch == NULL) {
4326 			connp->conn_latch = iplatch_create();
4327 			if (connp->conn_latch == NULL)
4328 				return (B_FALSE);
4329 		}
4330 		ipsec_latch_inbound(connp->conn_latch, ii);
4331 	}
4332 	return (B_TRUE);
4333 }
4334 
4335 /*
4336  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4337  * and to arrange for power-fanout assist.  The ULP is identified by
4338  * adding a single byte at the end of the original bind message.
4339  * A ULP other than UDP or TCP that wishes to be recognized passes
4340  * down a bind with a zero length address.
4341  *
4342  * The binding works as follows:
4343  * - A zero byte address means just bind to the protocol.
4344  * - A four byte address is treated as a request to validate
4345  *   that the address is a valid local address, appropriate for
4346  *   an application to bind to. This does not affect any fanout
4347  *   information in IP.
4348  * - A sizeof sin_t byte address is used to bind to only the local address
4349  *   and port.
4350  * - A sizeof ipa_conn_t byte address contains complete fanout information
4351  *   consisting of local and remote addresses and ports.  In
4352  *   this case, the addresses are both validated as appropriate
4353  *   for this operation, and, if so, the information is retained
4354  *   for use in the inbound fanout.
4355  *
4356  * The ULP (except in the zero-length bind) can append an
4357  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4358  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4359  * a copy of the source or destination IRE (source for local bind;
4360  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4361  * policy information contained should be copied on to the conn.
4362  *
4363  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4364  */
4365 mblk_t *
4366 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4367 {
4368 	ssize_t		len;
4369 	struct T_bind_req	*tbr;
4370 	sin_t		*sin;
4371 	ipa_conn_t	*ac;
4372 	uchar_t		*ucp;
4373 	mblk_t		*mp1;
4374 	boolean_t	ire_requested;
4375 	boolean_t	ipsec_policy_set = B_FALSE;
4376 	int		error = 0;
4377 	int		protocol;
4378 	ipa_conn_x_t	*acx;
4379 
4380 	ASSERT(!connp->conn_af_isv6);
4381 	connp->conn_pkt_isv6 = B_FALSE;
4382 
4383 	len = MBLKL(mp);
4384 	if (len < (sizeof (*tbr) + 1)) {
4385 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4386 		    "ip_bind: bogus msg, len %ld", len);
4387 		/* XXX: Need to return something better */
4388 		goto bad_addr;
4389 	}
4390 	/* Back up and extract the protocol identifier. */
4391 	mp->b_wptr--;
4392 	protocol = *mp->b_wptr & 0xFF;
4393 	tbr = (struct T_bind_req *)mp->b_rptr;
4394 	/* Reset the message type in preparation for shipping it back. */
4395 	DB_TYPE(mp) = M_PCPROTO;
4396 
4397 	connp->conn_ulp = (uint8_t)protocol;
4398 
4399 	/*
4400 	 * Check for a zero length address.  This is from a protocol that
4401 	 * wants to register to receive all packets of its type.
4402 	 */
4403 	if (tbr->ADDR_length == 0) {
4404 		/*
4405 		 * These protocols are now intercepted in ip_bind_v6().
4406 		 * Reject protocol-level binds here for now.
4407 		 *
4408 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4409 		 * so that the protocol type cannot be SCTP.
4410 		 */
4411 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4412 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4413 			goto bad_addr;
4414 		}
4415 
4416 		/*
4417 		 *
4418 		 * The udp module never sends down a zero-length address,
4419 		 * and allowing this on a labeled system will break MLP
4420 		 * functionality.
4421 		 */
4422 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4423 			goto bad_addr;
4424 
4425 		if (connp->conn_mac_exempt)
4426 			goto bad_addr;
4427 
4428 		/* No hash here really.  The table is big enough. */
4429 		connp->conn_srcv6 = ipv6_all_zeros;
4430 
4431 		ipcl_proto_insert(connp, protocol);
4432 
4433 		tbr->PRIM_type = T_BIND_ACK;
4434 		return (mp);
4435 	}
4436 
4437 	/* Extract the address pointer from the message. */
4438 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4439 	    tbr->ADDR_length);
4440 	if (ucp == NULL) {
4441 		ip1dbg(("ip_bind: no address\n"));
4442 		goto bad_addr;
4443 	}
4444 	if (!OK_32PTR(ucp)) {
4445 		ip1dbg(("ip_bind: unaligned address\n"));
4446 		goto bad_addr;
4447 	}
4448 	/*
4449 	 * Check for trailing mps.
4450 	 */
4451 
4452 	mp1 = mp->b_cont;
4453 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4454 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4455 
4456 	switch (tbr->ADDR_length) {
4457 	default:
4458 		ip1dbg(("ip_bind: bad address length %d\n",
4459 		    (int)tbr->ADDR_length));
4460 		goto bad_addr;
4461 
4462 	case IP_ADDR_LEN:
4463 		/* Verification of local address only */
4464 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4465 		    ire_requested, ipsec_policy_set, B_FALSE);
4466 		break;
4467 
4468 	case sizeof (sin_t):
4469 		sin = (sin_t *)ucp;
4470 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4471 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4472 		break;
4473 
4474 	case sizeof (ipa_conn_t):
4475 		ac = (ipa_conn_t *)ucp;
4476 		/* For raw socket, the local port is not set. */
4477 		if (ac->ac_lport == 0)
4478 			ac->ac_lport = connp->conn_lport;
4479 		/* Always verify destination reachability. */
4480 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4481 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4482 		    ipsec_policy_set, B_TRUE, B_TRUE);
4483 		break;
4484 
4485 	case sizeof (ipa_conn_x_t):
4486 		acx = (ipa_conn_x_t *)ucp;
4487 		/*
4488 		 * Whether or not to verify destination reachability depends
4489 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4490 		 */
4491 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4492 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4493 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4494 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4495 		break;
4496 	}
4497 	if (error == EINPROGRESS)
4498 		return (NULL);
4499 	else if (error != 0)
4500 		goto bad_addr;
4501 	/*
4502 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4503 	 * We can't do this in ip_bind_insert_ire because the policy
4504 	 * may not have been inherited at that point in time and hence
4505 	 * conn_out_enforce_policy may not be set.
4506 	 */
4507 	mp1 = mp->b_cont;
4508 	if (ire_requested && connp->conn_out_enforce_policy &&
4509 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4510 		ire_t *ire = (ire_t *)mp1->b_rptr;
4511 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4512 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4513 	}
4514 
4515 	/* Send it home. */
4516 	mp->b_datap->db_type = M_PCPROTO;
4517 	tbr->PRIM_type = T_BIND_ACK;
4518 	return (mp);
4519 
4520 bad_addr:
4521 	/*
4522 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4523 	 * a unix errno.
4524 	 */
4525 	if (error > 0)
4526 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4527 	else
4528 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4529 	return (mp);
4530 }
4531 
4532 /*
4533  * Here address is verified to be a valid local address.
4534  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4535  * address is also considered a valid local address.
4536  * In the case of a broadcast/multicast address, however, the
4537  * upper protocol is expected to reset the src address
4538  * to 0 if it sees a IRE_BROADCAST type returned so that
4539  * no packets are emitted with broadcast/multicast address as
4540  * source address (that violates hosts requirements RFC1122)
4541  * The addresses valid for bind are:
4542  *	(1) - INADDR_ANY (0)
4543  *	(2) - IP address of an UP interface
4544  *	(3) - IP address of a DOWN interface
4545  *	(4) - valid local IP broadcast addresses. In this case
4546  *	the conn will only receive packets destined to
4547  *	the specified broadcast address.
4548  *	(5) - a multicast address. In this case
4549  *	the conn will only receive packets destined to
4550  *	the specified multicast address. Note: the
4551  *	application still has to issue an
4552  *	IP_ADD_MEMBERSHIP socket option.
4553  *
4554  * On error, return -1 for TBADADDR otherwise pass the
4555  * errno with TSYSERR reply.
4556  *
4557  * In all the above cases, the bound address must be valid in the current zone.
4558  * When the address is loopback, multicast or broadcast, there might be many
4559  * matching IREs so bind has to look up based on the zone.
4560  *
4561  * Note: lport is in network byte order.
4562  */
4563 int
4564 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4565     boolean_t ire_requested, boolean_t ipsec_policy_set,
4566     boolean_t fanout_insert)
4567 {
4568 	int		error = 0;
4569 	ire_t		*src_ire;
4570 	mblk_t		*policy_mp;
4571 	ipif_t		*ipif;
4572 	zoneid_t	zoneid;
4573 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4574 
4575 	if (ipsec_policy_set) {
4576 		policy_mp = mp->b_cont;
4577 	}
4578 
4579 	/*
4580 	 * If it was previously connected, conn_fully_bound would have
4581 	 * been set.
4582 	 */
4583 	connp->conn_fully_bound = B_FALSE;
4584 
4585 	src_ire = NULL;
4586 	ipif = NULL;
4587 
4588 	zoneid = IPCL_ZONEID(connp);
4589 
4590 	if (src_addr) {
4591 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4592 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4593 		/*
4594 		 * If an address other than 0.0.0.0 is requested,
4595 		 * we verify that it is a valid address for bind
4596 		 * Note: Following code is in if-else-if form for
4597 		 * readability compared to a condition check.
4598 		 */
4599 		/* LINTED - statement has no consequent */
4600 		if (IRE_IS_LOCAL(src_ire)) {
4601 			/*
4602 			 * (2) Bind to address of local UP interface
4603 			 */
4604 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4605 			/*
4606 			 * (4) Bind to broadcast address
4607 			 * Note: permitted only from transports that
4608 			 * request IRE
4609 			 */
4610 			if (!ire_requested)
4611 				error = EADDRNOTAVAIL;
4612 		} else {
4613 			/*
4614 			 * (3) Bind to address of local DOWN interface
4615 			 * (ipif_lookup_addr() looks up all interfaces
4616 			 * but we do not get here for UP interfaces
4617 			 * - case (2) above)
4618 			 * We put the protocol byte back into the mblk
4619 			 * since we may come back via ip_wput_nondata()
4620 			 * later with this mblk if ipif_lookup_addr chooses
4621 			 * to defer processing.
4622 			 */
4623 			*mp->b_wptr++ = (char)connp->conn_ulp;
4624 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4625 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4626 			    &error, ipst)) != NULL) {
4627 				ipif_refrele(ipif);
4628 			} else if (error == EINPROGRESS) {
4629 				if (src_ire != NULL)
4630 					ire_refrele(src_ire);
4631 				return (EINPROGRESS);
4632 			} else if (CLASSD(src_addr)) {
4633 				error = 0;
4634 				if (src_ire != NULL)
4635 					ire_refrele(src_ire);
4636 				/*
4637 				 * (5) bind to multicast address.
4638 				 * Fake out the IRE returned to upper
4639 				 * layer to be a broadcast IRE.
4640 				 */
4641 				src_ire = ire_ctable_lookup(
4642 				    INADDR_BROADCAST, INADDR_ANY,
4643 				    IRE_BROADCAST, NULL, zoneid, NULL,
4644 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4645 				    ipst);
4646 				if (src_ire == NULL || !ire_requested)
4647 					error = EADDRNOTAVAIL;
4648 			} else {
4649 				/*
4650 				 * Not a valid address for bind
4651 				 */
4652 				error = EADDRNOTAVAIL;
4653 			}
4654 			/*
4655 			 * Just to keep it consistent with the processing in
4656 			 * ip_bind_v4()
4657 			 */
4658 			mp->b_wptr--;
4659 		}
4660 		if (error) {
4661 			/* Red Alert!  Attempting to be a bogon! */
4662 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4663 			    ntohl(src_addr)));
4664 			goto bad_addr;
4665 		}
4666 	}
4667 
4668 	/*
4669 	 * Allow setting new policies. For example, disconnects come
4670 	 * down as ipa_t bind. As we would have set conn_policy_cached
4671 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4672 	 * can change after the disconnect.
4673 	 */
4674 	connp->conn_policy_cached = B_FALSE;
4675 
4676 	/*
4677 	 * If not fanout_insert this was just an address verification
4678 	 */
4679 	if (fanout_insert) {
4680 		/*
4681 		 * The addresses have been verified. Time to insert in
4682 		 * the correct fanout list.
4683 		 */
4684 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4685 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4686 		connp->conn_lport = lport;
4687 		connp->conn_fport = 0;
4688 		/*
4689 		 * Do we need to add a check to reject Multicast packets
4690 		 *
4691 		 * We need to make sure that the conn_recv is set to a non-null
4692 		 * value before we insert the conn into the classifier table.
4693 		 * This is to avoid a race with an incoming packet which does an
4694 		 * ipcl_classify().
4695 		 */
4696 		if (*mp->b_wptr == IPPROTO_TCP)
4697 			connp->conn_recv = tcp_conn_request;
4698 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4699 	}
4700 
4701 	if (error == 0) {
4702 		if (ire_requested) {
4703 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4704 				error = -1;
4705 				/* Falls through to bad_addr */
4706 			}
4707 		} else if (ipsec_policy_set) {
4708 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4709 				error = -1;
4710 				/* Falls through to bad_addr */
4711 			}
4712 		}
4713 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4714 		connp->conn_recv = tcp_input;
4715 	}
4716 bad_addr:
4717 	if (error != 0) {
4718 		if (connp->conn_anon_port) {
4719 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4720 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4721 			    B_FALSE);
4722 		}
4723 		connp->conn_mlp_type = mlptSingle;
4724 	}
4725 	if (src_ire != NULL)
4726 		IRE_REFRELE(src_ire);
4727 	if (ipsec_policy_set) {
4728 		ASSERT(policy_mp == mp->b_cont);
4729 		ASSERT(policy_mp != NULL);
4730 		freeb(policy_mp);
4731 		/*
4732 		 * As of now assume that nothing else accompanies
4733 		 * IPSEC_POLICY_SET.
4734 		 */
4735 		mp->b_cont = NULL;
4736 	}
4737 	return (error);
4738 }
4739 
4740 /*
4741  * Verify that both the source and destination addresses
4742  * are valid.  If verify_dst is false, then the destination address may be
4743  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4744  * destination reachability, while tunnels do not.
4745  * Note that we allow connect to broadcast and multicast
4746  * addresses when ire_requested is set. Thus the ULP
4747  * has to check for IRE_BROADCAST and multicast.
4748  *
4749  * Returns zero if ok.
4750  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4751  * (for use with TSYSERR reply).
4752  *
4753  * Note: lport and fport are in network byte order.
4754  */
4755 int
4756 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4757     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4758     boolean_t ire_requested, boolean_t ipsec_policy_set,
4759     boolean_t fanout_insert, boolean_t verify_dst)
4760 {
4761 	ire_t		*src_ire;
4762 	ire_t		*dst_ire;
4763 	int		error = 0;
4764 	int 		protocol;
4765 	mblk_t		*policy_mp;
4766 	ire_t		*sire = NULL;
4767 	ire_t		*md_dst_ire = NULL;
4768 	ire_t		*lso_dst_ire = NULL;
4769 	ill_t		*ill = NULL;
4770 	zoneid_t	zoneid;
4771 	ipaddr_t	src_addr = *src_addrp;
4772 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4773 
4774 	src_ire = dst_ire = NULL;
4775 	protocol = *mp->b_wptr & 0xFF;
4776 
4777 	/*
4778 	 * If we never got a disconnect before, clear it now.
4779 	 */
4780 	connp->conn_fully_bound = B_FALSE;
4781 
4782 	if (ipsec_policy_set) {
4783 		policy_mp = mp->b_cont;
4784 	}
4785 
4786 	zoneid = IPCL_ZONEID(connp);
4787 
4788 	if (CLASSD(dst_addr)) {
4789 		/* Pick up an IRE_BROADCAST */
4790 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4791 		    NULL, zoneid, MBLK_GETLABEL(mp),
4792 		    (MATCH_IRE_RECURSIVE |
4793 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4794 		    MATCH_IRE_SECATTR), ipst);
4795 	} else {
4796 		/*
4797 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4798 		 * and onlink ipif is not found set ENETUNREACH error.
4799 		 */
4800 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4801 			ipif_t *ipif;
4802 
4803 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4804 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4805 			if (ipif == NULL) {
4806 				error = ENETUNREACH;
4807 				goto bad_addr;
4808 			}
4809 			ipif_refrele(ipif);
4810 		}
4811 
4812 		if (connp->conn_nexthop_set) {
4813 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4814 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4815 			    MATCH_IRE_SECATTR, ipst);
4816 		} else {
4817 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4818 			    &sire, zoneid, MBLK_GETLABEL(mp),
4819 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4820 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4821 			    MATCH_IRE_SECATTR), ipst);
4822 		}
4823 	}
4824 	/*
4825 	 * dst_ire can't be a broadcast when not ire_requested.
4826 	 * We also prevent ire's with src address INADDR_ANY to
4827 	 * be used, which are created temporarily for
4828 	 * sending out packets from endpoints that have
4829 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4830 	 * reachable.  If verify_dst is false, the destination needn't be
4831 	 * reachable.
4832 	 *
4833 	 * If we match on a reject or black hole, then we've got a
4834 	 * local failure.  May as well fail out the connect() attempt,
4835 	 * since it's never going to succeed.
4836 	 */
4837 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4838 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4839 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4840 		/*
4841 		 * If we're verifying destination reachability, we always want
4842 		 * to complain here.
4843 		 *
4844 		 * If we're not verifying destination reachability but the
4845 		 * destination has a route, we still want to fail on the
4846 		 * temporary address and broadcast address tests.
4847 		 */
4848 		if (verify_dst || (dst_ire != NULL)) {
4849 			if (ip_debug > 2) {
4850 				pr_addr_dbg("ip_bind_connected: bad connected "
4851 				    "dst %s\n", AF_INET, &dst_addr);
4852 			}
4853 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4854 				error = ENETUNREACH;
4855 			else
4856 				error = EHOSTUNREACH;
4857 			goto bad_addr;
4858 		}
4859 	}
4860 
4861 	/*
4862 	 * We now know that routing will allow us to reach the destination.
4863 	 * Check whether Trusted Solaris policy allows communication with this
4864 	 * host, and pretend that the destination is unreachable if not.
4865 	 *
4866 	 * This is never a problem for TCP, since that transport is known to
4867 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4868 	 * handling.  If the remote is unreachable, it will be detected at that
4869 	 * point, so there's no reason to check it here.
4870 	 *
4871 	 * Note that for sendto (and other datagram-oriented friends), this
4872 	 * check is done as part of the data path label computation instead.
4873 	 * The check here is just to make non-TCP connect() report the right
4874 	 * error.
4875 	 */
4876 	if (dst_ire != NULL && is_system_labeled() &&
4877 	    !IPCL_IS_TCP(connp) &&
4878 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4879 	    connp->conn_mac_exempt, ipst) != 0) {
4880 		error = EHOSTUNREACH;
4881 		if (ip_debug > 2) {
4882 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4883 			    AF_INET, &dst_addr);
4884 		}
4885 		goto bad_addr;
4886 	}
4887 
4888 	/*
4889 	 * If the app does a connect(), it means that it will most likely
4890 	 * send more than 1 packet to the destination.  It makes sense
4891 	 * to clear the temporary flag.
4892 	 */
4893 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4894 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4895 		irb_t *irb = dst_ire->ire_bucket;
4896 
4897 		rw_enter(&irb->irb_lock, RW_WRITER);
4898 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4899 		irb->irb_tmp_ire_cnt--;
4900 		rw_exit(&irb->irb_lock);
4901 	}
4902 
4903 	/*
4904 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4905 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4906 	 * eligibility tests for passive connects are handled separately
4907 	 * through tcp_adapt_ire().  We do this before the source address
4908 	 * selection, because dst_ire may change after a call to
4909 	 * ipif_select_source().  This is a best-effort check, as the
4910 	 * packet for this connection may not actually go through
4911 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4912 	 * calling ip_newroute().  This is why we further check on the
4913 	 * IRE during LSO/Multidata packet transmission in
4914 	 * tcp_lsosend()/tcp_multisend().
4915 	 */
4916 	if (!ipsec_policy_set && dst_ire != NULL &&
4917 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4918 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4919 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4920 			lso_dst_ire = dst_ire;
4921 			IRE_REFHOLD(lso_dst_ire);
4922 		} else if (ipst->ips_ip_multidata_outbound &&
4923 		    ILL_MDT_CAPABLE(ill)) {
4924 			md_dst_ire = dst_ire;
4925 			IRE_REFHOLD(md_dst_ire);
4926 		}
4927 	}
4928 
4929 	if (dst_ire != NULL &&
4930 	    dst_ire->ire_type == IRE_LOCAL &&
4931 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4932 		/*
4933 		 * If the IRE belongs to a different zone, look for a matching
4934 		 * route in the forwarding table and use the source address from
4935 		 * that route.
4936 		 */
4937 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4938 		    zoneid, 0, NULL,
4939 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4940 		    MATCH_IRE_RJ_BHOLE, ipst);
4941 		if (src_ire == NULL) {
4942 			error = EHOSTUNREACH;
4943 			goto bad_addr;
4944 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4945 			if (!(src_ire->ire_type & IRE_HOST))
4946 				error = ENETUNREACH;
4947 			else
4948 				error = EHOSTUNREACH;
4949 			goto bad_addr;
4950 		}
4951 		if (src_addr == INADDR_ANY)
4952 			src_addr = src_ire->ire_src_addr;
4953 		ire_refrele(src_ire);
4954 		src_ire = NULL;
4955 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4956 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4957 			src_addr = sire->ire_src_addr;
4958 			ire_refrele(dst_ire);
4959 			dst_ire = sire;
4960 			sire = NULL;
4961 		} else {
4962 			/*
4963 			 * Pick a source address so that a proper inbound
4964 			 * load spreading would happen.
4965 			 */
4966 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4967 			ipif_t *src_ipif = NULL;
4968 			ire_t *ipif_ire;
4969 
4970 			/*
4971 			 * Supply a local source address such that inbound
4972 			 * load spreading happens.
4973 			 *
4974 			 * Determine the best source address on this ill for
4975 			 * the destination.
4976 			 *
4977 			 * 1) For broadcast, we should return a broadcast ire
4978 			 *    found above so that upper layers know that the
4979 			 *    destination address is a broadcast address.
4980 			 *
4981 			 * 2) If this is part of a group, select a better
4982 			 *    source address so that better inbound load
4983 			 *    balancing happens. Do the same if the ipif
4984 			 *    is DEPRECATED.
4985 			 *
4986 			 * 3) If the outgoing interface is part of a usesrc
4987 			 *    group, then try selecting a source address from
4988 			 *    the usesrc ILL.
4989 			 */
4990 			if ((dst_ire->ire_zoneid != zoneid &&
4991 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4992 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4993 			    ((dst_ill->ill_group != NULL) ||
4994 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4995 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4996 				/*
4997 				 * If the destination is reachable via a
4998 				 * given gateway, the selected source address
4999 				 * should be in the same subnet as the gateway.
5000 				 * Otherwise, the destination is not reachable.
5001 				 *
5002 				 * If there are no interfaces on the same subnet
5003 				 * as the destination, ipif_select_source gives
5004 				 * first non-deprecated interface which might be
5005 				 * on a different subnet than the gateway.
5006 				 * This is not desirable. Hence pass the dst_ire
5007 				 * source address to ipif_select_source.
5008 				 * It is sure that the destination is reachable
5009 				 * with the dst_ire source address subnet.
5010 				 * So passing dst_ire source address to
5011 				 * ipif_select_source will make sure that the
5012 				 * selected source will be on the same subnet
5013 				 * as dst_ire source address.
5014 				 */
5015 				ipaddr_t saddr =
5016 				    dst_ire->ire_ipif->ipif_src_addr;
5017 				src_ipif = ipif_select_source(dst_ill,
5018 				    saddr, zoneid);
5019 				if (src_ipif != NULL) {
5020 					if (IS_VNI(src_ipif->ipif_ill)) {
5021 						/*
5022 						 * For VNI there is no
5023 						 * interface route
5024 						 */
5025 						src_addr =
5026 						    src_ipif->ipif_src_addr;
5027 					} else {
5028 						ipif_ire =
5029 						    ipif_to_ire(src_ipif);
5030 						if (ipif_ire != NULL) {
5031 							IRE_REFRELE(dst_ire);
5032 							dst_ire = ipif_ire;
5033 						}
5034 						src_addr =
5035 						    dst_ire->ire_src_addr;
5036 					}
5037 					ipif_refrele(src_ipif);
5038 				} else {
5039 					src_addr = dst_ire->ire_src_addr;
5040 				}
5041 			} else {
5042 				src_addr = dst_ire->ire_src_addr;
5043 			}
5044 		}
5045 	}
5046 
5047 	/*
5048 	 * We do ire_route_lookup() here (and not
5049 	 * interface lookup as we assert that
5050 	 * src_addr should only come from an
5051 	 * UP interface for hard binding.
5052 	 */
5053 	ASSERT(src_ire == NULL);
5054 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5055 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5056 	/* src_ire must be a local|loopback */
5057 	if (!IRE_IS_LOCAL(src_ire)) {
5058 		if (ip_debug > 2) {
5059 			pr_addr_dbg("ip_bind_connected: bad connected "
5060 			    "src %s\n", AF_INET, &src_addr);
5061 		}
5062 		error = EADDRNOTAVAIL;
5063 		goto bad_addr;
5064 	}
5065 
5066 	/*
5067 	 * If the source address is a loopback address, the
5068 	 * destination had best be local or multicast.
5069 	 * The transports that can't handle multicast will reject
5070 	 * those addresses.
5071 	 */
5072 	if (src_ire->ire_type == IRE_LOOPBACK &&
5073 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5074 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5075 		error = -1;
5076 		goto bad_addr;
5077 	}
5078 
5079 	/*
5080 	 * Allow setting new policies. For example, disconnects come
5081 	 * down as ipa_t bind. As we would have set conn_policy_cached
5082 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5083 	 * can change after the disconnect.
5084 	 */
5085 	connp->conn_policy_cached = B_FALSE;
5086 
5087 	/*
5088 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5089 	 * can handle their passed-in conn's.
5090 	 */
5091 
5092 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5093 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5094 	connp->conn_lport = lport;
5095 	connp->conn_fport = fport;
5096 	*src_addrp = src_addr;
5097 
5098 	ASSERT(!(ipsec_policy_set && ire_requested));
5099 	if (ire_requested) {
5100 		iulp_t *ulp_info = NULL;
5101 
5102 		/*
5103 		 * Note that sire will not be NULL if this is an off-link
5104 		 * connection and there is not cache for that dest yet.
5105 		 *
5106 		 * XXX Because of an existing bug, if there are multiple
5107 		 * default routes, the IRE returned now may not be the actual
5108 		 * default route used (default routes are chosen in a
5109 		 * round robin fashion).  So if the metrics for different
5110 		 * default routes are different, we may return the wrong
5111 		 * metrics.  This will not be a problem if the existing
5112 		 * bug is fixed.
5113 		 */
5114 		if (sire != NULL) {
5115 			ulp_info = &(sire->ire_uinfo);
5116 		}
5117 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5118 			error = -1;
5119 			goto bad_addr;
5120 		}
5121 	} else if (ipsec_policy_set) {
5122 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5123 			error = -1;
5124 			goto bad_addr;
5125 		}
5126 	}
5127 
5128 	/*
5129 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5130 	 * we'll cache that.  If we don't, we'll inherit global policy.
5131 	 *
5132 	 * We can't insert until the conn reflects the policy. Note that
5133 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5134 	 * connections where we don't have a policy. This is to prevent
5135 	 * global policy lookups in the inbound path.
5136 	 *
5137 	 * If we insert before we set conn_policy_cached,
5138 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5139 	 * because global policy cound be non-empty. We normally call
5140 	 * ipsec_check_policy() for conn_policy_cached connections only if
5141 	 * ipc_in_enforce_policy is set. But in this case,
5142 	 * conn_policy_cached can get set anytime since we made the
5143 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5144 	 * called, which will make the above assumption false.  Thus, we
5145 	 * need to insert after we set conn_policy_cached.
5146 	 */
5147 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5148 		goto bad_addr;
5149 
5150 	if (fanout_insert) {
5151 		/*
5152 		 * The addresses have been verified. Time to insert in
5153 		 * the correct fanout list.
5154 		 * We need to make sure that the conn_recv is set to a non-null
5155 		 * value before we insert into the classifier table to avoid a
5156 		 * race with an incoming packet which does an ipcl_classify().
5157 		 */
5158 		if (protocol == IPPROTO_TCP)
5159 			connp->conn_recv = tcp_input;
5160 		error = ipcl_conn_insert(connp, protocol, src_addr,
5161 		    dst_addr, connp->conn_ports);
5162 	}
5163 
5164 	if (error == 0) {
5165 		connp->conn_fully_bound = B_TRUE;
5166 		/*
5167 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5168 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5169 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5170 		 * ip_xxinfo_return(), which performs further checks
5171 		 * against them and upon success, returns the LSO/MDT info
5172 		 * mblk which we will attach to the bind acknowledgment.
5173 		 */
5174 		if (lso_dst_ire != NULL) {
5175 			mblk_t *lsoinfo_mp;
5176 
5177 			ASSERT(ill->ill_lso_capab != NULL);
5178 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5179 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5180 				linkb(mp, lsoinfo_mp);
5181 		} else if (md_dst_ire != NULL) {
5182 			mblk_t *mdinfo_mp;
5183 
5184 			ASSERT(ill->ill_mdt_capab != NULL);
5185 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5186 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5187 				linkb(mp, mdinfo_mp);
5188 		}
5189 	}
5190 bad_addr:
5191 	if (ipsec_policy_set) {
5192 		ASSERT(policy_mp == mp->b_cont);
5193 		ASSERT(policy_mp != NULL);
5194 		freeb(policy_mp);
5195 		/*
5196 		 * As of now assume that nothing else accompanies
5197 		 * IPSEC_POLICY_SET.
5198 		 */
5199 		mp->b_cont = NULL;
5200 	}
5201 	if (src_ire != NULL)
5202 		IRE_REFRELE(src_ire);
5203 	if (dst_ire != NULL)
5204 		IRE_REFRELE(dst_ire);
5205 	if (sire != NULL)
5206 		IRE_REFRELE(sire);
5207 	if (md_dst_ire != NULL)
5208 		IRE_REFRELE(md_dst_ire);
5209 	if (lso_dst_ire != NULL)
5210 		IRE_REFRELE(lso_dst_ire);
5211 	return (error);
5212 }
5213 
5214 /*
5215  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5216  * Prefers dst_ire over src_ire.
5217  */
5218 static boolean_t
5219 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5220 {
5221 	mblk_t	*mp1;
5222 	ire_t *ret_ire = NULL;
5223 
5224 	mp1 = mp->b_cont;
5225 	ASSERT(mp1 != NULL);
5226 
5227 	if (ire != NULL) {
5228 		/*
5229 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5230 		 * appended mblk. Its <upper protocol>'s
5231 		 * job to make sure there is room.
5232 		 */
5233 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5234 			return (0);
5235 
5236 		mp1->b_datap->db_type = IRE_DB_TYPE;
5237 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5238 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5239 		ret_ire = (ire_t *)mp1->b_rptr;
5240 		/*
5241 		 * Pass the latest setting of the ip_path_mtu_discovery and
5242 		 * copy the ulp info if any.
5243 		 */
5244 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5245 		    IPH_DF : 0;
5246 		if (ulp_info != NULL) {
5247 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5248 			    sizeof (iulp_t));
5249 		}
5250 		ret_ire->ire_mp = mp1;
5251 	} else {
5252 		/*
5253 		 * No IRE was found. Remove IRE mblk.
5254 		 */
5255 		mp->b_cont = mp1->b_cont;
5256 		freeb(mp1);
5257 	}
5258 
5259 	return (1);
5260 }
5261 
5262 /*
5263  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5264  * the final piece where we don't.  Return a pointer to the first mblk in the
5265  * result, and update the pointer to the next mblk to chew on.  If anything
5266  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5267  * NULL pointer.
5268  */
5269 mblk_t *
5270 ip_carve_mp(mblk_t **mpp, ssize_t len)
5271 {
5272 	mblk_t	*mp0;
5273 	mblk_t	*mp1;
5274 	mblk_t	*mp2;
5275 
5276 	if (!len || !mpp || !(mp0 = *mpp))
5277 		return (NULL);
5278 	/* If we aren't going to consume the first mblk, we need a dup. */
5279 	if (mp0->b_wptr - mp0->b_rptr > len) {
5280 		mp1 = dupb(mp0);
5281 		if (mp1) {
5282 			/* Partition the data between the two mblks. */
5283 			mp1->b_wptr = mp1->b_rptr + len;
5284 			mp0->b_rptr = mp1->b_wptr;
5285 			/*
5286 			 * after adjustments if mblk not consumed is now
5287 			 * unaligned, try to align it. If this fails free
5288 			 * all messages and let upper layer recover.
5289 			 */
5290 			if (!OK_32PTR(mp0->b_rptr)) {
5291 				if (!pullupmsg(mp0, -1)) {
5292 					freemsg(mp0);
5293 					freemsg(mp1);
5294 					*mpp = NULL;
5295 					return (NULL);
5296 				}
5297 			}
5298 		}
5299 		return (mp1);
5300 	}
5301 	/* Eat through as many mblks as we need to get len bytes. */
5302 	len -= mp0->b_wptr - mp0->b_rptr;
5303 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5304 		if (mp2->b_wptr - mp2->b_rptr > len) {
5305 			/*
5306 			 * We won't consume the entire last mblk.  Like
5307 			 * above, dup and partition it.
5308 			 */
5309 			mp1->b_cont = dupb(mp2);
5310 			mp1 = mp1->b_cont;
5311 			if (!mp1) {
5312 				/*
5313 				 * Trouble.  Rather than go to a lot of
5314 				 * trouble to clean up, we free the messages.
5315 				 * This won't be any worse than losing it on
5316 				 * the wire.
5317 				 */
5318 				freemsg(mp0);
5319 				freemsg(mp2);
5320 				*mpp = NULL;
5321 				return (NULL);
5322 			}
5323 			mp1->b_wptr = mp1->b_rptr + len;
5324 			mp2->b_rptr = mp1->b_wptr;
5325 			/*
5326 			 * after adjustments if mblk not consumed is now
5327 			 * unaligned, try to align it. If this fails free
5328 			 * all messages and let upper layer recover.
5329 			 */
5330 			if (!OK_32PTR(mp2->b_rptr)) {
5331 				if (!pullupmsg(mp2, -1)) {
5332 					freemsg(mp0);
5333 					freemsg(mp2);
5334 					*mpp = NULL;
5335 					return (NULL);
5336 				}
5337 			}
5338 			*mpp = mp2;
5339 			return (mp0);
5340 		}
5341 		/* Decrement len by the amount we just got. */
5342 		len -= mp2->b_wptr - mp2->b_rptr;
5343 	}
5344 	/*
5345 	 * len should be reduced to zero now.  If not our caller has
5346 	 * screwed up.
5347 	 */
5348 	if (len) {
5349 		/* Shouldn't happen! */
5350 		freemsg(mp0);
5351 		*mpp = NULL;
5352 		return (NULL);
5353 	}
5354 	/*
5355 	 * We consumed up to exactly the end of an mblk.  Detach the part
5356 	 * we are returning from the rest of the chain.
5357 	 */
5358 	mp1->b_cont = NULL;
5359 	*mpp = mp2;
5360 	return (mp0);
5361 }
5362 
5363 /* The ill stream is being unplumbed. Called from ip_close */
5364 int
5365 ip_modclose(ill_t *ill)
5366 {
5367 	boolean_t success;
5368 	ipsq_t	*ipsq;
5369 	ipif_t	*ipif;
5370 	queue_t	*q = ill->ill_rq;
5371 	ip_stack_t	*ipst = ill->ill_ipst;
5372 	clock_t timeout;
5373 
5374 	/*
5375 	 * Wait for the ACKs of all deferred control messages to be processed.
5376 	 * In particular, we wait for a potential capability reset initiated
5377 	 * in ip_sioctl_plink() to complete before proceeding.
5378 	 *
5379 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5380 	 * in case the driver never replies.
5381 	 */
5382 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5383 	mutex_enter(&ill->ill_lock);
5384 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5385 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5386 			/* Timeout */
5387 			break;
5388 		}
5389 	}
5390 	mutex_exit(&ill->ill_lock);
5391 
5392 	/*
5393 	 * Forcibly enter the ipsq after some delay. This is to take
5394 	 * care of the case when some ioctl does not complete because
5395 	 * we sent a control message to the driver and it did not
5396 	 * send us a reply. We want to be able to at least unplumb
5397 	 * and replumb rather than force the user to reboot the system.
5398 	 */
5399 	success = ipsq_enter(ill, B_FALSE);
5400 
5401 	/*
5402 	 * Open/close/push/pop is guaranteed to be single threaded
5403 	 * per stream by STREAMS. FS guarantees that all references
5404 	 * from top are gone before close is called. So there can't
5405 	 * be another close thread that has set CONDEMNED on this ill.
5406 	 * and cause ipsq_enter to return failure.
5407 	 */
5408 	ASSERT(success);
5409 	ipsq = ill->ill_phyint->phyint_ipsq;
5410 
5411 	/*
5412 	 * Mark it condemned. No new reference will be made to this ill.
5413 	 * Lookup functions will return an error. Threads that try to
5414 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5415 	 * that the refcnt will drop down to zero.
5416 	 */
5417 	mutex_enter(&ill->ill_lock);
5418 	ill->ill_state_flags |= ILL_CONDEMNED;
5419 	for (ipif = ill->ill_ipif; ipif != NULL;
5420 	    ipif = ipif->ipif_next) {
5421 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5422 	}
5423 	/*
5424 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5425 	 * returns  error if ILL_CONDEMNED is set
5426 	 */
5427 	cv_broadcast(&ill->ill_cv);
5428 	mutex_exit(&ill->ill_lock);
5429 
5430 	/*
5431 	 * Send all the deferred DLPI messages downstream which came in
5432 	 * during the small window right before ipsq_enter(). We do this
5433 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5434 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5435 	 */
5436 	ill_dlpi_send_deferred(ill);
5437 
5438 	/*
5439 	 * Shut down fragmentation reassembly.
5440 	 * ill_frag_timer won't start a timer again.
5441 	 * Now cancel any existing timer
5442 	 */
5443 	(void) untimeout(ill->ill_frag_timer_id);
5444 	(void) ill_frag_timeout(ill, 0);
5445 
5446 	/*
5447 	 * If MOVE was in progress, clear the
5448 	 * move_in_progress fields also.
5449 	 */
5450 	if (ill->ill_move_in_progress) {
5451 		ILL_CLEAR_MOVE(ill);
5452 	}
5453 
5454 	/*
5455 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5456 	 * this ill. Then wait for the refcnts to drop to zero.
5457 	 * ill_is_quiescent checks whether the ill is really quiescent.
5458 	 * Then make sure that threads that are waiting to enter the
5459 	 * ipsq have seen the error returned by ipsq_enter and have
5460 	 * gone away. Then we call ill_delete_tail which does the
5461 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5462 	 */
5463 	ill_delete(ill);
5464 	mutex_enter(&ill->ill_lock);
5465 	while (!ill_is_quiescent(ill))
5466 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5467 	while (ill->ill_waiters)
5468 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5469 
5470 	mutex_exit(&ill->ill_lock);
5471 
5472 	/*
5473 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5474 	 * it held until the end of the function since the cleanup
5475 	 * below needs to be able to use the ip_stack_t.
5476 	 */
5477 	netstack_hold(ipst->ips_netstack);
5478 
5479 	/* qprocsoff is called in ill_delete_tail */
5480 	ill_delete_tail(ill);
5481 	ASSERT(ill->ill_ipst == NULL);
5482 
5483 	/*
5484 	 * Walk through all upper (conn) streams and qenable
5485 	 * those that have queued data.
5486 	 * close synchronization needs this to
5487 	 * be done to ensure that all upper layers blocked
5488 	 * due to flow control to the closing device
5489 	 * get unblocked.
5490 	 */
5491 	ip1dbg(("ip_wsrv: walking\n"));
5492 	conn_walk_drain(ipst);
5493 
5494 	mutex_enter(&ipst->ips_ip_mi_lock);
5495 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5496 	mutex_exit(&ipst->ips_ip_mi_lock);
5497 
5498 	/*
5499 	 * credp could be null if the open didn't succeed and ip_modopen
5500 	 * itself calls ip_close.
5501 	 */
5502 	if (ill->ill_credp != NULL)
5503 		crfree(ill->ill_credp);
5504 
5505 	mutex_enter(&ill->ill_lock);
5506 	ill_nic_info_dispatch(ill);
5507 	mutex_exit(&ill->ill_lock);
5508 
5509 	/*
5510 	 * Now we are done with the module close pieces that
5511 	 * need the netstack_t.
5512 	 */
5513 	netstack_rele(ipst->ips_netstack);
5514 
5515 	mi_close_free((IDP)ill);
5516 	q->q_ptr = WR(q)->q_ptr = NULL;
5517 
5518 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5519 
5520 	return (0);
5521 }
5522 
5523 /*
5524  * This is called as part of close() for both IP and UDP
5525  * in order to quiesce the conn.
5526  */
5527 void
5528 ip_quiesce_conn(conn_t *connp)
5529 {
5530 	boolean_t	drain_cleanup_reqd = B_FALSE;
5531 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5532 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5533 	ip_stack_t	*ipst;
5534 
5535 	ASSERT(!IPCL_IS_TCP(connp));
5536 	ipst = connp->conn_netstack->netstack_ip;
5537 
5538 	/*
5539 	 * Mark the conn as closing, and this conn must not be
5540 	 * inserted in future into any list. Eg. conn_drain_insert(),
5541 	 * won't insert this conn into the conn_drain_list.
5542 	 * Similarly ill_pending_mp_add() will not add any mp to
5543 	 * the pending mp list, after this conn has started closing.
5544 	 *
5545 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5546 	 * cannot get set henceforth.
5547 	 */
5548 	mutex_enter(&connp->conn_lock);
5549 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5550 	connp->conn_state_flags |= CONN_CLOSING;
5551 	if (connp->conn_idl != NULL)
5552 		drain_cleanup_reqd = B_TRUE;
5553 	if (connp->conn_oper_pending_ill != NULL)
5554 		conn_ioctl_cleanup_reqd = B_TRUE;
5555 	if (connp->conn_ilg_inuse != 0)
5556 		ilg_cleanup_reqd = B_TRUE;
5557 	mutex_exit(&connp->conn_lock);
5558 
5559 	if (IPCL_IS_UDP(connp))
5560 		udp_quiesce_conn(connp);
5561 
5562 	if (conn_ioctl_cleanup_reqd)
5563 		conn_ioctl_cleanup(connp);
5564 
5565 	if (is_system_labeled() && connp->conn_anon_port) {
5566 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5567 		    connp->conn_mlp_type, connp->conn_ulp,
5568 		    ntohs(connp->conn_lport), B_FALSE);
5569 		connp->conn_anon_port = 0;
5570 	}
5571 	connp->conn_mlp_type = mlptSingle;
5572 
5573 	/*
5574 	 * Remove this conn from any fanout list it is on.
5575 	 * and then wait for any threads currently operating
5576 	 * on this endpoint to finish
5577 	 */
5578 	ipcl_hash_remove(connp);
5579 
5580 	/*
5581 	 * Remove this conn from the drain list, and do
5582 	 * any other cleanup that may be required.
5583 	 * (Only non-tcp streams may have a non-null conn_idl.
5584 	 * TCP streams are never flow controlled, and
5585 	 * conn_idl will be null)
5586 	 */
5587 	if (drain_cleanup_reqd)
5588 		conn_drain_tail(connp, B_TRUE);
5589 
5590 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5591 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5592 		(void) ip_mrouter_done(NULL, ipst);
5593 
5594 	if (ilg_cleanup_reqd)
5595 		ilg_delete_all(connp);
5596 
5597 	conn_delete_ire(connp, NULL);
5598 
5599 	/*
5600 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5601 	 * callers from write side can't be there now because close
5602 	 * is in progress. The only other caller is ipcl_walk
5603 	 * which checks for the condemned flag.
5604 	 */
5605 	mutex_enter(&connp->conn_lock);
5606 	connp->conn_state_flags |= CONN_CONDEMNED;
5607 	while (connp->conn_ref != 1)
5608 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5609 	connp->conn_state_flags |= CONN_QUIESCED;
5610 	mutex_exit(&connp->conn_lock);
5611 }
5612 
5613 /* ARGSUSED */
5614 int
5615 ip_close(queue_t *q, int flags)
5616 {
5617 	conn_t		*connp;
5618 
5619 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5620 
5621 	/*
5622 	 * Call the appropriate delete routine depending on whether this is
5623 	 * a module or device.
5624 	 */
5625 	if (WR(q)->q_next != NULL) {
5626 		/* This is a module close */
5627 		return (ip_modclose((ill_t *)q->q_ptr));
5628 	}
5629 
5630 	connp = q->q_ptr;
5631 	ip_quiesce_conn(connp);
5632 
5633 	qprocsoff(q);
5634 
5635 	/*
5636 	 * Now we are truly single threaded on this stream, and can
5637 	 * delete the things hanging off the connp, and finally the connp.
5638 	 * We removed this connp from the fanout list, it cannot be
5639 	 * accessed thru the fanouts, and we already waited for the
5640 	 * conn_ref to drop to 0. We are already in close, so
5641 	 * there cannot be any other thread from the top. qprocsoff
5642 	 * has completed, and service has completed or won't run in
5643 	 * future.
5644 	 */
5645 	ASSERT(connp->conn_ref == 1);
5646 
5647 	/*
5648 	 * A conn which was previously marked as IPCL_UDP cannot
5649 	 * retain the flag because it would have been cleared by
5650 	 * udp_close().
5651 	 */
5652 	ASSERT(!IPCL_IS_UDP(connp));
5653 
5654 	if (connp->conn_latch != NULL) {
5655 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5656 		connp->conn_latch = NULL;
5657 	}
5658 	if (connp->conn_policy != NULL) {
5659 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5660 		connp->conn_policy = NULL;
5661 	}
5662 	if (connp->conn_ipsec_opt_mp != NULL) {
5663 		freemsg(connp->conn_ipsec_opt_mp);
5664 		connp->conn_ipsec_opt_mp = NULL;
5665 	}
5666 
5667 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5668 
5669 	connp->conn_ref--;
5670 	ipcl_conn_destroy(connp);
5671 
5672 	q->q_ptr = WR(q)->q_ptr = NULL;
5673 	return (0);
5674 }
5675 
5676 int
5677 ip_snmpmod_close(queue_t *q)
5678 {
5679 	conn_t *connp = Q_TO_CONN(q);
5680 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5681 
5682 	qprocsoff(q);
5683 
5684 	if (connp->conn_flags & IPCL_UDPMOD)
5685 		udp_close_free(connp);
5686 
5687 	if (connp->conn_cred != NULL) {
5688 		crfree(connp->conn_cred);
5689 		connp->conn_cred = NULL;
5690 	}
5691 	CONN_DEC_REF(connp);
5692 	q->q_ptr = WR(q)->q_ptr = NULL;
5693 	return (0);
5694 }
5695 
5696 /*
5697  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5698  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5699  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5700  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5701  * queues as we never enqueue messages there and we don't handle any ioctls.
5702  * Everything else is freed.
5703  */
5704 void
5705 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5706 {
5707 	conn_t	*connp = q->q_ptr;
5708 	pfi_t	setfn;
5709 	pfi_t	getfn;
5710 
5711 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5712 
5713 	switch (DB_TYPE(mp)) {
5714 	case M_PROTO:
5715 	case M_PCPROTO:
5716 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5717 		    ((((union T_primitives *)mp->b_rptr)->type ==
5718 		    T_SVR4_OPTMGMT_REQ) ||
5719 		    (((union T_primitives *)mp->b_rptr)->type ==
5720 		    T_OPTMGMT_REQ))) {
5721 			/*
5722 			 * This is the only TPI primitive supported. Its
5723 			 * handling does not require tcp_t, but it does require
5724 			 * conn_t to check permissions.
5725 			 */
5726 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5727 
5728 			if (connp->conn_flags & IPCL_TCPMOD) {
5729 				setfn = tcp_snmp_set;
5730 				getfn = tcp_snmp_get;
5731 			} else {
5732 				setfn = udp_snmp_set;
5733 				getfn = udp_snmp_get;
5734 			}
5735 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5736 				freemsg(mp);
5737 				return;
5738 			}
5739 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5740 		    != NULL)
5741 			qreply(q, mp);
5742 		break;
5743 	case M_FLUSH:
5744 	case M_IOCTL:
5745 		putnext(q, mp);
5746 		break;
5747 	default:
5748 		freemsg(mp);
5749 		break;
5750 	}
5751 }
5752 
5753 /* Return the IP checksum for the IP header at "iph". */
5754 uint16_t
5755 ip_csum_hdr(ipha_t *ipha)
5756 {
5757 	uint16_t	*uph;
5758 	uint32_t	sum;
5759 	int		opt_len;
5760 
5761 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5762 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5763 	uph = (uint16_t *)ipha;
5764 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5765 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5766 	if (opt_len > 0) {
5767 		do {
5768 			sum += uph[10];
5769 			sum += uph[11];
5770 			uph += 2;
5771 		} while (--opt_len);
5772 	}
5773 	sum = (sum & 0xFFFF) + (sum >> 16);
5774 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5775 	if (sum == 0xffff)
5776 		sum = 0;
5777 	return ((uint16_t)sum);
5778 }
5779 
5780 /*
5781  * Called when the module is about to be unloaded
5782  */
5783 void
5784 ip_ddi_destroy(void)
5785 {
5786 	tnet_fini();
5787 
5788 	sctp_ddi_g_destroy();
5789 	tcp_ddi_g_destroy();
5790 	ipsec_policy_g_destroy();
5791 	ipcl_g_destroy();
5792 	ip_net_g_destroy();
5793 	ip_ire_g_fini();
5794 	inet_minor_destroy(ip_minor_arena);
5795 
5796 	netstack_unregister(NS_IP);
5797 }
5798 
5799 /*
5800  * First step in cleanup.
5801  */
5802 /* ARGSUSED */
5803 static void
5804 ip_stack_shutdown(netstackid_t stackid, void *arg)
5805 {
5806 	ip_stack_t *ipst = (ip_stack_t *)arg;
5807 
5808 #ifdef NS_DEBUG
5809 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5810 #endif
5811 
5812 	/* Get rid of loopback interfaces and their IREs */
5813 	ip_loopback_cleanup(ipst);
5814 }
5815 
5816 /*
5817  * Free the IP stack instance.
5818  */
5819 static void
5820 ip_stack_fini(netstackid_t stackid, void *arg)
5821 {
5822 	ip_stack_t *ipst = (ip_stack_t *)arg;
5823 	int ret;
5824 
5825 #ifdef NS_DEBUG
5826 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5827 #endif
5828 	ipv4_hook_destroy(ipst);
5829 	ipv6_hook_destroy(ipst);
5830 	ip_net_destroy(ipst);
5831 
5832 	rw_destroy(&ipst->ips_srcid_lock);
5833 
5834 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5835 	ipst->ips_ip_mibkp = NULL;
5836 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5837 	ipst->ips_icmp_mibkp = NULL;
5838 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5839 	ipst->ips_ip_kstat = NULL;
5840 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5841 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5842 	ipst->ips_ip6_kstat = NULL;
5843 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5844 
5845 	nd_free(&ipst->ips_ip_g_nd);
5846 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5847 	ipst->ips_param_arr = NULL;
5848 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5849 	ipst->ips_ndp_arr = NULL;
5850 
5851 	ip_mrouter_stack_destroy(ipst);
5852 
5853 	mutex_destroy(&ipst->ips_ip_mi_lock);
5854 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5855 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5856 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5857 
5858 	ret = untimeout(ipst->ips_igmp_timeout_id);
5859 	if (ret == -1) {
5860 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5861 	} else {
5862 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5863 		ipst->ips_igmp_timeout_id = 0;
5864 	}
5865 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5866 	if (ret == -1) {
5867 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5868 	} else {
5869 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5870 		ipst->ips_igmp_slowtimeout_id = 0;
5871 	}
5872 	ret = untimeout(ipst->ips_mld_timeout_id);
5873 	if (ret == -1) {
5874 		ASSERT(ipst->ips_mld_timeout_id == 0);
5875 	} else {
5876 		ASSERT(ipst->ips_mld_timeout_id != 0);
5877 		ipst->ips_mld_timeout_id = 0;
5878 	}
5879 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5880 	if (ret == -1) {
5881 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5882 	} else {
5883 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5884 		ipst->ips_mld_slowtimeout_id = 0;
5885 	}
5886 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5887 	if (ret == -1) {
5888 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5889 	} else {
5890 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5891 		ipst->ips_ip_ire_expire_id = 0;
5892 	}
5893 
5894 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5895 	mutex_destroy(&ipst->ips_mld_timer_lock);
5896 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5897 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5898 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5899 	rw_destroy(&ipst->ips_ill_g_lock);
5900 
5901 	ip_ire_fini(ipst);
5902 	ip6_asp_free(ipst);
5903 	conn_drain_fini(ipst);
5904 	ipcl_destroy(ipst);
5905 
5906 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5907 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5908 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5909 	ipst->ips_ndp4 = NULL;
5910 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5911 	ipst->ips_ndp6 = NULL;
5912 
5913 	if (ipst->ips_loopback_ksp != NULL) {
5914 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5915 		ipst->ips_loopback_ksp = NULL;
5916 	}
5917 
5918 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5919 	ipst->ips_phyint_g_list = NULL;
5920 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5921 	ipst->ips_ill_g_heads = NULL;
5922 
5923 	kmem_free(ipst, sizeof (*ipst));
5924 }
5925 
5926 /*
5927  * Called when the IP kernel module is loaded into the kernel
5928  */
5929 void
5930 ip_ddi_init(void)
5931 {
5932 	TCP6_MAJ = ddi_name_to_major(TCP6);
5933 	TCP_MAJ	= ddi_name_to_major(TCP);
5934 	SCTP_MAJ = ddi_name_to_major(SCTP);
5935 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5936 
5937 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5938 
5939 	/*
5940 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5941 	 * initial devices: ip, ip6, tcp, tcp6.
5942 	 */
5943 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5944 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5945 		cmn_err(CE_PANIC,
5946 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5947 	}
5948 
5949 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5950 
5951 	ipcl_g_init();
5952 	ip_ire_g_init();
5953 	ip_net_g_init();
5954 
5955 #ifdef ILL_DEBUG
5956 	/* Default cleanup function */
5957 	ip_cleanup_func = ip_thread_exit;
5958 #endif
5959 
5960 	/*
5961 	 * We want to be informed each time a stack is created or
5962 	 * destroyed in the kernel, so we can maintain the
5963 	 * set of udp_stack_t's.
5964 	 */
5965 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5966 	    ip_stack_fini);
5967 
5968 	ipsec_policy_g_init();
5969 	tcp_ddi_g_init();
5970 	sctp_ddi_g_init();
5971 
5972 	tnet_init();
5973 }
5974 
5975 /*
5976  * Initialize the IP stack instance.
5977  */
5978 static void *
5979 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5980 {
5981 	ip_stack_t	*ipst;
5982 	ipparam_t	*pa;
5983 	ipndp_t		*na;
5984 
5985 #ifdef NS_DEBUG
5986 	printf("ip_stack_init(stack %d)\n", stackid);
5987 #endif
5988 
5989 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5990 	ipst->ips_netstack = ns;
5991 
5992 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5993 	    KM_SLEEP);
5994 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5995 	    KM_SLEEP);
5996 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5997 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5998 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5999 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6000 
6001 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6002 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6003 	ipst->ips_igmp_deferred_next = INFINITY;
6004 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6005 	ipst->ips_mld_deferred_next = INFINITY;
6006 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6007 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6008 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6009 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6010 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6011 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6012 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6013 
6014 	ipcl_init(ipst);
6015 	ip_ire_init(ipst);
6016 	ip6_asp_init(ipst);
6017 	ipif_init(ipst);
6018 	conn_drain_init(ipst);
6019 	ip_mrouter_stack_init(ipst);
6020 
6021 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6022 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6023 
6024 	ipst->ips_ip_multirt_log_interval = 1000;
6025 
6026 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6027 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6028 	ipst->ips_ill_index = 1;
6029 
6030 	ipst->ips_saved_ip_g_forward = -1;
6031 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6032 
6033 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6034 	ipst->ips_param_arr = pa;
6035 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6036 
6037 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6038 	ipst->ips_ndp_arr = na;
6039 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6040 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6041 	    (caddr_t)&ipst->ips_ip_g_forward;
6042 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6043 	    (caddr_t)&ipst->ips_ipv6_forward;
6044 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6045 	    "ip_cgtp_filter") == 0);
6046 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6047 	    (caddr_t)&ip_cgtp_filter;
6048 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6049 	    "ipmp_hook_emulation") == 0);
6050 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6051 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6052 
6053 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6054 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6055 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6056 
6057 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6058 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6059 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6060 	ipst->ips_ip6_kstat =
6061 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6062 
6063 	ipst->ips_ipmp_enable_failback = B_TRUE;
6064 
6065 	ipst->ips_ip_src_id = 1;
6066 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6067 
6068 	ip_net_init(ipst, ns);
6069 	ipv4_hook_init(ipst);
6070 	ipv6_hook_init(ipst);
6071 
6072 	return (ipst);
6073 }
6074 
6075 /*
6076  * Allocate and initialize a DLPI template of the specified length.  (May be
6077  * called as writer.)
6078  */
6079 mblk_t *
6080 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6081 {
6082 	mblk_t	*mp;
6083 
6084 	mp = allocb(len, BPRI_MED);
6085 	if (!mp)
6086 		return (NULL);
6087 
6088 	/*
6089 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6090 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6091 	 * that other DLPI are M_PROTO.
6092 	 */
6093 	if (prim == DL_INFO_REQ) {
6094 		mp->b_datap->db_type = M_PCPROTO;
6095 	} else {
6096 		mp->b_datap->db_type = M_PROTO;
6097 	}
6098 
6099 	mp->b_wptr = mp->b_rptr + len;
6100 	bzero(mp->b_rptr, len);
6101 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6102 	return (mp);
6103 }
6104 
6105 const char *
6106 dlpi_prim_str(int prim)
6107 {
6108 	switch (prim) {
6109 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6110 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6111 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6112 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6113 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6114 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6115 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6116 	case DL_OK_ACK:		return ("DL_OK_ACK");
6117 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6118 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6119 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6120 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6121 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6122 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6123 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6124 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6125 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6126 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6127 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6128 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6129 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6130 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6131 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6132 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6133 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6134 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6135 	default:		return ("<unknown primitive>");
6136 	}
6137 }
6138 
6139 const char *
6140 dlpi_err_str(int err)
6141 {
6142 	switch (err) {
6143 	case DL_ACCESS:		return ("DL_ACCESS");
6144 	case DL_BADADDR:	return ("DL_BADADDR");
6145 	case DL_BADCORR:	return ("DL_BADCORR");
6146 	case DL_BADDATA:	return ("DL_BADDATA");
6147 	case DL_BADPPA:		return ("DL_BADPPA");
6148 	case DL_BADPRIM:	return ("DL_BADPRIM");
6149 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6150 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6151 	case DL_BADSAP:		return ("DL_BADSAP");
6152 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6153 	case DL_BOUND:		return ("DL_BOUND");
6154 	case DL_INITFAILED:	return ("DL_INITFAILED");
6155 	case DL_NOADDR:		return ("DL_NOADDR");
6156 	case DL_NOTINIT:	return ("DL_NOTINIT");
6157 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6158 	case DL_SYSERR:		return ("DL_SYSERR");
6159 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6160 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6161 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6162 	case DL_TOOMANY:	return ("DL_TOOMANY");
6163 	case DL_NOTENAB:	return ("DL_NOTENAB");
6164 	case DL_BUSY:		return ("DL_BUSY");
6165 	case DL_NOAUTO:		return ("DL_NOAUTO");
6166 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6167 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6168 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6169 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6170 	case DL_PENDING:	return ("DL_PENDING");
6171 	default:		return ("<unknown error>");
6172 	}
6173 }
6174 
6175 /*
6176  * Debug formatting routine.  Returns a character string representation of the
6177  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6178  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6179  *
6180  * Once the ndd table-printing interfaces are removed, this can be changed to
6181  * standard dotted-decimal form.
6182  */
6183 char *
6184 ip_dot_addr(ipaddr_t addr, char *buf)
6185 {
6186 	uint8_t *ap = (uint8_t *)&addr;
6187 
6188 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6189 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6190 	return (buf);
6191 }
6192 
6193 /*
6194  * Write the given MAC address as a printable string in the usual colon-
6195  * separated format.
6196  */
6197 const char *
6198 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6199 {
6200 	char *bp;
6201 
6202 	if (alen == 0 || buflen < 4)
6203 		return ("?");
6204 	bp = buf;
6205 	for (;;) {
6206 		/*
6207 		 * If there are more MAC address bytes available, but we won't
6208 		 * have any room to print them, then add "..." to the string
6209 		 * instead.  See below for the 'magic number' explanation.
6210 		 */
6211 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6212 			(void) strcpy(bp, "...");
6213 			break;
6214 		}
6215 		(void) sprintf(bp, "%02x", *addr++);
6216 		bp += 2;
6217 		if (--alen == 0)
6218 			break;
6219 		*bp++ = ':';
6220 		buflen -= 3;
6221 		/*
6222 		 * At this point, based on the first 'if' statement above,
6223 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6224 		 * buflen >= 4.  The first case leaves room for the final "xx"
6225 		 * number and trailing NUL byte.  The second leaves room for at
6226 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6227 		 * that statement.
6228 		 */
6229 	}
6230 	return (buf);
6231 }
6232 
6233 /*
6234  * Send an ICMP error after patching up the packet appropriately.  Returns
6235  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6236  */
6237 static boolean_t
6238 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6239     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6240     zoneid_t zoneid, ip_stack_t *ipst)
6241 {
6242 	ipha_t *ipha;
6243 	mblk_t *first_mp;
6244 	boolean_t secure;
6245 	unsigned char db_type;
6246 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6247 
6248 	first_mp = mp;
6249 	if (mctl_present) {
6250 		mp = mp->b_cont;
6251 		secure = ipsec_in_is_secure(first_mp);
6252 		ASSERT(mp != NULL);
6253 	} else {
6254 		/*
6255 		 * If this is an ICMP error being reported - which goes
6256 		 * up as M_CTLs, we need to convert them to M_DATA till
6257 		 * we finish checking with global policy because
6258 		 * ipsec_check_global_policy() assumes M_DATA as clear
6259 		 * and M_CTL as secure.
6260 		 */
6261 		db_type = DB_TYPE(mp);
6262 		DB_TYPE(mp) = M_DATA;
6263 		secure = B_FALSE;
6264 	}
6265 	/*
6266 	 * We are generating an icmp error for some inbound packet.
6267 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6268 	 * Before we generate an error, check with global policy
6269 	 * to see whether this is allowed to enter the system. As
6270 	 * there is no "conn", we are checking with global policy.
6271 	 */
6272 	ipha = (ipha_t *)mp->b_rptr;
6273 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6274 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6275 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6276 		if (first_mp == NULL)
6277 			return (B_FALSE);
6278 	}
6279 
6280 	if (!mctl_present)
6281 		DB_TYPE(mp) = db_type;
6282 
6283 	if (flags & IP_FF_SEND_ICMP) {
6284 		if (flags & IP_FF_HDR_COMPLETE) {
6285 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6286 				freemsg(first_mp);
6287 				return (B_TRUE);
6288 			}
6289 		}
6290 		if (flags & IP_FF_CKSUM) {
6291 			/*
6292 			 * Have to correct checksum since
6293 			 * the packet might have been
6294 			 * fragmented and the reassembly code in ip_rput
6295 			 * does not restore the IP checksum.
6296 			 */
6297 			ipha->ipha_hdr_checksum = 0;
6298 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6299 		}
6300 		switch (icmp_type) {
6301 		case ICMP_DEST_UNREACHABLE:
6302 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6303 			    ipst);
6304 			break;
6305 		default:
6306 			freemsg(first_mp);
6307 			break;
6308 		}
6309 	} else {
6310 		freemsg(first_mp);
6311 		return (B_FALSE);
6312 	}
6313 
6314 	return (B_TRUE);
6315 }
6316 
6317 /*
6318  * Used to send an ICMP error message when a packet is received for
6319  * a protocol that is not supported. The mblk passed as argument
6320  * is consumed by this function.
6321  */
6322 void
6323 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6324     ip_stack_t *ipst)
6325 {
6326 	mblk_t *mp;
6327 	ipha_t *ipha;
6328 	ill_t *ill;
6329 	ipsec_in_t *ii;
6330 
6331 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6332 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6333 
6334 	mp = ipsec_mp->b_cont;
6335 	ipsec_mp->b_cont = NULL;
6336 	ipha = (ipha_t *)mp->b_rptr;
6337 	/* Get ill from index in ipsec_in_t. */
6338 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6339 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6340 	    ipst);
6341 	if (ill != NULL) {
6342 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6343 			if (ip_fanout_send_icmp(q, mp, flags,
6344 			    ICMP_DEST_UNREACHABLE,
6345 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6346 				BUMP_MIB(ill->ill_ip_mib,
6347 				    ipIfStatsInUnknownProtos);
6348 			}
6349 		} else {
6350 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6351 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6352 			    0, B_FALSE, zoneid, ipst)) {
6353 				BUMP_MIB(ill->ill_ip_mib,
6354 				    ipIfStatsInUnknownProtos);
6355 			}
6356 		}
6357 		ill_refrele(ill);
6358 	} else { /* re-link for the freemsg() below. */
6359 		ipsec_mp->b_cont = mp;
6360 	}
6361 
6362 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6363 	freemsg(ipsec_mp);
6364 }
6365 
6366 /*
6367  * See if the inbound datagram has had IPsec processing applied to it.
6368  */
6369 boolean_t
6370 ipsec_in_is_secure(mblk_t *ipsec_mp)
6371 {
6372 	ipsec_in_t *ii;
6373 
6374 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6375 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6376 
6377 	if (ii->ipsec_in_loopback) {
6378 		return (ii->ipsec_in_secure);
6379 	} else {
6380 		return (ii->ipsec_in_ah_sa != NULL ||
6381 		    ii->ipsec_in_esp_sa != NULL ||
6382 		    ii->ipsec_in_decaps);
6383 	}
6384 }
6385 
6386 /*
6387  * Handle protocols with which IP is less intimate.  There
6388  * can be more than one stream bound to a particular
6389  * protocol.  When this is the case, normally each one gets a copy
6390  * of any incoming packets.
6391  *
6392  * IPSEC NOTE :
6393  *
6394  * Don't allow a secure packet going up a non-secure connection.
6395  * We don't allow this because
6396  *
6397  * 1) Reply might go out in clear which will be dropped at
6398  *    the sending side.
6399  * 2) If the reply goes out in clear it will give the
6400  *    adversary enough information for getting the key in
6401  *    most of the cases.
6402  *
6403  * Moreover getting a secure packet when we expect clear
6404  * implies that SA's were added without checking for
6405  * policy on both ends. This should not happen once ISAKMP
6406  * is used to negotiate SAs as SAs will be added only after
6407  * verifying the policy.
6408  *
6409  * NOTE : If the packet was tunneled and not multicast we only send
6410  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6411  * back to delivering packets to AF_INET6 raw sockets.
6412  *
6413  * IPQoS Notes:
6414  * Once we have determined the client, invoke IPPF processing.
6415  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6416  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6417  * ip_policy will be false.
6418  *
6419  * Zones notes:
6420  * Currently only applications in the global zone can create raw sockets for
6421  * protocols other than ICMP. So unlike the broadcast / multicast case of
6422  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6423  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6424  */
6425 static void
6426 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6427     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6428     zoneid_t zoneid)
6429 {
6430 	queue_t	*rq;
6431 	mblk_t	*mp1, *first_mp1;
6432 	uint_t	protocol = ipha->ipha_protocol;
6433 	ipaddr_t dst;
6434 	boolean_t one_only;
6435 	mblk_t *first_mp = mp;
6436 	boolean_t secure;
6437 	uint32_t ill_index;
6438 	conn_t	*connp, *first_connp, *next_connp;
6439 	connf_t	*connfp;
6440 	boolean_t shared_addr;
6441 	mib2_ipIfStatsEntry_t *mibptr;
6442 	ip_stack_t *ipst = recv_ill->ill_ipst;
6443 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6444 
6445 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6446 	if (mctl_present) {
6447 		mp = first_mp->b_cont;
6448 		secure = ipsec_in_is_secure(first_mp);
6449 		ASSERT(mp != NULL);
6450 	} else {
6451 		secure = B_FALSE;
6452 	}
6453 	dst = ipha->ipha_dst;
6454 	/*
6455 	 * If the packet was tunneled and not multicast we only send to it
6456 	 * the first match.
6457 	 */
6458 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6459 	    !CLASSD(dst));
6460 
6461 	shared_addr = (zoneid == ALL_ZONES);
6462 	if (shared_addr) {
6463 		/*
6464 		 * We don't allow multilevel ports for raw IP, so no need to
6465 		 * check for that here.
6466 		 */
6467 		zoneid = tsol_packet_to_zoneid(mp);
6468 	}
6469 
6470 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6471 	mutex_enter(&connfp->connf_lock);
6472 	connp = connfp->connf_head;
6473 	for (connp = connfp->connf_head; connp != NULL;
6474 	    connp = connp->conn_next) {
6475 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6476 		    zoneid) &&
6477 		    (!is_system_labeled() ||
6478 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6479 		    connp))) {
6480 			break;
6481 		}
6482 	}
6483 
6484 	if (connp == NULL || connp->conn_upq == NULL) {
6485 		/*
6486 		 * No one bound to these addresses.  Is
6487 		 * there a client that wants all
6488 		 * unclaimed datagrams?
6489 		 */
6490 		mutex_exit(&connfp->connf_lock);
6491 		/*
6492 		 * Check for IPPROTO_ENCAP...
6493 		 */
6494 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6495 			/*
6496 			 * If an IPsec mblk is here on a multicast
6497 			 * tunnel (using ip_mroute stuff), check policy here,
6498 			 * THEN ship off to ip_mroute_decap().
6499 			 *
6500 			 * BTW,  If I match a configured IP-in-IP
6501 			 * tunnel, this path will not be reached, and
6502 			 * ip_mroute_decap will never be called.
6503 			 */
6504 			first_mp = ipsec_check_global_policy(first_mp, connp,
6505 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6506 			if (first_mp != NULL) {
6507 				if (mctl_present)
6508 					freeb(first_mp);
6509 				ip_mroute_decap(q, mp, ill);
6510 			} /* Else we already freed everything! */
6511 		} else {
6512 			/*
6513 			 * Otherwise send an ICMP protocol unreachable.
6514 			 */
6515 			if (ip_fanout_send_icmp(q, first_mp, flags,
6516 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6517 			    mctl_present, zoneid, ipst)) {
6518 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6519 			}
6520 		}
6521 		return;
6522 	}
6523 	CONN_INC_REF(connp);
6524 	first_connp = connp;
6525 
6526 	/*
6527 	 * Only send message to one tunnel driver by immediately
6528 	 * terminating the loop.
6529 	 */
6530 	connp = one_only ? NULL : connp->conn_next;
6531 
6532 	for (;;) {
6533 		while (connp != NULL) {
6534 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6535 			    flags, zoneid) &&
6536 			    (!is_system_labeled() ||
6537 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6538 			    shared_addr, connp)))
6539 				break;
6540 			connp = connp->conn_next;
6541 		}
6542 
6543 		/*
6544 		 * Copy the packet.
6545 		 */
6546 		if (connp == NULL || connp->conn_upq == NULL ||
6547 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6548 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6549 			/*
6550 			 * No more interested clients or memory
6551 			 * allocation failed
6552 			 */
6553 			connp = first_connp;
6554 			break;
6555 		}
6556 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6557 		CONN_INC_REF(connp);
6558 		mutex_exit(&connfp->connf_lock);
6559 		rq = connp->conn_rq;
6560 		if (!canputnext(rq)) {
6561 			if (flags & IP_FF_RAWIP) {
6562 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6563 			} else {
6564 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6565 			}
6566 
6567 			freemsg(first_mp1);
6568 		} else {
6569 			/*
6570 			 * Don't enforce here if we're an actual tunnel -
6571 			 * let "tun" do it instead.
6572 			 */
6573 			if (!IPCL_IS_IPTUN(connp) &&
6574 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6575 			    secure)) {
6576 				first_mp1 = ipsec_check_inbound_policy
6577 				    (first_mp1, connp, ipha, NULL,
6578 				    mctl_present);
6579 			}
6580 			if (first_mp1 != NULL) {
6581 				int in_flags = 0;
6582 				/*
6583 				 * ip_fanout_proto also gets called from
6584 				 * icmp_inbound_error_fanout, in which case
6585 				 * the msg type is M_CTL.  Don't add info
6586 				 * in this case for the time being. In future
6587 				 * when there is a need for knowing the
6588 				 * inbound iface index for ICMP error msgs,
6589 				 * then this can be changed.
6590 				 */
6591 				if (connp->conn_recvif)
6592 					in_flags = IPF_RECVIF;
6593 				/*
6594 				 * The ULP may support IP_RECVPKTINFO for both
6595 				 * IP v4 and v6 so pass the appropriate argument
6596 				 * based on conn IP version.
6597 				 */
6598 				if (connp->conn_ip_recvpktinfo) {
6599 					if (connp->conn_af_isv6) {
6600 						/*
6601 						 * V6 only needs index
6602 						 */
6603 						in_flags |= IPF_RECVIF;
6604 					} else {
6605 						/*
6606 						 * V4 needs index +
6607 						 * matching address.
6608 						 */
6609 						in_flags |= IPF_RECVADDR;
6610 					}
6611 				}
6612 				if ((in_flags != 0) &&
6613 				    (mp->b_datap->db_type != M_CTL)) {
6614 					/*
6615 					 * the actual data will be
6616 					 * contained in b_cont upon
6617 					 * successful return of the
6618 					 * following call else
6619 					 * original mblk is returned
6620 					 */
6621 					ASSERT(recv_ill != NULL);
6622 					mp1 = ip_add_info(mp1, recv_ill,
6623 					    in_flags, IPCL_ZONEID(connp), ipst);
6624 				}
6625 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6626 				if (mctl_present)
6627 					freeb(first_mp1);
6628 				putnext(rq, mp1);
6629 			}
6630 		}
6631 		mutex_enter(&connfp->connf_lock);
6632 		/* Follow the next pointer before releasing the conn. */
6633 		next_connp = connp->conn_next;
6634 		CONN_DEC_REF(connp);
6635 		connp = next_connp;
6636 	}
6637 
6638 	/* Last one.  Send it upstream. */
6639 	mutex_exit(&connfp->connf_lock);
6640 
6641 	/*
6642 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6643 	 * will be set to false.
6644 	 */
6645 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6646 		ill_index = ill->ill_phyint->phyint_ifindex;
6647 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6648 		if (mp == NULL) {
6649 			CONN_DEC_REF(connp);
6650 			if (mctl_present) {
6651 				freeb(first_mp);
6652 			}
6653 			return;
6654 		}
6655 	}
6656 
6657 	rq = connp->conn_rq;
6658 	if (!canputnext(rq)) {
6659 		if (flags & IP_FF_RAWIP) {
6660 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6661 		} else {
6662 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6663 		}
6664 
6665 		freemsg(first_mp);
6666 	} else {
6667 		if (IPCL_IS_IPTUN(connp)) {
6668 			/*
6669 			 * Tunneled packet.  We enforce policy in the tunnel
6670 			 * module itself.
6671 			 *
6672 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6673 			 * a policy check.
6674 			 */
6675 			putnext(rq, first_mp);
6676 			CONN_DEC_REF(connp);
6677 			return;
6678 		}
6679 
6680 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6681 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6682 			    ipha, NULL, mctl_present);
6683 		}
6684 
6685 		if (first_mp != NULL) {
6686 			int in_flags = 0;
6687 
6688 			/*
6689 			 * ip_fanout_proto also gets called
6690 			 * from icmp_inbound_error_fanout, in
6691 			 * which case the msg type is M_CTL.
6692 			 * Don't add info in this case for time
6693 			 * being. In future when there is a
6694 			 * need for knowing the inbound iface
6695 			 * index for ICMP error msgs, then this
6696 			 * can be changed
6697 			 */
6698 			if (connp->conn_recvif)
6699 				in_flags = IPF_RECVIF;
6700 			if (connp->conn_ip_recvpktinfo) {
6701 				if (connp->conn_af_isv6) {
6702 					/*
6703 					 * V6 only needs index
6704 					 */
6705 					in_flags |= IPF_RECVIF;
6706 				} else {
6707 					/*
6708 					 * V4 needs index +
6709 					 * matching address.
6710 					 */
6711 					in_flags |= IPF_RECVADDR;
6712 				}
6713 			}
6714 			if ((in_flags != 0) &&
6715 			    (mp->b_datap->db_type != M_CTL)) {
6716 
6717 				/*
6718 				 * the actual data will be contained in
6719 				 * b_cont upon successful return
6720 				 * of the following call else original
6721 				 * mblk is returned
6722 				 */
6723 				ASSERT(recv_ill != NULL);
6724 				mp = ip_add_info(mp, recv_ill,
6725 				    in_flags, IPCL_ZONEID(connp), ipst);
6726 			}
6727 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6728 			putnext(rq, mp);
6729 			if (mctl_present)
6730 				freeb(first_mp);
6731 		}
6732 	}
6733 	CONN_DEC_REF(connp);
6734 }
6735 
6736 /*
6737  * Fanout for TCP packets
6738  * The caller puts <fport, lport> in the ports parameter.
6739  *
6740  * IPQoS Notes
6741  * Before sending it to the client, invoke IPPF processing.
6742  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6743  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6744  * ip_policy is false.
6745  */
6746 static void
6747 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6748     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6749 {
6750 	mblk_t  *first_mp;
6751 	boolean_t secure;
6752 	uint32_t ill_index;
6753 	int	ip_hdr_len;
6754 	tcph_t	*tcph;
6755 	boolean_t syn_present = B_FALSE;
6756 	conn_t	*connp;
6757 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6758 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6759 
6760 	ASSERT(recv_ill != NULL);
6761 
6762 	first_mp = mp;
6763 	if (mctl_present) {
6764 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6765 		mp = first_mp->b_cont;
6766 		secure = ipsec_in_is_secure(first_mp);
6767 		ASSERT(mp != NULL);
6768 	} else {
6769 		secure = B_FALSE;
6770 	}
6771 
6772 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6773 
6774 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6775 	    zoneid, ipst)) == NULL) {
6776 		/*
6777 		 * No connected connection or listener. Send a
6778 		 * TH_RST via tcp_xmit_listeners_reset.
6779 		 */
6780 
6781 		/* Initiate IPPf processing, if needed. */
6782 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6783 			uint32_t ill_index;
6784 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6785 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6786 			if (first_mp == NULL)
6787 				return;
6788 		}
6789 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6790 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6791 		    zoneid));
6792 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6793 		    ipst->ips_netstack->netstack_tcp);
6794 		return;
6795 	}
6796 
6797 	/*
6798 	 * Allocate the SYN for the TCP connection here itself
6799 	 */
6800 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6801 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6802 		if (IPCL_IS_TCP(connp)) {
6803 			squeue_t *sqp;
6804 
6805 			/*
6806 			 * For fused tcp loopback, assign the eager's
6807 			 * squeue to be that of the active connect's.
6808 			 * Note that we don't check for IP_FF_LOOPBACK
6809 			 * here since this routine gets called only
6810 			 * for loopback (unlike the IPv6 counterpart).
6811 			 */
6812 			ASSERT(Q_TO_CONN(q) != NULL);
6813 			if (do_tcp_fusion &&
6814 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6815 			    !secure &&
6816 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6817 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6818 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6819 				sqp = Q_TO_CONN(q)->conn_sqp;
6820 			} else {
6821 				sqp = IP_SQUEUE_GET(lbolt);
6822 			}
6823 
6824 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6825 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6826 			syn_present = B_TRUE;
6827 		}
6828 	}
6829 
6830 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6831 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6832 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6833 		if ((flags & TH_RST) || (flags & TH_URG)) {
6834 			CONN_DEC_REF(connp);
6835 			freemsg(first_mp);
6836 			return;
6837 		}
6838 		if (flags & TH_ACK) {
6839 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6840 			    ipst->ips_netstack->netstack_tcp);
6841 			CONN_DEC_REF(connp);
6842 			return;
6843 		}
6844 
6845 		CONN_DEC_REF(connp);
6846 		freemsg(first_mp);
6847 		return;
6848 	}
6849 
6850 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6851 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6852 		    NULL, mctl_present);
6853 		if (first_mp == NULL) {
6854 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6855 			CONN_DEC_REF(connp);
6856 			return;
6857 		}
6858 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6859 			ASSERT(syn_present);
6860 			if (mctl_present) {
6861 				ASSERT(first_mp != mp);
6862 				first_mp->b_datap->db_struioflag |=
6863 				    STRUIO_POLICY;
6864 			} else {
6865 				ASSERT(first_mp == mp);
6866 				mp->b_datap->db_struioflag &=
6867 				    ~STRUIO_EAGER;
6868 				mp->b_datap->db_struioflag |=
6869 				    STRUIO_POLICY;
6870 			}
6871 		} else {
6872 			/*
6873 			 * Discard first_mp early since we're dealing with a
6874 			 * fully-connected conn_t and tcp doesn't do policy in
6875 			 * this case.
6876 			 */
6877 			if (mctl_present) {
6878 				freeb(first_mp);
6879 				mctl_present = B_FALSE;
6880 			}
6881 			first_mp = mp;
6882 		}
6883 	}
6884 
6885 	/*
6886 	 * Initiate policy processing here if needed. If we get here from
6887 	 * icmp_inbound_error_fanout, ip_policy is false.
6888 	 */
6889 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6890 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6891 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6892 		if (mp == NULL) {
6893 			CONN_DEC_REF(connp);
6894 			if (mctl_present)
6895 				freeb(first_mp);
6896 			return;
6897 		} else if (mctl_present) {
6898 			ASSERT(first_mp != mp);
6899 			first_mp->b_cont = mp;
6900 		} else {
6901 			first_mp = mp;
6902 		}
6903 	}
6904 
6905 
6906 
6907 	/* Handle socket options. */
6908 	if (!syn_present &&
6909 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6910 		/* Add header */
6911 		ASSERT(recv_ill != NULL);
6912 		/*
6913 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6914 		 * IPF_RECVIF.
6915 		 */
6916 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6917 		    ipst);
6918 		if (mp == NULL) {
6919 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6920 			CONN_DEC_REF(connp);
6921 			if (mctl_present)
6922 				freeb(first_mp);
6923 			return;
6924 		} else if (mctl_present) {
6925 			/*
6926 			 * ip_add_info might return a new mp.
6927 			 */
6928 			ASSERT(first_mp != mp);
6929 			first_mp->b_cont = mp;
6930 		} else {
6931 			first_mp = mp;
6932 		}
6933 	}
6934 
6935 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6936 	if (IPCL_IS_TCP(connp)) {
6937 		(*ip_input_proc)(connp->conn_sqp, first_mp,
6938 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6939 	} else {
6940 		putnext(connp->conn_rq, first_mp);
6941 		CONN_DEC_REF(connp);
6942 	}
6943 }
6944 
6945 /*
6946  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6947  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6948  * Caller is responsible for dropping references to the conn, and freeing
6949  * first_mp.
6950  *
6951  * IPQoS Notes
6952  * Before sending it to the client, invoke IPPF processing. Policy processing
6953  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6954  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6955  * ip_wput_local, ip_policy is false.
6956  */
6957 static void
6958 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6959     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6960     boolean_t ip_policy)
6961 {
6962 	boolean_t	mctl_present = (first_mp != NULL);
6963 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6964 	uint32_t	ill_index;
6965 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6966 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6967 
6968 	ASSERT(ill != NULL);
6969 
6970 	if (mctl_present)
6971 		first_mp->b_cont = mp;
6972 	else
6973 		first_mp = mp;
6974 
6975 	if (CONN_UDP_FLOWCTLD(connp)) {
6976 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6977 		freemsg(first_mp);
6978 		return;
6979 	}
6980 
6981 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6982 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6983 		    NULL, mctl_present);
6984 		if (first_mp == NULL) {
6985 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6986 			return;	/* Freed by ipsec_check_inbound_policy(). */
6987 		}
6988 	}
6989 	if (mctl_present)
6990 		freeb(first_mp);
6991 
6992 	/* Handle options. */
6993 	if (connp->conn_recvif)
6994 		in_flags = IPF_RECVIF;
6995 	/*
6996 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6997 	 * passed to ip_add_info is based on IP version of connp.
6998 	 */
6999 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7000 		if (connp->conn_af_isv6) {
7001 			/*
7002 			 * V6 only needs index
7003 			 */
7004 			in_flags |= IPF_RECVIF;
7005 		} else {
7006 			/*
7007 			 * V4 needs index + matching address.
7008 			 */
7009 			in_flags |= IPF_RECVADDR;
7010 		}
7011 	}
7012 
7013 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7014 		in_flags |= IPF_RECVSLLA;
7015 
7016 	/*
7017 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7018 	 * freed if the packet is dropped. The caller will do so.
7019 	 */
7020 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7021 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7022 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7023 		if (mp == NULL) {
7024 			return;
7025 		}
7026 	}
7027 	if ((in_flags != 0) &&
7028 	    (mp->b_datap->db_type != M_CTL)) {
7029 		/*
7030 		 * The actual data will be contained in b_cont
7031 		 * upon successful return of the following call
7032 		 * else original mblk is returned
7033 		 */
7034 		ASSERT(recv_ill != NULL);
7035 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7036 		    ipst);
7037 	}
7038 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7039 	/* Send it upstream */
7040 	CONN_UDP_RECV(connp, mp);
7041 }
7042 
7043 /*
7044  * Fanout for UDP packets.
7045  * The caller puts <fport, lport> in the ports parameter.
7046  *
7047  * If SO_REUSEADDR is set all multicast and broadcast packets
7048  * will be delivered to all streams bound to the same port.
7049  *
7050  * Zones notes:
7051  * Multicast and broadcast packets will be distributed to streams in all zones.
7052  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7053  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7054  * packets. To maintain this behavior with multiple zones, the conns are grouped
7055  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7056  * each zone. If unset, all the following conns in the same zone are skipped.
7057  */
7058 static void
7059 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7060     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7061     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7062 {
7063 	uint32_t	dstport, srcport;
7064 	ipaddr_t	dst;
7065 	mblk_t		*first_mp;
7066 	boolean_t	secure;
7067 	in6_addr_t	v6src;
7068 	conn_t		*connp;
7069 	connf_t		*connfp;
7070 	conn_t		*first_connp;
7071 	conn_t		*next_connp;
7072 	mblk_t		*mp1, *first_mp1;
7073 	ipaddr_t	src;
7074 	zoneid_t	last_zoneid;
7075 	boolean_t	reuseaddr;
7076 	boolean_t	shared_addr;
7077 	ip_stack_t	*ipst;
7078 
7079 	ASSERT(recv_ill != NULL);
7080 	ipst = recv_ill->ill_ipst;
7081 
7082 	first_mp = mp;
7083 	if (mctl_present) {
7084 		mp = first_mp->b_cont;
7085 		first_mp->b_cont = NULL;
7086 		secure = ipsec_in_is_secure(first_mp);
7087 		ASSERT(mp != NULL);
7088 	} else {
7089 		first_mp = NULL;
7090 		secure = B_FALSE;
7091 	}
7092 
7093 	/* Extract ports in net byte order */
7094 	dstport = htons(ntohl(ports) & 0xFFFF);
7095 	srcport = htons(ntohl(ports) >> 16);
7096 	dst = ipha->ipha_dst;
7097 	src = ipha->ipha_src;
7098 
7099 	shared_addr = (zoneid == ALL_ZONES);
7100 	if (shared_addr) {
7101 		/*
7102 		 * No need to handle exclusive-stack zones since ALL_ZONES
7103 		 * only applies to the shared stack.
7104 		 */
7105 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7106 		if (zoneid == ALL_ZONES)
7107 			zoneid = tsol_packet_to_zoneid(mp);
7108 	}
7109 
7110 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7111 	mutex_enter(&connfp->connf_lock);
7112 	connp = connfp->connf_head;
7113 	if (!broadcast && !CLASSD(dst)) {
7114 		/*
7115 		 * Not broadcast or multicast. Send to the one (first)
7116 		 * client we find. No need to check conn_wantpacket()
7117 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7118 		 * IPv4 unicast packets.
7119 		 */
7120 		while ((connp != NULL) &&
7121 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7122 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7123 			connp = connp->conn_next;
7124 		}
7125 
7126 		if (connp == NULL || connp->conn_upq == NULL)
7127 			goto notfound;
7128 
7129 		if (is_system_labeled() &&
7130 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7131 		    connp))
7132 			goto notfound;
7133 
7134 		CONN_INC_REF(connp);
7135 		mutex_exit(&connfp->connf_lock);
7136 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7137 		    flags, recv_ill, ip_policy);
7138 		IP_STAT(ipst, ip_udp_fannorm);
7139 		CONN_DEC_REF(connp);
7140 		return;
7141 	}
7142 
7143 	/*
7144 	 * Broadcast and multicast case
7145 	 *
7146 	 * Need to check conn_wantpacket().
7147 	 * If SO_REUSEADDR has been set on the first we send the
7148 	 * packet to all clients that have joined the group and
7149 	 * match the port.
7150 	 */
7151 
7152 	while (connp != NULL) {
7153 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7154 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7155 		    (!is_system_labeled() ||
7156 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7157 		    connp)))
7158 			break;
7159 		connp = connp->conn_next;
7160 	}
7161 
7162 	if (connp == NULL || connp->conn_upq == NULL)
7163 		goto notfound;
7164 
7165 	first_connp = connp;
7166 	/*
7167 	 * When SO_REUSEADDR is not set, send the packet only to the first
7168 	 * matching connection in its zone by keeping track of the zoneid.
7169 	 */
7170 	reuseaddr = first_connp->conn_reuseaddr;
7171 	last_zoneid = first_connp->conn_zoneid;
7172 
7173 	CONN_INC_REF(connp);
7174 	connp = connp->conn_next;
7175 	for (;;) {
7176 		while (connp != NULL) {
7177 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7178 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7179 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7180 			    (!is_system_labeled() ||
7181 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7182 			    shared_addr, connp)))
7183 				break;
7184 			connp = connp->conn_next;
7185 		}
7186 		/*
7187 		 * Just copy the data part alone. The mctl part is
7188 		 * needed just for verifying policy and it is never
7189 		 * sent up.
7190 		 */
7191 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7192 		    ((mp1 = copymsg(mp)) == NULL))) {
7193 			/*
7194 			 * No more interested clients or memory
7195 			 * allocation failed
7196 			 */
7197 			connp = first_connp;
7198 			break;
7199 		}
7200 		if (connp->conn_zoneid != last_zoneid) {
7201 			/*
7202 			 * Update the zoneid so that the packet isn't sent to
7203 			 * any more conns in the same zone unless SO_REUSEADDR
7204 			 * is set.
7205 			 */
7206 			reuseaddr = connp->conn_reuseaddr;
7207 			last_zoneid = connp->conn_zoneid;
7208 		}
7209 		if (first_mp != NULL) {
7210 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7211 			    ipsec_info_type == IPSEC_IN);
7212 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7213 			    ipst->ips_netstack);
7214 			if (first_mp1 == NULL) {
7215 				freemsg(mp1);
7216 				connp = first_connp;
7217 				break;
7218 			}
7219 		} else {
7220 			first_mp1 = NULL;
7221 		}
7222 		CONN_INC_REF(connp);
7223 		mutex_exit(&connfp->connf_lock);
7224 		/*
7225 		 * IPQoS notes: We don't send the packet for policy
7226 		 * processing here, will do it for the last one (below).
7227 		 * i.e. we do it per-packet now, but if we do policy
7228 		 * processing per-conn, then we would need to do it
7229 		 * here too.
7230 		 */
7231 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7232 		    ipha, flags, recv_ill, B_FALSE);
7233 		mutex_enter(&connfp->connf_lock);
7234 		/* Follow the next pointer before releasing the conn. */
7235 		next_connp = connp->conn_next;
7236 		IP_STAT(ipst, ip_udp_fanmb);
7237 		CONN_DEC_REF(connp);
7238 		connp = next_connp;
7239 	}
7240 
7241 	/* Last one.  Send it upstream. */
7242 	mutex_exit(&connfp->connf_lock);
7243 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7244 	    recv_ill, ip_policy);
7245 	IP_STAT(ipst, ip_udp_fanmb);
7246 	CONN_DEC_REF(connp);
7247 	return;
7248 
7249 notfound:
7250 
7251 	mutex_exit(&connfp->connf_lock);
7252 	IP_STAT(ipst, ip_udp_fanothers);
7253 	/*
7254 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7255 	 * have already been matched above, since they live in the IPv4
7256 	 * fanout tables. This implies we only need to
7257 	 * check for IPv6 in6addr_any endpoints here.
7258 	 * Thus we compare using ipv6_all_zeros instead of the destination
7259 	 * address, except for the multicast group membership lookup which
7260 	 * uses the IPv4 destination.
7261 	 */
7262 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7263 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7264 	mutex_enter(&connfp->connf_lock);
7265 	connp = connfp->connf_head;
7266 	if (!broadcast && !CLASSD(dst)) {
7267 		while (connp != NULL) {
7268 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7269 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7270 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7271 			    !connp->conn_ipv6_v6only)
7272 				break;
7273 			connp = connp->conn_next;
7274 		}
7275 
7276 		if (connp != NULL && is_system_labeled() &&
7277 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7278 		    connp))
7279 			connp = NULL;
7280 
7281 		if (connp == NULL || connp->conn_upq == NULL) {
7282 			/*
7283 			 * No one bound to this port.  Is
7284 			 * there a client that wants all
7285 			 * unclaimed datagrams?
7286 			 */
7287 			mutex_exit(&connfp->connf_lock);
7288 
7289 			if (mctl_present)
7290 				first_mp->b_cont = mp;
7291 			else
7292 				first_mp = mp;
7293 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7294 			    connf_head != NULL) {
7295 				ip_fanout_proto(q, first_mp, ill, ipha,
7296 				    flags | IP_FF_RAWIP, mctl_present,
7297 				    ip_policy, recv_ill, zoneid);
7298 			} else {
7299 				if (ip_fanout_send_icmp(q, first_mp, flags,
7300 				    ICMP_DEST_UNREACHABLE,
7301 				    ICMP_PORT_UNREACHABLE,
7302 				    mctl_present, zoneid, ipst)) {
7303 					BUMP_MIB(ill->ill_ip_mib,
7304 					    udpIfStatsNoPorts);
7305 				}
7306 			}
7307 			return;
7308 		}
7309 
7310 		CONN_INC_REF(connp);
7311 		mutex_exit(&connfp->connf_lock);
7312 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7313 		    flags, recv_ill, ip_policy);
7314 		CONN_DEC_REF(connp);
7315 		return;
7316 	}
7317 	/*
7318 	 * IPv4 multicast packet being delivered to an AF_INET6
7319 	 * in6addr_any endpoint.
7320 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7321 	 * and not conn_wantpacket_v6() since any multicast membership is
7322 	 * for an IPv4-mapped multicast address.
7323 	 * The packet is sent to all clients in all zones that have joined the
7324 	 * group and match the port.
7325 	 */
7326 	while (connp != NULL) {
7327 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7328 		    srcport, v6src) &&
7329 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7330 		    (!is_system_labeled() ||
7331 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7332 		    connp)))
7333 			break;
7334 		connp = connp->conn_next;
7335 	}
7336 
7337 	if (connp == NULL || connp->conn_upq == NULL) {
7338 		/*
7339 		 * No one bound to this port.  Is
7340 		 * there a client that wants all
7341 		 * unclaimed datagrams?
7342 		 */
7343 		mutex_exit(&connfp->connf_lock);
7344 
7345 		if (mctl_present)
7346 			first_mp->b_cont = mp;
7347 		else
7348 			first_mp = mp;
7349 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7350 		    NULL) {
7351 			ip_fanout_proto(q, first_mp, ill, ipha,
7352 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7353 			    recv_ill, zoneid);
7354 		} else {
7355 			/*
7356 			 * We used to attempt to send an icmp error here, but
7357 			 * since this is known to be a multicast packet
7358 			 * and we don't send icmp errors in response to
7359 			 * multicast, just drop the packet and give up sooner.
7360 			 */
7361 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7362 			freemsg(first_mp);
7363 		}
7364 		return;
7365 	}
7366 
7367 	first_connp = connp;
7368 
7369 	CONN_INC_REF(connp);
7370 	connp = connp->conn_next;
7371 	for (;;) {
7372 		while (connp != NULL) {
7373 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7374 			    ipv6_all_zeros, srcport, v6src) &&
7375 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7376 			    (!is_system_labeled() ||
7377 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7378 			    shared_addr, connp)))
7379 				break;
7380 			connp = connp->conn_next;
7381 		}
7382 		/*
7383 		 * Just copy the data part alone. The mctl part is
7384 		 * needed just for verifying policy and it is never
7385 		 * sent up.
7386 		 */
7387 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7388 		    ((mp1 = copymsg(mp)) == NULL))) {
7389 			/*
7390 			 * No more intested clients or memory
7391 			 * allocation failed
7392 			 */
7393 			connp = first_connp;
7394 			break;
7395 		}
7396 		if (first_mp != NULL) {
7397 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7398 			    ipsec_info_type == IPSEC_IN);
7399 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7400 			    ipst->ips_netstack);
7401 			if (first_mp1 == NULL) {
7402 				freemsg(mp1);
7403 				connp = first_connp;
7404 				break;
7405 			}
7406 		} else {
7407 			first_mp1 = NULL;
7408 		}
7409 		CONN_INC_REF(connp);
7410 		mutex_exit(&connfp->connf_lock);
7411 		/*
7412 		 * IPQoS notes: We don't send the packet for policy
7413 		 * processing here, will do it for the last one (below).
7414 		 * i.e. we do it per-packet now, but if we do policy
7415 		 * processing per-conn, then we would need to do it
7416 		 * here too.
7417 		 */
7418 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7419 		    ipha, flags, recv_ill, B_FALSE);
7420 		mutex_enter(&connfp->connf_lock);
7421 		/* Follow the next pointer before releasing the conn. */
7422 		next_connp = connp->conn_next;
7423 		CONN_DEC_REF(connp);
7424 		connp = next_connp;
7425 	}
7426 
7427 	/* Last one.  Send it upstream. */
7428 	mutex_exit(&connfp->connf_lock);
7429 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7430 	    recv_ill, ip_policy);
7431 	CONN_DEC_REF(connp);
7432 }
7433 
7434 /*
7435  * Complete the ip_wput header so that it
7436  * is possible to generate ICMP
7437  * errors.
7438  */
7439 int
7440 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7441 {
7442 	ire_t *ire;
7443 
7444 	if (ipha->ipha_src == INADDR_ANY) {
7445 		ire = ire_lookup_local(zoneid, ipst);
7446 		if (ire == NULL) {
7447 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7448 			return (1);
7449 		}
7450 		ipha->ipha_src = ire->ire_addr;
7451 		ire_refrele(ire);
7452 	}
7453 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7454 	ipha->ipha_hdr_checksum = 0;
7455 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7456 	return (0);
7457 }
7458 
7459 /*
7460  * Nobody should be sending
7461  * packets up this stream
7462  */
7463 static void
7464 ip_lrput(queue_t *q, mblk_t *mp)
7465 {
7466 	mblk_t *mp1;
7467 
7468 	switch (mp->b_datap->db_type) {
7469 	case M_FLUSH:
7470 		/* Turn around */
7471 		if (*mp->b_rptr & FLUSHW) {
7472 			*mp->b_rptr &= ~FLUSHR;
7473 			qreply(q, mp);
7474 			return;
7475 		}
7476 		break;
7477 	}
7478 	/* Could receive messages that passed through ar_rput */
7479 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7480 		mp1->b_prev = mp1->b_next = NULL;
7481 	freemsg(mp);
7482 }
7483 
7484 /* Nobody should be sending packets down this stream */
7485 /* ARGSUSED */
7486 void
7487 ip_lwput(queue_t *q, mblk_t *mp)
7488 {
7489 	freemsg(mp);
7490 }
7491 
7492 /*
7493  * Move the first hop in any source route to ipha_dst and remove that part of
7494  * the source route.  Called by other protocols.  Errors in option formatting
7495  * are ignored - will be handled by ip_wput_options Return the final
7496  * destination (either ipha_dst or the last entry in a source route.)
7497  */
7498 ipaddr_t
7499 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7500 {
7501 	ipoptp_t	opts;
7502 	uchar_t		*opt;
7503 	uint8_t		optval;
7504 	uint8_t		optlen;
7505 	ipaddr_t	dst;
7506 	int		i;
7507 	ire_t		*ire;
7508 	ip_stack_t	*ipst = ns->netstack_ip;
7509 
7510 	ip2dbg(("ip_massage_options\n"));
7511 	dst = ipha->ipha_dst;
7512 	for (optval = ipoptp_first(&opts, ipha);
7513 	    optval != IPOPT_EOL;
7514 	    optval = ipoptp_next(&opts)) {
7515 		opt = opts.ipoptp_cur;
7516 		switch (optval) {
7517 			uint8_t off;
7518 		case IPOPT_SSRR:
7519 		case IPOPT_LSRR:
7520 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7521 				ip1dbg(("ip_massage_options: bad src route\n"));
7522 				break;
7523 			}
7524 			optlen = opts.ipoptp_len;
7525 			off = opt[IPOPT_OFFSET];
7526 			off--;
7527 		redo_srr:
7528 			if (optlen < IP_ADDR_LEN ||
7529 			    off > optlen - IP_ADDR_LEN) {
7530 				/* End of source route */
7531 				ip1dbg(("ip_massage_options: end of SR\n"));
7532 				break;
7533 			}
7534 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7535 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7536 			    ntohl(dst)));
7537 			/*
7538 			 * Check if our address is present more than
7539 			 * once as consecutive hops in source route.
7540 			 * XXX verify per-interface ip_forwarding
7541 			 * for source route?
7542 			 */
7543 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7544 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7545 			if (ire != NULL) {
7546 				ire_refrele(ire);
7547 				off += IP_ADDR_LEN;
7548 				goto redo_srr;
7549 			}
7550 			if (dst == htonl(INADDR_LOOPBACK)) {
7551 				ip1dbg(("ip_massage_options: loopback addr in "
7552 				    "source route!\n"));
7553 				break;
7554 			}
7555 			/*
7556 			 * Update ipha_dst to be the first hop and remove the
7557 			 * first hop from the source route (by overwriting
7558 			 * part of the option with NOP options).
7559 			 */
7560 			ipha->ipha_dst = dst;
7561 			/* Put the last entry in dst */
7562 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7563 			    3;
7564 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7565 
7566 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7567 			    ntohl(dst)));
7568 			/* Move down and overwrite */
7569 			opt[IP_ADDR_LEN] = opt[0];
7570 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7571 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7572 			for (i = 0; i < IP_ADDR_LEN; i++)
7573 				opt[i] = IPOPT_NOP;
7574 			break;
7575 		}
7576 	}
7577 	return (dst);
7578 }
7579 
7580 /*
7581  * This function's job is to forward data to the reverse tunnel (FA->HA)
7582  * after doing a few checks. It is assumed that the incoming interface
7583  * of the packet is always different than the outgoing interface and the
7584  * ire_type of the found ire has to be a non-resolver type.
7585  *
7586  * IPQoS notes
7587  * IP policy is invoked twice for a forwarded packet, once on the read side
7588  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7589  * enabled.
7590  */
7591 static void
7592 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7593 {
7594 	ipha_t		*ipha;
7595 	queue_t		*q;
7596 	uint32_t 	pkt_len;
7597 #define	rptr    ((uchar_t *)ipha)
7598 	uint32_t 	sum;
7599 	uint32_t 	max_frag;
7600 	mblk_t		*first_mp;
7601 	uint32_t	ill_index;
7602 	ipxmit_state_t	pktxmit_state;
7603 	ill_t		*out_ill;
7604 	ip_stack_t	*ipst = in_ill->ill_ipst;
7605 
7606 	ASSERT(ire != NULL);
7607 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7608 	ASSERT(ire->ire_stq != NULL);
7609 
7610 	/* Initiate read side IPPF processing */
7611 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7612 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7613 		ip_process(IPP_FWD_IN, &mp, ill_index);
7614 		if (mp == NULL) {
7615 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7616 			    "dropped during IPPF processing\n"));
7617 			return;
7618 		}
7619 	}
7620 
7621 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7622 	    ILLF_ROUTER) == 0) ||
7623 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7624 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7625 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7626 		    "forwarding is not turned on\n"));
7627 		goto drop_pkt;
7628 	}
7629 
7630 	/*
7631 	 * Don't forward if the interface is down
7632 	 */
7633 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7634 		goto discard_pkt;
7635 	}
7636 
7637 	ipha = (ipha_t *)mp->b_rptr;
7638 	pkt_len = ntohs(ipha->ipha_length);
7639 	/* Adjust the checksum to reflect the ttl decrement. */
7640 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7641 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7642 	if (ipha->ipha_ttl-- <= 1) {
7643 		if (ip_csum_hdr(ipha)) {
7644 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7645 			goto drop_pkt;
7646 		}
7647 		q = ire->ire_stq;
7648 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7649 		    BPRI_HI)) == NULL) {
7650 			goto discard_pkt;
7651 		}
7652 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7653 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7654 		/* Sent by forwarding path, and router is global zone */
7655 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7656 		    GLOBAL_ZONEID, ipst);
7657 		return;
7658 	}
7659 
7660 	/* Get the ill_index of the ILL */
7661 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7662 
7663 	/*
7664 	 * This location is chosen for the placement of the forwarding hook
7665 	 * because at this point we know that we have a path out for the
7666 	 * packet but haven't yet applied any logic (such as fragmenting)
7667 	 * that happen as part of transmitting the packet out.
7668 	 */
7669 	out_ill = ire->ire_ipif->ipif_ill;
7670 
7671 	DTRACE_PROBE4(ip4__forwarding__start,
7672 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7673 
7674 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7675 	    ipst->ips_ipv4firewall_forwarding,
7676 	    in_ill, out_ill, ipha, mp, mp, ipst);
7677 
7678 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7679 
7680 	if (mp == NULL)
7681 		return;
7682 	pkt_len = ntohs(ipha->ipha_length);
7683 
7684 	/*
7685 	 * ip_mrtun_forward is only used by foreign agent to reverse
7686 	 * tunnel the incoming packet. So it does not do any option
7687 	 * processing for source routing.
7688 	 */
7689 	max_frag = ire->ire_max_frag;
7690 	if (pkt_len > max_frag) {
7691 		/*
7692 		 * It needs fragging on its way out.  We haven't
7693 		 * verified the header checksum yet.  Since we
7694 		 * are going to put a surely good checksum in the
7695 		 * outgoing header, we have to make sure that it
7696 		 * was good coming in.
7697 		 */
7698 		if (ip_csum_hdr(ipha)) {
7699 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7700 			goto drop_pkt;
7701 		}
7702 
7703 		/* Initiate write side IPPF processing */
7704 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7705 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7706 			if (mp == NULL) {
7707 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7708 				    "dropped/deferred during ip policy "\
7709 				    "processing\n"));
7710 				return;
7711 			}
7712 		}
7713 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7714 		    BPRI_HI)) == NULL) {
7715 			goto discard_pkt;
7716 		}
7717 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7718 		mp = first_mp;
7719 
7720 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7721 		return;
7722 	}
7723 
7724 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7725 
7726 	ASSERT(ire->ire_ipif != NULL);
7727 
7728 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7729 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7730 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7731 	    ipst->ips_ipv4firewall_physical_out,
7732 	    NULL, out_ill, ipha, mp, mp, ipst);
7733 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7734 	if (mp == NULL)
7735 		return;
7736 
7737 	/* Now send the packet to the tunnel interface */
7738 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7739 	q = ire->ire_stq;
7740 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7741 	if ((pktxmit_state == SEND_FAILED) ||
7742 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7743 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7744 		    q->q_ptr));
7745 	}
7746 
7747 	return;
7748 discard_pkt:
7749 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7750 drop_pkt:;
7751 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7752 	freemsg(mp);
7753 #undef	rptr
7754 }
7755 
7756 /*
7757  * Fills the ipsec_out_t data structure with appropriate fields and
7758  * prepends it to mp which contains the IP hdr + data that was meant
7759  * to be forwarded. Please note that ipsec_out_info data structure
7760  * is used here to communicate the outgoing ill path at ip_wput()
7761  * for the ICMP error packet. This has nothing to do with ipsec IP
7762  * security. ipsec_out_t is really used to pass the info to the module
7763  * IP where this information cannot be extracted from conn.
7764  * This functions is called by ip_mrtun_forward().
7765  */
7766 void
7767 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7768 {
7769 	ipsec_out_t	*io;
7770 
7771 	ASSERT(xmit_ill != NULL);
7772 	first_mp->b_datap->db_type = M_CTL;
7773 	first_mp->b_wptr += sizeof (ipsec_info_t);
7774 	/*
7775 	 * This is to pass info to ip_wput in absence of conn.
7776 	 * ipsec_out_secure will be B_FALSE because of this.
7777 	 * Thus ipsec_out_secure being B_FALSE indicates that
7778 	 * this is not IPSEC security related information.
7779 	 */
7780 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7781 	io = (ipsec_out_t *)first_mp->b_rptr;
7782 	io->ipsec_out_type = IPSEC_OUT;
7783 	io->ipsec_out_len = sizeof (ipsec_out_t);
7784 	first_mp->b_cont = mp;
7785 	io->ipsec_out_ill_index =
7786 	    xmit_ill->ill_phyint->phyint_ifindex;
7787 	io->ipsec_out_xmit_if = B_TRUE;
7788 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7789 }
7790 
7791 /*
7792  * Return the network mask
7793  * associated with the specified address.
7794  */
7795 ipaddr_t
7796 ip_net_mask(ipaddr_t addr)
7797 {
7798 	uchar_t	*up = (uchar_t *)&addr;
7799 	ipaddr_t mask = 0;
7800 	uchar_t	*maskp = (uchar_t *)&mask;
7801 
7802 #if defined(__i386) || defined(__amd64)
7803 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7804 #endif
7805 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7806 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7807 #endif
7808 	if (CLASSD(addr)) {
7809 		maskp[0] = 0xF0;
7810 		return (mask);
7811 	}
7812 	if (addr == 0)
7813 		return (0);
7814 	maskp[0] = 0xFF;
7815 	if ((up[0] & 0x80) == 0)
7816 		return (mask);
7817 
7818 	maskp[1] = 0xFF;
7819 	if ((up[0] & 0xC0) == 0x80)
7820 		return (mask);
7821 
7822 	maskp[2] = 0xFF;
7823 	if ((up[0] & 0xE0) == 0xC0)
7824 		return (mask);
7825 
7826 	/* Must be experimental or multicast, indicate as much */
7827 	return ((ipaddr_t)0);
7828 }
7829 
7830 /*
7831  * Select an ill for the packet by considering load spreading across
7832  * a different ill in the group if dst_ill is part of some group.
7833  */
7834 ill_t *
7835 ip_newroute_get_dst_ill(ill_t *dst_ill)
7836 {
7837 	ill_t *ill;
7838 
7839 	/*
7840 	 * We schedule irrespective of whether the source address is
7841 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7842 	 */
7843 	ill = illgrp_scheduler(dst_ill);
7844 	if (ill == NULL)
7845 		return (NULL);
7846 
7847 	/*
7848 	 * For groups with names ip_sioctl_groupname ensures that all
7849 	 * ills are of same type. For groups without names, ifgrp_insert
7850 	 * ensures this.
7851 	 */
7852 	ASSERT(dst_ill->ill_type == ill->ill_type);
7853 
7854 	return (ill);
7855 }
7856 
7857 /*
7858  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7859  */
7860 ill_t *
7861 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7862     ip_stack_t *ipst)
7863 {
7864 	ill_t *ret_ill;
7865 
7866 	ASSERT(ifindex != 0);
7867 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7868 	    ipst);
7869 	if (ret_ill == NULL ||
7870 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7871 		if (isv6) {
7872 			if (ill != NULL) {
7873 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7874 			} else {
7875 				BUMP_MIB(&ipst->ips_ip6_mib,
7876 				    ipIfStatsOutDiscards);
7877 			}
7878 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7879 			    "bad ifindex %d.\n", ifindex));
7880 		} else {
7881 			if (ill != NULL) {
7882 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7883 			} else {
7884 				BUMP_MIB(&ipst->ips_ip_mib,
7885 				    ipIfStatsOutDiscards);
7886 			}
7887 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7888 			    "bad ifindex %d.\n", ifindex));
7889 		}
7890 		if (ret_ill != NULL)
7891 			ill_refrele(ret_ill);
7892 		freemsg(first_mp);
7893 		return (NULL);
7894 	}
7895 
7896 	return (ret_ill);
7897 }
7898 
7899 /*
7900  * IPv4 -
7901  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7902  * out a packet to a destination address for which we do not have specific
7903  * (or sufficient) routing information.
7904  *
7905  * NOTE : These are the scopes of some of the variables that point at IRE,
7906  *	  which needs to be followed while making any future modifications
7907  *	  to avoid memory leaks.
7908  *
7909  *	- ire and sire are the entries looked up initially by
7910  *	  ire_ftable_lookup.
7911  *	- ipif_ire is used to hold the interface ire associated with
7912  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7913  *	  it before branching out to error paths.
7914  *	- save_ire is initialized before ire_create, so that ire returned
7915  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7916  *	  before breaking out of the switch.
7917  *
7918  *	Thus on failures, we have to REFRELE only ire and sire, if they
7919  *	are not NULL.
7920  */
7921 void
7922 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7923     zoneid_t zoneid, ip_stack_t *ipst)
7924 {
7925 	areq_t	*areq;
7926 	ipaddr_t gw = 0;
7927 	ire_t	*ire = NULL;
7928 	mblk_t	*res_mp;
7929 	ipaddr_t *addrp;
7930 	ipaddr_t nexthop_addr;
7931 	ipif_t  *src_ipif = NULL;
7932 	ill_t	*dst_ill = NULL;
7933 	ipha_t  *ipha;
7934 	ire_t	*sire = NULL;
7935 	mblk_t	*first_mp;
7936 	ire_t	*save_ire;
7937 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7938 	ushort_t ire_marks = 0;
7939 	boolean_t mctl_present;
7940 	ipsec_out_t *io;
7941 	mblk_t	*saved_mp;
7942 	ire_t	*first_sire = NULL;
7943 	mblk_t	*copy_mp = NULL;
7944 	mblk_t	*xmit_mp = NULL;
7945 	ipaddr_t save_dst;
7946 	uint32_t multirt_flags =
7947 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7948 	boolean_t multirt_is_resolvable;
7949 	boolean_t multirt_resolve_next;
7950 	boolean_t do_attach_ill = B_FALSE;
7951 	boolean_t ip_nexthop = B_FALSE;
7952 	tsol_ire_gw_secattr_t *attrp = NULL;
7953 	tsol_gcgrp_t *gcgrp = NULL;
7954 	tsol_gcgrp_addr_t ga;
7955 
7956 	if (ip_debug > 2) {
7957 		/* ip1dbg */
7958 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7959 	}
7960 
7961 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7962 	if (mctl_present) {
7963 		io = (ipsec_out_t *)first_mp->b_rptr;
7964 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7965 		ASSERT(zoneid == io->ipsec_out_zoneid);
7966 		ASSERT(zoneid != ALL_ZONES);
7967 	}
7968 
7969 	ipha = (ipha_t *)mp->b_rptr;
7970 
7971 	/* All multicast lookups come through ip_newroute_ipif() */
7972 	if (CLASSD(dst)) {
7973 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7974 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7975 		freemsg(first_mp);
7976 		return;
7977 	}
7978 
7979 	if (mctl_present && io->ipsec_out_attach_if) {
7980 		/* ip_grab_attach_ill returns a held ill */
7981 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7982 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7983 
7984 		/* Failure case frees things for us. */
7985 		if (attach_ill == NULL)
7986 			return;
7987 
7988 		/*
7989 		 * Check if we need an ire that will not be
7990 		 * looked up by anybody else i.e. HIDDEN.
7991 		 */
7992 		if (ill_is_probeonly(attach_ill))
7993 			ire_marks = IRE_MARK_HIDDEN;
7994 	}
7995 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7996 		ip_nexthop = B_TRUE;
7997 		nexthop_addr = io->ipsec_out_nexthop_addr;
7998 	}
7999 	/*
8000 	 * If this IRE is created for forwarding or it is not for
8001 	 * traffic for congestion controlled protocols, mark it as temporary.
8002 	 */
8003 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
8004 		ire_marks |= IRE_MARK_TEMPORARY;
8005 
8006 	/*
8007 	 * Get what we can from ire_ftable_lookup which will follow an IRE
8008 	 * chain until it gets the most specific information available.
8009 	 * For example, we know that there is no IRE_CACHE for this dest,
8010 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
8011 	 * ire_ftable_lookup will look up the gateway, etc.
8012 	 * Check if in_ill != NULL. If it is true, the packet must be
8013 	 * from an incoming interface where RTA_SRCIFP is set.
8014 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8015 	 * to the destination, of equal netmask length in the forward table,
8016 	 * will be recursively explored. If no information is available
8017 	 * for the final gateway of that route, we force the returned ire
8018 	 * to be equal to sire using MATCH_IRE_PARENT.
8019 	 * At least, in this case we have a starting point (in the buckets)
8020 	 * to look for other routes to the destination in the forward table.
8021 	 * This is actually used only for multirouting, where a list
8022 	 * of routes has to be processed in sequence.
8023 	 *
8024 	 * In the process of coming up with the most specific information,
8025 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8026 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8027 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8028 	 * Two caveats when handling incomplete ire's in ip_newroute:
8029 	 * - we should be careful when accessing its ire_nce (specifically
8030 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8031 	 * - not all legacy code path callers are prepared to handle
8032 	 *   incomplete ire's, so we should not create/add incomplete
8033 	 *   ire_cache entries here. (See discussion about temporary solution
8034 	 *   further below).
8035 	 *
8036 	 * In order to minimize packet dropping, and to preserve existing
8037 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8038 	 * gateway, and instead use the IF_RESOLVER ire to send out
8039 	 * another request to ARP (this is achieved by passing the
8040 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8041 	 * arp response comes back in ip_wput_nondata, we will create
8042 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8043 	 *
8044 	 * Note that this is a temporary solution; the correct solution is
8045 	 * to create an incomplete  per-dst ire_cache entry, and send the
8046 	 * packet out when the gw's nce is resolved. In order to achieve this,
8047 	 * all packet processing must have been completed prior to calling
8048 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8049 	 * to be modified to accomodate this solution.
8050 	 */
8051 	if (in_ill != NULL) {
8052 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8053 		    in_ill, MATCH_IRE_TYPE);
8054 	} else if (ip_nexthop) {
8055 		/*
8056 		 * The first time we come here, we look for an IRE_INTERFACE
8057 		 * entry for the specified nexthop, set the dst to be the
8058 		 * nexthop address and create an IRE_CACHE entry for the
8059 		 * nexthop. The next time around, we are able to find an
8060 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8061 		 * nexthop address and create an IRE_CACHE entry for the
8062 		 * destination address via the specified nexthop.
8063 		 */
8064 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8065 		    MBLK_GETLABEL(mp), ipst);
8066 		if (ire != NULL) {
8067 			gw = nexthop_addr;
8068 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8069 		} else {
8070 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8071 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8072 			    MBLK_GETLABEL(mp),
8073 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8074 			    ipst);
8075 			if (ire != NULL) {
8076 				dst = nexthop_addr;
8077 			}
8078 		}
8079 	} else if (attach_ill == NULL) {
8080 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8081 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8082 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8083 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8084 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8085 		    ipst);
8086 	} else {
8087 		/*
8088 		 * attach_ill is set only for communicating with
8089 		 * on-link hosts. So, don't look for DEFAULT.
8090 		 */
8091 		ipif_t	*attach_ipif;
8092 
8093 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8094 		if (attach_ipif == NULL) {
8095 			ill_refrele(attach_ill);
8096 			goto icmp_err_ret;
8097 		}
8098 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8099 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8100 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8101 		    MATCH_IRE_SECATTR, ipst);
8102 		ipif_refrele(attach_ipif);
8103 	}
8104 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8105 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8106 
8107 	/*
8108 	 * This loop is run only once in most cases.
8109 	 * We loop to resolve further routes only when the destination
8110 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8111 	 */
8112 	do {
8113 		/* Clear the previous iteration's values */
8114 		if (src_ipif != NULL) {
8115 			ipif_refrele(src_ipif);
8116 			src_ipif = NULL;
8117 		}
8118 		if (dst_ill != NULL) {
8119 			ill_refrele(dst_ill);
8120 			dst_ill = NULL;
8121 		}
8122 
8123 		multirt_resolve_next = B_FALSE;
8124 		/*
8125 		 * We check if packets have to be multirouted.
8126 		 * In this case, given the current <ire, sire> couple,
8127 		 * we look for the next suitable <ire, sire>.
8128 		 * This check is done in ire_multirt_lookup(),
8129 		 * which applies various criteria to find the next route
8130 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8131 		 * unchanged if it detects it has not been tried yet.
8132 		 */
8133 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8134 			ip3dbg(("ip_newroute: starting next_resolution "
8135 			    "with first_mp %p, tag %d\n",
8136 			    (void *)first_mp,
8137 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8138 
8139 			ASSERT(sire != NULL);
8140 			multirt_is_resolvable =
8141 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8142 			    MBLK_GETLABEL(mp), ipst);
8143 
8144 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8145 			    "ire %p, sire %p\n",
8146 			    multirt_is_resolvable,
8147 			    (void *)ire, (void *)sire));
8148 
8149 			if (!multirt_is_resolvable) {
8150 				/*
8151 				 * No more multirt route to resolve; give up
8152 				 * (all routes resolved or no more
8153 				 * resolvable routes).
8154 				 */
8155 				if (ire != NULL) {
8156 					ire_refrele(ire);
8157 					ire = NULL;
8158 				}
8159 			} else {
8160 				ASSERT(sire != NULL);
8161 				ASSERT(ire != NULL);
8162 				/*
8163 				 * We simply use first_sire as a flag that
8164 				 * indicates if a resolvable multirt route
8165 				 * has already been found.
8166 				 * If it is not the case, we may have to send
8167 				 * an ICMP error to report that the
8168 				 * destination is unreachable.
8169 				 * We do not IRE_REFHOLD first_sire.
8170 				 */
8171 				if (first_sire == NULL) {
8172 					first_sire = sire;
8173 				}
8174 			}
8175 		}
8176 		if (ire == NULL) {
8177 			if (ip_debug > 3) {
8178 				/* ip2dbg */
8179 				pr_addr_dbg("ip_newroute: "
8180 				    "can't resolve %s\n", AF_INET, &dst);
8181 			}
8182 			ip3dbg(("ip_newroute: "
8183 			    "ire %p, sire %p, first_sire %p\n",
8184 			    (void *)ire, (void *)sire, (void *)first_sire));
8185 
8186 			if (sire != NULL) {
8187 				ire_refrele(sire);
8188 				sire = NULL;
8189 			}
8190 
8191 			if (first_sire != NULL) {
8192 				/*
8193 				 * At least one multirt route has been found
8194 				 * in the same call to ip_newroute();
8195 				 * there is no need to report an ICMP error.
8196 				 * first_sire was not IRE_REFHOLDed.
8197 				 */
8198 				MULTIRT_DEBUG_UNTAG(first_mp);
8199 				freemsg(first_mp);
8200 				return;
8201 			}
8202 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8203 			    RTA_DST, ipst);
8204 			if (attach_ill != NULL)
8205 				ill_refrele(attach_ill);
8206 			goto icmp_err_ret;
8207 		}
8208 
8209 		/*
8210 		 * When RTA_SRCIFP is used to add a route, then an interface
8211 		 * route is added in the source interface's routing table.
8212 		 * If the outgoing interface of this route is of type
8213 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8214 		 * ire_nce->nce_res_mp is set to NULL.
8215 		 * Later, when this route is first used for forwarding
8216 		 * a packet, ip_newroute() is called
8217 		 * to resolve the hardware address of the outgoing ipif.
8218 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8219 		 * source interface based table. We only come here if the
8220 		 * outgoing interface is a resolver interface and we don't
8221 		 * have the ire_nce->nce_res_mp information yet.
8222 		 * If in_ill is not null that means it is called from
8223 		 * ip_rput.
8224 		 */
8225 
8226 		ASSERT(ire->ire_in_ill == NULL ||
8227 		    (ire->ire_type == IRE_IF_RESOLVER &&
8228 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8229 
8230 		/*
8231 		 * Verify that the returned IRE does not have either
8232 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8233 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8234 		 */
8235 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8236 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8237 			if (attach_ill != NULL)
8238 				ill_refrele(attach_ill);
8239 			goto icmp_err_ret;
8240 		}
8241 		/*
8242 		 * Increment the ire_ob_pkt_count field for ire if it is an
8243 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8244 		 * increment the same for the parent IRE, sire, if it is some
8245 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8246 		 */
8247 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8248 			UPDATE_OB_PKT_COUNT(ire);
8249 			ire->ire_last_used_time = lbolt;
8250 		}
8251 
8252 		if (sire != NULL) {
8253 			gw = sire->ire_gateway_addr;
8254 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8255 			    IRE_INTERFACE)) == 0);
8256 			UPDATE_OB_PKT_COUNT(sire);
8257 			sire->ire_last_used_time = lbolt;
8258 		}
8259 		/*
8260 		 * We have a route to reach the destination.
8261 		 *
8262 		 * 1) If the interface is part of ill group, try to get a new
8263 		 *    ill taking load spreading into account.
8264 		 *
8265 		 * 2) After selecting the ill, get a source address that
8266 		 *    might create good inbound load spreading.
8267 		 *    ipif_select_source does this for us.
8268 		 *
8269 		 * If the application specified the ill (ifindex), we still
8270 		 * load spread. Only if the packets needs to go out
8271 		 * specifically on a given ill e.g. binding to
8272 		 * IPIF_NOFAILOVER address, then we don't try to use a
8273 		 * different ill for load spreading.
8274 		 */
8275 		if (attach_ill == NULL) {
8276 			/*
8277 			 * Don't perform outbound load spreading in the
8278 			 * case of an RTF_MULTIRT route, as we actually
8279 			 * typically want to replicate outgoing packets
8280 			 * through particular interfaces.
8281 			 */
8282 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8283 				dst_ill = ire->ire_ipif->ipif_ill;
8284 				/* for uniformity */
8285 				ill_refhold(dst_ill);
8286 			} else {
8287 				/*
8288 				 * If we are here trying to create an IRE_CACHE
8289 				 * for an offlink destination and have the
8290 				 * IRE_CACHE for the next hop and the latter is
8291 				 * using virtual IP source address selection i.e
8292 				 * it's ire->ire_ipif is pointing to a virtual
8293 				 * network interface (vni) then
8294 				 * ip_newroute_get_dst_ll() will return the vni
8295 				 * interface as the dst_ill. Since the vni is
8296 				 * virtual i.e not associated with any physical
8297 				 * interface, it cannot be the dst_ill, hence
8298 				 * in such a case call ip_newroute_get_dst_ll()
8299 				 * with the stq_ill instead of the ire_ipif ILL.
8300 				 * The function returns a refheld ill.
8301 				 */
8302 				if ((ire->ire_type == IRE_CACHE) &&
8303 				    IS_VNI(ire->ire_ipif->ipif_ill))
8304 					dst_ill = ip_newroute_get_dst_ill(
8305 					    ire->ire_stq->q_ptr);
8306 				else
8307 					dst_ill = ip_newroute_get_dst_ill(
8308 					    ire->ire_ipif->ipif_ill);
8309 			}
8310 			if (dst_ill == NULL) {
8311 				if (ip_debug > 2) {
8312 					pr_addr_dbg("ip_newroute: "
8313 					    "no dst ill for dst"
8314 					    " %s\n", AF_INET, &dst);
8315 				}
8316 				goto icmp_err_ret;
8317 			}
8318 		} else {
8319 			dst_ill = ire->ire_ipif->ipif_ill;
8320 			/* for uniformity */
8321 			ill_refhold(dst_ill);
8322 			/*
8323 			 * We should have found a route matching ill as we
8324 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8325 			 * Rather than asserting, when there is a mismatch,
8326 			 * we just drop the packet.
8327 			 */
8328 			if (dst_ill != attach_ill) {
8329 				ip0dbg(("ip_newroute: Packet dropped as "
8330 				    "IPIF_NOFAILOVER ill is %s, "
8331 				    "ire->ire_ipif->ipif_ill is %s\n",
8332 				    attach_ill->ill_name,
8333 				    dst_ill->ill_name));
8334 				ill_refrele(attach_ill);
8335 				goto icmp_err_ret;
8336 			}
8337 		}
8338 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8339 		if (attach_ill != NULL) {
8340 			ill_refrele(attach_ill);
8341 			attach_ill = NULL;
8342 			do_attach_ill = B_TRUE;
8343 		}
8344 		ASSERT(dst_ill != NULL);
8345 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8346 
8347 		/*
8348 		 * Pick the best source address from dst_ill.
8349 		 *
8350 		 * 1) If it is part of a multipathing group, we would
8351 		 *    like to spread the inbound packets across different
8352 		 *    interfaces. ipif_select_source picks a random source
8353 		 *    across the different ills in the group.
8354 		 *
8355 		 * 2) If it is not part of a multipathing group, we try
8356 		 *    to pick the source address from the destination
8357 		 *    route. Clustering assumes that when we have multiple
8358 		 *    prefixes hosted on an interface, the prefix of the
8359 		 *    source address matches the prefix of the destination
8360 		 *    route. We do this only if the address is not
8361 		 *    DEPRECATED.
8362 		 *
8363 		 * 3) If the conn is in a different zone than the ire, we
8364 		 *    need to pick a source address from the right zone.
8365 		 *
8366 		 * NOTE : If we hit case (1) above, the prefix of the source
8367 		 *	  address picked may not match the prefix of the
8368 		 *	  destination routes prefix as ipif_select_source
8369 		 *	  does not look at "dst" while picking a source
8370 		 *	  address.
8371 		 *	  If we want the same behavior as (2), we will need
8372 		 *	  to change the behavior of ipif_select_source.
8373 		 */
8374 		ASSERT(src_ipif == NULL);
8375 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8376 			/*
8377 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8378 			 * Check that the ipif matching the requested source
8379 			 * address still exists.
8380 			 */
8381 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8382 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8383 		}
8384 		if (src_ipif == NULL) {
8385 			ire_marks |= IRE_MARK_USESRC_CHECK;
8386 			if ((dst_ill->ill_group != NULL) ||
8387 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8388 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8389 			    ire->ire_zoneid != ALL_ZONES) ||
8390 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8391 				/*
8392 				 * If the destination is reachable via a
8393 				 * given gateway, the selected source address
8394 				 * should be in the same subnet as the gateway.
8395 				 * Otherwise, the destination is not reachable.
8396 				 *
8397 				 * If there are no interfaces on the same subnet
8398 				 * as the destination, ipif_select_source gives
8399 				 * first non-deprecated interface which might be
8400 				 * on a different subnet than the gateway.
8401 				 * This is not desirable. Hence pass the dst_ire
8402 				 * source address to ipif_select_source.
8403 				 * It is sure that the destination is reachable
8404 				 * with the dst_ire source address subnet.
8405 				 * So passing dst_ire source address to
8406 				 * ipif_select_source will make sure that the
8407 				 * selected source will be on the same subnet
8408 				 * as dst_ire source address.
8409 				 */
8410 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8411 				src_ipif = ipif_select_source(dst_ill, saddr,
8412 				    zoneid);
8413 				if (src_ipif == NULL) {
8414 					if (ip_debug > 2) {
8415 						pr_addr_dbg("ip_newroute: "
8416 						    "no src for dst %s ",
8417 						    AF_INET, &dst);
8418 						printf("through interface %s\n",
8419 						    dst_ill->ill_name);
8420 					}
8421 					goto icmp_err_ret;
8422 				}
8423 			} else {
8424 				src_ipif = ire->ire_ipif;
8425 				ASSERT(src_ipif != NULL);
8426 				/* hold src_ipif for uniformity */
8427 				ipif_refhold(src_ipif);
8428 			}
8429 		}
8430 
8431 		/*
8432 		 * Assign a source address while we have the conn.
8433 		 * We can't have ip_wput_ire pick a source address when the
8434 		 * packet returns from arp since we need to look at
8435 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8436 		 * going through arp.
8437 		 *
8438 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8439 		 *	  it uses ip6i to store this information.
8440 		 */
8441 		if (ipha->ipha_src == INADDR_ANY &&
8442 		    (connp == NULL || !connp->conn_unspec_src)) {
8443 			ipha->ipha_src = src_ipif->ipif_src_addr;
8444 		}
8445 		if (ip_debug > 3) {
8446 			/* ip2dbg */
8447 			pr_addr_dbg("ip_newroute: first hop %s\n",
8448 			    AF_INET, &gw);
8449 		}
8450 		ip2dbg(("\tire type %s (%d)\n",
8451 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8452 
8453 		/*
8454 		 * The TTL of multirouted packets is bounded by the
8455 		 * ip_multirt_ttl ndd variable.
8456 		 */
8457 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8458 			/* Force TTL of multirouted packets */
8459 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8460 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8461 				ip2dbg(("ip_newroute: forcing multirt TTL "
8462 				    "to %d (was %d), dst 0x%08x\n",
8463 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8464 				    ntohl(sire->ire_addr)));
8465 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8466 			}
8467 		}
8468 		/*
8469 		 * At this point in ip_newroute(), ire is either the
8470 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8471 		 * destination or an IRE_INTERFACE type that should be used
8472 		 * to resolve an on-subnet destination or an on-subnet
8473 		 * next-hop gateway.
8474 		 *
8475 		 * In the IRE_CACHE case, we have the following :
8476 		 *
8477 		 * 1) src_ipif - used for getting a source address.
8478 		 *
8479 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8480 		 *    means packets using this IRE_CACHE will go out on
8481 		 *    dst_ill.
8482 		 *
8483 		 * 3) The IRE sire will point to the prefix that is the
8484 		 *    longest  matching route for the destination. These
8485 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8486 		 *
8487 		 *    The newly created IRE_CACHE entry for the off-subnet
8488 		 *    destination is tied to both the prefix route and the
8489 		 *    interface route used to resolve the next-hop gateway
8490 		 *    via the ire_phandle and ire_ihandle fields,
8491 		 *    respectively.
8492 		 *
8493 		 * In the IRE_INTERFACE case, we have the following :
8494 		 *
8495 		 * 1) src_ipif - used for getting a source address.
8496 		 *
8497 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8498 		 *    means packets using the IRE_CACHE that we will build
8499 		 *    here will go out on dst_ill.
8500 		 *
8501 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8502 		 *    to be created will only be tied to the IRE_INTERFACE
8503 		 *    that was derived from the ire_ihandle field.
8504 		 *
8505 		 *    If sire is non-NULL, it means the destination is
8506 		 *    off-link and we will first create the IRE_CACHE for the
8507 		 *    gateway. Next time through ip_newroute, we will create
8508 		 *    the IRE_CACHE for the final destination as described
8509 		 *    above.
8510 		 *
8511 		 * In both cases, after the current resolution has been
8512 		 * completed (or possibly initialised, in the IRE_INTERFACE
8513 		 * case), the loop may be re-entered to attempt the resolution
8514 		 * of another RTF_MULTIRT route.
8515 		 *
8516 		 * When an IRE_CACHE entry for the off-subnet destination is
8517 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8518 		 * for further processing in emission loops.
8519 		 */
8520 		save_ire = ire;
8521 		switch (ire->ire_type) {
8522 		case IRE_CACHE: {
8523 			ire_t	*ipif_ire;
8524 			mblk_t	*ire_fp_mp;
8525 
8526 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8527 			if (gw == 0)
8528 				gw = ire->ire_gateway_addr;
8529 			/*
8530 			 * We need 3 ire's to create a new cache ire for an
8531 			 * off-link destination from the cache ire of the
8532 			 * gateway.
8533 			 *
8534 			 *	1. The prefix ire 'sire' (Note that this does
8535 			 *	   not apply to the conn_nexthop_set case)
8536 			 *	2. The cache ire of the gateway 'ire'
8537 			 *	3. The interface ire 'ipif_ire'
8538 			 *
8539 			 * We have (1) and (2). We lookup (3) below.
8540 			 *
8541 			 * If there is no interface route to the gateway,
8542 			 * it is a race condition, where we found the cache
8543 			 * but the interface route has been deleted.
8544 			 */
8545 			if (ip_nexthop) {
8546 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8547 			} else {
8548 				ipif_ire =
8549 				    ire_ihandle_lookup_offlink(ire, sire);
8550 			}
8551 			if (ipif_ire == NULL) {
8552 				ip1dbg(("ip_newroute: "
8553 				    "ire_ihandle_lookup_offlink failed\n"));
8554 				goto icmp_err_ret;
8555 			}
8556 			/*
8557 			 * XXX We are using the same res_mp
8558 			 * (DL_UNITDATA_REQ) though the save_ire is not
8559 			 * pointing at the same ill.
8560 			 * This is incorrect. We need to send it up to the
8561 			 * resolver to get the right res_mp. For ethernets
8562 			 * this may be okay (ill_type == DL_ETHER).
8563 			 */
8564 			res_mp = save_ire->ire_nce->nce_res_mp;
8565 			ire_fp_mp = NULL;
8566 
8567 			/*
8568 			 * Check cached gateway IRE for any security
8569 			 * attributes; if found, associate the gateway
8570 			 * credentials group to the destination IRE.
8571 			 */
8572 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8573 				mutex_enter(&attrp->igsa_lock);
8574 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8575 					GCGRP_REFHOLD(gcgrp);
8576 				mutex_exit(&attrp->igsa_lock);
8577 			}
8578 
8579 			ire = ire_create(
8580 			    (uchar_t *)&dst,		/* dest address */
8581 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8582 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8583 			    (uchar_t *)&gw,		/* gateway address */
8584 			    NULL,
8585 			    &save_ire->ire_max_frag,
8586 			    ire_fp_mp,			/* Fast Path header */
8587 			    dst_ill->ill_rq,		/* recv-from queue */
8588 			    dst_ill->ill_wq,		/* send-to queue */
8589 			    IRE_CACHE,			/* IRE type */
8590 			    res_mp,
8591 			    src_ipif,
8592 			    in_ill,			/* incoming ill */
8593 			    (sire != NULL) ?
8594 			    sire->ire_mask : 0, 	/* Parent mask */
8595 			    (sire != NULL) ?
8596 			    sire->ire_phandle : 0,	/* Parent handle */
8597 			    ipif_ire->ire_ihandle,	/* Interface handle */
8598 			    (sire != NULL) ? (sire->ire_flags &
8599 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8600 			    (sire != NULL) ?
8601 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8602 			    NULL,
8603 			    gcgrp,
8604 			    ipst);
8605 
8606 			if (ire == NULL) {
8607 				if (gcgrp != NULL) {
8608 					GCGRP_REFRELE(gcgrp);
8609 					gcgrp = NULL;
8610 				}
8611 				ire_refrele(ipif_ire);
8612 				ire_refrele(save_ire);
8613 				break;
8614 			}
8615 
8616 			/* reference now held by IRE */
8617 			gcgrp = NULL;
8618 
8619 			ire->ire_marks |= ire_marks;
8620 
8621 			/*
8622 			 * Prevent sire and ipif_ire from getting deleted.
8623 			 * The newly created ire is tied to both of them via
8624 			 * the phandle and ihandle respectively.
8625 			 */
8626 			if (sire != NULL) {
8627 				IRB_REFHOLD(sire->ire_bucket);
8628 				/* Has it been removed already ? */
8629 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8630 					IRB_REFRELE(sire->ire_bucket);
8631 					ire_refrele(ipif_ire);
8632 					ire_refrele(save_ire);
8633 					break;
8634 				}
8635 			}
8636 
8637 			IRB_REFHOLD(ipif_ire->ire_bucket);
8638 			/* Has it been removed already ? */
8639 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8640 				IRB_REFRELE(ipif_ire->ire_bucket);
8641 				if (sire != NULL)
8642 					IRB_REFRELE(sire->ire_bucket);
8643 				ire_refrele(ipif_ire);
8644 				ire_refrele(save_ire);
8645 				break;
8646 			}
8647 
8648 			xmit_mp = first_mp;
8649 			/*
8650 			 * In the case of multirouting, a copy
8651 			 * of the packet is done before its sending.
8652 			 * The copy is used to attempt another
8653 			 * route resolution, in a next loop.
8654 			 */
8655 			if (ire->ire_flags & RTF_MULTIRT) {
8656 				copy_mp = copymsg(first_mp);
8657 				if (copy_mp != NULL) {
8658 					xmit_mp = copy_mp;
8659 					MULTIRT_DEBUG_TAG(first_mp);
8660 				}
8661 			}
8662 			ire_add_then_send(q, ire, xmit_mp);
8663 			ire_refrele(save_ire);
8664 
8665 			/* Assert that sire is not deleted yet. */
8666 			if (sire != NULL) {
8667 				ASSERT(sire->ire_ptpn != NULL);
8668 				IRB_REFRELE(sire->ire_bucket);
8669 			}
8670 
8671 			/* Assert that ipif_ire is not deleted yet. */
8672 			ASSERT(ipif_ire->ire_ptpn != NULL);
8673 			IRB_REFRELE(ipif_ire->ire_bucket);
8674 			ire_refrele(ipif_ire);
8675 
8676 			/*
8677 			 * If copy_mp is not NULL, multirouting was
8678 			 * requested. We loop to initiate a next
8679 			 * route resolution attempt, starting from sire.
8680 			 */
8681 			if (copy_mp != NULL) {
8682 				/*
8683 				 * Search for the next unresolved
8684 				 * multirt route.
8685 				 */
8686 				copy_mp = NULL;
8687 				ipif_ire = NULL;
8688 				ire = NULL;
8689 				multirt_resolve_next = B_TRUE;
8690 				continue;
8691 			}
8692 			if (sire != NULL)
8693 				ire_refrele(sire);
8694 			ipif_refrele(src_ipif);
8695 			ill_refrele(dst_ill);
8696 			return;
8697 		}
8698 		case IRE_IF_NORESOLVER: {
8699 			/*
8700 			 * We have what we need to build an IRE_CACHE.
8701 			 *
8702 			 * Create a new res_mp with the IP gateway address
8703 			 * in destination address in the DLPI hdr if the
8704 			 * physical length is exactly 4 bytes.
8705 			 */
8706 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
8707 				uchar_t *addr;
8708 
8709 				if (gw)
8710 					addr = (uchar_t *)&gw;
8711 				else
8712 					addr = (uchar_t *)&dst;
8713 
8714 				res_mp = ill_dlur_gen(addr,
8715 				    dst_ill->ill_phys_addr_length,
8716 				    dst_ill->ill_sap,
8717 				    dst_ill->ill_sap_length);
8718 
8719 				if (res_mp == NULL) {
8720 					ip1dbg(("ip_newroute: res_mp NULL\n"));
8721 					break;
8722 				}
8723 			} else if (dst_ill->ill_resolver_mp == NULL) {
8724 				ip1dbg(("ip_newroute: dst_ill %p "
8725 				    "for IF_NORESOLV ire %p has "
8726 				    "no ill_resolver_mp\n",
8727 				    (void *)dst_ill, (void *)ire));
8728 				break;
8729 			} else {
8730 				res_mp = NULL;
8731 			}
8732 
8733 			/*
8734 			 * TSol note: We are creating the ire cache for the
8735 			 * destination 'dst'. If 'dst' is offlink, going
8736 			 * through the first hop 'gw', the security attributes
8737 			 * of 'dst' must be set to point to the gateway
8738 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8739 			 * is possible that 'dst' is a potential gateway that is
8740 			 * referenced by some route that has some security
8741 			 * attributes. Thus in the former case, we need to do a
8742 			 * gcgrp_lookup of 'gw' while in the latter case we
8743 			 * need to do gcgrp_lookup of 'dst' itself.
8744 			 */
8745 			ga.ga_af = AF_INET;
8746 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8747 			    &ga.ga_addr);
8748 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8749 
8750 			ire = ire_create(
8751 			    (uchar_t *)&dst,		/* dest address */
8752 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8753 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8754 			    (uchar_t *)&gw,		/* gateway address */
8755 			    NULL,
8756 			    &save_ire->ire_max_frag,
8757 			    NULL,			/* Fast Path header */
8758 			    dst_ill->ill_rq,		/* recv-from queue */
8759 			    dst_ill->ill_wq,		/* send-to queue */
8760 			    IRE_CACHE,
8761 			    res_mp,
8762 			    src_ipif,
8763 			    in_ill,			/* Incoming ill */
8764 			    save_ire->ire_mask,		/* Parent mask */
8765 			    (sire != NULL) ?		/* Parent handle */
8766 			    sire->ire_phandle : 0,
8767 			    save_ire->ire_ihandle,	/* Interface handle */
8768 			    (sire != NULL) ? sire->ire_flags &
8769 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8770 			    &(save_ire->ire_uinfo),
8771 			    NULL,
8772 			    gcgrp,
8773 			    ipst);
8774 
8775 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN)
8776 				freeb(res_mp);
8777 
8778 			if (ire == NULL) {
8779 				if (gcgrp != NULL) {
8780 					GCGRP_REFRELE(gcgrp);
8781 					gcgrp = NULL;
8782 				}
8783 				ire_refrele(save_ire);
8784 				break;
8785 			}
8786 
8787 			/* reference now held by IRE */
8788 			gcgrp = NULL;
8789 
8790 			ire->ire_marks |= ire_marks;
8791 
8792 			/* Prevent save_ire from getting deleted */
8793 			IRB_REFHOLD(save_ire->ire_bucket);
8794 			/* Has it been removed already ? */
8795 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8796 				IRB_REFRELE(save_ire->ire_bucket);
8797 				ire_refrele(save_ire);
8798 				break;
8799 			}
8800 
8801 			/*
8802 			 * In the case of multirouting, a copy
8803 			 * of the packet is made before it is sent.
8804 			 * The copy is used in the next
8805 			 * loop to attempt another resolution.
8806 			 */
8807 			xmit_mp = first_mp;
8808 			if ((sire != NULL) &&
8809 			    (sire->ire_flags & RTF_MULTIRT)) {
8810 				copy_mp = copymsg(first_mp);
8811 				if (copy_mp != NULL) {
8812 					xmit_mp = copy_mp;
8813 					MULTIRT_DEBUG_TAG(first_mp);
8814 				}
8815 			}
8816 			ire_add_then_send(q, ire, xmit_mp);
8817 
8818 			/* Assert that it is not deleted yet. */
8819 			ASSERT(save_ire->ire_ptpn != NULL);
8820 			IRB_REFRELE(save_ire->ire_bucket);
8821 			ire_refrele(save_ire);
8822 
8823 			if (copy_mp != NULL) {
8824 				/*
8825 				 * If we found a (no)resolver, we ignore any
8826 				 * trailing top priority IRE_CACHE in further
8827 				 * loops. This ensures that we do not omit any
8828 				 * (no)resolver.
8829 				 * This IRE_CACHE, if any, will be processed
8830 				 * by another thread entering ip_newroute().
8831 				 * IRE_CACHE entries, if any, will be processed
8832 				 * by another thread entering ip_newroute(),
8833 				 * (upon resolver response, for instance).
8834 				 * This aims to force parallel multirt
8835 				 * resolutions as soon as a packet must be sent.
8836 				 * In the best case, after the tx of only one
8837 				 * packet, all reachable routes are resolved.
8838 				 * Otherwise, the resolution of all RTF_MULTIRT
8839 				 * routes would require several emissions.
8840 				 */
8841 				multirt_flags &= ~MULTIRT_CACHEGW;
8842 
8843 				/*
8844 				 * Search for the next unresolved multirt
8845 				 * route.
8846 				 */
8847 				copy_mp = NULL;
8848 				save_ire = NULL;
8849 				ire = NULL;
8850 				multirt_resolve_next = B_TRUE;
8851 				continue;
8852 			}
8853 
8854 			/*
8855 			 * Don't need sire anymore
8856 			 */
8857 			if (sire != NULL)
8858 				ire_refrele(sire);
8859 
8860 			ipif_refrele(src_ipif);
8861 			ill_refrele(dst_ill);
8862 			return;
8863 		}
8864 		case IRE_IF_RESOLVER:
8865 			/*
8866 			 * We can't build an IRE_CACHE yet, but at least we
8867 			 * found a resolver that can help.
8868 			 */
8869 			res_mp = dst_ill->ill_resolver_mp;
8870 			if (!OK_RESOLVER_MP(res_mp))
8871 				break;
8872 
8873 			/*
8874 			 * To be at this point in the code with a non-zero gw
8875 			 * means that dst is reachable through a gateway that
8876 			 * we have never resolved.  By changing dst to the gw
8877 			 * addr we resolve the gateway first.
8878 			 * When ire_add_then_send() tries to put the IP dg
8879 			 * to dst, it will reenter ip_newroute() at which
8880 			 * time we will find the IRE_CACHE for the gw and
8881 			 * create another IRE_CACHE in case IRE_CACHE above.
8882 			 */
8883 			if (gw != INADDR_ANY) {
8884 				/*
8885 				 * The source ipif that was determined above was
8886 				 * relative to the destination address, not the
8887 				 * gateway's. If src_ipif was not taken out of
8888 				 * the IRE_IF_RESOLVER entry, we'll need to call
8889 				 * ipif_select_source() again.
8890 				 */
8891 				if (src_ipif != ire->ire_ipif) {
8892 					ipif_refrele(src_ipif);
8893 					src_ipif = ipif_select_source(dst_ill,
8894 					    gw, zoneid);
8895 					if (src_ipif == NULL) {
8896 						if (ip_debug > 2) {
8897 							pr_addr_dbg(
8898 							    "ip_newroute: no "
8899 							    "src for gw %s ",
8900 							    AF_INET, &gw);
8901 							printf("through "
8902 							    "interface %s\n",
8903 							    dst_ill->ill_name);
8904 						}
8905 						goto icmp_err_ret;
8906 					}
8907 				}
8908 				save_dst = dst;
8909 				dst = gw;
8910 				gw = INADDR_ANY;
8911 			}
8912 
8913 			/*
8914 			 * We obtain a partial IRE_CACHE which we will pass
8915 			 * along with the resolver query.  When the response
8916 			 * comes back it will be there ready for us to add.
8917 			 * The ire_max_frag is atomically set under the
8918 			 * irebucket lock in ire_add_v[46].
8919 			 */
8920 
8921 			ire = ire_create_mp(
8922 			    (uchar_t *)&dst,		/* dest address */
8923 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8924 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8925 			    (uchar_t *)&gw,		/* gateway address */
8926 			    NULL,			/* no in_src_addr */
8927 			    NULL,			/* ire_max_frag */
8928 			    NULL,			/* Fast Path header */
8929 			    dst_ill->ill_rq,		/* recv-from queue */
8930 			    dst_ill->ill_wq,		/* send-to queue */
8931 			    IRE_CACHE,
8932 			    NULL,
8933 			    src_ipif,			/* Interface ipif */
8934 			    in_ill,			/* Incoming ILL */
8935 			    save_ire->ire_mask,		/* Parent mask */
8936 			    0,
8937 			    save_ire->ire_ihandle,	/* Interface handle */
8938 			    0,				/* flags if any */
8939 			    &(save_ire->ire_uinfo),
8940 			    NULL,
8941 			    NULL,
8942 			    ipst);
8943 
8944 			if (ire == NULL) {
8945 				ire_refrele(save_ire);
8946 				break;
8947 			}
8948 
8949 			if ((sire != NULL) &&
8950 			    (sire->ire_flags & RTF_MULTIRT)) {
8951 				copy_mp = copymsg(first_mp);
8952 				if (copy_mp != NULL)
8953 					MULTIRT_DEBUG_TAG(copy_mp);
8954 			}
8955 
8956 			ire->ire_marks |= ire_marks;
8957 
8958 			/*
8959 			 * Construct message chain for the resolver
8960 			 * of the form:
8961 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8962 			 * Packet could contain a IPSEC_OUT mp.
8963 			 *
8964 			 * NOTE : ire will be added later when the response
8965 			 * comes back from ARP. If the response does not
8966 			 * come back, ARP frees the packet. For this reason,
8967 			 * we can't REFHOLD the bucket of save_ire to prevent
8968 			 * deletions. We may not be able to REFRELE the bucket
8969 			 * if the response never comes back. Thus, before
8970 			 * adding the ire, ire_add_v4 will make sure that the
8971 			 * interface route does not get deleted. This is the
8972 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8973 			 * where we can always prevent deletions because of
8974 			 * the synchronous nature of adding IRES i.e
8975 			 * ire_add_then_send is called after creating the IRE.
8976 			 */
8977 			ASSERT(ire->ire_mp != NULL);
8978 			ire->ire_mp->b_cont = first_mp;
8979 			/* Have saved_mp handy, for cleanup if canput fails */
8980 			saved_mp = mp;
8981 			mp = copyb(res_mp);
8982 			if (mp == NULL) {
8983 				/* Prepare for cleanup */
8984 				mp = saved_mp; /* pkt */
8985 				ire_delete(ire); /* ire_mp */
8986 				ire = NULL;
8987 				ire_refrele(save_ire);
8988 				if (copy_mp != NULL) {
8989 					MULTIRT_DEBUG_UNTAG(copy_mp);
8990 					freemsg(copy_mp);
8991 					copy_mp = NULL;
8992 				}
8993 				break;
8994 			}
8995 			linkb(mp, ire->ire_mp);
8996 
8997 			/*
8998 			 * Fill in the source and dest addrs for the resolver.
8999 			 * NOTE: this depends on memory layouts imposed by
9000 			 * ill_init().
9001 			 */
9002 			areq = (areq_t *)mp->b_rptr;
9003 			addrp = (ipaddr_t *)((char *)areq +
9004 			    areq->areq_sender_addr_offset);
9005 			if (do_attach_ill) {
9006 				/*
9007 				 * This is bind to no failover case.
9008 				 * arp packet also must go out on attach_ill.
9009 				 */
9010 				ASSERT(ipha->ipha_src != NULL);
9011 				*addrp = ipha->ipha_src;
9012 			} else {
9013 				*addrp = save_ire->ire_src_addr;
9014 			}
9015 
9016 			ire_refrele(save_ire);
9017 			addrp = (ipaddr_t *)((char *)areq +
9018 			    areq->areq_target_addr_offset);
9019 			*addrp = dst;
9020 			/* Up to the resolver. */
9021 			if (canputnext(dst_ill->ill_rq) &&
9022 			    !(dst_ill->ill_arp_closing)) {
9023 				putnext(dst_ill->ill_rq, mp);
9024 				ire = NULL;
9025 				if (copy_mp != NULL) {
9026 					/*
9027 					 * If we found a resolver, we ignore
9028 					 * any trailing top priority IRE_CACHE
9029 					 * in the further loops. This ensures
9030 					 * that we do not omit any resolver.
9031 					 * IRE_CACHE entries, if any, will be
9032 					 * processed next time we enter
9033 					 * ip_newroute().
9034 					 */
9035 					multirt_flags &= ~MULTIRT_CACHEGW;
9036 					/*
9037 					 * Search for the next unresolved
9038 					 * multirt route.
9039 					 */
9040 					first_mp = copy_mp;
9041 					copy_mp = NULL;
9042 					/* Prepare the next resolution loop. */
9043 					mp = first_mp;
9044 					EXTRACT_PKT_MP(mp, first_mp,
9045 					    mctl_present);
9046 					if (mctl_present)
9047 						io = (ipsec_out_t *)
9048 						    first_mp->b_rptr;
9049 					ipha = (ipha_t *)mp->b_rptr;
9050 
9051 					ASSERT(sire != NULL);
9052 
9053 					dst = save_dst;
9054 					multirt_resolve_next = B_TRUE;
9055 					continue;
9056 				}
9057 
9058 				if (sire != NULL)
9059 					ire_refrele(sire);
9060 
9061 				/*
9062 				 * The response will come back in ip_wput
9063 				 * with db_type IRE_DB_TYPE.
9064 				 */
9065 				ipif_refrele(src_ipif);
9066 				ill_refrele(dst_ill);
9067 				return;
9068 			} else {
9069 				/* Prepare for cleanup */
9070 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9071 				    mp);
9072 				mp->b_cont = NULL;
9073 				freeb(mp); /* areq */
9074 				/*
9075 				 * this is an ire that is not added to the
9076 				 * cache. ire_freemblk will handle the release
9077 				 * of any resources associated with the ire.
9078 				 */
9079 				ire_delete(ire); /* ire_mp */
9080 				mp = saved_mp; /* pkt */
9081 				ire = NULL;
9082 				if (copy_mp != NULL) {
9083 					MULTIRT_DEBUG_UNTAG(copy_mp);
9084 					freemsg(copy_mp);
9085 					copy_mp = NULL;
9086 				}
9087 				break;
9088 			}
9089 		default:
9090 			break;
9091 		}
9092 	} while (multirt_resolve_next);
9093 
9094 	ip1dbg(("ip_newroute: dropped\n"));
9095 	/* Did this packet originate externally? */
9096 	if (mp->b_prev) {
9097 		mp->b_next = NULL;
9098 		mp->b_prev = NULL;
9099 		if (in_ill != NULL) {
9100 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9101 		} else {
9102 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9103 		}
9104 	} else {
9105 		if (dst_ill != NULL) {
9106 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9107 		} else {
9108 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9109 		}
9110 	}
9111 	ASSERT(copy_mp == NULL);
9112 	MULTIRT_DEBUG_UNTAG(first_mp);
9113 	freemsg(first_mp);
9114 	if (ire != NULL)
9115 		ire_refrele(ire);
9116 	if (sire != NULL)
9117 		ire_refrele(sire);
9118 	if (src_ipif != NULL)
9119 		ipif_refrele(src_ipif);
9120 	if (dst_ill != NULL)
9121 		ill_refrele(dst_ill);
9122 	return;
9123 
9124 icmp_err_ret:
9125 	ip1dbg(("ip_newroute: no route\n"));
9126 	if (src_ipif != NULL)
9127 		ipif_refrele(src_ipif);
9128 	if (dst_ill != NULL)
9129 		ill_refrele(dst_ill);
9130 	if (sire != NULL)
9131 		ire_refrele(sire);
9132 	/* Did this packet originate externally? */
9133 	if (mp->b_prev) {
9134 		mp->b_next = NULL;
9135 		mp->b_prev = NULL;
9136 		if (in_ill != NULL) {
9137 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9138 		} else {
9139 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9140 		}
9141 		q = WR(q);
9142 	} else {
9143 		/*
9144 		 * There is no outgoing ill, so just increment the
9145 		 * system MIB.
9146 		 */
9147 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9148 		/*
9149 		 * Since ip_wput() isn't close to finished, we fill
9150 		 * in enough of the header for credible error reporting.
9151 		 */
9152 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9153 			/* Failed */
9154 			MULTIRT_DEBUG_UNTAG(first_mp);
9155 			freemsg(first_mp);
9156 			if (ire != NULL)
9157 				ire_refrele(ire);
9158 			return;
9159 		}
9160 	}
9161 
9162 	/*
9163 	 * At this point we will have ire only if RTF_BLACKHOLE
9164 	 * or RTF_REJECT flags are set on the IRE. It will not
9165 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9166 	 */
9167 	if (ire != NULL) {
9168 		if (ire->ire_flags & RTF_BLACKHOLE) {
9169 			ire_refrele(ire);
9170 			MULTIRT_DEBUG_UNTAG(first_mp);
9171 			freemsg(first_mp);
9172 			return;
9173 		}
9174 		ire_refrele(ire);
9175 	}
9176 	if (ip_source_routed(ipha, ipst)) {
9177 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9178 		    zoneid, ipst);
9179 		return;
9180 	}
9181 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9182 }
9183 
9184 ip_opt_info_t zero_info;
9185 
9186 /*
9187  * IPv4 -
9188  * ip_newroute_ipif is called by ip_wput_multicast and
9189  * ip_rput_forward_multicast whenever we need to send
9190  * out a packet to a destination address for which we do not have specific
9191  * routing information. It is used when the packet will be sent out
9192  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9193  * socket option is set or icmp error message wants to go out on a particular
9194  * interface for a unicast packet.
9195  *
9196  * In most cases, the destination address is resolved thanks to the ipif
9197  * intrinsic resolver. However, there are some cases where the call to
9198  * ip_newroute_ipif must take into account the potential presence of
9199  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9200  * that uses the interface. This is specified through flags,
9201  * which can be a combination of:
9202  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9203  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9204  *   and flags. Additionally, the packet source address has to be set to
9205  *   the specified address. The caller is thus expected to set this flag
9206  *   if the packet has no specific source address yet.
9207  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9208  *   flag, the resulting ire will inherit the flag. All unresolved routes
9209  *   to the destination must be explored in the same call to
9210  *   ip_newroute_ipif().
9211  */
9212 static void
9213 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9214     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9215 {
9216 	areq_t	*areq;
9217 	ire_t	*ire = NULL;
9218 	mblk_t	*res_mp;
9219 	ipaddr_t *addrp;
9220 	mblk_t *first_mp;
9221 	ire_t	*save_ire = NULL;
9222 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9223 	ipif_t	*src_ipif = NULL;
9224 	ushort_t ire_marks = 0;
9225 	ill_t	*dst_ill = NULL;
9226 	boolean_t mctl_present;
9227 	ipsec_out_t *io;
9228 	ipha_t *ipha;
9229 	int	ihandle = 0;
9230 	mblk_t	*saved_mp;
9231 	ire_t   *fire = NULL;
9232 	mblk_t  *copy_mp = NULL;
9233 	boolean_t multirt_resolve_next;
9234 	ipaddr_t ipha_dst;
9235 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9236 
9237 	/*
9238 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9239 	 * here for uniformity
9240 	 */
9241 	ipif_refhold(ipif);
9242 
9243 	/*
9244 	 * This loop is run only once in most cases.
9245 	 * We loop to resolve further routes only when the destination
9246 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9247 	 */
9248 	do {
9249 		if (dst_ill != NULL) {
9250 			ill_refrele(dst_ill);
9251 			dst_ill = NULL;
9252 		}
9253 		if (src_ipif != NULL) {
9254 			ipif_refrele(src_ipif);
9255 			src_ipif = NULL;
9256 		}
9257 		multirt_resolve_next = B_FALSE;
9258 
9259 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9260 		    ipif->ipif_ill->ill_name));
9261 
9262 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9263 		if (mctl_present)
9264 			io = (ipsec_out_t *)first_mp->b_rptr;
9265 
9266 		ipha = (ipha_t *)mp->b_rptr;
9267 
9268 		/*
9269 		 * Save the packet destination address, we may need it after
9270 		 * the packet has been consumed.
9271 		 */
9272 		ipha_dst = ipha->ipha_dst;
9273 
9274 		/*
9275 		 * If the interface is a pt-pt interface we look for an
9276 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9277 		 * local_address and the pt-pt destination address. Otherwise
9278 		 * we just match the local address.
9279 		 * NOTE: dst could be different than ipha->ipha_dst in case
9280 		 * of sending igmp multicast packets over a point-to-point
9281 		 * connection.
9282 		 * Thus we must be careful enough to check ipha_dst to be a
9283 		 * multicast address, otherwise it will take xmit_if path for
9284 		 * multicast packets resulting into kernel stack overflow by
9285 		 * repeated calls to ip_newroute_ipif from ire_send().
9286 		 */
9287 		if (CLASSD(ipha_dst) &&
9288 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9289 			goto err_ret;
9290 		}
9291 
9292 		/*
9293 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9294 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9295 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9296 		 * propagate its flags to the new ire.
9297 		 */
9298 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9299 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9300 			ip2dbg(("ip_newroute_ipif: "
9301 			    "ipif_lookup_multi_ire("
9302 			    "ipif %p, dst %08x) = fire %p\n",
9303 			    (void *)ipif, ntohl(dst), (void *)fire));
9304 		}
9305 
9306 		if (mctl_present && io->ipsec_out_attach_if) {
9307 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9308 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9309 
9310 			/* Failure case frees things for us. */
9311 			if (attach_ill == NULL) {
9312 				ipif_refrele(ipif);
9313 				if (fire != NULL)
9314 					ire_refrele(fire);
9315 				return;
9316 			}
9317 
9318 			/*
9319 			 * Check if we need an ire that will not be
9320 			 * looked up by anybody else i.e. HIDDEN.
9321 			 */
9322 			if (ill_is_probeonly(attach_ill)) {
9323 				ire_marks = IRE_MARK_HIDDEN;
9324 			}
9325 			/*
9326 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9327 			 * case.
9328 			 */
9329 			dst_ill = ipif->ipif_ill;
9330 			/* attach_ill has been refheld by ip_grab_attach_ill */
9331 			ASSERT(dst_ill == attach_ill);
9332 		} else {
9333 			/*
9334 			 * If this is set by IP_XMIT_IF, then make sure that
9335 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9336 			 * specified ill.
9337 			 */
9338 			ASSERT((connp == NULL) ||
9339 			    (connp->conn_xmit_if_ill == NULL) ||
9340 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9341 			/*
9342 			 * If the interface belongs to an interface group,
9343 			 * make sure the next possible interface in the group
9344 			 * is used.  This encourages load spreading among
9345 			 * peers in an interface group.
9346 			 * Note: load spreading is disabled for RTF_MULTIRT
9347 			 * routes.
9348 			 */
9349 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9350 			    (fire->ire_flags & RTF_MULTIRT)) {
9351 				/*
9352 				 * Don't perform outbound load spreading
9353 				 * in the case of an RTF_MULTIRT issued route,
9354 				 * we actually typically want to replicate
9355 				 * outgoing packets through particular
9356 				 * interfaces.
9357 				 */
9358 				dst_ill = ipif->ipif_ill;
9359 				ill_refhold(dst_ill);
9360 			} else {
9361 				dst_ill = ip_newroute_get_dst_ill(
9362 				    ipif->ipif_ill);
9363 			}
9364 			if (dst_ill == NULL) {
9365 				if (ip_debug > 2) {
9366 					pr_addr_dbg("ip_newroute_ipif: "
9367 					    "no dst ill for dst %s\n",
9368 					    AF_INET, &dst);
9369 				}
9370 				goto err_ret;
9371 			}
9372 		}
9373 
9374 		/*
9375 		 * Pick a source address preferring non-deprecated ones.
9376 		 * Unlike ip_newroute, we don't do any source address
9377 		 * selection here since for multicast it really does not help
9378 		 * in inbound load spreading as in the unicast case.
9379 		 */
9380 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9381 		    (fire->ire_flags & RTF_SETSRC)) {
9382 			/*
9383 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9384 			 * on that interface. This ire has RTF_SETSRC flag, so
9385 			 * the source address of the packet must be changed.
9386 			 * Check that the ipif matching the requested source
9387 			 * address still exists.
9388 			 */
9389 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9390 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9391 		}
9392 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9393 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9394 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9395 		    (src_ipif == NULL)) {
9396 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9397 			if (src_ipif == NULL) {
9398 				if (ip_debug > 2) {
9399 					/* ip1dbg */
9400 					pr_addr_dbg("ip_newroute_ipif: "
9401 					    "no src for dst %s",
9402 					    AF_INET, &dst);
9403 				}
9404 				ip1dbg((" through interface %s\n",
9405 				    dst_ill->ill_name));
9406 				goto err_ret;
9407 			}
9408 			ipif_refrele(ipif);
9409 			ipif = src_ipif;
9410 			ipif_refhold(ipif);
9411 		}
9412 		if (src_ipif == NULL) {
9413 			src_ipif = ipif;
9414 			ipif_refhold(src_ipif);
9415 		}
9416 
9417 		/*
9418 		 * Assign a source address while we have the conn.
9419 		 * We can't have ip_wput_ire pick a source address when the
9420 		 * packet returns from arp since conn_unspec_src might be set
9421 		 * and we loose the conn when going through arp.
9422 		 */
9423 		if (ipha->ipha_src == INADDR_ANY &&
9424 		    (connp == NULL || !connp->conn_unspec_src)) {
9425 			ipha->ipha_src = src_ipif->ipif_src_addr;
9426 		}
9427 
9428 		/*
9429 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9430 		 * interface does not have an interface ire.
9431 		 * Example: Thousands of mobileip PPP interfaces to mobile
9432 		 * nodes. We don't want to create interface ires because
9433 		 * packets from other mobile nodes must not take the route
9434 		 * via interface ires to the visiting mobile node without
9435 		 * going through the home agent, in absence of mobileip
9436 		 * route optimization.
9437 		 */
9438 		if (CLASSD(ipha_dst) && (connp == NULL ||
9439 		    connp->conn_xmit_if_ill == NULL) &&
9440 		    infop->ip_opt_ill_index == 0) {
9441 			/* ipif_to_ire returns an held ire */
9442 			ire = ipif_to_ire(ipif);
9443 			if (ire == NULL)
9444 				goto err_ret;
9445 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9446 				goto err_ret;
9447 			/*
9448 			 * ihandle is needed when the ire is added to
9449 			 * cache table.
9450 			 */
9451 			save_ire = ire;
9452 			ihandle = save_ire->ire_ihandle;
9453 
9454 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9455 			    "flags %04x\n",
9456 			    (void *)ire, (void *)ipif, flags));
9457 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9458 			    (fire->ire_flags & RTF_MULTIRT)) {
9459 				/*
9460 				 * As requested by flags, an IRE_OFFSUBNET was
9461 				 * looked up on that interface. This ire has
9462 				 * RTF_MULTIRT flag, so the resolution loop will
9463 				 * be re-entered to resolve additional routes on
9464 				 * other interfaces. For that purpose, a copy of
9465 				 * the packet is performed at this point.
9466 				 */
9467 				fire->ire_last_used_time = lbolt;
9468 				copy_mp = copymsg(first_mp);
9469 				if (copy_mp) {
9470 					MULTIRT_DEBUG_TAG(copy_mp);
9471 				}
9472 			}
9473 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9474 			    (fire->ire_flags & RTF_SETSRC)) {
9475 				/*
9476 				 * As requested by flags, an IRE_OFFSUBET was
9477 				 * looked up on that interface. This ire has
9478 				 * RTF_SETSRC flag, so the source address of the
9479 				 * packet must be changed.
9480 				 */
9481 				ipha->ipha_src = fire->ire_src_addr;
9482 			}
9483 		} else {
9484 			ASSERT((connp == NULL) ||
9485 			    (connp->conn_xmit_if_ill != NULL) ||
9486 			    (connp->conn_dontroute) ||
9487 			    infop->ip_opt_ill_index != 0);
9488 			/*
9489 			 * The only ways we can come here are:
9490 			 * 1) IP_XMIT_IF socket option is set
9491 			 * 2) ICMP error message generated from
9492 			 *    ip_mrtun_forward() routine and it needs
9493 			 *    to go through the specified ill.
9494 			 * 3) SO_DONTROUTE socket option is set
9495 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9496 			 * In all cases, the new ire will not be added
9497 			 * into cache table.
9498 			 */
9499 			ire_marks |= IRE_MARK_NOADD;
9500 		}
9501 
9502 		switch (ipif->ipif_net_type) {
9503 		case IRE_IF_NORESOLVER: {
9504 			/* We have what we need to build an IRE_CACHE. */
9505 			mblk_t	*res_mp;
9506 
9507 			/*
9508 			 * Create a new res_mp with the
9509 			 * IP gateway address as destination address in the
9510 			 * DLPI hdr if the physical length is exactly 4 bytes.
9511 			 */
9512 			if (dst_ill->ill_phys_addr_length == IP_ADDR_LEN) {
9513 				res_mp = ill_dlur_gen((uchar_t *)&dst,
9514 				    dst_ill->ill_phys_addr_length,
9515 				    dst_ill->ill_sap,
9516 				    dst_ill->ill_sap_length);
9517 			} else if (dst_ill->ill_resolver_mp == NULL) {
9518 				ip1dbg(("ip_newroute: dst_ill %p "
9519 				    "for IF_NORESOLV ire %p has "
9520 				    "no ill_resolver_mp\n",
9521 				    (void *)dst_ill, (void *)ire));
9522 				break;
9523 			} else {
9524 				/* use the value set in ip_ll_subnet_defaults */
9525 				res_mp = ill_dlur_gen(NULL,
9526 				    dst_ill->ill_phys_addr_length,
9527 				    dst_ill->ill_sap,
9528 				    dst_ill->ill_sap_length);
9529 			}
9530 
9531 			if (res_mp == NULL)
9532 				break;
9533 			/*
9534 			 * The new ire inherits the IRE_OFFSUBNET flags
9535 			 * and source address, if this was requested.
9536 			 */
9537 			ire = ire_create(
9538 			    (uchar_t *)&dst,		/* dest address */
9539 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9540 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9541 			    NULL,			/* gateway address */
9542 			    NULL,
9543 			    &ipif->ipif_mtu,
9544 			    NULL,			/* Fast Path header */
9545 			    dst_ill->ill_rq,		/* recv-from queue */
9546 			    dst_ill->ill_wq,		/* send-to queue */
9547 			    IRE_CACHE,
9548 			    res_mp,
9549 			    src_ipif,
9550 			    NULL,
9551 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9552 			    (fire != NULL) ?		/* Parent handle */
9553 			    fire->ire_phandle : 0,
9554 			    ihandle,			/* Interface handle */
9555 			    (fire != NULL) ?
9556 			    (fire->ire_flags &
9557 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9558 			    (save_ire == NULL ? &ire_uinfo_null :
9559 			    &save_ire->ire_uinfo),
9560 			    NULL,
9561 			    NULL,
9562 			    ipst);
9563 
9564 			freeb(res_mp);
9565 
9566 			if (ire == NULL) {
9567 				if (save_ire != NULL)
9568 					ire_refrele(save_ire);
9569 				break;
9570 			}
9571 
9572 			ire->ire_marks |= ire_marks;
9573 
9574 			/*
9575 			 * If IRE_MARK_NOADD is set then we need to convert
9576 			 * the max_fragp to a useable value now. This is
9577 			 * normally done in ire_add_v[46]. We also need to
9578 			 * associate the ire with an nce (normally would be
9579 			 * done in ip_wput_nondata()).
9580 			 *
9581 			 * Note that IRE_MARK_NOADD packets created here
9582 			 * do not have a non-null ire_mp pointer. The null
9583 			 * value of ire_bucket indicates that they were
9584 			 * never added.
9585 			 */
9586 			if (ire->ire_marks & IRE_MARK_NOADD) {
9587 				uint_t  max_frag;
9588 
9589 				max_frag = *ire->ire_max_fragp;
9590 				ire->ire_max_fragp = NULL;
9591 				ire->ire_max_frag = max_frag;
9592 
9593 				if ((ire->ire_nce = ndp_lookup_v4(
9594 				    ire_to_ill(ire),
9595 				    (ire->ire_gateway_addr != INADDR_ANY ?
9596 				    &ire->ire_gateway_addr : &ire->ire_addr),
9597 				    B_FALSE)) == NULL) {
9598 					if (save_ire != NULL)
9599 						ire_refrele(save_ire);
9600 					break;
9601 				}
9602 				ASSERT(ire->ire_nce->nce_state ==
9603 				    ND_REACHABLE);
9604 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9605 			}
9606 
9607 			/* Prevent save_ire from getting deleted */
9608 			if (save_ire != NULL) {
9609 				IRB_REFHOLD(save_ire->ire_bucket);
9610 				/* Has it been removed already ? */
9611 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9612 					IRB_REFRELE(save_ire->ire_bucket);
9613 					ire_refrele(save_ire);
9614 					break;
9615 				}
9616 			}
9617 
9618 			ire_add_then_send(q, ire, first_mp);
9619 
9620 			/* Assert that save_ire is not deleted yet. */
9621 			if (save_ire != NULL) {
9622 				ASSERT(save_ire->ire_ptpn != NULL);
9623 				IRB_REFRELE(save_ire->ire_bucket);
9624 				ire_refrele(save_ire);
9625 				save_ire = NULL;
9626 			}
9627 			if (fire != NULL) {
9628 				ire_refrele(fire);
9629 				fire = NULL;
9630 			}
9631 
9632 			/*
9633 			 * the resolution loop is re-entered if this
9634 			 * was requested through flags and if we
9635 			 * actually are in a multirouting case.
9636 			 */
9637 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9638 				boolean_t need_resolve =
9639 				    ire_multirt_need_resolve(ipha_dst,
9640 				    MBLK_GETLABEL(copy_mp), ipst);
9641 				if (!need_resolve) {
9642 					MULTIRT_DEBUG_UNTAG(copy_mp);
9643 					freemsg(copy_mp);
9644 					copy_mp = NULL;
9645 				} else {
9646 					/*
9647 					 * ipif_lookup_group() calls
9648 					 * ire_lookup_multi() that uses
9649 					 * ire_ftable_lookup() to find
9650 					 * an IRE_INTERFACE for the group.
9651 					 * In the multirt case,
9652 					 * ire_lookup_multi() then invokes
9653 					 * ire_multirt_lookup() to find
9654 					 * the next resolvable ire.
9655 					 * As a result, we obtain an new
9656 					 * interface, derived from the
9657 					 * next ire.
9658 					 */
9659 					ipif_refrele(ipif);
9660 					ipif = ipif_lookup_group(ipha_dst,
9661 					    zoneid, ipst);
9662 					ip2dbg(("ip_newroute_ipif: "
9663 					    "multirt dst %08x, ipif %p\n",
9664 					    htonl(dst), (void *)ipif));
9665 					if (ipif != NULL) {
9666 						mp = copy_mp;
9667 						copy_mp = NULL;
9668 						multirt_resolve_next = B_TRUE;
9669 						continue;
9670 					} else {
9671 						freemsg(copy_mp);
9672 					}
9673 				}
9674 			}
9675 			if (ipif != NULL)
9676 				ipif_refrele(ipif);
9677 			ill_refrele(dst_ill);
9678 			ipif_refrele(src_ipif);
9679 			return;
9680 		}
9681 		case IRE_IF_RESOLVER:
9682 			/*
9683 			 * We can't build an IRE_CACHE yet, but at least
9684 			 * we found a resolver that can help.
9685 			 */
9686 			res_mp = dst_ill->ill_resolver_mp;
9687 			if (!OK_RESOLVER_MP(res_mp))
9688 				break;
9689 
9690 			/*
9691 			 * We obtain a partial IRE_CACHE which we will pass
9692 			 * along with the resolver query.  When the response
9693 			 * comes back it will be there ready for us to add.
9694 			 * The new ire inherits the IRE_OFFSUBNET flags
9695 			 * and source address, if this was requested.
9696 			 * The ire_max_frag is atomically set under the
9697 			 * irebucket lock in ire_add_v[46]. Only in the
9698 			 * case of IRE_MARK_NOADD, we set it here itself.
9699 			 */
9700 			ire = ire_create_mp(
9701 			    (uchar_t *)&dst,		/* dest address */
9702 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9703 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9704 			    NULL,			/* gateway address */
9705 			    NULL,			/* no in_src_addr */
9706 			    (ire_marks & IRE_MARK_NOADD) ?
9707 			    ipif->ipif_mtu : 0,	/* max_frag */
9708 			    NULL,			/* Fast path header */
9709 			    dst_ill->ill_rq,		/* recv-from queue */
9710 			    dst_ill->ill_wq,		/* send-to queue */
9711 			    IRE_CACHE,
9712 			    NULL,	/* let ire_nce_init figure res_mp out */
9713 			    src_ipif,
9714 			    NULL,
9715 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9716 			    (fire != NULL) ?		/* Parent handle */
9717 			    fire->ire_phandle : 0,
9718 			    ihandle,			/* Interface handle */
9719 			    (fire != NULL) ?		/* flags if any */
9720 			    (fire->ire_flags &
9721 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9722 			    (save_ire == NULL ? &ire_uinfo_null :
9723 			    &save_ire->ire_uinfo),
9724 			    NULL,
9725 			    NULL,
9726 			    ipst);
9727 
9728 			if (save_ire != NULL) {
9729 				ire_refrele(save_ire);
9730 				save_ire = NULL;
9731 			}
9732 			if (ire == NULL)
9733 				break;
9734 
9735 			ire->ire_marks |= ire_marks;
9736 			/*
9737 			 * Construct message chain for the resolver of the
9738 			 * form:
9739 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9740 			 *
9741 			 * NOTE : ire will be added later when the response
9742 			 * comes back from ARP. If the response does not
9743 			 * come back, ARP frees the packet. For this reason,
9744 			 * we can't REFHOLD the bucket of save_ire to prevent
9745 			 * deletions. We may not be able to REFRELE the
9746 			 * bucket if the response never comes back.
9747 			 * Thus, before adding the ire, ire_add_v4 will make
9748 			 * sure that the interface route does not get deleted.
9749 			 * This is the only case unlike ip_newroute_v6,
9750 			 * ip_newroute_ipif_v6 where we can always prevent
9751 			 * deletions because ire_add_then_send is called after
9752 			 * creating the IRE.
9753 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9754 			 * does not add this IRE into the IRE CACHE.
9755 			 */
9756 			ASSERT(ire->ire_mp != NULL);
9757 			ire->ire_mp->b_cont = first_mp;
9758 			/* Have saved_mp handy, for cleanup if canput fails */
9759 			saved_mp = mp;
9760 			mp = copyb(res_mp);
9761 			if (mp == NULL) {
9762 				/* Prepare for cleanup */
9763 				mp = saved_mp; /* pkt */
9764 				ire_delete(ire); /* ire_mp */
9765 				ire = NULL;
9766 				if (copy_mp != NULL) {
9767 					MULTIRT_DEBUG_UNTAG(copy_mp);
9768 					freemsg(copy_mp);
9769 					copy_mp = NULL;
9770 				}
9771 				break;
9772 			}
9773 			linkb(mp, ire->ire_mp);
9774 
9775 			/*
9776 			 * Fill in the source and dest addrs for the resolver.
9777 			 * NOTE: this depends on memory layouts imposed by
9778 			 * ill_init().
9779 			 */
9780 			areq = (areq_t *)mp->b_rptr;
9781 			addrp = (ipaddr_t *)((char *)areq +
9782 			    areq->areq_sender_addr_offset);
9783 			*addrp = ire->ire_src_addr;
9784 			addrp = (ipaddr_t *)((char *)areq +
9785 			    areq->areq_target_addr_offset);
9786 			*addrp = dst;
9787 			/* Up to the resolver. */
9788 			if (canputnext(dst_ill->ill_rq) &&
9789 			    !(dst_ill->ill_arp_closing)) {
9790 				putnext(dst_ill->ill_rq, mp);
9791 				/*
9792 				 * The response will come back in ip_wput
9793 				 * with db_type IRE_DB_TYPE.
9794 				 */
9795 			} else {
9796 				mp->b_cont = NULL;
9797 				freeb(mp); /* areq */
9798 				ire_delete(ire); /* ire_mp */
9799 				saved_mp->b_next = NULL;
9800 				saved_mp->b_prev = NULL;
9801 				freemsg(first_mp); /* pkt */
9802 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9803 			}
9804 
9805 			if (fire != NULL) {
9806 				ire_refrele(fire);
9807 				fire = NULL;
9808 			}
9809 
9810 
9811 			/*
9812 			 * The resolution loop is re-entered if this was
9813 			 * requested through flags and we actually are
9814 			 * in a multirouting case.
9815 			 */
9816 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9817 				boolean_t need_resolve =
9818 				    ire_multirt_need_resolve(ipha_dst,
9819 				    MBLK_GETLABEL(copy_mp), ipst);
9820 				if (!need_resolve) {
9821 					MULTIRT_DEBUG_UNTAG(copy_mp);
9822 					freemsg(copy_mp);
9823 					copy_mp = NULL;
9824 				} else {
9825 					/*
9826 					 * ipif_lookup_group() calls
9827 					 * ire_lookup_multi() that uses
9828 					 * ire_ftable_lookup() to find
9829 					 * an IRE_INTERFACE for the group.
9830 					 * In the multirt case,
9831 					 * ire_lookup_multi() then invokes
9832 					 * ire_multirt_lookup() to find
9833 					 * the next resolvable ire.
9834 					 * As a result, we obtain an new
9835 					 * interface, derived from the
9836 					 * next ire.
9837 					 */
9838 					ipif_refrele(ipif);
9839 					ipif = ipif_lookup_group(ipha_dst,
9840 					    zoneid, ipst);
9841 					if (ipif != NULL) {
9842 						mp = copy_mp;
9843 						copy_mp = NULL;
9844 						multirt_resolve_next = B_TRUE;
9845 						continue;
9846 					} else {
9847 						freemsg(copy_mp);
9848 					}
9849 				}
9850 			}
9851 			if (ipif != NULL)
9852 				ipif_refrele(ipif);
9853 			ill_refrele(dst_ill);
9854 			ipif_refrele(src_ipif);
9855 			return;
9856 		default:
9857 			break;
9858 		}
9859 	} while (multirt_resolve_next);
9860 
9861 err_ret:
9862 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9863 	if (fire != NULL)
9864 		ire_refrele(fire);
9865 	ipif_refrele(ipif);
9866 	/* Did this packet originate externally? */
9867 	if (dst_ill != NULL)
9868 		ill_refrele(dst_ill);
9869 	if (src_ipif != NULL)
9870 		ipif_refrele(src_ipif);
9871 	if (mp->b_prev || mp->b_next) {
9872 		mp->b_next = NULL;
9873 		mp->b_prev = NULL;
9874 	} else {
9875 		/*
9876 		 * Since ip_wput() isn't close to finished, we fill
9877 		 * in enough of the header for credible error reporting.
9878 		 */
9879 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9880 			/* Failed */
9881 			freemsg(first_mp);
9882 			if (ire != NULL)
9883 				ire_refrele(ire);
9884 			return;
9885 		}
9886 	}
9887 	/*
9888 	 * At this point we will have ire only if RTF_BLACKHOLE
9889 	 * or RTF_REJECT flags are set on the IRE. It will not
9890 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9891 	 */
9892 	if (ire != NULL) {
9893 		if (ire->ire_flags & RTF_BLACKHOLE) {
9894 			ire_refrele(ire);
9895 			freemsg(first_mp);
9896 			return;
9897 		}
9898 		ire_refrele(ire);
9899 	}
9900 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9901 }
9902 
9903 /* Name/Value Table Lookup Routine */
9904 char *
9905 ip_nv_lookup(nv_t *nv, int value)
9906 {
9907 	if (!nv)
9908 		return (NULL);
9909 	for (; nv->nv_name; nv++) {
9910 		if (nv->nv_value == value)
9911 			return (nv->nv_name);
9912 	}
9913 	return ("unknown");
9914 }
9915 
9916 /*
9917  * This is a module open, i.e. this is a control stream for access
9918  * to a DLPI device.  We allocate an ill_t as the instance data in
9919  * this case.
9920  */
9921 int
9922 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9923 {
9924 	ill_t	*ill;
9925 	int	err;
9926 	zoneid_t zoneid;
9927 	netstack_t *ns;
9928 	ip_stack_t *ipst;
9929 
9930 	/*
9931 	 * Prevent unprivileged processes from pushing IP so that
9932 	 * they can't send raw IP.
9933 	 */
9934 	if (secpolicy_net_rawaccess(credp) != 0)
9935 		return (EPERM);
9936 
9937 	ns = netstack_find_by_cred(credp);
9938 	ASSERT(ns != NULL);
9939 	ipst = ns->netstack_ip;
9940 	ASSERT(ipst != NULL);
9941 
9942 	/*
9943 	 * For exclusive stacks we set the zoneid to zero
9944 	 * to make IP operate as if in the global zone.
9945 	 */
9946 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9947 		zoneid = GLOBAL_ZONEID;
9948 	else
9949 		zoneid = crgetzoneid(credp);
9950 
9951 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9952 	q->q_ptr = WR(q)->q_ptr = ill;
9953 	ill->ill_ipst = ipst;
9954 	ill->ill_zoneid = zoneid;
9955 
9956 	/*
9957 	 * ill_init initializes the ill fields and then sends down
9958 	 * down a DL_INFO_REQ after calling qprocson.
9959 	 */
9960 	err = ill_init(q, ill);
9961 	if (err != 0) {
9962 		mi_free(ill);
9963 		netstack_rele(ipst->ips_netstack);
9964 		q->q_ptr = NULL;
9965 		WR(q)->q_ptr = NULL;
9966 		return (err);
9967 	}
9968 
9969 	/* ill_init initializes the ipsq marking this thread as writer */
9970 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9971 	/* Wait for the DL_INFO_ACK */
9972 	mutex_enter(&ill->ill_lock);
9973 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9974 		/*
9975 		 * Return value of 0 indicates a pending signal.
9976 		 */
9977 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9978 		if (err == 0) {
9979 			mutex_exit(&ill->ill_lock);
9980 			(void) ip_close(q, 0);
9981 			return (EINTR);
9982 		}
9983 	}
9984 	mutex_exit(&ill->ill_lock);
9985 
9986 	/*
9987 	 * ip_rput_other could have set an error  in ill_error on
9988 	 * receipt of M_ERROR.
9989 	 */
9990 
9991 	err = ill->ill_error;
9992 	if (err != 0) {
9993 		(void) ip_close(q, 0);
9994 		return (err);
9995 	}
9996 
9997 	ill->ill_credp = credp;
9998 	crhold(credp);
9999 
10000 	mutex_enter(&ipst->ips_ip_mi_lock);
10001 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
10002 	    credp);
10003 	mutex_exit(&ipst->ips_ip_mi_lock);
10004 	if (err) {
10005 		(void) ip_close(q, 0);
10006 		return (err);
10007 	}
10008 	return (0);
10009 }
10010 
10011 /* IP open routine. */
10012 int
10013 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
10014 {
10015 	conn_t 		*connp;
10016 	major_t		maj;
10017 	zoneid_t	zoneid;
10018 	netstack_t	*ns;
10019 	ip_stack_t	*ipst;
10020 
10021 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
10022 
10023 	/* Allow reopen. */
10024 	if (q->q_ptr != NULL)
10025 		return (0);
10026 
10027 	if (sflag & MODOPEN) {
10028 		/* This is a module open */
10029 		return (ip_modopen(q, devp, flag, sflag, credp));
10030 	}
10031 
10032 	ns = netstack_find_by_cred(credp);
10033 	ASSERT(ns != NULL);
10034 	ipst = ns->netstack_ip;
10035 	ASSERT(ipst != NULL);
10036 
10037 	/*
10038 	 * For exclusive stacks we set the zoneid to zero
10039 	 * to make IP operate as if in the global zone.
10040 	 */
10041 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10042 		zoneid = GLOBAL_ZONEID;
10043 	else
10044 		zoneid = crgetzoneid(credp);
10045 
10046 	/*
10047 	 * We are opening as a device. This is an IP client stream, and we
10048 	 * allocate an conn_t as the instance data.
10049 	 */
10050 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10051 
10052 	/*
10053 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10054 	 * done by netstack_find_by_cred()
10055 	 */
10056 	netstack_rele(ipst->ips_netstack);
10057 
10058 	connp->conn_zoneid = zoneid;
10059 
10060 	connp->conn_upq = q;
10061 	q->q_ptr = WR(q)->q_ptr = connp;
10062 
10063 	if (flag & SO_SOCKSTR)
10064 		connp->conn_flags |= IPCL_SOCKET;
10065 
10066 	/* Minor tells us which /dev entry was opened */
10067 	if (geteminor(*devp) == IPV6_MINOR) {
10068 		connp->conn_flags |= IPCL_ISV6;
10069 		connp->conn_af_isv6 = B_TRUE;
10070 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10071 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10072 	} else {
10073 		connp->conn_af_isv6 = B_FALSE;
10074 		connp->conn_pkt_isv6 = B_FALSE;
10075 	}
10076 
10077 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10078 		/* CONN_DEC_REF takes care of netstack_rele() */
10079 		q->q_ptr = WR(q)->q_ptr = NULL;
10080 		CONN_DEC_REF(connp);
10081 		return (EBUSY);
10082 	}
10083 
10084 	maj = getemajor(*devp);
10085 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10086 
10087 	/*
10088 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10089 	 */
10090 	connp->conn_cred = credp;
10091 	crhold(connp->conn_cred);
10092 
10093 	/*
10094 	 * If the caller has the process-wide flag set, then default to MAC
10095 	 * exempt mode.  This allows read-down to unlabeled hosts.
10096 	 */
10097 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10098 		connp->conn_mac_exempt = B_TRUE;
10099 
10100 	/*
10101 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10102 	 * administrative ops.  In these cases, we just need a normal conn_t
10103 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10104 	 * an error will be returned.
10105 	 */
10106 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10107 		connp->conn_rq = q;
10108 		connp->conn_wq = WR(q);
10109 	} else {
10110 		connp->conn_ulp = IPPROTO_SCTP;
10111 		connp->conn_rq = connp->conn_wq = NULL;
10112 	}
10113 	/* Non-zero default values */
10114 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10115 
10116 	/*
10117 	 * Make the conn globally visible to walkers
10118 	 */
10119 	mutex_enter(&connp->conn_lock);
10120 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10121 	mutex_exit(&connp->conn_lock);
10122 	ASSERT(connp->conn_ref == 1);
10123 
10124 	qprocson(q);
10125 
10126 	return (0);
10127 }
10128 
10129 /*
10130  * Change q_qinfo based on the value of isv6.
10131  * This can not called on an ill queue.
10132  * Note that there is no race since either q_qinfo works for conn queues - it
10133  * is just an optimization to enter the best wput routine directly.
10134  */
10135 void
10136 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10137 {
10138 	ASSERT(q->q_flag & QREADR);
10139 	ASSERT(WR(q)->q_next == NULL);
10140 	ASSERT(q->q_ptr != NULL);
10141 
10142 	if (minor == IPV6_MINOR)  {
10143 		if (bump_mib) {
10144 			BUMP_MIB(&ipst->ips_ip6_mib,
10145 			    ipIfStatsOutSwitchIPVersion);
10146 		}
10147 		q->q_qinfo = &rinit_ipv6;
10148 		WR(q)->q_qinfo = &winit_ipv6;
10149 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10150 	} else {
10151 		if (bump_mib) {
10152 			BUMP_MIB(&ipst->ips_ip_mib,
10153 			    ipIfStatsOutSwitchIPVersion);
10154 		}
10155 		q->q_qinfo = &iprinit;
10156 		WR(q)->q_qinfo = &ipwinit;
10157 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10158 	}
10159 
10160 }
10161 
10162 /*
10163  * See if IPsec needs loading because of the options in mp.
10164  */
10165 static boolean_t
10166 ipsec_opt_present(mblk_t *mp)
10167 {
10168 	uint8_t *optcp, *next_optcp, *opt_endcp;
10169 	struct opthdr *opt;
10170 	struct T_opthdr *topt;
10171 	int opthdr_len;
10172 	t_uscalar_t optname, optlevel;
10173 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10174 	ipsec_req_t *ipsr;
10175 
10176 	/*
10177 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10178 	 * return TRUE.
10179 	 */
10180 
10181 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10182 	opt_endcp = optcp + tor->OPT_length;
10183 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10184 		opthdr_len = sizeof (struct T_opthdr);
10185 	} else {		/* O_OPTMGMT_REQ */
10186 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10187 		opthdr_len = sizeof (struct opthdr);
10188 	}
10189 	for (; optcp < opt_endcp; optcp = next_optcp) {
10190 		if (optcp + opthdr_len > opt_endcp)
10191 			return (B_FALSE);	/* Not enough option header. */
10192 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10193 			topt = (struct T_opthdr *)optcp;
10194 			optlevel = topt->level;
10195 			optname = topt->name;
10196 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10197 		} else {
10198 			opt = (struct opthdr *)optcp;
10199 			optlevel = opt->level;
10200 			optname = opt->name;
10201 			next_optcp = optcp + opthdr_len +
10202 			    _TPI_ALIGN_OPT(opt->len);
10203 		}
10204 		if ((next_optcp < optcp) || /* wraparound pointer space */
10205 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10206 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10207 			return (B_FALSE); /* bad option buffer */
10208 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10209 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10210 			/*
10211 			 * Check to see if it's an all-bypass or all-zeroes
10212 			 * IPsec request.  Don't bother loading IPsec if
10213 			 * the socket doesn't want to use it.  (A good example
10214 			 * is a bypass request.)
10215 			 *
10216 			 * Basically, if any of the non-NEVER bits are set,
10217 			 * load IPsec.
10218 			 */
10219 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10220 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10221 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10222 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10223 			    != 0)
10224 				return (B_TRUE);
10225 		}
10226 	}
10227 	return (B_FALSE);
10228 }
10229 
10230 /*
10231  * If conn is is waiting for ipsec to finish loading, kick it.
10232  */
10233 /* ARGSUSED */
10234 static void
10235 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10236 {
10237 	t_scalar_t	optreq_prim;
10238 	mblk_t		*mp;
10239 	cred_t		*cr;
10240 	int		err = 0;
10241 
10242 	/*
10243 	 * This function is called, after ipsec loading is complete.
10244 	 * Since IP checks exclusively and atomically (i.e it prevents
10245 	 * ipsec load from completing until ip_optcom_req completes)
10246 	 * whether ipsec load is complete, there cannot be a race with IP
10247 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10248 	 */
10249 	mutex_enter(&connp->conn_lock);
10250 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10251 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10252 		mp = connp->conn_ipsec_opt_mp;
10253 		connp->conn_ipsec_opt_mp = NULL;
10254 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10255 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10256 		mutex_exit(&connp->conn_lock);
10257 
10258 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10259 
10260 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10261 		if (optreq_prim == T_OPTMGMT_REQ) {
10262 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10263 			    &ip_opt_obj);
10264 		} else {
10265 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10266 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10267 			    &ip_opt_obj);
10268 		}
10269 		if (err != EINPROGRESS)
10270 			CONN_OPER_PENDING_DONE(connp);
10271 		return;
10272 	}
10273 	mutex_exit(&connp->conn_lock);
10274 }
10275 
10276 /*
10277  * Called from the ipsec_loader thread, outside any perimeter, to tell
10278  * ip qenable any of the queues waiting for the ipsec loader to
10279  * complete.
10280  */
10281 void
10282 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10283 {
10284 	netstack_t *ns = ipss->ipsec_netstack;
10285 
10286 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10287 }
10288 
10289 /*
10290  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10291  * determines the grp on which it has to become exclusive, queues the mp
10292  * and sq draining restarts the optmgmt
10293  */
10294 static boolean_t
10295 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10296 {
10297 	conn_t *connp = Q_TO_CONN(q);
10298 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10299 
10300 	/*
10301 	 * Take IPsec requests and treat them special.
10302 	 */
10303 	if (ipsec_opt_present(mp)) {
10304 		/* First check if IPsec is loaded. */
10305 		mutex_enter(&ipss->ipsec_loader_lock);
10306 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10307 			mutex_exit(&ipss->ipsec_loader_lock);
10308 			return (B_FALSE);
10309 		}
10310 		mutex_enter(&connp->conn_lock);
10311 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10312 
10313 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10314 		connp->conn_ipsec_opt_mp = mp;
10315 		mutex_exit(&connp->conn_lock);
10316 		mutex_exit(&ipss->ipsec_loader_lock);
10317 
10318 		ipsec_loader_loadnow(ipss);
10319 		return (B_TRUE);
10320 	}
10321 	return (B_FALSE);
10322 }
10323 
10324 /*
10325  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10326  * all of them are copied to the conn_t. If the req is "zero", the policy is
10327  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10328  * fields.
10329  * We keep only the latest setting of the policy and thus policy setting
10330  * is not incremental/cumulative.
10331  *
10332  * Requests to set policies with multiple alternative actions will
10333  * go through a different API.
10334  */
10335 int
10336 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10337 {
10338 	uint_t ah_req = 0;
10339 	uint_t esp_req = 0;
10340 	uint_t se_req = 0;
10341 	ipsec_selkey_t sel;
10342 	ipsec_act_t *actp = NULL;
10343 	uint_t nact;
10344 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10345 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10346 	ipsec_policy_root_t *pr;
10347 	ipsec_policy_head_t *ph;
10348 	int fam;
10349 	boolean_t is_pol_reset;
10350 	int error = 0;
10351 	netstack_t	*ns = connp->conn_netstack;
10352 	ip_stack_t	*ipst = ns->netstack_ip;
10353 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10354 
10355 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10356 
10357 	/*
10358 	 * The IP_SEC_OPT option does not allow variable length parameters,
10359 	 * hence a request cannot be NULL.
10360 	 */
10361 	if (req == NULL)
10362 		return (EINVAL);
10363 
10364 	ah_req = req->ipsr_ah_req;
10365 	esp_req = req->ipsr_esp_req;
10366 	se_req = req->ipsr_self_encap_req;
10367 
10368 	/*
10369 	 * Are we dealing with a request to reset the policy (i.e.
10370 	 * zero requests).
10371 	 */
10372 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10373 	    (esp_req & REQ_MASK) == 0 &&
10374 	    (se_req & REQ_MASK) == 0);
10375 
10376 	if (!is_pol_reset) {
10377 		/*
10378 		 * If we couldn't load IPsec, fail with "protocol
10379 		 * not supported".
10380 		 * IPsec may not have been loaded for a request with zero
10381 		 * policies, so we don't fail in this case.
10382 		 */
10383 		mutex_enter(&ipss->ipsec_loader_lock);
10384 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10385 			mutex_exit(&ipss->ipsec_loader_lock);
10386 			return (EPROTONOSUPPORT);
10387 		}
10388 		mutex_exit(&ipss->ipsec_loader_lock);
10389 
10390 		/*
10391 		 * Test for valid requests. Invalid algorithms
10392 		 * need to be tested by IPSEC code because new
10393 		 * algorithms can be added dynamically.
10394 		 */
10395 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10396 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10397 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10398 			return (EINVAL);
10399 		}
10400 
10401 		/*
10402 		 * Only privileged users can issue these
10403 		 * requests.
10404 		 */
10405 		if (((ah_req & IPSEC_PREF_NEVER) ||
10406 		    (esp_req & IPSEC_PREF_NEVER) ||
10407 		    (se_req & IPSEC_PREF_NEVER)) &&
10408 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10409 			return (EPERM);
10410 		}
10411 
10412 		/*
10413 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10414 		 * are mutually exclusive.
10415 		 */
10416 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10417 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10418 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10419 			/* Both of them are set */
10420 			return (EINVAL);
10421 		}
10422 	}
10423 
10424 	mutex_enter(&connp->conn_lock);
10425 
10426 	/*
10427 	 * If we have already cached policies in ip_bind_connected*(), don't
10428 	 * let them change now. We cache policies for connections
10429 	 * whose src,dst [addr, port] is known.
10430 	 */
10431 	if (connp->conn_policy_cached) {
10432 		mutex_exit(&connp->conn_lock);
10433 		return (EINVAL);
10434 	}
10435 
10436 	/*
10437 	 * We have a zero policies, reset the connection policy if already
10438 	 * set. This will cause the connection to inherit the
10439 	 * global policy, if any.
10440 	 */
10441 	if (is_pol_reset) {
10442 		if (connp->conn_policy != NULL) {
10443 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10444 			connp->conn_policy = NULL;
10445 		}
10446 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10447 		connp->conn_in_enforce_policy = B_FALSE;
10448 		connp->conn_out_enforce_policy = B_FALSE;
10449 		mutex_exit(&connp->conn_lock);
10450 		return (0);
10451 	}
10452 
10453 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10454 	    ipst->ips_netstack);
10455 	if (ph == NULL)
10456 		goto enomem;
10457 
10458 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10459 	if (actp == NULL)
10460 		goto enomem;
10461 
10462 	/*
10463 	 * Always allocate IPv4 policy entries, since they can also
10464 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10465 	 */
10466 	bzero(&sel, sizeof (sel));
10467 	sel.ipsl_valid = IPSL_IPV4;
10468 
10469 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10470 	    ipst->ips_netstack);
10471 	if (pin4 == NULL)
10472 		goto enomem;
10473 
10474 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10475 	    ipst->ips_netstack);
10476 	if (pout4 == NULL)
10477 		goto enomem;
10478 
10479 	if (connp->conn_pkt_isv6) {
10480 		/*
10481 		 * We're looking at a v6 socket, also allocate the
10482 		 * v6-specific entries...
10483 		 */
10484 		sel.ipsl_valid = IPSL_IPV6;
10485 		pin6 = ipsec_policy_create(&sel, actp, nact,
10486 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10487 		if (pin6 == NULL)
10488 			goto enomem;
10489 
10490 		pout6 = ipsec_policy_create(&sel, actp, nact,
10491 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10492 		if (pout6 == NULL)
10493 			goto enomem;
10494 
10495 		/*
10496 		 * .. and file them away in the right place.
10497 		 */
10498 		fam = IPSEC_AF_V6;
10499 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10500 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10501 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10502 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10503 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10504 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10505 	}
10506 
10507 	ipsec_actvec_free(actp, nact);
10508 
10509 	/*
10510 	 * File the v4 policies.
10511 	 */
10512 	fam = IPSEC_AF_V4;
10513 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10514 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10515 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10516 
10517 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10518 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10519 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10520 
10521 	/*
10522 	 * If the requests need security, set enforce_policy.
10523 	 * If the requests are IPSEC_PREF_NEVER, one should
10524 	 * still set conn_out_enforce_policy so that an ipsec_out
10525 	 * gets attached in ip_wput. This is needed so that
10526 	 * for connections that we don't cache policy in ip_bind,
10527 	 * if global policy matches in ip_wput_attach_policy, we
10528 	 * don't wrongly inherit global policy. Similarly, we need
10529 	 * to set conn_in_enforce_policy also so that we don't verify
10530 	 * policy wrongly.
10531 	 */
10532 	if ((ah_req & REQ_MASK) != 0 ||
10533 	    (esp_req & REQ_MASK) != 0 ||
10534 	    (se_req & REQ_MASK) != 0) {
10535 		connp->conn_in_enforce_policy = B_TRUE;
10536 		connp->conn_out_enforce_policy = B_TRUE;
10537 		connp->conn_flags |= IPCL_CHECK_POLICY;
10538 	}
10539 
10540 	mutex_exit(&connp->conn_lock);
10541 	return (error);
10542 #undef REQ_MASK
10543 
10544 	/*
10545 	 * Common memory-allocation-failure exit path.
10546 	 */
10547 enomem:
10548 	mutex_exit(&connp->conn_lock);
10549 	if (actp != NULL)
10550 		ipsec_actvec_free(actp, nact);
10551 	if (pin4 != NULL)
10552 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10553 	if (pout4 != NULL)
10554 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10555 	if (pin6 != NULL)
10556 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10557 	if (pout6 != NULL)
10558 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10559 	return (ENOMEM);
10560 }
10561 
10562 /*
10563  * Only for options that pass in an IP addr. Currently only V4 options
10564  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10565  * So this function assumes level is IPPROTO_IP
10566  */
10567 int
10568 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10569     mblk_t *first_mp)
10570 {
10571 	ipif_t *ipif = NULL;
10572 	int error;
10573 	ill_t *ill;
10574 	int zoneid;
10575 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10576 
10577 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10578 
10579 	if (addr != INADDR_ANY || checkonly) {
10580 		ASSERT(connp != NULL);
10581 		zoneid = IPCL_ZONEID(connp);
10582 		if (option == IP_NEXTHOP) {
10583 			ipif = ipif_lookup_onlink_addr(addr,
10584 			    connp->conn_zoneid, ipst);
10585 		} else {
10586 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10587 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10588 			    &error, ipst);
10589 		}
10590 		if (ipif == NULL) {
10591 			if (error == EINPROGRESS)
10592 				return (error);
10593 			else if ((option == IP_MULTICAST_IF) ||
10594 			    (option == IP_NEXTHOP))
10595 				return (EHOSTUNREACH);
10596 			else
10597 				return (EINVAL);
10598 		} else if (checkonly) {
10599 			if (option == IP_MULTICAST_IF) {
10600 				ill = ipif->ipif_ill;
10601 				/* not supported by the virtual network iface */
10602 				if (IS_VNI(ill)) {
10603 					ipif_refrele(ipif);
10604 					return (EINVAL);
10605 				}
10606 			}
10607 			ipif_refrele(ipif);
10608 			return (0);
10609 		}
10610 		ill = ipif->ipif_ill;
10611 		mutex_enter(&connp->conn_lock);
10612 		mutex_enter(&ill->ill_lock);
10613 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10614 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10615 			mutex_exit(&ill->ill_lock);
10616 			mutex_exit(&connp->conn_lock);
10617 			ipif_refrele(ipif);
10618 			return (option == IP_MULTICAST_IF ?
10619 			    EHOSTUNREACH : EINVAL);
10620 		}
10621 	} else {
10622 		mutex_enter(&connp->conn_lock);
10623 	}
10624 
10625 	/* None of the options below are supported on the VNI */
10626 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10627 		mutex_exit(&ill->ill_lock);
10628 		mutex_exit(&connp->conn_lock);
10629 		ipif_refrele(ipif);
10630 		return (EINVAL);
10631 	}
10632 
10633 	switch (option) {
10634 	case IP_DONTFAILOVER_IF:
10635 		/*
10636 		 * This option is used by in.mpathd to ensure
10637 		 * that IPMP probe packets only go out on the
10638 		 * test interfaces. in.mpathd sets this option
10639 		 * on the non-failover interfaces.
10640 		 * For backward compatibility, this option
10641 		 * implicitly sets IP_MULTICAST_IF, as used
10642 		 * be done in bind(), so that ip_wput gets
10643 		 * this ipif to send mcast packets.
10644 		 */
10645 		if (ipif != NULL) {
10646 			ASSERT(addr != INADDR_ANY);
10647 			connp->conn_nofailover_ill = ipif->ipif_ill;
10648 			connp->conn_multicast_ipif = ipif;
10649 		} else {
10650 			ASSERT(addr == INADDR_ANY);
10651 			connp->conn_nofailover_ill = NULL;
10652 			connp->conn_multicast_ipif = NULL;
10653 		}
10654 		break;
10655 
10656 	case IP_MULTICAST_IF:
10657 		connp->conn_multicast_ipif = ipif;
10658 		break;
10659 	case IP_NEXTHOP:
10660 		connp->conn_nexthop_v4 = addr;
10661 		connp->conn_nexthop_set = B_TRUE;
10662 		break;
10663 	}
10664 
10665 	if (ipif != NULL) {
10666 		mutex_exit(&ill->ill_lock);
10667 		mutex_exit(&connp->conn_lock);
10668 		ipif_refrele(ipif);
10669 		return (0);
10670 	}
10671 	mutex_exit(&connp->conn_lock);
10672 	/* We succeded in cleared the option */
10673 	return (0);
10674 }
10675 
10676 /*
10677  * For options that pass in an ifindex specifying the ill. V6 options always
10678  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10679  */
10680 int
10681 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10682     int level, int option, mblk_t *first_mp)
10683 {
10684 	ill_t *ill = NULL;
10685 	int error = 0;
10686 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10687 
10688 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10689 	if (ifindex != 0) {
10690 		ASSERT(connp != NULL);
10691 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10692 		    first_mp, ip_restart_optmgmt, &error, ipst);
10693 		if (ill != NULL) {
10694 			if (checkonly) {
10695 				/* not supported by the virtual network iface */
10696 				if (IS_VNI(ill)) {
10697 					ill_refrele(ill);
10698 					return (EINVAL);
10699 				}
10700 				ill_refrele(ill);
10701 				return (0);
10702 			}
10703 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10704 			    0, NULL)) {
10705 				ill_refrele(ill);
10706 				ill = NULL;
10707 				mutex_enter(&connp->conn_lock);
10708 				goto setit;
10709 			}
10710 			mutex_enter(&connp->conn_lock);
10711 			mutex_enter(&ill->ill_lock);
10712 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10713 				mutex_exit(&ill->ill_lock);
10714 				mutex_exit(&connp->conn_lock);
10715 				ill_refrele(ill);
10716 				ill = NULL;
10717 				mutex_enter(&connp->conn_lock);
10718 			}
10719 			goto setit;
10720 		} else if (error == EINPROGRESS) {
10721 			return (error);
10722 		} else {
10723 			error = 0;
10724 		}
10725 	}
10726 	mutex_enter(&connp->conn_lock);
10727 setit:
10728 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10729 
10730 	/*
10731 	 * The options below assume that the ILL (if any) transmits and/or
10732 	 * receives traffic. Neither of which is true for the virtual network
10733 	 * interface, so fail setting these on a VNI.
10734 	 */
10735 	if (IS_VNI(ill)) {
10736 		ASSERT(ill != NULL);
10737 		mutex_exit(&ill->ill_lock);
10738 		mutex_exit(&connp->conn_lock);
10739 		ill_refrele(ill);
10740 		return (EINVAL);
10741 	}
10742 
10743 	if (level == IPPROTO_IP) {
10744 		switch (option) {
10745 		case IP_BOUND_IF:
10746 			connp->conn_incoming_ill = ill;
10747 			connp->conn_outgoing_ill = ill;
10748 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10749 			    0 : ifindex;
10750 			break;
10751 
10752 		case IP_XMIT_IF:
10753 			/*
10754 			 * Similar to IP_BOUND_IF, but this only
10755 			 * determines the outgoing interface for
10756 			 * unicast packets. Also no IRE_CACHE entry
10757 			 * is added for the destination of the
10758 			 * outgoing packets. This feature is needed
10759 			 * for mobile IP.
10760 			 */
10761 			connp->conn_xmit_if_ill = ill;
10762 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10763 			    0 : ifindex;
10764 			break;
10765 
10766 		case IP_MULTICAST_IF:
10767 			/*
10768 			 * This option is an internal special. The socket
10769 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10770 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10771 			 * specifies an ifindex and we try first on V6 ill's.
10772 			 * If we don't find one, we they try using on v4 ill's
10773 			 * intenally and we come here.
10774 			 */
10775 			if (!checkonly && ill != NULL) {
10776 				ipif_t	*ipif;
10777 				ipif = ill->ill_ipif;
10778 
10779 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10780 					mutex_exit(&ill->ill_lock);
10781 					mutex_exit(&connp->conn_lock);
10782 					ill_refrele(ill);
10783 					ill = NULL;
10784 					mutex_enter(&connp->conn_lock);
10785 				} else {
10786 					connp->conn_multicast_ipif = ipif;
10787 				}
10788 			}
10789 			break;
10790 		}
10791 	} else {
10792 		switch (option) {
10793 		case IPV6_BOUND_IF:
10794 			connp->conn_incoming_ill = ill;
10795 			connp->conn_outgoing_ill = ill;
10796 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10797 			    0 : ifindex;
10798 			break;
10799 
10800 		case IPV6_BOUND_PIF:
10801 			/*
10802 			 * Limit all transmit to this ill.
10803 			 * Unlike IPV6_BOUND_IF, using this option
10804 			 * prevents load spreading and failover from
10805 			 * happening when the interface is part of the
10806 			 * group. That's why we don't need to remember
10807 			 * the ifindex in orig_bound_ifindex as in
10808 			 * IPV6_BOUND_IF.
10809 			 */
10810 			connp->conn_outgoing_pill = ill;
10811 			break;
10812 
10813 		case IPV6_DONTFAILOVER_IF:
10814 			/*
10815 			 * This option is used by in.mpathd to ensure
10816 			 * that IPMP probe packets only go out on the
10817 			 * test interfaces. in.mpathd sets this option
10818 			 * on the non-failover interfaces.
10819 			 */
10820 			connp->conn_nofailover_ill = ill;
10821 			/*
10822 			 * For backward compatibility, this option
10823 			 * implicitly sets ip_multicast_ill as used in
10824 			 * IP_MULTICAST_IF so that ip_wput gets
10825 			 * this ipif to send mcast packets.
10826 			 */
10827 			connp->conn_multicast_ill = ill;
10828 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10829 			    0 : ifindex;
10830 			break;
10831 
10832 		case IPV6_MULTICAST_IF:
10833 			/*
10834 			 * Set conn_multicast_ill to be the IPv6 ill.
10835 			 * Set conn_multicast_ipif to be an IPv4 ipif
10836 			 * for ifindex to make IPv4 mapped addresses
10837 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10838 			 * Even if no IPv6 ill exists for the ifindex
10839 			 * we need to check for an IPv4 ifindex in order
10840 			 * for this to work with mapped addresses. In that
10841 			 * case only set conn_multicast_ipif.
10842 			 */
10843 			if (!checkonly) {
10844 				if (ifindex == 0) {
10845 					connp->conn_multicast_ill = NULL;
10846 					connp->conn_orig_multicast_ifindex = 0;
10847 					connp->conn_multicast_ipif = NULL;
10848 				} else if (ill != NULL) {
10849 					connp->conn_multicast_ill = ill;
10850 					connp->conn_orig_multicast_ifindex =
10851 					    ifindex;
10852 				}
10853 			}
10854 			break;
10855 		}
10856 	}
10857 
10858 	if (ill != NULL) {
10859 		mutex_exit(&ill->ill_lock);
10860 		mutex_exit(&connp->conn_lock);
10861 		ill_refrele(ill);
10862 		return (0);
10863 	}
10864 	mutex_exit(&connp->conn_lock);
10865 	/*
10866 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10867 	 * locate the ill and could not set the option (ifindex != 0)
10868 	 */
10869 	return (ifindex == 0 ? 0 : EINVAL);
10870 }
10871 
10872 /* This routine sets socket options. */
10873 /* ARGSUSED */
10874 int
10875 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10876     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10877     void *dummy, cred_t *cr, mblk_t *first_mp)
10878 {
10879 	int		*i1 = (int *)invalp;
10880 	conn_t		*connp = Q_TO_CONN(q);
10881 	int		error = 0;
10882 	boolean_t	checkonly;
10883 	ire_t		*ire;
10884 	boolean_t	found;
10885 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10886 
10887 	switch (optset_context) {
10888 
10889 	case SETFN_OPTCOM_CHECKONLY:
10890 		checkonly = B_TRUE;
10891 		/*
10892 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10893 		 * inlen != 0 implies value supplied and
10894 		 * 	we have to "pretend" to set it.
10895 		 * inlen == 0 implies that there is no
10896 		 * 	value part in T_CHECK request and just validation
10897 		 * done elsewhere should be enough, we just return here.
10898 		 */
10899 		if (inlen == 0) {
10900 			*outlenp = 0;
10901 			return (0);
10902 		}
10903 		break;
10904 	case SETFN_OPTCOM_NEGOTIATE:
10905 	case SETFN_UD_NEGOTIATE:
10906 	case SETFN_CONN_NEGOTIATE:
10907 		checkonly = B_FALSE;
10908 		break;
10909 	default:
10910 		/*
10911 		 * We should never get here
10912 		 */
10913 		*outlenp = 0;
10914 		return (EINVAL);
10915 	}
10916 
10917 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10918 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10919 
10920 	/*
10921 	 * For fixed length options, no sanity check
10922 	 * of passed in length is done. It is assumed *_optcom_req()
10923 	 * routines do the right thing.
10924 	 */
10925 
10926 	switch (level) {
10927 	case SOL_SOCKET:
10928 		/*
10929 		 * conn_lock protects the bitfields, and is used to
10930 		 * set the fields atomically.
10931 		 */
10932 		switch (name) {
10933 		case SO_BROADCAST:
10934 			if (!checkonly) {
10935 				/* TODO: use value someplace? */
10936 				mutex_enter(&connp->conn_lock);
10937 				connp->conn_broadcast = *i1 ? 1 : 0;
10938 				mutex_exit(&connp->conn_lock);
10939 			}
10940 			break;	/* goto sizeof (int) option return */
10941 		case SO_USELOOPBACK:
10942 			if (!checkonly) {
10943 				/* TODO: use value someplace? */
10944 				mutex_enter(&connp->conn_lock);
10945 				connp->conn_loopback = *i1 ? 1 : 0;
10946 				mutex_exit(&connp->conn_lock);
10947 			}
10948 			break;	/* goto sizeof (int) option return */
10949 		case SO_DONTROUTE:
10950 			if (!checkonly) {
10951 				mutex_enter(&connp->conn_lock);
10952 				connp->conn_dontroute = *i1 ? 1 : 0;
10953 				mutex_exit(&connp->conn_lock);
10954 			}
10955 			break;	/* goto sizeof (int) option return */
10956 		case SO_REUSEADDR:
10957 			if (!checkonly) {
10958 				mutex_enter(&connp->conn_lock);
10959 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10960 				mutex_exit(&connp->conn_lock);
10961 			}
10962 			break;	/* goto sizeof (int) option return */
10963 		case SO_PROTOTYPE:
10964 			if (!checkonly) {
10965 				mutex_enter(&connp->conn_lock);
10966 				connp->conn_proto = *i1;
10967 				mutex_exit(&connp->conn_lock);
10968 			}
10969 			break;	/* goto sizeof (int) option return */
10970 		case SO_ALLZONES:
10971 			if (!checkonly) {
10972 				mutex_enter(&connp->conn_lock);
10973 				if (IPCL_IS_BOUND(connp)) {
10974 					mutex_exit(&connp->conn_lock);
10975 					return (EINVAL);
10976 				}
10977 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10978 				mutex_exit(&connp->conn_lock);
10979 			}
10980 			break;	/* goto sizeof (int) option return */
10981 		case SO_ANON_MLP:
10982 			if (!checkonly) {
10983 				mutex_enter(&connp->conn_lock);
10984 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10985 				mutex_exit(&connp->conn_lock);
10986 			}
10987 			break;	/* goto sizeof (int) option return */
10988 		case SO_MAC_EXEMPT:
10989 			if (secpolicy_net_mac_aware(cr) != 0 ||
10990 			    IPCL_IS_BOUND(connp))
10991 				return (EACCES);
10992 			if (!checkonly) {
10993 				mutex_enter(&connp->conn_lock);
10994 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10995 				mutex_exit(&connp->conn_lock);
10996 			}
10997 			break;	/* goto sizeof (int) option return */
10998 		default:
10999 			/*
11000 			 * "soft" error (negative)
11001 			 * option not handled at this level
11002 			 * Note: Do not modify *outlenp
11003 			 */
11004 			return (-EINVAL);
11005 		}
11006 		break;
11007 	case IPPROTO_IP:
11008 		switch (name) {
11009 		case IP_NEXTHOP:
11010 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
11011 				return (EPERM);
11012 			/* FALLTHRU */
11013 		case IP_MULTICAST_IF:
11014 		case IP_DONTFAILOVER_IF: {
11015 			ipaddr_t addr = *i1;
11016 
11017 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
11018 			    first_mp);
11019 			if (error != 0)
11020 				return (error);
11021 			break;	/* goto sizeof (int) option return */
11022 		}
11023 
11024 		case IP_MULTICAST_TTL:
11025 			/* Recorded in transport above IP */
11026 			*outvalp = *invalp;
11027 			*outlenp = sizeof (uchar_t);
11028 			return (0);
11029 		case IP_MULTICAST_LOOP:
11030 			if (!checkonly) {
11031 				mutex_enter(&connp->conn_lock);
11032 				connp->conn_multicast_loop = *invalp ? 1 : 0;
11033 				mutex_exit(&connp->conn_lock);
11034 			}
11035 			*outvalp = *invalp;
11036 			*outlenp = sizeof (uchar_t);
11037 			return (0);
11038 		case IP_ADD_MEMBERSHIP:
11039 		case MCAST_JOIN_GROUP:
11040 		case IP_DROP_MEMBERSHIP:
11041 		case MCAST_LEAVE_GROUP: {
11042 			struct ip_mreq *mreqp;
11043 			struct group_req *greqp;
11044 			ire_t *ire;
11045 			boolean_t done = B_FALSE;
11046 			ipaddr_t group, ifaddr;
11047 			struct sockaddr_in *sin;
11048 			uint32_t *ifindexp;
11049 			boolean_t mcast_opt = B_TRUE;
11050 			mcast_record_t fmode;
11051 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11052 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11053 
11054 			switch (name) {
11055 			case IP_ADD_MEMBERSHIP:
11056 				mcast_opt = B_FALSE;
11057 				/* FALLTHRU */
11058 			case MCAST_JOIN_GROUP:
11059 				fmode = MODE_IS_EXCLUDE;
11060 				optfn = ip_opt_add_group;
11061 				break;
11062 
11063 			case IP_DROP_MEMBERSHIP:
11064 				mcast_opt = B_FALSE;
11065 				/* FALLTHRU */
11066 			case MCAST_LEAVE_GROUP:
11067 				fmode = MODE_IS_INCLUDE;
11068 				optfn = ip_opt_delete_group;
11069 				break;
11070 			}
11071 
11072 			if (mcast_opt) {
11073 				greqp = (struct group_req *)i1;
11074 				sin = (struct sockaddr_in *)&greqp->gr_group;
11075 				if (sin->sin_family != AF_INET) {
11076 					*outlenp = 0;
11077 					return (ENOPROTOOPT);
11078 				}
11079 				group = (ipaddr_t)sin->sin_addr.s_addr;
11080 				ifaddr = INADDR_ANY;
11081 				ifindexp = &greqp->gr_interface;
11082 			} else {
11083 				mreqp = (struct ip_mreq *)i1;
11084 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11085 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11086 				ifindexp = NULL;
11087 			}
11088 
11089 			/*
11090 			 * In the multirouting case, we need to replicate
11091 			 * the request on all interfaces that will take part
11092 			 * in replication.  We do so because multirouting is
11093 			 * reflective, thus we will probably receive multi-
11094 			 * casts on those interfaces.
11095 			 * The ip_multirt_apply_membership() succeeds if the
11096 			 * operation succeeds on at least one interface.
11097 			 */
11098 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11099 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11100 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11101 			if (ire != NULL) {
11102 				if (ire->ire_flags & RTF_MULTIRT) {
11103 					error = ip_multirt_apply_membership(
11104 					    optfn, ire, connp, checkonly, group,
11105 					    fmode, INADDR_ANY, first_mp);
11106 					done = B_TRUE;
11107 				}
11108 				ire_refrele(ire);
11109 			}
11110 			if (!done) {
11111 				error = optfn(connp, checkonly, group, ifaddr,
11112 				    ifindexp, fmode, INADDR_ANY, first_mp);
11113 			}
11114 			if (error) {
11115 				/*
11116 				 * EINPROGRESS is a soft error, needs retry
11117 				 * so don't make *outlenp zero.
11118 				 */
11119 				if (error != EINPROGRESS)
11120 					*outlenp = 0;
11121 				return (error);
11122 			}
11123 			/* OK return - copy input buffer into output buffer */
11124 			if (invalp != outvalp) {
11125 				/* don't trust bcopy for identical src/dst */
11126 				bcopy(invalp, outvalp, inlen);
11127 			}
11128 			*outlenp = inlen;
11129 			return (0);
11130 		}
11131 		case IP_BLOCK_SOURCE:
11132 		case IP_UNBLOCK_SOURCE:
11133 		case IP_ADD_SOURCE_MEMBERSHIP:
11134 		case IP_DROP_SOURCE_MEMBERSHIP:
11135 		case MCAST_BLOCK_SOURCE:
11136 		case MCAST_UNBLOCK_SOURCE:
11137 		case MCAST_JOIN_SOURCE_GROUP:
11138 		case MCAST_LEAVE_SOURCE_GROUP: {
11139 			struct ip_mreq_source *imreqp;
11140 			struct group_source_req *gsreqp;
11141 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11142 			uint32_t ifindex = 0;
11143 			mcast_record_t fmode;
11144 			struct sockaddr_in *sin;
11145 			ire_t *ire;
11146 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11147 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11148 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11149 
11150 			switch (name) {
11151 			case IP_BLOCK_SOURCE:
11152 				mcast_opt = B_FALSE;
11153 				/* FALLTHRU */
11154 			case MCAST_BLOCK_SOURCE:
11155 				fmode = MODE_IS_EXCLUDE;
11156 				optfn = ip_opt_add_group;
11157 				break;
11158 
11159 			case IP_UNBLOCK_SOURCE:
11160 				mcast_opt = B_FALSE;
11161 				/* FALLTHRU */
11162 			case MCAST_UNBLOCK_SOURCE:
11163 				fmode = MODE_IS_EXCLUDE;
11164 				optfn = ip_opt_delete_group;
11165 				break;
11166 
11167 			case IP_ADD_SOURCE_MEMBERSHIP:
11168 				mcast_opt = B_FALSE;
11169 				/* FALLTHRU */
11170 			case MCAST_JOIN_SOURCE_GROUP:
11171 				fmode = MODE_IS_INCLUDE;
11172 				optfn = ip_opt_add_group;
11173 				break;
11174 
11175 			case IP_DROP_SOURCE_MEMBERSHIP:
11176 				mcast_opt = B_FALSE;
11177 				/* FALLTHRU */
11178 			case MCAST_LEAVE_SOURCE_GROUP:
11179 				fmode = MODE_IS_INCLUDE;
11180 				optfn = ip_opt_delete_group;
11181 				break;
11182 			}
11183 
11184 			if (mcast_opt) {
11185 				gsreqp = (struct group_source_req *)i1;
11186 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11187 					*outlenp = 0;
11188 					return (ENOPROTOOPT);
11189 				}
11190 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11191 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11192 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11193 				src = (ipaddr_t)sin->sin_addr.s_addr;
11194 				ifindex = gsreqp->gsr_interface;
11195 			} else {
11196 				imreqp = (struct ip_mreq_source *)i1;
11197 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11198 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11199 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11200 			}
11201 
11202 			/*
11203 			 * In the multirouting case, we need to replicate
11204 			 * the request as noted in the mcast cases above.
11205 			 */
11206 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11207 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11208 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11209 			if (ire != NULL) {
11210 				if (ire->ire_flags & RTF_MULTIRT) {
11211 					error = ip_multirt_apply_membership(
11212 					    optfn, ire, connp, checkonly, grp,
11213 					    fmode, src, first_mp);
11214 					done = B_TRUE;
11215 				}
11216 				ire_refrele(ire);
11217 			}
11218 			if (!done) {
11219 				error = optfn(connp, checkonly, grp, ifaddr,
11220 				    &ifindex, fmode, src, first_mp);
11221 			}
11222 			if (error != 0) {
11223 				/*
11224 				 * EINPROGRESS is a soft error, needs retry
11225 				 * so don't make *outlenp zero.
11226 				 */
11227 				if (error != EINPROGRESS)
11228 					*outlenp = 0;
11229 				return (error);
11230 			}
11231 			/* OK return - copy input buffer into output buffer */
11232 			if (invalp != outvalp) {
11233 				bcopy(invalp, outvalp, inlen);
11234 			}
11235 			*outlenp = inlen;
11236 			return (0);
11237 		}
11238 		case IP_SEC_OPT:
11239 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11240 			if (error != 0) {
11241 				*outlenp = 0;
11242 				return (error);
11243 			}
11244 			break;
11245 		case IP_HDRINCL:
11246 		case IP_OPTIONS:
11247 		case T_IP_OPTIONS:
11248 		case IP_TOS:
11249 		case T_IP_TOS:
11250 		case IP_TTL:
11251 		case IP_RECVDSTADDR:
11252 		case IP_RECVOPTS:
11253 			/* OK return - copy input buffer into output buffer */
11254 			if (invalp != outvalp) {
11255 				/* don't trust bcopy for identical src/dst */
11256 				bcopy(invalp, outvalp, inlen);
11257 			}
11258 			*outlenp = inlen;
11259 			return (0);
11260 		case IP_RECVIF:
11261 			/* Retrieve the inbound interface index */
11262 			if (!checkonly) {
11263 				mutex_enter(&connp->conn_lock);
11264 				connp->conn_recvif = *i1 ? 1 : 0;
11265 				mutex_exit(&connp->conn_lock);
11266 			}
11267 			break;	/* goto sizeof (int) option return */
11268 		case IP_RECVPKTINFO:
11269 			if (!checkonly) {
11270 				mutex_enter(&connp->conn_lock);
11271 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11272 				mutex_exit(&connp->conn_lock);
11273 			}
11274 			break;	/* goto sizeof (int) option return */
11275 		case IP_RECVSLLA:
11276 			/* Retrieve the source link layer address */
11277 			if (!checkonly) {
11278 				mutex_enter(&connp->conn_lock);
11279 				connp->conn_recvslla = *i1 ? 1 : 0;
11280 				mutex_exit(&connp->conn_lock);
11281 			}
11282 			break;	/* goto sizeof (int) option return */
11283 		case MRT_INIT:
11284 		case MRT_DONE:
11285 		case MRT_ADD_VIF:
11286 		case MRT_DEL_VIF:
11287 		case MRT_ADD_MFC:
11288 		case MRT_DEL_MFC:
11289 		case MRT_ASSERT:
11290 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11291 				*outlenp = 0;
11292 				return (error);
11293 			}
11294 			error = ip_mrouter_set((int)name, q, checkonly,
11295 			    (uchar_t *)invalp, inlen, first_mp);
11296 			if (error) {
11297 				*outlenp = 0;
11298 				return (error);
11299 			}
11300 			/* OK return - copy input buffer into output buffer */
11301 			if (invalp != outvalp) {
11302 				/* don't trust bcopy for identical src/dst */
11303 				bcopy(invalp, outvalp, inlen);
11304 			}
11305 			*outlenp = inlen;
11306 			return (0);
11307 		case IP_BOUND_IF:
11308 		case IP_XMIT_IF:
11309 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11310 			    level, name, first_mp);
11311 			if (error != 0)
11312 				return (error);
11313 			break; 		/* goto sizeof (int) option return */
11314 
11315 		case IP_UNSPEC_SRC:
11316 			/* Allow sending with a zero source address */
11317 			if (!checkonly) {
11318 				mutex_enter(&connp->conn_lock);
11319 				connp->conn_unspec_src = *i1 ? 1 : 0;
11320 				mutex_exit(&connp->conn_lock);
11321 			}
11322 			break;	/* goto sizeof (int) option return */
11323 		default:
11324 			/*
11325 			 * "soft" error (negative)
11326 			 * option not handled at this level
11327 			 * Note: Do not modify *outlenp
11328 			 */
11329 			return (-EINVAL);
11330 		}
11331 		break;
11332 	case IPPROTO_IPV6:
11333 		switch (name) {
11334 		case IPV6_BOUND_IF:
11335 		case IPV6_BOUND_PIF:
11336 		case IPV6_DONTFAILOVER_IF:
11337 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11338 			    level, name, first_mp);
11339 			if (error != 0)
11340 				return (error);
11341 			break; 		/* goto sizeof (int) option return */
11342 
11343 		case IPV6_MULTICAST_IF:
11344 			/*
11345 			 * The only possible errors are EINPROGRESS and
11346 			 * EINVAL. EINPROGRESS will be restarted and is not
11347 			 * a hard error. We call this option on both V4 and V6
11348 			 * If both return EINVAL, then this call returns
11349 			 * EINVAL. If at least one of them succeeds we
11350 			 * return success.
11351 			 */
11352 			found = B_FALSE;
11353 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11354 			    level, name, first_mp);
11355 			if (error == EINPROGRESS)
11356 				return (error);
11357 			if (error == 0)
11358 				found = B_TRUE;
11359 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11360 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11361 			if (error == 0)
11362 				found = B_TRUE;
11363 			if (!found)
11364 				return (error);
11365 			break; 		/* goto sizeof (int) option return */
11366 
11367 		case IPV6_MULTICAST_HOPS:
11368 			/* Recorded in transport above IP */
11369 			break;	/* goto sizeof (int) option return */
11370 		case IPV6_MULTICAST_LOOP:
11371 			if (!checkonly) {
11372 				mutex_enter(&connp->conn_lock);
11373 				connp->conn_multicast_loop = *i1;
11374 				mutex_exit(&connp->conn_lock);
11375 			}
11376 			break;	/* goto sizeof (int) option return */
11377 		case IPV6_JOIN_GROUP:
11378 		case MCAST_JOIN_GROUP:
11379 		case IPV6_LEAVE_GROUP:
11380 		case MCAST_LEAVE_GROUP: {
11381 			struct ipv6_mreq *ip_mreqp;
11382 			struct group_req *greqp;
11383 			ire_t *ire;
11384 			boolean_t done = B_FALSE;
11385 			in6_addr_t groupv6;
11386 			uint32_t ifindex;
11387 			boolean_t mcast_opt = B_TRUE;
11388 			mcast_record_t fmode;
11389 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11390 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11391 
11392 			switch (name) {
11393 			case IPV6_JOIN_GROUP:
11394 				mcast_opt = B_FALSE;
11395 				/* FALLTHRU */
11396 			case MCAST_JOIN_GROUP:
11397 				fmode = MODE_IS_EXCLUDE;
11398 				optfn = ip_opt_add_group_v6;
11399 				break;
11400 
11401 			case IPV6_LEAVE_GROUP:
11402 				mcast_opt = B_FALSE;
11403 				/* FALLTHRU */
11404 			case MCAST_LEAVE_GROUP:
11405 				fmode = MODE_IS_INCLUDE;
11406 				optfn = ip_opt_delete_group_v6;
11407 				break;
11408 			}
11409 
11410 			if (mcast_opt) {
11411 				struct sockaddr_in *sin;
11412 				struct sockaddr_in6 *sin6;
11413 				greqp = (struct group_req *)i1;
11414 				if (greqp->gr_group.ss_family == AF_INET) {
11415 					sin = (struct sockaddr_in *)
11416 					    &(greqp->gr_group);
11417 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11418 					    &groupv6);
11419 				} else {
11420 					sin6 = (struct sockaddr_in6 *)
11421 					    &(greqp->gr_group);
11422 					groupv6 = sin6->sin6_addr;
11423 				}
11424 				ifindex = greqp->gr_interface;
11425 			} else {
11426 				ip_mreqp = (struct ipv6_mreq *)i1;
11427 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11428 				ifindex = ip_mreqp->ipv6mr_interface;
11429 			}
11430 			/*
11431 			 * In the multirouting case, we need to replicate
11432 			 * the request on all interfaces that will take part
11433 			 * in replication.  We do so because multirouting is
11434 			 * reflective, thus we will probably receive multi-
11435 			 * casts on those interfaces.
11436 			 * The ip_multirt_apply_membership_v6() succeeds if
11437 			 * the operation succeeds on at least one interface.
11438 			 */
11439 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11440 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11441 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11442 			if (ire != NULL) {
11443 				if (ire->ire_flags & RTF_MULTIRT) {
11444 					error = ip_multirt_apply_membership_v6(
11445 					    optfn, ire, connp, checkonly,
11446 					    &groupv6, fmode, &ipv6_all_zeros,
11447 					    first_mp);
11448 					done = B_TRUE;
11449 				}
11450 				ire_refrele(ire);
11451 			}
11452 			if (!done) {
11453 				error = optfn(connp, checkonly, &groupv6,
11454 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11455 			}
11456 			if (error) {
11457 				/*
11458 				 * EINPROGRESS is a soft error, needs retry
11459 				 * so don't make *outlenp zero.
11460 				 */
11461 				if (error != EINPROGRESS)
11462 					*outlenp = 0;
11463 				return (error);
11464 			}
11465 			/* OK return - copy input buffer into output buffer */
11466 			if (invalp != outvalp) {
11467 				/* don't trust bcopy for identical src/dst */
11468 				bcopy(invalp, outvalp, inlen);
11469 			}
11470 			*outlenp = inlen;
11471 			return (0);
11472 		}
11473 		case MCAST_BLOCK_SOURCE:
11474 		case MCAST_UNBLOCK_SOURCE:
11475 		case MCAST_JOIN_SOURCE_GROUP:
11476 		case MCAST_LEAVE_SOURCE_GROUP: {
11477 			struct group_source_req *gsreqp;
11478 			in6_addr_t v6grp, v6src;
11479 			uint32_t ifindex;
11480 			mcast_record_t fmode;
11481 			ire_t *ire;
11482 			boolean_t done = B_FALSE;
11483 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11484 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11485 
11486 			switch (name) {
11487 			case MCAST_BLOCK_SOURCE:
11488 				fmode = MODE_IS_EXCLUDE;
11489 				optfn = ip_opt_add_group_v6;
11490 				break;
11491 			case MCAST_UNBLOCK_SOURCE:
11492 				fmode = MODE_IS_EXCLUDE;
11493 				optfn = ip_opt_delete_group_v6;
11494 				break;
11495 			case MCAST_JOIN_SOURCE_GROUP:
11496 				fmode = MODE_IS_INCLUDE;
11497 				optfn = ip_opt_add_group_v6;
11498 				break;
11499 			case MCAST_LEAVE_SOURCE_GROUP:
11500 				fmode = MODE_IS_INCLUDE;
11501 				optfn = ip_opt_delete_group_v6;
11502 				break;
11503 			}
11504 
11505 			gsreqp = (struct group_source_req *)i1;
11506 			ifindex = gsreqp->gsr_interface;
11507 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11508 				struct sockaddr_in *s;
11509 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11510 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11511 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11512 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11513 			} else {
11514 				struct sockaddr_in6 *s6;
11515 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11516 				v6grp = s6->sin6_addr;
11517 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11518 				v6src = s6->sin6_addr;
11519 			}
11520 
11521 			/*
11522 			 * In the multirouting case, we need to replicate
11523 			 * the request as noted in the mcast cases above.
11524 			 */
11525 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11526 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11527 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11528 			if (ire != NULL) {
11529 				if (ire->ire_flags & RTF_MULTIRT) {
11530 					error = ip_multirt_apply_membership_v6(
11531 					    optfn, ire, connp, checkonly,
11532 					    &v6grp, fmode, &v6src, first_mp);
11533 					done = B_TRUE;
11534 				}
11535 				ire_refrele(ire);
11536 			}
11537 			if (!done) {
11538 				error = optfn(connp, checkonly, &v6grp,
11539 				    ifindex, fmode, &v6src, first_mp);
11540 			}
11541 			if (error != 0) {
11542 				/*
11543 				 * EINPROGRESS is a soft error, needs retry
11544 				 * so don't make *outlenp zero.
11545 				 */
11546 				if (error != EINPROGRESS)
11547 					*outlenp = 0;
11548 				return (error);
11549 			}
11550 			/* OK return - copy input buffer into output buffer */
11551 			if (invalp != outvalp) {
11552 				bcopy(invalp, outvalp, inlen);
11553 			}
11554 			*outlenp = inlen;
11555 			return (0);
11556 		}
11557 		case IPV6_UNICAST_HOPS:
11558 			/* Recorded in transport above IP */
11559 			break;	/* goto sizeof (int) option return */
11560 		case IPV6_UNSPEC_SRC:
11561 			/* Allow sending with a zero source address */
11562 			if (!checkonly) {
11563 				mutex_enter(&connp->conn_lock);
11564 				connp->conn_unspec_src = *i1 ? 1 : 0;
11565 				mutex_exit(&connp->conn_lock);
11566 			}
11567 			break;	/* goto sizeof (int) option return */
11568 		case IPV6_RECVPKTINFO:
11569 			if (!checkonly) {
11570 				mutex_enter(&connp->conn_lock);
11571 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11572 				mutex_exit(&connp->conn_lock);
11573 			}
11574 			break;	/* goto sizeof (int) option return */
11575 		case IPV6_RECVTCLASS:
11576 			if (!checkonly) {
11577 				if (*i1 < 0 || *i1 > 1) {
11578 					return (EINVAL);
11579 				}
11580 				mutex_enter(&connp->conn_lock);
11581 				connp->conn_ipv6_recvtclass = *i1;
11582 				mutex_exit(&connp->conn_lock);
11583 			}
11584 			break;
11585 		case IPV6_RECVPATHMTU:
11586 			if (!checkonly) {
11587 				if (*i1 < 0 || *i1 > 1) {
11588 					return (EINVAL);
11589 				}
11590 				mutex_enter(&connp->conn_lock);
11591 				connp->conn_ipv6_recvpathmtu = *i1;
11592 				mutex_exit(&connp->conn_lock);
11593 			}
11594 			break;
11595 		case IPV6_RECVHOPLIMIT:
11596 			if (!checkonly) {
11597 				mutex_enter(&connp->conn_lock);
11598 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11599 				mutex_exit(&connp->conn_lock);
11600 			}
11601 			break;	/* goto sizeof (int) option return */
11602 		case IPV6_RECVHOPOPTS:
11603 			if (!checkonly) {
11604 				mutex_enter(&connp->conn_lock);
11605 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11606 				mutex_exit(&connp->conn_lock);
11607 			}
11608 			break;	/* goto sizeof (int) option return */
11609 		case IPV6_RECVDSTOPTS:
11610 			if (!checkonly) {
11611 				mutex_enter(&connp->conn_lock);
11612 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11613 				mutex_exit(&connp->conn_lock);
11614 			}
11615 			break;	/* goto sizeof (int) option return */
11616 		case IPV6_RECVRTHDR:
11617 			if (!checkonly) {
11618 				mutex_enter(&connp->conn_lock);
11619 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11620 				mutex_exit(&connp->conn_lock);
11621 			}
11622 			break;	/* goto sizeof (int) option return */
11623 		case IPV6_RECVRTHDRDSTOPTS:
11624 			if (!checkonly) {
11625 				mutex_enter(&connp->conn_lock);
11626 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11627 				mutex_exit(&connp->conn_lock);
11628 			}
11629 			break;	/* goto sizeof (int) option return */
11630 		case IPV6_PKTINFO:
11631 			if (inlen == 0)
11632 				return (-EINVAL);	/* clearing option */
11633 			error = ip6_set_pktinfo(cr, connp,
11634 			    (struct in6_pktinfo *)invalp, first_mp);
11635 			if (error != 0)
11636 				*outlenp = 0;
11637 			else
11638 				*outlenp = inlen;
11639 			return (error);
11640 		case IPV6_NEXTHOP: {
11641 			struct sockaddr_in6 *sin6;
11642 
11643 			/* Verify that the nexthop is reachable */
11644 			if (inlen == 0)
11645 				return (-EINVAL);	/* clearing option */
11646 
11647 			sin6 = (struct sockaddr_in6 *)invalp;
11648 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11649 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11650 			    NULL, MATCH_IRE_DEFAULT, ipst);
11651 
11652 			if (ire == NULL) {
11653 				*outlenp = 0;
11654 				return (EHOSTUNREACH);
11655 			}
11656 			ire_refrele(ire);
11657 			return (-EINVAL);
11658 		}
11659 		case IPV6_SEC_OPT:
11660 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11661 			if (error != 0) {
11662 				*outlenp = 0;
11663 				return (error);
11664 			}
11665 			break;
11666 		case IPV6_SRC_PREFERENCES: {
11667 			/*
11668 			 * This is implemented strictly in the ip module
11669 			 * (here and in tcp_opt_*() to accomodate tcp
11670 			 * sockets).  Modules above ip pass this option
11671 			 * down here since ip is the only one that needs to
11672 			 * be aware of source address preferences.
11673 			 *
11674 			 * This socket option only affects connected
11675 			 * sockets that haven't already bound to a specific
11676 			 * IPv6 address.  In other words, sockets that
11677 			 * don't call bind() with an address other than the
11678 			 * unspecified address and that call connect().
11679 			 * ip_bind_connected_v6() passes these preferences
11680 			 * to the ipif_select_source_v6() function.
11681 			 */
11682 			if (inlen != sizeof (uint32_t))
11683 				return (EINVAL);
11684 			error = ip6_set_src_preferences(connp,
11685 			    *(uint32_t *)invalp);
11686 			if (error != 0) {
11687 				*outlenp = 0;
11688 				return (error);
11689 			} else {
11690 				*outlenp = sizeof (uint32_t);
11691 			}
11692 			break;
11693 		}
11694 		case IPV6_V6ONLY:
11695 			if (*i1 < 0 || *i1 > 1) {
11696 				return (EINVAL);
11697 			}
11698 			mutex_enter(&connp->conn_lock);
11699 			connp->conn_ipv6_v6only = *i1;
11700 			mutex_exit(&connp->conn_lock);
11701 			break;
11702 		default:
11703 			return (-EINVAL);
11704 		}
11705 		break;
11706 	default:
11707 		/*
11708 		 * "soft" error (negative)
11709 		 * option not handled at this level
11710 		 * Note: Do not modify *outlenp
11711 		 */
11712 		return (-EINVAL);
11713 	}
11714 	/*
11715 	 * Common case of return from an option that is sizeof (int)
11716 	 */
11717 	*(int *)outvalp = *i1;
11718 	*outlenp = sizeof (int);
11719 	return (0);
11720 }
11721 
11722 /*
11723  * This routine gets default values of certain options whose default
11724  * values are maintained by protocol specific code
11725  */
11726 /* ARGSUSED */
11727 int
11728 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11729 {
11730 	int *i1 = (int *)ptr;
11731 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11732 
11733 	switch (level) {
11734 	case IPPROTO_IP:
11735 		switch (name) {
11736 		case IP_MULTICAST_TTL:
11737 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11738 			return (sizeof (uchar_t));
11739 		case IP_MULTICAST_LOOP:
11740 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11741 			return (sizeof (uchar_t));
11742 		default:
11743 			return (-1);
11744 		}
11745 	case IPPROTO_IPV6:
11746 		switch (name) {
11747 		case IPV6_UNICAST_HOPS:
11748 			*i1 = ipst->ips_ipv6_def_hops;
11749 			return (sizeof (int));
11750 		case IPV6_MULTICAST_HOPS:
11751 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11752 			return (sizeof (int));
11753 		case IPV6_MULTICAST_LOOP:
11754 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11755 			return (sizeof (int));
11756 		case IPV6_V6ONLY:
11757 			*i1 = 1;
11758 			return (sizeof (int));
11759 		default:
11760 			return (-1);
11761 		}
11762 	default:
11763 		return (-1);
11764 	}
11765 	/* NOTREACHED */
11766 }
11767 
11768 /*
11769  * Given a destination address and a pointer to where to put the information
11770  * this routine fills in the mtuinfo.
11771  */
11772 int
11773 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11774     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11775 {
11776 	ire_t *ire;
11777 	ip_stack_t	*ipst = ns->netstack_ip;
11778 
11779 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11780 		return (-1);
11781 
11782 	bzero(mtuinfo, sizeof (*mtuinfo));
11783 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11784 	mtuinfo->ip6m_addr.sin6_port = port;
11785 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11786 
11787 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11788 	if (ire != NULL) {
11789 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11790 		ire_refrele(ire);
11791 	} else {
11792 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11793 	}
11794 	return (sizeof (struct ip6_mtuinfo));
11795 }
11796 
11797 /*
11798  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11799  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11800  * isn't.  This doesn't matter as the error checking is done properly for the
11801  * other MRT options coming in through ip_opt_set.
11802  */
11803 int
11804 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11805 {
11806 	conn_t		*connp = Q_TO_CONN(q);
11807 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11808 
11809 	switch (level) {
11810 	case IPPROTO_IP:
11811 		switch (name) {
11812 		case MRT_VERSION:
11813 		case MRT_ASSERT:
11814 			(void) ip_mrouter_get(name, q, ptr);
11815 			return (sizeof (int));
11816 		case IP_SEC_OPT:
11817 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11818 		case IP_NEXTHOP:
11819 			if (connp->conn_nexthop_set) {
11820 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11821 				return (sizeof (ipaddr_t));
11822 			} else
11823 				return (0);
11824 		case IP_RECVPKTINFO:
11825 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11826 			return (sizeof (int));
11827 		default:
11828 			break;
11829 		}
11830 		break;
11831 	case IPPROTO_IPV6:
11832 		switch (name) {
11833 		case IPV6_SEC_OPT:
11834 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11835 		case IPV6_SRC_PREFERENCES: {
11836 			return (ip6_get_src_preferences(connp,
11837 			    (uint32_t *)ptr));
11838 		}
11839 		case IPV6_V6ONLY:
11840 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11841 			return (sizeof (int));
11842 		case IPV6_PATHMTU:
11843 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11844 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11845 		default:
11846 			break;
11847 		}
11848 		break;
11849 	default:
11850 		break;
11851 	}
11852 	return (-1);
11853 }
11854 
11855 /* Named Dispatch routine to get a current value out of our parameter table. */
11856 /* ARGSUSED */
11857 static int
11858 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11859 {
11860 	ipparam_t *ippa = (ipparam_t *)cp;
11861 
11862 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11863 	return (0);
11864 }
11865 
11866 /* ARGSUSED */
11867 static int
11868 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11869 {
11870 
11871 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11872 	return (0);
11873 }
11874 
11875 /*
11876  * Set ip{,6}_forwarding values.  This means walking through all of the
11877  * ill's and toggling their forwarding values.
11878  */
11879 /* ARGSUSED */
11880 static int
11881 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11882 {
11883 	long new_value;
11884 	int *forwarding_value = (int *)cp;
11885 	ill_t *ill;
11886 	boolean_t isv6;
11887 	ill_walk_context_t ctx;
11888 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11889 
11890 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11891 
11892 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11893 	    new_value < 0 || new_value > 1) {
11894 		return (EINVAL);
11895 	}
11896 
11897 	*forwarding_value = new_value;
11898 
11899 	/*
11900 	 * Regardless of the current value of ip_forwarding, set all per-ill
11901 	 * values of ip_forwarding to the value being set.
11902 	 *
11903 	 * Bring all the ill's up to date with the new global value.
11904 	 */
11905 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11906 
11907 	if (isv6)
11908 		ill = ILL_START_WALK_V6(&ctx, ipst);
11909 	else
11910 		ill = ILL_START_WALK_V4(&ctx, ipst);
11911 
11912 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11913 		(void) ill_forward_set(ill, new_value != 0);
11914 
11915 	rw_exit(&ipst->ips_ill_g_lock);
11916 	return (0);
11917 }
11918 
11919 /*
11920  * Walk through the param array specified registering each element with the
11921  * Named Dispatch handler. This is called only during init. So it is ok
11922  * not to acquire any locks
11923  */
11924 static boolean_t
11925 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11926     ipndp_t *ipnd, size_t ipnd_cnt)
11927 {
11928 	for (; ippa_cnt-- > 0; ippa++) {
11929 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11930 			if (!nd_load(ndp, ippa->ip_param_name,
11931 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11932 				nd_free(ndp);
11933 				return (B_FALSE);
11934 			}
11935 		}
11936 	}
11937 
11938 	for (; ipnd_cnt-- > 0; ipnd++) {
11939 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11940 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11941 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11942 			    ipnd->ip_ndp_data)) {
11943 				nd_free(ndp);
11944 				return (B_FALSE);
11945 			}
11946 		}
11947 	}
11948 
11949 	return (B_TRUE);
11950 }
11951 
11952 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11953 /* ARGSUSED */
11954 static int
11955 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11956 {
11957 	long		new_value;
11958 	ipparam_t	*ippa = (ipparam_t *)cp;
11959 
11960 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11961 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11962 		return (EINVAL);
11963 	}
11964 	ippa->ip_param_value = new_value;
11965 	return (0);
11966 }
11967 
11968 /*
11969  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11970  * When an ipf is passed here for the first time, if
11971  * we already have in-order fragments on the queue, we convert from the fast-
11972  * path reassembly scheme to the hard-case scheme.  From then on, additional
11973  * fragments are reassembled here.  We keep track of the start and end offsets
11974  * of each piece, and the number of holes in the chain.  When the hole count
11975  * goes to zero, we are done!
11976  *
11977  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11978  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11979  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11980  * after the call to ip_reassemble().
11981  */
11982 int
11983 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11984     size_t msg_len)
11985 {
11986 	uint_t	end;
11987 	mblk_t	*next_mp;
11988 	mblk_t	*mp1;
11989 	uint_t	offset;
11990 	boolean_t incr_dups = B_TRUE;
11991 	boolean_t offset_zero_seen = B_FALSE;
11992 	boolean_t pkt_boundary_checked = B_FALSE;
11993 
11994 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11995 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11996 
11997 	/* Add in byte count */
11998 	ipf->ipf_count += msg_len;
11999 	if (ipf->ipf_end) {
12000 		/*
12001 		 * We were part way through in-order reassembly, but now there
12002 		 * is a hole.  We walk through messages already queued, and
12003 		 * mark them for hard case reassembly.  We know that up till
12004 		 * now they were in order starting from offset zero.
12005 		 */
12006 		offset = 0;
12007 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12008 			IP_REASS_SET_START(mp1, offset);
12009 			if (offset == 0) {
12010 				ASSERT(ipf->ipf_nf_hdr_len != 0);
12011 				offset = -ipf->ipf_nf_hdr_len;
12012 			}
12013 			offset += mp1->b_wptr - mp1->b_rptr;
12014 			IP_REASS_SET_END(mp1, offset);
12015 		}
12016 		/* One hole at the end. */
12017 		ipf->ipf_hole_cnt = 1;
12018 		/* Brand it as a hard case, forever. */
12019 		ipf->ipf_end = 0;
12020 	}
12021 	/* Walk through all the new pieces. */
12022 	do {
12023 		end = start + (mp->b_wptr - mp->b_rptr);
12024 		/*
12025 		 * If start is 0, decrease 'end' only for the first mblk of
12026 		 * the fragment. Otherwise 'end' can get wrong value in the
12027 		 * second pass of the loop if first mblk is exactly the
12028 		 * size of ipf_nf_hdr_len.
12029 		 */
12030 		if (start == 0 && !offset_zero_seen) {
12031 			/* First segment */
12032 			ASSERT(ipf->ipf_nf_hdr_len != 0);
12033 			end -= ipf->ipf_nf_hdr_len;
12034 			offset_zero_seen = B_TRUE;
12035 		}
12036 		next_mp = mp->b_cont;
12037 		/*
12038 		 * We are checking to see if there is any interesing data
12039 		 * to process.  If there isn't and the mblk isn't the
12040 		 * one which carries the unfragmentable header then we
12041 		 * drop it.  It's possible to have just the unfragmentable
12042 		 * header come through without any data.  That needs to be
12043 		 * saved.
12044 		 *
12045 		 * If the assert at the top of this function holds then the
12046 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12047 		 * is infrequently traveled enough that the test is left in
12048 		 * to protect against future code changes which break that
12049 		 * invariant.
12050 		 */
12051 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12052 			/* Empty.  Blast it. */
12053 			IP_REASS_SET_START(mp, 0);
12054 			IP_REASS_SET_END(mp, 0);
12055 			/*
12056 			 * If the ipf points to the mblk we are about to free,
12057 			 * update ipf to point to the next mblk (or NULL
12058 			 * if none).
12059 			 */
12060 			if (ipf->ipf_mp->b_cont == mp)
12061 				ipf->ipf_mp->b_cont = next_mp;
12062 			freeb(mp);
12063 			continue;
12064 		}
12065 		mp->b_cont = NULL;
12066 		IP_REASS_SET_START(mp, start);
12067 		IP_REASS_SET_END(mp, end);
12068 		if (!ipf->ipf_tail_mp) {
12069 			ipf->ipf_tail_mp = mp;
12070 			ipf->ipf_mp->b_cont = mp;
12071 			if (start == 0 || !more) {
12072 				ipf->ipf_hole_cnt = 1;
12073 				/*
12074 				 * if the first fragment comes in more than one
12075 				 * mblk, this loop will be executed for each
12076 				 * mblk. Need to adjust hole count so exiting
12077 				 * this routine will leave hole count at 1.
12078 				 */
12079 				if (next_mp)
12080 					ipf->ipf_hole_cnt++;
12081 			} else
12082 				ipf->ipf_hole_cnt = 2;
12083 			continue;
12084 		} else if (ipf->ipf_last_frag_seen && !more &&
12085 		    !pkt_boundary_checked) {
12086 			/*
12087 			 * We check datagram boundary only if this fragment
12088 			 * claims to be the last fragment and we have seen a
12089 			 * last fragment in the past too. We do this only
12090 			 * once for a given fragment.
12091 			 *
12092 			 * start cannot be 0 here as fragments with start=0
12093 			 * and MF=0 gets handled as a complete packet. These
12094 			 * fragments should not reach here.
12095 			 */
12096 
12097 			if (start + msgdsize(mp) !=
12098 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12099 				/*
12100 				 * We have two fragments both of which claim
12101 				 * to be the last fragment but gives conflicting
12102 				 * information about the whole datagram size.
12103 				 * Something fishy is going on. Drop the
12104 				 * fragment and free up the reassembly list.
12105 				 */
12106 				return (IP_REASS_FAILED);
12107 			}
12108 
12109 			/*
12110 			 * We shouldn't come to this code block again for this
12111 			 * particular fragment.
12112 			 */
12113 			pkt_boundary_checked = B_TRUE;
12114 		}
12115 
12116 		/* New stuff at or beyond tail? */
12117 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12118 		if (start >= offset) {
12119 			if (ipf->ipf_last_frag_seen) {
12120 				/* current fragment is beyond last fragment */
12121 				return (IP_REASS_FAILED);
12122 			}
12123 			/* Link it on end. */
12124 			ipf->ipf_tail_mp->b_cont = mp;
12125 			ipf->ipf_tail_mp = mp;
12126 			if (more) {
12127 				if (start != offset)
12128 					ipf->ipf_hole_cnt++;
12129 			} else if (start == offset && next_mp == NULL)
12130 					ipf->ipf_hole_cnt--;
12131 			continue;
12132 		}
12133 		mp1 = ipf->ipf_mp->b_cont;
12134 		offset = IP_REASS_START(mp1);
12135 		/* New stuff at the front? */
12136 		if (start < offset) {
12137 			if (start == 0) {
12138 				if (end >= offset) {
12139 					/* Nailed the hole at the begining. */
12140 					ipf->ipf_hole_cnt--;
12141 				}
12142 			} else if (end < offset) {
12143 				/*
12144 				 * A hole, stuff, and a hole where there used
12145 				 * to be just a hole.
12146 				 */
12147 				ipf->ipf_hole_cnt++;
12148 			}
12149 			mp->b_cont = mp1;
12150 			/* Check for overlap. */
12151 			while (end > offset) {
12152 				if (end < IP_REASS_END(mp1)) {
12153 					mp->b_wptr -= end - offset;
12154 					IP_REASS_SET_END(mp, offset);
12155 					BUMP_MIB(ill->ill_ip_mib,
12156 					    ipIfStatsReasmPartDups);
12157 					break;
12158 				}
12159 				/* Did we cover another hole? */
12160 				if ((mp1->b_cont &&
12161 				    IP_REASS_END(mp1) !=
12162 				    IP_REASS_START(mp1->b_cont) &&
12163 				    end >= IP_REASS_START(mp1->b_cont)) ||
12164 				    (!ipf->ipf_last_frag_seen && !more)) {
12165 					ipf->ipf_hole_cnt--;
12166 				}
12167 				/* Clip out mp1. */
12168 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12169 					/*
12170 					 * After clipping out mp1, this guy
12171 					 * is now hanging off the end.
12172 					 */
12173 					ipf->ipf_tail_mp = mp;
12174 				}
12175 				IP_REASS_SET_START(mp1, 0);
12176 				IP_REASS_SET_END(mp1, 0);
12177 				/* Subtract byte count */
12178 				ipf->ipf_count -= mp1->b_datap->db_lim -
12179 				    mp1->b_datap->db_base;
12180 				freeb(mp1);
12181 				BUMP_MIB(ill->ill_ip_mib,
12182 				    ipIfStatsReasmPartDups);
12183 				mp1 = mp->b_cont;
12184 				if (!mp1)
12185 					break;
12186 				offset = IP_REASS_START(mp1);
12187 			}
12188 			ipf->ipf_mp->b_cont = mp;
12189 			continue;
12190 		}
12191 		/*
12192 		 * The new piece starts somewhere between the start of the head
12193 		 * and before the end of the tail.
12194 		 */
12195 		for (; mp1; mp1 = mp1->b_cont) {
12196 			offset = IP_REASS_END(mp1);
12197 			if (start < offset) {
12198 				if (end <= offset) {
12199 					/* Nothing new. */
12200 					IP_REASS_SET_START(mp, 0);
12201 					IP_REASS_SET_END(mp, 0);
12202 					/* Subtract byte count */
12203 					ipf->ipf_count -= mp->b_datap->db_lim -
12204 					    mp->b_datap->db_base;
12205 					if (incr_dups) {
12206 						ipf->ipf_num_dups++;
12207 						incr_dups = B_FALSE;
12208 					}
12209 					freeb(mp);
12210 					BUMP_MIB(ill->ill_ip_mib,
12211 					    ipIfStatsReasmDuplicates);
12212 					break;
12213 				}
12214 				/*
12215 				 * Trim redundant stuff off beginning of new
12216 				 * piece.
12217 				 */
12218 				IP_REASS_SET_START(mp, offset);
12219 				mp->b_rptr += offset - start;
12220 				BUMP_MIB(ill->ill_ip_mib,
12221 				    ipIfStatsReasmPartDups);
12222 				start = offset;
12223 				if (!mp1->b_cont) {
12224 					/*
12225 					 * After trimming, this guy is now
12226 					 * hanging off the end.
12227 					 */
12228 					mp1->b_cont = mp;
12229 					ipf->ipf_tail_mp = mp;
12230 					if (!more) {
12231 						ipf->ipf_hole_cnt--;
12232 					}
12233 					break;
12234 				}
12235 			}
12236 			if (start >= IP_REASS_START(mp1->b_cont))
12237 				continue;
12238 			/* Fill a hole */
12239 			if (start > offset)
12240 				ipf->ipf_hole_cnt++;
12241 			mp->b_cont = mp1->b_cont;
12242 			mp1->b_cont = mp;
12243 			mp1 = mp->b_cont;
12244 			offset = IP_REASS_START(mp1);
12245 			if (end >= offset) {
12246 				ipf->ipf_hole_cnt--;
12247 				/* Check for overlap. */
12248 				while (end > offset) {
12249 					if (end < IP_REASS_END(mp1)) {
12250 						mp->b_wptr -= end - offset;
12251 						IP_REASS_SET_END(mp, offset);
12252 						/*
12253 						 * TODO we might bump
12254 						 * this up twice if there is
12255 						 * overlap at both ends.
12256 						 */
12257 						BUMP_MIB(ill->ill_ip_mib,
12258 						    ipIfStatsReasmPartDups);
12259 						break;
12260 					}
12261 					/* Did we cover another hole? */
12262 					if ((mp1->b_cont &&
12263 					    IP_REASS_END(mp1)
12264 					    != IP_REASS_START(mp1->b_cont) &&
12265 					    end >=
12266 					    IP_REASS_START(mp1->b_cont)) ||
12267 					    (!ipf->ipf_last_frag_seen &&
12268 					    !more)) {
12269 						ipf->ipf_hole_cnt--;
12270 					}
12271 					/* Clip out mp1. */
12272 					if ((mp->b_cont = mp1->b_cont) ==
12273 					    NULL) {
12274 						/*
12275 						 * After clipping out mp1,
12276 						 * this guy is now hanging
12277 						 * off the end.
12278 						 */
12279 						ipf->ipf_tail_mp = mp;
12280 					}
12281 					IP_REASS_SET_START(mp1, 0);
12282 					IP_REASS_SET_END(mp1, 0);
12283 					/* Subtract byte count */
12284 					ipf->ipf_count -=
12285 					    mp1->b_datap->db_lim -
12286 					    mp1->b_datap->db_base;
12287 					freeb(mp1);
12288 					BUMP_MIB(ill->ill_ip_mib,
12289 					    ipIfStatsReasmPartDups);
12290 					mp1 = mp->b_cont;
12291 					if (!mp1)
12292 						break;
12293 					offset = IP_REASS_START(mp1);
12294 				}
12295 			}
12296 			break;
12297 		}
12298 	} while (start = end, mp = next_mp);
12299 
12300 	/* Fragment just processed could be the last one. Remember this fact */
12301 	if (!more)
12302 		ipf->ipf_last_frag_seen = B_TRUE;
12303 
12304 	/* Still got holes? */
12305 	if (ipf->ipf_hole_cnt)
12306 		return (IP_REASS_PARTIAL);
12307 	/* Clean up overloaded fields to avoid upstream disasters. */
12308 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12309 		IP_REASS_SET_START(mp1, 0);
12310 		IP_REASS_SET_END(mp1, 0);
12311 	}
12312 	return (IP_REASS_COMPLETE);
12313 }
12314 
12315 /*
12316  * ipsec processing for the fast path, used for input UDP Packets
12317  */
12318 static boolean_t
12319 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12320     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12321 {
12322 	uint32_t	ill_index;
12323 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12324 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12325 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12326 
12327 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12328 	/* The ill_index of the incoming ILL */
12329 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12330 
12331 	/* pass packet up to the transport */
12332 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12333 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12334 		    NULL, mctl_present);
12335 		if (*first_mpp == NULL) {
12336 			return (B_FALSE);
12337 		}
12338 	}
12339 
12340 	/* Initiate IPPF processing for fastpath UDP */
12341 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12342 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12343 		if (*mpp == NULL) {
12344 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12345 			    "deferred/dropped during IPPF processing\n"));
12346 			return (B_FALSE);
12347 		}
12348 	}
12349 	/*
12350 	 * We make the checks as below since we are in the fast path
12351 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12352 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12353 	 */
12354 	if (connp->conn_recvif || connp->conn_recvslla ||
12355 	    connp->conn_ip_recvpktinfo) {
12356 		if (connp->conn_recvif) {
12357 			in_flags = IPF_RECVIF;
12358 		}
12359 		/*
12360 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12361 		 * so the flag passed to ip_add_info is based on IP version
12362 		 * of connp.
12363 		 */
12364 		if (connp->conn_ip_recvpktinfo) {
12365 			if (connp->conn_af_isv6) {
12366 				/*
12367 				 * V6 only needs index
12368 				 */
12369 				in_flags |= IPF_RECVIF;
12370 			} else {
12371 				/*
12372 				 * V4 needs index + matching address.
12373 				 */
12374 				in_flags |= IPF_RECVADDR;
12375 			}
12376 		}
12377 		if (connp->conn_recvslla) {
12378 			in_flags |= IPF_RECVSLLA;
12379 		}
12380 		/*
12381 		 * since in_flags are being set ill will be
12382 		 * referenced in ip_add_info, so it better not
12383 		 * be NULL.
12384 		 */
12385 		/*
12386 		 * the actual data will be contained in b_cont
12387 		 * upon successful return of the following call.
12388 		 * If the call fails then the original mblk is
12389 		 * returned.
12390 		 */
12391 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12392 		    ipst);
12393 	}
12394 
12395 	return (B_TRUE);
12396 }
12397 
12398 /*
12399  * Fragmentation reassembly.  Each ILL has a hash table for
12400  * queuing packets undergoing reassembly for all IPIFs
12401  * associated with the ILL.  The hash is based on the packet
12402  * IP ident field.  The ILL frag hash table was allocated
12403  * as a timer block at the time the ILL was created.  Whenever
12404  * there is anything on the reassembly queue, the timer will
12405  * be running.  Returns B_TRUE if successful else B_FALSE;
12406  * frees mp on failure.
12407  */
12408 static boolean_t
12409 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12410     uint32_t *cksum_val, uint16_t *cksum_flags)
12411 {
12412 	uint32_t	frag_offset_flags;
12413 	ill_t		*ill = (ill_t *)q->q_ptr;
12414 	mblk_t		*mp = *mpp;
12415 	mblk_t		*t_mp;
12416 	ipaddr_t	dst;
12417 	uint8_t		proto = ipha->ipha_protocol;
12418 	uint32_t	sum_val;
12419 	uint16_t	sum_flags;
12420 	ipf_t		*ipf;
12421 	ipf_t		**ipfp;
12422 	ipfb_t		*ipfb;
12423 	uint16_t	ident;
12424 	uint32_t	offset;
12425 	ipaddr_t	src;
12426 	uint_t		hdr_length;
12427 	uint32_t	end;
12428 	mblk_t		*mp1;
12429 	mblk_t		*tail_mp;
12430 	size_t		count;
12431 	size_t		msg_len;
12432 	uint8_t		ecn_info = 0;
12433 	uint32_t	packet_size;
12434 	boolean_t	pruned = B_FALSE;
12435 	ip_stack_t *ipst = ill->ill_ipst;
12436 
12437 	if (cksum_val != NULL)
12438 		*cksum_val = 0;
12439 	if (cksum_flags != NULL)
12440 		*cksum_flags = 0;
12441 
12442 	/*
12443 	 * Drop the fragmented as early as possible, if
12444 	 * we don't have resource(s) to re-assemble.
12445 	 */
12446 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12447 		freemsg(mp);
12448 		return (B_FALSE);
12449 	}
12450 
12451 	/* Check for fragmentation offset; return if there's none */
12452 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12453 	    (IPH_MF | IPH_OFFSET)) == 0)
12454 		return (B_TRUE);
12455 
12456 	/*
12457 	 * We utilize hardware computed checksum info only for UDP since
12458 	 * IP fragmentation is a normal occurence for the protocol.  In
12459 	 * addition, checksum offload support for IP fragments carrying
12460 	 * UDP payload is commonly implemented across network adapters.
12461 	 */
12462 	ASSERT(ill != NULL);
12463 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12464 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12465 		mblk_t *mp1 = mp->b_cont;
12466 		int32_t len;
12467 
12468 		/* Record checksum information from the packet */
12469 		sum_val = (uint32_t)DB_CKSUM16(mp);
12470 		sum_flags = DB_CKSUMFLAGS(mp);
12471 
12472 		/* IP payload offset from beginning of mblk */
12473 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12474 
12475 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12476 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12477 		    offset >= DB_CKSUMSTART(mp) &&
12478 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12479 			uint32_t adj;
12480 			/*
12481 			 * Partial checksum has been calculated by hardware
12482 			 * and attached to the packet; in addition, any
12483 			 * prepended extraneous data is even byte aligned.
12484 			 * If any such data exists, we adjust the checksum;
12485 			 * this would also handle any postpended data.
12486 			 */
12487 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12488 			    mp, mp1, len, adj);
12489 
12490 			/* One's complement subtract extraneous checksum */
12491 			if (adj >= sum_val)
12492 				sum_val = ~(adj - sum_val) & 0xFFFF;
12493 			else
12494 				sum_val -= adj;
12495 		}
12496 	} else {
12497 		sum_val = 0;
12498 		sum_flags = 0;
12499 	}
12500 
12501 	/* Clear hardware checksumming flag */
12502 	DB_CKSUMFLAGS(mp) = 0;
12503 
12504 	ident = ipha->ipha_ident;
12505 	offset = (frag_offset_flags << 3) & 0xFFFF;
12506 	src = ipha->ipha_src;
12507 	dst = ipha->ipha_dst;
12508 	hdr_length = IPH_HDR_LENGTH(ipha);
12509 	end = ntohs(ipha->ipha_length) - hdr_length;
12510 
12511 	/* If end == 0 then we have a packet with no data, so just free it */
12512 	if (end == 0) {
12513 		freemsg(mp);
12514 		return (B_FALSE);
12515 	}
12516 
12517 	/* Record the ECN field info. */
12518 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12519 	if (offset != 0) {
12520 		/*
12521 		 * If this isn't the first piece, strip the header, and
12522 		 * add the offset to the end value.
12523 		 */
12524 		mp->b_rptr += hdr_length;
12525 		end += offset;
12526 	}
12527 
12528 	msg_len = MBLKSIZE(mp);
12529 	tail_mp = mp;
12530 	while (tail_mp->b_cont != NULL) {
12531 		tail_mp = tail_mp->b_cont;
12532 		msg_len += MBLKSIZE(tail_mp);
12533 	}
12534 
12535 	/* If the reassembly list for this ILL will get too big, prune it */
12536 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12537 	    ipst->ips_ip_reass_queue_bytes) {
12538 		ill_frag_prune(ill,
12539 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12540 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12541 		pruned = B_TRUE;
12542 	}
12543 
12544 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12545 	mutex_enter(&ipfb->ipfb_lock);
12546 
12547 	ipfp = &ipfb->ipfb_ipf;
12548 	/* Try to find an existing fragment queue for this packet. */
12549 	for (;;) {
12550 		ipf = ipfp[0];
12551 		if (ipf != NULL) {
12552 			/*
12553 			 * It has to match on ident and src/dst address.
12554 			 */
12555 			if (ipf->ipf_ident == ident &&
12556 			    ipf->ipf_src == src &&
12557 			    ipf->ipf_dst == dst &&
12558 			    ipf->ipf_protocol == proto) {
12559 				/*
12560 				 * If we have received too many
12561 				 * duplicate fragments for this packet
12562 				 * free it.
12563 				 */
12564 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12565 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12566 					freemsg(mp);
12567 					mutex_exit(&ipfb->ipfb_lock);
12568 					return (B_FALSE);
12569 				}
12570 				/* Found it. */
12571 				break;
12572 			}
12573 			ipfp = &ipf->ipf_hash_next;
12574 			continue;
12575 		}
12576 
12577 		/*
12578 		 * If we pruned the list, do we want to store this new
12579 		 * fragment?. We apply an optimization here based on the
12580 		 * fact that most fragments will be received in order.
12581 		 * So if the offset of this incoming fragment is zero,
12582 		 * it is the first fragment of a new packet. We will
12583 		 * keep it.  Otherwise drop the fragment, as we have
12584 		 * probably pruned the packet already (since the
12585 		 * packet cannot be found).
12586 		 */
12587 		if (pruned && offset != 0) {
12588 			mutex_exit(&ipfb->ipfb_lock);
12589 			freemsg(mp);
12590 			return (B_FALSE);
12591 		}
12592 
12593 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12594 			/*
12595 			 * Too many fragmented packets in this hash
12596 			 * bucket. Free the oldest.
12597 			 */
12598 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12599 		}
12600 
12601 		/* New guy.  Allocate a frag message. */
12602 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12603 		if (mp1 == NULL) {
12604 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12605 			freemsg(mp);
12606 reass_done:
12607 			mutex_exit(&ipfb->ipfb_lock);
12608 			return (B_FALSE);
12609 		}
12610 
12611 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12612 		mp1->b_cont = mp;
12613 
12614 		/* Initialize the fragment header. */
12615 		ipf = (ipf_t *)mp1->b_rptr;
12616 		ipf->ipf_mp = mp1;
12617 		ipf->ipf_ptphn = ipfp;
12618 		ipfp[0] = ipf;
12619 		ipf->ipf_hash_next = NULL;
12620 		ipf->ipf_ident = ident;
12621 		ipf->ipf_protocol = proto;
12622 		ipf->ipf_src = src;
12623 		ipf->ipf_dst = dst;
12624 		ipf->ipf_nf_hdr_len = 0;
12625 		/* Record reassembly start time. */
12626 		ipf->ipf_timestamp = gethrestime_sec();
12627 		/* Record ipf generation and account for frag header */
12628 		ipf->ipf_gen = ill->ill_ipf_gen++;
12629 		ipf->ipf_count = MBLKSIZE(mp1);
12630 		ipf->ipf_last_frag_seen = B_FALSE;
12631 		ipf->ipf_ecn = ecn_info;
12632 		ipf->ipf_num_dups = 0;
12633 		ipfb->ipfb_frag_pkts++;
12634 		ipf->ipf_checksum = 0;
12635 		ipf->ipf_checksum_flags = 0;
12636 
12637 		/* Store checksum value in fragment header */
12638 		if (sum_flags != 0) {
12639 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12640 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12641 			ipf->ipf_checksum = sum_val;
12642 			ipf->ipf_checksum_flags = sum_flags;
12643 		}
12644 
12645 		/*
12646 		 * We handle reassembly two ways.  In the easy case,
12647 		 * where all the fragments show up in order, we do
12648 		 * minimal bookkeeping, and just clip new pieces on
12649 		 * the end.  If we ever see a hole, then we go off
12650 		 * to ip_reassemble which has to mark the pieces and
12651 		 * keep track of the number of holes, etc.  Obviously,
12652 		 * the point of having both mechanisms is so we can
12653 		 * handle the easy case as efficiently as possible.
12654 		 */
12655 		if (offset == 0) {
12656 			/* Easy case, in-order reassembly so far. */
12657 			ipf->ipf_count += msg_len;
12658 			ipf->ipf_tail_mp = tail_mp;
12659 			/*
12660 			 * Keep track of next expected offset in
12661 			 * ipf_end.
12662 			 */
12663 			ipf->ipf_end = end;
12664 			ipf->ipf_nf_hdr_len = hdr_length;
12665 		} else {
12666 			/* Hard case, hole at the beginning. */
12667 			ipf->ipf_tail_mp = NULL;
12668 			/*
12669 			 * ipf_end == 0 means that we have given up
12670 			 * on easy reassembly.
12671 			 */
12672 			ipf->ipf_end = 0;
12673 
12674 			/* Forget checksum offload from now on */
12675 			ipf->ipf_checksum_flags = 0;
12676 
12677 			/*
12678 			 * ipf_hole_cnt is set by ip_reassemble.
12679 			 * ipf_count is updated by ip_reassemble.
12680 			 * No need to check for return value here
12681 			 * as we don't expect reassembly to complete
12682 			 * or fail for the first fragment itself.
12683 			 */
12684 			(void) ip_reassemble(mp, ipf,
12685 			    (frag_offset_flags & IPH_OFFSET) << 3,
12686 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12687 		}
12688 		/* Update per ipfb and ill byte counts */
12689 		ipfb->ipfb_count += ipf->ipf_count;
12690 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12691 		ill->ill_frag_count += ipf->ipf_count;
12692 		/* If the frag timer wasn't already going, start it. */
12693 		mutex_enter(&ill->ill_lock);
12694 		ill_frag_timer_start(ill);
12695 		mutex_exit(&ill->ill_lock);
12696 		goto reass_done;
12697 	}
12698 
12699 	/*
12700 	 * If the packet's flag has changed (it could be coming up
12701 	 * from an interface different than the previous, therefore
12702 	 * possibly different checksum capability), then forget about
12703 	 * any stored checksum states.  Otherwise add the value to
12704 	 * the existing one stored in the fragment header.
12705 	 */
12706 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12707 		sum_val += ipf->ipf_checksum;
12708 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12709 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12710 		ipf->ipf_checksum = sum_val;
12711 	} else if (ipf->ipf_checksum_flags != 0) {
12712 		/* Forget checksum offload from now on */
12713 		ipf->ipf_checksum_flags = 0;
12714 	}
12715 
12716 	/*
12717 	 * We have a new piece of a datagram which is already being
12718 	 * reassembled.  Update the ECN info if all IP fragments
12719 	 * are ECN capable.  If there is one which is not, clear
12720 	 * all the info.  If there is at least one which has CE
12721 	 * code point, IP needs to report that up to transport.
12722 	 */
12723 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12724 		if (ecn_info == IPH_ECN_CE)
12725 			ipf->ipf_ecn = IPH_ECN_CE;
12726 	} else {
12727 		ipf->ipf_ecn = IPH_ECN_NECT;
12728 	}
12729 	if (offset && ipf->ipf_end == offset) {
12730 		/* The new fragment fits at the end */
12731 		ipf->ipf_tail_mp->b_cont = mp;
12732 		/* Update the byte count */
12733 		ipf->ipf_count += msg_len;
12734 		/* Update per ipfb and ill byte counts */
12735 		ipfb->ipfb_count += msg_len;
12736 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12737 		ill->ill_frag_count += msg_len;
12738 		if (frag_offset_flags & IPH_MF) {
12739 			/* More to come. */
12740 			ipf->ipf_end = end;
12741 			ipf->ipf_tail_mp = tail_mp;
12742 			goto reass_done;
12743 		}
12744 	} else {
12745 		/* Go do the hard cases. */
12746 		int ret;
12747 
12748 		if (offset == 0)
12749 			ipf->ipf_nf_hdr_len = hdr_length;
12750 
12751 		/* Save current byte count */
12752 		count = ipf->ipf_count;
12753 		ret = ip_reassemble(mp, ipf,
12754 		    (frag_offset_flags & IPH_OFFSET) << 3,
12755 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12756 		/* Count of bytes added and subtracted (freeb()ed) */
12757 		count = ipf->ipf_count - count;
12758 		if (count) {
12759 			/* Update per ipfb and ill byte counts */
12760 			ipfb->ipfb_count += count;
12761 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12762 			ill->ill_frag_count += count;
12763 		}
12764 		if (ret == IP_REASS_PARTIAL) {
12765 			goto reass_done;
12766 		} else if (ret == IP_REASS_FAILED) {
12767 			/* Reassembly failed. Free up all resources */
12768 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12769 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12770 				IP_REASS_SET_START(t_mp, 0);
12771 				IP_REASS_SET_END(t_mp, 0);
12772 			}
12773 			freemsg(mp);
12774 			goto reass_done;
12775 		}
12776 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12777 	}
12778 	/*
12779 	 * We have completed reassembly.  Unhook the frag header from
12780 	 * the reassembly list.
12781 	 *
12782 	 * Before we free the frag header, record the ECN info
12783 	 * to report back to the transport.
12784 	 */
12785 	ecn_info = ipf->ipf_ecn;
12786 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12787 	ipfp = ipf->ipf_ptphn;
12788 
12789 	/* We need to supply these to caller */
12790 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12791 		sum_val = ipf->ipf_checksum;
12792 	else
12793 		sum_val = 0;
12794 
12795 	mp1 = ipf->ipf_mp;
12796 	count = ipf->ipf_count;
12797 	ipf = ipf->ipf_hash_next;
12798 	if (ipf != NULL)
12799 		ipf->ipf_ptphn = ipfp;
12800 	ipfp[0] = ipf;
12801 	ill->ill_frag_count -= count;
12802 	ASSERT(ipfb->ipfb_count >= count);
12803 	ipfb->ipfb_count -= count;
12804 	ipfb->ipfb_frag_pkts--;
12805 	mutex_exit(&ipfb->ipfb_lock);
12806 	/* Ditch the frag header. */
12807 	mp = mp1->b_cont;
12808 
12809 	freeb(mp1);
12810 
12811 	/* Restore original IP length in header. */
12812 	packet_size = (uint32_t)msgdsize(mp);
12813 	if (packet_size > IP_MAXPACKET) {
12814 		freemsg(mp);
12815 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12816 		return (B_FALSE);
12817 	}
12818 
12819 	if (DB_REF(mp) > 1) {
12820 		mblk_t *mp2 = copymsg(mp);
12821 
12822 		freemsg(mp);
12823 		if (mp2 == NULL) {
12824 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12825 			return (B_FALSE);
12826 		}
12827 		mp = mp2;
12828 	}
12829 	ipha = (ipha_t *)mp->b_rptr;
12830 
12831 	ipha->ipha_length = htons((uint16_t)packet_size);
12832 	/* We're now complete, zip the frag state */
12833 	ipha->ipha_fragment_offset_and_flags = 0;
12834 	/* Record the ECN info. */
12835 	ipha->ipha_type_of_service &= 0xFC;
12836 	ipha->ipha_type_of_service |= ecn_info;
12837 	*mpp = mp;
12838 
12839 	/* Reassembly is successful; return checksum information if needed */
12840 	if (cksum_val != NULL)
12841 		*cksum_val = sum_val;
12842 	if (cksum_flags != NULL)
12843 		*cksum_flags = sum_flags;
12844 
12845 	return (B_TRUE);
12846 }
12847 
12848 /*
12849  * Perform ip header check sum update local options.
12850  * return B_TRUE if all is well, else return B_FALSE and release
12851  * the mp. caller is responsible for decrementing ire ref cnt.
12852  */
12853 static boolean_t
12854 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12855     ip_stack_t *ipst)
12856 {
12857 	mblk_t		*first_mp;
12858 	boolean_t	mctl_present;
12859 	uint16_t	sum;
12860 
12861 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12862 	/*
12863 	 * Don't do the checksum if it has gone through AH/ESP
12864 	 * processing.
12865 	 */
12866 	if (!mctl_present) {
12867 		sum = ip_csum_hdr(ipha);
12868 		if (sum != 0) {
12869 			if (ill != NULL) {
12870 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12871 			} else {
12872 				BUMP_MIB(&ipst->ips_ip_mib,
12873 				    ipIfStatsInCksumErrs);
12874 			}
12875 			freemsg(first_mp);
12876 			return (B_FALSE);
12877 		}
12878 	}
12879 
12880 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12881 		if (mctl_present)
12882 			freeb(first_mp);
12883 		return (B_FALSE);
12884 	}
12885 
12886 	return (B_TRUE);
12887 }
12888 
12889 /*
12890  * All udp packet are delivered to the local host via this routine.
12891  */
12892 void
12893 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12894     ill_t *recv_ill)
12895 {
12896 	uint32_t	sum;
12897 	uint32_t	u1;
12898 	boolean_t	mctl_present;
12899 	conn_t		*connp;
12900 	mblk_t		*first_mp;
12901 	uint16_t	*up;
12902 	ill_t		*ill = (ill_t *)q->q_ptr;
12903 	uint16_t	reass_hck_flags = 0;
12904 	ip_stack_t	*ipst;
12905 
12906 	ASSERT(recv_ill != NULL);
12907 	ipst = recv_ill->ill_ipst;
12908 
12909 #define	rptr    ((uchar_t *)ipha)
12910 
12911 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12912 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12913 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12914 	ASSERT(ill != NULL);
12915 
12916 	/*
12917 	 * FAST PATH for udp packets
12918 	 */
12919 
12920 	/* u1 is # words of IP options */
12921 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12922 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12923 
12924 	/* IP options present */
12925 	if (u1 != 0)
12926 		goto ipoptions;
12927 
12928 	/* Check the IP header checksum.  */
12929 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12930 		/* Clear the IP header h/w cksum flag */
12931 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12932 	} else {
12933 #define	uph	((uint16_t *)ipha)
12934 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12935 		    uph[6] + uph[7] + uph[8] + uph[9];
12936 #undef	uph
12937 		/* finish doing IP checksum */
12938 		sum = (sum & 0xFFFF) + (sum >> 16);
12939 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12940 		/*
12941 		 * Don't verify header checksum if this packet is coming
12942 		 * back from AH/ESP as we already did it.
12943 		 */
12944 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12945 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12946 			freemsg(first_mp);
12947 			return;
12948 		}
12949 	}
12950 
12951 	/*
12952 	 * Count for SNMP of inbound packets for ire.
12953 	 * if mctl is present this might be a secure packet and
12954 	 * has already been counted for in ip_proto_input().
12955 	 */
12956 	if (!mctl_present) {
12957 		UPDATE_IB_PKT_COUNT(ire);
12958 		ire->ire_last_used_time = lbolt;
12959 	}
12960 
12961 	/* packet part of fragmented IP packet? */
12962 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12963 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12964 		goto fragmented;
12965 	}
12966 
12967 	/* u1 = IP header length (20 bytes) */
12968 	u1 = IP_SIMPLE_HDR_LENGTH;
12969 
12970 	/* packet does not contain complete IP & UDP headers */
12971 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12972 		goto udppullup;
12973 
12974 	/* up points to UDP header */
12975 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12976 #define	iphs    ((uint16_t *)ipha)
12977 
12978 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12979 	if (up[3] != 0) {
12980 		mblk_t *mp1 = mp->b_cont;
12981 		boolean_t cksum_err;
12982 		uint16_t hck_flags = 0;
12983 
12984 		/* Pseudo-header checksum */
12985 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12986 		    iphs[9] + up[2];
12987 
12988 		/*
12989 		 * Revert to software checksum calculation if the interface
12990 		 * isn't capable of checksum offload or if IPsec is present.
12991 		 */
12992 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12993 			hck_flags = DB_CKSUMFLAGS(mp);
12994 
12995 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12996 			IP_STAT(ipst, ip_in_sw_cksum);
12997 
12998 		IP_CKSUM_RECV(hck_flags, u1,
12999 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13000 		    (int32_t)((uchar_t *)up - rptr),
13001 		    mp, mp1, cksum_err);
13002 
13003 		if (cksum_err) {
13004 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13005 			if (hck_flags & HCK_FULLCKSUM)
13006 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13007 			else if (hck_flags & HCK_PARTIALCKSUM)
13008 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13009 			else
13010 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13011 
13012 			freemsg(first_mp);
13013 			return;
13014 		}
13015 	}
13016 
13017 	/* Non-fragmented broadcast or multicast packet? */
13018 	if (ire->ire_type == IRE_BROADCAST)
13019 		goto udpslowpath;
13020 
13021 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
13022 	    ire->ire_zoneid, ipst)) != NULL) {
13023 		ASSERT(connp->conn_upq != NULL);
13024 		IP_STAT(ipst, ip_udp_fast_path);
13025 
13026 		if (CONN_UDP_FLOWCTLD(connp)) {
13027 			freemsg(mp);
13028 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
13029 		} else {
13030 			if (!mctl_present) {
13031 				BUMP_MIB(ill->ill_ip_mib,
13032 				    ipIfStatsHCInDelivers);
13033 			}
13034 			/*
13035 			 * mp and first_mp can change.
13036 			 */
13037 			if (ip_udp_check(q, connp, recv_ill,
13038 			    ipha, &mp, &first_mp, mctl_present)) {
13039 				/* Send it upstream */
13040 				CONN_UDP_RECV(connp, mp);
13041 			}
13042 		}
13043 		/*
13044 		 * freeb() cannot deal with null mblk being passed
13045 		 * in and first_mp can be set to null in the call
13046 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13047 		 */
13048 		if (mctl_present && first_mp != NULL) {
13049 			freeb(first_mp);
13050 		}
13051 		CONN_DEC_REF(connp);
13052 		return;
13053 	}
13054 
13055 	/*
13056 	 * if we got here we know the packet is not fragmented and
13057 	 * has no options. The classifier could not find a conn_t and
13058 	 * most likely its an icmp packet so send it through slow path.
13059 	 */
13060 
13061 	goto udpslowpath;
13062 
13063 ipoptions:
13064 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13065 		goto slow_done;
13066 	}
13067 
13068 	UPDATE_IB_PKT_COUNT(ire);
13069 	ire->ire_last_used_time = lbolt;
13070 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13071 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13072 fragmented:
13073 		/*
13074 		 * "sum" and "reass_hck_flags" are non-zero if the
13075 		 * reassembled packet has a valid hardware computed
13076 		 * checksum information associated with it.
13077 		 */
13078 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13079 			goto slow_done;
13080 		/*
13081 		 * Make sure that first_mp points back to mp as
13082 		 * the mp we came in with could have changed in
13083 		 * ip_rput_fragment().
13084 		 */
13085 		ASSERT(!mctl_present);
13086 		ipha = (ipha_t *)mp->b_rptr;
13087 		first_mp = mp;
13088 	}
13089 
13090 	/* Now we have a complete datagram, destined for this machine. */
13091 	u1 = IPH_HDR_LENGTH(ipha);
13092 	/* Pull up the UDP header, if necessary. */
13093 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13094 udppullup:
13095 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13096 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13097 			freemsg(first_mp);
13098 			goto slow_done;
13099 		}
13100 		ipha = (ipha_t *)mp->b_rptr;
13101 	}
13102 
13103 	/*
13104 	 * Validate the checksum for the reassembled packet; for the
13105 	 * pullup case we calculate the payload checksum in software.
13106 	 */
13107 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13108 	if (up[3] != 0) {
13109 		boolean_t cksum_err;
13110 
13111 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13112 			IP_STAT(ipst, ip_in_sw_cksum);
13113 
13114 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13115 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13116 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13117 		    iphs[9] + up[2], sum, cksum_err);
13118 
13119 		if (cksum_err) {
13120 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13121 
13122 			if (reass_hck_flags & HCK_FULLCKSUM)
13123 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13124 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13125 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13126 			else
13127 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13128 
13129 			freemsg(first_mp);
13130 			goto slow_done;
13131 		}
13132 	}
13133 udpslowpath:
13134 
13135 	/* Clear hardware checksum flag to be safe */
13136 	DB_CKSUMFLAGS(mp) = 0;
13137 
13138 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13139 	    (ire->ire_type == IRE_BROADCAST),
13140 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13141 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13142 
13143 slow_done:
13144 	IP_STAT(ipst, ip_udp_slow_path);
13145 	return;
13146 
13147 #undef  iphs
13148 #undef  rptr
13149 }
13150 
13151 /* ARGSUSED */
13152 static mblk_t *
13153 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13154     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13155     ill_rx_ring_t *ill_ring)
13156 {
13157 	conn_t		*connp;
13158 	uint32_t	sum;
13159 	uint32_t	u1;
13160 	uint16_t	*up;
13161 	int		offset;
13162 	ssize_t		len;
13163 	mblk_t		*mp1;
13164 	boolean_t	syn_present = B_FALSE;
13165 	tcph_t		*tcph;
13166 	uint_t		ip_hdr_len;
13167 	ill_t		*ill = (ill_t *)q->q_ptr;
13168 	zoneid_t	zoneid = ire->ire_zoneid;
13169 	boolean_t	cksum_err;
13170 	uint16_t	hck_flags = 0;
13171 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13172 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13173 
13174 #define	rptr	((uchar_t *)ipha)
13175 
13176 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13177 	ASSERT(ill != NULL);
13178 
13179 	/*
13180 	 * FAST PATH for tcp packets
13181 	 */
13182 
13183 	/* u1 is # words of IP options */
13184 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13185 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13186 
13187 	/* IP options present */
13188 	if (u1) {
13189 		goto ipoptions;
13190 	} else {
13191 		/* Check the IP header checksum.  */
13192 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13193 			/* Clear the IP header h/w cksum flag */
13194 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13195 		} else {
13196 #define	uph	((uint16_t *)ipha)
13197 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13198 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13199 #undef	uph
13200 			/* finish doing IP checksum */
13201 			sum = (sum & 0xFFFF) + (sum >> 16);
13202 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13203 			/*
13204 			 * Don't verify header checksum if this packet
13205 			 * is coming back from AH/ESP as we already did it.
13206 			 */
13207 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13208 				BUMP_MIB(ill->ill_ip_mib,
13209 				    ipIfStatsInCksumErrs);
13210 				goto error;
13211 			}
13212 		}
13213 	}
13214 
13215 	if (!mctl_present) {
13216 		UPDATE_IB_PKT_COUNT(ire);
13217 		ire->ire_last_used_time = lbolt;
13218 	}
13219 
13220 	/* packet part of fragmented IP packet? */
13221 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13222 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13223 		goto fragmented;
13224 	}
13225 
13226 	/* u1 = IP header length (20 bytes) */
13227 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13228 
13229 	/* does packet contain IP+TCP headers? */
13230 	len = mp->b_wptr - rptr;
13231 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13232 		IP_STAT(ipst, ip_tcppullup);
13233 		goto tcppullup;
13234 	}
13235 
13236 	/* TCP options present? */
13237 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13238 
13239 	/*
13240 	 * If options need to be pulled up, then goto tcpoptions.
13241 	 * otherwise we are still in the fast path
13242 	 */
13243 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13244 		IP_STAT(ipst, ip_tcpoptions);
13245 		goto tcpoptions;
13246 	}
13247 
13248 	/* multiple mblks of tcp data? */
13249 	if ((mp1 = mp->b_cont) != NULL) {
13250 		/* more then two? */
13251 		if (mp1->b_cont != NULL) {
13252 			IP_STAT(ipst, ip_multipkttcp);
13253 			goto multipkttcp;
13254 		}
13255 		len += mp1->b_wptr - mp1->b_rptr;
13256 	}
13257 
13258 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13259 
13260 	/* part of pseudo checksum */
13261 
13262 	/* TCP datagram length */
13263 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13264 
13265 #define	iphs    ((uint16_t *)ipha)
13266 
13267 #ifdef	_BIG_ENDIAN
13268 	u1 += IPPROTO_TCP;
13269 #else
13270 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13271 #endif
13272 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13273 
13274 	/*
13275 	 * Revert to software checksum calculation if the interface
13276 	 * isn't capable of checksum offload or if IPsec is present.
13277 	 */
13278 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13279 		hck_flags = DB_CKSUMFLAGS(mp);
13280 
13281 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13282 		IP_STAT(ipst, ip_in_sw_cksum);
13283 
13284 	IP_CKSUM_RECV(hck_flags, u1,
13285 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13286 	    (int32_t)((uchar_t *)up - rptr),
13287 	    mp, mp1, cksum_err);
13288 
13289 	if (cksum_err) {
13290 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13291 
13292 		if (hck_flags & HCK_FULLCKSUM)
13293 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13294 		else if (hck_flags & HCK_PARTIALCKSUM)
13295 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13296 		else
13297 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13298 
13299 		goto error;
13300 	}
13301 
13302 try_again:
13303 
13304 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13305 	    zoneid, ipst)) == NULL) {
13306 		/* Send the TH_RST */
13307 		goto no_conn;
13308 	}
13309 
13310 	/*
13311 	 * TCP FAST PATH for AF_INET socket.
13312 	 *
13313 	 * TCP fast path to avoid extra work. An AF_INET socket type
13314 	 * does not have facility to receive extra information via
13315 	 * ip_process or ip_add_info. Also, when the connection was
13316 	 * established, we made a check if this connection is impacted
13317 	 * by any global IPSec policy or per connection policy (a
13318 	 * policy that comes in effect later will not apply to this
13319 	 * connection). Since all this can be determined at the
13320 	 * connection establishment time, a quick check of flags
13321 	 * can avoid extra work.
13322 	 */
13323 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13324 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13325 		ASSERT(first_mp == mp);
13326 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13327 		SET_SQUEUE(mp, tcp_rput_data, connp);
13328 		return (mp);
13329 	}
13330 
13331 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13332 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13333 		if (IPCL_IS_TCP(connp)) {
13334 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13335 			DB_CKSUMSTART(mp) =
13336 			    (intptr_t)ip_squeue_get(ill_ring);
13337 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13338 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13339 				BUMP_MIB(ill->ill_ip_mib,
13340 				    ipIfStatsHCInDelivers);
13341 				SET_SQUEUE(mp, connp->conn_recv, connp);
13342 				return (mp);
13343 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13344 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13345 				BUMP_MIB(ill->ill_ip_mib,
13346 				    ipIfStatsHCInDelivers);
13347 				ip_squeue_enter_unbound++;
13348 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13349 				    connp);
13350 				return (mp);
13351 			}
13352 			syn_present = B_TRUE;
13353 		}
13354 
13355 	}
13356 
13357 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13358 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13359 
13360 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13361 		/* No need to send this packet to TCP */
13362 		if ((flags & TH_RST) || (flags & TH_URG)) {
13363 			CONN_DEC_REF(connp);
13364 			freemsg(first_mp);
13365 			return (NULL);
13366 		}
13367 		if (flags & TH_ACK) {
13368 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13369 			    ipst->ips_netstack->netstack_tcp);
13370 			CONN_DEC_REF(connp);
13371 			return (NULL);
13372 		}
13373 
13374 		CONN_DEC_REF(connp);
13375 		freemsg(first_mp);
13376 		return (NULL);
13377 	}
13378 
13379 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13380 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13381 		    ipha, NULL, mctl_present);
13382 		if (first_mp == NULL) {
13383 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13384 			CONN_DEC_REF(connp);
13385 			return (NULL);
13386 		}
13387 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13388 			ASSERT(syn_present);
13389 			if (mctl_present) {
13390 				ASSERT(first_mp != mp);
13391 				first_mp->b_datap->db_struioflag |=
13392 				    STRUIO_POLICY;
13393 			} else {
13394 				ASSERT(first_mp == mp);
13395 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13396 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13397 			}
13398 		} else {
13399 			/*
13400 			 * Discard first_mp early since we're dealing with a
13401 			 * fully-connected conn_t and tcp doesn't do policy in
13402 			 * this case.
13403 			 */
13404 			if (mctl_present) {
13405 				freeb(first_mp);
13406 				mctl_present = B_FALSE;
13407 			}
13408 			first_mp = mp;
13409 		}
13410 	}
13411 
13412 	/* Initiate IPPF processing for fastpath */
13413 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13414 		uint32_t	ill_index;
13415 
13416 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13417 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13418 		if (mp == NULL) {
13419 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13420 			    "deferred/dropped during IPPF processing\n"));
13421 			CONN_DEC_REF(connp);
13422 			if (mctl_present)
13423 				freeb(first_mp);
13424 			return (NULL);
13425 		} else if (mctl_present) {
13426 			/*
13427 			 * ip_process might return a new mp.
13428 			 */
13429 			ASSERT(first_mp != mp);
13430 			first_mp->b_cont = mp;
13431 		} else {
13432 			first_mp = mp;
13433 		}
13434 
13435 	}
13436 
13437 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13438 		/*
13439 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13440 		 * make sure IPF_RECVIF is passed to ip_add_info.
13441 		 */
13442 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13443 		    IPCL_ZONEID(connp), ipst);
13444 		if (mp == NULL) {
13445 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13446 			CONN_DEC_REF(connp);
13447 			if (mctl_present)
13448 				freeb(first_mp);
13449 			return (NULL);
13450 		} else if (mctl_present) {
13451 			/*
13452 			 * ip_add_info might return a new mp.
13453 			 */
13454 			ASSERT(first_mp != mp);
13455 			first_mp->b_cont = mp;
13456 		} else {
13457 			first_mp = mp;
13458 		}
13459 	}
13460 
13461 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13462 	if (IPCL_IS_TCP(connp)) {
13463 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13464 		return (first_mp);
13465 	} else {
13466 		putnext(connp->conn_rq, first_mp);
13467 		CONN_DEC_REF(connp);
13468 		return (NULL);
13469 	}
13470 
13471 no_conn:
13472 	/* Initiate IPPf processing, if needed. */
13473 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13474 		uint32_t ill_index;
13475 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13476 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13477 		if (first_mp == NULL) {
13478 			return (NULL);
13479 		}
13480 	}
13481 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13482 
13483 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13484 	    ipst->ips_netstack->netstack_tcp);
13485 	return (NULL);
13486 ipoptions:
13487 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13488 		goto slow_done;
13489 	}
13490 
13491 	UPDATE_IB_PKT_COUNT(ire);
13492 	ire->ire_last_used_time = lbolt;
13493 
13494 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13495 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13496 fragmented:
13497 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13498 			if (mctl_present)
13499 				freeb(first_mp);
13500 			goto slow_done;
13501 		}
13502 		/*
13503 		 * Make sure that first_mp points back to mp as
13504 		 * the mp we came in with could have changed in
13505 		 * ip_rput_fragment().
13506 		 */
13507 		ASSERT(!mctl_present);
13508 		ipha = (ipha_t *)mp->b_rptr;
13509 		first_mp = mp;
13510 	}
13511 
13512 	/* Now we have a complete datagram, destined for this machine. */
13513 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13514 
13515 	len = mp->b_wptr - mp->b_rptr;
13516 	/* Pull up a minimal TCP header, if necessary. */
13517 	if (len < (u1 + 20)) {
13518 tcppullup:
13519 		if (!pullupmsg(mp, u1 + 20)) {
13520 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13521 			goto error;
13522 		}
13523 		ipha = (ipha_t *)mp->b_rptr;
13524 		len = mp->b_wptr - mp->b_rptr;
13525 	}
13526 
13527 	/*
13528 	 * Extract the offset field from the TCP header.  As usual, we
13529 	 * try to help the compiler more than the reader.
13530 	 */
13531 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13532 	if (offset != 5) {
13533 tcpoptions:
13534 		if (offset < 5) {
13535 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13536 			goto error;
13537 		}
13538 		/*
13539 		 * There must be TCP options.
13540 		 * Make sure we can grab them.
13541 		 */
13542 		offset <<= 2;
13543 		offset += u1;
13544 		if (len < offset) {
13545 			if (!pullupmsg(mp, offset)) {
13546 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13547 				goto error;
13548 			}
13549 			ipha = (ipha_t *)mp->b_rptr;
13550 			len = mp->b_wptr - rptr;
13551 		}
13552 	}
13553 
13554 	/* Get the total packet length in len, including headers. */
13555 	if (mp->b_cont) {
13556 multipkttcp:
13557 		len = msgdsize(mp);
13558 	}
13559 
13560 	/*
13561 	 * Check the TCP checksum by pulling together the pseudo-
13562 	 * header checksum, and passing it to ip_csum to be added in
13563 	 * with the TCP datagram.
13564 	 *
13565 	 * Since we are not using the hwcksum if available we must
13566 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13567 	 * If either of these fails along the way the mblk is freed.
13568 	 * If this logic ever changes and mblk is reused to say send
13569 	 * ICMP's back, then this flag may need to be cleared in
13570 	 * other places as well.
13571 	 */
13572 	DB_CKSUMFLAGS(mp) = 0;
13573 
13574 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13575 
13576 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13577 #ifdef	_BIG_ENDIAN
13578 	u1 += IPPROTO_TCP;
13579 #else
13580 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13581 #endif
13582 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13583 	/*
13584 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13585 	 */
13586 	IP_STAT(ipst, ip_in_sw_cksum);
13587 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13588 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13589 		goto error;
13590 	}
13591 
13592 	IP_STAT(ipst, ip_tcp_slow_path);
13593 	goto try_again;
13594 #undef  iphs
13595 #undef  rptr
13596 
13597 error:
13598 	freemsg(first_mp);
13599 slow_done:
13600 	return (NULL);
13601 }
13602 
13603 /* ARGSUSED */
13604 static void
13605 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13606     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13607 {
13608 	conn_t		*connp;
13609 	uint32_t	sum;
13610 	uint32_t	u1;
13611 	ssize_t		len;
13612 	sctp_hdr_t	*sctph;
13613 	zoneid_t	zoneid = ire->ire_zoneid;
13614 	uint32_t	pktsum;
13615 	uint32_t	calcsum;
13616 	uint32_t	ports;
13617 	in6_addr_t	map_src, map_dst;
13618 	ill_t		*ill = (ill_t *)q->q_ptr;
13619 	ip_stack_t	*ipst;
13620 	sctp_stack_t	*sctps;
13621 
13622 	ASSERT(recv_ill != NULL);
13623 	ipst = recv_ill->ill_ipst;
13624 	sctps = ipst->ips_netstack->netstack_sctp;
13625 
13626 #define	rptr	((uchar_t *)ipha)
13627 
13628 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13629 	ASSERT(ill != NULL);
13630 
13631 	/* u1 is # words of IP options */
13632 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13633 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13634 
13635 	/* IP options present */
13636 	if (u1 > 0) {
13637 		goto ipoptions;
13638 	} else {
13639 		/* Check the IP header checksum.  */
13640 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13641 #define	uph	((uint16_t *)ipha)
13642 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13643 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13644 #undef	uph
13645 			/* finish doing IP checksum */
13646 			sum = (sum & 0xFFFF) + (sum >> 16);
13647 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13648 			/*
13649 			 * Don't verify header checksum if this packet
13650 			 * is coming back from AH/ESP as we already did it.
13651 			 */
13652 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13653 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13654 				goto error;
13655 			}
13656 		}
13657 		/*
13658 		 * Since there is no SCTP h/w cksum support yet, just
13659 		 * clear the flag.
13660 		 */
13661 		DB_CKSUMFLAGS(mp) = 0;
13662 	}
13663 
13664 	/*
13665 	 * Don't verify header checksum if this packet is coming
13666 	 * back from AH/ESP as we already did it.
13667 	 */
13668 	if (!mctl_present) {
13669 		UPDATE_IB_PKT_COUNT(ire);
13670 		ire->ire_last_used_time = lbolt;
13671 	}
13672 
13673 	/* packet part of fragmented IP packet? */
13674 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13675 	if (u1 & (IPH_MF | IPH_OFFSET))
13676 		goto fragmented;
13677 
13678 	/* u1 = IP header length (20 bytes) */
13679 	u1 = IP_SIMPLE_HDR_LENGTH;
13680 
13681 find_sctp_client:
13682 	/* Pullup if we don't have the sctp common header. */
13683 	len = MBLKL(mp);
13684 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13685 		if (mp->b_cont == NULL ||
13686 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13687 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13688 			goto error;
13689 		}
13690 		ipha = (ipha_t *)mp->b_rptr;
13691 		len = MBLKL(mp);
13692 	}
13693 
13694 	sctph = (sctp_hdr_t *)(rptr + u1);
13695 #ifdef	DEBUG
13696 	if (!skip_sctp_cksum) {
13697 #endif
13698 		pktsum = sctph->sh_chksum;
13699 		sctph->sh_chksum = 0;
13700 		calcsum = sctp_cksum(mp, u1);
13701 		if (calcsum != pktsum) {
13702 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13703 			goto error;
13704 		}
13705 		sctph->sh_chksum = pktsum;
13706 #ifdef	DEBUG	/* skip_sctp_cksum */
13707 	}
13708 #endif
13709 	/* get the ports */
13710 	ports = *(uint32_t *)&sctph->sh_sport;
13711 
13712 	IRE_REFRELE(ire);
13713 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13714 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13715 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13716 	    sctps)) == NULL) {
13717 		/* Check for raw socket or OOTB handling */
13718 		goto no_conn;
13719 	}
13720 
13721 	/* Found a client; up it goes */
13722 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13723 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13724 	return;
13725 
13726 no_conn:
13727 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13728 	    ports, mctl_present, flags, B_TRUE, zoneid);
13729 	return;
13730 
13731 ipoptions:
13732 	DB_CKSUMFLAGS(mp) = 0;
13733 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13734 		goto slow_done;
13735 
13736 	UPDATE_IB_PKT_COUNT(ire);
13737 	ire->ire_last_used_time = lbolt;
13738 
13739 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13740 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13741 fragmented:
13742 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13743 			goto slow_done;
13744 		/*
13745 		 * Make sure that first_mp points back to mp as
13746 		 * the mp we came in with could have changed in
13747 		 * ip_rput_fragment().
13748 		 */
13749 		ASSERT(!mctl_present);
13750 		ipha = (ipha_t *)mp->b_rptr;
13751 		first_mp = mp;
13752 	}
13753 
13754 	/* Now we have a complete datagram, destined for this machine. */
13755 	u1 = IPH_HDR_LENGTH(ipha);
13756 	goto find_sctp_client;
13757 #undef  iphs
13758 #undef  rptr
13759 
13760 error:
13761 	freemsg(first_mp);
13762 slow_done:
13763 	IRE_REFRELE(ire);
13764 }
13765 
13766 #define	VER_BITS	0xF0
13767 #define	VERSION_6	0x60
13768 
13769 static boolean_t
13770 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13771     ipaddr_t *dstp, ip_stack_t *ipst)
13772 {
13773 	uint_t	opt_len;
13774 	ipha_t *ipha;
13775 	ssize_t len;
13776 	uint_t	pkt_len;
13777 
13778 	ASSERT(ill != NULL);
13779 	IP_STAT(ipst, ip_ipoptions);
13780 	ipha = *iphapp;
13781 
13782 #define	rptr    ((uchar_t *)ipha)
13783 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13784 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13785 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13786 		freemsg(mp);
13787 		return (B_FALSE);
13788 	}
13789 
13790 	/* multiple mblk or too short */
13791 	pkt_len = ntohs(ipha->ipha_length);
13792 
13793 	/* Get the number of words of IP options in the IP header. */
13794 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13795 	if (opt_len) {
13796 		/* IP Options present!  Validate and process. */
13797 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13798 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13799 			goto done;
13800 		}
13801 		/*
13802 		 * Recompute complete header length and make sure we
13803 		 * have access to all of it.
13804 		 */
13805 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13806 		if (len > (mp->b_wptr - rptr)) {
13807 			if (len > pkt_len) {
13808 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13809 				goto done;
13810 			}
13811 			if (!pullupmsg(mp, len)) {
13812 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13813 				goto done;
13814 			}
13815 			ipha = (ipha_t *)mp->b_rptr;
13816 		}
13817 		/*
13818 		 * Go off to ip_rput_options which returns the next hop
13819 		 * destination address, which may have been affected
13820 		 * by source routing.
13821 		 */
13822 		IP_STAT(ipst, ip_opt);
13823 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13824 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13825 			return (B_FALSE);
13826 		}
13827 	}
13828 	*iphapp = ipha;
13829 	return (B_TRUE);
13830 done:
13831 	/* clear b_prev - used by ip_mroute_decap */
13832 	mp->b_prev = NULL;
13833 	freemsg(mp);
13834 	return (B_FALSE);
13835 #undef  rptr
13836 }
13837 
13838 /*
13839  * Deal with the fact that there is no ire for the destination.
13840  * The incoming ill (in_ill) is passed in to ip_newroute only
13841  * in the case of packets coming from mobile ip forward tunnel.
13842  * It must be null otherwise.
13843  */
13844 static ire_t *
13845 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13846     ipaddr_t dst)
13847 {
13848 	ipha_t	*ipha;
13849 	ill_t	*ill;
13850 	ire_t	*ire;
13851 	boolean_t	check_multirt = B_FALSE;
13852 	ip_stack_t *ipst;
13853 
13854 	ipha = (ipha_t *)mp->b_rptr;
13855 	ill = (ill_t *)q->q_ptr;
13856 
13857 	ASSERT(ill != NULL);
13858 	ipst = ill->ill_ipst;
13859 
13860 	/*
13861 	 * No IRE for this destination, so it can't be for us.
13862 	 * Unless we are forwarding, drop the packet.
13863 	 * We have to let source routed packets through
13864 	 * since we don't yet know if they are 'ping -l'
13865 	 * packets i.e. if they will go out over the
13866 	 * same interface as they came in on.
13867 	 */
13868 	if (ll_multicast) {
13869 		freemsg(mp);
13870 		return (NULL);
13871 	}
13872 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13873 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13874 		freemsg(mp);
13875 		return (NULL);
13876 	}
13877 
13878 	/*
13879 	 * Mark this packet as having originated externally.
13880 	 *
13881 	 * For non-forwarding code path, ire_send later double
13882 	 * checks this interface to see if it is still exists
13883 	 * post-ARP resolution.
13884 	 *
13885 	 * Also, IPQOS uses this to differentiate between
13886 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13887 	 * QOS packet processing in ip_wput_attach_llhdr().
13888 	 * The QoS module can mark the b_band for a fastpath message
13889 	 * or the dl_priority field in a unitdata_req header for
13890 	 * CoS marking. This info can only be found in
13891 	 * ip_wput_attach_llhdr().
13892 	 */
13893 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13894 	/*
13895 	 * Clear the indication that this may have a hardware checksum
13896 	 * as we are not using it
13897 	 */
13898 	DB_CKSUMFLAGS(mp) = 0;
13899 
13900 	if (in_ill != NULL) {
13901 		/*
13902 		 * Now hand the packet to ip_newroute.
13903 		 */
13904 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13905 		return (NULL);
13906 	}
13907 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13908 	    MBLK_GETLABEL(mp), ipst);
13909 
13910 	if (ire == NULL && check_multirt) {
13911 		/* Let ip_newroute handle CGTP  */
13912 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13913 		return (NULL);
13914 	}
13915 
13916 	if (ire != NULL)
13917 		return (ire);
13918 
13919 	mp->b_prev = mp->b_next = 0;
13920 	/* send icmp unreachable */
13921 	q = WR(q);
13922 	/* Sent by forwarding path, and router is global zone */
13923 	if (ip_source_routed(ipha, ipst)) {
13924 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13925 		    GLOBAL_ZONEID, ipst);
13926 	} else {
13927 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13928 		    ipst);
13929 	}
13930 
13931 	return (NULL);
13932 
13933 }
13934 
13935 /*
13936  * check ip header length and align it.
13937  */
13938 static boolean_t
13939 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13940 {
13941 	ssize_t len;
13942 	ill_t *ill;
13943 	ipha_t	*ipha;
13944 
13945 	len = MBLKL(mp);
13946 
13947 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13948 		ill = (ill_t *)q->q_ptr;
13949 
13950 		if (!OK_32PTR(mp->b_rptr))
13951 			IP_STAT(ipst, ip_notaligned1);
13952 		else
13953 			IP_STAT(ipst, ip_notaligned2);
13954 		/* Guard against bogus device drivers */
13955 		if (len < 0) {
13956 			/* clear b_prev - used by ip_mroute_decap */
13957 			mp->b_prev = NULL;
13958 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13959 			freemsg(mp);
13960 			return (B_FALSE);
13961 		}
13962 
13963 		if (ip_rput_pullups++ == 0) {
13964 			ipha = (ipha_t *)mp->b_rptr;
13965 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13966 			    "ip_check_and_align_header: %s forced us to "
13967 			    " pullup pkt, hdr len %ld, hdr addr %p",
13968 			    ill->ill_name, len, ipha);
13969 		}
13970 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13971 			/* clear b_prev - used by ip_mroute_decap */
13972 			mp->b_prev = NULL;
13973 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13974 			freemsg(mp);
13975 			return (B_FALSE);
13976 		}
13977 	}
13978 	return (B_TRUE);
13979 }
13980 
13981 ire_t *
13982 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13983 {
13984 	ire_t		*new_ire;
13985 	ill_t		*ire_ill;
13986 	uint_t		ifindex;
13987 	ip_stack_t	*ipst = ill->ill_ipst;
13988 	boolean_t	strict_check = B_FALSE;
13989 
13990 	/*
13991 	 * This packet came in on an interface other than the one associated
13992 	 * with the first ire we found for the destination address. We do
13993 	 * another ire lookup here, using the ingress ill, to see if the
13994 	 * interface is in an interface group.
13995 	 * As long as the ills belong to the same group, we don't consider
13996 	 * them to be arriving on the wrong interface. Thus, if the switch
13997 	 * is doing inbound load spreading, we won't drop packets when the
13998 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13999 	 * for 'usesrc groups' where the destination address may belong to
14000 	 * another interface to allow multipathing to happen.
14001 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
14002 	 * where the local address may not be unique. In this case we were
14003 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
14004 	 * actually returned. The new lookup, which is more specific, should
14005 	 * only find the IRE_LOCAL associated with the ingress ill if one
14006 	 * exists.
14007 	 */
14008 
14009 	if (ire->ire_ipversion == IPV4_VERSION) {
14010 		if (ipst->ips_ip_strict_dst_multihoming)
14011 			strict_check = B_TRUE;
14012 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
14013 		    ill->ill_ipif, ALL_ZONES, NULL,
14014 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14015 	} else {
14016 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
14017 		if (ipst->ips_ipv6_strict_dst_multihoming)
14018 			strict_check = B_TRUE;
14019 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
14020 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
14021 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
14022 	}
14023 	/*
14024 	 * If the same ire that was returned in ip_input() is found then this
14025 	 * is an indication that interface groups are in use. The packet
14026 	 * arrived on a different ill in the group than the one associated with
14027 	 * the destination address.  If a different ire was found then the same
14028 	 * IP address must be hosted on multiple ills. This is possible with
14029 	 * unnumbered point2point interfaces. We switch to use this new ire in
14030 	 * order to have accurate interface statistics.
14031 	 */
14032 	if (new_ire != NULL) {
14033 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
14034 			ire_refrele(ire);
14035 			ire = new_ire;
14036 		} else {
14037 			ire_refrele(new_ire);
14038 		}
14039 		return (ire);
14040 	} else if ((ire->ire_rfq == NULL) &&
14041 	    (ire->ire_ipversion == IPV4_VERSION)) {
14042 		/*
14043 		 * The best match could have been the original ire which
14044 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14045 		 * the strict multihoming checks are irrelevant as we consider
14046 		 * local addresses hosted on lo0 to be interface agnostic. We
14047 		 * only expect a null ire_rfq on IREs which are associated with
14048 		 * lo0 hence we can return now.
14049 		 */
14050 		return (ire);
14051 	}
14052 
14053 	/*
14054 	 * Chase pointers once and store locally.
14055 	 */
14056 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14057 	    (ill_t *)(ire->ire_rfq->q_ptr);
14058 	ifindex = ill->ill_usesrc_ifindex;
14059 
14060 	/*
14061 	 * Check if it's a legal address on the 'usesrc' interface.
14062 	 */
14063 	if ((ifindex != 0) && (ire_ill != NULL) &&
14064 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14065 		return (ire);
14066 	}
14067 
14068 	/*
14069 	 * If the ip*_strict_dst_multihoming switch is on then we can
14070 	 * only accept this packet if the interface is marked as routing.
14071 	 */
14072 	if (!(strict_check))
14073 		return (ire);
14074 
14075 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14076 	    ILLF_ROUTER) != 0) {
14077 		return (ire);
14078 	}
14079 
14080 	ire_refrele(ire);
14081 	return (NULL);
14082 }
14083 
14084 ire_t *
14085 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14086 {
14087 	ipha_t	*ipha;
14088 	ipaddr_t ip_dst, ip_src;
14089 	ire_t	*src_ire = NULL;
14090 	ill_t	*stq_ill;
14091 	uint_t	hlen;
14092 	uint_t	pkt_len;
14093 	uint32_t sum;
14094 	queue_t	*dev_q;
14095 	boolean_t check_multirt = B_FALSE;
14096 	ip_stack_t *ipst = ill->ill_ipst;
14097 
14098 	ipha = (ipha_t *)mp->b_rptr;
14099 
14100 	/*
14101 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14102 	 * The loopback address check for both src and dst has already
14103 	 * been checked in ip_input
14104 	 */
14105 	ip_dst = ntohl(dst);
14106 	ip_src = ntohl(ipha->ipha_src);
14107 
14108 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14109 	    IN_CLASSD(ip_src)) {
14110 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14111 		goto drop;
14112 	}
14113 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14114 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14115 
14116 	if (src_ire != NULL) {
14117 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14118 		goto drop;
14119 	}
14120 
14121 
14122 	/* No ire cache of nexthop. So first create one  */
14123 	if (ire == NULL) {
14124 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14125 		/*
14126 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14127 		 * is not set. So upon return from ire_forward
14128 		 * check_multirt should remain as false.
14129 		 */
14130 		ASSERT(!check_multirt);
14131 		if (ire == NULL) {
14132 			/* An attempt was made to forward the packet */
14133 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14134 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14135 			mp->b_prev = mp->b_next = 0;
14136 			/* send icmp unreachable */
14137 			/* Sent by forwarding path, and router is global zone */
14138 			if (ip_source_routed(ipha, ipst)) {
14139 				icmp_unreachable(ill->ill_wq, mp,
14140 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14141 				    ipst);
14142 			} else {
14143 				icmp_unreachable(ill->ill_wq, mp,
14144 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14145 				    ipst);
14146 			}
14147 			return (ire);
14148 		}
14149 	}
14150 
14151 	/*
14152 	 * Forwarding fastpath exception case:
14153 	 * If either of the follwoing case is true, we take
14154 	 * the slowpath
14155 	 *	o forwarding is not enabled
14156 	 *	o incoming and outgoing interface are the same, or the same
14157 	 *	  IPMP group
14158 	 *	o corresponding ire is in incomplete state
14159 	 *	o packet needs fragmentation
14160 	 *
14161 	 * The codeflow from here on is thus:
14162 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14163 	 */
14164 	pkt_len = ntohs(ipha->ipha_length);
14165 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14166 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14167 	    !(ill->ill_flags & ILLF_ROUTER) ||
14168 	    (ill == stq_ill) ||
14169 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14170 	    (ire->ire_nce == NULL) ||
14171 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14172 	    (pkt_len > ire->ire_max_frag) ||
14173 	    ipha->ipha_ttl <= 1) {
14174 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14175 		    ipha, ill, B_FALSE);
14176 		return (ire);
14177 	}
14178 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14179 
14180 	DTRACE_PROBE4(ip4__forwarding__start,
14181 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14182 
14183 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14184 	    ipst->ips_ipv4firewall_forwarding,
14185 	    ill, stq_ill, ipha, mp, mp, ipst);
14186 
14187 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14188 
14189 	if (mp == NULL)
14190 		goto drop;
14191 
14192 	mp->b_datap->db_struioun.cksum.flags = 0;
14193 	/* Adjust the checksum to reflect the ttl decrement. */
14194 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14195 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14196 	ipha->ipha_ttl--;
14197 
14198 	dev_q = ire->ire_stq->q_next;
14199 	if ((dev_q->q_next != NULL ||
14200 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14201 		goto indiscard;
14202 	}
14203 
14204 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14205 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14206 
14207 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14208 		mblk_t *mpip = mp;
14209 
14210 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14211 		if (mp != NULL) {
14212 			DTRACE_PROBE4(ip4__physical__out__start,
14213 			    ill_t *, NULL, ill_t *, stq_ill,
14214 			    ipha_t *, ipha, mblk_t *, mp);
14215 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14216 			    ipst->ips_ipv4firewall_physical_out,
14217 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14218 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14219 			    mp);
14220 			if (mp == NULL)
14221 				goto drop;
14222 
14223 			UPDATE_IB_PKT_COUNT(ire);
14224 			ire->ire_last_used_time = lbolt;
14225 			BUMP_MIB(stq_ill->ill_ip_mib,
14226 			    ipIfStatsHCOutForwDatagrams);
14227 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14228 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14229 			    pkt_len);
14230 			putnext(ire->ire_stq, mp);
14231 			return (ire);
14232 		}
14233 	}
14234 
14235 indiscard:
14236 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14237 drop:
14238 	if (mp != NULL)
14239 		freemsg(mp);
14240 	if (src_ire != NULL)
14241 		ire_refrele(src_ire);
14242 	return (ire);
14243 
14244 }
14245 
14246 /*
14247  * This function is called in the forwarding slowpath, when
14248  * either the ire lacks the link-layer address, or the packet needs
14249  * further processing(eg. fragmentation), before transmission.
14250  */
14251 
14252 static void
14253 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14254     ill_t *ill, boolean_t ll_multicast)
14255 {
14256 	ill_group_t	*ill_group;
14257 	ill_group_t	*ire_group;
14258 	queue_t		*dev_q;
14259 	ire_t		*src_ire;
14260 	ip_stack_t	*ipst = ill->ill_ipst;
14261 
14262 	ASSERT(ire->ire_stq != NULL);
14263 
14264 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14265 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14266 
14267 	if (ll_multicast != 0) {
14268 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14269 		goto drop_pkt;
14270 	}
14271 
14272 	/*
14273 	 * check if ipha_src is a broadcast address. Note that this
14274 	 * check is redundant when we get here from ip_fast_forward()
14275 	 * which has already done this check. However, since we can
14276 	 * also get here from ip_rput_process_broadcast() or, for
14277 	 * for the slow path through ip_fast_forward(), we perform
14278 	 * the check again for code-reusability
14279 	 */
14280 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14281 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14282 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14283 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14284 		if (src_ire != NULL)
14285 			ire_refrele(src_ire);
14286 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14287 		ip2dbg(("ip_rput_process_forward: Received packet with"
14288 		    " bad src/dst address on %s\n", ill->ill_name));
14289 		goto drop_pkt;
14290 	}
14291 
14292 	ill_group = ill->ill_group;
14293 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14294 	/*
14295 	 * Check if we want to forward this one at this time.
14296 	 * We allow source routed packets on a host provided that
14297 	 * they go out the same interface or same interface group
14298 	 * as they came in on.
14299 	 *
14300 	 * XXX To be quicker, we may wish to not chase pointers to
14301 	 * get the ILLF_ROUTER flag and instead store the
14302 	 * forwarding policy in the ire.  An unfortunate
14303 	 * side-effect of that would be requiring an ire flush
14304 	 * whenever the ILLF_ROUTER flag changes.
14305 	 */
14306 	if (((ill->ill_flags &
14307 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14308 	    ILLF_ROUTER) == 0) &&
14309 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14310 	    (ill_group != NULL && ill_group == ire_group)))) {
14311 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14312 		if (ip_source_routed(ipha, ipst)) {
14313 			q = WR(q);
14314 			/*
14315 			 * Clear the indication that this may have
14316 			 * hardware checksum as we are not using it.
14317 			 */
14318 			DB_CKSUMFLAGS(mp) = 0;
14319 			/* Sent by forwarding path, and router is global zone */
14320 			icmp_unreachable(q, mp,
14321 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14322 			return;
14323 		}
14324 		goto drop_pkt;
14325 	}
14326 
14327 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14328 
14329 	/* Packet is being forwarded. Turning off hwcksum flag. */
14330 	DB_CKSUMFLAGS(mp) = 0;
14331 	if (ipst->ips_ip_g_send_redirects) {
14332 		/*
14333 		 * Check whether the incoming interface and outgoing
14334 		 * interface is part of the same group. If so,
14335 		 * send redirects.
14336 		 *
14337 		 * Check the source address to see if it originated
14338 		 * on the same logical subnet it is going back out on.
14339 		 * If so, we should be able to send it a redirect.
14340 		 * Avoid sending a redirect if the destination
14341 		 * is directly connected (i.e., ipha_dst is the same
14342 		 * as ire_gateway_addr or the ire_addr of the
14343 		 * nexthop IRE_CACHE ), or if the packet was source
14344 		 * routed out this interface.
14345 		 */
14346 		ipaddr_t src, nhop;
14347 		mblk_t	*mp1;
14348 		ire_t	*nhop_ire = NULL;
14349 
14350 		/*
14351 		 * Check whether ire_rfq and q are from the same ill
14352 		 * or if they are not same, they at least belong
14353 		 * to the same group. If so, send redirects.
14354 		 */
14355 		if ((ire->ire_rfq == q ||
14356 		    (ill_group != NULL && ill_group == ire_group)) &&
14357 		    !ip_source_routed(ipha, ipst)) {
14358 
14359 			nhop = (ire->ire_gateway_addr != 0 ?
14360 			    ire->ire_gateway_addr : ire->ire_addr);
14361 
14362 			if (ipha->ipha_dst == nhop) {
14363 				/*
14364 				 * We avoid sending a redirect if the
14365 				 * destination is directly connected
14366 				 * because it is possible that multiple
14367 				 * IP subnets may have been configured on
14368 				 * the link, and the source may not
14369 				 * be on the same subnet as ip destination,
14370 				 * even though they are on the same
14371 				 * physical link.
14372 				 */
14373 				goto sendit;
14374 			}
14375 
14376 			src = ipha->ipha_src;
14377 
14378 			/*
14379 			 * We look up the interface ire for the nexthop,
14380 			 * to see if ipha_src is in the same subnet
14381 			 * as the nexthop.
14382 			 *
14383 			 * Note that, if, in the future, IRE_CACHE entries
14384 			 * are obsoleted,  this lookup will not be needed,
14385 			 * as the ire passed to this function will be the
14386 			 * same as the nhop_ire computed below.
14387 			 */
14388 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14389 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14390 			    0, NULL, MATCH_IRE_TYPE, ipst);
14391 
14392 			if (nhop_ire != NULL) {
14393 				if ((src & nhop_ire->ire_mask) ==
14394 				    (nhop & nhop_ire->ire_mask)) {
14395 					/*
14396 					 * The source is directly connected.
14397 					 * Just copy the ip header (which is
14398 					 * in the first mblk)
14399 					 */
14400 					mp1 = copyb(mp);
14401 					if (mp1 != NULL) {
14402 						icmp_send_redirect(WR(q), mp1,
14403 						    nhop, ipst);
14404 					}
14405 				}
14406 				ire_refrele(nhop_ire);
14407 			}
14408 		}
14409 	}
14410 sendit:
14411 	dev_q = ire->ire_stq->q_next;
14412 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14413 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14414 		freemsg(mp);
14415 		return;
14416 	}
14417 
14418 	ip_rput_forward(ire, ipha, mp, ill);
14419 	return;
14420 
14421 drop_pkt:
14422 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14423 	freemsg(mp);
14424 }
14425 
14426 ire_t *
14427 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14428     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14429 {
14430 	queue_t		*q;
14431 	uint16_t	hcksumflags;
14432 	ip_stack_t	*ipst = ill->ill_ipst;
14433 
14434 	q = *qp;
14435 
14436 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14437 
14438 	/*
14439 	 * Clear the indication that this may have hardware
14440 	 * checksum as we are not using it for forwarding.
14441 	 */
14442 	hcksumflags = DB_CKSUMFLAGS(mp);
14443 	DB_CKSUMFLAGS(mp) = 0;
14444 
14445 	/*
14446 	 * Directed broadcast forwarding: if the packet came in over a
14447 	 * different interface then it is routed out over we can forward it.
14448 	 */
14449 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14450 		ire_refrele(ire);
14451 		freemsg(mp);
14452 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14453 		return (NULL);
14454 	}
14455 	/*
14456 	 * For multicast we have set dst to be INADDR_BROADCAST
14457 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14458 	 * only for broadcast packets.
14459 	 */
14460 	if (!CLASSD(ipha->ipha_dst)) {
14461 		ire_t *new_ire;
14462 		ipif_t *ipif;
14463 		/*
14464 		 * For ill groups, as the switch duplicates broadcasts
14465 		 * across all the ports, we need to filter out and
14466 		 * send up only one copy. There is one copy for every
14467 		 * broadcast address on each ill. Thus, we look for a
14468 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14469 		 * later to see whether this ill is eligible to receive
14470 		 * them or not. ill_nominate_bcast_rcv() nominates only
14471 		 * one set of IREs for receiving.
14472 		 */
14473 
14474 		ipif = ipif_get_next_ipif(NULL, ill);
14475 		if (ipif == NULL) {
14476 			ire_refrele(ire);
14477 			freemsg(mp);
14478 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14479 			return (NULL);
14480 		}
14481 		new_ire = ire_ctable_lookup(dst, 0, 0,
14482 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14483 		ipif_refrele(ipif);
14484 
14485 		if (new_ire != NULL) {
14486 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14487 				ire_refrele(ire);
14488 				ire_refrele(new_ire);
14489 				freemsg(mp);
14490 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14491 				return (NULL);
14492 			}
14493 			/*
14494 			 * In the special case of multirouted broadcast
14495 			 * packets, we unconditionally need to "gateway"
14496 			 * them to the appropriate interface here.
14497 			 * In the normal case, this cannot happen, because
14498 			 * there is no broadcast IRE tagged with the
14499 			 * RTF_MULTIRT flag.
14500 			 */
14501 			if (new_ire->ire_flags & RTF_MULTIRT) {
14502 				ire_refrele(new_ire);
14503 				if (ire->ire_rfq != NULL) {
14504 					q = ire->ire_rfq;
14505 					*qp = q;
14506 				}
14507 			} else {
14508 				ire_refrele(ire);
14509 				ire = new_ire;
14510 			}
14511 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14512 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14513 				/*
14514 				 * Free the message if
14515 				 * ip_g_forward_directed_bcast is turned
14516 				 * off for non-local broadcast.
14517 				 */
14518 				ire_refrele(ire);
14519 				freemsg(mp);
14520 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14521 				return (NULL);
14522 			}
14523 		} else {
14524 			/*
14525 			 * This CGTP packet successfully passed the
14526 			 * CGTP filter, but the related CGTP
14527 			 * broadcast IRE has not been found,
14528 			 * meaning that the redundant ipif is
14529 			 * probably down. However, if we discarded
14530 			 * this packet, its duplicate would be
14531 			 * filtered out by the CGTP filter so none
14532 			 * of them would get through. So we keep
14533 			 * going with this one.
14534 			 */
14535 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14536 			if (ire->ire_rfq != NULL) {
14537 				q = ire->ire_rfq;
14538 				*qp = q;
14539 			}
14540 		}
14541 	}
14542 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14543 		/*
14544 		 * Verify that there are not more then one
14545 		 * IRE_BROADCAST with this broadcast address which
14546 		 * has ire_stq set.
14547 		 * TODO: simplify, loop over all IRE's
14548 		 */
14549 		ire_t	*ire1;
14550 		int	num_stq = 0;
14551 		mblk_t	*mp1;
14552 
14553 		/* Find the first one with ire_stq set */
14554 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14555 		for (ire1 = ire; ire1 &&
14556 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14557 		    ire1 = ire1->ire_next)
14558 			;
14559 		if (ire1) {
14560 			ire_refrele(ire);
14561 			ire = ire1;
14562 			IRE_REFHOLD(ire);
14563 		}
14564 
14565 		/* Check if there are additional ones with stq set */
14566 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14567 			if (ire->ire_addr != ire1->ire_addr)
14568 				break;
14569 			if (ire1->ire_stq) {
14570 				num_stq++;
14571 				break;
14572 			}
14573 		}
14574 		rw_exit(&ire->ire_bucket->irb_lock);
14575 		if (num_stq == 1 && ire->ire_stq != NULL) {
14576 			ip1dbg(("ip_rput_process_broadcast: directed "
14577 			    "broadcast to 0x%x\n",
14578 			    ntohl(ire->ire_addr)));
14579 			mp1 = copymsg(mp);
14580 			if (mp1) {
14581 				switch (ipha->ipha_protocol) {
14582 				case IPPROTO_UDP:
14583 					ip_udp_input(q, mp1, ipha, ire, ill);
14584 					break;
14585 				default:
14586 					ip_proto_input(q, mp1, ipha, ire, ill);
14587 					break;
14588 				}
14589 			}
14590 			/*
14591 			 * Adjust ttl to 2 (1+1 - the forward engine
14592 			 * will decrement it by one.
14593 			 */
14594 			if (ip_csum_hdr(ipha)) {
14595 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14596 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14597 				freemsg(mp);
14598 				ire_refrele(ire);
14599 				return (NULL);
14600 			}
14601 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14602 			ipha->ipha_hdr_checksum = 0;
14603 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14604 			ip_rput_process_forward(q, mp, ire, ipha,
14605 			    ill, ll_multicast);
14606 			ire_refrele(ire);
14607 			return (NULL);
14608 		}
14609 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14610 		    ntohl(ire->ire_addr)));
14611 	}
14612 
14613 
14614 	/* Restore any hardware checksum flags */
14615 	DB_CKSUMFLAGS(mp) = hcksumflags;
14616 	return (ire);
14617 }
14618 
14619 /* ARGSUSED */
14620 static boolean_t
14621 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14622     int *ll_multicast, ipaddr_t *dstp)
14623 {
14624 	ip_stack_t	*ipst = ill->ill_ipst;
14625 
14626 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14627 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14628 	    ntohs(ipha->ipha_length));
14629 
14630 	/*
14631 	 * Forward packets only if we have joined the allmulti
14632 	 * group on this interface.
14633 	 */
14634 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14635 		int retval;
14636 
14637 		/*
14638 		 * Clear the indication that this may have hardware
14639 		 * checksum as we are not using it.
14640 		 */
14641 		DB_CKSUMFLAGS(mp) = 0;
14642 		retval = ip_mforward(ill, ipha, mp);
14643 		/* ip_mforward updates mib variables if needed */
14644 		/* clear b_prev - used by ip_mroute_decap */
14645 		mp->b_prev = NULL;
14646 
14647 		switch (retval) {
14648 		case 0:
14649 			/*
14650 			 * pkt is okay and arrived on phyint.
14651 			 *
14652 			 * If we are running as a multicast router
14653 			 * we need to see all IGMP and/or PIM packets.
14654 			 */
14655 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14656 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14657 				goto done;
14658 			}
14659 			break;
14660 		case -1:
14661 			/* pkt is mal-formed, toss it */
14662 			goto drop_pkt;
14663 		case 1:
14664 			/* pkt is okay and arrived on a tunnel */
14665 			/*
14666 			 * If we are running a multicast router
14667 			 *  we need to see all igmp packets.
14668 			 */
14669 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14670 				*dstp = INADDR_BROADCAST;
14671 				*ll_multicast = 1;
14672 				return (B_FALSE);
14673 			}
14674 
14675 			goto drop_pkt;
14676 		}
14677 	}
14678 
14679 	ILM_WALKER_HOLD(ill);
14680 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14681 		/*
14682 		 * This might just be caused by the fact that
14683 		 * multiple IP Multicast addresses map to the same
14684 		 * link layer multicast - no need to increment counter!
14685 		 */
14686 		ILM_WALKER_RELE(ill);
14687 		freemsg(mp);
14688 		return (B_TRUE);
14689 	}
14690 	ILM_WALKER_RELE(ill);
14691 done:
14692 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14693 	/*
14694 	 * This assumes the we deliver to all streams for multicast
14695 	 * and broadcast packets.
14696 	 */
14697 	*dstp = INADDR_BROADCAST;
14698 	*ll_multicast = 1;
14699 	return (B_FALSE);
14700 drop_pkt:
14701 	ip2dbg(("ip_rput: drop pkt\n"));
14702 	freemsg(mp);
14703 	return (B_TRUE);
14704 }
14705 
14706 static boolean_t
14707 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14708     int *ll_multicast, mblk_t **mpp)
14709 {
14710 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14711 	boolean_t must_copy = B_FALSE;
14712 	struct iocblk   *iocp;
14713 	ipha_t		*ipha;
14714 	ip_stack_t	*ipst = ill->ill_ipst;
14715 
14716 #define	rptr    ((uchar_t *)ipha)
14717 
14718 	first_mp = *first_mpp;
14719 	mp = *mpp;
14720 
14721 	ASSERT(first_mp == mp);
14722 
14723 	/*
14724 	 * if db_ref > 1 then copymsg and free original. Packet may be
14725 	 * changed and do not want other entity who has a reference to this
14726 	 * message to trip over the changes. This is a blind change because
14727 	 * trying to catch all places that might change packet is too
14728 	 * difficult (since it may be a module above this one)
14729 	 *
14730 	 * This corresponds to the non-fast path case. We walk down the full
14731 	 * chain in this case, and check the db_ref count of all the dblks,
14732 	 * and do a copymsg if required. It is possible that the db_ref counts
14733 	 * of the data blocks in the mblk chain can be different.
14734 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14735 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14736 	 * 'snoop' is running.
14737 	 */
14738 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14739 		if (mp1->b_datap->db_ref > 1) {
14740 			must_copy = B_TRUE;
14741 			break;
14742 		}
14743 	}
14744 
14745 	if (must_copy) {
14746 		mp1 = copymsg(mp);
14747 		if (mp1 == NULL) {
14748 			for (mp1 = mp; mp1 != NULL;
14749 			    mp1 = mp1->b_cont) {
14750 				mp1->b_next = NULL;
14751 				mp1->b_prev = NULL;
14752 			}
14753 			freemsg(mp);
14754 			if (ill != NULL) {
14755 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14756 			} else {
14757 				BUMP_MIB(&ipst->ips_ip_mib,
14758 				    ipIfStatsInDiscards);
14759 			}
14760 			return (B_TRUE);
14761 		}
14762 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14763 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14764 			/* Copy b_prev - used by ip_mroute_decap */
14765 			to_mp->b_prev = from_mp->b_prev;
14766 			from_mp->b_prev = NULL;
14767 		}
14768 		*first_mpp = first_mp = mp1;
14769 		freemsg(mp);
14770 		mp = mp1;
14771 		*mpp = mp1;
14772 	}
14773 
14774 	ipha = (ipha_t *)mp->b_rptr;
14775 
14776 	/*
14777 	 * previous code has a case for M_DATA.
14778 	 * We want to check how that happens.
14779 	 */
14780 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14781 	switch (first_mp->b_datap->db_type) {
14782 	case M_PROTO:
14783 	case M_PCPROTO:
14784 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14785 		    DL_UNITDATA_IND) {
14786 			/* Go handle anything other than data elsewhere. */
14787 			ip_rput_dlpi(q, mp);
14788 			return (B_TRUE);
14789 		}
14790 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14791 		/* Ditch the DLPI header. */
14792 		mp1 = mp->b_cont;
14793 		ASSERT(first_mp == mp);
14794 		*first_mpp = mp1;
14795 		freeb(mp);
14796 		*mpp = mp1;
14797 		return (B_FALSE);
14798 	case M_IOCACK:
14799 		ip1dbg(("got iocack "));
14800 		iocp = (struct iocblk *)mp->b_rptr;
14801 		switch (iocp->ioc_cmd) {
14802 		case DL_IOC_HDR_INFO:
14803 			ill = (ill_t *)q->q_ptr;
14804 			ill_fastpath_ack(ill, mp);
14805 			return (B_TRUE);
14806 		case SIOCSTUNPARAM:
14807 		case OSIOCSTUNPARAM:
14808 			/* Go through qwriter_ip */
14809 			break;
14810 		case SIOCGTUNPARAM:
14811 		case OSIOCGTUNPARAM:
14812 			ip_rput_other(NULL, q, mp, NULL);
14813 			return (B_TRUE);
14814 		default:
14815 			putnext(q, mp);
14816 			return (B_TRUE);
14817 		}
14818 		/* FALLTHRU */
14819 	case M_ERROR:
14820 	case M_HANGUP:
14821 		/*
14822 		 * Since this is on the ill stream we unconditionally
14823 		 * bump up the refcount
14824 		 */
14825 		ill_refhold(ill);
14826 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14827 		return (B_TRUE);
14828 	case M_CTL:
14829 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14830 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14831 		    IPHADA_M_CTL)) {
14832 			/*
14833 			 * It's an IPsec accelerated packet.
14834 			 * Make sure that the ill from which we received the
14835 			 * packet has enabled IPsec hardware acceleration.
14836 			 */
14837 			if (!(ill->ill_capabilities &
14838 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14839 				/* IPsec kstats: bean counter */
14840 				freemsg(mp);
14841 				return (B_TRUE);
14842 			}
14843 
14844 			/*
14845 			 * Make mp point to the mblk following the M_CTL,
14846 			 * then process according to type of mp.
14847 			 * After this processing, first_mp will point to
14848 			 * the data-attributes and mp to the pkt following
14849 			 * the M_CTL.
14850 			 */
14851 			mp = first_mp->b_cont;
14852 			if (mp == NULL) {
14853 				freemsg(first_mp);
14854 				return (B_TRUE);
14855 			}
14856 			/*
14857 			 * A Hardware Accelerated packet can only be M_DATA
14858 			 * ESP or AH packet.
14859 			 */
14860 			if (mp->b_datap->db_type != M_DATA) {
14861 				/* non-M_DATA IPsec accelerated packet */
14862 				IPSECHW_DEBUG(IPSECHW_PKT,
14863 				    ("non-M_DATA IPsec accelerated pkt\n"));
14864 				freemsg(first_mp);
14865 				return (B_TRUE);
14866 			}
14867 			ipha = (ipha_t *)mp->b_rptr;
14868 			if (ipha->ipha_protocol != IPPROTO_AH &&
14869 			    ipha->ipha_protocol != IPPROTO_ESP) {
14870 				IPSECHW_DEBUG(IPSECHW_PKT,
14871 				    ("non-M_DATA IPsec accelerated pkt\n"));
14872 				freemsg(first_mp);
14873 				return (B_TRUE);
14874 			}
14875 			*mpp = mp;
14876 			return (B_FALSE);
14877 		}
14878 		putnext(q, mp);
14879 		return (B_TRUE);
14880 	case M_IOCNAK:
14881 		ip1dbg(("got iocnak "));
14882 		iocp = (struct iocblk *)mp->b_rptr;
14883 		switch (iocp->ioc_cmd) {
14884 		case SIOCSTUNPARAM:
14885 		case OSIOCSTUNPARAM:
14886 			/*
14887 			 * Since this is on the ill stream we unconditionally
14888 			 * bump up the refcount
14889 			 */
14890 			ill_refhold(ill);
14891 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14892 			return (B_TRUE);
14893 		case DL_IOC_HDR_INFO:
14894 		case SIOCGTUNPARAM:
14895 		case OSIOCGTUNPARAM:
14896 			ip_rput_other(NULL, q, mp, NULL);
14897 			return (B_TRUE);
14898 		default:
14899 			break;
14900 		}
14901 		/* FALLTHRU */
14902 	default:
14903 		putnext(q, mp);
14904 		return (B_TRUE);
14905 	}
14906 }
14907 
14908 /* Read side put procedure.  Packets coming from the wire arrive here. */
14909 void
14910 ip_rput(queue_t *q, mblk_t *mp)
14911 {
14912 	ill_t		*ill = (ill_t *)q->q_ptr;
14913 	ip_stack_t	*ipst = ill->ill_ipst;
14914 	union DL_primitives *dl;
14915 
14916 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14917 
14918 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14919 		/*
14920 		 * If things are opening or closing, only accept high-priority
14921 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14922 		 * created; on close, things hanging off the ill may have been
14923 		 * freed already.)
14924 		 */
14925 		dl = (union DL_primitives *)mp->b_rptr;
14926 		if (DB_TYPE(mp) != M_PCPROTO ||
14927 		    dl->dl_primitive == DL_UNITDATA_IND) {
14928 			/*
14929 			 * SIOC[GS]TUNPARAM ioctls can come here.
14930 			 */
14931 			inet_freemsg(mp);
14932 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14933 			    "ip_rput_end: q %p (%S)", q, "uninit");
14934 			return;
14935 		}
14936 	}
14937 
14938 	/*
14939 	 * if db_ref > 1 then copymsg and free original. Packet may be
14940 	 * changed and we do not want the other entity who has a reference to
14941 	 * this message to trip over the changes. This is a blind change because
14942 	 * trying to catch all places that might change the packet is too
14943 	 * difficult.
14944 	 *
14945 	 * This corresponds to the fast path case, where we have a chain of
14946 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14947 	 * in the mblk chain. There doesn't seem to be a reason why a device
14948 	 * driver would send up data with varying db_ref counts in the mblk
14949 	 * chain. In any case the Fast path is a private interface, and our
14950 	 * drivers don't do such a thing. Given the above assumption, there is
14951 	 * no need to walk down the entire mblk chain (which could have a
14952 	 * potential performance problem)
14953 	 */
14954 	if (mp->b_datap->db_ref > 1) {
14955 		mblk_t  *mp1;
14956 		boolean_t adjusted = B_FALSE;
14957 		IP_STAT(ipst, ip_db_ref);
14958 
14959 		/*
14960 		 * The IP_RECVSLLA option depends on having the link layer
14961 		 * header. First check that:
14962 		 * a> the underlying device is of type ether, since this
14963 		 * option is currently supported only over ethernet.
14964 		 * b> there is enough room to copy over the link layer header.
14965 		 *
14966 		 * Once the checks are done, adjust rptr so that the link layer
14967 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14968 		 * be returned by some non-ethernet drivers but in this case the
14969 		 * second check will fail.
14970 		 */
14971 		if (ill->ill_type == IFT_ETHER &&
14972 		    (mp->b_rptr - mp->b_datap->db_base) >=
14973 		    sizeof (struct ether_header)) {
14974 			mp->b_rptr -= sizeof (struct ether_header);
14975 			adjusted = B_TRUE;
14976 		}
14977 		mp1 = copymsg(mp);
14978 		if (mp1 == NULL) {
14979 			mp->b_next = NULL;
14980 			/* clear b_prev - used by ip_mroute_decap */
14981 			mp->b_prev = NULL;
14982 			freemsg(mp);
14983 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14984 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14985 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14986 			return;
14987 		}
14988 		if (adjusted) {
14989 			/*
14990 			 * Copy is done. Restore the pointer in the _new_ mblk
14991 			 */
14992 			mp1->b_rptr += sizeof (struct ether_header);
14993 		}
14994 		/* Copy b_prev - used by ip_mroute_decap */
14995 		mp1->b_prev = mp->b_prev;
14996 		mp->b_prev = NULL;
14997 		freemsg(mp);
14998 		mp = mp1;
14999 	}
15000 
15001 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15002 	    "ip_rput_end: q %p (%S)", q, "end");
15003 
15004 	ip_input(ill, NULL, mp, NULL);
15005 }
15006 
15007 /*
15008  * Direct read side procedure capable of dealing with chains. GLDv3 based
15009  * drivers call this function directly with mblk chains while STREAMS
15010  * read side procedure ip_rput() calls this for single packet with ip_ring
15011  * set to NULL to process one packet at a time.
15012  *
15013  * The ill will always be valid if this function is called directly from
15014  * the driver.
15015  *
15016  * If ip_input() is called from GLDv3:
15017  *
15018  *   - This must be a non-VLAN IP stream.
15019  *   - 'mp' is either an untagged or a special priority-tagged packet.
15020  *   - Any VLAN tag that was in the MAC header has been stripped.
15021  *
15022  * If the IP header in packet is not 32-bit aligned, every message in the
15023  * chain will be aligned before further operations. This is required on SPARC
15024  * platform.
15025  */
15026 /* ARGSUSED */
15027 void
15028 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
15029     struct mac_header_info_s *mhip)
15030 {
15031 	ipaddr_t		dst = NULL;
15032 	ipaddr_t		prev_dst;
15033 	ire_t			*ire = NULL;
15034 	ipha_t			*ipha;
15035 	uint_t			pkt_len;
15036 	ssize_t			len;
15037 	uint_t			opt_len;
15038 	int			ll_multicast;
15039 	int			cgtp_flt_pkt;
15040 	queue_t			*q = ill->ill_rq;
15041 	squeue_t		*curr_sqp = NULL;
15042 	mblk_t 			*head = NULL;
15043 	mblk_t			*tail = NULL;
15044 	mblk_t			*first_mp;
15045 	mblk_t 			*mp;
15046 	mblk_t			*dmp;
15047 	int			cnt = 0;
15048 	ip_stack_t		*ipst = ill->ill_ipst;
15049 
15050 	ASSERT(mp_chain != NULL);
15051 	ASSERT(ill != NULL);
15052 
15053 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15054 
15055 #define	rptr	((uchar_t *)ipha)
15056 
15057 	while (mp_chain != NULL) {
15058 		first_mp = mp = mp_chain;
15059 		mp_chain = mp_chain->b_next;
15060 		mp->b_next = NULL;
15061 		ll_multicast = 0;
15062 
15063 		/*
15064 		 * We do ire caching from one iteration to
15065 		 * another. In the event the packet chain contains
15066 		 * all packets from the same dst, this caching saves
15067 		 * an ire_cache_lookup for each of the succeeding
15068 		 * packets in a packet chain.
15069 		 */
15070 		prev_dst = dst;
15071 
15072 		/*
15073 		 * Check and align the IP header.
15074 		 */
15075 		if (DB_TYPE(mp) == M_DATA) {
15076 			dmp = mp;
15077 		} else if (DB_TYPE(mp) == M_PROTO &&
15078 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15079 			dmp = mp->b_cont;
15080 		} else {
15081 			dmp = NULL;
15082 		}
15083 		if (dmp != NULL) {
15084 			/*
15085 			 * IP header ptr not aligned?
15086 			 * OR IP header not complete in first mblk
15087 			 */
15088 			if (!OK_32PTR(dmp->b_rptr) ||
15089 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15090 				if (!ip_check_and_align_header(q, dmp, ipst))
15091 					continue;
15092 			}
15093 		}
15094 
15095 		/*
15096 		 * ip_input fast path
15097 		 */
15098 
15099 		/* mblk type is not M_DATA */
15100 		if (DB_TYPE(mp) != M_DATA) {
15101 			if (ip_rput_process_notdata(q, &first_mp, ill,
15102 			    &ll_multicast, &mp))
15103 				continue;
15104 		}
15105 
15106 		/* Make sure its an M_DATA and that its aligned */
15107 		ASSERT(DB_TYPE(mp) == M_DATA);
15108 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15109 
15110 		ipha = (ipha_t *)mp->b_rptr;
15111 		len = mp->b_wptr - rptr;
15112 		pkt_len = ntohs(ipha->ipha_length);
15113 
15114 		/*
15115 		 * We must count all incoming packets, even if they end
15116 		 * up being dropped later on.
15117 		 */
15118 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15119 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15120 
15121 		/* multiple mblk or too short */
15122 		len -= pkt_len;
15123 		if (len != 0) {
15124 			/*
15125 			 * Make sure we have data length consistent
15126 			 * with the IP header.
15127 			 */
15128 			if (mp->b_cont == NULL) {
15129 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15130 					BUMP_MIB(ill->ill_ip_mib,
15131 					    ipIfStatsInHdrErrors);
15132 					ip2dbg(("ip_input: drop pkt\n"));
15133 					freemsg(mp);
15134 					continue;
15135 				}
15136 				mp->b_wptr = rptr + pkt_len;
15137 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
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 				(void) adjmsg(mp, -len);
15146 				IP_STAT(ipst, ip_multimblk3);
15147 			}
15148 		}
15149 
15150 		/* Obtain the dst of the current packet */
15151 		dst = ipha->ipha_dst;
15152 
15153 		if (IP_LOOPBACK_ADDR(dst) ||
15154 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15155 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15156 			cmn_err(CE_CONT, "dst %X src %X\n",
15157 			    dst, ipha->ipha_src);
15158 			freemsg(mp);
15159 			continue;
15160 		}
15161 
15162 		/*
15163 		 * The event for packets being received from a 'physical'
15164 		 * interface is placed after validation of the source and/or
15165 		 * destination address as being local so that packets can be
15166 		 * redirected to loopback addresses using ipnat.
15167 		 */
15168 		DTRACE_PROBE4(ip4__physical__in__start,
15169 		    ill_t *, ill, ill_t *, NULL,
15170 		    ipha_t *, ipha, mblk_t *, first_mp);
15171 
15172 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15173 		    ipst->ips_ipv4firewall_physical_in,
15174 		    ill, NULL, ipha, first_mp, mp, ipst);
15175 
15176 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15177 
15178 		if (first_mp == NULL) {
15179 			continue;
15180 		}
15181 		dst = ipha->ipha_dst;
15182 
15183 		/*
15184 		 * Attach any necessary label information to
15185 		 * this packet
15186 		 */
15187 		if (is_system_labeled() &&
15188 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15189 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15190 			freemsg(mp);
15191 			continue;
15192 		}
15193 
15194 		/*
15195 		 * Reuse the cached ire only if the ipha_dst of the previous
15196 		 * packet is the same as the current packet AND it is not
15197 		 * INADDR_ANY.
15198 		 */
15199 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15200 		    (ire != NULL)) {
15201 			ire_refrele(ire);
15202 			ire = NULL;
15203 		}
15204 		opt_len = ipha->ipha_version_and_hdr_length -
15205 		    IP_SIMPLE_HDR_VERSION;
15206 
15207 		/*
15208 		 * Check to see if we can take the fastpath.
15209 		 * That is possible if the following conditions are met
15210 		 *	o Tsol disabled
15211 		 *	o CGTP disabled
15212 		 *	o ipp_action_count is 0
15213 		 *	o Mobile IP not running
15214 		 *	o no options in the packet
15215 		 *	o not a RSVP packet
15216 		 * 	o not a multicast packet
15217 		 */
15218 		if (!is_system_labeled() &&
15219 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15220 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15221 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15222 		    !ll_multicast && !CLASSD(dst)) {
15223 			if (ire == NULL)
15224 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15225 				    ipst);
15226 
15227 			/* incoming packet is for forwarding */
15228 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15229 				ire = ip_fast_forward(ire, dst, ill, mp);
15230 				continue;
15231 			}
15232 			/* incoming packet is for local consumption */
15233 			if (ire->ire_type & IRE_LOCAL)
15234 				goto local;
15235 		}
15236 
15237 		/*
15238 		 * Disable ire caching for anything more complex
15239 		 * than the simple fast path case we checked for above.
15240 		 */
15241 		if (ire != NULL) {
15242 			ire_refrele(ire);
15243 			ire = NULL;
15244 		}
15245 
15246 		/* Full-blown slow path */
15247 		if (opt_len != 0) {
15248 			if (len != 0)
15249 				IP_STAT(ipst, ip_multimblk4);
15250 			else
15251 				IP_STAT(ipst, ip_ipoptions);
15252 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15253 			    &dst, ipst))
15254 				continue;
15255 		}
15256 
15257 		/*
15258 		 * Invoke the CGTP (multirouting) filtering module to process
15259 		 * the incoming packet. Packets identified as duplicates
15260 		 * must be discarded. Filtering is active only if the
15261 		 * the ip_cgtp_filter ndd variable is non-zero.
15262 		 *
15263 		 * Only applies to the shared stack since the filter_ops
15264 		 * do not carry an ip_stack_t or zoneid.
15265 		 */
15266 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15267 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15268 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15269 			cgtp_flt_pkt =
15270 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15271 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15272 				freemsg(first_mp);
15273 				continue;
15274 			}
15275 		}
15276 
15277 		/*
15278 		 * If rsvpd is running, let RSVP daemon handle its processing
15279 		 * and forwarding of RSVP multicast/unicast packets.
15280 		 * If rsvpd is not running but mrouted is running, RSVP
15281 		 * multicast packets are forwarded as multicast traffic
15282 		 * and RSVP unicast packets are forwarded by unicast router.
15283 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15284 		 * packets are not forwarded, but the unicast packets are
15285 		 * forwarded like unicast traffic.
15286 		 */
15287 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15288 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15289 		    NULL) {
15290 			/* RSVP packet and rsvpd running. Treat as ours */
15291 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15292 			/*
15293 			 * This assumes that we deliver to all streams for
15294 			 * multicast and broadcast packets.
15295 			 * We have to force ll_multicast to 1 to handle the
15296 			 * M_DATA messages passed in from ip_mroute_decap.
15297 			 */
15298 			dst = INADDR_BROADCAST;
15299 			ll_multicast = 1;
15300 		} else if (CLASSD(dst)) {
15301 			/* packet is multicast */
15302 			mp->b_next = NULL;
15303 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15304 			    &ll_multicast, &dst))
15305 				continue;
15306 		}
15307 
15308 
15309 		/*
15310 		 * Check if the packet is coming from the Mobile IP
15311 		 * forward tunnel interface
15312 		 */
15313 		if (ill->ill_srcif_refcnt > 0) {
15314 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15315 			    NULL, ill, MATCH_IRE_TYPE);
15316 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15317 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15318 
15319 				/* We need to resolve the link layer info */
15320 				ire_refrele(ire);
15321 				ire = NULL;
15322 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15323 				    ll_multicast, dst);
15324 				continue;
15325 			}
15326 		}
15327 
15328 		if (ire == NULL) {
15329 			ire = ire_cache_lookup(dst, ALL_ZONES,
15330 			    MBLK_GETLABEL(mp), ipst);
15331 		}
15332 
15333 		/*
15334 		 * If mipagent is running and reverse tunnel is created as per
15335 		 * mobile node request, then any packet coming through the
15336 		 * incoming interface from the mobile-node, should be reverse
15337 		 * tunneled to it's home agent except those that are destined
15338 		 * to foreign agent only.
15339 		 * This needs source address based ire lookup. The routing
15340 		 * entries for source address based lookup are only created by
15341 		 * mipagent program only when a reverse tunnel is created.
15342 		 * Reference : RFC2002, RFC2344
15343 		 */
15344 		if (ill->ill_mrtun_refcnt > 0) {
15345 			ipaddr_t	srcaddr;
15346 			ire_t		*tmp_ire;
15347 
15348 			tmp_ire = ire;	/* Save, we might need it later */
15349 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15350 			    ire->ire_type != IRE_BROADCAST)) {
15351 				srcaddr = ipha->ipha_src;
15352 				ire = ire_mrtun_lookup(srcaddr, ill);
15353 				if (ire != NULL) {
15354 					/*
15355 					 * Should not be getting iphada packet
15356 					 * here. we should only get those for
15357 					 * IRE_LOCAL traffic, excluded above.
15358 					 * Fail-safe (drop packet) in the event
15359 					 * hardware is misbehaving.
15360 					 */
15361 					if (first_mp != mp) {
15362 						/* IPsec KSTATS: beancount me */
15363 						freemsg(first_mp);
15364 					} else {
15365 						/*
15366 						 * This packet must be forwarded
15367 						 * to Reverse Tunnel
15368 						 */
15369 						ip_mrtun_forward(ire, ill, mp);
15370 					}
15371 					ire_refrele(ire);
15372 					ire = NULL;
15373 					if (tmp_ire != NULL) {
15374 						ire_refrele(tmp_ire);
15375 						tmp_ire = NULL;
15376 					}
15377 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15378 					    "ip_input_end: q %p (%S)",
15379 					    q, "uninit");
15380 					continue;
15381 				}
15382 			}
15383 			/*
15384 			 * If this packet is from a non-mobilenode  or a
15385 			 * mobile-node which does not request reverse
15386 			 * tunnel service
15387 			 */
15388 			ire = tmp_ire;
15389 		}
15390 
15391 
15392 		/*
15393 		 * If we reach here that means the incoming packet satisfies
15394 		 * one of the following conditions:
15395 		 *   - packet is from a mobile node which does not request
15396 		 *	reverse tunnel
15397 		 *   - packet is from a non-mobile node, which is the most
15398 		 *	common case
15399 		 *   - packet is from a reverse tunnel enabled mobile node
15400 		 *	and destined to foreign agent only
15401 		 */
15402 
15403 		if (ire == NULL) {
15404 			/*
15405 			 * No IRE for this destination, so it can't be for us.
15406 			 * Unless we are forwarding, drop the packet.
15407 			 * We have to let source routed packets through
15408 			 * since we don't yet know if they are 'ping -l'
15409 			 * packets i.e. if they will go out over the
15410 			 * same interface as they came in on.
15411 			 */
15412 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15413 			if (ire == NULL)
15414 				continue;
15415 		}
15416 
15417 		/*
15418 		 * Broadcast IRE may indicate either broadcast or
15419 		 * multicast packet
15420 		 */
15421 		if (ire->ire_type == IRE_BROADCAST) {
15422 			/*
15423 			 * Skip broadcast checks if packet is UDP multicast;
15424 			 * we'd rather not enter ip_rput_process_broadcast()
15425 			 * unless the packet is broadcast for real, since
15426 			 * that routine is a no-op for multicast.
15427 			 */
15428 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15429 			    !CLASSD(ipha->ipha_dst)) {
15430 				ire = ip_rput_process_broadcast(&q, mp,
15431 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15432 				    ll_multicast);
15433 				if (ire == NULL)
15434 					continue;
15435 			}
15436 		} else if (ire->ire_stq != NULL) {
15437 			/* fowarding? */
15438 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15439 			    ll_multicast);
15440 			/* ip_rput_process_forward consumed the packet */
15441 			continue;
15442 		}
15443 
15444 local:
15445 		/*
15446 		 * If the queue in the ire is different to the ingress queue
15447 		 * then we need to check to see if we can accept the packet.
15448 		 * Note that for multicast packets and broadcast packets sent
15449 		 * to a broadcast address which is shared between multiple
15450 		 * interfaces we should not do this since we just got a random
15451 		 * broadcast ire.
15452 		 */
15453 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15454 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15455 			    ill)) == NULL) {
15456 				/* Drop packet */
15457 				BUMP_MIB(ill->ill_ip_mib,
15458 				    ipIfStatsForwProhibits);
15459 				freemsg(mp);
15460 				continue;
15461 			}
15462 			if (ire->ire_rfq != NULL)
15463 				q = ire->ire_rfq;
15464 		}
15465 
15466 		switch (ipha->ipha_protocol) {
15467 		case IPPROTO_TCP:
15468 			ASSERT(first_mp == mp);
15469 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15470 			    mp, 0, q, ip_ring)) != NULL) {
15471 				if (curr_sqp == NULL) {
15472 					curr_sqp = GET_SQUEUE(mp);
15473 					ASSERT(cnt == 0);
15474 					cnt++;
15475 					head = tail = mp;
15476 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15477 					ASSERT(tail != NULL);
15478 					cnt++;
15479 					tail->b_next = mp;
15480 					tail = mp;
15481 				} else {
15482 					/*
15483 					 * A different squeue. Send the
15484 					 * chain for the previous squeue on
15485 					 * its way. This shouldn't happen
15486 					 * often unless interrupt binding
15487 					 * changes.
15488 					 */
15489 					IP_STAT(ipst, ip_input_multi_squeue);
15490 					squeue_enter_chain(curr_sqp, head,
15491 					    tail, cnt, SQTAG_IP_INPUT);
15492 					curr_sqp = GET_SQUEUE(mp);
15493 					head = mp;
15494 					tail = mp;
15495 					cnt = 1;
15496 				}
15497 			}
15498 			continue;
15499 		case IPPROTO_UDP:
15500 			ASSERT(first_mp == mp);
15501 			ip_udp_input(q, mp, ipha, ire, ill);
15502 			continue;
15503 		case IPPROTO_SCTP:
15504 			ASSERT(first_mp == mp);
15505 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15506 			    q, dst);
15507 			/* ire has been released by ip_sctp_input */
15508 			ire = NULL;
15509 			continue;
15510 		default:
15511 			ip_proto_input(q, first_mp, ipha, ire, ill);
15512 			continue;
15513 		}
15514 	}
15515 
15516 	if (ire != NULL)
15517 		ire_refrele(ire);
15518 
15519 	if (head != NULL)
15520 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15521 
15522 	/*
15523 	 * This code is there just to make netperf/ttcp look good.
15524 	 *
15525 	 * Its possible that after being in polling mode (and having cleared
15526 	 * the backlog), squeues have turned the interrupt frequency higher
15527 	 * to improve latency at the expense of more CPU utilization (less
15528 	 * packets per interrupts or more number of interrupts). Workloads
15529 	 * like ttcp/netperf do manage to tickle polling once in a while
15530 	 * but for the remaining time, stay in higher interrupt mode since
15531 	 * their packet arrival rate is pretty uniform and this shows up
15532 	 * as higher CPU utilization. Since people care about CPU utilization
15533 	 * while running netperf/ttcp, turn the interrupt frequency back to
15534 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15535 	 */
15536 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15537 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15538 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15539 			ip_ring->rr_blank(ip_ring->rr_handle,
15540 			    ip_ring->rr_normal_blank_time,
15541 			    ip_ring->rr_normal_pkt_cnt);
15542 		}
15543 		}
15544 
15545 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15546 	    "ip_input_end: q %p (%S)", q, "end");
15547 #undef  rptr
15548 }
15549 
15550 static void
15551 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15552     t_uscalar_t err)
15553 {
15554 	if (dl_err == DL_SYSERR) {
15555 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15556 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15557 		    ill->ill_name, dlpi_prim_str(prim), err);
15558 		return;
15559 	}
15560 
15561 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15562 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15563 	    dlpi_err_str(dl_err));
15564 }
15565 
15566 /*
15567  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15568  * than DL_UNITDATA_IND messages. If we need to process this message
15569  * exclusively, we call qwriter_ip, in which case we also need to call
15570  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15571  */
15572 void
15573 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15574 {
15575 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15576 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15577 	ill_t		*ill = (ill_t *)q->q_ptr;
15578 	boolean_t	pending;
15579 
15580 	ip1dbg(("ip_rput_dlpi"));
15581 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15582 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15583 		    "%s (0x%x), unix %u\n", ill->ill_name,
15584 		    dlpi_prim_str(dlea->dl_error_primitive),
15585 		    dlea->dl_error_primitive,
15586 		    dlpi_err_str(dlea->dl_errno),
15587 		    dlea->dl_errno,
15588 		    dlea->dl_unix_errno));
15589 	}
15590 
15591 	/*
15592 	 * If we received an ACK but didn't send a request for it, then it
15593 	 * can't be part of any pending operation; discard up-front.
15594 	 */
15595 	switch (dloa->dl_primitive) {
15596 	case DL_NOTIFY_IND:
15597 		pending = B_TRUE;
15598 		break;
15599 	case DL_ERROR_ACK:
15600 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15601 		break;
15602 	case DL_OK_ACK:
15603 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15604 		break;
15605 	case DL_INFO_ACK:
15606 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15607 		break;
15608 	case DL_BIND_ACK:
15609 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15610 		break;
15611 	case DL_PHYS_ADDR_ACK:
15612 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15613 		break;
15614 	case DL_NOTIFY_ACK:
15615 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15616 		break;
15617 	case DL_CONTROL_ACK:
15618 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15619 		break;
15620 	case DL_CAPABILITY_ACK:
15621 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15622 		break;
15623 	default:
15624 		/* Not a DLPI message we support or were expecting */
15625 		freemsg(mp);
15626 		return;
15627 	}
15628 
15629 	if (!pending) {
15630 		freemsg(mp);
15631 		return;
15632 	}
15633 
15634 	switch (dloa->dl_primitive) {
15635 	case DL_ERROR_ACK:
15636 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15637 			mutex_enter(&ill->ill_lock);
15638 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15639 			cv_signal(&ill->ill_cv);
15640 			mutex_exit(&ill->ill_lock);
15641 		}
15642 		break;
15643 
15644 	case DL_OK_ACK:
15645 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15646 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15647 		switch (dloa->dl_correct_primitive) {
15648 		case DL_UNBIND_REQ:
15649 			mutex_enter(&ill->ill_lock);
15650 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15651 			cv_signal(&ill->ill_cv);
15652 			mutex_exit(&ill->ill_lock);
15653 			break;
15654 
15655 		case DL_ENABMULTI_REQ:
15656 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15657 				ill->ill_dlpi_multicast_state = IDS_OK;
15658 			break;
15659 		}
15660 		break;
15661 	default:
15662 		break;
15663 	}
15664 
15665 	/*
15666 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15667 	 * and we need to become writer to continue to process it. If it's not
15668 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15669 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15670 	 * some work as part of the current exclusive operation that actually
15671 	 * is not part of it -- which is wrong, but better than the
15672 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15673 	 * should track which DLPI requests have ACKs that we wait on
15674 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15675 	 *
15676 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15677 	 * Since this is on the ill stream we unconditionally bump up the
15678 	 * refcount without doing ILL_CAN_LOOKUP().
15679 	 */
15680 	ill_refhold(ill);
15681 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15682 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15683 	else
15684 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15685 }
15686 
15687 /*
15688  * Handling of DLPI messages that require exclusive access to the ipsq.
15689  *
15690  * Need to do ill_pending_mp_release on ioctl completion, which could
15691  * happen here. (along with mi_copy_done)
15692  */
15693 /* ARGSUSED */
15694 static void
15695 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15696 {
15697 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15698 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15699 	int		err = 0;
15700 	ill_t		*ill;
15701 	ipif_t		*ipif = NULL;
15702 	mblk_t		*mp1 = NULL;
15703 	conn_t		*connp = NULL;
15704 	t_uscalar_t	paddrreq;
15705 	mblk_t		*mp_hw;
15706 	boolean_t	success;
15707 	boolean_t	ioctl_aborted = B_FALSE;
15708 	boolean_t	log = B_TRUE;
15709 	hook_nic_event_t	*info;
15710 	ip_stack_t		*ipst;
15711 
15712 	ip1dbg(("ip_rput_dlpi_writer .."));
15713 	ill = (ill_t *)q->q_ptr;
15714 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15715 
15716 	ASSERT(IAM_WRITER_ILL(ill));
15717 
15718 	ipst = ill->ill_ipst;
15719 
15720 	/*
15721 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15722 	 * both are null or non-null. However we can assert that only
15723 	 * after grabbing the ipsq_lock. So we don't make any assertion
15724 	 * here and in other places in the code.
15725 	 */
15726 	ipif = ipsq->ipsq_pending_ipif;
15727 	/*
15728 	 * The current ioctl could have been aborted by the user and a new
15729 	 * ioctl to bring up another ill could have started. We could still
15730 	 * get a response from the driver later.
15731 	 */
15732 	if (ipif != NULL && ipif->ipif_ill != ill)
15733 		ioctl_aborted = B_TRUE;
15734 
15735 	switch (dloa->dl_primitive) {
15736 	case DL_ERROR_ACK:
15737 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15738 		    dlpi_prim_str(dlea->dl_error_primitive)));
15739 
15740 		switch (dlea->dl_error_primitive) {
15741 		case DL_PROMISCON_REQ:
15742 		case DL_PROMISCOFF_REQ:
15743 		case DL_DISABMULTI_REQ:
15744 		case DL_UNBIND_REQ:
15745 		case DL_ATTACH_REQ:
15746 		case DL_INFO_REQ:
15747 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15748 			break;
15749 		case DL_NOTIFY_REQ:
15750 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15751 			log = B_FALSE;
15752 			break;
15753 		case DL_PHYS_ADDR_REQ:
15754 			/*
15755 			 * For IPv6 only, there are two additional
15756 			 * phys_addr_req's sent to the driver to get the
15757 			 * IPv6 token and lla. This allows IP to acquire
15758 			 * the hardware address format for a given interface
15759 			 * without having built in knowledge of the hardware
15760 			 * address. ill_phys_addr_pend keeps track of the last
15761 			 * DL_PAR sent so we know which response we are
15762 			 * dealing with. ill_dlpi_done will update
15763 			 * ill_phys_addr_pend when it sends the next req.
15764 			 * We don't complete the IOCTL until all three DL_PARs
15765 			 * have been attempted, so set *_len to 0 and break.
15766 			 */
15767 			paddrreq = ill->ill_phys_addr_pend;
15768 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15769 			if (paddrreq == DL_IPV6_TOKEN) {
15770 				ill->ill_token_length = 0;
15771 				log = B_FALSE;
15772 				break;
15773 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15774 				ill->ill_nd_lla_len = 0;
15775 				log = B_FALSE;
15776 				break;
15777 			}
15778 			/*
15779 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15780 			 * We presumably have an IOCTL hanging out waiting
15781 			 * for completion. Find it and complete the IOCTL
15782 			 * with the error noted.
15783 			 * However, ill_dl_phys was called on an ill queue
15784 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15785 			 * set. But the ioctl is known to be pending on ill_wq.
15786 			 */
15787 			if (!ill->ill_ifname_pending)
15788 				break;
15789 			ill->ill_ifname_pending = 0;
15790 			if (!ioctl_aborted)
15791 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15792 			if (mp1 != NULL) {
15793 				/*
15794 				 * This operation (SIOCSLIFNAME) must have
15795 				 * happened on the ill. Assert there is no conn
15796 				 */
15797 				ASSERT(connp == NULL);
15798 				q = ill->ill_wq;
15799 			}
15800 			break;
15801 		case DL_BIND_REQ:
15802 			ill_dlpi_done(ill, DL_BIND_REQ);
15803 			if (ill->ill_ifname_pending)
15804 				break;
15805 			/*
15806 			 * Something went wrong with the bind.  We presumably
15807 			 * have an IOCTL hanging out waiting for completion.
15808 			 * Find it, take down the interface that was coming
15809 			 * up, and complete the IOCTL with the error noted.
15810 			 */
15811 			if (!ioctl_aborted)
15812 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15813 			if (mp1 != NULL) {
15814 				/*
15815 				 * This operation (SIOCSLIFFLAGS) must have
15816 				 * happened from a conn.
15817 				 */
15818 				ASSERT(connp != NULL);
15819 				q = CONNP_TO_WQ(connp);
15820 				if (ill->ill_move_in_progress) {
15821 					ILL_CLEAR_MOVE(ill);
15822 				}
15823 				(void) ipif_down(ipif, NULL, NULL);
15824 				/* error is set below the switch */
15825 			}
15826 			break;
15827 		case DL_ENABMULTI_REQ:
15828 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15829 
15830 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15831 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15832 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15833 				ipif_t *ipif;
15834 
15835 				printf("ip: joining multicasts failed (%d)"
15836 				    " on %s - will use link layer "
15837 				    "broadcasts for multicast\n",
15838 				    dlea->dl_errno, ill->ill_name);
15839 
15840 				/*
15841 				 * Set up the multicast mapping alone.
15842 				 * writer, so ok to access ill->ill_ipif
15843 				 * without any lock.
15844 				 */
15845 				ipif = ill->ill_ipif;
15846 				mutex_enter(&ill->ill_phyint->phyint_lock);
15847 				ill->ill_phyint->phyint_flags |=
15848 				    PHYI_MULTI_BCAST;
15849 				mutex_exit(&ill->ill_phyint->phyint_lock);
15850 
15851 				if (!ill->ill_isv6) {
15852 					(void) ipif_arp_setup_multicast(ipif,
15853 					    NULL);
15854 				} else {
15855 					(void) ipif_ndp_setup_multicast(ipif,
15856 					    NULL);
15857 				}
15858 			}
15859 			freemsg(mp);	/* Don't want to pass this up */
15860 			return;
15861 
15862 		case DL_CAPABILITY_REQ:
15863 		case DL_CONTROL_REQ:
15864 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15865 			ill->ill_dlpi_capab_state = IDS_FAILED;
15866 			freemsg(mp);
15867 			return;
15868 		}
15869 		/*
15870 		 * Note the error for IOCTL completion (mp1 is set when
15871 		 * ready to complete ioctl). If ill_ifname_pending_err is
15872 		 * set, an error occured during plumbing (ill_ifname_pending),
15873 		 * so we want to report that error.
15874 		 *
15875 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15876 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15877 		 * expected to get errack'd if the driver doesn't support
15878 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15879 		 * if these error conditions are encountered.
15880 		 */
15881 		if (mp1 != NULL) {
15882 			if (ill->ill_ifname_pending_err != 0)  {
15883 				err = ill->ill_ifname_pending_err;
15884 				ill->ill_ifname_pending_err = 0;
15885 			} else {
15886 				err = dlea->dl_unix_errno ?
15887 				    dlea->dl_unix_errno : ENXIO;
15888 			}
15889 		/*
15890 		 * If we're plumbing an interface and an error hasn't already
15891 		 * been saved, set ill_ifname_pending_err to the error passed
15892 		 * up. Ignore the error if log is B_FALSE (see comment above).
15893 		 */
15894 		} else if (log && ill->ill_ifname_pending &&
15895 		    ill->ill_ifname_pending_err == 0) {
15896 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15897 			    dlea->dl_unix_errno : ENXIO;
15898 		}
15899 
15900 		if (log)
15901 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15902 			    dlea->dl_errno, dlea->dl_unix_errno);
15903 		break;
15904 	case DL_CAPABILITY_ACK: {
15905 		boolean_t reneg_flag = B_FALSE;
15906 		/* Call a routine to handle this one. */
15907 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15908 		/*
15909 		 * Check if the ACK is due to renegotiation case since we
15910 		 * will need to send a new CAPABILITY_REQ later.
15911 		 */
15912 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15913 			/* This is the ack for a renogiation case */
15914 			reneg_flag = B_TRUE;
15915 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15916 		}
15917 		ill_capability_ack(ill, mp);
15918 		if (reneg_flag)
15919 			ill_capability_probe(ill);
15920 		break;
15921 	}
15922 	case DL_CONTROL_ACK:
15923 		/* We treat all of these as "fire and forget" */
15924 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15925 		break;
15926 	case DL_INFO_ACK:
15927 		/* Call a routine to handle this one. */
15928 		ill_dlpi_done(ill, DL_INFO_REQ);
15929 		ip_ll_subnet_defaults(ill, mp);
15930 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15931 		return;
15932 	case DL_BIND_ACK:
15933 		/*
15934 		 * We should have an IOCTL waiting on this unless
15935 		 * sent by ill_dl_phys, in which case just return
15936 		 */
15937 		ill_dlpi_done(ill, DL_BIND_REQ);
15938 		if (ill->ill_ifname_pending)
15939 			break;
15940 
15941 		if (!ioctl_aborted)
15942 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15943 		if (mp1 == NULL)
15944 			break;
15945 		/*
15946 		 * Because mp1 was added by ill_dl_up(), and it always
15947 		 * passes a valid connp, connp must be valid here.
15948 		 */
15949 		ASSERT(connp != NULL);
15950 		q = CONNP_TO_WQ(connp);
15951 
15952 		/*
15953 		 * We are exclusive. So nothing can change even after
15954 		 * we get the pending mp. If need be we can put it back
15955 		 * and restart, as in calling ipif_arp_up()  below.
15956 		 */
15957 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15958 
15959 		mutex_enter(&ill->ill_lock);
15960 
15961 		ill->ill_dl_up = 1;
15962 
15963 		if ((info = ill->ill_nic_event_info) != NULL) {
15964 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15965 			    "attached for %s\n", info->hne_event,
15966 			    ill->ill_name));
15967 			if (info->hne_data != NULL)
15968 				kmem_free(info->hne_data, info->hne_datalen);
15969 			kmem_free(info, sizeof (hook_nic_event_t));
15970 		}
15971 
15972 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15973 		if (info != NULL) {
15974 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15975 			info->hne_lif = 0;
15976 			info->hne_event = NE_UP;
15977 			info->hne_data = NULL;
15978 			info->hne_datalen = 0;
15979 			info->hne_family = ill->ill_isv6 ?
15980 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15981 		} else
15982 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15983 			    "event information for %s (ENOMEM)\n",
15984 			    ill->ill_name));
15985 
15986 		ill->ill_nic_event_info = info;
15987 
15988 		mutex_exit(&ill->ill_lock);
15989 
15990 		/*
15991 		 * Now bring up the resolver; when that is complete, we'll
15992 		 * create IREs.  Note that we intentionally mirror what
15993 		 * ipif_up() would have done, because we got here by way of
15994 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15995 		 */
15996 		if (ill->ill_isv6) {
15997 			/*
15998 			 * v6 interfaces.
15999 			 * Unlike ARP which has to do another bind
16000 			 * and attach, once we get here we are
16001 			 * done with NDP. Except in the case of
16002 			 * ILLF_XRESOLV, in which case we send an
16003 			 * AR_INTERFACE_UP to the external resolver.
16004 			 * If all goes well, the ioctl will complete
16005 			 * in ip_rput(). If there's an error, we
16006 			 * complete it here.
16007 			 */
16008 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
16009 			if (err == 0) {
16010 				if (ill->ill_flags & ILLF_XRESOLV) {
16011 					mutex_enter(&connp->conn_lock);
16012 					mutex_enter(&ill->ill_lock);
16013 					success = ipsq_pending_mp_add(
16014 					    connp, ipif, q, mp1, 0);
16015 					mutex_exit(&ill->ill_lock);
16016 					mutex_exit(&connp->conn_lock);
16017 					if (success) {
16018 						err = ipif_resolver_up(ipif,
16019 						    Res_act_initial);
16020 						if (err == EINPROGRESS) {
16021 							freemsg(mp);
16022 							return;
16023 						}
16024 						ASSERT(err != 0);
16025 						mp1 = ipsq_pending_mp_get(ipsq,
16026 						    &connp);
16027 						ASSERT(mp1 != NULL);
16028 					} else {
16029 						/* conn has started closing */
16030 						err = EINTR;
16031 					}
16032 				} else { /* Non XRESOLV interface */
16033 					(void) ipif_resolver_up(ipif,
16034 					    Res_act_initial);
16035 					err = ipif_up_done_v6(ipif);
16036 				}
16037 			}
16038 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16039 			/*
16040 			 * ARP and other v4 external resolvers.
16041 			 * Leave the pending mblk intact so that
16042 			 * the ioctl completes in ip_rput().
16043 			 */
16044 			mutex_enter(&connp->conn_lock);
16045 			mutex_enter(&ill->ill_lock);
16046 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16047 			mutex_exit(&ill->ill_lock);
16048 			mutex_exit(&connp->conn_lock);
16049 			if (success) {
16050 				err = ipif_resolver_up(ipif, Res_act_initial);
16051 				if (err == EINPROGRESS) {
16052 					freemsg(mp);
16053 					return;
16054 				}
16055 				ASSERT(err != 0);
16056 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16057 			} else {
16058 				/* The conn has started closing */
16059 				err = EINTR;
16060 			}
16061 		} else {
16062 			/*
16063 			 * This one is complete. Reply to pending ioctl.
16064 			 */
16065 			(void) ipif_resolver_up(ipif, Res_act_initial);
16066 			err = ipif_up_done(ipif);
16067 		}
16068 
16069 		if ((err == 0) && (ill->ill_up_ipifs)) {
16070 			err = ill_up_ipifs(ill, q, mp1);
16071 			if (err == EINPROGRESS) {
16072 				freemsg(mp);
16073 				return;
16074 			}
16075 		}
16076 
16077 		if (ill->ill_up_ipifs) {
16078 			ill_group_cleanup(ill);
16079 		}
16080 
16081 		break;
16082 	case DL_NOTIFY_IND: {
16083 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16084 		ire_t *ire;
16085 		boolean_t need_ire_walk_v4 = B_FALSE;
16086 		boolean_t need_ire_walk_v6 = B_FALSE;
16087 
16088 		switch (notify->dl_notification) {
16089 		case DL_NOTE_PHYS_ADDR:
16090 			err = ill_set_phys_addr(ill, mp);
16091 			break;
16092 
16093 		case DL_NOTE_FASTPATH_FLUSH:
16094 			ill_fastpath_flush(ill);
16095 			break;
16096 
16097 		case DL_NOTE_SDU_SIZE:
16098 			/*
16099 			 * Change the MTU size of the interface, of all
16100 			 * attached ipif's, and of all relevant ire's.  The
16101 			 * new value's a uint32_t at notify->dl_data.
16102 			 * Mtu change Vs. new ire creation - protocol below.
16103 			 *
16104 			 * a Mark the ipif as IPIF_CHANGING.
16105 			 * b Set the new mtu in the ipif.
16106 			 * c Change the ire_max_frag on all affected ires
16107 			 * d Unmark the IPIF_CHANGING
16108 			 *
16109 			 * To see how the protocol works, assume an interface
16110 			 * route is also being added simultaneously by
16111 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16112 			 * the ire. If the ire is created before step a,
16113 			 * it will be cleaned up by step c. If the ire is
16114 			 * created after step d, it will see the new value of
16115 			 * ipif_mtu. Any attempt to create the ire between
16116 			 * steps a to d will fail because of the IPIF_CHANGING
16117 			 * flag. Note that ire_create() is passed a pointer to
16118 			 * the ipif_mtu, and not the value. During ire_add
16119 			 * under the bucket lock, the ire_max_frag of the
16120 			 * new ire being created is set from the ipif/ire from
16121 			 * which it is being derived.
16122 			 */
16123 			mutex_enter(&ill->ill_lock);
16124 			ill->ill_max_frag = (uint_t)notify->dl_data;
16125 
16126 			/*
16127 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16128 			 * leave it alone
16129 			 */
16130 			if (ill->ill_mtu_userspecified) {
16131 				mutex_exit(&ill->ill_lock);
16132 				break;
16133 			}
16134 			ill->ill_max_mtu = ill->ill_max_frag;
16135 			if (ill->ill_isv6) {
16136 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16137 					ill->ill_max_mtu = IPV6_MIN_MTU;
16138 			} else {
16139 				if (ill->ill_max_mtu < IP_MIN_MTU)
16140 					ill->ill_max_mtu = IP_MIN_MTU;
16141 			}
16142 			for (ipif = ill->ill_ipif; ipif != NULL;
16143 			    ipif = ipif->ipif_next) {
16144 				/*
16145 				 * Don't override the mtu if the user
16146 				 * has explicitly set it.
16147 				 */
16148 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16149 					continue;
16150 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16151 				if (ipif->ipif_isv6)
16152 					ire = ipif_to_ire_v6(ipif);
16153 				else
16154 					ire = ipif_to_ire(ipif);
16155 				if (ire != NULL) {
16156 					ire->ire_max_frag = ipif->ipif_mtu;
16157 					ire_refrele(ire);
16158 				}
16159 				if (ipif->ipif_flags & IPIF_UP) {
16160 					if (ill->ill_isv6)
16161 						need_ire_walk_v6 = B_TRUE;
16162 					else
16163 						need_ire_walk_v4 = B_TRUE;
16164 				}
16165 			}
16166 			mutex_exit(&ill->ill_lock);
16167 			if (need_ire_walk_v4)
16168 				ire_walk_v4(ill_mtu_change, (char *)ill,
16169 				    ALL_ZONES, ipst);
16170 			if (need_ire_walk_v6)
16171 				ire_walk_v6(ill_mtu_change, (char *)ill,
16172 				    ALL_ZONES, ipst);
16173 			break;
16174 		case DL_NOTE_LINK_UP:
16175 		case DL_NOTE_LINK_DOWN: {
16176 			/*
16177 			 * We are writer. ill / phyint / ipsq assocs stable.
16178 			 * The RUNNING flag reflects the state of the link.
16179 			 */
16180 			phyint_t *phyint = ill->ill_phyint;
16181 			uint64_t new_phyint_flags;
16182 			boolean_t changed = B_FALSE;
16183 			boolean_t went_up;
16184 
16185 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16186 			mutex_enter(&phyint->phyint_lock);
16187 			new_phyint_flags = went_up ?
16188 			    phyint->phyint_flags | PHYI_RUNNING :
16189 			    phyint->phyint_flags & ~PHYI_RUNNING;
16190 			if (new_phyint_flags != phyint->phyint_flags) {
16191 				phyint->phyint_flags = new_phyint_flags;
16192 				changed = B_TRUE;
16193 			}
16194 			mutex_exit(&phyint->phyint_lock);
16195 			/*
16196 			 * ill_restart_dad handles the DAD restart and routing
16197 			 * socket notification logic.
16198 			 */
16199 			if (changed) {
16200 				ill_restart_dad(phyint->phyint_illv4, went_up);
16201 				ill_restart_dad(phyint->phyint_illv6, went_up);
16202 			}
16203 			break;
16204 		}
16205 		case DL_NOTE_PROMISC_ON_PHYS:
16206 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16207 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16208 			mutex_enter(&ill->ill_lock);
16209 			ill->ill_promisc_on_phys = B_TRUE;
16210 			mutex_exit(&ill->ill_lock);
16211 			break;
16212 		case DL_NOTE_PROMISC_OFF_PHYS:
16213 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16214 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16215 			mutex_enter(&ill->ill_lock);
16216 			ill->ill_promisc_on_phys = B_FALSE;
16217 			mutex_exit(&ill->ill_lock);
16218 			break;
16219 		case DL_NOTE_CAPAB_RENEG:
16220 			/*
16221 			 * Something changed on the driver side.
16222 			 * It wants us to renegotiate the capabilities
16223 			 * on this ill. The most likely cause is the
16224 			 * aggregation interface under us where a
16225 			 * port got added or went away.
16226 			 *
16227 			 * We reset the capabilities and set the
16228 			 * state to IDS_RENG so that when the ack
16229 			 * comes back, we can start the
16230 			 * renegotiation process.
16231 			 */
16232 			ill_capability_reset(ill);
16233 			ill->ill_dlpi_capab_state = IDS_RENEG;
16234 			break;
16235 		default:
16236 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16237 			    "type 0x%x for DL_NOTIFY_IND\n",
16238 			    notify->dl_notification));
16239 			break;
16240 		}
16241 
16242 		/*
16243 		 * As this is an asynchronous operation, we
16244 		 * should not call ill_dlpi_done
16245 		 */
16246 		break;
16247 	}
16248 	case DL_NOTIFY_ACK: {
16249 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16250 
16251 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16252 			ill->ill_note_link = 1;
16253 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16254 		break;
16255 	}
16256 	case DL_PHYS_ADDR_ACK: {
16257 		/*
16258 		 * As part of plumbing the interface via SIOCSLIFNAME,
16259 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16260 		 * whose answers we receive here.  As each answer is received,
16261 		 * we call ill_dlpi_done() to dispatch the next request as
16262 		 * we're processing the current one.  Once all answers have
16263 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16264 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16265 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16266 		 * available, but we know the ioctl is pending on ill_wq.)
16267 		 */
16268 		uint_t paddrlen, paddroff;
16269 
16270 		paddrreq = ill->ill_phys_addr_pend;
16271 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16272 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16273 
16274 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16275 		if (paddrreq == DL_IPV6_TOKEN) {
16276 			/*
16277 			 * bcopy to low-order bits of ill_token
16278 			 *
16279 			 * XXX Temporary hack - currently, all known tokens
16280 			 * are 64 bits, so I'll cheat for the moment.
16281 			 */
16282 			bcopy(mp->b_rptr + paddroff,
16283 			    &ill->ill_token.s6_addr32[2], paddrlen);
16284 			ill->ill_token_length = paddrlen;
16285 			break;
16286 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16287 			ASSERT(ill->ill_nd_lla_mp == NULL);
16288 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16289 			mp = NULL;
16290 			break;
16291 		}
16292 
16293 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16294 		ASSERT(ill->ill_phys_addr_mp == NULL);
16295 		if (!ill->ill_ifname_pending)
16296 			break;
16297 		ill->ill_ifname_pending = 0;
16298 		if (!ioctl_aborted)
16299 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16300 		if (mp1 != NULL) {
16301 			ASSERT(connp == NULL);
16302 			q = ill->ill_wq;
16303 		}
16304 		/*
16305 		 * If any error acks received during the plumbing sequence,
16306 		 * ill_ifname_pending_err will be set. Break out and send up
16307 		 * the error to the pending ioctl.
16308 		 */
16309 		if (ill->ill_ifname_pending_err != 0) {
16310 			err = ill->ill_ifname_pending_err;
16311 			ill->ill_ifname_pending_err = 0;
16312 			break;
16313 		}
16314 
16315 		ill->ill_phys_addr_mp = mp;
16316 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16317 		mp = NULL;
16318 
16319 		/*
16320 		 * If paddrlen is zero, the DLPI provider doesn't support
16321 		 * physical addresses.  The other two tests were historical
16322 		 * workarounds for bugs in our former PPP implementation, but
16323 		 * now other things have grown dependencies on them -- e.g.,
16324 		 * the tun module specifies a dl_addr_length of zero in its
16325 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16326 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16327 		 * but only after careful testing ensures that all dependent
16328 		 * broken DLPI providers have been fixed.
16329 		 */
16330 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16331 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16332 			ill->ill_phys_addr = NULL;
16333 		} else if (paddrlen != ill->ill_phys_addr_length) {
16334 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16335 			    paddrlen, ill->ill_phys_addr_length));
16336 			err = EINVAL;
16337 			break;
16338 		}
16339 
16340 		if (ill->ill_nd_lla_mp == NULL) {
16341 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16342 				err = ENOMEM;
16343 				break;
16344 			}
16345 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16346 		}
16347 
16348 		/*
16349 		 * Set the interface token.  If the zeroth interface address
16350 		 * is unspecified, then set it to the link local address.
16351 		 */
16352 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16353 			(void) ill_setdefaulttoken(ill);
16354 
16355 		ASSERT(ill->ill_ipif->ipif_id == 0);
16356 		if (ipif != NULL &&
16357 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16358 			(void) ipif_setlinklocal(ipif);
16359 		}
16360 		break;
16361 	}
16362 	case DL_OK_ACK:
16363 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16364 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16365 		    dloa->dl_correct_primitive));
16366 		switch (dloa->dl_correct_primitive) {
16367 		case DL_PROMISCON_REQ:
16368 		case DL_PROMISCOFF_REQ:
16369 		case DL_ENABMULTI_REQ:
16370 		case DL_DISABMULTI_REQ:
16371 		case DL_UNBIND_REQ:
16372 		case DL_ATTACH_REQ:
16373 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16374 			break;
16375 		}
16376 		break;
16377 	default:
16378 		break;
16379 	}
16380 
16381 	freemsg(mp);
16382 	if (mp1 != NULL) {
16383 		/*
16384 		 * The operation must complete without EINPROGRESS
16385 		 * since ipsq_pending_mp_get() has removed the mblk
16386 		 * from ipsq_pending_mp.  Otherwise, the operation
16387 		 * will be stuck forever in the ipsq.
16388 		 */
16389 		ASSERT(err != EINPROGRESS);
16390 
16391 		switch (ipsq->ipsq_current_ioctl) {
16392 		case 0:
16393 			ipsq_current_finish(ipsq);
16394 			break;
16395 
16396 		case SIOCLIFADDIF:
16397 		case SIOCSLIFNAME:
16398 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16399 			break;
16400 
16401 		default:
16402 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16403 			break;
16404 		}
16405 	}
16406 }
16407 
16408 /*
16409  * ip_rput_other is called by ip_rput to handle messages modifying the global
16410  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16411  */
16412 /* ARGSUSED */
16413 void
16414 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16415 {
16416 	ill_t		*ill;
16417 	struct iocblk	*iocp;
16418 	mblk_t		*mp1;
16419 	conn_t		*connp = NULL;
16420 
16421 	ip1dbg(("ip_rput_other "));
16422 	ill = (ill_t *)q->q_ptr;
16423 	/*
16424 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16425 	 * in which case ipsq is NULL.
16426 	 */
16427 	if (ipsq != NULL) {
16428 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16429 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16430 	}
16431 
16432 	switch (mp->b_datap->db_type) {
16433 	case M_ERROR:
16434 	case M_HANGUP:
16435 		/*
16436 		 * The device has a problem.  We force the ILL down.  It can
16437 		 * be brought up again manually using SIOCSIFFLAGS (via
16438 		 * ifconfig or equivalent).
16439 		 */
16440 		ASSERT(ipsq != NULL);
16441 		if (mp->b_rptr < mp->b_wptr)
16442 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16443 		if (ill->ill_error == 0)
16444 			ill->ill_error = ENXIO;
16445 		if (!ill_down_start(q, mp))
16446 			return;
16447 		ipif_all_down_tail(ipsq, q, mp, NULL);
16448 		break;
16449 	case M_IOCACK:
16450 		iocp = (struct iocblk *)mp->b_rptr;
16451 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16452 		switch (iocp->ioc_cmd) {
16453 		case SIOCSTUNPARAM:
16454 		case OSIOCSTUNPARAM:
16455 			ASSERT(ipsq != NULL);
16456 			/*
16457 			 * Finish socket ioctl passed through to tun.
16458 			 * We should have an IOCTL waiting on this.
16459 			 */
16460 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16461 			if (ill->ill_isv6) {
16462 				struct iftun_req *ta;
16463 
16464 				/*
16465 				 * if a source or destination is
16466 				 * being set, try and set the link
16467 				 * local address for the tunnel
16468 				 */
16469 				ta = (struct iftun_req *)mp->b_cont->
16470 				    b_cont->b_rptr;
16471 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16472 					ipif_set_tun_llink(ill, ta);
16473 				}
16474 
16475 			}
16476 			if (mp1 != NULL) {
16477 				/*
16478 				 * Now copy back the b_next/b_prev used by
16479 				 * mi code for the mi_copy* functions.
16480 				 * See ip_sioctl_tunparam() for the reason.
16481 				 * Also protect against missing b_cont.
16482 				 */
16483 				if (mp->b_cont != NULL) {
16484 					mp->b_cont->b_next =
16485 					    mp1->b_cont->b_next;
16486 					mp->b_cont->b_prev =
16487 					    mp1->b_cont->b_prev;
16488 				}
16489 				inet_freemsg(mp1);
16490 				ASSERT(connp != NULL);
16491 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16492 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16493 			} else {
16494 				ASSERT(connp == NULL);
16495 				putnext(q, mp);
16496 			}
16497 			break;
16498 		case SIOCGTUNPARAM:
16499 		case OSIOCGTUNPARAM:
16500 			/*
16501 			 * This is really M_IOCDATA from the tunnel driver.
16502 			 * convert back and complete the ioctl.
16503 			 * We should have an IOCTL waiting on this.
16504 			 */
16505 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16506 			if (mp1) {
16507 				/*
16508 				 * Now copy back the b_next/b_prev used by
16509 				 * mi code for the mi_copy* functions.
16510 				 * See ip_sioctl_tunparam() for the reason.
16511 				 * Also protect against missing b_cont.
16512 				 */
16513 				if (mp->b_cont != NULL) {
16514 					mp->b_cont->b_next =
16515 					    mp1->b_cont->b_next;
16516 					mp->b_cont->b_prev =
16517 					    mp1->b_cont->b_prev;
16518 				}
16519 				inet_freemsg(mp1);
16520 				if (iocp->ioc_error == 0)
16521 					mp->b_datap->db_type = M_IOCDATA;
16522 				ASSERT(connp != NULL);
16523 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16524 				    iocp->ioc_error, COPYOUT, NULL);
16525 			} else {
16526 				ASSERT(connp == NULL);
16527 				putnext(q, mp);
16528 			}
16529 			break;
16530 		default:
16531 			break;
16532 		}
16533 		break;
16534 	case M_IOCNAK:
16535 		iocp = (struct iocblk *)mp->b_rptr;
16536 
16537 		switch (iocp->ioc_cmd) {
16538 		int mode;
16539 
16540 		case DL_IOC_HDR_INFO:
16541 			/*
16542 			 * If this was the first attempt turn of the
16543 			 * fastpath probing.
16544 			 */
16545 			mutex_enter(&ill->ill_lock);
16546 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16547 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16548 				mutex_exit(&ill->ill_lock);
16549 				ill_fastpath_nack(ill);
16550 				ip1dbg(("ip_rput: DLPI fastpath off on "
16551 				    "interface %s\n",
16552 				    ill->ill_name));
16553 			} else {
16554 				mutex_exit(&ill->ill_lock);
16555 			}
16556 			freemsg(mp);
16557 			break;
16558 		case SIOCSTUNPARAM:
16559 		case OSIOCSTUNPARAM:
16560 			ASSERT(ipsq != NULL);
16561 			/*
16562 			 * Finish socket ioctl passed through to tun
16563 			 * We should have an IOCTL waiting on this.
16564 			 */
16565 			/* FALLTHRU */
16566 		case SIOCGTUNPARAM:
16567 		case OSIOCGTUNPARAM:
16568 			/*
16569 			 * This is really M_IOCDATA from the tunnel driver.
16570 			 * convert back and complete the ioctl.
16571 			 * We should have an IOCTL waiting on this.
16572 			 */
16573 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16574 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16575 				mp1 = ill_pending_mp_get(ill, &connp,
16576 				    iocp->ioc_id);
16577 				mode = COPYOUT;
16578 				ipsq = NULL;
16579 			} else {
16580 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16581 				mode = NO_COPYOUT;
16582 			}
16583 			if (mp1 != NULL) {
16584 				/*
16585 				 * Now copy back the b_next/b_prev used by
16586 				 * mi code for the mi_copy* functions.
16587 				 * See ip_sioctl_tunparam() for the reason.
16588 				 * Also protect against missing b_cont.
16589 				 */
16590 				if (mp->b_cont != NULL) {
16591 					mp->b_cont->b_next =
16592 					    mp1->b_cont->b_next;
16593 					mp->b_cont->b_prev =
16594 					    mp1->b_cont->b_prev;
16595 				}
16596 				inet_freemsg(mp1);
16597 				if (iocp->ioc_error == 0)
16598 					iocp->ioc_error = EINVAL;
16599 				ASSERT(connp != NULL);
16600 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16601 				    iocp->ioc_error, mode, ipsq);
16602 			} else {
16603 				ASSERT(connp == NULL);
16604 				putnext(q, mp);
16605 			}
16606 			break;
16607 		default:
16608 			break;
16609 		}
16610 	default:
16611 		break;
16612 	}
16613 }
16614 
16615 /*
16616  * NOTE : This function does not ire_refrele the ire argument passed in.
16617  *
16618  * IPQoS notes
16619  * IP policy is invoked twice for a forwarded packet, once on the read side
16620  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16621  * enabled. An additional parameter, in_ill, has been added for this purpose.
16622  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16623  * because ip_mroute drops this information.
16624  *
16625  */
16626 void
16627 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16628 {
16629 	uint32_t	pkt_len;
16630 	queue_t	*q;
16631 	uint32_t	sum;
16632 #define	rptr	((uchar_t *)ipha)
16633 	uint32_t	max_frag;
16634 	uint32_t	ill_index;
16635 	ill_t		*out_ill;
16636 	mib2_ipIfStatsEntry_t *mibptr;
16637 	ip_stack_t	*ipst = in_ill->ill_ipst;
16638 
16639 	/* Get the ill_index of the incoming ILL */
16640 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16641 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16642 
16643 	/* Initiate Read side IPPF processing */
16644 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16645 		ip_process(IPP_FWD_IN, &mp, ill_index);
16646 		if (mp == NULL) {
16647 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16648 			    "during IPPF processing\n"));
16649 			return;
16650 		}
16651 	}
16652 
16653 	pkt_len = ntohs(ipha->ipha_length);
16654 
16655 	/* Adjust the checksum to reflect the ttl decrement. */
16656 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16657 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16658 
16659 	if (ipha->ipha_ttl-- <= 1) {
16660 		if (ip_csum_hdr(ipha)) {
16661 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16662 			goto drop_pkt;
16663 		}
16664 		/*
16665 		 * Note: ire_stq this will be NULL for multicast
16666 		 * datagrams using the long path through arp (the IRE
16667 		 * is not an IRE_CACHE). This should not cause
16668 		 * problems since we don't generate ICMP errors for
16669 		 * multicast packets.
16670 		 */
16671 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16672 		q = ire->ire_stq;
16673 		if (q != NULL) {
16674 			/* Sent by forwarding path, and router is global zone */
16675 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16676 			    GLOBAL_ZONEID, ipst);
16677 		} else
16678 			freemsg(mp);
16679 		return;
16680 	}
16681 
16682 	/*
16683 	 * Don't forward if the interface is down
16684 	 */
16685 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16686 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16687 		ip2dbg(("ip_rput_forward:interface is down\n"));
16688 		goto drop_pkt;
16689 	}
16690 
16691 	/* Get the ill_index of the outgoing ILL */
16692 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16693 
16694 	out_ill = ire->ire_ipif->ipif_ill;
16695 
16696 	DTRACE_PROBE4(ip4__forwarding__start,
16697 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16698 
16699 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16700 	    ipst->ips_ipv4firewall_forwarding,
16701 	    in_ill, out_ill, ipha, mp, mp, ipst);
16702 
16703 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16704 
16705 	if (mp == NULL)
16706 		return;
16707 	pkt_len = ntohs(ipha->ipha_length);
16708 
16709 	if (is_system_labeled()) {
16710 		mblk_t *mp1;
16711 
16712 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16713 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16714 			goto drop_pkt;
16715 		}
16716 		/* Size may have changed */
16717 		mp = mp1;
16718 		ipha = (ipha_t *)mp->b_rptr;
16719 		pkt_len = ntohs(ipha->ipha_length);
16720 	}
16721 
16722 	/* Check if there are options to update */
16723 	if (!IS_SIMPLE_IPH(ipha)) {
16724 		if (ip_csum_hdr(ipha)) {
16725 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16726 			goto drop_pkt;
16727 		}
16728 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16729 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16730 			return;
16731 		}
16732 
16733 		ipha->ipha_hdr_checksum = 0;
16734 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16735 	}
16736 	max_frag = ire->ire_max_frag;
16737 	if (pkt_len > max_frag) {
16738 		/*
16739 		 * It needs fragging on its way out.  We haven't
16740 		 * verified the header checksum yet.  Since we
16741 		 * are going to put a surely good checksum in the
16742 		 * outgoing header, we have to make sure that it
16743 		 * was good coming in.
16744 		 */
16745 		if (ip_csum_hdr(ipha)) {
16746 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16747 			goto drop_pkt;
16748 		}
16749 		/* Initiate Write side IPPF processing */
16750 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16751 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16752 			if (mp == NULL) {
16753 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16754 				    " during IPPF processing\n"));
16755 				return;
16756 			}
16757 		}
16758 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16759 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16760 		return;
16761 	}
16762 
16763 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16764 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16765 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16766 	    ipst->ips_ipv4firewall_physical_out,
16767 	    NULL, out_ill, ipha, mp, mp, ipst);
16768 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16769 	if (mp == NULL)
16770 		return;
16771 
16772 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16773 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16774 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16775 	/* ip_xmit_v4 always consumes the packet */
16776 	return;
16777 
16778 drop_pkt:;
16779 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16780 	freemsg(mp);
16781 #undef	rptr
16782 }
16783 
16784 void
16785 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16786 {
16787 	ire_t	*ire;
16788 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16789 
16790 	ASSERT(!ipif->ipif_isv6);
16791 	/*
16792 	 * Find an IRE which matches the destination and the outgoing
16793 	 * queue in the cache table. All we need is an IRE_CACHE which
16794 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16795 	 * then it is enough to have some IRE_CACHE in the group.
16796 	 */
16797 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16798 		dst = ipif->ipif_pp_dst_addr;
16799 
16800 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16801 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16802 	if (ire == NULL) {
16803 		/*
16804 		 * Mark this packet to make it be delivered to
16805 		 * ip_rput_forward after the new ire has been
16806 		 * created.
16807 		 */
16808 		mp->b_prev = NULL;
16809 		mp->b_next = mp;
16810 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16811 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16812 	} else {
16813 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16814 		IRE_REFRELE(ire);
16815 	}
16816 }
16817 
16818 /* Update any source route, record route or timestamp options */
16819 static int
16820 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16821 {
16822 	ipoptp_t	opts;
16823 	uchar_t		*opt;
16824 	uint8_t		optval;
16825 	uint8_t		optlen;
16826 	ipaddr_t	dst;
16827 	uint32_t	ts;
16828 	ire_t		*dst_ire = NULL;
16829 	ire_t		*tmp_ire = NULL;
16830 	timestruc_t	now;
16831 
16832 	ip2dbg(("ip_rput_forward_options\n"));
16833 	dst = ipha->ipha_dst;
16834 	for (optval = ipoptp_first(&opts, ipha);
16835 	    optval != IPOPT_EOL;
16836 	    optval = ipoptp_next(&opts)) {
16837 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16838 		opt = opts.ipoptp_cur;
16839 		optlen = opts.ipoptp_len;
16840 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16841 		    optval, opts.ipoptp_len));
16842 		switch (optval) {
16843 			uint32_t off;
16844 		case IPOPT_SSRR:
16845 		case IPOPT_LSRR:
16846 			/* Check if adminstratively disabled */
16847 			if (!ipst->ips_ip_forward_src_routed) {
16848 				if (ire->ire_stq != NULL) {
16849 					/*
16850 					 * Sent by forwarding path, and router
16851 					 * is global zone
16852 					 */
16853 					icmp_unreachable(ire->ire_stq, mp,
16854 					    ICMP_SOURCE_ROUTE_FAILED,
16855 					    GLOBAL_ZONEID, ipst);
16856 				} else {
16857 					ip0dbg(("ip_rput_forward_options: "
16858 					    "unable to send unreach\n"));
16859 					freemsg(mp);
16860 				}
16861 				return (-1);
16862 			}
16863 
16864 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16865 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16866 			if (dst_ire == NULL) {
16867 				/*
16868 				 * Must be partial since ip_rput_options
16869 				 * checked for strict.
16870 				 */
16871 				break;
16872 			}
16873 			off = opt[IPOPT_OFFSET];
16874 			off--;
16875 		redo_srr:
16876 			if (optlen < IP_ADDR_LEN ||
16877 			    off > optlen - IP_ADDR_LEN) {
16878 				/* End of source route */
16879 				ip1dbg((
16880 				    "ip_rput_forward_options: end of SR\n"));
16881 				ire_refrele(dst_ire);
16882 				break;
16883 			}
16884 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16885 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16886 			    IP_ADDR_LEN);
16887 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16888 			    ntohl(dst)));
16889 
16890 			/*
16891 			 * Check if our address is present more than
16892 			 * once as consecutive hops in source route.
16893 			 */
16894 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16895 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16896 			if (tmp_ire != NULL) {
16897 				ire_refrele(tmp_ire);
16898 				off += IP_ADDR_LEN;
16899 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16900 				goto redo_srr;
16901 			}
16902 			ipha->ipha_dst = dst;
16903 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16904 			ire_refrele(dst_ire);
16905 			break;
16906 		case IPOPT_RR:
16907 			off = opt[IPOPT_OFFSET];
16908 			off--;
16909 			if (optlen < IP_ADDR_LEN ||
16910 			    off > optlen - IP_ADDR_LEN) {
16911 				/* No more room - ignore */
16912 				ip1dbg((
16913 				    "ip_rput_forward_options: end of RR\n"));
16914 				break;
16915 			}
16916 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16917 			    IP_ADDR_LEN);
16918 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16919 			break;
16920 		case IPOPT_TS:
16921 			/* Insert timestamp if there is room */
16922 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16923 			case IPOPT_TS_TSONLY:
16924 				off = IPOPT_TS_TIMELEN;
16925 				break;
16926 			case IPOPT_TS_PRESPEC:
16927 			case IPOPT_TS_PRESPEC_RFC791:
16928 				/* Verify that the address matched */
16929 				off = opt[IPOPT_OFFSET] - 1;
16930 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16931 				dst_ire = ire_ctable_lookup(dst, 0,
16932 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16933 				    MATCH_IRE_TYPE, ipst);
16934 				if (dst_ire == NULL) {
16935 					/* Not for us */
16936 					break;
16937 				}
16938 				ire_refrele(dst_ire);
16939 				/* FALLTHRU */
16940 			case IPOPT_TS_TSANDADDR:
16941 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16942 				break;
16943 			default:
16944 				/*
16945 				 * ip_*put_options should have already
16946 				 * dropped this packet.
16947 				 */
16948 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16949 				    "unknown IT - bug in ip_rput_options?\n");
16950 				return (0);	/* Keep "lint" happy */
16951 			}
16952 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16953 				/* Increase overflow counter */
16954 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16955 				opt[IPOPT_POS_OV_FLG] =
16956 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16957 				    (off << 4));
16958 				break;
16959 			}
16960 			off = opt[IPOPT_OFFSET] - 1;
16961 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16962 			case IPOPT_TS_PRESPEC:
16963 			case IPOPT_TS_PRESPEC_RFC791:
16964 			case IPOPT_TS_TSANDADDR:
16965 				bcopy(&ire->ire_src_addr,
16966 				    (char *)opt + off, IP_ADDR_LEN);
16967 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16968 				/* FALLTHRU */
16969 			case IPOPT_TS_TSONLY:
16970 				off = opt[IPOPT_OFFSET] - 1;
16971 				/* Compute # of milliseconds since midnight */
16972 				gethrestime(&now);
16973 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16974 				    now.tv_nsec / (NANOSEC / MILLISEC);
16975 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16976 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16977 				break;
16978 			}
16979 			break;
16980 		}
16981 	}
16982 	return (0);
16983 }
16984 
16985 /*
16986  * This is called after processing at least one of AH/ESP headers.
16987  *
16988  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16989  * the actual, physical interface on which the packet was received,
16990  * but, when ip_strict_dst_multihoming is set to 1, could be the
16991  * interface which had the ipha_dst configured when the packet went
16992  * through ip_rput. The ill_index corresponding to the recv_ill
16993  * is saved in ipsec_in_rill_index
16994  *
16995  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16996  * cannot assume "ire" points to valid data for any IPv6 cases.
16997  */
16998 void
16999 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
17000 {
17001 	mblk_t *mp;
17002 	ipaddr_t dst;
17003 	in6_addr_t *v6dstp;
17004 	ipha_t *ipha;
17005 	ip6_t *ip6h;
17006 	ipsec_in_t *ii;
17007 	boolean_t ill_need_rele = B_FALSE;
17008 	boolean_t rill_need_rele = B_FALSE;
17009 	boolean_t ire_need_rele = B_FALSE;
17010 	netstack_t	*ns;
17011 	ip_stack_t	*ipst;
17012 
17013 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
17014 	ASSERT(ii->ipsec_in_ill_index != 0);
17015 	ns = ii->ipsec_in_ns;
17016 	ASSERT(ii->ipsec_in_ns != NULL);
17017 	ipst = ns->netstack_ip;
17018 
17019 	mp = ipsec_mp->b_cont;
17020 	ASSERT(mp != NULL);
17021 
17022 
17023 	if (ill == NULL) {
17024 		ASSERT(recv_ill == NULL);
17025 		/*
17026 		 * We need to get the original queue on which ip_rput_local
17027 		 * or ip_rput_data_v6 was called.
17028 		 */
17029 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17030 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17031 		ill_need_rele = B_TRUE;
17032 
17033 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17034 			recv_ill = ill_lookup_on_ifindex(
17035 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17036 			    NULL, NULL, NULL, NULL, ipst);
17037 			rill_need_rele = B_TRUE;
17038 		} else {
17039 			recv_ill = ill;
17040 		}
17041 
17042 		if ((ill == NULL) || (recv_ill == NULL)) {
17043 			ip0dbg(("ip_fanout_proto_again: interface "
17044 			    "disappeared\n"));
17045 			if (ill != NULL)
17046 				ill_refrele(ill);
17047 			if (recv_ill != NULL)
17048 				ill_refrele(recv_ill);
17049 			freemsg(ipsec_mp);
17050 			return;
17051 		}
17052 	}
17053 
17054 	ASSERT(ill != NULL && recv_ill != NULL);
17055 
17056 	if (mp->b_datap->db_type == M_CTL) {
17057 		/*
17058 		 * AH/ESP is returning the ICMP message after
17059 		 * removing their headers. Fanout again till
17060 		 * it gets to the right protocol.
17061 		 */
17062 		if (ii->ipsec_in_v4) {
17063 			icmph_t *icmph;
17064 			int iph_hdr_length;
17065 			int hdr_length;
17066 
17067 			ipha = (ipha_t *)mp->b_rptr;
17068 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17069 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17070 			ipha = (ipha_t *)&icmph[1];
17071 			hdr_length = IPH_HDR_LENGTH(ipha);
17072 			/*
17073 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17074 			 * Reset the type to M_DATA.
17075 			 */
17076 			mp->b_datap->db_type = M_DATA;
17077 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17078 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17079 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17080 		} else {
17081 			icmp6_t *icmp6;
17082 			int hdr_length;
17083 
17084 			ip6h = (ip6_t *)mp->b_rptr;
17085 			/* Don't call hdr_length_v6() unless you have to. */
17086 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17087 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17088 			else
17089 				hdr_length = IPV6_HDR_LEN;
17090 
17091 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17092 			/*
17093 			 * icmp_inbound_error_fanout_v6 may need to do
17094 			 * pullupmsg.  Reset the type to M_DATA.
17095 			 */
17096 			mp->b_datap->db_type = M_DATA;
17097 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17098 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17099 		}
17100 		if (ill_need_rele)
17101 			ill_refrele(ill);
17102 		if (rill_need_rele)
17103 			ill_refrele(recv_ill);
17104 		return;
17105 	}
17106 
17107 	if (ii->ipsec_in_v4) {
17108 		ipha = (ipha_t *)mp->b_rptr;
17109 		dst = ipha->ipha_dst;
17110 		if (CLASSD(dst)) {
17111 			/*
17112 			 * Multicast has to be delivered to all streams.
17113 			 */
17114 			dst = INADDR_BROADCAST;
17115 		}
17116 
17117 		if (ire == NULL) {
17118 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17119 			    MBLK_GETLABEL(mp), ipst);
17120 			if (ire == NULL) {
17121 				if (ill_need_rele)
17122 					ill_refrele(ill);
17123 				if (rill_need_rele)
17124 					ill_refrele(recv_ill);
17125 				ip1dbg(("ip_fanout_proto_again: "
17126 				    "IRE not found"));
17127 				freemsg(ipsec_mp);
17128 				return;
17129 			}
17130 			ire_need_rele = B_TRUE;
17131 		}
17132 
17133 		switch (ipha->ipha_protocol) {
17134 			case IPPROTO_UDP:
17135 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17136 				    recv_ill);
17137 				if (ire_need_rele)
17138 					ire_refrele(ire);
17139 				break;
17140 			case IPPROTO_TCP:
17141 				if (!ire_need_rele)
17142 					IRE_REFHOLD(ire);
17143 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17144 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17145 				IRE_REFRELE(ire);
17146 				if (mp != NULL)
17147 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17148 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17149 				break;
17150 			case IPPROTO_SCTP:
17151 				if (!ire_need_rele)
17152 					IRE_REFHOLD(ire);
17153 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17154 				    ipsec_mp, 0, ill->ill_rq, dst);
17155 				break;
17156 			default:
17157 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17158 				    recv_ill);
17159 				if (ire_need_rele)
17160 					ire_refrele(ire);
17161 				break;
17162 		}
17163 	} else {
17164 		uint32_t rput_flags = 0;
17165 
17166 		ip6h = (ip6_t *)mp->b_rptr;
17167 		v6dstp = &ip6h->ip6_dst;
17168 		/*
17169 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17170 		 * address.
17171 		 *
17172 		 * Currently, we don't store that state in the IPSEC_IN
17173 		 * message, and we may need to.
17174 		 */
17175 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17176 		    IP6_IN_LLMCAST : 0);
17177 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17178 		    NULL, NULL);
17179 	}
17180 	if (ill_need_rele)
17181 		ill_refrele(ill);
17182 	if (rill_need_rele)
17183 		ill_refrele(recv_ill);
17184 }
17185 
17186 /*
17187  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17188  * returns 'true' if there are still fragments left on the queue, in
17189  * which case we restart the timer.
17190  */
17191 void
17192 ill_frag_timer(void *arg)
17193 {
17194 	ill_t	*ill = (ill_t *)arg;
17195 	boolean_t frag_pending;
17196 	ip_stack_t	*ipst = ill->ill_ipst;
17197 
17198 	mutex_enter(&ill->ill_lock);
17199 	ASSERT(!ill->ill_fragtimer_executing);
17200 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17201 		ill->ill_frag_timer_id = 0;
17202 		mutex_exit(&ill->ill_lock);
17203 		return;
17204 	}
17205 	ill->ill_fragtimer_executing = 1;
17206 	mutex_exit(&ill->ill_lock);
17207 
17208 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17209 
17210 	/*
17211 	 * Restart the timer, if we have fragments pending or if someone
17212 	 * wanted us to be scheduled again.
17213 	 */
17214 	mutex_enter(&ill->ill_lock);
17215 	ill->ill_fragtimer_executing = 0;
17216 	ill->ill_frag_timer_id = 0;
17217 	if (frag_pending || ill->ill_fragtimer_needrestart)
17218 		ill_frag_timer_start(ill);
17219 	mutex_exit(&ill->ill_lock);
17220 }
17221 
17222 void
17223 ill_frag_timer_start(ill_t *ill)
17224 {
17225 	ip_stack_t	*ipst = ill->ill_ipst;
17226 
17227 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17228 
17229 	/* If the ill is closing or opening don't proceed */
17230 	if (ill->ill_state_flags & ILL_CONDEMNED)
17231 		return;
17232 
17233 	if (ill->ill_fragtimer_executing) {
17234 		/*
17235 		 * ill_frag_timer is currently executing. Just record the
17236 		 * the fact that we want the timer to be restarted.
17237 		 * ill_frag_timer will post a timeout before it returns,
17238 		 * ensuring it will be called again.
17239 		 */
17240 		ill->ill_fragtimer_needrestart = 1;
17241 		return;
17242 	}
17243 
17244 	if (ill->ill_frag_timer_id == 0) {
17245 		/*
17246 		 * The timer is neither running nor is the timeout handler
17247 		 * executing. Post a timeout so that ill_frag_timer will be
17248 		 * called
17249 		 */
17250 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17251 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17252 		ill->ill_fragtimer_needrestart = 0;
17253 	}
17254 }
17255 
17256 /*
17257  * This routine is needed for loopback when forwarding multicasts.
17258  *
17259  * IPQoS Notes:
17260  * IPPF processing is done in fanout routines.
17261  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17262  * processing for IPSec packets is done when it comes back in clear.
17263  * NOTE : The callers of this function need to do the ire_refrele for the
17264  *	  ire that is being passed in.
17265  */
17266 void
17267 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17268     ill_t *recv_ill)
17269 {
17270 	ill_t	*ill = (ill_t *)q->q_ptr;
17271 	uint32_t	sum;
17272 	uint32_t	u1;
17273 	uint32_t	u2;
17274 	int		hdr_length;
17275 	boolean_t	mctl_present;
17276 	mblk_t		*first_mp = mp;
17277 	mblk_t		*hada_mp = NULL;
17278 	ipha_t		*inner_ipha;
17279 	ip_stack_t	*ipst;
17280 
17281 	ASSERT(recv_ill != NULL);
17282 	ipst = recv_ill->ill_ipst;
17283 
17284 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17285 	    "ip_rput_locl_start: q %p", q);
17286 
17287 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17288 	ASSERT(ill != NULL);
17289 
17290 
17291 #define	rptr	((uchar_t *)ipha)
17292 #define	iphs	((uint16_t *)ipha)
17293 
17294 	/*
17295 	 * no UDP or TCP packet should come here anymore.
17296 	 */
17297 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17298 	    (ipha->ipha_protocol != IPPROTO_UDP));
17299 
17300 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17301 	if (mctl_present &&
17302 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17303 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17304 
17305 		/*
17306 		 * It's an IPsec accelerated packet.
17307 		 * Keep a pointer to the data attributes around until
17308 		 * we allocate the ipsec_info_t.
17309 		 */
17310 		IPSECHW_DEBUG(IPSECHW_PKT,
17311 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17312 		hada_mp = first_mp;
17313 		hada_mp->b_cont = NULL;
17314 		/*
17315 		 * Since it is accelerated, it comes directly from
17316 		 * the ill and the data attributes is followed by
17317 		 * the packet data.
17318 		 */
17319 		ASSERT(mp->b_datap->db_type != M_CTL);
17320 		first_mp = mp;
17321 		mctl_present = B_FALSE;
17322 	}
17323 
17324 	/*
17325 	 * IF M_CTL is not present, then ipsec_in_is_secure
17326 	 * should return B_TRUE. There is a case where loopback
17327 	 * packets has an M_CTL in the front with all the
17328 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17329 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17330 	 * packets never comes here, it is safe to ASSERT the
17331 	 * following.
17332 	 */
17333 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17334 
17335 
17336 	/* u1 is # words of IP options */
17337 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17338 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17339 
17340 	if (u1) {
17341 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17342 			if (hada_mp != NULL)
17343 				freemsg(hada_mp);
17344 			return;
17345 		}
17346 	} else {
17347 		/* Check the IP header checksum.  */
17348 #define	uph	((uint16_t *)ipha)
17349 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17350 		    uph[6] + uph[7] + uph[8] + uph[9];
17351 #undef  uph
17352 		/* finish doing IP checksum */
17353 		sum = (sum & 0xFFFF) + (sum >> 16);
17354 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17355 		/*
17356 		 * Don't verify header checksum if this packet is coming
17357 		 * back from AH/ESP as we already did it.
17358 		 */
17359 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17360 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17361 			goto drop_pkt;
17362 		}
17363 	}
17364 
17365 	/*
17366 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17367 	 * might be called more than once for secure packets, count only
17368 	 * the first time.
17369 	 */
17370 	if (!mctl_present) {
17371 		UPDATE_IB_PKT_COUNT(ire);
17372 		ire->ire_last_used_time = lbolt;
17373 	}
17374 
17375 	/* Check for fragmentation offset. */
17376 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17377 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17378 	if (u1) {
17379 		/*
17380 		 * We re-assemble fragments before we do the AH/ESP
17381 		 * processing. Thus, M_CTL should not be present
17382 		 * while we are re-assembling.
17383 		 */
17384 		ASSERT(!mctl_present);
17385 		ASSERT(first_mp == mp);
17386 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17387 			return;
17388 		}
17389 		/*
17390 		 * Make sure that first_mp points back to mp as
17391 		 * the mp we came in with could have changed in
17392 		 * ip_rput_fragment().
17393 		 */
17394 		ipha = (ipha_t *)mp->b_rptr;
17395 		first_mp = mp;
17396 	}
17397 
17398 	/*
17399 	 * Clear hardware checksumming flag as it is currently only
17400 	 * used by TCP and UDP.
17401 	 */
17402 	DB_CKSUMFLAGS(mp) = 0;
17403 
17404 	/* Now we have a complete datagram, destined for this machine. */
17405 	u1 = IPH_HDR_LENGTH(ipha);
17406 	switch (ipha->ipha_protocol) {
17407 	case IPPROTO_ICMP: {
17408 		ire_t		*ire_zone;
17409 		ilm_t		*ilm;
17410 		mblk_t		*mp1;
17411 		zoneid_t	last_zoneid;
17412 
17413 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17414 			ASSERT(ire->ire_type == IRE_BROADCAST);
17415 			/*
17416 			 * In the multicast case, applications may have joined
17417 			 * the group from different zones, so we need to deliver
17418 			 * the packet to each of them. Loop through the
17419 			 * multicast memberships structures (ilm) on the receive
17420 			 * ill and send a copy of the packet up each matching
17421 			 * one. However, we don't do this for multicasts sent on
17422 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17423 			 * they must stay in the sender's zone.
17424 			 *
17425 			 * ilm_add_v6() ensures that ilms in the same zone are
17426 			 * contiguous in the ill_ilm list. We use this property
17427 			 * to avoid sending duplicates needed when two
17428 			 * applications in the same zone join the same group on
17429 			 * different logical interfaces: we ignore the ilm if
17430 			 * its zoneid is the same as the last matching one.
17431 			 * In addition, the sending of the packet for
17432 			 * ire_zoneid is delayed until all of the other ilms
17433 			 * have been exhausted.
17434 			 */
17435 			last_zoneid = -1;
17436 			ILM_WALKER_HOLD(recv_ill);
17437 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17438 			    ilm = ilm->ilm_next) {
17439 				if ((ilm->ilm_flags & ILM_DELETED) ||
17440 				    ipha->ipha_dst != ilm->ilm_addr ||
17441 				    ilm->ilm_zoneid == last_zoneid ||
17442 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17443 				    ilm->ilm_zoneid == ALL_ZONES ||
17444 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17445 					continue;
17446 				mp1 = ip_copymsg(first_mp);
17447 				if (mp1 == NULL)
17448 					continue;
17449 				icmp_inbound(q, mp1, B_TRUE, ill,
17450 				    0, sum, mctl_present, B_TRUE,
17451 				    recv_ill, ilm->ilm_zoneid);
17452 				last_zoneid = ilm->ilm_zoneid;
17453 			}
17454 			ILM_WALKER_RELE(recv_ill);
17455 		} else if (ire->ire_type == IRE_BROADCAST) {
17456 			/*
17457 			 * In the broadcast case, there may be many zones
17458 			 * which need a copy of the packet delivered to them.
17459 			 * There is one IRE_BROADCAST per broadcast address
17460 			 * and per zone; we walk those using a helper function.
17461 			 * In addition, the sending of the packet for ire is
17462 			 * delayed until all of the other ires have been
17463 			 * processed.
17464 			 */
17465 			IRB_REFHOLD(ire->ire_bucket);
17466 			ire_zone = NULL;
17467 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17468 			    ire)) != NULL) {
17469 				mp1 = ip_copymsg(first_mp);
17470 				if (mp1 == NULL)
17471 					continue;
17472 
17473 				UPDATE_IB_PKT_COUNT(ire_zone);
17474 				ire_zone->ire_last_used_time = lbolt;
17475 				icmp_inbound(q, mp1, B_TRUE, ill,
17476 				    0, sum, mctl_present, B_TRUE,
17477 				    recv_ill, ire_zone->ire_zoneid);
17478 			}
17479 			IRB_REFRELE(ire->ire_bucket);
17480 		}
17481 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17482 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17483 		    ire->ire_zoneid);
17484 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17485 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17486 		return;
17487 	}
17488 	case IPPROTO_IGMP:
17489 		/*
17490 		 * If we are not willing to accept IGMP packets in clear,
17491 		 * then check with global policy.
17492 		 */
17493 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17494 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17495 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17496 			if (first_mp == NULL)
17497 				return;
17498 		}
17499 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17500 			freemsg(first_mp);
17501 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17502 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17503 			return;
17504 		}
17505 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17506 			/* Bad packet - discarded by igmp_input */
17507 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17508 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17509 			if (mctl_present)
17510 				freeb(first_mp);
17511 			return;
17512 		}
17513 		/*
17514 		 * igmp_input() may have returned the pulled up message.
17515 		 * So first_mp and ipha need to be reinitialized.
17516 		 */
17517 		ipha = (ipha_t *)mp->b_rptr;
17518 		if (mctl_present)
17519 			first_mp->b_cont = mp;
17520 		else
17521 			first_mp = mp;
17522 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17523 		    connf_head != NULL) {
17524 			/* No user-level listener for IGMP packets */
17525 			goto drop_pkt;
17526 		}
17527 		/* deliver to local raw users */
17528 		break;
17529 	case IPPROTO_PIM:
17530 		/*
17531 		 * If we are not willing to accept PIM packets in clear,
17532 		 * then check with global policy.
17533 		 */
17534 		if (ipst->ips_pim_accept_clear_messages == 0) {
17535 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17536 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17537 			if (first_mp == NULL)
17538 				return;
17539 		}
17540 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17541 			freemsg(first_mp);
17542 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17543 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17544 			return;
17545 		}
17546 		if (pim_input(q, mp, ill) != 0) {
17547 			/* Bad packet - discarded by pim_input */
17548 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17549 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17550 			if (mctl_present)
17551 				freeb(first_mp);
17552 			return;
17553 		}
17554 
17555 		/*
17556 		 * pim_input() may have pulled up the message so ipha needs to
17557 		 * be reinitialized.
17558 		 */
17559 		ipha = (ipha_t *)mp->b_rptr;
17560 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17561 		    connf_head != NULL) {
17562 			/* No user-level listener for PIM packets */
17563 			goto drop_pkt;
17564 		}
17565 		/* deliver to local raw users */
17566 		break;
17567 	case IPPROTO_ENCAP:
17568 		/*
17569 		 * Handle self-encapsulated packets (IP-in-IP where
17570 		 * the inner addresses == the outer addresses).
17571 		 */
17572 		hdr_length = IPH_HDR_LENGTH(ipha);
17573 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17574 		    mp->b_wptr) {
17575 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17576 			    sizeof (ipha_t) - mp->b_rptr)) {
17577 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17578 				freemsg(first_mp);
17579 				return;
17580 			}
17581 			ipha = (ipha_t *)mp->b_rptr;
17582 		}
17583 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17584 		/*
17585 		 * Check the sanity of the inner IP header.
17586 		 */
17587 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17588 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17589 			freemsg(first_mp);
17590 			return;
17591 		}
17592 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17593 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17594 			freemsg(first_mp);
17595 			return;
17596 		}
17597 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17598 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17599 			ipsec_in_t *ii;
17600 
17601 			/*
17602 			 * Self-encapsulated tunnel packet. Remove
17603 			 * the outer IP header and fanout again.
17604 			 * We also need to make sure that the inner
17605 			 * header is pulled up until options.
17606 			 */
17607 			mp->b_rptr = (uchar_t *)inner_ipha;
17608 			ipha = inner_ipha;
17609 			hdr_length = IPH_HDR_LENGTH(ipha);
17610 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17611 				if (!pullupmsg(mp, (uchar_t *)ipha +
17612 				    + hdr_length - mp->b_rptr)) {
17613 					freemsg(first_mp);
17614 					return;
17615 				}
17616 				ipha = (ipha_t *)mp->b_rptr;
17617 			}
17618 			if (!mctl_present) {
17619 				ASSERT(first_mp == mp);
17620 				/*
17621 				 * This means that somebody is sending
17622 				 * Self-encapsualted packets without AH/ESP.
17623 				 * If AH/ESP was present, we would have already
17624 				 * allocated the first_mp.
17625 				 */
17626 				first_mp = ipsec_in_alloc(B_TRUE,
17627 				    ipst->ips_netstack);
17628 				if (first_mp == NULL) {
17629 					ip1dbg(("ip_proto_input: IPSEC_IN "
17630 					    "allocation failure.\n"));
17631 					BUMP_MIB(ill->ill_ip_mib,
17632 					    ipIfStatsInDiscards);
17633 					freemsg(mp);
17634 					return;
17635 				}
17636 				first_mp->b_cont = mp;
17637 			}
17638 			/*
17639 			 * We generally store the ill_index if we need to
17640 			 * do IPSEC processing as we lose the ill queue when
17641 			 * we come back. But in this case, we never should
17642 			 * have to store the ill_index here as it should have
17643 			 * been stored previously when we processed the
17644 			 * AH/ESP header in this routine or for non-ipsec
17645 			 * cases, we still have the queue. But for some bad
17646 			 * packets from the wire, we can get to IPSEC after
17647 			 * this and we better store the index for that case.
17648 			 */
17649 			ill = (ill_t *)q->q_ptr;
17650 			ii = (ipsec_in_t *)first_mp->b_rptr;
17651 			ii->ipsec_in_ill_index =
17652 			    ill->ill_phyint->phyint_ifindex;
17653 			ii->ipsec_in_rill_index =
17654 			    recv_ill->ill_phyint->phyint_ifindex;
17655 			if (ii->ipsec_in_decaps) {
17656 				/*
17657 				 * This packet is self-encapsulated multiple
17658 				 * times. We don't want to recurse infinitely.
17659 				 * To keep it simple, drop the packet.
17660 				 */
17661 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17662 				freemsg(first_mp);
17663 				return;
17664 			}
17665 			ii->ipsec_in_decaps = B_TRUE;
17666 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17667 			    ire);
17668 			return;
17669 		}
17670 		break;
17671 	case IPPROTO_AH:
17672 	case IPPROTO_ESP: {
17673 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17674 
17675 		/*
17676 		 * Fast path for AH/ESP. If this is the first time
17677 		 * we are sending a datagram to AH/ESP, allocate
17678 		 * a IPSEC_IN message and prepend it. Otherwise,
17679 		 * just fanout.
17680 		 */
17681 
17682 		int ipsec_rc;
17683 		ipsec_in_t *ii;
17684 		netstack_t *ns = ipst->ips_netstack;
17685 
17686 		IP_STAT(ipst, ipsec_proto_ahesp);
17687 		if (!mctl_present) {
17688 			ASSERT(first_mp == mp);
17689 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17690 			if (first_mp == NULL) {
17691 				ip1dbg(("ip_proto_input: IPSEC_IN "
17692 				    "allocation failure.\n"));
17693 				freemsg(hada_mp); /* okay ifnull */
17694 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17695 				freemsg(mp);
17696 				return;
17697 			}
17698 			/*
17699 			 * Store the ill_index so that when we come back
17700 			 * from IPSEC we ride on the same queue.
17701 			 */
17702 			ill = (ill_t *)q->q_ptr;
17703 			ii = (ipsec_in_t *)first_mp->b_rptr;
17704 			ii->ipsec_in_ill_index =
17705 			    ill->ill_phyint->phyint_ifindex;
17706 			ii->ipsec_in_rill_index =
17707 			    recv_ill->ill_phyint->phyint_ifindex;
17708 			first_mp->b_cont = mp;
17709 			/*
17710 			 * Cache hardware acceleration info.
17711 			 */
17712 			if (hada_mp != NULL) {
17713 				IPSECHW_DEBUG(IPSECHW_PKT,
17714 				    ("ip_rput_local: caching data attr.\n"));
17715 				ii->ipsec_in_accelerated = B_TRUE;
17716 				ii->ipsec_in_da = hada_mp;
17717 				hada_mp = NULL;
17718 			}
17719 		} else {
17720 			ii = (ipsec_in_t *)first_mp->b_rptr;
17721 		}
17722 
17723 		if (!ipsec_loaded(ipss)) {
17724 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17725 			    ire->ire_zoneid, ipst);
17726 			return;
17727 		}
17728 
17729 		ns = ipst->ips_netstack;
17730 		/* select inbound SA and have IPsec process the pkt */
17731 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17732 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17733 			if (esph == NULL)
17734 				return;
17735 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17736 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17737 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17738 			    first_mp, esph);
17739 		} else {
17740 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17741 			if (ah == NULL)
17742 				return;
17743 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17744 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17745 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17746 			    first_mp, ah);
17747 		}
17748 
17749 		switch (ipsec_rc) {
17750 		case IPSEC_STATUS_SUCCESS:
17751 			break;
17752 		case IPSEC_STATUS_FAILED:
17753 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17754 			/* FALLTHRU */
17755 		case IPSEC_STATUS_PENDING:
17756 			return;
17757 		}
17758 		/* we're done with IPsec processing, send it up */
17759 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17760 		return;
17761 	}
17762 	default:
17763 		break;
17764 	}
17765 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17766 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17767 		    ire->ire_zoneid));
17768 		goto drop_pkt;
17769 	}
17770 	/*
17771 	 * Handle protocols with which IP is less intimate.  There
17772 	 * can be more than one stream bound to a particular
17773 	 * protocol.  When this is the case, each one gets a copy
17774 	 * of any incoming packets.
17775 	 */
17776 	ip_fanout_proto(q, first_mp, ill, ipha,
17777 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17778 	    B_TRUE, recv_ill, ire->ire_zoneid);
17779 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17780 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17781 	return;
17782 
17783 drop_pkt:
17784 	freemsg(first_mp);
17785 	if (hada_mp != NULL)
17786 		freeb(hada_mp);
17787 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17788 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17789 #undef	rptr
17790 #undef  iphs
17791 
17792 }
17793 
17794 /*
17795  * Update any source route, record route or timestamp options.
17796  * Check that we are at end of strict source route.
17797  * The options have already been checked for sanity in ip_rput_options().
17798  */
17799 static boolean_t
17800 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17801     ip_stack_t *ipst)
17802 {
17803 	ipoptp_t	opts;
17804 	uchar_t		*opt;
17805 	uint8_t		optval;
17806 	uint8_t		optlen;
17807 	ipaddr_t	dst;
17808 	uint32_t	ts;
17809 	ire_t		*dst_ire;
17810 	timestruc_t	now;
17811 	zoneid_t	zoneid;
17812 	ill_t		*ill;
17813 
17814 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17815 
17816 	ip2dbg(("ip_rput_local_options\n"));
17817 
17818 	for (optval = ipoptp_first(&opts, ipha);
17819 	    optval != IPOPT_EOL;
17820 	    optval = ipoptp_next(&opts)) {
17821 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17822 		opt = opts.ipoptp_cur;
17823 		optlen = opts.ipoptp_len;
17824 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17825 		    optval, optlen));
17826 		switch (optval) {
17827 			uint32_t off;
17828 		case IPOPT_SSRR:
17829 		case IPOPT_LSRR:
17830 			off = opt[IPOPT_OFFSET];
17831 			off--;
17832 			if (optlen < IP_ADDR_LEN ||
17833 			    off > optlen - IP_ADDR_LEN) {
17834 				/* End of source route */
17835 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17836 				break;
17837 			}
17838 			/*
17839 			 * This will only happen if two consecutive entries
17840 			 * in the source route contains our address or if
17841 			 * it is a packet with a loose source route which
17842 			 * reaches us before consuming the whole source route
17843 			 */
17844 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17845 			if (optval == IPOPT_SSRR) {
17846 				goto bad_src_route;
17847 			}
17848 			/*
17849 			 * Hack: instead of dropping the packet truncate the
17850 			 * source route to what has been used by filling the
17851 			 * rest with IPOPT_NOP.
17852 			 */
17853 			opt[IPOPT_OLEN] = (uint8_t)off;
17854 			while (off < optlen) {
17855 				opt[off++] = IPOPT_NOP;
17856 			}
17857 			break;
17858 		case IPOPT_RR:
17859 			off = opt[IPOPT_OFFSET];
17860 			off--;
17861 			if (optlen < IP_ADDR_LEN ||
17862 			    off > optlen - IP_ADDR_LEN) {
17863 				/* No more room - ignore */
17864 				ip1dbg((
17865 				    "ip_rput_local_options: end of RR\n"));
17866 				break;
17867 			}
17868 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17869 			    IP_ADDR_LEN);
17870 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17871 			break;
17872 		case IPOPT_TS:
17873 			/* Insert timestamp if there is romm */
17874 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17875 			case IPOPT_TS_TSONLY:
17876 				off = IPOPT_TS_TIMELEN;
17877 				break;
17878 			case IPOPT_TS_PRESPEC:
17879 			case IPOPT_TS_PRESPEC_RFC791:
17880 				/* Verify that the address matched */
17881 				off = opt[IPOPT_OFFSET] - 1;
17882 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17883 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17884 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17885 				    ipst);
17886 				if (dst_ire == NULL) {
17887 					/* Not for us */
17888 					break;
17889 				}
17890 				ire_refrele(dst_ire);
17891 				/* FALLTHRU */
17892 			case IPOPT_TS_TSANDADDR:
17893 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17894 				break;
17895 			default:
17896 				/*
17897 				 * ip_*put_options should have already
17898 				 * dropped this packet.
17899 				 */
17900 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17901 				    "unknown IT - bug in ip_rput_options?\n");
17902 				return (B_TRUE);	/* Keep "lint" happy */
17903 			}
17904 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17905 				/* Increase overflow counter */
17906 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17907 				opt[IPOPT_POS_OV_FLG] =
17908 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17909 				    (off << 4));
17910 				break;
17911 			}
17912 			off = opt[IPOPT_OFFSET] - 1;
17913 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17914 			case IPOPT_TS_PRESPEC:
17915 			case IPOPT_TS_PRESPEC_RFC791:
17916 			case IPOPT_TS_TSANDADDR:
17917 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17918 				    IP_ADDR_LEN);
17919 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17920 				/* FALLTHRU */
17921 			case IPOPT_TS_TSONLY:
17922 				off = opt[IPOPT_OFFSET] - 1;
17923 				/* Compute # of milliseconds since midnight */
17924 				gethrestime(&now);
17925 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17926 				    now.tv_nsec / (NANOSEC / MILLISEC);
17927 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17928 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17929 				break;
17930 			}
17931 			break;
17932 		}
17933 	}
17934 	return (B_TRUE);
17935 
17936 bad_src_route:
17937 	q = WR(q);
17938 	if (q->q_next != NULL)
17939 		ill = q->q_ptr;
17940 	else
17941 		ill = NULL;
17942 
17943 	/* make sure we clear any indication of a hardware checksum */
17944 	DB_CKSUMFLAGS(mp) = 0;
17945 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17946 	if (zoneid == ALL_ZONES)
17947 		freemsg(mp);
17948 	else
17949 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17950 	return (B_FALSE);
17951 
17952 }
17953 
17954 /*
17955  * Process IP options in an inbound packet.  If an option affects the
17956  * effective destination address, return the next hop address via dstp.
17957  * Returns -1 if something fails in which case an ICMP error has been sent
17958  * and mp freed.
17959  */
17960 static int
17961 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17962     ip_stack_t *ipst)
17963 {
17964 	ipoptp_t	opts;
17965 	uchar_t		*opt;
17966 	uint8_t		optval;
17967 	uint8_t		optlen;
17968 	ipaddr_t	dst;
17969 	intptr_t	code = 0;
17970 	ire_t		*ire = NULL;
17971 	zoneid_t	zoneid;
17972 	ill_t		*ill;
17973 
17974 	ip2dbg(("ip_rput_options\n"));
17975 	dst = ipha->ipha_dst;
17976 	for (optval = ipoptp_first(&opts, ipha);
17977 	    optval != IPOPT_EOL;
17978 	    optval = ipoptp_next(&opts)) {
17979 		opt = opts.ipoptp_cur;
17980 		optlen = opts.ipoptp_len;
17981 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17982 		    optval, optlen));
17983 		/*
17984 		 * Note: we need to verify the checksum before we
17985 		 * modify anything thus this routine only extracts the next
17986 		 * hop dst from any source route.
17987 		 */
17988 		switch (optval) {
17989 			uint32_t off;
17990 		case IPOPT_SSRR:
17991 		case IPOPT_LSRR:
17992 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17993 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17994 			if (ire == NULL) {
17995 				if (optval == IPOPT_SSRR) {
17996 					ip1dbg(("ip_rput_options: not next"
17997 					    " strict source route 0x%x\n",
17998 					    ntohl(dst)));
17999 					code = (char *)&ipha->ipha_dst -
18000 					    (char *)ipha;
18001 					goto param_prob; /* RouterReq's */
18002 				}
18003 				ip2dbg(("ip_rput_options: "
18004 				    "not next source route 0x%x\n",
18005 				    ntohl(dst)));
18006 				break;
18007 			}
18008 			ire_refrele(ire);
18009 
18010 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18011 				ip1dbg((
18012 				    "ip_rput_options: bad option offset\n"));
18013 				code = (char *)&opt[IPOPT_OLEN] -
18014 				    (char *)ipha;
18015 				goto param_prob;
18016 			}
18017 			off = opt[IPOPT_OFFSET];
18018 			off--;
18019 		redo_srr:
18020 			if (optlen < IP_ADDR_LEN ||
18021 			    off > optlen - IP_ADDR_LEN) {
18022 				/* End of source route */
18023 				ip1dbg(("ip_rput_options: end of SR\n"));
18024 				break;
18025 			}
18026 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18027 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18028 			    ntohl(dst)));
18029 
18030 			/*
18031 			 * Check if our address is present more than
18032 			 * once as consecutive hops in source route.
18033 			 * XXX verify per-interface ip_forwarding
18034 			 * for source route?
18035 			 */
18036 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18037 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18038 
18039 			if (ire != NULL) {
18040 				ire_refrele(ire);
18041 				off += IP_ADDR_LEN;
18042 				goto redo_srr;
18043 			}
18044 
18045 			if (dst == htonl(INADDR_LOOPBACK)) {
18046 				ip1dbg(("ip_rput_options: loopback addr in "
18047 				    "source route!\n"));
18048 				goto bad_src_route;
18049 			}
18050 			/*
18051 			 * For strict: verify that dst is directly
18052 			 * reachable.
18053 			 */
18054 			if (optval == IPOPT_SSRR) {
18055 				ire = ire_ftable_lookup(dst, 0, 0,
18056 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18057 				    MBLK_GETLABEL(mp),
18058 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18059 				if (ire == NULL) {
18060 					ip1dbg(("ip_rput_options: SSRR not "
18061 					    "directly reachable: 0x%x\n",
18062 					    ntohl(dst)));
18063 					goto bad_src_route;
18064 				}
18065 				ire_refrele(ire);
18066 			}
18067 			/*
18068 			 * Defer update of the offset and the record route
18069 			 * until the packet is forwarded.
18070 			 */
18071 			break;
18072 		case IPOPT_RR:
18073 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18074 				ip1dbg((
18075 				    "ip_rput_options: bad option offset\n"));
18076 				code = (char *)&opt[IPOPT_OLEN] -
18077 				    (char *)ipha;
18078 				goto param_prob;
18079 			}
18080 			break;
18081 		case IPOPT_TS:
18082 			/*
18083 			 * Verify that length >= 5 and that there is either
18084 			 * room for another timestamp or that the overflow
18085 			 * counter is not maxed out.
18086 			 */
18087 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18088 			if (optlen < IPOPT_MINLEN_IT) {
18089 				goto param_prob;
18090 			}
18091 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18092 				ip1dbg((
18093 				    "ip_rput_options: bad option offset\n"));
18094 				code = (char *)&opt[IPOPT_OFFSET] -
18095 				    (char *)ipha;
18096 				goto param_prob;
18097 			}
18098 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18099 			case IPOPT_TS_TSONLY:
18100 				off = IPOPT_TS_TIMELEN;
18101 				break;
18102 			case IPOPT_TS_TSANDADDR:
18103 			case IPOPT_TS_PRESPEC:
18104 			case IPOPT_TS_PRESPEC_RFC791:
18105 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18106 				break;
18107 			default:
18108 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18109 				    (char *)ipha;
18110 				goto param_prob;
18111 			}
18112 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18113 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18114 				/*
18115 				 * No room and the overflow counter is 15
18116 				 * already.
18117 				 */
18118 				goto param_prob;
18119 			}
18120 			break;
18121 		}
18122 	}
18123 
18124 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18125 		*dstp = dst;
18126 		return (0);
18127 	}
18128 
18129 	ip1dbg(("ip_rput_options: error processing IP options."));
18130 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18131 
18132 param_prob:
18133 	q = WR(q);
18134 	if (q->q_next != NULL)
18135 		ill = q->q_ptr;
18136 	else
18137 		ill = NULL;
18138 
18139 	/* make sure we clear any indication of a hardware checksum */
18140 	DB_CKSUMFLAGS(mp) = 0;
18141 	/* Don't know whether this is for non-global or global/forwarding */
18142 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18143 	if (zoneid == ALL_ZONES)
18144 		freemsg(mp);
18145 	else
18146 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18147 	return (-1);
18148 
18149 bad_src_route:
18150 	q = WR(q);
18151 	if (q->q_next != NULL)
18152 		ill = q->q_ptr;
18153 	else
18154 		ill = NULL;
18155 
18156 	/* make sure we clear any indication of a hardware checksum */
18157 	DB_CKSUMFLAGS(mp) = 0;
18158 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18159 	if (zoneid == ALL_ZONES)
18160 		freemsg(mp);
18161 	else
18162 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18163 	return (-1);
18164 }
18165 
18166 /*
18167  * IP & ICMP info in >=14 msg's ...
18168  *  - ip fixed part (mib2_ip_t)
18169  *  - icmp fixed part (mib2_icmp_t)
18170  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18171  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18172  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18173  *  - ipRouteAttributeTable (ip 102)	labeled routes
18174  *  - ip multicast membership (ip_member_t)
18175  *  - ip multicast source filtering (ip_grpsrc_t)
18176  *  - igmp fixed part (struct igmpstat)
18177  *  - multicast routing stats (struct mrtstat)
18178  *  - multicast routing vifs (array of struct vifctl)
18179  *  - multicast routing routes (array of struct mfcctl)
18180  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18181  *					One per ill plus one generic
18182  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18183  *					One per ill plus one generic
18184  *  - ipv6RouteEntry			all IPv6 IREs
18185  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18186  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18187  *  - ipv6AddrEntry			all IPv6 ipifs
18188  *  - ipv6 multicast membership (ipv6_member_t)
18189  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18190  *
18191  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18192  *
18193  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18194  * already filled in by the caller.
18195  * Return value of 0 indicates that no messages were sent and caller
18196  * should free mpctl.
18197  */
18198 int
18199 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18200 {
18201 	ip_stack_t *ipst;
18202 	sctp_stack_t *sctps;
18203 
18204 
18205 	if (q->q_next != NULL) {
18206 		ipst = ILLQ_TO_IPST(q);
18207 	} else {
18208 		ipst = CONNQ_TO_IPST(q);
18209 	}
18210 	ASSERT(ipst != NULL);
18211 	sctps = ipst->ips_netstack->netstack_sctp;
18212 
18213 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18214 		return (0);
18215 	}
18216 
18217 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18218 	    ipst)) == NULL) {
18219 		return (1);
18220 	}
18221 
18222 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18223 		return (1);
18224 	}
18225 
18226 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18227 		return (1);
18228 	}
18229 
18230 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18231 		return (1);
18232 	}
18233 
18234 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18235 		return (1);
18236 	}
18237 
18238 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18239 		return (1);
18240 	}
18241 
18242 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18243 		return (1);
18244 	}
18245 
18246 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18247 		return (1);
18248 	}
18249 
18250 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18251 		return (1);
18252 	}
18253 
18254 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18255 		return (1);
18256 	}
18257 
18258 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18259 		return (1);
18260 	}
18261 
18262 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18263 		return (1);
18264 	}
18265 
18266 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18267 		return (1);
18268 	}
18269 
18270 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18271 		return (1);
18272 	}
18273 
18274 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18275 		return (1);
18276 	}
18277 
18278 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18279 	if (mpctl == NULL) {
18280 		return (1);
18281 	}
18282 
18283 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18284 		return (1);
18285 	}
18286 	freemsg(mpctl);
18287 	return (1);
18288 }
18289 
18290 
18291 /* Get global (legacy) IPv4 statistics */
18292 static mblk_t *
18293 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18294     ip_stack_t *ipst)
18295 {
18296 	mib2_ip_t		old_ip_mib;
18297 	struct opthdr		*optp;
18298 	mblk_t			*mp2ctl;
18299 
18300 	/*
18301 	 * make a copy of the original message
18302 	 */
18303 	mp2ctl = copymsg(mpctl);
18304 
18305 	/* fixed length IP structure... */
18306 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18307 	optp->level = MIB2_IP;
18308 	optp->name = 0;
18309 	SET_MIB(old_ip_mib.ipForwarding,
18310 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18311 	SET_MIB(old_ip_mib.ipDefaultTTL,
18312 	    (uint32_t)ipst->ips_ip_def_ttl);
18313 	SET_MIB(old_ip_mib.ipReasmTimeout,
18314 	    ipst->ips_ip_g_frag_timeout);
18315 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18316 	    sizeof (mib2_ipAddrEntry_t));
18317 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18318 	    sizeof (mib2_ipRouteEntry_t));
18319 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18320 	    sizeof (mib2_ipNetToMediaEntry_t));
18321 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18322 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18323 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18324 	    sizeof (mib2_ipAttributeEntry_t));
18325 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18326 
18327 	/*
18328 	 * Grab the statistics from the new IP MIB
18329 	 */
18330 	SET_MIB(old_ip_mib.ipInReceives,
18331 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18332 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18333 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18334 	SET_MIB(old_ip_mib.ipForwDatagrams,
18335 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18336 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18337 	    ipmib->ipIfStatsInUnknownProtos);
18338 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18339 	SET_MIB(old_ip_mib.ipInDelivers,
18340 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18341 	SET_MIB(old_ip_mib.ipOutRequests,
18342 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18343 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18344 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18345 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18346 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18347 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18348 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18349 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18350 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18351 
18352 	/* ipRoutingDiscards is not being used */
18353 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18354 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18355 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18356 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18357 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18358 	    ipmib->ipIfStatsReasmDuplicates);
18359 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18360 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18361 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18362 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18363 	SET_MIB(old_ip_mib.rawipInOverflows,
18364 	    ipmib->rawipIfStatsInOverflows);
18365 
18366 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18367 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18368 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18369 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18370 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18371 	    ipmib->ipIfStatsOutSwitchIPVersion);
18372 
18373 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18374 	    (int)sizeof (old_ip_mib))) {
18375 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18376 		    (uint_t)sizeof (old_ip_mib)));
18377 	}
18378 
18379 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18380 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18381 	    (int)optp->level, (int)optp->name, (int)optp->len));
18382 	qreply(q, mpctl);
18383 	return (mp2ctl);
18384 }
18385 
18386 /* Per interface IPv4 statistics */
18387 static mblk_t *
18388 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18389 {
18390 	struct opthdr		*optp;
18391 	mblk_t			*mp2ctl;
18392 	ill_t			*ill;
18393 	ill_walk_context_t	ctx;
18394 	mblk_t			*mp_tail = NULL;
18395 	mib2_ipIfStatsEntry_t	global_ip_mib;
18396 
18397 	/*
18398 	 * Make a copy of the original message
18399 	 */
18400 	mp2ctl = copymsg(mpctl);
18401 
18402 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18403 	optp->level = MIB2_IP;
18404 	optp->name = MIB2_IP_TRAFFIC_STATS;
18405 	/* Include "unknown interface" ip_mib */
18406 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18407 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18408 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18409 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18410 	    (ipst->ips_ip_g_forward ? 1 : 2));
18411 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18412 	    (uint32_t)ipst->ips_ip_def_ttl);
18413 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18414 	    sizeof (mib2_ipIfStatsEntry_t));
18415 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18416 	    sizeof (mib2_ipAddrEntry_t));
18417 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18418 	    sizeof (mib2_ipRouteEntry_t));
18419 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18420 	    sizeof (mib2_ipNetToMediaEntry_t));
18421 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18422 	    sizeof (ip_member_t));
18423 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18424 	    sizeof (ip_grpsrc_t));
18425 
18426 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18427 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18428 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18429 		    "failed to allocate %u bytes\n",
18430 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18431 	}
18432 
18433 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18434 
18435 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18436 	ill = ILL_START_WALK_V4(&ctx, ipst);
18437 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18438 		ill->ill_ip_mib->ipIfStatsIfIndex =
18439 		    ill->ill_phyint->phyint_ifindex;
18440 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18441 		    (ipst->ips_ip_g_forward ? 1 : 2));
18442 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18443 		    (uint32_t)ipst->ips_ip_def_ttl);
18444 
18445 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18446 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18447 		    (char *)ill->ill_ip_mib,
18448 		    (int)sizeof (*ill->ill_ip_mib))) {
18449 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18450 			    "failed to allocate %u bytes\n",
18451 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18452 		}
18453 	}
18454 	rw_exit(&ipst->ips_ill_g_lock);
18455 
18456 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18457 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18458 	    "level %d, name %d, len %d\n",
18459 	    (int)optp->level, (int)optp->name, (int)optp->len));
18460 	qreply(q, mpctl);
18461 
18462 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18463 }
18464 
18465 /* Global IPv4 ICMP statistics */
18466 static mblk_t *
18467 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18468 {
18469 	struct opthdr		*optp;
18470 	mblk_t			*mp2ctl;
18471 
18472 	/*
18473 	 * Make a copy of the original message
18474 	 */
18475 	mp2ctl = copymsg(mpctl);
18476 
18477 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18478 	optp->level = MIB2_ICMP;
18479 	optp->name = 0;
18480 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18481 	    (int)sizeof (ipst->ips_icmp_mib))) {
18482 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18483 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18484 	}
18485 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18486 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18487 	    (int)optp->level, (int)optp->name, (int)optp->len));
18488 	qreply(q, mpctl);
18489 	return (mp2ctl);
18490 }
18491 
18492 /* Global IPv4 IGMP statistics */
18493 static mblk_t *
18494 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18495 {
18496 	struct opthdr		*optp;
18497 	mblk_t			*mp2ctl;
18498 
18499 	/*
18500 	 * make a copy of the original message
18501 	 */
18502 	mp2ctl = copymsg(mpctl);
18503 
18504 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18505 	optp->level = EXPER_IGMP;
18506 	optp->name = 0;
18507 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18508 	    (int)sizeof (ipst->ips_igmpstat))) {
18509 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18510 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18511 	}
18512 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18513 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18514 	    (int)optp->level, (int)optp->name, (int)optp->len));
18515 	qreply(q, mpctl);
18516 	return (mp2ctl);
18517 }
18518 
18519 /* Global IPv4 Multicast Routing statistics */
18520 static mblk_t *
18521 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18522 {
18523 	struct opthdr		*optp;
18524 	mblk_t			*mp2ctl;
18525 
18526 	/*
18527 	 * make a copy of the original message
18528 	 */
18529 	mp2ctl = copymsg(mpctl);
18530 
18531 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18532 	optp->level = EXPER_DVMRP;
18533 	optp->name = 0;
18534 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18535 		ip0dbg(("ip_mroute_stats: failed\n"));
18536 	}
18537 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18538 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18539 	    (int)optp->level, (int)optp->name, (int)optp->len));
18540 	qreply(q, mpctl);
18541 	return (mp2ctl);
18542 }
18543 
18544 /* IPv4 address information */
18545 static mblk_t *
18546 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18547 {
18548 	struct opthdr		*optp;
18549 	mblk_t			*mp2ctl;
18550 	mblk_t			*mp_tail = NULL;
18551 	ill_t			*ill;
18552 	ipif_t			*ipif;
18553 	uint_t			bitval;
18554 	mib2_ipAddrEntry_t	mae;
18555 	zoneid_t		zoneid;
18556 	ill_walk_context_t ctx;
18557 
18558 	/*
18559 	 * make a copy of the original message
18560 	 */
18561 	mp2ctl = copymsg(mpctl);
18562 
18563 	/* ipAddrEntryTable */
18564 
18565 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18566 	optp->level = MIB2_IP;
18567 	optp->name = MIB2_IP_ADDR;
18568 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18569 
18570 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18571 	ill = ILL_START_WALK_V4(&ctx, ipst);
18572 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18573 		for (ipif = ill->ill_ipif; ipif != NULL;
18574 		    ipif = ipif->ipif_next) {
18575 			if (ipif->ipif_zoneid != zoneid &&
18576 			    ipif->ipif_zoneid != ALL_ZONES)
18577 				continue;
18578 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18579 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18580 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18581 
18582 			(void) ipif_get_name(ipif,
18583 			    mae.ipAdEntIfIndex.o_bytes,
18584 			    OCTET_LENGTH);
18585 			mae.ipAdEntIfIndex.o_length =
18586 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18587 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18588 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18589 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18590 			mae.ipAdEntInfo.ae_subnet_len =
18591 			    ip_mask_to_plen(ipif->ipif_net_mask);
18592 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18593 			for (bitval = 1;
18594 			    bitval &&
18595 			    !(bitval & ipif->ipif_brd_addr);
18596 			    bitval <<= 1)
18597 				noop;
18598 			mae.ipAdEntBcastAddr = bitval;
18599 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18600 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18601 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18602 			mae.ipAdEntInfo.ae_broadcast_addr =
18603 			    ipif->ipif_brd_addr;
18604 			mae.ipAdEntInfo.ae_pp_dst_addr =
18605 			    ipif->ipif_pp_dst_addr;
18606 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18607 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18608 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18609 
18610 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18611 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18612 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18613 				    "allocate %u bytes\n",
18614 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18615 			}
18616 		}
18617 	}
18618 	rw_exit(&ipst->ips_ill_g_lock);
18619 
18620 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18621 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18622 	    (int)optp->level, (int)optp->name, (int)optp->len));
18623 	qreply(q, mpctl);
18624 	return (mp2ctl);
18625 }
18626 
18627 /* IPv6 address information */
18628 static mblk_t *
18629 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18630 {
18631 	struct opthdr		*optp;
18632 	mblk_t			*mp2ctl;
18633 	mblk_t			*mp_tail = NULL;
18634 	ill_t			*ill;
18635 	ipif_t			*ipif;
18636 	mib2_ipv6AddrEntry_t	mae6;
18637 	zoneid_t		zoneid;
18638 	ill_walk_context_t	ctx;
18639 
18640 	/*
18641 	 * make a copy of the original message
18642 	 */
18643 	mp2ctl = copymsg(mpctl);
18644 
18645 	/* ipv6AddrEntryTable */
18646 
18647 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18648 	optp->level = MIB2_IP6;
18649 	optp->name = MIB2_IP6_ADDR;
18650 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18651 
18652 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18653 	ill = ILL_START_WALK_V6(&ctx, ipst);
18654 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18655 		for (ipif = ill->ill_ipif; ipif != NULL;
18656 		    ipif = ipif->ipif_next) {
18657 			if (ipif->ipif_zoneid != zoneid &&
18658 			    ipif->ipif_zoneid != ALL_ZONES)
18659 				continue;
18660 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18661 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18662 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18663 
18664 			(void) ipif_get_name(ipif,
18665 			    mae6.ipv6AddrIfIndex.o_bytes,
18666 			    OCTET_LENGTH);
18667 			mae6.ipv6AddrIfIndex.o_length =
18668 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18669 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18670 			mae6.ipv6AddrPfxLength =
18671 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18672 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18673 			mae6.ipv6AddrInfo.ae_subnet_len =
18674 			    mae6.ipv6AddrPfxLength;
18675 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18676 
18677 			/* Type: stateless(1), stateful(2), unknown(3) */
18678 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18679 				mae6.ipv6AddrType = 1;
18680 			else
18681 				mae6.ipv6AddrType = 2;
18682 			/* Anycast: true(1), false(2) */
18683 			if (ipif->ipif_flags & IPIF_ANYCAST)
18684 				mae6.ipv6AddrAnycastFlag = 1;
18685 			else
18686 				mae6.ipv6AddrAnycastFlag = 2;
18687 
18688 			/*
18689 			 * Address status: preferred(1), deprecated(2),
18690 			 * invalid(3), inaccessible(4), unknown(5)
18691 			 */
18692 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18693 				mae6.ipv6AddrStatus = 3;
18694 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18695 				mae6.ipv6AddrStatus = 2;
18696 			else
18697 				mae6.ipv6AddrStatus = 1;
18698 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18699 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18700 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18701 			    ipif->ipif_v6pp_dst_addr;
18702 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18703 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18704 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18705 			mae6.ipv6AddrIdentifier = ill->ill_token;
18706 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18707 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18708 			mae6.ipv6AddrRetransmitTime =
18709 			    ill->ill_reachable_retrans_time;
18710 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18711 			    (char *)&mae6,
18712 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18713 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18714 				    "allocate %u bytes\n",
18715 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18716 			}
18717 		}
18718 	}
18719 	rw_exit(&ipst->ips_ill_g_lock);
18720 
18721 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18722 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18723 	    (int)optp->level, (int)optp->name, (int)optp->len));
18724 	qreply(q, mpctl);
18725 	return (mp2ctl);
18726 }
18727 
18728 /* IPv4 multicast group membership. */
18729 static mblk_t *
18730 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18731 {
18732 	struct opthdr		*optp;
18733 	mblk_t			*mp2ctl;
18734 	ill_t			*ill;
18735 	ipif_t			*ipif;
18736 	ilm_t			*ilm;
18737 	ip_member_t		ipm;
18738 	mblk_t			*mp_tail = NULL;
18739 	ill_walk_context_t	ctx;
18740 	zoneid_t		zoneid;
18741 
18742 	/*
18743 	 * make a copy of the original message
18744 	 */
18745 	mp2ctl = copymsg(mpctl);
18746 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18747 
18748 	/* ipGroupMember table */
18749 	optp = (struct opthdr *)&mpctl->b_rptr[
18750 	    sizeof (struct T_optmgmt_ack)];
18751 	optp->level = MIB2_IP;
18752 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18753 
18754 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18755 	ill = ILL_START_WALK_V4(&ctx, ipst);
18756 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18757 		ILM_WALKER_HOLD(ill);
18758 		for (ipif = ill->ill_ipif; ipif != NULL;
18759 		    ipif = ipif->ipif_next) {
18760 			if (ipif->ipif_zoneid != zoneid &&
18761 			    ipif->ipif_zoneid != ALL_ZONES)
18762 				continue;	/* not this zone */
18763 			(void) ipif_get_name(ipif,
18764 			    ipm.ipGroupMemberIfIndex.o_bytes,
18765 			    OCTET_LENGTH);
18766 			ipm.ipGroupMemberIfIndex.o_length =
18767 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18768 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18769 				ASSERT(ilm->ilm_ipif != NULL);
18770 				ASSERT(ilm->ilm_ill == NULL);
18771 				if (ilm->ilm_ipif != ipif)
18772 					continue;
18773 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18774 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18775 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18776 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18777 				    (char *)&ipm, (int)sizeof (ipm))) {
18778 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18779 					    "failed to allocate %u bytes\n",
18780 					    (uint_t)sizeof (ipm)));
18781 				}
18782 			}
18783 		}
18784 		ILM_WALKER_RELE(ill);
18785 	}
18786 	rw_exit(&ipst->ips_ill_g_lock);
18787 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18788 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18789 	    (int)optp->level, (int)optp->name, (int)optp->len));
18790 	qreply(q, mpctl);
18791 	return (mp2ctl);
18792 }
18793 
18794 /* IPv6 multicast group membership. */
18795 static mblk_t *
18796 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18797 {
18798 	struct opthdr		*optp;
18799 	mblk_t			*mp2ctl;
18800 	ill_t			*ill;
18801 	ilm_t			*ilm;
18802 	ipv6_member_t		ipm6;
18803 	mblk_t			*mp_tail = NULL;
18804 	ill_walk_context_t	ctx;
18805 	zoneid_t		zoneid;
18806 
18807 	/*
18808 	 * make a copy of the original message
18809 	 */
18810 	mp2ctl = copymsg(mpctl);
18811 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18812 
18813 	/* ip6GroupMember table */
18814 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18815 	optp->level = MIB2_IP6;
18816 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18817 
18818 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18819 	ill = ILL_START_WALK_V6(&ctx, ipst);
18820 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18821 		ILM_WALKER_HOLD(ill);
18822 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18823 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18824 			ASSERT(ilm->ilm_ipif == NULL);
18825 			ASSERT(ilm->ilm_ill != NULL);
18826 			if (ilm->ilm_zoneid != zoneid)
18827 				continue;	/* not this zone */
18828 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18829 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18830 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18831 			if (!snmp_append_data2(mpctl->b_cont,
18832 			    &mp_tail,
18833 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18834 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18835 				    "failed to allocate %u bytes\n",
18836 				    (uint_t)sizeof (ipm6)));
18837 			}
18838 		}
18839 		ILM_WALKER_RELE(ill);
18840 	}
18841 	rw_exit(&ipst->ips_ill_g_lock);
18842 
18843 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18844 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18845 	    (int)optp->level, (int)optp->name, (int)optp->len));
18846 	qreply(q, mpctl);
18847 	return (mp2ctl);
18848 }
18849 
18850 /* IP multicast filtered sources */
18851 static mblk_t *
18852 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18853 {
18854 	struct opthdr		*optp;
18855 	mblk_t			*mp2ctl;
18856 	ill_t			*ill;
18857 	ipif_t			*ipif;
18858 	ilm_t			*ilm;
18859 	ip_grpsrc_t		ips;
18860 	mblk_t			*mp_tail = NULL;
18861 	ill_walk_context_t	ctx;
18862 	zoneid_t		zoneid;
18863 	int			i;
18864 	slist_t			*sl;
18865 
18866 	/*
18867 	 * make a copy of the original message
18868 	 */
18869 	mp2ctl = copymsg(mpctl);
18870 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18871 
18872 	/* ipGroupSource table */
18873 	optp = (struct opthdr *)&mpctl->b_rptr[
18874 	    sizeof (struct T_optmgmt_ack)];
18875 	optp->level = MIB2_IP;
18876 	optp->name = EXPER_IP_GROUP_SOURCES;
18877 
18878 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18879 	ill = ILL_START_WALK_V4(&ctx, ipst);
18880 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18881 		ILM_WALKER_HOLD(ill);
18882 		for (ipif = ill->ill_ipif; ipif != NULL;
18883 		    ipif = ipif->ipif_next) {
18884 			if (ipif->ipif_zoneid != zoneid)
18885 				continue;	/* not this zone */
18886 			(void) ipif_get_name(ipif,
18887 			    ips.ipGroupSourceIfIndex.o_bytes,
18888 			    OCTET_LENGTH);
18889 			ips.ipGroupSourceIfIndex.o_length =
18890 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18891 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18892 				ASSERT(ilm->ilm_ipif != NULL);
18893 				ASSERT(ilm->ilm_ill == NULL);
18894 				sl = ilm->ilm_filter;
18895 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18896 					continue;
18897 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18898 				for (i = 0; i < sl->sl_numsrc; i++) {
18899 					if (!IN6_IS_ADDR_V4MAPPED(
18900 					    &sl->sl_addr[i]))
18901 						continue;
18902 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18903 					    ips.ipGroupSourceAddress);
18904 					if (snmp_append_data2(mpctl->b_cont,
18905 					    &mp_tail, (char *)&ips,
18906 					    (int)sizeof (ips)) == 0) {
18907 						ip1dbg(("ip_snmp_get_mib2_"
18908 						    "ip_group_src: failed to "
18909 						    "allocate %u bytes\n",
18910 						    (uint_t)sizeof (ips)));
18911 					}
18912 				}
18913 			}
18914 		}
18915 		ILM_WALKER_RELE(ill);
18916 	}
18917 	rw_exit(&ipst->ips_ill_g_lock);
18918 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18919 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18920 	    (int)optp->level, (int)optp->name, (int)optp->len));
18921 	qreply(q, mpctl);
18922 	return (mp2ctl);
18923 }
18924 
18925 /* IPv6 multicast filtered sources. */
18926 static mblk_t *
18927 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18928 {
18929 	struct opthdr		*optp;
18930 	mblk_t			*mp2ctl;
18931 	ill_t			*ill;
18932 	ilm_t			*ilm;
18933 	ipv6_grpsrc_t		ips6;
18934 	mblk_t			*mp_tail = NULL;
18935 	ill_walk_context_t	ctx;
18936 	zoneid_t		zoneid;
18937 	int			i;
18938 	slist_t			*sl;
18939 
18940 	/*
18941 	 * make a copy of the original message
18942 	 */
18943 	mp2ctl = copymsg(mpctl);
18944 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18945 
18946 	/* ip6GroupMember table */
18947 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18948 	optp->level = MIB2_IP6;
18949 	optp->name = EXPER_IP6_GROUP_SOURCES;
18950 
18951 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18952 	ill = ILL_START_WALK_V6(&ctx, ipst);
18953 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18954 		ILM_WALKER_HOLD(ill);
18955 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18956 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18957 			ASSERT(ilm->ilm_ipif == NULL);
18958 			ASSERT(ilm->ilm_ill != NULL);
18959 			sl = ilm->ilm_filter;
18960 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18961 				continue;
18962 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18963 			for (i = 0; i < sl->sl_numsrc; i++) {
18964 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18965 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18966 				    (char *)&ips6, (int)sizeof (ips6))) {
18967 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18968 					    "group_src: failed to allocate "
18969 					    "%u bytes\n",
18970 					    (uint_t)sizeof (ips6)));
18971 				}
18972 			}
18973 		}
18974 		ILM_WALKER_RELE(ill);
18975 	}
18976 	rw_exit(&ipst->ips_ill_g_lock);
18977 
18978 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18979 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18980 	    (int)optp->level, (int)optp->name, (int)optp->len));
18981 	qreply(q, mpctl);
18982 	return (mp2ctl);
18983 }
18984 
18985 /* Multicast routing virtual interface table. */
18986 static mblk_t *
18987 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18988 {
18989 	struct opthdr		*optp;
18990 	mblk_t			*mp2ctl;
18991 
18992 	/*
18993 	 * make a copy of the original message
18994 	 */
18995 	mp2ctl = copymsg(mpctl);
18996 
18997 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18998 	optp->level = EXPER_DVMRP;
18999 	optp->name = EXPER_DVMRP_VIF;
19000 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
19001 		ip0dbg(("ip_mroute_vif: failed\n"));
19002 	}
19003 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19004 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
19005 	    (int)optp->level, (int)optp->name, (int)optp->len));
19006 	qreply(q, mpctl);
19007 	return (mp2ctl);
19008 }
19009 
19010 /* Multicast routing table. */
19011 static mblk_t *
19012 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19013 {
19014 	struct opthdr		*optp;
19015 	mblk_t			*mp2ctl;
19016 
19017 	/*
19018 	 * make a copy of the original message
19019 	 */
19020 	mp2ctl = copymsg(mpctl);
19021 
19022 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19023 	optp->level = EXPER_DVMRP;
19024 	optp->name = EXPER_DVMRP_MRT;
19025 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19026 		ip0dbg(("ip_mroute_mrt: failed\n"));
19027 	}
19028 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19029 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19030 	    (int)optp->level, (int)optp->name, (int)optp->len));
19031 	qreply(q, mpctl);
19032 	return (mp2ctl);
19033 }
19034 
19035 /*
19036  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19037  * in one IRE walk.
19038  */
19039 static mblk_t *
19040 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19041 {
19042 	struct opthdr	*optp;
19043 	mblk_t		*mp2ctl;	/* Returned */
19044 	mblk_t		*mp3ctl;	/* nettomedia */
19045 	mblk_t		*mp4ctl;	/* routeattrs */
19046 	iproutedata_t	ird;
19047 	zoneid_t	zoneid;
19048 
19049 	/*
19050 	 * make copies of the original message
19051 	 *	- mp2ctl is returned unchanged to the caller for his use
19052 	 *	- mpctl is sent upstream as ipRouteEntryTable
19053 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19054 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19055 	 */
19056 	mp2ctl = copymsg(mpctl);
19057 	mp3ctl = copymsg(mpctl);
19058 	mp4ctl = copymsg(mpctl);
19059 	if (mp3ctl == NULL || mp4ctl == NULL) {
19060 		freemsg(mp4ctl);
19061 		freemsg(mp3ctl);
19062 		freemsg(mp2ctl);
19063 		freemsg(mpctl);
19064 		return (NULL);
19065 	}
19066 
19067 	bzero(&ird, sizeof (ird));
19068 
19069 	ird.ird_route.lp_head = mpctl->b_cont;
19070 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19071 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19072 
19073 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19074 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19075 	if (zoneid == GLOBAL_ZONEID) {
19076 		/*
19077 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19078 		 * requires the sys_net_config or sys_ip_config privilege,
19079 		 * it can only run in the global zone or an exclusive-IP zone,
19080 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19081 		 */
19082 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19083 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19084 	}
19085 
19086 	/* ipRouteEntryTable in mpctl */
19087 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19088 	optp->level = MIB2_IP;
19089 	optp->name = MIB2_IP_ROUTE;
19090 	optp->len = msgdsize(ird.ird_route.lp_head);
19091 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19092 	    (int)optp->level, (int)optp->name, (int)optp->len));
19093 	qreply(q, mpctl);
19094 
19095 	/* ipNetToMediaEntryTable in mp3ctl */
19096 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19097 	optp->level = MIB2_IP;
19098 	optp->name = MIB2_IP_MEDIA;
19099 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19100 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19101 	    (int)optp->level, (int)optp->name, (int)optp->len));
19102 	qreply(q, mp3ctl);
19103 
19104 	/* ipRouteAttributeTable in mp4ctl */
19105 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19106 	optp->level = MIB2_IP;
19107 	optp->name = EXPER_IP_RTATTR;
19108 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19109 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19110 	    (int)optp->level, (int)optp->name, (int)optp->len));
19111 	if (optp->len == 0)
19112 		freemsg(mp4ctl);
19113 	else
19114 		qreply(q, mp4ctl);
19115 
19116 	return (mp2ctl);
19117 }
19118 
19119 /*
19120  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19121  * ipv6NetToMediaEntryTable in an NDP walk.
19122  */
19123 static mblk_t *
19124 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19125 {
19126 	struct opthdr	*optp;
19127 	mblk_t		*mp2ctl;	/* Returned */
19128 	mblk_t		*mp3ctl;	/* nettomedia */
19129 	mblk_t		*mp4ctl;	/* routeattrs */
19130 	iproutedata_t	ird;
19131 	zoneid_t	zoneid;
19132 
19133 	/*
19134 	 * make copies of the original message
19135 	 *	- mp2ctl is returned unchanged to the caller for his use
19136 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19137 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19138 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19139 	 */
19140 	mp2ctl = copymsg(mpctl);
19141 	mp3ctl = copymsg(mpctl);
19142 	mp4ctl = copymsg(mpctl);
19143 	if (mp3ctl == NULL || mp4ctl == NULL) {
19144 		freemsg(mp4ctl);
19145 		freemsg(mp3ctl);
19146 		freemsg(mp2ctl);
19147 		freemsg(mpctl);
19148 		return (NULL);
19149 	}
19150 
19151 	bzero(&ird, sizeof (ird));
19152 
19153 	ird.ird_route.lp_head = mpctl->b_cont;
19154 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19155 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19156 
19157 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19158 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19159 
19160 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19161 	optp->level = MIB2_IP6;
19162 	optp->name = MIB2_IP6_ROUTE;
19163 	optp->len = msgdsize(ird.ird_route.lp_head);
19164 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19165 	    (int)optp->level, (int)optp->name, (int)optp->len));
19166 	qreply(q, mpctl);
19167 
19168 	/* ipv6NetToMediaEntryTable in mp3ctl */
19169 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19170 
19171 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19172 	optp->level = MIB2_IP6;
19173 	optp->name = MIB2_IP6_MEDIA;
19174 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19175 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19176 	    (int)optp->level, (int)optp->name, (int)optp->len));
19177 	qreply(q, mp3ctl);
19178 
19179 	/* ipv6RouteAttributeTable in mp4ctl */
19180 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19181 	optp->level = MIB2_IP6;
19182 	optp->name = EXPER_IP_RTATTR;
19183 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19184 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19185 	    (int)optp->level, (int)optp->name, (int)optp->len));
19186 	if (optp->len == 0)
19187 		freemsg(mp4ctl);
19188 	else
19189 		qreply(q, mp4ctl);
19190 
19191 	return (mp2ctl);
19192 }
19193 
19194 /*
19195  * IPv6 mib: One per ill
19196  */
19197 static mblk_t *
19198 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19199 {
19200 	struct opthdr		*optp;
19201 	mblk_t			*mp2ctl;
19202 	ill_t			*ill;
19203 	ill_walk_context_t	ctx;
19204 	mblk_t			*mp_tail = NULL;
19205 
19206 	/*
19207 	 * Make a copy of the original message
19208 	 */
19209 	mp2ctl = copymsg(mpctl);
19210 
19211 	/* fixed length IPv6 structure ... */
19212 
19213 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19214 	optp->level = MIB2_IP6;
19215 	optp->name = 0;
19216 	/* Include "unknown interface" ip6_mib */
19217 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19218 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19219 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19220 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19221 	    ipst->ips_ipv6_forward ? 1 : 2);
19222 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19223 	    ipst->ips_ipv6_def_hops);
19224 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19225 	    sizeof (mib2_ipIfStatsEntry_t));
19226 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19227 	    sizeof (mib2_ipv6AddrEntry_t));
19228 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19229 	    sizeof (mib2_ipv6RouteEntry_t));
19230 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19231 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19232 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19233 	    sizeof (ipv6_member_t));
19234 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19235 	    sizeof (ipv6_grpsrc_t));
19236 
19237 	/*
19238 	 * Synchronize 64- and 32-bit counters
19239 	 */
19240 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19241 	    ipIfStatsHCInReceives);
19242 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19243 	    ipIfStatsHCInDelivers);
19244 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19245 	    ipIfStatsHCOutRequests);
19246 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19247 	    ipIfStatsHCOutForwDatagrams);
19248 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19249 	    ipIfStatsHCOutMcastPkts);
19250 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19251 	    ipIfStatsHCInMcastPkts);
19252 
19253 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19254 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19255 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19256 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19257 	}
19258 
19259 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19260 	ill = ILL_START_WALK_V6(&ctx, ipst);
19261 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19262 		ill->ill_ip_mib->ipIfStatsIfIndex =
19263 		    ill->ill_phyint->phyint_ifindex;
19264 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19265 		    ipst->ips_ipv6_forward ? 1 : 2);
19266 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19267 		    ill->ill_max_hops);
19268 
19269 		/*
19270 		 * Synchronize 64- and 32-bit counters
19271 		 */
19272 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19273 		    ipIfStatsHCInReceives);
19274 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19275 		    ipIfStatsHCInDelivers);
19276 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19277 		    ipIfStatsHCOutRequests);
19278 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19279 		    ipIfStatsHCOutForwDatagrams);
19280 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19281 		    ipIfStatsHCOutMcastPkts);
19282 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19283 		    ipIfStatsHCInMcastPkts);
19284 
19285 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19286 		    (char *)ill->ill_ip_mib,
19287 		    (int)sizeof (*ill->ill_ip_mib))) {
19288 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19289 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19290 		}
19291 	}
19292 	rw_exit(&ipst->ips_ill_g_lock);
19293 
19294 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19295 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19296 	    (int)optp->level, (int)optp->name, (int)optp->len));
19297 	qreply(q, mpctl);
19298 	return (mp2ctl);
19299 }
19300 
19301 /*
19302  * ICMPv6 mib: One per ill
19303  */
19304 static mblk_t *
19305 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19306 {
19307 	struct opthdr		*optp;
19308 	mblk_t			*mp2ctl;
19309 	ill_t			*ill;
19310 	ill_walk_context_t	ctx;
19311 	mblk_t			*mp_tail = NULL;
19312 	/*
19313 	 * Make a copy of the original message
19314 	 */
19315 	mp2ctl = copymsg(mpctl);
19316 
19317 	/* fixed length ICMPv6 structure ... */
19318 
19319 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19320 	optp->level = MIB2_ICMP6;
19321 	optp->name = 0;
19322 	/* Include "unknown interface" icmp6_mib */
19323 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19324 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19325 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19326 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19327 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19328 	    (char *)&ipst->ips_icmp6_mib,
19329 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19330 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19331 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19332 	}
19333 
19334 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19335 	ill = ILL_START_WALK_V6(&ctx, ipst);
19336 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19337 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19338 		    ill->ill_phyint->phyint_ifindex;
19339 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19340 		    (char *)ill->ill_icmp6_mib,
19341 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19342 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19343 			    "%u bytes\n",
19344 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19345 		}
19346 	}
19347 	rw_exit(&ipst->ips_ill_g_lock);
19348 
19349 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19350 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19351 	    (int)optp->level, (int)optp->name, (int)optp->len));
19352 	qreply(q, mpctl);
19353 	return (mp2ctl);
19354 }
19355 
19356 /*
19357  * ire_walk routine to create both ipRouteEntryTable and
19358  * ipRouteAttributeTable in one IRE walk
19359  */
19360 static void
19361 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19362 {
19363 	ill_t				*ill;
19364 	ipif_t				*ipif;
19365 	mib2_ipRouteEntry_t		*re;
19366 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19367 	ipaddr_t			gw_addr;
19368 	tsol_ire_gw_secattr_t		*attrp;
19369 	tsol_gc_t			*gc = NULL;
19370 	tsol_gcgrp_t			*gcgrp = NULL;
19371 	uint_t				sacnt = 0;
19372 	int				i;
19373 
19374 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19375 
19376 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19377 		return;
19378 
19379 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19380 		mutex_enter(&attrp->igsa_lock);
19381 		if ((gc = attrp->igsa_gc) != NULL) {
19382 			gcgrp = gc->gc_grp;
19383 			ASSERT(gcgrp != NULL);
19384 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19385 			sacnt = 1;
19386 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19387 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19388 			gc = gcgrp->gcgrp_head;
19389 			sacnt = gcgrp->gcgrp_count;
19390 		}
19391 		mutex_exit(&attrp->igsa_lock);
19392 
19393 		/* do nothing if there's no gc to report */
19394 		if (gc == NULL) {
19395 			ASSERT(sacnt == 0);
19396 			if (gcgrp != NULL) {
19397 				/* we might as well drop the lock now */
19398 				rw_exit(&gcgrp->gcgrp_rwlock);
19399 				gcgrp = NULL;
19400 			}
19401 			attrp = NULL;
19402 		}
19403 
19404 		ASSERT(gc == NULL || (gcgrp != NULL &&
19405 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19406 	}
19407 	ASSERT(sacnt == 0 || gc != NULL);
19408 
19409 	if (sacnt != 0 &&
19410 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19411 		kmem_free(re, sizeof (*re));
19412 		rw_exit(&gcgrp->gcgrp_rwlock);
19413 		return;
19414 	}
19415 
19416 	/*
19417 	 * Return all IRE types for route table... let caller pick and choose
19418 	 */
19419 	re->ipRouteDest = ire->ire_addr;
19420 	ipif = ire->ire_ipif;
19421 	re->ipRouteIfIndex.o_length = 0;
19422 	if (ire->ire_type == IRE_CACHE) {
19423 		ill = (ill_t *)ire->ire_stq->q_ptr;
19424 		re->ipRouteIfIndex.o_length =
19425 		    ill->ill_name_length == 0 ? 0 :
19426 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19427 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19428 		    re->ipRouteIfIndex.o_length);
19429 	} else if (ipif != NULL) {
19430 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19431 		    OCTET_LENGTH);
19432 		re->ipRouteIfIndex.o_length =
19433 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19434 	}
19435 	re->ipRouteMetric1 = -1;
19436 	re->ipRouteMetric2 = -1;
19437 	re->ipRouteMetric3 = -1;
19438 	re->ipRouteMetric4 = -1;
19439 
19440 	gw_addr = ire->ire_gateway_addr;
19441 
19442 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19443 		re->ipRouteNextHop = ire->ire_src_addr;
19444 	else
19445 		re->ipRouteNextHop = gw_addr;
19446 	/* indirect(4), direct(3), or invalid(2) */
19447 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19448 		re->ipRouteType = 2;
19449 	else
19450 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19451 	re->ipRouteProto = -1;
19452 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19453 	re->ipRouteMask = ire->ire_mask;
19454 	re->ipRouteMetric5 = -1;
19455 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19456 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19457 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19458 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19459 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19460 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19461 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19462 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19463 	re->ipRouteInfo.re_in_ill.o_length = 0;
19464 
19465 	if (ire->ire_flags & RTF_DYNAMIC) {
19466 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19467 	} else {
19468 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19469 	}
19470 
19471 	if (ire->ire_in_ill != NULL) {
19472 		re->ipRouteInfo.re_in_ill.o_length =
19473 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19474 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19475 		bcopy(ire->ire_in_ill->ill_name,
19476 		    re->ipRouteInfo.re_in_ill.o_bytes,
19477 		    re->ipRouteInfo.re_in_ill.o_length);
19478 	}
19479 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19480 
19481 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19482 	    (char *)re, (int)sizeof (*re))) {
19483 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19484 		    (uint_t)sizeof (*re)));
19485 	}
19486 
19487 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19488 		iaeptr->iae_routeidx = ird->ird_idx;
19489 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19490 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19491 	}
19492 
19493 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19494 	    (char *)iae, sacnt * sizeof (*iae))) {
19495 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19496 		    (unsigned)(sacnt * sizeof (*iae))));
19497 	}
19498 
19499 	/* bump route index for next pass */
19500 	ird->ird_idx++;
19501 
19502 	kmem_free(re, sizeof (*re));
19503 	if (sacnt != 0)
19504 		kmem_free(iae, sacnt * sizeof (*iae));
19505 
19506 	if (gcgrp != NULL)
19507 		rw_exit(&gcgrp->gcgrp_rwlock);
19508 }
19509 
19510 /*
19511  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19512  */
19513 static void
19514 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19515 {
19516 	ill_t				*ill;
19517 	ipif_t				*ipif;
19518 	mib2_ipv6RouteEntry_t		*re;
19519 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19520 	in6_addr_t			gw_addr_v6;
19521 	tsol_ire_gw_secattr_t		*attrp;
19522 	tsol_gc_t			*gc = NULL;
19523 	tsol_gcgrp_t			*gcgrp = NULL;
19524 	uint_t				sacnt = 0;
19525 	int				i;
19526 
19527 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19528 
19529 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19530 		return;
19531 
19532 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19533 		mutex_enter(&attrp->igsa_lock);
19534 		if ((gc = attrp->igsa_gc) != NULL) {
19535 			gcgrp = gc->gc_grp;
19536 			ASSERT(gcgrp != NULL);
19537 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19538 			sacnt = 1;
19539 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19540 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19541 			gc = gcgrp->gcgrp_head;
19542 			sacnt = gcgrp->gcgrp_count;
19543 		}
19544 		mutex_exit(&attrp->igsa_lock);
19545 
19546 		/* do nothing if there's no gc to report */
19547 		if (gc == NULL) {
19548 			ASSERT(sacnt == 0);
19549 			if (gcgrp != NULL) {
19550 				/* we might as well drop the lock now */
19551 				rw_exit(&gcgrp->gcgrp_rwlock);
19552 				gcgrp = NULL;
19553 			}
19554 			attrp = NULL;
19555 		}
19556 
19557 		ASSERT(gc == NULL || (gcgrp != NULL &&
19558 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19559 	}
19560 	ASSERT(sacnt == 0 || gc != NULL);
19561 
19562 	if (sacnt != 0 &&
19563 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19564 		kmem_free(re, sizeof (*re));
19565 		rw_exit(&gcgrp->gcgrp_rwlock);
19566 		return;
19567 	}
19568 
19569 	/*
19570 	 * Return all IRE types for route table... let caller pick and choose
19571 	 */
19572 	re->ipv6RouteDest = ire->ire_addr_v6;
19573 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19574 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19575 	re->ipv6RouteIfIndex.o_length = 0;
19576 	ipif = ire->ire_ipif;
19577 	if (ire->ire_type == IRE_CACHE) {
19578 		ill = (ill_t *)ire->ire_stq->q_ptr;
19579 		re->ipv6RouteIfIndex.o_length =
19580 		    ill->ill_name_length == 0 ? 0 :
19581 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19582 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19583 		    re->ipv6RouteIfIndex.o_length);
19584 	} else if (ipif != NULL) {
19585 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19586 		    OCTET_LENGTH);
19587 		re->ipv6RouteIfIndex.o_length =
19588 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19589 	}
19590 
19591 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19592 
19593 	mutex_enter(&ire->ire_lock);
19594 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19595 	mutex_exit(&ire->ire_lock);
19596 
19597 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19598 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19599 	else
19600 		re->ipv6RouteNextHop = gw_addr_v6;
19601 
19602 	/* remote(4), local(3), or discard(2) */
19603 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19604 		re->ipv6RouteType = 2;
19605 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19606 		re->ipv6RouteType = 3;
19607 	else
19608 		re->ipv6RouteType = 4;
19609 
19610 	re->ipv6RouteProtocol	= -1;
19611 	re->ipv6RoutePolicy	= 0;
19612 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19613 	re->ipv6RouteNextHopRDI	= 0;
19614 	re->ipv6RouteWeight	= 0;
19615 	re->ipv6RouteMetric	= 0;
19616 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19617 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19618 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19619 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19620 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19621 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19622 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19623 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19624 
19625 	if (ire->ire_flags & RTF_DYNAMIC) {
19626 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19627 	} else {
19628 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19629 	}
19630 
19631 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19632 	    (char *)re, (int)sizeof (*re))) {
19633 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19634 		    (uint_t)sizeof (*re)));
19635 	}
19636 
19637 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19638 		iaeptr->iae_routeidx = ird->ird_idx;
19639 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19640 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19641 	}
19642 
19643 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19644 	    (char *)iae, sacnt * sizeof (*iae))) {
19645 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19646 		    (unsigned)(sacnt * sizeof (*iae))));
19647 	}
19648 
19649 	/* bump route index for next pass */
19650 	ird->ird_idx++;
19651 
19652 	kmem_free(re, sizeof (*re));
19653 	if (sacnt != 0)
19654 		kmem_free(iae, sacnt * sizeof (*iae));
19655 
19656 	if (gcgrp != NULL)
19657 		rw_exit(&gcgrp->gcgrp_rwlock);
19658 }
19659 
19660 /*
19661  * ndp_walk routine to create ipv6NetToMediaEntryTable
19662  */
19663 static int
19664 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19665 {
19666 	ill_t				*ill;
19667 	mib2_ipv6NetToMediaEntry_t	ntme;
19668 	dl_unitdata_req_t		*dl;
19669 
19670 	ill = nce->nce_ill;
19671 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19672 		return (0);
19673 
19674 	/*
19675 	 * Neighbor cache entry attached to IRE with on-link
19676 	 * destination.
19677 	 */
19678 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19679 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19680 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19681 	    (nce->nce_res_mp != NULL)) {
19682 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19683 		ntme.ipv6NetToMediaPhysAddress.o_length =
19684 		    dl->dl_dest_addr_length;
19685 	} else {
19686 		ntme.ipv6NetToMediaPhysAddress.o_length =
19687 		    ill->ill_phys_addr_length;
19688 	}
19689 	if (nce->nce_res_mp != NULL) {
19690 		bcopy((char *)nce->nce_res_mp->b_rptr +
19691 		    NCE_LL_ADDR_OFFSET(ill),
19692 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19693 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19694 	} else {
19695 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19696 		    ill->ill_phys_addr_length);
19697 	}
19698 	/*
19699 	 * Note: Returns ND_* states. Should be:
19700 	 * reachable(1), stale(2), delay(3), probe(4),
19701 	 * invalid(5), unknown(6)
19702 	 */
19703 	ntme.ipv6NetToMediaState = nce->nce_state;
19704 	ntme.ipv6NetToMediaLastUpdated = 0;
19705 
19706 	/* other(1), dynamic(2), static(3), local(4) */
19707 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19708 		ntme.ipv6NetToMediaType = 4;
19709 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19710 		ntme.ipv6NetToMediaType = 1;
19711 	} else {
19712 		ntme.ipv6NetToMediaType = 2;
19713 	}
19714 
19715 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19716 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19717 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19718 		    (uint_t)sizeof (ntme)));
19719 	}
19720 	return (0);
19721 }
19722 
19723 /*
19724  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19725  */
19726 /* ARGSUSED */
19727 int
19728 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19729 {
19730 	switch (level) {
19731 	case MIB2_IP:
19732 	case MIB2_ICMP:
19733 		switch (name) {
19734 		default:
19735 			break;
19736 		}
19737 		return (1);
19738 	default:
19739 		return (1);
19740 	}
19741 }
19742 
19743 /*
19744  * When there exists both a 64- and 32-bit counter of a particular type
19745  * (i.e., InReceives), only the 64-bit counters are added.
19746  */
19747 void
19748 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19749 {
19750 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19751 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19752 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19753 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19754 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19755 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19756 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19757 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19758 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19759 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19760 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19761 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19762 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19763 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19764 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19765 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19766 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19767 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19768 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19769 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19770 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19771 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19772 	    o2->ipIfStatsInWrongIPVersion);
19773 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19774 	    o2->ipIfStatsInWrongIPVersion);
19775 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19776 	    o2->ipIfStatsOutSwitchIPVersion);
19777 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19778 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19779 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19780 	    o2->ipIfStatsHCInForwDatagrams);
19781 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19782 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19783 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19784 	    o2->ipIfStatsHCOutForwDatagrams);
19785 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19786 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19787 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19788 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19789 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19790 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19791 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19792 	    o2->ipIfStatsHCOutMcastOctets);
19793 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19794 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19795 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19796 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19797 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19798 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19799 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19800 }
19801 
19802 void
19803 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19804 {
19805 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19806 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19807 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19808 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19809 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19810 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19811 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19812 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19813 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19814 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19815 	    o2->ipv6IfIcmpInRouterSolicits);
19816 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19817 	    o2->ipv6IfIcmpInRouterAdvertisements);
19818 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19819 	    o2->ipv6IfIcmpInNeighborSolicits);
19820 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19821 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19822 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19823 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19824 	    o2->ipv6IfIcmpInGroupMembQueries);
19825 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19826 	    o2->ipv6IfIcmpInGroupMembResponses);
19827 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19828 	    o2->ipv6IfIcmpInGroupMembReductions);
19829 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19830 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19831 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19832 	    o2->ipv6IfIcmpOutDestUnreachs);
19833 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19834 	    o2->ipv6IfIcmpOutAdminProhibs);
19835 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19836 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19837 	    o2->ipv6IfIcmpOutParmProblems);
19838 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19839 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19840 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19841 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19842 	    o2->ipv6IfIcmpOutRouterSolicits);
19843 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19844 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19845 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19846 	    o2->ipv6IfIcmpOutNeighborSolicits);
19847 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19848 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19849 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19850 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19851 	    o2->ipv6IfIcmpOutGroupMembQueries);
19852 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19853 	    o2->ipv6IfIcmpOutGroupMembResponses);
19854 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19855 	    o2->ipv6IfIcmpOutGroupMembReductions);
19856 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19857 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19858 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19859 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19860 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19861 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19862 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19863 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19864 	    o2->ipv6IfIcmpInGroupMembTotal);
19865 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19866 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19867 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19868 	    o2->ipv6IfIcmpInGroupMembBadReports);
19869 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19870 	    o2->ipv6IfIcmpInGroupMembOurReports);
19871 }
19872 
19873 /*
19874  * Called before the options are updated to check if this packet will
19875  * be source routed from here.
19876  * This routine assumes that the options are well formed i.e. that they
19877  * have already been checked.
19878  */
19879 static boolean_t
19880 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19881 {
19882 	ipoptp_t	opts;
19883 	uchar_t		*opt;
19884 	uint8_t		optval;
19885 	uint8_t		optlen;
19886 	ipaddr_t	dst;
19887 	ire_t		*ire;
19888 
19889 	if (IS_SIMPLE_IPH(ipha)) {
19890 		ip2dbg(("not source routed\n"));
19891 		return (B_FALSE);
19892 	}
19893 	dst = ipha->ipha_dst;
19894 	for (optval = ipoptp_first(&opts, ipha);
19895 	    optval != IPOPT_EOL;
19896 	    optval = ipoptp_next(&opts)) {
19897 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19898 		opt = opts.ipoptp_cur;
19899 		optlen = opts.ipoptp_len;
19900 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19901 		    optval, optlen));
19902 		switch (optval) {
19903 			uint32_t off;
19904 		case IPOPT_SSRR:
19905 		case IPOPT_LSRR:
19906 			/*
19907 			 * If dst is one of our addresses and there are some
19908 			 * entries left in the source route return (true).
19909 			 */
19910 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19911 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19912 			if (ire == NULL) {
19913 				ip2dbg(("ip_source_routed: not next"
19914 				    " source route 0x%x\n",
19915 				    ntohl(dst)));
19916 				return (B_FALSE);
19917 			}
19918 			ire_refrele(ire);
19919 			off = opt[IPOPT_OFFSET];
19920 			off--;
19921 			if (optlen < IP_ADDR_LEN ||
19922 			    off > optlen - IP_ADDR_LEN) {
19923 				/* End of source route */
19924 				ip1dbg(("ip_source_routed: end of SR\n"));
19925 				return (B_FALSE);
19926 			}
19927 			return (B_TRUE);
19928 		}
19929 	}
19930 	ip2dbg(("not source routed\n"));
19931 	return (B_FALSE);
19932 }
19933 
19934 /*
19935  * Check if the packet contains any source route.
19936  */
19937 static boolean_t
19938 ip_source_route_included(ipha_t *ipha)
19939 {
19940 	ipoptp_t	opts;
19941 	uint8_t		optval;
19942 
19943 	if (IS_SIMPLE_IPH(ipha))
19944 		return (B_FALSE);
19945 	for (optval = ipoptp_first(&opts, ipha);
19946 	    optval != IPOPT_EOL;
19947 	    optval = ipoptp_next(&opts)) {
19948 		switch (optval) {
19949 		case IPOPT_SSRR:
19950 		case IPOPT_LSRR:
19951 			return (B_TRUE);
19952 		}
19953 	}
19954 	return (B_FALSE);
19955 }
19956 
19957 /*
19958  * Called when the IRE expiration timer fires.
19959  */
19960 void
19961 ip_trash_timer_expire(void *args)
19962 {
19963 	int			flush_flag = 0;
19964 	ire_expire_arg_t	iea;
19965 	ip_stack_t		*ipst = (ip_stack_t *)args;
19966 
19967 	iea.iea_ipst = ipst;	/* No netstack_hold */
19968 
19969 	/*
19970 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19971 	 * This lock makes sure that a new invocation of this function
19972 	 * that occurs due to an almost immediate timer firing will not
19973 	 * progress beyond this point until the current invocation is done
19974 	 */
19975 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19976 	ipst->ips_ip_ire_expire_id = 0;
19977 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19978 
19979 	/* Periodic timer */
19980 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19981 	    ipst->ips_ip_ire_arp_interval) {
19982 		/*
19983 		 * Remove all IRE_CACHE entries since they might
19984 		 * contain arp information.
19985 		 */
19986 		flush_flag |= FLUSH_ARP_TIME;
19987 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19988 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19989 	}
19990 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19991 	    ipst->ips_ip_ire_redir_interval) {
19992 		/* Remove all redirects */
19993 		flush_flag |= FLUSH_REDIRECT_TIME;
19994 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19995 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19996 	}
19997 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19998 	    ipst->ips_ip_ire_pathmtu_interval) {
19999 		/* Increase path mtu */
20000 		flush_flag |= FLUSH_MTU_TIME;
20001 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
20002 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
20003 	}
20004 
20005 	/*
20006 	 * Optimize for the case when there are no redirects in the
20007 	 * ftable, that is, no need to walk the ftable in that case.
20008 	 */
20009 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
20010 		iea.iea_flush_flag = flush_flag;
20011 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
20012 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
20013 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
20014 		    NULL, ALL_ZONES, ipst);
20015 	}
20016 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
20017 	    ipst->ips_ip_redirect_cnt > 0) {
20018 		iea.iea_flush_flag = flush_flag;
20019 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
20020 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
20021 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
20022 	}
20023 	if (flush_flag & FLUSH_MTU_TIME) {
20024 		/*
20025 		 * Walk all IPv6 IRE's and update them
20026 		 * Note that ARP and redirect timers are not
20027 		 * needed since NUD handles stale entries.
20028 		 */
20029 		flush_flag = FLUSH_MTU_TIME;
20030 		iea.iea_flush_flag = flush_flag;
20031 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20032 		    ALL_ZONES, ipst);
20033 	}
20034 
20035 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20036 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20037 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20038 
20039 	/*
20040 	 * Hold the lock to serialize timeout calls and prevent
20041 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20042 	 * for the timer to fire and a new invocation of this function
20043 	 * to start before the return value of timeout has been stored
20044 	 * in ip_ire_expire_id by the current invocation.
20045 	 */
20046 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20047 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20048 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20049 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20050 }
20051 
20052 /*
20053  * Called by the memory allocator subsystem directly, when the system
20054  * is running low on memory.
20055  */
20056 /* ARGSUSED */
20057 void
20058 ip_trash_ire_reclaim(void *args)
20059 {
20060 	netstack_handle_t nh;
20061 	netstack_t *ns;
20062 
20063 	netstack_next_init(&nh);
20064 	while ((ns = netstack_next(&nh)) != NULL) {
20065 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20066 		netstack_rele(ns);
20067 	}
20068 	netstack_next_fini(&nh);
20069 }
20070 
20071 static void
20072 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20073 {
20074 	ire_cache_count_t icc;
20075 	ire_cache_reclaim_t icr;
20076 	ncc_cache_count_t ncc;
20077 	nce_cache_reclaim_t ncr;
20078 	uint_t delete_cnt;
20079 	/*
20080 	 * Memory reclaim call back.
20081 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20082 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20083 	 * entries, determine what fraction to free for
20084 	 * each category of IRE_CACHE entries giving absolute priority
20085 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20086 	 * entry will be freed unless all offlink entries are freed).
20087 	 */
20088 	icc.icc_total = 0;
20089 	icc.icc_unused = 0;
20090 	icc.icc_offlink = 0;
20091 	icc.icc_pmtu = 0;
20092 	icc.icc_onlink = 0;
20093 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20094 
20095 	/*
20096 	 * Free NCEs for IPv6 like the onlink ires.
20097 	 */
20098 	ncc.ncc_total = 0;
20099 	ncc.ncc_host = 0;
20100 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20101 
20102 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20103 	    icc.icc_pmtu + icc.icc_onlink);
20104 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20105 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20106 	if (delete_cnt == 0)
20107 		return;
20108 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20109 	/* Always delete all unused offlink entries */
20110 	icr.icr_ipst = ipst;
20111 	icr.icr_unused = 1;
20112 	if (delete_cnt <= icc.icc_unused) {
20113 		/*
20114 		 * Only need to free unused entries.  In other words,
20115 		 * there are enough unused entries to free to meet our
20116 		 * target number of freed ire cache entries.
20117 		 */
20118 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20119 		ncr.ncr_host = 0;
20120 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20121 		/*
20122 		 * Only need to free unused entries, plus a fraction of offlink
20123 		 * entries.  It follows from the first if statement that
20124 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20125 		 */
20126 		delete_cnt -= icc.icc_unused;
20127 		/* Round up # deleted by truncating fraction */
20128 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20129 		icr.icr_pmtu = icr.icr_onlink = 0;
20130 		ncr.ncr_host = 0;
20131 	} else if (delete_cnt <=
20132 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20133 		/*
20134 		 * Free all unused and offlink entries, plus a fraction of
20135 		 * pmtu entries.  It follows from the previous if statement
20136 		 * that icc_pmtu is non-zero, and that
20137 		 * delete_cnt != icc_unused + icc_offlink.
20138 		 */
20139 		icr.icr_offlink = 1;
20140 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20141 		/* Round up # deleted by truncating fraction */
20142 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20143 		icr.icr_onlink = 0;
20144 		ncr.ncr_host = 0;
20145 	} else {
20146 		/*
20147 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20148 		 * of onlink entries.  If we're here, then we know that
20149 		 * icc_onlink is non-zero, and that
20150 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20151 		 */
20152 		icr.icr_offlink = icr.icr_pmtu = 1;
20153 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20154 		    icc.icc_pmtu;
20155 		/* Round up # deleted by truncating fraction */
20156 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20157 		/* Using the same delete fraction as for onlink IREs */
20158 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20159 	}
20160 #ifdef DEBUG
20161 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20162 	    "fractions %d/%d/%d/%d\n",
20163 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20164 	    icc.icc_unused, icc.icc_offlink,
20165 	    icc.icc_pmtu, icc.icc_onlink,
20166 	    icr.icr_unused, icr.icr_offlink,
20167 	    icr.icr_pmtu, icr.icr_onlink));
20168 #endif
20169 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20170 	if (ncr.ncr_host != 0)
20171 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20172 		    (uchar_t *)&ncr, ipst);
20173 #ifdef DEBUG
20174 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20175 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20176 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20177 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20178 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20179 	    icc.icc_pmtu, icc.icc_onlink));
20180 #endif
20181 }
20182 
20183 /*
20184  * ip_unbind is called when a copy of an unbind request is received from the
20185  * upper level protocol.  We remove this conn from any fanout hash list it is
20186  * on, and zero out the bind information.  No reply is expected up above.
20187  */
20188 mblk_t *
20189 ip_unbind(queue_t *q, mblk_t *mp)
20190 {
20191 	conn_t	*connp = Q_TO_CONN(q);
20192 
20193 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20194 
20195 	if (is_system_labeled() && connp->conn_anon_port) {
20196 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20197 		    connp->conn_mlp_type, connp->conn_ulp,
20198 		    ntohs(connp->conn_lport), B_FALSE);
20199 		connp->conn_anon_port = 0;
20200 	}
20201 	connp->conn_mlp_type = mlptSingle;
20202 
20203 	ipcl_hash_remove(connp);
20204 
20205 	ASSERT(mp->b_cont == NULL);
20206 	/*
20207 	 * Convert mp into a T_OK_ACK
20208 	 */
20209 	mp = mi_tpi_ok_ack_alloc(mp);
20210 
20211 	/*
20212 	 * should not happen in practice... T_OK_ACK is smaller than the
20213 	 * original message.
20214 	 */
20215 	if (mp == NULL)
20216 		return (NULL);
20217 
20218 	/*
20219 	 * Don't bzero the ports if its TCP since TCP still needs the
20220 	 * lport to remove it from its own bind hash. TCP will do the
20221 	 * cleanup.
20222 	 */
20223 	if (!IPCL_IS_TCP(connp))
20224 		bzero(&connp->u_port, sizeof (connp->u_port));
20225 
20226 	return (mp);
20227 }
20228 
20229 /*
20230  * Write side put procedure.  Outbound data, IOCTLs, responses from
20231  * resolvers, etc, come down through here.
20232  *
20233  * arg2 is always a queue_t *.
20234  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20235  * the zoneid.
20236  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20237  */
20238 void
20239 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20240 {
20241 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20242 }
20243 
20244 void
20245 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20246     ip_opt_info_t *infop)
20247 {
20248 	conn_t		*connp = NULL;
20249 	queue_t		*q = (queue_t *)arg2;
20250 	ipha_t		*ipha;
20251 #define	rptr	((uchar_t *)ipha)
20252 	ire_t		*ire = NULL;
20253 	ire_t		*sctp_ire = NULL;
20254 	uint32_t	v_hlen_tos_len;
20255 	ipaddr_t	dst;
20256 	mblk_t		*first_mp = NULL;
20257 	boolean_t	mctl_present;
20258 	ipsec_out_t	*io;
20259 	int		match_flags;
20260 	ill_t		*attach_ill = NULL;
20261 					/* Bind to IPIF_NOFAILOVER ill etc. */
20262 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20263 	ipif_t		*dst_ipif;
20264 	boolean_t	multirt_need_resolve = B_FALSE;
20265 	mblk_t		*copy_mp = NULL;
20266 	int		err;
20267 	zoneid_t	zoneid;
20268 	int	adjust;
20269 	uint16_t iplen;
20270 	boolean_t	need_decref = B_FALSE;
20271 	boolean_t	ignore_dontroute = B_FALSE;
20272 	boolean_t	ignore_nexthop = B_FALSE;
20273 	boolean_t	ip_nexthop = B_FALSE;
20274 	ipaddr_t	nexthop_addr;
20275 	ip_stack_t	*ipst;
20276 
20277 #ifdef	_BIG_ENDIAN
20278 #define	V_HLEN	(v_hlen_tos_len >> 24)
20279 #else
20280 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20281 #endif
20282 
20283 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20284 	    "ip_wput_start: q %p", q);
20285 
20286 	/*
20287 	 * ip_wput fast path
20288 	 */
20289 
20290 	/* is packet from ARP ? */
20291 	if (q->q_next != NULL) {
20292 		zoneid = (zoneid_t)(uintptr_t)arg;
20293 		goto qnext;
20294 	}
20295 
20296 	connp = (conn_t *)arg;
20297 	ASSERT(connp != NULL);
20298 	zoneid = connp->conn_zoneid;
20299 	ipst = connp->conn_netstack->netstack_ip;
20300 
20301 	/* is queue flow controlled? */
20302 	if ((q->q_first != NULL || connp->conn_draining) &&
20303 	    (caller == IP_WPUT)) {
20304 		ASSERT(!need_decref);
20305 		(void) putq(q, mp);
20306 		return;
20307 	}
20308 
20309 	/* Multidata transmit? */
20310 	if (DB_TYPE(mp) == M_MULTIDATA) {
20311 		/*
20312 		 * We should never get here, since all Multidata messages
20313 		 * originating from tcp should have been directed over to
20314 		 * tcp_multisend() in the first place.
20315 		 */
20316 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20317 		freemsg(mp);
20318 		return;
20319 	} else if (DB_TYPE(mp) != M_DATA)
20320 		goto notdata;
20321 
20322 	if (mp->b_flag & MSGHASREF) {
20323 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20324 		mp->b_flag &= ~MSGHASREF;
20325 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20326 		need_decref = B_TRUE;
20327 	}
20328 	ipha = (ipha_t *)mp->b_rptr;
20329 
20330 	/* is IP header non-aligned or mblk smaller than basic IP header */
20331 #ifndef SAFETY_BEFORE_SPEED
20332 	if (!OK_32PTR(rptr) ||
20333 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20334 		goto hdrtoosmall;
20335 #endif
20336 
20337 	ASSERT(OK_32PTR(ipha));
20338 
20339 	/*
20340 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20341 	 * wrong version, we'll catch it again in ip_output_v6.
20342 	 *
20343 	 * Note that this is *only* locally-generated output here, and never
20344 	 * forwarded data, and that we need to deal only with transports that
20345 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20346 	 * label.)
20347 	 */
20348 	if (is_system_labeled() &&
20349 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20350 	    !connp->conn_ulp_labeled) {
20351 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20352 		    connp->conn_mac_exempt, ipst);
20353 		ipha = (ipha_t *)mp->b_rptr;
20354 		if (err != 0) {
20355 			first_mp = mp;
20356 			if (err == EINVAL)
20357 				goto icmp_parameter_problem;
20358 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20359 			goto discard_pkt;
20360 		}
20361 		iplen = ntohs(ipha->ipha_length) + adjust;
20362 		ipha->ipha_length = htons(iplen);
20363 	}
20364 
20365 	ASSERT(infop != NULL);
20366 
20367 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20368 		/*
20369 		 * IP_PKTINFO ancillary option is present.
20370 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20371 		 * allows using address of any zone as the source address.
20372 		 */
20373 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20374 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20375 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20376 		if (ire == NULL)
20377 			goto drop_pkt;
20378 		ire_refrele(ire);
20379 		ire = NULL;
20380 	}
20381 
20382 	/*
20383 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20384 	 * ill index passed in IP_PKTINFO.
20385 	 */
20386 	if (infop->ip_opt_ill_index != 0 &&
20387 	    connp->conn_xmit_if_ill == NULL &&
20388 	    connp->conn_nofailover_ill == NULL) {
20389 
20390 		xmit_ill = ill_lookup_on_ifindex(
20391 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20392 		    ipst);
20393 
20394 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20395 			goto drop_pkt;
20396 		/*
20397 		 * check that there is an ipif belonging
20398 		 * to our zone. IPCL_ZONEID is not used because
20399 		 * IP_ALLZONES option is valid only when the ill is
20400 		 * accessible from all zones i.e has a valid ipif in
20401 		 * all zones.
20402 		 */
20403 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20404 			goto drop_pkt;
20405 		}
20406 	}
20407 
20408 	/*
20409 	 * If there is a policy, try to attach an ipsec_out in
20410 	 * the front. At the end, first_mp either points to a
20411 	 * M_DATA message or IPSEC_OUT message linked to a
20412 	 * M_DATA message. We have to do it now as we might
20413 	 * lose the "conn" if we go through ip_newroute.
20414 	 */
20415 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20416 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20417 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20418 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20419 			if (need_decref)
20420 				CONN_DEC_REF(connp);
20421 			return;
20422 		} else {
20423 			ASSERT(mp->b_datap->db_type == M_CTL);
20424 			first_mp = mp;
20425 			mp = mp->b_cont;
20426 			mctl_present = B_TRUE;
20427 		}
20428 	} else {
20429 		first_mp = mp;
20430 		mctl_present = B_FALSE;
20431 	}
20432 
20433 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20434 
20435 	/* is wrong version or IP options present */
20436 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20437 		goto version_hdrlen_check;
20438 	dst = ipha->ipha_dst;
20439 
20440 	if (connp->conn_nofailover_ill != NULL) {
20441 		attach_ill = conn_get_held_ill(connp,
20442 		    &connp->conn_nofailover_ill, &err);
20443 		if (err == ILL_LOOKUP_FAILED) {
20444 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20445 			if (need_decref)
20446 				CONN_DEC_REF(connp);
20447 			freemsg(first_mp);
20448 			return;
20449 		}
20450 	}
20451 
20452 
20453 	/* is packet multicast? */
20454 	if (CLASSD(dst))
20455 		goto multicast;
20456 
20457 	/*
20458 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20459 	 * takes precedence over conn_dontroute and conn_nexthop_set
20460 	 */
20461 	if (xmit_ill != NULL) {
20462 		goto send_from_ill;
20463 	}
20464 
20465 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20466 	    (connp->conn_nexthop_set)) {
20467 		/*
20468 		 * If the destination is a broadcast or a loopback
20469 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20470 		 * through the standard path. But in the case of local
20471 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20472 		 * the standard path not IP_XMIT_IF.
20473 		 */
20474 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20475 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20476 		    (ire->ire_type != IRE_LOOPBACK))) {
20477 			if ((connp->conn_dontroute ||
20478 			    connp->conn_nexthop_set) && (ire != NULL) &&
20479 			    (ire->ire_type == IRE_LOCAL))
20480 				goto standard_path;
20481 
20482 			if (ire != NULL) {
20483 				ire_refrele(ire);
20484 				/* No more access to ire */
20485 				ire = NULL;
20486 			}
20487 			/*
20488 			 * bypass routing checks and go directly to
20489 			 * interface.
20490 			 */
20491 			if (connp->conn_dontroute) {
20492 				goto dontroute;
20493 			} else if (connp->conn_nexthop_set) {
20494 				ip_nexthop = B_TRUE;
20495 				nexthop_addr = connp->conn_nexthop_v4;
20496 				goto send_from_ill;
20497 			}
20498 
20499 			/*
20500 			 * If IP_XMIT_IF socket option is set,
20501 			 * then we allow unicast and multicast
20502 			 * packets to go through the ill. It is
20503 			 * quite possible that the destination
20504 			 * is not in the ire cache table and we
20505 			 * do not want to go to ip_newroute()
20506 			 * instead we call ip_newroute_ipif.
20507 			 */
20508 			xmit_ill = conn_get_held_ill(connp,
20509 			    &connp->conn_xmit_if_ill, &err);
20510 			if (err == ILL_LOOKUP_FAILED) {
20511 				BUMP_MIB(&ipst->ips_ip_mib,
20512 				    ipIfStatsOutDiscards);
20513 				if (attach_ill != NULL)
20514 					ill_refrele(attach_ill);
20515 				if (need_decref)
20516 					CONN_DEC_REF(connp);
20517 				freemsg(first_mp);
20518 				return;
20519 			}
20520 			goto send_from_ill;
20521 		}
20522 standard_path:
20523 		/* Must be a broadcast, a loopback or a local ire */
20524 		if (ire != NULL) {
20525 			ire_refrele(ire);
20526 			/* No more access to ire */
20527 			ire = NULL;
20528 		}
20529 	}
20530 
20531 	if (attach_ill != NULL)
20532 		goto send_from_ill;
20533 
20534 	/*
20535 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20536 	 * this for the tcp global queue and listen end point
20537 	 * as it does not really have a real destination to
20538 	 * talk to.  This is also true for SCTP.
20539 	 */
20540 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20541 	    !connp->conn_fully_bound) {
20542 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20543 		if (ire == NULL)
20544 			goto noirefound;
20545 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20546 		    "ip_wput_end: q %p (%S)", q, "end");
20547 
20548 		/*
20549 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20550 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20551 		 */
20552 		if (ire->ire_flags & RTF_MULTIRT) {
20553 
20554 			/*
20555 			 * Force the TTL of multirouted packets if required.
20556 			 * The TTL of such packets is bounded by the
20557 			 * ip_multirt_ttl ndd variable.
20558 			 */
20559 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20560 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20561 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20562 				    "(was %d), dst 0x%08x\n",
20563 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20564 				    ntohl(ire->ire_addr)));
20565 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20566 			}
20567 			/*
20568 			 * We look at this point if there are pending
20569 			 * unresolved routes. ire_multirt_resolvable()
20570 			 * checks in O(n) that all IRE_OFFSUBNET ire
20571 			 * entries for the packet's destination and
20572 			 * flagged RTF_MULTIRT are currently resolved.
20573 			 * If some remain unresolved, we make a copy
20574 			 * of the current message. It will be used
20575 			 * to initiate additional route resolutions.
20576 			 */
20577 			multirt_need_resolve =
20578 			    ire_multirt_need_resolve(ire->ire_addr,
20579 			    MBLK_GETLABEL(first_mp), ipst);
20580 			ip2dbg(("ip_wput[TCP]: ire %p, "
20581 			    "multirt_need_resolve %d, first_mp %p\n",
20582 			    (void *)ire, multirt_need_resolve,
20583 			    (void *)first_mp));
20584 			if (multirt_need_resolve) {
20585 				copy_mp = copymsg(first_mp);
20586 				if (copy_mp != NULL) {
20587 					MULTIRT_DEBUG_TAG(copy_mp);
20588 				}
20589 			}
20590 		}
20591 
20592 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20593 
20594 		/*
20595 		 * Try to resolve another multiroute if
20596 		 * ire_multirt_need_resolve() deemed it necessary.
20597 		 */
20598 		if (copy_mp != NULL) {
20599 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20600 		}
20601 		if (need_decref)
20602 			CONN_DEC_REF(connp);
20603 		return;
20604 	}
20605 
20606 	/*
20607 	 * Access to conn_ire_cache. (protected by conn_lock)
20608 	 *
20609 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20610 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20611 	 * send a packet or two with the IRE_CACHE that is going away.
20612 	 * Access to the ire requires an ire refhold on the ire prior to
20613 	 * its use since an interface unplumb thread may delete the cached
20614 	 * ire and release the refhold at any time.
20615 	 *
20616 	 * Caching an ire in the conn_ire_cache
20617 	 *
20618 	 * o Caching an ire pointer in the conn requires a strict check for
20619 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20620 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20621 	 * in the conn is done after making sure under the bucket lock that the
20622 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20623 	 * caching an ire after the unplumb thread has cleaned up the conn.
20624 	 * If the conn does not send a packet subsequently the unplumb thread
20625 	 * will be hanging waiting for the ire count to drop to zero.
20626 	 *
20627 	 * o We also need to atomically test for a null conn_ire_cache and
20628 	 * set the conn_ire_cache under the the protection of the conn_lock
20629 	 * to avoid races among concurrent threads trying to simultaneously
20630 	 * cache an ire in the conn_ire_cache.
20631 	 */
20632 	mutex_enter(&connp->conn_lock);
20633 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20634 
20635 	if (ire != NULL && ire->ire_addr == dst &&
20636 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20637 
20638 		IRE_REFHOLD(ire);
20639 		mutex_exit(&connp->conn_lock);
20640 
20641 	} else {
20642 		boolean_t cached = B_FALSE;
20643 		connp->conn_ire_cache = NULL;
20644 		mutex_exit(&connp->conn_lock);
20645 		/* Release the old ire */
20646 		if (ire != NULL && sctp_ire == NULL)
20647 			IRE_REFRELE_NOTR(ire);
20648 
20649 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20650 		if (ire == NULL)
20651 			goto noirefound;
20652 		IRE_REFHOLD_NOTR(ire);
20653 
20654 		mutex_enter(&connp->conn_lock);
20655 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20656 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20657 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20658 				if (connp->conn_ulp == IPPROTO_TCP)
20659 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20660 				connp->conn_ire_cache = ire;
20661 				cached = B_TRUE;
20662 			}
20663 			rw_exit(&ire->ire_bucket->irb_lock);
20664 		}
20665 		mutex_exit(&connp->conn_lock);
20666 
20667 		/*
20668 		 * We can continue to use the ire but since it was
20669 		 * not cached, we should drop the extra reference.
20670 		 */
20671 		if (!cached)
20672 			IRE_REFRELE_NOTR(ire);
20673 	}
20674 
20675 
20676 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20677 	    "ip_wput_end: q %p (%S)", q, "end");
20678 
20679 	/*
20680 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20681 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20682 	 */
20683 	if (ire->ire_flags & RTF_MULTIRT) {
20684 
20685 		/*
20686 		 * Force the TTL of multirouted packets if required.
20687 		 * The TTL of such packets is bounded by the
20688 		 * ip_multirt_ttl ndd variable.
20689 		 */
20690 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20691 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20692 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20693 			    "(was %d), dst 0x%08x\n",
20694 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20695 			    ntohl(ire->ire_addr)));
20696 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20697 		}
20698 
20699 		/*
20700 		 * At this point, we check to see if there are any pending
20701 		 * unresolved routes. ire_multirt_resolvable()
20702 		 * checks in O(n) that all IRE_OFFSUBNET ire
20703 		 * entries for the packet's destination and
20704 		 * flagged RTF_MULTIRT are currently resolved.
20705 		 * If some remain unresolved, we make a copy
20706 		 * of the current message. It will be used
20707 		 * to initiate additional route resolutions.
20708 		 */
20709 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20710 		    MBLK_GETLABEL(first_mp), ipst);
20711 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20712 		    "multirt_need_resolve %d, first_mp %p\n",
20713 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20714 		if (multirt_need_resolve) {
20715 			copy_mp = copymsg(first_mp);
20716 			if (copy_mp != NULL) {
20717 				MULTIRT_DEBUG_TAG(copy_mp);
20718 			}
20719 		}
20720 	}
20721 
20722 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20723 
20724 	/*
20725 	 * Try to resolve another multiroute if
20726 	 * ire_multirt_resolvable() deemed it necessary
20727 	 */
20728 	if (copy_mp != NULL) {
20729 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20730 	}
20731 	if (need_decref)
20732 		CONN_DEC_REF(connp);
20733 	return;
20734 
20735 qnext:
20736 	/*
20737 	 * Upper Level Protocols pass down complete IP datagrams
20738 	 * as M_DATA messages.	Everything else is a sideshow.
20739 	 *
20740 	 * 1) We could be re-entering ip_wput because of ip_neworute
20741 	 *    in which case we could have a IPSEC_OUT message. We
20742 	 *    need to pass through ip_wput like other datagrams and
20743 	 *    hence cannot branch to ip_wput_nondata.
20744 	 *
20745 	 * 2) ARP, AH, ESP, and other clients who are on the module
20746 	 *    instance of IP stream, give us something to deal with.
20747 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20748 	 *
20749 	 * 3) ICMP replies also could come here.
20750 	 */
20751 	ipst = ILLQ_TO_IPST(q);
20752 
20753 	if (DB_TYPE(mp) != M_DATA) {
20754 notdata:
20755 		if (DB_TYPE(mp) == M_CTL) {
20756 			/*
20757 			 * M_CTL messages are used by ARP, AH and ESP to
20758 			 * communicate with IP. We deal with IPSEC_IN and
20759 			 * IPSEC_OUT here. ip_wput_nondata handles other
20760 			 * cases.
20761 			 */
20762 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20763 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20764 				first_mp = mp->b_cont;
20765 				first_mp->b_flag &= ~MSGHASREF;
20766 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20767 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20768 				CONN_DEC_REF(connp);
20769 				connp = NULL;
20770 			}
20771 			if (ii->ipsec_info_type == IPSEC_IN) {
20772 				/*
20773 				 * Either this message goes back to
20774 				 * IPSEC for further processing or to
20775 				 * ULP after policy checks.
20776 				 */
20777 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20778 				return;
20779 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20780 				io = (ipsec_out_t *)ii;
20781 				if (io->ipsec_out_proc_begin) {
20782 					/*
20783 					 * IPSEC processing has already started.
20784 					 * Complete it.
20785 					 * IPQoS notes: We don't care what is
20786 					 * in ipsec_out_ill_index since this
20787 					 * won't be processed for IPQoS policies
20788 					 * in ipsec_out_process.
20789 					 */
20790 					ipsec_out_process(q, mp, NULL,
20791 					    io->ipsec_out_ill_index);
20792 					return;
20793 				} else {
20794 					connp = (q->q_next != NULL) ?
20795 					    NULL : Q_TO_CONN(q);
20796 					first_mp = mp;
20797 					mp = mp->b_cont;
20798 					mctl_present = B_TRUE;
20799 				}
20800 				zoneid = io->ipsec_out_zoneid;
20801 				ASSERT(zoneid != ALL_ZONES);
20802 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20803 				/*
20804 				 * It's an IPsec control message requesting
20805 				 * an SADB update to be sent to the IPsec
20806 				 * hardware acceleration capable ills.
20807 				 */
20808 				ipsec_ctl_t *ipsec_ctl =
20809 				    (ipsec_ctl_t *)mp->b_rptr;
20810 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20811 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20812 				mblk_t *cmp = mp->b_cont;
20813 
20814 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20815 				ASSERT(cmp != NULL);
20816 
20817 				freeb(mp);
20818 				ill_ipsec_capab_send_all(satype, cmp, sa,
20819 				    ipst->ips_netstack);
20820 				return;
20821 			} else {
20822 				/*
20823 				 * This must be ARP or special TSOL signaling.
20824 				 */
20825 				ip_wput_nondata(NULL, q, mp, NULL);
20826 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20827 				    "ip_wput_end: q %p (%S)", q, "nondata");
20828 				return;
20829 			}
20830 		} else {
20831 			/*
20832 			 * This must be non-(ARP/AH/ESP) messages.
20833 			 */
20834 			ASSERT(!need_decref);
20835 			ip_wput_nondata(NULL, q, mp, NULL);
20836 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20837 			    "ip_wput_end: q %p (%S)", q, "nondata");
20838 			return;
20839 		}
20840 	} else {
20841 		first_mp = mp;
20842 		mctl_present = B_FALSE;
20843 	}
20844 
20845 	ASSERT(first_mp != NULL);
20846 	/*
20847 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20848 	 * to make sure that this packet goes out on the same interface it
20849 	 * came in. We handle that here.
20850 	 */
20851 	if (mctl_present) {
20852 		uint_t ifindex;
20853 
20854 		io = (ipsec_out_t *)first_mp->b_rptr;
20855 		if (io->ipsec_out_attach_if ||
20856 		    io->ipsec_out_xmit_if ||
20857 		    io->ipsec_out_ip_nexthop) {
20858 			ill_t	*ill;
20859 
20860 			/*
20861 			 * We may have lost the conn context if we are
20862 			 * coming here from ip_newroute(). Copy the
20863 			 * nexthop information.
20864 			 */
20865 			if (io->ipsec_out_ip_nexthop) {
20866 				ip_nexthop = B_TRUE;
20867 				nexthop_addr = io->ipsec_out_nexthop_addr;
20868 
20869 				ipha = (ipha_t *)mp->b_rptr;
20870 				dst = ipha->ipha_dst;
20871 				goto send_from_ill;
20872 			} else {
20873 				ASSERT(io->ipsec_out_ill_index != 0);
20874 				ifindex = io->ipsec_out_ill_index;
20875 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20876 				    NULL, NULL, NULL, NULL, ipst);
20877 				/*
20878 				 * ipsec_out_xmit_if bit is used to tell
20879 				 * ip_wput to use the ill to send outgoing data
20880 				 * as we have no conn when data comes from ICMP
20881 				 * error msg routines. Currently this feature is
20882 				 * only used by ip_mrtun_forward routine.
20883 				 */
20884 				if (io->ipsec_out_xmit_if) {
20885 					xmit_ill = ill;
20886 					if (xmit_ill == NULL) {
20887 						ip1dbg(("ip_output:bad ifindex "
20888 						    "for xmit_ill %d\n",
20889 						    ifindex));
20890 						freemsg(first_mp);
20891 						BUMP_MIB(&ipst->ips_ip_mib,
20892 						    ipIfStatsOutDiscards);
20893 						ASSERT(!need_decref);
20894 						return;
20895 					}
20896 					/* Free up the ipsec_out_t mblk */
20897 					ASSERT(first_mp->b_cont == mp);
20898 					first_mp->b_cont = NULL;
20899 					freeb(first_mp);
20900 					/* Just send the IP header+ICMP+data */
20901 					first_mp = mp;
20902 					ipha = (ipha_t *)mp->b_rptr;
20903 					dst = ipha->ipha_dst;
20904 					goto send_from_ill;
20905 				} else {
20906 					attach_ill = ill;
20907 				}
20908 
20909 				if (attach_ill == NULL) {
20910 					ASSERT(xmit_ill == NULL);
20911 					ip1dbg(("ip_output: bad ifindex for "
20912 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20913 					    ifindex));
20914 					freemsg(first_mp);
20915 					BUMP_MIB(&ipst->ips_ip_mib,
20916 					    ipIfStatsOutDiscards);
20917 					ASSERT(!need_decref);
20918 					return;
20919 				}
20920 			}
20921 		}
20922 	}
20923 
20924 	ASSERT(xmit_ill == NULL);
20925 
20926 	/* We have a complete IP datagram heading outbound. */
20927 	ipha = (ipha_t *)mp->b_rptr;
20928 
20929 #ifndef SPEED_BEFORE_SAFETY
20930 	/*
20931 	 * Make sure we have a full-word aligned message and that at least
20932 	 * a simple IP header is accessible in the first message.  If not,
20933 	 * try a pullup.
20934 	 */
20935 	if (!OK_32PTR(rptr) ||
20936 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20937 hdrtoosmall:
20938 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20939 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20940 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20941 			if (first_mp == NULL)
20942 				first_mp = mp;
20943 			goto discard_pkt;
20944 		}
20945 
20946 		/* This function assumes that mp points to an IPv4 packet. */
20947 		if (is_system_labeled() && q->q_next == NULL &&
20948 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20949 		    !connp->conn_ulp_labeled) {
20950 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20951 			    &adjust, connp->conn_mac_exempt, ipst);
20952 			ipha = (ipha_t *)mp->b_rptr;
20953 			if (first_mp != NULL)
20954 				first_mp->b_cont = mp;
20955 			if (err != 0) {
20956 				if (first_mp == NULL)
20957 					first_mp = mp;
20958 				if (err == EINVAL)
20959 					goto icmp_parameter_problem;
20960 				ip2dbg(("ip_wput: label check failed (%d)\n",
20961 				    err));
20962 				goto discard_pkt;
20963 			}
20964 			iplen = ntohs(ipha->ipha_length) + adjust;
20965 			ipha->ipha_length = htons(iplen);
20966 		}
20967 
20968 		ipha = (ipha_t *)mp->b_rptr;
20969 		if (first_mp == NULL) {
20970 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20971 			/*
20972 			 * If we got here because of "goto hdrtoosmall"
20973 			 * We need to attach a IPSEC_OUT.
20974 			 */
20975 			if (connp->conn_out_enforce_policy) {
20976 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20977 				    NULL, ipha->ipha_protocol,
20978 				    ipst->ips_netstack)) == NULL)) {
20979 					BUMP_MIB(&ipst->ips_ip_mib,
20980 					    ipIfStatsOutDiscards);
20981 					if (need_decref)
20982 						CONN_DEC_REF(connp);
20983 					return;
20984 				} else {
20985 					ASSERT(mp->b_datap->db_type == M_CTL);
20986 					first_mp = mp;
20987 					mp = mp->b_cont;
20988 					mctl_present = B_TRUE;
20989 				}
20990 			} else {
20991 				first_mp = mp;
20992 				mctl_present = B_FALSE;
20993 			}
20994 		}
20995 	}
20996 #endif
20997 
20998 	/* Most of the code below is written for speed, not readability */
20999 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21000 
21001 	/*
21002 	 * If ip_newroute() fails, we're going to need a full
21003 	 * header for the icmp wraparound.
21004 	 */
21005 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
21006 		uint_t	v_hlen;
21007 version_hdrlen_check:
21008 		ASSERT(first_mp != NULL);
21009 		v_hlen = V_HLEN;
21010 		/*
21011 		 * siphon off IPv6 packets coming down from transport
21012 		 * layer modules here.
21013 		 * Note: high-order bit carries NUD reachability confirmation
21014 		 */
21015 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
21016 			/*
21017 			 * XXX implement a IPv4 and IPv6 packet counter per
21018 			 * conn and switch when ratio exceeds e.g. 10:1
21019 			 */
21020 #ifdef notyet
21021 			if (q->q_next == NULL) /* Avoid ill queue */
21022 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21023 #endif
21024 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21025 			ASSERT(xmit_ill == NULL);
21026 			if (attach_ill != NULL)
21027 				ill_refrele(attach_ill);
21028 			if (need_decref)
21029 				mp->b_flag |= MSGHASREF;
21030 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21031 			return;
21032 		}
21033 
21034 		if ((v_hlen >> 4) != IP_VERSION) {
21035 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21036 			    "ip_wput_end: q %p (%S)", q, "badvers");
21037 			goto discard_pkt;
21038 		}
21039 		/*
21040 		 * Is the header length at least 20 bytes?
21041 		 *
21042 		 * Are there enough bytes accessible in the header?  If
21043 		 * not, try a pullup.
21044 		 */
21045 		v_hlen &= 0xF;
21046 		v_hlen <<= 2;
21047 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21048 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21049 			    "ip_wput_end: q %p (%S)", q, "badlen");
21050 			goto discard_pkt;
21051 		}
21052 		if (v_hlen > (mp->b_wptr - rptr)) {
21053 			if (!pullupmsg(mp, v_hlen)) {
21054 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21055 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21056 				goto discard_pkt;
21057 			}
21058 			ipha = (ipha_t *)mp->b_rptr;
21059 		}
21060 		/*
21061 		 * Move first entry from any source route into ipha_dst and
21062 		 * verify the options
21063 		 */
21064 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21065 		    zoneid, ipst)) {
21066 			ASSERT(xmit_ill == NULL);
21067 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21068 			if (attach_ill != NULL)
21069 				ill_refrele(attach_ill);
21070 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21071 			    "ip_wput_end: q %p (%S)", q, "badopts");
21072 			if (need_decref)
21073 				CONN_DEC_REF(connp);
21074 			return;
21075 		}
21076 	}
21077 	dst = ipha->ipha_dst;
21078 
21079 	/*
21080 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21081 	 * we have to run the packet through ip_newroute which will take
21082 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21083 	 * a resolver, or assigning a default gateway, etc.
21084 	 */
21085 	if (CLASSD(dst)) {
21086 		ipif_t	*ipif;
21087 		uint32_t setsrc = 0;
21088 
21089 multicast:
21090 		ASSERT(first_mp != NULL);
21091 		ip2dbg(("ip_wput: CLASSD\n"));
21092 		if (connp == NULL) {
21093 			/*
21094 			 * Use the first good ipif on the ill.
21095 			 * XXX Should this ever happen? (Appears
21096 			 * to show up with just ppp and no ethernet due
21097 			 * to in.rdisc.)
21098 			 * However, ire_send should be able to
21099 			 * call ip_wput_ire directly.
21100 			 *
21101 			 * XXX Also, this can happen for ICMP and other packets
21102 			 * with multicast source addresses.  Perhaps we should
21103 			 * fix things so that we drop the packet in question,
21104 			 * but for now, just run with it.
21105 			 */
21106 			ill_t *ill = (ill_t *)q->q_ptr;
21107 
21108 			/*
21109 			 * Don't honor attach_if for this case. If ill
21110 			 * is part of the group, ipif could belong to
21111 			 * any ill and we cannot maintain attach_ill
21112 			 * and ipif_ill same anymore and the assert
21113 			 * below would fail.
21114 			 */
21115 			if (mctl_present && io->ipsec_out_attach_if) {
21116 				io->ipsec_out_ill_index = 0;
21117 				io->ipsec_out_attach_if = B_FALSE;
21118 				ASSERT(attach_ill != NULL);
21119 				ill_refrele(attach_ill);
21120 				attach_ill = NULL;
21121 			}
21122 
21123 			ASSERT(attach_ill == NULL);
21124 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21125 			if (ipif == NULL) {
21126 				if (need_decref)
21127 					CONN_DEC_REF(connp);
21128 				freemsg(first_mp);
21129 				return;
21130 			}
21131 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21132 			    ntohl(dst), ill->ill_name));
21133 		} else {
21134 			/*
21135 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21136 			 * and IP_MULTICAST_IF.
21137 			 * Block comment above this function explains the
21138 			 * locking mechanism used here
21139 			 */
21140 			if (xmit_ill == NULL) {
21141 				xmit_ill = conn_get_held_ill(connp,
21142 				    &connp->conn_xmit_if_ill, &err);
21143 				if (err == ILL_LOOKUP_FAILED) {
21144 					ip1dbg(("ip_wput: No ill for "
21145 					    "IP_XMIT_IF\n"));
21146 					BUMP_MIB(&ipst->ips_ip_mib,
21147 					    ipIfStatsOutNoRoutes);
21148 					goto drop_pkt;
21149 				}
21150 			}
21151 
21152 			if (xmit_ill == NULL) {
21153 				ipif = conn_get_held_ipif(connp,
21154 				    &connp->conn_multicast_ipif, &err);
21155 				if (err == IPIF_LOOKUP_FAILED) {
21156 					ip1dbg(("ip_wput: No ipif for "
21157 					    "multicast\n"));
21158 					BUMP_MIB(&ipst->ips_ip_mib,
21159 					    ipIfStatsOutNoRoutes);
21160 					goto drop_pkt;
21161 				}
21162 			}
21163 			if (xmit_ill != NULL) {
21164 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21165 				if (ipif == NULL) {
21166 					ip1dbg(("ip_wput: No ipif for "
21167 					    "IP_XMIT_IF\n"));
21168 					BUMP_MIB(&ipst->ips_ip_mib,
21169 					    ipIfStatsOutNoRoutes);
21170 					goto drop_pkt;
21171 				}
21172 			} else if (ipif == NULL || ipif->ipif_isv6) {
21173 				/*
21174 				 * We must do this ipif determination here
21175 				 * else we could pass through ip_newroute
21176 				 * and come back here without the conn context.
21177 				 *
21178 				 * Note: we do late binding i.e. we bind to
21179 				 * the interface when the first packet is sent.
21180 				 * For performance reasons we do not rebind on
21181 				 * each packet but keep the binding until the
21182 				 * next IP_MULTICAST_IF option.
21183 				 *
21184 				 * conn_multicast_{ipif,ill} are shared between
21185 				 * IPv4 and IPv6 and AF_INET6 sockets can
21186 				 * send both IPv4 and IPv6 packets. Hence
21187 				 * we have to check that "isv6" matches above.
21188 				 */
21189 				if (ipif != NULL)
21190 					ipif_refrele(ipif);
21191 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21192 				if (ipif == NULL) {
21193 					ip1dbg(("ip_wput: No ipif for "
21194 					    "multicast\n"));
21195 					BUMP_MIB(&ipst->ips_ip_mib,
21196 					    ipIfStatsOutNoRoutes);
21197 					goto drop_pkt;
21198 				}
21199 				err = conn_set_held_ipif(connp,
21200 				    &connp->conn_multicast_ipif, ipif);
21201 				if (err == IPIF_LOOKUP_FAILED) {
21202 					ipif_refrele(ipif);
21203 					ip1dbg(("ip_wput: No ipif for "
21204 					    "multicast\n"));
21205 					BUMP_MIB(&ipst->ips_ip_mib,
21206 					    ipIfStatsOutNoRoutes);
21207 					goto drop_pkt;
21208 				}
21209 			}
21210 		}
21211 		ASSERT(!ipif->ipif_isv6);
21212 		/*
21213 		 * As we may lose the conn by the time we reach ip_wput_ire,
21214 		 * we copy conn_multicast_loop and conn_dontroute on to an
21215 		 * ipsec_out. In case if this datagram goes out secure,
21216 		 * we need the ill_index also. Copy that also into the
21217 		 * ipsec_out.
21218 		 */
21219 		if (mctl_present) {
21220 			io = (ipsec_out_t *)first_mp->b_rptr;
21221 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21222 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21223 		} else {
21224 			ASSERT(mp == first_mp);
21225 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21226 			    BPRI_HI)) == NULL) {
21227 				ipif_refrele(ipif);
21228 				first_mp = mp;
21229 				goto discard_pkt;
21230 			}
21231 			first_mp->b_datap->db_type = M_CTL;
21232 			first_mp->b_wptr += sizeof (ipsec_info_t);
21233 			/* ipsec_out_secure is B_FALSE now */
21234 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21235 			io = (ipsec_out_t *)first_mp->b_rptr;
21236 			io->ipsec_out_type = IPSEC_OUT;
21237 			io->ipsec_out_len = sizeof (ipsec_out_t);
21238 			io->ipsec_out_use_global_policy = B_TRUE;
21239 			io->ipsec_out_ns = ipst->ips_netstack;
21240 			first_mp->b_cont = mp;
21241 			mctl_present = B_TRUE;
21242 		}
21243 		if (attach_ill != NULL) {
21244 			ASSERT(attach_ill == ipif->ipif_ill);
21245 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21246 
21247 			/*
21248 			 * Check if we need an ire that will not be
21249 			 * looked up by anybody else i.e. HIDDEN.
21250 			 */
21251 			if (ill_is_probeonly(attach_ill)) {
21252 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21253 			}
21254 			io->ipsec_out_ill_index =
21255 			    attach_ill->ill_phyint->phyint_ifindex;
21256 			io->ipsec_out_attach_if = B_TRUE;
21257 		} else {
21258 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21259 			io->ipsec_out_ill_index =
21260 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21261 		}
21262 		if (connp != NULL) {
21263 			io->ipsec_out_multicast_loop =
21264 			    connp->conn_multicast_loop;
21265 			io->ipsec_out_dontroute = connp->conn_dontroute;
21266 			io->ipsec_out_zoneid = connp->conn_zoneid;
21267 		}
21268 		/*
21269 		 * If the application uses IP_MULTICAST_IF with
21270 		 * different logical addresses of the same ILL, we
21271 		 * need to make sure that the soruce address of
21272 		 * the packet matches the logical IP address used
21273 		 * in the option. We do it by initializing ipha_src
21274 		 * here. This should keep IPSEC also happy as
21275 		 * when we return from IPSEC processing, we don't
21276 		 * have to worry about getting the right address on
21277 		 * the packet. Thus it is sufficient to look for
21278 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21279 		 * MATCH_IRE_IPIF.
21280 		 *
21281 		 * NOTE : We need to do it for non-secure case also as
21282 		 * this might go out secure if there is a global policy
21283 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21284 		 * address, the source should be initialized already and
21285 		 * hence we won't be initializing here.
21286 		 *
21287 		 * As we do not have the ire yet, it is possible that
21288 		 * we set the source address here and then later discover
21289 		 * that the ire implies the source address to be assigned
21290 		 * through the RTF_SETSRC flag.
21291 		 * In that case, the setsrc variable will remind us
21292 		 * that overwritting the source address by the one
21293 		 * of the RTF_SETSRC-flagged ire is allowed.
21294 		 */
21295 		if (ipha->ipha_src == INADDR_ANY &&
21296 		    (connp == NULL || !connp->conn_unspec_src)) {
21297 			ipha->ipha_src = ipif->ipif_src_addr;
21298 			setsrc = RTF_SETSRC;
21299 		}
21300 		/*
21301 		 * Find an IRE which matches the destination and the outgoing
21302 		 * queue (i.e. the outgoing interface.)
21303 		 * For loopback use a unicast IP address for
21304 		 * the ire lookup.
21305 		 */
21306 		if (IS_LOOPBACK(ipif->ipif_ill))
21307 			dst = ipif->ipif_lcl_addr;
21308 
21309 		/*
21310 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21311 		 * We don't need to lookup ire in ctable as the packet
21312 		 * needs to be sent to the destination through the specified
21313 		 * ill irrespective of ires in the cache table.
21314 		 */
21315 		ire = NULL;
21316 		if (xmit_ill == NULL) {
21317 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21318 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21319 		}
21320 
21321 		/*
21322 		 * refrele attach_ill as its not needed anymore.
21323 		 */
21324 		if (attach_ill != NULL) {
21325 			ill_refrele(attach_ill);
21326 			attach_ill = NULL;
21327 		}
21328 
21329 		if (ire == NULL) {
21330 			/*
21331 			 * Multicast loopback and multicast forwarding is
21332 			 * done in ip_wput_ire.
21333 			 *
21334 			 * Mark this packet to make it be delivered to
21335 			 * ip_wput_ire after the new ire has been
21336 			 * created.
21337 			 *
21338 			 * The call to ip_newroute_ipif takes into account
21339 			 * the setsrc reminder. In any case, we take care
21340 			 * of the RTF_MULTIRT flag.
21341 			 */
21342 			mp->b_prev = mp->b_next = NULL;
21343 			if (xmit_ill == NULL ||
21344 			    xmit_ill->ill_ipif_up_count > 0) {
21345 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21346 				    setsrc | RTF_MULTIRT, zoneid, infop);
21347 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21348 				    "ip_wput_end: q %p (%S)", q, "noire");
21349 			} else {
21350 				freemsg(first_mp);
21351 			}
21352 			ipif_refrele(ipif);
21353 			if (xmit_ill != NULL)
21354 				ill_refrele(xmit_ill);
21355 			if (need_decref)
21356 				CONN_DEC_REF(connp);
21357 			return;
21358 		}
21359 
21360 		ipif_refrele(ipif);
21361 		ipif = NULL;
21362 		ASSERT(xmit_ill == NULL);
21363 
21364 		/*
21365 		 * Honor the RTF_SETSRC flag for multicast packets,
21366 		 * if allowed by the setsrc reminder.
21367 		 */
21368 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21369 			ipha->ipha_src = ire->ire_src_addr;
21370 		}
21371 
21372 		/*
21373 		 * Unconditionally force the TTL to 1 for
21374 		 * multirouted multicast packets:
21375 		 * multirouted multicast should not cross
21376 		 * multicast routers.
21377 		 */
21378 		if (ire->ire_flags & RTF_MULTIRT) {
21379 			if (ipha->ipha_ttl > 1) {
21380 				ip2dbg(("ip_wput: forcing multicast "
21381 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21382 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21383 				ipha->ipha_ttl = 1;
21384 			}
21385 		}
21386 	} else {
21387 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21388 		if ((ire != NULL) && (ire->ire_type &
21389 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21390 			ignore_dontroute = B_TRUE;
21391 			ignore_nexthop = B_TRUE;
21392 		}
21393 		if (ire != NULL) {
21394 			ire_refrele(ire);
21395 			ire = NULL;
21396 		}
21397 		/*
21398 		 * Guard against coming in from arp in which case conn is NULL.
21399 		 * Also guard against non M_DATA with dontroute set but
21400 		 * destined to local, loopback or broadcast addresses.
21401 		 */
21402 		if (connp != NULL && connp->conn_dontroute &&
21403 		    !ignore_dontroute) {
21404 dontroute:
21405 			/*
21406 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21407 			 * routing protocols from seeing false direct
21408 			 * connectivity.
21409 			 */
21410 			ipha->ipha_ttl = 1;
21411 			/*
21412 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21413 			 * along with SO_DONTROUTE, higher precedence is
21414 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21415 			 */
21416 			if (connp->conn_xmit_if_ill == NULL) {
21417 				/* If suitable ipif not found, drop packet */
21418 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21419 				    ipst);
21420 				if (dst_ipif == NULL) {
21421 					ip1dbg(("ip_wput: no route for "
21422 					    "dst using SO_DONTROUTE\n"));
21423 					BUMP_MIB(&ipst->ips_ip_mib,
21424 					    ipIfStatsOutNoRoutes);
21425 					mp->b_prev = mp->b_next = NULL;
21426 					if (first_mp == NULL)
21427 						first_mp = mp;
21428 					goto drop_pkt;
21429 				} else {
21430 					/*
21431 					 * If suitable ipif has been found, set
21432 					 * xmit_ill to the corresponding
21433 					 * ipif_ill because we'll be following
21434 					 * the IP_XMIT_IF logic.
21435 					 */
21436 					ASSERT(xmit_ill == NULL);
21437 					xmit_ill = dst_ipif->ipif_ill;
21438 					mutex_enter(&xmit_ill->ill_lock);
21439 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21440 						mutex_exit(&xmit_ill->ill_lock);
21441 						xmit_ill = NULL;
21442 						ipif_refrele(dst_ipif);
21443 						ip1dbg(("ip_wput: no route for"
21444 						    " dst using"
21445 						    " SO_DONTROUTE\n"));
21446 						BUMP_MIB(&ipst->ips_ip_mib,
21447 						    ipIfStatsOutNoRoutes);
21448 						mp->b_prev = mp->b_next = NULL;
21449 						if (first_mp == NULL)
21450 							first_mp = mp;
21451 						goto drop_pkt;
21452 					}
21453 					ill_refhold_locked(xmit_ill);
21454 					mutex_exit(&xmit_ill->ill_lock);
21455 					ipif_refrele(dst_ipif);
21456 				}
21457 			}
21458 
21459 		}
21460 		/*
21461 		 * If we are bound to IPIF_NOFAILOVER address, look for
21462 		 * an IRE_CACHE matching the ill.
21463 		 */
21464 send_from_ill:
21465 		if (attach_ill != NULL) {
21466 			ipif_t	*attach_ipif;
21467 
21468 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21469 
21470 			/*
21471 			 * Check if we need an ire that will not be
21472 			 * looked up by anybody else i.e. HIDDEN.
21473 			 */
21474 			if (ill_is_probeonly(attach_ill)) {
21475 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21476 			}
21477 
21478 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21479 			if (attach_ipif == NULL) {
21480 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21481 				goto discard_pkt;
21482 			}
21483 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21484 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21485 			ipif_refrele(attach_ipif);
21486 		} else if (xmit_ill != NULL || (connp != NULL &&
21487 		    connp->conn_xmit_if_ill != NULL)) {
21488 			/*
21489 			 * Mark this packet as originated locally
21490 			 */
21491 			mp->b_prev = mp->b_next = NULL;
21492 			/*
21493 			 * xmit_ill could be NULL if SO_DONTROUTE
21494 			 * is also set.
21495 			 */
21496 			if (xmit_ill == NULL) {
21497 				xmit_ill = conn_get_held_ill(connp,
21498 				    &connp->conn_xmit_if_ill, &err);
21499 				if (err == ILL_LOOKUP_FAILED) {
21500 					BUMP_MIB(&ipst->ips_ip_mib,
21501 					    ipIfStatsOutDiscards);
21502 					if (need_decref)
21503 						CONN_DEC_REF(connp);
21504 					freemsg(first_mp);
21505 					return;
21506 				}
21507 				if (xmit_ill == NULL) {
21508 					if (connp->conn_dontroute)
21509 						goto dontroute;
21510 					goto send_from_ill;
21511 				}
21512 			}
21513 			/*
21514 			 * Could be SO_DONTROUTE case also.
21515 			 * check at least one interface is UP as
21516 			 * specified by this ILL
21517 			 */
21518 			if (xmit_ill->ill_ipif_up_count > 0) {
21519 				ipif_t *ipif;
21520 
21521 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21522 				if (ipif == NULL) {
21523 					ip1dbg(("ip_output: "
21524 					    "xmit_ill NULL ipif\n"));
21525 					goto drop_pkt;
21526 				}
21527 				/*
21528 				 * Look for a ire that is part of the group,
21529 				 * if found use it else call ip_newroute_ipif.
21530 				 * IPCL_ZONEID is not used for matching because
21531 				 * IP_ALLZONES option is valid only when the
21532 				 * ill is accessible from all zones i.e has a
21533 				 * valid ipif in all zones.
21534 				 */
21535 				match_flags = MATCH_IRE_ILL_GROUP |
21536 				    MATCH_IRE_SECATTR;
21537 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21538 				    MBLK_GETLABEL(mp), match_flags, ipst);
21539 				/*
21540 				 * If an ire exists use it or else create
21541 				 * an ire but don't add it to the cache.
21542 				 * Adding an ire may cause issues with
21543 				 * asymmetric routing.
21544 				 * In case of multiroute always act as if
21545 				 * ire does not exist.
21546 				 */
21547 				if (ire == NULL ||
21548 				    ire->ire_flags & RTF_MULTIRT) {
21549 					if (ire != NULL)
21550 						ire_refrele(ire);
21551 					ip_newroute_ipif(q, first_mp, ipif,
21552 					    dst, connp, 0, zoneid, infop);
21553 					ipif_refrele(ipif);
21554 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21555 					ill_refrele(xmit_ill);
21556 					if (need_decref)
21557 						CONN_DEC_REF(connp);
21558 					return;
21559 				}
21560 				ipif_refrele(ipif);
21561 			} else {
21562 				goto drop_pkt;
21563 			}
21564 		} else if (ip_nexthop || (connp != NULL &&
21565 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21566 			if (!ip_nexthop) {
21567 				ip_nexthop = B_TRUE;
21568 				nexthop_addr = connp->conn_nexthop_v4;
21569 			}
21570 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21571 			    MATCH_IRE_GW;
21572 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21573 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21574 		} else {
21575 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21576 			    ipst);
21577 		}
21578 		if (!ire) {
21579 			/*
21580 			 * Make sure we don't load spread if this
21581 			 * is IPIF_NOFAILOVER case.
21582 			 */
21583 			if ((attach_ill != NULL) ||
21584 			    (ip_nexthop && !ignore_nexthop)) {
21585 				if (mctl_present) {
21586 					io = (ipsec_out_t *)first_mp->b_rptr;
21587 					ASSERT(first_mp->b_datap->db_type ==
21588 					    M_CTL);
21589 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21590 				} else {
21591 					ASSERT(mp == first_mp);
21592 					first_mp = allocb(
21593 					    sizeof (ipsec_info_t), BPRI_HI);
21594 					if (first_mp == NULL) {
21595 						first_mp = mp;
21596 						goto discard_pkt;
21597 					}
21598 					first_mp->b_datap->db_type = M_CTL;
21599 					first_mp->b_wptr +=
21600 					    sizeof (ipsec_info_t);
21601 					/* ipsec_out_secure is B_FALSE now */
21602 					bzero(first_mp->b_rptr,
21603 					    sizeof (ipsec_info_t));
21604 					io = (ipsec_out_t *)first_mp->b_rptr;
21605 					io->ipsec_out_type = IPSEC_OUT;
21606 					io->ipsec_out_len =
21607 					    sizeof (ipsec_out_t);
21608 					io->ipsec_out_use_global_policy =
21609 					    B_TRUE;
21610 					io->ipsec_out_ns = ipst->ips_netstack;
21611 					first_mp->b_cont = mp;
21612 					mctl_present = B_TRUE;
21613 				}
21614 				if (attach_ill != NULL) {
21615 					io->ipsec_out_ill_index = attach_ill->
21616 					    ill_phyint->phyint_ifindex;
21617 					io->ipsec_out_attach_if = B_TRUE;
21618 				} else {
21619 					io->ipsec_out_ip_nexthop = ip_nexthop;
21620 					io->ipsec_out_nexthop_addr =
21621 					    nexthop_addr;
21622 				}
21623 			}
21624 noirefound:
21625 			/*
21626 			 * Mark this packet as having originated on
21627 			 * this machine.  This will be noted in
21628 			 * ire_add_then_send, which needs to know
21629 			 * whether to run it back through ip_wput or
21630 			 * ip_rput following successful resolution.
21631 			 */
21632 			mp->b_prev = NULL;
21633 			mp->b_next = NULL;
21634 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21635 			    ipst);
21636 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21637 			    "ip_wput_end: q %p (%S)", q, "newroute");
21638 			if (attach_ill != NULL)
21639 				ill_refrele(attach_ill);
21640 			if (xmit_ill != NULL)
21641 				ill_refrele(xmit_ill);
21642 			if (need_decref)
21643 				CONN_DEC_REF(connp);
21644 			return;
21645 		}
21646 	}
21647 
21648 	/* We now know where we are going with it. */
21649 
21650 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21651 	    "ip_wput_end: q %p (%S)", q, "end");
21652 
21653 	/*
21654 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21655 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21656 	 */
21657 	if (ire->ire_flags & RTF_MULTIRT) {
21658 		/*
21659 		 * Force the TTL of multirouted packets if required.
21660 		 * The TTL of such packets is bounded by the
21661 		 * ip_multirt_ttl ndd variable.
21662 		 */
21663 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21664 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21665 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21666 			    "(was %d), dst 0x%08x\n",
21667 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21668 			    ntohl(ire->ire_addr)));
21669 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21670 		}
21671 		/*
21672 		 * At this point, we check to see if there are any pending
21673 		 * unresolved routes. ire_multirt_resolvable()
21674 		 * checks in O(n) that all IRE_OFFSUBNET ire
21675 		 * entries for the packet's destination and
21676 		 * flagged RTF_MULTIRT are currently resolved.
21677 		 * If some remain unresolved, we make a copy
21678 		 * of the current message. It will be used
21679 		 * to initiate additional route resolutions.
21680 		 */
21681 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21682 		    MBLK_GETLABEL(first_mp), ipst);
21683 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21684 		    "multirt_need_resolve %d, first_mp %p\n",
21685 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21686 		if (multirt_need_resolve) {
21687 			copy_mp = copymsg(first_mp);
21688 			if (copy_mp != NULL) {
21689 				MULTIRT_DEBUG_TAG(copy_mp);
21690 			}
21691 		}
21692 	}
21693 
21694 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21695 	/*
21696 	 * Try to resolve another multiroute if
21697 	 * ire_multirt_resolvable() deemed it necessary.
21698 	 * At this point, we need to distinguish
21699 	 * multicasts from other packets. For multicasts,
21700 	 * we call ip_newroute_ipif() and request that both
21701 	 * multirouting and setsrc flags are checked.
21702 	 */
21703 	if (copy_mp != NULL) {
21704 		if (CLASSD(dst)) {
21705 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21706 			if (ipif) {
21707 				ASSERT(infop->ip_opt_ill_index == 0);
21708 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21709 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21710 				ipif_refrele(ipif);
21711 			} else {
21712 				MULTIRT_DEBUG_UNTAG(copy_mp);
21713 				freemsg(copy_mp);
21714 				copy_mp = NULL;
21715 			}
21716 		} else {
21717 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21718 		}
21719 	}
21720 	if (attach_ill != NULL)
21721 		ill_refrele(attach_ill);
21722 	if (xmit_ill != NULL)
21723 		ill_refrele(xmit_ill);
21724 	if (need_decref)
21725 		CONN_DEC_REF(connp);
21726 	return;
21727 
21728 icmp_parameter_problem:
21729 	/* could not have originated externally */
21730 	ASSERT(mp->b_prev == NULL);
21731 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21732 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21733 		/* it's the IP header length that's in trouble */
21734 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21735 		first_mp = NULL;
21736 	}
21737 
21738 discard_pkt:
21739 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21740 drop_pkt:
21741 	ip1dbg(("ip_wput: dropped packet\n"));
21742 	if (ire != NULL)
21743 		ire_refrele(ire);
21744 	if (need_decref)
21745 		CONN_DEC_REF(connp);
21746 	freemsg(first_mp);
21747 	if (attach_ill != NULL)
21748 		ill_refrele(attach_ill);
21749 	if (xmit_ill != NULL)
21750 		ill_refrele(xmit_ill);
21751 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21752 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21753 }
21754 
21755 /*
21756  * If this is a conn_t queue, then we pass in the conn. This includes the
21757  * zoneid.
21758  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21759  * in which case we use the global zoneid since those are all part of
21760  * the global zone.
21761  */
21762 void
21763 ip_wput(queue_t *q, mblk_t *mp)
21764 {
21765 	if (CONN_Q(q))
21766 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21767 	else
21768 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21769 }
21770 
21771 /*
21772  *
21773  * The following rules must be observed when accessing any ipif or ill
21774  * that has been cached in the conn. Typically conn_nofailover_ill,
21775  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21776  *
21777  * Access: The ipif or ill pointed to from the conn can be accessed under
21778  * the protection of the conn_lock or after it has been refheld under the
21779  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21780  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21781  * The reason for this is that a concurrent unplumb could actually be
21782  * cleaning up these cached pointers by walking the conns and might have
21783  * finished cleaning up the conn in question. The macros check that an
21784  * unplumb has not yet started on the ipif or ill.
21785  *
21786  * Caching: An ipif or ill pointer may be cached in the conn only after
21787  * making sure that an unplumb has not started. So the caching is done
21788  * while holding both the conn_lock and the ill_lock and after using the
21789  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21790  * flag before starting the cleanup of conns.
21791  *
21792  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21793  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21794  * or a reference to the ipif or a reference to an ire that references the
21795  * ipif. An ipif does not change its ill except for failover/failback. Since
21796  * failover/failback happens only after bringing down the ipif and making sure
21797  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21798  * the above holds.
21799  */
21800 ipif_t *
21801 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21802 {
21803 	ipif_t	*ipif;
21804 	ill_t	*ill;
21805 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21806 
21807 	*err = 0;
21808 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21809 	mutex_enter(&connp->conn_lock);
21810 	ipif = *ipifp;
21811 	if (ipif != NULL) {
21812 		ill = ipif->ipif_ill;
21813 		mutex_enter(&ill->ill_lock);
21814 		if (IPIF_CAN_LOOKUP(ipif)) {
21815 			ipif_refhold_locked(ipif);
21816 			mutex_exit(&ill->ill_lock);
21817 			mutex_exit(&connp->conn_lock);
21818 			rw_exit(&ipst->ips_ill_g_lock);
21819 			return (ipif);
21820 		} else {
21821 			*err = IPIF_LOOKUP_FAILED;
21822 		}
21823 		mutex_exit(&ill->ill_lock);
21824 	}
21825 	mutex_exit(&connp->conn_lock);
21826 	rw_exit(&ipst->ips_ill_g_lock);
21827 	return (NULL);
21828 }
21829 
21830 ill_t *
21831 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21832 {
21833 	ill_t	*ill;
21834 
21835 	*err = 0;
21836 	mutex_enter(&connp->conn_lock);
21837 	ill = *illp;
21838 	if (ill != NULL) {
21839 		mutex_enter(&ill->ill_lock);
21840 		if (ILL_CAN_LOOKUP(ill)) {
21841 			ill_refhold_locked(ill);
21842 			mutex_exit(&ill->ill_lock);
21843 			mutex_exit(&connp->conn_lock);
21844 			return (ill);
21845 		} else {
21846 			*err = ILL_LOOKUP_FAILED;
21847 		}
21848 		mutex_exit(&ill->ill_lock);
21849 	}
21850 	mutex_exit(&connp->conn_lock);
21851 	return (NULL);
21852 }
21853 
21854 static int
21855 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21856 {
21857 	ill_t	*ill;
21858 
21859 	ill = ipif->ipif_ill;
21860 	mutex_enter(&connp->conn_lock);
21861 	mutex_enter(&ill->ill_lock);
21862 	if (IPIF_CAN_LOOKUP(ipif)) {
21863 		*ipifp = ipif;
21864 		mutex_exit(&ill->ill_lock);
21865 		mutex_exit(&connp->conn_lock);
21866 		return (0);
21867 	}
21868 	mutex_exit(&ill->ill_lock);
21869 	mutex_exit(&connp->conn_lock);
21870 	return (IPIF_LOOKUP_FAILED);
21871 }
21872 
21873 /*
21874  * This is called if the outbound datagram needs fragmentation.
21875  *
21876  * NOTE : This function does not ire_refrele the ire argument passed in.
21877  */
21878 static void
21879 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21880     ip_stack_t *ipst)
21881 {
21882 	ipha_t		*ipha;
21883 	mblk_t		*mp;
21884 	uint32_t	v_hlen_tos_len;
21885 	uint32_t	max_frag;
21886 	uint32_t	frag_flag;
21887 	boolean_t	dont_use;
21888 
21889 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21890 		mp = ipsec_mp->b_cont;
21891 	} else {
21892 		mp = ipsec_mp;
21893 	}
21894 
21895 	ipha = (ipha_t *)mp->b_rptr;
21896 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21897 
21898 #ifdef	_BIG_ENDIAN
21899 #define	V_HLEN	(v_hlen_tos_len >> 24)
21900 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21901 #else
21902 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21903 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21904 #endif
21905 
21906 #ifndef SPEED_BEFORE_SAFETY
21907 	/*
21908 	 * Check that ipha_length is consistent with
21909 	 * the mblk length
21910 	 */
21911 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21912 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21913 		    LENGTH, msgdsize(mp)));
21914 		freemsg(ipsec_mp);
21915 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21916 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21917 		    "packet length mismatch");
21918 		return;
21919 	}
21920 #endif
21921 	/*
21922 	 * Don't use frag_flag if pre-built packet or source
21923 	 * routed or if multicast (since multicast packets do not solicit
21924 	 * ICMP "packet too big" messages). Get the values of
21925 	 * max_frag and frag_flag atomically by acquiring the
21926 	 * ire_lock.
21927 	 */
21928 	mutex_enter(&ire->ire_lock);
21929 	max_frag = ire->ire_max_frag;
21930 	frag_flag = ire->ire_frag_flag;
21931 	mutex_exit(&ire->ire_lock);
21932 
21933 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21934 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21935 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21936 
21937 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21938 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21939 }
21940 
21941 /*
21942  * Used for deciding the MSS size for the upper layer. Thus
21943  * we need to check the outbound policy values in the conn.
21944  */
21945 int
21946 conn_ipsec_length(conn_t *connp)
21947 {
21948 	ipsec_latch_t *ipl;
21949 
21950 	ipl = connp->conn_latch;
21951 	if (ipl == NULL)
21952 		return (0);
21953 
21954 	if (ipl->ipl_out_policy == NULL)
21955 		return (0);
21956 
21957 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21958 }
21959 
21960 /*
21961  * Returns an estimate of the IPSEC headers size. This is used if
21962  * we don't want to call into IPSEC to get the exact size.
21963  */
21964 int
21965 ipsec_out_extra_length(mblk_t *ipsec_mp)
21966 {
21967 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21968 	ipsec_action_t *a;
21969 
21970 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21971 	if (!io->ipsec_out_secure)
21972 		return (0);
21973 
21974 	a = io->ipsec_out_act;
21975 
21976 	if (a == NULL) {
21977 		ASSERT(io->ipsec_out_policy != NULL);
21978 		a = io->ipsec_out_policy->ipsp_act;
21979 	}
21980 	ASSERT(a != NULL);
21981 
21982 	return (a->ipa_ovhd);
21983 }
21984 
21985 /*
21986  * Returns an estimate of the IPSEC headers size. This is used if
21987  * we don't want to call into IPSEC to get the exact size.
21988  */
21989 int
21990 ipsec_in_extra_length(mblk_t *ipsec_mp)
21991 {
21992 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21993 	ipsec_action_t *a;
21994 
21995 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21996 
21997 	a = ii->ipsec_in_action;
21998 	return (a == NULL ? 0 : a->ipa_ovhd);
21999 }
22000 
22001 /*
22002  * If there are any source route options, return the true final
22003  * destination. Otherwise, return the destination.
22004  */
22005 ipaddr_t
22006 ip_get_dst(ipha_t *ipha)
22007 {
22008 	ipoptp_t	opts;
22009 	uchar_t		*opt;
22010 	uint8_t		optval;
22011 	uint8_t		optlen;
22012 	ipaddr_t	dst;
22013 	uint32_t off;
22014 
22015 	dst = ipha->ipha_dst;
22016 
22017 	if (IS_SIMPLE_IPH(ipha))
22018 		return (dst);
22019 
22020 	for (optval = ipoptp_first(&opts, ipha);
22021 	    optval != IPOPT_EOL;
22022 	    optval = ipoptp_next(&opts)) {
22023 		opt = opts.ipoptp_cur;
22024 		optlen = opts.ipoptp_len;
22025 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22026 		switch (optval) {
22027 		case IPOPT_SSRR:
22028 		case IPOPT_LSRR:
22029 			off = opt[IPOPT_OFFSET];
22030 			/*
22031 			 * If one of the conditions is true, it means
22032 			 * end of options and dst already has the right
22033 			 * value.
22034 			 */
22035 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22036 				off = optlen - IP_ADDR_LEN;
22037 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22038 			}
22039 			return (dst);
22040 		default:
22041 			break;
22042 		}
22043 	}
22044 
22045 	return (dst);
22046 }
22047 
22048 mblk_t *
22049 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22050     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22051 {
22052 	ipsec_out_t	*io;
22053 	mblk_t		*first_mp;
22054 	boolean_t policy_present;
22055 	ip_stack_t	*ipst;
22056 	ipsec_stack_t	*ipss;
22057 
22058 	ASSERT(ire != NULL);
22059 	ipst = ire->ire_ipst;
22060 	ipss = ipst->ips_netstack->netstack_ipsec;
22061 
22062 	first_mp = mp;
22063 	if (mp->b_datap->db_type == M_CTL) {
22064 		io = (ipsec_out_t *)first_mp->b_rptr;
22065 		/*
22066 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22067 		 *
22068 		 * 1) There is per-socket policy (including cached global
22069 		 *    policy) or a policy on the IP-in-IP tunnel.
22070 		 * 2) There is no per-socket policy, but it is
22071 		 *    a multicast packet that needs to go out
22072 		 *    on a specific interface. This is the case
22073 		 *    where (ip_wput and ip_wput_multicast) attaches
22074 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22075 		 *
22076 		 * In case (2) we check with global policy to
22077 		 * see if there is a match and set the ill_index
22078 		 * appropriately so that we can lookup the ire
22079 		 * properly in ip_wput_ipsec_out.
22080 		 */
22081 
22082 		/*
22083 		 * ipsec_out_use_global_policy is set to B_FALSE
22084 		 * in ipsec_in_to_out(). Refer to that function for
22085 		 * details.
22086 		 */
22087 		if ((io->ipsec_out_latch == NULL) &&
22088 		    (io->ipsec_out_use_global_policy)) {
22089 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22090 			    ire, connp, unspec_src, zoneid));
22091 		}
22092 		if (!io->ipsec_out_secure) {
22093 			/*
22094 			 * If this is not a secure packet, drop
22095 			 * the IPSEC_OUT mp and treat it as a clear
22096 			 * packet. This happens when we are sending
22097 			 * a ICMP reply back to a clear packet. See
22098 			 * ipsec_in_to_out() for details.
22099 			 */
22100 			mp = first_mp->b_cont;
22101 			freeb(first_mp);
22102 		}
22103 		return (mp);
22104 	}
22105 	/*
22106 	 * See whether we need to attach a global policy here. We
22107 	 * don't depend on the conn (as it could be null) for deciding
22108 	 * what policy this datagram should go through because it
22109 	 * should have happened in ip_wput if there was some
22110 	 * policy. This normally happens for connections which are not
22111 	 * fully bound preventing us from caching policies in
22112 	 * ip_bind. Packets coming from the TCP listener/global queue
22113 	 * - which are non-hard_bound - could also be affected by
22114 	 * applying policy here.
22115 	 *
22116 	 * If this packet is coming from tcp global queue or listener,
22117 	 * we will be applying policy here.  This may not be *right*
22118 	 * if these packets are coming from the detached connection as
22119 	 * it could have gone in clear before. This happens only if a
22120 	 * TCP connection started when there is no policy and somebody
22121 	 * added policy before it became detached. Thus packets of the
22122 	 * detached connection could go out secure and the other end
22123 	 * would drop it because it will be expecting in clear. The
22124 	 * converse is not true i.e if somebody starts a TCP
22125 	 * connection and deletes the policy, all the packets will
22126 	 * still go out with the policy that existed before deleting
22127 	 * because ip_unbind sends up policy information which is used
22128 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22129 	 * TCP to attach a dummy IPSEC_OUT and set
22130 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22131 	 * affect performance for normal cases, we are not doing it.
22132 	 * Thus, set policy before starting any TCP connections.
22133 	 *
22134 	 * NOTE - We might apply policy even for a hard bound connection
22135 	 * - for which we cached policy in ip_bind - if somebody added
22136 	 * global policy after we inherited the policy in ip_bind.
22137 	 * This means that the packets that were going out in clear
22138 	 * previously would start going secure and hence get dropped
22139 	 * on the other side. To fix this, TCP attaches a dummy
22140 	 * ipsec_out and make sure that we don't apply global policy.
22141 	 */
22142 	if (ipha != NULL)
22143 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22144 	else
22145 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22146 	if (!policy_present)
22147 		return (mp);
22148 
22149 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22150 	    zoneid));
22151 }
22152 
22153 ire_t *
22154 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22155 {
22156 	ipaddr_t addr;
22157 	ire_t *save_ire;
22158 	irb_t *irb;
22159 	ill_group_t *illgrp;
22160 	int	err;
22161 
22162 	save_ire = ire;
22163 	addr = ire->ire_addr;
22164 
22165 	ASSERT(ire->ire_type == IRE_BROADCAST);
22166 
22167 	illgrp = connp->conn_outgoing_ill->ill_group;
22168 	if (illgrp == NULL) {
22169 		*conn_outgoing_ill = conn_get_held_ill(connp,
22170 		    &connp->conn_outgoing_ill, &err);
22171 		if (err == ILL_LOOKUP_FAILED) {
22172 			ire_refrele(save_ire);
22173 			return (NULL);
22174 		}
22175 		return (save_ire);
22176 	}
22177 	/*
22178 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22179 	 * If it is part of the group, we need to send on the ire
22180 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22181 	 * to this group. This is okay as IP_BOUND_IF really means
22182 	 * any ill in the group. We depend on the fact that the
22183 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22184 	 * if such an ire exists. This is possible only if you have
22185 	 * at least one ill in the group that has not failed.
22186 	 *
22187 	 * First get to the ire that matches the address and group.
22188 	 *
22189 	 * We don't look for an ire with a matching zoneid because a given zone
22190 	 * won't always have broadcast ires on all ills in the group.
22191 	 */
22192 	irb = ire->ire_bucket;
22193 	rw_enter(&irb->irb_lock, RW_READER);
22194 	if (ire->ire_marks & IRE_MARK_NORECV) {
22195 		/*
22196 		 * If the current zone only has an ire broadcast for this
22197 		 * address marked NORECV, the ire we want is ahead in the
22198 		 * bucket, so we look it up deliberately ignoring the zoneid.
22199 		 */
22200 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22201 			if (ire->ire_addr != addr)
22202 				continue;
22203 			/* skip over deleted ires */
22204 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22205 				continue;
22206 		}
22207 	}
22208 	while (ire != NULL) {
22209 		/*
22210 		 * If a new interface is coming up, we could end up
22211 		 * seeing the loopback ire and the non-loopback ire
22212 		 * may not have been added yet. So check for ire_stq
22213 		 */
22214 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22215 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22216 			break;
22217 		}
22218 		ire = ire->ire_next;
22219 	}
22220 	if (ire != NULL && ire->ire_addr == addr &&
22221 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22222 		IRE_REFHOLD(ire);
22223 		rw_exit(&irb->irb_lock);
22224 		ire_refrele(save_ire);
22225 		*conn_outgoing_ill = ire_to_ill(ire);
22226 		/*
22227 		 * Refhold the ill to make the conn_outgoing_ill
22228 		 * independent of the ire. ip_wput_ire goes in a loop
22229 		 * and may refrele the ire. Since we have an ire at this
22230 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22231 		 */
22232 		ill_refhold(*conn_outgoing_ill);
22233 		return (ire);
22234 	}
22235 	rw_exit(&irb->irb_lock);
22236 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22237 	/*
22238 	 * If we can't find a suitable ire, return the original ire.
22239 	 */
22240 	return (save_ire);
22241 }
22242 
22243 /*
22244  * This function does the ire_refrele of the ire passed in as the
22245  * argument. As this function looks up more ires i.e broadcast ires,
22246  * it needs to REFRELE them. Currently, for simplicity we don't
22247  * differentiate the one passed in and looked up here. We always
22248  * REFRELE.
22249  * IPQoS Notes:
22250  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22251  * IPSec packets are done in ipsec_out_process.
22252  *
22253  */
22254 void
22255 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22256     zoneid_t zoneid)
22257 {
22258 	ipha_t		*ipha;
22259 #define	rptr	((uchar_t *)ipha)
22260 	queue_t		*stq;
22261 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22262 	uint32_t	v_hlen_tos_len;
22263 	uint32_t	ttl_protocol;
22264 	ipaddr_t	src;
22265 	ipaddr_t	dst;
22266 	uint32_t	cksum;
22267 	ipaddr_t	orig_src;
22268 	ire_t		*ire1;
22269 	mblk_t		*next_mp;
22270 	uint_t		hlen;
22271 	uint16_t	*up;
22272 	uint32_t	max_frag = ire->ire_max_frag;
22273 	ill_t		*ill = ire_to_ill(ire);
22274 	int		clusterwide;
22275 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22276 	int		ipsec_len;
22277 	mblk_t		*first_mp;
22278 	ipsec_out_t	*io;
22279 	boolean_t	conn_dontroute;		/* conn value for multicast */
22280 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22281 	boolean_t	multicast_forward;	/* Should we forward ? */
22282 	boolean_t	unspec_src;
22283 	ill_t		*conn_outgoing_ill = NULL;
22284 	ill_t		*ire_ill;
22285 	ill_t		*ire1_ill;
22286 	ill_t		*out_ill;
22287 	uint32_t 	ill_index = 0;
22288 	boolean_t	multirt_send = B_FALSE;
22289 	int		err;
22290 	ipxmit_state_t	pktxmit_state;
22291 	ip_stack_t	*ipst = ire->ire_ipst;
22292 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22293 
22294 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22295 	    "ip_wput_ire_start: q %p", q);
22296 
22297 	multicast_forward = B_FALSE;
22298 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22299 
22300 	if (ire->ire_flags & RTF_MULTIRT) {
22301 		/*
22302 		 * Multirouting case. The bucket where ire is stored
22303 		 * probably holds other RTF_MULTIRT flagged ire
22304 		 * to the destination. In this call to ip_wput_ire,
22305 		 * we attempt to send the packet through all
22306 		 * those ires. Thus, we first ensure that ire is the
22307 		 * first RTF_MULTIRT ire in the bucket,
22308 		 * before walking the ire list.
22309 		 */
22310 		ire_t *first_ire;
22311 		irb_t *irb = ire->ire_bucket;
22312 		ASSERT(irb != NULL);
22313 
22314 		/* Make sure we do not omit any multiroute ire. */
22315 		IRB_REFHOLD(irb);
22316 		for (first_ire = irb->irb_ire;
22317 		    first_ire != NULL;
22318 		    first_ire = first_ire->ire_next) {
22319 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22320 			    (first_ire->ire_addr == ire->ire_addr) &&
22321 			    !(first_ire->ire_marks &
22322 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22323 				break;
22324 			}
22325 		}
22326 
22327 		if ((first_ire != NULL) && (first_ire != ire)) {
22328 			IRE_REFHOLD(first_ire);
22329 			ire_refrele(ire);
22330 			ire = first_ire;
22331 			ill = ire_to_ill(ire);
22332 		}
22333 		IRB_REFRELE(irb);
22334 	}
22335 
22336 	/*
22337 	 * conn_outgoing_ill is used only in the broadcast loop.
22338 	 * for performance we don't grab the mutexs in the fastpath
22339 	 */
22340 	if ((connp != NULL) &&
22341 	    (connp->conn_xmit_if_ill == NULL) &&
22342 	    (ire->ire_type == IRE_BROADCAST) &&
22343 	    ((connp->conn_nofailover_ill != NULL) ||
22344 	    (connp->conn_outgoing_ill != NULL))) {
22345 		/*
22346 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22347 		 * option. So, see if this endpoint is bound to a
22348 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22349 		 * that if the interface is failed, we will still send
22350 		 * the packet on the same ill which is what we want.
22351 		 */
22352 		conn_outgoing_ill = conn_get_held_ill(connp,
22353 		    &connp->conn_nofailover_ill, &err);
22354 		if (err == ILL_LOOKUP_FAILED) {
22355 			ire_refrele(ire);
22356 			freemsg(mp);
22357 			return;
22358 		}
22359 		if (conn_outgoing_ill == NULL) {
22360 			/*
22361 			 * Choose a good ill in the group to send the
22362 			 * packets on.
22363 			 */
22364 			ire = conn_set_outgoing_ill(connp, ire,
22365 			    &conn_outgoing_ill);
22366 			if (ire == NULL) {
22367 				freemsg(mp);
22368 				return;
22369 			}
22370 		}
22371 	}
22372 
22373 	if (mp->b_datap->db_type != M_CTL) {
22374 		ipha = (ipha_t *)mp->b_rptr;
22375 	} else {
22376 		io = (ipsec_out_t *)mp->b_rptr;
22377 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22378 		ASSERT(zoneid == io->ipsec_out_zoneid);
22379 		ASSERT(zoneid != ALL_ZONES);
22380 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22381 		dst = ipha->ipha_dst;
22382 		/*
22383 		 * For the multicast case, ipsec_out carries conn_dontroute and
22384 		 * conn_multicast_loop as conn may not be available here. We
22385 		 * need this for multicast loopback and forwarding which is done
22386 		 * later in the code.
22387 		 */
22388 		if (CLASSD(dst)) {
22389 			conn_dontroute = io->ipsec_out_dontroute;
22390 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22391 			/*
22392 			 * If conn_dontroute is not set or conn_multicast_loop
22393 			 * is set, we need to do forwarding/loopback. For
22394 			 * datagrams from ip_wput_multicast, conn_dontroute is
22395 			 * set to B_TRUE and conn_multicast_loop is set to
22396 			 * B_FALSE so that we neither do forwarding nor
22397 			 * loopback.
22398 			 */
22399 			if (!conn_dontroute || conn_multicast_loop)
22400 				multicast_forward = B_TRUE;
22401 		}
22402 	}
22403 
22404 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22405 	    ire->ire_zoneid != ALL_ZONES) {
22406 		/*
22407 		 * When a zone sends a packet to another zone, we try to deliver
22408 		 * the packet under the same conditions as if the destination
22409 		 * was a real node on the network. To do so, we look for a
22410 		 * matching route in the forwarding table.
22411 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22412 		 * ip_newroute() does.
22413 		 * Note that IRE_LOCAL are special, since they are used
22414 		 * when the zoneid doesn't match in some cases. This means that
22415 		 * we need to handle ipha_src differently since ire_src_addr
22416 		 * belongs to the receiving zone instead of the sending zone.
22417 		 * When ip_restrict_interzone_loopback is set, then
22418 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22419 		 * for loopback between zones when the logical "Ethernet" would
22420 		 * have looped them back.
22421 		 */
22422 		ire_t *src_ire;
22423 
22424 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22425 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22426 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22427 		if (src_ire != NULL &&
22428 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22429 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22430 		    ire_local_same_ill_group(ire, src_ire))) {
22431 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22432 				ipha->ipha_src = src_ire->ire_src_addr;
22433 			ire_refrele(src_ire);
22434 		} else {
22435 			ire_refrele(ire);
22436 			if (conn_outgoing_ill != NULL)
22437 				ill_refrele(conn_outgoing_ill);
22438 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22439 			if (src_ire != NULL) {
22440 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22441 					ire_refrele(src_ire);
22442 					freemsg(mp);
22443 					return;
22444 				}
22445 				ire_refrele(src_ire);
22446 			}
22447 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22448 				/* Failed */
22449 				freemsg(mp);
22450 				return;
22451 			}
22452 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22453 			    ipst);
22454 			return;
22455 		}
22456 	}
22457 
22458 	if (mp->b_datap->db_type == M_CTL ||
22459 	    ipss->ipsec_outbound_v4_policy_present) {
22460 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22461 		    unspec_src, zoneid);
22462 		if (mp == NULL) {
22463 			ire_refrele(ire);
22464 			if (conn_outgoing_ill != NULL)
22465 				ill_refrele(conn_outgoing_ill);
22466 			return;
22467 		}
22468 	}
22469 
22470 	first_mp = mp;
22471 	ipsec_len = 0;
22472 
22473 	if (first_mp->b_datap->db_type == M_CTL) {
22474 		io = (ipsec_out_t *)first_mp->b_rptr;
22475 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22476 		mp = first_mp->b_cont;
22477 		ipsec_len = ipsec_out_extra_length(first_mp);
22478 		ASSERT(ipsec_len >= 0);
22479 		/* We already picked up the zoneid from the M_CTL above */
22480 		ASSERT(zoneid == io->ipsec_out_zoneid);
22481 		ASSERT(zoneid != ALL_ZONES);
22482 
22483 		/*
22484 		 * Drop M_CTL here if IPsec processing is not needed.
22485 		 * (Non-IPsec use of M_CTL extracted any information it
22486 		 * needed above).
22487 		 */
22488 		if (ipsec_len == 0) {
22489 			freeb(first_mp);
22490 			first_mp = mp;
22491 		}
22492 	}
22493 
22494 	/*
22495 	 * Fast path for ip_wput_ire
22496 	 */
22497 
22498 	ipha = (ipha_t *)mp->b_rptr;
22499 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22500 	dst = ipha->ipha_dst;
22501 
22502 	/*
22503 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22504 	 * if the socket is a SOCK_RAW type. The transport checksum should
22505 	 * be provided in the pre-built packet, so we don't need to compute it.
22506 	 * Also, other application set flags, like DF, should not be altered.
22507 	 * Other transport MUST pass down zero.
22508 	 */
22509 	ip_hdr_included = ipha->ipha_ident;
22510 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22511 
22512 	if (CLASSD(dst)) {
22513 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22514 		    ntohl(dst),
22515 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22516 		    ntohl(ire->ire_addr)));
22517 	}
22518 
22519 /* Macros to extract header fields from data already in registers */
22520 #ifdef	_BIG_ENDIAN
22521 #define	V_HLEN	(v_hlen_tos_len >> 24)
22522 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22523 #define	PROTO	(ttl_protocol & 0xFF)
22524 #else
22525 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22526 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22527 #define	PROTO	(ttl_protocol >> 8)
22528 #endif
22529 
22530 
22531 	orig_src = src = ipha->ipha_src;
22532 	/* (The loop back to "another" is explained down below.) */
22533 another:;
22534 	/*
22535 	 * Assign an ident value for this packet.  We assign idents on
22536 	 * a per destination basis out of the IRE.  There could be
22537 	 * other threads targeting the same destination, so we have to
22538 	 * arrange for a atomic increment.  Note that we use a 32-bit
22539 	 * atomic add because it has better performance than its
22540 	 * 16-bit sibling.
22541 	 *
22542 	 * If running in cluster mode and if the source address
22543 	 * belongs to a replicated service then vector through
22544 	 * cl_inet_ipident vector to allocate ip identifier
22545 	 * NOTE: This is a contract private interface with the
22546 	 * clustering group.
22547 	 */
22548 	clusterwide = 0;
22549 	if (cl_inet_ipident) {
22550 		ASSERT(cl_inet_isclusterwide);
22551 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22552 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22553 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22554 			    AF_INET, (uint8_t *)(uintptr_t)src,
22555 			    (uint8_t *)(uintptr_t)dst);
22556 			clusterwide = 1;
22557 		}
22558 	}
22559 	if (!clusterwide) {
22560 		ipha->ipha_ident =
22561 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22562 	}
22563 
22564 #ifndef _BIG_ENDIAN
22565 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22566 #endif
22567 
22568 	/*
22569 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22570 	 * This is needed to obey conn_unspec_src when packets go through
22571 	 * ip_newroute + arp.
22572 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22573 	 */
22574 	if (src == INADDR_ANY && !unspec_src) {
22575 		/*
22576 		 * Assign the appropriate source address from the IRE if none
22577 		 * was specified.
22578 		 */
22579 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22580 
22581 		/*
22582 		 * With IP multipathing, broadcast packets are sent on the ire
22583 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22584 		 * the group. However, this ire might not be in the same zone so
22585 		 * we can't always use its source address. We look for a
22586 		 * broadcast ire in the same group and in the right zone.
22587 		 */
22588 		if (ire->ire_type == IRE_BROADCAST &&
22589 		    ire->ire_zoneid != zoneid) {
22590 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22591 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22592 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22593 			if (src_ire != NULL) {
22594 				src = src_ire->ire_src_addr;
22595 				ire_refrele(src_ire);
22596 			} else {
22597 				ire_refrele(ire);
22598 				if (conn_outgoing_ill != NULL)
22599 					ill_refrele(conn_outgoing_ill);
22600 				freemsg(first_mp);
22601 				if (ill != NULL) {
22602 					BUMP_MIB(ill->ill_ip_mib,
22603 					    ipIfStatsOutDiscards);
22604 				} else {
22605 					BUMP_MIB(&ipst->ips_ip_mib,
22606 					    ipIfStatsOutDiscards);
22607 				}
22608 				return;
22609 			}
22610 		} else {
22611 			src = ire->ire_src_addr;
22612 		}
22613 
22614 		if (connp == NULL) {
22615 			ip1dbg(("ip_wput_ire: no connp and no src "
22616 			    "address for dst 0x%x, using src 0x%x\n",
22617 			    ntohl(dst),
22618 			    ntohl(src)));
22619 		}
22620 		ipha->ipha_src = src;
22621 	}
22622 	stq = ire->ire_stq;
22623 
22624 	/*
22625 	 * We only allow ire chains for broadcasts since there will
22626 	 * be multiple IRE_CACHE entries for the same multicast
22627 	 * address (one per ipif).
22628 	 */
22629 	next_mp = NULL;
22630 
22631 	/* broadcast packet */
22632 	if (ire->ire_type == IRE_BROADCAST)
22633 		goto broadcast;
22634 
22635 	/* loopback ? */
22636 	if (stq == NULL)
22637 		goto nullstq;
22638 
22639 	/* The ill_index for outbound ILL */
22640 	ill_index = Q_TO_INDEX(stq);
22641 
22642 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22643 	ttl_protocol = ((uint16_t *)ipha)[4];
22644 
22645 	/* pseudo checksum (do it in parts for IP header checksum) */
22646 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22647 
22648 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22649 		queue_t *dev_q = stq->q_next;
22650 
22651 		/* flow controlled */
22652 		if ((dev_q->q_next || dev_q->q_first) &&
22653 		    !canput(dev_q))
22654 			goto blocked;
22655 		if ((PROTO == IPPROTO_UDP) &&
22656 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22657 			hlen = (V_HLEN & 0xF) << 2;
22658 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22659 			if (*up != 0) {
22660 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22661 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22662 				/* Software checksum? */
22663 				if (DB_CKSUMFLAGS(mp) == 0) {
22664 					IP_STAT(ipst, ip_out_sw_cksum);
22665 					IP_STAT_UPDATE(ipst,
22666 					    ip_udp_out_sw_cksum_bytes,
22667 					    LENGTH - hlen);
22668 				}
22669 			}
22670 		}
22671 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22672 		hlen = (V_HLEN & 0xF) << 2;
22673 		if (PROTO == IPPROTO_TCP) {
22674 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22675 			/*
22676 			 * The packet header is processed once and for all, even
22677 			 * in the multirouting case. We disable hardware
22678 			 * checksum if the packet is multirouted, as it will be
22679 			 * replicated via several interfaces, and not all of
22680 			 * them may have this capability.
22681 			 */
22682 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22683 			    LENGTH, max_frag, ipsec_len, cksum);
22684 			/* Software checksum? */
22685 			if (DB_CKSUMFLAGS(mp) == 0) {
22686 				IP_STAT(ipst, ip_out_sw_cksum);
22687 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22688 				    LENGTH - hlen);
22689 			}
22690 		} else {
22691 			sctp_hdr_t	*sctph;
22692 
22693 			ASSERT(PROTO == IPPROTO_SCTP);
22694 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22695 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22696 			/*
22697 			 * Zero out the checksum field to ensure proper
22698 			 * checksum calculation.
22699 			 */
22700 			sctph->sh_chksum = 0;
22701 #ifdef	DEBUG
22702 			if (!skip_sctp_cksum)
22703 #endif
22704 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22705 		}
22706 	}
22707 
22708 	/*
22709 	 * If this is a multicast packet and originated from ip_wput
22710 	 * we need to do loopback and forwarding checks. If it comes
22711 	 * from ip_wput_multicast, we SHOULD not do this.
22712 	 */
22713 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22714 
22715 	/* checksum */
22716 	cksum += ttl_protocol;
22717 
22718 	/* fragment the packet */
22719 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22720 		goto fragmentit;
22721 	/*
22722 	 * Don't use frag_flag if packet is pre-built or source
22723 	 * routed or if multicast (since multicast packets do
22724 	 * not solicit ICMP "packet too big" messages).
22725 	 */
22726 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22727 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22728 	    !ip_source_route_included(ipha)) &&
22729 	    !CLASSD(ipha->ipha_dst))
22730 		ipha->ipha_fragment_offset_and_flags |=
22731 		    htons(ire->ire_frag_flag);
22732 
22733 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22734 		/* calculate IP header checksum */
22735 		cksum += ipha->ipha_ident;
22736 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22737 		cksum += ipha->ipha_fragment_offset_and_flags;
22738 
22739 		/* IP options present */
22740 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22741 		if (hlen)
22742 			goto checksumoptions;
22743 
22744 		/* calculate hdr checksum */
22745 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22746 		cksum = ~(cksum + (cksum >> 16));
22747 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22748 	}
22749 	if (ipsec_len != 0) {
22750 		/*
22751 		 * We will do the rest of the processing after
22752 		 * we come back from IPSEC in ip_wput_ipsec_out().
22753 		 */
22754 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22755 
22756 		io = (ipsec_out_t *)first_mp->b_rptr;
22757 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22758 		    ill_phyint->phyint_ifindex;
22759 
22760 		ipsec_out_process(q, first_mp, ire, ill_index);
22761 		ire_refrele(ire);
22762 		if (conn_outgoing_ill != NULL)
22763 			ill_refrele(conn_outgoing_ill);
22764 		return;
22765 	}
22766 
22767 	/*
22768 	 * In most cases, the emission loop below is entered only
22769 	 * once. Only in the case where the ire holds the
22770 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22771 	 * flagged ires in the bucket, and send the packet
22772 	 * through all crossed RTF_MULTIRT routes.
22773 	 */
22774 	if (ire->ire_flags & RTF_MULTIRT) {
22775 		multirt_send = B_TRUE;
22776 	}
22777 	do {
22778 		if (multirt_send) {
22779 			irb_t *irb;
22780 			/*
22781 			 * We are in a multiple send case, need to get
22782 			 * the next ire and make a duplicate of the packet.
22783 			 * ire1 holds here the next ire to process in the
22784 			 * bucket. If multirouting is expected,
22785 			 * any non-RTF_MULTIRT ire that has the
22786 			 * right destination address is ignored.
22787 			 */
22788 			irb = ire->ire_bucket;
22789 			ASSERT(irb != NULL);
22790 
22791 			IRB_REFHOLD(irb);
22792 			for (ire1 = ire->ire_next;
22793 			    ire1 != NULL;
22794 			    ire1 = ire1->ire_next) {
22795 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22796 					continue;
22797 				if (ire1->ire_addr != ire->ire_addr)
22798 					continue;
22799 				if (ire1->ire_marks &
22800 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22801 					continue;
22802 
22803 				/* Got one */
22804 				IRE_REFHOLD(ire1);
22805 				break;
22806 			}
22807 			IRB_REFRELE(irb);
22808 
22809 			if (ire1 != NULL) {
22810 				next_mp = copyb(mp);
22811 				if ((next_mp == NULL) ||
22812 				    ((mp->b_cont != NULL) &&
22813 				    ((next_mp->b_cont =
22814 				    dupmsg(mp->b_cont)) == NULL))) {
22815 					freemsg(next_mp);
22816 					next_mp = NULL;
22817 					ire_refrele(ire1);
22818 					ire1 = NULL;
22819 				}
22820 			}
22821 
22822 			/* Last multiroute ire; don't loop anymore. */
22823 			if (ire1 == NULL) {
22824 				multirt_send = B_FALSE;
22825 			}
22826 		}
22827 
22828 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22829 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22830 		    mblk_t *, mp);
22831 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22832 		    ipst->ips_ipv4firewall_physical_out,
22833 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22834 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22835 		if (mp == NULL)
22836 			goto release_ire_and_ill;
22837 
22838 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22839 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22840 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22841 		if ((pktxmit_state == SEND_FAILED) ||
22842 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22843 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22844 			    "- packet dropped\n"));
22845 release_ire_and_ill:
22846 			ire_refrele(ire);
22847 			if (next_mp != NULL) {
22848 				freemsg(next_mp);
22849 				ire_refrele(ire1);
22850 			}
22851 			if (conn_outgoing_ill != NULL)
22852 				ill_refrele(conn_outgoing_ill);
22853 			return;
22854 		}
22855 
22856 		if (CLASSD(dst)) {
22857 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22858 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22859 			    LENGTH);
22860 		}
22861 
22862 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22863 		    "ip_wput_ire_end: q %p (%S)",
22864 		    q, "last copy out");
22865 		IRE_REFRELE(ire);
22866 
22867 		if (multirt_send) {
22868 			ASSERT(ire1);
22869 			/*
22870 			 * Proceed with the next RTF_MULTIRT ire,
22871 			 * Also set up the send-to queue accordingly.
22872 			 */
22873 			ire = ire1;
22874 			ire1 = NULL;
22875 			stq = ire->ire_stq;
22876 			mp = next_mp;
22877 			next_mp = NULL;
22878 			ipha = (ipha_t *)mp->b_rptr;
22879 			ill_index = Q_TO_INDEX(stq);
22880 			ill = (ill_t *)stq->q_ptr;
22881 		}
22882 	} while (multirt_send);
22883 	if (conn_outgoing_ill != NULL)
22884 		ill_refrele(conn_outgoing_ill);
22885 	return;
22886 
22887 	/*
22888 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22889 	 */
22890 broadcast:
22891 	{
22892 		/*
22893 		 * Avoid broadcast storms by setting the ttl to 1
22894 		 * for broadcasts. This parameter can be set
22895 		 * via ndd, so make sure that for the SO_DONTROUTE
22896 		 * case that ipha_ttl is always set to 1.
22897 		 * In the event that we are replying to incoming
22898 		 * ICMP packets, conn could be NULL.
22899 		 */
22900 		if ((connp != NULL) && connp->conn_dontroute)
22901 			ipha->ipha_ttl = 1;
22902 		else
22903 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22904 
22905 		/*
22906 		 * Note that we are not doing a IRB_REFHOLD here.
22907 		 * Actually we don't care if the list changes i.e
22908 		 * if somebody deletes an IRE from the list while
22909 		 * we drop the lock, the next time we come around
22910 		 * ire_next will be NULL and hence we won't send
22911 		 * out multiple copies which is fine.
22912 		 */
22913 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22914 		ire1 = ire->ire_next;
22915 		if (conn_outgoing_ill != NULL) {
22916 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22917 				ASSERT(ire1 == ire->ire_next);
22918 				if (ire1 != NULL && ire1->ire_addr == dst) {
22919 					ire_refrele(ire);
22920 					ire = ire1;
22921 					IRE_REFHOLD(ire);
22922 					ire1 = ire->ire_next;
22923 					continue;
22924 				}
22925 				rw_exit(&ire->ire_bucket->irb_lock);
22926 				/* Did not find a matching ill */
22927 				ip1dbg(("ip_wput_ire: broadcast with no "
22928 				    "matching IP_BOUND_IF ill %s\n",
22929 				    conn_outgoing_ill->ill_name));
22930 				freemsg(first_mp);
22931 				if (ire != NULL)
22932 					ire_refrele(ire);
22933 				ill_refrele(conn_outgoing_ill);
22934 				return;
22935 			}
22936 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22937 			/*
22938 			 * If the next IRE has the same address and is not one
22939 			 * of the two copies that we need to send, try to see
22940 			 * whether this copy should be sent at all. This
22941 			 * assumes that we insert loopbacks first and then
22942 			 * non-loopbacks. This is acheived by inserting the
22943 			 * loopback always before non-loopback.
22944 			 * This is used to send a single copy of a broadcast
22945 			 * packet out all physical interfaces that have an
22946 			 * matching IRE_BROADCAST while also looping
22947 			 * back one copy (to ip_wput_local) for each
22948 			 * matching physical interface. However, we avoid
22949 			 * sending packets out different logical that match by
22950 			 * having ipif_up/ipif_down supress duplicate
22951 			 * IRE_BROADCASTS.
22952 			 *
22953 			 * This feature is currently used to get broadcasts
22954 			 * sent to multiple interfaces, when the broadcast
22955 			 * address being used applies to multiple interfaces.
22956 			 * For example, a whole net broadcast will be
22957 			 * replicated on every connected subnet of
22958 			 * the target net.
22959 			 *
22960 			 * Each zone has its own set of IRE_BROADCASTs, so that
22961 			 * we're able to distribute inbound packets to multiple
22962 			 * zones who share a broadcast address. We avoid looping
22963 			 * back outbound packets in different zones but on the
22964 			 * same ill, as the application would see duplicates.
22965 			 *
22966 			 * If the interfaces are part of the same group,
22967 			 * we would want to send only one copy out for
22968 			 * whole group.
22969 			 *
22970 			 * This logic assumes that ire_add_v4() groups the
22971 			 * IRE_BROADCAST entries so that those with the same
22972 			 * ire_addr and ill_group are kept together.
22973 			 */
22974 			ire_ill = ire->ire_ipif->ipif_ill;
22975 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22976 				if (ire_ill->ill_group != NULL &&
22977 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22978 					/*
22979 					 * If the current zone only has an ire
22980 					 * broadcast for this address marked
22981 					 * NORECV, the ire we want is ahead in
22982 					 * the bucket, so we look it up
22983 					 * deliberately ignoring the zoneid.
22984 					 */
22985 					for (ire1 = ire->ire_bucket->irb_ire;
22986 					    ire1 != NULL;
22987 					    ire1 = ire1->ire_next) {
22988 						ire1_ill =
22989 						    ire1->ire_ipif->ipif_ill;
22990 						if (ire1->ire_addr != dst)
22991 							continue;
22992 						/* skip over the current ire */
22993 						if (ire1 == ire)
22994 							continue;
22995 						/* skip over deleted ires */
22996 						if (ire1->ire_marks &
22997 						    IRE_MARK_CONDEMNED)
22998 							continue;
22999 						/*
23000 						 * non-loopback ire in our
23001 						 * group: use it for the next
23002 						 * pass in the loop
23003 						 */
23004 						if (ire1->ire_stq != NULL &&
23005 						    ire1_ill->ill_group ==
23006 						    ire_ill->ill_group)
23007 							break;
23008 					}
23009 				}
23010 			} else {
23011 				while (ire1 != NULL && ire1->ire_addr == dst) {
23012 					ire1_ill = ire1->ire_ipif->ipif_ill;
23013 					/*
23014 					 * We can have two broadcast ires on the
23015 					 * same ill in different zones; here
23016 					 * we'll send a copy of the packet on
23017 					 * each ill and the fanout code will
23018 					 * call conn_wantpacket() to check that
23019 					 * the zone has the broadcast address
23020 					 * configured on the ill. If the two
23021 					 * ires are in the same group we only
23022 					 * send one copy up.
23023 					 */
23024 					if (ire1_ill != ire_ill &&
23025 					    (ire1_ill->ill_group == NULL ||
23026 					    ire_ill->ill_group == NULL ||
23027 					    ire1_ill->ill_group !=
23028 					    ire_ill->ill_group)) {
23029 						break;
23030 					}
23031 					ire1 = ire1->ire_next;
23032 				}
23033 			}
23034 		}
23035 		ASSERT(multirt_send == B_FALSE);
23036 		if (ire1 != NULL && ire1->ire_addr == dst) {
23037 			if ((ire->ire_flags & RTF_MULTIRT) &&
23038 			    (ire1->ire_flags & RTF_MULTIRT)) {
23039 				/*
23040 				 * We are in the multirouting case.
23041 				 * The message must be sent at least
23042 				 * on both ires. These ires have been
23043 				 * inserted AFTER the standard ones
23044 				 * in ip_rt_add(). There are thus no
23045 				 * other ire entries for the destination
23046 				 * address in the rest of the bucket
23047 				 * that do not have the RTF_MULTIRT
23048 				 * flag. We don't process a copy
23049 				 * of the message here. This will be
23050 				 * done in the final sending loop.
23051 				 */
23052 				multirt_send = B_TRUE;
23053 			} else {
23054 				next_mp = ip_copymsg(first_mp);
23055 				if (next_mp != NULL)
23056 					IRE_REFHOLD(ire1);
23057 			}
23058 		}
23059 		rw_exit(&ire->ire_bucket->irb_lock);
23060 	}
23061 
23062 	if (stq) {
23063 		/*
23064 		 * A non-NULL send-to queue means this packet is going
23065 		 * out of this machine.
23066 		 */
23067 		out_ill = (ill_t *)stq->q_ptr;
23068 
23069 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23070 		ttl_protocol = ((uint16_t *)ipha)[4];
23071 		/*
23072 		 * We accumulate the pseudo header checksum in cksum.
23073 		 * This is pretty hairy code, so watch close.  One
23074 		 * thing to keep in mind is that UDP and TCP have
23075 		 * stored their respective datagram lengths in their
23076 		 * checksum fields.  This lines things up real nice.
23077 		 */
23078 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23079 		    (src >> 16) + (src & 0xFFFF);
23080 		/*
23081 		 * We assume the udp checksum field contains the
23082 		 * length, so to compute the pseudo header checksum,
23083 		 * all we need is the protocol number and src/dst.
23084 		 */
23085 		/* Provide the checksums for UDP and TCP. */
23086 		if ((PROTO == IPPROTO_TCP) &&
23087 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23088 			/* hlen gets the number of uchar_ts in the IP header */
23089 			hlen = (V_HLEN & 0xF) << 2;
23090 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23091 			IP_STAT(ipst, ip_out_sw_cksum);
23092 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23093 			    LENGTH - hlen);
23094 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23095 		} else if (PROTO == IPPROTO_SCTP &&
23096 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23097 			sctp_hdr_t	*sctph;
23098 
23099 			hlen = (V_HLEN & 0xF) << 2;
23100 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23101 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23102 			sctph->sh_chksum = 0;
23103 #ifdef	DEBUG
23104 			if (!skip_sctp_cksum)
23105 #endif
23106 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23107 		} else {
23108 			queue_t *dev_q = stq->q_next;
23109 
23110 			if ((dev_q->q_next || dev_q->q_first) &&
23111 			    !canput(dev_q)) {
23112 blocked:
23113 				ipha->ipha_ident = ip_hdr_included;
23114 				/*
23115 				 * If we don't have a conn to apply
23116 				 * backpressure, free the message.
23117 				 * In the ire_send path, we don't know
23118 				 * the position to requeue the packet. Rather
23119 				 * than reorder packets, we just drop this
23120 				 * packet.
23121 				 */
23122 				if (ipst->ips_ip_output_queue &&
23123 				    connp != NULL &&
23124 				    caller != IRE_SEND) {
23125 					if (caller == IP_WSRV) {
23126 						connp->conn_did_putbq = 1;
23127 						(void) putbq(connp->conn_wq,
23128 						    first_mp);
23129 						conn_drain_insert(connp);
23130 						/*
23131 						 * This is the service thread,
23132 						 * and the queue is already
23133 						 * noenabled. The check for
23134 						 * canput and the putbq is not
23135 						 * atomic. So we need to check
23136 						 * again.
23137 						 */
23138 						if (canput(stq->q_next))
23139 							connp->conn_did_putbq
23140 							    = 0;
23141 						IP_STAT(ipst, ip_conn_flputbq);
23142 					} else {
23143 						/*
23144 						 * We are not the service proc.
23145 						 * ip_wsrv will be scheduled or
23146 						 * is already running.
23147 						 */
23148 						(void) putq(connp->conn_wq,
23149 						    first_mp);
23150 					}
23151 				} else {
23152 					out_ill = (ill_t *)stq->q_ptr;
23153 					BUMP_MIB(out_ill->ill_ip_mib,
23154 					    ipIfStatsOutDiscards);
23155 					freemsg(first_mp);
23156 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23157 					    "ip_wput_ire_end: q %p (%S)",
23158 					    q, "discard");
23159 				}
23160 				ire_refrele(ire);
23161 				if (next_mp) {
23162 					ire_refrele(ire1);
23163 					freemsg(next_mp);
23164 				}
23165 				if (conn_outgoing_ill != NULL)
23166 					ill_refrele(conn_outgoing_ill);
23167 				return;
23168 			}
23169 			if ((PROTO == IPPROTO_UDP) &&
23170 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23171 				/*
23172 				 * hlen gets the number of uchar_ts in the
23173 				 * IP header
23174 				 */
23175 				hlen = (V_HLEN & 0xF) << 2;
23176 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23177 				max_frag = ire->ire_max_frag;
23178 				if (*up != 0) {
23179 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23180 					    up, PROTO, hlen, LENGTH, max_frag,
23181 					    ipsec_len, cksum);
23182 					/* Software checksum? */
23183 					if (DB_CKSUMFLAGS(mp) == 0) {
23184 						IP_STAT(ipst, ip_out_sw_cksum);
23185 						IP_STAT_UPDATE(ipst,
23186 						    ip_udp_out_sw_cksum_bytes,
23187 						    LENGTH - hlen);
23188 					}
23189 				}
23190 			}
23191 		}
23192 		/*
23193 		 * Need to do this even when fragmenting. The local
23194 		 * loopback can be done without computing checksums
23195 		 * but forwarding out other interface must be done
23196 		 * after the IP checksum (and ULP checksums) have been
23197 		 * computed.
23198 		 *
23199 		 * NOTE : multicast_forward is set only if this packet
23200 		 * originated from ip_wput. For packets originating from
23201 		 * ip_wput_multicast, it is not set.
23202 		 */
23203 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23204 multi_loopback:
23205 			ip2dbg(("ip_wput: multicast, loop %d\n",
23206 			    conn_multicast_loop));
23207 
23208 			/*  Forget header checksum offload */
23209 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23210 
23211 			/*
23212 			 * Local loopback of multicasts?  Check the
23213 			 * ill.
23214 			 *
23215 			 * Note that the loopback function will not come
23216 			 * in through ip_rput - it will only do the
23217 			 * client fanout thus we need to do an mforward
23218 			 * as well.  The is different from the BSD
23219 			 * logic.
23220 			 */
23221 			if (ill != NULL) {
23222 				ilm_t	*ilm;
23223 
23224 				ILM_WALKER_HOLD(ill);
23225 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23226 				    ALL_ZONES);
23227 				ILM_WALKER_RELE(ill);
23228 				if (ilm != NULL) {
23229 					/*
23230 					 * Pass along the virtual output q.
23231 					 * ip_wput_local() will distribute the
23232 					 * packet to all the matching zones,
23233 					 * except the sending zone when
23234 					 * IP_MULTICAST_LOOP is false.
23235 					 */
23236 					ip_multicast_loopback(q, ill, first_mp,
23237 					    conn_multicast_loop ? 0 :
23238 					    IP_FF_NO_MCAST_LOOP, zoneid);
23239 				}
23240 			}
23241 			if (ipha->ipha_ttl == 0) {
23242 				/*
23243 				 * 0 => only to this host i.e. we are
23244 				 * done. We are also done if this was the
23245 				 * loopback interface since it is sufficient
23246 				 * to loopback one copy of a multicast packet.
23247 				 */
23248 				freemsg(first_mp);
23249 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23250 				    "ip_wput_ire_end: q %p (%S)",
23251 				    q, "loopback");
23252 				ire_refrele(ire);
23253 				if (conn_outgoing_ill != NULL)
23254 					ill_refrele(conn_outgoing_ill);
23255 				return;
23256 			}
23257 			/*
23258 			 * ILLF_MULTICAST is checked in ip_newroute
23259 			 * i.e. we don't need to check it here since
23260 			 * all IRE_CACHEs come from ip_newroute.
23261 			 * For multicast traffic, SO_DONTROUTE is interpreted
23262 			 * to mean only send the packet out the interface
23263 			 * (optionally specified with IP_MULTICAST_IF)
23264 			 * and do not forward it out additional interfaces.
23265 			 * RSVP and the rsvp daemon is an example of a
23266 			 * protocol and user level process that
23267 			 * handles it's own routing. Hence, it uses the
23268 			 * SO_DONTROUTE option to accomplish this.
23269 			 */
23270 
23271 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23272 			    ill != NULL) {
23273 				/* Unconditionally redo the checksum */
23274 				ipha->ipha_hdr_checksum = 0;
23275 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23276 
23277 				/*
23278 				 * If this needs to go out secure, we need
23279 				 * to wait till we finish the IPSEC
23280 				 * processing.
23281 				 */
23282 				if (ipsec_len == 0 &&
23283 				    ip_mforward(ill, ipha, mp)) {
23284 					freemsg(first_mp);
23285 					ip1dbg(("ip_wput: mforward failed\n"));
23286 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23287 					    "ip_wput_ire_end: q %p (%S)",
23288 					    q, "mforward failed");
23289 					ire_refrele(ire);
23290 					if (conn_outgoing_ill != NULL)
23291 						ill_refrele(conn_outgoing_ill);
23292 					return;
23293 				}
23294 			}
23295 		}
23296 		max_frag = ire->ire_max_frag;
23297 		cksum += ttl_protocol;
23298 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23299 			/* No fragmentation required for this one. */
23300 			/*
23301 			 * Don't use frag_flag if packet is pre-built or source
23302 			 * routed or if multicast (since multicast packets do
23303 			 * not solicit ICMP "packet too big" messages).
23304 			 */
23305 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23306 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23307 			    !ip_source_route_included(ipha)) &&
23308 			    !CLASSD(ipha->ipha_dst))
23309 				ipha->ipha_fragment_offset_and_flags |=
23310 				    htons(ire->ire_frag_flag);
23311 
23312 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23313 				/* Complete the IP header checksum. */
23314 				cksum += ipha->ipha_ident;
23315 				cksum += (v_hlen_tos_len >> 16)+
23316 				    (v_hlen_tos_len & 0xFFFF);
23317 				cksum += ipha->ipha_fragment_offset_and_flags;
23318 				hlen = (V_HLEN & 0xF) -
23319 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23320 				if (hlen) {
23321 checksumoptions:
23322 					/*
23323 					 * Account for the IP Options in the IP
23324 					 * header checksum.
23325 					 */
23326 					up = (uint16_t *)(rptr+
23327 					    IP_SIMPLE_HDR_LENGTH);
23328 					do {
23329 						cksum += up[0];
23330 						cksum += up[1];
23331 						up += 2;
23332 					} while (--hlen);
23333 				}
23334 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23335 				cksum = ~(cksum + (cksum >> 16));
23336 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23337 			}
23338 			if (ipsec_len != 0) {
23339 				ipsec_out_process(q, first_mp, ire, ill_index);
23340 				if (!next_mp) {
23341 					ire_refrele(ire);
23342 					if (conn_outgoing_ill != NULL)
23343 						ill_refrele(conn_outgoing_ill);
23344 					return;
23345 				}
23346 				goto next;
23347 			}
23348 
23349 			/*
23350 			 * multirt_send has already been handled
23351 			 * for broadcast, but not yet for multicast
23352 			 * or IP options.
23353 			 */
23354 			if (next_mp == NULL) {
23355 				if (ire->ire_flags & RTF_MULTIRT) {
23356 					multirt_send = B_TRUE;
23357 				}
23358 			}
23359 
23360 			/*
23361 			 * In most cases, the emission loop below is
23362 			 * entered only once. Only in the case where
23363 			 * the ire holds the RTF_MULTIRT flag, do we loop
23364 			 * to process all RTF_MULTIRT ires in the bucket,
23365 			 * and send the packet through all crossed
23366 			 * RTF_MULTIRT routes.
23367 			 */
23368 			do {
23369 				if (multirt_send) {
23370 					irb_t *irb;
23371 
23372 					irb = ire->ire_bucket;
23373 					ASSERT(irb != NULL);
23374 					/*
23375 					 * We are in a multiple send case,
23376 					 * need to get the next IRE and make
23377 					 * a duplicate of the packet.
23378 					 */
23379 					IRB_REFHOLD(irb);
23380 					for (ire1 = ire->ire_next;
23381 					    ire1 != NULL;
23382 					    ire1 = ire1->ire_next) {
23383 						if (!(ire1->ire_flags &
23384 						    RTF_MULTIRT)) {
23385 							continue;
23386 						}
23387 						if (ire1->ire_addr !=
23388 						    ire->ire_addr) {
23389 							continue;
23390 						}
23391 						if (ire1->ire_marks &
23392 						    (IRE_MARK_CONDEMNED|
23393 						    IRE_MARK_HIDDEN)) {
23394 							continue;
23395 						}
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 	if (max_frag == 0) {
24346 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24347 		    " -  dropping packet\n"));
24348 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24349 		freemsg(mp);
24350 		return;
24351 	}
24352 
24353 	/*
24354 	 * IPSEC does not allow hw accelerated packets to be fragmented
24355 	 * This check is made in ip_wput_ipsec_out prior to coming here
24356 	 * via ip_wput_ire_fragmentit.
24357 	 *
24358 	 * If at this point we have an ire whose ARP request has not
24359 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24360 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24361 	 * This packet and all fragmentable packets for this ire will
24362 	 * continue to get dropped while ire_nce->nce_state remains in
24363 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24364 	 * ND_REACHABLE, all subsquent large packets for this ire will
24365 	 * get fragemented and sent out by this function.
24366 	 */
24367 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24368 		/* If nce_state is ND_INITIAL, trigger ARP query */
24369 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24370 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24371 		    " -  dropping packet\n"));
24372 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24373 		freemsg(mp);
24374 		return;
24375 	}
24376 
24377 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24378 	    "ip_wput_frag_start:");
24379 
24380 	if (mp->b_datap->db_type == M_CTL) {
24381 		first_mp = mp;
24382 		mp_orig = mp = mp->b_cont;
24383 		mctl_present = B_TRUE;
24384 	} else {
24385 		first_mp = mp;
24386 		mctl_present = B_FALSE;
24387 	}
24388 
24389 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24390 	ipha = (ipha_t *)mp->b_rptr;
24391 
24392 	/*
24393 	 * If the Don't Fragment flag is on, generate an ICMP destination
24394 	 * unreachable, fragmentation needed.
24395 	 */
24396 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24397 	if (offset & IPH_DF) {
24398 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24399 		/*
24400 		 * Need to compute hdr checksum if called from ip_wput_ire.
24401 		 * Note that ip_rput_forward verifies the checksum before
24402 		 * calling this routine so in that case this is a noop.
24403 		 */
24404 		ipha->ipha_hdr_checksum = 0;
24405 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24406 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24407 		    ipst);
24408 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24409 		    "ip_wput_frag_end:(%S)",
24410 		    "don't fragment");
24411 		return;
24412 	}
24413 	if (mctl_present)
24414 		freeb(first_mp);
24415 	/*
24416 	 * Establish the starting offset.  May not be zero if we are fragging
24417 	 * a fragment that is being forwarded.
24418 	 */
24419 	offset = offset & IPH_OFFSET;
24420 
24421 	/* TODO why is this test needed? */
24422 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24423 	if (((max_frag - LENGTH) & ~7) < 8) {
24424 		/* TODO: notify ulp somehow */
24425 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24426 		freemsg(mp);
24427 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24428 		    "ip_wput_frag_end:(%S)",
24429 		    "len < 8");
24430 		return;
24431 	}
24432 
24433 	hdr_len = (V_HLEN & 0xF) << 2;
24434 
24435 	ipha->ipha_hdr_checksum = 0;
24436 
24437 	/*
24438 	 * Establish the number of bytes maximum per frag, after putting
24439 	 * in the header.
24440 	 */
24441 	len = (max_frag - hdr_len) & ~7;
24442 
24443 	/* Check if we can use MDT to send out the frags. */
24444 	ASSERT(!IRE_IS_LOCAL(ire));
24445 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24446 	    ipst->ips_ip_multidata_outbound &&
24447 	    !(ire->ire_flags & RTF_MULTIRT) &&
24448 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24449 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24450 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24451 		ASSERT(ill->ill_mdt_capab != NULL);
24452 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24453 			/*
24454 			 * If MDT has been previously turned off in the past,
24455 			 * and we currently can do MDT (due to IPQoS policy
24456 			 * removal, etc.) then enable it for this interface.
24457 			 */
24458 			ill->ill_mdt_capab->ill_mdt_on = 1;
24459 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24460 			    ill->ill_name));
24461 		}
24462 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24463 		    offset);
24464 		return;
24465 	}
24466 
24467 	/* Get a copy of the header for the trailing frags */
24468 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24469 	if (!hdr_mp) {
24470 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24471 		freemsg(mp);
24472 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24473 		    "ip_wput_frag_end:(%S)",
24474 		    "couldn't copy hdr");
24475 		return;
24476 	}
24477 	if (DB_CRED(mp) != NULL)
24478 		mblk_setcred(hdr_mp, DB_CRED(mp));
24479 
24480 	/* Store the starting offset, with the MoreFrags flag. */
24481 	i1 = offset | IPH_MF | frag_flag;
24482 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24483 
24484 	/* Establish the ending byte offset, based on the starting offset. */
24485 	offset <<= 3;
24486 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24487 
24488 	/* Store the length of the first fragment in the IP header. */
24489 	i1 = len + hdr_len;
24490 	ASSERT(i1 <= IP_MAXPACKET);
24491 	ipha->ipha_length = htons((uint16_t)i1);
24492 
24493 	/*
24494 	 * Compute the IP header checksum for the first frag.  We have to
24495 	 * watch out that we stop at the end of the header.
24496 	 */
24497 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24498 
24499 	/*
24500 	 * Now carve off the first frag.  Note that this will include the
24501 	 * original IP header.
24502 	 */
24503 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24504 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24505 		freeb(hdr_mp);
24506 		freemsg(mp_orig);
24507 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24508 		    "ip_wput_frag_end:(%S)",
24509 		    "couldn't carve first");
24510 		return;
24511 	}
24512 
24513 	/*
24514 	 * Multirouting case. Each fragment is replicated
24515 	 * via all non-condemned RTF_MULTIRT routes
24516 	 * currently resolved.
24517 	 * We ensure that first_ire is the first RTF_MULTIRT
24518 	 * ire in the bucket.
24519 	 */
24520 	if (ire->ire_flags & RTF_MULTIRT) {
24521 		irb = ire->ire_bucket;
24522 		ASSERT(irb != NULL);
24523 
24524 		multirt_send = B_TRUE;
24525 
24526 		/* Make sure we do not omit any multiroute ire. */
24527 		IRB_REFHOLD(irb);
24528 		for (first_ire = irb->irb_ire;
24529 		    first_ire != NULL;
24530 		    first_ire = first_ire->ire_next) {
24531 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24532 			    (first_ire->ire_addr == ire->ire_addr) &&
24533 			    !(first_ire->ire_marks &
24534 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24535 				break;
24536 			}
24537 		}
24538 
24539 		if (first_ire != NULL) {
24540 			if (first_ire != ire) {
24541 				IRE_REFHOLD(first_ire);
24542 				/*
24543 				 * Do not release the ire passed in
24544 				 * as the argument.
24545 				 */
24546 				ire = first_ire;
24547 			} else {
24548 				first_ire = NULL;
24549 			}
24550 		}
24551 		IRB_REFRELE(irb);
24552 
24553 		/*
24554 		 * Save the first ire; we will need to restore it
24555 		 * for the trailing frags.
24556 		 * We REFHOLD save_ire, as each iterated ire will be
24557 		 * REFRELEd.
24558 		 */
24559 		save_ire = ire;
24560 		IRE_REFHOLD(save_ire);
24561 	}
24562 
24563 	/*
24564 	 * First fragment emission loop.
24565 	 * In most cases, the emission loop below is entered only
24566 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24567 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24568 	 * bucket, and send the fragment through all crossed
24569 	 * RTF_MULTIRT routes.
24570 	 */
24571 	do {
24572 		if (ire->ire_flags & RTF_MULTIRT) {
24573 			/*
24574 			 * We are in a multiple send case, need to get
24575 			 * the next ire and make a copy of the packet.
24576 			 * ire1 holds here the next ire to process in the
24577 			 * bucket. If multirouting is expected,
24578 			 * any non-RTF_MULTIRT ire that has the
24579 			 * right destination address is ignored.
24580 			 *
24581 			 * We have to take into account the MTU of
24582 			 * each walked ire. max_frag is set by the
24583 			 * the caller and generally refers to
24584 			 * the primary ire entry. Here we ensure that
24585 			 * no route with a lower MTU will be used, as
24586 			 * fragments are carved once for all ires,
24587 			 * then replicated.
24588 			 */
24589 			ASSERT(irb != NULL);
24590 			IRB_REFHOLD(irb);
24591 			for (ire1 = ire->ire_next;
24592 			    ire1 != NULL;
24593 			    ire1 = ire1->ire_next) {
24594 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24595 					continue;
24596 				if (ire1->ire_addr != ire->ire_addr)
24597 					continue;
24598 				if (ire1->ire_marks &
24599 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24600 					continue;
24601 				/*
24602 				 * Ensure we do not exceed the MTU
24603 				 * of the next route.
24604 				 */
24605 				if (ire1->ire_max_frag < max_frag) {
24606 					ip_multirt_bad_mtu(ire1, max_frag);
24607 					continue;
24608 				}
24609 
24610 				/* Got one. */
24611 				IRE_REFHOLD(ire1);
24612 				break;
24613 			}
24614 			IRB_REFRELE(irb);
24615 
24616 			if (ire1 != NULL) {
24617 				next_mp = copyb(mp);
24618 				if ((next_mp == NULL) ||
24619 				    ((mp->b_cont != NULL) &&
24620 				    ((next_mp->b_cont =
24621 				    dupmsg(mp->b_cont)) == NULL))) {
24622 					freemsg(next_mp);
24623 					next_mp = NULL;
24624 					ire_refrele(ire1);
24625 					ire1 = NULL;
24626 				}
24627 			}
24628 
24629 			/* Last multiroute ire; don't loop anymore. */
24630 			if (ire1 == NULL) {
24631 				multirt_send = B_FALSE;
24632 			}
24633 		}
24634 
24635 		ll_hdr_len = 0;
24636 		LOCK_IRE_FP_MP(ire);
24637 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24638 		if (ll_hdr_mp != NULL) {
24639 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24640 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24641 		} else {
24642 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24643 		}
24644 
24645 		/* If there is a transmit header, get a copy for this frag. */
24646 		/*
24647 		 * TODO: should check db_ref before calling ip_carve_mp since
24648 		 * it might give us a dup.
24649 		 */
24650 		if (!ll_hdr_mp) {
24651 			/* No xmit header. */
24652 			xmit_mp = mp;
24653 
24654 		/* We have a link-layer header that can fit in our mblk. */
24655 		} else if (mp->b_datap->db_ref == 1 &&
24656 		    ll_hdr_len != 0 &&
24657 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24658 			/* M_DATA fastpath */
24659 			mp->b_rptr -= ll_hdr_len;
24660 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24661 			xmit_mp = mp;
24662 
24663 		/* Corner case if copyb has failed */
24664 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24665 			UNLOCK_IRE_FP_MP(ire);
24666 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24667 			freeb(hdr_mp);
24668 			freemsg(mp);
24669 			freemsg(mp_orig);
24670 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24671 			    "ip_wput_frag_end:(%S)",
24672 			    "discard");
24673 
24674 			if (multirt_send) {
24675 				ASSERT(ire1);
24676 				ASSERT(next_mp);
24677 
24678 				freemsg(next_mp);
24679 				ire_refrele(ire1);
24680 			}
24681 			if (save_ire != NULL)
24682 				IRE_REFRELE(save_ire);
24683 
24684 			if (first_ire != NULL)
24685 				ire_refrele(first_ire);
24686 			return;
24687 
24688 		/*
24689 		 * Case of res_mp OR the fastpath mp can't fit
24690 		 * in the mblk
24691 		 */
24692 		} else {
24693 			xmit_mp->b_cont = mp;
24694 			if (DB_CRED(mp) != NULL)
24695 				mblk_setcred(xmit_mp, DB_CRED(mp));
24696 			/*
24697 			 * Get priority marking, if any.
24698 			 * We propagate the CoS marking from the
24699 			 * original packet that went to QoS processing
24700 			 * in ip_wput_ire to the newly carved mp.
24701 			 */
24702 			if (DB_TYPE(xmit_mp) == M_DATA)
24703 				xmit_mp->b_band = mp->b_band;
24704 		}
24705 		UNLOCK_IRE_FP_MP(ire);
24706 
24707 		q = ire->ire_stq;
24708 		out_ill = (ill_t *)q->q_ptr;
24709 
24710 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24711 
24712 		DTRACE_PROBE4(ip4__physical__out__start,
24713 		    ill_t *, NULL, ill_t *, out_ill,
24714 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24715 
24716 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24717 		    ipst->ips_ipv4firewall_physical_out,
24718 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24719 
24720 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24721 
24722 		if (xmit_mp != NULL) {
24723 			putnext(q, xmit_mp);
24724 
24725 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24726 			UPDATE_MIB(out_ill->ill_ip_mib,
24727 			    ipIfStatsHCOutOctets, i1);
24728 
24729 			if (pkt_type != OB_PKT) {
24730 				/*
24731 				 * Update the packet count and MIB stats
24732 				 * of trailing RTF_MULTIRT ires.
24733 				 */
24734 				UPDATE_OB_PKT_COUNT(ire);
24735 				BUMP_MIB(out_ill->ill_ip_mib,
24736 				    ipIfStatsOutFragReqds);
24737 			}
24738 		}
24739 
24740 		if (multirt_send) {
24741 			/*
24742 			 * We are in a multiple send case; look for
24743 			 * the next ire and re-enter the loop.
24744 			 */
24745 			ASSERT(ire1);
24746 			ASSERT(next_mp);
24747 			/* REFRELE the current ire before looping */
24748 			ire_refrele(ire);
24749 			ire = ire1;
24750 			ire1 = NULL;
24751 			mp = next_mp;
24752 			next_mp = NULL;
24753 		}
24754 	} while (multirt_send);
24755 
24756 	ASSERT(ire1 == NULL);
24757 
24758 	/* Restore the original ire; we need it for the trailing frags */
24759 	if (save_ire != NULL) {
24760 		/* REFRELE the last iterated ire */
24761 		ire_refrele(ire);
24762 		/* save_ire has been REFHOLDed */
24763 		ire = save_ire;
24764 		save_ire = NULL;
24765 		q = ire->ire_stq;
24766 	}
24767 
24768 	if (pkt_type == OB_PKT) {
24769 		UPDATE_OB_PKT_COUNT(ire);
24770 	} else {
24771 		out_ill = (ill_t *)q->q_ptr;
24772 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24773 		UPDATE_IB_PKT_COUNT(ire);
24774 	}
24775 
24776 	/* Advance the offset to the second frag starting point. */
24777 	offset += len;
24778 	/*
24779 	 * Update hdr_len from the copied header - there might be less options
24780 	 * in the later fragments.
24781 	 */
24782 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24783 	/* Loop until done. */
24784 	for (;;) {
24785 		uint16_t	offset_and_flags;
24786 		uint16_t	ip_len;
24787 
24788 		if (ip_data_end - offset > len) {
24789 			/*
24790 			 * Carve off the appropriate amount from the original
24791 			 * datagram.
24792 			 */
24793 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24794 				mp = NULL;
24795 				break;
24796 			}
24797 			/*
24798 			 * More frags after this one.  Get another copy
24799 			 * of the header.
24800 			 */
24801 			if (carve_mp->b_datap->db_ref == 1 &&
24802 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24803 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24804 				/* Inline IP header */
24805 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24806 				    hdr_mp->b_rptr;
24807 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24808 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24809 				mp = carve_mp;
24810 			} else {
24811 				if (!(mp = copyb(hdr_mp))) {
24812 					freemsg(carve_mp);
24813 					break;
24814 				}
24815 				/* Get priority marking, if any. */
24816 				mp->b_band = carve_mp->b_band;
24817 				mp->b_cont = carve_mp;
24818 			}
24819 			ipha = (ipha_t *)mp->b_rptr;
24820 			offset_and_flags = IPH_MF;
24821 		} else {
24822 			/*
24823 			 * Last frag.  Consume the header. Set len to
24824 			 * the length of this last piece.
24825 			 */
24826 			len = ip_data_end - offset;
24827 
24828 			/*
24829 			 * Carve off the appropriate amount from the original
24830 			 * datagram.
24831 			 */
24832 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24833 				mp = NULL;
24834 				break;
24835 			}
24836 			if (carve_mp->b_datap->db_ref == 1 &&
24837 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24838 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24839 				/* Inline IP header */
24840 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24841 				    hdr_mp->b_rptr;
24842 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24843 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24844 				mp = carve_mp;
24845 				freeb(hdr_mp);
24846 				hdr_mp = mp;
24847 			} else {
24848 				mp = hdr_mp;
24849 				/* Get priority marking, if any. */
24850 				mp->b_band = carve_mp->b_band;
24851 				mp->b_cont = carve_mp;
24852 			}
24853 			ipha = (ipha_t *)mp->b_rptr;
24854 			/* A frag of a frag might have IPH_MF non-zero */
24855 			offset_and_flags =
24856 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24857 			    IPH_MF;
24858 		}
24859 		offset_and_flags |= (uint16_t)(offset >> 3);
24860 		offset_and_flags |= (uint16_t)frag_flag;
24861 		/* Store the offset and flags in the IP header. */
24862 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24863 
24864 		/* Store the length in the IP header. */
24865 		ip_len = (uint16_t)(len + hdr_len);
24866 		ipha->ipha_length = htons(ip_len);
24867 
24868 		/*
24869 		 * Set the IP header checksum.	Note that mp is just
24870 		 * the header, so this is easy to pass to ip_csum.
24871 		 */
24872 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24873 
24874 		/* Attach a transmit header, if any, and ship it. */
24875 		if (pkt_type == OB_PKT) {
24876 			UPDATE_OB_PKT_COUNT(ire);
24877 		} else {
24878 			out_ill = (ill_t *)q->q_ptr;
24879 			BUMP_MIB(out_ill->ill_ip_mib,
24880 			    ipIfStatsHCOutForwDatagrams);
24881 			UPDATE_IB_PKT_COUNT(ire);
24882 		}
24883 
24884 		if (ire->ire_flags & RTF_MULTIRT) {
24885 			irb = ire->ire_bucket;
24886 			ASSERT(irb != NULL);
24887 
24888 			multirt_send = B_TRUE;
24889 
24890 			/*
24891 			 * Save the original ire; we will need to restore it
24892 			 * for the tailing frags.
24893 			 */
24894 			save_ire = ire;
24895 			IRE_REFHOLD(save_ire);
24896 		}
24897 		/*
24898 		 * Emission loop for this fragment, similar
24899 		 * to what is done for the first fragment.
24900 		 */
24901 		do {
24902 			if (multirt_send) {
24903 				/*
24904 				 * We are in a multiple send case, need to get
24905 				 * the next ire and make a copy of the packet.
24906 				 */
24907 				ASSERT(irb != NULL);
24908 				IRB_REFHOLD(irb);
24909 				for (ire1 = ire->ire_next;
24910 				    ire1 != NULL;
24911 				    ire1 = ire1->ire_next) {
24912 					if (!(ire1->ire_flags & RTF_MULTIRT))
24913 						continue;
24914 					if (ire1->ire_addr != ire->ire_addr)
24915 						continue;
24916 					if (ire1->ire_marks &
24917 					    (IRE_MARK_CONDEMNED|
24918 					    IRE_MARK_HIDDEN)) {
24919 						continue;
24920 					}
24921 					/*
24922 					 * Ensure we do not exceed the MTU
24923 					 * of the next route.
24924 					 */
24925 					if (ire1->ire_max_frag < max_frag) {
24926 						ip_multirt_bad_mtu(ire1,
24927 						    max_frag);
24928 						continue;
24929 					}
24930 
24931 					/* Got one. */
24932 					IRE_REFHOLD(ire1);
24933 					break;
24934 				}
24935 				IRB_REFRELE(irb);
24936 
24937 				if (ire1 != NULL) {
24938 					next_mp = copyb(mp);
24939 					if ((next_mp == NULL) ||
24940 					    ((mp->b_cont != NULL) &&
24941 					    ((next_mp->b_cont =
24942 					    dupmsg(mp->b_cont)) == NULL))) {
24943 						freemsg(next_mp);
24944 						next_mp = NULL;
24945 						ire_refrele(ire1);
24946 						ire1 = NULL;
24947 					}
24948 				}
24949 
24950 				/* Last multiroute ire; don't loop anymore. */
24951 				if (ire1 == NULL) {
24952 					multirt_send = B_FALSE;
24953 				}
24954 			}
24955 
24956 			/* Update transmit header */
24957 			ll_hdr_len = 0;
24958 			LOCK_IRE_FP_MP(ire);
24959 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24960 			if (ll_hdr_mp != NULL) {
24961 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24962 				ll_hdr_len = MBLKL(ll_hdr_mp);
24963 			} else {
24964 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24965 			}
24966 
24967 			if (!ll_hdr_mp) {
24968 				xmit_mp = mp;
24969 
24970 			/*
24971 			 * We have link-layer header that can fit in
24972 			 * our mblk.
24973 			 */
24974 			} else if (mp->b_datap->db_ref == 1 &&
24975 			    ll_hdr_len != 0 &&
24976 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24977 				/* M_DATA fastpath */
24978 				mp->b_rptr -= ll_hdr_len;
24979 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24980 				    ll_hdr_len);
24981 				xmit_mp = mp;
24982 
24983 			/*
24984 			 * Case of res_mp OR the fastpath mp can't fit
24985 			 * in the mblk
24986 			 */
24987 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24988 				xmit_mp->b_cont = mp;
24989 				if (DB_CRED(mp) != NULL)
24990 					mblk_setcred(xmit_mp, DB_CRED(mp));
24991 				/* Get priority marking, if any. */
24992 				if (DB_TYPE(xmit_mp) == M_DATA)
24993 					xmit_mp->b_band = mp->b_band;
24994 
24995 			/* Corner case if copyb failed */
24996 			} else {
24997 				/*
24998 				 * Exit both the replication and
24999 				 * fragmentation loops.
25000 				 */
25001 				UNLOCK_IRE_FP_MP(ire);
25002 				goto drop_pkt;
25003 			}
25004 			UNLOCK_IRE_FP_MP(ire);
25005 
25006 			mp1 = mp;
25007 			out_ill = (ill_t *)q->q_ptr;
25008 
25009 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
25010 
25011 			DTRACE_PROBE4(ip4__physical__out__start,
25012 			    ill_t *, NULL, ill_t *, out_ill,
25013 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25014 
25015 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25016 			    ipst->ips_ipv4firewall_physical_out,
25017 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25018 
25019 			DTRACE_PROBE1(ip4__physical__out__end,
25020 			    mblk_t *, xmit_mp);
25021 
25022 			if (mp != mp1 && hdr_mp == mp1)
25023 				hdr_mp = mp;
25024 			if (mp != mp1 && mp_orig == mp1)
25025 				mp_orig = mp;
25026 
25027 			if (xmit_mp != NULL) {
25028 				putnext(q, xmit_mp);
25029 
25030 				BUMP_MIB(out_ill->ill_ip_mib,
25031 				    ipIfStatsHCOutTransmits);
25032 				UPDATE_MIB(out_ill->ill_ip_mib,
25033 				    ipIfStatsHCOutOctets, ip_len);
25034 
25035 				if (pkt_type != OB_PKT) {
25036 					/*
25037 					 * Update the packet count of trailing
25038 					 * RTF_MULTIRT ires.
25039 					 */
25040 					UPDATE_OB_PKT_COUNT(ire);
25041 				}
25042 			}
25043 
25044 			/* All done if we just consumed the hdr_mp. */
25045 			if (mp == hdr_mp) {
25046 				last_frag = B_TRUE;
25047 				BUMP_MIB(out_ill->ill_ip_mib,
25048 				    ipIfStatsOutFragOKs);
25049 			}
25050 
25051 			if (multirt_send) {
25052 				/*
25053 				 * We are in a multiple send case; look for
25054 				 * the next ire and re-enter the loop.
25055 				 */
25056 				ASSERT(ire1);
25057 				ASSERT(next_mp);
25058 				/* REFRELE the current ire before looping */
25059 				ire_refrele(ire);
25060 				ire = ire1;
25061 				ire1 = NULL;
25062 				q = ire->ire_stq;
25063 				mp = next_mp;
25064 				next_mp = NULL;
25065 			}
25066 		} while (multirt_send);
25067 		/*
25068 		 * Restore the original ire; we need it for the
25069 		 * trailing frags
25070 		 */
25071 		if (save_ire != NULL) {
25072 			ASSERT(ire1 == NULL);
25073 			/* REFRELE the last iterated ire */
25074 			ire_refrele(ire);
25075 			/* save_ire has been REFHOLDed */
25076 			ire = save_ire;
25077 			q = ire->ire_stq;
25078 			save_ire = NULL;
25079 		}
25080 
25081 		if (last_frag) {
25082 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25083 			    "ip_wput_frag_end:(%S)",
25084 			    "consumed hdr_mp");
25085 
25086 			if (first_ire != NULL)
25087 				ire_refrele(first_ire);
25088 			return;
25089 		}
25090 		/* Otherwise, advance and loop. */
25091 		offset += len;
25092 	}
25093 
25094 drop_pkt:
25095 	/* Clean up following allocation failure. */
25096 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25097 	freemsg(mp);
25098 	if (mp != hdr_mp)
25099 		freeb(hdr_mp);
25100 	if (mp != mp_orig)
25101 		freemsg(mp_orig);
25102 
25103 	if (save_ire != NULL)
25104 		IRE_REFRELE(save_ire);
25105 	if (first_ire != NULL)
25106 		ire_refrele(first_ire);
25107 
25108 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25109 	    "ip_wput_frag_end:(%S)",
25110 	    "end--alloc failure");
25111 }
25112 
25113 /*
25114  * Copy the header plus those options which have the copy bit set
25115  */
25116 static mblk_t *
25117 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25118 {
25119 	mblk_t	*mp;
25120 	uchar_t	*up;
25121 
25122 	/*
25123 	 * Quick check if we need to look for options without the copy bit
25124 	 * set
25125 	 */
25126 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25127 	if (!mp)
25128 		return (mp);
25129 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25130 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25131 		bcopy(rptr, mp->b_rptr, hdr_len);
25132 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25133 		return (mp);
25134 	}
25135 	up  = mp->b_rptr;
25136 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25137 	up += IP_SIMPLE_HDR_LENGTH;
25138 	rptr += IP_SIMPLE_HDR_LENGTH;
25139 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25140 	while (hdr_len > 0) {
25141 		uint32_t optval;
25142 		uint32_t optlen;
25143 
25144 		optval = *rptr;
25145 		if (optval == IPOPT_EOL)
25146 			break;
25147 		if (optval == IPOPT_NOP)
25148 			optlen = 1;
25149 		else
25150 			optlen = rptr[1];
25151 		if (optval & IPOPT_COPY) {
25152 			bcopy(rptr, up, optlen);
25153 			up += optlen;
25154 		}
25155 		rptr += optlen;
25156 		hdr_len -= optlen;
25157 	}
25158 	/*
25159 	 * Make sure that we drop an even number of words by filling
25160 	 * with EOL to the next word boundary.
25161 	 */
25162 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25163 	    hdr_len & 0x3; hdr_len++)
25164 		*up++ = IPOPT_EOL;
25165 	mp->b_wptr = up;
25166 	/* Update header length */
25167 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25168 	return (mp);
25169 }
25170 
25171 /*
25172  * Delivery to local recipients including fanout to multiple recipients.
25173  * Does not do checksumming of UDP/TCP.
25174  * Note: q should be the read side queue for either the ill or conn.
25175  * Note: rq should be the read side q for the lower (ill) stream.
25176  * We don't send packets to IPPF processing, thus the last argument
25177  * to all the fanout calls are B_FALSE.
25178  */
25179 void
25180 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25181     int fanout_flags, zoneid_t zoneid)
25182 {
25183 	uint32_t	protocol;
25184 	mblk_t		*first_mp;
25185 	boolean_t	mctl_present;
25186 	int		ire_type;
25187 #define	rptr	((uchar_t *)ipha)
25188 	ip_stack_t	*ipst = ill->ill_ipst;
25189 
25190 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25191 	    "ip_wput_local_start: q %p", q);
25192 
25193 	if (ire != NULL) {
25194 		ire_type = ire->ire_type;
25195 	} else {
25196 		/*
25197 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25198 		 * packet is not multicast, we can't tell the ire type.
25199 		 */
25200 		ASSERT(CLASSD(ipha->ipha_dst));
25201 		ire_type = IRE_BROADCAST;
25202 	}
25203 
25204 	first_mp = mp;
25205 	if (first_mp->b_datap->db_type == M_CTL) {
25206 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25207 		if (!io->ipsec_out_secure) {
25208 			/*
25209 			 * This ipsec_out_t was allocated in ip_wput
25210 			 * for multicast packets to store the ill_index.
25211 			 * As this is being delivered locally, we don't
25212 			 * need this anymore.
25213 			 */
25214 			mp = first_mp->b_cont;
25215 			freeb(first_mp);
25216 			first_mp = mp;
25217 			mctl_present = B_FALSE;
25218 		} else {
25219 			/*
25220 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25221 			 * security properties for the looped-back packet.
25222 			 */
25223 			mctl_present = B_TRUE;
25224 			mp = first_mp->b_cont;
25225 			ASSERT(mp != NULL);
25226 			ipsec_out_to_in(first_mp);
25227 		}
25228 	} else {
25229 		mctl_present = B_FALSE;
25230 	}
25231 
25232 	DTRACE_PROBE4(ip4__loopback__in__start,
25233 	    ill_t *, ill, ill_t *, NULL,
25234 	    ipha_t *, ipha, mblk_t *, first_mp);
25235 
25236 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25237 	    ipst->ips_ipv4firewall_loopback_in,
25238 	    ill, NULL, ipha, first_mp, mp, ipst);
25239 
25240 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25241 
25242 	if (first_mp == NULL)
25243 		return;
25244 
25245 	ipst->ips_loopback_packets++;
25246 
25247 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25248 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25249 	if (!IS_SIMPLE_IPH(ipha)) {
25250 		ip_wput_local_options(ipha, ipst);
25251 	}
25252 
25253 	protocol = ipha->ipha_protocol;
25254 	switch (protocol) {
25255 	case IPPROTO_ICMP: {
25256 		ire_t		*ire_zone;
25257 		ilm_t		*ilm;
25258 		mblk_t		*mp1;
25259 		zoneid_t	last_zoneid;
25260 
25261 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25262 			ASSERT(ire_type == IRE_BROADCAST);
25263 			/*
25264 			 * In the multicast case, applications may have joined
25265 			 * the group from different zones, so we need to deliver
25266 			 * the packet to each of them. Loop through the
25267 			 * multicast memberships structures (ilm) on the receive
25268 			 * ill and send a copy of the packet up each matching
25269 			 * one. However, we don't do this for multicasts sent on
25270 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25271 			 * they must stay in the sender's zone.
25272 			 *
25273 			 * ilm_add_v6() ensures that ilms in the same zone are
25274 			 * contiguous in the ill_ilm list. We use this property
25275 			 * to avoid sending duplicates needed when two
25276 			 * applications in the same zone join the same group on
25277 			 * different logical interfaces: we ignore the ilm if
25278 			 * it's zoneid is the same as the last matching one.
25279 			 * In addition, the sending of the packet for
25280 			 * ire_zoneid is delayed until all of the other ilms
25281 			 * have been exhausted.
25282 			 */
25283 			last_zoneid = -1;
25284 			ILM_WALKER_HOLD(ill);
25285 			for (ilm = ill->ill_ilm; ilm != NULL;
25286 			    ilm = ilm->ilm_next) {
25287 				if ((ilm->ilm_flags & ILM_DELETED) ||
25288 				    ipha->ipha_dst != ilm->ilm_addr ||
25289 				    ilm->ilm_zoneid == last_zoneid ||
25290 				    ilm->ilm_zoneid == zoneid ||
25291 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25292 					continue;
25293 				mp1 = ip_copymsg(first_mp);
25294 				if (mp1 == NULL)
25295 					continue;
25296 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25297 				    mctl_present, B_FALSE, ill,
25298 				    ilm->ilm_zoneid);
25299 				last_zoneid = ilm->ilm_zoneid;
25300 			}
25301 			ILM_WALKER_RELE(ill);
25302 			/*
25303 			 * Loopback case: the sending endpoint has
25304 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25305 			 * dispatch the multicast packet to the sending zone.
25306 			 */
25307 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25308 				freemsg(first_mp);
25309 				return;
25310 			}
25311 		} else if (ire_type == IRE_BROADCAST) {
25312 			/*
25313 			 * In the broadcast case, there may be many zones
25314 			 * which need a copy of the packet delivered to them.
25315 			 * There is one IRE_BROADCAST per broadcast address
25316 			 * and per zone; we walk those using a helper function.
25317 			 * In addition, the sending of the packet for zoneid is
25318 			 * delayed until all of the other ires have been
25319 			 * processed.
25320 			 */
25321 			IRB_REFHOLD(ire->ire_bucket);
25322 			ire_zone = NULL;
25323 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25324 			    ire)) != NULL) {
25325 				mp1 = ip_copymsg(first_mp);
25326 				if (mp1 == NULL)
25327 					continue;
25328 
25329 				UPDATE_IB_PKT_COUNT(ire_zone);
25330 				ire_zone->ire_last_used_time = lbolt;
25331 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25332 				    mctl_present, B_FALSE, ill,
25333 				    ire_zone->ire_zoneid);
25334 			}
25335 			IRB_REFRELE(ire->ire_bucket);
25336 		}
25337 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25338 		    0, mctl_present, B_FALSE, ill, zoneid);
25339 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25340 		    "ip_wput_local_end: q %p (%S)",
25341 		    q, "icmp");
25342 		return;
25343 	}
25344 	case IPPROTO_IGMP:
25345 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25346 			/* Bad packet - discarded by igmp_input */
25347 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25348 			    "ip_wput_local_end: q %p (%S)",
25349 			    q, "igmp_input--bad packet");
25350 			if (mctl_present)
25351 				freeb(first_mp);
25352 			return;
25353 		}
25354 		/*
25355 		 * igmp_input() may have returned the pulled up message.
25356 		 * So first_mp and ipha need to be reinitialized.
25357 		 */
25358 		ipha = (ipha_t *)mp->b_rptr;
25359 		if (mctl_present)
25360 			first_mp->b_cont = mp;
25361 		else
25362 			first_mp = mp;
25363 		/* deliver to local raw users */
25364 		break;
25365 	case IPPROTO_ENCAP:
25366 		/*
25367 		 * This case is covered by either ip_fanout_proto, or by
25368 		 * the above security processing for self-tunneled packets.
25369 		 */
25370 		break;
25371 	case IPPROTO_UDP: {
25372 		uint16_t	*up;
25373 		uint32_t	ports;
25374 
25375 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25376 		    UDP_PORTS_OFFSET);
25377 		/* Force a 'valid' checksum. */
25378 		up[3] = 0;
25379 
25380 		ports = *(uint32_t *)up;
25381 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25382 		    (ire_type == IRE_BROADCAST),
25383 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25384 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25385 		    ill, zoneid);
25386 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25387 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25388 		return;
25389 	}
25390 	case IPPROTO_TCP: {
25391 
25392 		/*
25393 		 * For TCP, discard broadcast packets.
25394 		 */
25395 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25396 			freemsg(first_mp);
25397 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25398 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25399 			return;
25400 		}
25401 
25402 		if (mp->b_datap->db_type == M_DATA) {
25403 			/*
25404 			 * M_DATA mblk, so init mblk (chain) for no struio().
25405 			 */
25406 			mblk_t	*mp1 = mp;
25407 
25408 			do {
25409 				mp1->b_datap->db_struioflag = 0;
25410 			} while ((mp1 = mp1->b_cont) != NULL);
25411 		}
25412 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25413 		    <= mp->b_wptr);
25414 		ip_fanout_tcp(q, first_mp, ill, ipha,
25415 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25416 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25417 		    mctl_present, B_FALSE, zoneid);
25418 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25419 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25420 		return;
25421 	}
25422 	case IPPROTO_SCTP:
25423 	{
25424 		uint32_t	ports;
25425 
25426 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25427 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25428 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25429 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25430 		return;
25431 	}
25432 
25433 	default:
25434 		break;
25435 	}
25436 	/*
25437 	 * Find a client for some other protocol.  We give
25438 	 * copies to multiple clients, if more than one is
25439 	 * bound.
25440 	 */
25441 	ip_fanout_proto(q, first_mp, ill, ipha,
25442 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25443 	    mctl_present, B_FALSE, ill, zoneid);
25444 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25445 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25446 #undef	rptr
25447 }
25448 
25449 /*
25450  * Update any source route, record route, or timestamp options.
25451  * Check that we are at end of strict source route.
25452  * The options have been sanity checked by ip_wput_options().
25453  */
25454 static void
25455 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25456 {
25457 	ipoptp_t	opts;
25458 	uchar_t		*opt;
25459 	uint8_t		optval;
25460 	uint8_t		optlen;
25461 	ipaddr_t	dst;
25462 	uint32_t	ts;
25463 	ire_t		*ire;
25464 	timestruc_t	now;
25465 
25466 	ip2dbg(("ip_wput_local_options\n"));
25467 	for (optval = ipoptp_first(&opts, ipha);
25468 	    optval != IPOPT_EOL;
25469 	    optval = ipoptp_next(&opts)) {
25470 		opt = opts.ipoptp_cur;
25471 		optlen = opts.ipoptp_len;
25472 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25473 		switch (optval) {
25474 			uint32_t off;
25475 		case IPOPT_SSRR:
25476 		case IPOPT_LSRR:
25477 			off = opt[IPOPT_OFFSET];
25478 			off--;
25479 			if (optlen < IP_ADDR_LEN ||
25480 			    off > optlen - IP_ADDR_LEN) {
25481 				/* End of source route */
25482 				break;
25483 			}
25484 			/*
25485 			 * This will only happen if two consecutive entries
25486 			 * in the source route contains our address or if
25487 			 * it is a packet with a loose source route which
25488 			 * reaches us before consuming the whole source route
25489 			 */
25490 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25491 			if (optval == IPOPT_SSRR) {
25492 				return;
25493 			}
25494 			/*
25495 			 * Hack: instead of dropping the packet truncate the
25496 			 * source route to what has been used by filling the
25497 			 * rest with IPOPT_NOP.
25498 			 */
25499 			opt[IPOPT_OLEN] = (uint8_t)off;
25500 			while (off < optlen) {
25501 				opt[off++] = IPOPT_NOP;
25502 			}
25503 			break;
25504 		case IPOPT_RR:
25505 			off = opt[IPOPT_OFFSET];
25506 			off--;
25507 			if (optlen < IP_ADDR_LEN ||
25508 			    off > optlen - IP_ADDR_LEN) {
25509 				/* No more room - ignore */
25510 				ip1dbg((
25511 				    "ip_wput_forward_options: end of RR\n"));
25512 				break;
25513 			}
25514 			dst = htonl(INADDR_LOOPBACK);
25515 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25516 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25517 			break;
25518 		case IPOPT_TS:
25519 			/* Insert timestamp if there is romm */
25520 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25521 			case IPOPT_TS_TSONLY:
25522 				off = IPOPT_TS_TIMELEN;
25523 				break;
25524 			case IPOPT_TS_PRESPEC:
25525 			case IPOPT_TS_PRESPEC_RFC791:
25526 				/* Verify that the address matched */
25527 				off = opt[IPOPT_OFFSET] - 1;
25528 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25529 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25530 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25531 				    ipst);
25532 				if (ire == NULL) {
25533 					/* Not for us */
25534 					break;
25535 				}
25536 				ire_refrele(ire);
25537 				/* FALLTHRU */
25538 			case IPOPT_TS_TSANDADDR:
25539 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25540 				break;
25541 			default:
25542 				/*
25543 				 * ip_*put_options should have already
25544 				 * dropped this packet.
25545 				 */
25546 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25547 				    "unknown IT - bug in ip_wput_options?\n");
25548 				return;	/* Keep "lint" happy */
25549 			}
25550 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25551 				/* Increase overflow counter */
25552 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25553 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25554 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25555 				    (off << 4);
25556 				break;
25557 			}
25558 			off = opt[IPOPT_OFFSET] - 1;
25559 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25560 			case IPOPT_TS_PRESPEC:
25561 			case IPOPT_TS_PRESPEC_RFC791:
25562 			case IPOPT_TS_TSANDADDR:
25563 				dst = htonl(INADDR_LOOPBACK);
25564 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25565 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25566 				/* FALLTHRU */
25567 			case IPOPT_TS_TSONLY:
25568 				off = opt[IPOPT_OFFSET] - 1;
25569 				/* Compute # of milliseconds since midnight */
25570 				gethrestime(&now);
25571 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25572 				    now.tv_nsec / (NANOSEC / MILLISEC);
25573 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25574 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25575 				break;
25576 			}
25577 			break;
25578 		}
25579 	}
25580 }
25581 
25582 /*
25583  * Send out a multicast packet on interface ipif.
25584  * The sender does not have an conn.
25585  * Caller verifies that this isn't a PHYI_LOOPBACK.
25586  */
25587 void
25588 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25589 {
25590 	ipha_t	*ipha;
25591 	ire_t	*ire;
25592 	ipaddr_t	dst;
25593 	mblk_t		*first_mp;
25594 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25595 
25596 	/* igmp_sendpkt always allocates a ipsec_out_t */
25597 	ASSERT(mp->b_datap->db_type == M_CTL);
25598 	ASSERT(!ipif->ipif_isv6);
25599 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25600 
25601 	first_mp = mp;
25602 	mp = first_mp->b_cont;
25603 	ASSERT(mp->b_datap->db_type == M_DATA);
25604 	ipha = (ipha_t *)mp->b_rptr;
25605 
25606 	/*
25607 	 * Find an IRE which matches the destination and the outgoing
25608 	 * queue (i.e. the outgoing interface.)
25609 	 */
25610 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25611 		dst = ipif->ipif_pp_dst_addr;
25612 	else
25613 		dst = ipha->ipha_dst;
25614 	/*
25615 	 * The source address has already been initialized by the
25616 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25617 	 * be sufficient rather than MATCH_IRE_IPIF.
25618 	 *
25619 	 * This function is used for sending IGMP packets. We need
25620 	 * to make sure that we send the packet out of the interface
25621 	 * (ipif->ipif_ill) where we joined the group. This is to
25622 	 * prevent from switches doing IGMP snooping to send us multicast
25623 	 * packets for a given group on the interface we have joined.
25624 	 * If we can't find an ire, igmp_sendpkt has already initialized
25625 	 * ipsec_out_attach_if so that this will not be load spread in
25626 	 * ip_newroute_ipif.
25627 	 */
25628 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25629 	    MATCH_IRE_ILL, ipst);
25630 	if (!ire) {
25631 		/*
25632 		 * Mark this packet to make it be delivered to
25633 		 * ip_wput_ire after the new ire has been
25634 		 * created.
25635 		 */
25636 		mp->b_prev = NULL;
25637 		mp->b_next = NULL;
25638 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25639 		    zoneid, &zero_info);
25640 		return;
25641 	}
25642 
25643 	/*
25644 	 * Honor the RTF_SETSRC flag; this is the only case
25645 	 * where we force this addr whatever the current src addr is,
25646 	 * because this address is set by igmp_sendpkt(), and
25647 	 * cannot be specified by any user.
25648 	 */
25649 	if (ire->ire_flags & RTF_SETSRC) {
25650 		ipha->ipha_src = ire->ire_src_addr;
25651 	}
25652 
25653 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25654 }
25655 
25656 /*
25657  * NOTE : This function does not ire_refrele the ire argument passed in.
25658  *
25659  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25660  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25661  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25662  * the ire_lock to access the nce_fp_mp in this case.
25663  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25664  * prepending a fastpath message IPQoS processing must precede it, we also set
25665  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25666  * (IPQoS might have set the b_band for CoS marking).
25667  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25668  * must follow it so that IPQoS can mark the dl_priority field for CoS
25669  * marking, if needed.
25670  */
25671 static mblk_t *
25672 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25673 {
25674 	uint_t	hlen;
25675 	ipha_t *ipha;
25676 	mblk_t *mp1;
25677 	boolean_t qos_done = B_FALSE;
25678 	uchar_t	*ll_hdr;
25679 	ip_stack_t	*ipst = ire->ire_ipst;
25680 
25681 #define	rptr	((uchar_t *)ipha)
25682 
25683 	ipha = (ipha_t *)mp->b_rptr;
25684 	hlen = 0;
25685 	LOCK_IRE_FP_MP(ire);
25686 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25687 		ASSERT(DB_TYPE(mp1) == M_DATA);
25688 		/* Initiate IPPF processing */
25689 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25690 			UNLOCK_IRE_FP_MP(ire);
25691 			ip_process(proc, &mp, ill_index);
25692 			if (mp == NULL)
25693 				return (NULL);
25694 
25695 			ipha = (ipha_t *)mp->b_rptr;
25696 			LOCK_IRE_FP_MP(ire);
25697 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25698 				qos_done = B_TRUE;
25699 				goto no_fp_mp;
25700 			}
25701 			ASSERT(DB_TYPE(mp1) == M_DATA);
25702 		}
25703 		hlen = MBLKL(mp1);
25704 		/*
25705 		 * Check if we have enough room to prepend fastpath
25706 		 * header
25707 		 */
25708 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25709 			ll_hdr = rptr - hlen;
25710 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25711 			/*
25712 			 * Set the b_rptr to the start of the link layer
25713 			 * header
25714 			 */
25715 			mp->b_rptr = ll_hdr;
25716 			mp1 = mp;
25717 		} else {
25718 			mp1 = copyb(mp1);
25719 			if (mp1 == NULL)
25720 				goto unlock_err;
25721 			mp1->b_band = mp->b_band;
25722 			mp1->b_cont = mp;
25723 			/*
25724 			 * certain system generated traffic may not
25725 			 * have cred/label in ip header block. This
25726 			 * is true even for a labeled system. But for
25727 			 * labeled traffic, inherit the label in the
25728 			 * new header.
25729 			 */
25730 			if (DB_CRED(mp) != NULL)
25731 				mblk_setcred(mp1, DB_CRED(mp));
25732 			/*
25733 			 * XXX disable ICK_VALID and compute checksum
25734 			 * here; can happen if nce_fp_mp changes and
25735 			 * it can't be copied now due to insufficient
25736 			 * space. (unlikely, fp mp can change, but it
25737 			 * does not increase in length)
25738 			 */
25739 		}
25740 		UNLOCK_IRE_FP_MP(ire);
25741 	} else {
25742 no_fp_mp:
25743 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25744 		if (mp1 == NULL) {
25745 unlock_err:
25746 			UNLOCK_IRE_FP_MP(ire);
25747 			freemsg(mp);
25748 			return (NULL);
25749 		}
25750 		UNLOCK_IRE_FP_MP(ire);
25751 		mp1->b_cont = mp;
25752 		/*
25753 		 * certain system generated traffic may not
25754 		 * have cred/label in ip header block. This
25755 		 * is true even for a labeled system. But for
25756 		 * labeled traffic, inherit the label in the
25757 		 * new header.
25758 		 */
25759 		if (DB_CRED(mp) != NULL)
25760 			mblk_setcred(mp1, DB_CRED(mp));
25761 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25762 			ip_process(proc, &mp1, ill_index);
25763 			if (mp1 == NULL)
25764 				return (NULL);
25765 		}
25766 	}
25767 	return (mp1);
25768 #undef rptr
25769 }
25770 
25771 /*
25772  * Finish the outbound IPsec processing for an IPv6 packet. This function
25773  * is called from ipsec_out_process() if the IPsec packet was processed
25774  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25775  * asynchronously.
25776  */
25777 void
25778 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25779     ire_t *ire_arg)
25780 {
25781 	in6_addr_t *v6dstp;
25782 	ire_t *ire;
25783 	mblk_t *mp;
25784 	ip6_t *ip6h1;
25785 	uint_t	ill_index;
25786 	ipsec_out_t *io;
25787 	boolean_t attach_if, hwaccel;
25788 	uint32_t flags = IP6_NO_IPPOLICY;
25789 	int match_flags;
25790 	zoneid_t zoneid;
25791 	boolean_t ill_need_rele = B_FALSE;
25792 	boolean_t ire_need_rele = B_FALSE;
25793 	ip_stack_t	*ipst;
25794 
25795 	mp = ipsec_mp->b_cont;
25796 	ip6h1 = (ip6_t *)mp->b_rptr;
25797 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25798 	ASSERT(io->ipsec_out_ns != NULL);
25799 	ipst = io->ipsec_out_ns->netstack_ip;
25800 	ill_index = io->ipsec_out_ill_index;
25801 	if (io->ipsec_out_reachable) {
25802 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25803 	}
25804 	attach_if = io->ipsec_out_attach_if;
25805 	hwaccel = io->ipsec_out_accelerated;
25806 	zoneid = io->ipsec_out_zoneid;
25807 	ASSERT(zoneid != ALL_ZONES);
25808 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25809 	/* Multicast addresses should have non-zero ill_index. */
25810 	v6dstp = &ip6h->ip6_dst;
25811 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25812 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25813 	ASSERT(!attach_if || ill_index != 0);
25814 	if (ill_index != 0) {
25815 		if (ill == NULL) {
25816 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25817 			    B_TRUE, ipst);
25818 
25819 			/* Failure case frees things for us. */
25820 			if (ill == NULL)
25821 				return;
25822 
25823 			ill_need_rele = B_TRUE;
25824 		}
25825 		/*
25826 		 * If this packet needs to go out on a particular interface
25827 		 * honor it.
25828 		 */
25829 		if (attach_if) {
25830 			match_flags = MATCH_IRE_ILL;
25831 
25832 			/*
25833 			 * Check if we need an ire that will not be
25834 			 * looked up by anybody else i.e. HIDDEN.
25835 			 */
25836 			if (ill_is_probeonly(ill)) {
25837 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25838 			}
25839 		}
25840 	}
25841 	ASSERT(mp != NULL);
25842 
25843 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25844 		boolean_t unspec_src;
25845 		ipif_t	*ipif;
25846 
25847 		/*
25848 		 * Use the ill_index to get the right ill.
25849 		 */
25850 		unspec_src = io->ipsec_out_unspec_src;
25851 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25852 		if (ipif == NULL) {
25853 			if (ill_need_rele)
25854 				ill_refrele(ill);
25855 			freemsg(ipsec_mp);
25856 			return;
25857 		}
25858 
25859 		if (ire_arg != NULL) {
25860 			ire = ire_arg;
25861 		} else {
25862 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25863 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25864 			ire_need_rele = B_TRUE;
25865 		}
25866 		if (ire != NULL) {
25867 			ipif_refrele(ipif);
25868 			/*
25869 			 * XXX Do the multicast forwarding now, as the IPSEC
25870 			 * processing has been done.
25871 			 */
25872 			goto send;
25873 		}
25874 
25875 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25876 		mp->b_prev = NULL;
25877 		mp->b_next = NULL;
25878 
25879 		/*
25880 		 * If the IPsec packet was processed asynchronously,
25881 		 * drop it now.
25882 		 */
25883 		if (q == NULL) {
25884 			if (ill_need_rele)
25885 				ill_refrele(ill);
25886 			freemsg(ipsec_mp);
25887 			return;
25888 		}
25889 
25890 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25891 		    unspec_src, zoneid);
25892 		ipif_refrele(ipif);
25893 	} else {
25894 		if (attach_if) {
25895 			ipif_t	*ipif;
25896 
25897 			ipif = ipif_get_next_ipif(NULL, ill);
25898 			if (ipif == NULL) {
25899 				if (ill_need_rele)
25900 					ill_refrele(ill);
25901 				freemsg(ipsec_mp);
25902 				return;
25903 			}
25904 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25905 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25906 			ire_need_rele = B_TRUE;
25907 			ipif_refrele(ipif);
25908 		} else {
25909 			if (ire_arg != NULL) {
25910 				ire = ire_arg;
25911 			} else {
25912 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25913 				    ipst);
25914 				ire_need_rele = B_TRUE;
25915 			}
25916 		}
25917 		if (ire != NULL)
25918 			goto send;
25919 		/*
25920 		 * ire disappeared underneath.
25921 		 *
25922 		 * What we need to do here is the ip_newroute
25923 		 * logic to get the ire without doing the IPSEC
25924 		 * processing. Follow the same old path. But this
25925 		 * time, ip_wput or ire_add_then_send will call us
25926 		 * directly as all the IPSEC operations are done.
25927 		 */
25928 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25929 		mp->b_prev = NULL;
25930 		mp->b_next = NULL;
25931 
25932 		/*
25933 		 * If the IPsec packet was processed asynchronously,
25934 		 * drop it now.
25935 		 */
25936 		if (q == NULL) {
25937 			if (ill_need_rele)
25938 				ill_refrele(ill);
25939 			freemsg(ipsec_mp);
25940 			return;
25941 		}
25942 
25943 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25944 		    zoneid, ipst);
25945 	}
25946 	if (ill != NULL && ill_need_rele)
25947 		ill_refrele(ill);
25948 	return;
25949 send:
25950 	if (ill != NULL && ill_need_rele)
25951 		ill_refrele(ill);
25952 
25953 	/* Local delivery */
25954 	if (ire->ire_stq == NULL) {
25955 		ill_t	*out_ill;
25956 		ASSERT(q != NULL);
25957 
25958 		/* PFHooks: LOOPBACK_OUT */
25959 		out_ill = ire->ire_ipif->ipif_ill;
25960 
25961 		DTRACE_PROBE4(ip6__loopback__out__start,
25962 		    ill_t *, NULL, ill_t *, out_ill,
25963 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25964 
25965 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25966 		    ipst->ips_ipv6firewall_loopback_out,
25967 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25968 
25969 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25970 
25971 		if (ipsec_mp != NULL)
25972 			ip_wput_local_v6(RD(q), out_ill,
25973 			    ip6h, ipsec_mp, ire, 0);
25974 		if (ire_need_rele)
25975 			ire_refrele(ire);
25976 		return;
25977 	}
25978 	/*
25979 	 * Everything is done. Send it out on the wire.
25980 	 * We force the insertion of a fragment header using the
25981 	 * IPH_FRAG_HDR flag in two cases:
25982 	 * - after reception of an ICMPv6 "packet too big" message
25983 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25984 	 * - for multirouted IPv6 packets, so that the receiver can
25985 	 *   discard duplicates according to their fragment identifier
25986 	 */
25987 	/* XXX fix flow control problems. */
25988 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25989 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25990 		if (hwaccel) {
25991 			/*
25992 			 * hardware acceleration does not handle these
25993 			 * "slow path" cases.
25994 			 */
25995 			/* IPsec KSTATS: should bump bean counter here. */
25996 			if (ire_need_rele)
25997 				ire_refrele(ire);
25998 			freemsg(ipsec_mp);
25999 			return;
26000 		}
26001 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
26002 		    (mp->b_cont ? msgdsize(mp) :
26003 		    mp->b_wptr - (uchar_t *)ip6h)) {
26004 			/* IPsec KSTATS: should bump bean counter here. */
26005 			ip0dbg(("Packet length mismatch: %d, %ld\n",
26006 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
26007 			    msgdsize(mp)));
26008 			if (ire_need_rele)
26009 				ire_refrele(ire);
26010 			freemsg(ipsec_mp);
26011 			return;
26012 		}
26013 		ASSERT(mp->b_prev == NULL);
26014 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26015 		    ntohs(ip6h->ip6_plen) +
26016 		    IPV6_HDR_LEN, ire->ire_max_frag));
26017 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26018 		    ire->ire_max_frag);
26019 	} else {
26020 		UPDATE_OB_PKT_COUNT(ire);
26021 		ire->ire_last_used_time = lbolt;
26022 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26023 	}
26024 	if (ire_need_rele)
26025 		ire_refrele(ire);
26026 	freeb(ipsec_mp);
26027 }
26028 
26029 void
26030 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26031 {
26032 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26033 	da_ipsec_t *hada;	/* data attributes */
26034 	ill_t *ill = (ill_t *)q->q_ptr;
26035 
26036 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26037 
26038 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26039 		/* IPsec KSTATS: Bump lose counter here! */
26040 		freemsg(mp);
26041 		return;
26042 	}
26043 
26044 	/*
26045 	 * It's an IPsec packet that must be
26046 	 * accelerated by the Provider, and the
26047 	 * outbound ill is IPsec acceleration capable.
26048 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26049 	 * to the ill.
26050 	 * IPsec KSTATS: should bump packet counter here.
26051 	 */
26052 
26053 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26054 	if (hada_mp == NULL) {
26055 		/* IPsec KSTATS: should bump packet counter here. */
26056 		freemsg(mp);
26057 		return;
26058 	}
26059 
26060 	hada_mp->b_datap->db_type = M_CTL;
26061 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26062 	hada_mp->b_cont = mp;
26063 
26064 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26065 	bzero(hada, sizeof (da_ipsec_t));
26066 	hada->da_type = IPHADA_M_CTL;
26067 
26068 	putnext(q, hada_mp);
26069 }
26070 
26071 /*
26072  * Finish the outbound IPsec processing. This function is called from
26073  * ipsec_out_process() if the IPsec packet was processed
26074  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26075  * asynchronously.
26076  */
26077 void
26078 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26079     ire_t *ire_arg)
26080 {
26081 	uint32_t v_hlen_tos_len;
26082 	ipaddr_t	dst;
26083 	ipif_t	*ipif = NULL;
26084 	ire_t *ire;
26085 	ire_t *ire1 = NULL;
26086 	mblk_t *next_mp = NULL;
26087 	uint32_t max_frag;
26088 	boolean_t multirt_send = B_FALSE;
26089 	mblk_t *mp;
26090 	mblk_t *mp1;
26091 	ipha_t *ipha1;
26092 	uint_t	ill_index;
26093 	ipsec_out_t *io;
26094 	boolean_t attach_if;
26095 	int match_flags, offset;
26096 	irb_t *irb = NULL;
26097 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26098 	zoneid_t zoneid;
26099 	uint32_t cksum;
26100 	uint16_t *up;
26101 	ipxmit_state_t	pktxmit_state;
26102 	ip_stack_t	*ipst;
26103 
26104 #ifdef	_BIG_ENDIAN
26105 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26106 #else
26107 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26108 #endif
26109 
26110 	mp = ipsec_mp->b_cont;
26111 	ipha1 = (ipha_t *)mp->b_rptr;
26112 	ASSERT(mp != NULL);
26113 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26114 	dst = ipha->ipha_dst;
26115 
26116 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26117 	ill_index = io->ipsec_out_ill_index;
26118 	attach_if = io->ipsec_out_attach_if;
26119 	zoneid = io->ipsec_out_zoneid;
26120 	ASSERT(zoneid != ALL_ZONES);
26121 	ipst = io->ipsec_out_ns->netstack_ip;
26122 	ASSERT(io->ipsec_out_ns != NULL);
26123 
26124 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26125 	if (ill_index != 0) {
26126 		if (ill == NULL) {
26127 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26128 			    ill_index, B_FALSE, ipst);
26129 
26130 			/* Failure case frees things for us. */
26131 			if (ill == NULL)
26132 				return;
26133 
26134 			ill_need_rele = B_TRUE;
26135 		}
26136 		/*
26137 		 * If this packet needs to go out on a particular interface
26138 		 * honor it.
26139 		 */
26140 		if (attach_if) {
26141 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26142 
26143 			/*
26144 			 * Check if we need an ire that will not be
26145 			 * looked up by anybody else i.e. HIDDEN.
26146 			 */
26147 			if (ill_is_probeonly(ill)) {
26148 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26149 			}
26150 		}
26151 	}
26152 
26153 	if (CLASSD(dst)) {
26154 		boolean_t conn_dontroute;
26155 		/*
26156 		 * Use the ill_index to get the right ipif.
26157 		 */
26158 		conn_dontroute = io->ipsec_out_dontroute;
26159 		if (ill_index == 0)
26160 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26161 		else
26162 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26163 		if (ipif == NULL) {
26164 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26165 			    " multicast\n"));
26166 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26167 			freemsg(ipsec_mp);
26168 			goto done;
26169 		}
26170 		/*
26171 		 * ipha_src has already been intialized with the
26172 		 * value of the ipif in ip_wput. All we need now is
26173 		 * an ire to send this downstream.
26174 		 */
26175 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26176 		    MBLK_GETLABEL(mp), match_flags, ipst);
26177 		if (ire != NULL) {
26178 			ill_t *ill1;
26179 			/*
26180 			 * Do the multicast forwarding now, as the IPSEC
26181 			 * processing has been done.
26182 			 */
26183 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26184 			    (ill1 = ire_to_ill(ire))) {
26185 				if (ip_mforward(ill1, ipha, mp)) {
26186 					freemsg(ipsec_mp);
26187 					ip1dbg(("ip_wput_ipsec_out: mforward "
26188 					    "failed\n"));
26189 					ire_refrele(ire);
26190 					goto done;
26191 				}
26192 			}
26193 			goto send;
26194 		}
26195 
26196 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26197 		mp->b_prev = NULL;
26198 		mp->b_next = NULL;
26199 
26200 		/*
26201 		 * If the IPsec packet was processed asynchronously,
26202 		 * drop it now.
26203 		 */
26204 		if (q == NULL) {
26205 			freemsg(ipsec_mp);
26206 			goto done;
26207 		}
26208 
26209 		/*
26210 		 * We may be using a wrong ipif to create the ire.
26211 		 * But it is okay as the source address is assigned
26212 		 * for the packet already. Next outbound packet would
26213 		 * create the IRE with the right IPIF in ip_wput.
26214 		 *
26215 		 * Also handle RTF_MULTIRT routes.
26216 		 */
26217 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26218 		    zoneid, &zero_info);
26219 	} else {
26220 		if (attach_if) {
26221 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26222 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26223 		} else {
26224 			if (ire_arg != NULL) {
26225 				ire = ire_arg;
26226 				ire_need_rele = B_FALSE;
26227 			} else {
26228 				ire = ire_cache_lookup(dst, zoneid,
26229 				    MBLK_GETLABEL(mp), ipst);
26230 			}
26231 		}
26232 		if (ire != NULL) {
26233 			goto send;
26234 		}
26235 
26236 		/*
26237 		 * ire disappeared underneath.
26238 		 *
26239 		 * What we need to do here is the ip_newroute
26240 		 * logic to get the ire without doing the IPSEC
26241 		 * processing. Follow the same old path. But this
26242 		 * time, ip_wput or ire_add_then_put will call us
26243 		 * directly as all the IPSEC operations are done.
26244 		 */
26245 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26246 		mp->b_prev = NULL;
26247 		mp->b_next = NULL;
26248 
26249 		/*
26250 		 * If the IPsec packet was processed asynchronously,
26251 		 * drop it now.
26252 		 */
26253 		if (q == NULL) {
26254 			freemsg(ipsec_mp);
26255 			goto done;
26256 		}
26257 
26258 		/*
26259 		 * Since we're going through ip_newroute() again, we
26260 		 * need to make sure we don't:
26261 		 *
26262 		 *	1.) Trigger the ASSERT() with the ipha_ident
26263 		 *	    overloading.
26264 		 *	2.) Redo transport-layer checksumming, since we've
26265 		 *	    already done all that to get this far.
26266 		 *
26267 		 * The easiest way not do either of the above is to set
26268 		 * the ipha_ident field to IP_HDR_INCLUDED.
26269 		 */
26270 		ipha->ipha_ident = IP_HDR_INCLUDED;
26271 		ip_newroute(q, ipsec_mp, dst, NULL,
26272 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26273 	}
26274 	goto done;
26275 send:
26276 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26277 	    udp_compute_checksum(ipst->ips_netstack)) {
26278 		/*
26279 		 * ESP NAT-Traversal packet.
26280 		 *
26281 		 * Just do software checksum for now.
26282 		 */
26283 
26284 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26285 		IP_STAT(ipst, ip_out_sw_cksum);
26286 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26287 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26288 #define	iphs	((uint16_t *)ipha)
26289 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26290 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26291 		    IP_SIMPLE_HDR_LENGTH);
26292 #undef iphs
26293 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
26294 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26295 			if (mp1->b_wptr - mp1->b_rptr >=
26296 			    offset + sizeof (uint16_t)) {
26297 				up = (uint16_t *)(mp1->b_rptr + offset);
26298 				*up = cksum;
26299 				break;	/* out of for loop */
26300 			} else {
26301 				offset -= (mp->b_wptr - mp->b_rptr);
26302 			}
26303 	} /* Otherwise, just keep the all-zero checksum. */
26304 
26305 	if (ire->ire_stq == NULL) {
26306 		ill_t	*out_ill;
26307 		/*
26308 		 * Loopbacks go through ip_wput_local except for one case.
26309 		 * We come here if we generate a icmp_frag_needed message
26310 		 * after IPSEC processing is over. When this function calls
26311 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26312 		 * icmp_frag_needed. The message generated comes back here
26313 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26314 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26315 		 * source address as it is usually set in ip_wput_ire. As
26316 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26317 		 * and we end up here. We can't enter ip_wput_ire once the
26318 		 * IPSEC processing is over and hence we need to do it here.
26319 		 */
26320 		ASSERT(q != NULL);
26321 		UPDATE_OB_PKT_COUNT(ire);
26322 		ire->ire_last_used_time = lbolt;
26323 		if (ipha->ipha_src == 0)
26324 			ipha->ipha_src = ire->ire_src_addr;
26325 
26326 		/* PFHooks: LOOPBACK_OUT */
26327 		out_ill = ire->ire_ipif->ipif_ill;
26328 
26329 		DTRACE_PROBE4(ip4__loopback__out__start,
26330 		    ill_t *, NULL, ill_t *, out_ill,
26331 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26332 
26333 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26334 		    ipst->ips_ipv4firewall_loopback_out,
26335 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26336 
26337 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26338 
26339 		if (ipsec_mp != NULL)
26340 			ip_wput_local(RD(q), out_ill,
26341 			    ipha, ipsec_mp, ire, 0, zoneid);
26342 		if (ire_need_rele)
26343 			ire_refrele(ire);
26344 		goto done;
26345 	}
26346 
26347 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26348 		/*
26349 		 * We are through with IPSEC processing.
26350 		 * Fragment this and send it on the wire.
26351 		 */
26352 		if (io->ipsec_out_accelerated) {
26353 			/*
26354 			 * The packet has been accelerated but must
26355 			 * be fragmented. This should not happen
26356 			 * since AH and ESP must not accelerate
26357 			 * packets that need fragmentation, however
26358 			 * the configuration could have changed
26359 			 * since the AH or ESP processing.
26360 			 * Drop packet.
26361 			 * IPsec KSTATS: bump bean counter here.
26362 			 */
26363 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26364 			    "fragmented accelerated packet!\n"));
26365 			freemsg(ipsec_mp);
26366 		} else {
26367 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26368 		}
26369 		if (ire_need_rele)
26370 			ire_refrele(ire);
26371 		goto done;
26372 	}
26373 
26374 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26375 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26376 	    (void *)ire->ire_ipif, (void *)ipif));
26377 
26378 	/*
26379 	 * Multiroute the secured packet, unless IPsec really
26380 	 * requires the packet to go out only through a particular
26381 	 * interface.
26382 	 */
26383 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26384 		ire_t *first_ire;
26385 		irb = ire->ire_bucket;
26386 		ASSERT(irb != NULL);
26387 		/*
26388 		 * This ire has been looked up as the one that
26389 		 * goes through the given ipif;
26390 		 * make sure we do not omit any other multiroute ire
26391 		 * that may be present in the bucket before this one.
26392 		 */
26393 		IRB_REFHOLD(irb);
26394 		for (first_ire = irb->irb_ire;
26395 		    first_ire != NULL;
26396 		    first_ire = first_ire->ire_next) {
26397 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26398 			    (first_ire->ire_addr == ire->ire_addr) &&
26399 			    !(first_ire->ire_marks &
26400 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26401 				break;
26402 			}
26403 		}
26404 
26405 		if ((first_ire != NULL) && (first_ire != ire)) {
26406 			/*
26407 			 * Don't change the ire if the packet must
26408 			 * be fragmented if sent via this new one.
26409 			 */
26410 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26411 				IRE_REFHOLD(first_ire);
26412 				if (ire_need_rele)
26413 					ire_refrele(ire);
26414 				else
26415 					ire_need_rele = B_TRUE;
26416 				ire = first_ire;
26417 			}
26418 		}
26419 		IRB_REFRELE(irb);
26420 
26421 		multirt_send = B_TRUE;
26422 		max_frag = ire->ire_max_frag;
26423 	} else {
26424 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26425 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26426 			    "flag, attach_if %d\n", attach_if));
26427 		}
26428 	}
26429 
26430 	/*
26431 	 * In most cases, the emission loop below is entered only once.
26432 	 * Only in the case where the ire holds the RTF_MULTIRT
26433 	 * flag, we loop to process all RTF_MULTIRT ires in the
26434 	 * bucket, and send the packet through all crossed
26435 	 * RTF_MULTIRT routes.
26436 	 */
26437 	do {
26438 		if (multirt_send) {
26439 			/*
26440 			 * ire1 holds here the next ire to process in the
26441 			 * bucket. If multirouting is expected,
26442 			 * any non-RTF_MULTIRT ire that has the
26443 			 * right destination address is ignored.
26444 			 */
26445 			ASSERT(irb != NULL);
26446 			IRB_REFHOLD(irb);
26447 			for (ire1 = ire->ire_next;
26448 			    ire1 != NULL;
26449 			    ire1 = ire1->ire_next) {
26450 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26451 					continue;
26452 				if (ire1->ire_addr != ire->ire_addr)
26453 					continue;
26454 				if (ire1->ire_marks &
26455 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26456 					continue;
26457 				/* No loopback here */
26458 				if (ire1->ire_stq == NULL)
26459 					continue;
26460 				/*
26461 				 * Ensure we do not exceed the MTU
26462 				 * of the next route.
26463 				 */
26464 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26465 					ip_multirt_bad_mtu(ire1, max_frag);
26466 					continue;
26467 				}
26468 
26469 				IRE_REFHOLD(ire1);
26470 				break;
26471 			}
26472 			IRB_REFRELE(irb);
26473 			if (ire1 != NULL) {
26474 				/*
26475 				 * We are in a multiple send case, need to
26476 				 * make a copy of the packet.
26477 				 */
26478 				next_mp = copymsg(ipsec_mp);
26479 				if (next_mp == NULL) {
26480 					ire_refrele(ire1);
26481 					ire1 = NULL;
26482 				}
26483 			}
26484 		}
26485 		/*
26486 		 * Everything is done. Send it out on the wire
26487 		 *
26488 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26489 		 * either send it on the wire or, in the case of
26490 		 * HW acceleration, call ipsec_hw_putnext.
26491 		 */
26492 		if (ire->ire_nce &&
26493 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26494 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26495 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26496 			/*
26497 			 * If ire's link-layer is unresolved (this
26498 			 * would only happen if the incomplete ire
26499 			 * was added to cachetable via forwarding path)
26500 			 * don't bother going to ip_xmit_v4. Just drop the
26501 			 * packet.
26502 			 * There is a slight risk here, in that, if we
26503 			 * have the forwarding path create an incomplete
26504 			 * IRE, then until the IRE is completed, any
26505 			 * transmitted IPSEC packets will be dropped
26506 			 * instead of being queued waiting for resolution.
26507 			 *
26508 			 * But the likelihood of a forwarding packet and a wput
26509 			 * packet sending to the same dst at the same time
26510 			 * and there not yet be an ARP entry for it is small.
26511 			 * Furthermore, if this actually happens, it might
26512 			 * be likely that wput would generate multiple
26513 			 * packets (and forwarding would also have a train
26514 			 * of packets) for that destination. If this is
26515 			 * the case, some of them would have been dropped
26516 			 * anyway, since ARP only queues a few packets while
26517 			 * waiting for resolution
26518 			 *
26519 			 * NOTE: We should really call ip_xmit_v4,
26520 			 * and let it queue the packet and send the
26521 			 * ARP query and have ARP come back thus:
26522 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26523 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26524 			 * hw accel work. But it's too complex to get
26525 			 * the IPsec hw  acceleration approach to fit
26526 			 * well with ip_xmit_v4 doing ARP without
26527 			 * doing IPSEC simplification. For now, we just
26528 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26529 			 * that we can continue with the send on the next
26530 			 * attempt.
26531 			 *
26532 			 * XXX THis should be revisited, when
26533 			 * the IPsec/IP interaction is cleaned up
26534 			 */
26535 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26536 			    " - dropping packet\n"));
26537 			freemsg(ipsec_mp);
26538 			/*
26539 			 * Call ip_xmit_v4() to trigger ARP query
26540 			 * in case the nce_state is ND_INITIAL
26541 			 */
26542 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26543 			goto drop_pkt;
26544 		}
26545 
26546 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26547 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26548 		    mblk_t *, ipsec_mp);
26549 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26550 		    ipst->ips_ipv4firewall_physical_out,
26551 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26552 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26553 		if (ipsec_mp == NULL)
26554 			goto drop_pkt;
26555 
26556 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26557 		pktxmit_state = ip_xmit_v4(mp, ire,
26558 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26559 
26560 		if ((pktxmit_state ==  SEND_FAILED) ||
26561 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26562 
26563 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26564 drop_pkt:
26565 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26566 			    ipIfStatsOutDiscards);
26567 			if (ire_need_rele)
26568 				ire_refrele(ire);
26569 			if (ire1 != NULL) {
26570 				ire_refrele(ire1);
26571 				freemsg(next_mp);
26572 			}
26573 			goto done;
26574 		}
26575 
26576 		freeb(ipsec_mp);
26577 		if (ire_need_rele)
26578 			ire_refrele(ire);
26579 
26580 		if (ire1 != NULL) {
26581 			ire = ire1;
26582 			ire_need_rele = B_TRUE;
26583 			ASSERT(next_mp);
26584 			ipsec_mp = next_mp;
26585 			mp = ipsec_mp->b_cont;
26586 			ire1 = NULL;
26587 			next_mp = NULL;
26588 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26589 		} else {
26590 			multirt_send = B_FALSE;
26591 		}
26592 	} while (multirt_send);
26593 done:
26594 	if (ill != NULL && ill_need_rele)
26595 		ill_refrele(ill);
26596 	if (ipif != NULL)
26597 		ipif_refrele(ipif);
26598 }
26599 
26600 /*
26601  * Get the ill corresponding to the specified ire, and compare its
26602  * capabilities with the protocol and algorithms specified by the
26603  * the SA obtained from ipsec_out. If they match, annotate the
26604  * ipsec_out structure to indicate that the packet needs acceleration.
26605  *
26606  *
26607  * A packet is eligible for outbound hardware acceleration if the
26608  * following conditions are satisfied:
26609  *
26610  * 1. the packet will not be fragmented
26611  * 2. the provider supports the algorithm
26612  * 3. there is no pending control message being exchanged
26613  * 4. snoop is not attached
26614  * 5. the destination address is not a broadcast or multicast address.
26615  *
26616  * Rationale:
26617  *	- Hardware drivers do not support fragmentation with
26618  *	  the current interface.
26619  *	- snoop, multicast, and broadcast may result in exposure of
26620  *	  a cleartext datagram.
26621  * We check all five of these conditions here.
26622  *
26623  * XXX would like to nuke "ire_t *" parameter here; problem is that
26624  * IRE is only way to figure out if a v4 address is a broadcast and
26625  * thus ineligible for acceleration...
26626  */
26627 static void
26628 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26629 {
26630 	ipsec_out_t *io;
26631 	mblk_t *data_mp;
26632 	uint_t plen, overhead;
26633 	ip_stack_t	*ipst;
26634 
26635 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26636 		return;
26637 
26638 	if (ill == NULL)
26639 		return;
26640 	ipst = ill->ill_ipst;
26641 	/*
26642 	 * Destination address is a broadcast or multicast.  Punt.
26643 	 */
26644 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26645 	    IRE_LOCAL)))
26646 		return;
26647 
26648 	data_mp = ipsec_mp->b_cont;
26649 
26650 	if (ill->ill_isv6) {
26651 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26652 
26653 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26654 			return;
26655 
26656 		plen = ip6h->ip6_plen;
26657 	} else {
26658 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26659 
26660 		if (CLASSD(ipha->ipha_dst))
26661 			return;
26662 
26663 		plen = ipha->ipha_length;
26664 	}
26665 	/*
26666 	 * Is there a pending DLPI control message being exchanged
26667 	 * between IP/IPsec and the DLS Provider? If there is, it
26668 	 * could be a SADB update, and the state of the DLS Provider
26669 	 * SADB might not be in sync with the SADB maintained by
26670 	 * IPsec. To avoid dropping packets or using the wrong keying
26671 	 * material, we do not accelerate this packet.
26672 	 */
26673 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26674 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26675 		    "ill_dlpi_pending! don't accelerate packet\n"));
26676 		return;
26677 	}
26678 
26679 	/*
26680 	 * Is the Provider in promiscous mode? If it does, we don't
26681 	 * accelerate the packet since it will bounce back up to the
26682 	 * listeners in the clear.
26683 	 */
26684 	if (ill->ill_promisc_on_phys) {
26685 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26686 		    "ill in promiscous mode, don't accelerate packet\n"));
26687 		return;
26688 	}
26689 
26690 	/*
26691 	 * Will the packet require fragmentation?
26692 	 */
26693 
26694 	/*
26695 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26696 	 * as is used elsewhere.
26697 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26698 	 *	+ 2-byte trailer
26699 	 */
26700 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26701 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26702 
26703 	if ((plen + overhead) > ill->ill_max_mtu)
26704 		return;
26705 
26706 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26707 
26708 	/*
26709 	 * Can the ill accelerate this IPsec protocol and algorithm
26710 	 * specified by the SA?
26711 	 */
26712 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26713 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26714 		return;
26715 	}
26716 
26717 	/*
26718 	 * Tell AH or ESP that the outbound ill is capable of
26719 	 * accelerating this packet.
26720 	 */
26721 	io->ipsec_out_is_capab_ill = B_TRUE;
26722 }
26723 
26724 /*
26725  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26726  *
26727  * If this function returns B_TRUE, the requested SA's have been filled
26728  * into the ipsec_out_*_sa pointers.
26729  *
26730  * If the function returns B_FALSE, the packet has been "consumed", most
26731  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26732  *
26733  * The SA references created by the protocol-specific "select"
26734  * function will be released when the ipsec_mp is freed, thanks to the
26735  * ipsec_out_free destructor -- see spd.c.
26736  */
26737 static boolean_t
26738 ipsec_out_select_sa(mblk_t *ipsec_mp)
26739 {
26740 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26741 	ipsec_out_t *io;
26742 	ipsec_policy_t *pp;
26743 	ipsec_action_t *ap;
26744 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26745 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26746 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26747 
26748 	if (!io->ipsec_out_secure) {
26749 		/*
26750 		 * We came here by mistake.
26751 		 * Don't bother with ipsec processing
26752 		 * We should "discourage" this path in the future.
26753 		 */
26754 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26755 		return (B_FALSE);
26756 	}
26757 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26758 	ASSERT((io->ipsec_out_policy != NULL) ||
26759 	    (io->ipsec_out_act != NULL));
26760 
26761 	ASSERT(io->ipsec_out_failed == B_FALSE);
26762 
26763 	/*
26764 	 * IPSEC processing has started.
26765 	 */
26766 	io->ipsec_out_proc_begin = B_TRUE;
26767 	ap = io->ipsec_out_act;
26768 	if (ap == NULL) {
26769 		pp = io->ipsec_out_policy;
26770 		ASSERT(pp != NULL);
26771 		ap = pp->ipsp_act;
26772 		ASSERT(ap != NULL);
26773 	}
26774 
26775 	/*
26776 	 * We have an action.  now, let's select SA's.
26777 	 * (In the future, we can cache this in the conn_t..)
26778 	 */
26779 	if (ap->ipa_want_esp) {
26780 		if (io->ipsec_out_esp_sa == NULL) {
26781 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26782 			    IPPROTO_ESP);
26783 		}
26784 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26785 	}
26786 
26787 	if (ap->ipa_want_ah) {
26788 		if (io->ipsec_out_ah_sa == NULL) {
26789 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26790 			    IPPROTO_AH);
26791 		}
26792 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26793 		/*
26794 		 * The ESP and AH processing order needs to be preserved
26795 		 * when both protocols are required (ESP should be applied
26796 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26797 		 * when both ESP and AH are required, and an AH ACQUIRE
26798 		 * is needed.
26799 		 */
26800 		if (ap->ipa_want_esp && need_ah_acquire)
26801 			need_esp_acquire = B_TRUE;
26802 	}
26803 
26804 	/*
26805 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26806 	 * Release SAs that got referenced, but will not be used until we
26807 	 * acquire _all_ of the SAs we need.
26808 	 */
26809 	if (need_ah_acquire || need_esp_acquire) {
26810 		if (io->ipsec_out_ah_sa != NULL) {
26811 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26812 			io->ipsec_out_ah_sa = NULL;
26813 		}
26814 		if (io->ipsec_out_esp_sa != NULL) {
26815 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26816 			io->ipsec_out_esp_sa = NULL;
26817 		}
26818 
26819 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26820 		return (B_FALSE);
26821 	}
26822 
26823 	return (B_TRUE);
26824 }
26825 
26826 /*
26827  * Process an IPSEC_OUT message and see what you can
26828  * do with it.
26829  * IPQoS Notes:
26830  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26831  * IPSec.
26832  * XXX would like to nuke ire_t.
26833  * XXX ill_index better be "real"
26834  */
26835 void
26836 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26837 {
26838 	ipsec_out_t *io;
26839 	ipsec_policy_t *pp;
26840 	ipsec_action_t *ap;
26841 	ipha_t *ipha;
26842 	ip6_t *ip6h;
26843 	mblk_t *mp;
26844 	ill_t *ill;
26845 	zoneid_t zoneid;
26846 	ipsec_status_t ipsec_rc;
26847 	boolean_t ill_need_rele = B_FALSE;
26848 	ip_stack_t	*ipst;
26849 	ipsec_stack_t	*ipss;
26850 
26851 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26852 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26853 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26854 	ipst = io->ipsec_out_ns->netstack_ip;
26855 	mp = ipsec_mp->b_cont;
26856 
26857 	/*
26858 	 * Initiate IPPF processing. We do it here to account for packets
26859 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26860 	 * We can check for ipsec_out_proc_begin even for such packets, as
26861 	 * they will always be false (asserted below).
26862 	 */
26863 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26864 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26865 		    io->ipsec_out_ill_index : ill_index);
26866 		if (mp == NULL) {
26867 			ip2dbg(("ipsec_out_process: packet dropped "\
26868 			    "during IPPF processing\n"));
26869 			freeb(ipsec_mp);
26870 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26871 			return;
26872 		}
26873 	}
26874 
26875 	if (!io->ipsec_out_secure) {
26876 		/*
26877 		 * We came here by mistake.
26878 		 * Don't bother with ipsec processing
26879 		 * Should "discourage" this path in the future.
26880 		 */
26881 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26882 		goto done;
26883 	}
26884 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26885 	ASSERT((io->ipsec_out_policy != NULL) ||
26886 	    (io->ipsec_out_act != NULL));
26887 	ASSERT(io->ipsec_out_failed == B_FALSE);
26888 
26889 	ipss = ipst->ips_netstack->netstack_ipsec;
26890 	if (!ipsec_loaded(ipss)) {
26891 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26892 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26893 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26894 		} else {
26895 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26896 		}
26897 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26898 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26899 		    &ipss->ipsec_dropper);
26900 		return;
26901 	}
26902 
26903 	/*
26904 	 * IPSEC processing has started.
26905 	 */
26906 	io->ipsec_out_proc_begin = B_TRUE;
26907 	ap = io->ipsec_out_act;
26908 	if (ap == NULL) {
26909 		pp = io->ipsec_out_policy;
26910 		ASSERT(pp != NULL);
26911 		ap = pp->ipsp_act;
26912 		ASSERT(ap != NULL);
26913 	}
26914 
26915 	/*
26916 	 * Save the outbound ill index. When the packet comes back
26917 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26918 	 * before sending it the accelerated packet.
26919 	 */
26920 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26921 		int ifindex;
26922 		ill = ire_to_ill(ire);
26923 		ifindex = ill->ill_phyint->phyint_ifindex;
26924 		io->ipsec_out_capab_ill_index = ifindex;
26925 	}
26926 
26927 	/*
26928 	 * The order of processing is first insert a IP header if needed.
26929 	 * Then insert the ESP header and then the AH header.
26930 	 */
26931 	if ((io->ipsec_out_se_done == B_FALSE) &&
26932 	    (ap->ipa_want_se)) {
26933 		/*
26934 		 * First get the outer IP header before sending
26935 		 * it to ESP.
26936 		 */
26937 		ipha_t *oipha, *iipha;
26938 		mblk_t *outer_mp, *inner_mp;
26939 
26940 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26941 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26942 			    "ipsec_out_process: "
26943 			    "Self-Encapsulation failed: Out of memory\n");
26944 			freemsg(ipsec_mp);
26945 			if (ill != NULL) {
26946 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26947 			} else {
26948 				BUMP_MIB(&ipst->ips_ip_mib,
26949 				    ipIfStatsOutDiscards);
26950 			}
26951 			return;
26952 		}
26953 		inner_mp = ipsec_mp->b_cont;
26954 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26955 		oipha = (ipha_t *)outer_mp->b_rptr;
26956 		iipha = (ipha_t *)inner_mp->b_rptr;
26957 		*oipha = *iipha;
26958 		outer_mp->b_wptr += sizeof (ipha_t);
26959 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26960 		    sizeof (ipha_t));
26961 		oipha->ipha_protocol = IPPROTO_ENCAP;
26962 		oipha->ipha_version_and_hdr_length =
26963 		    IP_SIMPLE_HDR_VERSION;
26964 		oipha->ipha_hdr_checksum = 0;
26965 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26966 		outer_mp->b_cont = inner_mp;
26967 		ipsec_mp->b_cont = outer_mp;
26968 
26969 		io->ipsec_out_se_done = B_TRUE;
26970 		io->ipsec_out_tunnel = B_TRUE;
26971 	}
26972 
26973 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26974 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26975 	    !ipsec_out_select_sa(ipsec_mp))
26976 		return;
26977 
26978 	/*
26979 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26980 	 * to do the heavy lifting.
26981 	 */
26982 	zoneid = io->ipsec_out_zoneid;
26983 	ASSERT(zoneid != ALL_ZONES);
26984 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26985 		ASSERT(io->ipsec_out_esp_sa != NULL);
26986 		io->ipsec_out_esp_done = B_TRUE;
26987 		/*
26988 		 * Note that since hw accel can only apply one transform,
26989 		 * not two, we skip hw accel for ESP if we also have AH
26990 		 * This is an design limitation of the interface
26991 		 * which should be revisited.
26992 		 */
26993 		ASSERT(ire != NULL);
26994 		if (io->ipsec_out_ah_sa == NULL) {
26995 			ill = (ill_t *)ire->ire_stq->q_ptr;
26996 			ipsec_out_is_accelerated(ipsec_mp,
26997 			    io->ipsec_out_esp_sa, ill, ire);
26998 		}
26999 
27000 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
27001 		switch (ipsec_rc) {
27002 		case IPSEC_STATUS_SUCCESS:
27003 			break;
27004 		case IPSEC_STATUS_FAILED:
27005 			if (ill != NULL) {
27006 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27007 			} else {
27008 				BUMP_MIB(&ipst->ips_ip_mib,
27009 				    ipIfStatsOutDiscards);
27010 			}
27011 			/* FALLTHRU */
27012 		case IPSEC_STATUS_PENDING:
27013 			return;
27014 		}
27015 	}
27016 
27017 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27018 		ASSERT(io->ipsec_out_ah_sa != NULL);
27019 		io->ipsec_out_ah_done = B_TRUE;
27020 		if (ire == NULL) {
27021 			int idx = io->ipsec_out_capab_ill_index;
27022 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27023 			    NULL, NULL, NULL, NULL, ipst);
27024 			ill_need_rele = B_TRUE;
27025 		} else {
27026 			ill = (ill_t *)ire->ire_stq->q_ptr;
27027 		}
27028 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27029 		    ire);
27030 
27031 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27032 		switch (ipsec_rc) {
27033 		case IPSEC_STATUS_SUCCESS:
27034 			break;
27035 		case IPSEC_STATUS_FAILED:
27036 			if (ill != NULL) {
27037 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27038 			} else {
27039 				BUMP_MIB(&ipst->ips_ip_mib,
27040 				    ipIfStatsOutDiscards);
27041 			}
27042 			/* FALLTHRU */
27043 		case IPSEC_STATUS_PENDING:
27044 			if (ill != NULL && ill_need_rele)
27045 				ill_refrele(ill);
27046 			return;
27047 		}
27048 	}
27049 	/*
27050 	 * We are done with IPSEC processing. Send it over
27051 	 * the wire.
27052 	 */
27053 done:
27054 	mp = ipsec_mp->b_cont;
27055 	ipha = (ipha_t *)mp->b_rptr;
27056 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27057 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27058 	} else {
27059 		ip6h = (ip6_t *)ipha;
27060 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27061 	}
27062 	if (ill != NULL && ill_need_rele)
27063 		ill_refrele(ill);
27064 }
27065 
27066 /* ARGSUSED */
27067 void
27068 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27069 {
27070 	opt_restart_t	*or;
27071 	int	err;
27072 	conn_t	*connp;
27073 
27074 	ASSERT(CONN_Q(q));
27075 	connp = Q_TO_CONN(q);
27076 
27077 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27078 	or = (opt_restart_t *)first_mp->b_rptr;
27079 	/*
27080 	 * We don't need to pass any credentials here since this is just
27081 	 * a restart. The credentials are passed in when svr4_optcom_req
27082 	 * is called the first time (from ip_wput_nondata).
27083 	 */
27084 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27085 		err = svr4_optcom_req(q, first_mp, NULL,
27086 		    &ip_opt_obj);
27087 	} else {
27088 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27089 		err = tpi_optcom_req(q, first_mp, NULL,
27090 		    &ip_opt_obj);
27091 	}
27092 	if (err != EINPROGRESS) {
27093 		/* operation is done */
27094 		CONN_OPER_PENDING_DONE(connp);
27095 	}
27096 }
27097 
27098 /*
27099  * ioctls that go through a down/up sequence may need to wait for the down
27100  * to complete. This involves waiting for the ire and ipif refcnts to go down
27101  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27102  */
27103 /* ARGSUSED */
27104 void
27105 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27106 {
27107 	struct iocblk *iocp;
27108 	mblk_t *mp1;
27109 	ip_ioctl_cmd_t *ipip;
27110 	int err;
27111 	sin_t	*sin;
27112 	struct lifreq *lifr;
27113 	struct ifreq *ifr;
27114 
27115 	iocp = (struct iocblk *)mp->b_rptr;
27116 	ASSERT(ipsq != NULL);
27117 	/* Existence of mp1 verified in ip_wput_nondata */
27118 	mp1 = mp->b_cont->b_cont;
27119 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27120 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27121 		/*
27122 		 * Special case where ipsq_current_ipif is not set:
27123 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27124 		 * ill could also have become part of a ipmp group in the
27125 		 * process, we are here as were not able to complete the
27126 		 * operation in ipif_set_values because we could not become
27127 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27128 		 * will not be set so we need to set it.
27129 		 */
27130 		ill_t *ill = q->q_ptr;
27131 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27132 	}
27133 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27134 
27135 	if (ipip->ipi_cmd_type == IF_CMD) {
27136 		/* This a old style SIOC[GS]IF* command */
27137 		ifr = (struct ifreq *)mp1->b_rptr;
27138 		sin = (sin_t *)&ifr->ifr_addr;
27139 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27140 		/* This a new style SIOC[GS]LIF* command */
27141 		lifr = (struct lifreq *)mp1->b_rptr;
27142 		sin = (sin_t *)&lifr->lifr_addr;
27143 	} else {
27144 		sin = NULL;
27145 	}
27146 
27147 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27148 	    ipip, mp1->b_rptr);
27149 
27150 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27151 }
27152 
27153 /*
27154  * ioctl processing
27155  *
27156  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27157  * the ioctl command in the ioctl tables and determines the copyin data size
27158  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27159  * size.
27160  *
27161  * ioctl processing then continues when the M_IOCDATA makes its way down.
27162  * Now the ioctl is looked up again in the ioctl table, and its properties are
27163  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27164  * and the general ioctl processing function ip_process_ioctl is called.
27165  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27166  * so goes thru the serialization primitive ipsq_try_enter. Then the
27167  * appropriate function to handle the ioctl is called based on the entry in
27168  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27169  * which also refreleases the 'conn' that was refheld at the start of the
27170  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27171  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27172  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27173  *
27174  * Many exclusive ioctls go thru an internal down up sequence as part of
27175  * the operation. For example an attempt to change the IP address of an
27176  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27177  * does all the cleanup such as deleting all ires that use this address.
27178  * Then we need to wait till all references to the interface go away.
27179  */
27180 void
27181 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27182 {
27183 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27184 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27185 	cmd_info_t ci;
27186 	int err;
27187 	boolean_t entered_ipsq = B_FALSE;
27188 
27189 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27190 
27191 	if (ipip == NULL)
27192 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27193 
27194 	/*
27195 	 * SIOCLIFADDIF needs to go thru a special path since the
27196 	 * ill may not exist yet. This happens in the case of lo0
27197 	 * which is created using this ioctl.
27198 	 */
27199 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27200 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27201 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27202 		return;
27203 	}
27204 
27205 	ci.ci_ipif = NULL;
27206 	switch (ipip->ipi_cmd_type) {
27207 	case IF_CMD:
27208 	case LIF_CMD:
27209 		/*
27210 		 * ioctls that pass in a [l]ifreq appear here.
27211 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27212 		 * ci.ci_ipif
27213 		 */
27214 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27215 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27216 		if (err != 0) {
27217 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27218 			return;
27219 		}
27220 		ASSERT(ci.ci_ipif != NULL);
27221 		break;
27222 
27223 	case TUN_CMD:
27224 		/*
27225 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27226 		 * a refheld ipif in ci.ci_ipif
27227 		 */
27228 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27229 		if (err != 0) {
27230 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27231 			return;
27232 		}
27233 		ASSERT(ci.ci_ipif != NULL);
27234 		break;
27235 
27236 	case MISC_CMD:
27237 		/*
27238 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27239 		 * For eg. SIOCGLIFCONF will appear here.
27240 		 */
27241 		switch (ipip->ipi_cmd) {
27242 		case IF_UNITSEL:
27243 			/* ioctl comes down the ill */
27244 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27245 			ipif_refhold(ci.ci_ipif);
27246 			break;
27247 		case SIOCGMSFILTER:
27248 		case SIOCSMSFILTER:
27249 		case SIOCGIPMSFILTER:
27250 		case SIOCSIPMSFILTER:
27251 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27252 			    ip_process_ioctl);
27253 			if (err != 0) {
27254 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27255 				    NULL);
27256 			}
27257 			break;
27258 		}
27259 		err = 0;
27260 		ci.ci_sin = NULL;
27261 		ci.ci_sin6 = NULL;
27262 		ci.ci_lifr = NULL;
27263 		break;
27264 	}
27265 
27266 	/*
27267 	 * If ipsq is non-null, we are already being called exclusively
27268 	 */
27269 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27270 	if (!(ipip->ipi_flags & IPI_WR)) {
27271 		/*
27272 		 * A return value of EINPROGRESS means the ioctl is
27273 		 * either queued and waiting for some reason or has
27274 		 * already completed.
27275 		 */
27276 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27277 		    ci.ci_lifr);
27278 		if (ci.ci_ipif != NULL)
27279 			ipif_refrele(ci.ci_ipif);
27280 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27281 		return;
27282 	}
27283 
27284 	ASSERT(ci.ci_ipif != NULL);
27285 
27286 	if (ipsq == NULL) {
27287 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27288 		    ip_process_ioctl, NEW_OP, B_TRUE);
27289 		entered_ipsq = B_TRUE;
27290 	}
27291 	/*
27292 	 * Release the ipif so that ipif_down and friends that wait for
27293 	 * references to go away are not misled about the current ipif_refcnt
27294 	 * values. We are writer so we can access the ipif even after releasing
27295 	 * the ipif.
27296 	 */
27297 	ipif_refrele(ci.ci_ipif);
27298 	if (ipsq == NULL)
27299 		return;
27300 
27301 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27302 
27303 	/*
27304 	 * For most set ioctls that come here, this serves as a single point
27305 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27306 	 * be any new references to the ipif. This helps functions that go
27307 	 * through this path and end up trying to wait for the refcnts
27308 	 * associated with the ipif to go down to zero. Some exceptions are
27309 	 * Failover, Failback, and Groupname commands that operate on more than
27310 	 * just the ci.ci_ipif. These commands internally determine the
27311 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27312 	 * flags on that set. Another exception is the Removeif command that
27313 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27314 	 * ipif to operate on.
27315 	 */
27316 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27317 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27318 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27319 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27320 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27321 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27322 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27323 
27324 	/*
27325 	 * A return value of EINPROGRESS means the ioctl is
27326 	 * either queued and waiting for some reason or has
27327 	 * already completed.
27328 	 */
27329 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27330 
27331 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27332 
27333 	if (entered_ipsq)
27334 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27335 }
27336 
27337 /*
27338  * Complete the ioctl. Typically ioctls use the mi package and need to
27339  * do mi_copyout/mi_copy_done.
27340  */
27341 void
27342 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27343 {
27344 	conn_t	*connp = NULL;
27345 
27346 	if (err == EINPROGRESS)
27347 		return;
27348 
27349 	if (CONN_Q(q)) {
27350 		connp = Q_TO_CONN(q);
27351 		ASSERT(connp->conn_ref >= 2);
27352 	}
27353 
27354 	switch (mode) {
27355 	case COPYOUT:
27356 		if (err == 0)
27357 			mi_copyout(q, mp);
27358 		else
27359 			mi_copy_done(q, mp, err);
27360 		break;
27361 
27362 	case NO_COPYOUT:
27363 		mi_copy_done(q, mp, err);
27364 		break;
27365 
27366 	default:
27367 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27368 		break;
27369 	}
27370 
27371 	/*
27372 	 * The refhold placed at the start of the ioctl is released here.
27373 	 */
27374 	if (connp != NULL)
27375 		CONN_OPER_PENDING_DONE(connp);
27376 
27377 	if (ipsq != NULL)
27378 		ipsq_current_finish(ipsq);
27379 }
27380 
27381 /*
27382  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27383  */
27384 /* ARGSUSED */
27385 void
27386 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27387 {
27388 	conn_t *connp = arg;
27389 	tcp_t	*tcp;
27390 
27391 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27392 	tcp = connp->conn_tcp;
27393 
27394 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27395 		freemsg(mp);
27396 	else
27397 		tcp_rput_other(tcp, mp);
27398 	CONN_OPER_PENDING_DONE(connp);
27399 }
27400 
27401 /* Called from ip_wput for all non data messages */
27402 /* ARGSUSED */
27403 void
27404 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27405 {
27406 	mblk_t		*mp1;
27407 	ire_t		*ire, *fake_ire;
27408 	ill_t		*ill;
27409 	struct iocblk	*iocp;
27410 	ip_ioctl_cmd_t	*ipip;
27411 	cred_t		*cr;
27412 	conn_t		*connp;
27413 	int		cmd, err;
27414 	nce_t		*nce;
27415 	ipif_t		*ipif;
27416 	ip_stack_t	*ipst;
27417 	char		*proto_str;
27418 
27419 	if (CONN_Q(q)) {
27420 		connp = Q_TO_CONN(q);
27421 		ipst = connp->conn_netstack->netstack_ip;
27422 	} else {
27423 		connp = NULL;
27424 		ipst = ILLQ_TO_IPST(q);
27425 	}
27426 
27427 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27428 
27429 	/* Check if it is a queue to /dev/sctp. */
27430 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27431 	    connp->conn_rq == NULL) {
27432 		sctp_wput(q, mp);
27433 		return;
27434 	}
27435 
27436 	switch (DB_TYPE(mp)) {
27437 	case M_IOCTL:
27438 		/*
27439 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27440 		 * will arrange to copy in associated control structures.
27441 		 */
27442 		ip_sioctl_copyin_setup(q, mp);
27443 		return;
27444 	case M_IOCDATA:
27445 		/*
27446 		 * Ensure that this is associated with one of our trans-
27447 		 * parent ioctls.  If it's not ours, discard it if we're
27448 		 * running as a driver, or pass it on if we're a module.
27449 		 */
27450 		iocp = (struct iocblk *)mp->b_rptr;
27451 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27452 		if (ipip == NULL) {
27453 			if (q->q_next == NULL) {
27454 				goto nak;
27455 			} else {
27456 				putnext(q, mp);
27457 			}
27458 			return;
27459 		} else if ((q->q_next != NULL) &&
27460 		    !(ipip->ipi_flags & IPI_MODOK)) {
27461 			/*
27462 			 * the ioctl is one we recognise, but is not
27463 			 * consumed by IP as a module, pass M_IOCDATA
27464 			 * for processing downstream, but only for
27465 			 * common Streams ioctls.
27466 			 */
27467 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27468 				putnext(q, mp);
27469 				return;
27470 			} else {
27471 				goto nak;
27472 			}
27473 		}
27474 
27475 		/* IOCTL continuation following copyin or copyout. */
27476 		if (mi_copy_state(q, mp, NULL) == -1) {
27477 			/*
27478 			 * The copy operation failed.  mi_copy_state already
27479 			 * cleaned up, so we're out of here.
27480 			 */
27481 			return;
27482 		}
27483 		/*
27484 		 * If we just completed a copy in, we become writer and
27485 		 * continue processing in ip_sioctl_copyin_done.  If it
27486 		 * was a copy out, we call mi_copyout again.  If there is
27487 		 * nothing more to copy out, it will complete the IOCTL.
27488 		 */
27489 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27490 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27491 				mi_copy_done(q, mp, EPROTO);
27492 				return;
27493 			}
27494 			/*
27495 			 * Check for cases that need more copying.  A return
27496 			 * value of 0 means a second copyin has been started,
27497 			 * so we return; a return value of 1 means no more
27498 			 * copying is needed, so we continue.
27499 			 */
27500 			cmd = iocp->ioc_cmd;
27501 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27502 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27503 			    MI_COPY_COUNT(mp) == 1) {
27504 				if (ip_copyin_msfilter(q, mp) == 0)
27505 					return;
27506 			}
27507 			/*
27508 			 * Refhold the conn, till the ioctl completes. This is
27509 			 * needed in case the ioctl ends up in the pending mp
27510 			 * list. Every mp in the ill_pending_mp list and
27511 			 * the ipsq_pending_mp must have a refhold on the conn
27512 			 * to resume processing. The refhold is released when
27513 			 * the ioctl completes. (normally or abnormally)
27514 			 * In all cases ip_ioctl_finish is called to finish
27515 			 * the ioctl.
27516 			 */
27517 			if (connp != NULL) {
27518 				/* This is not a reentry */
27519 				ASSERT(ipsq == NULL);
27520 				CONN_INC_REF(connp);
27521 			} else {
27522 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27523 					mi_copy_done(q, mp, EINVAL);
27524 					return;
27525 				}
27526 			}
27527 
27528 			ip_process_ioctl(ipsq, q, mp, ipip);
27529 
27530 		} else {
27531 			mi_copyout(q, mp);
27532 		}
27533 		return;
27534 nak:
27535 		iocp->ioc_error = EINVAL;
27536 		mp->b_datap->db_type = M_IOCNAK;
27537 		iocp->ioc_count = 0;
27538 		qreply(q, mp);
27539 		return;
27540 
27541 	case M_IOCNAK:
27542 		/*
27543 		 * The only way we could get here is if a resolver didn't like
27544 		 * an IOCTL we sent it.	 This shouldn't happen.
27545 		 */
27546 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27547 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27548 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27549 		freemsg(mp);
27550 		return;
27551 	case M_IOCACK:
27552 		/* /dev/ip shouldn't see this */
27553 		if (CONN_Q(q))
27554 			goto nak;
27555 
27556 		/* Finish socket ioctls passed through to ARP. */
27557 		ip_sioctl_iocack(q, mp);
27558 		return;
27559 	case M_FLUSH:
27560 		if (*mp->b_rptr & FLUSHW)
27561 			flushq(q, FLUSHALL);
27562 		if (q->q_next) {
27563 			putnext(q, mp);
27564 			return;
27565 		}
27566 		if (*mp->b_rptr & FLUSHR) {
27567 			*mp->b_rptr &= ~FLUSHW;
27568 			qreply(q, mp);
27569 			return;
27570 		}
27571 		freemsg(mp);
27572 		return;
27573 	case IRE_DB_REQ_TYPE:
27574 		if (connp == NULL) {
27575 			proto_str = "IRE_DB_REQ_TYPE";
27576 			goto protonak;
27577 		}
27578 		/* An Upper Level Protocol wants a copy of an IRE. */
27579 		ip_ire_req(q, mp);
27580 		return;
27581 	case M_CTL:
27582 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27583 			break;
27584 
27585 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27586 		    TUN_HELLO) {
27587 			ASSERT(connp != NULL);
27588 			connp->conn_flags |= IPCL_IPTUN;
27589 			freeb(mp);
27590 			return;
27591 		}
27592 
27593 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27594 		    IP_ULP_OUT_LABELED) {
27595 			out_labeled_t *olp;
27596 
27597 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27598 				break;
27599 			olp = (out_labeled_t *)mp->b_rptr;
27600 			connp->conn_ulp_labeled = olp->out_qnext == q;
27601 			freemsg(mp);
27602 			return;
27603 		}
27604 
27605 		/* M_CTL messages are used by ARP to tell us things. */
27606 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27607 			break;
27608 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27609 		case AR_ENTRY_SQUERY:
27610 			ip_wput_ctl(q, mp);
27611 			return;
27612 		case AR_CLIENT_NOTIFY:
27613 			ip_arp_news(q, mp);
27614 			return;
27615 		case AR_DLPIOP_DONE:
27616 			ASSERT(q->q_next != NULL);
27617 			ill = (ill_t *)q->q_ptr;
27618 			/* qwriter_ip releases the refhold */
27619 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27620 			ill_refhold(ill);
27621 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27622 			return;
27623 		case AR_ARP_CLOSING:
27624 			/*
27625 			 * ARP (above us) is closing. If no ARP bringup is
27626 			 * currently pending, ack the message so that ARP
27627 			 * can complete its close. Also mark ill_arp_closing
27628 			 * so that new ARP bringups will fail. If any
27629 			 * ARP bringup is currently in progress, we will
27630 			 * ack this when the current ARP bringup completes.
27631 			 */
27632 			ASSERT(q->q_next != NULL);
27633 			ill = (ill_t *)q->q_ptr;
27634 			mutex_enter(&ill->ill_lock);
27635 			ill->ill_arp_closing = 1;
27636 			if (!ill->ill_arp_bringup_pending) {
27637 				mutex_exit(&ill->ill_lock);
27638 				qreply(q, mp);
27639 			} else {
27640 				mutex_exit(&ill->ill_lock);
27641 				freemsg(mp);
27642 			}
27643 			return;
27644 		case AR_ARP_EXTEND:
27645 			/*
27646 			 * The ARP module above us is capable of duplicate
27647 			 * address detection.  Old ATM drivers will not send
27648 			 * this message.
27649 			 */
27650 			ASSERT(q->q_next != NULL);
27651 			ill = (ill_t *)q->q_ptr;
27652 			ill->ill_arp_extend = B_TRUE;
27653 			freemsg(mp);
27654 			return;
27655 		default:
27656 			break;
27657 		}
27658 		break;
27659 	case M_PROTO:
27660 	case M_PCPROTO:
27661 		/*
27662 		 * The only PROTO messages we expect are ULP binds and
27663 		 * copies of option negotiation acknowledgements.
27664 		 */
27665 		switch (((union T_primitives *)mp->b_rptr)->type) {
27666 		case O_T_BIND_REQ:
27667 		case T_BIND_REQ: {
27668 			/* Request can get queued in bind */
27669 			if (connp == NULL) {
27670 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27671 				goto protonak;
27672 			}
27673 			/*
27674 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27675 			 * instead of going through this path.  We only get
27676 			 * here in the following cases:
27677 			 *
27678 			 * a. Bind retries, where ipsq is non-NULL.
27679 			 * b. T_BIND_REQ is issued from non TCP/UDP
27680 			 *    transport, e.g. icmp for raw socket,
27681 			 *    in which case ipsq will be NULL.
27682 			 */
27683 			ASSERT(ipsq != NULL ||
27684 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27685 
27686 			/* Don't increment refcnt if this is a re-entry */
27687 			if (ipsq == NULL)
27688 				CONN_INC_REF(connp);
27689 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27690 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27691 			if (mp == NULL)
27692 				return;
27693 			if (IPCL_IS_TCP(connp)) {
27694 				/*
27695 				 * In the case of TCP endpoint we
27696 				 * come here only for bind retries
27697 				 */
27698 				ASSERT(ipsq != NULL);
27699 				CONN_INC_REF(connp);
27700 				squeue_fill(connp->conn_sqp, mp,
27701 				    ip_resume_tcp_bind, connp,
27702 				    SQTAG_BIND_RETRY);
27703 				return;
27704 			} else if (IPCL_IS_UDP(connp)) {
27705 				/*
27706 				 * In the case of UDP endpoint we
27707 				 * come here only for bind retries
27708 				 */
27709 				ASSERT(ipsq != NULL);
27710 				udp_resume_bind(connp, mp);
27711 				return;
27712 			}
27713 			qreply(q, mp);
27714 			CONN_OPER_PENDING_DONE(connp);
27715 			return;
27716 		}
27717 		case T_SVR4_OPTMGMT_REQ:
27718 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27719 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27720 
27721 			if (connp == NULL) {
27722 				proto_str = "T_SVR4_OPTMGMT_REQ";
27723 				goto protonak;
27724 			}
27725 
27726 			if (!snmpcom_req(q, mp, ip_snmp_set,
27727 			    ip_snmp_get, cr)) {
27728 				/*
27729 				 * Call svr4_optcom_req so that it can
27730 				 * generate the ack. We don't come here
27731 				 * if this operation is being restarted.
27732 				 * ip_restart_optmgmt will drop the conn ref.
27733 				 * In the case of ipsec option after the ipsec
27734 				 * load is complete conn_restart_ipsec_waiter
27735 				 * drops the conn ref.
27736 				 */
27737 				ASSERT(ipsq == NULL);
27738 				CONN_INC_REF(connp);
27739 				if (ip_check_for_ipsec_opt(q, mp))
27740 					return;
27741 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27742 				if (err != EINPROGRESS) {
27743 					/* Operation is done */
27744 					CONN_OPER_PENDING_DONE(connp);
27745 				}
27746 			}
27747 			return;
27748 		case T_OPTMGMT_REQ:
27749 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27750 			/*
27751 			 * Note: No snmpcom_req support through new
27752 			 * T_OPTMGMT_REQ.
27753 			 * Call tpi_optcom_req so that it can
27754 			 * generate the ack.
27755 			 */
27756 			if (connp == NULL) {
27757 				proto_str = "T_OPTMGMT_REQ";
27758 				goto protonak;
27759 			}
27760 
27761 			ASSERT(ipsq == NULL);
27762 			/*
27763 			 * We don't come here for restart. ip_restart_optmgmt
27764 			 * will drop the conn ref. In the case of ipsec option
27765 			 * after the ipsec load is complete
27766 			 * conn_restart_ipsec_waiter drops the conn ref.
27767 			 */
27768 			CONN_INC_REF(connp);
27769 			if (ip_check_for_ipsec_opt(q, mp))
27770 				return;
27771 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27772 			if (err != EINPROGRESS) {
27773 				/* Operation is done */
27774 				CONN_OPER_PENDING_DONE(connp);
27775 			}
27776 			return;
27777 		case T_UNBIND_REQ:
27778 			if (connp == NULL) {
27779 				proto_str = "T_UNBIND_REQ";
27780 				goto protonak;
27781 			}
27782 			mp = ip_unbind(q, mp);
27783 			qreply(q, mp);
27784 			return;
27785 		default:
27786 			/*
27787 			 * Have to drop any DLPI messages coming down from
27788 			 * arp (such as an info_req which would cause ip
27789 			 * to receive an extra info_ack if it was passed
27790 			 * through.
27791 			 */
27792 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27793 			    (int)*(uint_t *)mp->b_rptr));
27794 			freemsg(mp);
27795 			return;
27796 		}
27797 		/* NOTREACHED */
27798 	case IRE_DB_TYPE: {
27799 		nce_t		*nce;
27800 		ill_t		*ill;
27801 		in6_addr_t	gw_addr_v6;
27802 
27803 
27804 		/*
27805 		 * This is a response back from a resolver.  It
27806 		 * consists of a message chain containing:
27807 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27808 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27809 		 * The LL_HDR_MBLK is the DLPI header to use to get
27810 		 * the attached packet, and subsequent ones for the
27811 		 * same destination, transmitted.
27812 		 */
27813 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27814 			break;
27815 		/*
27816 		 * First, check to make sure the resolution succeeded.
27817 		 * If it failed, the second mblk will be empty.
27818 		 * If it is, free the chain, dropping the packet.
27819 		 * (We must ire_delete the ire; that frees the ire mblk)
27820 		 * We're doing this now to support PVCs for ATM; it's
27821 		 * a partial xresolv implementation. When we fully implement
27822 		 * xresolv interfaces, instead of freeing everything here
27823 		 * we'll initiate neighbor discovery.
27824 		 *
27825 		 * For v4 (ARP and other external resolvers) the resolver
27826 		 * frees the message, so no check is needed. This check
27827 		 * is required, though, for a full xresolve implementation.
27828 		 * Including this code here now both shows how external
27829 		 * resolvers can NACK a resolution request using an
27830 		 * existing design that has no specific provisions for NACKs,
27831 		 * and also takes into account that the current non-ARP
27832 		 * external resolver has been coded to use this method of
27833 		 * NACKing for all IPv6 (xresolv) cases,
27834 		 * whether our xresolv implementation is complete or not.
27835 		 *
27836 		 */
27837 		ire = (ire_t *)mp->b_rptr;
27838 		ill = ire_to_ill(ire);
27839 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27840 		if (mp1->b_rptr == mp1->b_wptr) {
27841 			if (ire->ire_ipversion == IPV6_VERSION) {
27842 				/*
27843 				 * XRESOLV interface.
27844 				 */
27845 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27846 				mutex_enter(&ire->ire_lock);
27847 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27848 				mutex_exit(&ire->ire_lock);
27849 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27850 					nce = ndp_lookup_v6(ill,
27851 					    &ire->ire_addr_v6, B_FALSE);
27852 				} else {
27853 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27854 					    B_FALSE);
27855 				}
27856 				if (nce != NULL) {
27857 					nce_resolv_failed(nce);
27858 					ndp_delete(nce);
27859 					NCE_REFRELE(nce);
27860 				}
27861 			}
27862 			mp->b_cont = NULL;
27863 			freemsg(mp1);		/* frees the pkt as well */
27864 			ASSERT(ire->ire_nce == NULL);
27865 			ire_delete((ire_t *)mp->b_rptr);
27866 			return;
27867 		}
27868 
27869 		/*
27870 		 * Split them into IRE_MBLK and pkt and feed it into
27871 		 * ire_add_then_send. Then in ire_add_then_send
27872 		 * the IRE will be added, and then the packet will be
27873 		 * run back through ip_wput. This time it will make
27874 		 * it to the wire.
27875 		 */
27876 		mp->b_cont = NULL;
27877 		mp = mp1->b_cont;		/* now, mp points to pkt */
27878 		mp1->b_cont = NULL;
27879 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27880 		if (ire->ire_ipversion == IPV6_VERSION) {
27881 			/*
27882 			 * XRESOLV interface. Find the nce and put a copy
27883 			 * of the dl_unitdata_req in nce_res_mp
27884 			 */
27885 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27886 			mutex_enter(&ire->ire_lock);
27887 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27888 			mutex_exit(&ire->ire_lock);
27889 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27890 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27891 				    B_FALSE);
27892 			} else {
27893 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27894 			}
27895 			if (nce != NULL) {
27896 				/*
27897 				 * We have to protect nce_res_mp here
27898 				 * from being accessed by other threads
27899 				 * while we change the mblk pointer.
27900 				 * Other functions will also lock the nce when
27901 				 * accessing nce_res_mp.
27902 				 *
27903 				 * The reason we change the mblk pointer
27904 				 * here rather than copying the resolved address
27905 				 * into the template is that, unlike with
27906 				 * ethernet, we have no guarantee that the
27907 				 * resolved address length will be
27908 				 * smaller than or equal to the lla length
27909 				 * with which the template was allocated,
27910 				 * (for ethernet, they're equal)
27911 				 * so we have to use the actual resolved
27912 				 * address mblk - which holds the real
27913 				 * dl_unitdata_req with the resolved address.
27914 				 *
27915 				 * Doing this is the same behavior as was
27916 				 * previously used in the v4 ARP case.
27917 				 */
27918 				mutex_enter(&nce->nce_lock);
27919 				if (nce->nce_res_mp != NULL)
27920 					freemsg(nce->nce_res_mp);
27921 				nce->nce_res_mp = mp1;
27922 				mutex_exit(&nce->nce_lock);
27923 				/*
27924 				 * We do a fastpath probe here because
27925 				 * we have resolved the address without
27926 				 * using Neighbor Discovery.
27927 				 * In the non-XRESOLV v6 case, the fastpath
27928 				 * probe is done right after neighbor
27929 				 * discovery completes.
27930 				 */
27931 				if (nce->nce_res_mp != NULL) {
27932 					int res;
27933 					nce_fastpath_list_add(nce);
27934 					res = ill_fastpath_probe(ill,
27935 					    nce->nce_res_mp);
27936 					if (res != 0 && res != EAGAIN)
27937 						nce_fastpath_list_delete(nce);
27938 				}
27939 
27940 				ire_add_then_send(q, ire, mp);
27941 				/*
27942 				 * Now we have to clean out any packets
27943 				 * that may have been queued on the nce
27944 				 * while it was waiting for address resolution
27945 				 * to complete.
27946 				 */
27947 				mutex_enter(&nce->nce_lock);
27948 				mp1 = nce->nce_qd_mp;
27949 				nce->nce_qd_mp = NULL;
27950 				mutex_exit(&nce->nce_lock);
27951 				while (mp1 != NULL) {
27952 					mblk_t *nxt_mp;
27953 					queue_t *fwdq = NULL;
27954 					ill_t   *inbound_ill;
27955 					uint_t ifindex;
27956 
27957 					nxt_mp = mp1->b_next;
27958 					mp1->b_next = NULL;
27959 					/*
27960 					 * Retrieve ifindex stored in
27961 					 * ip_rput_data_v6()
27962 					 */
27963 					ifindex =
27964 					    (uint_t)(uintptr_t)mp1->b_prev;
27965 					inbound_ill =
27966 					    ill_lookup_on_ifindex(ifindex,
27967 					    B_TRUE, NULL, NULL, NULL,
27968 					    NULL, ipst);
27969 					mp1->b_prev = NULL;
27970 					if (inbound_ill != NULL)
27971 						fwdq = inbound_ill->ill_rq;
27972 
27973 					if (fwdq != NULL) {
27974 						put(fwdq, mp1);
27975 						ill_refrele(inbound_ill);
27976 					} else
27977 						put(WR(ill->ill_rq), mp1);
27978 					mp1 = nxt_mp;
27979 				}
27980 				NCE_REFRELE(nce);
27981 			} else {	/* nce is NULL; clean up */
27982 				ire_delete(ire);
27983 				freemsg(mp);
27984 				freemsg(mp1);
27985 				return;
27986 			}
27987 		} else {
27988 			nce_t *arpce;
27989 			/*
27990 			 * Link layer resolution succeeded. Recompute the
27991 			 * ire_nce.
27992 			 */
27993 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27994 			if ((arpce = ndp_lookup_v4(ill,
27995 			    (ire->ire_gateway_addr != INADDR_ANY ?
27996 			    &ire->ire_gateway_addr : &ire->ire_addr),
27997 			    B_FALSE)) == NULL) {
27998 				freeb(ire->ire_mp);
27999 				freeb(mp1);
28000 				freemsg(mp);
28001 				return;
28002 			}
28003 			mutex_enter(&arpce->nce_lock);
28004 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
28005 			if (arpce->nce_state == ND_REACHABLE) {
28006 				/*
28007 				 * Someone resolved this before us;
28008 				 * cleanup the res_mp. Since ire has
28009 				 * not been added yet, the call to ire_add_v4
28010 				 * from ire_add_then_send (when a dup is
28011 				 * detected) will clean up the ire.
28012 				 */
28013 				freeb(mp1);
28014 			} else {
28015 				if (arpce->nce_res_mp != NULL)
28016 					freemsg(arpce->nce_res_mp);
28017 				arpce->nce_res_mp = mp1;
28018 				arpce->nce_state = ND_REACHABLE;
28019 			}
28020 			mutex_exit(&arpce->nce_lock);
28021 			if (ire->ire_marks & IRE_MARK_NOADD) {
28022 				/*
28023 				 * this ire will not be added to the ire
28024 				 * cache table, so we can set the ire_nce
28025 				 * here, as there are no atomicity constraints.
28026 				 */
28027 				ire->ire_nce = arpce;
28028 				/*
28029 				 * We are associating this nce with the ire
28030 				 * so change the nce ref taken in
28031 				 * ndp_lookup_v4() from
28032 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28033 				 */
28034 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28035 			} else {
28036 				NCE_REFRELE(arpce);
28037 			}
28038 			ire_add_then_send(q, ire, mp);
28039 		}
28040 		return;	/* All is well, the packet has been sent. */
28041 	}
28042 	case IRE_ARPRESOLVE_TYPE: {
28043 
28044 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28045 			break;
28046 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28047 		mp->b_cont = NULL;
28048 		/*
28049 		 * First, check to make sure the resolution succeeded.
28050 		 * If it failed, the second mblk will be empty.
28051 		 */
28052 		if (mp1->b_rptr == mp1->b_wptr) {
28053 			/* cleanup  the incomplete ire, free queued packets */
28054 			freemsg(mp); /* fake ire */
28055 			freeb(mp1);  /* dl_unitdata response */
28056 			return;
28057 		}
28058 
28059 		/*
28060 		 * update any incomplete nce_t found. we lookup the ctable
28061 		 * and find the nce from the ire->ire_nce because we need
28062 		 * to pass the ire to ip_xmit_v4 later, and can find both
28063 		 * ire and nce in one lookup from the ctable.
28064 		 */
28065 		fake_ire = (ire_t *)mp->b_rptr;
28066 		/*
28067 		 * By the time we come back here from ARP
28068 		 * the logical outgoing interface  of the incomplete ire
28069 		 * we added in ire_forward could have disappeared,
28070 		 * causing the incomplete ire to also have
28071 		 * dissapeared. So we need to retreive the
28072 		 * proper ipif for the ire  before looking
28073 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28074 		 */
28075 		ill = q->q_ptr;
28076 
28077 		/* Get the outgoing ipif */
28078 		mutex_enter(&ill->ill_lock);
28079 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28080 			mutex_exit(&ill->ill_lock);
28081 			freemsg(mp); /* fake ire */
28082 			freeb(mp1);  /* dl_unitdata response */
28083 			return;
28084 		}
28085 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28086 
28087 		if (ipif == NULL) {
28088 			mutex_exit(&ill->ill_lock);
28089 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28090 			freemsg(mp);
28091 			freeb(mp1);
28092 			return;
28093 		}
28094 		ipif_refhold_locked(ipif);
28095 		mutex_exit(&ill->ill_lock);
28096 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28097 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28098 		    ipif, fake_ire->ire_zoneid, NULL,
28099 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28100 		ipif_refrele(ipif);
28101 		if (ire == NULL) {
28102 			/*
28103 			 * no ire was found; check if there is an nce
28104 			 * for this lookup; if it has no ire's pointing at it
28105 			 * cleanup.
28106 			 */
28107 			if ((nce = ndp_lookup_v4(ill,
28108 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28109 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28110 			    B_FALSE)) != NULL) {
28111 				/*
28112 				 * cleanup:
28113 				 * We check for refcnt 2 (one for the nce
28114 				 * hash list + 1 for the ref taken by
28115 				 * ndp_lookup_v4) to check that there are
28116 				 * no ire's pointing at the nce.
28117 				 */
28118 				if (nce->nce_refcnt == 2)
28119 					ndp_delete(nce);
28120 				NCE_REFRELE(nce);
28121 			}
28122 			freeb(mp1);  /* dl_unitdata response */
28123 			freemsg(mp); /* fake ire */
28124 			return;
28125 		}
28126 		nce = ire->ire_nce;
28127 		DTRACE_PROBE2(ire__arpresolve__type,
28128 		    ire_t *, ire, nce_t *, nce);
28129 		ASSERT(nce->nce_state != ND_INITIAL);
28130 		mutex_enter(&nce->nce_lock);
28131 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28132 		if (nce->nce_state == ND_REACHABLE) {
28133 			/*
28134 			 * Someone resolved this before us;
28135 			 * our response is not needed any more.
28136 			 */
28137 			mutex_exit(&nce->nce_lock);
28138 			freeb(mp1);  /* dl_unitdata response */
28139 		} else {
28140 			if (nce->nce_res_mp != NULL) {
28141 				freemsg(nce->nce_res_mp);
28142 				/* existing dl_unitdata template */
28143 			}
28144 			nce->nce_res_mp = mp1;
28145 			nce->nce_state = ND_REACHABLE;
28146 			mutex_exit(&nce->nce_lock);
28147 			nce_fastpath(nce);
28148 		}
28149 		/*
28150 		 * The cached nce_t has been updated to be reachable;
28151 		 * Set the IRE_MARK_UNCACHED flag and free the fake_ire.
28152 		 */
28153 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28154 		freemsg(mp);
28155 		/*
28156 		 * send out queued packets.
28157 		 */
28158 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28159 
28160 		IRE_REFRELE(ire);
28161 		return;
28162 	}
28163 	default:
28164 		break;
28165 	}
28166 	if (q->q_next) {
28167 		putnext(q, mp);
28168 	} else
28169 		freemsg(mp);
28170 	return;
28171 
28172 protonak:
28173 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28174 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28175 		qreply(q, mp);
28176 }
28177 
28178 /*
28179  * Process IP options in an outbound packet.  Modify the destination if there
28180  * is a source route option.
28181  * Returns non-zero if something fails in which case an ICMP error has been
28182  * sent and mp freed.
28183  */
28184 static int
28185 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28186     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28187 {
28188 	ipoptp_t	opts;
28189 	uchar_t		*opt;
28190 	uint8_t		optval;
28191 	uint8_t		optlen;
28192 	ipaddr_t	dst;
28193 	intptr_t	code = 0;
28194 	mblk_t		*mp;
28195 	ire_t		*ire = NULL;
28196 
28197 	ip2dbg(("ip_wput_options\n"));
28198 	mp = ipsec_mp;
28199 	if (mctl_present) {
28200 		mp = ipsec_mp->b_cont;
28201 	}
28202 
28203 	dst = ipha->ipha_dst;
28204 	for (optval = ipoptp_first(&opts, ipha);
28205 	    optval != IPOPT_EOL;
28206 	    optval = ipoptp_next(&opts)) {
28207 		opt = opts.ipoptp_cur;
28208 		optlen = opts.ipoptp_len;
28209 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28210 		    optval, optlen));
28211 		switch (optval) {
28212 			uint32_t off;
28213 		case IPOPT_SSRR:
28214 		case IPOPT_LSRR:
28215 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28216 				ip1dbg((
28217 				    "ip_wput_options: bad option offset\n"));
28218 				code = (char *)&opt[IPOPT_OLEN] -
28219 				    (char *)ipha;
28220 				goto param_prob;
28221 			}
28222 			off = opt[IPOPT_OFFSET];
28223 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28224 			    ntohl(dst)));
28225 			/*
28226 			 * For strict: verify that dst is directly
28227 			 * reachable.
28228 			 */
28229 			if (optval == IPOPT_SSRR) {
28230 				ire = ire_ftable_lookup(dst, 0, 0,
28231 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28232 				    MBLK_GETLABEL(mp),
28233 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28234 				if (ire == NULL) {
28235 					ip1dbg(("ip_wput_options: SSRR not"
28236 					    " directly reachable: 0x%x\n",
28237 					    ntohl(dst)));
28238 					goto bad_src_route;
28239 				}
28240 				ire_refrele(ire);
28241 			}
28242 			break;
28243 		case IPOPT_RR:
28244 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28245 				ip1dbg((
28246 				    "ip_wput_options: bad option offset\n"));
28247 				code = (char *)&opt[IPOPT_OLEN] -
28248 				    (char *)ipha;
28249 				goto param_prob;
28250 			}
28251 			break;
28252 		case IPOPT_TS:
28253 			/*
28254 			 * Verify that length >=5 and that there is either
28255 			 * room for another timestamp or that the overflow
28256 			 * counter is not maxed out.
28257 			 */
28258 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28259 			if (optlen < IPOPT_MINLEN_IT) {
28260 				goto param_prob;
28261 			}
28262 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28263 				ip1dbg((
28264 				    "ip_wput_options: bad option offset\n"));
28265 				code = (char *)&opt[IPOPT_OFFSET] -
28266 				    (char *)ipha;
28267 				goto param_prob;
28268 			}
28269 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28270 			case IPOPT_TS_TSONLY:
28271 				off = IPOPT_TS_TIMELEN;
28272 				break;
28273 			case IPOPT_TS_TSANDADDR:
28274 			case IPOPT_TS_PRESPEC:
28275 			case IPOPT_TS_PRESPEC_RFC791:
28276 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28277 				break;
28278 			default:
28279 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28280 				    (char *)ipha;
28281 				goto param_prob;
28282 			}
28283 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28284 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28285 				/*
28286 				 * No room and the overflow counter is 15
28287 				 * already.
28288 				 */
28289 				goto param_prob;
28290 			}
28291 			break;
28292 		}
28293 	}
28294 
28295 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28296 		return (0);
28297 
28298 	ip1dbg(("ip_wput_options: error processing IP options."));
28299 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28300 
28301 param_prob:
28302 	/*
28303 	 * Since ip_wput() isn't close to finished, we fill
28304 	 * in enough of the header for credible error reporting.
28305 	 */
28306 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28307 		/* Failed */
28308 		freemsg(ipsec_mp);
28309 		return (-1);
28310 	}
28311 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28312 	return (-1);
28313 
28314 bad_src_route:
28315 	/*
28316 	 * Since ip_wput() isn't close to finished, we fill
28317 	 * in enough of the header for credible error reporting.
28318 	 */
28319 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28320 		/* Failed */
28321 		freemsg(ipsec_mp);
28322 		return (-1);
28323 	}
28324 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28325 	return (-1);
28326 }
28327 
28328 /*
28329  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28330  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28331  * thru /etc/system.
28332  */
28333 #define	CONN_MAXDRAINCNT	64
28334 
28335 static void
28336 conn_drain_init(ip_stack_t *ipst)
28337 {
28338 	int i;
28339 
28340 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28341 
28342 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28343 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28344 		/*
28345 		 * Default value of the number of drainers is the
28346 		 * number of cpus, subject to maximum of 8 drainers.
28347 		 */
28348 		if (boot_max_ncpus != -1)
28349 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28350 		else
28351 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28352 	}
28353 
28354 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28355 	    sizeof (idl_t), KM_SLEEP);
28356 
28357 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28358 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28359 		    MUTEX_DEFAULT, NULL);
28360 	}
28361 }
28362 
28363 static void
28364 conn_drain_fini(ip_stack_t *ipst)
28365 {
28366 	int i;
28367 
28368 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28369 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28370 	kmem_free(ipst->ips_conn_drain_list,
28371 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28372 	ipst->ips_conn_drain_list = NULL;
28373 }
28374 
28375 /*
28376  * Note: For an overview of how flowcontrol is handled in IP please see the
28377  * IP Flowcontrol notes at the top of this file.
28378  *
28379  * Flow control has blocked us from proceeding. Insert the given conn in one
28380  * of the conn drain lists. These conn wq's will be qenabled later on when
28381  * STREAMS flow control does a backenable. conn_walk_drain will enable
28382  * the first conn in each of these drain lists. Each of these qenabled conns
28383  * in turn enables the next in the list, after it runs, or when it closes,
28384  * thus sustaining the drain process.
28385  *
28386  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28387  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28388  * running at any time, on a given conn, since there can be only 1 service proc
28389  * running on a queue at any time.
28390  */
28391 void
28392 conn_drain_insert(conn_t *connp)
28393 {
28394 	idl_t	*idl;
28395 	uint_t	index;
28396 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28397 
28398 	mutex_enter(&connp->conn_lock);
28399 	if (connp->conn_state_flags & CONN_CLOSING) {
28400 		/*
28401 		 * The conn is closing as a result of which CONN_CLOSING
28402 		 * is set. Return.
28403 		 */
28404 		mutex_exit(&connp->conn_lock);
28405 		return;
28406 	} else if (connp->conn_idl == NULL) {
28407 		/*
28408 		 * Assign the next drain list round robin. We dont' use
28409 		 * a lock, and thus it may not be strictly round robin.
28410 		 * Atomicity of load/stores is enough to make sure that
28411 		 * conn_drain_list_index is always within bounds.
28412 		 */
28413 		index = ipst->ips_conn_drain_list_index;
28414 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28415 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28416 		index++;
28417 		if (index == ipst->ips_conn_drain_list_cnt)
28418 			index = 0;
28419 		ipst->ips_conn_drain_list_index = index;
28420 	}
28421 	mutex_exit(&connp->conn_lock);
28422 
28423 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28424 	if ((connp->conn_drain_prev != NULL) ||
28425 	    (connp->conn_state_flags & CONN_CLOSING)) {
28426 		/*
28427 		 * The conn is already in the drain list, OR
28428 		 * the conn is closing. We need to check again for
28429 		 * the closing case again since close can happen
28430 		 * after we drop the conn_lock, and before we
28431 		 * acquire the CONN_DRAIN_LIST_LOCK.
28432 		 */
28433 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28434 		return;
28435 	} else {
28436 		idl = connp->conn_idl;
28437 	}
28438 
28439 	/*
28440 	 * The conn is not in the drain list. Insert it at the
28441 	 * tail of the drain list. The drain list is circular
28442 	 * and doubly linked. idl_conn points to the 1st element
28443 	 * in the list.
28444 	 */
28445 	if (idl->idl_conn == NULL) {
28446 		idl->idl_conn = connp;
28447 		connp->conn_drain_next = connp;
28448 		connp->conn_drain_prev = connp;
28449 	} else {
28450 		conn_t *head = idl->idl_conn;
28451 
28452 		connp->conn_drain_next = head;
28453 		connp->conn_drain_prev = head->conn_drain_prev;
28454 		head->conn_drain_prev->conn_drain_next = connp;
28455 		head->conn_drain_prev = connp;
28456 	}
28457 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28458 }
28459 
28460 /*
28461  * This conn is closing, and we are called from ip_close. OR
28462  * This conn has been serviced by ip_wsrv, and we need to do the tail
28463  * processing.
28464  * If this conn is part of the drain list, we may need to sustain the drain
28465  * process by qenabling the next conn in the drain list. We may also need to
28466  * remove this conn from the list, if it is done.
28467  */
28468 static void
28469 conn_drain_tail(conn_t *connp, boolean_t closing)
28470 {
28471 	idl_t *idl;
28472 
28473 	/*
28474 	 * connp->conn_idl is stable at this point, and no lock is needed
28475 	 * to check it. If we are called from ip_close, close has already
28476 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28477 	 * called us only because conn_idl is non-null. If we are called thru
28478 	 * service, conn_idl could be null, but it cannot change because
28479 	 * service is single-threaded per queue, and there cannot be another
28480 	 * instance of service trying to call conn_drain_insert on this conn
28481 	 * now.
28482 	 */
28483 	ASSERT(!closing || (connp->conn_idl != NULL));
28484 
28485 	/*
28486 	 * If connp->conn_idl is null, the conn has not been inserted into any
28487 	 * drain list even once since creation of the conn. Just return.
28488 	 */
28489 	if (connp->conn_idl == NULL)
28490 		return;
28491 
28492 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28493 
28494 	if (connp->conn_drain_prev == NULL) {
28495 		/* This conn is currently not in the drain list.  */
28496 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28497 		return;
28498 	}
28499 	idl = connp->conn_idl;
28500 	if (idl->idl_conn_draining == connp) {
28501 		/*
28502 		 * This conn is the current drainer. If this is the last conn
28503 		 * in the drain list, we need to do more checks, in the 'if'
28504 		 * below. Otherwwise we need to just qenable the next conn,
28505 		 * to sustain the draining, and is handled in the 'else'
28506 		 * below.
28507 		 */
28508 		if (connp->conn_drain_next == idl->idl_conn) {
28509 			/*
28510 			 * This conn is the last in this list. This round
28511 			 * of draining is complete. If idl_repeat is set,
28512 			 * it means another flow enabling has happened from
28513 			 * the driver/streams and we need to another round
28514 			 * of draining.
28515 			 * If there are more than 2 conns in the drain list,
28516 			 * do a left rotate by 1, so that all conns except the
28517 			 * conn at the head move towards the head by 1, and the
28518 			 * the conn at the head goes to the tail. This attempts
28519 			 * a more even share for all queues that are being
28520 			 * drained.
28521 			 */
28522 			if ((connp->conn_drain_next != connp) &&
28523 			    (idl->idl_conn->conn_drain_next != connp)) {
28524 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28525 			}
28526 			if (idl->idl_repeat) {
28527 				qenable(idl->idl_conn->conn_wq);
28528 				idl->idl_conn_draining = idl->idl_conn;
28529 				idl->idl_repeat = 0;
28530 			} else {
28531 				idl->idl_conn_draining = NULL;
28532 			}
28533 		} else {
28534 			/*
28535 			 * If the next queue that we are now qenable'ing,
28536 			 * is closing, it will remove itself from this list
28537 			 * and qenable the subsequent queue in ip_close().
28538 			 * Serialization is acheived thru idl_lock.
28539 			 */
28540 			qenable(connp->conn_drain_next->conn_wq);
28541 			idl->idl_conn_draining = connp->conn_drain_next;
28542 		}
28543 	}
28544 	if (!connp->conn_did_putbq || closing) {
28545 		/*
28546 		 * Remove ourself from the drain list, if we did not do
28547 		 * a putbq, or if the conn is closing.
28548 		 * Note: It is possible that q->q_first is non-null. It means
28549 		 * that these messages landed after we did a enableok() in
28550 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28551 		 * service them.
28552 		 */
28553 		if (connp->conn_drain_next == connp) {
28554 			/* Singleton in the list */
28555 			ASSERT(connp->conn_drain_prev == connp);
28556 			idl->idl_conn = NULL;
28557 			idl->idl_conn_draining = NULL;
28558 		} else {
28559 			connp->conn_drain_prev->conn_drain_next =
28560 			    connp->conn_drain_next;
28561 			connp->conn_drain_next->conn_drain_prev =
28562 			    connp->conn_drain_prev;
28563 			if (idl->idl_conn == connp)
28564 				idl->idl_conn = connp->conn_drain_next;
28565 			ASSERT(idl->idl_conn_draining != connp);
28566 
28567 		}
28568 		connp->conn_drain_next = NULL;
28569 		connp->conn_drain_prev = NULL;
28570 	}
28571 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28572 }
28573 
28574 /*
28575  * Write service routine. Shared perimeter entry point.
28576  * ip_wsrv can be called in any of the following ways.
28577  * 1. The device queue's messages has fallen below the low water mark
28578  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28579  *    the drain lists and backenable the first conn in each list.
28580  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28581  *    qenabled non-tcp upper layers. We start dequeing messages and call
28582  *    ip_wput for each message.
28583  */
28584 
28585 void
28586 ip_wsrv(queue_t *q)
28587 {
28588 	conn_t	*connp;
28589 	ill_t	*ill;
28590 	mblk_t	*mp;
28591 
28592 	if (q->q_next) {
28593 		ill = (ill_t *)q->q_ptr;
28594 		if (ill->ill_state_flags == 0) {
28595 			/*
28596 			 * The device flow control has opened up.
28597 			 * Walk through conn drain lists and qenable the
28598 			 * first conn in each list. This makes sense only
28599 			 * if the stream is fully plumbed and setup.
28600 			 * Hence the if check above.
28601 			 */
28602 			ip1dbg(("ip_wsrv: walking\n"));
28603 			conn_walk_drain(ill->ill_ipst);
28604 		}
28605 		return;
28606 	}
28607 
28608 	connp = Q_TO_CONN(q);
28609 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28610 
28611 	/*
28612 	 * 1. Set conn_draining flag to signal that service is active.
28613 	 *
28614 	 * 2. ip_output determines whether it has been called from service,
28615 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28616 	 *    has been called from service.
28617 	 *
28618 	 * 3. Message ordering is preserved by the following logic.
28619 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28620 	 *    the message at the tail, if conn_draining is set (i.e. service
28621 	 *    is running) or if q->q_first is non-null.
28622 	 *
28623 	 *    ii. If ip_output is called from service, and if ip_output cannot
28624 	 *    putnext due to flow control, it does a putbq.
28625 	 *
28626 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28627 	 *    (causing an infinite loop).
28628 	 */
28629 	ASSERT(!connp->conn_did_putbq);
28630 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28631 		connp->conn_draining = 1;
28632 		noenable(q);
28633 		while ((mp = getq(q)) != NULL) {
28634 			ASSERT(CONN_Q(q));
28635 
28636 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28637 			if (connp->conn_did_putbq) {
28638 				/* ip_wput did a putbq */
28639 				break;
28640 			}
28641 		}
28642 		/*
28643 		 * At this point, a thread coming down from top, calling
28644 		 * ip_wput, may end up queueing the message. We have not yet
28645 		 * enabled the queue, so ip_wsrv won't be called again.
28646 		 * To avoid this race, check q->q_first again (in the loop)
28647 		 * If the other thread queued the message before we call
28648 		 * enableok(), we will catch it in the q->q_first check.
28649 		 * If the other thread queues the message after we call
28650 		 * enableok(), ip_wsrv will be called again by STREAMS.
28651 		 */
28652 		connp->conn_draining = 0;
28653 		enableok(q);
28654 	}
28655 
28656 	/* Enable the next conn for draining */
28657 	conn_drain_tail(connp, B_FALSE);
28658 
28659 	connp->conn_did_putbq = 0;
28660 }
28661 
28662 /*
28663  * Walk the list of all conn's calling the function provided with the
28664  * specified argument for each.	 Note that this only walks conn's that
28665  * have been bound.
28666  * Applies to both IPv4 and IPv6.
28667  */
28668 static void
28669 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28670 {
28671 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28672 	    ipst->ips_ipcl_udp_fanout_size,
28673 	    func, arg, zoneid);
28674 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28675 	    ipst->ips_ipcl_conn_fanout_size,
28676 	    func, arg, zoneid);
28677 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28678 	    ipst->ips_ipcl_bind_fanout_size,
28679 	    func, arg, zoneid);
28680 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28681 	    IPPROTO_MAX, func, arg, zoneid);
28682 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28683 	    IPPROTO_MAX, func, arg, zoneid);
28684 }
28685 
28686 /*
28687  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28688  * of conns that need to be drained, check if drain is already in progress.
28689  * If so set the idl_repeat bit, indicating that the last conn in the list
28690  * needs to reinitiate the drain once again, for the list. If drain is not
28691  * in progress for the list, initiate the draining, by qenabling the 1st
28692  * conn in the list. The drain is self-sustaining, each qenabled conn will
28693  * in turn qenable the next conn, when it is done/blocked/closing.
28694  */
28695 static void
28696 conn_walk_drain(ip_stack_t *ipst)
28697 {
28698 	int i;
28699 	idl_t *idl;
28700 
28701 	IP_STAT(ipst, ip_conn_walk_drain);
28702 
28703 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28704 		idl = &ipst->ips_conn_drain_list[i];
28705 		mutex_enter(&idl->idl_lock);
28706 		if (idl->idl_conn == NULL) {
28707 			mutex_exit(&idl->idl_lock);
28708 			continue;
28709 		}
28710 		/*
28711 		 * If this list is not being drained currently by
28712 		 * an ip_wsrv thread, start the process.
28713 		 */
28714 		if (idl->idl_conn_draining == NULL) {
28715 			ASSERT(idl->idl_repeat == 0);
28716 			qenable(idl->idl_conn->conn_wq);
28717 			idl->idl_conn_draining = idl->idl_conn;
28718 		} else {
28719 			idl->idl_repeat = 1;
28720 		}
28721 		mutex_exit(&idl->idl_lock);
28722 	}
28723 }
28724 
28725 /*
28726  * Walk an conn hash table of `count' buckets, calling func for each entry.
28727  */
28728 static void
28729 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28730     zoneid_t zoneid)
28731 {
28732 	conn_t	*connp;
28733 
28734 	while (count-- > 0) {
28735 		mutex_enter(&connfp->connf_lock);
28736 		for (connp = connfp->connf_head; connp != NULL;
28737 		    connp = connp->conn_next) {
28738 			if (zoneid == GLOBAL_ZONEID ||
28739 			    zoneid == connp->conn_zoneid) {
28740 				CONN_INC_REF(connp);
28741 				mutex_exit(&connfp->connf_lock);
28742 				(*func)(connp, arg);
28743 				mutex_enter(&connfp->connf_lock);
28744 				CONN_DEC_REF(connp);
28745 			}
28746 		}
28747 		mutex_exit(&connfp->connf_lock);
28748 		connfp++;
28749 	}
28750 }
28751 
28752 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28753 static void
28754 conn_report1(conn_t *connp, void *mp)
28755 {
28756 	char	buf1[INET6_ADDRSTRLEN];
28757 	char	buf2[INET6_ADDRSTRLEN];
28758 	uint_t	print_len, buf_len;
28759 
28760 	ASSERT(connp != NULL);
28761 
28762 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28763 	if (buf_len <= 0)
28764 		return;
28765 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28766 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28767 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28768 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28769 	    "%5d %s/%05d %s/%05d\n",
28770 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28771 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28772 	    buf1, connp->conn_lport,
28773 	    buf2, connp->conn_fport);
28774 	if (print_len < buf_len) {
28775 		((mblk_t *)mp)->b_wptr += print_len;
28776 	} else {
28777 		((mblk_t *)mp)->b_wptr += buf_len;
28778 	}
28779 }
28780 
28781 /*
28782  * Named Dispatch routine to produce a formatted report on all conns
28783  * that are listed in one of the fanout tables.
28784  * This report is accessed by using the ndd utility to "get" ND variable
28785  * "ip_conn_status".
28786  */
28787 /* ARGSUSED */
28788 static int
28789 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28790 {
28791 	conn_t *connp = Q_TO_CONN(q);
28792 
28793 	(void) mi_mpprintf(mp,
28794 	    "CONN      " MI_COL_HDRPAD_STR
28795 	    "rfq      " MI_COL_HDRPAD_STR
28796 	    "stq      " MI_COL_HDRPAD_STR
28797 	    " zone local                 remote");
28798 
28799 	/*
28800 	 * Because of the ndd constraint, at most we can have 64K buffer
28801 	 * to put in all conn info.  So to be more efficient, just
28802 	 * allocate a 64K buffer here, assuming we need that large buffer.
28803 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28804 	 */
28805 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28806 		/* The following may work even if we cannot get a large buf. */
28807 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28808 		return (0);
28809 	}
28810 
28811 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28812 	    connp->conn_netstack->netstack_ip);
28813 	return (0);
28814 }
28815 
28816 /*
28817  * Determine if the ill and multicast aspects of that packets
28818  * "matches" the conn.
28819  */
28820 boolean_t
28821 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28822     zoneid_t zoneid)
28823 {
28824 	ill_t *in_ill;
28825 	boolean_t found;
28826 	ipif_t *ipif;
28827 	ire_t *ire;
28828 	ipaddr_t dst, src;
28829 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28830 
28831 	dst = ipha->ipha_dst;
28832 	src = ipha->ipha_src;
28833 
28834 	/*
28835 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28836 	 * unicast, broadcast and multicast reception to
28837 	 * conn_incoming_ill. conn_wantpacket itself is called
28838 	 * only for BROADCAST and multicast.
28839 	 *
28840 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28841 	 *    is part of a group. Hence, we should be receiving
28842 	 *    just one copy of broadcast for the whole group.
28843 	 *    Thus, if it is part of the group the packet could
28844 	 *    come on any ill of the group and hence we need a
28845 	 *    match on the group. Otherwise, match on ill should
28846 	 *    be sufficient.
28847 	 *
28848 	 * 2) ip_rput does not suppress duplicate multicast packets.
28849 	 *    If there are two interfaces in a ill group and we have
28850 	 *    2 applications (conns) joined a multicast group G on
28851 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28852 	 *    will give us two packets because we join G on both the
28853 	 *    interfaces rather than nominating just one interface
28854 	 *    for receiving multicast like broadcast above. So,
28855 	 *    we have to call ilg_lookup_ill to filter out duplicate
28856 	 *    copies, if ill is part of a group.
28857 	 */
28858 	in_ill = connp->conn_incoming_ill;
28859 	if (in_ill != NULL) {
28860 		if (in_ill->ill_group == NULL) {
28861 			if (in_ill != ill)
28862 				return (B_FALSE);
28863 		} else if (in_ill->ill_group != ill->ill_group) {
28864 			return (B_FALSE);
28865 		}
28866 	}
28867 
28868 	if (!CLASSD(dst)) {
28869 		if (IPCL_ZONE_MATCH(connp, zoneid))
28870 			return (B_TRUE);
28871 		/*
28872 		 * The conn is in a different zone; we need to check that this
28873 		 * broadcast address is configured in the application's zone and
28874 		 * on one ill in the group.
28875 		 */
28876 		ipif = ipif_get_next_ipif(NULL, ill);
28877 		if (ipif == NULL)
28878 			return (B_FALSE);
28879 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28880 		    connp->conn_zoneid, NULL,
28881 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28882 		ipif_refrele(ipif);
28883 		if (ire != NULL) {
28884 			ire_refrele(ire);
28885 			return (B_TRUE);
28886 		} else {
28887 			return (B_FALSE);
28888 		}
28889 	}
28890 
28891 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28892 	    connp->conn_zoneid == zoneid) {
28893 		/*
28894 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28895 		 * disabled, therefore we don't dispatch the multicast packet to
28896 		 * the sending zone.
28897 		 */
28898 		return (B_FALSE);
28899 	}
28900 
28901 	if (IS_LOOPBACK(ill) && 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), 0, stackid);
29661 	if (ksp == NULL || ksp->ks_data == NULL)
29662 		return (NULL);
29663 
29664 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29665 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29666 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29667 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29668 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29669 
29670 	template.netToMediaEntrySize.value.i32 =
29671 	    sizeof (mib2_ipNetToMediaEntry_t);
29672 
29673 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29674 
29675 	bcopy(&template, ksp->ks_data, sizeof (template));
29676 	ksp->ks_update = ip_kstat_update;
29677 	ksp->ks_private = (void *)(uintptr_t)stackid;
29678 
29679 	kstat_install(ksp);
29680 	return (ksp);
29681 }
29682 
29683 static void
29684 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29685 {
29686 	if (ksp != NULL) {
29687 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29688 		kstat_delete_netstack(ksp, stackid);
29689 	}
29690 }
29691 
29692 static int
29693 ip_kstat_update(kstat_t *kp, int rw)
29694 {
29695 	ip_named_kstat_t *ipkp;
29696 	mib2_ipIfStatsEntry_t ipmib;
29697 	ill_walk_context_t ctx;
29698 	ill_t *ill;
29699 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29700 	netstack_t	*ns;
29701 	ip_stack_t	*ipst;
29702 
29703 	if (kp == NULL || kp->ks_data == NULL)
29704 		return (EIO);
29705 
29706 	if (rw == KSTAT_WRITE)
29707 		return (EACCES);
29708 
29709 	ns = netstack_find_by_stackid(stackid);
29710 	if (ns == NULL)
29711 		return (-1);
29712 	ipst = ns->netstack_ip;
29713 	if (ipst == NULL) {
29714 		netstack_rele(ns);
29715 		return (-1);
29716 	}
29717 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29718 
29719 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29720 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29721 	ill = ILL_START_WALK_V4(&ctx, ipst);
29722 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29723 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29724 	rw_exit(&ipst->ips_ill_g_lock);
29725 
29726 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29727 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29728 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29729 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29730 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29731 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29732 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29733 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29734 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29735 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29736 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29737 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29738 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29739 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29740 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29741 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29742 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29743 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29744 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29745 
29746 	ipkp->routingDiscards.value.ui32 =	0;
29747 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29748 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29749 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29750 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29751 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29752 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29753 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29754 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29755 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29756 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29757 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29758 
29759 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29760 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29761 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29762 
29763 	netstack_rele(ns);
29764 
29765 	return (0);
29766 }
29767 
29768 static void *
29769 icmp_kstat_init(netstackid_t stackid)
29770 {
29771 	kstat_t	*ksp;
29772 
29773 	icmp_named_kstat_t template = {
29774 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29775 		{ "inErrors",		KSTAT_DATA_UINT32 },
29776 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29777 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29778 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29779 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29780 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29781 		{ "inEchos",		KSTAT_DATA_UINT32 },
29782 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29783 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29784 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29785 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29786 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29787 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29788 		{ "outErrors",		KSTAT_DATA_UINT32 },
29789 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29790 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29791 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29792 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29793 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29794 		{ "outEchos",		KSTAT_DATA_UINT32 },
29795 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29796 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29797 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29798 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29799 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29800 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29801 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29802 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29803 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29804 		{ "outDrops",		KSTAT_DATA_UINT32 },
29805 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29806 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29807 	};
29808 
29809 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29810 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29811 	if (ksp == NULL || ksp->ks_data == NULL)
29812 		return (NULL);
29813 
29814 	bcopy(&template, ksp->ks_data, sizeof (template));
29815 
29816 	ksp->ks_update = icmp_kstat_update;
29817 	ksp->ks_private = (void *)(uintptr_t)stackid;
29818 
29819 	kstat_install(ksp);
29820 	return (ksp);
29821 }
29822 
29823 static void
29824 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29825 {
29826 	if (ksp != NULL) {
29827 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29828 		kstat_delete_netstack(ksp, stackid);
29829 	}
29830 }
29831 
29832 static int
29833 icmp_kstat_update(kstat_t *kp, int rw)
29834 {
29835 	icmp_named_kstat_t *icmpkp;
29836 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29837 	netstack_t	*ns;
29838 	ip_stack_t	*ipst;
29839 
29840 	if ((kp == NULL) || (kp->ks_data == NULL))
29841 		return (EIO);
29842 
29843 	if (rw == KSTAT_WRITE)
29844 		return (EACCES);
29845 
29846 	ns = netstack_find_by_stackid(stackid);
29847 	if (ns == NULL)
29848 		return (-1);
29849 	ipst = ns->netstack_ip;
29850 	if (ipst == NULL) {
29851 		netstack_rele(ns);
29852 		return (-1);
29853 	}
29854 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29855 
29856 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29857 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29858 	icmpkp->inDestUnreachs.value.ui32 =
29859 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29860 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29861 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29862 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29863 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29864 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29865 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29866 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29867 	icmpkp->inTimestampReps.value.ui32 =
29868 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29869 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29870 	icmpkp->inAddrMaskReps.value.ui32 =
29871 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29872 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29873 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29874 	icmpkp->outDestUnreachs.value.ui32 =
29875 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29876 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29877 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29878 	icmpkp->outSrcQuenchs.value.ui32 =
29879 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29880 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29881 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29882 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29883 	icmpkp->outTimestamps.value.ui32 =
29884 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29885 	icmpkp->outTimestampReps.value.ui32 =
29886 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29887 	icmpkp->outAddrMasks.value.ui32 =
29888 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29889 	icmpkp->outAddrMaskReps.value.ui32 =
29890 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29891 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29892 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29893 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29894 	icmpkp->outFragNeeded.value.ui32 =
29895 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29896 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29897 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29898 	icmpkp->inBadRedirects.value.ui32 =
29899 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29900 
29901 	netstack_rele(ns);
29902 	return (0);
29903 }
29904 
29905 /*
29906  * This is the fanout function for raw socket opened for SCTP.  Note
29907  * that it is called after SCTP checks that there is no socket which
29908  * wants a packet.  Then before SCTP handles this out of the blue packet,
29909  * this function is called to see if there is any raw socket for SCTP.
29910  * If there is and it is bound to the correct address, the packet will
29911  * be sent to that socket.  Note that only one raw socket can be bound to
29912  * a port.  This is assured in ipcl_sctp_hash_insert();
29913  */
29914 void
29915 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29916     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29917     zoneid_t zoneid)
29918 {
29919 	conn_t		*connp;
29920 	queue_t		*rq;
29921 	mblk_t		*first_mp;
29922 	boolean_t	secure;
29923 	ip6_t		*ip6h;
29924 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29925 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29926 
29927 	first_mp = mp;
29928 	if (mctl_present) {
29929 		mp = first_mp->b_cont;
29930 		secure = ipsec_in_is_secure(first_mp);
29931 		ASSERT(mp != NULL);
29932 	} else {
29933 		secure = B_FALSE;
29934 	}
29935 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29936 
29937 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29938 	if (connp == NULL) {
29939 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29940 		return;
29941 	}
29942 	rq = connp->conn_rq;
29943 	if (!canputnext(rq)) {
29944 		CONN_DEC_REF(connp);
29945 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29946 		freemsg(first_mp);
29947 		return;
29948 	}
29949 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29950 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29951 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29952 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29953 		if (first_mp == NULL) {
29954 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29955 			CONN_DEC_REF(connp);
29956 			return;
29957 		}
29958 	}
29959 	/*
29960 	 * We probably should not send M_CTL message up to
29961 	 * raw socket.
29962 	 */
29963 	if (mctl_present)
29964 		freeb(first_mp);
29965 
29966 	/* Initiate IPPF processing here if needed. */
29967 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29968 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29969 		ip_process(IPP_LOCAL_IN, &mp,
29970 		    recv_ill->ill_phyint->phyint_ifindex);
29971 		if (mp == NULL) {
29972 			CONN_DEC_REF(connp);
29973 			return;
29974 		}
29975 	}
29976 
29977 	if (connp->conn_recvif || connp->conn_recvslla ||
29978 	    ((connp->conn_ip_recvpktinfo ||
29979 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29980 	    (flags & IP_FF_IPINFO))) {
29981 		int in_flags = 0;
29982 
29983 		/*
29984 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29985 		 * IPF_RECVIF.
29986 		 */
29987 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29988 			in_flags = IPF_RECVIF;
29989 		}
29990 		if (connp->conn_recvslla) {
29991 			in_flags |= IPF_RECVSLLA;
29992 		}
29993 		if (isv4) {
29994 			mp = ip_add_info(mp, recv_ill, in_flags,
29995 			    IPCL_ZONEID(connp), ipst);
29996 		} else {
29997 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29998 			if (mp == NULL) {
29999 				BUMP_MIB(recv_ill->ill_ip_mib,
30000 				    ipIfStatsInDiscards);
30001 				CONN_DEC_REF(connp);
30002 				return;
30003 			}
30004 		}
30005 	}
30006 
30007 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
30008 	/*
30009 	 * We are sending the IPSEC_IN message also up. Refer
30010 	 * to comments above this function.
30011 	 */
30012 	putnext(rq, mp);
30013 	CONN_DEC_REF(connp);
30014 }
30015 
30016 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30017 {									\
30018 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30019 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30020 }
30021 /*
30022  * This function should be called only if all packet processing
30023  * including fragmentation is complete. Callers of this function
30024  * must set mp->b_prev to one of these values:
30025  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30026  * prior to handing over the mp as first argument to this function.
30027  *
30028  * If the ire passed by caller is incomplete, this function
30029  * queues the packet and if necessary, sends ARP request and bails.
30030  * If the ire passed is fully resolved, we simply prepend
30031  * the link-layer header to the packet, do ipsec hw acceleration
30032  * work if necessary, and send the packet out on the wire.
30033  *
30034  * NOTE: IPSEC will only call this function with fully resolved
30035  * ires if hw acceleration is involved.
30036  * TODO list :
30037  * 	a Handle M_MULTIDATA so that
30038  *	  tcp_multisend->tcp_multisend_data can
30039  *	  call ip_xmit_v4 directly
30040  *	b Handle post-ARP work for fragments so that
30041  *	  ip_wput_frag can call this function.
30042  */
30043 ipxmit_state_t
30044 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30045 {
30046 	nce_t		*arpce;
30047 	queue_t		*q;
30048 	int		ill_index;
30049 	mblk_t		*nxt_mp, *first_mp;
30050 	boolean_t	xmit_drop = B_FALSE;
30051 	ip_proc_t	proc;
30052 	ill_t		*out_ill;
30053 	int		pkt_len;
30054 
30055 	arpce = ire->ire_nce;
30056 	ASSERT(arpce != NULL);
30057 
30058 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30059 
30060 	mutex_enter(&arpce->nce_lock);
30061 	switch (arpce->nce_state) {
30062 	case ND_REACHABLE:
30063 		/* If there are other queued packets, queue this packet */
30064 		if (arpce->nce_qd_mp != NULL) {
30065 			if (mp != NULL)
30066 				nce_queue_mp_common(arpce, mp, B_FALSE);
30067 			mp = arpce->nce_qd_mp;
30068 		}
30069 		arpce->nce_qd_mp = NULL;
30070 		mutex_exit(&arpce->nce_lock);
30071 
30072 		/*
30073 		 * Flush the queue.  In the common case, where the
30074 		 * ARP is already resolved,  it will go through the
30075 		 * while loop only once.
30076 		 */
30077 		while (mp != NULL) {
30078 
30079 			nxt_mp = mp->b_next;
30080 			mp->b_next = NULL;
30081 			ASSERT(mp->b_datap->db_type != M_CTL);
30082 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30083 			/*
30084 			 * This info is needed for IPQOS to do COS marking
30085 			 * in ip_wput_attach_llhdr->ip_process.
30086 			 */
30087 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30088 			mp->b_prev = NULL;
30089 
30090 			/* set up ill index for outbound qos processing */
30091 			out_ill = ire->ire_ipif->ipif_ill;
30092 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30093 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30094 			    ill_index);
30095 			if (first_mp == NULL) {
30096 				xmit_drop = B_TRUE;
30097 				BUMP_MIB(out_ill->ill_ip_mib,
30098 				    ipIfStatsOutDiscards);
30099 				goto next_mp;
30100 			}
30101 			/* non-ipsec hw accel case */
30102 			if (io == NULL || !io->ipsec_out_accelerated) {
30103 				/* send it */
30104 				q = ire->ire_stq;
30105 				if (proc == IPP_FWD_OUT) {
30106 					UPDATE_IB_PKT_COUNT(ire);
30107 				} else {
30108 					UPDATE_OB_PKT_COUNT(ire);
30109 				}
30110 				ire->ire_last_used_time = lbolt;
30111 
30112 				if (flow_ctl_enabled || canputnext(q)) {
30113 					if (proc == IPP_FWD_OUT) {
30114 
30115 					BUMP_MIB(out_ill->ill_ip_mib,
30116 					    ipIfStatsHCOutForwDatagrams);
30117 
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