xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 76939ce0e89c177cb48bf98208fd3d831eb283d5)
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 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
884 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
885 #ifdef DEBUG
886 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
887 #else
888 	{  0,	0,	0,	"" },
889 #endif
890 };
891 
892 /*
893  * Extended NDP table
894  * The addresses for the first two are filled in to be ips_ip_g_forward
895  * and ips_ipv6_forward at init time.
896  */
897 static ipndp_t	lcl_ndp_arr[] = {
898 	/* getf			setf		data			name */
899 #define	IPNDP_IP_FORWARDING_OFFSET	0
900 	{  ip_param_generic_get,	ip_forward_set,	NULL,
901 	    "ip_forwarding" },
902 #define	IPNDP_IP6_FORWARDING_OFFSET	1
903 	{  ip_param_generic_get,	ip_forward_set,	NULL,
904 	    "ip6_forwarding" },
905 	{  ip_ill_report,	NULL,		NULL,
906 	    "ip_ill_status" },
907 	{  ip_ipif_report,	NULL,		NULL,
908 	    "ip_ipif_status" },
909 	{  ip_ire_report,	NULL,		NULL,
910 	    "ipv4_ire_status" },
911 	{  ip_ire_report_mrtun,	NULL,		NULL,
912 	    "ipv4_mrtun_ire_status" },
913 	{  ip_ire_report_srcif,	NULL,		NULL,
914 	    "ipv4_srcif_ire_status" },
915 	{  ip_ire_report_v6,	NULL,		NULL,
916 	    "ipv6_ire_status" },
917 	{  ip_conn_report,	NULL,		NULL,
918 	    "ip_conn_status" },
919 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
920 	    "ip_rput_pullups" },
921 	{  ndp_report,		NULL,		NULL,
922 	    "ip_ndp_cache_report" },
923 	{  ip_srcid_report,	NULL,		NULL,
924 	    "ip_srcid_status" },
925 	{ ip_param_generic_get, ip_squeue_profile_set,
926 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
927 	{ ip_param_generic_get, ip_squeue_bind_set,
928 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
929 	{ ip_param_generic_get, ip_input_proc_set,
930 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
931 	{ ip_param_generic_get, ip_int_set,
932 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
933 #define	IPNDP_CGTP_FILTER_OFFSET	16
934 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
935 	    "ip_cgtp_filter" },
936 	{ ip_param_generic_get, ip_int_set,
937 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
938 #define	IPNDP_IPMP_HOOK_OFFSET	18
939 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
940 	    "ipmp_hook_emulation" },
941 };
942 
943 /*
944  * Table of IP ioctls encoding the various properties of the ioctl and
945  * indexed based on the last byte of the ioctl command. Occasionally there
946  * is a clash, and there is more than 1 ioctl with the same last byte.
947  * In such a case 1 ioctl is encoded in the ndx table and the remaining
948  * ioctls are encoded in the misc table. An entry in the ndx table is
949  * retrieved by indexing on the last byte of the ioctl command and comparing
950  * the ioctl command with the value in the ndx table. In the event of a
951  * mismatch the misc table is then searched sequentially for the desired
952  * ioctl command.
953  *
954  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
955  */
956 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
957 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
963 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
964 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
965 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
966 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
967 
968 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
969 			MISC_CMD, ip_siocaddrt, NULL },
970 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
971 			MISC_CMD, ip_siocdelrt, NULL },
972 
973 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
974 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
975 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
976 			IF_CMD, ip_sioctl_get_addr, NULL },
977 
978 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
979 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
980 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
981 			IPI_GET_CMD | IPI_REPL,
982 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
983 
984 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
985 			IPI_PRIV | IPI_WR | IPI_REPL,
986 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
987 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
988 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
989 			IF_CMD, ip_sioctl_get_flags, NULL },
990 
991 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
992 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
993 
994 	/* copyin size cannot be coded for SIOCGIFCONF */
995 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
996 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
997 
998 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
999 			IF_CMD, ip_sioctl_mtu, NULL },
1000 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1001 			IF_CMD, ip_sioctl_get_mtu, NULL },
1002 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
1003 			IPI_GET_CMD | IPI_REPL,
1004 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1005 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1006 			IF_CMD, ip_sioctl_brdaddr, NULL },
1007 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1008 			IPI_GET_CMD | IPI_REPL,
1009 			IF_CMD, ip_sioctl_get_netmask, NULL },
1010 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1011 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1012 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1013 			IPI_GET_CMD | IPI_REPL,
1014 			IF_CMD, ip_sioctl_get_metric, NULL },
1015 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1016 			IF_CMD, ip_sioctl_metric, NULL },
1017 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 
1019 	/* See 166-168 below for extended SIOC*XARP ioctls */
1020 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1021 			MISC_CMD, ip_sioctl_arp, NULL },
1022 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1023 			MISC_CMD, ip_sioctl_arp, NULL },
1024 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1025 			MISC_CMD, ip_sioctl_arp, NULL },
1026 
1027 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 
1049 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1050 			MISC_CMD, if_unitsel, if_unitsel_restart },
1051 
1052 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 
1071 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1072 			IPI_PRIV | IPI_WR | IPI_MODOK,
1073 			IF_CMD, ip_sioctl_sifname, NULL },
1074 
1075 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1085 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1086 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1087 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1088 
1089 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1090 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1091 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1092 			IF_CMD, ip_sioctl_get_muxid, NULL },
1093 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1094 			IPI_PRIV | IPI_WR | IPI_REPL,
1095 			IF_CMD, ip_sioctl_muxid, NULL },
1096 
1097 	/* Both if and lif variants share same func */
1098 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1099 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1100 	/* Both if and lif variants share same func */
1101 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1102 			IPI_PRIV | IPI_WR | IPI_REPL,
1103 			IF_CMD, ip_sioctl_slifindex, NULL },
1104 
1105 	/* copyin size cannot be coded for SIOCGIFCONF */
1106 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD | IPI_REPL,
1107 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1108 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1122 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1123 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1124 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1125 
1126 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1127 			IPI_PRIV | IPI_WR | IPI_REPL,
1128 			LIF_CMD, ip_sioctl_removeif,
1129 			ip_sioctl_removeif_restart },
1130 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1131 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1132 			LIF_CMD, ip_sioctl_addif, NULL },
1133 #define	SIOCLIFADDR_NDX 112
1134 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1135 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1136 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1137 			IPI_GET_CMD | IPI_REPL,
1138 			LIF_CMD, ip_sioctl_get_addr, NULL },
1139 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1140 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1141 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1142 			IPI_GET_CMD | IPI_REPL,
1143 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1144 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1145 			IPI_PRIV | IPI_WR | IPI_REPL,
1146 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1147 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1148 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1149 			LIF_CMD, ip_sioctl_get_flags, NULL },
1150 
1151 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1152 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1153 
1154 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1155 			ip_sioctl_get_lifconf, NULL },
1156 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1157 			LIF_CMD, ip_sioctl_mtu, NULL },
1158 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1159 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1160 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1161 			IPI_GET_CMD | IPI_REPL,
1162 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1163 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1164 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1165 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1166 			IPI_GET_CMD | IPI_REPL,
1167 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1168 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1169 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1170 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1171 			IPI_GET_CMD | IPI_REPL,
1172 			LIF_CMD, ip_sioctl_get_metric, NULL },
1173 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1174 			LIF_CMD, ip_sioctl_metric, NULL },
1175 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1176 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_slifname,
1178 			ip_sioctl_slifname_restart },
1179 
1180 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1181 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1182 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1183 			IPI_GET_CMD | IPI_REPL,
1184 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1185 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1186 			IPI_PRIV | IPI_WR | IPI_REPL,
1187 			LIF_CMD, ip_sioctl_muxid, NULL },
1188 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1189 			IPI_GET_CMD | IPI_REPL,
1190 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1191 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1192 			IPI_PRIV | IPI_WR | IPI_REPL,
1193 			LIF_CMD, ip_sioctl_slifindex, 0 },
1194 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1195 			LIF_CMD, ip_sioctl_token, NULL },
1196 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1197 			IPI_GET_CMD | IPI_REPL,
1198 			LIF_CMD, ip_sioctl_get_token, NULL },
1199 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1200 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1201 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1202 			IPI_GET_CMD | IPI_REPL,
1203 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1204 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1205 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1206 
1207 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1208 			IPI_GET_CMD | IPI_REPL,
1209 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1210 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1211 			LIF_CMD, ip_siocdelndp_v6, NULL },
1212 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1213 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1214 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1215 			LIF_CMD, ip_siocsetndp_v6, NULL },
1216 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1217 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1218 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1219 			MISC_CMD, ip_sioctl_tonlink, NULL },
1220 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1221 			MISC_CMD, ip_sioctl_tmysite, NULL },
1222 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1223 			TUN_CMD, ip_sioctl_tunparam, NULL },
1224 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1225 			IPI_PRIV | IPI_WR,
1226 			TUN_CMD, ip_sioctl_tunparam, NULL },
1227 
1228 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1229 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1230 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1231 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1232 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1233 
1234 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1235 			IPI_PRIV | IPI_WR | IPI_REPL,
1236 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1237 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1238 			IPI_PRIV | IPI_WR | IPI_REPL,
1239 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1240 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1241 			IPI_PRIV | IPI_WR,
1242 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1243 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1244 			IPI_GET_CMD | IPI_REPL,
1245 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1246 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1247 			IPI_GET_CMD | IPI_REPL,
1248 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1249 
1250 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1251 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1252 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1253 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1254 
1255 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1256 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1257 
1258 	/* These are handled in ip_sioctl_copyin_setup itself */
1259 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1260 			MISC_CMD, NULL, NULL },
1261 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1262 			MISC_CMD, NULL, NULL },
1263 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1264 
1265 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD | IPI_REPL,
1266 			ip_sioctl_get_lifconf, NULL },
1267 
1268 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1269 			MISC_CMD, ip_sioctl_xarp, NULL },
1270 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1271 			MISC_CMD, ip_sioctl_xarp, NULL },
1272 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1273 			MISC_CMD, ip_sioctl_xarp, NULL },
1274 
1275 	/* SIOCPOPSOCKFS is not handled by IP */
1276 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1277 
1278 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1279 			IPI_GET_CMD | IPI_REPL,
1280 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1281 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1282 			IPI_PRIV | IPI_WR | IPI_REPL,
1283 			LIF_CMD, ip_sioctl_slifzone,
1284 			ip_sioctl_slifzone_restart },
1285 	/* 172-174 are SCTP ioctls and not handled by IP */
1286 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1287 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1288 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1289 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1290 			IPI_GET_CMD, LIF_CMD,
1291 			ip_sioctl_get_lifusesrc, 0 },
1292 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1293 			IPI_PRIV | IPI_WR,
1294 			LIF_CMD, ip_sioctl_slifusesrc,
1295 			NULL },
1296 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1297 			ip_sioctl_get_lifsrcof, NULL },
1298 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1299 			MISC_CMD, ip_sioctl_msfilter, NULL },
1300 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1301 			MISC_CMD, ip_sioctl_msfilter, NULL },
1302 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1303 			MISC_CMD, ip_sioctl_msfilter, NULL },
1304 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1305 			MISC_CMD, ip_sioctl_msfilter, NULL },
1306 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1307 			ip_sioctl_set_ipmpfailback, NULL }
1308 };
1309 
1310 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1311 
1312 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1313 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1314 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1315 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1316 		TUN_CMD, ip_sioctl_tunparam, NULL },
1317 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1319 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1320 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1321 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1322 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1323 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1324 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1325 		MISC_CMD, mrt_ioctl},
1326 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1327 		MISC_CMD, mrt_ioctl},
1328 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1329 		MISC_CMD, mrt_ioctl}
1330 };
1331 
1332 int ip_misc_ioctl_count =
1333     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1334 
1335 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1336 					/* Settable in /etc/system */
1337 /* Defined in ip_ire.c */
1338 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1339 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1340 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1341 
1342 static nv_t	ire_nv_arr[] = {
1343 	{ IRE_BROADCAST, "BROADCAST" },
1344 	{ IRE_LOCAL, "LOCAL" },
1345 	{ IRE_LOOPBACK, "LOOPBACK" },
1346 	{ IRE_CACHE, "CACHE" },
1347 	{ IRE_DEFAULT, "DEFAULT" },
1348 	{ IRE_PREFIX, "PREFIX" },
1349 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1350 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1351 	{ IRE_HOST, "HOST" },
1352 	{ 0 }
1353 };
1354 
1355 nv_t	*ire_nv_tbl = ire_nv_arr;
1356 
1357 /* Defined in ip_netinfo.c */
1358 extern ddi_taskq_t	*eventq_queue_nic;
1359 
1360 /* Simple ICMP IP Header Template */
1361 static ipha_t icmp_ipha = {
1362 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1363 };
1364 
1365 struct module_info ip_mod_info = {
1366 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1367 };
1368 
1369 /*
1370  * Duplicate static symbols within a module confuses mdb; so we avoid the
1371  * problem by making the symbols here distinct from those in udp.c.
1372  */
1373 
1374 static struct qinit iprinit = {
1375 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1376 	&ip_mod_info
1377 };
1378 
1379 static struct qinit ipwinit = {
1380 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1381 	&ip_mod_info
1382 };
1383 
1384 static struct qinit iplrinit = {
1385 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1386 	&ip_mod_info
1387 };
1388 
1389 static struct qinit iplwinit = {
1390 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1391 	&ip_mod_info
1392 };
1393 
1394 struct streamtab ipinfo = {
1395 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1396 };
1397 
1398 #ifdef	DEBUG
1399 static boolean_t skip_sctp_cksum = B_FALSE;
1400 #endif
1401 
1402 /*
1403  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1404  * ip_rput_v6(), ip_output(), etc.  If the message
1405  * block already has a M_CTL at the front of it, then simply set the zoneid
1406  * appropriately.
1407  */
1408 mblk_t *
1409 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1410 {
1411 	mblk_t		*first_mp;
1412 	ipsec_out_t	*io;
1413 
1414 	ASSERT(zoneid != ALL_ZONES);
1415 	if (mp->b_datap->db_type == M_CTL) {
1416 		io = (ipsec_out_t *)mp->b_rptr;
1417 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1418 		io->ipsec_out_zoneid = zoneid;
1419 		return (mp);
1420 	}
1421 
1422 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1423 	if (first_mp == NULL)
1424 		return (NULL);
1425 	io = (ipsec_out_t *)first_mp->b_rptr;
1426 	/* This is not a secure packet */
1427 	io->ipsec_out_secure = B_FALSE;
1428 	io->ipsec_out_zoneid = zoneid;
1429 	first_mp->b_cont = mp;
1430 	return (first_mp);
1431 }
1432 
1433 /*
1434  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1435  */
1436 mblk_t *
1437 ip_copymsg(mblk_t *mp)
1438 {
1439 	mblk_t *nmp;
1440 	ipsec_info_t *in;
1441 
1442 	if (mp->b_datap->db_type != M_CTL)
1443 		return (copymsg(mp));
1444 
1445 	in = (ipsec_info_t *)mp->b_rptr;
1446 
1447 	/*
1448 	 * Note that M_CTL is also used for delivering ICMP error messages
1449 	 * upstream to transport layers.
1450 	 */
1451 	if (in->ipsec_info_type != IPSEC_OUT &&
1452 	    in->ipsec_info_type != IPSEC_IN)
1453 		return (copymsg(mp));
1454 
1455 	nmp = copymsg(mp->b_cont);
1456 
1457 	if (in->ipsec_info_type == IPSEC_OUT) {
1458 		return (ipsec_out_tag(mp, nmp,
1459 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1460 	} else {
1461 		return (ipsec_in_tag(mp, nmp,
1462 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1463 	}
1464 }
1465 
1466 /* Generate an ICMP fragmentation needed message. */
1467 static void
1468 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1469     ip_stack_t *ipst)
1470 {
1471 	icmph_t	icmph;
1472 	mblk_t *first_mp;
1473 	boolean_t mctl_present;
1474 
1475 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1476 
1477 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1478 		if (mctl_present)
1479 			freeb(first_mp);
1480 		return;
1481 	}
1482 
1483 	bzero(&icmph, sizeof (icmph_t));
1484 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1485 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1486 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1487 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1488 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1489 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1490 	    ipst);
1491 }
1492 
1493 /*
1494  * icmp_inbound deals with ICMP messages in the following ways.
1495  *
1496  * 1) It needs to send a reply back and possibly delivering it
1497  *    to the "interested" upper clients.
1498  * 2) It needs to send it to the upper clients only.
1499  * 3) It needs to change some values in IP only.
1500  * 4) It needs to change some values in IP and upper layers e.g TCP.
1501  *
1502  * We need to accomodate icmp messages coming in clear until we get
1503  * everything secure from the wire. If icmp_accept_clear_messages
1504  * is zero we check with the global policy and act accordingly. If
1505  * it is non-zero, we accept the message without any checks. But
1506  * *this does not mean* that this will be delivered to the upper
1507  * clients. By accepting we might send replies back, change our MTU
1508  * value etc. but delivery to the ULP/clients depends on their policy
1509  * dispositions.
1510  *
1511  * We handle the above 4 cases in the context of IPSEC in the
1512  * following way :
1513  *
1514  * 1) Send the reply back in the same way as the request came in.
1515  *    If it came in encrypted, it goes out encrypted. If it came in
1516  *    clear, it goes out in clear. Thus, this will prevent chosen
1517  *    plain text attack.
1518  * 2) The client may or may not expect things to come in secure.
1519  *    If it comes in secure, the policy constraints are checked
1520  *    before delivering it to the upper layers. If it comes in
1521  *    clear, ipsec_inbound_accept_clear will decide whether to
1522  *    accept this in clear or not. In both the cases, if the returned
1523  *    message (IP header + 8 bytes) that caused the icmp message has
1524  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1525  *    sending up. If there are only 8 bytes of returned message, then
1526  *    upper client will not be notified.
1527  * 3) Check with global policy to see whether it matches the constaints.
1528  *    But this will be done only if icmp_accept_messages_in_clear is
1529  *    zero.
1530  * 4) If we need to change both in IP and ULP, then the decision taken
1531  *    while affecting the values in IP and while delivering up to TCP
1532  *    should be the same.
1533  *
1534  * 	There are two cases.
1535  *
1536  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1537  *	   failed), we will not deliver it to the ULP, even though they
1538  *	   are *willing* to accept in *clear*. This is fine as our global
1539  *	   disposition to icmp messages asks us reject the datagram.
1540  *
1541  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1542  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1543  *	   to deliver it to ULP (policy failed), it can lead to
1544  *	   consistency problems. The cases known at this time are
1545  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1546  *	   values :
1547  *
1548  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1549  *	     and Upper layer rejects. Then the communication will
1550  *	     come to a stop. This is solved by making similar decisions
1551  *	     at both levels. Currently, when we are unable to deliver
1552  *	     to the Upper Layer (due to policy failures) while IP has
1553  *	     adjusted ire_max_frag, the next outbound datagram would
1554  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1555  *	     will be with the right level of protection. Thus the right
1556  *	     value will be communicated even if we are not able to
1557  *	     communicate when we get from the wire initially. But this
1558  *	     assumes there would be at least one outbound datagram after
1559  *	     IP has adjusted its ire_max_frag value. To make things
1560  *	     simpler, we accept in clear after the validation of
1561  *	     AH/ESP headers.
1562  *
1563  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1564  *	     upper layer depending on the level of protection the upper
1565  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1566  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1567  *	     should be accepted in clear when the Upper layer expects secure.
1568  *	     Thus the communication may get aborted by some bad ICMP
1569  *	     packets.
1570  *
1571  * IPQoS Notes:
1572  * The only instance when a packet is sent for processing is when there
1573  * isn't an ICMP client and if we are interested in it.
1574  * If there is a client, IPPF processing will take place in the
1575  * ip_fanout_proto routine.
1576  *
1577  * Zones notes:
1578  * The packet is only processed in the context of the specified zone: typically
1579  * only this zone will reply to an echo request, and only interested clients in
1580  * this zone will receive a copy of the packet. This means that the caller must
1581  * call icmp_inbound() for each relevant zone.
1582  */
1583 static void
1584 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1585     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1586     ill_t *recv_ill, zoneid_t zoneid)
1587 {
1588 	icmph_t	*icmph;
1589 	ipha_t	*ipha;
1590 	int	iph_hdr_length;
1591 	int	hdr_length;
1592 	boolean_t	interested;
1593 	uint32_t	ts;
1594 	uchar_t	*wptr;
1595 	ipif_t	*ipif;
1596 	mblk_t *first_mp;
1597 	ipsec_in_t *ii;
1598 	ire_t *src_ire;
1599 	boolean_t onlink;
1600 	timestruc_t now;
1601 	uint32_t ill_index;
1602 	ip_stack_t *ipst;
1603 
1604 	ASSERT(ill != NULL);
1605 	ipst = ill->ill_ipst;
1606 
1607 	first_mp = mp;
1608 	if (mctl_present) {
1609 		mp = first_mp->b_cont;
1610 		ASSERT(mp != NULL);
1611 	}
1612 
1613 	ipha = (ipha_t *)mp->b_rptr;
1614 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1615 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1616 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1617 		if (first_mp == NULL)
1618 			return;
1619 	}
1620 
1621 	/*
1622 	 * On a labeled system, we have to check whether the zone itself is
1623 	 * permitted to receive raw traffic.
1624 	 */
1625 	if (is_system_labeled()) {
1626 		if (zoneid == ALL_ZONES)
1627 			zoneid = tsol_packet_to_zoneid(mp);
1628 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1629 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1630 			    zoneid));
1631 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1632 			freemsg(first_mp);
1633 			return;
1634 		}
1635 	}
1636 
1637 	/*
1638 	 * We have accepted the ICMP message. It means that we will
1639 	 * respond to the packet if needed. It may not be delivered
1640 	 * to the upper client depending on the policy constraints
1641 	 * and the disposition in ipsec_inbound_accept_clear.
1642 	 */
1643 
1644 	ASSERT(ill != NULL);
1645 
1646 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1647 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1648 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1649 		/* Last chance to get real. */
1650 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1651 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1652 			freemsg(first_mp);
1653 			return;
1654 		}
1655 		/* Refresh iph following the pullup. */
1656 		ipha = (ipha_t *)mp->b_rptr;
1657 	}
1658 	/* ICMP header checksum, including checksum field, should be zero. */
1659 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1660 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1661 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1662 		freemsg(first_mp);
1663 		return;
1664 	}
1665 	/* The IP header will always be a multiple of four bytes */
1666 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1667 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1668 	    icmph->icmph_code));
1669 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1670 	/* We will set "interested" to "true" if we want a copy */
1671 	interested = B_FALSE;
1672 	switch (icmph->icmph_type) {
1673 	case ICMP_ECHO_REPLY:
1674 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1675 		break;
1676 	case ICMP_DEST_UNREACHABLE:
1677 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1678 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1679 		interested = B_TRUE;	/* Pass up to transport */
1680 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1681 		break;
1682 	case ICMP_SOURCE_QUENCH:
1683 		interested = B_TRUE;	/* Pass up to transport */
1684 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1685 		break;
1686 	case ICMP_REDIRECT:
1687 		if (!ipst->ips_ip_ignore_redirect)
1688 			interested = B_TRUE;
1689 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1690 		break;
1691 	case ICMP_ECHO_REQUEST:
1692 		/*
1693 		 * Whether to respond to echo requests that come in as IP
1694 		 * broadcasts or as IP multicast is subject to debate
1695 		 * (what isn't?).  We aim to please, you pick it.
1696 		 * Default is do it.
1697 		 */
1698 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1699 			/* unicast: always respond */
1700 			interested = B_TRUE;
1701 		} else if (CLASSD(ipha->ipha_dst)) {
1702 			/* multicast: respond based on tunable */
1703 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1704 		} else if (broadcast) {
1705 			/* broadcast: respond based on tunable */
1706 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1707 		}
1708 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1709 		break;
1710 	case ICMP_ROUTER_ADVERTISEMENT:
1711 	case ICMP_ROUTER_SOLICITATION:
1712 		break;
1713 	case ICMP_TIME_EXCEEDED:
1714 		interested = B_TRUE;	/* Pass up to transport */
1715 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1716 		break;
1717 	case ICMP_PARAM_PROBLEM:
1718 		interested = B_TRUE;	/* Pass up to transport */
1719 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1720 		break;
1721 	case ICMP_TIME_STAMP_REQUEST:
1722 		/* Response to Time Stamp Requests is local policy. */
1723 		if (ipst->ips_ip_g_resp_to_timestamp &&
1724 		    /* So is whether to respond if it was an IP broadcast. */
1725 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1726 			int tstamp_len = 3 * sizeof (uint32_t);
1727 
1728 			if (wptr +  tstamp_len > mp->b_wptr) {
1729 				if (!pullupmsg(mp, wptr + tstamp_len -
1730 				    mp->b_rptr)) {
1731 					BUMP_MIB(ill->ill_ip_mib,
1732 					    ipIfStatsInDiscards);
1733 					freemsg(first_mp);
1734 					return;
1735 				}
1736 				/* Refresh ipha following the pullup. */
1737 				ipha = (ipha_t *)mp->b_rptr;
1738 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1739 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1740 			}
1741 			interested = B_TRUE;
1742 		}
1743 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1744 		break;
1745 	case ICMP_TIME_STAMP_REPLY:
1746 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1747 		break;
1748 	case ICMP_INFO_REQUEST:
1749 		/* Per RFC 1122 3.2.2.7, ignore this. */
1750 	case ICMP_INFO_REPLY:
1751 		break;
1752 	case ICMP_ADDRESS_MASK_REQUEST:
1753 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1754 		    !broadcast) &&
1755 		    /* TODO m_pullup of complete header? */
1756 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1757 			interested = B_TRUE;
1758 		}
1759 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1760 		break;
1761 	case ICMP_ADDRESS_MASK_REPLY:
1762 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1763 		break;
1764 	default:
1765 		interested = B_TRUE;	/* Pass up to transport */
1766 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1767 		break;
1768 	}
1769 	/* See if there is an ICMP client. */
1770 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1771 		/* If there is an ICMP client and we want one too, copy it. */
1772 		mblk_t *first_mp1;
1773 
1774 		if (!interested) {
1775 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1776 			    ip_policy, recv_ill, zoneid);
1777 			return;
1778 		}
1779 		first_mp1 = ip_copymsg(first_mp);
1780 		if (first_mp1 != NULL) {
1781 			ip_fanout_proto(q, first_mp1, ill, ipha,
1782 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1783 		}
1784 	} else if (!interested) {
1785 		freemsg(first_mp);
1786 		return;
1787 	} else {
1788 		/*
1789 		 * Initiate policy processing for this packet if ip_policy
1790 		 * is true.
1791 		 */
1792 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1793 			ill_index = ill->ill_phyint->phyint_ifindex;
1794 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1795 			if (mp == NULL) {
1796 				if (mctl_present) {
1797 					freeb(first_mp);
1798 				}
1799 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1800 				return;
1801 			}
1802 		}
1803 	}
1804 	/* We want to do something with it. */
1805 	/* Check db_ref to make sure we can modify the packet. */
1806 	if (mp->b_datap->db_ref > 1) {
1807 		mblk_t	*first_mp1;
1808 
1809 		first_mp1 = ip_copymsg(first_mp);
1810 		freemsg(first_mp);
1811 		if (!first_mp1) {
1812 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1813 			return;
1814 		}
1815 		first_mp = first_mp1;
1816 		if (mctl_present) {
1817 			mp = first_mp->b_cont;
1818 			ASSERT(mp != NULL);
1819 		} else {
1820 			mp = first_mp;
1821 		}
1822 		ipha = (ipha_t *)mp->b_rptr;
1823 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1824 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1825 	}
1826 	switch (icmph->icmph_type) {
1827 	case ICMP_ADDRESS_MASK_REQUEST:
1828 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1829 		if (ipif == NULL) {
1830 			freemsg(first_mp);
1831 			return;
1832 		}
1833 		/*
1834 		 * outging interface must be IPv4
1835 		 */
1836 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1837 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1838 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1839 		ipif_refrele(ipif);
1840 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1841 		break;
1842 	case ICMP_ECHO_REQUEST:
1843 		icmph->icmph_type = ICMP_ECHO_REPLY;
1844 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1845 		break;
1846 	case ICMP_TIME_STAMP_REQUEST: {
1847 		uint32_t *tsp;
1848 
1849 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1850 		tsp = (uint32_t *)wptr;
1851 		tsp++;		/* Skip past 'originate time' */
1852 		/* Compute # of milliseconds since midnight */
1853 		gethrestime(&now);
1854 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1855 		    now.tv_nsec / (NANOSEC / MILLISEC);
1856 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1857 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1858 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1859 		break;
1860 	}
1861 	default:
1862 		ipha = (ipha_t *)&icmph[1];
1863 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1864 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1865 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1866 				freemsg(first_mp);
1867 				return;
1868 			}
1869 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1870 			ipha = (ipha_t *)&icmph[1];
1871 		}
1872 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1873 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1874 			freemsg(first_mp);
1875 			return;
1876 		}
1877 		hdr_length = IPH_HDR_LENGTH(ipha);
1878 		if (hdr_length < sizeof (ipha_t)) {
1879 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1880 			freemsg(first_mp);
1881 			return;
1882 		}
1883 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1884 			if (!pullupmsg(mp,
1885 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1886 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1887 				freemsg(first_mp);
1888 				return;
1889 			}
1890 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1891 			ipha = (ipha_t *)&icmph[1];
1892 		}
1893 		switch (icmph->icmph_type) {
1894 		case ICMP_REDIRECT:
1895 			/*
1896 			 * As there is no upper client to deliver, we don't
1897 			 * need the first_mp any more.
1898 			 */
1899 			if (mctl_present) {
1900 				freeb(first_mp);
1901 			}
1902 			icmp_redirect(ill, mp);
1903 			return;
1904 		case ICMP_DEST_UNREACHABLE:
1905 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1906 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1907 				    zoneid, mp, iph_hdr_length, ipst)) {
1908 					freemsg(first_mp);
1909 					return;
1910 				}
1911 				/*
1912 				 * icmp_inbound_too_big() may alter mp.
1913 				 * Resynch ipha and icmph accordingly.
1914 				 */
1915 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1916 				ipha = (ipha_t *)&icmph[1];
1917 			}
1918 			/* FALLTHRU */
1919 		default :
1920 			/*
1921 			 * IPQoS notes: Since we have already done IPQoS
1922 			 * processing we don't want to do it again in
1923 			 * the fanout routines called by
1924 			 * icmp_inbound_error_fanout, hence the last
1925 			 * argument, ip_policy, is B_FALSE.
1926 			 */
1927 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1928 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1929 			    B_FALSE, recv_ill, zoneid);
1930 		}
1931 		return;
1932 	}
1933 	/* Send out an ICMP packet */
1934 	icmph->icmph_checksum = 0;
1935 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1936 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1937 		ipif_t	*ipif_chosen;
1938 		/*
1939 		 * Make it look like it was directed to us, so we don't look
1940 		 * like a fool with a broadcast or multicast source address.
1941 		 */
1942 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1943 		/*
1944 		 * Make sure that we haven't grabbed an interface that's DOWN.
1945 		 */
1946 		if (ipif != NULL) {
1947 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1948 			    ipha->ipha_src, zoneid);
1949 			if (ipif_chosen != NULL) {
1950 				ipif_refrele(ipif);
1951 				ipif = ipif_chosen;
1952 			}
1953 		}
1954 		if (ipif == NULL) {
1955 			ip0dbg(("icmp_inbound: "
1956 			    "No source for broadcast/multicast:\n"
1957 			    "\tsrc 0x%x dst 0x%x ill %p "
1958 			    "ipif_lcl_addr 0x%x\n",
1959 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1960 			    (void *)ill,
1961 			    ill->ill_ipif->ipif_lcl_addr));
1962 			freemsg(first_mp);
1963 			return;
1964 		}
1965 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1966 		ipha->ipha_dst = ipif->ipif_src_addr;
1967 		ipif_refrele(ipif);
1968 	}
1969 	/* Reset time to live. */
1970 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1971 	{
1972 		/* Swap source and destination addresses */
1973 		ipaddr_t tmp;
1974 
1975 		tmp = ipha->ipha_src;
1976 		ipha->ipha_src = ipha->ipha_dst;
1977 		ipha->ipha_dst = tmp;
1978 	}
1979 	ipha->ipha_ident = 0;
1980 	if (!IS_SIMPLE_IPH(ipha))
1981 		icmp_options_update(ipha);
1982 
1983 	/*
1984 	 * ICMP echo replies should go out on the same interface
1985 	 * the request came on as probes used by in.mpathd for detecting
1986 	 * NIC failures are ECHO packets. We turn-off load spreading
1987 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1988 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1989 	 * function. This is in turn handled by ip_wput and ip_newroute
1990 	 * to make sure that the packet goes out on the interface it came
1991 	 * in on. If we don't turnoff load spreading, the packets might get
1992 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1993 	 * to go out and in.mpathd would wrongly detect a failure or
1994 	 * mis-detect a NIC failure for link failure. As load spreading
1995 	 * can happen only if ill_group is not NULL, we do only for
1996 	 * that case and this does not affect the normal case.
1997 	 *
1998 	 * We turn off load spreading only on echo packets that came from
1999 	 * on-link hosts. If the interface route has been deleted, this will
2000 	 * not be enforced as we can't do much. For off-link hosts, as the
2001 	 * default routes in IPv4 does not typically have an ire_ipif
2002 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2003 	 * Moreover, expecting a default route through this interface may
2004 	 * not be correct. We use ipha_dst because of the swap above.
2005 	 */
2006 	onlink = B_FALSE;
2007 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2008 		/*
2009 		 * First, we need to make sure that it is not one of our
2010 		 * local addresses. If we set onlink when it is one of
2011 		 * our local addresses, we will end up creating IRE_CACHES
2012 		 * for one of our local addresses. Then, we will never
2013 		 * accept packets for them afterwards.
2014 		 */
2015 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2016 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2017 		if (src_ire == NULL) {
2018 			ipif = ipif_get_next_ipif(NULL, ill);
2019 			if (ipif == NULL) {
2020 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2021 				freemsg(mp);
2022 				return;
2023 			}
2024 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2025 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2026 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2027 			ipif_refrele(ipif);
2028 			if (src_ire != NULL) {
2029 				onlink = B_TRUE;
2030 				ire_refrele(src_ire);
2031 			}
2032 		} else {
2033 			ire_refrele(src_ire);
2034 		}
2035 	}
2036 	if (!mctl_present) {
2037 		/*
2038 		 * This packet should go out the same way as it
2039 		 * came in i.e in clear. To make sure that global
2040 		 * policy will not be applied to this in ip_wput_ire,
2041 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2042 		 */
2043 		ASSERT(first_mp == mp);
2044 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2045 		if (first_mp == NULL) {
2046 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2047 			freemsg(mp);
2048 			return;
2049 		}
2050 		ii = (ipsec_in_t *)first_mp->b_rptr;
2051 
2052 		/* This is not a secure packet */
2053 		ii->ipsec_in_secure = B_FALSE;
2054 		if (onlink) {
2055 			ii->ipsec_in_attach_if = B_TRUE;
2056 			ii->ipsec_in_ill_index =
2057 			    ill->ill_phyint->phyint_ifindex;
2058 			ii->ipsec_in_rill_index =
2059 			    recv_ill->ill_phyint->phyint_ifindex;
2060 		}
2061 		first_mp->b_cont = mp;
2062 	} else if (onlink) {
2063 		ii = (ipsec_in_t *)first_mp->b_rptr;
2064 		ii->ipsec_in_attach_if = B_TRUE;
2065 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2066 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2067 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2068 	} else {
2069 		ii = (ipsec_in_t *)first_mp->b_rptr;
2070 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2071 	}
2072 	ii->ipsec_in_zoneid = zoneid;
2073 	ASSERT(zoneid != ALL_ZONES);
2074 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2075 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2076 		return;
2077 	}
2078 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2079 	put(WR(q), first_mp);
2080 }
2081 
2082 static ipaddr_t
2083 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2084 {
2085 	conn_t *connp;
2086 	connf_t *connfp;
2087 	ipaddr_t nexthop_addr = INADDR_ANY;
2088 	int hdr_length = IPH_HDR_LENGTH(ipha);
2089 	uint16_t *up;
2090 	uint32_t ports;
2091 	ip_stack_t *ipst = ill->ill_ipst;
2092 
2093 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2094 	switch (ipha->ipha_protocol) {
2095 		case IPPROTO_TCP:
2096 		{
2097 			tcph_t *tcph;
2098 
2099 			/* do a reverse lookup */
2100 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2101 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2102 			    TCPS_LISTEN, ipst);
2103 			break;
2104 		}
2105 		case IPPROTO_UDP:
2106 		{
2107 			uint32_t dstport, srcport;
2108 
2109 			((uint16_t *)&ports)[0] = up[1];
2110 			((uint16_t *)&ports)[1] = up[0];
2111 
2112 			/* Extract ports in net byte order */
2113 			dstport = htons(ntohl(ports) & 0xFFFF);
2114 			srcport = htons(ntohl(ports) >> 16);
2115 
2116 			connfp = &ipst->ips_ipcl_udp_fanout[
2117 			    IPCL_UDP_HASH(dstport, ipst)];
2118 			mutex_enter(&connfp->connf_lock);
2119 			connp = connfp->connf_head;
2120 
2121 			/* do a reverse lookup */
2122 			while ((connp != NULL) &&
2123 			    (!IPCL_UDP_MATCH(connp, dstport,
2124 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2125 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2126 				connp = connp->conn_next;
2127 			}
2128 			if (connp != NULL)
2129 				CONN_INC_REF(connp);
2130 			mutex_exit(&connfp->connf_lock);
2131 			break;
2132 		}
2133 		case IPPROTO_SCTP:
2134 		{
2135 			in6_addr_t map_src, map_dst;
2136 
2137 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2138 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2139 			((uint16_t *)&ports)[0] = up[1];
2140 			((uint16_t *)&ports)[1] = up[0];
2141 
2142 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2143 			    zoneid, ipst->ips_netstack->netstack_sctp);
2144 			if (connp == NULL) {
2145 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2146 				    zoneid, ports, ipha, ipst);
2147 			} else {
2148 				CONN_INC_REF(connp);
2149 				SCTP_REFRELE(CONN2SCTP(connp));
2150 			}
2151 			break;
2152 		}
2153 		default:
2154 		{
2155 			ipha_t ripha;
2156 
2157 			ripha.ipha_src = ipha->ipha_dst;
2158 			ripha.ipha_dst = ipha->ipha_src;
2159 			ripha.ipha_protocol = ipha->ipha_protocol;
2160 
2161 			connfp = &ipst->ips_ipcl_proto_fanout[
2162 			    ipha->ipha_protocol];
2163 			mutex_enter(&connfp->connf_lock);
2164 			connp = connfp->connf_head;
2165 			for (connp = connfp->connf_head; connp != NULL;
2166 			    connp = connp->conn_next) {
2167 				if (IPCL_PROTO_MATCH(connp,
2168 				    ipha->ipha_protocol, &ripha, ill,
2169 				    0, zoneid)) {
2170 					CONN_INC_REF(connp);
2171 					break;
2172 				}
2173 			}
2174 			mutex_exit(&connfp->connf_lock);
2175 		}
2176 	}
2177 	if (connp != NULL) {
2178 		if (connp->conn_nexthop_set)
2179 			nexthop_addr = connp->conn_nexthop_v4;
2180 		CONN_DEC_REF(connp);
2181 	}
2182 	return (nexthop_addr);
2183 }
2184 
2185 /* Table from RFC 1191 */
2186 static int icmp_frag_size_table[] =
2187 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2188 
2189 /*
2190  * Process received ICMP Packet too big.
2191  * After updating any IRE it does the fanout to any matching transport streams.
2192  * Assumes the message has been pulled up till the IP header that caused
2193  * the error.
2194  *
2195  * Returns B_FALSE on failure and B_TRUE on success.
2196  */
2197 static boolean_t
2198 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2199     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2200     ip_stack_t *ipst)
2201 {
2202 	ire_t	*ire, *first_ire;
2203 	int	mtu;
2204 	int	hdr_length;
2205 	ipaddr_t nexthop_addr;
2206 
2207 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2208 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2209 	ASSERT(ill != NULL);
2210 
2211 	hdr_length = IPH_HDR_LENGTH(ipha);
2212 
2213 	/* Drop if the original packet contained a source route */
2214 	if (ip_source_route_included(ipha)) {
2215 		return (B_FALSE);
2216 	}
2217 	/*
2218 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2219 	 * header.
2220 	 */
2221 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2222 	    mp->b_wptr) {
2223 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2224 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2225 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2226 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2227 			return (B_FALSE);
2228 		}
2229 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2230 		ipha = (ipha_t *)&icmph[1];
2231 	}
2232 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2233 	if (nexthop_addr != INADDR_ANY) {
2234 		/* nexthop set */
2235 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2236 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2237 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2238 	} else {
2239 		/* nexthop not set */
2240 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2241 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2242 	}
2243 
2244 	if (!first_ire) {
2245 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2246 		    ntohl(ipha->ipha_dst)));
2247 		return (B_FALSE);
2248 	}
2249 	/* Check for MTU discovery advice as described in RFC 1191 */
2250 	mtu = ntohs(icmph->icmph_du_mtu);
2251 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2252 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2253 	    ire = ire->ire_next) {
2254 		/*
2255 		 * Look for the connection to which this ICMP message is
2256 		 * directed. If it has the IP_NEXTHOP option set, then the
2257 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2258 		 * option. Else the search is limited to regular IREs.
2259 		 */
2260 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2261 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2262 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2263 		    (nexthop_addr != INADDR_ANY)))
2264 			continue;
2265 
2266 		mutex_enter(&ire->ire_lock);
2267 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2268 			/* Reduce the IRE max frag value as advised. */
2269 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2270 			    mtu, ire->ire_max_frag));
2271 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2272 		} else {
2273 			uint32_t length;
2274 			int	i;
2275 
2276 			/*
2277 			 * Use the table from RFC 1191 to figure out
2278 			 * the next "plateau" based on the length in
2279 			 * the original IP packet.
2280 			 */
2281 			length = ntohs(ipha->ipha_length);
2282 			if (ire->ire_max_frag <= length &&
2283 			    ire->ire_max_frag >= length - hdr_length) {
2284 				/*
2285 				 * Handle broken BSD 4.2 systems that
2286 				 * return the wrong iph_length in ICMP
2287 				 * errors.
2288 				 */
2289 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2290 				    length, ire->ire_max_frag));
2291 				length -= hdr_length;
2292 			}
2293 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2294 				if (length > icmp_frag_size_table[i])
2295 					break;
2296 			}
2297 			if (i == A_CNT(icmp_frag_size_table)) {
2298 				/* Smaller than 68! */
2299 				ip1dbg(("Too big for packet size %d\n",
2300 				    length));
2301 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2302 				ire->ire_frag_flag = 0;
2303 			} else {
2304 				mtu = icmp_frag_size_table[i];
2305 				ip1dbg(("Calculated mtu %d, packet size %d, "
2306 				    "before %d", mtu, length,
2307 				    ire->ire_max_frag));
2308 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2309 				ip1dbg((", after %d\n", ire->ire_max_frag));
2310 			}
2311 			/* Record the new max frag size for the ULP. */
2312 			icmph->icmph_du_zero = 0;
2313 			icmph->icmph_du_mtu =
2314 			    htons((uint16_t)ire->ire_max_frag);
2315 		}
2316 		mutex_exit(&ire->ire_lock);
2317 	}
2318 	rw_exit(&first_ire->ire_bucket->irb_lock);
2319 	ire_refrele(first_ire);
2320 	return (B_TRUE);
2321 }
2322 
2323 /*
2324  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2325  * calls this function.
2326  */
2327 static mblk_t *
2328 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2329 {
2330 	ipha_t *ipha;
2331 	icmph_t *icmph;
2332 	ipha_t *in_ipha;
2333 	int length;
2334 
2335 	ASSERT(mp->b_datap->db_type == M_DATA);
2336 
2337 	/*
2338 	 * For Self-encapsulated packets, we added an extra IP header
2339 	 * without the options. Inner IP header is the one from which
2340 	 * the outer IP header was formed. Thus, we need to remove the
2341 	 * outer IP header. To do this, we pullup the whole message
2342 	 * and overlay whatever follows the outer IP header over the
2343 	 * outer IP header.
2344 	 */
2345 
2346 	if (!pullupmsg(mp, -1))
2347 		return (NULL);
2348 
2349 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2350 	ipha = (ipha_t *)&icmph[1];
2351 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2352 
2353 	/*
2354 	 * The length that we want to overlay is following the inner
2355 	 * IP header. Subtracting the IP header + icmp header + outer
2356 	 * IP header's length should give us the length that we want to
2357 	 * overlay.
2358 	 */
2359 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2360 	    hdr_length;
2361 	/*
2362 	 * Overlay whatever follows the inner header over the
2363 	 * outer header.
2364 	 */
2365 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2366 
2367 	/* Set the wptr to account for the outer header */
2368 	mp->b_wptr -= hdr_length;
2369 	return (mp);
2370 }
2371 
2372 /*
2373  * Try to pass the ICMP message upstream in case the ULP cares.
2374  *
2375  * If the packet that caused the ICMP error is secure, we send
2376  * it to AH/ESP to make sure that the attached packet has a
2377  * valid association. ipha in the code below points to the
2378  * IP header of the packet that caused the error.
2379  *
2380  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2381  * in the context of IPSEC. Normally we tell the upper layer
2382  * whenever we send the ire (including ip_bind), the IPSEC header
2383  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2384  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2385  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2386  * same thing. As TCP has the IPSEC options size that needs to be
2387  * adjusted, we just pass the MTU unchanged.
2388  *
2389  * IFN could have been generated locally or by some router.
2390  *
2391  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2392  *	    This happens because IP adjusted its value of MTU on an
2393  *	    earlier IFN message and could not tell the upper layer,
2394  *	    the new adjusted value of MTU e.g. Packet was encrypted
2395  *	    or there was not enough information to fanout to upper
2396  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2397  *	    generates the IFN, where IPSEC processing has *not* been
2398  *	    done.
2399  *
2400  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2401  *	    could have generated this. This happens because ire_max_frag
2402  *	    value in IP was set to a new value, while the IPSEC processing
2403  *	    was being done and after we made the fragmentation check in
2404  *	    ip_wput_ire. Thus on return from IPSEC processing,
2405  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2406  *	    and generates the IFN. As IPSEC processing is over, we fanout
2407  *	    to AH/ESP to remove the header.
2408  *
2409  *	    In both these cases, ipsec_in_loopback will be set indicating
2410  *	    that IFN was generated locally.
2411  *
2412  * ROUTER : IFN could be secure or non-secure.
2413  *
2414  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2415  *	      packet in error has AH/ESP headers to validate the AH/ESP
2416  *	      headers. AH/ESP will verify whether there is a valid SA or
2417  *	      not and send it back. We will fanout again if we have more
2418  *	      data in the packet.
2419  *
2420  *	      If the packet in error does not have AH/ESP, we handle it
2421  *	      like any other case.
2422  *
2423  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2424  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2425  *	      for validation. AH/ESP will verify whether there is a
2426  *	      valid SA or not and send it back. We will fanout again if
2427  *	      we have more data in the packet.
2428  *
2429  *	      If the packet in error does not have AH/ESP, we handle it
2430  *	      like any other case.
2431  */
2432 static void
2433 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2434     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2435     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2436     zoneid_t zoneid)
2437 {
2438 	uint16_t *up;	/* Pointer to ports in ULP header */
2439 	uint32_t ports;	/* reversed ports for fanout */
2440 	ipha_t ripha;	/* With reversed addresses */
2441 	mblk_t *first_mp;
2442 	ipsec_in_t *ii;
2443 	tcph_t	*tcph;
2444 	conn_t	*connp;
2445 	ip_stack_t *ipst;
2446 
2447 	ASSERT(ill != NULL);
2448 
2449 	ASSERT(recv_ill != NULL);
2450 	ipst = recv_ill->ill_ipst;
2451 
2452 	first_mp = mp;
2453 	if (mctl_present) {
2454 		mp = first_mp->b_cont;
2455 		ASSERT(mp != NULL);
2456 
2457 		ii = (ipsec_in_t *)first_mp->b_rptr;
2458 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2459 	} else {
2460 		ii = NULL;
2461 	}
2462 
2463 	switch (ipha->ipha_protocol) {
2464 	case IPPROTO_UDP:
2465 		/*
2466 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2467 		 * transport header.
2468 		 */
2469 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2470 		    mp->b_wptr) {
2471 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2472 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2473 				goto discard_pkt;
2474 			}
2475 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2476 			ipha = (ipha_t *)&icmph[1];
2477 		}
2478 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2479 
2480 		/*
2481 		 * Attempt to find a client stream based on port.
2482 		 * Note that we do a reverse lookup since the header is
2483 		 * in the form we sent it out.
2484 		 * The ripha header is only used for the IP_UDP_MATCH and we
2485 		 * only set the src and dst addresses and protocol.
2486 		 */
2487 		ripha.ipha_src = ipha->ipha_dst;
2488 		ripha.ipha_dst = ipha->ipha_src;
2489 		ripha.ipha_protocol = ipha->ipha_protocol;
2490 		((uint16_t *)&ports)[0] = up[1];
2491 		((uint16_t *)&ports)[1] = up[0];
2492 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2493 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2494 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2495 		    icmph->icmph_type, icmph->icmph_code));
2496 
2497 		/* Have to change db_type after any pullupmsg */
2498 		DB_TYPE(mp) = M_CTL;
2499 
2500 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2501 		    mctl_present, ip_policy, recv_ill, zoneid);
2502 		return;
2503 
2504 	case IPPROTO_TCP:
2505 		/*
2506 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2507 		 * transport header.
2508 		 */
2509 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2510 		    mp->b_wptr) {
2511 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2512 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2513 				goto discard_pkt;
2514 			}
2515 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2516 			ipha = (ipha_t *)&icmph[1];
2517 		}
2518 		/*
2519 		 * Find a TCP client stream for this packet.
2520 		 * Note that we do a reverse lookup since the header is
2521 		 * in the form we sent it out.
2522 		 */
2523 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2524 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2525 		    ipst);
2526 		if (connp == NULL)
2527 			goto discard_pkt;
2528 
2529 		/* Have to change db_type after any pullupmsg */
2530 		DB_TYPE(mp) = M_CTL;
2531 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2532 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2533 		return;
2534 
2535 	case IPPROTO_SCTP:
2536 		/*
2537 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2538 		 * transport header.
2539 		 */
2540 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2541 		    mp->b_wptr) {
2542 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2543 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2544 				goto discard_pkt;
2545 			}
2546 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2547 			ipha = (ipha_t *)&icmph[1];
2548 		}
2549 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2550 		/*
2551 		 * Find a SCTP client stream for this packet.
2552 		 * Note that we do a reverse lookup since the header is
2553 		 * in the form we sent it out.
2554 		 * The ripha header is only used for the matching and we
2555 		 * only set the src and dst addresses, protocol, and version.
2556 		 */
2557 		ripha.ipha_src = ipha->ipha_dst;
2558 		ripha.ipha_dst = ipha->ipha_src;
2559 		ripha.ipha_protocol = ipha->ipha_protocol;
2560 		ripha.ipha_version_and_hdr_length =
2561 		    ipha->ipha_version_and_hdr_length;
2562 		((uint16_t *)&ports)[0] = up[1];
2563 		((uint16_t *)&ports)[1] = up[0];
2564 
2565 		/* Have to change db_type after any pullupmsg */
2566 		DB_TYPE(mp) = M_CTL;
2567 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2568 		    mctl_present, ip_policy, zoneid);
2569 		return;
2570 
2571 	case IPPROTO_ESP:
2572 	case IPPROTO_AH: {
2573 		int ipsec_rc;
2574 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2575 
2576 		/*
2577 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2578 		 * We will re-use the IPSEC_IN if it is already present as
2579 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2580 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2581 		 * one and attach it in the front.
2582 		 */
2583 		if (ii != NULL) {
2584 			/*
2585 			 * ip_fanout_proto_again converts the ICMP errors
2586 			 * that come back from AH/ESP to M_DATA so that
2587 			 * if it is non-AH/ESP and we do a pullupmsg in
2588 			 * this function, it would work. Convert it back
2589 			 * to M_CTL before we send up as this is a ICMP
2590 			 * error. This could have been generated locally or
2591 			 * by some router. Validate the inner IPSEC
2592 			 * headers.
2593 			 *
2594 			 * NOTE : ill_index is used by ip_fanout_proto_again
2595 			 * to locate the ill.
2596 			 */
2597 			ASSERT(ill != NULL);
2598 			ii->ipsec_in_ill_index =
2599 			    ill->ill_phyint->phyint_ifindex;
2600 			ii->ipsec_in_rill_index =
2601 			    recv_ill->ill_phyint->phyint_ifindex;
2602 			DB_TYPE(first_mp->b_cont) = M_CTL;
2603 		} else {
2604 			/*
2605 			 * IPSEC_IN is not present. We attach a ipsec_in
2606 			 * message and send up to IPSEC for validating
2607 			 * and removing the IPSEC headers. Clear
2608 			 * ipsec_in_secure so that when we return
2609 			 * from IPSEC, we don't mistakenly think that this
2610 			 * is a secure packet came from the network.
2611 			 *
2612 			 * NOTE : ill_index is used by ip_fanout_proto_again
2613 			 * to locate the ill.
2614 			 */
2615 			ASSERT(first_mp == mp);
2616 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2617 			if (first_mp == NULL) {
2618 				freemsg(mp);
2619 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2620 				return;
2621 			}
2622 			ii = (ipsec_in_t *)first_mp->b_rptr;
2623 
2624 			/* This is not a secure packet */
2625 			ii->ipsec_in_secure = B_FALSE;
2626 			first_mp->b_cont = mp;
2627 			DB_TYPE(mp) = M_CTL;
2628 			ASSERT(ill != NULL);
2629 			ii->ipsec_in_ill_index =
2630 			    ill->ill_phyint->phyint_ifindex;
2631 			ii->ipsec_in_rill_index =
2632 			    recv_ill->ill_phyint->phyint_ifindex;
2633 		}
2634 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2635 
2636 		if (!ipsec_loaded(ipss)) {
2637 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2638 			return;
2639 		}
2640 
2641 		if (ipha->ipha_protocol == IPPROTO_ESP)
2642 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2643 		else
2644 			ipsec_rc = ipsecah_icmp_error(first_mp);
2645 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2646 			return;
2647 
2648 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2649 		return;
2650 	}
2651 	default:
2652 		/*
2653 		 * The ripha header is only used for the lookup and we
2654 		 * only set the src and dst addresses and protocol.
2655 		 */
2656 		ripha.ipha_src = ipha->ipha_dst;
2657 		ripha.ipha_dst = ipha->ipha_src;
2658 		ripha.ipha_protocol = ipha->ipha_protocol;
2659 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2660 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2661 		    ntohl(ipha->ipha_dst),
2662 		    icmph->icmph_type, icmph->icmph_code));
2663 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2664 			ipha_t *in_ipha;
2665 
2666 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2667 			    mp->b_wptr) {
2668 				if (!pullupmsg(mp, (uchar_t *)ipha +
2669 				    hdr_length + sizeof (ipha_t) -
2670 				    mp->b_rptr)) {
2671 					goto discard_pkt;
2672 				}
2673 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2674 				ipha = (ipha_t *)&icmph[1];
2675 			}
2676 			/*
2677 			 * Caller has verified that length has to be
2678 			 * at least the size of IP header.
2679 			 */
2680 			ASSERT(hdr_length >= sizeof (ipha_t));
2681 			/*
2682 			 * Check the sanity of the inner IP header like
2683 			 * we did for the outer header.
2684 			 */
2685 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2686 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2687 				goto discard_pkt;
2688 			}
2689 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2690 				goto discard_pkt;
2691 			}
2692 			/* Check for Self-encapsulated tunnels */
2693 			if (in_ipha->ipha_src == ipha->ipha_src &&
2694 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2695 
2696 				mp = icmp_inbound_self_encap_error(mp,
2697 				    iph_hdr_length, hdr_length);
2698 				if (mp == NULL)
2699 					goto discard_pkt;
2700 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2701 				ipha = (ipha_t *)&icmph[1];
2702 				hdr_length = IPH_HDR_LENGTH(ipha);
2703 				/*
2704 				 * The packet in error is self-encapsualted.
2705 				 * And we are finding it further encapsulated
2706 				 * which we could not have possibly generated.
2707 				 */
2708 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2709 					goto discard_pkt;
2710 				}
2711 				icmp_inbound_error_fanout(q, ill, first_mp,
2712 				    icmph, ipha, iph_hdr_length, hdr_length,
2713 				    mctl_present, ip_policy, recv_ill, zoneid);
2714 				return;
2715 			}
2716 		}
2717 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2718 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2719 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2720 		    ii != NULL &&
2721 		    ii->ipsec_in_loopback &&
2722 		    ii->ipsec_in_secure) {
2723 			/*
2724 			 * For IP tunnels that get a looped-back
2725 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2726 			 * reported new MTU to take into account the IPsec
2727 			 * headers protecting this configured tunnel.
2728 			 *
2729 			 * This allows the tunnel module (tun.c) to blindly
2730 			 * accept the MTU reported in an ICMP "too big"
2731 			 * message.
2732 			 *
2733 			 * Non-looped back ICMP messages will just be
2734 			 * handled by the security protocols (if needed),
2735 			 * and the first subsequent packet will hit this
2736 			 * path.
2737 			 */
2738 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2739 			    ipsec_in_extra_length(first_mp));
2740 		}
2741 		/* Have to change db_type after any pullupmsg */
2742 		DB_TYPE(mp) = M_CTL;
2743 
2744 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2745 		    ip_policy, recv_ill, zoneid);
2746 		return;
2747 	}
2748 	/* NOTREACHED */
2749 discard_pkt:
2750 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2751 drop_pkt:;
2752 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2753 	freemsg(first_mp);
2754 }
2755 
2756 /*
2757  * Common IP options parser.
2758  *
2759  * Setup routine: fill in *optp with options-parsing state, then
2760  * tail-call ipoptp_next to return the first option.
2761  */
2762 uint8_t
2763 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2764 {
2765 	uint32_t totallen; /* total length of all options */
2766 
2767 	totallen = ipha->ipha_version_and_hdr_length -
2768 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2769 	totallen <<= 2;
2770 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2771 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2772 	optp->ipoptp_flags = 0;
2773 	return (ipoptp_next(optp));
2774 }
2775 
2776 /*
2777  * Common IP options parser: extract next option.
2778  */
2779 uint8_t
2780 ipoptp_next(ipoptp_t *optp)
2781 {
2782 	uint8_t *end = optp->ipoptp_end;
2783 	uint8_t *cur = optp->ipoptp_next;
2784 	uint8_t opt, len, pointer;
2785 
2786 	/*
2787 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2788 	 * has been corrupted.
2789 	 */
2790 	ASSERT(cur <= end);
2791 
2792 	if (cur == end)
2793 		return (IPOPT_EOL);
2794 
2795 	opt = cur[IPOPT_OPTVAL];
2796 
2797 	/*
2798 	 * Skip any NOP options.
2799 	 */
2800 	while (opt == IPOPT_NOP) {
2801 		cur++;
2802 		if (cur == end)
2803 			return (IPOPT_EOL);
2804 		opt = cur[IPOPT_OPTVAL];
2805 	}
2806 
2807 	if (opt == IPOPT_EOL)
2808 		return (IPOPT_EOL);
2809 
2810 	/*
2811 	 * Option requiring a length.
2812 	 */
2813 	if ((cur + 1) >= end) {
2814 		optp->ipoptp_flags |= IPOPTP_ERROR;
2815 		return (IPOPT_EOL);
2816 	}
2817 	len = cur[IPOPT_OLEN];
2818 	if (len < 2) {
2819 		optp->ipoptp_flags |= IPOPTP_ERROR;
2820 		return (IPOPT_EOL);
2821 	}
2822 	optp->ipoptp_cur = cur;
2823 	optp->ipoptp_len = len;
2824 	optp->ipoptp_next = cur + len;
2825 	if (cur + len > end) {
2826 		optp->ipoptp_flags |= IPOPTP_ERROR;
2827 		return (IPOPT_EOL);
2828 	}
2829 
2830 	/*
2831 	 * For the options which require a pointer field, make sure
2832 	 * its there, and make sure it points to either something
2833 	 * inside this option, or the end of the option.
2834 	 */
2835 	switch (opt) {
2836 	case IPOPT_RR:
2837 	case IPOPT_TS:
2838 	case IPOPT_LSRR:
2839 	case IPOPT_SSRR:
2840 		if (len <= IPOPT_OFFSET) {
2841 			optp->ipoptp_flags |= IPOPTP_ERROR;
2842 			return (opt);
2843 		}
2844 		pointer = cur[IPOPT_OFFSET];
2845 		if (pointer - 1 > len) {
2846 			optp->ipoptp_flags |= IPOPTP_ERROR;
2847 			return (opt);
2848 		}
2849 		break;
2850 	}
2851 
2852 	/*
2853 	 * Sanity check the pointer field based on the type of the
2854 	 * option.
2855 	 */
2856 	switch (opt) {
2857 	case IPOPT_RR:
2858 	case IPOPT_SSRR:
2859 	case IPOPT_LSRR:
2860 		if (pointer < IPOPT_MINOFF_SR)
2861 			optp->ipoptp_flags |= IPOPTP_ERROR;
2862 		break;
2863 	case IPOPT_TS:
2864 		if (pointer < IPOPT_MINOFF_IT)
2865 			optp->ipoptp_flags |= IPOPTP_ERROR;
2866 		/*
2867 		 * Note that the Internet Timestamp option also
2868 		 * contains two four bit fields (the Overflow field,
2869 		 * and the Flag field), which follow the pointer
2870 		 * field.  We don't need to check that these fields
2871 		 * fall within the length of the option because this
2872 		 * was implicitely done above.  We've checked that the
2873 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2874 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2875 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2876 		 */
2877 		ASSERT(len > IPOPT_POS_OV_FLG);
2878 		break;
2879 	}
2880 
2881 	return (opt);
2882 }
2883 
2884 /*
2885  * Use the outgoing IP header to create an IP_OPTIONS option the way
2886  * it was passed down from the application.
2887  */
2888 int
2889 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2890 {
2891 	ipoptp_t	opts;
2892 	const uchar_t	*opt;
2893 	uint8_t		optval;
2894 	uint8_t		optlen;
2895 	uint32_t	len = 0;
2896 	uchar_t	*buf1 = buf;
2897 
2898 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2899 	len += IP_ADDR_LEN;
2900 	bzero(buf1, IP_ADDR_LEN);
2901 
2902 	/*
2903 	 * OK to cast away const here, as we don't store through the returned
2904 	 * opts.ipoptp_cur pointer.
2905 	 */
2906 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2907 	    optval != IPOPT_EOL;
2908 	    optval = ipoptp_next(&opts)) {
2909 		int	off;
2910 
2911 		opt = opts.ipoptp_cur;
2912 		optlen = opts.ipoptp_len;
2913 		switch (optval) {
2914 		case IPOPT_SSRR:
2915 		case IPOPT_LSRR:
2916 
2917 			/*
2918 			 * Insert ipha_dst as the first entry in the source
2919 			 * route and move down the entries on step.
2920 			 * The last entry gets placed at buf1.
2921 			 */
2922 			buf[IPOPT_OPTVAL] = optval;
2923 			buf[IPOPT_OLEN] = optlen;
2924 			buf[IPOPT_OFFSET] = optlen;
2925 
2926 			off = optlen - IP_ADDR_LEN;
2927 			if (off < 0) {
2928 				/* No entries in source route */
2929 				break;
2930 			}
2931 			/* Last entry in source route */
2932 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2933 			off -= IP_ADDR_LEN;
2934 
2935 			while (off > 0) {
2936 				bcopy(opt + off,
2937 				    buf + off + IP_ADDR_LEN,
2938 				    IP_ADDR_LEN);
2939 				off -= IP_ADDR_LEN;
2940 			}
2941 			/* ipha_dst into first slot */
2942 			bcopy(&ipha->ipha_dst,
2943 			    buf + off + IP_ADDR_LEN,
2944 			    IP_ADDR_LEN);
2945 			buf += optlen;
2946 			len += optlen;
2947 			break;
2948 
2949 		case IPOPT_COMSEC:
2950 		case IPOPT_SECURITY:
2951 			/* if passing up a label is not ok, then remove */
2952 			if (is_system_labeled())
2953 				break;
2954 			/* FALLTHROUGH */
2955 		default:
2956 			bcopy(opt, buf, optlen);
2957 			buf += optlen;
2958 			len += optlen;
2959 			break;
2960 		}
2961 	}
2962 done:
2963 	/* Pad the resulting options */
2964 	while (len & 0x3) {
2965 		*buf++ = IPOPT_EOL;
2966 		len++;
2967 	}
2968 	return (len);
2969 }
2970 
2971 /*
2972  * Update any record route or timestamp options to include this host.
2973  * Reverse any source route option.
2974  * This routine assumes that the options are well formed i.e. that they
2975  * have already been checked.
2976  */
2977 static void
2978 icmp_options_update(ipha_t *ipha)
2979 {
2980 	ipoptp_t	opts;
2981 	uchar_t		*opt;
2982 	uint8_t		optval;
2983 	ipaddr_t	src;		/* Our local address */
2984 	ipaddr_t	dst;
2985 
2986 	ip2dbg(("icmp_options_update\n"));
2987 	src = ipha->ipha_src;
2988 	dst = ipha->ipha_dst;
2989 
2990 	for (optval = ipoptp_first(&opts, ipha);
2991 	    optval != IPOPT_EOL;
2992 	    optval = ipoptp_next(&opts)) {
2993 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2994 		opt = opts.ipoptp_cur;
2995 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2996 		    optval, opts.ipoptp_len));
2997 		switch (optval) {
2998 			int off1, off2;
2999 		case IPOPT_SSRR:
3000 		case IPOPT_LSRR:
3001 			/*
3002 			 * Reverse the source route.  The first entry
3003 			 * should be the next to last one in the current
3004 			 * source route (the last entry is our address).
3005 			 * The last entry should be the final destination.
3006 			 */
3007 			off1 = IPOPT_MINOFF_SR - 1;
3008 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3009 			if (off2 < 0) {
3010 				/* No entries in source route */
3011 				ip1dbg((
3012 				    "icmp_options_update: bad src route\n"));
3013 				break;
3014 			}
3015 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3016 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3017 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3018 			off2 -= IP_ADDR_LEN;
3019 
3020 			while (off1 < off2) {
3021 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3022 				bcopy((char *)opt + off2, (char *)opt + off1,
3023 				    IP_ADDR_LEN);
3024 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3025 				off1 += IP_ADDR_LEN;
3026 				off2 -= IP_ADDR_LEN;
3027 			}
3028 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3029 			break;
3030 		}
3031 	}
3032 }
3033 
3034 /*
3035  * Process received ICMP Redirect messages.
3036  */
3037 static void
3038 icmp_redirect(ill_t *ill, mblk_t *mp)
3039 {
3040 	ipha_t	*ipha;
3041 	int	iph_hdr_length;
3042 	icmph_t	*icmph;
3043 	ipha_t	*ipha_err;
3044 	ire_t	*ire;
3045 	ire_t	*prev_ire;
3046 	ire_t	*save_ire;
3047 	ipaddr_t  src, dst, gateway;
3048 	iulp_t	ulp_info = { 0 };
3049 	int	error;
3050 	ip_stack_t *ipst;
3051 
3052 	ASSERT(ill != NULL);
3053 	ipst = ill->ill_ipst;
3054 
3055 	ipha = (ipha_t *)mp->b_rptr;
3056 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3057 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3058 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3059 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3060 		freemsg(mp);
3061 		return;
3062 	}
3063 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3064 	ipha_err = (ipha_t *)&icmph[1];
3065 	src = ipha->ipha_src;
3066 	dst = ipha_err->ipha_dst;
3067 	gateway = icmph->icmph_rd_gateway;
3068 	/* Make sure the new gateway is reachable somehow. */
3069 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3070 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3071 	/*
3072 	 * Make sure we had a route for the dest in question and that
3073 	 * that route was pointing to the old gateway (the source of the
3074 	 * redirect packet.)
3075 	 */
3076 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3077 	    NULL, MATCH_IRE_GW, ipst);
3078 	/*
3079 	 * Check that
3080 	 *	the redirect was not from ourselves
3081 	 *	the new gateway and the old gateway are directly reachable
3082 	 */
3083 	if (!prev_ire ||
3084 	    !ire ||
3085 	    ire->ire_type == IRE_LOCAL) {
3086 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3087 		freemsg(mp);
3088 		if (ire != NULL)
3089 			ire_refrele(ire);
3090 		if (prev_ire != NULL)
3091 			ire_refrele(prev_ire);
3092 		return;
3093 	}
3094 
3095 	/*
3096 	 * Should we use the old ULP info to create the new gateway?  From
3097 	 * a user's perspective, we should inherit the info so that it
3098 	 * is a "smooth" transition.  If we do not do that, then new
3099 	 * connections going thru the new gateway will have no route metrics,
3100 	 * which is counter-intuitive to user.  From a network point of
3101 	 * view, this may or may not make sense even though the new gateway
3102 	 * is still directly connected to us so the route metrics should not
3103 	 * change much.
3104 	 *
3105 	 * But if the old ire_uinfo is not initialized, we do another
3106 	 * recursive lookup on the dest using the new gateway.  There may
3107 	 * be a route to that.  If so, use it to initialize the redirect
3108 	 * route.
3109 	 */
3110 	if (prev_ire->ire_uinfo.iulp_set) {
3111 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3112 	} else {
3113 		ire_t *tmp_ire;
3114 		ire_t *sire;
3115 
3116 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3117 		    ALL_ZONES, 0, NULL,
3118 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3119 		    ipst);
3120 		if (sire != NULL) {
3121 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3122 			/*
3123 			 * If sire != NULL, ire_ftable_lookup() should not
3124 			 * return a NULL value.
3125 			 */
3126 			ASSERT(tmp_ire != NULL);
3127 			ire_refrele(tmp_ire);
3128 			ire_refrele(sire);
3129 		} else if (tmp_ire != NULL) {
3130 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3131 			    sizeof (iulp_t));
3132 			ire_refrele(tmp_ire);
3133 		}
3134 	}
3135 	if (prev_ire->ire_type == IRE_CACHE)
3136 		ire_delete(prev_ire);
3137 	ire_refrele(prev_ire);
3138 	/*
3139 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3140 	 * require TOS routing
3141 	 */
3142 	switch (icmph->icmph_code) {
3143 	case 0:
3144 	case 1:
3145 		/* TODO: TOS specificity for cases 2 and 3 */
3146 	case 2:
3147 	case 3:
3148 		break;
3149 	default:
3150 		freemsg(mp);
3151 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3152 		ire_refrele(ire);
3153 		return;
3154 	}
3155 	/*
3156 	 * Create a Route Association.  This will allow us to remember that
3157 	 * someone we believe told us to use the particular gateway.
3158 	 */
3159 	save_ire = ire;
3160 	ire = ire_create(
3161 	    (uchar_t *)&dst,			/* dest addr */
3162 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3163 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3164 	    (uchar_t *)&gateway,		/* gateway addr */
3165 	    NULL,				/* no in_srcaddr */
3166 	    &save_ire->ire_max_frag,		/* max frag */
3167 	    NULL,				/* no src nce */
3168 	    NULL,				/* no rfq */
3169 	    NULL,				/* no stq */
3170 	    IRE_HOST,
3171 	    NULL,				/* ipif */
3172 	    NULL,				/* in_ill */
3173 	    0,					/* cmask */
3174 	    0,					/* phandle */
3175 	    0,					/* ihandle */
3176 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3177 	    &ulp_info,
3178 	    NULL,				/* tsol_gc_t */
3179 	    NULL,				/* gcgrp */
3180 	    ipst);
3181 
3182 	if (ire == NULL) {
3183 		freemsg(mp);
3184 		ire_refrele(save_ire);
3185 		return;
3186 	}
3187 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3188 	ire_refrele(save_ire);
3189 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3190 
3191 	if (error == 0) {
3192 		ire_refrele(ire);		/* Held in ire_add_v4 */
3193 		/* tell routing sockets that we received a redirect */
3194 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3195 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3196 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3197 	}
3198 
3199 	/*
3200 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3201 	 * This together with the added IRE has the effect of
3202 	 * modifying an existing redirect.
3203 	 */
3204 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3205 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3206 	if (prev_ire != NULL) {
3207 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3208 			ire_delete(prev_ire);
3209 		ire_refrele(prev_ire);
3210 	}
3211 
3212 	freemsg(mp);
3213 }
3214 
3215 /*
3216  * Generate an ICMP parameter problem message.
3217  */
3218 static void
3219 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3220 	ip_stack_t *ipst)
3221 {
3222 	icmph_t	icmph;
3223 	boolean_t mctl_present;
3224 	mblk_t *first_mp;
3225 
3226 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3227 
3228 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3229 		if (mctl_present)
3230 			freeb(first_mp);
3231 		return;
3232 	}
3233 
3234 	bzero(&icmph, sizeof (icmph_t));
3235 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3236 	icmph.icmph_pp_ptr = ptr;
3237 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3238 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3239 	    ipst);
3240 }
3241 
3242 /*
3243  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3244  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3245  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3246  * an icmp error packet can be sent.
3247  * Assigns an appropriate source address to the packet. If ipha_dst is
3248  * one of our addresses use it for source. Otherwise pick a source based
3249  * on a route lookup back to ipha_src.
3250  * Note that ipha_src must be set here since the
3251  * packet is likely to arrive on an ill queue in ip_wput() which will
3252  * not set a source address.
3253  */
3254 static void
3255 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3256     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3257 {
3258 	ipaddr_t dst;
3259 	icmph_t	*icmph;
3260 	ipha_t	*ipha;
3261 	uint_t	len_needed;
3262 	size_t	msg_len;
3263 	mblk_t	*mp1;
3264 	ipaddr_t src;
3265 	ire_t	*ire;
3266 	mblk_t *ipsec_mp;
3267 	ipsec_out_t	*io = NULL;
3268 	boolean_t xmit_if_on = B_FALSE;
3269 
3270 	if (mctl_present) {
3271 		/*
3272 		 * If it is :
3273 		 *
3274 		 * 1) a IPSEC_OUT, then this is caused by outbound
3275 		 *    datagram originating on this host. IPSEC processing
3276 		 *    may or may not have been done. Refer to comments above
3277 		 *    icmp_inbound_error_fanout for details.
3278 		 *
3279 		 * 2) a IPSEC_IN if we are generating a icmp_message
3280 		 *    for an incoming datagram destined for us i.e called
3281 		 *    from ip_fanout_send_icmp.
3282 		 */
3283 		ipsec_info_t *in;
3284 		ipsec_mp = mp;
3285 		mp = ipsec_mp->b_cont;
3286 
3287 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3288 		ipha = (ipha_t *)mp->b_rptr;
3289 
3290 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3291 		    in->ipsec_info_type == IPSEC_IN);
3292 
3293 		if (in->ipsec_info_type == IPSEC_IN) {
3294 			/*
3295 			 * Convert the IPSEC_IN to IPSEC_OUT.
3296 			 */
3297 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3298 				BUMP_MIB(&ipst->ips_ip_mib,
3299 				    ipIfStatsOutDiscards);
3300 				return;
3301 			}
3302 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3303 		} else {
3304 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3305 			io = (ipsec_out_t *)in;
3306 			if (io->ipsec_out_xmit_if)
3307 				xmit_if_on = B_TRUE;
3308 			/*
3309 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3310 			 * ire lookup.
3311 			 */
3312 			io->ipsec_out_proc_begin = B_FALSE;
3313 		}
3314 		ASSERT(zoneid == io->ipsec_out_zoneid);
3315 		ASSERT(zoneid != ALL_ZONES);
3316 	} else {
3317 		/*
3318 		 * This is in clear. The icmp message we are building
3319 		 * here should go out in clear.
3320 		 *
3321 		 * Pardon the convolution of it all, but it's easier to
3322 		 * allocate a "use cleartext" IPSEC_IN message and convert
3323 		 * it than it is to allocate a new one.
3324 		 */
3325 		ipsec_in_t *ii;
3326 		ASSERT(DB_TYPE(mp) == M_DATA);
3327 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3328 		if (ipsec_mp == NULL) {
3329 			freemsg(mp);
3330 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3331 			return;
3332 		}
3333 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3334 
3335 		/* This is not a secure packet */
3336 		ii->ipsec_in_secure = B_FALSE;
3337 		/*
3338 		 * For trusted extensions using a shared IP address we can
3339 		 * send using any zoneid.
3340 		 */
3341 		if (zoneid == ALL_ZONES)
3342 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3343 		else
3344 			ii->ipsec_in_zoneid = zoneid;
3345 		ipsec_mp->b_cont = mp;
3346 		ipha = (ipha_t *)mp->b_rptr;
3347 		/*
3348 		 * Convert the IPSEC_IN to IPSEC_OUT.
3349 		 */
3350 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3351 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3352 			return;
3353 		}
3354 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3355 	}
3356 
3357 	/* Remember our eventual destination */
3358 	dst = ipha->ipha_src;
3359 
3360 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3361 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3362 	if (ire != NULL &&
3363 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3364 		src = ipha->ipha_dst;
3365 	} else if (!xmit_if_on) {
3366 		if (ire != NULL)
3367 			ire_refrele(ire);
3368 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3369 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3370 		    ipst);
3371 		if (ire == NULL) {
3372 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3373 			freemsg(ipsec_mp);
3374 			return;
3375 		}
3376 		src = ire->ire_src_addr;
3377 	} else {
3378 		ipif_t	*ipif = NULL;
3379 		ill_t	*ill;
3380 		/*
3381 		 * This must be an ICMP error coming from
3382 		 * ip_mrtun_forward(). The src addr should
3383 		 * be equal to the IP-addr of the outgoing
3384 		 * interface.
3385 		 */
3386 		if (io == NULL) {
3387 			/* This is not a IPSEC_OUT type control msg */
3388 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3389 			freemsg(ipsec_mp);
3390 			return;
3391 		}
3392 		ill = ill_lookup_on_ifindex(io->ipsec_out_ill_index, B_FALSE,
3393 		    NULL, NULL, NULL, NULL, ipst);
3394 		if (ill != NULL) {
3395 			ipif = ipif_get_next_ipif(NULL, ill);
3396 			ill_refrele(ill);
3397 		}
3398 		if (ipif == NULL) {
3399 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3400 			freemsg(ipsec_mp);
3401 			return;
3402 		}
3403 		src = ipif->ipif_src_addr;
3404 		ipif_refrele(ipif);
3405 	}
3406 
3407 	if (ire != NULL)
3408 		ire_refrele(ire);
3409 
3410 	/*
3411 	 * Check if we can send back more then 8 bytes in addition to
3412 	 * the IP header.  We try to send 64 bytes of data and the internal
3413 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3414 	 */
3415 	len_needed = IPH_HDR_LENGTH(ipha);
3416 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3417 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3418 
3419 		if (!pullupmsg(mp, -1)) {
3420 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3421 			freemsg(ipsec_mp);
3422 			return;
3423 		}
3424 		ipha = (ipha_t *)mp->b_rptr;
3425 
3426 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3427 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3428 			    len_needed));
3429 		} else {
3430 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3431 
3432 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3433 			len_needed += ip_hdr_length_v6(mp, ip6h);
3434 		}
3435 	}
3436 	len_needed += ipst->ips_ip_icmp_return;
3437 	msg_len = msgdsize(mp);
3438 	if (msg_len > len_needed) {
3439 		(void) adjmsg(mp, len_needed - msg_len);
3440 		msg_len = len_needed;
3441 	}
3442 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3443 	if (mp1 == NULL) {
3444 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3445 		freemsg(ipsec_mp);
3446 		return;
3447 	}
3448 	mp1->b_cont = mp;
3449 	mp = mp1;
3450 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3451 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3452 	    io->ipsec_out_type == IPSEC_OUT);
3453 	ipsec_mp->b_cont = mp;
3454 
3455 	/*
3456 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3457 	 * node generates be accepted in peace by all on-host destinations.
3458 	 * If we do NOT assume that all on-host destinations trust
3459 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3460 	 * (Look for ipsec_out_icmp_loopback).
3461 	 */
3462 	io->ipsec_out_icmp_loopback = B_TRUE;
3463 
3464 	ipha = (ipha_t *)mp->b_rptr;
3465 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3466 	*ipha = icmp_ipha;
3467 	ipha->ipha_src = src;
3468 	ipha->ipha_dst = dst;
3469 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3470 	msg_len += sizeof (icmp_ipha) + len;
3471 	if (msg_len > IP_MAXPACKET) {
3472 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3473 		msg_len = IP_MAXPACKET;
3474 	}
3475 	ipha->ipha_length = htons((uint16_t)msg_len);
3476 	icmph = (icmph_t *)&ipha[1];
3477 	bcopy(stuff, icmph, len);
3478 	icmph->icmph_checksum = 0;
3479 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3480 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3481 	put(q, ipsec_mp);
3482 }
3483 
3484 /*
3485  * Determine if an ICMP error packet can be sent given the rate limit.
3486  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3487  * in milliseconds) and a burst size. Burst size number of packets can
3488  * be sent arbitrarely closely spaced.
3489  * The state is tracked using two variables to implement an approximate
3490  * token bucket filter:
3491  *	icmp_pkt_err_last - lbolt value when the last burst started
3492  *	icmp_pkt_err_sent - number of packets sent in current burst
3493  */
3494 boolean_t
3495 icmp_err_rate_limit(ip_stack_t *ipst)
3496 {
3497 	clock_t now = TICK_TO_MSEC(lbolt);
3498 	uint_t refilled; /* Number of packets refilled in tbf since last */
3499 	/* Guard against changes by loading into local variable */
3500 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3501 
3502 	if (err_interval == 0)
3503 		return (B_FALSE);
3504 
3505 	if (ipst->ips_icmp_pkt_err_last > now) {
3506 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3507 		ipst->ips_icmp_pkt_err_last = 0;
3508 		ipst->ips_icmp_pkt_err_sent = 0;
3509 	}
3510 	/*
3511 	 * If we are in a burst update the token bucket filter.
3512 	 * Update the "last" time to be close to "now" but make sure
3513 	 * we don't loose precision.
3514 	 */
3515 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3516 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3517 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3518 			ipst->ips_icmp_pkt_err_sent = 0;
3519 		} else {
3520 			ipst->ips_icmp_pkt_err_sent -= refilled;
3521 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3522 		}
3523 	}
3524 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3525 		/* Start of new burst */
3526 		ipst->ips_icmp_pkt_err_last = now;
3527 	}
3528 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3529 		ipst->ips_icmp_pkt_err_sent++;
3530 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3531 		    ipst->ips_icmp_pkt_err_sent));
3532 		return (B_FALSE);
3533 	}
3534 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3535 	return (B_TRUE);
3536 }
3537 
3538 /*
3539  * Check if it is ok to send an IPv4 ICMP error packet in
3540  * response to the IPv4 packet in mp.
3541  * Free the message and return null if no
3542  * ICMP error packet should be sent.
3543  */
3544 static mblk_t *
3545 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3546 {
3547 	icmph_t	*icmph;
3548 	ipha_t	*ipha;
3549 	uint_t	len_needed;
3550 	ire_t	*src_ire;
3551 	ire_t	*dst_ire;
3552 
3553 	if (!mp)
3554 		return (NULL);
3555 	ipha = (ipha_t *)mp->b_rptr;
3556 	if (ip_csum_hdr(ipha)) {
3557 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3558 		freemsg(mp);
3559 		return (NULL);
3560 	}
3561 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3562 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3563 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3564 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3565 	if (src_ire != NULL || dst_ire != NULL ||
3566 	    CLASSD(ipha->ipha_dst) ||
3567 	    CLASSD(ipha->ipha_src) ||
3568 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3569 		/* Note: only errors to the fragment with offset 0 */
3570 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3571 		freemsg(mp);
3572 		if (src_ire != NULL)
3573 			ire_refrele(src_ire);
3574 		if (dst_ire != NULL)
3575 			ire_refrele(dst_ire);
3576 		return (NULL);
3577 	}
3578 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3579 		/*
3580 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3581 		 * errors in response to any ICMP errors.
3582 		 */
3583 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3584 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3585 			if (!pullupmsg(mp, len_needed)) {
3586 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3587 				freemsg(mp);
3588 				return (NULL);
3589 			}
3590 			ipha = (ipha_t *)mp->b_rptr;
3591 		}
3592 		icmph = (icmph_t *)
3593 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3594 		switch (icmph->icmph_type) {
3595 		case ICMP_DEST_UNREACHABLE:
3596 		case ICMP_SOURCE_QUENCH:
3597 		case ICMP_TIME_EXCEEDED:
3598 		case ICMP_PARAM_PROBLEM:
3599 		case ICMP_REDIRECT:
3600 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3601 			freemsg(mp);
3602 			return (NULL);
3603 		default:
3604 			break;
3605 		}
3606 	}
3607 	/*
3608 	 * If this is a labeled system, then check to see if we're allowed to
3609 	 * send a response to this particular sender.  If not, then just drop.
3610 	 */
3611 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3612 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3613 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3614 		freemsg(mp);
3615 		return (NULL);
3616 	}
3617 	if (icmp_err_rate_limit(ipst)) {
3618 		/*
3619 		 * Only send ICMP error packets every so often.
3620 		 * This should be done on a per port/source basis,
3621 		 * but for now this will suffice.
3622 		 */
3623 		freemsg(mp);
3624 		return (NULL);
3625 	}
3626 	return (mp);
3627 }
3628 
3629 /*
3630  * Generate an ICMP redirect message.
3631  */
3632 static void
3633 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3634 {
3635 	icmph_t	icmph;
3636 
3637 	/*
3638 	 * We are called from ip_rput where we could
3639 	 * not have attached an IPSEC_IN.
3640 	 */
3641 	ASSERT(mp->b_datap->db_type == M_DATA);
3642 
3643 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3644 		return;
3645 	}
3646 
3647 	bzero(&icmph, sizeof (icmph_t));
3648 	icmph.icmph_type = ICMP_REDIRECT;
3649 	icmph.icmph_code = 1;
3650 	icmph.icmph_rd_gateway = gateway;
3651 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3652 	/* Redirects sent by router, and router is global zone */
3653 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3654 }
3655 
3656 /*
3657  * Generate an ICMP time exceeded message.
3658  */
3659 void
3660 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3661     ip_stack_t *ipst)
3662 {
3663 	icmph_t	icmph;
3664 	boolean_t mctl_present;
3665 	mblk_t *first_mp;
3666 
3667 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3668 
3669 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3670 		if (mctl_present)
3671 			freeb(first_mp);
3672 		return;
3673 	}
3674 
3675 	bzero(&icmph, sizeof (icmph_t));
3676 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3677 	icmph.icmph_code = code;
3678 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3679 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3680 	    ipst);
3681 }
3682 
3683 /*
3684  * Generate an ICMP unreachable message.
3685  */
3686 void
3687 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3688     ip_stack_t *ipst)
3689 {
3690 	icmph_t	icmph;
3691 	mblk_t *first_mp;
3692 	boolean_t mctl_present;
3693 
3694 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3695 
3696 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3697 		if (mctl_present)
3698 			freeb(first_mp);
3699 		return;
3700 	}
3701 
3702 	bzero(&icmph, sizeof (icmph_t));
3703 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3704 	icmph.icmph_code = code;
3705 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3706 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3707 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3708 	    zoneid, ipst);
3709 }
3710 
3711 /*
3712  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3713  * duplicate.  As long as someone else holds the address, the interface will
3714  * stay down.  When that conflict goes away, the interface is brought back up.
3715  * This is done so that accidental shutdowns of addresses aren't made
3716  * permanent.  Your server will recover from a failure.
3717  *
3718  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3719  * user space process (dhcpagent).
3720  *
3721  * Recovery completes if ARP reports that the address is now ours (via
3722  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3723  *
3724  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3725  */
3726 static void
3727 ipif_dup_recovery(void *arg)
3728 {
3729 	ipif_t *ipif = arg;
3730 	ill_t *ill = ipif->ipif_ill;
3731 	mblk_t *arp_add_mp;
3732 	mblk_t *arp_del_mp;
3733 	area_t *area;
3734 	ip_stack_t *ipst = ill->ill_ipst;
3735 
3736 	ipif->ipif_recovery_id = 0;
3737 
3738 	/*
3739 	 * No lock needed for moving or condemned check, as this is just an
3740 	 * optimization.
3741 	 */
3742 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3743 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3744 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3745 		/* No reason to try to bring this address back. */
3746 		return;
3747 	}
3748 
3749 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3750 		goto alloc_fail;
3751 
3752 	if (ipif->ipif_arp_del_mp == NULL) {
3753 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3754 			goto alloc_fail;
3755 		ipif->ipif_arp_del_mp = arp_del_mp;
3756 	}
3757 
3758 	/* Setting the 'unverified' flag restarts DAD */
3759 	area = (area_t *)arp_add_mp->b_rptr;
3760 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3761 	    ACE_F_UNVERIFIED;
3762 	putnext(ill->ill_rq, arp_add_mp);
3763 	return;
3764 
3765 alloc_fail:
3766 	/*
3767 	 * On allocation failure, just restart the timer.  Note that the ipif
3768 	 * is down here, so no other thread could be trying to start a recovery
3769 	 * timer.  The ill_lock protects the condemned flag and the recovery
3770 	 * timer ID.
3771 	 */
3772 	freemsg(arp_add_mp);
3773 	mutex_enter(&ill->ill_lock);
3774 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3775 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3776 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3777 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3778 	}
3779 	mutex_exit(&ill->ill_lock);
3780 }
3781 
3782 /*
3783  * This is for exclusive changes due to ARP.  Either tear down an interface due
3784  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3785  */
3786 /* ARGSUSED */
3787 static void
3788 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3789 {
3790 	ill_t	*ill = rq->q_ptr;
3791 	arh_t *arh;
3792 	ipaddr_t src;
3793 	ipif_t	*ipif;
3794 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3795 	char hbuf[MAC_STR_LEN];
3796 	char sbuf[INET_ADDRSTRLEN];
3797 	const char *failtype;
3798 	boolean_t bring_up;
3799 	ip_stack_t *ipst = ill->ill_ipst;
3800 
3801 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3802 	case AR_CN_READY:
3803 		failtype = NULL;
3804 		bring_up = B_TRUE;
3805 		break;
3806 	case AR_CN_FAILED:
3807 		failtype = "in use";
3808 		bring_up = B_FALSE;
3809 		break;
3810 	default:
3811 		failtype = "claimed";
3812 		bring_up = B_FALSE;
3813 		break;
3814 	}
3815 
3816 	arh = (arh_t *)mp->b_cont->b_rptr;
3817 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3818 
3819 	/* Handle failures due to probes */
3820 	if (src == 0) {
3821 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3822 		    IP_ADDR_LEN);
3823 	}
3824 
3825 	(void) strlcpy(ibuf, ill->ill_name, sizeof (ibuf));
3826 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3827 	    sizeof (hbuf));
3828 	(void) ip_dot_addr(src, sbuf);
3829 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3830 
3831 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3832 		    ipif->ipif_lcl_addr != src) {
3833 			continue;
3834 		}
3835 
3836 		/*
3837 		 * If we failed on a recovery probe, then restart the timer to
3838 		 * try again later.
3839 		 */
3840 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3841 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3842 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3843 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3844 		    ipst->ips_ip_dup_recovery > 0 &&
3845 		    ipif->ipif_recovery_id == 0) {
3846 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3847 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3848 			continue;
3849 		}
3850 
3851 		/*
3852 		 * If what we're trying to do has already been done, then do
3853 		 * nothing.
3854 		 */
3855 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3856 			continue;
3857 
3858 		if (ipif->ipif_id != 0) {
3859 			(void) snprintf(ibuf + ill->ill_name_length - 1,
3860 			    sizeof (ibuf) - ill->ill_name_length + 1, ":%d",
3861 			    ipif->ipif_id);
3862 		}
3863 		if (failtype == NULL) {
3864 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3865 			    ibuf);
3866 		} else {
3867 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3868 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3869 		}
3870 
3871 		if (bring_up) {
3872 			ASSERT(ill->ill_dl_up);
3873 			/*
3874 			 * Free up the ARP delete message so we can allocate
3875 			 * a fresh one through the normal path.
3876 			 */
3877 			freemsg(ipif->ipif_arp_del_mp);
3878 			ipif->ipif_arp_del_mp = NULL;
3879 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3880 			    EINPROGRESS) {
3881 				ipif->ipif_addr_ready = 1;
3882 				(void) ipif_up_done(ipif);
3883 			}
3884 			continue;
3885 		}
3886 
3887 		mutex_enter(&ill->ill_lock);
3888 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3889 		ipif->ipif_flags |= IPIF_DUPLICATE;
3890 		ill->ill_ipif_dup_count++;
3891 		mutex_exit(&ill->ill_lock);
3892 		/*
3893 		 * Already exclusive on the ill; no need to handle deferred
3894 		 * processing here.
3895 		 */
3896 		(void) ipif_down(ipif, NULL, NULL);
3897 		ipif_down_tail(ipif);
3898 		mutex_enter(&ill->ill_lock);
3899 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3900 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3901 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3902 		    ipst->ips_ip_dup_recovery > 0) {
3903 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3904 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3905 		}
3906 		mutex_exit(&ill->ill_lock);
3907 	}
3908 	freemsg(mp);
3909 }
3910 
3911 /* ARGSUSED */
3912 static void
3913 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3914 {
3915 	ill_t	*ill = rq->q_ptr;
3916 	arh_t *arh;
3917 	ipaddr_t src;
3918 	ipif_t	*ipif;
3919 
3920 	arh = (arh_t *)mp->b_cont->b_rptr;
3921 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3922 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3923 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3924 			(void) ipif_resolver_up(ipif, Res_act_defend);
3925 	}
3926 	freemsg(mp);
3927 }
3928 
3929 /*
3930  * News from ARP.  ARP sends notification of interesting events down
3931  * to its clients using M_CTL messages with the interesting ARP packet
3932  * attached via b_cont.
3933  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3934  * queue as opposed to ARP sending the message to all the clients, i.e. all
3935  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3936  * table if a cache IRE is found to delete all the entries for the address in
3937  * the packet.
3938  */
3939 static void
3940 ip_arp_news(queue_t *q, mblk_t *mp)
3941 {
3942 	arcn_t		*arcn;
3943 	arh_t		*arh;
3944 	ire_t		*ire = NULL;
3945 	char		hbuf[MAC_STR_LEN];
3946 	char		sbuf[INET_ADDRSTRLEN];
3947 	ipaddr_t	src;
3948 	in6_addr_t	v6src;
3949 	boolean_t	isv6 = B_FALSE;
3950 	ipif_t		*ipif;
3951 	ill_t		*ill;
3952 	ip_stack_t	*ipst;
3953 
3954 	if (CONN_Q(q)) {
3955 		conn_t *connp = Q_TO_CONN(q);
3956 
3957 		ipst = connp->conn_netstack->netstack_ip;
3958 	} else {
3959 		ill_t *ill = (ill_t *)q->q_ptr;
3960 
3961 		ipst = ill->ill_ipst;
3962 	}
3963 
3964 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3965 		if (q->q_next) {
3966 			putnext(q, mp);
3967 		} else
3968 			freemsg(mp);
3969 		return;
3970 	}
3971 	arh = (arh_t *)mp->b_cont->b_rptr;
3972 	/* Is it one we are interested in? */
3973 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3974 		isv6 = B_TRUE;
3975 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3976 		    IPV6_ADDR_LEN);
3977 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3978 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3979 		    IP_ADDR_LEN);
3980 	} else {
3981 		freemsg(mp);
3982 		return;
3983 	}
3984 
3985 	ill = q->q_ptr;
3986 
3987 	arcn = (arcn_t *)mp->b_rptr;
3988 	switch (arcn->arcn_code) {
3989 	case AR_CN_BOGON:
3990 		/*
3991 		 * Someone is sending ARP packets with a source protocol
3992 		 * address that we have published and for which we believe our
3993 		 * entry is authoritative and (when ill_arp_extend is set)
3994 		 * verified to be unique on the network.
3995 		 *
3996 		 * The ARP module internally handles the cases where the sender
3997 		 * is just probing (for DAD) and where the hardware address of
3998 		 * a non-authoritative entry has changed.  Thus, these are the
3999 		 * real conflicts, and we have to do resolution.
4000 		 *
4001 		 * We back away quickly from the address if it's from DHCP or
4002 		 * otherwise temporary and hasn't been used recently (or at
4003 		 * all).  We'd like to include "deprecated" addresses here as
4004 		 * well (as there's no real reason to defend something we're
4005 		 * discarding), but IPMP "reuses" this flag to mean something
4006 		 * other than the standard meaning.
4007 		 *
4008 		 * If the ARP module above is not extended (meaning that it
4009 		 * doesn't know how to defend the address), then we just log
4010 		 * the problem as we always did and continue on.  It's not
4011 		 * right, but there's little else we can do, and those old ATM
4012 		 * users are going away anyway.
4013 		 */
4014 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
4015 		    hbuf, sizeof (hbuf));
4016 		(void) ip_dot_addr(src, sbuf);
4017 		if (isv6) {
4018 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
4019 			    ipst);
4020 		} else {
4021 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4022 		}
4023 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4024 			uint32_t now;
4025 			uint32_t maxage;
4026 			clock_t lused;
4027 			uint_t maxdefense;
4028 			uint_t defs;
4029 
4030 			/*
4031 			 * First, figure out if this address hasn't been used
4032 			 * in a while.  If it hasn't, then it's a better
4033 			 * candidate for abandoning.
4034 			 */
4035 			ipif = ire->ire_ipif;
4036 			ASSERT(ipif != NULL);
4037 			now = gethrestime_sec();
4038 			maxage = now - ire->ire_create_time;
4039 			if (maxage > ipst->ips_ip_max_temp_idle)
4040 				maxage = ipst->ips_ip_max_temp_idle;
4041 			lused = drv_hztousec(ddi_get_lbolt() -
4042 			    ire->ire_last_used_time) / MICROSEC + 1;
4043 			if (lused >= maxage && (ipif->ipif_flags &
4044 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4045 				maxdefense = ipst->ips_ip_max_temp_defend;
4046 			else
4047 				maxdefense = ipst->ips_ip_max_defend;
4048 
4049 			/*
4050 			 * Now figure out how many times we've defended
4051 			 * ourselves.  Ignore defenses that happened long in
4052 			 * the past.
4053 			 */
4054 			mutex_enter(&ire->ire_lock);
4055 			if ((defs = ire->ire_defense_count) > 0 &&
4056 			    now - ire->ire_defense_time >
4057 			    ipst->ips_ip_defend_interval) {
4058 				ire->ire_defense_count = defs = 0;
4059 			}
4060 			ire->ire_defense_count++;
4061 			ire->ire_defense_time = now;
4062 			mutex_exit(&ire->ire_lock);
4063 			ill_refhold(ill);
4064 			ire_refrele(ire);
4065 
4066 			/*
4067 			 * If we've defended ourselves too many times already,
4068 			 * then give up and tear down the interface(s) using
4069 			 * this address.  Otherwise, defend by sending out a
4070 			 * gratuitous ARP.
4071 			 */
4072 			if (defs >= maxdefense && ill->ill_arp_extend) {
4073 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4074 				    B_FALSE);
4075 			} else {
4076 				cmn_err(CE_WARN,
4077 				    "node %s is using our IP address %s on %s",
4078 				    hbuf, sbuf, ill->ill_name);
4079 				/*
4080 				 * If this is an old (ATM) ARP module, then
4081 				 * don't try to defend the address.  Remain
4082 				 * compatible with the old behavior.  Defend
4083 				 * only with new ARP.
4084 				 */
4085 				if (ill->ill_arp_extend) {
4086 					qwriter_ip(ill, q, mp, ip_arp_defend,
4087 					    NEW_OP, B_FALSE);
4088 				} else {
4089 					ill_refrele(ill);
4090 				}
4091 			}
4092 			return;
4093 		}
4094 		cmn_err(CE_WARN,
4095 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4096 		    hbuf, sbuf, ill->ill_name);
4097 		if (ire != NULL)
4098 			ire_refrele(ire);
4099 		break;
4100 	case AR_CN_ANNOUNCE:
4101 		if (isv6) {
4102 			/*
4103 			 * For XRESOLV interfaces.
4104 			 * Delete the IRE cache entry and NCE for this
4105 			 * v6 address
4106 			 */
4107 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4108 			/*
4109 			 * If v6src is a non-zero, it's a router address
4110 			 * as below. Do the same sort of thing to clean
4111 			 * out off-net IRE_CACHE entries that go through
4112 			 * the router.
4113 			 */
4114 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4115 				ire_walk_v6(ire_delete_cache_gw_v6,
4116 				    (char *)&v6src, ALL_ZONES, ipst);
4117 			}
4118 		} else {
4119 			nce_hw_map_t hwm;
4120 
4121 			/*
4122 			 * ARP gives us a copy of any packet where it thinks
4123 			 * the address has changed, so that we can update our
4124 			 * caches.  We're responsible for caching known answers
4125 			 * in the current design.  We check whether the
4126 			 * hardware address really has changed in all of our
4127 			 * entries that have cached this mapping, and if so, we
4128 			 * blow them away.  This way we will immediately pick
4129 			 * up the rare case of a host changing hardware
4130 			 * address.
4131 			 */
4132 			if (src == 0)
4133 				break;
4134 			hwm.hwm_addr = src;
4135 			hwm.hwm_hwlen = arh->arh_hlen;
4136 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4137 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4138 			ndp_walk_common(ipst->ips_ndp4, NULL,
4139 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4140 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4141 		}
4142 		break;
4143 	case AR_CN_READY:
4144 		/* No external v6 resolver has a contract to use this */
4145 		if (isv6)
4146 			break;
4147 		/* If the link is down, we'll retry this later */
4148 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4149 			break;
4150 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4151 		    NULL, NULL, ipst);
4152 		if (ipif != NULL) {
4153 			/*
4154 			 * If this is a duplicate recovery, then we now need to
4155 			 * go exclusive to bring this thing back up.
4156 			 */
4157 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4158 			    IPIF_DUPLICATE) {
4159 				ipif_refrele(ipif);
4160 				ill_refhold(ill);
4161 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4162 				    B_FALSE);
4163 				return;
4164 			}
4165 			/*
4166 			 * If this is the first notice that this address is
4167 			 * ready, then let the user know now.
4168 			 */
4169 			if ((ipif->ipif_flags & IPIF_UP) &&
4170 			    !ipif->ipif_addr_ready) {
4171 				ipif_mask_reply(ipif);
4172 				ip_rts_ifmsg(ipif);
4173 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4174 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4175 			}
4176 			ipif->ipif_addr_ready = 1;
4177 			ipif_refrele(ipif);
4178 		}
4179 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4180 		if (ire != NULL) {
4181 			ire->ire_defense_count = 0;
4182 			ire_refrele(ire);
4183 		}
4184 		break;
4185 	case AR_CN_FAILED:
4186 		/* No external v6 resolver has a contract to use this */
4187 		if (isv6)
4188 			break;
4189 		ill_refhold(ill);
4190 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4191 		return;
4192 	}
4193 	freemsg(mp);
4194 }
4195 
4196 /*
4197  * Create a mblk suitable for carrying the interface index and/or source link
4198  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4199  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4200  * application.
4201  */
4202 mblk_t *
4203 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4204     ip_stack_t *ipst)
4205 {
4206 	mblk_t		*mp;
4207 	ip_pktinfo_t	*pinfo;
4208 	ipha_t *ipha;
4209 	struct ether_header *pether;
4210 
4211 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4212 	if (mp == NULL) {
4213 		ip1dbg(("ip_add_info: allocation failure.\n"));
4214 		return (data_mp);
4215 	}
4216 
4217 	ipha	= (ipha_t *)data_mp->b_rptr;
4218 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4219 	bzero(pinfo, sizeof (ip_pktinfo_t));
4220 	pinfo->ip_pkt_flags = (uchar_t)flags;
4221 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4222 
4223 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4224 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4225 	if (flags & IPF_RECVADDR) {
4226 		ipif_t	*ipif;
4227 		ire_t	*ire;
4228 
4229 		/*
4230 		 * Only valid for V4
4231 		 */
4232 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4233 		    (IPV4_VERSION << 4));
4234 
4235 		ipif = ipif_get_next_ipif(NULL, ill);
4236 		if (ipif != NULL) {
4237 			/*
4238 			 * Since a decision has already been made to deliver the
4239 			 * packet, there is no need to test for SECATTR and
4240 			 * ZONEONLY.
4241 			 * When a multicast packet is transmitted
4242 			 * a cache entry is created for the multicast address.
4243 			 * When delivering a copy of the packet or when new
4244 			 * packets are received we do not want to match on the
4245 			 * cached entry so explicitly match on
4246 			 * IRE_LOCAL and IRE_LOOPBACK
4247 			 */
4248 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4249 			    IRE_LOCAL | IRE_LOOPBACK,
4250 			    ipif, zoneid, NULL,
4251 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4252 			if (ire == NULL) {
4253 				/*
4254 				 * packet must have come on a different
4255 				 * interface.
4256 				 * Since a decision has already been made to
4257 				 * deliver the packet, there is no need to test
4258 				 * for SECATTR and ZONEONLY.
4259 				 * Only match on local and broadcast ire's.
4260 				 * See detailed comment above.
4261 				 */
4262 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4263 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4264 				    NULL, MATCH_IRE_TYPE, ipst);
4265 			}
4266 
4267 			if (ire == NULL) {
4268 				/*
4269 				 * This is either a multicast packet or
4270 				 * the address has been removed since
4271 				 * the packet was received.
4272 				 * Return INADDR_ANY so that normal source
4273 				 * selection occurs for the response.
4274 				 */
4275 
4276 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4277 			} else {
4278 				pinfo->ip_pkt_match_addr.s_addr =
4279 				    ire->ire_src_addr;
4280 				ire_refrele(ire);
4281 			}
4282 			ipif_refrele(ipif);
4283 		} else {
4284 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4285 		}
4286 	}
4287 
4288 	pether = (struct ether_header *)((char *)ipha
4289 	    - sizeof (struct ether_header));
4290 	/*
4291 	 * Make sure the interface is an ethernet type, since this option
4292 	 * is currently supported only on this type of interface. Also make
4293 	 * sure we are pointing correctly above db_base.
4294 	 */
4295 
4296 	if ((flags & IPF_RECVSLLA) &&
4297 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4298 	    (ill->ill_type == IFT_ETHER) &&
4299 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4300 
4301 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4302 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4303 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4304 	} else {
4305 		/*
4306 		 * Clear the bit. Indicate to upper layer that IP is not
4307 		 * sending this ancillary info.
4308 		 */
4309 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4310 	}
4311 
4312 	mp->b_datap->db_type = M_CTL;
4313 	mp->b_wptr += sizeof (ip_pktinfo_t);
4314 	mp->b_cont = data_mp;
4315 
4316 	return (mp);
4317 }
4318 
4319 /*
4320  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4321  * part of the bind request.
4322  */
4323 
4324 boolean_t
4325 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4326 {
4327 	ipsec_in_t *ii;
4328 
4329 	ASSERT(policy_mp != NULL);
4330 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4331 
4332 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4333 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4334 
4335 	connp->conn_policy = ii->ipsec_in_policy;
4336 	ii->ipsec_in_policy = NULL;
4337 
4338 	if (ii->ipsec_in_action != NULL) {
4339 		if (connp->conn_latch == NULL) {
4340 			connp->conn_latch = iplatch_create();
4341 			if (connp->conn_latch == NULL)
4342 				return (B_FALSE);
4343 		}
4344 		ipsec_latch_inbound(connp->conn_latch, ii);
4345 	}
4346 	return (B_TRUE);
4347 }
4348 
4349 /*
4350  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4351  * and to arrange for power-fanout assist.  The ULP is identified by
4352  * adding a single byte at the end of the original bind message.
4353  * A ULP other than UDP or TCP that wishes to be recognized passes
4354  * down a bind with a zero length address.
4355  *
4356  * The binding works as follows:
4357  * - A zero byte address means just bind to the protocol.
4358  * - A four byte address is treated as a request to validate
4359  *   that the address is a valid local address, appropriate for
4360  *   an application to bind to. This does not affect any fanout
4361  *   information in IP.
4362  * - A sizeof sin_t byte address is used to bind to only the local address
4363  *   and port.
4364  * - A sizeof ipa_conn_t byte address contains complete fanout information
4365  *   consisting of local and remote addresses and ports.  In
4366  *   this case, the addresses are both validated as appropriate
4367  *   for this operation, and, if so, the information is retained
4368  *   for use in the inbound fanout.
4369  *
4370  * The ULP (except in the zero-length bind) can append an
4371  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4372  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4373  * a copy of the source or destination IRE (source for local bind;
4374  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4375  * policy information contained should be copied on to the conn.
4376  *
4377  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4378  */
4379 mblk_t *
4380 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4381 {
4382 	ssize_t		len;
4383 	struct T_bind_req	*tbr;
4384 	sin_t		*sin;
4385 	ipa_conn_t	*ac;
4386 	uchar_t		*ucp;
4387 	mblk_t		*mp1;
4388 	boolean_t	ire_requested;
4389 	boolean_t	ipsec_policy_set = B_FALSE;
4390 	int		error = 0;
4391 	int		protocol;
4392 	ipa_conn_x_t	*acx;
4393 
4394 	ASSERT(!connp->conn_af_isv6);
4395 	connp->conn_pkt_isv6 = B_FALSE;
4396 
4397 	len = MBLKL(mp);
4398 	if (len < (sizeof (*tbr) + 1)) {
4399 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4400 		    "ip_bind: bogus msg, len %ld", len);
4401 		/* XXX: Need to return something better */
4402 		goto bad_addr;
4403 	}
4404 	/* Back up and extract the protocol identifier. */
4405 	mp->b_wptr--;
4406 	protocol = *mp->b_wptr & 0xFF;
4407 	tbr = (struct T_bind_req *)mp->b_rptr;
4408 	/* Reset the message type in preparation for shipping it back. */
4409 	DB_TYPE(mp) = M_PCPROTO;
4410 
4411 	connp->conn_ulp = (uint8_t)protocol;
4412 
4413 	/*
4414 	 * Check for a zero length address.  This is from a protocol that
4415 	 * wants to register to receive all packets of its type.
4416 	 */
4417 	if (tbr->ADDR_length == 0) {
4418 		/*
4419 		 * These protocols are now intercepted in ip_bind_v6().
4420 		 * Reject protocol-level binds here for now.
4421 		 *
4422 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4423 		 * so that the protocol type cannot be SCTP.
4424 		 */
4425 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4426 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4427 			goto bad_addr;
4428 		}
4429 
4430 		/*
4431 		 *
4432 		 * The udp module never sends down a zero-length address,
4433 		 * and allowing this on a labeled system will break MLP
4434 		 * functionality.
4435 		 */
4436 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4437 			goto bad_addr;
4438 
4439 		if (connp->conn_mac_exempt)
4440 			goto bad_addr;
4441 
4442 		/* No hash here really.  The table is big enough. */
4443 		connp->conn_srcv6 = ipv6_all_zeros;
4444 
4445 		ipcl_proto_insert(connp, protocol);
4446 
4447 		tbr->PRIM_type = T_BIND_ACK;
4448 		return (mp);
4449 	}
4450 
4451 	/* Extract the address pointer from the message. */
4452 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4453 	    tbr->ADDR_length);
4454 	if (ucp == NULL) {
4455 		ip1dbg(("ip_bind: no address\n"));
4456 		goto bad_addr;
4457 	}
4458 	if (!OK_32PTR(ucp)) {
4459 		ip1dbg(("ip_bind: unaligned address\n"));
4460 		goto bad_addr;
4461 	}
4462 	/*
4463 	 * Check for trailing mps.
4464 	 */
4465 
4466 	mp1 = mp->b_cont;
4467 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4468 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4469 
4470 	switch (tbr->ADDR_length) {
4471 	default:
4472 		ip1dbg(("ip_bind: bad address length %d\n",
4473 		    (int)tbr->ADDR_length));
4474 		goto bad_addr;
4475 
4476 	case IP_ADDR_LEN:
4477 		/* Verification of local address only */
4478 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4479 		    ire_requested, ipsec_policy_set, B_FALSE);
4480 		break;
4481 
4482 	case sizeof (sin_t):
4483 		sin = (sin_t *)ucp;
4484 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4485 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4486 		break;
4487 
4488 	case sizeof (ipa_conn_t):
4489 		ac = (ipa_conn_t *)ucp;
4490 		/* For raw socket, the local port is not set. */
4491 		if (ac->ac_lport == 0)
4492 			ac->ac_lport = connp->conn_lport;
4493 		/* Always verify destination reachability. */
4494 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4495 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4496 		    ipsec_policy_set, B_TRUE, B_TRUE);
4497 		break;
4498 
4499 	case sizeof (ipa_conn_x_t):
4500 		acx = (ipa_conn_x_t *)ucp;
4501 		/*
4502 		 * Whether or not to verify destination reachability depends
4503 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4504 		 */
4505 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4506 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4507 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4508 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4509 		break;
4510 	}
4511 	if (error == EINPROGRESS)
4512 		return (NULL);
4513 	else if (error != 0)
4514 		goto bad_addr;
4515 	/*
4516 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4517 	 * We can't do this in ip_bind_insert_ire because the policy
4518 	 * may not have been inherited at that point in time and hence
4519 	 * conn_out_enforce_policy may not be set.
4520 	 */
4521 	mp1 = mp->b_cont;
4522 	if (ire_requested && connp->conn_out_enforce_policy &&
4523 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4524 		ire_t *ire = (ire_t *)mp1->b_rptr;
4525 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4526 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4527 	}
4528 
4529 	/* Send it home. */
4530 	mp->b_datap->db_type = M_PCPROTO;
4531 	tbr->PRIM_type = T_BIND_ACK;
4532 	return (mp);
4533 
4534 bad_addr:
4535 	/*
4536 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4537 	 * a unix errno.
4538 	 */
4539 	if (error > 0)
4540 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4541 	else
4542 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4543 	return (mp);
4544 }
4545 
4546 /*
4547  * Here address is verified to be a valid local address.
4548  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4549  * address is also considered a valid local address.
4550  * In the case of a broadcast/multicast address, however, the
4551  * upper protocol is expected to reset the src address
4552  * to 0 if it sees a IRE_BROADCAST type returned so that
4553  * no packets are emitted with broadcast/multicast address as
4554  * source address (that violates hosts requirements RFC1122)
4555  * The addresses valid for bind are:
4556  *	(1) - INADDR_ANY (0)
4557  *	(2) - IP address of an UP interface
4558  *	(3) - IP address of a DOWN interface
4559  *	(4) - valid local IP broadcast addresses. In this case
4560  *	the conn will only receive packets destined to
4561  *	the specified broadcast address.
4562  *	(5) - a multicast address. In this case
4563  *	the conn will only receive packets destined to
4564  *	the specified multicast address. Note: the
4565  *	application still has to issue an
4566  *	IP_ADD_MEMBERSHIP socket option.
4567  *
4568  * On error, return -1 for TBADADDR otherwise pass the
4569  * errno with TSYSERR reply.
4570  *
4571  * In all the above cases, the bound address must be valid in the current zone.
4572  * When the address is loopback, multicast or broadcast, there might be many
4573  * matching IREs so bind has to look up based on the zone.
4574  *
4575  * Note: lport is in network byte order.
4576  */
4577 int
4578 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4579     boolean_t ire_requested, boolean_t ipsec_policy_set,
4580     boolean_t fanout_insert)
4581 {
4582 	int		error = 0;
4583 	ire_t		*src_ire;
4584 	mblk_t		*policy_mp;
4585 	ipif_t		*ipif;
4586 	zoneid_t	zoneid;
4587 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4588 
4589 	if (ipsec_policy_set) {
4590 		policy_mp = mp->b_cont;
4591 	}
4592 
4593 	/*
4594 	 * If it was previously connected, conn_fully_bound would have
4595 	 * been set.
4596 	 */
4597 	connp->conn_fully_bound = B_FALSE;
4598 
4599 	src_ire = NULL;
4600 	ipif = NULL;
4601 
4602 	zoneid = IPCL_ZONEID(connp);
4603 
4604 	if (src_addr) {
4605 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4606 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4607 		/*
4608 		 * If an address other than 0.0.0.0 is requested,
4609 		 * we verify that it is a valid address for bind
4610 		 * Note: Following code is in if-else-if form for
4611 		 * readability compared to a condition check.
4612 		 */
4613 		/* LINTED - statement has no consequent */
4614 		if (IRE_IS_LOCAL(src_ire)) {
4615 			/*
4616 			 * (2) Bind to address of local UP interface
4617 			 */
4618 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4619 			/*
4620 			 * (4) Bind to broadcast address
4621 			 * Note: permitted only from transports that
4622 			 * request IRE
4623 			 */
4624 			if (!ire_requested)
4625 				error = EADDRNOTAVAIL;
4626 		} else {
4627 			/*
4628 			 * (3) Bind to address of local DOWN interface
4629 			 * (ipif_lookup_addr() looks up all interfaces
4630 			 * but we do not get here for UP interfaces
4631 			 * - case (2) above)
4632 			 * We put the protocol byte back into the mblk
4633 			 * since we may come back via ip_wput_nondata()
4634 			 * later with this mblk if ipif_lookup_addr chooses
4635 			 * to defer processing.
4636 			 */
4637 			*mp->b_wptr++ = (char)connp->conn_ulp;
4638 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4639 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4640 			    &error, ipst)) != NULL) {
4641 				ipif_refrele(ipif);
4642 			} else if (error == EINPROGRESS) {
4643 				if (src_ire != NULL)
4644 					ire_refrele(src_ire);
4645 				return (EINPROGRESS);
4646 			} else if (CLASSD(src_addr)) {
4647 				error = 0;
4648 				if (src_ire != NULL)
4649 					ire_refrele(src_ire);
4650 				/*
4651 				 * (5) bind to multicast address.
4652 				 * Fake out the IRE returned to upper
4653 				 * layer to be a broadcast IRE.
4654 				 */
4655 				src_ire = ire_ctable_lookup(
4656 				    INADDR_BROADCAST, INADDR_ANY,
4657 				    IRE_BROADCAST, NULL, zoneid, NULL,
4658 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4659 				    ipst);
4660 				if (src_ire == NULL || !ire_requested)
4661 					error = EADDRNOTAVAIL;
4662 			} else {
4663 				/*
4664 				 * Not a valid address for bind
4665 				 */
4666 				error = EADDRNOTAVAIL;
4667 			}
4668 			/*
4669 			 * Just to keep it consistent with the processing in
4670 			 * ip_bind_v4()
4671 			 */
4672 			mp->b_wptr--;
4673 		}
4674 		if (error) {
4675 			/* Red Alert!  Attempting to be a bogon! */
4676 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4677 			    ntohl(src_addr)));
4678 			goto bad_addr;
4679 		}
4680 	}
4681 
4682 	/*
4683 	 * Allow setting new policies. For example, disconnects come
4684 	 * down as ipa_t bind. As we would have set conn_policy_cached
4685 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4686 	 * can change after the disconnect.
4687 	 */
4688 	connp->conn_policy_cached = B_FALSE;
4689 
4690 	/*
4691 	 * If not fanout_insert this was just an address verification
4692 	 */
4693 	if (fanout_insert) {
4694 		/*
4695 		 * The addresses have been verified. Time to insert in
4696 		 * the correct fanout list.
4697 		 */
4698 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4699 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4700 		connp->conn_lport = lport;
4701 		connp->conn_fport = 0;
4702 		/*
4703 		 * Do we need to add a check to reject Multicast packets
4704 		 *
4705 		 * We need to make sure that the conn_recv is set to a non-null
4706 		 * value before we insert the conn into the classifier table.
4707 		 * This is to avoid a race with an incoming packet which does an
4708 		 * ipcl_classify().
4709 		 */
4710 		if (*mp->b_wptr == IPPROTO_TCP)
4711 			connp->conn_recv = tcp_conn_request;
4712 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4713 	}
4714 
4715 	if (error == 0) {
4716 		if (ire_requested) {
4717 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4718 				error = -1;
4719 				/* Falls through to bad_addr */
4720 			}
4721 		} else if (ipsec_policy_set) {
4722 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4723 				error = -1;
4724 				/* Falls through to bad_addr */
4725 			}
4726 		}
4727 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4728 		connp->conn_recv = tcp_input;
4729 	}
4730 bad_addr:
4731 	if (error != 0) {
4732 		if (connp->conn_anon_port) {
4733 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4734 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4735 			    B_FALSE);
4736 		}
4737 		connp->conn_mlp_type = mlptSingle;
4738 	}
4739 	if (src_ire != NULL)
4740 		IRE_REFRELE(src_ire);
4741 	if (ipsec_policy_set) {
4742 		ASSERT(policy_mp == mp->b_cont);
4743 		ASSERT(policy_mp != NULL);
4744 		freeb(policy_mp);
4745 		/*
4746 		 * As of now assume that nothing else accompanies
4747 		 * IPSEC_POLICY_SET.
4748 		 */
4749 		mp->b_cont = NULL;
4750 	}
4751 	return (error);
4752 }
4753 
4754 /*
4755  * Verify that both the source and destination addresses
4756  * are valid.  If verify_dst is false, then the destination address may be
4757  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4758  * destination reachability, while tunnels do not.
4759  * Note that we allow connect to broadcast and multicast
4760  * addresses when ire_requested is set. Thus the ULP
4761  * has to check for IRE_BROADCAST and multicast.
4762  *
4763  * Returns zero if ok.
4764  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4765  * (for use with TSYSERR reply).
4766  *
4767  * Note: lport and fport are in network byte order.
4768  */
4769 int
4770 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4771     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4772     boolean_t ire_requested, boolean_t ipsec_policy_set,
4773     boolean_t fanout_insert, boolean_t verify_dst)
4774 {
4775 	ire_t		*src_ire;
4776 	ire_t		*dst_ire;
4777 	int		error = 0;
4778 	int 		protocol;
4779 	mblk_t		*policy_mp;
4780 	ire_t		*sire = NULL;
4781 	ire_t		*md_dst_ire = NULL;
4782 	ire_t		*lso_dst_ire = NULL;
4783 	ill_t		*ill = NULL;
4784 	zoneid_t	zoneid;
4785 	ipaddr_t	src_addr = *src_addrp;
4786 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4787 
4788 	src_ire = dst_ire = NULL;
4789 	protocol = *mp->b_wptr & 0xFF;
4790 
4791 	/*
4792 	 * If we never got a disconnect before, clear it now.
4793 	 */
4794 	connp->conn_fully_bound = B_FALSE;
4795 
4796 	if (ipsec_policy_set) {
4797 		policy_mp = mp->b_cont;
4798 	}
4799 
4800 	zoneid = IPCL_ZONEID(connp);
4801 
4802 	if (CLASSD(dst_addr)) {
4803 		/* Pick up an IRE_BROADCAST */
4804 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4805 		    NULL, zoneid, MBLK_GETLABEL(mp),
4806 		    (MATCH_IRE_RECURSIVE |
4807 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4808 		    MATCH_IRE_SECATTR), ipst);
4809 	} else {
4810 		/*
4811 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4812 		 * and onlink ipif is not found set ENETUNREACH error.
4813 		 */
4814 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4815 			ipif_t *ipif;
4816 
4817 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4818 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4819 			if (ipif == NULL) {
4820 				error = ENETUNREACH;
4821 				goto bad_addr;
4822 			}
4823 			ipif_refrele(ipif);
4824 		}
4825 
4826 		if (connp->conn_nexthop_set) {
4827 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4828 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4829 			    MATCH_IRE_SECATTR, ipst);
4830 		} else {
4831 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4832 			    &sire, zoneid, MBLK_GETLABEL(mp),
4833 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4834 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4835 			    MATCH_IRE_SECATTR), ipst);
4836 		}
4837 	}
4838 	/*
4839 	 * dst_ire can't be a broadcast when not ire_requested.
4840 	 * We also prevent ire's with src address INADDR_ANY to
4841 	 * be used, which are created temporarily for
4842 	 * sending out packets from endpoints that have
4843 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4844 	 * reachable.  If verify_dst is false, the destination needn't be
4845 	 * reachable.
4846 	 *
4847 	 * If we match on a reject or black hole, then we've got a
4848 	 * local failure.  May as well fail out the connect() attempt,
4849 	 * since it's never going to succeed.
4850 	 */
4851 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4852 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4853 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4854 		/*
4855 		 * If we're verifying destination reachability, we always want
4856 		 * to complain here.
4857 		 *
4858 		 * If we're not verifying destination reachability but the
4859 		 * destination has a route, we still want to fail on the
4860 		 * temporary address and broadcast address tests.
4861 		 */
4862 		if (verify_dst || (dst_ire != NULL)) {
4863 			if (ip_debug > 2) {
4864 				pr_addr_dbg("ip_bind_connected: bad connected "
4865 				    "dst %s\n", AF_INET, &dst_addr);
4866 			}
4867 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4868 				error = ENETUNREACH;
4869 			else
4870 				error = EHOSTUNREACH;
4871 			goto bad_addr;
4872 		}
4873 	}
4874 
4875 	/*
4876 	 * We now know that routing will allow us to reach the destination.
4877 	 * Check whether Trusted Solaris policy allows communication with this
4878 	 * host, and pretend that the destination is unreachable if not.
4879 	 *
4880 	 * This is never a problem for TCP, since that transport is known to
4881 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4882 	 * handling.  If the remote is unreachable, it will be detected at that
4883 	 * point, so there's no reason to check it here.
4884 	 *
4885 	 * Note that for sendto (and other datagram-oriented friends), this
4886 	 * check is done as part of the data path label computation instead.
4887 	 * The check here is just to make non-TCP connect() report the right
4888 	 * error.
4889 	 */
4890 	if (dst_ire != NULL && is_system_labeled() &&
4891 	    !IPCL_IS_TCP(connp) &&
4892 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4893 	    connp->conn_mac_exempt, ipst) != 0) {
4894 		error = EHOSTUNREACH;
4895 		if (ip_debug > 2) {
4896 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4897 			    AF_INET, &dst_addr);
4898 		}
4899 		goto bad_addr;
4900 	}
4901 
4902 	/*
4903 	 * If the app does a connect(), it means that it will most likely
4904 	 * send more than 1 packet to the destination.  It makes sense
4905 	 * to clear the temporary flag.
4906 	 */
4907 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4908 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4909 		irb_t *irb = dst_ire->ire_bucket;
4910 
4911 		rw_enter(&irb->irb_lock, RW_WRITER);
4912 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4913 		irb->irb_tmp_ire_cnt--;
4914 		rw_exit(&irb->irb_lock);
4915 	}
4916 
4917 	/*
4918 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4919 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4920 	 * eligibility tests for passive connects are handled separately
4921 	 * through tcp_adapt_ire().  We do this before the source address
4922 	 * selection, because dst_ire may change after a call to
4923 	 * ipif_select_source().  This is a best-effort check, as the
4924 	 * packet for this connection may not actually go through
4925 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4926 	 * calling ip_newroute().  This is why we further check on the
4927 	 * IRE during LSO/Multidata packet transmission in
4928 	 * tcp_lsosend()/tcp_multisend().
4929 	 */
4930 	if (!ipsec_policy_set && dst_ire != NULL &&
4931 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4932 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4933 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4934 			lso_dst_ire = dst_ire;
4935 			IRE_REFHOLD(lso_dst_ire);
4936 		} else if (ipst->ips_ip_multidata_outbound &&
4937 		    ILL_MDT_CAPABLE(ill)) {
4938 			md_dst_ire = dst_ire;
4939 			IRE_REFHOLD(md_dst_ire);
4940 		}
4941 	}
4942 
4943 	if (dst_ire != NULL &&
4944 	    dst_ire->ire_type == IRE_LOCAL &&
4945 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4946 		/*
4947 		 * If the IRE belongs to a different zone, look for a matching
4948 		 * route in the forwarding table and use the source address from
4949 		 * that route.
4950 		 */
4951 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4952 		    zoneid, 0, NULL,
4953 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4954 		    MATCH_IRE_RJ_BHOLE, ipst);
4955 		if (src_ire == NULL) {
4956 			error = EHOSTUNREACH;
4957 			goto bad_addr;
4958 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4959 			if (!(src_ire->ire_type & IRE_HOST))
4960 				error = ENETUNREACH;
4961 			else
4962 				error = EHOSTUNREACH;
4963 			goto bad_addr;
4964 		}
4965 		if (src_addr == INADDR_ANY)
4966 			src_addr = src_ire->ire_src_addr;
4967 		ire_refrele(src_ire);
4968 		src_ire = NULL;
4969 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4970 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4971 			src_addr = sire->ire_src_addr;
4972 			ire_refrele(dst_ire);
4973 			dst_ire = sire;
4974 			sire = NULL;
4975 		} else {
4976 			/*
4977 			 * Pick a source address so that a proper inbound
4978 			 * load spreading would happen.
4979 			 */
4980 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4981 			ipif_t *src_ipif = NULL;
4982 			ire_t *ipif_ire;
4983 
4984 			/*
4985 			 * Supply a local source address such that inbound
4986 			 * load spreading happens.
4987 			 *
4988 			 * Determine the best source address on this ill for
4989 			 * the destination.
4990 			 *
4991 			 * 1) For broadcast, we should return a broadcast ire
4992 			 *    found above so that upper layers know that the
4993 			 *    destination address is a broadcast address.
4994 			 *
4995 			 * 2) If this is part of a group, select a better
4996 			 *    source address so that better inbound load
4997 			 *    balancing happens. Do the same if the ipif
4998 			 *    is DEPRECATED.
4999 			 *
5000 			 * 3) If the outgoing interface is part of a usesrc
5001 			 *    group, then try selecting a source address from
5002 			 *    the usesrc ILL.
5003 			 */
5004 			if ((dst_ire->ire_zoneid != zoneid &&
5005 			    dst_ire->ire_zoneid != ALL_ZONES) ||
5006 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
5007 			    ((dst_ill->ill_group != NULL) ||
5008 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
5009 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
5010 				/*
5011 				 * If the destination is reachable via a
5012 				 * given gateway, the selected source address
5013 				 * should be in the same subnet as the gateway.
5014 				 * Otherwise, the destination is not reachable.
5015 				 *
5016 				 * If there are no interfaces on the same subnet
5017 				 * as the destination, ipif_select_source gives
5018 				 * first non-deprecated interface which might be
5019 				 * on a different subnet than the gateway.
5020 				 * This is not desirable. Hence pass the dst_ire
5021 				 * source address to ipif_select_source.
5022 				 * It is sure that the destination is reachable
5023 				 * with the dst_ire source address subnet.
5024 				 * So passing dst_ire source address to
5025 				 * ipif_select_source will make sure that the
5026 				 * selected source will be on the same subnet
5027 				 * as dst_ire source address.
5028 				 */
5029 				ipaddr_t saddr =
5030 				    dst_ire->ire_ipif->ipif_src_addr;
5031 				src_ipif = ipif_select_source(dst_ill,
5032 				    saddr, zoneid);
5033 				if (src_ipif != NULL) {
5034 					if (IS_VNI(src_ipif->ipif_ill)) {
5035 						/*
5036 						 * For VNI there is no
5037 						 * interface route
5038 						 */
5039 						src_addr =
5040 						    src_ipif->ipif_src_addr;
5041 					} else {
5042 						ipif_ire =
5043 						    ipif_to_ire(src_ipif);
5044 						if (ipif_ire != NULL) {
5045 							IRE_REFRELE(dst_ire);
5046 							dst_ire = ipif_ire;
5047 						}
5048 						src_addr =
5049 						    dst_ire->ire_src_addr;
5050 					}
5051 					ipif_refrele(src_ipif);
5052 				} else {
5053 					src_addr = dst_ire->ire_src_addr;
5054 				}
5055 			} else {
5056 				src_addr = dst_ire->ire_src_addr;
5057 			}
5058 		}
5059 	}
5060 
5061 	/*
5062 	 * We do ire_route_lookup() here (and not
5063 	 * interface lookup as we assert that
5064 	 * src_addr should only come from an
5065 	 * UP interface for hard binding.
5066 	 */
5067 	ASSERT(src_ire == NULL);
5068 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5069 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5070 	/* src_ire must be a local|loopback */
5071 	if (!IRE_IS_LOCAL(src_ire)) {
5072 		if (ip_debug > 2) {
5073 			pr_addr_dbg("ip_bind_connected: bad connected "
5074 			    "src %s\n", AF_INET, &src_addr);
5075 		}
5076 		error = EADDRNOTAVAIL;
5077 		goto bad_addr;
5078 	}
5079 
5080 	/*
5081 	 * If the source address is a loopback address, the
5082 	 * destination had best be local or multicast.
5083 	 * The transports that can't handle multicast will reject
5084 	 * those addresses.
5085 	 */
5086 	if (src_ire->ire_type == IRE_LOOPBACK &&
5087 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5088 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5089 		error = -1;
5090 		goto bad_addr;
5091 	}
5092 
5093 	/*
5094 	 * Allow setting new policies. For example, disconnects come
5095 	 * down as ipa_t bind. As we would have set conn_policy_cached
5096 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5097 	 * can change after the disconnect.
5098 	 */
5099 	connp->conn_policy_cached = B_FALSE;
5100 
5101 	/*
5102 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5103 	 * can handle their passed-in conn's.
5104 	 */
5105 
5106 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5107 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5108 	connp->conn_lport = lport;
5109 	connp->conn_fport = fport;
5110 	*src_addrp = src_addr;
5111 
5112 	ASSERT(!(ipsec_policy_set && ire_requested));
5113 	if (ire_requested) {
5114 		iulp_t *ulp_info = NULL;
5115 
5116 		/*
5117 		 * Note that sire will not be NULL if this is an off-link
5118 		 * connection and there is not cache for that dest yet.
5119 		 *
5120 		 * XXX Because of an existing bug, if there are multiple
5121 		 * default routes, the IRE returned now may not be the actual
5122 		 * default route used (default routes are chosen in a
5123 		 * round robin fashion).  So if the metrics for different
5124 		 * default routes are different, we may return the wrong
5125 		 * metrics.  This will not be a problem if the existing
5126 		 * bug is fixed.
5127 		 */
5128 		if (sire != NULL) {
5129 			ulp_info = &(sire->ire_uinfo);
5130 		}
5131 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5132 			error = -1;
5133 			goto bad_addr;
5134 		}
5135 	} else if (ipsec_policy_set) {
5136 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5137 			error = -1;
5138 			goto bad_addr;
5139 		}
5140 	}
5141 
5142 	/*
5143 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5144 	 * we'll cache that.  If we don't, we'll inherit global policy.
5145 	 *
5146 	 * We can't insert until the conn reflects the policy. Note that
5147 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5148 	 * connections where we don't have a policy. This is to prevent
5149 	 * global policy lookups in the inbound path.
5150 	 *
5151 	 * If we insert before we set conn_policy_cached,
5152 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5153 	 * because global policy cound be non-empty. We normally call
5154 	 * ipsec_check_policy() for conn_policy_cached connections only if
5155 	 * ipc_in_enforce_policy is set. But in this case,
5156 	 * conn_policy_cached can get set anytime since we made the
5157 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5158 	 * called, which will make the above assumption false.  Thus, we
5159 	 * need to insert after we set conn_policy_cached.
5160 	 */
5161 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5162 		goto bad_addr;
5163 
5164 	if (fanout_insert) {
5165 		/*
5166 		 * The addresses have been verified. Time to insert in
5167 		 * the correct fanout list.
5168 		 * We need to make sure that the conn_recv is set to a non-null
5169 		 * value before we insert into the classifier table to avoid a
5170 		 * race with an incoming packet which does an ipcl_classify().
5171 		 */
5172 		if (protocol == IPPROTO_TCP)
5173 			connp->conn_recv = tcp_input;
5174 		error = ipcl_conn_insert(connp, protocol, src_addr,
5175 		    dst_addr, connp->conn_ports);
5176 	}
5177 
5178 	if (error == 0) {
5179 		connp->conn_fully_bound = B_TRUE;
5180 		/*
5181 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5182 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5183 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5184 		 * ip_xxinfo_return(), which performs further checks
5185 		 * against them and upon success, returns the LSO/MDT info
5186 		 * mblk which we will attach to the bind acknowledgment.
5187 		 */
5188 		if (lso_dst_ire != NULL) {
5189 			mblk_t *lsoinfo_mp;
5190 
5191 			ASSERT(ill->ill_lso_capab != NULL);
5192 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5193 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5194 				linkb(mp, lsoinfo_mp);
5195 		} else if (md_dst_ire != NULL) {
5196 			mblk_t *mdinfo_mp;
5197 
5198 			ASSERT(ill->ill_mdt_capab != NULL);
5199 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5200 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5201 				linkb(mp, mdinfo_mp);
5202 		}
5203 	}
5204 bad_addr:
5205 	if (ipsec_policy_set) {
5206 		ASSERT(policy_mp == mp->b_cont);
5207 		ASSERT(policy_mp != NULL);
5208 		freeb(policy_mp);
5209 		/*
5210 		 * As of now assume that nothing else accompanies
5211 		 * IPSEC_POLICY_SET.
5212 		 */
5213 		mp->b_cont = NULL;
5214 	}
5215 	if (src_ire != NULL)
5216 		IRE_REFRELE(src_ire);
5217 	if (dst_ire != NULL)
5218 		IRE_REFRELE(dst_ire);
5219 	if (sire != NULL)
5220 		IRE_REFRELE(sire);
5221 	if (md_dst_ire != NULL)
5222 		IRE_REFRELE(md_dst_ire);
5223 	if (lso_dst_ire != NULL)
5224 		IRE_REFRELE(lso_dst_ire);
5225 	return (error);
5226 }
5227 
5228 /*
5229  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5230  * Prefers dst_ire over src_ire.
5231  */
5232 static boolean_t
5233 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5234 {
5235 	mblk_t	*mp1;
5236 	ire_t *ret_ire = NULL;
5237 
5238 	mp1 = mp->b_cont;
5239 	ASSERT(mp1 != NULL);
5240 
5241 	if (ire != NULL) {
5242 		/*
5243 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5244 		 * appended mblk. Its <upper protocol>'s
5245 		 * job to make sure there is room.
5246 		 */
5247 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5248 			return (0);
5249 
5250 		mp1->b_datap->db_type = IRE_DB_TYPE;
5251 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5252 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5253 		ret_ire = (ire_t *)mp1->b_rptr;
5254 		/*
5255 		 * Pass the latest setting of the ip_path_mtu_discovery and
5256 		 * copy the ulp info if any.
5257 		 */
5258 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5259 		    IPH_DF : 0;
5260 		if (ulp_info != NULL) {
5261 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5262 			    sizeof (iulp_t));
5263 		}
5264 		ret_ire->ire_mp = mp1;
5265 	} else {
5266 		/*
5267 		 * No IRE was found. Remove IRE mblk.
5268 		 */
5269 		mp->b_cont = mp1->b_cont;
5270 		freeb(mp1);
5271 	}
5272 
5273 	return (1);
5274 }
5275 
5276 /*
5277  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5278  * the final piece where we don't.  Return a pointer to the first mblk in the
5279  * result, and update the pointer to the next mblk to chew on.  If anything
5280  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5281  * NULL pointer.
5282  */
5283 mblk_t *
5284 ip_carve_mp(mblk_t **mpp, ssize_t len)
5285 {
5286 	mblk_t	*mp0;
5287 	mblk_t	*mp1;
5288 	mblk_t	*mp2;
5289 
5290 	if (!len || !mpp || !(mp0 = *mpp))
5291 		return (NULL);
5292 	/* If we aren't going to consume the first mblk, we need a dup. */
5293 	if (mp0->b_wptr - mp0->b_rptr > len) {
5294 		mp1 = dupb(mp0);
5295 		if (mp1) {
5296 			/* Partition the data between the two mblks. */
5297 			mp1->b_wptr = mp1->b_rptr + len;
5298 			mp0->b_rptr = mp1->b_wptr;
5299 			/*
5300 			 * after adjustments if mblk not consumed is now
5301 			 * unaligned, try to align it. If this fails free
5302 			 * all messages and let upper layer recover.
5303 			 */
5304 			if (!OK_32PTR(mp0->b_rptr)) {
5305 				if (!pullupmsg(mp0, -1)) {
5306 					freemsg(mp0);
5307 					freemsg(mp1);
5308 					*mpp = NULL;
5309 					return (NULL);
5310 				}
5311 			}
5312 		}
5313 		return (mp1);
5314 	}
5315 	/* Eat through as many mblks as we need to get len bytes. */
5316 	len -= mp0->b_wptr - mp0->b_rptr;
5317 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5318 		if (mp2->b_wptr - mp2->b_rptr > len) {
5319 			/*
5320 			 * We won't consume the entire last mblk.  Like
5321 			 * above, dup and partition it.
5322 			 */
5323 			mp1->b_cont = dupb(mp2);
5324 			mp1 = mp1->b_cont;
5325 			if (!mp1) {
5326 				/*
5327 				 * Trouble.  Rather than go to a lot of
5328 				 * trouble to clean up, we free the messages.
5329 				 * This won't be any worse than losing it on
5330 				 * the wire.
5331 				 */
5332 				freemsg(mp0);
5333 				freemsg(mp2);
5334 				*mpp = NULL;
5335 				return (NULL);
5336 			}
5337 			mp1->b_wptr = mp1->b_rptr + len;
5338 			mp2->b_rptr = mp1->b_wptr;
5339 			/*
5340 			 * after adjustments if mblk not consumed is now
5341 			 * unaligned, try to align it. If this fails free
5342 			 * all messages and let upper layer recover.
5343 			 */
5344 			if (!OK_32PTR(mp2->b_rptr)) {
5345 				if (!pullupmsg(mp2, -1)) {
5346 					freemsg(mp0);
5347 					freemsg(mp2);
5348 					*mpp = NULL;
5349 					return (NULL);
5350 				}
5351 			}
5352 			*mpp = mp2;
5353 			return (mp0);
5354 		}
5355 		/* Decrement len by the amount we just got. */
5356 		len -= mp2->b_wptr - mp2->b_rptr;
5357 	}
5358 	/*
5359 	 * len should be reduced to zero now.  If not our caller has
5360 	 * screwed up.
5361 	 */
5362 	if (len) {
5363 		/* Shouldn't happen! */
5364 		freemsg(mp0);
5365 		*mpp = NULL;
5366 		return (NULL);
5367 	}
5368 	/*
5369 	 * We consumed up to exactly the end of an mblk.  Detach the part
5370 	 * we are returning from the rest of the chain.
5371 	 */
5372 	mp1->b_cont = NULL;
5373 	*mpp = mp2;
5374 	return (mp0);
5375 }
5376 
5377 /* The ill stream is being unplumbed. Called from ip_close */
5378 int
5379 ip_modclose(ill_t *ill)
5380 {
5381 	boolean_t success;
5382 	ipsq_t	*ipsq;
5383 	ipif_t	*ipif;
5384 	queue_t	*q = ill->ill_rq;
5385 	ip_stack_t	*ipst = ill->ill_ipst;
5386 	clock_t timeout;
5387 
5388 	/*
5389 	 * Wait for the ACKs of all deferred control messages to be processed.
5390 	 * In particular, we wait for a potential capability reset initiated
5391 	 * in ip_sioctl_plink() to complete before proceeding.
5392 	 *
5393 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5394 	 * in case the driver never replies.
5395 	 */
5396 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5397 	mutex_enter(&ill->ill_lock);
5398 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5399 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5400 			/* Timeout */
5401 			break;
5402 		}
5403 	}
5404 	mutex_exit(&ill->ill_lock);
5405 
5406 	/*
5407 	 * Forcibly enter the ipsq after some delay. This is to take
5408 	 * care of the case when some ioctl does not complete because
5409 	 * we sent a control message to the driver and it did not
5410 	 * send us a reply. We want to be able to at least unplumb
5411 	 * and replumb rather than force the user to reboot the system.
5412 	 */
5413 	success = ipsq_enter(ill, B_FALSE);
5414 
5415 	/*
5416 	 * Open/close/push/pop is guaranteed to be single threaded
5417 	 * per stream by STREAMS. FS guarantees that all references
5418 	 * from top are gone before close is called. So there can't
5419 	 * be another close thread that has set CONDEMNED on this ill.
5420 	 * and cause ipsq_enter to return failure.
5421 	 */
5422 	ASSERT(success);
5423 	ipsq = ill->ill_phyint->phyint_ipsq;
5424 
5425 	/*
5426 	 * Mark it condemned. No new reference will be made to this ill.
5427 	 * Lookup functions will return an error. Threads that try to
5428 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5429 	 * that the refcnt will drop down to zero.
5430 	 */
5431 	mutex_enter(&ill->ill_lock);
5432 	ill->ill_state_flags |= ILL_CONDEMNED;
5433 	for (ipif = ill->ill_ipif; ipif != NULL;
5434 	    ipif = ipif->ipif_next) {
5435 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5436 	}
5437 	/*
5438 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5439 	 * returns  error if ILL_CONDEMNED is set
5440 	 */
5441 	cv_broadcast(&ill->ill_cv);
5442 	mutex_exit(&ill->ill_lock);
5443 
5444 	/*
5445 	 * Send all the deferred DLPI messages downstream which came in
5446 	 * during the small window right before ipsq_enter(). We do this
5447 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5448 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5449 	 */
5450 	ill_dlpi_send_deferred(ill);
5451 
5452 	/*
5453 	 * Shut down fragmentation reassembly.
5454 	 * ill_frag_timer won't start a timer again.
5455 	 * Now cancel any existing timer
5456 	 */
5457 	(void) untimeout(ill->ill_frag_timer_id);
5458 	(void) ill_frag_timeout(ill, 0);
5459 
5460 	/*
5461 	 * If MOVE was in progress, clear the
5462 	 * move_in_progress fields also.
5463 	 */
5464 	if (ill->ill_move_in_progress) {
5465 		ILL_CLEAR_MOVE(ill);
5466 	}
5467 
5468 	/*
5469 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5470 	 * this ill. Then wait for the refcnts to drop to zero.
5471 	 * ill_is_quiescent checks whether the ill is really quiescent.
5472 	 * Then make sure that threads that are waiting to enter the
5473 	 * ipsq have seen the error returned by ipsq_enter and have
5474 	 * gone away. Then we call ill_delete_tail which does the
5475 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5476 	 */
5477 	ill_delete(ill);
5478 	mutex_enter(&ill->ill_lock);
5479 	while (!ill_is_quiescent(ill))
5480 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5481 	while (ill->ill_waiters)
5482 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5483 
5484 	mutex_exit(&ill->ill_lock);
5485 
5486 	/*
5487 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5488 	 * it held until the end of the function since the cleanup
5489 	 * below needs to be able to use the ip_stack_t.
5490 	 */
5491 	netstack_hold(ipst->ips_netstack);
5492 
5493 	/* qprocsoff is called in ill_delete_tail */
5494 	ill_delete_tail(ill);
5495 	ASSERT(ill->ill_ipst == NULL);
5496 
5497 	/*
5498 	 * Walk through all upper (conn) streams and qenable
5499 	 * those that have queued data.
5500 	 * close synchronization needs this to
5501 	 * be done to ensure that all upper layers blocked
5502 	 * due to flow control to the closing device
5503 	 * get unblocked.
5504 	 */
5505 	ip1dbg(("ip_wsrv: walking\n"));
5506 	conn_walk_drain(ipst);
5507 
5508 	mutex_enter(&ipst->ips_ip_mi_lock);
5509 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5510 	mutex_exit(&ipst->ips_ip_mi_lock);
5511 
5512 	/*
5513 	 * credp could be null if the open didn't succeed and ip_modopen
5514 	 * itself calls ip_close.
5515 	 */
5516 	if (ill->ill_credp != NULL)
5517 		crfree(ill->ill_credp);
5518 
5519 	mutex_enter(&ill->ill_lock);
5520 	ill_nic_info_dispatch(ill);
5521 	mutex_exit(&ill->ill_lock);
5522 
5523 	/*
5524 	 * Now we are done with the module close pieces that
5525 	 * need the netstack_t.
5526 	 */
5527 	netstack_rele(ipst->ips_netstack);
5528 
5529 	mi_close_free((IDP)ill);
5530 	q->q_ptr = WR(q)->q_ptr = NULL;
5531 
5532 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5533 
5534 	return (0);
5535 }
5536 
5537 /*
5538  * This is called as part of close() for both IP and UDP
5539  * in order to quiesce the conn.
5540  */
5541 void
5542 ip_quiesce_conn(conn_t *connp)
5543 {
5544 	boolean_t	drain_cleanup_reqd = B_FALSE;
5545 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5546 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5547 	ip_stack_t	*ipst;
5548 
5549 	ASSERT(!IPCL_IS_TCP(connp));
5550 	ipst = connp->conn_netstack->netstack_ip;
5551 
5552 	/*
5553 	 * Mark the conn as closing, and this conn must not be
5554 	 * inserted in future into any list. Eg. conn_drain_insert(),
5555 	 * won't insert this conn into the conn_drain_list.
5556 	 * Similarly ill_pending_mp_add() will not add any mp to
5557 	 * the pending mp list, after this conn has started closing.
5558 	 *
5559 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5560 	 * cannot get set henceforth.
5561 	 */
5562 	mutex_enter(&connp->conn_lock);
5563 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5564 	connp->conn_state_flags |= CONN_CLOSING;
5565 	if (connp->conn_idl != NULL)
5566 		drain_cleanup_reqd = B_TRUE;
5567 	if (connp->conn_oper_pending_ill != NULL)
5568 		conn_ioctl_cleanup_reqd = B_TRUE;
5569 	if (connp->conn_ilg_inuse != 0)
5570 		ilg_cleanup_reqd = B_TRUE;
5571 	mutex_exit(&connp->conn_lock);
5572 
5573 	if (IPCL_IS_UDP(connp))
5574 		udp_quiesce_conn(connp);
5575 
5576 	if (conn_ioctl_cleanup_reqd)
5577 		conn_ioctl_cleanup(connp);
5578 
5579 	if (is_system_labeled() && connp->conn_anon_port) {
5580 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5581 		    connp->conn_mlp_type, connp->conn_ulp,
5582 		    ntohs(connp->conn_lport), B_FALSE);
5583 		connp->conn_anon_port = 0;
5584 	}
5585 	connp->conn_mlp_type = mlptSingle;
5586 
5587 	/*
5588 	 * Remove this conn from any fanout list it is on.
5589 	 * and then wait for any threads currently operating
5590 	 * on this endpoint to finish
5591 	 */
5592 	ipcl_hash_remove(connp);
5593 
5594 	/*
5595 	 * Remove this conn from the drain list, and do
5596 	 * any other cleanup that may be required.
5597 	 * (Only non-tcp streams may have a non-null conn_idl.
5598 	 * TCP streams are never flow controlled, and
5599 	 * conn_idl will be null)
5600 	 */
5601 	if (drain_cleanup_reqd)
5602 		conn_drain_tail(connp, B_TRUE);
5603 
5604 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5605 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5606 		(void) ip_mrouter_done(NULL, ipst);
5607 
5608 	if (ilg_cleanup_reqd)
5609 		ilg_delete_all(connp);
5610 
5611 	conn_delete_ire(connp, NULL);
5612 
5613 	/*
5614 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5615 	 * callers from write side can't be there now because close
5616 	 * is in progress. The only other caller is ipcl_walk
5617 	 * which checks for the condemned flag.
5618 	 */
5619 	mutex_enter(&connp->conn_lock);
5620 	connp->conn_state_flags |= CONN_CONDEMNED;
5621 	while (connp->conn_ref != 1)
5622 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5623 	connp->conn_state_flags |= CONN_QUIESCED;
5624 	mutex_exit(&connp->conn_lock);
5625 }
5626 
5627 /* ARGSUSED */
5628 int
5629 ip_close(queue_t *q, int flags)
5630 {
5631 	conn_t		*connp;
5632 
5633 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5634 
5635 	/*
5636 	 * Call the appropriate delete routine depending on whether this is
5637 	 * a module or device.
5638 	 */
5639 	if (WR(q)->q_next != NULL) {
5640 		/* This is a module close */
5641 		return (ip_modclose((ill_t *)q->q_ptr));
5642 	}
5643 
5644 	connp = q->q_ptr;
5645 	ip_quiesce_conn(connp);
5646 
5647 	qprocsoff(q);
5648 
5649 	/*
5650 	 * Now we are truly single threaded on this stream, and can
5651 	 * delete the things hanging off the connp, and finally the connp.
5652 	 * We removed this connp from the fanout list, it cannot be
5653 	 * accessed thru the fanouts, and we already waited for the
5654 	 * conn_ref to drop to 0. We are already in close, so
5655 	 * there cannot be any other thread from the top. qprocsoff
5656 	 * has completed, and service has completed or won't run in
5657 	 * future.
5658 	 */
5659 	ASSERT(connp->conn_ref == 1);
5660 
5661 	/*
5662 	 * A conn which was previously marked as IPCL_UDP cannot
5663 	 * retain the flag because it would have been cleared by
5664 	 * udp_close().
5665 	 */
5666 	ASSERT(!IPCL_IS_UDP(connp));
5667 
5668 	if (connp->conn_latch != NULL) {
5669 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5670 		connp->conn_latch = NULL;
5671 	}
5672 	if (connp->conn_policy != NULL) {
5673 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5674 		connp->conn_policy = NULL;
5675 	}
5676 	if (connp->conn_ipsec_opt_mp != NULL) {
5677 		freemsg(connp->conn_ipsec_opt_mp);
5678 		connp->conn_ipsec_opt_mp = NULL;
5679 	}
5680 
5681 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5682 
5683 	connp->conn_ref--;
5684 	ipcl_conn_destroy(connp);
5685 
5686 	q->q_ptr = WR(q)->q_ptr = NULL;
5687 	return (0);
5688 }
5689 
5690 int
5691 ip_snmpmod_close(queue_t *q)
5692 {
5693 	conn_t *connp = Q_TO_CONN(q);
5694 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5695 
5696 	qprocsoff(q);
5697 
5698 	if (connp->conn_flags & IPCL_UDPMOD)
5699 		udp_close_free(connp);
5700 
5701 	if (connp->conn_cred != NULL) {
5702 		crfree(connp->conn_cred);
5703 		connp->conn_cred = NULL;
5704 	}
5705 	CONN_DEC_REF(connp);
5706 	q->q_ptr = WR(q)->q_ptr = NULL;
5707 	return (0);
5708 }
5709 
5710 /*
5711  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5712  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5713  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5714  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5715  * queues as we never enqueue messages there and we don't handle any ioctls.
5716  * Everything else is freed.
5717  */
5718 void
5719 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5720 {
5721 	conn_t	*connp = q->q_ptr;
5722 	pfi_t	setfn;
5723 	pfi_t	getfn;
5724 
5725 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5726 
5727 	switch (DB_TYPE(mp)) {
5728 	case M_PROTO:
5729 	case M_PCPROTO:
5730 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5731 		    ((((union T_primitives *)mp->b_rptr)->type ==
5732 		    T_SVR4_OPTMGMT_REQ) ||
5733 		    (((union T_primitives *)mp->b_rptr)->type ==
5734 		    T_OPTMGMT_REQ))) {
5735 			/*
5736 			 * This is the only TPI primitive supported. Its
5737 			 * handling does not require tcp_t, but it does require
5738 			 * conn_t to check permissions.
5739 			 */
5740 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5741 
5742 			if (connp->conn_flags & IPCL_TCPMOD) {
5743 				setfn = tcp_snmp_set;
5744 				getfn = tcp_snmp_get;
5745 			} else {
5746 				setfn = udp_snmp_set;
5747 				getfn = udp_snmp_get;
5748 			}
5749 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5750 				freemsg(mp);
5751 				return;
5752 			}
5753 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5754 		    != NULL)
5755 			qreply(q, mp);
5756 		break;
5757 	case M_FLUSH:
5758 	case M_IOCTL:
5759 		putnext(q, mp);
5760 		break;
5761 	default:
5762 		freemsg(mp);
5763 		break;
5764 	}
5765 }
5766 
5767 /* Return the IP checksum for the IP header at "iph". */
5768 uint16_t
5769 ip_csum_hdr(ipha_t *ipha)
5770 {
5771 	uint16_t	*uph;
5772 	uint32_t	sum;
5773 	int		opt_len;
5774 
5775 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5776 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5777 	uph = (uint16_t *)ipha;
5778 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5779 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5780 	if (opt_len > 0) {
5781 		do {
5782 			sum += uph[10];
5783 			sum += uph[11];
5784 			uph += 2;
5785 		} while (--opt_len);
5786 	}
5787 	sum = (sum & 0xFFFF) + (sum >> 16);
5788 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5789 	if (sum == 0xffff)
5790 		sum = 0;
5791 	return ((uint16_t)sum);
5792 }
5793 
5794 /*
5795  * Called when the module is about to be unloaded
5796  */
5797 void
5798 ip_ddi_destroy(void)
5799 {
5800 	tnet_fini();
5801 
5802 	sctp_ddi_g_destroy();
5803 	tcp_ddi_g_destroy();
5804 	ipsec_policy_g_destroy();
5805 	ipcl_g_destroy();
5806 	ip_net_g_destroy();
5807 	ip_ire_g_fini();
5808 	inet_minor_destroy(ip_minor_arena);
5809 
5810 	netstack_unregister(NS_IP);
5811 }
5812 
5813 /*
5814  * First step in cleanup.
5815  */
5816 /* ARGSUSED */
5817 static void
5818 ip_stack_shutdown(netstackid_t stackid, void *arg)
5819 {
5820 	ip_stack_t *ipst = (ip_stack_t *)arg;
5821 
5822 #ifdef NS_DEBUG
5823 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5824 #endif
5825 
5826 	/* Get rid of loopback interfaces and their IREs */
5827 	ip_loopback_cleanup(ipst);
5828 }
5829 
5830 /*
5831  * Free the IP stack instance.
5832  */
5833 static void
5834 ip_stack_fini(netstackid_t stackid, void *arg)
5835 {
5836 	ip_stack_t *ipst = (ip_stack_t *)arg;
5837 	int ret;
5838 
5839 #ifdef NS_DEBUG
5840 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5841 #endif
5842 	ipv4_hook_destroy(ipst);
5843 	ipv6_hook_destroy(ipst);
5844 	ip_net_destroy(ipst);
5845 
5846 	rw_destroy(&ipst->ips_srcid_lock);
5847 
5848 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5849 	ipst->ips_ip_mibkp = NULL;
5850 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5851 	ipst->ips_icmp_mibkp = NULL;
5852 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5853 	ipst->ips_ip_kstat = NULL;
5854 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5855 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5856 	ipst->ips_ip6_kstat = NULL;
5857 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5858 
5859 	nd_free(&ipst->ips_ip_g_nd);
5860 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5861 	ipst->ips_param_arr = NULL;
5862 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5863 	ipst->ips_ndp_arr = NULL;
5864 
5865 	ip_mrouter_stack_destroy(ipst);
5866 
5867 	mutex_destroy(&ipst->ips_ip_mi_lock);
5868 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5869 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5870 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5871 
5872 	ret = untimeout(ipst->ips_igmp_timeout_id);
5873 	if (ret == -1) {
5874 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5875 	} else {
5876 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5877 		ipst->ips_igmp_timeout_id = 0;
5878 	}
5879 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5880 	if (ret == -1) {
5881 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5882 	} else {
5883 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5884 		ipst->ips_igmp_slowtimeout_id = 0;
5885 	}
5886 	ret = untimeout(ipst->ips_mld_timeout_id);
5887 	if (ret == -1) {
5888 		ASSERT(ipst->ips_mld_timeout_id == 0);
5889 	} else {
5890 		ASSERT(ipst->ips_mld_timeout_id != 0);
5891 		ipst->ips_mld_timeout_id = 0;
5892 	}
5893 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5894 	if (ret == -1) {
5895 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5896 	} else {
5897 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5898 		ipst->ips_mld_slowtimeout_id = 0;
5899 	}
5900 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5901 	if (ret == -1) {
5902 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5903 	} else {
5904 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5905 		ipst->ips_ip_ire_expire_id = 0;
5906 	}
5907 
5908 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5909 	mutex_destroy(&ipst->ips_mld_timer_lock);
5910 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5911 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5912 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5913 	rw_destroy(&ipst->ips_ill_g_lock);
5914 
5915 	ip_ire_fini(ipst);
5916 	ip6_asp_free(ipst);
5917 	conn_drain_fini(ipst);
5918 	ipcl_destroy(ipst);
5919 
5920 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5921 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5922 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5923 	ipst->ips_ndp4 = NULL;
5924 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5925 	ipst->ips_ndp6 = NULL;
5926 
5927 	if (ipst->ips_loopback_ksp != NULL) {
5928 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5929 		ipst->ips_loopback_ksp = NULL;
5930 	}
5931 
5932 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5933 	ipst->ips_phyint_g_list = NULL;
5934 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5935 	ipst->ips_ill_g_heads = NULL;
5936 
5937 	kmem_free(ipst, sizeof (*ipst));
5938 }
5939 
5940 /*
5941  * Called when the IP kernel module is loaded into the kernel
5942  */
5943 void
5944 ip_ddi_init(void)
5945 {
5946 	TCP6_MAJ = ddi_name_to_major(TCP6);
5947 	TCP_MAJ	= ddi_name_to_major(TCP);
5948 	SCTP_MAJ = ddi_name_to_major(SCTP);
5949 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5950 
5951 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5952 
5953 	/*
5954 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5955 	 * initial devices: ip, ip6, tcp, tcp6.
5956 	 */
5957 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5958 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5959 		cmn_err(CE_PANIC,
5960 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5961 	}
5962 
5963 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5964 
5965 	ipcl_g_init();
5966 	ip_ire_g_init();
5967 	ip_net_g_init();
5968 
5969 #ifdef ILL_DEBUG
5970 	/* Default cleanup function */
5971 	ip_cleanup_func = ip_thread_exit;
5972 #endif
5973 
5974 	/*
5975 	 * We want to be informed each time a stack is created or
5976 	 * destroyed in the kernel, so we can maintain the
5977 	 * set of udp_stack_t's.
5978 	 */
5979 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5980 	    ip_stack_fini);
5981 
5982 	ipsec_policy_g_init();
5983 	tcp_ddi_g_init();
5984 	sctp_ddi_g_init();
5985 
5986 	tnet_init();
5987 }
5988 
5989 /*
5990  * Initialize the IP stack instance.
5991  */
5992 static void *
5993 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5994 {
5995 	ip_stack_t	*ipst;
5996 	ipparam_t	*pa;
5997 	ipndp_t		*na;
5998 
5999 #ifdef NS_DEBUG
6000 	printf("ip_stack_init(stack %d)\n", stackid);
6001 #endif
6002 
6003 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
6004 	ipst->ips_netstack = ns;
6005 
6006 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
6007 	    KM_SLEEP);
6008 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
6009 	    KM_SLEEP);
6010 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6011 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
6012 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6013 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
6014 
6015 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6016 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6017 	ipst->ips_igmp_deferred_next = INFINITY;
6018 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6019 	ipst->ips_mld_deferred_next = INFINITY;
6020 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6021 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6022 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6023 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6024 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6025 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6026 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6027 
6028 	ipcl_init(ipst);
6029 	ip_ire_init(ipst);
6030 	ip6_asp_init(ipst);
6031 	ipif_init(ipst);
6032 	conn_drain_init(ipst);
6033 	ip_mrouter_stack_init(ipst);
6034 
6035 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6036 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6037 
6038 	ipst->ips_ip_multirt_log_interval = 1000;
6039 
6040 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6041 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6042 	ipst->ips_ill_index = 1;
6043 
6044 	ipst->ips_saved_ip_g_forward = -1;
6045 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6046 
6047 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6048 	ipst->ips_param_arr = pa;
6049 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6050 
6051 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6052 	ipst->ips_ndp_arr = na;
6053 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6054 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6055 	    (caddr_t)&ipst->ips_ip_g_forward;
6056 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6057 	    (caddr_t)&ipst->ips_ipv6_forward;
6058 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6059 	    "ip_cgtp_filter") == 0);
6060 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6061 	    (caddr_t)&ip_cgtp_filter;
6062 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6063 	    "ipmp_hook_emulation") == 0);
6064 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6065 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6066 
6067 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6068 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6069 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6070 
6071 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6072 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6073 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6074 	ipst->ips_ip6_kstat =
6075 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6076 
6077 	ipst->ips_ipmp_enable_failback = B_TRUE;
6078 
6079 	ipst->ips_ip_src_id = 1;
6080 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6081 
6082 	ip_net_init(ipst, ns);
6083 	ipv4_hook_init(ipst);
6084 	ipv6_hook_init(ipst);
6085 
6086 	return (ipst);
6087 }
6088 
6089 /*
6090  * Allocate and initialize a DLPI template of the specified length.  (May be
6091  * called as writer.)
6092  */
6093 mblk_t *
6094 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6095 {
6096 	mblk_t	*mp;
6097 
6098 	mp = allocb(len, BPRI_MED);
6099 	if (!mp)
6100 		return (NULL);
6101 
6102 	/*
6103 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6104 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6105 	 * that other DLPI are M_PROTO.
6106 	 */
6107 	if (prim == DL_INFO_REQ) {
6108 		mp->b_datap->db_type = M_PCPROTO;
6109 	} else {
6110 		mp->b_datap->db_type = M_PROTO;
6111 	}
6112 
6113 	mp->b_wptr = mp->b_rptr + len;
6114 	bzero(mp->b_rptr, len);
6115 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6116 	return (mp);
6117 }
6118 
6119 const char *
6120 dlpi_prim_str(int prim)
6121 {
6122 	switch (prim) {
6123 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6124 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6125 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6126 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6127 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6128 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6129 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6130 	case DL_OK_ACK:		return ("DL_OK_ACK");
6131 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6132 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6133 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6134 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6135 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6136 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6137 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6138 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6139 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6140 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6141 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6142 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6143 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6144 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6145 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6146 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6147 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6148 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6149 	default:		return ("<unknown primitive>");
6150 	}
6151 }
6152 
6153 const char *
6154 dlpi_err_str(int err)
6155 {
6156 	switch (err) {
6157 	case DL_ACCESS:		return ("DL_ACCESS");
6158 	case DL_BADADDR:	return ("DL_BADADDR");
6159 	case DL_BADCORR:	return ("DL_BADCORR");
6160 	case DL_BADDATA:	return ("DL_BADDATA");
6161 	case DL_BADPPA:		return ("DL_BADPPA");
6162 	case DL_BADPRIM:	return ("DL_BADPRIM");
6163 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6164 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6165 	case DL_BADSAP:		return ("DL_BADSAP");
6166 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6167 	case DL_BOUND:		return ("DL_BOUND");
6168 	case DL_INITFAILED:	return ("DL_INITFAILED");
6169 	case DL_NOADDR:		return ("DL_NOADDR");
6170 	case DL_NOTINIT:	return ("DL_NOTINIT");
6171 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6172 	case DL_SYSERR:		return ("DL_SYSERR");
6173 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6174 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6175 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6176 	case DL_TOOMANY:	return ("DL_TOOMANY");
6177 	case DL_NOTENAB:	return ("DL_NOTENAB");
6178 	case DL_BUSY:		return ("DL_BUSY");
6179 	case DL_NOAUTO:		return ("DL_NOAUTO");
6180 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6181 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6182 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6183 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6184 	case DL_PENDING:	return ("DL_PENDING");
6185 	default:		return ("<unknown error>");
6186 	}
6187 }
6188 
6189 /*
6190  * Debug formatting routine.  Returns a character string representation of the
6191  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6192  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6193  *
6194  * Once the ndd table-printing interfaces are removed, this can be changed to
6195  * standard dotted-decimal form.
6196  */
6197 char *
6198 ip_dot_addr(ipaddr_t addr, char *buf)
6199 {
6200 	uint8_t *ap = (uint8_t *)&addr;
6201 
6202 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6203 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6204 	return (buf);
6205 }
6206 
6207 /*
6208  * Write the given MAC address as a printable string in the usual colon-
6209  * separated format.
6210  */
6211 const char *
6212 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6213 {
6214 	char *bp;
6215 
6216 	if (alen == 0 || buflen < 4)
6217 		return ("?");
6218 	bp = buf;
6219 	for (;;) {
6220 		/*
6221 		 * If there are more MAC address bytes available, but we won't
6222 		 * have any room to print them, then add "..." to the string
6223 		 * instead.  See below for the 'magic number' explanation.
6224 		 */
6225 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6226 			(void) strcpy(bp, "...");
6227 			break;
6228 		}
6229 		(void) sprintf(bp, "%02x", *addr++);
6230 		bp += 2;
6231 		if (--alen == 0)
6232 			break;
6233 		*bp++ = ':';
6234 		buflen -= 3;
6235 		/*
6236 		 * At this point, based on the first 'if' statement above,
6237 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6238 		 * buflen >= 4.  The first case leaves room for the final "xx"
6239 		 * number and trailing NUL byte.  The second leaves room for at
6240 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6241 		 * that statement.
6242 		 */
6243 	}
6244 	return (buf);
6245 }
6246 
6247 /*
6248  * Send an ICMP error after patching up the packet appropriately.  Returns
6249  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6250  */
6251 static boolean_t
6252 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6253     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6254     zoneid_t zoneid, ip_stack_t *ipst)
6255 {
6256 	ipha_t *ipha;
6257 	mblk_t *first_mp;
6258 	boolean_t secure;
6259 	unsigned char db_type;
6260 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6261 
6262 	first_mp = mp;
6263 	if (mctl_present) {
6264 		mp = mp->b_cont;
6265 		secure = ipsec_in_is_secure(first_mp);
6266 		ASSERT(mp != NULL);
6267 	} else {
6268 		/*
6269 		 * If this is an ICMP error being reported - which goes
6270 		 * up as M_CTLs, we need to convert them to M_DATA till
6271 		 * we finish checking with global policy because
6272 		 * ipsec_check_global_policy() assumes M_DATA as clear
6273 		 * and M_CTL as secure.
6274 		 */
6275 		db_type = DB_TYPE(mp);
6276 		DB_TYPE(mp) = M_DATA;
6277 		secure = B_FALSE;
6278 	}
6279 	/*
6280 	 * We are generating an icmp error for some inbound packet.
6281 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6282 	 * Before we generate an error, check with global policy
6283 	 * to see whether this is allowed to enter the system. As
6284 	 * there is no "conn", we are checking with global policy.
6285 	 */
6286 	ipha = (ipha_t *)mp->b_rptr;
6287 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6288 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6289 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6290 		if (first_mp == NULL)
6291 			return (B_FALSE);
6292 	}
6293 
6294 	if (!mctl_present)
6295 		DB_TYPE(mp) = db_type;
6296 
6297 	if (flags & IP_FF_SEND_ICMP) {
6298 		if (flags & IP_FF_HDR_COMPLETE) {
6299 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6300 				freemsg(first_mp);
6301 				return (B_TRUE);
6302 			}
6303 		}
6304 		if (flags & IP_FF_CKSUM) {
6305 			/*
6306 			 * Have to correct checksum since
6307 			 * the packet might have been
6308 			 * fragmented and the reassembly code in ip_rput
6309 			 * does not restore the IP checksum.
6310 			 */
6311 			ipha->ipha_hdr_checksum = 0;
6312 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6313 		}
6314 		switch (icmp_type) {
6315 		case ICMP_DEST_UNREACHABLE:
6316 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6317 			    ipst);
6318 			break;
6319 		default:
6320 			freemsg(first_mp);
6321 			break;
6322 		}
6323 	} else {
6324 		freemsg(first_mp);
6325 		return (B_FALSE);
6326 	}
6327 
6328 	return (B_TRUE);
6329 }
6330 
6331 /*
6332  * Used to send an ICMP error message when a packet is received for
6333  * a protocol that is not supported. The mblk passed as argument
6334  * is consumed by this function.
6335  */
6336 void
6337 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6338     ip_stack_t *ipst)
6339 {
6340 	mblk_t *mp;
6341 	ipha_t *ipha;
6342 	ill_t *ill;
6343 	ipsec_in_t *ii;
6344 
6345 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6346 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6347 
6348 	mp = ipsec_mp->b_cont;
6349 	ipsec_mp->b_cont = NULL;
6350 	ipha = (ipha_t *)mp->b_rptr;
6351 	/* Get ill from index in ipsec_in_t. */
6352 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6353 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6354 	    ipst);
6355 	if (ill != NULL) {
6356 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6357 			if (ip_fanout_send_icmp(q, mp, flags,
6358 			    ICMP_DEST_UNREACHABLE,
6359 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6360 				BUMP_MIB(ill->ill_ip_mib,
6361 				    ipIfStatsInUnknownProtos);
6362 			}
6363 		} else {
6364 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6365 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6366 			    0, B_FALSE, zoneid, ipst)) {
6367 				BUMP_MIB(ill->ill_ip_mib,
6368 				    ipIfStatsInUnknownProtos);
6369 			}
6370 		}
6371 		ill_refrele(ill);
6372 	} else { /* re-link for the freemsg() below. */
6373 		ipsec_mp->b_cont = mp;
6374 	}
6375 
6376 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6377 	freemsg(ipsec_mp);
6378 }
6379 
6380 /*
6381  * See if the inbound datagram has had IPsec processing applied to it.
6382  */
6383 boolean_t
6384 ipsec_in_is_secure(mblk_t *ipsec_mp)
6385 {
6386 	ipsec_in_t *ii;
6387 
6388 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6389 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6390 
6391 	if (ii->ipsec_in_loopback) {
6392 		return (ii->ipsec_in_secure);
6393 	} else {
6394 		return (ii->ipsec_in_ah_sa != NULL ||
6395 		    ii->ipsec_in_esp_sa != NULL ||
6396 		    ii->ipsec_in_decaps);
6397 	}
6398 }
6399 
6400 /*
6401  * Handle protocols with which IP is less intimate.  There
6402  * can be more than one stream bound to a particular
6403  * protocol.  When this is the case, normally each one gets a copy
6404  * of any incoming packets.
6405  *
6406  * IPSEC NOTE :
6407  *
6408  * Don't allow a secure packet going up a non-secure connection.
6409  * We don't allow this because
6410  *
6411  * 1) Reply might go out in clear which will be dropped at
6412  *    the sending side.
6413  * 2) If the reply goes out in clear it will give the
6414  *    adversary enough information for getting the key in
6415  *    most of the cases.
6416  *
6417  * Moreover getting a secure packet when we expect clear
6418  * implies that SA's were added without checking for
6419  * policy on both ends. This should not happen once ISAKMP
6420  * is used to negotiate SAs as SAs will be added only after
6421  * verifying the policy.
6422  *
6423  * NOTE : If the packet was tunneled and not multicast we only send
6424  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6425  * back to delivering packets to AF_INET6 raw sockets.
6426  *
6427  * IPQoS Notes:
6428  * Once we have determined the client, invoke IPPF processing.
6429  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6430  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6431  * ip_policy will be false.
6432  *
6433  * Zones notes:
6434  * Currently only applications in the global zone can create raw sockets for
6435  * protocols other than ICMP. So unlike the broadcast / multicast case of
6436  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6437  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6438  */
6439 static void
6440 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6441     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6442     zoneid_t zoneid)
6443 {
6444 	queue_t	*rq;
6445 	mblk_t	*mp1, *first_mp1;
6446 	uint_t	protocol = ipha->ipha_protocol;
6447 	ipaddr_t dst;
6448 	boolean_t one_only;
6449 	mblk_t *first_mp = mp;
6450 	boolean_t secure;
6451 	uint32_t ill_index;
6452 	conn_t	*connp, *first_connp, *next_connp;
6453 	connf_t	*connfp;
6454 	boolean_t shared_addr;
6455 	mib2_ipIfStatsEntry_t *mibptr;
6456 	ip_stack_t *ipst = recv_ill->ill_ipst;
6457 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6458 
6459 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6460 	if (mctl_present) {
6461 		mp = first_mp->b_cont;
6462 		secure = ipsec_in_is_secure(first_mp);
6463 		ASSERT(mp != NULL);
6464 	} else {
6465 		secure = B_FALSE;
6466 	}
6467 	dst = ipha->ipha_dst;
6468 	/*
6469 	 * If the packet was tunneled and not multicast we only send to it
6470 	 * the first match.
6471 	 */
6472 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6473 	    !CLASSD(dst));
6474 
6475 	shared_addr = (zoneid == ALL_ZONES);
6476 	if (shared_addr) {
6477 		/*
6478 		 * We don't allow multilevel ports for raw IP, so no need to
6479 		 * check for that here.
6480 		 */
6481 		zoneid = tsol_packet_to_zoneid(mp);
6482 	}
6483 
6484 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6485 	mutex_enter(&connfp->connf_lock);
6486 	connp = connfp->connf_head;
6487 	for (connp = connfp->connf_head; connp != NULL;
6488 	    connp = connp->conn_next) {
6489 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6490 		    zoneid) &&
6491 		    (!is_system_labeled() ||
6492 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6493 		    connp))) {
6494 			break;
6495 		}
6496 	}
6497 
6498 	if (connp == NULL || connp->conn_upq == NULL) {
6499 		/*
6500 		 * No one bound to these addresses.  Is
6501 		 * there a client that wants all
6502 		 * unclaimed datagrams?
6503 		 */
6504 		mutex_exit(&connfp->connf_lock);
6505 		/*
6506 		 * Check for IPPROTO_ENCAP...
6507 		 */
6508 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6509 			/*
6510 			 * If an IPsec mblk is here on a multicast
6511 			 * tunnel (using ip_mroute stuff), check policy here,
6512 			 * THEN ship off to ip_mroute_decap().
6513 			 *
6514 			 * BTW,  If I match a configured IP-in-IP
6515 			 * tunnel, this path will not be reached, and
6516 			 * ip_mroute_decap will never be called.
6517 			 */
6518 			first_mp = ipsec_check_global_policy(first_mp, connp,
6519 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6520 			if (first_mp != NULL) {
6521 				if (mctl_present)
6522 					freeb(first_mp);
6523 				ip_mroute_decap(q, mp, ill);
6524 			} /* Else we already freed everything! */
6525 		} else {
6526 			/*
6527 			 * Otherwise send an ICMP protocol unreachable.
6528 			 */
6529 			if (ip_fanout_send_icmp(q, first_mp, flags,
6530 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6531 			    mctl_present, zoneid, ipst)) {
6532 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6533 			}
6534 		}
6535 		return;
6536 	}
6537 	CONN_INC_REF(connp);
6538 	first_connp = connp;
6539 
6540 	/*
6541 	 * Only send message to one tunnel driver by immediately
6542 	 * terminating the loop.
6543 	 */
6544 	connp = one_only ? NULL : connp->conn_next;
6545 
6546 	for (;;) {
6547 		while (connp != NULL) {
6548 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6549 			    flags, zoneid) &&
6550 			    (!is_system_labeled() ||
6551 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6552 			    shared_addr, connp)))
6553 				break;
6554 			connp = connp->conn_next;
6555 		}
6556 
6557 		/*
6558 		 * Copy the packet.
6559 		 */
6560 		if (connp == NULL || connp->conn_upq == NULL ||
6561 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6562 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6563 			/*
6564 			 * No more interested clients or memory
6565 			 * allocation failed
6566 			 */
6567 			connp = first_connp;
6568 			break;
6569 		}
6570 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6571 		CONN_INC_REF(connp);
6572 		mutex_exit(&connfp->connf_lock);
6573 		rq = connp->conn_rq;
6574 		if (!canputnext(rq)) {
6575 			if (flags & IP_FF_RAWIP) {
6576 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6577 			} else {
6578 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6579 			}
6580 
6581 			freemsg(first_mp1);
6582 		} else {
6583 			/*
6584 			 * Don't enforce here if we're an actual tunnel -
6585 			 * let "tun" do it instead.
6586 			 */
6587 			if (!IPCL_IS_IPTUN(connp) &&
6588 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6589 			    secure)) {
6590 				first_mp1 = ipsec_check_inbound_policy
6591 				    (first_mp1, connp, ipha, NULL,
6592 				    mctl_present);
6593 			}
6594 			if (first_mp1 != NULL) {
6595 				int in_flags = 0;
6596 				/*
6597 				 * ip_fanout_proto also gets called from
6598 				 * icmp_inbound_error_fanout, in which case
6599 				 * the msg type is M_CTL.  Don't add info
6600 				 * in this case for the time being. In future
6601 				 * when there is a need for knowing the
6602 				 * inbound iface index for ICMP error msgs,
6603 				 * then this can be changed.
6604 				 */
6605 				if (connp->conn_recvif)
6606 					in_flags = IPF_RECVIF;
6607 				/*
6608 				 * The ULP may support IP_RECVPKTINFO for both
6609 				 * IP v4 and v6 so pass the appropriate argument
6610 				 * based on conn IP version.
6611 				 */
6612 				if (connp->conn_ip_recvpktinfo) {
6613 					if (connp->conn_af_isv6) {
6614 						/*
6615 						 * V6 only needs index
6616 						 */
6617 						in_flags |= IPF_RECVIF;
6618 					} else {
6619 						/*
6620 						 * V4 needs index +
6621 						 * matching address.
6622 						 */
6623 						in_flags |= IPF_RECVADDR;
6624 					}
6625 				}
6626 				if ((in_flags != 0) &&
6627 				    (mp->b_datap->db_type != M_CTL)) {
6628 					/*
6629 					 * the actual data will be
6630 					 * contained in b_cont upon
6631 					 * successful return of the
6632 					 * following call else
6633 					 * original mblk is returned
6634 					 */
6635 					ASSERT(recv_ill != NULL);
6636 					mp1 = ip_add_info(mp1, recv_ill,
6637 					    in_flags, IPCL_ZONEID(connp), ipst);
6638 				}
6639 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6640 				if (mctl_present)
6641 					freeb(first_mp1);
6642 				putnext(rq, mp1);
6643 			}
6644 		}
6645 		mutex_enter(&connfp->connf_lock);
6646 		/* Follow the next pointer before releasing the conn. */
6647 		next_connp = connp->conn_next;
6648 		CONN_DEC_REF(connp);
6649 		connp = next_connp;
6650 	}
6651 
6652 	/* Last one.  Send it upstream. */
6653 	mutex_exit(&connfp->connf_lock);
6654 
6655 	/*
6656 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6657 	 * will be set to false.
6658 	 */
6659 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6660 		ill_index = ill->ill_phyint->phyint_ifindex;
6661 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6662 		if (mp == NULL) {
6663 			CONN_DEC_REF(connp);
6664 			if (mctl_present) {
6665 				freeb(first_mp);
6666 			}
6667 			return;
6668 		}
6669 	}
6670 
6671 	rq = connp->conn_rq;
6672 	if (!canputnext(rq)) {
6673 		if (flags & IP_FF_RAWIP) {
6674 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6675 		} else {
6676 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6677 		}
6678 
6679 		freemsg(first_mp);
6680 	} else {
6681 		if (IPCL_IS_IPTUN(connp)) {
6682 			/*
6683 			 * Tunneled packet.  We enforce policy in the tunnel
6684 			 * module itself.
6685 			 *
6686 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6687 			 * a policy check.
6688 			 */
6689 			putnext(rq, first_mp);
6690 			CONN_DEC_REF(connp);
6691 			return;
6692 		}
6693 
6694 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6695 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6696 			    ipha, NULL, mctl_present);
6697 		}
6698 
6699 		if (first_mp != NULL) {
6700 			int in_flags = 0;
6701 
6702 			/*
6703 			 * ip_fanout_proto also gets called
6704 			 * from icmp_inbound_error_fanout, in
6705 			 * which case the msg type is M_CTL.
6706 			 * Don't add info in this case for time
6707 			 * being. In future when there is a
6708 			 * need for knowing the inbound iface
6709 			 * index for ICMP error msgs, then this
6710 			 * can be changed
6711 			 */
6712 			if (connp->conn_recvif)
6713 				in_flags = IPF_RECVIF;
6714 			if (connp->conn_ip_recvpktinfo) {
6715 				if (connp->conn_af_isv6) {
6716 					/*
6717 					 * V6 only needs index
6718 					 */
6719 					in_flags |= IPF_RECVIF;
6720 				} else {
6721 					/*
6722 					 * V4 needs index +
6723 					 * matching address.
6724 					 */
6725 					in_flags |= IPF_RECVADDR;
6726 				}
6727 			}
6728 			if ((in_flags != 0) &&
6729 			    (mp->b_datap->db_type != M_CTL)) {
6730 
6731 				/*
6732 				 * the actual data will be contained in
6733 				 * b_cont upon successful return
6734 				 * of the following call else original
6735 				 * mblk is returned
6736 				 */
6737 				ASSERT(recv_ill != NULL);
6738 				mp = ip_add_info(mp, recv_ill,
6739 				    in_flags, IPCL_ZONEID(connp), ipst);
6740 			}
6741 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6742 			putnext(rq, mp);
6743 			if (mctl_present)
6744 				freeb(first_mp);
6745 		}
6746 	}
6747 	CONN_DEC_REF(connp);
6748 }
6749 
6750 /*
6751  * Fanout for TCP packets
6752  * The caller puts <fport, lport> in the ports parameter.
6753  *
6754  * IPQoS Notes
6755  * Before sending it to the client, invoke IPPF processing.
6756  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6757  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6758  * ip_policy is false.
6759  */
6760 static void
6761 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6762     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6763 {
6764 	mblk_t  *first_mp;
6765 	boolean_t secure;
6766 	uint32_t ill_index;
6767 	int	ip_hdr_len;
6768 	tcph_t	*tcph;
6769 	boolean_t syn_present = B_FALSE;
6770 	conn_t	*connp;
6771 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6772 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6773 
6774 	ASSERT(recv_ill != NULL);
6775 
6776 	first_mp = mp;
6777 	if (mctl_present) {
6778 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6779 		mp = first_mp->b_cont;
6780 		secure = ipsec_in_is_secure(first_mp);
6781 		ASSERT(mp != NULL);
6782 	} else {
6783 		secure = B_FALSE;
6784 	}
6785 
6786 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6787 
6788 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6789 	    zoneid, ipst)) == NULL) {
6790 		/*
6791 		 * No connected connection or listener. Send a
6792 		 * TH_RST via tcp_xmit_listeners_reset.
6793 		 */
6794 
6795 		/* Initiate IPPf processing, if needed. */
6796 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6797 			uint32_t ill_index;
6798 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6799 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6800 			if (first_mp == NULL)
6801 				return;
6802 		}
6803 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6804 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6805 		    zoneid));
6806 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6807 		    ipst->ips_netstack->netstack_tcp);
6808 		return;
6809 	}
6810 
6811 	/*
6812 	 * Allocate the SYN for the TCP connection here itself
6813 	 */
6814 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6815 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6816 		if (IPCL_IS_TCP(connp)) {
6817 			squeue_t *sqp;
6818 
6819 			/*
6820 			 * For fused tcp loopback, assign the eager's
6821 			 * squeue to be that of the active connect's.
6822 			 * Note that we don't check for IP_FF_LOOPBACK
6823 			 * here since this routine gets called only
6824 			 * for loopback (unlike the IPv6 counterpart).
6825 			 */
6826 			ASSERT(Q_TO_CONN(q) != NULL);
6827 			if (do_tcp_fusion &&
6828 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6829 			    !secure &&
6830 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6831 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6832 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6833 				sqp = Q_TO_CONN(q)->conn_sqp;
6834 			} else {
6835 				sqp = IP_SQUEUE_GET(lbolt);
6836 			}
6837 
6838 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6839 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6840 			syn_present = B_TRUE;
6841 		}
6842 	}
6843 
6844 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6845 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6846 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6847 		if ((flags & TH_RST) || (flags & TH_URG)) {
6848 			CONN_DEC_REF(connp);
6849 			freemsg(first_mp);
6850 			return;
6851 		}
6852 		if (flags & TH_ACK) {
6853 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6854 			    ipst->ips_netstack->netstack_tcp);
6855 			CONN_DEC_REF(connp);
6856 			return;
6857 		}
6858 
6859 		CONN_DEC_REF(connp);
6860 		freemsg(first_mp);
6861 		return;
6862 	}
6863 
6864 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6865 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6866 		    NULL, mctl_present);
6867 		if (first_mp == NULL) {
6868 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6869 			CONN_DEC_REF(connp);
6870 			return;
6871 		}
6872 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6873 			ASSERT(syn_present);
6874 			if (mctl_present) {
6875 				ASSERT(first_mp != mp);
6876 				first_mp->b_datap->db_struioflag |=
6877 				    STRUIO_POLICY;
6878 			} else {
6879 				ASSERT(first_mp == mp);
6880 				mp->b_datap->db_struioflag &=
6881 				    ~STRUIO_EAGER;
6882 				mp->b_datap->db_struioflag |=
6883 				    STRUIO_POLICY;
6884 			}
6885 		} else {
6886 			/*
6887 			 * Discard first_mp early since we're dealing with a
6888 			 * fully-connected conn_t and tcp doesn't do policy in
6889 			 * this case.
6890 			 */
6891 			if (mctl_present) {
6892 				freeb(first_mp);
6893 				mctl_present = B_FALSE;
6894 			}
6895 			first_mp = mp;
6896 		}
6897 	}
6898 
6899 	/*
6900 	 * Initiate policy processing here if needed. If we get here from
6901 	 * icmp_inbound_error_fanout, ip_policy is false.
6902 	 */
6903 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6904 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6905 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6906 		if (mp == NULL) {
6907 			CONN_DEC_REF(connp);
6908 			if (mctl_present)
6909 				freeb(first_mp);
6910 			return;
6911 		} else if (mctl_present) {
6912 			ASSERT(first_mp != mp);
6913 			first_mp->b_cont = mp;
6914 		} else {
6915 			first_mp = mp;
6916 		}
6917 	}
6918 
6919 
6920 
6921 	/* Handle socket options. */
6922 	if (!syn_present &&
6923 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6924 		/* Add header */
6925 		ASSERT(recv_ill != NULL);
6926 		/*
6927 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6928 		 * IPF_RECVIF.
6929 		 */
6930 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6931 		    ipst);
6932 		if (mp == NULL) {
6933 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6934 			CONN_DEC_REF(connp);
6935 			if (mctl_present)
6936 				freeb(first_mp);
6937 			return;
6938 		} else if (mctl_present) {
6939 			/*
6940 			 * ip_add_info might return a new mp.
6941 			 */
6942 			ASSERT(first_mp != mp);
6943 			first_mp->b_cont = mp;
6944 		} else {
6945 			first_mp = mp;
6946 		}
6947 	}
6948 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6949 	if (IPCL_IS_TCP(connp)) {
6950 		/* do not drain, certain use cases can blow the stack */
6951 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6952 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6953 	} else {
6954 		putnext(connp->conn_rq, first_mp);
6955 		CONN_DEC_REF(connp);
6956 	}
6957 }
6958 
6959 /*
6960  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6961  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6962  * Caller is responsible for dropping references to the conn, and freeing
6963  * first_mp.
6964  *
6965  * IPQoS Notes
6966  * Before sending it to the client, invoke IPPF processing. Policy processing
6967  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6968  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6969  * ip_wput_local, ip_policy is false.
6970  */
6971 static void
6972 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6973     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6974     boolean_t ip_policy)
6975 {
6976 	boolean_t	mctl_present = (first_mp != NULL);
6977 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6978 	uint32_t	ill_index;
6979 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6980 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6981 
6982 	ASSERT(ill != NULL);
6983 
6984 	if (mctl_present)
6985 		first_mp->b_cont = mp;
6986 	else
6987 		first_mp = mp;
6988 
6989 	if (CONN_UDP_FLOWCTLD(connp)) {
6990 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6991 		freemsg(first_mp);
6992 		return;
6993 	}
6994 
6995 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6996 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6997 		    NULL, mctl_present);
6998 		if (first_mp == NULL) {
6999 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7000 			return;	/* Freed by ipsec_check_inbound_policy(). */
7001 		}
7002 	}
7003 	if (mctl_present)
7004 		freeb(first_mp);
7005 
7006 	/* Handle options. */
7007 	if (connp->conn_recvif)
7008 		in_flags = IPF_RECVIF;
7009 	/*
7010 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7011 	 * passed to ip_add_info is based on IP version of connp.
7012 	 */
7013 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7014 		if (connp->conn_af_isv6) {
7015 			/*
7016 			 * V6 only needs index
7017 			 */
7018 			in_flags |= IPF_RECVIF;
7019 		} else {
7020 			/*
7021 			 * V4 needs index + matching address.
7022 			 */
7023 			in_flags |= IPF_RECVADDR;
7024 		}
7025 	}
7026 
7027 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7028 		in_flags |= IPF_RECVSLLA;
7029 
7030 	/*
7031 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7032 	 * freed if the packet is dropped. The caller will do so.
7033 	 */
7034 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7035 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7036 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7037 		if (mp == NULL) {
7038 			return;
7039 		}
7040 	}
7041 	if ((in_flags != 0) &&
7042 	    (mp->b_datap->db_type != M_CTL)) {
7043 		/*
7044 		 * The actual data will be contained in b_cont
7045 		 * upon successful return of the following call
7046 		 * else original mblk is returned
7047 		 */
7048 		ASSERT(recv_ill != NULL);
7049 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7050 		    ipst);
7051 	}
7052 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7053 	/* Send it upstream */
7054 	CONN_UDP_RECV(connp, mp);
7055 }
7056 
7057 /*
7058  * Fanout for UDP packets.
7059  * The caller puts <fport, lport> in the ports parameter.
7060  *
7061  * If SO_REUSEADDR is set all multicast and broadcast packets
7062  * will be delivered to all streams bound to the same port.
7063  *
7064  * Zones notes:
7065  * Multicast and broadcast packets will be distributed to streams in all zones.
7066  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7067  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7068  * packets. To maintain this behavior with multiple zones, the conns are grouped
7069  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7070  * each zone. If unset, all the following conns in the same zone are skipped.
7071  */
7072 static void
7073 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7074     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7075     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7076 {
7077 	uint32_t	dstport, srcport;
7078 	ipaddr_t	dst;
7079 	mblk_t		*first_mp;
7080 	boolean_t	secure;
7081 	in6_addr_t	v6src;
7082 	conn_t		*connp;
7083 	connf_t		*connfp;
7084 	conn_t		*first_connp;
7085 	conn_t		*next_connp;
7086 	mblk_t		*mp1, *first_mp1;
7087 	ipaddr_t	src;
7088 	zoneid_t	last_zoneid;
7089 	boolean_t	reuseaddr;
7090 	boolean_t	shared_addr;
7091 	ip_stack_t	*ipst;
7092 
7093 	ASSERT(recv_ill != NULL);
7094 	ipst = recv_ill->ill_ipst;
7095 
7096 	first_mp = mp;
7097 	if (mctl_present) {
7098 		mp = first_mp->b_cont;
7099 		first_mp->b_cont = NULL;
7100 		secure = ipsec_in_is_secure(first_mp);
7101 		ASSERT(mp != NULL);
7102 	} else {
7103 		first_mp = NULL;
7104 		secure = B_FALSE;
7105 	}
7106 
7107 	/* Extract ports in net byte order */
7108 	dstport = htons(ntohl(ports) & 0xFFFF);
7109 	srcport = htons(ntohl(ports) >> 16);
7110 	dst = ipha->ipha_dst;
7111 	src = ipha->ipha_src;
7112 
7113 	shared_addr = (zoneid == ALL_ZONES);
7114 	if (shared_addr) {
7115 		/*
7116 		 * No need to handle exclusive-stack zones since ALL_ZONES
7117 		 * only applies to the shared stack.
7118 		 */
7119 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7120 		if (zoneid == ALL_ZONES)
7121 			zoneid = tsol_packet_to_zoneid(mp);
7122 	}
7123 
7124 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7125 	mutex_enter(&connfp->connf_lock);
7126 	connp = connfp->connf_head;
7127 	if (!broadcast && !CLASSD(dst)) {
7128 		/*
7129 		 * Not broadcast or multicast. Send to the one (first)
7130 		 * client we find. No need to check conn_wantpacket()
7131 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7132 		 * IPv4 unicast packets.
7133 		 */
7134 		while ((connp != NULL) &&
7135 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7136 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7137 			connp = connp->conn_next;
7138 		}
7139 
7140 		if (connp == NULL || connp->conn_upq == NULL)
7141 			goto notfound;
7142 
7143 		if (is_system_labeled() &&
7144 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7145 		    connp))
7146 			goto notfound;
7147 
7148 		CONN_INC_REF(connp);
7149 		mutex_exit(&connfp->connf_lock);
7150 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7151 		    flags, recv_ill, ip_policy);
7152 		IP_STAT(ipst, ip_udp_fannorm);
7153 		CONN_DEC_REF(connp);
7154 		return;
7155 	}
7156 
7157 	/*
7158 	 * Broadcast and multicast case
7159 	 *
7160 	 * Need to check conn_wantpacket().
7161 	 * If SO_REUSEADDR has been set on the first we send the
7162 	 * packet to all clients that have joined the group and
7163 	 * match the port.
7164 	 */
7165 
7166 	while (connp != NULL) {
7167 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7168 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7169 		    (!is_system_labeled() ||
7170 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7171 		    connp)))
7172 			break;
7173 		connp = connp->conn_next;
7174 	}
7175 
7176 	if (connp == NULL || connp->conn_upq == NULL)
7177 		goto notfound;
7178 
7179 	first_connp = connp;
7180 	/*
7181 	 * When SO_REUSEADDR is not set, send the packet only to the first
7182 	 * matching connection in its zone by keeping track of the zoneid.
7183 	 */
7184 	reuseaddr = first_connp->conn_reuseaddr;
7185 	last_zoneid = first_connp->conn_zoneid;
7186 
7187 	CONN_INC_REF(connp);
7188 	connp = connp->conn_next;
7189 	for (;;) {
7190 		while (connp != NULL) {
7191 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7192 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7193 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7194 			    (!is_system_labeled() ||
7195 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7196 			    shared_addr, connp)))
7197 				break;
7198 			connp = connp->conn_next;
7199 		}
7200 		/*
7201 		 * Just copy the data part alone. The mctl part is
7202 		 * needed just for verifying policy and it is never
7203 		 * sent up.
7204 		 */
7205 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7206 		    ((mp1 = copymsg(mp)) == NULL))) {
7207 			/*
7208 			 * No more interested clients or memory
7209 			 * allocation failed
7210 			 */
7211 			connp = first_connp;
7212 			break;
7213 		}
7214 		if (connp->conn_zoneid != last_zoneid) {
7215 			/*
7216 			 * Update the zoneid so that the packet isn't sent to
7217 			 * any more conns in the same zone unless SO_REUSEADDR
7218 			 * is set.
7219 			 */
7220 			reuseaddr = connp->conn_reuseaddr;
7221 			last_zoneid = connp->conn_zoneid;
7222 		}
7223 		if (first_mp != NULL) {
7224 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7225 			    ipsec_info_type == IPSEC_IN);
7226 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7227 			    ipst->ips_netstack);
7228 			if (first_mp1 == NULL) {
7229 				freemsg(mp1);
7230 				connp = first_connp;
7231 				break;
7232 			}
7233 		} else {
7234 			first_mp1 = NULL;
7235 		}
7236 		CONN_INC_REF(connp);
7237 		mutex_exit(&connfp->connf_lock);
7238 		/*
7239 		 * IPQoS notes: We don't send the packet for policy
7240 		 * processing here, will do it for the last one (below).
7241 		 * i.e. we do it per-packet now, but if we do policy
7242 		 * processing per-conn, then we would need to do it
7243 		 * here too.
7244 		 */
7245 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7246 		    ipha, flags, recv_ill, B_FALSE);
7247 		mutex_enter(&connfp->connf_lock);
7248 		/* Follow the next pointer before releasing the conn. */
7249 		next_connp = connp->conn_next;
7250 		IP_STAT(ipst, ip_udp_fanmb);
7251 		CONN_DEC_REF(connp);
7252 		connp = next_connp;
7253 	}
7254 
7255 	/* Last one.  Send it upstream. */
7256 	mutex_exit(&connfp->connf_lock);
7257 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7258 	    recv_ill, ip_policy);
7259 	IP_STAT(ipst, ip_udp_fanmb);
7260 	CONN_DEC_REF(connp);
7261 	return;
7262 
7263 notfound:
7264 
7265 	mutex_exit(&connfp->connf_lock);
7266 	IP_STAT(ipst, ip_udp_fanothers);
7267 	/*
7268 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7269 	 * have already been matched above, since they live in the IPv4
7270 	 * fanout tables. This implies we only need to
7271 	 * check for IPv6 in6addr_any endpoints here.
7272 	 * Thus we compare using ipv6_all_zeros instead of the destination
7273 	 * address, except for the multicast group membership lookup which
7274 	 * uses the IPv4 destination.
7275 	 */
7276 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7277 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7278 	mutex_enter(&connfp->connf_lock);
7279 	connp = connfp->connf_head;
7280 	if (!broadcast && !CLASSD(dst)) {
7281 		while (connp != NULL) {
7282 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7283 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7284 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7285 			    !connp->conn_ipv6_v6only)
7286 				break;
7287 			connp = connp->conn_next;
7288 		}
7289 
7290 		if (connp != NULL && is_system_labeled() &&
7291 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7292 		    connp))
7293 			connp = NULL;
7294 
7295 		if (connp == NULL || connp->conn_upq == NULL) {
7296 			/*
7297 			 * No one bound to this port.  Is
7298 			 * there a client that wants all
7299 			 * unclaimed datagrams?
7300 			 */
7301 			mutex_exit(&connfp->connf_lock);
7302 
7303 			if (mctl_present)
7304 				first_mp->b_cont = mp;
7305 			else
7306 				first_mp = mp;
7307 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7308 			    connf_head != NULL) {
7309 				ip_fanout_proto(q, first_mp, ill, ipha,
7310 				    flags | IP_FF_RAWIP, mctl_present,
7311 				    ip_policy, recv_ill, zoneid);
7312 			} else {
7313 				if (ip_fanout_send_icmp(q, first_mp, flags,
7314 				    ICMP_DEST_UNREACHABLE,
7315 				    ICMP_PORT_UNREACHABLE,
7316 				    mctl_present, zoneid, ipst)) {
7317 					BUMP_MIB(ill->ill_ip_mib,
7318 					    udpIfStatsNoPorts);
7319 				}
7320 			}
7321 			return;
7322 		}
7323 
7324 		CONN_INC_REF(connp);
7325 		mutex_exit(&connfp->connf_lock);
7326 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7327 		    flags, recv_ill, ip_policy);
7328 		CONN_DEC_REF(connp);
7329 		return;
7330 	}
7331 	/*
7332 	 * IPv4 multicast packet being delivered to an AF_INET6
7333 	 * in6addr_any endpoint.
7334 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7335 	 * and not conn_wantpacket_v6() since any multicast membership is
7336 	 * for an IPv4-mapped multicast address.
7337 	 * The packet is sent to all clients in all zones that have joined the
7338 	 * group and match the port.
7339 	 */
7340 	while (connp != NULL) {
7341 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7342 		    srcport, v6src) &&
7343 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7344 		    (!is_system_labeled() ||
7345 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7346 		    connp)))
7347 			break;
7348 		connp = connp->conn_next;
7349 	}
7350 
7351 	if (connp == NULL || connp->conn_upq == NULL) {
7352 		/*
7353 		 * No one bound to this port.  Is
7354 		 * there a client that wants all
7355 		 * unclaimed datagrams?
7356 		 */
7357 		mutex_exit(&connfp->connf_lock);
7358 
7359 		if (mctl_present)
7360 			first_mp->b_cont = mp;
7361 		else
7362 			first_mp = mp;
7363 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7364 		    NULL) {
7365 			ip_fanout_proto(q, first_mp, ill, ipha,
7366 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7367 			    recv_ill, zoneid);
7368 		} else {
7369 			/*
7370 			 * We used to attempt to send an icmp error here, but
7371 			 * since this is known to be a multicast packet
7372 			 * and we don't send icmp errors in response to
7373 			 * multicast, just drop the packet and give up sooner.
7374 			 */
7375 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7376 			freemsg(first_mp);
7377 		}
7378 		return;
7379 	}
7380 
7381 	first_connp = connp;
7382 
7383 	CONN_INC_REF(connp);
7384 	connp = connp->conn_next;
7385 	for (;;) {
7386 		while (connp != NULL) {
7387 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7388 			    ipv6_all_zeros, srcport, v6src) &&
7389 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7390 			    (!is_system_labeled() ||
7391 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7392 			    shared_addr, connp)))
7393 				break;
7394 			connp = connp->conn_next;
7395 		}
7396 		/*
7397 		 * Just copy the data part alone. The mctl part is
7398 		 * needed just for verifying policy and it is never
7399 		 * sent up.
7400 		 */
7401 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7402 		    ((mp1 = copymsg(mp)) == NULL))) {
7403 			/*
7404 			 * No more intested clients or memory
7405 			 * allocation failed
7406 			 */
7407 			connp = first_connp;
7408 			break;
7409 		}
7410 		if (first_mp != NULL) {
7411 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7412 			    ipsec_info_type == IPSEC_IN);
7413 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7414 			    ipst->ips_netstack);
7415 			if (first_mp1 == NULL) {
7416 				freemsg(mp1);
7417 				connp = first_connp;
7418 				break;
7419 			}
7420 		} else {
7421 			first_mp1 = NULL;
7422 		}
7423 		CONN_INC_REF(connp);
7424 		mutex_exit(&connfp->connf_lock);
7425 		/*
7426 		 * IPQoS notes: We don't send the packet for policy
7427 		 * processing here, will do it for the last one (below).
7428 		 * i.e. we do it per-packet now, but if we do policy
7429 		 * processing per-conn, then we would need to do it
7430 		 * here too.
7431 		 */
7432 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7433 		    ipha, flags, recv_ill, B_FALSE);
7434 		mutex_enter(&connfp->connf_lock);
7435 		/* Follow the next pointer before releasing the conn. */
7436 		next_connp = connp->conn_next;
7437 		CONN_DEC_REF(connp);
7438 		connp = next_connp;
7439 	}
7440 
7441 	/* Last one.  Send it upstream. */
7442 	mutex_exit(&connfp->connf_lock);
7443 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7444 	    recv_ill, ip_policy);
7445 	CONN_DEC_REF(connp);
7446 }
7447 
7448 /*
7449  * Complete the ip_wput header so that it
7450  * is possible to generate ICMP
7451  * errors.
7452  */
7453 int
7454 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7455 {
7456 	ire_t *ire;
7457 
7458 	if (ipha->ipha_src == INADDR_ANY) {
7459 		ire = ire_lookup_local(zoneid, ipst);
7460 		if (ire == NULL) {
7461 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7462 			return (1);
7463 		}
7464 		ipha->ipha_src = ire->ire_addr;
7465 		ire_refrele(ire);
7466 	}
7467 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7468 	ipha->ipha_hdr_checksum = 0;
7469 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7470 	return (0);
7471 }
7472 
7473 /*
7474  * Nobody should be sending
7475  * packets up this stream
7476  */
7477 static void
7478 ip_lrput(queue_t *q, mblk_t *mp)
7479 {
7480 	mblk_t *mp1;
7481 
7482 	switch (mp->b_datap->db_type) {
7483 	case M_FLUSH:
7484 		/* Turn around */
7485 		if (*mp->b_rptr & FLUSHW) {
7486 			*mp->b_rptr &= ~FLUSHR;
7487 			qreply(q, mp);
7488 			return;
7489 		}
7490 		break;
7491 	}
7492 	/* Could receive messages that passed through ar_rput */
7493 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7494 		mp1->b_prev = mp1->b_next = NULL;
7495 	freemsg(mp);
7496 }
7497 
7498 /* Nobody should be sending packets down this stream */
7499 /* ARGSUSED */
7500 void
7501 ip_lwput(queue_t *q, mblk_t *mp)
7502 {
7503 	freemsg(mp);
7504 }
7505 
7506 /*
7507  * Move the first hop in any source route to ipha_dst and remove that part of
7508  * the source route.  Called by other protocols.  Errors in option formatting
7509  * are ignored - will be handled by ip_wput_options Return the final
7510  * destination (either ipha_dst or the last entry in a source route.)
7511  */
7512 ipaddr_t
7513 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7514 {
7515 	ipoptp_t	opts;
7516 	uchar_t		*opt;
7517 	uint8_t		optval;
7518 	uint8_t		optlen;
7519 	ipaddr_t	dst;
7520 	int		i;
7521 	ire_t		*ire;
7522 	ip_stack_t	*ipst = ns->netstack_ip;
7523 
7524 	ip2dbg(("ip_massage_options\n"));
7525 	dst = ipha->ipha_dst;
7526 	for (optval = ipoptp_first(&opts, ipha);
7527 	    optval != IPOPT_EOL;
7528 	    optval = ipoptp_next(&opts)) {
7529 		opt = opts.ipoptp_cur;
7530 		switch (optval) {
7531 			uint8_t off;
7532 		case IPOPT_SSRR:
7533 		case IPOPT_LSRR:
7534 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7535 				ip1dbg(("ip_massage_options: bad src route\n"));
7536 				break;
7537 			}
7538 			optlen = opts.ipoptp_len;
7539 			off = opt[IPOPT_OFFSET];
7540 			off--;
7541 		redo_srr:
7542 			if (optlen < IP_ADDR_LEN ||
7543 			    off > optlen - IP_ADDR_LEN) {
7544 				/* End of source route */
7545 				ip1dbg(("ip_massage_options: end of SR\n"));
7546 				break;
7547 			}
7548 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7549 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7550 			    ntohl(dst)));
7551 			/*
7552 			 * Check if our address is present more than
7553 			 * once as consecutive hops in source route.
7554 			 * XXX verify per-interface ip_forwarding
7555 			 * for source route?
7556 			 */
7557 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7558 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7559 			if (ire != NULL) {
7560 				ire_refrele(ire);
7561 				off += IP_ADDR_LEN;
7562 				goto redo_srr;
7563 			}
7564 			if (dst == htonl(INADDR_LOOPBACK)) {
7565 				ip1dbg(("ip_massage_options: loopback addr in "
7566 				    "source route!\n"));
7567 				break;
7568 			}
7569 			/*
7570 			 * Update ipha_dst to be the first hop and remove the
7571 			 * first hop from the source route (by overwriting
7572 			 * part of the option with NOP options).
7573 			 */
7574 			ipha->ipha_dst = dst;
7575 			/* Put the last entry in dst */
7576 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7577 			    3;
7578 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7579 
7580 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7581 			    ntohl(dst)));
7582 			/* Move down and overwrite */
7583 			opt[IP_ADDR_LEN] = opt[0];
7584 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7585 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7586 			for (i = 0; i < IP_ADDR_LEN; i++)
7587 				opt[i] = IPOPT_NOP;
7588 			break;
7589 		}
7590 	}
7591 	return (dst);
7592 }
7593 
7594 /*
7595  * This function's job is to forward data to the reverse tunnel (FA->HA)
7596  * after doing a few checks. It is assumed that the incoming interface
7597  * of the packet is always different than the outgoing interface and the
7598  * ire_type of the found ire has to be a non-resolver type.
7599  *
7600  * IPQoS notes
7601  * IP policy is invoked twice for a forwarded packet, once on the read side
7602  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
7603  * enabled.
7604  */
7605 static void
7606 ip_mrtun_forward(ire_t *ire, ill_t *in_ill, mblk_t *mp)
7607 {
7608 	ipha_t		*ipha;
7609 	queue_t		*q;
7610 	uint32_t 	pkt_len;
7611 #define	rptr    ((uchar_t *)ipha)
7612 	uint32_t 	sum;
7613 	uint32_t 	max_frag;
7614 	mblk_t		*first_mp;
7615 	uint32_t	ill_index;
7616 	ipxmit_state_t	pktxmit_state;
7617 	ill_t		*out_ill;
7618 	ip_stack_t	*ipst = in_ill->ill_ipst;
7619 
7620 	ASSERT(ire != NULL);
7621 	ASSERT(ire->ire_ipif->ipif_net_type == IRE_IF_NORESOLVER);
7622 	ASSERT(ire->ire_stq != NULL);
7623 
7624 	/* Initiate read side IPPF processing */
7625 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
7626 		ill_index = in_ill->ill_phyint->phyint_ifindex;
7627 		ip_process(IPP_FWD_IN, &mp, ill_index);
7628 		if (mp == NULL) {
7629 			ip2dbg(("ip_mrtun_forward: inbound pkt "
7630 			    "dropped during IPPF processing\n"));
7631 			return;
7632 		}
7633 	}
7634 
7635 	if (((in_ill->ill_flags & ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
7636 	    ILLF_ROUTER) == 0) ||
7637 	    (in_ill == (ill_t *)ire->ire_stq->q_ptr)) {
7638 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7639 		ip0dbg(("ip_mrtun_forward: Can't forward :"
7640 		    "forwarding is not turned on\n"));
7641 		goto drop_pkt;
7642 	}
7643 
7644 	/*
7645 	 * Don't forward if the interface is down
7646 	 */
7647 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
7648 		goto discard_pkt;
7649 	}
7650 
7651 	ipha = (ipha_t *)mp->b_rptr;
7652 	pkt_len = ntohs(ipha->ipha_length);
7653 	/* Adjust the checksum to reflect the ttl decrement. */
7654 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
7655 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
7656 	if (ipha->ipha_ttl-- <= 1) {
7657 		if (ip_csum_hdr(ipha)) {
7658 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7659 			goto drop_pkt;
7660 		}
7661 		q = ire->ire_stq;
7662 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7663 		    BPRI_HI)) == NULL) {
7664 			goto discard_pkt;
7665 		}
7666 		BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsForwProhibits);
7667 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7668 		/* Sent by forwarding path, and router is global zone */
7669 		icmp_time_exceeded(q, first_mp, ICMP_TTL_EXCEEDED,
7670 		    GLOBAL_ZONEID, ipst);
7671 		return;
7672 	}
7673 
7674 	/* Get the ill_index of the ILL */
7675 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
7676 
7677 	/*
7678 	 * This location is chosen for the placement of the forwarding hook
7679 	 * because at this point we know that we have a path out for the
7680 	 * packet but haven't yet applied any logic (such as fragmenting)
7681 	 * that happen as part of transmitting the packet out.
7682 	 */
7683 	out_ill = ire->ire_ipif->ipif_ill;
7684 
7685 	DTRACE_PROBE4(ip4__forwarding__start,
7686 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7687 
7688 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
7689 	    ipst->ips_ipv4firewall_forwarding,
7690 	    in_ill, out_ill, ipha, mp, mp, ipst);
7691 
7692 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
7693 
7694 	if (mp == NULL)
7695 		return;
7696 	pkt_len = ntohs(ipha->ipha_length);
7697 
7698 	/*
7699 	 * ip_mrtun_forward is only used by foreign agent to reverse
7700 	 * tunnel the incoming packet. So it does not do any option
7701 	 * processing for source routing.
7702 	 */
7703 	max_frag = ire->ire_max_frag;
7704 	if (pkt_len > max_frag) {
7705 		/*
7706 		 * It needs fragging on its way out.  We haven't
7707 		 * verified the header checksum yet.  Since we
7708 		 * are going to put a surely good checksum in the
7709 		 * outgoing header, we have to make sure that it
7710 		 * was good coming in.
7711 		 */
7712 		if (ip_csum_hdr(ipha)) {
7713 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInCksumErrs);
7714 			goto drop_pkt;
7715 		}
7716 
7717 		/* Initiate write side IPPF processing */
7718 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
7719 			ip_process(IPP_FWD_OUT, &mp, ill_index);
7720 			if (mp == NULL) {
7721 				ip2dbg(("ip_mrtun_forward: outbound pkt "\
7722 				    "dropped/deferred during ip policy "\
7723 				    "processing\n"));
7724 				return;
7725 			}
7726 		}
7727 		if ((first_mp = allocb(sizeof (ipsec_info_t),
7728 		    BPRI_HI)) == NULL) {
7729 			goto discard_pkt;
7730 		}
7731 		ip_ipsec_out_prepend(first_mp, mp, in_ill);
7732 		mp = first_mp;
7733 
7734 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
7735 		return;
7736 	}
7737 
7738 	ip2dbg(("ip_mrtun_forward: ire type (%d)\n", ire->ire_type));
7739 
7740 	ASSERT(ire->ire_ipif != NULL);
7741 
7742 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
7743 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
7744 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
7745 	    ipst->ips_ipv4firewall_physical_out,
7746 	    NULL, out_ill, ipha, mp, mp, ipst);
7747 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
7748 	if (mp == NULL)
7749 		return;
7750 
7751 	/* Now send the packet to the tunnel interface */
7752 	mp->b_prev = SET_BPREV_FLAG(IPP_FWD_OUT);
7753 	q = ire->ire_stq;
7754 	pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_FALSE);
7755 	if ((pktxmit_state == SEND_FAILED) ||
7756 	    (pktxmit_state == LLHDR_RESLV_FAILED)) {
7757 		ip2dbg(("ip_mrtun_forward: failed to send packet to ill %p\n",
7758 		    q->q_ptr));
7759 	}
7760 
7761 	return;
7762 discard_pkt:
7763 	BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
7764 drop_pkt:;
7765 	ip2dbg(("ip_mrtun_forward: dropping pkt\n"));
7766 	freemsg(mp);
7767 #undef	rptr
7768 }
7769 
7770 /*
7771  * Fills the ipsec_out_t data structure with appropriate fields and
7772  * prepends it to mp which contains the IP hdr + data that was meant
7773  * to be forwarded. Please note that ipsec_out_info data structure
7774  * is used here to communicate the outgoing ill path at ip_wput()
7775  * for the ICMP error packet. This has nothing to do with ipsec IP
7776  * security. ipsec_out_t is really used to pass the info to the module
7777  * IP where this information cannot be extracted from conn.
7778  * This functions is called by ip_mrtun_forward().
7779  */
7780 void
7781 ip_ipsec_out_prepend(mblk_t *first_mp, mblk_t *mp, ill_t *xmit_ill)
7782 {
7783 	ipsec_out_t	*io;
7784 
7785 	ASSERT(xmit_ill != NULL);
7786 	first_mp->b_datap->db_type = M_CTL;
7787 	first_mp->b_wptr += sizeof (ipsec_info_t);
7788 	/*
7789 	 * This is to pass info to ip_wput in absence of conn.
7790 	 * ipsec_out_secure will be B_FALSE because of this.
7791 	 * Thus ipsec_out_secure being B_FALSE indicates that
7792 	 * this is not IPSEC security related information.
7793 	 */
7794 	bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
7795 	io = (ipsec_out_t *)first_mp->b_rptr;
7796 	io->ipsec_out_type = IPSEC_OUT;
7797 	io->ipsec_out_len = sizeof (ipsec_out_t);
7798 	first_mp->b_cont = mp;
7799 	io->ipsec_out_ill_index =
7800 	    xmit_ill->ill_phyint->phyint_ifindex;
7801 	io->ipsec_out_xmit_if = B_TRUE;
7802 	io->ipsec_out_ns = xmit_ill->ill_ipst->ips_netstack;
7803 }
7804 
7805 /*
7806  * Return the network mask
7807  * associated with the specified address.
7808  */
7809 ipaddr_t
7810 ip_net_mask(ipaddr_t addr)
7811 {
7812 	uchar_t	*up = (uchar_t *)&addr;
7813 	ipaddr_t mask = 0;
7814 	uchar_t	*maskp = (uchar_t *)&mask;
7815 
7816 #if defined(__i386) || defined(__amd64)
7817 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7818 #endif
7819 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7820 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7821 #endif
7822 	if (CLASSD(addr)) {
7823 		maskp[0] = 0xF0;
7824 		return (mask);
7825 	}
7826 	if (addr == 0)
7827 		return (0);
7828 	maskp[0] = 0xFF;
7829 	if ((up[0] & 0x80) == 0)
7830 		return (mask);
7831 
7832 	maskp[1] = 0xFF;
7833 	if ((up[0] & 0xC0) == 0x80)
7834 		return (mask);
7835 
7836 	maskp[2] = 0xFF;
7837 	if ((up[0] & 0xE0) == 0xC0)
7838 		return (mask);
7839 
7840 	/* Must be experimental or multicast, indicate as much */
7841 	return ((ipaddr_t)0);
7842 }
7843 
7844 /*
7845  * Select an ill for the packet by considering load spreading across
7846  * a different ill in the group if dst_ill is part of some group.
7847  */
7848 ill_t *
7849 ip_newroute_get_dst_ill(ill_t *dst_ill)
7850 {
7851 	ill_t *ill;
7852 
7853 	/*
7854 	 * We schedule irrespective of whether the source address is
7855 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7856 	 */
7857 	ill = illgrp_scheduler(dst_ill);
7858 	if (ill == NULL)
7859 		return (NULL);
7860 
7861 	/*
7862 	 * For groups with names ip_sioctl_groupname ensures that all
7863 	 * ills are of same type. For groups without names, ifgrp_insert
7864 	 * ensures this.
7865 	 */
7866 	ASSERT(dst_ill->ill_type == ill->ill_type);
7867 
7868 	return (ill);
7869 }
7870 
7871 /*
7872  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7873  */
7874 ill_t *
7875 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7876     ip_stack_t *ipst)
7877 {
7878 	ill_t *ret_ill;
7879 
7880 	ASSERT(ifindex != 0);
7881 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7882 	    ipst);
7883 	if (ret_ill == NULL ||
7884 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7885 		if (isv6) {
7886 			if (ill != NULL) {
7887 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7888 			} else {
7889 				BUMP_MIB(&ipst->ips_ip6_mib,
7890 				    ipIfStatsOutDiscards);
7891 			}
7892 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7893 			    "bad ifindex %d.\n", ifindex));
7894 		} else {
7895 			if (ill != NULL) {
7896 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7897 			} else {
7898 				BUMP_MIB(&ipst->ips_ip_mib,
7899 				    ipIfStatsOutDiscards);
7900 			}
7901 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7902 			    "bad ifindex %d.\n", ifindex));
7903 		}
7904 		if (ret_ill != NULL)
7905 			ill_refrele(ret_ill);
7906 		freemsg(first_mp);
7907 		return (NULL);
7908 	}
7909 
7910 	return (ret_ill);
7911 }
7912 
7913 /*
7914  * IPv4 -
7915  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7916  * out a packet to a destination address for which we do not have specific
7917  * (or sufficient) routing information.
7918  *
7919  * NOTE : These are the scopes of some of the variables that point at IRE,
7920  *	  which needs to be followed while making any future modifications
7921  *	  to avoid memory leaks.
7922  *
7923  *	- ire and sire are the entries looked up initially by
7924  *	  ire_ftable_lookup.
7925  *	- ipif_ire is used to hold the interface ire associated with
7926  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7927  *	  it before branching out to error paths.
7928  *	- save_ire is initialized before ire_create, so that ire returned
7929  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7930  *	  before breaking out of the switch.
7931  *
7932  *	Thus on failures, we have to REFRELE only ire and sire, if they
7933  *	are not NULL.
7934  */
7935 void
7936 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, ill_t *in_ill, conn_t *connp,
7937     zoneid_t zoneid, ip_stack_t *ipst)
7938 {
7939 	areq_t	*areq;
7940 	ipaddr_t gw = 0;
7941 	ire_t	*ire = NULL;
7942 	mblk_t	*res_mp;
7943 	ipaddr_t *addrp;
7944 	ipaddr_t nexthop_addr;
7945 	ipif_t  *src_ipif = NULL;
7946 	ill_t	*dst_ill = NULL;
7947 	ipha_t  *ipha;
7948 	ire_t	*sire = NULL;
7949 	mblk_t	*first_mp;
7950 	ire_t	*save_ire;
7951 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7952 	ushort_t ire_marks = 0;
7953 	boolean_t mctl_present;
7954 	ipsec_out_t *io;
7955 	mblk_t	*saved_mp;
7956 	ire_t	*first_sire = NULL;
7957 	mblk_t	*copy_mp = NULL;
7958 	mblk_t	*xmit_mp = NULL;
7959 	ipaddr_t save_dst;
7960 	uint32_t multirt_flags =
7961 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7962 	boolean_t multirt_is_resolvable;
7963 	boolean_t multirt_resolve_next;
7964 	boolean_t do_attach_ill = B_FALSE;
7965 	boolean_t ip_nexthop = B_FALSE;
7966 	tsol_ire_gw_secattr_t *attrp = NULL;
7967 	tsol_gcgrp_t *gcgrp = NULL;
7968 	tsol_gcgrp_addr_t ga;
7969 
7970 	if (ip_debug > 2) {
7971 		/* ip1dbg */
7972 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7973 	}
7974 
7975 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7976 	if (mctl_present) {
7977 		io = (ipsec_out_t *)first_mp->b_rptr;
7978 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7979 		ASSERT(zoneid == io->ipsec_out_zoneid);
7980 		ASSERT(zoneid != ALL_ZONES);
7981 	}
7982 
7983 	ipha = (ipha_t *)mp->b_rptr;
7984 
7985 	/* All multicast lookups come through ip_newroute_ipif() */
7986 	if (CLASSD(dst)) {
7987 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7988 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7989 		freemsg(first_mp);
7990 		return;
7991 	}
7992 
7993 	if (mctl_present && io->ipsec_out_attach_if) {
7994 		/* ip_grab_attach_ill returns a held ill */
7995 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7996 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7997 
7998 		/* Failure case frees things for us. */
7999 		if (attach_ill == NULL)
8000 			return;
8001 
8002 		/*
8003 		 * Check if we need an ire that will not be
8004 		 * looked up by anybody else i.e. HIDDEN.
8005 		 */
8006 		if (ill_is_probeonly(attach_ill))
8007 			ire_marks = IRE_MARK_HIDDEN;
8008 	}
8009 	if (mctl_present && io->ipsec_out_ip_nexthop) {
8010 		ip_nexthop = B_TRUE;
8011 		nexthop_addr = io->ipsec_out_nexthop_addr;
8012 	}
8013 	/*
8014 	 * If this IRE is created for forwarding or it is not for
8015 	 * traffic for congestion controlled protocols, mark it as temporary.
8016 	 */
8017 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
8018 		ire_marks |= IRE_MARK_TEMPORARY;
8019 
8020 	/*
8021 	 * Get what we can from ire_ftable_lookup which will follow an IRE
8022 	 * chain until it gets the most specific information available.
8023 	 * For example, we know that there is no IRE_CACHE for this dest,
8024 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
8025 	 * ire_ftable_lookup will look up the gateway, etc.
8026 	 * Check if in_ill != NULL. If it is true, the packet must be
8027 	 * from an incoming interface where RTA_SRCIFP is set.
8028 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
8029 	 * to the destination, of equal netmask length in the forward table,
8030 	 * will be recursively explored. If no information is available
8031 	 * for the final gateway of that route, we force the returned ire
8032 	 * to be equal to sire using MATCH_IRE_PARENT.
8033 	 * At least, in this case we have a starting point (in the buckets)
8034 	 * to look for other routes to the destination in the forward table.
8035 	 * This is actually used only for multirouting, where a list
8036 	 * of routes has to be processed in sequence.
8037 	 *
8038 	 * In the process of coming up with the most specific information,
8039 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
8040 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
8041 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
8042 	 * Two caveats when handling incomplete ire's in ip_newroute:
8043 	 * - we should be careful when accessing its ire_nce (specifically
8044 	 *   the nce_res_mp) ast it might change underneath our feet, and,
8045 	 * - not all legacy code path callers are prepared to handle
8046 	 *   incomplete ire's, so we should not create/add incomplete
8047 	 *   ire_cache entries here. (See discussion about temporary solution
8048 	 *   further below).
8049 	 *
8050 	 * In order to minimize packet dropping, and to preserve existing
8051 	 * behavior, we treat this case as if there were no IRE_CACHE for the
8052 	 * gateway, and instead use the IF_RESOLVER ire to send out
8053 	 * another request to ARP (this is achieved by passing the
8054 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
8055 	 * arp response comes back in ip_wput_nondata, we will create
8056 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
8057 	 *
8058 	 * Note that this is a temporary solution; the correct solution is
8059 	 * to create an incomplete  per-dst ire_cache entry, and send the
8060 	 * packet out when the gw's nce is resolved. In order to achieve this,
8061 	 * all packet processing must have been completed prior to calling
8062 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
8063 	 * to be modified to accomodate this solution.
8064 	 */
8065 	if (in_ill != NULL) {
8066 		ire = ire_srcif_table_lookup(dst, IRE_IF_RESOLVER, NULL,
8067 		    in_ill, MATCH_IRE_TYPE);
8068 	} else if (ip_nexthop) {
8069 		/*
8070 		 * The first time we come here, we look for an IRE_INTERFACE
8071 		 * entry for the specified nexthop, set the dst to be the
8072 		 * nexthop address and create an IRE_CACHE entry for the
8073 		 * nexthop. The next time around, we are able to find an
8074 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
8075 		 * nexthop address and create an IRE_CACHE entry for the
8076 		 * destination address via the specified nexthop.
8077 		 */
8078 		ire = ire_cache_lookup(nexthop_addr, zoneid,
8079 		    MBLK_GETLABEL(mp), ipst);
8080 		if (ire != NULL) {
8081 			gw = nexthop_addr;
8082 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
8083 		} else {
8084 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
8085 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
8086 			    MBLK_GETLABEL(mp),
8087 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
8088 			    ipst);
8089 			if (ire != NULL) {
8090 				dst = nexthop_addr;
8091 			}
8092 		}
8093 	} else if (attach_ill == NULL) {
8094 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8095 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8096 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8097 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8098 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8099 		    ipst);
8100 	} else {
8101 		/*
8102 		 * attach_ill is set only for communicating with
8103 		 * on-link hosts. So, don't look for DEFAULT.
8104 		 */
8105 		ipif_t	*attach_ipif;
8106 
8107 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8108 		if (attach_ipif == NULL) {
8109 			ill_refrele(attach_ill);
8110 			goto icmp_err_ret;
8111 		}
8112 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8113 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8114 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8115 		    MATCH_IRE_SECATTR, ipst);
8116 		ipif_refrele(attach_ipif);
8117 	}
8118 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8119 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8120 
8121 	/*
8122 	 * This loop is run only once in most cases.
8123 	 * We loop to resolve further routes only when the destination
8124 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8125 	 */
8126 	do {
8127 		/* Clear the previous iteration's values */
8128 		if (src_ipif != NULL) {
8129 			ipif_refrele(src_ipif);
8130 			src_ipif = NULL;
8131 		}
8132 		if (dst_ill != NULL) {
8133 			ill_refrele(dst_ill);
8134 			dst_ill = NULL;
8135 		}
8136 
8137 		multirt_resolve_next = B_FALSE;
8138 		/*
8139 		 * We check if packets have to be multirouted.
8140 		 * In this case, given the current <ire, sire> couple,
8141 		 * we look for the next suitable <ire, sire>.
8142 		 * This check is done in ire_multirt_lookup(),
8143 		 * which applies various criteria to find the next route
8144 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8145 		 * unchanged if it detects it has not been tried yet.
8146 		 */
8147 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8148 			ip3dbg(("ip_newroute: starting next_resolution "
8149 			    "with first_mp %p, tag %d\n",
8150 			    (void *)first_mp,
8151 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8152 
8153 			ASSERT(sire != NULL);
8154 			multirt_is_resolvable =
8155 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8156 			    MBLK_GETLABEL(mp), ipst);
8157 
8158 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8159 			    "ire %p, sire %p\n",
8160 			    multirt_is_resolvable,
8161 			    (void *)ire, (void *)sire));
8162 
8163 			if (!multirt_is_resolvable) {
8164 				/*
8165 				 * No more multirt route to resolve; give up
8166 				 * (all routes resolved or no more
8167 				 * resolvable routes).
8168 				 */
8169 				if (ire != NULL) {
8170 					ire_refrele(ire);
8171 					ire = NULL;
8172 				}
8173 			} else {
8174 				ASSERT(sire != NULL);
8175 				ASSERT(ire != NULL);
8176 				/*
8177 				 * We simply use first_sire as a flag that
8178 				 * indicates if a resolvable multirt route
8179 				 * has already been found.
8180 				 * If it is not the case, we may have to send
8181 				 * an ICMP error to report that the
8182 				 * destination is unreachable.
8183 				 * We do not IRE_REFHOLD first_sire.
8184 				 */
8185 				if (first_sire == NULL) {
8186 					first_sire = sire;
8187 				}
8188 			}
8189 		}
8190 		if (ire == NULL) {
8191 			if (ip_debug > 3) {
8192 				/* ip2dbg */
8193 				pr_addr_dbg("ip_newroute: "
8194 				    "can't resolve %s\n", AF_INET, &dst);
8195 			}
8196 			ip3dbg(("ip_newroute: "
8197 			    "ire %p, sire %p, first_sire %p\n",
8198 			    (void *)ire, (void *)sire, (void *)first_sire));
8199 
8200 			if (sire != NULL) {
8201 				ire_refrele(sire);
8202 				sire = NULL;
8203 			}
8204 
8205 			if (first_sire != NULL) {
8206 				/*
8207 				 * At least one multirt route has been found
8208 				 * in the same call to ip_newroute();
8209 				 * there is no need to report an ICMP error.
8210 				 * first_sire was not IRE_REFHOLDed.
8211 				 */
8212 				MULTIRT_DEBUG_UNTAG(first_mp);
8213 				freemsg(first_mp);
8214 				return;
8215 			}
8216 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8217 			    RTA_DST, ipst);
8218 			if (attach_ill != NULL)
8219 				ill_refrele(attach_ill);
8220 			goto icmp_err_ret;
8221 		}
8222 
8223 		/*
8224 		 * When RTA_SRCIFP is used to add a route, then an interface
8225 		 * route is added in the source interface's routing table.
8226 		 * If the outgoing interface of this route is of type
8227 		 * IRE_IF_RESOLVER, then upon creation of the ire,
8228 		 * ire_nce->nce_res_mp is set to NULL.
8229 		 * Later, when this route is first used for forwarding
8230 		 * a packet, ip_newroute() is called
8231 		 * to resolve the hardware address of the outgoing ipif.
8232 		 * We do not come here for IRE_IF_NORESOLVER entries in the
8233 		 * source interface based table. We only come here if the
8234 		 * outgoing interface is a resolver interface and we don't
8235 		 * have the ire_nce->nce_res_mp information yet.
8236 		 * If in_ill is not null that means it is called from
8237 		 * ip_rput.
8238 		 */
8239 
8240 		ASSERT(ire->ire_in_ill == NULL ||
8241 		    (ire->ire_type == IRE_IF_RESOLVER &&
8242 		    ire->ire_nce != NULL && ire->ire_nce->nce_res_mp == NULL));
8243 
8244 		/*
8245 		 * Verify that the returned IRE does not have either
8246 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8247 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8248 		 */
8249 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8250 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8251 			if (attach_ill != NULL)
8252 				ill_refrele(attach_ill);
8253 			goto icmp_err_ret;
8254 		}
8255 		/*
8256 		 * Increment the ire_ob_pkt_count field for ire if it is an
8257 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8258 		 * increment the same for the parent IRE, sire, if it is some
8259 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8260 		 */
8261 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8262 			UPDATE_OB_PKT_COUNT(ire);
8263 			ire->ire_last_used_time = lbolt;
8264 		}
8265 
8266 		if (sire != NULL) {
8267 			gw = sire->ire_gateway_addr;
8268 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8269 			    IRE_INTERFACE)) == 0);
8270 			UPDATE_OB_PKT_COUNT(sire);
8271 			sire->ire_last_used_time = lbolt;
8272 		}
8273 		/*
8274 		 * We have a route to reach the destination.
8275 		 *
8276 		 * 1) If the interface is part of ill group, try to get a new
8277 		 *    ill taking load spreading into account.
8278 		 *
8279 		 * 2) After selecting the ill, get a source address that
8280 		 *    might create good inbound load spreading.
8281 		 *    ipif_select_source does this for us.
8282 		 *
8283 		 * If the application specified the ill (ifindex), we still
8284 		 * load spread. Only if the packets needs to go out
8285 		 * specifically on a given ill e.g. binding to
8286 		 * IPIF_NOFAILOVER address, then we don't try to use a
8287 		 * different ill for load spreading.
8288 		 */
8289 		if (attach_ill == NULL) {
8290 			/*
8291 			 * Don't perform outbound load spreading in the
8292 			 * case of an RTF_MULTIRT route, as we actually
8293 			 * typically want to replicate outgoing packets
8294 			 * through particular interfaces.
8295 			 */
8296 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8297 				dst_ill = ire->ire_ipif->ipif_ill;
8298 				/* for uniformity */
8299 				ill_refhold(dst_ill);
8300 			} else {
8301 				/*
8302 				 * If we are here trying to create an IRE_CACHE
8303 				 * for an offlink destination and have the
8304 				 * IRE_CACHE for the next hop and the latter is
8305 				 * using virtual IP source address selection i.e
8306 				 * it's ire->ire_ipif is pointing to a virtual
8307 				 * network interface (vni) then
8308 				 * ip_newroute_get_dst_ll() will return the vni
8309 				 * interface as the dst_ill. Since the vni is
8310 				 * virtual i.e not associated with any physical
8311 				 * interface, it cannot be the dst_ill, hence
8312 				 * in such a case call ip_newroute_get_dst_ll()
8313 				 * with the stq_ill instead of the ire_ipif ILL.
8314 				 * The function returns a refheld ill.
8315 				 */
8316 				if ((ire->ire_type == IRE_CACHE) &&
8317 				    IS_VNI(ire->ire_ipif->ipif_ill))
8318 					dst_ill = ip_newroute_get_dst_ill(
8319 					    ire->ire_stq->q_ptr);
8320 				else
8321 					dst_ill = ip_newroute_get_dst_ill(
8322 					    ire->ire_ipif->ipif_ill);
8323 			}
8324 			if (dst_ill == NULL) {
8325 				if (ip_debug > 2) {
8326 					pr_addr_dbg("ip_newroute: "
8327 					    "no dst ill for dst"
8328 					    " %s\n", AF_INET, &dst);
8329 				}
8330 				goto icmp_err_ret;
8331 			}
8332 		} else {
8333 			dst_ill = ire->ire_ipif->ipif_ill;
8334 			/* for uniformity */
8335 			ill_refhold(dst_ill);
8336 			/*
8337 			 * We should have found a route matching ill as we
8338 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8339 			 * Rather than asserting, when there is a mismatch,
8340 			 * we just drop the packet.
8341 			 */
8342 			if (dst_ill != attach_ill) {
8343 				ip0dbg(("ip_newroute: Packet dropped as "
8344 				    "IPIF_NOFAILOVER ill is %s, "
8345 				    "ire->ire_ipif->ipif_ill is %s\n",
8346 				    attach_ill->ill_name,
8347 				    dst_ill->ill_name));
8348 				ill_refrele(attach_ill);
8349 				goto icmp_err_ret;
8350 			}
8351 		}
8352 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8353 		if (attach_ill != NULL) {
8354 			ill_refrele(attach_ill);
8355 			attach_ill = NULL;
8356 			do_attach_ill = B_TRUE;
8357 		}
8358 		ASSERT(dst_ill != NULL);
8359 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8360 
8361 		/*
8362 		 * Pick the best source address from dst_ill.
8363 		 *
8364 		 * 1) If it is part of a multipathing group, we would
8365 		 *    like to spread the inbound packets across different
8366 		 *    interfaces. ipif_select_source picks a random source
8367 		 *    across the different ills in the group.
8368 		 *
8369 		 * 2) If it is not part of a multipathing group, we try
8370 		 *    to pick the source address from the destination
8371 		 *    route. Clustering assumes that when we have multiple
8372 		 *    prefixes hosted on an interface, the prefix of the
8373 		 *    source address matches the prefix of the destination
8374 		 *    route. We do this only if the address is not
8375 		 *    DEPRECATED.
8376 		 *
8377 		 * 3) If the conn is in a different zone than the ire, we
8378 		 *    need to pick a source address from the right zone.
8379 		 *
8380 		 * NOTE : If we hit case (1) above, the prefix of the source
8381 		 *	  address picked may not match the prefix of the
8382 		 *	  destination routes prefix as ipif_select_source
8383 		 *	  does not look at "dst" while picking a source
8384 		 *	  address.
8385 		 *	  If we want the same behavior as (2), we will need
8386 		 *	  to change the behavior of ipif_select_source.
8387 		 */
8388 		ASSERT(src_ipif == NULL);
8389 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8390 			/*
8391 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8392 			 * Check that the ipif matching the requested source
8393 			 * address still exists.
8394 			 */
8395 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8396 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8397 		}
8398 		if (src_ipif == NULL) {
8399 			ire_marks |= IRE_MARK_USESRC_CHECK;
8400 			if ((dst_ill->ill_group != NULL) ||
8401 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8402 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8403 			    ire->ire_zoneid != ALL_ZONES) ||
8404 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8405 				/*
8406 				 * If the destination is reachable via a
8407 				 * given gateway, the selected source address
8408 				 * should be in the same subnet as the gateway.
8409 				 * Otherwise, the destination is not reachable.
8410 				 *
8411 				 * If there are no interfaces on the same subnet
8412 				 * as the destination, ipif_select_source gives
8413 				 * first non-deprecated interface which might be
8414 				 * on a different subnet than the gateway.
8415 				 * This is not desirable. Hence pass the dst_ire
8416 				 * source address to ipif_select_source.
8417 				 * It is sure that the destination is reachable
8418 				 * with the dst_ire source address subnet.
8419 				 * So passing dst_ire source address to
8420 				 * ipif_select_source will make sure that the
8421 				 * selected source will be on the same subnet
8422 				 * as dst_ire source address.
8423 				 */
8424 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8425 				src_ipif = ipif_select_source(dst_ill, saddr,
8426 				    zoneid);
8427 				if (src_ipif == NULL) {
8428 					if (ip_debug > 2) {
8429 						pr_addr_dbg("ip_newroute: "
8430 						    "no src for dst %s ",
8431 						    AF_INET, &dst);
8432 						printf("through interface %s\n",
8433 						    dst_ill->ill_name);
8434 					}
8435 					goto icmp_err_ret;
8436 				}
8437 			} else {
8438 				src_ipif = ire->ire_ipif;
8439 				ASSERT(src_ipif != NULL);
8440 				/* hold src_ipif for uniformity */
8441 				ipif_refhold(src_ipif);
8442 			}
8443 		}
8444 
8445 		/*
8446 		 * Assign a source address while we have the conn.
8447 		 * We can't have ip_wput_ire pick a source address when the
8448 		 * packet returns from arp since we need to look at
8449 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8450 		 * going through arp.
8451 		 *
8452 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8453 		 *	  it uses ip6i to store this information.
8454 		 */
8455 		if (ipha->ipha_src == INADDR_ANY &&
8456 		    (connp == NULL || !connp->conn_unspec_src)) {
8457 			ipha->ipha_src = src_ipif->ipif_src_addr;
8458 		}
8459 		if (ip_debug > 3) {
8460 			/* ip2dbg */
8461 			pr_addr_dbg("ip_newroute: first hop %s\n",
8462 			    AF_INET, &gw);
8463 		}
8464 		ip2dbg(("\tire type %s (%d)\n",
8465 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8466 
8467 		/*
8468 		 * The TTL of multirouted packets is bounded by the
8469 		 * ip_multirt_ttl ndd variable.
8470 		 */
8471 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8472 			/* Force TTL of multirouted packets */
8473 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8474 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8475 				ip2dbg(("ip_newroute: forcing multirt TTL "
8476 				    "to %d (was %d), dst 0x%08x\n",
8477 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8478 				    ntohl(sire->ire_addr)));
8479 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8480 			}
8481 		}
8482 		/*
8483 		 * At this point in ip_newroute(), ire is either the
8484 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8485 		 * destination or an IRE_INTERFACE type that should be used
8486 		 * to resolve an on-subnet destination or an on-subnet
8487 		 * next-hop gateway.
8488 		 *
8489 		 * In the IRE_CACHE case, we have the following :
8490 		 *
8491 		 * 1) src_ipif - used for getting a source address.
8492 		 *
8493 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8494 		 *    means packets using this IRE_CACHE will go out on
8495 		 *    dst_ill.
8496 		 *
8497 		 * 3) The IRE sire will point to the prefix that is the
8498 		 *    longest  matching route for the destination. These
8499 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8500 		 *
8501 		 *    The newly created IRE_CACHE entry for the off-subnet
8502 		 *    destination is tied to both the prefix route and the
8503 		 *    interface route used to resolve the next-hop gateway
8504 		 *    via the ire_phandle and ire_ihandle fields,
8505 		 *    respectively.
8506 		 *
8507 		 * In the IRE_INTERFACE case, we have the following :
8508 		 *
8509 		 * 1) src_ipif - used for getting a source address.
8510 		 *
8511 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8512 		 *    means packets using the IRE_CACHE that we will build
8513 		 *    here will go out on dst_ill.
8514 		 *
8515 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8516 		 *    to be created will only be tied to the IRE_INTERFACE
8517 		 *    that was derived from the ire_ihandle field.
8518 		 *
8519 		 *    If sire is non-NULL, it means the destination is
8520 		 *    off-link and we will first create the IRE_CACHE for the
8521 		 *    gateway. Next time through ip_newroute, we will create
8522 		 *    the IRE_CACHE for the final destination as described
8523 		 *    above.
8524 		 *
8525 		 * In both cases, after the current resolution has been
8526 		 * completed (or possibly initialised, in the IRE_INTERFACE
8527 		 * case), the loop may be re-entered to attempt the resolution
8528 		 * of another RTF_MULTIRT route.
8529 		 *
8530 		 * When an IRE_CACHE entry for the off-subnet destination is
8531 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8532 		 * for further processing in emission loops.
8533 		 */
8534 		save_ire = ire;
8535 		switch (ire->ire_type) {
8536 		case IRE_CACHE: {
8537 			ire_t	*ipif_ire;
8538 
8539 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8540 			if (gw == 0)
8541 				gw = ire->ire_gateway_addr;
8542 			/*
8543 			 * We need 3 ire's to create a new cache ire for an
8544 			 * off-link destination from the cache ire of the
8545 			 * gateway.
8546 			 *
8547 			 *	1. The prefix ire 'sire' (Note that this does
8548 			 *	   not apply to the conn_nexthop_set case)
8549 			 *	2. The cache ire of the gateway 'ire'
8550 			 *	3. The interface ire 'ipif_ire'
8551 			 *
8552 			 * We have (1) and (2). We lookup (3) below.
8553 			 *
8554 			 * If there is no interface route to the gateway,
8555 			 * it is a race condition, where we found the cache
8556 			 * but the interface route has been deleted.
8557 			 */
8558 			if (ip_nexthop) {
8559 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8560 			} else {
8561 				ipif_ire =
8562 				    ire_ihandle_lookup_offlink(ire, sire);
8563 			}
8564 			if (ipif_ire == NULL) {
8565 				ip1dbg(("ip_newroute: "
8566 				    "ire_ihandle_lookup_offlink failed\n"));
8567 				goto icmp_err_ret;
8568 			}
8569 
8570 			/*
8571 			 * Check cached gateway IRE for any security
8572 			 * attributes; if found, associate the gateway
8573 			 * credentials group to the destination IRE.
8574 			 */
8575 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8576 				mutex_enter(&attrp->igsa_lock);
8577 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8578 					GCGRP_REFHOLD(gcgrp);
8579 				mutex_exit(&attrp->igsa_lock);
8580 			}
8581 
8582 			/*
8583 			 * XXX For the source of the resolver mp,
8584 			 * we are using the same DL_UNITDATA_REQ
8585 			 * (from save_ire->ire_nce->nce_res_mp)
8586 			 * though the save_ire is not pointing at the same ill.
8587 			 * This is incorrect. We need to send it up to the
8588 			 * resolver to get the right res_mp. For ethernets
8589 			 * this may be okay (ill_type == DL_ETHER).
8590 			 */
8591 
8592 			ire = ire_create(
8593 			    (uchar_t *)&dst,		/* dest address */
8594 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8595 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8596 			    (uchar_t *)&gw,		/* gateway address */
8597 			    NULL,
8598 			    &save_ire->ire_max_frag,
8599 			    save_ire->ire_nce,		/* src nce */
8600 			    dst_ill->ill_rq,		/* recv-from queue */
8601 			    dst_ill->ill_wq,		/* send-to queue */
8602 			    IRE_CACHE,			/* IRE type */
8603 			    src_ipif,
8604 			    in_ill,			/* incoming ill */
8605 			    (sire != NULL) ?
8606 			    sire->ire_mask : 0, 	/* Parent mask */
8607 			    (sire != NULL) ?
8608 			    sire->ire_phandle : 0,	/* Parent handle */
8609 			    ipif_ire->ire_ihandle,	/* Interface handle */
8610 			    (sire != NULL) ? (sire->ire_flags &
8611 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8612 			    (sire != NULL) ?
8613 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8614 			    NULL,
8615 			    gcgrp,
8616 			    ipst);
8617 
8618 			if (ire == NULL) {
8619 				if (gcgrp != NULL) {
8620 					GCGRP_REFRELE(gcgrp);
8621 					gcgrp = NULL;
8622 				}
8623 				ire_refrele(ipif_ire);
8624 				ire_refrele(save_ire);
8625 				break;
8626 			}
8627 
8628 			/* reference now held by IRE */
8629 			gcgrp = NULL;
8630 
8631 			ire->ire_marks |= ire_marks;
8632 
8633 			/*
8634 			 * Prevent sire and ipif_ire from getting deleted.
8635 			 * The newly created ire is tied to both of them via
8636 			 * the phandle and ihandle respectively.
8637 			 */
8638 			if (sire != NULL) {
8639 				IRB_REFHOLD(sire->ire_bucket);
8640 				/* Has it been removed already ? */
8641 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8642 					IRB_REFRELE(sire->ire_bucket);
8643 					ire_refrele(ipif_ire);
8644 					ire_refrele(save_ire);
8645 					break;
8646 				}
8647 			}
8648 
8649 			IRB_REFHOLD(ipif_ire->ire_bucket);
8650 			/* Has it been removed already ? */
8651 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8652 				IRB_REFRELE(ipif_ire->ire_bucket);
8653 				if (sire != NULL)
8654 					IRB_REFRELE(sire->ire_bucket);
8655 				ire_refrele(ipif_ire);
8656 				ire_refrele(save_ire);
8657 				break;
8658 			}
8659 
8660 			xmit_mp = first_mp;
8661 			/*
8662 			 * In the case of multirouting, a copy
8663 			 * of the packet is done before its sending.
8664 			 * The copy is used to attempt another
8665 			 * route resolution, in a next loop.
8666 			 */
8667 			if (ire->ire_flags & RTF_MULTIRT) {
8668 				copy_mp = copymsg(first_mp);
8669 				if (copy_mp != NULL) {
8670 					xmit_mp = copy_mp;
8671 					MULTIRT_DEBUG_TAG(first_mp);
8672 				}
8673 			}
8674 			ire_add_then_send(q, ire, xmit_mp);
8675 			ire_refrele(save_ire);
8676 
8677 			/* Assert that sire is not deleted yet. */
8678 			if (sire != NULL) {
8679 				ASSERT(sire->ire_ptpn != NULL);
8680 				IRB_REFRELE(sire->ire_bucket);
8681 			}
8682 
8683 			/* Assert that ipif_ire is not deleted yet. */
8684 			ASSERT(ipif_ire->ire_ptpn != NULL);
8685 			IRB_REFRELE(ipif_ire->ire_bucket);
8686 			ire_refrele(ipif_ire);
8687 
8688 			/*
8689 			 * If copy_mp is not NULL, multirouting was
8690 			 * requested. We loop to initiate a next
8691 			 * route resolution attempt, starting from sire.
8692 			 */
8693 			if (copy_mp != NULL) {
8694 				/*
8695 				 * Search for the next unresolved
8696 				 * multirt route.
8697 				 */
8698 				copy_mp = NULL;
8699 				ipif_ire = NULL;
8700 				ire = NULL;
8701 				multirt_resolve_next = B_TRUE;
8702 				continue;
8703 			}
8704 			if (sire != NULL)
8705 				ire_refrele(sire);
8706 			ipif_refrele(src_ipif);
8707 			ill_refrele(dst_ill);
8708 			return;
8709 		}
8710 		case IRE_IF_NORESOLVER: {
8711 
8712 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8713 			    dst_ill->ill_resolver_mp == NULL) {
8714 				ip1dbg(("ip_newroute: dst_ill %p "
8715 				    "for IRE_IF_NORESOLVER ire %p has "
8716 				    "no ill_resolver_mp\n",
8717 				    (void *)dst_ill, (void *)ire));
8718 				break;
8719 			}
8720 
8721 			/*
8722 			 * TSol note: We are creating the ire cache for the
8723 			 * destination 'dst'. If 'dst' is offlink, going
8724 			 * through the first hop 'gw', the security attributes
8725 			 * of 'dst' must be set to point to the gateway
8726 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8727 			 * is possible that 'dst' is a potential gateway that is
8728 			 * referenced by some route that has some security
8729 			 * attributes. Thus in the former case, we need to do a
8730 			 * gcgrp_lookup of 'gw' while in the latter case we
8731 			 * need to do gcgrp_lookup of 'dst' itself.
8732 			 */
8733 			ga.ga_af = AF_INET;
8734 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8735 			    &ga.ga_addr);
8736 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8737 
8738 			ire = ire_create(
8739 			    (uchar_t *)&dst,		/* dest address */
8740 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8741 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8742 			    (uchar_t *)&gw,		/* gateway address */
8743 			    NULL,
8744 			    &save_ire->ire_max_frag,
8745 			    NULL,			/* no src nce */
8746 			    dst_ill->ill_rq,		/* recv-from queue */
8747 			    dst_ill->ill_wq,		/* send-to queue */
8748 			    IRE_CACHE,
8749 			    src_ipif,
8750 			    in_ill,			/* Incoming ill */
8751 			    save_ire->ire_mask,		/* Parent mask */
8752 			    (sire != NULL) ?		/* Parent handle */
8753 			    sire->ire_phandle : 0,
8754 			    save_ire->ire_ihandle,	/* Interface handle */
8755 			    (sire != NULL) ? sire->ire_flags &
8756 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8757 			    &(save_ire->ire_uinfo),
8758 			    NULL,
8759 			    gcgrp,
8760 			    ipst);
8761 
8762 			if (ire == NULL) {
8763 				if (gcgrp != NULL) {
8764 					GCGRP_REFRELE(gcgrp);
8765 					gcgrp = NULL;
8766 				}
8767 				ire_refrele(save_ire);
8768 				break;
8769 			}
8770 
8771 			/* reference now held by IRE */
8772 			gcgrp = NULL;
8773 
8774 			ire->ire_marks |= ire_marks;
8775 
8776 			/* Prevent save_ire from getting deleted */
8777 			IRB_REFHOLD(save_ire->ire_bucket);
8778 			/* Has it been removed already ? */
8779 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8780 				IRB_REFRELE(save_ire->ire_bucket);
8781 				ire_refrele(save_ire);
8782 				break;
8783 			}
8784 
8785 			/*
8786 			 * In the case of multirouting, a copy
8787 			 * of the packet is made before it is sent.
8788 			 * The copy is used in the next
8789 			 * loop to attempt another resolution.
8790 			 */
8791 			xmit_mp = first_mp;
8792 			if ((sire != NULL) &&
8793 			    (sire->ire_flags & RTF_MULTIRT)) {
8794 				copy_mp = copymsg(first_mp);
8795 				if (copy_mp != NULL) {
8796 					xmit_mp = copy_mp;
8797 					MULTIRT_DEBUG_TAG(first_mp);
8798 				}
8799 			}
8800 			ire_add_then_send(q, ire, xmit_mp);
8801 
8802 			/* Assert that it is not deleted yet. */
8803 			ASSERT(save_ire->ire_ptpn != NULL);
8804 			IRB_REFRELE(save_ire->ire_bucket);
8805 			ire_refrele(save_ire);
8806 
8807 			if (copy_mp != NULL) {
8808 				/*
8809 				 * If we found a (no)resolver, we ignore any
8810 				 * trailing top priority IRE_CACHE in further
8811 				 * loops. This ensures that we do not omit any
8812 				 * (no)resolver.
8813 				 * This IRE_CACHE, if any, will be processed
8814 				 * by another thread entering ip_newroute().
8815 				 * IRE_CACHE entries, if any, will be processed
8816 				 * by another thread entering ip_newroute(),
8817 				 * (upon resolver response, for instance).
8818 				 * This aims to force parallel multirt
8819 				 * resolutions as soon as a packet must be sent.
8820 				 * In the best case, after the tx of only one
8821 				 * packet, all reachable routes are resolved.
8822 				 * Otherwise, the resolution of all RTF_MULTIRT
8823 				 * routes would require several emissions.
8824 				 */
8825 				multirt_flags &= ~MULTIRT_CACHEGW;
8826 
8827 				/*
8828 				 * Search for the next unresolved multirt
8829 				 * route.
8830 				 */
8831 				copy_mp = NULL;
8832 				save_ire = NULL;
8833 				ire = NULL;
8834 				multirt_resolve_next = B_TRUE;
8835 				continue;
8836 			}
8837 
8838 			/*
8839 			 * Don't need sire anymore
8840 			 */
8841 			if (sire != NULL)
8842 				ire_refrele(sire);
8843 
8844 			ipif_refrele(src_ipif);
8845 			ill_refrele(dst_ill);
8846 			return;
8847 		}
8848 		case IRE_IF_RESOLVER:
8849 			/*
8850 			 * We can't build an IRE_CACHE yet, but at least we
8851 			 * found a resolver that can help.
8852 			 */
8853 			res_mp = dst_ill->ill_resolver_mp;
8854 			if (!OK_RESOLVER_MP(res_mp))
8855 				break;
8856 
8857 			/*
8858 			 * To be at this point in the code with a non-zero gw
8859 			 * means that dst is reachable through a gateway that
8860 			 * we have never resolved.  By changing dst to the gw
8861 			 * addr we resolve the gateway first.
8862 			 * When ire_add_then_send() tries to put the IP dg
8863 			 * to dst, it will reenter ip_newroute() at which
8864 			 * time we will find the IRE_CACHE for the gw and
8865 			 * create another IRE_CACHE in case IRE_CACHE above.
8866 			 */
8867 			if (gw != INADDR_ANY) {
8868 				/*
8869 				 * The source ipif that was determined above was
8870 				 * relative to the destination address, not the
8871 				 * gateway's. If src_ipif was not taken out of
8872 				 * the IRE_IF_RESOLVER entry, we'll need to call
8873 				 * ipif_select_source() again.
8874 				 */
8875 				if (src_ipif != ire->ire_ipif) {
8876 					ipif_refrele(src_ipif);
8877 					src_ipif = ipif_select_source(dst_ill,
8878 					    gw, zoneid);
8879 					if (src_ipif == NULL) {
8880 						if (ip_debug > 2) {
8881 							pr_addr_dbg(
8882 							    "ip_newroute: no "
8883 							    "src for gw %s ",
8884 							    AF_INET, &gw);
8885 							printf("through "
8886 							    "interface %s\n",
8887 							    dst_ill->ill_name);
8888 						}
8889 						goto icmp_err_ret;
8890 					}
8891 				}
8892 				save_dst = dst;
8893 				dst = gw;
8894 				gw = INADDR_ANY;
8895 			}
8896 
8897 			/*
8898 			 * We obtain a partial IRE_CACHE which we will pass
8899 			 * along with the resolver query.  When the response
8900 			 * comes back it will be there ready for us to add.
8901 			 * The ire_max_frag is atomically set under the
8902 			 * irebucket lock in ire_add_v[46].
8903 			 */
8904 
8905 			ire = ire_create_mp(
8906 			    (uchar_t *)&dst,		/* dest address */
8907 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8908 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8909 			    (uchar_t *)&gw,		/* gateway address */
8910 			    NULL,			/* no in_src_addr */
8911 			    NULL,			/* ire_max_frag */
8912 			    NULL,			/* no src nce */
8913 			    dst_ill->ill_rq,		/* recv-from queue */
8914 			    dst_ill->ill_wq,		/* send-to queue */
8915 			    IRE_CACHE,
8916 			    src_ipif,			/* Interface ipif */
8917 			    in_ill,			/* Incoming ILL */
8918 			    save_ire->ire_mask,		/* Parent mask */
8919 			    0,
8920 			    save_ire->ire_ihandle,	/* Interface handle */
8921 			    0,				/* flags if any */
8922 			    &(save_ire->ire_uinfo),
8923 			    NULL,
8924 			    NULL,
8925 			    ipst);
8926 
8927 			if (ire == NULL) {
8928 				ire_refrele(save_ire);
8929 				break;
8930 			}
8931 
8932 			if ((sire != NULL) &&
8933 			    (sire->ire_flags & RTF_MULTIRT)) {
8934 				copy_mp = copymsg(first_mp);
8935 				if (copy_mp != NULL)
8936 					MULTIRT_DEBUG_TAG(copy_mp);
8937 			}
8938 
8939 			ire->ire_marks |= ire_marks;
8940 
8941 			/*
8942 			 * Construct message chain for the resolver
8943 			 * of the form:
8944 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8945 			 * Packet could contain a IPSEC_OUT mp.
8946 			 *
8947 			 * NOTE : ire will be added later when the response
8948 			 * comes back from ARP. If the response does not
8949 			 * come back, ARP frees the packet. For this reason,
8950 			 * we can't REFHOLD the bucket of save_ire to prevent
8951 			 * deletions. We may not be able to REFRELE the bucket
8952 			 * if the response never comes back. Thus, before
8953 			 * adding the ire, ire_add_v4 will make sure that the
8954 			 * interface route does not get deleted. This is the
8955 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8956 			 * where we can always prevent deletions because of
8957 			 * the synchronous nature of adding IRES i.e
8958 			 * ire_add_then_send is called after creating the IRE.
8959 			 */
8960 			ASSERT(ire->ire_mp != NULL);
8961 			ire->ire_mp->b_cont = first_mp;
8962 			/* Have saved_mp handy, for cleanup if canput fails */
8963 			saved_mp = mp;
8964 			mp = copyb(res_mp);
8965 			if (mp == NULL) {
8966 				/* Prepare for cleanup */
8967 				mp = saved_mp; /* pkt */
8968 				ire_delete(ire); /* ire_mp */
8969 				ire = NULL;
8970 				ire_refrele(save_ire);
8971 				if (copy_mp != NULL) {
8972 					MULTIRT_DEBUG_UNTAG(copy_mp);
8973 					freemsg(copy_mp);
8974 					copy_mp = NULL;
8975 				}
8976 				break;
8977 			}
8978 			linkb(mp, ire->ire_mp);
8979 
8980 			/*
8981 			 * Fill in the source and dest addrs for the resolver.
8982 			 * NOTE: this depends on memory layouts imposed by
8983 			 * ill_init().
8984 			 */
8985 			areq = (areq_t *)mp->b_rptr;
8986 			addrp = (ipaddr_t *)((char *)areq +
8987 			    areq->areq_sender_addr_offset);
8988 			if (do_attach_ill) {
8989 				/*
8990 				 * This is bind to no failover case.
8991 				 * arp packet also must go out on attach_ill.
8992 				 */
8993 				ASSERT(ipha->ipha_src != NULL);
8994 				*addrp = ipha->ipha_src;
8995 			} else {
8996 				*addrp = save_ire->ire_src_addr;
8997 			}
8998 
8999 			ire_refrele(save_ire);
9000 			addrp = (ipaddr_t *)((char *)areq +
9001 			    areq->areq_target_addr_offset);
9002 			*addrp = dst;
9003 			/* Up to the resolver. */
9004 			if (canputnext(dst_ill->ill_rq) &&
9005 			    !(dst_ill->ill_arp_closing)) {
9006 				putnext(dst_ill->ill_rq, mp);
9007 				ire = NULL;
9008 				if (copy_mp != NULL) {
9009 					/*
9010 					 * If we found a resolver, we ignore
9011 					 * any trailing top priority IRE_CACHE
9012 					 * in the further loops. This ensures
9013 					 * that we do not omit any resolver.
9014 					 * IRE_CACHE entries, if any, will be
9015 					 * processed next time we enter
9016 					 * ip_newroute().
9017 					 */
9018 					multirt_flags &= ~MULTIRT_CACHEGW;
9019 					/*
9020 					 * Search for the next unresolved
9021 					 * multirt route.
9022 					 */
9023 					first_mp = copy_mp;
9024 					copy_mp = NULL;
9025 					/* Prepare the next resolution loop. */
9026 					mp = first_mp;
9027 					EXTRACT_PKT_MP(mp, first_mp,
9028 					    mctl_present);
9029 					if (mctl_present)
9030 						io = (ipsec_out_t *)
9031 						    first_mp->b_rptr;
9032 					ipha = (ipha_t *)mp->b_rptr;
9033 
9034 					ASSERT(sire != NULL);
9035 
9036 					dst = save_dst;
9037 					multirt_resolve_next = B_TRUE;
9038 					continue;
9039 				}
9040 
9041 				if (sire != NULL)
9042 					ire_refrele(sire);
9043 
9044 				/*
9045 				 * The response will come back in ip_wput
9046 				 * with db_type IRE_DB_TYPE.
9047 				 */
9048 				ipif_refrele(src_ipif);
9049 				ill_refrele(dst_ill);
9050 				return;
9051 			} else {
9052 				/* Prepare for cleanup */
9053 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
9054 				    mp);
9055 				mp->b_cont = NULL;
9056 				freeb(mp); /* areq */
9057 				/*
9058 				 * this is an ire that is not added to the
9059 				 * cache. ire_freemblk will handle the release
9060 				 * of any resources associated with the ire.
9061 				 */
9062 				ire_delete(ire); /* ire_mp */
9063 				mp = saved_mp; /* pkt */
9064 				ire = NULL;
9065 				if (copy_mp != NULL) {
9066 					MULTIRT_DEBUG_UNTAG(copy_mp);
9067 					freemsg(copy_mp);
9068 					copy_mp = NULL;
9069 				}
9070 				break;
9071 			}
9072 		default:
9073 			break;
9074 		}
9075 	} while (multirt_resolve_next);
9076 
9077 	ip1dbg(("ip_newroute: dropped\n"));
9078 	/* Did this packet originate externally? */
9079 	if (mp->b_prev) {
9080 		mp->b_next = NULL;
9081 		mp->b_prev = NULL;
9082 		if (in_ill != NULL) {
9083 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInDiscards);
9084 		} else {
9085 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
9086 		}
9087 	} else {
9088 		if (dst_ill != NULL) {
9089 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
9090 		} else {
9091 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
9092 		}
9093 	}
9094 	ASSERT(copy_mp == NULL);
9095 	MULTIRT_DEBUG_UNTAG(first_mp);
9096 	freemsg(first_mp);
9097 	if (ire != NULL)
9098 		ire_refrele(ire);
9099 	if (sire != NULL)
9100 		ire_refrele(sire);
9101 	if (src_ipif != NULL)
9102 		ipif_refrele(src_ipif);
9103 	if (dst_ill != NULL)
9104 		ill_refrele(dst_ill);
9105 	return;
9106 
9107 icmp_err_ret:
9108 	ip1dbg(("ip_newroute: no route\n"));
9109 	if (src_ipif != NULL)
9110 		ipif_refrele(src_ipif);
9111 	if (dst_ill != NULL)
9112 		ill_refrele(dst_ill);
9113 	if (sire != NULL)
9114 		ire_refrele(sire);
9115 	/* Did this packet originate externally? */
9116 	if (mp->b_prev) {
9117 		mp->b_next = NULL;
9118 		mp->b_prev = NULL;
9119 		if (in_ill != NULL) {
9120 			BUMP_MIB(in_ill->ill_ip_mib, ipIfStatsInNoRoutes);
9121 		} else {
9122 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
9123 		}
9124 		q = WR(q);
9125 	} else {
9126 		/*
9127 		 * There is no outgoing ill, so just increment the
9128 		 * system MIB.
9129 		 */
9130 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9131 		/*
9132 		 * Since ip_wput() isn't close to finished, we fill
9133 		 * in enough of the header for credible error reporting.
9134 		 */
9135 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9136 			/* Failed */
9137 			MULTIRT_DEBUG_UNTAG(first_mp);
9138 			freemsg(first_mp);
9139 			if (ire != NULL)
9140 				ire_refrele(ire);
9141 			return;
9142 		}
9143 	}
9144 
9145 	/*
9146 	 * At this point we will have ire only if RTF_BLACKHOLE
9147 	 * or RTF_REJECT flags are set on the IRE. It will not
9148 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9149 	 */
9150 	if (ire != NULL) {
9151 		if (ire->ire_flags & RTF_BLACKHOLE) {
9152 			ire_refrele(ire);
9153 			MULTIRT_DEBUG_UNTAG(first_mp);
9154 			freemsg(first_mp);
9155 			return;
9156 		}
9157 		ire_refrele(ire);
9158 	}
9159 	if (ip_source_routed(ipha, ipst)) {
9160 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9161 		    zoneid, ipst);
9162 		return;
9163 	}
9164 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9165 }
9166 
9167 ip_opt_info_t zero_info;
9168 
9169 /*
9170  * IPv4 -
9171  * ip_newroute_ipif is called by ip_wput_multicast and
9172  * ip_rput_forward_multicast whenever we need to send
9173  * out a packet to a destination address for which we do not have specific
9174  * routing information. It is used when the packet will be sent out
9175  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9176  * socket option is set or icmp error message wants to go out on a particular
9177  * interface for a unicast packet.
9178  *
9179  * In most cases, the destination address is resolved thanks to the ipif
9180  * intrinsic resolver. However, there are some cases where the call to
9181  * ip_newroute_ipif must take into account the potential presence of
9182  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9183  * that uses the interface. This is specified through flags,
9184  * which can be a combination of:
9185  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9186  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9187  *   and flags. Additionally, the packet source address has to be set to
9188  *   the specified address. The caller is thus expected to set this flag
9189  *   if the packet has no specific source address yet.
9190  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9191  *   flag, the resulting ire will inherit the flag. All unresolved routes
9192  *   to the destination must be explored in the same call to
9193  *   ip_newroute_ipif().
9194  */
9195 static void
9196 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9197     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9198 {
9199 	areq_t	*areq;
9200 	ire_t	*ire = NULL;
9201 	mblk_t	*res_mp;
9202 	ipaddr_t *addrp;
9203 	mblk_t *first_mp;
9204 	ire_t	*save_ire = NULL;
9205 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9206 	ipif_t	*src_ipif = NULL;
9207 	ushort_t ire_marks = 0;
9208 	ill_t	*dst_ill = NULL;
9209 	boolean_t mctl_present;
9210 	ipsec_out_t *io;
9211 	ipha_t *ipha;
9212 	int	ihandle = 0;
9213 	mblk_t	*saved_mp;
9214 	ire_t   *fire = NULL;
9215 	mblk_t  *copy_mp = NULL;
9216 	boolean_t multirt_resolve_next;
9217 	ipaddr_t ipha_dst;
9218 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9219 
9220 	/*
9221 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9222 	 * here for uniformity
9223 	 */
9224 	ipif_refhold(ipif);
9225 
9226 	/*
9227 	 * This loop is run only once in most cases.
9228 	 * We loop to resolve further routes only when the destination
9229 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9230 	 */
9231 	do {
9232 		if (dst_ill != NULL) {
9233 			ill_refrele(dst_ill);
9234 			dst_ill = NULL;
9235 		}
9236 		if (src_ipif != NULL) {
9237 			ipif_refrele(src_ipif);
9238 			src_ipif = NULL;
9239 		}
9240 		multirt_resolve_next = B_FALSE;
9241 
9242 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9243 		    ipif->ipif_ill->ill_name));
9244 
9245 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9246 		if (mctl_present)
9247 			io = (ipsec_out_t *)first_mp->b_rptr;
9248 
9249 		ipha = (ipha_t *)mp->b_rptr;
9250 
9251 		/*
9252 		 * Save the packet destination address, we may need it after
9253 		 * the packet has been consumed.
9254 		 */
9255 		ipha_dst = ipha->ipha_dst;
9256 
9257 		/*
9258 		 * If the interface is a pt-pt interface we look for an
9259 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9260 		 * local_address and the pt-pt destination address. Otherwise
9261 		 * we just match the local address.
9262 		 * NOTE: dst could be different than ipha->ipha_dst in case
9263 		 * of sending igmp multicast packets over a point-to-point
9264 		 * connection.
9265 		 * Thus we must be careful enough to check ipha_dst to be a
9266 		 * multicast address, otherwise it will take xmit_if path for
9267 		 * multicast packets resulting into kernel stack overflow by
9268 		 * repeated calls to ip_newroute_ipif from ire_send().
9269 		 */
9270 		if (CLASSD(ipha_dst) &&
9271 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9272 			goto err_ret;
9273 		}
9274 
9275 		/*
9276 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9277 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9278 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9279 		 * propagate its flags to the new ire.
9280 		 */
9281 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9282 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9283 			ip2dbg(("ip_newroute_ipif: "
9284 			    "ipif_lookup_multi_ire("
9285 			    "ipif %p, dst %08x) = fire %p\n",
9286 			    (void *)ipif, ntohl(dst), (void *)fire));
9287 		}
9288 
9289 		if (mctl_present && io->ipsec_out_attach_if) {
9290 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9291 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9292 
9293 			/* Failure case frees things for us. */
9294 			if (attach_ill == NULL) {
9295 				ipif_refrele(ipif);
9296 				if (fire != NULL)
9297 					ire_refrele(fire);
9298 				return;
9299 			}
9300 
9301 			/*
9302 			 * Check if we need an ire that will not be
9303 			 * looked up by anybody else i.e. HIDDEN.
9304 			 */
9305 			if (ill_is_probeonly(attach_ill)) {
9306 				ire_marks = IRE_MARK_HIDDEN;
9307 			}
9308 			/*
9309 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9310 			 * case.
9311 			 */
9312 			dst_ill = ipif->ipif_ill;
9313 			/* attach_ill has been refheld by ip_grab_attach_ill */
9314 			ASSERT(dst_ill == attach_ill);
9315 		} else {
9316 			/*
9317 			 * If this is set by IP_XMIT_IF, then make sure that
9318 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9319 			 * specified ill.
9320 			 */
9321 			ASSERT((connp == NULL) ||
9322 			    (connp->conn_xmit_if_ill == NULL) ||
9323 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9324 			/*
9325 			 * If the interface belongs to an interface group,
9326 			 * make sure the next possible interface in the group
9327 			 * is used.  This encourages load spreading among
9328 			 * peers in an interface group.
9329 			 * Note: load spreading is disabled for RTF_MULTIRT
9330 			 * routes.
9331 			 */
9332 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9333 			    (fire->ire_flags & RTF_MULTIRT)) {
9334 				/*
9335 				 * Don't perform outbound load spreading
9336 				 * in the case of an RTF_MULTIRT issued route,
9337 				 * we actually typically want to replicate
9338 				 * outgoing packets through particular
9339 				 * interfaces.
9340 				 */
9341 				dst_ill = ipif->ipif_ill;
9342 				ill_refhold(dst_ill);
9343 			} else {
9344 				dst_ill = ip_newroute_get_dst_ill(
9345 				    ipif->ipif_ill);
9346 			}
9347 			if (dst_ill == NULL) {
9348 				if (ip_debug > 2) {
9349 					pr_addr_dbg("ip_newroute_ipif: "
9350 					    "no dst ill for dst %s\n",
9351 					    AF_INET, &dst);
9352 				}
9353 				goto err_ret;
9354 			}
9355 		}
9356 
9357 		/*
9358 		 * Pick a source address preferring non-deprecated ones.
9359 		 * Unlike ip_newroute, we don't do any source address
9360 		 * selection here since for multicast it really does not help
9361 		 * in inbound load spreading as in the unicast case.
9362 		 */
9363 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9364 		    (fire->ire_flags & RTF_SETSRC)) {
9365 			/*
9366 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9367 			 * on that interface. This ire has RTF_SETSRC flag, so
9368 			 * the source address of the packet must be changed.
9369 			 * Check that the ipif matching the requested source
9370 			 * address still exists.
9371 			 */
9372 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9373 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9374 		}
9375 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9376 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9377 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9378 		    (src_ipif == NULL)) {
9379 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9380 			if (src_ipif == NULL) {
9381 				if (ip_debug > 2) {
9382 					/* ip1dbg */
9383 					pr_addr_dbg("ip_newroute_ipif: "
9384 					    "no src for dst %s",
9385 					    AF_INET, &dst);
9386 				}
9387 				ip1dbg((" through interface %s\n",
9388 				    dst_ill->ill_name));
9389 				goto err_ret;
9390 			}
9391 			ipif_refrele(ipif);
9392 			ipif = src_ipif;
9393 			ipif_refhold(ipif);
9394 		}
9395 		if (src_ipif == NULL) {
9396 			src_ipif = ipif;
9397 			ipif_refhold(src_ipif);
9398 		}
9399 
9400 		/*
9401 		 * Assign a source address while we have the conn.
9402 		 * We can't have ip_wput_ire pick a source address when the
9403 		 * packet returns from arp since conn_unspec_src might be set
9404 		 * and we loose the conn when going through arp.
9405 		 */
9406 		if (ipha->ipha_src == INADDR_ANY &&
9407 		    (connp == NULL || !connp->conn_unspec_src)) {
9408 			ipha->ipha_src = src_ipif->ipif_src_addr;
9409 		}
9410 
9411 		/*
9412 		 * In case of IP_XMIT_IF, it is possible that the outgoing
9413 		 * interface does not have an interface ire.
9414 		 * Example: Thousands of mobileip PPP interfaces to mobile
9415 		 * nodes. We don't want to create interface ires because
9416 		 * packets from other mobile nodes must not take the route
9417 		 * via interface ires to the visiting mobile node without
9418 		 * going through the home agent, in absence of mobileip
9419 		 * route optimization.
9420 		 */
9421 		if (CLASSD(ipha_dst) && (connp == NULL ||
9422 		    connp->conn_xmit_if_ill == NULL) &&
9423 		    infop->ip_opt_ill_index == 0) {
9424 			/* ipif_to_ire returns an held ire */
9425 			ire = ipif_to_ire(ipif);
9426 			if (ire == NULL)
9427 				goto err_ret;
9428 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9429 				goto err_ret;
9430 			/*
9431 			 * ihandle is needed when the ire is added to
9432 			 * cache table.
9433 			 */
9434 			save_ire = ire;
9435 			ihandle = save_ire->ire_ihandle;
9436 
9437 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9438 			    "flags %04x\n",
9439 			    (void *)ire, (void *)ipif, flags));
9440 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9441 			    (fire->ire_flags & RTF_MULTIRT)) {
9442 				/*
9443 				 * As requested by flags, an IRE_OFFSUBNET was
9444 				 * looked up on that interface. This ire has
9445 				 * RTF_MULTIRT flag, so the resolution loop will
9446 				 * be re-entered to resolve additional routes on
9447 				 * other interfaces. For that purpose, a copy of
9448 				 * the packet is performed at this point.
9449 				 */
9450 				fire->ire_last_used_time = lbolt;
9451 				copy_mp = copymsg(first_mp);
9452 				if (copy_mp) {
9453 					MULTIRT_DEBUG_TAG(copy_mp);
9454 				}
9455 			}
9456 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9457 			    (fire->ire_flags & RTF_SETSRC)) {
9458 				/*
9459 				 * As requested by flags, an IRE_OFFSUBET was
9460 				 * looked up on that interface. This ire has
9461 				 * RTF_SETSRC flag, so the source address of the
9462 				 * packet must be changed.
9463 				 */
9464 				ipha->ipha_src = fire->ire_src_addr;
9465 			}
9466 		} else {
9467 			ASSERT((connp == NULL) ||
9468 			    (connp->conn_xmit_if_ill != NULL) ||
9469 			    (connp->conn_dontroute) ||
9470 			    infop->ip_opt_ill_index != 0);
9471 			/*
9472 			 * The only ways we can come here are:
9473 			 * 1) IP_XMIT_IF socket option is set
9474 			 * 2) ICMP error message generated from
9475 			 *    ip_mrtun_forward() routine and it needs
9476 			 *    to go through the specified ill.
9477 			 * 3) SO_DONTROUTE socket option is set
9478 			 * 4) IP_PKTINFO option is passed in as ancillary data.
9479 			 * In all cases, the new ire will not be added
9480 			 * into cache table.
9481 			 */
9482 			ire_marks |= IRE_MARK_NOADD;
9483 		}
9484 
9485 		switch (ipif->ipif_net_type) {
9486 		case IRE_IF_NORESOLVER: {
9487 			/* We have what we need to build an IRE_CACHE. */
9488 
9489 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9490 			    (dst_ill->ill_resolver_mp == NULL)) {
9491 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9492 				    "for IRE_IF_NORESOLVER ire %p has "
9493 				    "no ill_resolver_mp\n",
9494 				    (void *)dst_ill, (void *)ire));
9495 				break;
9496 			}
9497 
9498 			/*
9499 			 * The new ire inherits the IRE_OFFSUBNET flags
9500 			 * and source address, if this was requested.
9501 			 */
9502 			ire = ire_create(
9503 			    (uchar_t *)&dst,		/* dest address */
9504 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9505 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9506 			    NULL,			/* gateway address */
9507 			    NULL,
9508 			    &ipif->ipif_mtu,
9509 			    NULL,			/* no src nce */
9510 			    dst_ill->ill_rq,		/* recv-from queue */
9511 			    dst_ill->ill_wq,		/* send-to queue */
9512 			    IRE_CACHE,
9513 			    src_ipif,
9514 			    NULL,
9515 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9516 			    (fire != NULL) ?		/* Parent handle */
9517 			    fire->ire_phandle : 0,
9518 			    ihandle,			/* Interface handle */
9519 			    (fire != NULL) ?
9520 			    (fire->ire_flags &
9521 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9522 			    (save_ire == NULL ? &ire_uinfo_null :
9523 			    &save_ire->ire_uinfo),
9524 			    NULL,
9525 			    NULL,
9526 			    ipst);
9527 
9528 			if (ire == NULL) {
9529 				if (save_ire != NULL)
9530 					ire_refrele(save_ire);
9531 				break;
9532 			}
9533 
9534 			ire->ire_marks |= ire_marks;
9535 
9536 			/*
9537 			 * If IRE_MARK_NOADD is set then we need to convert
9538 			 * the max_fragp to a useable value now. This is
9539 			 * normally done in ire_add_v[46]. We also need to
9540 			 * associate the ire with an nce (normally would be
9541 			 * done in ip_wput_nondata()).
9542 			 *
9543 			 * Note that IRE_MARK_NOADD packets created here
9544 			 * do not have a non-null ire_mp pointer. The null
9545 			 * value of ire_bucket indicates that they were
9546 			 * never added.
9547 			 */
9548 			if (ire->ire_marks & IRE_MARK_NOADD) {
9549 				uint_t  max_frag;
9550 
9551 				max_frag = *ire->ire_max_fragp;
9552 				ire->ire_max_fragp = NULL;
9553 				ire->ire_max_frag = max_frag;
9554 
9555 				if ((ire->ire_nce = ndp_lookup_v4(
9556 				    ire_to_ill(ire),
9557 				    (ire->ire_gateway_addr != INADDR_ANY ?
9558 				    &ire->ire_gateway_addr : &ire->ire_addr),
9559 				    B_FALSE)) == NULL) {
9560 					if (save_ire != NULL)
9561 						ire_refrele(save_ire);
9562 					break;
9563 				}
9564 				ASSERT(ire->ire_nce->nce_state ==
9565 				    ND_REACHABLE);
9566 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9567 			}
9568 
9569 			/* Prevent save_ire from getting deleted */
9570 			if (save_ire != NULL) {
9571 				IRB_REFHOLD(save_ire->ire_bucket);
9572 				/* Has it been removed already ? */
9573 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9574 					IRB_REFRELE(save_ire->ire_bucket);
9575 					ire_refrele(save_ire);
9576 					break;
9577 				}
9578 			}
9579 
9580 			ire_add_then_send(q, ire, first_mp);
9581 
9582 			/* Assert that save_ire is not deleted yet. */
9583 			if (save_ire != NULL) {
9584 				ASSERT(save_ire->ire_ptpn != NULL);
9585 				IRB_REFRELE(save_ire->ire_bucket);
9586 				ire_refrele(save_ire);
9587 				save_ire = NULL;
9588 			}
9589 			if (fire != NULL) {
9590 				ire_refrele(fire);
9591 				fire = NULL;
9592 			}
9593 
9594 			/*
9595 			 * the resolution loop is re-entered if this
9596 			 * was requested through flags and if we
9597 			 * actually are in a multirouting case.
9598 			 */
9599 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9600 				boolean_t need_resolve =
9601 				    ire_multirt_need_resolve(ipha_dst,
9602 				    MBLK_GETLABEL(copy_mp), ipst);
9603 				if (!need_resolve) {
9604 					MULTIRT_DEBUG_UNTAG(copy_mp);
9605 					freemsg(copy_mp);
9606 					copy_mp = NULL;
9607 				} else {
9608 					/*
9609 					 * ipif_lookup_group() calls
9610 					 * ire_lookup_multi() that uses
9611 					 * ire_ftable_lookup() to find
9612 					 * an IRE_INTERFACE for the group.
9613 					 * In the multirt case,
9614 					 * ire_lookup_multi() then invokes
9615 					 * ire_multirt_lookup() to find
9616 					 * the next resolvable ire.
9617 					 * As a result, we obtain an new
9618 					 * interface, derived from the
9619 					 * next ire.
9620 					 */
9621 					ipif_refrele(ipif);
9622 					ipif = ipif_lookup_group(ipha_dst,
9623 					    zoneid, ipst);
9624 					ip2dbg(("ip_newroute_ipif: "
9625 					    "multirt dst %08x, ipif %p\n",
9626 					    htonl(dst), (void *)ipif));
9627 					if (ipif != NULL) {
9628 						mp = copy_mp;
9629 						copy_mp = NULL;
9630 						multirt_resolve_next = B_TRUE;
9631 						continue;
9632 					} else {
9633 						freemsg(copy_mp);
9634 					}
9635 				}
9636 			}
9637 			if (ipif != NULL)
9638 				ipif_refrele(ipif);
9639 			ill_refrele(dst_ill);
9640 			ipif_refrele(src_ipif);
9641 			return;
9642 		}
9643 		case IRE_IF_RESOLVER:
9644 			/*
9645 			 * We can't build an IRE_CACHE yet, but at least
9646 			 * we found a resolver that can help.
9647 			 */
9648 			res_mp = dst_ill->ill_resolver_mp;
9649 			if (!OK_RESOLVER_MP(res_mp))
9650 				break;
9651 
9652 			/*
9653 			 * We obtain a partial IRE_CACHE which we will pass
9654 			 * along with the resolver query.  When the response
9655 			 * comes back it will be there ready for us to add.
9656 			 * The new ire inherits the IRE_OFFSUBNET flags
9657 			 * and source address, if this was requested.
9658 			 * The ire_max_frag is atomically set under the
9659 			 * irebucket lock in ire_add_v[46]. Only in the
9660 			 * case of IRE_MARK_NOADD, we set it here itself.
9661 			 */
9662 			ire = ire_create_mp(
9663 			    (uchar_t *)&dst,		/* dest address */
9664 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9665 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9666 			    NULL,			/* gateway address */
9667 			    NULL,			/* no in_src_addr */
9668 			    (ire_marks & IRE_MARK_NOADD) ?
9669 			    ipif->ipif_mtu : 0,		/* max_frag */
9670 			    NULL,			/* no src nce */
9671 			    dst_ill->ill_rq,		/* recv-from queue */
9672 			    dst_ill->ill_wq,		/* send-to queue */
9673 			    IRE_CACHE,
9674 			    src_ipif,
9675 			    NULL,
9676 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9677 			    (fire != NULL) ?		/* Parent handle */
9678 			    fire->ire_phandle : 0,
9679 			    ihandle,			/* Interface handle */
9680 			    (fire != NULL) ?		/* flags if any */
9681 			    (fire->ire_flags &
9682 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9683 			    (save_ire == NULL ? &ire_uinfo_null :
9684 			    &save_ire->ire_uinfo),
9685 			    NULL,
9686 			    NULL,
9687 			    ipst);
9688 
9689 			if (save_ire != NULL) {
9690 				ire_refrele(save_ire);
9691 				save_ire = NULL;
9692 			}
9693 			if (ire == NULL)
9694 				break;
9695 
9696 			ire->ire_marks |= ire_marks;
9697 			/*
9698 			 * Construct message chain for the resolver of the
9699 			 * form:
9700 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9701 			 *
9702 			 * NOTE : ire will be added later when the response
9703 			 * comes back from ARP. If the response does not
9704 			 * come back, ARP frees the packet. For this reason,
9705 			 * we can't REFHOLD the bucket of save_ire to prevent
9706 			 * deletions. We may not be able to REFRELE the
9707 			 * bucket if the response never comes back.
9708 			 * Thus, before adding the ire, ire_add_v4 will make
9709 			 * sure that the interface route does not get deleted.
9710 			 * This is the only case unlike ip_newroute_v6,
9711 			 * ip_newroute_ipif_v6 where we can always prevent
9712 			 * deletions because ire_add_then_send is called after
9713 			 * creating the IRE.
9714 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9715 			 * does not add this IRE into the IRE CACHE.
9716 			 */
9717 			ASSERT(ire->ire_mp != NULL);
9718 			ire->ire_mp->b_cont = first_mp;
9719 			/* Have saved_mp handy, for cleanup if canput fails */
9720 			saved_mp = mp;
9721 			mp = copyb(res_mp);
9722 			if (mp == NULL) {
9723 				/* Prepare for cleanup */
9724 				mp = saved_mp; /* pkt */
9725 				ire_delete(ire); /* ire_mp */
9726 				ire = NULL;
9727 				if (copy_mp != NULL) {
9728 					MULTIRT_DEBUG_UNTAG(copy_mp);
9729 					freemsg(copy_mp);
9730 					copy_mp = NULL;
9731 				}
9732 				break;
9733 			}
9734 			linkb(mp, ire->ire_mp);
9735 
9736 			/*
9737 			 * Fill in the source and dest addrs for the resolver.
9738 			 * NOTE: this depends on memory layouts imposed by
9739 			 * ill_init().
9740 			 */
9741 			areq = (areq_t *)mp->b_rptr;
9742 			addrp = (ipaddr_t *)((char *)areq +
9743 			    areq->areq_sender_addr_offset);
9744 			*addrp = ire->ire_src_addr;
9745 			addrp = (ipaddr_t *)((char *)areq +
9746 			    areq->areq_target_addr_offset);
9747 			*addrp = dst;
9748 			/* Up to the resolver. */
9749 			if (canputnext(dst_ill->ill_rq) &&
9750 			    !(dst_ill->ill_arp_closing)) {
9751 				putnext(dst_ill->ill_rq, mp);
9752 				/*
9753 				 * The response will come back in ip_wput
9754 				 * with db_type IRE_DB_TYPE.
9755 				 */
9756 			} else {
9757 				mp->b_cont = NULL;
9758 				freeb(mp); /* areq */
9759 				ire_delete(ire); /* ire_mp */
9760 				saved_mp->b_next = NULL;
9761 				saved_mp->b_prev = NULL;
9762 				freemsg(first_mp); /* pkt */
9763 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9764 			}
9765 
9766 			if (fire != NULL) {
9767 				ire_refrele(fire);
9768 				fire = NULL;
9769 			}
9770 
9771 
9772 			/*
9773 			 * The resolution loop is re-entered if this was
9774 			 * requested through flags and we actually are
9775 			 * in a multirouting case.
9776 			 */
9777 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9778 				boolean_t need_resolve =
9779 				    ire_multirt_need_resolve(ipha_dst,
9780 				    MBLK_GETLABEL(copy_mp), ipst);
9781 				if (!need_resolve) {
9782 					MULTIRT_DEBUG_UNTAG(copy_mp);
9783 					freemsg(copy_mp);
9784 					copy_mp = NULL;
9785 				} else {
9786 					/*
9787 					 * ipif_lookup_group() calls
9788 					 * ire_lookup_multi() that uses
9789 					 * ire_ftable_lookup() to find
9790 					 * an IRE_INTERFACE for the group.
9791 					 * In the multirt case,
9792 					 * ire_lookup_multi() then invokes
9793 					 * ire_multirt_lookup() to find
9794 					 * the next resolvable ire.
9795 					 * As a result, we obtain an new
9796 					 * interface, derived from the
9797 					 * next ire.
9798 					 */
9799 					ipif_refrele(ipif);
9800 					ipif = ipif_lookup_group(ipha_dst,
9801 					    zoneid, ipst);
9802 					if (ipif != NULL) {
9803 						mp = copy_mp;
9804 						copy_mp = NULL;
9805 						multirt_resolve_next = B_TRUE;
9806 						continue;
9807 					} else {
9808 						freemsg(copy_mp);
9809 					}
9810 				}
9811 			}
9812 			if (ipif != NULL)
9813 				ipif_refrele(ipif);
9814 			ill_refrele(dst_ill);
9815 			ipif_refrele(src_ipif);
9816 			return;
9817 		default:
9818 			break;
9819 		}
9820 	} while (multirt_resolve_next);
9821 
9822 err_ret:
9823 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9824 	if (fire != NULL)
9825 		ire_refrele(fire);
9826 	ipif_refrele(ipif);
9827 	/* Did this packet originate externally? */
9828 	if (dst_ill != NULL)
9829 		ill_refrele(dst_ill);
9830 	if (src_ipif != NULL)
9831 		ipif_refrele(src_ipif);
9832 	if (mp->b_prev || mp->b_next) {
9833 		mp->b_next = NULL;
9834 		mp->b_prev = NULL;
9835 	} else {
9836 		/*
9837 		 * Since ip_wput() isn't close to finished, we fill
9838 		 * in enough of the header for credible error reporting.
9839 		 */
9840 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9841 			/* Failed */
9842 			freemsg(first_mp);
9843 			if (ire != NULL)
9844 				ire_refrele(ire);
9845 			return;
9846 		}
9847 	}
9848 	/*
9849 	 * At this point we will have ire only if RTF_BLACKHOLE
9850 	 * or RTF_REJECT flags are set on the IRE. It will not
9851 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9852 	 */
9853 	if (ire != NULL) {
9854 		if (ire->ire_flags & RTF_BLACKHOLE) {
9855 			ire_refrele(ire);
9856 			freemsg(first_mp);
9857 			return;
9858 		}
9859 		ire_refrele(ire);
9860 	}
9861 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9862 }
9863 
9864 /* Name/Value Table Lookup Routine */
9865 char *
9866 ip_nv_lookup(nv_t *nv, int value)
9867 {
9868 	if (!nv)
9869 		return (NULL);
9870 	for (; nv->nv_name; nv++) {
9871 		if (nv->nv_value == value)
9872 			return (nv->nv_name);
9873 	}
9874 	return ("unknown");
9875 }
9876 
9877 /*
9878  * This is a module open, i.e. this is a control stream for access
9879  * to a DLPI device.  We allocate an ill_t as the instance data in
9880  * this case.
9881  */
9882 int
9883 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9884 {
9885 	ill_t	*ill;
9886 	int	err;
9887 	zoneid_t zoneid;
9888 	netstack_t *ns;
9889 	ip_stack_t *ipst;
9890 
9891 	/*
9892 	 * Prevent unprivileged processes from pushing IP so that
9893 	 * they can't send raw IP.
9894 	 */
9895 	if (secpolicy_net_rawaccess(credp) != 0)
9896 		return (EPERM);
9897 
9898 	ns = netstack_find_by_cred(credp);
9899 	ASSERT(ns != NULL);
9900 	ipst = ns->netstack_ip;
9901 	ASSERT(ipst != NULL);
9902 
9903 	/*
9904 	 * For exclusive stacks we set the zoneid to zero
9905 	 * to make IP operate as if in the global zone.
9906 	 */
9907 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9908 		zoneid = GLOBAL_ZONEID;
9909 	else
9910 		zoneid = crgetzoneid(credp);
9911 
9912 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9913 	q->q_ptr = WR(q)->q_ptr = ill;
9914 	ill->ill_ipst = ipst;
9915 	ill->ill_zoneid = zoneid;
9916 
9917 	/*
9918 	 * ill_init initializes the ill fields and then sends down
9919 	 * down a DL_INFO_REQ after calling qprocson.
9920 	 */
9921 	err = ill_init(q, ill);
9922 	if (err != 0) {
9923 		mi_free(ill);
9924 		netstack_rele(ipst->ips_netstack);
9925 		q->q_ptr = NULL;
9926 		WR(q)->q_ptr = NULL;
9927 		return (err);
9928 	}
9929 
9930 	/* ill_init initializes the ipsq marking this thread as writer */
9931 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9932 	/* Wait for the DL_INFO_ACK */
9933 	mutex_enter(&ill->ill_lock);
9934 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9935 		/*
9936 		 * Return value of 0 indicates a pending signal.
9937 		 */
9938 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9939 		if (err == 0) {
9940 			mutex_exit(&ill->ill_lock);
9941 			(void) ip_close(q, 0);
9942 			return (EINTR);
9943 		}
9944 	}
9945 	mutex_exit(&ill->ill_lock);
9946 
9947 	/*
9948 	 * ip_rput_other could have set an error  in ill_error on
9949 	 * receipt of M_ERROR.
9950 	 */
9951 
9952 	err = ill->ill_error;
9953 	if (err != 0) {
9954 		(void) ip_close(q, 0);
9955 		return (err);
9956 	}
9957 
9958 	ill->ill_credp = credp;
9959 	crhold(credp);
9960 
9961 	mutex_enter(&ipst->ips_ip_mi_lock);
9962 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9963 	    credp);
9964 	mutex_exit(&ipst->ips_ip_mi_lock);
9965 	if (err) {
9966 		(void) ip_close(q, 0);
9967 		return (err);
9968 	}
9969 	return (0);
9970 }
9971 
9972 /* IP open routine. */
9973 int
9974 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9975 {
9976 	conn_t 		*connp;
9977 	major_t		maj;
9978 	zoneid_t	zoneid;
9979 	netstack_t	*ns;
9980 	ip_stack_t	*ipst;
9981 
9982 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9983 
9984 	/* Allow reopen. */
9985 	if (q->q_ptr != NULL)
9986 		return (0);
9987 
9988 	if (sflag & MODOPEN) {
9989 		/* This is a module open */
9990 		return (ip_modopen(q, devp, flag, sflag, credp));
9991 	}
9992 
9993 	ns = netstack_find_by_cred(credp);
9994 	ASSERT(ns != NULL);
9995 	ipst = ns->netstack_ip;
9996 	ASSERT(ipst != NULL);
9997 
9998 	/*
9999 	 * For exclusive stacks we set the zoneid to zero
10000 	 * to make IP operate as if in the global zone.
10001 	 */
10002 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
10003 		zoneid = GLOBAL_ZONEID;
10004 	else
10005 		zoneid = crgetzoneid(credp);
10006 
10007 	/*
10008 	 * We are opening as a device. This is an IP client stream, and we
10009 	 * allocate an conn_t as the instance data.
10010 	 */
10011 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
10012 
10013 	/*
10014 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
10015 	 * done by netstack_find_by_cred()
10016 	 */
10017 	netstack_rele(ipst->ips_netstack);
10018 
10019 	connp->conn_zoneid = zoneid;
10020 
10021 	connp->conn_upq = q;
10022 	q->q_ptr = WR(q)->q_ptr = connp;
10023 
10024 	if (flag & SO_SOCKSTR)
10025 		connp->conn_flags |= IPCL_SOCKET;
10026 
10027 	/* Minor tells us which /dev entry was opened */
10028 	if (geteminor(*devp) == IPV6_MINOR) {
10029 		connp->conn_flags |= IPCL_ISV6;
10030 		connp->conn_af_isv6 = B_TRUE;
10031 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
10032 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
10033 	} else {
10034 		connp->conn_af_isv6 = B_FALSE;
10035 		connp->conn_pkt_isv6 = B_FALSE;
10036 	}
10037 
10038 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
10039 		/* CONN_DEC_REF takes care of netstack_rele() */
10040 		q->q_ptr = WR(q)->q_ptr = NULL;
10041 		CONN_DEC_REF(connp);
10042 		return (EBUSY);
10043 	}
10044 
10045 	maj = getemajor(*devp);
10046 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
10047 
10048 	/*
10049 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
10050 	 */
10051 	connp->conn_cred = credp;
10052 	crhold(connp->conn_cred);
10053 
10054 	/*
10055 	 * If the caller has the process-wide flag set, then default to MAC
10056 	 * exempt mode.  This allows read-down to unlabeled hosts.
10057 	 */
10058 	if (getpflags(NET_MAC_AWARE, credp) != 0)
10059 		connp->conn_mac_exempt = B_TRUE;
10060 
10061 	/*
10062 	 * This should only happen for ndd, netstat, raw socket or other SCTP
10063 	 * administrative ops.  In these cases, we just need a normal conn_t
10064 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
10065 	 * an error will be returned.
10066 	 */
10067 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
10068 		connp->conn_rq = q;
10069 		connp->conn_wq = WR(q);
10070 	} else {
10071 		connp->conn_ulp = IPPROTO_SCTP;
10072 		connp->conn_rq = connp->conn_wq = NULL;
10073 	}
10074 	/* Non-zero default values */
10075 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
10076 
10077 	/*
10078 	 * Make the conn globally visible to walkers
10079 	 */
10080 	mutex_enter(&connp->conn_lock);
10081 	connp->conn_state_flags &= ~CONN_INCIPIENT;
10082 	mutex_exit(&connp->conn_lock);
10083 	ASSERT(connp->conn_ref == 1);
10084 
10085 	qprocson(q);
10086 
10087 	return (0);
10088 }
10089 
10090 /*
10091  * Change q_qinfo based on the value of isv6.
10092  * This can not called on an ill queue.
10093  * Note that there is no race since either q_qinfo works for conn queues - it
10094  * is just an optimization to enter the best wput routine directly.
10095  */
10096 void
10097 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
10098 {
10099 	ASSERT(q->q_flag & QREADR);
10100 	ASSERT(WR(q)->q_next == NULL);
10101 	ASSERT(q->q_ptr != NULL);
10102 
10103 	if (minor == IPV6_MINOR)  {
10104 		if (bump_mib) {
10105 			BUMP_MIB(&ipst->ips_ip6_mib,
10106 			    ipIfStatsOutSwitchIPVersion);
10107 		}
10108 		q->q_qinfo = &rinit_ipv6;
10109 		WR(q)->q_qinfo = &winit_ipv6;
10110 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
10111 	} else {
10112 		if (bump_mib) {
10113 			BUMP_MIB(&ipst->ips_ip_mib,
10114 			    ipIfStatsOutSwitchIPVersion);
10115 		}
10116 		q->q_qinfo = &iprinit;
10117 		WR(q)->q_qinfo = &ipwinit;
10118 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
10119 	}
10120 
10121 }
10122 
10123 /*
10124  * See if IPsec needs loading because of the options in mp.
10125  */
10126 static boolean_t
10127 ipsec_opt_present(mblk_t *mp)
10128 {
10129 	uint8_t *optcp, *next_optcp, *opt_endcp;
10130 	struct opthdr *opt;
10131 	struct T_opthdr *topt;
10132 	int opthdr_len;
10133 	t_uscalar_t optname, optlevel;
10134 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
10135 	ipsec_req_t *ipsr;
10136 
10137 	/*
10138 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10139 	 * return TRUE.
10140 	 */
10141 
10142 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10143 	opt_endcp = optcp + tor->OPT_length;
10144 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10145 		opthdr_len = sizeof (struct T_opthdr);
10146 	} else {		/* O_OPTMGMT_REQ */
10147 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10148 		opthdr_len = sizeof (struct opthdr);
10149 	}
10150 	for (; optcp < opt_endcp; optcp = next_optcp) {
10151 		if (optcp + opthdr_len > opt_endcp)
10152 			return (B_FALSE);	/* Not enough option header. */
10153 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10154 			topt = (struct T_opthdr *)optcp;
10155 			optlevel = topt->level;
10156 			optname = topt->name;
10157 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10158 		} else {
10159 			opt = (struct opthdr *)optcp;
10160 			optlevel = opt->level;
10161 			optname = opt->name;
10162 			next_optcp = optcp + opthdr_len +
10163 			    _TPI_ALIGN_OPT(opt->len);
10164 		}
10165 		if ((next_optcp < optcp) || /* wraparound pointer space */
10166 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10167 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10168 			return (B_FALSE); /* bad option buffer */
10169 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10170 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10171 			/*
10172 			 * Check to see if it's an all-bypass or all-zeroes
10173 			 * IPsec request.  Don't bother loading IPsec if
10174 			 * the socket doesn't want to use it.  (A good example
10175 			 * is a bypass request.)
10176 			 *
10177 			 * Basically, if any of the non-NEVER bits are set,
10178 			 * load IPsec.
10179 			 */
10180 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10181 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10182 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10183 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10184 			    != 0)
10185 				return (B_TRUE);
10186 		}
10187 	}
10188 	return (B_FALSE);
10189 }
10190 
10191 /*
10192  * If conn is is waiting for ipsec to finish loading, kick it.
10193  */
10194 /* ARGSUSED */
10195 static void
10196 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10197 {
10198 	t_scalar_t	optreq_prim;
10199 	mblk_t		*mp;
10200 	cred_t		*cr;
10201 	int		err = 0;
10202 
10203 	/*
10204 	 * This function is called, after ipsec loading is complete.
10205 	 * Since IP checks exclusively and atomically (i.e it prevents
10206 	 * ipsec load from completing until ip_optcom_req completes)
10207 	 * whether ipsec load is complete, there cannot be a race with IP
10208 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10209 	 */
10210 	mutex_enter(&connp->conn_lock);
10211 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10212 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10213 		mp = connp->conn_ipsec_opt_mp;
10214 		connp->conn_ipsec_opt_mp = NULL;
10215 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10216 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10217 		mutex_exit(&connp->conn_lock);
10218 
10219 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10220 
10221 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10222 		if (optreq_prim == T_OPTMGMT_REQ) {
10223 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10224 			    &ip_opt_obj);
10225 		} else {
10226 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10227 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10228 			    &ip_opt_obj);
10229 		}
10230 		if (err != EINPROGRESS)
10231 			CONN_OPER_PENDING_DONE(connp);
10232 		return;
10233 	}
10234 	mutex_exit(&connp->conn_lock);
10235 }
10236 
10237 /*
10238  * Called from the ipsec_loader thread, outside any perimeter, to tell
10239  * ip qenable any of the queues waiting for the ipsec loader to
10240  * complete.
10241  */
10242 void
10243 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10244 {
10245 	netstack_t *ns = ipss->ipsec_netstack;
10246 
10247 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10248 }
10249 
10250 /*
10251  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10252  * determines the grp on which it has to become exclusive, queues the mp
10253  * and sq draining restarts the optmgmt
10254  */
10255 static boolean_t
10256 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10257 {
10258 	conn_t *connp = Q_TO_CONN(q);
10259 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10260 
10261 	/*
10262 	 * Take IPsec requests and treat them special.
10263 	 */
10264 	if (ipsec_opt_present(mp)) {
10265 		/* First check if IPsec is loaded. */
10266 		mutex_enter(&ipss->ipsec_loader_lock);
10267 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10268 			mutex_exit(&ipss->ipsec_loader_lock);
10269 			return (B_FALSE);
10270 		}
10271 		mutex_enter(&connp->conn_lock);
10272 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10273 
10274 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10275 		connp->conn_ipsec_opt_mp = mp;
10276 		mutex_exit(&connp->conn_lock);
10277 		mutex_exit(&ipss->ipsec_loader_lock);
10278 
10279 		ipsec_loader_loadnow(ipss);
10280 		return (B_TRUE);
10281 	}
10282 	return (B_FALSE);
10283 }
10284 
10285 /*
10286  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10287  * all of them are copied to the conn_t. If the req is "zero", the policy is
10288  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10289  * fields.
10290  * We keep only the latest setting of the policy and thus policy setting
10291  * is not incremental/cumulative.
10292  *
10293  * Requests to set policies with multiple alternative actions will
10294  * go through a different API.
10295  */
10296 int
10297 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10298 {
10299 	uint_t ah_req = 0;
10300 	uint_t esp_req = 0;
10301 	uint_t se_req = 0;
10302 	ipsec_selkey_t sel;
10303 	ipsec_act_t *actp = NULL;
10304 	uint_t nact;
10305 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10306 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10307 	ipsec_policy_root_t *pr;
10308 	ipsec_policy_head_t *ph;
10309 	int fam;
10310 	boolean_t is_pol_reset;
10311 	int error = 0;
10312 	netstack_t	*ns = connp->conn_netstack;
10313 	ip_stack_t	*ipst = ns->netstack_ip;
10314 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10315 
10316 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10317 
10318 	/*
10319 	 * The IP_SEC_OPT option does not allow variable length parameters,
10320 	 * hence a request cannot be NULL.
10321 	 */
10322 	if (req == NULL)
10323 		return (EINVAL);
10324 
10325 	ah_req = req->ipsr_ah_req;
10326 	esp_req = req->ipsr_esp_req;
10327 	se_req = req->ipsr_self_encap_req;
10328 
10329 	/*
10330 	 * Are we dealing with a request to reset the policy (i.e.
10331 	 * zero requests).
10332 	 */
10333 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10334 	    (esp_req & REQ_MASK) == 0 &&
10335 	    (se_req & REQ_MASK) == 0);
10336 
10337 	if (!is_pol_reset) {
10338 		/*
10339 		 * If we couldn't load IPsec, fail with "protocol
10340 		 * not supported".
10341 		 * IPsec may not have been loaded for a request with zero
10342 		 * policies, so we don't fail in this case.
10343 		 */
10344 		mutex_enter(&ipss->ipsec_loader_lock);
10345 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10346 			mutex_exit(&ipss->ipsec_loader_lock);
10347 			return (EPROTONOSUPPORT);
10348 		}
10349 		mutex_exit(&ipss->ipsec_loader_lock);
10350 
10351 		/*
10352 		 * Test for valid requests. Invalid algorithms
10353 		 * need to be tested by IPSEC code because new
10354 		 * algorithms can be added dynamically.
10355 		 */
10356 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10357 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10358 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10359 			return (EINVAL);
10360 		}
10361 
10362 		/*
10363 		 * Only privileged users can issue these
10364 		 * requests.
10365 		 */
10366 		if (((ah_req & IPSEC_PREF_NEVER) ||
10367 		    (esp_req & IPSEC_PREF_NEVER) ||
10368 		    (se_req & IPSEC_PREF_NEVER)) &&
10369 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10370 			return (EPERM);
10371 		}
10372 
10373 		/*
10374 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10375 		 * are mutually exclusive.
10376 		 */
10377 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10378 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10379 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10380 			/* Both of them are set */
10381 			return (EINVAL);
10382 		}
10383 	}
10384 
10385 	mutex_enter(&connp->conn_lock);
10386 
10387 	/*
10388 	 * If we have already cached policies in ip_bind_connected*(), don't
10389 	 * let them change now. We cache policies for connections
10390 	 * whose src,dst [addr, port] is known.
10391 	 */
10392 	if (connp->conn_policy_cached) {
10393 		mutex_exit(&connp->conn_lock);
10394 		return (EINVAL);
10395 	}
10396 
10397 	/*
10398 	 * We have a zero policies, reset the connection policy if already
10399 	 * set. This will cause the connection to inherit the
10400 	 * global policy, if any.
10401 	 */
10402 	if (is_pol_reset) {
10403 		if (connp->conn_policy != NULL) {
10404 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10405 			connp->conn_policy = NULL;
10406 		}
10407 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10408 		connp->conn_in_enforce_policy = B_FALSE;
10409 		connp->conn_out_enforce_policy = B_FALSE;
10410 		mutex_exit(&connp->conn_lock);
10411 		return (0);
10412 	}
10413 
10414 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10415 	    ipst->ips_netstack);
10416 	if (ph == NULL)
10417 		goto enomem;
10418 
10419 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10420 	if (actp == NULL)
10421 		goto enomem;
10422 
10423 	/*
10424 	 * Always allocate IPv4 policy entries, since they can also
10425 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10426 	 */
10427 	bzero(&sel, sizeof (sel));
10428 	sel.ipsl_valid = IPSL_IPV4;
10429 
10430 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10431 	    ipst->ips_netstack);
10432 	if (pin4 == NULL)
10433 		goto enomem;
10434 
10435 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10436 	    ipst->ips_netstack);
10437 	if (pout4 == NULL)
10438 		goto enomem;
10439 
10440 	if (connp->conn_pkt_isv6) {
10441 		/*
10442 		 * We're looking at a v6 socket, also allocate the
10443 		 * v6-specific entries...
10444 		 */
10445 		sel.ipsl_valid = IPSL_IPV6;
10446 		pin6 = ipsec_policy_create(&sel, actp, nact,
10447 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10448 		if (pin6 == NULL)
10449 			goto enomem;
10450 
10451 		pout6 = ipsec_policy_create(&sel, actp, nact,
10452 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10453 		if (pout6 == NULL)
10454 			goto enomem;
10455 
10456 		/*
10457 		 * .. and file them away in the right place.
10458 		 */
10459 		fam = IPSEC_AF_V6;
10460 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10461 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10462 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10463 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10464 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10465 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10466 	}
10467 
10468 	ipsec_actvec_free(actp, nact);
10469 
10470 	/*
10471 	 * File the v4 policies.
10472 	 */
10473 	fam = IPSEC_AF_V4;
10474 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10475 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10476 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10477 
10478 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10479 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10480 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10481 
10482 	/*
10483 	 * If the requests need security, set enforce_policy.
10484 	 * If the requests are IPSEC_PREF_NEVER, one should
10485 	 * still set conn_out_enforce_policy so that an ipsec_out
10486 	 * gets attached in ip_wput. This is needed so that
10487 	 * for connections that we don't cache policy in ip_bind,
10488 	 * if global policy matches in ip_wput_attach_policy, we
10489 	 * don't wrongly inherit global policy. Similarly, we need
10490 	 * to set conn_in_enforce_policy also so that we don't verify
10491 	 * policy wrongly.
10492 	 */
10493 	if ((ah_req & REQ_MASK) != 0 ||
10494 	    (esp_req & REQ_MASK) != 0 ||
10495 	    (se_req & REQ_MASK) != 0) {
10496 		connp->conn_in_enforce_policy = B_TRUE;
10497 		connp->conn_out_enforce_policy = B_TRUE;
10498 		connp->conn_flags |= IPCL_CHECK_POLICY;
10499 	}
10500 
10501 	mutex_exit(&connp->conn_lock);
10502 	return (error);
10503 #undef REQ_MASK
10504 
10505 	/*
10506 	 * Common memory-allocation-failure exit path.
10507 	 */
10508 enomem:
10509 	mutex_exit(&connp->conn_lock);
10510 	if (actp != NULL)
10511 		ipsec_actvec_free(actp, nact);
10512 	if (pin4 != NULL)
10513 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10514 	if (pout4 != NULL)
10515 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10516 	if (pin6 != NULL)
10517 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10518 	if (pout6 != NULL)
10519 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10520 	return (ENOMEM);
10521 }
10522 
10523 /*
10524  * Only for options that pass in an IP addr. Currently only V4 options
10525  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10526  * So this function assumes level is IPPROTO_IP
10527  */
10528 int
10529 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10530     mblk_t *first_mp)
10531 {
10532 	ipif_t *ipif = NULL;
10533 	int error;
10534 	ill_t *ill;
10535 	int zoneid;
10536 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10537 
10538 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10539 
10540 	if (addr != INADDR_ANY || checkonly) {
10541 		ASSERT(connp != NULL);
10542 		zoneid = IPCL_ZONEID(connp);
10543 		if (option == IP_NEXTHOP) {
10544 			ipif = ipif_lookup_onlink_addr(addr,
10545 			    connp->conn_zoneid, ipst);
10546 		} else {
10547 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10548 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10549 			    &error, ipst);
10550 		}
10551 		if (ipif == NULL) {
10552 			if (error == EINPROGRESS)
10553 				return (error);
10554 			else if ((option == IP_MULTICAST_IF) ||
10555 			    (option == IP_NEXTHOP))
10556 				return (EHOSTUNREACH);
10557 			else
10558 				return (EINVAL);
10559 		} else if (checkonly) {
10560 			if (option == IP_MULTICAST_IF) {
10561 				ill = ipif->ipif_ill;
10562 				/* not supported by the virtual network iface */
10563 				if (IS_VNI(ill)) {
10564 					ipif_refrele(ipif);
10565 					return (EINVAL);
10566 				}
10567 			}
10568 			ipif_refrele(ipif);
10569 			return (0);
10570 		}
10571 		ill = ipif->ipif_ill;
10572 		mutex_enter(&connp->conn_lock);
10573 		mutex_enter(&ill->ill_lock);
10574 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10575 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10576 			mutex_exit(&ill->ill_lock);
10577 			mutex_exit(&connp->conn_lock);
10578 			ipif_refrele(ipif);
10579 			return (option == IP_MULTICAST_IF ?
10580 			    EHOSTUNREACH : EINVAL);
10581 		}
10582 	} else {
10583 		mutex_enter(&connp->conn_lock);
10584 	}
10585 
10586 	/* None of the options below are supported on the VNI */
10587 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10588 		mutex_exit(&ill->ill_lock);
10589 		mutex_exit(&connp->conn_lock);
10590 		ipif_refrele(ipif);
10591 		return (EINVAL);
10592 	}
10593 
10594 	switch (option) {
10595 	case IP_DONTFAILOVER_IF:
10596 		/*
10597 		 * This option is used by in.mpathd to ensure
10598 		 * that IPMP probe packets only go out on the
10599 		 * test interfaces. in.mpathd sets this option
10600 		 * on the non-failover interfaces.
10601 		 * For backward compatibility, this option
10602 		 * implicitly sets IP_MULTICAST_IF, as used
10603 		 * be done in bind(), so that ip_wput gets
10604 		 * this ipif to send mcast packets.
10605 		 */
10606 		if (ipif != NULL) {
10607 			ASSERT(addr != INADDR_ANY);
10608 			connp->conn_nofailover_ill = ipif->ipif_ill;
10609 			connp->conn_multicast_ipif = ipif;
10610 		} else {
10611 			ASSERT(addr == INADDR_ANY);
10612 			connp->conn_nofailover_ill = NULL;
10613 			connp->conn_multicast_ipif = NULL;
10614 		}
10615 		break;
10616 
10617 	case IP_MULTICAST_IF:
10618 		connp->conn_multicast_ipif = ipif;
10619 		break;
10620 	case IP_NEXTHOP:
10621 		connp->conn_nexthop_v4 = addr;
10622 		connp->conn_nexthop_set = B_TRUE;
10623 		break;
10624 	}
10625 
10626 	if (ipif != NULL) {
10627 		mutex_exit(&ill->ill_lock);
10628 		mutex_exit(&connp->conn_lock);
10629 		ipif_refrele(ipif);
10630 		return (0);
10631 	}
10632 	mutex_exit(&connp->conn_lock);
10633 	/* We succeded in cleared the option */
10634 	return (0);
10635 }
10636 
10637 /*
10638  * For options that pass in an ifindex specifying the ill. V6 options always
10639  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10640  */
10641 int
10642 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10643     int level, int option, mblk_t *first_mp)
10644 {
10645 	ill_t *ill = NULL;
10646 	int error = 0;
10647 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10648 
10649 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10650 	if (ifindex != 0) {
10651 		ASSERT(connp != NULL);
10652 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10653 		    first_mp, ip_restart_optmgmt, &error, ipst);
10654 		if (ill != NULL) {
10655 			if (checkonly) {
10656 				/* not supported by the virtual network iface */
10657 				if (IS_VNI(ill)) {
10658 					ill_refrele(ill);
10659 					return (EINVAL);
10660 				}
10661 				ill_refrele(ill);
10662 				return (0);
10663 			}
10664 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10665 			    0, NULL)) {
10666 				ill_refrele(ill);
10667 				ill = NULL;
10668 				mutex_enter(&connp->conn_lock);
10669 				goto setit;
10670 			}
10671 			mutex_enter(&connp->conn_lock);
10672 			mutex_enter(&ill->ill_lock);
10673 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10674 				mutex_exit(&ill->ill_lock);
10675 				mutex_exit(&connp->conn_lock);
10676 				ill_refrele(ill);
10677 				ill = NULL;
10678 				mutex_enter(&connp->conn_lock);
10679 			}
10680 			goto setit;
10681 		} else if (error == EINPROGRESS) {
10682 			return (error);
10683 		} else {
10684 			error = 0;
10685 		}
10686 	}
10687 	mutex_enter(&connp->conn_lock);
10688 setit:
10689 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10690 
10691 	/*
10692 	 * The options below assume that the ILL (if any) transmits and/or
10693 	 * receives traffic. Neither of which is true for the virtual network
10694 	 * interface, so fail setting these on a VNI.
10695 	 */
10696 	if (IS_VNI(ill)) {
10697 		ASSERT(ill != NULL);
10698 		mutex_exit(&ill->ill_lock);
10699 		mutex_exit(&connp->conn_lock);
10700 		ill_refrele(ill);
10701 		return (EINVAL);
10702 	}
10703 
10704 	if (level == IPPROTO_IP) {
10705 		switch (option) {
10706 		case IP_BOUND_IF:
10707 			connp->conn_incoming_ill = ill;
10708 			connp->conn_outgoing_ill = ill;
10709 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10710 			    0 : ifindex;
10711 			break;
10712 
10713 		case IP_XMIT_IF:
10714 			/*
10715 			 * Similar to IP_BOUND_IF, but this only
10716 			 * determines the outgoing interface for
10717 			 * unicast packets. Also no IRE_CACHE entry
10718 			 * is added for the destination of the
10719 			 * outgoing packets. This feature is needed
10720 			 * for mobile IP.
10721 			 */
10722 			connp->conn_xmit_if_ill = ill;
10723 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10724 			    0 : ifindex;
10725 			break;
10726 
10727 		case IP_MULTICAST_IF:
10728 			/*
10729 			 * This option is an internal special. The socket
10730 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10731 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10732 			 * specifies an ifindex and we try first on V6 ill's.
10733 			 * If we don't find one, we they try using on v4 ill's
10734 			 * intenally and we come here.
10735 			 */
10736 			if (!checkonly && ill != NULL) {
10737 				ipif_t	*ipif;
10738 				ipif = ill->ill_ipif;
10739 
10740 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10741 					mutex_exit(&ill->ill_lock);
10742 					mutex_exit(&connp->conn_lock);
10743 					ill_refrele(ill);
10744 					ill = NULL;
10745 					mutex_enter(&connp->conn_lock);
10746 				} else {
10747 					connp->conn_multicast_ipif = ipif;
10748 				}
10749 			}
10750 			break;
10751 		}
10752 	} else {
10753 		switch (option) {
10754 		case IPV6_BOUND_IF:
10755 			connp->conn_incoming_ill = ill;
10756 			connp->conn_outgoing_ill = ill;
10757 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10758 			    0 : ifindex;
10759 			break;
10760 
10761 		case IPV6_BOUND_PIF:
10762 			/*
10763 			 * Limit all transmit to this ill.
10764 			 * Unlike IPV6_BOUND_IF, using this option
10765 			 * prevents load spreading and failover from
10766 			 * happening when the interface is part of the
10767 			 * group. That's why we don't need to remember
10768 			 * the ifindex in orig_bound_ifindex as in
10769 			 * IPV6_BOUND_IF.
10770 			 */
10771 			connp->conn_outgoing_pill = ill;
10772 			break;
10773 
10774 		case IPV6_DONTFAILOVER_IF:
10775 			/*
10776 			 * This option is used by in.mpathd to ensure
10777 			 * that IPMP probe packets only go out on the
10778 			 * test interfaces. in.mpathd sets this option
10779 			 * on the non-failover interfaces.
10780 			 */
10781 			connp->conn_nofailover_ill = ill;
10782 			/*
10783 			 * For backward compatibility, this option
10784 			 * implicitly sets ip_multicast_ill as used in
10785 			 * IP_MULTICAST_IF so that ip_wput gets
10786 			 * this ipif to send mcast packets.
10787 			 */
10788 			connp->conn_multicast_ill = ill;
10789 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10790 			    0 : ifindex;
10791 			break;
10792 
10793 		case IPV6_MULTICAST_IF:
10794 			/*
10795 			 * Set conn_multicast_ill to be the IPv6 ill.
10796 			 * Set conn_multicast_ipif to be an IPv4 ipif
10797 			 * for ifindex to make IPv4 mapped addresses
10798 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10799 			 * Even if no IPv6 ill exists for the ifindex
10800 			 * we need to check for an IPv4 ifindex in order
10801 			 * for this to work with mapped addresses. In that
10802 			 * case only set conn_multicast_ipif.
10803 			 */
10804 			if (!checkonly) {
10805 				if (ifindex == 0) {
10806 					connp->conn_multicast_ill = NULL;
10807 					connp->conn_orig_multicast_ifindex = 0;
10808 					connp->conn_multicast_ipif = NULL;
10809 				} else if (ill != NULL) {
10810 					connp->conn_multicast_ill = ill;
10811 					connp->conn_orig_multicast_ifindex =
10812 					    ifindex;
10813 				}
10814 			}
10815 			break;
10816 		}
10817 	}
10818 
10819 	if (ill != NULL) {
10820 		mutex_exit(&ill->ill_lock);
10821 		mutex_exit(&connp->conn_lock);
10822 		ill_refrele(ill);
10823 		return (0);
10824 	}
10825 	mutex_exit(&connp->conn_lock);
10826 	/*
10827 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10828 	 * locate the ill and could not set the option (ifindex != 0)
10829 	 */
10830 	return (ifindex == 0 ? 0 : EINVAL);
10831 }
10832 
10833 /* This routine sets socket options. */
10834 /* ARGSUSED */
10835 int
10836 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10837     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10838     void *dummy, cred_t *cr, mblk_t *first_mp)
10839 {
10840 	int		*i1 = (int *)invalp;
10841 	conn_t		*connp = Q_TO_CONN(q);
10842 	int		error = 0;
10843 	boolean_t	checkonly;
10844 	ire_t		*ire;
10845 	boolean_t	found;
10846 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10847 
10848 	switch (optset_context) {
10849 
10850 	case SETFN_OPTCOM_CHECKONLY:
10851 		checkonly = B_TRUE;
10852 		/*
10853 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10854 		 * inlen != 0 implies value supplied and
10855 		 * 	we have to "pretend" to set it.
10856 		 * inlen == 0 implies that there is no
10857 		 * 	value part in T_CHECK request and just validation
10858 		 * done elsewhere should be enough, we just return here.
10859 		 */
10860 		if (inlen == 0) {
10861 			*outlenp = 0;
10862 			return (0);
10863 		}
10864 		break;
10865 	case SETFN_OPTCOM_NEGOTIATE:
10866 	case SETFN_UD_NEGOTIATE:
10867 	case SETFN_CONN_NEGOTIATE:
10868 		checkonly = B_FALSE;
10869 		break;
10870 	default:
10871 		/*
10872 		 * We should never get here
10873 		 */
10874 		*outlenp = 0;
10875 		return (EINVAL);
10876 	}
10877 
10878 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10879 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10880 
10881 	/*
10882 	 * For fixed length options, no sanity check
10883 	 * of passed in length is done. It is assumed *_optcom_req()
10884 	 * routines do the right thing.
10885 	 */
10886 
10887 	switch (level) {
10888 	case SOL_SOCKET:
10889 		/*
10890 		 * conn_lock protects the bitfields, and is used to
10891 		 * set the fields atomically.
10892 		 */
10893 		switch (name) {
10894 		case SO_BROADCAST:
10895 			if (!checkonly) {
10896 				/* TODO: use value someplace? */
10897 				mutex_enter(&connp->conn_lock);
10898 				connp->conn_broadcast = *i1 ? 1 : 0;
10899 				mutex_exit(&connp->conn_lock);
10900 			}
10901 			break;	/* goto sizeof (int) option return */
10902 		case SO_USELOOPBACK:
10903 			if (!checkonly) {
10904 				/* TODO: use value someplace? */
10905 				mutex_enter(&connp->conn_lock);
10906 				connp->conn_loopback = *i1 ? 1 : 0;
10907 				mutex_exit(&connp->conn_lock);
10908 			}
10909 			break;	/* goto sizeof (int) option return */
10910 		case SO_DONTROUTE:
10911 			if (!checkonly) {
10912 				mutex_enter(&connp->conn_lock);
10913 				connp->conn_dontroute = *i1 ? 1 : 0;
10914 				mutex_exit(&connp->conn_lock);
10915 			}
10916 			break;	/* goto sizeof (int) option return */
10917 		case SO_REUSEADDR:
10918 			if (!checkonly) {
10919 				mutex_enter(&connp->conn_lock);
10920 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10921 				mutex_exit(&connp->conn_lock);
10922 			}
10923 			break;	/* goto sizeof (int) option return */
10924 		case SO_PROTOTYPE:
10925 			if (!checkonly) {
10926 				mutex_enter(&connp->conn_lock);
10927 				connp->conn_proto = *i1;
10928 				mutex_exit(&connp->conn_lock);
10929 			}
10930 			break;	/* goto sizeof (int) option return */
10931 		case SO_ALLZONES:
10932 			if (!checkonly) {
10933 				mutex_enter(&connp->conn_lock);
10934 				if (IPCL_IS_BOUND(connp)) {
10935 					mutex_exit(&connp->conn_lock);
10936 					return (EINVAL);
10937 				}
10938 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10939 				mutex_exit(&connp->conn_lock);
10940 			}
10941 			break;	/* goto sizeof (int) option return */
10942 		case SO_ANON_MLP:
10943 			if (!checkonly) {
10944 				mutex_enter(&connp->conn_lock);
10945 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10946 				mutex_exit(&connp->conn_lock);
10947 			}
10948 			break;	/* goto sizeof (int) option return */
10949 		case SO_MAC_EXEMPT:
10950 			if (secpolicy_net_mac_aware(cr) != 0 ||
10951 			    IPCL_IS_BOUND(connp))
10952 				return (EACCES);
10953 			if (!checkonly) {
10954 				mutex_enter(&connp->conn_lock);
10955 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10956 				mutex_exit(&connp->conn_lock);
10957 			}
10958 			break;	/* goto sizeof (int) option return */
10959 		default:
10960 			/*
10961 			 * "soft" error (negative)
10962 			 * option not handled at this level
10963 			 * Note: Do not modify *outlenp
10964 			 */
10965 			return (-EINVAL);
10966 		}
10967 		break;
10968 	case IPPROTO_IP:
10969 		switch (name) {
10970 		case IP_NEXTHOP:
10971 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10972 				return (EPERM);
10973 			/* FALLTHRU */
10974 		case IP_MULTICAST_IF:
10975 		case IP_DONTFAILOVER_IF: {
10976 			ipaddr_t addr = *i1;
10977 
10978 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10979 			    first_mp);
10980 			if (error != 0)
10981 				return (error);
10982 			break;	/* goto sizeof (int) option return */
10983 		}
10984 
10985 		case IP_MULTICAST_TTL:
10986 			/* Recorded in transport above IP */
10987 			*outvalp = *invalp;
10988 			*outlenp = sizeof (uchar_t);
10989 			return (0);
10990 		case IP_MULTICAST_LOOP:
10991 			if (!checkonly) {
10992 				mutex_enter(&connp->conn_lock);
10993 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10994 				mutex_exit(&connp->conn_lock);
10995 			}
10996 			*outvalp = *invalp;
10997 			*outlenp = sizeof (uchar_t);
10998 			return (0);
10999 		case IP_ADD_MEMBERSHIP:
11000 		case MCAST_JOIN_GROUP:
11001 		case IP_DROP_MEMBERSHIP:
11002 		case MCAST_LEAVE_GROUP: {
11003 			struct ip_mreq *mreqp;
11004 			struct group_req *greqp;
11005 			ire_t *ire;
11006 			boolean_t done = B_FALSE;
11007 			ipaddr_t group, ifaddr;
11008 			struct sockaddr_in *sin;
11009 			uint32_t *ifindexp;
11010 			boolean_t mcast_opt = B_TRUE;
11011 			mcast_record_t fmode;
11012 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11013 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11014 
11015 			switch (name) {
11016 			case IP_ADD_MEMBERSHIP:
11017 				mcast_opt = B_FALSE;
11018 				/* FALLTHRU */
11019 			case MCAST_JOIN_GROUP:
11020 				fmode = MODE_IS_EXCLUDE;
11021 				optfn = ip_opt_add_group;
11022 				break;
11023 
11024 			case IP_DROP_MEMBERSHIP:
11025 				mcast_opt = B_FALSE;
11026 				/* FALLTHRU */
11027 			case MCAST_LEAVE_GROUP:
11028 				fmode = MODE_IS_INCLUDE;
11029 				optfn = ip_opt_delete_group;
11030 				break;
11031 			}
11032 
11033 			if (mcast_opt) {
11034 				greqp = (struct group_req *)i1;
11035 				sin = (struct sockaddr_in *)&greqp->gr_group;
11036 				if (sin->sin_family != AF_INET) {
11037 					*outlenp = 0;
11038 					return (ENOPROTOOPT);
11039 				}
11040 				group = (ipaddr_t)sin->sin_addr.s_addr;
11041 				ifaddr = INADDR_ANY;
11042 				ifindexp = &greqp->gr_interface;
11043 			} else {
11044 				mreqp = (struct ip_mreq *)i1;
11045 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
11046 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
11047 				ifindexp = NULL;
11048 			}
11049 
11050 			/*
11051 			 * In the multirouting case, we need to replicate
11052 			 * the request on all interfaces that will take part
11053 			 * in replication.  We do so because multirouting is
11054 			 * reflective, thus we will probably receive multi-
11055 			 * casts on those interfaces.
11056 			 * The ip_multirt_apply_membership() succeeds if the
11057 			 * operation succeeds on at least one interface.
11058 			 */
11059 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
11060 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11061 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11062 			if (ire != NULL) {
11063 				if (ire->ire_flags & RTF_MULTIRT) {
11064 					error = ip_multirt_apply_membership(
11065 					    optfn, ire, connp, checkonly, group,
11066 					    fmode, INADDR_ANY, first_mp);
11067 					done = B_TRUE;
11068 				}
11069 				ire_refrele(ire);
11070 			}
11071 			if (!done) {
11072 				error = optfn(connp, checkonly, group, ifaddr,
11073 				    ifindexp, fmode, INADDR_ANY, first_mp);
11074 			}
11075 			if (error) {
11076 				/*
11077 				 * EINPROGRESS is a soft error, needs retry
11078 				 * so don't make *outlenp zero.
11079 				 */
11080 				if (error != EINPROGRESS)
11081 					*outlenp = 0;
11082 				return (error);
11083 			}
11084 			/* OK return - copy input buffer into output buffer */
11085 			if (invalp != outvalp) {
11086 				/* don't trust bcopy for identical src/dst */
11087 				bcopy(invalp, outvalp, inlen);
11088 			}
11089 			*outlenp = inlen;
11090 			return (0);
11091 		}
11092 		case IP_BLOCK_SOURCE:
11093 		case IP_UNBLOCK_SOURCE:
11094 		case IP_ADD_SOURCE_MEMBERSHIP:
11095 		case IP_DROP_SOURCE_MEMBERSHIP:
11096 		case MCAST_BLOCK_SOURCE:
11097 		case MCAST_UNBLOCK_SOURCE:
11098 		case MCAST_JOIN_SOURCE_GROUP:
11099 		case MCAST_LEAVE_SOURCE_GROUP: {
11100 			struct ip_mreq_source *imreqp;
11101 			struct group_source_req *gsreqp;
11102 			in_addr_t grp, src, ifaddr = INADDR_ANY;
11103 			uint32_t ifindex = 0;
11104 			mcast_record_t fmode;
11105 			struct sockaddr_in *sin;
11106 			ire_t *ire;
11107 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
11108 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
11109 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
11110 
11111 			switch (name) {
11112 			case IP_BLOCK_SOURCE:
11113 				mcast_opt = B_FALSE;
11114 				/* FALLTHRU */
11115 			case MCAST_BLOCK_SOURCE:
11116 				fmode = MODE_IS_EXCLUDE;
11117 				optfn = ip_opt_add_group;
11118 				break;
11119 
11120 			case IP_UNBLOCK_SOURCE:
11121 				mcast_opt = B_FALSE;
11122 				/* FALLTHRU */
11123 			case MCAST_UNBLOCK_SOURCE:
11124 				fmode = MODE_IS_EXCLUDE;
11125 				optfn = ip_opt_delete_group;
11126 				break;
11127 
11128 			case IP_ADD_SOURCE_MEMBERSHIP:
11129 				mcast_opt = B_FALSE;
11130 				/* FALLTHRU */
11131 			case MCAST_JOIN_SOURCE_GROUP:
11132 				fmode = MODE_IS_INCLUDE;
11133 				optfn = ip_opt_add_group;
11134 				break;
11135 
11136 			case IP_DROP_SOURCE_MEMBERSHIP:
11137 				mcast_opt = B_FALSE;
11138 				/* FALLTHRU */
11139 			case MCAST_LEAVE_SOURCE_GROUP:
11140 				fmode = MODE_IS_INCLUDE;
11141 				optfn = ip_opt_delete_group;
11142 				break;
11143 			}
11144 
11145 			if (mcast_opt) {
11146 				gsreqp = (struct group_source_req *)i1;
11147 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11148 					*outlenp = 0;
11149 					return (ENOPROTOOPT);
11150 				}
11151 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11152 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11153 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11154 				src = (ipaddr_t)sin->sin_addr.s_addr;
11155 				ifindex = gsreqp->gsr_interface;
11156 			} else {
11157 				imreqp = (struct ip_mreq_source *)i1;
11158 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11159 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11160 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11161 			}
11162 
11163 			/*
11164 			 * In the multirouting case, we need to replicate
11165 			 * the request as noted in the mcast cases above.
11166 			 */
11167 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11168 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11169 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11170 			if (ire != NULL) {
11171 				if (ire->ire_flags & RTF_MULTIRT) {
11172 					error = ip_multirt_apply_membership(
11173 					    optfn, ire, connp, checkonly, grp,
11174 					    fmode, src, first_mp);
11175 					done = B_TRUE;
11176 				}
11177 				ire_refrele(ire);
11178 			}
11179 			if (!done) {
11180 				error = optfn(connp, checkonly, grp, ifaddr,
11181 				    &ifindex, fmode, src, first_mp);
11182 			}
11183 			if (error != 0) {
11184 				/*
11185 				 * EINPROGRESS is a soft error, needs retry
11186 				 * so don't make *outlenp zero.
11187 				 */
11188 				if (error != EINPROGRESS)
11189 					*outlenp = 0;
11190 				return (error);
11191 			}
11192 			/* OK return - copy input buffer into output buffer */
11193 			if (invalp != outvalp) {
11194 				bcopy(invalp, outvalp, inlen);
11195 			}
11196 			*outlenp = inlen;
11197 			return (0);
11198 		}
11199 		case IP_SEC_OPT:
11200 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11201 			if (error != 0) {
11202 				*outlenp = 0;
11203 				return (error);
11204 			}
11205 			break;
11206 		case IP_HDRINCL:
11207 		case IP_OPTIONS:
11208 		case T_IP_OPTIONS:
11209 		case IP_TOS:
11210 		case T_IP_TOS:
11211 		case IP_TTL:
11212 		case IP_RECVDSTADDR:
11213 		case IP_RECVOPTS:
11214 			/* OK return - copy input buffer into output buffer */
11215 			if (invalp != outvalp) {
11216 				/* don't trust bcopy for identical src/dst */
11217 				bcopy(invalp, outvalp, inlen);
11218 			}
11219 			*outlenp = inlen;
11220 			return (0);
11221 		case IP_RECVIF:
11222 			/* Retrieve the inbound interface index */
11223 			if (!checkonly) {
11224 				mutex_enter(&connp->conn_lock);
11225 				connp->conn_recvif = *i1 ? 1 : 0;
11226 				mutex_exit(&connp->conn_lock);
11227 			}
11228 			break;	/* goto sizeof (int) option return */
11229 		case IP_RECVPKTINFO:
11230 			if (!checkonly) {
11231 				mutex_enter(&connp->conn_lock);
11232 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11233 				mutex_exit(&connp->conn_lock);
11234 			}
11235 			break;	/* goto sizeof (int) option return */
11236 		case IP_RECVSLLA:
11237 			/* Retrieve the source link layer address */
11238 			if (!checkonly) {
11239 				mutex_enter(&connp->conn_lock);
11240 				connp->conn_recvslla = *i1 ? 1 : 0;
11241 				mutex_exit(&connp->conn_lock);
11242 			}
11243 			break;	/* goto sizeof (int) option return */
11244 		case MRT_INIT:
11245 		case MRT_DONE:
11246 		case MRT_ADD_VIF:
11247 		case MRT_DEL_VIF:
11248 		case MRT_ADD_MFC:
11249 		case MRT_DEL_MFC:
11250 		case MRT_ASSERT:
11251 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11252 				*outlenp = 0;
11253 				return (error);
11254 			}
11255 			error = ip_mrouter_set((int)name, q, checkonly,
11256 			    (uchar_t *)invalp, inlen, first_mp);
11257 			if (error) {
11258 				*outlenp = 0;
11259 				return (error);
11260 			}
11261 			/* OK return - copy input buffer into output buffer */
11262 			if (invalp != outvalp) {
11263 				/* don't trust bcopy for identical src/dst */
11264 				bcopy(invalp, outvalp, inlen);
11265 			}
11266 			*outlenp = inlen;
11267 			return (0);
11268 		case IP_BOUND_IF:
11269 		case IP_XMIT_IF:
11270 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11271 			    level, name, first_mp);
11272 			if (error != 0)
11273 				return (error);
11274 			break; 		/* goto sizeof (int) option return */
11275 
11276 		case IP_UNSPEC_SRC:
11277 			/* Allow sending with a zero source address */
11278 			if (!checkonly) {
11279 				mutex_enter(&connp->conn_lock);
11280 				connp->conn_unspec_src = *i1 ? 1 : 0;
11281 				mutex_exit(&connp->conn_lock);
11282 			}
11283 			break;	/* goto sizeof (int) option return */
11284 		default:
11285 			/*
11286 			 * "soft" error (negative)
11287 			 * option not handled at this level
11288 			 * Note: Do not modify *outlenp
11289 			 */
11290 			return (-EINVAL);
11291 		}
11292 		break;
11293 	case IPPROTO_IPV6:
11294 		switch (name) {
11295 		case IPV6_BOUND_IF:
11296 		case IPV6_BOUND_PIF:
11297 		case IPV6_DONTFAILOVER_IF:
11298 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11299 			    level, name, first_mp);
11300 			if (error != 0)
11301 				return (error);
11302 			break; 		/* goto sizeof (int) option return */
11303 
11304 		case IPV6_MULTICAST_IF:
11305 			/*
11306 			 * The only possible errors are EINPROGRESS and
11307 			 * EINVAL. EINPROGRESS will be restarted and is not
11308 			 * a hard error. We call this option on both V4 and V6
11309 			 * If both return EINVAL, then this call returns
11310 			 * EINVAL. If at least one of them succeeds we
11311 			 * return success.
11312 			 */
11313 			found = B_FALSE;
11314 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11315 			    level, name, first_mp);
11316 			if (error == EINPROGRESS)
11317 				return (error);
11318 			if (error == 0)
11319 				found = B_TRUE;
11320 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11321 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11322 			if (error == 0)
11323 				found = B_TRUE;
11324 			if (!found)
11325 				return (error);
11326 			break; 		/* goto sizeof (int) option return */
11327 
11328 		case IPV6_MULTICAST_HOPS:
11329 			/* Recorded in transport above IP */
11330 			break;	/* goto sizeof (int) option return */
11331 		case IPV6_MULTICAST_LOOP:
11332 			if (!checkonly) {
11333 				mutex_enter(&connp->conn_lock);
11334 				connp->conn_multicast_loop = *i1;
11335 				mutex_exit(&connp->conn_lock);
11336 			}
11337 			break;	/* goto sizeof (int) option return */
11338 		case IPV6_JOIN_GROUP:
11339 		case MCAST_JOIN_GROUP:
11340 		case IPV6_LEAVE_GROUP:
11341 		case MCAST_LEAVE_GROUP: {
11342 			struct ipv6_mreq *ip_mreqp;
11343 			struct group_req *greqp;
11344 			ire_t *ire;
11345 			boolean_t done = B_FALSE;
11346 			in6_addr_t groupv6;
11347 			uint32_t ifindex;
11348 			boolean_t mcast_opt = B_TRUE;
11349 			mcast_record_t fmode;
11350 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11351 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11352 
11353 			switch (name) {
11354 			case IPV6_JOIN_GROUP:
11355 				mcast_opt = B_FALSE;
11356 				/* FALLTHRU */
11357 			case MCAST_JOIN_GROUP:
11358 				fmode = MODE_IS_EXCLUDE;
11359 				optfn = ip_opt_add_group_v6;
11360 				break;
11361 
11362 			case IPV6_LEAVE_GROUP:
11363 				mcast_opt = B_FALSE;
11364 				/* FALLTHRU */
11365 			case MCAST_LEAVE_GROUP:
11366 				fmode = MODE_IS_INCLUDE;
11367 				optfn = ip_opt_delete_group_v6;
11368 				break;
11369 			}
11370 
11371 			if (mcast_opt) {
11372 				struct sockaddr_in *sin;
11373 				struct sockaddr_in6 *sin6;
11374 				greqp = (struct group_req *)i1;
11375 				if (greqp->gr_group.ss_family == AF_INET) {
11376 					sin = (struct sockaddr_in *)
11377 					    &(greqp->gr_group);
11378 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11379 					    &groupv6);
11380 				} else {
11381 					sin6 = (struct sockaddr_in6 *)
11382 					    &(greqp->gr_group);
11383 					groupv6 = sin6->sin6_addr;
11384 				}
11385 				ifindex = greqp->gr_interface;
11386 			} else {
11387 				ip_mreqp = (struct ipv6_mreq *)i1;
11388 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11389 				ifindex = ip_mreqp->ipv6mr_interface;
11390 			}
11391 			/*
11392 			 * In the multirouting case, we need to replicate
11393 			 * the request on all interfaces that will take part
11394 			 * in replication.  We do so because multirouting is
11395 			 * reflective, thus we will probably receive multi-
11396 			 * casts on those interfaces.
11397 			 * The ip_multirt_apply_membership_v6() succeeds if
11398 			 * the operation succeeds on at least one interface.
11399 			 */
11400 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11401 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11402 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11403 			if (ire != NULL) {
11404 				if (ire->ire_flags & RTF_MULTIRT) {
11405 					error = ip_multirt_apply_membership_v6(
11406 					    optfn, ire, connp, checkonly,
11407 					    &groupv6, fmode, &ipv6_all_zeros,
11408 					    first_mp);
11409 					done = B_TRUE;
11410 				}
11411 				ire_refrele(ire);
11412 			}
11413 			if (!done) {
11414 				error = optfn(connp, checkonly, &groupv6,
11415 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11416 			}
11417 			if (error) {
11418 				/*
11419 				 * EINPROGRESS is a soft error, needs retry
11420 				 * so don't make *outlenp zero.
11421 				 */
11422 				if (error != EINPROGRESS)
11423 					*outlenp = 0;
11424 				return (error);
11425 			}
11426 			/* OK return - copy input buffer into output buffer */
11427 			if (invalp != outvalp) {
11428 				/* don't trust bcopy for identical src/dst */
11429 				bcopy(invalp, outvalp, inlen);
11430 			}
11431 			*outlenp = inlen;
11432 			return (0);
11433 		}
11434 		case MCAST_BLOCK_SOURCE:
11435 		case MCAST_UNBLOCK_SOURCE:
11436 		case MCAST_JOIN_SOURCE_GROUP:
11437 		case MCAST_LEAVE_SOURCE_GROUP: {
11438 			struct group_source_req *gsreqp;
11439 			in6_addr_t v6grp, v6src;
11440 			uint32_t ifindex;
11441 			mcast_record_t fmode;
11442 			ire_t *ire;
11443 			boolean_t done = B_FALSE;
11444 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11445 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11446 
11447 			switch (name) {
11448 			case MCAST_BLOCK_SOURCE:
11449 				fmode = MODE_IS_EXCLUDE;
11450 				optfn = ip_opt_add_group_v6;
11451 				break;
11452 			case MCAST_UNBLOCK_SOURCE:
11453 				fmode = MODE_IS_EXCLUDE;
11454 				optfn = ip_opt_delete_group_v6;
11455 				break;
11456 			case MCAST_JOIN_SOURCE_GROUP:
11457 				fmode = MODE_IS_INCLUDE;
11458 				optfn = ip_opt_add_group_v6;
11459 				break;
11460 			case MCAST_LEAVE_SOURCE_GROUP:
11461 				fmode = MODE_IS_INCLUDE;
11462 				optfn = ip_opt_delete_group_v6;
11463 				break;
11464 			}
11465 
11466 			gsreqp = (struct group_source_req *)i1;
11467 			ifindex = gsreqp->gsr_interface;
11468 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11469 				struct sockaddr_in *s;
11470 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11471 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11472 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11473 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11474 			} else {
11475 				struct sockaddr_in6 *s6;
11476 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11477 				v6grp = s6->sin6_addr;
11478 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11479 				v6src = s6->sin6_addr;
11480 			}
11481 
11482 			/*
11483 			 * In the multirouting case, we need to replicate
11484 			 * the request as noted in the mcast cases above.
11485 			 */
11486 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11487 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11488 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11489 			if (ire != NULL) {
11490 				if (ire->ire_flags & RTF_MULTIRT) {
11491 					error = ip_multirt_apply_membership_v6(
11492 					    optfn, ire, connp, checkonly,
11493 					    &v6grp, fmode, &v6src, first_mp);
11494 					done = B_TRUE;
11495 				}
11496 				ire_refrele(ire);
11497 			}
11498 			if (!done) {
11499 				error = optfn(connp, checkonly, &v6grp,
11500 				    ifindex, fmode, &v6src, first_mp);
11501 			}
11502 			if (error != 0) {
11503 				/*
11504 				 * EINPROGRESS is a soft error, needs retry
11505 				 * so don't make *outlenp zero.
11506 				 */
11507 				if (error != EINPROGRESS)
11508 					*outlenp = 0;
11509 				return (error);
11510 			}
11511 			/* OK return - copy input buffer into output buffer */
11512 			if (invalp != outvalp) {
11513 				bcopy(invalp, outvalp, inlen);
11514 			}
11515 			*outlenp = inlen;
11516 			return (0);
11517 		}
11518 		case IPV6_UNICAST_HOPS:
11519 			/* Recorded in transport above IP */
11520 			break;	/* goto sizeof (int) option return */
11521 		case IPV6_UNSPEC_SRC:
11522 			/* Allow sending with a zero source address */
11523 			if (!checkonly) {
11524 				mutex_enter(&connp->conn_lock);
11525 				connp->conn_unspec_src = *i1 ? 1 : 0;
11526 				mutex_exit(&connp->conn_lock);
11527 			}
11528 			break;	/* goto sizeof (int) option return */
11529 		case IPV6_RECVPKTINFO:
11530 			if (!checkonly) {
11531 				mutex_enter(&connp->conn_lock);
11532 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11533 				mutex_exit(&connp->conn_lock);
11534 			}
11535 			break;	/* goto sizeof (int) option return */
11536 		case IPV6_RECVTCLASS:
11537 			if (!checkonly) {
11538 				if (*i1 < 0 || *i1 > 1) {
11539 					return (EINVAL);
11540 				}
11541 				mutex_enter(&connp->conn_lock);
11542 				connp->conn_ipv6_recvtclass = *i1;
11543 				mutex_exit(&connp->conn_lock);
11544 			}
11545 			break;
11546 		case IPV6_RECVPATHMTU:
11547 			if (!checkonly) {
11548 				if (*i1 < 0 || *i1 > 1) {
11549 					return (EINVAL);
11550 				}
11551 				mutex_enter(&connp->conn_lock);
11552 				connp->conn_ipv6_recvpathmtu = *i1;
11553 				mutex_exit(&connp->conn_lock);
11554 			}
11555 			break;
11556 		case IPV6_RECVHOPLIMIT:
11557 			if (!checkonly) {
11558 				mutex_enter(&connp->conn_lock);
11559 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11560 				mutex_exit(&connp->conn_lock);
11561 			}
11562 			break;	/* goto sizeof (int) option return */
11563 		case IPV6_RECVHOPOPTS:
11564 			if (!checkonly) {
11565 				mutex_enter(&connp->conn_lock);
11566 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11567 				mutex_exit(&connp->conn_lock);
11568 			}
11569 			break;	/* goto sizeof (int) option return */
11570 		case IPV6_RECVDSTOPTS:
11571 			if (!checkonly) {
11572 				mutex_enter(&connp->conn_lock);
11573 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11574 				mutex_exit(&connp->conn_lock);
11575 			}
11576 			break;	/* goto sizeof (int) option return */
11577 		case IPV6_RECVRTHDR:
11578 			if (!checkonly) {
11579 				mutex_enter(&connp->conn_lock);
11580 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11581 				mutex_exit(&connp->conn_lock);
11582 			}
11583 			break;	/* goto sizeof (int) option return */
11584 		case IPV6_RECVRTHDRDSTOPTS:
11585 			if (!checkonly) {
11586 				mutex_enter(&connp->conn_lock);
11587 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11588 				mutex_exit(&connp->conn_lock);
11589 			}
11590 			break;	/* goto sizeof (int) option return */
11591 		case IPV6_PKTINFO:
11592 			if (inlen == 0)
11593 				return (-EINVAL);	/* clearing option */
11594 			error = ip6_set_pktinfo(cr, connp,
11595 			    (struct in6_pktinfo *)invalp, first_mp);
11596 			if (error != 0)
11597 				*outlenp = 0;
11598 			else
11599 				*outlenp = inlen;
11600 			return (error);
11601 		case IPV6_NEXTHOP: {
11602 			struct sockaddr_in6 *sin6;
11603 
11604 			/* Verify that the nexthop is reachable */
11605 			if (inlen == 0)
11606 				return (-EINVAL);	/* clearing option */
11607 
11608 			sin6 = (struct sockaddr_in6 *)invalp;
11609 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11610 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11611 			    NULL, MATCH_IRE_DEFAULT, ipst);
11612 
11613 			if (ire == NULL) {
11614 				*outlenp = 0;
11615 				return (EHOSTUNREACH);
11616 			}
11617 			ire_refrele(ire);
11618 			return (-EINVAL);
11619 		}
11620 		case IPV6_SEC_OPT:
11621 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11622 			if (error != 0) {
11623 				*outlenp = 0;
11624 				return (error);
11625 			}
11626 			break;
11627 		case IPV6_SRC_PREFERENCES: {
11628 			/*
11629 			 * This is implemented strictly in the ip module
11630 			 * (here and in tcp_opt_*() to accomodate tcp
11631 			 * sockets).  Modules above ip pass this option
11632 			 * down here since ip is the only one that needs to
11633 			 * be aware of source address preferences.
11634 			 *
11635 			 * This socket option only affects connected
11636 			 * sockets that haven't already bound to a specific
11637 			 * IPv6 address.  In other words, sockets that
11638 			 * don't call bind() with an address other than the
11639 			 * unspecified address and that call connect().
11640 			 * ip_bind_connected_v6() passes these preferences
11641 			 * to the ipif_select_source_v6() function.
11642 			 */
11643 			if (inlen != sizeof (uint32_t))
11644 				return (EINVAL);
11645 			error = ip6_set_src_preferences(connp,
11646 			    *(uint32_t *)invalp);
11647 			if (error != 0) {
11648 				*outlenp = 0;
11649 				return (error);
11650 			} else {
11651 				*outlenp = sizeof (uint32_t);
11652 			}
11653 			break;
11654 		}
11655 		case IPV6_V6ONLY:
11656 			if (*i1 < 0 || *i1 > 1) {
11657 				return (EINVAL);
11658 			}
11659 			mutex_enter(&connp->conn_lock);
11660 			connp->conn_ipv6_v6only = *i1;
11661 			mutex_exit(&connp->conn_lock);
11662 			break;
11663 		default:
11664 			return (-EINVAL);
11665 		}
11666 		break;
11667 	default:
11668 		/*
11669 		 * "soft" error (negative)
11670 		 * option not handled at this level
11671 		 * Note: Do not modify *outlenp
11672 		 */
11673 		return (-EINVAL);
11674 	}
11675 	/*
11676 	 * Common case of return from an option that is sizeof (int)
11677 	 */
11678 	*(int *)outvalp = *i1;
11679 	*outlenp = sizeof (int);
11680 	return (0);
11681 }
11682 
11683 /*
11684  * This routine gets default values of certain options whose default
11685  * values are maintained by protocol specific code
11686  */
11687 /* ARGSUSED */
11688 int
11689 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11690 {
11691 	int *i1 = (int *)ptr;
11692 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11693 
11694 	switch (level) {
11695 	case IPPROTO_IP:
11696 		switch (name) {
11697 		case IP_MULTICAST_TTL:
11698 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11699 			return (sizeof (uchar_t));
11700 		case IP_MULTICAST_LOOP:
11701 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11702 			return (sizeof (uchar_t));
11703 		default:
11704 			return (-1);
11705 		}
11706 	case IPPROTO_IPV6:
11707 		switch (name) {
11708 		case IPV6_UNICAST_HOPS:
11709 			*i1 = ipst->ips_ipv6_def_hops;
11710 			return (sizeof (int));
11711 		case IPV6_MULTICAST_HOPS:
11712 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11713 			return (sizeof (int));
11714 		case IPV6_MULTICAST_LOOP:
11715 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11716 			return (sizeof (int));
11717 		case IPV6_V6ONLY:
11718 			*i1 = 1;
11719 			return (sizeof (int));
11720 		default:
11721 			return (-1);
11722 		}
11723 	default:
11724 		return (-1);
11725 	}
11726 	/* NOTREACHED */
11727 }
11728 
11729 /*
11730  * Given a destination address and a pointer to where to put the information
11731  * this routine fills in the mtuinfo.
11732  */
11733 int
11734 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11735     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11736 {
11737 	ire_t *ire;
11738 	ip_stack_t	*ipst = ns->netstack_ip;
11739 
11740 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11741 		return (-1);
11742 
11743 	bzero(mtuinfo, sizeof (*mtuinfo));
11744 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11745 	mtuinfo->ip6m_addr.sin6_port = port;
11746 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11747 
11748 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11749 	if (ire != NULL) {
11750 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11751 		ire_refrele(ire);
11752 	} else {
11753 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11754 	}
11755 	return (sizeof (struct ip6_mtuinfo));
11756 }
11757 
11758 /*
11759  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11760  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11761  * isn't.  This doesn't matter as the error checking is done properly for the
11762  * other MRT options coming in through ip_opt_set.
11763  */
11764 int
11765 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11766 {
11767 	conn_t		*connp = Q_TO_CONN(q);
11768 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11769 
11770 	switch (level) {
11771 	case IPPROTO_IP:
11772 		switch (name) {
11773 		case MRT_VERSION:
11774 		case MRT_ASSERT:
11775 			(void) ip_mrouter_get(name, q, ptr);
11776 			return (sizeof (int));
11777 		case IP_SEC_OPT:
11778 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11779 		case IP_NEXTHOP:
11780 			if (connp->conn_nexthop_set) {
11781 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11782 				return (sizeof (ipaddr_t));
11783 			} else
11784 				return (0);
11785 		case IP_RECVPKTINFO:
11786 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11787 			return (sizeof (int));
11788 		default:
11789 			break;
11790 		}
11791 		break;
11792 	case IPPROTO_IPV6:
11793 		switch (name) {
11794 		case IPV6_SEC_OPT:
11795 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11796 		case IPV6_SRC_PREFERENCES: {
11797 			return (ip6_get_src_preferences(connp,
11798 			    (uint32_t *)ptr));
11799 		}
11800 		case IPV6_V6ONLY:
11801 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11802 			return (sizeof (int));
11803 		case IPV6_PATHMTU:
11804 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11805 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11806 		default:
11807 			break;
11808 		}
11809 		break;
11810 	default:
11811 		break;
11812 	}
11813 	return (-1);
11814 }
11815 
11816 /* Named Dispatch routine to get a current value out of our parameter table. */
11817 /* ARGSUSED */
11818 static int
11819 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11820 {
11821 	ipparam_t *ippa = (ipparam_t *)cp;
11822 
11823 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11824 	return (0);
11825 }
11826 
11827 /* ARGSUSED */
11828 static int
11829 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11830 {
11831 
11832 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11833 	return (0);
11834 }
11835 
11836 /*
11837  * Set ip{,6}_forwarding values.  This means walking through all of the
11838  * ill's and toggling their forwarding values.
11839  */
11840 /* ARGSUSED */
11841 static int
11842 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11843 {
11844 	long new_value;
11845 	int *forwarding_value = (int *)cp;
11846 	ill_t *ill;
11847 	boolean_t isv6;
11848 	ill_walk_context_t ctx;
11849 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11850 
11851 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11852 
11853 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11854 	    new_value < 0 || new_value > 1) {
11855 		return (EINVAL);
11856 	}
11857 
11858 	*forwarding_value = new_value;
11859 
11860 	/*
11861 	 * Regardless of the current value of ip_forwarding, set all per-ill
11862 	 * values of ip_forwarding to the value being set.
11863 	 *
11864 	 * Bring all the ill's up to date with the new global value.
11865 	 */
11866 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11867 
11868 	if (isv6)
11869 		ill = ILL_START_WALK_V6(&ctx, ipst);
11870 	else
11871 		ill = ILL_START_WALK_V4(&ctx, ipst);
11872 
11873 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11874 		(void) ill_forward_set(ill, new_value != 0);
11875 
11876 	rw_exit(&ipst->ips_ill_g_lock);
11877 	return (0);
11878 }
11879 
11880 /*
11881  * Walk through the param array specified registering each element with the
11882  * Named Dispatch handler. This is called only during init. So it is ok
11883  * not to acquire any locks
11884  */
11885 static boolean_t
11886 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11887     ipndp_t *ipnd, size_t ipnd_cnt)
11888 {
11889 	for (; ippa_cnt-- > 0; ippa++) {
11890 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11891 			if (!nd_load(ndp, ippa->ip_param_name,
11892 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11893 				nd_free(ndp);
11894 				return (B_FALSE);
11895 			}
11896 		}
11897 	}
11898 
11899 	for (; ipnd_cnt-- > 0; ipnd++) {
11900 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11901 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11902 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11903 			    ipnd->ip_ndp_data)) {
11904 				nd_free(ndp);
11905 				return (B_FALSE);
11906 			}
11907 		}
11908 	}
11909 
11910 	return (B_TRUE);
11911 }
11912 
11913 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11914 /* ARGSUSED */
11915 static int
11916 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11917 {
11918 	long		new_value;
11919 	ipparam_t	*ippa = (ipparam_t *)cp;
11920 
11921 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11922 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11923 		return (EINVAL);
11924 	}
11925 	ippa->ip_param_value = new_value;
11926 	return (0);
11927 }
11928 
11929 /*
11930  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11931  * When an ipf is passed here for the first time, if
11932  * we already have in-order fragments on the queue, we convert from the fast-
11933  * path reassembly scheme to the hard-case scheme.  From then on, additional
11934  * fragments are reassembled here.  We keep track of the start and end offsets
11935  * of each piece, and the number of holes in the chain.  When the hole count
11936  * goes to zero, we are done!
11937  *
11938  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11939  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11940  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11941  * after the call to ip_reassemble().
11942  */
11943 int
11944 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11945     size_t msg_len)
11946 {
11947 	uint_t	end;
11948 	mblk_t	*next_mp;
11949 	mblk_t	*mp1;
11950 	uint_t	offset;
11951 	boolean_t incr_dups = B_TRUE;
11952 	boolean_t offset_zero_seen = B_FALSE;
11953 	boolean_t pkt_boundary_checked = B_FALSE;
11954 
11955 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11956 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11957 
11958 	/* Add in byte count */
11959 	ipf->ipf_count += msg_len;
11960 	if (ipf->ipf_end) {
11961 		/*
11962 		 * We were part way through in-order reassembly, but now there
11963 		 * is a hole.  We walk through messages already queued, and
11964 		 * mark them for hard case reassembly.  We know that up till
11965 		 * now they were in order starting from offset zero.
11966 		 */
11967 		offset = 0;
11968 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11969 			IP_REASS_SET_START(mp1, offset);
11970 			if (offset == 0) {
11971 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11972 				offset = -ipf->ipf_nf_hdr_len;
11973 			}
11974 			offset += mp1->b_wptr - mp1->b_rptr;
11975 			IP_REASS_SET_END(mp1, offset);
11976 		}
11977 		/* One hole at the end. */
11978 		ipf->ipf_hole_cnt = 1;
11979 		/* Brand it as a hard case, forever. */
11980 		ipf->ipf_end = 0;
11981 	}
11982 	/* Walk through all the new pieces. */
11983 	do {
11984 		end = start + (mp->b_wptr - mp->b_rptr);
11985 		/*
11986 		 * If start is 0, decrease 'end' only for the first mblk of
11987 		 * the fragment. Otherwise 'end' can get wrong value in the
11988 		 * second pass of the loop if first mblk is exactly the
11989 		 * size of ipf_nf_hdr_len.
11990 		 */
11991 		if (start == 0 && !offset_zero_seen) {
11992 			/* First segment */
11993 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11994 			end -= ipf->ipf_nf_hdr_len;
11995 			offset_zero_seen = B_TRUE;
11996 		}
11997 		next_mp = mp->b_cont;
11998 		/*
11999 		 * We are checking to see if there is any interesing data
12000 		 * to process.  If there isn't and the mblk isn't the
12001 		 * one which carries the unfragmentable header then we
12002 		 * drop it.  It's possible to have just the unfragmentable
12003 		 * header come through without any data.  That needs to be
12004 		 * saved.
12005 		 *
12006 		 * If the assert at the top of this function holds then the
12007 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
12008 		 * is infrequently traveled enough that the test is left in
12009 		 * to protect against future code changes which break that
12010 		 * invariant.
12011 		 */
12012 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
12013 			/* Empty.  Blast it. */
12014 			IP_REASS_SET_START(mp, 0);
12015 			IP_REASS_SET_END(mp, 0);
12016 			/*
12017 			 * If the ipf points to the mblk we are about to free,
12018 			 * update ipf to point to the next mblk (or NULL
12019 			 * if none).
12020 			 */
12021 			if (ipf->ipf_mp->b_cont == mp)
12022 				ipf->ipf_mp->b_cont = next_mp;
12023 			freeb(mp);
12024 			continue;
12025 		}
12026 		mp->b_cont = NULL;
12027 		IP_REASS_SET_START(mp, start);
12028 		IP_REASS_SET_END(mp, end);
12029 		if (!ipf->ipf_tail_mp) {
12030 			ipf->ipf_tail_mp = mp;
12031 			ipf->ipf_mp->b_cont = mp;
12032 			if (start == 0 || !more) {
12033 				ipf->ipf_hole_cnt = 1;
12034 				/*
12035 				 * if the first fragment comes in more than one
12036 				 * mblk, this loop will be executed for each
12037 				 * mblk. Need to adjust hole count so exiting
12038 				 * this routine will leave hole count at 1.
12039 				 */
12040 				if (next_mp)
12041 					ipf->ipf_hole_cnt++;
12042 			} else
12043 				ipf->ipf_hole_cnt = 2;
12044 			continue;
12045 		} else if (ipf->ipf_last_frag_seen && !more &&
12046 		    !pkt_boundary_checked) {
12047 			/*
12048 			 * We check datagram boundary only if this fragment
12049 			 * claims to be the last fragment and we have seen a
12050 			 * last fragment in the past too. We do this only
12051 			 * once for a given fragment.
12052 			 *
12053 			 * start cannot be 0 here as fragments with start=0
12054 			 * and MF=0 gets handled as a complete packet. These
12055 			 * fragments should not reach here.
12056 			 */
12057 
12058 			if (start + msgdsize(mp) !=
12059 			    IP_REASS_END(ipf->ipf_tail_mp)) {
12060 				/*
12061 				 * We have two fragments both of which claim
12062 				 * to be the last fragment but gives conflicting
12063 				 * information about the whole datagram size.
12064 				 * Something fishy is going on. Drop the
12065 				 * fragment and free up the reassembly list.
12066 				 */
12067 				return (IP_REASS_FAILED);
12068 			}
12069 
12070 			/*
12071 			 * We shouldn't come to this code block again for this
12072 			 * particular fragment.
12073 			 */
12074 			pkt_boundary_checked = B_TRUE;
12075 		}
12076 
12077 		/* New stuff at or beyond tail? */
12078 		offset = IP_REASS_END(ipf->ipf_tail_mp);
12079 		if (start >= offset) {
12080 			if (ipf->ipf_last_frag_seen) {
12081 				/* current fragment is beyond last fragment */
12082 				return (IP_REASS_FAILED);
12083 			}
12084 			/* Link it on end. */
12085 			ipf->ipf_tail_mp->b_cont = mp;
12086 			ipf->ipf_tail_mp = mp;
12087 			if (more) {
12088 				if (start != offset)
12089 					ipf->ipf_hole_cnt++;
12090 			} else if (start == offset && next_mp == NULL)
12091 					ipf->ipf_hole_cnt--;
12092 			continue;
12093 		}
12094 		mp1 = ipf->ipf_mp->b_cont;
12095 		offset = IP_REASS_START(mp1);
12096 		/* New stuff at the front? */
12097 		if (start < offset) {
12098 			if (start == 0) {
12099 				if (end >= offset) {
12100 					/* Nailed the hole at the begining. */
12101 					ipf->ipf_hole_cnt--;
12102 				}
12103 			} else if (end < offset) {
12104 				/*
12105 				 * A hole, stuff, and a hole where there used
12106 				 * to be just a hole.
12107 				 */
12108 				ipf->ipf_hole_cnt++;
12109 			}
12110 			mp->b_cont = mp1;
12111 			/* Check for overlap. */
12112 			while (end > offset) {
12113 				if (end < IP_REASS_END(mp1)) {
12114 					mp->b_wptr -= end - offset;
12115 					IP_REASS_SET_END(mp, offset);
12116 					BUMP_MIB(ill->ill_ip_mib,
12117 					    ipIfStatsReasmPartDups);
12118 					break;
12119 				}
12120 				/* Did we cover another hole? */
12121 				if ((mp1->b_cont &&
12122 				    IP_REASS_END(mp1) !=
12123 				    IP_REASS_START(mp1->b_cont) &&
12124 				    end >= IP_REASS_START(mp1->b_cont)) ||
12125 				    (!ipf->ipf_last_frag_seen && !more)) {
12126 					ipf->ipf_hole_cnt--;
12127 				}
12128 				/* Clip out mp1. */
12129 				if ((mp->b_cont = mp1->b_cont) == NULL) {
12130 					/*
12131 					 * After clipping out mp1, this guy
12132 					 * is now hanging off the end.
12133 					 */
12134 					ipf->ipf_tail_mp = mp;
12135 				}
12136 				IP_REASS_SET_START(mp1, 0);
12137 				IP_REASS_SET_END(mp1, 0);
12138 				/* Subtract byte count */
12139 				ipf->ipf_count -= mp1->b_datap->db_lim -
12140 				    mp1->b_datap->db_base;
12141 				freeb(mp1);
12142 				BUMP_MIB(ill->ill_ip_mib,
12143 				    ipIfStatsReasmPartDups);
12144 				mp1 = mp->b_cont;
12145 				if (!mp1)
12146 					break;
12147 				offset = IP_REASS_START(mp1);
12148 			}
12149 			ipf->ipf_mp->b_cont = mp;
12150 			continue;
12151 		}
12152 		/*
12153 		 * The new piece starts somewhere between the start of the head
12154 		 * and before the end of the tail.
12155 		 */
12156 		for (; mp1; mp1 = mp1->b_cont) {
12157 			offset = IP_REASS_END(mp1);
12158 			if (start < offset) {
12159 				if (end <= offset) {
12160 					/* Nothing new. */
12161 					IP_REASS_SET_START(mp, 0);
12162 					IP_REASS_SET_END(mp, 0);
12163 					/* Subtract byte count */
12164 					ipf->ipf_count -= mp->b_datap->db_lim -
12165 					    mp->b_datap->db_base;
12166 					if (incr_dups) {
12167 						ipf->ipf_num_dups++;
12168 						incr_dups = B_FALSE;
12169 					}
12170 					freeb(mp);
12171 					BUMP_MIB(ill->ill_ip_mib,
12172 					    ipIfStatsReasmDuplicates);
12173 					break;
12174 				}
12175 				/*
12176 				 * Trim redundant stuff off beginning of new
12177 				 * piece.
12178 				 */
12179 				IP_REASS_SET_START(mp, offset);
12180 				mp->b_rptr += offset - start;
12181 				BUMP_MIB(ill->ill_ip_mib,
12182 				    ipIfStatsReasmPartDups);
12183 				start = offset;
12184 				if (!mp1->b_cont) {
12185 					/*
12186 					 * After trimming, this guy is now
12187 					 * hanging off the end.
12188 					 */
12189 					mp1->b_cont = mp;
12190 					ipf->ipf_tail_mp = mp;
12191 					if (!more) {
12192 						ipf->ipf_hole_cnt--;
12193 					}
12194 					break;
12195 				}
12196 			}
12197 			if (start >= IP_REASS_START(mp1->b_cont))
12198 				continue;
12199 			/* Fill a hole */
12200 			if (start > offset)
12201 				ipf->ipf_hole_cnt++;
12202 			mp->b_cont = mp1->b_cont;
12203 			mp1->b_cont = mp;
12204 			mp1 = mp->b_cont;
12205 			offset = IP_REASS_START(mp1);
12206 			if (end >= offset) {
12207 				ipf->ipf_hole_cnt--;
12208 				/* Check for overlap. */
12209 				while (end > offset) {
12210 					if (end < IP_REASS_END(mp1)) {
12211 						mp->b_wptr -= end - offset;
12212 						IP_REASS_SET_END(mp, offset);
12213 						/*
12214 						 * TODO we might bump
12215 						 * this up twice if there is
12216 						 * overlap at both ends.
12217 						 */
12218 						BUMP_MIB(ill->ill_ip_mib,
12219 						    ipIfStatsReasmPartDups);
12220 						break;
12221 					}
12222 					/* Did we cover another hole? */
12223 					if ((mp1->b_cont &&
12224 					    IP_REASS_END(mp1)
12225 					    != IP_REASS_START(mp1->b_cont) &&
12226 					    end >=
12227 					    IP_REASS_START(mp1->b_cont)) ||
12228 					    (!ipf->ipf_last_frag_seen &&
12229 					    !more)) {
12230 						ipf->ipf_hole_cnt--;
12231 					}
12232 					/* Clip out mp1. */
12233 					if ((mp->b_cont = mp1->b_cont) ==
12234 					    NULL) {
12235 						/*
12236 						 * After clipping out mp1,
12237 						 * this guy is now hanging
12238 						 * off the end.
12239 						 */
12240 						ipf->ipf_tail_mp = mp;
12241 					}
12242 					IP_REASS_SET_START(mp1, 0);
12243 					IP_REASS_SET_END(mp1, 0);
12244 					/* Subtract byte count */
12245 					ipf->ipf_count -=
12246 					    mp1->b_datap->db_lim -
12247 					    mp1->b_datap->db_base;
12248 					freeb(mp1);
12249 					BUMP_MIB(ill->ill_ip_mib,
12250 					    ipIfStatsReasmPartDups);
12251 					mp1 = mp->b_cont;
12252 					if (!mp1)
12253 						break;
12254 					offset = IP_REASS_START(mp1);
12255 				}
12256 			}
12257 			break;
12258 		}
12259 	} while (start = end, mp = next_mp);
12260 
12261 	/* Fragment just processed could be the last one. Remember this fact */
12262 	if (!more)
12263 		ipf->ipf_last_frag_seen = B_TRUE;
12264 
12265 	/* Still got holes? */
12266 	if (ipf->ipf_hole_cnt)
12267 		return (IP_REASS_PARTIAL);
12268 	/* Clean up overloaded fields to avoid upstream disasters. */
12269 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12270 		IP_REASS_SET_START(mp1, 0);
12271 		IP_REASS_SET_END(mp1, 0);
12272 	}
12273 	return (IP_REASS_COMPLETE);
12274 }
12275 
12276 /*
12277  * ipsec processing for the fast path, used for input UDP Packets
12278  */
12279 static boolean_t
12280 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12281     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
12282 {
12283 	uint32_t	ill_index;
12284 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12285 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12286 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12287 
12288 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12289 	/* The ill_index of the incoming ILL */
12290 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12291 
12292 	/* pass packet up to the transport */
12293 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12294 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12295 		    NULL, mctl_present);
12296 		if (*first_mpp == NULL) {
12297 			return (B_FALSE);
12298 		}
12299 	}
12300 
12301 	/* Initiate IPPF processing for fastpath UDP */
12302 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12303 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12304 		if (*mpp == NULL) {
12305 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12306 			    "deferred/dropped during IPPF processing\n"));
12307 			return (B_FALSE);
12308 		}
12309 	}
12310 	/*
12311 	 * We make the checks as below since we are in the fast path
12312 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12313 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12314 	 */
12315 	if (connp->conn_recvif || connp->conn_recvslla ||
12316 	    connp->conn_ip_recvpktinfo) {
12317 		if (connp->conn_recvif) {
12318 			in_flags = IPF_RECVIF;
12319 		}
12320 		/*
12321 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12322 		 * so the flag passed to ip_add_info is based on IP version
12323 		 * of connp.
12324 		 */
12325 		if (connp->conn_ip_recvpktinfo) {
12326 			if (connp->conn_af_isv6) {
12327 				/*
12328 				 * V6 only needs index
12329 				 */
12330 				in_flags |= IPF_RECVIF;
12331 			} else {
12332 				/*
12333 				 * V4 needs index + matching address.
12334 				 */
12335 				in_flags |= IPF_RECVADDR;
12336 			}
12337 		}
12338 		if (connp->conn_recvslla) {
12339 			in_flags |= IPF_RECVSLLA;
12340 		}
12341 		/*
12342 		 * since in_flags are being set ill will be
12343 		 * referenced in ip_add_info, so it better not
12344 		 * be NULL.
12345 		 */
12346 		/*
12347 		 * the actual data will be contained in b_cont
12348 		 * upon successful return of the following call.
12349 		 * If the call fails then the original mblk is
12350 		 * returned.
12351 		 */
12352 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12353 		    ipst);
12354 	}
12355 
12356 	return (B_TRUE);
12357 }
12358 
12359 /*
12360  * Fragmentation reassembly.  Each ILL has a hash table for
12361  * queuing packets undergoing reassembly for all IPIFs
12362  * associated with the ILL.  The hash is based on the packet
12363  * IP ident field.  The ILL frag hash table was allocated
12364  * as a timer block at the time the ILL was created.  Whenever
12365  * there is anything on the reassembly queue, the timer will
12366  * be running.  Returns B_TRUE if successful else B_FALSE;
12367  * frees mp on failure.
12368  */
12369 static boolean_t
12370 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12371     uint32_t *cksum_val, uint16_t *cksum_flags)
12372 {
12373 	uint32_t	frag_offset_flags;
12374 	ill_t		*ill = (ill_t *)q->q_ptr;
12375 	mblk_t		*mp = *mpp;
12376 	mblk_t		*t_mp;
12377 	ipaddr_t	dst;
12378 	uint8_t		proto = ipha->ipha_protocol;
12379 	uint32_t	sum_val;
12380 	uint16_t	sum_flags;
12381 	ipf_t		*ipf;
12382 	ipf_t		**ipfp;
12383 	ipfb_t		*ipfb;
12384 	uint16_t	ident;
12385 	uint32_t	offset;
12386 	ipaddr_t	src;
12387 	uint_t		hdr_length;
12388 	uint32_t	end;
12389 	mblk_t		*mp1;
12390 	mblk_t		*tail_mp;
12391 	size_t		count;
12392 	size_t		msg_len;
12393 	uint8_t		ecn_info = 0;
12394 	uint32_t	packet_size;
12395 	boolean_t	pruned = B_FALSE;
12396 	ip_stack_t *ipst = ill->ill_ipst;
12397 
12398 	if (cksum_val != NULL)
12399 		*cksum_val = 0;
12400 	if (cksum_flags != NULL)
12401 		*cksum_flags = 0;
12402 
12403 	/*
12404 	 * Drop the fragmented as early as possible, if
12405 	 * we don't have resource(s) to re-assemble.
12406 	 */
12407 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12408 		freemsg(mp);
12409 		return (B_FALSE);
12410 	}
12411 
12412 	/* Check for fragmentation offset; return if there's none */
12413 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12414 	    (IPH_MF | IPH_OFFSET)) == 0)
12415 		return (B_TRUE);
12416 
12417 	/*
12418 	 * We utilize hardware computed checksum info only for UDP since
12419 	 * IP fragmentation is a normal occurence for the protocol.  In
12420 	 * addition, checksum offload support for IP fragments carrying
12421 	 * UDP payload is commonly implemented across network adapters.
12422 	 */
12423 	ASSERT(ill != NULL);
12424 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12425 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12426 		mblk_t *mp1 = mp->b_cont;
12427 		int32_t len;
12428 
12429 		/* Record checksum information from the packet */
12430 		sum_val = (uint32_t)DB_CKSUM16(mp);
12431 		sum_flags = DB_CKSUMFLAGS(mp);
12432 
12433 		/* IP payload offset from beginning of mblk */
12434 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12435 
12436 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12437 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12438 		    offset >= DB_CKSUMSTART(mp) &&
12439 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12440 			uint32_t adj;
12441 			/*
12442 			 * Partial checksum has been calculated by hardware
12443 			 * and attached to the packet; in addition, any
12444 			 * prepended extraneous data is even byte aligned.
12445 			 * If any such data exists, we adjust the checksum;
12446 			 * this would also handle any postpended data.
12447 			 */
12448 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12449 			    mp, mp1, len, adj);
12450 
12451 			/* One's complement subtract extraneous checksum */
12452 			if (adj >= sum_val)
12453 				sum_val = ~(adj - sum_val) & 0xFFFF;
12454 			else
12455 				sum_val -= adj;
12456 		}
12457 	} else {
12458 		sum_val = 0;
12459 		sum_flags = 0;
12460 	}
12461 
12462 	/* Clear hardware checksumming flag */
12463 	DB_CKSUMFLAGS(mp) = 0;
12464 
12465 	ident = ipha->ipha_ident;
12466 	offset = (frag_offset_flags << 3) & 0xFFFF;
12467 	src = ipha->ipha_src;
12468 	dst = ipha->ipha_dst;
12469 	hdr_length = IPH_HDR_LENGTH(ipha);
12470 	end = ntohs(ipha->ipha_length) - hdr_length;
12471 
12472 	/* If end == 0 then we have a packet with no data, so just free it */
12473 	if (end == 0) {
12474 		freemsg(mp);
12475 		return (B_FALSE);
12476 	}
12477 
12478 	/* Record the ECN field info. */
12479 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12480 	if (offset != 0) {
12481 		/*
12482 		 * If this isn't the first piece, strip the header, and
12483 		 * add the offset to the end value.
12484 		 */
12485 		mp->b_rptr += hdr_length;
12486 		end += offset;
12487 	}
12488 
12489 	msg_len = MBLKSIZE(mp);
12490 	tail_mp = mp;
12491 	while (tail_mp->b_cont != NULL) {
12492 		tail_mp = tail_mp->b_cont;
12493 		msg_len += MBLKSIZE(tail_mp);
12494 	}
12495 
12496 	/* If the reassembly list for this ILL will get too big, prune it */
12497 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12498 	    ipst->ips_ip_reass_queue_bytes) {
12499 		ill_frag_prune(ill,
12500 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12501 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12502 		pruned = B_TRUE;
12503 	}
12504 
12505 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12506 	mutex_enter(&ipfb->ipfb_lock);
12507 
12508 	ipfp = &ipfb->ipfb_ipf;
12509 	/* Try to find an existing fragment queue for this packet. */
12510 	for (;;) {
12511 		ipf = ipfp[0];
12512 		if (ipf != NULL) {
12513 			/*
12514 			 * It has to match on ident and src/dst address.
12515 			 */
12516 			if (ipf->ipf_ident == ident &&
12517 			    ipf->ipf_src == src &&
12518 			    ipf->ipf_dst == dst &&
12519 			    ipf->ipf_protocol == proto) {
12520 				/*
12521 				 * If we have received too many
12522 				 * duplicate fragments for this packet
12523 				 * free it.
12524 				 */
12525 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12526 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12527 					freemsg(mp);
12528 					mutex_exit(&ipfb->ipfb_lock);
12529 					return (B_FALSE);
12530 				}
12531 				/* Found it. */
12532 				break;
12533 			}
12534 			ipfp = &ipf->ipf_hash_next;
12535 			continue;
12536 		}
12537 
12538 		/*
12539 		 * If we pruned the list, do we want to store this new
12540 		 * fragment?. We apply an optimization here based on the
12541 		 * fact that most fragments will be received in order.
12542 		 * So if the offset of this incoming fragment is zero,
12543 		 * it is the first fragment of a new packet. We will
12544 		 * keep it.  Otherwise drop the fragment, as we have
12545 		 * probably pruned the packet already (since the
12546 		 * packet cannot be found).
12547 		 */
12548 		if (pruned && offset != 0) {
12549 			mutex_exit(&ipfb->ipfb_lock);
12550 			freemsg(mp);
12551 			return (B_FALSE);
12552 		}
12553 
12554 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12555 			/*
12556 			 * Too many fragmented packets in this hash
12557 			 * bucket. Free the oldest.
12558 			 */
12559 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12560 		}
12561 
12562 		/* New guy.  Allocate a frag message. */
12563 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12564 		if (mp1 == NULL) {
12565 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12566 			freemsg(mp);
12567 reass_done:
12568 			mutex_exit(&ipfb->ipfb_lock);
12569 			return (B_FALSE);
12570 		}
12571 
12572 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12573 		mp1->b_cont = mp;
12574 
12575 		/* Initialize the fragment header. */
12576 		ipf = (ipf_t *)mp1->b_rptr;
12577 		ipf->ipf_mp = mp1;
12578 		ipf->ipf_ptphn = ipfp;
12579 		ipfp[0] = ipf;
12580 		ipf->ipf_hash_next = NULL;
12581 		ipf->ipf_ident = ident;
12582 		ipf->ipf_protocol = proto;
12583 		ipf->ipf_src = src;
12584 		ipf->ipf_dst = dst;
12585 		ipf->ipf_nf_hdr_len = 0;
12586 		/* Record reassembly start time. */
12587 		ipf->ipf_timestamp = gethrestime_sec();
12588 		/* Record ipf generation and account for frag header */
12589 		ipf->ipf_gen = ill->ill_ipf_gen++;
12590 		ipf->ipf_count = MBLKSIZE(mp1);
12591 		ipf->ipf_last_frag_seen = B_FALSE;
12592 		ipf->ipf_ecn = ecn_info;
12593 		ipf->ipf_num_dups = 0;
12594 		ipfb->ipfb_frag_pkts++;
12595 		ipf->ipf_checksum = 0;
12596 		ipf->ipf_checksum_flags = 0;
12597 
12598 		/* Store checksum value in fragment header */
12599 		if (sum_flags != 0) {
12600 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12601 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12602 			ipf->ipf_checksum = sum_val;
12603 			ipf->ipf_checksum_flags = sum_flags;
12604 		}
12605 
12606 		/*
12607 		 * We handle reassembly two ways.  In the easy case,
12608 		 * where all the fragments show up in order, we do
12609 		 * minimal bookkeeping, and just clip new pieces on
12610 		 * the end.  If we ever see a hole, then we go off
12611 		 * to ip_reassemble which has to mark the pieces and
12612 		 * keep track of the number of holes, etc.  Obviously,
12613 		 * the point of having both mechanisms is so we can
12614 		 * handle the easy case as efficiently as possible.
12615 		 */
12616 		if (offset == 0) {
12617 			/* Easy case, in-order reassembly so far. */
12618 			ipf->ipf_count += msg_len;
12619 			ipf->ipf_tail_mp = tail_mp;
12620 			/*
12621 			 * Keep track of next expected offset in
12622 			 * ipf_end.
12623 			 */
12624 			ipf->ipf_end = end;
12625 			ipf->ipf_nf_hdr_len = hdr_length;
12626 		} else {
12627 			/* Hard case, hole at the beginning. */
12628 			ipf->ipf_tail_mp = NULL;
12629 			/*
12630 			 * ipf_end == 0 means that we have given up
12631 			 * on easy reassembly.
12632 			 */
12633 			ipf->ipf_end = 0;
12634 
12635 			/* Forget checksum offload from now on */
12636 			ipf->ipf_checksum_flags = 0;
12637 
12638 			/*
12639 			 * ipf_hole_cnt is set by ip_reassemble.
12640 			 * ipf_count is updated by ip_reassemble.
12641 			 * No need to check for return value here
12642 			 * as we don't expect reassembly to complete
12643 			 * or fail for the first fragment itself.
12644 			 */
12645 			(void) ip_reassemble(mp, ipf,
12646 			    (frag_offset_flags & IPH_OFFSET) << 3,
12647 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12648 		}
12649 		/* Update per ipfb and ill byte counts */
12650 		ipfb->ipfb_count += ipf->ipf_count;
12651 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12652 		ill->ill_frag_count += ipf->ipf_count;
12653 		/* If the frag timer wasn't already going, start it. */
12654 		mutex_enter(&ill->ill_lock);
12655 		ill_frag_timer_start(ill);
12656 		mutex_exit(&ill->ill_lock);
12657 		goto reass_done;
12658 	}
12659 
12660 	/*
12661 	 * If the packet's flag has changed (it could be coming up
12662 	 * from an interface different than the previous, therefore
12663 	 * possibly different checksum capability), then forget about
12664 	 * any stored checksum states.  Otherwise add the value to
12665 	 * the existing one stored in the fragment header.
12666 	 */
12667 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12668 		sum_val += ipf->ipf_checksum;
12669 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12670 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12671 		ipf->ipf_checksum = sum_val;
12672 	} else if (ipf->ipf_checksum_flags != 0) {
12673 		/* Forget checksum offload from now on */
12674 		ipf->ipf_checksum_flags = 0;
12675 	}
12676 
12677 	/*
12678 	 * We have a new piece of a datagram which is already being
12679 	 * reassembled.  Update the ECN info if all IP fragments
12680 	 * are ECN capable.  If there is one which is not, clear
12681 	 * all the info.  If there is at least one which has CE
12682 	 * code point, IP needs to report that up to transport.
12683 	 */
12684 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12685 		if (ecn_info == IPH_ECN_CE)
12686 			ipf->ipf_ecn = IPH_ECN_CE;
12687 	} else {
12688 		ipf->ipf_ecn = IPH_ECN_NECT;
12689 	}
12690 	if (offset && ipf->ipf_end == offset) {
12691 		/* The new fragment fits at the end */
12692 		ipf->ipf_tail_mp->b_cont = mp;
12693 		/* Update the byte count */
12694 		ipf->ipf_count += msg_len;
12695 		/* Update per ipfb and ill byte counts */
12696 		ipfb->ipfb_count += msg_len;
12697 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12698 		ill->ill_frag_count += msg_len;
12699 		if (frag_offset_flags & IPH_MF) {
12700 			/* More to come. */
12701 			ipf->ipf_end = end;
12702 			ipf->ipf_tail_mp = tail_mp;
12703 			goto reass_done;
12704 		}
12705 	} else {
12706 		/* Go do the hard cases. */
12707 		int ret;
12708 
12709 		if (offset == 0)
12710 			ipf->ipf_nf_hdr_len = hdr_length;
12711 
12712 		/* Save current byte count */
12713 		count = ipf->ipf_count;
12714 		ret = ip_reassemble(mp, ipf,
12715 		    (frag_offset_flags & IPH_OFFSET) << 3,
12716 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12717 		/* Count of bytes added and subtracted (freeb()ed) */
12718 		count = ipf->ipf_count - count;
12719 		if (count) {
12720 			/* Update per ipfb and ill byte counts */
12721 			ipfb->ipfb_count += count;
12722 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12723 			ill->ill_frag_count += count;
12724 		}
12725 		if (ret == IP_REASS_PARTIAL) {
12726 			goto reass_done;
12727 		} else if (ret == IP_REASS_FAILED) {
12728 			/* Reassembly failed. Free up all resources */
12729 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12730 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12731 				IP_REASS_SET_START(t_mp, 0);
12732 				IP_REASS_SET_END(t_mp, 0);
12733 			}
12734 			freemsg(mp);
12735 			goto reass_done;
12736 		}
12737 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12738 	}
12739 	/*
12740 	 * We have completed reassembly.  Unhook the frag header from
12741 	 * the reassembly list.
12742 	 *
12743 	 * Before we free the frag header, record the ECN info
12744 	 * to report back to the transport.
12745 	 */
12746 	ecn_info = ipf->ipf_ecn;
12747 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12748 	ipfp = ipf->ipf_ptphn;
12749 
12750 	/* We need to supply these to caller */
12751 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12752 		sum_val = ipf->ipf_checksum;
12753 	else
12754 		sum_val = 0;
12755 
12756 	mp1 = ipf->ipf_mp;
12757 	count = ipf->ipf_count;
12758 	ipf = ipf->ipf_hash_next;
12759 	if (ipf != NULL)
12760 		ipf->ipf_ptphn = ipfp;
12761 	ipfp[0] = ipf;
12762 	ill->ill_frag_count -= count;
12763 	ASSERT(ipfb->ipfb_count >= count);
12764 	ipfb->ipfb_count -= count;
12765 	ipfb->ipfb_frag_pkts--;
12766 	mutex_exit(&ipfb->ipfb_lock);
12767 	/* Ditch the frag header. */
12768 	mp = mp1->b_cont;
12769 
12770 	freeb(mp1);
12771 
12772 	/* Restore original IP length in header. */
12773 	packet_size = (uint32_t)msgdsize(mp);
12774 	if (packet_size > IP_MAXPACKET) {
12775 		freemsg(mp);
12776 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12777 		return (B_FALSE);
12778 	}
12779 
12780 	if (DB_REF(mp) > 1) {
12781 		mblk_t *mp2 = copymsg(mp);
12782 
12783 		freemsg(mp);
12784 		if (mp2 == NULL) {
12785 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12786 			return (B_FALSE);
12787 		}
12788 		mp = mp2;
12789 	}
12790 	ipha = (ipha_t *)mp->b_rptr;
12791 
12792 	ipha->ipha_length = htons((uint16_t)packet_size);
12793 	/* We're now complete, zip the frag state */
12794 	ipha->ipha_fragment_offset_and_flags = 0;
12795 	/* Record the ECN info. */
12796 	ipha->ipha_type_of_service &= 0xFC;
12797 	ipha->ipha_type_of_service |= ecn_info;
12798 	*mpp = mp;
12799 
12800 	/* Reassembly is successful; return checksum information if needed */
12801 	if (cksum_val != NULL)
12802 		*cksum_val = sum_val;
12803 	if (cksum_flags != NULL)
12804 		*cksum_flags = sum_flags;
12805 
12806 	return (B_TRUE);
12807 }
12808 
12809 /*
12810  * Perform ip header check sum update local options.
12811  * return B_TRUE if all is well, else return B_FALSE and release
12812  * the mp. caller is responsible for decrementing ire ref cnt.
12813  */
12814 static boolean_t
12815 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12816     ip_stack_t *ipst)
12817 {
12818 	mblk_t		*first_mp;
12819 	boolean_t	mctl_present;
12820 	uint16_t	sum;
12821 
12822 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12823 	/*
12824 	 * Don't do the checksum if it has gone through AH/ESP
12825 	 * processing.
12826 	 */
12827 	if (!mctl_present) {
12828 		sum = ip_csum_hdr(ipha);
12829 		if (sum != 0) {
12830 			if (ill != NULL) {
12831 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12832 			} else {
12833 				BUMP_MIB(&ipst->ips_ip_mib,
12834 				    ipIfStatsInCksumErrs);
12835 			}
12836 			freemsg(first_mp);
12837 			return (B_FALSE);
12838 		}
12839 	}
12840 
12841 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12842 		if (mctl_present)
12843 			freeb(first_mp);
12844 		return (B_FALSE);
12845 	}
12846 
12847 	return (B_TRUE);
12848 }
12849 
12850 /*
12851  * All udp packet are delivered to the local host via this routine.
12852  */
12853 void
12854 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12855     ill_t *recv_ill)
12856 {
12857 	uint32_t	sum;
12858 	uint32_t	u1;
12859 	boolean_t	mctl_present;
12860 	conn_t		*connp;
12861 	mblk_t		*first_mp;
12862 	uint16_t	*up;
12863 	ill_t		*ill = (ill_t *)q->q_ptr;
12864 	uint16_t	reass_hck_flags = 0;
12865 	ip_stack_t	*ipst;
12866 
12867 	ASSERT(recv_ill != NULL);
12868 	ipst = recv_ill->ill_ipst;
12869 
12870 #define	rptr    ((uchar_t *)ipha)
12871 
12872 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12873 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12874 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12875 	ASSERT(ill != NULL);
12876 
12877 	/*
12878 	 * FAST PATH for udp packets
12879 	 */
12880 
12881 	/* u1 is # words of IP options */
12882 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12883 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12884 
12885 	/* IP options present */
12886 	if (u1 != 0)
12887 		goto ipoptions;
12888 
12889 	/* Check the IP header checksum.  */
12890 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12891 		/* Clear the IP header h/w cksum flag */
12892 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12893 	} else {
12894 #define	uph	((uint16_t *)ipha)
12895 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12896 		    uph[6] + uph[7] + uph[8] + uph[9];
12897 #undef	uph
12898 		/* finish doing IP checksum */
12899 		sum = (sum & 0xFFFF) + (sum >> 16);
12900 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12901 		/*
12902 		 * Don't verify header checksum if this packet is coming
12903 		 * back from AH/ESP as we already did it.
12904 		 */
12905 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12906 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12907 			freemsg(first_mp);
12908 			return;
12909 		}
12910 	}
12911 
12912 	/*
12913 	 * Count for SNMP of inbound packets for ire.
12914 	 * if mctl is present this might be a secure packet and
12915 	 * has already been counted for in ip_proto_input().
12916 	 */
12917 	if (!mctl_present) {
12918 		UPDATE_IB_PKT_COUNT(ire);
12919 		ire->ire_last_used_time = lbolt;
12920 	}
12921 
12922 	/* packet part of fragmented IP packet? */
12923 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12924 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12925 		goto fragmented;
12926 	}
12927 
12928 	/* u1 = IP header length (20 bytes) */
12929 	u1 = IP_SIMPLE_HDR_LENGTH;
12930 
12931 	/* packet does not contain complete IP & UDP headers */
12932 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12933 		goto udppullup;
12934 
12935 	/* up points to UDP header */
12936 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12937 #define	iphs    ((uint16_t *)ipha)
12938 
12939 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12940 	if (up[3] != 0) {
12941 		mblk_t *mp1 = mp->b_cont;
12942 		boolean_t cksum_err;
12943 		uint16_t hck_flags = 0;
12944 
12945 		/* Pseudo-header checksum */
12946 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12947 		    iphs[9] + up[2];
12948 
12949 		/*
12950 		 * Revert to software checksum calculation if the interface
12951 		 * isn't capable of checksum offload or if IPsec is present.
12952 		 */
12953 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12954 			hck_flags = DB_CKSUMFLAGS(mp);
12955 
12956 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12957 			IP_STAT(ipst, ip_in_sw_cksum);
12958 
12959 		IP_CKSUM_RECV(hck_flags, u1,
12960 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12961 		    (int32_t)((uchar_t *)up - rptr),
12962 		    mp, mp1, cksum_err);
12963 
12964 		if (cksum_err) {
12965 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12966 			if (hck_flags & HCK_FULLCKSUM)
12967 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12968 			else if (hck_flags & HCK_PARTIALCKSUM)
12969 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12970 			else
12971 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12972 
12973 			freemsg(first_mp);
12974 			return;
12975 		}
12976 	}
12977 
12978 	/* Non-fragmented broadcast or multicast packet? */
12979 	if (ire->ire_type == IRE_BROADCAST)
12980 		goto udpslowpath;
12981 
12982 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12983 	    ire->ire_zoneid, ipst)) != NULL) {
12984 		ASSERT(connp->conn_upq != NULL);
12985 		IP_STAT(ipst, ip_udp_fast_path);
12986 
12987 		if (CONN_UDP_FLOWCTLD(connp)) {
12988 			freemsg(mp);
12989 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12990 		} else {
12991 			if (!mctl_present) {
12992 				BUMP_MIB(ill->ill_ip_mib,
12993 				    ipIfStatsHCInDelivers);
12994 			}
12995 			/*
12996 			 * mp and first_mp can change.
12997 			 */
12998 			if (ip_udp_check(q, connp, recv_ill,
12999 			    ipha, &mp, &first_mp, mctl_present)) {
13000 				/* Send it upstream */
13001 				CONN_UDP_RECV(connp, mp);
13002 			}
13003 		}
13004 		/*
13005 		 * freeb() cannot deal with null mblk being passed
13006 		 * in and first_mp can be set to null in the call
13007 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
13008 		 */
13009 		if (mctl_present && first_mp != NULL) {
13010 			freeb(first_mp);
13011 		}
13012 		CONN_DEC_REF(connp);
13013 		return;
13014 	}
13015 
13016 	/*
13017 	 * if we got here we know the packet is not fragmented and
13018 	 * has no options. The classifier could not find a conn_t and
13019 	 * most likely its an icmp packet so send it through slow path.
13020 	 */
13021 
13022 	goto udpslowpath;
13023 
13024 ipoptions:
13025 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
13026 		goto slow_done;
13027 	}
13028 
13029 	UPDATE_IB_PKT_COUNT(ire);
13030 	ire->ire_last_used_time = lbolt;
13031 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13032 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13033 fragmented:
13034 		/*
13035 		 * "sum" and "reass_hck_flags" are non-zero if the
13036 		 * reassembled packet has a valid hardware computed
13037 		 * checksum information associated with it.
13038 		 */
13039 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
13040 			goto slow_done;
13041 		/*
13042 		 * Make sure that first_mp points back to mp as
13043 		 * the mp we came in with could have changed in
13044 		 * ip_rput_fragment().
13045 		 */
13046 		ASSERT(!mctl_present);
13047 		ipha = (ipha_t *)mp->b_rptr;
13048 		first_mp = mp;
13049 	}
13050 
13051 	/* Now we have a complete datagram, destined for this machine. */
13052 	u1 = IPH_HDR_LENGTH(ipha);
13053 	/* Pull up the UDP header, if necessary. */
13054 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
13055 udppullup:
13056 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
13057 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13058 			freemsg(first_mp);
13059 			goto slow_done;
13060 		}
13061 		ipha = (ipha_t *)mp->b_rptr;
13062 	}
13063 
13064 	/*
13065 	 * Validate the checksum for the reassembled packet; for the
13066 	 * pullup case we calculate the payload checksum in software.
13067 	 */
13068 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
13069 	if (up[3] != 0) {
13070 		boolean_t cksum_err;
13071 
13072 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13073 			IP_STAT(ipst, ip_in_sw_cksum);
13074 
13075 		IP_CKSUM_RECV_REASS(reass_hck_flags,
13076 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
13077 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
13078 		    iphs[9] + up[2], sum, cksum_err);
13079 
13080 		if (cksum_err) {
13081 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
13082 
13083 			if (reass_hck_flags & HCK_FULLCKSUM)
13084 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
13085 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
13086 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
13087 			else
13088 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
13089 
13090 			freemsg(first_mp);
13091 			goto slow_done;
13092 		}
13093 	}
13094 udpslowpath:
13095 
13096 	/* Clear hardware checksum flag to be safe */
13097 	DB_CKSUMFLAGS(mp) = 0;
13098 
13099 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
13100 	    (ire->ire_type == IRE_BROADCAST),
13101 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
13102 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
13103 
13104 slow_done:
13105 	IP_STAT(ipst, ip_udp_slow_path);
13106 	return;
13107 
13108 #undef  iphs
13109 #undef  rptr
13110 }
13111 
13112 /* ARGSUSED */
13113 static mblk_t *
13114 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13115     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13116     ill_rx_ring_t *ill_ring)
13117 {
13118 	conn_t		*connp;
13119 	uint32_t	sum;
13120 	uint32_t	u1;
13121 	uint16_t	*up;
13122 	int		offset;
13123 	ssize_t		len;
13124 	mblk_t		*mp1;
13125 	boolean_t	syn_present = B_FALSE;
13126 	tcph_t		*tcph;
13127 	uint_t		ip_hdr_len;
13128 	ill_t		*ill = (ill_t *)q->q_ptr;
13129 	zoneid_t	zoneid = ire->ire_zoneid;
13130 	boolean_t	cksum_err;
13131 	uint16_t	hck_flags = 0;
13132 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13133 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13134 
13135 #define	rptr	((uchar_t *)ipha)
13136 
13137 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13138 	ASSERT(ill != NULL);
13139 
13140 	/*
13141 	 * FAST PATH for tcp packets
13142 	 */
13143 
13144 	/* u1 is # words of IP options */
13145 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13146 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13147 
13148 	/* IP options present */
13149 	if (u1) {
13150 		goto ipoptions;
13151 	} else {
13152 		/* Check the IP header checksum.  */
13153 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13154 			/* Clear the IP header h/w cksum flag */
13155 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13156 		} else {
13157 #define	uph	((uint16_t *)ipha)
13158 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13159 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13160 #undef	uph
13161 			/* finish doing IP checksum */
13162 			sum = (sum & 0xFFFF) + (sum >> 16);
13163 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13164 			/*
13165 			 * Don't verify header checksum if this packet
13166 			 * is coming back from AH/ESP as we already did it.
13167 			 */
13168 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13169 				BUMP_MIB(ill->ill_ip_mib,
13170 				    ipIfStatsInCksumErrs);
13171 				goto error;
13172 			}
13173 		}
13174 	}
13175 
13176 	if (!mctl_present) {
13177 		UPDATE_IB_PKT_COUNT(ire);
13178 		ire->ire_last_used_time = lbolt;
13179 	}
13180 
13181 	/* packet part of fragmented IP packet? */
13182 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13183 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13184 		goto fragmented;
13185 	}
13186 
13187 	/* u1 = IP header length (20 bytes) */
13188 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13189 
13190 	/* does packet contain IP+TCP headers? */
13191 	len = mp->b_wptr - rptr;
13192 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13193 		IP_STAT(ipst, ip_tcppullup);
13194 		goto tcppullup;
13195 	}
13196 
13197 	/* TCP options present? */
13198 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13199 
13200 	/*
13201 	 * If options need to be pulled up, then goto tcpoptions.
13202 	 * otherwise we are still in the fast path
13203 	 */
13204 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13205 		IP_STAT(ipst, ip_tcpoptions);
13206 		goto tcpoptions;
13207 	}
13208 
13209 	/* multiple mblks of tcp data? */
13210 	if ((mp1 = mp->b_cont) != NULL) {
13211 		/* more then two? */
13212 		if (mp1->b_cont != NULL) {
13213 			IP_STAT(ipst, ip_multipkttcp);
13214 			goto multipkttcp;
13215 		}
13216 		len += mp1->b_wptr - mp1->b_rptr;
13217 	}
13218 
13219 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13220 
13221 	/* part of pseudo checksum */
13222 
13223 	/* TCP datagram length */
13224 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13225 
13226 #define	iphs    ((uint16_t *)ipha)
13227 
13228 #ifdef	_BIG_ENDIAN
13229 	u1 += IPPROTO_TCP;
13230 #else
13231 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13232 #endif
13233 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13234 
13235 	/*
13236 	 * Revert to software checksum calculation if the interface
13237 	 * isn't capable of checksum offload or if IPsec is present.
13238 	 */
13239 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13240 		hck_flags = DB_CKSUMFLAGS(mp);
13241 
13242 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13243 		IP_STAT(ipst, ip_in_sw_cksum);
13244 
13245 	IP_CKSUM_RECV(hck_flags, u1,
13246 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13247 	    (int32_t)((uchar_t *)up - rptr),
13248 	    mp, mp1, cksum_err);
13249 
13250 	if (cksum_err) {
13251 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13252 
13253 		if (hck_flags & HCK_FULLCKSUM)
13254 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13255 		else if (hck_flags & HCK_PARTIALCKSUM)
13256 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13257 		else
13258 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13259 
13260 		goto error;
13261 	}
13262 
13263 try_again:
13264 
13265 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13266 	    zoneid, ipst)) == NULL) {
13267 		/* Send the TH_RST */
13268 		goto no_conn;
13269 	}
13270 
13271 	/*
13272 	 * TCP FAST PATH for AF_INET socket.
13273 	 *
13274 	 * TCP fast path to avoid extra work. An AF_INET socket type
13275 	 * does not have facility to receive extra information via
13276 	 * ip_process or ip_add_info. Also, when the connection was
13277 	 * established, we made a check if this connection is impacted
13278 	 * by any global IPSec policy or per connection policy (a
13279 	 * policy that comes in effect later will not apply to this
13280 	 * connection). Since all this can be determined at the
13281 	 * connection establishment time, a quick check of flags
13282 	 * can avoid extra work.
13283 	 */
13284 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13285 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13286 		ASSERT(first_mp == mp);
13287 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13288 		SET_SQUEUE(mp, tcp_rput_data, connp);
13289 		return (mp);
13290 	}
13291 
13292 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13293 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13294 		if (IPCL_IS_TCP(connp)) {
13295 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13296 			DB_CKSUMSTART(mp) =
13297 			    (intptr_t)ip_squeue_get(ill_ring);
13298 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13299 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13300 				BUMP_MIB(ill->ill_ip_mib,
13301 				    ipIfStatsHCInDelivers);
13302 				SET_SQUEUE(mp, connp->conn_recv, connp);
13303 				return (mp);
13304 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13305 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13306 				BUMP_MIB(ill->ill_ip_mib,
13307 				    ipIfStatsHCInDelivers);
13308 				ip_squeue_enter_unbound++;
13309 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13310 				    connp);
13311 				return (mp);
13312 			}
13313 			syn_present = B_TRUE;
13314 		}
13315 
13316 	}
13317 
13318 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13319 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13320 
13321 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13322 		/* No need to send this packet to TCP */
13323 		if ((flags & TH_RST) || (flags & TH_URG)) {
13324 			CONN_DEC_REF(connp);
13325 			freemsg(first_mp);
13326 			return (NULL);
13327 		}
13328 		if (flags & TH_ACK) {
13329 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13330 			    ipst->ips_netstack->netstack_tcp);
13331 			CONN_DEC_REF(connp);
13332 			return (NULL);
13333 		}
13334 
13335 		CONN_DEC_REF(connp);
13336 		freemsg(first_mp);
13337 		return (NULL);
13338 	}
13339 
13340 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13341 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13342 		    ipha, NULL, mctl_present);
13343 		if (first_mp == NULL) {
13344 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13345 			CONN_DEC_REF(connp);
13346 			return (NULL);
13347 		}
13348 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13349 			ASSERT(syn_present);
13350 			if (mctl_present) {
13351 				ASSERT(first_mp != mp);
13352 				first_mp->b_datap->db_struioflag |=
13353 				    STRUIO_POLICY;
13354 			} else {
13355 				ASSERT(first_mp == mp);
13356 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13357 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13358 			}
13359 		} else {
13360 			/*
13361 			 * Discard first_mp early since we're dealing with a
13362 			 * fully-connected conn_t and tcp doesn't do policy in
13363 			 * this case.
13364 			 */
13365 			if (mctl_present) {
13366 				freeb(first_mp);
13367 				mctl_present = B_FALSE;
13368 			}
13369 			first_mp = mp;
13370 		}
13371 	}
13372 
13373 	/* Initiate IPPF processing for fastpath */
13374 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13375 		uint32_t	ill_index;
13376 
13377 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13378 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13379 		if (mp == NULL) {
13380 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13381 			    "deferred/dropped during IPPF processing\n"));
13382 			CONN_DEC_REF(connp);
13383 			if (mctl_present)
13384 				freeb(first_mp);
13385 			return (NULL);
13386 		} else if (mctl_present) {
13387 			/*
13388 			 * ip_process might return a new mp.
13389 			 */
13390 			ASSERT(first_mp != mp);
13391 			first_mp->b_cont = mp;
13392 		} else {
13393 			first_mp = mp;
13394 		}
13395 
13396 	}
13397 
13398 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13399 		/*
13400 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13401 		 * make sure IPF_RECVIF is passed to ip_add_info.
13402 		 */
13403 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13404 		    IPCL_ZONEID(connp), ipst);
13405 		if (mp == NULL) {
13406 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13407 			CONN_DEC_REF(connp);
13408 			if (mctl_present)
13409 				freeb(first_mp);
13410 			return (NULL);
13411 		} else if (mctl_present) {
13412 			/*
13413 			 * ip_add_info might return a new mp.
13414 			 */
13415 			ASSERT(first_mp != mp);
13416 			first_mp->b_cont = mp;
13417 		} else {
13418 			first_mp = mp;
13419 		}
13420 	}
13421 
13422 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13423 	if (IPCL_IS_TCP(connp)) {
13424 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13425 		return (first_mp);
13426 	} else {
13427 		putnext(connp->conn_rq, first_mp);
13428 		CONN_DEC_REF(connp);
13429 		return (NULL);
13430 	}
13431 
13432 no_conn:
13433 	/* Initiate IPPf processing, if needed. */
13434 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13435 		uint32_t ill_index;
13436 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13437 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13438 		if (first_mp == NULL) {
13439 			return (NULL);
13440 		}
13441 	}
13442 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13443 
13444 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13445 	    ipst->ips_netstack->netstack_tcp);
13446 	return (NULL);
13447 ipoptions:
13448 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13449 		goto slow_done;
13450 	}
13451 
13452 	UPDATE_IB_PKT_COUNT(ire);
13453 	ire->ire_last_used_time = lbolt;
13454 
13455 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13456 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13457 fragmented:
13458 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13459 			if (mctl_present)
13460 				freeb(first_mp);
13461 			goto slow_done;
13462 		}
13463 		/*
13464 		 * Make sure that first_mp points back to mp as
13465 		 * the mp we came in with could have changed in
13466 		 * ip_rput_fragment().
13467 		 */
13468 		ASSERT(!mctl_present);
13469 		ipha = (ipha_t *)mp->b_rptr;
13470 		first_mp = mp;
13471 	}
13472 
13473 	/* Now we have a complete datagram, destined for this machine. */
13474 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13475 
13476 	len = mp->b_wptr - mp->b_rptr;
13477 	/* Pull up a minimal TCP header, if necessary. */
13478 	if (len < (u1 + 20)) {
13479 tcppullup:
13480 		if (!pullupmsg(mp, u1 + 20)) {
13481 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13482 			goto error;
13483 		}
13484 		ipha = (ipha_t *)mp->b_rptr;
13485 		len = mp->b_wptr - mp->b_rptr;
13486 	}
13487 
13488 	/*
13489 	 * Extract the offset field from the TCP header.  As usual, we
13490 	 * try to help the compiler more than the reader.
13491 	 */
13492 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13493 	if (offset != 5) {
13494 tcpoptions:
13495 		if (offset < 5) {
13496 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13497 			goto error;
13498 		}
13499 		/*
13500 		 * There must be TCP options.
13501 		 * Make sure we can grab them.
13502 		 */
13503 		offset <<= 2;
13504 		offset += u1;
13505 		if (len < offset) {
13506 			if (!pullupmsg(mp, offset)) {
13507 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13508 				goto error;
13509 			}
13510 			ipha = (ipha_t *)mp->b_rptr;
13511 			len = mp->b_wptr - rptr;
13512 		}
13513 	}
13514 
13515 	/* Get the total packet length in len, including headers. */
13516 	if (mp->b_cont) {
13517 multipkttcp:
13518 		len = msgdsize(mp);
13519 	}
13520 
13521 	/*
13522 	 * Check the TCP checksum by pulling together the pseudo-
13523 	 * header checksum, and passing it to ip_csum to be added in
13524 	 * with the TCP datagram.
13525 	 *
13526 	 * Since we are not using the hwcksum if available we must
13527 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13528 	 * If either of these fails along the way the mblk is freed.
13529 	 * If this logic ever changes and mblk is reused to say send
13530 	 * ICMP's back, then this flag may need to be cleared in
13531 	 * other places as well.
13532 	 */
13533 	DB_CKSUMFLAGS(mp) = 0;
13534 
13535 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13536 
13537 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13538 #ifdef	_BIG_ENDIAN
13539 	u1 += IPPROTO_TCP;
13540 #else
13541 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13542 #endif
13543 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13544 	/*
13545 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13546 	 */
13547 	IP_STAT(ipst, ip_in_sw_cksum);
13548 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13549 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13550 		goto error;
13551 	}
13552 
13553 	IP_STAT(ipst, ip_tcp_slow_path);
13554 	goto try_again;
13555 #undef  iphs
13556 #undef  rptr
13557 
13558 error:
13559 	freemsg(first_mp);
13560 slow_done:
13561 	return (NULL);
13562 }
13563 
13564 /* ARGSUSED */
13565 static void
13566 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13567     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13568 {
13569 	conn_t		*connp;
13570 	uint32_t	sum;
13571 	uint32_t	u1;
13572 	ssize_t		len;
13573 	sctp_hdr_t	*sctph;
13574 	zoneid_t	zoneid = ire->ire_zoneid;
13575 	uint32_t	pktsum;
13576 	uint32_t	calcsum;
13577 	uint32_t	ports;
13578 	in6_addr_t	map_src, map_dst;
13579 	ill_t		*ill = (ill_t *)q->q_ptr;
13580 	ip_stack_t	*ipst;
13581 	sctp_stack_t	*sctps;
13582 
13583 	ASSERT(recv_ill != NULL);
13584 	ipst = recv_ill->ill_ipst;
13585 	sctps = ipst->ips_netstack->netstack_sctp;
13586 
13587 #define	rptr	((uchar_t *)ipha)
13588 
13589 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13590 	ASSERT(ill != NULL);
13591 
13592 	/* u1 is # words of IP options */
13593 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13594 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13595 
13596 	/* IP options present */
13597 	if (u1 > 0) {
13598 		goto ipoptions;
13599 	} else {
13600 		/* Check the IP header checksum.  */
13601 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13602 #define	uph	((uint16_t *)ipha)
13603 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13604 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13605 #undef	uph
13606 			/* finish doing IP checksum */
13607 			sum = (sum & 0xFFFF) + (sum >> 16);
13608 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13609 			/*
13610 			 * Don't verify header checksum if this packet
13611 			 * is coming back from AH/ESP as we already did it.
13612 			 */
13613 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13614 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13615 				goto error;
13616 			}
13617 		}
13618 		/*
13619 		 * Since there is no SCTP h/w cksum support yet, just
13620 		 * clear the flag.
13621 		 */
13622 		DB_CKSUMFLAGS(mp) = 0;
13623 	}
13624 
13625 	/*
13626 	 * Don't verify header checksum if this packet is coming
13627 	 * back from AH/ESP as we already did it.
13628 	 */
13629 	if (!mctl_present) {
13630 		UPDATE_IB_PKT_COUNT(ire);
13631 		ire->ire_last_used_time = lbolt;
13632 	}
13633 
13634 	/* packet part of fragmented IP packet? */
13635 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13636 	if (u1 & (IPH_MF | IPH_OFFSET))
13637 		goto fragmented;
13638 
13639 	/* u1 = IP header length (20 bytes) */
13640 	u1 = IP_SIMPLE_HDR_LENGTH;
13641 
13642 find_sctp_client:
13643 	/* Pullup if we don't have the sctp common header. */
13644 	len = MBLKL(mp);
13645 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13646 		if (mp->b_cont == NULL ||
13647 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13648 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13649 			goto error;
13650 		}
13651 		ipha = (ipha_t *)mp->b_rptr;
13652 		len = MBLKL(mp);
13653 	}
13654 
13655 	sctph = (sctp_hdr_t *)(rptr + u1);
13656 #ifdef	DEBUG
13657 	if (!skip_sctp_cksum) {
13658 #endif
13659 		pktsum = sctph->sh_chksum;
13660 		sctph->sh_chksum = 0;
13661 		calcsum = sctp_cksum(mp, u1);
13662 		if (calcsum != pktsum) {
13663 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13664 			goto error;
13665 		}
13666 		sctph->sh_chksum = pktsum;
13667 #ifdef	DEBUG	/* skip_sctp_cksum */
13668 	}
13669 #endif
13670 	/* get the ports */
13671 	ports = *(uint32_t *)&sctph->sh_sport;
13672 
13673 	IRE_REFRELE(ire);
13674 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13675 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13676 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13677 	    sctps)) == NULL) {
13678 		/* Check for raw socket or OOTB handling */
13679 		goto no_conn;
13680 	}
13681 
13682 	/* Found a client; up it goes */
13683 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13684 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13685 	return;
13686 
13687 no_conn:
13688 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13689 	    ports, mctl_present, flags, B_TRUE, zoneid);
13690 	return;
13691 
13692 ipoptions:
13693 	DB_CKSUMFLAGS(mp) = 0;
13694 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13695 		goto slow_done;
13696 
13697 	UPDATE_IB_PKT_COUNT(ire);
13698 	ire->ire_last_used_time = lbolt;
13699 
13700 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13701 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13702 fragmented:
13703 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13704 			goto slow_done;
13705 		/*
13706 		 * Make sure that first_mp points back to mp as
13707 		 * the mp we came in with could have changed in
13708 		 * ip_rput_fragment().
13709 		 */
13710 		ASSERT(!mctl_present);
13711 		ipha = (ipha_t *)mp->b_rptr;
13712 		first_mp = mp;
13713 	}
13714 
13715 	/* Now we have a complete datagram, destined for this machine. */
13716 	u1 = IPH_HDR_LENGTH(ipha);
13717 	goto find_sctp_client;
13718 #undef  iphs
13719 #undef  rptr
13720 
13721 error:
13722 	freemsg(first_mp);
13723 slow_done:
13724 	IRE_REFRELE(ire);
13725 }
13726 
13727 #define	VER_BITS	0xF0
13728 #define	VERSION_6	0x60
13729 
13730 static boolean_t
13731 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13732     ipaddr_t *dstp, ip_stack_t *ipst)
13733 {
13734 	uint_t	opt_len;
13735 	ipha_t *ipha;
13736 	ssize_t len;
13737 	uint_t	pkt_len;
13738 
13739 	ASSERT(ill != NULL);
13740 	IP_STAT(ipst, ip_ipoptions);
13741 	ipha = *iphapp;
13742 
13743 #define	rptr    ((uchar_t *)ipha)
13744 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13745 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13746 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13747 		freemsg(mp);
13748 		return (B_FALSE);
13749 	}
13750 
13751 	/* multiple mblk or too short */
13752 	pkt_len = ntohs(ipha->ipha_length);
13753 
13754 	/* Get the number of words of IP options in the IP header. */
13755 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13756 	if (opt_len) {
13757 		/* IP Options present!  Validate and process. */
13758 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13759 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13760 			goto done;
13761 		}
13762 		/*
13763 		 * Recompute complete header length and make sure we
13764 		 * have access to all of it.
13765 		 */
13766 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13767 		if (len > (mp->b_wptr - rptr)) {
13768 			if (len > pkt_len) {
13769 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13770 				goto done;
13771 			}
13772 			if (!pullupmsg(mp, len)) {
13773 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13774 				goto done;
13775 			}
13776 			ipha = (ipha_t *)mp->b_rptr;
13777 		}
13778 		/*
13779 		 * Go off to ip_rput_options which returns the next hop
13780 		 * destination address, which may have been affected
13781 		 * by source routing.
13782 		 */
13783 		IP_STAT(ipst, ip_opt);
13784 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13785 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13786 			return (B_FALSE);
13787 		}
13788 	}
13789 	*iphapp = ipha;
13790 	return (B_TRUE);
13791 done:
13792 	/* clear b_prev - used by ip_mroute_decap */
13793 	mp->b_prev = NULL;
13794 	freemsg(mp);
13795 	return (B_FALSE);
13796 #undef  rptr
13797 }
13798 
13799 /*
13800  * Deal with the fact that there is no ire for the destination.
13801  * The incoming ill (in_ill) is passed in to ip_newroute only
13802  * in the case of packets coming from mobile ip forward tunnel.
13803  * It must be null otherwise.
13804  */
13805 static ire_t *
13806 ip_rput_noire(queue_t *q, ill_t *in_ill, mblk_t *mp, int ll_multicast,
13807     ipaddr_t dst)
13808 {
13809 	ipha_t	*ipha;
13810 	ill_t	*ill;
13811 	ire_t	*ire;
13812 	boolean_t	check_multirt = B_FALSE;
13813 	ip_stack_t *ipst;
13814 
13815 	ipha = (ipha_t *)mp->b_rptr;
13816 	ill = (ill_t *)q->q_ptr;
13817 
13818 	ASSERT(ill != NULL);
13819 	ipst = ill->ill_ipst;
13820 
13821 	/*
13822 	 * No IRE for this destination, so it can't be for us.
13823 	 * Unless we are forwarding, drop the packet.
13824 	 * We have to let source routed packets through
13825 	 * since we don't yet know if they are 'ping -l'
13826 	 * packets i.e. if they will go out over the
13827 	 * same interface as they came in on.
13828 	 */
13829 	if (ll_multicast) {
13830 		freemsg(mp);
13831 		return (NULL);
13832 	}
13833 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13834 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13835 		freemsg(mp);
13836 		return (NULL);
13837 	}
13838 
13839 	/*
13840 	 * Mark this packet as having originated externally.
13841 	 *
13842 	 * For non-forwarding code path, ire_send later double
13843 	 * checks this interface to see if it is still exists
13844 	 * post-ARP resolution.
13845 	 *
13846 	 * Also, IPQOS uses this to differentiate between
13847 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13848 	 * QOS packet processing in ip_wput_attach_llhdr().
13849 	 * The QoS module can mark the b_band for a fastpath message
13850 	 * or the dl_priority field in a unitdata_req header for
13851 	 * CoS marking. This info can only be found in
13852 	 * ip_wput_attach_llhdr().
13853 	 */
13854 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13855 	/*
13856 	 * Clear the indication that this may have a hardware checksum
13857 	 * as we are not using it
13858 	 */
13859 	DB_CKSUMFLAGS(mp) = 0;
13860 
13861 	if (in_ill != NULL) {
13862 		/*
13863 		 * Now hand the packet to ip_newroute.
13864 		 */
13865 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13866 		return (NULL);
13867 	}
13868 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13869 	    MBLK_GETLABEL(mp), ipst);
13870 
13871 	if (ire == NULL && check_multirt) {
13872 		/* Let ip_newroute handle CGTP  */
13873 		ip_newroute(q, mp, dst, in_ill, NULL, GLOBAL_ZONEID, ipst);
13874 		return (NULL);
13875 	}
13876 
13877 	if (ire != NULL)
13878 		return (ire);
13879 
13880 	mp->b_prev = mp->b_next = 0;
13881 	/* send icmp unreachable */
13882 	q = WR(q);
13883 	/* Sent by forwarding path, and router is global zone */
13884 	if (ip_source_routed(ipha, ipst)) {
13885 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13886 		    GLOBAL_ZONEID, ipst);
13887 	} else {
13888 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13889 		    ipst);
13890 	}
13891 
13892 	return (NULL);
13893 
13894 }
13895 
13896 /*
13897  * check ip header length and align it.
13898  */
13899 static boolean_t
13900 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13901 {
13902 	ssize_t len;
13903 	ill_t *ill;
13904 	ipha_t	*ipha;
13905 
13906 	len = MBLKL(mp);
13907 
13908 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13909 		ill = (ill_t *)q->q_ptr;
13910 
13911 		if (!OK_32PTR(mp->b_rptr))
13912 			IP_STAT(ipst, ip_notaligned1);
13913 		else
13914 			IP_STAT(ipst, ip_notaligned2);
13915 		/* Guard against bogus device drivers */
13916 		if (len < 0) {
13917 			/* clear b_prev - used by ip_mroute_decap */
13918 			mp->b_prev = NULL;
13919 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13920 			freemsg(mp);
13921 			return (B_FALSE);
13922 		}
13923 
13924 		if (ip_rput_pullups++ == 0) {
13925 			ipha = (ipha_t *)mp->b_rptr;
13926 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13927 			    "ip_check_and_align_header: %s forced us to "
13928 			    " pullup pkt, hdr len %ld, hdr addr %p",
13929 			    ill->ill_name, len, ipha);
13930 		}
13931 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13932 			/* clear b_prev - used by ip_mroute_decap */
13933 			mp->b_prev = NULL;
13934 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13935 			freemsg(mp);
13936 			return (B_FALSE);
13937 		}
13938 	}
13939 	return (B_TRUE);
13940 }
13941 
13942 ire_t *
13943 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13944 {
13945 	ire_t		*new_ire;
13946 	ill_t		*ire_ill;
13947 	uint_t		ifindex;
13948 	ip_stack_t	*ipst = ill->ill_ipst;
13949 	boolean_t	strict_check = B_FALSE;
13950 
13951 	/*
13952 	 * This packet came in on an interface other than the one associated
13953 	 * with the first ire we found for the destination address. We do
13954 	 * another ire lookup here, using the ingress ill, to see if the
13955 	 * interface is in an interface group.
13956 	 * As long as the ills belong to the same group, we don't consider
13957 	 * them to be arriving on the wrong interface. Thus, if the switch
13958 	 * is doing inbound load spreading, we won't drop packets when the
13959 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13960 	 * for 'usesrc groups' where the destination address may belong to
13961 	 * another interface to allow multipathing to happen.
13962 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13963 	 * where the local address may not be unique. In this case we were
13964 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13965 	 * actually returned. The new lookup, which is more specific, should
13966 	 * only find the IRE_LOCAL associated with the ingress ill if one
13967 	 * exists.
13968 	 */
13969 
13970 	if (ire->ire_ipversion == IPV4_VERSION) {
13971 		if (ipst->ips_ip_strict_dst_multihoming)
13972 			strict_check = B_TRUE;
13973 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13974 		    ill->ill_ipif, ALL_ZONES, NULL,
13975 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13976 	} else {
13977 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13978 		if (ipst->ips_ipv6_strict_dst_multihoming)
13979 			strict_check = B_TRUE;
13980 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13981 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13982 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13983 	}
13984 	/*
13985 	 * If the same ire that was returned in ip_input() is found then this
13986 	 * is an indication that interface groups are in use. The packet
13987 	 * arrived on a different ill in the group than the one associated with
13988 	 * the destination address.  If a different ire was found then the same
13989 	 * IP address must be hosted on multiple ills. This is possible with
13990 	 * unnumbered point2point interfaces. We switch to use this new ire in
13991 	 * order to have accurate interface statistics.
13992 	 */
13993 	if (new_ire != NULL) {
13994 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13995 			ire_refrele(ire);
13996 			ire = new_ire;
13997 		} else {
13998 			ire_refrele(new_ire);
13999 		}
14000 		return (ire);
14001 	} else if ((ire->ire_rfq == NULL) &&
14002 	    (ire->ire_ipversion == IPV4_VERSION)) {
14003 		/*
14004 		 * The best match could have been the original ire which
14005 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
14006 		 * the strict multihoming checks are irrelevant as we consider
14007 		 * local addresses hosted on lo0 to be interface agnostic. We
14008 		 * only expect a null ire_rfq on IREs which are associated with
14009 		 * lo0 hence we can return now.
14010 		 */
14011 		return (ire);
14012 	}
14013 
14014 	/*
14015 	 * Chase pointers once and store locally.
14016 	 */
14017 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
14018 	    (ill_t *)(ire->ire_rfq->q_ptr);
14019 	ifindex = ill->ill_usesrc_ifindex;
14020 
14021 	/*
14022 	 * Check if it's a legal address on the 'usesrc' interface.
14023 	 */
14024 	if ((ifindex != 0) && (ire_ill != NULL) &&
14025 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
14026 		return (ire);
14027 	}
14028 
14029 	/*
14030 	 * If the ip*_strict_dst_multihoming switch is on then we can
14031 	 * only accept this packet if the interface is marked as routing.
14032 	 */
14033 	if (!(strict_check))
14034 		return (ire);
14035 
14036 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
14037 	    ILLF_ROUTER) != 0) {
14038 		return (ire);
14039 	}
14040 
14041 	ire_refrele(ire);
14042 	return (NULL);
14043 }
14044 
14045 ire_t *
14046 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
14047 {
14048 	ipha_t	*ipha;
14049 	ipaddr_t ip_dst, ip_src;
14050 	ire_t	*src_ire = NULL;
14051 	ill_t	*stq_ill;
14052 	uint_t	hlen;
14053 	uint_t	pkt_len;
14054 	uint32_t sum;
14055 	queue_t	*dev_q;
14056 	boolean_t check_multirt = B_FALSE;
14057 	ip_stack_t *ipst = ill->ill_ipst;
14058 
14059 	ipha = (ipha_t *)mp->b_rptr;
14060 
14061 	/*
14062 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
14063 	 * The loopback address check for both src and dst has already
14064 	 * been checked in ip_input
14065 	 */
14066 	ip_dst = ntohl(dst);
14067 	ip_src = ntohl(ipha->ipha_src);
14068 
14069 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
14070 	    IN_CLASSD(ip_src)) {
14071 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14072 		goto drop;
14073 	}
14074 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14075 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14076 
14077 	if (src_ire != NULL) {
14078 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14079 		goto drop;
14080 	}
14081 
14082 
14083 	/* No ire cache of nexthop. So first create one  */
14084 	if (ire == NULL) {
14085 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
14086 		/*
14087 		 * We only come to ip_fast_forward if ip_cgtp_filter is
14088 		 * is not set. So upon return from ire_forward
14089 		 * check_multirt should remain as false.
14090 		 */
14091 		ASSERT(!check_multirt);
14092 		if (ire == NULL) {
14093 			/* An attempt was made to forward the packet */
14094 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14095 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14096 			mp->b_prev = mp->b_next = 0;
14097 			/* send icmp unreachable */
14098 			/* Sent by forwarding path, and router is global zone */
14099 			if (ip_source_routed(ipha, ipst)) {
14100 				icmp_unreachable(ill->ill_wq, mp,
14101 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
14102 				    ipst);
14103 			} else {
14104 				icmp_unreachable(ill->ill_wq, mp,
14105 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
14106 				    ipst);
14107 			}
14108 			return (ire);
14109 		}
14110 	}
14111 
14112 	/*
14113 	 * Forwarding fastpath exception case:
14114 	 * If either of the follwoing case is true, we take
14115 	 * the slowpath
14116 	 *	o forwarding is not enabled
14117 	 *	o incoming and outgoing interface are the same, or the same
14118 	 *	  IPMP group
14119 	 *	o corresponding ire is in incomplete state
14120 	 *	o packet needs fragmentation
14121 	 *
14122 	 * The codeflow from here on is thus:
14123 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14124 	 */
14125 	pkt_len = ntohs(ipha->ipha_length);
14126 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14127 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14128 	    !(ill->ill_flags & ILLF_ROUTER) ||
14129 	    (ill == stq_ill) ||
14130 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14131 	    (ire->ire_nce == NULL) ||
14132 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14133 	    (pkt_len > ire->ire_max_frag) ||
14134 	    ipha->ipha_ttl <= 1) {
14135 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14136 		    ipha, ill, B_FALSE);
14137 		return (ire);
14138 	}
14139 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14140 
14141 	DTRACE_PROBE4(ip4__forwarding__start,
14142 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14143 
14144 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14145 	    ipst->ips_ipv4firewall_forwarding,
14146 	    ill, stq_ill, ipha, mp, mp, ipst);
14147 
14148 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14149 
14150 	if (mp == NULL)
14151 		goto drop;
14152 
14153 	mp->b_datap->db_struioun.cksum.flags = 0;
14154 	/* Adjust the checksum to reflect the ttl decrement. */
14155 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14156 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14157 	ipha->ipha_ttl--;
14158 
14159 	dev_q = ire->ire_stq->q_next;
14160 	if ((dev_q->q_next != NULL ||
14161 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14162 		goto indiscard;
14163 	}
14164 
14165 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14166 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14167 
14168 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14169 		mblk_t *mpip = mp;
14170 
14171 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14172 		if (mp != NULL) {
14173 			DTRACE_PROBE4(ip4__physical__out__start,
14174 			    ill_t *, NULL, ill_t *, stq_ill,
14175 			    ipha_t *, ipha, mblk_t *, mp);
14176 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14177 			    ipst->ips_ipv4firewall_physical_out,
14178 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14179 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14180 			    mp);
14181 			if (mp == NULL)
14182 				goto drop;
14183 
14184 			UPDATE_IB_PKT_COUNT(ire);
14185 			ire->ire_last_used_time = lbolt;
14186 			BUMP_MIB(stq_ill->ill_ip_mib,
14187 			    ipIfStatsHCOutForwDatagrams);
14188 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14189 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14190 			    pkt_len);
14191 			putnext(ire->ire_stq, mp);
14192 			return (ire);
14193 		}
14194 	}
14195 
14196 indiscard:
14197 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14198 drop:
14199 	if (mp != NULL)
14200 		freemsg(mp);
14201 	if (src_ire != NULL)
14202 		ire_refrele(src_ire);
14203 	return (ire);
14204 
14205 }
14206 
14207 /*
14208  * This function is called in the forwarding slowpath, when
14209  * either the ire lacks the link-layer address, or the packet needs
14210  * further processing(eg. fragmentation), before transmission.
14211  */
14212 
14213 static void
14214 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14215     ill_t *ill, boolean_t ll_multicast)
14216 {
14217 	ill_group_t	*ill_group;
14218 	ill_group_t	*ire_group;
14219 	queue_t		*dev_q;
14220 	ire_t		*src_ire;
14221 	ip_stack_t	*ipst = ill->ill_ipst;
14222 
14223 	ASSERT(ire->ire_stq != NULL);
14224 
14225 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14226 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14227 
14228 	if (ll_multicast != 0) {
14229 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14230 		goto drop_pkt;
14231 	}
14232 
14233 	/*
14234 	 * check if ipha_src is a broadcast address. Note that this
14235 	 * check is redundant when we get here from ip_fast_forward()
14236 	 * which has already done this check. However, since we can
14237 	 * also get here from ip_rput_process_broadcast() or, for
14238 	 * for the slow path through ip_fast_forward(), we perform
14239 	 * the check again for code-reusability
14240 	 */
14241 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14242 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14243 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14244 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14245 		if (src_ire != NULL)
14246 			ire_refrele(src_ire);
14247 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14248 		ip2dbg(("ip_rput_process_forward: Received packet with"
14249 		    " bad src/dst address on %s\n", ill->ill_name));
14250 		goto drop_pkt;
14251 	}
14252 
14253 	ill_group = ill->ill_group;
14254 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14255 	/*
14256 	 * Check if we want to forward this one at this time.
14257 	 * We allow source routed packets on a host provided that
14258 	 * they go out the same interface or same interface group
14259 	 * as they came in on.
14260 	 *
14261 	 * XXX To be quicker, we may wish to not chase pointers to
14262 	 * get the ILLF_ROUTER flag and instead store the
14263 	 * forwarding policy in the ire.  An unfortunate
14264 	 * side-effect of that would be requiring an ire flush
14265 	 * whenever the ILLF_ROUTER flag changes.
14266 	 */
14267 	if (((ill->ill_flags &
14268 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14269 	    ILLF_ROUTER) == 0) &&
14270 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14271 	    (ill_group != NULL && ill_group == ire_group)))) {
14272 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14273 		if (ip_source_routed(ipha, ipst)) {
14274 			q = WR(q);
14275 			/*
14276 			 * Clear the indication that this may have
14277 			 * hardware checksum as we are not using it.
14278 			 */
14279 			DB_CKSUMFLAGS(mp) = 0;
14280 			/* Sent by forwarding path, and router is global zone */
14281 			icmp_unreachable(q, mp,
14282 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14283 			return;
14284 		}
14285 		goto drop_pkt;
14286 	}
14287 
14288 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14289 
14290 	/* Packet is being forwarded. Turning off hwcksum flag. */
14291 	DB_CKSUMFLAGS(mp) = 0;
14292 	if (ipst->ips_ip_g_send_redirects) {
14293 		/*
14294 		 * Check whether the incoming interface and outgoing
14295 		 * interface is part of the same group. If so,
14296 		 * send redirects.
14297 		 *
14298 		 * Check the source address to see if it originated
14299 		 * on the same logical subnet it is going back out on.
14300 		 * If so, we should be able to send it a redirect.
14301 		 * Avoid sending a redirect if the destination
14302 		 * is directly connected (i.e., ipha_dst is the same
14303 		 * as ire_gateway_addr or the ire_addr of the
14304 		 * nexthop IRE_CACHE ), or if the packet was source
14305 		 * routed out this interface.
14306 		 */
14307 		ipaddr_t src, nhop;
14308 		mblk_t	*mp1;
14309 		ire_t	*nhop_ire = NULL;
14310 
14311 		/*
14312 		 * Check whether ire_rfq and q are from the same ill
14313 		 * or if they are not same, they at least belong
14314 		 * to the same group. If so, send redirects.
14315 		 */
14316 		if ((ire->ire_rfq == q ||
14317 		    (ill_group != NULL && ill_group == ire_group)) &&
14318 		    !ip_source_routed(ipha, ipst)) {
14319 
14320 			nhop = (ire->ire_gateway_addr != 0 ?
14321 			    ire->ire_gateway_addr : ire->ire_addr);
14322 
14323 			if (ipha->ipha_dst == nhop) {
14324 				/*
14325 				 * We avoid sending a redirect if the
14326 				 * destination is directly connected
14327 				 * because it is possible that multiple
14328 				 * IP subnets may have been configured on
14329 				 * the link, and the source may not
14330 				 * be on the same subnet as ip destination,
14331 				 * even though they are on the same
14332 				 * physical link.
14333 				 */
14334 				goto sendit;
14335 			}
14336 
14337 			src = ipha->ipha_src;
14338 
14339 			/*
14340 			 * We look up the interface ire for the nexthop,
14341 			 * to see if ipha_src is in the same subnet
14342 			 * as the nexthop.
14343 			 *
14344 			 * Note that, if, in the future, IRE_CACHE entries
14345 			 * are obsoleted,  this lookup will not be needed,
14346 			 * as the ire passed to this function will be the
14347 			 * same as the nhop_ire computed below.
14348 			 */
14349 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14350 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14351 			    0, NULL, MATCH_IRE_TYPE, ipst);
14352 
14353 			if (nhop_ire != NULL) {
14354 				if ((src & nhop_ire->ire_mask) ==
14355 				    (nhop & nhop_ire->ire_mask)) {
14356 					/*
14357 					 * The source is directly connected.
14358 					 * Just copy the ip header (which is
14359 					 * in the first mblk)
14360 					 */
14361 					mp1 = copyb(mp);
14362 					if (mp1 != NULL) {
14363 						icmp_send_redirect(WR(q), mp1,
14364 						    nhop, ipst);
14365 					}
14366 				}
14367 				ire_refrele(nhop_ire);
14368 			}
14369 		}
14370 	}
14371 sendit:
14372 	dev_q = ire->ire_stq->q_next;
14373 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14374 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14375 		freemsg(mp);
14376 		return;
14377 	}
14378 
14379 	ip_rput_forward(ire, ipha, mp, ill);
14380 	return;
14381 
14382 drop_pkt:
14383 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14384 	freemsg(mp);
14385 }
14386 
14387 ire_t *
14388 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14389     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14390 {
14391 	queue_t		*q;
14392 	uint16_t	hcksumflags;
14393 	ip_stack_t	*ipst = ill->ill_ipst;
14394 
14395 	q = *qp;
14396 
14397 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14398 
14399 	/*
14400 	 * Clear the indication that this may have hardware
14401 	 * checksum as we are not using it for forwarding.
14402 	 */
14403 	hcksumflags = DB_CKSUMFLAGS(mp);
14404 	DB_CKSUMFLAGS(mp) = 0;
14405 
14406 	/*
14407 	 * Directed broadcast forwarding: if the packet came in over a
14408 	 * different interface then it is routed out over we can forward it.
14409 	 */
14410 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14411 		ire_refrele(ire);
14412 		freemsg(mp);
14413 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14414 		return (NULL);
14415 	}
14416 	/*
14417 	 * For multicast we have set dst to be INADDR_BROADCAST
14418 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14419 	 * only for broadcast packets.
14420 	 */
14421 	if (!CLASSD(ipha->ipha_dst)) {
14422 		ire_t *new_ire;
14423 		ipif_t *ipif;
14424 		/*
14425 		 * For ill groups, as the switch duplicates broadcasts
14426 		 * across all the ports, we need to filter out and
14427 		 * send up only one copy. There is one copy for every
14428 		 * broadcast address on each ill. Thus, we look for a
14429 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14430 		 * later to see whether this ill is eligible to receive
14431 		 * them or not. ill_nominate_bcast_rcv() nominates only
14432 		 * one set of IREs for receiving.
14433 		 */
14434 
14435 		ipif = ipif_get_next_ipif(NULL, ill);
14436 		if (ipif == NULL) {
14437 			ire_refrele(ire);
14438 			freemsg(mp);
14439 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14440 			return (NULL);
14441 		}
14442 		new_ire = ire_ctable_lookup(dst, 0, 0,
14443 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14444 		ipif_refrele(ipif);
14445 
14446 		if (new_ire != NULL) {
14447 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14448 				ire_refrele(ire);
14449 				ire_refrele(new_ire);
14450 				freemsg(mp);
14451 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14452 				return (NULL);
14453 			}
14454 			/*
14455 			 * In the special case of multirouted broadcast
14456 			 * packets, we unconditionally need to "gateway"
14457 			 * them to the appropriate interface here.
14458 			 * In the normal case, this cannot happen, because
14459 			 * there is no broadcast IRE tagged with the
14460 			 * RTF_MULTIRT flag.
14461 			 */
14462 			if (new_ire->ire_flags & RTF_MULTIRT) {
14463 				ire_refrele(new_ire);
14464 				if (ire->ire_rfq != NULL) {
14465 					q = ire->ire_rfq;
14466 					*qp = q;
14467 				}
14468 			} else {
14469 				ire_refrele(ire);
14470 				ire = new_ire;
14471 			}
14472 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14473 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14474 				/*
14475 				 * Free the message if
14476 				 * ip_g_forward_directed_bcast is turned
14477 				 * off for non-local broadcast.
14478 				 */
14479 				ire_refrele(ire);
14480 				freemsg(mp);
14481 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14482 				return (NULL);
14483 			}
14484 		} else {
14485 			/*
14486 			 * This CGTP packet successfully passed the
14487 			 * CGTP filter, but the related CGTP
14488 			 * broadcast IRE has not been found,
14489 			 * meaning that the redundant ipif is
14490 			 * probably down. However, if we discarded
14491 			 * this packet, its duplicate would be
14492 			 * filtered out by the CGTP filter so none
14493 			 * of them would get through. So we keep
14494 			 * going with this one.
14495 			 */
14496 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14497 			if (ire->ire_rfq != NULL) {
14498 				q = ire->ire_rfq;
14499 				*qp = q;
14500 			}
14501 		}
14502 	}
14503 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14504 		/*
14505 		 * Verify that there are not more then one
14506 		 * IRE_BROADCAST with this broadcast address which
14507 		 * has ire_stq set.
14508 		 * TODO: simplify, loop over all IRE's
14509 		 */
14510 		ire_t	*ire1;
14511 		int	num_stq = 0;
14512 		mblk_t	*mp1;
14513 
14514 		/* Find the first one with ire_stq set */
14515 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14516 		for (ire1 = ire; ire1 &&
14517 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14518 		    ire1 = ire1->ire_next)
14519 			;
14520 		if (ire1) {
14521 			ire_refrele(ire);
14522 			ire = ire1;
14523 			IRE_REFHOLD(ire);
14524 		}
14525 
14526 		/* Check if there are additional ones with stq set */
14527 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14528 			if (ire->ire_addr != ire1->ire_addr)
14529 				break;
14530 			if (ire1->ire_stq) {
14531 				num_stq++;
14532 				break;
14533 			}
14534 		}
14535 		rw_exit(&ire->ire_bucket->irb_lock);
14536 		if (num_stq == 1 && ire->ire_stq != NULL) {
14537 			ip1dbg(("ip_rput_process_broadcast: directed "
14538 			    "broadcast to 0x%x\n",
14539 			    ntohl(ire->ire_addr)));
14540 			mp1 = copymsg(mp);
14541 			if (mp1) {
14542 				switch (ipha->ipha_protocol) {
14543 				case IPPROTO_UDP:
14544 					ip_udp_input(q, mp1, ipha, ire, ill);
14545 					break;
14546 				default:
14547 					ip_proto_input(q, mp1, ipha, ire, ill);
14548 					break;
14549 				}
14550 			}
14551 			/*
14552 			 * Adjust ttl to 2 (1+1 - the forward engine
14553 			 * will decrement it by one.
14554 			 */
14555 			if (ip_csum_hdr(ipha)) {
14556 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14557 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14558 				freemsg(mp);
14559 				ire_refrele(ire);
14560 				return (NULL);
14561 			}
14562 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14563 			ipha->ipha_hdr_checksum = 0;
14564 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14565 			ip_rput_process_forward(q, mp, ire, ipha,
14566 			    ill, ll_multicast);
14567 			ire_refrele(ire);
14568 			return (NULL);
14569 		}
14570 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14571 		    ntohl(ire->ire_addr)));
14572 	}
14573 
14574 
14575 	/* Restore any hardware checksum flags */
14576 	DB_CKSUMFLAGS(mp) = hcksumflags;
14577 	return (ire);
14578 }
14579 
14580 /* ARGSUSED */
14581 static boolean_t
14582 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14583     int *ll_multicast, ipaddr_t *dstp)
14584 {
14585 	ip_stack_t	*ipst = ill->ill_ipst;
14586 
14587 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14588 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14589 	    ntohs(ipha->ipha_length));
14590 
14591 	/*
14592 	 * Forward packets only if we have joined the allmulti
14593 	 * group on this interface.
14594 	 */
14595 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14596 		int retval;
14597 
14598 		/*
14599 		 * Clear the indication that this may have hardware
14600 		 * checksum as we are not using it.
14601 		 */
14602 		DB_CKSUMFLAGS(mp) = 0;
14603 		retval = ip_mforward(ill, ipha, mp);
14604 		/* ip_mforward updates mib variables if needed */
14605 		/* clear b_prev - used by ip_mroute_decap */
14606 		mp->b_prev = NULL;
14607 
14608 		switch (retval) {
14609 		case 0:
14610 			/*
14611 			 * pkt is okay and arrived on phyint.
14612 			 *
14613 			 * If we are running as a multicast router
14614 			 * we need to see all IGMP and/or PIM packets.
14615 			 */
14616 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14617 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14618 				goto done;
14619 			}
14620 			break;
14621 		case -1:
14622 			/* pkt is mal-formed, toss it */
14623 			goto drop_pkt;
14624 		case 1:
14625 			/* pkt is okay and arrived on a tunnel */
14626 			/*
14627 			 * If we are running a multicast router
14628 			 *  we need to see all igmp packets.
14629 			 */
14630 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14631 				*dstp = INADDR_BROADCAST;
14632 				*ll_multicast = 1;
14633 				return (B_FALSE);
14634 			}
14635 
14636 			goto drop_pkt;
14637 		}
14638 	}
14639 
14640 	ILM_WALKER_HOLD(ill);
14641 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14642 		/*
14643 		 * This might just be caused by the fact that
14644 		 * multiple IP Multicast addresses map to the same
14645 		 * link layer multicast - no need to increment counter!
14646 		 */
14647 		ILM_WALKER_RELE(ill);
14648 		freemsg(mp);
14649 		return (B_TRUE);
14650 	}
14651 	ILM_WALKER_RELE(ill);
14652 done:
14653 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14654 	/*
14655 	 * This assumes the we deliver to all streams for multicast
14656 	 * and broadcast packets.
14657 	 */
14658 	*dstp = INADDR_BROADCAST;
14659 	*ll_multicast = 1;
14660 	return (B_FALSE);
14661 drop_pkt:
14662 	ip2dbg(("ip_rput: drop pkt\n"));
14663 	freemsg(mp);
14664 	return (B_TRUE);
14665 }
14666 
14667 static boolean_t
14668 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14669     int *ll_multicast, mblk_t **mpp)
14670 {
14671 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14672 	boolean_t must_copy = B_FALSE;
14673 	struct iocblk   *iocp;
14674 	ipha_t		*ipha;
14675 	ip_stack_t	*ipst = ill->ill_ipst;
14676 
14677 #define	rptr    ((uchar_t *)ipha)
14678 
14679 	first_mp = *first_mpp;
14680 	mp = *mpp;
14681 
14682 	ASSERT(first_mp == mp);
14683 
14684 	/*
14685 	 * if db_ref > 1 then copymsg and free original. Packet may be
14686 	 * changed and do not want other entity who has a reference to this
14687 	 * message to trip over the changes. This is a blind change because
14688 	 * trying to catch all places that might change packet is too
14689 	 * difficult (since it may be a module above this one)
14690 	 *
14691 	 * This corresponds to the non-fast path case. We walk down the full
14692 	 * chain in this case, and check the db_ref count of all the dblks,
14693 	 * and do a copymsg if required. It is possible that the db_ref counts
14694 	 * of the data blocks in the mblk chain can be different.
14695 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14696 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14697 	 * 'snoop' is running.
14698 	 */
14699 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14700 		if (mp1->b_datap->db_ref > 1) {
14701 			must_copy = B_TRUE;
14702 			break;
14703 		}
14704 	}
14705 
14706 	if (must_copy) {
14707 		mp1 = copymsg(mp);
14708 		if (mp1 == NULL) {
14709 			for (mp1 = mp; mp1 != NULL;
14710 			    mp1 = mp1->b_cont) {
14711 				mp1->b_next = NULL;
14712 				mp1->b_prev = NULL;
14713 			}
14714 			freemsg(mp);
14715 			if (ill != NULL) {
14716 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14717 			} else {
14718 				BUMP_MIB(&ipst->ips_ip_mib,
14719 				    ipIfStatsInDiscards);
14720 			}
14721 			return (B_TRUE);
14722 		}
14723 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14724 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14725 			/* Copy b_prev - used by ip_mroute_decap */
14726 			to_mp->b_prev = from_mp->b_prev;
14727 			from_mp->b_prev = NULL;
14728 		}
14729 		*first_mpp = first_mp = mp1;
14730 		freemsg(mp);
14731 		mp = mp1;
14732 		*mpp = mp1;
14733 	}
14734 
14735 	ipha = (ipha_t *)mp->b_rptr;
14736 
14737 	/*
14738 	 * previous code has a case for M_DATA.
14739 	 * We want to check how that happens.
14740 	 */
14741 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14742 	switch (first_mp->b_datap->db_type) {
14743 	case M_PROTO:
14744 	case M_PCPROTO:
14745 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14746 		    DL_UNITDATA_IND) {
14747 			/* Go handle anything other than data elsewhere. */
14748 			ip_rput_dlpi(q, mp);
14749 			return (B_TRUE);
14750 		}
14751 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14752 		/* Ditch the DLPI header. */
14753 		mp1 = mp->b_cont;
14754 		ASSERT(first_mp == mp);
14755 		*first_mpp = mp1;
14756 		freeb(mp);
14757 		*mpp = mp1;
14758 		return (B_FALSE);
14759 	case M_IOCACK:
14760 		ip1dbg(("got iocack "));
14761 		iocp = (struct iocblk *)mp->b_rptr;
14762 		switch (iocp->ioc_cmd) {
14763 		case DL_IOC_HDR_INFO:
14764 			ill = (ill_t *)q->q_ptr;
14765 			ill_fastpath_ack(ill, mp);
14766 			return (B_TRUE);
14767 		case SIOCSTUNPARAM:
14768 		case OSIOCSTUNPARAM:
14769 			/* Go through qwriter_ip */
14770 			break;
14771 		case SIOCGTUNPARAM:
14772 		case OSIOCGTUNPARAM:
14773 			ip_rput_other(NULL, q, mp, NULL);
14774 			return (B_TRUE);
14775 		default:
14776 			putnext(q, mp);
14777 			return (B_TRUE);
14778 		}
14779 		/* FALLTHRU */
14780 	case M_ERROR:
14781 	case M_HANGUP:
14782 		/*
14783 		 * Since this is on the ill stream we unconditionally
14784 		 * bump up the refcount
14785 		 */
14786 		ill_refhold(ill);
14787 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14788 		return (B_TRUE);
14789 	case M_CTL:
14790 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14791 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14792 		    IPHADA_M_CTL)) {
14793 			/*
14794 			 * It's an IPsec accelerated packet.
14795 			 * Make sure that the ill from which we received the
14796 			 * packet has enabled IPsec hardware acceleration.
14797 			 */
14798 			if (!(ill->ill_capabilities &
14799 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14800 				/* IPsec kstats: bean counter */
14801 				freemsg(mp);
14802 				return (B_TRUE);
14803 			}
14804 
14805 			/*
14806 			 * Make mp point to the mblk following the M_CTL,
14807 			 * then process according to type of mp.
14808 			 * After this processing, first_mp will point to
14809 			 * the data-attributes and mp to the pkt following
14810 			 * the M_CTL.
14811 			 */
14812 			mp = first_mp->b_cont;
14813 			if (mp == NULL) {
14814 				freemsg(first_mp);
14815 				return (B_TRUE);
14816 			}
14817 			/*
14818 			 * A Hardware Accelerated packet can only be M_DATA
14819 			 * ESP or AH packet.
14820 			 */
14821 			if (mp->b_datap->db_type != M_DATA) {
14822 				/* non-M_DATA IPsec accelerated packet */
14823 				IPSECHW_DEBUG(IPSECHW_PKT,
14824 				    ("non-M_DATA IPsec accelerated pkt\n"));
14825 				freemsg(first_mp);
14826 				return (B_TRUE);
14827 			}
14828 			ipha = (ipha_t *)mp->b_rptr;
14829 			if (ipha->ipha_protocol != IPPROTO_AH &&
14830 			    ipha->ipha_protocol != IPPROTO_ESP) {
14831 				IPSECHW_DEBUG(IPSECHW_PKT,
14832 				    ("non-M_DATA IPsec accelerated pkt\n"));
14833 				freemsg(first_mp);
14834 				return (B_TRUE);
14835 			}
14836 			*mpp = mp;
14837 			return (B_FALSE);
14838 		}
14839 		putnext(q, mp);
14840 		return (B_TRUE);
14841 	case M_IOCNAK:
14842 		ip1dbg(("got iocnak "));
14843 		iocp = (struct iocblk *)mp->b_rptr;
14844 		switch (iocp->ioc_cmd) {
14845 		case SIOCSTUNPARAM:
14846 		case OSIOCSTUNPARAM:
14847 			/*
14848 			 * Since this is on the ill stream we unconditionally
14849 			 * bump up the refcount
14850 			 */
14851 			ill_refhold(ill);
14852 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14853 			return (B_TRUE);
14854 		case DL_IOC_HDR_INFO:
14855 		case SIOCGTUNPARAM:
14856 		case OSIOCGTUNPARAM:
14857 			ip_rput_other(NULL, q, mp, NULL);
14858 			return (B_TRUE);
14859 		default:
14860 			break;
14861 		}
14862 		/* FALLTHRU */
14863 	default:
14864 		putnext(q, mp);
14865 		return (B_TRUE);
14866 	}
14867 }
14868 
14869 /* Read side put procedure.  Packets coming from the wire arrive here. */
14870 void
14871 ip_rput(queue_t *q, mblk_t *mp)
14872 {
14873 	ill_t		*ill = (ill_t *)q->q_ptr;
14874 	ip_stack_t	*ipst = ill->ill_ipst;
14875 	union DL_primitives *dl;
14876 
14877 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14878 
14879 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14880 		/*
14881 		 * If things are opening or closing, only accept high-priority
14882 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14883 		 * created; on close, things hanging off the ill may have been
14884 		 * freed already.)
14885 		 */
14886 		dl = (union DL_primitives *)mp->b_rptr;
14887 		if (DB_TYPE(mp) != M_PCPROTO ||
14888 		    dl->dl_primitive == DL_UNITDATA_IND) {
14889 			/*
14890 			 * SIOC[GS]TUNPARAM ioctls can come here.
14891 			 */
14892 			inet_freemsg(mp);
14893 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14894 			    "ip_rput_end: q %p (%S)", q, "uninit");
14895 			return;
14896 		}
14897 	}
14898 
14899 	/*
14900 	 * if db_ref > 1 then copymsg and free original. Packet may be
14901 	 * changed and we do not want the other entity who has a reference to
14902 	 * this message to trip over the changes. This is a blind change because
14903 	 * trying to catch all places that might change the packet is too
14904 	 * difficult.
14905 	 *
14906 	 * This corresponds to the fast path case, where we have a chain of
14907 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14908 	 * in the mblk chain. There doesn't seem to be a reason why a device
14909 	 * driver would send up data with varying db_ref counts in the mblk
14910 	 * chain. In any case the Fast path is a private interface, and our
14911 	 * drivers don't do such a thing. Given the above assumption, there is
14912 	 * no need to walk down the entire mblk chain (which could have a
14913 	 * potential performance problem)
14914 	 */
14915 	if (mp->b_datap->db_ref > 1) {
14916 		mblk_t  *mp1;
14917 		boolean_t adjusted = B_FALSE;
14918 		IP_STAT(ipst, ip_db_ref);
14919 
14920 		/*
14921 		 * The IP_RECVSLLA option depends on having the link layer
14922 		 * header. First check that:
14923 		 * a> the underlying device is of type ether, since this
14924 		 * option is currently supported only over ethernet.
14925 		 * b> there is enough room to copy over the link layer header.
14926 		 *
14927 		 * Once the checks are done, adjust rptr so that the link layer
14928 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14929 		 * be returned by some non-ethernet drivers but in this case the
14930 		 * second check will fail.
14931 		 */
14932 		if (ill->ill_type == IFT_ETHER &&
14933 		    (mp->b_rptr - mp->b_datap->db_base) >=
14934 		    sizeof (struct ether_header)) {
14935 			mp->b_rptr -= sizeof (struct ether_header);
14936 			adjusted = B_TRUE;
14937 		}
14938 		mp1 = copymsg(mp);
14939 		if (mp1 == NULL) {
14940 			mp->b_next = NULL;
14941 			/* clear b_prev - used by ip_mroute_decap */
14942 			mp->b_prev = NULL;
14943 			freemsg(mp);
14944 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14945 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14946 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14947 			return;
14948 		}
14949 		if (adjusted) {
14950 			/*
14951 			 * Copy is done. Restore the pointer in the _new_ mblk
14952 			 */
14953 			mp1->b_rptr += sizeof (struct ether_header);
14954 		}
14955 		/* Copy b_prev - used by ip_mroute_decap */
14956 		mp1->b_prev = mp->b_prev;
14957 		mp->b_prev = NULL;
14958 		freemsg(mp);
14959 		mp = mp1;
14960 	}
14961 
14962 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14963 	    "ip_rput_end: q %p (%S)", q, "end");
14964 
14965 	ip_input(ill, NULL, mp, NULL);
14966 }
14967 
14968 /*
14969  * Direct read side procedure capable of dealing with chains. GLDv3 based
14970  * drivers call this function directly with mblk chains while STREAMS
14971  * read side procedure ip_rput() calls this for single packet with ip_ring
14972  * set to NULL to process one packet at a time.
14973  *
14974  * The ill will always be valid if this function is called directly from
14975  * the driver.
14976  *
14977  * If ip_input() is called from GLDv3:
14978  *
14979  *   - This must be a non-VLAN IP stream.
14980  *   - 'mp' is either an untagged or a special priority-tagged packet.
14981  *   - Any VLAN tag that was in the MAC header has been stripped.
14982  *
14983  * If the IP header in packet is not 32-bit aligned, every message in the
14984  * chain will be aligned before further operations. This is required on SPARC
14985  * platform.
14986  */
14987 /* ARGSUSED */
14988 void
14989 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14990     struct mac_header_info_s *mhip)
14991 {
14992 	ipaddr_t		dst = NULL;
14993 	ipaddr_t		prev_dst;
14994 	ire_t			*ire = NULL;
14995 	ipha_t			*ipha;
14996 	uint_t			pkt_len;
14997 	ssize_t			len;
14998 	uint_t			opt_len;
14999 	int			ll_multicast;
15000 	int			cgtp_flt_pkt;
15001 	queue_t			*q = ill->ill_rq;
15002 	squeue_t		*curr_sqp = NULL;
15003 	mblk_t 			*head = NULL;
15004 	mblk_t			*tail = NULL;
15005 	mblk_t			*first_mp;
15006 	mblk_t 			*mp;
15007 	mblk_t			*dmp;
15008 	int			cnt = 0;
15009 	ip_stack_t		*ipst = ill->ill_ipst;
15010 
15011 	ASSERT(mp_chain != NULL);
15012 	ASSERT(ill != NULL);
15013 
15014 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
15015 
15016 #define	rptr	((uchar_t *)ipha)
15017 
15018 	while (mp_chain != NULL) {
15019 		first_mp = mp = mp_chain;
15020 		mp_chain = mp_chain->b_next;
15021 		mp->b_next = NULL;
15022 		ll_multicast = 0;
15023 
15024 		/*
15025 		 * We do ire caching from one iteration to
15026 		 * another. In the event the packet chain contains
15027 		 * all packets from the same dst, this caching saves
15028 		 * an ire_cache_lookup for each of the succeeding
15029 		 * packets in a packet chain.
15030 		 */
15031 		prev_dst = dst;
15032 
15033 		/*
15034 		 * Check and align the IP header.
15035 		 */
15036 		if (DB_TYPE(mp) == M_DATA) {
15037 			dmp = mp;
15038 		} else if (DB_TYPE(mp) == M_PROTO &&
15039 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
15040 			dmp = mp->b_cont;
15041 		} else {
15042 			dmp = NULL;
15043 		}
15044 		if (dmp != NULL) {
15045 			/*
15046 			 * IP header ptr not aligned?
15047 			 * OR IP header not complete in first mblk
15048 			 */
15049 			if (!OK_32PTR(dmp->b_rptr) ||
15050 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15051 				if (!ip_check_and_align_header(q, dmp, ipst))
15052 					continue;
15053 			}
15054 		}
15055 
15056 		/*
15057 		 * ip_input fast path
15058 		 */
15059 
15060 		/* mblk type is not M_DATA */
15061 		if (DB_TYPE(mp) != M_DATA) {
15062 			if (ip_rput_process_notdata(q, &first_mp, ill,
15063 			    &ll_multicast, &mp))
15064 				continue;
15065 		}
15066 
15067 		/* Make sure its an M_DATA and that its aligned */
15068 		ASSERT(DB_TYPE(mp) == M_DATA);
15069 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15070 
15071 		ipha = (ipha_t *)mp->b_rptr;
15072 		len = mp->b_wptr - rptr;
15073 		pkt_len = ntohs(ipha->ipha_length);
15074 
15075 		/*
15076 		 * We must count all incoming packets, even if they end
15077 		 * up being dropped later on.
15078 		 */
15079 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15080 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15081 
15082 		/* multiple mblk or too short */
15083 		len -= pkt_len;
15084 		if (len != 0) {
15085 			/*
15086 			 * Make sure we have data length consistent
15087 			 * with the IP header.
15088 			 */
15089 			if (mp->b_cont == NULL) {
15090 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15091 					BUMP_MIB(ill->ill_ip_mib,
15092 					    ipIfStatsInHdrErrors);
15093 					ip2dbg(("ip_input: drop pkt\n"));
15094 					freemsg(mp);
15095 					continue;
15096 				}
15097 				mp->b_wptr = rptr + pkt_len;
15098 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15099 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15100 					BUMP_MIB(ill->ill_ip_mib,
15101 					    ipIfStatsInHdrErrors);
15102 					ip2dbg(("ip_input: drop pkt\n"));
15103 					freemsg(mp);
15104 					continue;
15105 				}
15106 				(void) adjmsg(mp, -len);
15107 				IP_STAT(ipst, ip_multimblk3);
15108 			}
15109 		}
15110 
15111 		/* Obtain the dst of the current packet */
15112 		dst = ipha->ipha_dst;
15113 
15114 		if (IP_LOOPBACK_ADDR(dst) ||
15115 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15116 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15117 			cmn_err(CE_CONT, "dst %X src %X\n",
15118 			    dst, ipha->ipha_src);
15119 			freemsg(mp);
15120 			continue;
15121 		}
15122 
15123 		/*
15124 		 * The event for packets being received from a 'physical'
15125 		 * interface is placed after validation of the source and/or
15126 		 * destination address as being local so that packets can be
15127 		 * redirected to loopback addresses using ipnat.
15128 		 */
15129 		DTRACE_PROBE4(ip4__physical__in__start,
15130 		    ill_t *, ill, ill_t *, NULL,
15131 		    ipha_t *, ipha, mblk_t *, first_mp);
15132 
15133 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15134 		    ipst->ips_ipv4firewall_physical_in,
15135 		    ill, NULL, ipha, first_mp, mp, ipst);
15136 
15137 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15138 
15139 		if (first_mp == NULL) {
15140 			continue;
15141 		}
15142 		dst = ipha->ipha_dst;
15143 
15144 		/*
15145 		 * Attach any necessary label information to
15146 		 * this packet
15147 		 */
15148 		if (is_system_labeled() &&
15149 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15150 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15151 			freemsg(mp);
15152 			continue;
15153 		}
15154 
15155 		/*
15156 		 * Reuse the cached ire only if the ipha_dst of the previous
15157 		 * packet is the same as the current packet AND it is not
15158 		 * INADDR_ANY.
15159 		 */
15160 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15161 		    (ire != NULL)) {
15162 			ire_refrele(ire);
15163 			ire = NULL;
15164 		}
15165 		opt_len = ipha->ipha_version_and_hdr_length -
15166 		    IP_SIMPLE_HDR_VERSION;
15167 
15168 		/*
15169 		 * Check to see if we can take the fastpath.
15170 		 * That is possible if the following conditions are met
15171 		 *	o Tsol disabled
15172 		 *	o CGTP disabled
15173 		 *	o ipp_action_count is 0
15174 		 *	o Mobile IP not running
15175 		 *	o no options in the packet
15176 		 *	o not a RSVP packet
15177 		 * 	o not a multicast packet
15178 		 */
15179 		if (!is_system_labeled() &&
15180 		    !ip_cgtp_filter && ipp_action_count == 0 &&
15181 		    ill->ill_mrtun_refcnt == 0 && ill->ill_srcif_refcnt == 0 &&
15182 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15183 		    !ll_multicast && !CLASSD(dst)) {
15184 			if (ire == NULL)
15185 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15186 				    ipst);
15187 
15188 			/* incoming packet is for forwarding */
15189 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15190 				ire = ip_fast_forward(ire, dst, ill, mp);
15191 				continue;
15192 			}
15193 			/* incoming packet is for local consumption */
15194 			if (ire->ire_type & IRE_LOCAL)
15195 				goto local;
15196 		}
15197 
15198 		/*
15199 		 * Disable ire caching for anything more complex
15200 		 * than the simple fast path case we checked for above.
15201 		 */
15202 		if (ire != NULL) {
15203 			ire_refrele(ire);
15204 			ire = NULL;
15205 		}
15206 
15207 		/* Full-blown slow path */
15208 		if (opt_len != 0) {
15209 			if (len != 0)
15210 				IP_STAT(ipst, ip_multimblk4);
15211 			else
15212 				IP_STAT(ipst, ip_ipoptions);
15213 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15214 			    &dst, ipst))
15215 				continue;
15216 		}
15217 
15218 		/*
15219 		 * Invoke the CGTP (multirouting) filtering module to process
15220 		 * the incoming packet. Packets identified as duplicates
15221 		 * must be discarded. Filtering is active only if the
15222 		 * the ip_cgtp_filter ndd variable is non-zero.
15223 		 *
15224 		 * Only applies to the shared stack since the filter_ops
15225 		 * do not carry an ip_stack_t or zoneid.
15226 		 */
15227 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15228 		if (ip_cgtp_filter && (ip_cgtp_filter_ops != NULL) &&
15229 		    ipst->ips_netstack->netstack_stackid == GLOBAL_NETSTACKID) {
15230 			cgtp_flt_pkt =
15231 			    ip_cgtp_filter_ops->cfo_filter(q, mp);
15232 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15233 				freemsg(first_mp);
15234 				continue;
15235 			}
15236 		}
15237 
15238 		/*
15239 		 * If rsvpd is running, let RSVP daemon handle its processing
15240 		 * and forwarding of RSVP multicast/unicast packets.
15241 		 * If rsvpd is not running but mrouted is running, RSVP
15242 		 * multicast packets are forwarded as multicast traffic
15243 		 * and RSVP unicast packets are forwarded by unicast router.
15244 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15245 		 * packets are not forwarded, but the unicast packets are
15246 		 * forwarded like unicast traffic.
15247 		 */
15248 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15249 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15250 		    NULL) {
15251 			/* RSVP packet and rsvpd running. Treat as ours */
15252 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15253 			/*
15254 			 * This assumes that we deliver to all streams for
15255 			 * multicast and broadcast packets.
15256 			 * We have to force ll_multicast to 1 to handle the
15257 			 * M_DATA messages passed in from ip_mroute_decap.
15258 			 */
15259 			dst = INADDR_BROADCAST;
15260 			ll_multicast = 1;
15261 		} else if (CLASSD(dst)) {
15262 			/* packet is multicast */
15263 			mp->b_next = NULL;
15264 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15265 			    &ll_multicast, &dst))
15266 				continue;
15267 		}
15268 
15269 
15270 		/*
15271 		 * Check if the packet is coming from the Mobile IP
15272 		 * forward tunnel interface
15273 		 */
15274 		if (ill->ill_srcif_refcnt > 0) {
15275 			ire = ire_srcif_table_lookup(dst, IRE_INTERFACE,
15276 			    NULL, ill, MATCH_IRE_TYPE);
15277 			if (ire != NULL && ire->ire_nce->nce_res_mp == NULL &&
15278 			    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER) {
15279 
15280 				/* We need to resolve the link layer info */
15281 				ire_refrele(ire);
15282 				ire = NULL;
15283 				(void) ip_rput_noire(q, (ill_t *)q->q_ptr, mp,
15284 				    ll_multicast, dst);
15285 				continue;
15286 			}
15287 		}
15288 
15289 		if (ire == NULL) {
15290 			ire = ire_cache_lookup(dst, ALL_ZONES,
15291 			    MBLK_GETLABEL(mp), ipst);
15292 		}
15293 
15294 		/*
15295 		 * If mipagent is running and reverse tunnel is created as per
15296 		 * mobile node request, then any packet coming through the
15297 		 * incoming interface from the mobile-node, should be reverse
15298 		 * tunneled to it's home agent except those that are destined
15299 		 * to foreign agent only.
15300 		 * This needs source address based ire lookup. The routing
15301 		 * entries for source address based lookup are only created by
15302 		 * mipagent program only when a reverse tunnel is created.
15303 		 * Reference : RFC2002, RFC2344
15304 		 */
15305 		if (ill->ill_mrtun_refcnt > 0) {
15306 			ipaddr_t	srcaddr;
15307 			ire_t		*tmp_ire;
15308 
15309 			tmp_ire = ire;	/* Save, we might need it later */
15310 			if (ire == NULL || (ire->ire_type != IRE_LOCAL &&
15311 			    ire->ire_type != IRE_BROADCAST)) {
15312 				srcaddr = ipha->ipha_src;
15313 				ire = ire_mrtun_lookup(srcaddr, ill);
15314 				if (ire != NULL) {
15315 					/*
15316 					 * Should not be getting iphada packet
15317 					 * here. we should only get those for
15318 					 * IRE_LOCAL traffic, excluded above.
15319 					 * Fail-safe (drop packet) in the event
15320 					 * hardware is misbehaving.
15321 					 */
15322 					if (first_mp != mp) {
15323 						/* IPsec KSTATS: beancount me */
15324 						freemsg(first_mp);
15325 					} else {
15326 						/*
15327 						 * This packet must be forwarded
15328 						 * to Reverse Tunnel
15329 						 */
15330 						ip_mrtun_forward(ire, ill, mp);
15331 					}
15332 					ire_refrele(ire);
15333 					ire = NULL;
15334 					if (tmp_ire != NULL) {
15335 						ire_refrele(tmp_ire);
15336 						tmp_ire = NULL;
15337 					}
15338 					TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15339 					    "ip_input_end: q %p (%S)",
15340 					    q, "uninit");
15341 					continue;
15342 				}
15343 			}
15344 			/*
15345 			 * If this packet is from a non-mobilenode  or a
15346 			 * mobile-node which does not request reverse
15347 			 * tunnel service
15348 			 */
15349 			ire = tmp_ire;
15350 		}
15351 
15352 
15353 		/*
15354 		 * If we reach here that means the incoming packet satisfies
15355 		 * one of the following conditions:
15356 		 *   - packet is from a mobile node which does not request
15357 		 *	reverse tunnel
15358 		 *   - packet is from a non-mobile node, which is the most
15359 		 *	common case
15360 		 *   - packet is from a reverse tunnel enabled mobile node
15361 		 *	and destined to foreign agent only
15362 		 */
15363 
15364 		if (ire == NULL) {
15365 			/*
15366 			 * No IRE for this destination, so it can't be for us.
15367 			 * Unless we are forwarding, drop the packet.
15368 			 * We have to let source routed packets through
15369 			 * since we don't yet know if they are 'ping -l'
15370 			 * packets i.e. if they will go out over the
15371 			 * same interface as they came in on.
15372 			 */
15373 			ire = ip_rput_noire(q, NULL, mp, ll_multicast, dst);
15374 			if (ire == NULL)
15375 				continue;
15376 		}
15377 
15378 		/*
15379 		 * Broadcast IRE may indicate either broadcast or
15380 		 * multicast packet
15381 		 */
15382 		if (ire->ire_type == IRE_BROADCAST) {
15383 			/*
15384 			 * Skip broadcast checks if packet is UDP multicast;
15385 			 * we'd rather not enter ip_rput_process_broadcast()
15386 			 * unless the packet is broadcast for real, since
15387 			 * that routine is a no-op for multicast.
15388 			 */
15389 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15390 			    !CLASSD(ipha->ipha_dst)) {
15391 				ire = ip_rput_process_broadcast(&q, mp,
15392 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15393 				    ll_multicast);
15394 				if (ire == NULL)
15395 					continue;
15396 			}
15397 		} else if (ire->ire_stq != NULL) {
15398 			/* fowarding? */
15399 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15400 			    ll_multicast);
15401 			/* ip_rput_process_forward consumed the packet */
15402 			continue;
15403 		}
15404 
15405 local:
15406 		/*
15407 		 * If the queue in the ire is different to the ingress queue
15408 		 * then we need to check to see if we can accept the packet.
15409 		 * Note that for multicast packets and broadcast packets sent
15410 		 * to a broadcast address which is shared between multiple
15411 		 * interfaces we should not do this since we just got a random
15412 		 * broadcast ire.
15413 		 */
15414 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15415 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15416 			    ill)) == NULL) {
15417 				/* Drop packet */
15418 				BUMP_MIB(ill->ill_ip_mib,
15419 				    ipIfStatsForwProhibits);
15420 				freemsg(mp);
15421 				continue;
15422 			}
15423 			if (ire->ire_rfq != NULL)
15424 				q = ire->ire_rfq;
15425 		}
15426 
15427 		switch (ipha->ipha_protocol) {
15428 		case IPPROTO_TCP:
15429 			ASSERT(first_mp == mp);
15430 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15431 			    mp, 0, q, ip_ring)) != NULL) {
15432 				if (curr_sqp == NULL) {
15433 					curr_sqp = GET_SQUEUE(mp);
15434 					ASSERT(cnt == 0);
15435 					cnt++;
15436 					head = tail = mp;
15437 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15438 					ASSERT(tail != NULL);
15439 					cnt++;
15440 					tail->b_next = mp;
15441 					tail = mp;
15442 				} else {
15443 					/*
15444 					 * A different squeue. Send the
15445 					 * chain for the previous squeue on
15446 					 * its way. This shouldn't happen
15447 					 * often unless interrupt binding
15448 					 * changes.
15449 					 */
15450 					IP_STAT(ipst, ip_input_multi_squeue);
15451 					squeue_enter_chain(curr_sqp, head,
15452 					    tail, cnt, SQTAG_IP_INPUT);
15453 					curr_sqp = GET_SQUEUE(mp);
15454 					head = mp;
15455 					tail = mp;
15456 					cnt = 1;
15457 				}
15458 			}
15459 			continue;
15460 		case IPPROTO_UDP:
15461 			ASSERT(first_mp == mp);
15462 			ip_udp_input(q, mp, ipha, ire, ill);
15463 			continue;
15464 		case IPPROTO_SCTP:
15465 			ASSERT(first_mp == mp);
15466 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15467 			    q, dst);
15468 			/* ire has been released by ip_sctp_input */
15469 			ire = NULL;
15470 			continue;
15471 		default:
15472 			ip_proto_input(q, first_mp, ipha, ire, ill);
15473 			continue;
15474 		}
15475 	}
15476 
15477 	if (ire != NULL)
15478 		ire_refrele(ire);
15479 
15480 	if (head != NULL)
15481 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15482 
15483 	/*
15484 	 * This code is there just to make netperf/ttcp look good.
15485 	 *
15486 	 * Its possible that after being in polling mode (and having cleared
15487 	 * the backlog), squeues have turned the interrupt frequency higher
15488 	 * to improve latency at the expense of more CPU utilization (less
15489 	 * packets per interrupts or more number of interrupts). Workloads
15490 	 * like ttcp/netperf do manage to tickle polling once in a while
15491 	 * but for the remaining time, stay in higher interrupt mode since
15492 	 * their packet arrival rate is pretty uniform and this shows up
15493 	 * as higher CPU utilization. Since people care about CPU utilization
15494 	 * while running netperf/ttcp, turn the interrupt frequency back to
15495 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15496 	 */
15497 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15498 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15499 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15500 			ip_ring->rr_blank(ip_ring->rr_handle,
15501 			    ip_ring->rr_normal_blank_time,
15502 			    ip_ring->rr_normal_pkt_cnt);
15503 		}
15504 		}
15505 
15506 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15507 	    "ip_input_end: q %p (%S)", q, "end");
15508 #undef  rptr
15509 }
15510 
15511 static void
15512 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15513     t_uscalar_t err)
15514 {
15515 	if (dl_err == DL_SYSERR) {
15516 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15517 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15518 		    ill->ill_name, dlpi_prim_str(prim), err);
15519 		return;
15520 	}
15521 
15522 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15523 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15524 	    dlpi_err_str(dl_err));
15525 }
15526 
15527 /*
15528  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15529  * than DL_UNITDATA_IND messages. If we need to process this message
15530  * exclusively, we call qwriter_ip, in which case we also need to call
15531  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15532  */
15533 void
15534 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15535 {
15536 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15537 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15538 	ill_t		*ill = (ill_t *)q->q_ptr;
15539 	boolean_t	pending;
15540 
15541 	ip1dbg(("ip_rput_dlpi"));
15542 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15543 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15544 		    "%s (0x%x), unix %u\n", ill->ill_name,
15545 		    dlpi_prim_str(dlea->dl_error_primitive),
15546 		    dlea->dl_error_primitive,
15547 		    dlpi_err_str(dlea->dl_errno),
15548 		    dlea->dl_errno,
15549 		    dlea->dl_unix_errno));
15550 	}
15551 
15552 	/*
15553 	 * If we received an ACK but didn't send a request for it, then it
15554 	 * can't be part of any pending operation; discard up-front.
15555 	 */
15556 	switch (dloa->dl_primitive) {
15557 	case DL_NOTIFY_IND:
15558 		pending = B_TRUE;
15559 		break;
15560 	case DL_ERROR_ACK:
15561 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15562 		break;
15563 	case DL_OK_ACK:
15564 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15565 		break;
15566 	case DL_INFO_ACK:
15567 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15568 		break;
15569 	case DL_BIND_ACK:
15570 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15571 		break;
15572 	case DL_PHYS_ADDR_ACK:
15573 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15574 		break;
15575 	case DL_NOTIFY_ACK:
15576 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15577 		break;
15578 	case DL_CONTROL_ACK:
15579 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15580 		break;
15581 	case DL_CAPABILITY_ACK:
15582 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15583 		break;
15584 	default:
15585 		/* Not a DLPI message we support or were expecting */
15586 		freemsg(mp);
15587 		return;
15588 	}
15589 
15590 	if (!pending) {
15591 		freemsg(mp);
15592 		return;
15593 	}
15594 
15595 	switch (dloa->dl_primitive) {
15596 	case DL_ERROR_ACK:
15597 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15598 			mutex_enter(&ill->ill_lock);
15599 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15600 			cv_signal(&ill->ill_cv);
15601 			mutex_exit(&ill->ill_lock);
15602 		}
15603 		break;
15604 
15605 	case DL_OK_ACK:
15606 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15607 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15608 		switch (dloa->dl_correct_primitive) {
15609 		case DL_UNBIND_REQ:
15610 			mutex_enter(&ill->ill_lock);
15611 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15612 			cv_signal(&ill->ill_cv);
15613 			mutex_exit(&ill->ill_lock);
15614 			break;
15615 
15616 		case DL_ENABMULTI_REQ:
15617 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15618 				ill->ill_dlpi_multicast_state = IDS_OK;
15619 			break;
15620 		}
15621 		break;
15622 	default:
15623 		break;
15624 	}
15625 
15626 	/*
15627 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15628 	 * and we need to become writer to continue to process it. If it's not
15629 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15630 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15631 	 * some work as part of the current exclusive operation that actually
15632 	 * is not part of it -- which is wrong, but better than the
15633 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15634 	 * should track which DLPI requests have ACKs that we wait on
15635 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15636 	 *
15637 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15638 	 * Since this is on the ill stream we unconditionally bump up the
15639 	 * refcount without doing ILL_CAN_LOOKUP().
15640 	 */
15641 	ill_refhold(ill);
15642 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15643 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15644 	else
15645 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15646 }
15647 
15648 /*
15649  * Handling of DLPI messages that require exclusive access to the ipsq.
15650  *
15651  * Need to do ill_pending_mp_release on ioctl completion, which could
15652  * happen here. (along with mi_copy_done)
15653  */
15654 /* ARGSUSED */
15655 static void
15656 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15657 {
15658 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15659 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15660 	int		err = 0;
15661 	ill_t		*ill;
15662 	ipif_t		*ipif = NULL;
15663 	mblk_t		*mp1 = NULL;
15664 	conn_t		*connp = NULL;
15665 	t_uscalar_t	paddrreq;
15666 	mblk_t		*mp_hw;
15667 	boolean_t	success;
15668 	boolean_t	ioctl_aborted = B_FALSE;
15669 	boolean_t	log = B_TRUE;
15670 	hook_nic_event_t	*info;
15671 	ip_stack_t		*ipst;
15672 
15673 	ip1dbg(("ip_rput_dlpi_writer .."));
15674 	ill = (ill_t *)q->q_ptr;
15675 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15676 
15677 	ASSERT(IAM_WRITER_ILL(ill));
15678 
15679 	ipst = ill->ill_ipst;
15680 
15681 	/*
15682 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15683 	 * both are null or non-null. However we can assert that only
15684 	 * after grabbing the ipsq_lock. So we don't make any assertion
15685 	 * here and in other places in the code.
15686 	 */
15687 	ipif = ipsq->ipsq_pending_ipif;
15688 	/*
15689 	 * The current ioctl could have been aborted by the user and a new
15690 	 * ioctl to bring up another ill could have started. We could still
15691 	 * get a response from the driver later.
15692 	 */
15693 	if (ipif != NULL && ipif->ipif_ill != ill)
15694 		ioctl_aborted = B_TRUE;
15695 
15696 	switch (dloa->dl_primitive) {
15697 	case DL_ERROR_ACK:
15698 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15699 		    dlpi_prim_str(dlea->dl_error_primitive)));
15700 
15701 		switch (dlea->dl_error_primitive) {
15702 		case DL_PROMISCON_REQ:
15703 		case DL_PROMISCOFF_REQ:
15704 		case DL_DISABMULTI_REQ:
15705 		case DL_UNBIND_REQ:
15706 		case DL_ATTACH_REQ:
15707 		case DL_INFO_REQ:
15708 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15709 			break;
15710 		case DL_NOTIFY_REQ:
15711 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15712 			log = B_FALSE;
15713 			break;
15714 		case DL_PHYS_ADDR_REQ:
15715 			/*
15716 			 * For IPv6 only, there are two additional
15717 			 * phys_addr_req's sent to the driver to get the
15718 			 * IPv6 token and lla. This allows IP to acquire
15719 			 * the hardware address format for a given interface
15720 			 * without having built in knowledge of the hardware
15721 			 * address. ill_phys_addr_pend keeps track of the last
15722 			 * DL_PAR sent so we know which response we are
15723 			 * dealing with. ill_dlpi_done will update
15724 			 * ill_phys_addr_pend when it sends the next req.
15725 			 * We don't complete the IOCTL until all three DL_PARs
15726 			 * have been attempted, so set *_len to 0 and break.
15727 			 */
15728 			paddrreq = ill->ill_phys_addr_pend;
15729 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15730 			if (paddrreq == DL_IPV6_TOKEN) {
15731 				ill->ill_token_length = 0;
15732 				log = B_FALSE;
15733 				break;
15734 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15735 				ill->ill_nd_lla_len = 0;
15736 				log = B_FALSE;
15737 				break;
15738 			}
15739 			/*
15740 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15741 			 * We presumably have an IOCTL hanging out waiting
15742 			 * for completion. Find it and complete the IOCTL
15743 			 * with the error noted.
15744 			 * However, ill_dl_phys was called on an ill queue
15745 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15746 			 * set. But the ioctl is known to be pending on ill_wq.
15747 			 */
15748 			if (!ill->ill_ifname_pending)
15749 				break;
15750 			ill->ill_ifname_pending = 0;
15751 			if (!ioctl_aborted)
15752 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15753 			if (mp1 != NULL) {
15754 				/*
15755 				 * This operation (SIOCSLIFNAME) must have
15756 				 * happened on the ill. Assert there is no conn
15757 				 */
15758 				ASSERT(connp == NULL);
15759 				q = ill->ill_wq;
15760 			}
15761 			break;
15762 		case DL_BIND_REQ:
15763 			ill_dlpi_done(ill, DL_BIND_REQ);
15764 			if (ill->ill_ifname_pending)
15765 				break;
15766 			/*
15767 			 * Something went wrong with the bind.  We presumably
15768 			 * have an IOCTL hanging out waiting for completion.
15769 			 * Find it, take down the interface that was coming
15770 			 * up, and complete the IOCTL with the error noted.
15771 			 */
15772 			if (!ioctl_aborted)
15773 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15774 			if (mp1 != NULL) {
15775 				/*
15776 				 * This operation (SIOCSLIFFLAGS) must have
15777 				 * happened from a conn.
15778 				 */
15779 				ASSERT(connp != NULL);
15780 				q = CONNP_TO_WQ(connp);
15781 				if (ill->ill_move_in_progress) {
15782 					ILL_CLEAR_MOVE(ill);
15783 				}
15784 				(void) ipif_down(ipif, NULL, NULL);
15785 				/* error is set below the switch */
15786 			}
15787 			break;
15788 		case DL_ENABMULTI_REQ:
15789 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15790 
15791 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15792 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15793 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15794 				ipif_t *ipif;
15795 
15796 				printf("ip: joining multicasts failed (%d)"
15797 				    " on %s - will use link layer "
15798 				    "broadcasts for multicast\n",
15799 				    dlea->dl_errno, ill->ill_name);
15800 
15801 				/*
15802 				 * Set up the multicast mapping alone.
15803 				 * writer, so ok to access ill->ill_ipif
15804 				 * without any lock.
15805 				 */
15806 				ipif = ill->ill_ipif;
15807 				mutex_enter(&ill->ill_phyint->phyint_lock);
15808 				ill->ill_phyint->phyint_flags |=
15809 				    PHYI_MULTI_BCAST;
15810 				mutex_exit(&ill->ill_phyint->phyint_lock);
15811 
15812 				if (!ill->ill_isv6) {
15813 					(void) ipif_arp_setup_multicast(ipif,
15814 					    NULL);
15815 				} else {
15816 					(void) ipif_ndp_setup_multicast(ipif,
15817 					    NULL);
15818 				}
15819 			}
15820 			freemsg(mp);	/* Don't want to pass this up */
15821 			return;
15822 
15823 		case DL_CAPABILITY_REQ:
15824 		case DL_CONTROL_REQ:
15825 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15826 			ill->ill_dlpi_capab_state = IDS_FAILED;
15827 			freemsg(mp);
15828 			return;
15829 		}
15830 		/*
15831 		 * Note the error for IOCTL completion (mp1 is set when
15832 		 * ready to complete ioctl). If ill_ifname_pending_err is
15833 		 * set, an error occured during plumbing (ill_ifname_pending),
15834 		 * so we want to report that error.
15835 		 *
15836 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15837 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15838 		 * expected to get errack'd if the driver doesn't support
15839 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15840 		 * if these error conditions are encountered.
15841 		 */
15842 		if (mp1 != NULL) {
15843 			if (ill->ill_ifname_pending_err != 0)  {
15844 				err = ill->ill_ifname_pending_err;
15845 				ill->ill_ifname_pending_err = 0;
15846 			} else {
15847 				err = dlea->dl_unix_errno ?
15848 				    dlea->dl_unix_errno : ENXIO;
15849 			}
15850 		/*
15851 		 * If we're plumbing an interface and an error hasn't already
15852 		 * been saved, set ill_ifname_pending_err to the error passed
15853 		 * up. Ignore the error if log is B_FALSE (see comment above).
15854 		 */
15855 		} else if (log && ill->ill_ifname_pending &&
15856 		    ill->ill_ifname_pending_err == 0) {
15857 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15858 			    dlea->dl_unix_errno : ENXIO;
15859 		}
15860 
15861 		if (log)
15862 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15863 			    dlea->dl_errno, dlea->dl_unix_errno);
15864 		break;
15865 	case DL_CAPABILITY_ACK: {
15866 		boolean_t reneg_flag = B_FALSE;
15867 		/* Call a routine to handle this one. */
15868 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15869 		/*
15870 		 * Check if the ACK is due to renegotiation case since we
15871 		 * will need to send a new CAPABILITY_REQ later.
15872 		 */
15873 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15874 			/* This is the ack for a renogiation case */
15875 			reneg_flag = B_TRUE;
15876 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15877 		}
15878 		ill_capability_ack(ill, mp);
15879 		if (reneg_flag)
15880 			ill_capability_probe(ill);
15881 		break;
15882 	}
15883 	case DL_CONTROL_ACK:
15884 		/* We treat all of these as "fire and forget" */
15885 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15886 		break;
15887 	case DL_INFO_ACK:
15888 		/* Call a routine to handle this one. */
15889 		ill_dlpi_done(ill, DL_INFO_REQ);
15890 		ip_ll_subnet_defaults(ill, mp);
15891 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15892 		return;
15893 	case DL_BIND_ACK:
15894 		/*
15895 		 * We should have an IOCTL waiting on this unless
15896 		 * sent by ill_dl_phys, in which case just return
15897 		 */
15898 		ill_dlpi_done(ill, DL_BIND_REQ);
15899 		if (ill->ill_ifname_pending)
15900 			break;
15901 
15902 		if (!ioctl_aborted)
15903 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15904 		if (mp1 == NULL)
15905 			break;
15906 		/*
15907 		 * Because mp1 was added by ill_dl_up(), and it always
15908 		 * passes a valid connp, connp must be valid here.
15909 		 */
15910 		ASSERT(connp != NULL);
15911 		q = CONNP_TO_WQ(connp);
15912 
15913 		/*
15914 		 * We are exclusive. So nothing can change even after
15915 		 * we get the pending mp. If need be we can put it back
15916 		 * and restart, as in calling ipif_arp_up()  below.
15917 		 */
15918 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15919 
15920 		mutex_enter(&ill->ill_lock);
15921 
15922 		ill->ill_dl_up = 1;
15923 
15924 		if ((info = ill->ill_nic_event_info) != NULL) {
15925 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15926 			    "attached for %s\n", info->hne_event,
15927 			    ill->ill_name));
15928 			if (info->hne_data != NULL)
15929 				kmem_free(info->hne_data, info->hne_datalen);
15930 			kmem_free(info, sizeof (hook_nic_event_t));
15931 		}
15932 
15933 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15934 		if (info != NULL) {
15935 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15936 			info->hne_lif = 0;
15937 			info->hne_event = NE_UP;
15938 			info->hne_data = NULL;
15939 			info->hne_datalen = 0;
15940 			info->hne_family = ill->ill_isv6 ?
15941 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15942 		} else
15943 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15944 			    "event information for %s (ENOMEM)\n",
15945 			    ill->ill_name));
15946 
15947 		ill->ill_nic_event_info = info;
15948 
15949 		mutex_exit(&ill->ill_lock);
15950 
15951 		/*
15952 		 * Now bring up the resolver; when that is complete, we'll
15953 		 * create IREs.  Note that we intentionally mirror what
15954 		 * ipif_up() would have done, because we got here by way of
15955 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15956 		 */
15957 		if (ill->ill_isv6) {
15958 			/*
15959 			 * v6 interfaces.
15960 			 * Unlike ARP which has to do another bind
15961 			 * and attach, once we get here we are
15962 			 * done with NDP. Except in the case of
15963 			 * ILLF_XRESOLV, in which case we send an
15964 			 * AR_INTERFACE_UP to the external resolver.
15965 			 * If all goes well, the ioctl will complete
15966 			 * in ip_rput(). If there's an error, we
15967 			 * complete it here.
15968 			 */
15969 			err = ipif_ndp_up(ipif, &ipif->ipif_v6lcl_addr);
15970 			if (err == 0) {
15971 				if (ill->ill_flags & ILLF_XRESOLV) {
15972 					mutex_enter(&connp->conn_lock);
15973 					mutex_enter(&ill->ill_lock);
15974 					success = ipsq_pending_mp_add(
15975 					    connp, ipif, q, mp1, 0);
15976 					mutex_exit(&ill->ill_lock);
15977 					mutex_exit(&connp->conn_lock);
15978 					if (success) {
15979 						err = ipif_resolver_up(ipif,
15980 						    Res_act_initial);
15981 						if (err == EINPROGRESS) {
15982 							freemsg(mp);
15983 							return;
15984 						}
15985 						ASSERT(err != 0);
15986 						mp1 = ipsq_pending_mp_get(ipsq,
15987 						    &connp);
15988 						ASSERT(mp1 != NULL);
15989 					} else {
15990 						/* conn has started closing */
15991 						err = EINTR;
15992 					}
15993 				} else { /* Non XRESOLV interface */
15994 					(void) ipif_resolver_up(ipif,
15995 					    Res_act_initial);
15996 					err = ipif_up_done_v6(ipif);
15997 				}
15998 			}
15999 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
16000 			/*
16001 			 * ARP and other v4 external resolvers.
16002 			 * Leave the pending mblk intact so that
16003 			 * the ioctl completes in ip_rput().
16004 			 */
16005 			mutex_enter(&connp->conn_lock);
16006 			mutex_enter(&ill->ill_lock);
16007 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
16008 			mutex_exit(&ill->ill_lock);
16009 			mutex_exit(&connp->conn_lock);
16010 			if (success) {
16011 				err = ipif_resolver_up(ipif, Res_act_initial);
16012 				if (err == EINPROGRESS) {
16013 					freemsg(mp);
16014 					return;
16015 				}
16016 				ASSERT(err != 0);
16017 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16018 			} else {
16019 				/* The conn has started closing */
16020 				err = EINTR;
16021 			}
16022 		} else {
16023 			/*
16024 			 * This one is complete. Reply to pending ioctl.
16025 			 */
16026 			(void) ipif_resolver_up(ipif, Res_act_initial);
16027 			err = ipif_up_done(ipif);
16028 		}
16029 
16030 		if ((err == 0) && (ill->ill_up_ipifs)) {
16031 			err = ill_up_ipifs(ill, q, mp1);
16032 			if (err == EINPROGRESS) {
16033 				freemsg(mp);
16034 				return;
16035 			}
16036 		}
16037 
16038 		if (ill->ill_up_ipifs) {
16039 			ill_group_cleanup(ill);
16040 		}
16041 
16042 		break;
16043 	case DL_NOTIFY_IND: {
16044 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
16045 		ire_t *ire;
16046 		boolean_t need_ire_walk_v4 = B_FALSE;
16047 		boolean_t need_ire_walk_v6 = B_FALSE;
16048 
16049 		switch (notify->dl_notification) {
16050 		case DL_NOTE_PHYS_ADDR:
16051 			err = ill_set_phys_addr(ill, mp);
16052 			break;
16053 
16054 		case DL_NOTE_FASTPATH_FLUSH:
16055 			ill_fastpath_flush(ill);
16056 			break;
16057 
16058 		case DL_NOTE_SDU_SIZE:
16059 			/*
16060 			 * Change the MTU size of the interface, of all
16061 			 * attached ipif's, and of all relevant ire's.  The
16062 			 * new value's a uint32_t at notify->dl_data.
16063 			 * Mtu change Vs. new ire creation - protocol below.
16064 			 *
16065 			 * a Mark the ipif as IPIF_CHANGING.
16066 			 * b Set the new mtu in the ipif.
16067 			 * c Change the ire_max_frag on all affected ires
16068 			 * d Unmark the IPIF_CHANGING
16069 			 *
16070 			 * To see how the protocol works, assume an interface
16071 			 * route is also being added simultaneously by
16072 			 * ip_rt_add and let 'ipif' be the ipif referenced by
16073 			 * the ire. If the ire is created before step a,
16074 			 * it will be cleaned up by step c. If the ire is
16075 			 * created after step d, it will see the new value of
16076 			 * ipif_mtu. Any attempt to create the ire between
16077 			 * steps a to d will fail because of the IPIF_CHANGING
16078 			 * flag. Note that ire_create() is passed a pointer to
16079 			 * the ipif_mtu, and not the value. During ire_add
16080 			 * under the bucket lock, the ire_max_frag of the
16081 			 * new ire being created is set from the ipif/ire from
16082 			 * which it is being derived.
16083 			 */
16084 			mutex_enter(&ill->ill_lock);
16085 			ill->ill_max_frag = (uint_t)notify->dl_data;
16086 
16087 			/*
16088 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16089 			 * leave it alone
16090 			 */
16091 			if (ill->ill_mtu_userspecified) {
16092 				mutex_exit(&ill->ill_lock);
16093 				break;
16094 			}
16095 			ill->ill_max_mtu = ill->ill_max_frag;
16096 			if (ill->ill_isv6) {
16097 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16098 					ill->ill_max_mtu = IPV6_MIN_MTU;
16099 			} else {
16100 				if (ill->ill_max_mtu < IP_MIN_MTU)
16101 					ill->ill_max_mtu = IP_MIN_MTU;
16102 			}
16103 			for (ipif = ill->ill_ipif; ipif != NULL;
16104 			    ipif = ipif->ipif_next) {
16105 				/*
16106 				 * Don't override the mtu if the user
16107 				 * has explicitly set it.
16108 				 */
16109 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16110 					continue;
16111 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16112 				if (ipif->ipif_isv6)
16113 					ire = ipif_to_ire_v6(ipif);
16114 				else
16115 					ire = ipif_to_ire(ipif);
16116 				if (ire != NULL) {
16117 					ire->ire_max_frag = ipif->ipif_mtu;
16118 					ire_refrele(ire);
16119 				}
16120 				if (ipif->ipif_flags & IPIF_UP) {
16121 					if (ill->ill_isv6)
16122 						need_ire_walk_v6 = B_TRUE;
16123 					else
16124 						need_ire_walk_v4 = B_TRUE;
16125 				}
16126 			}
16127 			mutex_exit(&ill->ill_lock);
16128 			if (need_ire_walk_v4)
16129 				ire_walk_v4(ill_mtu_change, (char *)ill,
16130 				    ALL_ZONES, ipst);
16131 			if (need_ire_walk_v6)
16132 				ire_walk_v6(ill_mtu_change, (char *)ill,
16133 				    ALL_ZONES, ipst);
16134 			break;
16135 		case DL_NOTE_LINK_UP:
16136 		case DL_NOTE_LINK_DOWN: {
16137 			/*
16138 			 * We are writer. ill / phyint / ipsq assocs stable.
16139 			 * The RUNNING flag reflects the state of the link.
16140 			 */
16141 			phyint_t *phyint = ill->ill_phyint;
16142 			uint64_t new_phyint_flags;
16143 			boolean_t changed = B_FALSE;
16144 			boolean_t went_up;
16145 
16146 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16147 			mutex_enter(&phyint->phyint_lock);
16148 			new_phyint_flags = went_up ?
16149 			    phyint->phyint_flags | PHYI_RUNNING :
16150 			    phyint->phyint_flags & ~PHYI_RUNNING;
16151 			if (new_phyint_flags != phyint->phyint_flags) {
16152 				phyint->phyint_flags = new_phyint_flags;
16153 				changed = B_TRUE;
16154 			}
16155 			mutex_exit(&phyint->phyint_lock);
16156 			/*
16157 			 * ill_restart_dad handles the DAD restart and routing
16158 			 * socket notification logic.
16159 			 */
16160 			if (changed) {
16161 				ill_restart_dad(phyint->phyint_illv4, went_up);
16162 				ill_restart_dad(phyint->phyint_illv6, went_up);
16163 			}
16164 			break;
16165 		}
16166 		case DL_NOTE_PROMISC_ON_PHYS:
16167 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16168 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16169 			mutex_enter(&ill->ill_lock);
16170 			ill->ill_promisc_on_phys = B_TRUE;
16171 			mutex_exit(&ill->ill_lock);
16172 			break;
16173 		case DL_NOTE_PROMISC_OFF_PHYS:
16174 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16175 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16176 			mutex_enter(&ill->ill_lock);
16177 			ill->ill_promisc_on_phys = B_FALSE;
16178 			mutex_exit(&ill->ill_lock);
16179 			break;
16180 		case DL_NOTE_CAPAB_RENEG:
16181 			/*
16182 			 * Something changed on the driver side.
16183 			 * It wants us to renegotiate the capabilities
16184 			 * on this ill. The most likely cause is the
16185 			 * aggregation interface under us where a
16186 			 * port got added or went away.
16187 			 *
16188 			 * We reset the capabilities and set the
16189 			 * state to IDS_RENG so that when the ack
16190 			 * comes back, we can start the
16191 			 * renegotiation process.
16192 			 */
16193 			ill_capability_reset(ill);
16194 			ill->ill_dlpi_capab_state = IDS_RENEG;
16195 			break;
16196 		default:
16197 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16198 			    "type 0x%x for DL_NOTIFY_IND\n",
16199 			    notify->dl_notification));
16200 			break;
16201 		}
16202 
16203 		/*
16204 		 * As this is an asynchronous operation, we
16205 		 * should not call ill_dlpi_done
16206 		 */
16207 		break;
16208 	}
16209 	case DL_NOTIFY_ACK: {
16210 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16211 
16212 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16213 			ill->ill_note_link = 1;
16214 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16215 		break;
16216 	}
16217 	case DL_PHYS_ADDR_ACK: {
16218 		/*
16219 		 * As part of plumbing the interface via SIOCSLIFNAME,
16220 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16221 		 * whose answers we receive here.  As each answer is received,
16222 		 * we call ill_dlpi_done() to dispatch the next request as
16223 		 * we're processing the current one.  Once all answers have
16224 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16225 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16226 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16227 		 * available, but we know the ioctl is pending on ill_wq.)
16228 		 */
16229 		uint_t paddrlen, paddroff;
16230 
16231 		paddrreq = ill->ill_phys_addr_pend;
16232 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16233 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16234 
16235 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16236 		if (paddrreq == DL_IPV6_TOKEN) {
16237 			/*
16238 			 * bcopy to low-order bits of ill_token
16239 			 *
16240 			 * XXX Temporary hack - currently, all known tokens
16241 			 * are 64 bits, so I'll cheat for the moment.
16242 			 */
16243 			bcopy(mp->b_rptr + paddroff,
16244 			    &ill->ill_token.s6_addr32[2], paddrlen);
16245 			ill->ill_token_length = paddrlen;
16246 			break;
16247 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16248 			ASSERT(ill->ill_nd_lla_mp == NULL);
16249 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16250 			mp = NULL;
16251 			break;
16252 		}
16253 
16254 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16255 		ASSERT(ill->ill_phys_addr_mp == NULL);
16256 		if (!ill->ill_ifname_pending)
16257 			break;
16258 		ill->ill_ifname_pending = 0;
16259 		if (!ioctl_aborted)
16260 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16261 		if (mp1 != NULL) {
16262 			ASSERT(connp == NULL);
16263 			q = ill->ill_wq;
16264 		}
16265 		/*
16266 		 * If any error acks received during the plumbing sequence,
16267 		 * ill_ifname_pending_err will be set. Break out and send up
16268 		 * the error to the pending ioctl.
16269 		 */
16270 		if (ill->ill_ifname_pending_err != 0) {
16271 			err = ill->ill_ifname_pending_err;
16272 			ill->ill_ifname_pending_err = 0;
16273 			break;
16274 		}
16275 
16276 		ill->ill_phys_addr_mp = mp;
16277 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16278 		mp = NULL;
16279 
16280 		/*
16281 		 * If paddrlen is zero, the DLPI provider doesn't support
16282 		 * physical addresses.  The other two tests were historical
16283 		 * workarounds for bugs in our former PPP implementation, but
16284 		 * now other things have grown dependencies on them -- e.g.,
16285 		 * the tun module specifies a dl_addr_length of zero in its
16286 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16287 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16288 		 * but only after careful testing ensures that all dependent
16289 		 * broken DLPI providers have been fixed.
16290 		 */
16291 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16292 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16293 			ill->ill_phys_addr = NULL;
16294 		} else if (paddrlen != ill->ill_phys_addr_length) {
16295 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16296 			    paddrlen, ill->ill_phys_addr_length));
16297 			err = EINVAL;
16298 			break;
16299 		}
16300 
16301 		if (ill->ill_nd_lla_mp == NULL) {
16302 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16303 				err = ENOMEM;
16304 				break;
16305 			}
16306 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16307 		}
16308 
16309 		/*
16310 		 * Set the interface token.  If the zeroth interface address
16311 		 * is unspecified, then set it to the link local address.
16312 		 */
16313 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16314 			(void) ill_setdefaulttoken(ill);
16315 
16316 		ASSERT(ill->ill_ipif->ipif_id == 0);
16317 		if (ipif != NULL &&
16318 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16319 			(void) ipif_setlinklocal(ipif);
16320 		}
16321 		break;
16322 	}
16323 	case DL_OK_ACK:
16324 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16325 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16326 		    dloa->dl_correct_primitive));
16327 		switch (dloa->dl_correct_primitive) {
16328 		case DL_PROMISCON_REQ:
16329 		case DL_PROMISCOFF_REQ:
16330 		case DL_ENABMULTI_REQ:
16331 		case DL_DISABMULTI_REQ:
16332 		case DL_UNBIND_REQ:
16333 		case DL_ATTACH_REQ:
16334 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16335 			break;
16336 		}
16337 		break;
16338 	default:
16339 		break;
16340 	}
16341 
16342 	freemsg(mp);
16343 	if (mp1 != NULL) {
16344 		/*
16345 		 * The operation must complete without EINPROGRESS
16346 		 * since ipsq_pending_mp_get() has removed the mblk
16347 		 * from ipsq_pending_mp.  Otherwise, the operation
16348 		 * will be stuck forever in the ipsq.
16349 		 */
16350 		ASSERT(err != EINPROGRESS);
16351 
16352 		switch (ipsq->ipsq_current_ioctl) {
16353 		case 0:
16354 			ipsq_current_finish(ipsq);
16355 			break;
16356 
16357 		case SIOCLIFADDIF:
16358 		case SIOCSLIFNAME:
16359 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16360 			break;
16361 
16362 		default:
16363 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16364 			break;
16365 		}
16366 	}
16367 }
16368 
16369 /*
16370  * ip_rput_other is called by ip_rput to handle messages modifying the global
16371  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16372  */
16373 /* ARGSUSED */
16374 void
16375 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16376 {
16377 	ill_t		*ill;
16378 	struct iocblk	*iocp;
16379 	mblk_t		*mp1;
16380 	conn_t		*connp = NULL;
16381 
16382 	ip1dbg(("ip_rput_other "));
16383 	ill = (ill_t *)q->q_ptr;
16384 	/*
16385 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16386 	 * in which case ipsq is NULL.
16387 	 */
16388 	if (ipsq != NULL) {
16389 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16390 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16391 	}
16392 
16393 	switch (mp->b_datap->db_type) {
16394 	case M_ERROR:
16395 	case M_HANGUP:
16396 		/*
16397 		 * The device has a problem.  We force the ILL down.  It can
16398 		 * be brought up again manually using SIOCSIFFLAGS (via
16399 		 * ifconfig or equivalent).
16400 		 */
16401 		ASSERT(ipsq != NULL);
16402 		if (mp->b_rptr < mp->b_wptr)
16403 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16404 		if (ill->ill_error == 0)
16405 			ill->ill_error = ENXIO;
16406 		if (!ill_down_start(q, mp))
16407 			return;
16408 		ipif_all_down_tail(ipsq, q, mp, NULL);
16409 		break;
16410 	case M_IOCACK:
16411 		iocp = (struct iocblk *)mp->b_rptr;
16412 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16413 		switch (iocp->ioc_cmd) {
16414 		case SIOCSTUNPARAM:
16415 		case OSIOCSTUNPARAM:
16416 			ASSERT(ipsq != NULL);
16417 			/*
16418 			 * Finish socket ioctl passed through to tun.
16419 			 * We should have an IOCTL waiting on this.
16420 			 */
16421 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16422 			if (ill->ill_isv6) {
16423 				struct iftun_req *ta;
16424 
16425 				/*
16426 				 * if a source or destination is
16427 				 * being set, try and set the link
16428 				 * local address for the tunnel
16429 				 */
16430 				ta = (struct iftun_req *)mp->b_cont->
16431 				    b_cont->b_rptr;
16432 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16433 					ipif_set_tun_llink(ill, ta);
16434 				}
16435 
16436 			}
16437 			if (mp1 != NULL) {
16438 				/*
16439 				 * Now copy back the b_next/b_prev used by
16440 				 * mi code for the mi_copy* functions.
16441 				 * See ip_sioctl_tunparam() for the reason.
16442 				 * Also protect against missing b_cont.
16443 				 */
16444 				if (mp->b_cont != NULL) {
16445 					mp->b_cont->b_next =
16446 					    mp1->b_cont->b_next;
16447 					mp->b_cont->b_prev =
16448 					    mp1->b_cont->b_prev;
16449 				}
16450 				inet_freemsg(mp1);
16451 				ASSERT(connp != NULL);
16452 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16453 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16454 			} else {
16455 				ASSERT(connp == NULL);
16456 				putnext(q, mp);
16457 			}
16458 			break;
16459 		case SIOCGTUNPARAM:
16460 		case OSIOCGTUNPARAM:
16461 			/*
16462 			 * This is really M_IOCDATA from the tunnel driver.
16463 			 * convert back and complete the ioctl.
16464 			 * We should have an IOCTL waiting on this.
16465 			 */
16466 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16467 			if (mp1) {
16468 				/*
16469 				 * Now copy back the b_next/b_prev used by
16470 				 * mi code for the mi_copy* functions.
16471 				 * See ip_sioctl_tunparam() for the reason.
16472 				 * Also protect against missing b_cont.
16473 				 */
16474 				if (mp->b_cont != NULL) {
16475 					mp->b_cont->b_next =
16476 					    mp1->b_cont->b_next;
16477 					mp->b_cont->b_prev =
16478 					    mp1->b_cont->b_prev;
16479 				}
16480 				inet_freemsg(mp1);
16481 				if (iocp->ioc_error == 0)
16482 					mp->b_datap->db_type = M_IOCDATA;
16483 				ASSERT(connp != NULL);
16484 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16485 				    iocp->ioc_error, COPYOUT, NULL);
16486 			} else {
16487 				ASSERT(connp == NULL);
16488 				putnext(q, mp);
16489 			}
16490 			break;
16491 		default:
16492 			break;
16493 		}
16494 		break;
16495 	case M_IOCNAK:
16496 		iocp = (struct iocblk *)mp->b_rptr;
16497 
16498 		switch (iocp->ioc_cmd) {
16499 		int mode;
16500 
16501 		case DL_IOC_HDR_INFO:
16502 			/*
16503 			 * If this was the first attempt turn of the
16504 			 * fastpath probing.
16505 			 */
16506 			mutex_enter(&ill->ill_lock);
16507 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16508 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16509 				mutex_exit(&ill->ill_lock);
16510 				ill_fastpath_nack(ill);
16511 				ip1dbg(("ip_rput: DLPI fastpath off on "
16512 				    "interface %s\n",
16513 				    ill->ill_name));
16514 			} else {
16515 				mutex_exit(&ill->ill_lock);
16516 			}
16517 			freemsg(mp);
16518 			break;
16519 		case SIOCSTUNPARAM:
16520 		case OSIOCSTUNPARAM:
16521 			ASSERT(ipsq != NULL);
16522 			/*
16523 			 * Finish socket ioctl passed through to tun
16524 			 * We should have an IOCTL waiting on this.
16525 			 */
16526 			/* FALLTHRU */
16527 		case SIOCGTUNPARAM:
16528 		case OSIOCGTUNPARAM:
16529 			/*
16530 			 * This is really M_IOCDATA from the tunnel driver.
16531 			 * convert back and complete the ioctl.
16532 			 * We should have an IOCTL waiting on this.
16533 			 */
16534 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16535 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16536 				mp1 = ill_pending_mp_get(ill, &connp,
16537 				    iocp->ioc_id);
16538 				mode = COPYOUT;
16539 				ipsq = NULL;
16540 			} else {
16541 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16542 				mode = NO_COPYOUT;
16543 			}
16544 			if (mp1 != NULL) {
16545 				/*
16546 				 * Now copy back the b_next/b_prev used by
16547 				 * mi code for the mi_copy* functions.
16548 				 * See ip_sioctl_tunparam() for the reason.
16549 				 * Also protect against missing b_cont.
16550 				 */
16551 				if (mp->b_cont != NULL) {
16552 					mp->b_cont->b_next =
16553 					    mp1->b_cont->b_next;
16554 					mp->b_cont->b_prev =
16555 					    mp1->b_cont->b_prev;
16556 				}
16557 				inet_freemsg(mp1);
16558 				if (iocp->ioc_error == 0)
16559 					iocp->ioc_error = EINVAL;
16560 				ASSERT(connp != NULL);
16561 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16562 				    iocp->ioc_error, mode, ipsq);
16563 			} else {
16564 				ASSERT(connp == NULL);
16565 				putnext(q, mp);
16566 			}
16567 			break;
16568 		default:
16569 			break;
16570 		}
16571 	default:
16572 		break;
16573 	}
16574 }
16575 
16576 /*
16577  * NOTE : This function does not ire_refrele the ire argument passed in.
16578  *
16579  * IPQoS notes
16580  * IP policy is invoked twice for a forwarded packet, once on the read side
16581  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16582  * enabled. An additional parameter, in_ill, has been added for this purpose.
16583  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16584  * because ip_mroute drops this information.
16585  *
16586  */
16587 void
16588 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16589 {
16590 	uint32_t	old_pkt_len;
16591 	uint32_t	pkt_len;
16592 	queue_t	*q;
16593 	uint32_t	sum;
16594 #define	rptr	((uchar_t *)ipha)
16595 	uint32_t	max_frag;
16596 	uint32_t	ill_index;
16597 	ill_t		*out_ill;
16598 	mib2_ipIfStatsEntry_t *mibptr;
16599 	ip_stack_t	*ipst = in_ill->ill_ipst;
16600 
16601 	/* Get the ill_index of the incoming ILL */
16602 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16603 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16604 
16605 	/* Initiate Read side IPPF processing */
16606 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16607 		ip_process(IPP_FWD_IN, &mp, ill_index);
16608 		if (mp == NULL) {
16609 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16610 			    "during IPPF processing\n"));
16611 			return;
16612 		}
16613 	}
16614 
16615 	/* Adjust the checksum to reflect the ttl decrement. */
16616 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16617 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16618 
16619 	if (ipha->ipha_ttl-- <= 1) {
16620 		if (ip_csum_hdr(ipha)) {
16621 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16622 			goto drop_pkt;
16623 		}
16624 		/*
16625 		 * Note: ire_stq this will be NULL for multicast
16626 		 * datagrams using the long path through arp (the IRE
16627 		 * is not an IRE_CACHE). This should not cause
16628 		 * problems since we don't generate ICMP errors for
16629 		 * multicast packets.
16630 		 */
16631 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16632 		q = ire->ire_stq;
16633 		if (q != NULL) {
16634 			/* Sent by forwarding path, and router is global zone */
16635 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16636 			    GLOBAL_ZONEID, ipst);
16637 		} else
16638 			freemsg(mp);
16639 		return;
16640 	}
16641 
16642 	/*
16643 	 * Don't forward if the interface is down
16644 	 */
16645 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16646 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16647 		ip2dbg(("ip_rput_forward:interface is down\n"));
16648 		goto drop_pkt;
16649 	}
16650 
16651 	/* Get the ill_index of the outgoing ILL */
16652 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16653 
16654 	out_ill = ire->ire_ipif->ipif_ill;
16655 
16656 	DTRACE_PROBE4(ip4__forwarding__start,
16657 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16658 
16659 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16660 	    ipst->ips_ipv4firewall_forwarding,
16661 	    in_ill, out_ill, ipha, mp, mp, ipst);
16662 
16663 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16664 
16665 	if (mp == NULL)
16666 		return;
16667 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16668 
16669 	if (is_system_labeled()) {
16670 		mblk_t *mp1;
16671 
16672 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16673 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16674 			goto drop_pkt;
16675 		}
16676 		/* Size may have changed */
16677 		mp = mp1;
16678 		ipha = (ipha_t *)mp->b_rptr;
16679 		pkt_len = ntohs(ipha->ipha_length);
16680 	}
16681 
16682 	/* Check if there are options to update */
16683 	if (!IS_SIMPLE_IPH(ipha)) {
16684 		if (ip_csum_hdr(ipha)) {
16685 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16686 			goto drop_pkt;
16687 		}
16688 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16689 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16690 			return;
16691 		}
16692 
16693 		ipha->ipha_hdr_checksum = 0;
16694 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16695 	}
16696 	max_frag = ire->ire_max_frag;
16697 	if (pkt_len > max_frag) {
16698 		/*
16699 		 * It needs fragging on its way out.  We haven't
16700 		 * verified the header checksum yet.  Since we
16701 		 * are going to put a surely good checksum in the
16702 		 * outgoing header, we have to make sure that it
16703 		 * was good coming in.
16704 		 */
16705 		if (ip_csum_hdr(ipha)) {
16706 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16707 			goto drop_pkt;
16708 		}
16709 		/* Initiate Write side IPPF processing */
16710 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16711 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16712 			if (mp == NULL) {
16713 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16714 				    " during IPPF processing\n"));
16715 				return;
16716 			}
16717 		}
16718 		/*
16719 		 * Handle labeled packet resizing.
16720 		 *
16721 		 * If we have added a label, inform ip_wput_frag() of its
16722 		 * effect on the MTU for ICMP messages.
16723 		 */
16724 		if (pkt_len > old_pkt_len) {
16725 			uint32_t secopt_size;
16726 
16727 			secopt_size = pkt_len - old_pkt_len;
16728 			if (secopt_size < max_frag)
16729 				max_frag -= secopt_size;
16730 		}
16731 
16732 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16733 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16734 		return;
16735 	}
16736 
16737 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16738 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16739 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16740 	    ipst->ips_ipv4firewall_physical_out,
16741 	    NULL, out_ill, ipha, mp, mp, ipst);
16742 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16743 	if (mp == NULL)
16744 		return;
16745 
16746 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16747 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16748 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16749 	/* ip_xmit_v4 always consumes the packet */
16750 	return;
16751 
16752 drop_pkt:;
16753 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16754 	freemsg(mp);
16755 #undef	rptr
16756 }
16757 
16758 void
16759 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16760 {
16761 	ire_t	*ire;
16762 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16763 
16764 	ASSERT(!ipif->ipif_isv6);
16765 	/*
16766 	 * Find an IRE which matches the destination and the outgoing
16767 	 * queue in the cache table. All we need is an IRE_CACHE which
16768 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16769 	 * then it is enough to have some IRE_CACHE in the group.
16770 	 */
16771 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16772 		dst = ipif->ipif_pp_dst_addr;
16773 
16774 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16775 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16776 	if (ire == NULL) {
16777 		/*
16778 		 * Mark this packet to make it be delivered to
16779 		 * ip_rput_forward after the new ire has been
16780 		 * created.
16781 		 */
16782 		mp->b_prev = NULL;
16783 		mp->b_next = mp;
16784 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16785 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16786 	} else {
16787 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16788 		IRE_REFRELE(ire);
16789 	}
16790 }
16791 
16792 /* Update any source route, record route or timestamp options */
16793 static int
16794 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16795 {
16796 	ipoptp_t	opts;
16797 	uchar_t		*opt;
16798 	uint8_t		optval;
16799 	uint8_t		optlen;
16800 	ipaddr_t	dst;
16801 	uint32_t	ts;
16802 	ire_t		*dst_ire = NULL;
16803 	ire_t		*tmp_ire = NULL;
16804 	timestruc_t	now;
16805 
16806 	ip2dbg(("ip_rput_forward_options\n"));
16807 	dst = ipha->ipha_dst;
16808 	for (optval = ipoptp_first(&opts, ipha);
16809 	    optval != IPOPT_EOL;
16810 	    optval = ipoptp_next(&opts)) {
16811 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16812 		opt = opts.ipoptp_cur;
16813 		optlen = opts.ipoptp_len;
16814 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16815 		    optval, opts.ipoptp_len));
16816 		switch (optval) {
16817 			uint32_t off;
16818 		case IPOPT_SSRR:
16819 		case IPOPT_LSRR:
16820 			/* Check if adminstratively disabled */
16821 			if (!ipst->ips_ip_forward_src_routed) {
16822 				if (ire->ire_stq != NULL) {
16823 					/*
16824 					 * Sent by forwarding path, and router
16825 					 * is global zone
16826 					 */
16827 					icmp_unreachable(ire->ire_stq, mp,
16828 					    ICMP_SOURCE_ROUTE_FAILED,
16829 					    GLOBAL_ZONEID, ipst);
16830 				} else {
16831 					ip0dbg(("ip_rput_forward_options: "
16832 					    "unable to send unreach\n"));
16833 					freemsg(mp);
16834 				}
16835 				return (-1);
16836 			}
16837 
16838 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16839 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16840 			if (dst_ire == NULL) {
16841 				/*
16842 				 * Must be partial since ip_rput_options
16843 				 * checked for strict.
16844 				 */
16845 				break;
16846 			}
16847 			off = opt[IPOPT_OFFSET];
16848 			off--;
16849 		redo_srr:
16850 			if (optlen < IP_ADDR_LEN ||
16851 			    off > optlen - IP_ADDR_LEN) {
16852 				/* End of source route */
16853 				ip1dbg((
16854 				    "ip_rput_forward_options: end of SR\n"));
16855 				ire_refrele(dst_ire);
16856 				break;
16857 			}
16858 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16859 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16860 			    IP_ADDR_LEN);
16861 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16862 			    ntohl(dst)));
16863 
16864 			/*
16865 			 * Check if our address is present more than
16866 			 * once as consecutive hops in source route.
16867 			 */
16868 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16869 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16870 			if (tmp_ire != NULL) {
16871 				ire_refrele(tmp_ire);
16872 				off += IP_ADDR_LEN;
16873 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16874 				goto redo_srr;
16875 			}
16876 			ipha->ipha_dst = dst;
16877 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16878 			ire_refrele(dst_ire);
16879 			break;
16880 		case IPOPT_RR:
16881 			off = opt[IPOPT_OFFSET];
16882 			off--;
16883 			if (optlen < IP_ADDR_LEN ||
16884 			    off > optlen - IP_ADDR_LEN) {
16885 				/* No more room - ignore */
16886 				ip1dbg((
16887 				    "ip_rput_forward_options: end of RR\n"));
16888 				break;
16889 			}
16890 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16891 			    IP_ADDR_LEN);
16892 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16893 			break;
16894 		case IPOPT_TS:
16895 			/* Insert timestamp if there is room */
16896 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16897 			case IPOPT_TS_TSONLY:
16898 				off = IPOPT_TS_TIMELEN;
16899 				break;
16900 			case IPOPT_TS_PRESPEC:
16901 			case IPOPT_TS_PRESPEC_RFC791:
16902 				/* Verify that the address matched */
16903 				off = opt[IPOPT_OFFSET] - 1;
16904 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16905 				dst_ire = ire_ctable_lookup(dst, 0,
16906 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16907 				    MATCH_IRE_TYPE, ipst);
16908 				if (dst_ire == NULL) {
16909 					/* Not for us */
16910 					break;
16911 				}
16912 				ire_refrele(dst_ire);
16913 				/* FALLTHRU */
16914 			case IPOPT_TS_TSANDADDR:
16915 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16916 				break;
16917 			default:
16918 				/*
16919 				 * ip_*put_options should have already
16920 				 * dropped this packet.
16921 				 */
16922 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16923 				    "unknown IT - bug in ip_rput_options?\n");
16924 				return (0);	/* Keep "lint" happy */
16925 			}
16926 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16927 				/* Increase overflow counter */
16928 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16929 				opt[IPOPT_POS_OV_FLG] =
16930 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16931 				    (off << 4));
16932 				break;
16933 			}
16934 			off = opt[IPOPT_OFFSET] - 1;
16935 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16936 			case IPOPT_TS_PRESPEC:
16937 			case IPOPT_TS_PRESPEC_RFC791:
16938 			case IPOPT_TS_TSANDADDR:
16939 				bcopy(&ire->ire_src_addr,
16940 				    (char *)opt + off, IP_ADDR_LEN);
16941 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16942 				/* FALLTHRU */
16943 			case IPOPT_TS_TSONLY:
16944 				off = opt[IPOPT_OFFSET] - 1;
16945 				/* Compute # of milliseconds since midnight */
16946 				gethrestime(&now);
16947 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16948 				    now.tv_nsec / (NANOSEC / MILLISEC);
16949 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16950 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16951 				break;
16952 			}
16953 			break;
16954 		}
16955 	}
16956 	return (0);
16957 }
16958 
16959 /*
16960  * This is called after processing at least one of AH/ESP headers.
16961  *
16962  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16963  * the actual, physical interface on which the packet was received,
16964  * but, when ip_strict_dst_multihoming is set to 1, could be the
16965  * interface which had the ipha_dst configured when the packet went
16966  * through ip_rput. The ill_index corresponding to the recv_ill
16967  * is saved in ipsec_in_rill_index
16968  *
16969  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16970  * cannot assume "ire" points to valid data for any IPv6 cases.
16971  */
16972 void
16973 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16974 {
16975 	mblk_t *mp;
16976 	ipaddr_t dst;
16977 	in6_addr_t *v6dstp;
16978 	ipha_t *ipha;
16979 	ip6_t *ip6h;
16980 	ipsec_in_t *ii;
16981 	boolean_t ill_need_rele = B_FALSE;
16982 	boolean_t rill_need_rele = B_FALSE;
16983 	boolean_t ire_need_rele = B_FALSE;
16984 	netstack_t	*ns;
16985 	ip_stack_t	*ipst;
16986 
16987 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16988 	ASSERT(ii->ipsec_in_ill_index != 0);
16989 	ns = ii->ipsec_in_ns;
16990 	ASSERT(ii->ipsec_in_ns != NULL);
16991 	ipst = ns->netstack_ip;
16992 
16993 	mp = ipsec_mp->b_cont;
16994 	ASSERT(mp != NULL);
16995 
16996 
16997 	if (ill == NULL) {
16998 		ASSERT(recv_ill == NULL);
16999 		/*
17000 		 * We need to get the original queue on which ip_rput_local
17001 		 * or ip_rput_data_v6 was called.
17002 		 */
17003 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
17004 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
17005 		ill_need_rele = B_TRUE;
17006 
17007 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
17008 			recv_ill = ill_lookup_on_ifindex(
17009 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
17010 			    NULL, NULL, NULL, NULL, ipst);
17011 			rill_need_rele = B_TRUE;
17012 		} else {
17013 			recv_ill = ill;
17014 		}
17015 
17016 		if ((ill == NULL) || (recv_ill == NULL)) {
17017 			ip0dbg(("ip_fanout_proto_again: interface "
17018 			    "disappeared\n"));
17019 			if (ill != NULL)
17020 				ill_refrele(ill);
17021 			if (recv_ill != NULL)
17022 				ill_refrele(recv_ill);
17023 			freemsg(ipsec_mp);
17024 			return;
17025 		}
17026 	}
17027 
17028 	ASSERT(ill != NULL && recv_ill != NULL);
17029 
17030 	if (mp->b_datap->db_type == M_CTL) {
17031 		/*
17032 		 * AH/ESP is returning the ICMP message after
17033 		 * removing their headers. Fanout again till
17034 		 * it gets to the right protocol.
17035 		 */
17036 		if (ii->ipsec_in_v4) {
17037 			icmph_t *icmph;
17038 			int iph_hdr_length;
17039 			int hdr_length;
17040 
17041 			ipha = (ipha_t *)mp->b_rptr;
17042 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
17043 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
17044 			ipha = (ipha_t *)&icmph[1];
17045 			hdr_length = IPH_HDR_LENGTH(ipha);
17046 			/*
17047 			 * icmp_inbound_error_fanout may need to do pullupmsg.
17048 			 * Reset the type to M_DATA.
17049 			 */
17050 			mp->b_datap->db_type = M_DATA;
17051 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
17052 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
17053 			    B_FALSE, ill, ii->ipsec_in_zoneid);
17054 		} else {
17055 			icmp6_t *icmp6;
17056 			int hdr_length;
17057 
17058 			ip6h = (ip6_t *)mp->b_rptr;
17059 			/* Don't call hdr_length_v6() unless you have to. */
17060 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
17061 				hdr_length = ip_hdr_length_v6(mp, ip6h);
17062 			else
17063 				hdr_length = IPV6_HDR_LEN;
17064 
17065 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
17066 			/*
17067 			 * icmp_inbound_error_fanout_v6 may need to do
17068 			 * pullupmsg.  Reset the type to M_DATA.
17069 			 */
17070 			mp->b_datap->db_type = M_DATA;
17071 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17072 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17073 		}
17074 		if (ill_need_rele)
17075 			ill_refrele(ill);
17076 		if (rill_need_rele)
17077 			ill_refrele(recv_ill);
17078 		return;
17079 	}
17080 
17081 	if (ii->ipsec_in_v4) {
17082 		ipha = (ipha_t *)mp->b_rptr;
17083 		dst = ipha->ipha_dst;
17084 		if (CLASSD(dst)) {
17085 			/*
17086 			 * Multicast has to be delivered to all streams.
17087 			 */
17088 			dst = INADDR_BROADCAST;
17089 		}
17090 
17091 		if (ire == NULL) {
17092 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17093 			    MBLK_GETLABEL(mp), ipst);
17094 			if (ire == NULL) {
17095 				if (ill_need_rele)
17096 					ill_refrele(ill);
17097 				if (rill_need_rele)
17098 					ill_refrele(recv_ill);
17099 				ip1dbg(("ip_fanout_proto_again: "
17100 				    "IRE not found"));
17101 				freemsg(ipsec_mp);
17102 				return;
17103 			}
17104 			ire_need_rele = B_TRUE;
17105 		}
17106 
17107 		switch (ipha->ipha_protocol) {
17108 			case IPPROTO_UDP:
17109 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17110 				    recv_ill);
17111 				if (ire_need_rele)
17112 					ire_refrele(ire);
17113 				break;
17114 			case IPPROTO_TCP:
17115 				if (!ire_need_rele)
17116 					IRE_REFHOLD(ire);
17117 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17118 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17119 				IRE_REFRELE(ire);
17120 				if (mp != NULL)
17121 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17122 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17123 				break;
17124 			case IPPROTO_SCTP:
17125 				if (!ire_need_rele)
17126 					IRE_REFHOLD(ire);
17127 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17128 				    ipsec_mp, 0, ill->ill_rq, dst);
17129 				break;
17130 			default:
17131 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17132 				    recv_ill);
17133 				if (ire_need_rele)
17134 					ire_refrele(ire);
17135 				break;
17136 		}
17137 	} else {
17138 		uint32_t rput_flags = 0;
17139 
17140 		ip6h = (ip6_t *)mp->b_rptr;
17141 		v6dstp = &ip6h->ip6_dst;
17142 		/*
17143 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17144 		 * address.
17145 		 *
17146 		 * Currently, we don't store that state in the IPSEC_IN
17147 		 * message, and we may need to.
17148 		 */
17149 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17150 		    IP6_IN_LLMCAST : 0);
17151 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17152 		    NULL, NULL);
17153 	}
17154 	if (ill_need_rele)
17155 		ill_refrele(ill);
17156 	if (rill_need_rele)
17157 		ill_refrele(recv_ill);
17158 }
17159 
17160 /*
17161  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17162  * returns 'true' if there are still fragments left on the queue, in
17163  * which case we restart the timer.
17164  */
17165 void
17166 ill_frag_timer(void *arg)
17167 {
17168 	ill_t	*ill = (ill_t *)arg;
17169 	boolean_t frag_pending;
17170 	ip_stack_t	*ipst = ill->ill_ipst;
17171 
17172 	mutex_enter(&ill->ill_lock);
17173 	ASSERT(!ill->ill_fragtimer_executing);
17174 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17175 		ill->ill_frag_timer_id = 0;
17176 		mutex_exit(&ill->ill_lock);
17177 		return;
17178 	}
17179 	ill->ill_fragtimer_executing = 1;
17180 	mutex_exit(&ill->ill_lock);
17181 
17182 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17183 
17184 	/*
17185 	 * Restart the timer, if we have fragments pending or if someone
17186 	 * wanted us to be scheduled again.
17187 	 */
17188 	mutex_enter(&ill->ill_lock);
17189 	ill->ill_fragtimer_executing = 0;
17190 	ill->ill_frag_timer_id = 0;
17191 	if (frag_pending || ill->ill_fragtimer_needrestart)
17192 		ill_frag_timer_start(ill);
17193 	mutex_exit(&ill->ill_lock);
17194 }
17195 
17196 void
17197 ill_frag_timer_start(ill_t *ill)
17198 {
17199 	ip_stack_t	*ipst = ill->ill_ipst;
17200 
17201 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17202 
17203 	/* If the ill is closing or opening don't proceed */
17204 	if (ill->ill_state_flags & ILL_CONDEMNED)
17205 		return;
17206 
17207 	if (ill->ill_fragtimer_executing) {
17208 		/*
17209 		 * ill_frag_timer is currently executing. Just record the
17210 		 * the fact that we want the timer to be restarted.
17211 		 * ill_frag_timer will post a timeout before it returns,
17212 		 * ensuring it will be called again.
17213 		 */
17214 		ill->ill_fragtimer_needrestart = 1;
17215 		return;
17216 	}
17217 
17218 	if (ill->ill_frag_timer_id == 0) {
17219 		/*
17220 		 * The timer is neither running nor is the timeout handler
17221 		 * executing. Post a timeout so that ill_frag_timer will be
17222 		 * called
17223 		 */
17224 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17225 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17226 		ill->ill_fragtimer_needrestart = 0;
17227 	}
17228 }
17229 
17230 /*
17231  * This routine is needed for loopback when forwarding multicasts.
17232  *
17233  * IPQoS Notes:
17234  * IPPF processing is done in fanout routines.
17235  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17236  * processing for IPSec packets is done when it comes back in clear.
17237  * NOTE : The callers of this function need to do the ire_refrele for the
17238  *	  ire that is being passed in.
17239  */
17240 void
17241 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17242     ill_t *recv_ill)
17243 {
17244 	ill_t	*ill = (ill_t *)q->q_ptr;
17245 	uint32_t	sum;
17246 	uint32_t	u1;
17247 	uint32_t	u2;
17248 	int		hdr_length;
17249 	boolean_t	mctl_present;
17250 	mblk_t		*first_mp = mp;
17251 	mblk_t		*hada_mp = NULL;
17252 	ipha_t		*inner_ipha;
17253 	ip_stack_t	*ipst;
17254 
17255 	ASSERT(recv_ill != NULL);
17256 	ipst = recv_ill->ill_ipst;
17257 
17258 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17259 	    "ip_rput_locl_start: q %p", q);
17260 
17261 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17262 	ASSERT(ill != NULL);
17263 
17264 
17265 #define	rptr	((uchar_t *)ipha)
17266 #define	iphs	((uint16_t *)ipha)
17267 
17268 	/*
17269 	 * no UDP or TCP packet should come here anymore.
17270 	 */
17271 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
17272 	    (ipha->ipha_protocol != IPPROTO_UDP));
17273 
17274 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17275 	if (mctl_present &&
17276 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17277 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17278 
17279 		/*
17280 		 * It's an IPsec accelerated packet.
17281 		 * Keep a pointer to the data attributes around until
17282 		 * we allocate the ipsec_info_t.
17283 		 */
17284 		IPSECHW_DEBUG(IPSECHW_PKT,
17285 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17286 		hada_mp = first_mp;
17287 		hada_mp->b_cont = NULL;
17288 		/*
17289 		 * Since it is accelerated, it comes directly from
17290 		 * the ill and the data attributes is followed by
17291 		 * the packet data.
17292 		 */
17293 		ASSERT(mp->b_datap->db_type != M_CTL);
17294 		first_mp = mp;
17295 		mctl_present = B_FALSE;
17296 	}
17297 
17298 	/*
17299 	 * IF M_CTL is not present, then ipsec_in_is_secure
17300 	 * should return B_TRUE. There is a case where loopback
17301 	 * packets has an M_CTL in the front with all the
17302 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
17303 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17304 	 * packets never comes here, it is safe to ASSERT the
17305 	 * following.
17306 	 */
17307 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17308 
17309 
17310 	/* u1 is # words of IP options */
17311 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
17312 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17313 
17314 	if (u1) {
17315 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17316 			if (hada_mp != NULL)
17317 				freemsg(hada_mp);
17318 			return;
17319 		}
17320 	} else {
17321 		/* Check the IP header checksum.  */
17322 #define	uph	((uint16_t *)ipha)
17323 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
17324 		    uph[6] + uph[7] + uph[8] + uph[9];
17325 #undef  uph
17326 		/* finish doing IP checksum */
17327 		sum = (sum & 0xFFFF) + (sum >> 16);
17328 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
17329 		/*
17330 		 * Don't verify header checksum if this packet is coming
17331 		 * back from AH/ESP as we already did it.
17332 		 */
17333 		if (!mctl_present && (sum && sum != 0xFFFF)) {
17334 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17335 			goto drop_pkt;
17336 		}
17337 	}
17338 
17339 	/*
17340 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17341 	 * might be called more than once for secure packets, count only
17342 	 * the first time.
17343 	 */
17344 	if (!mctl_present) {
17345 		UPDATE_IB_PKT_COUNT(ire);
17346 		ire->ire_last_used_time = lbolt;
17347 	}
17348 
17349 	/* Check for fragmentation offset. */
17350 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17351 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17352 	if (u1) {
17353 		/*
17354 		 * We re-assemble fragments before we do the AH/ESP
17355 		 * processing. Thus, M_CTL should not be present
17356 		 * while we are re-assembling.
17357 		 */
17358 		ASSERT(!mctl_present);
17359 		ASSERT(first_mp == mp);
17360 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17361 			return;
17362 		}
17363 		/*
17364 		 * Make sure that first_mp points back to mp as
17365 		 * the mp we came in with could have changed in
17366 		 * ip_rput_fragment().
17367 		 */
17368 		ipha = (ipha_t *)mp->b_rptr;
17369 		first_mp = mp;
17370 	}
17371 
17372 	/*
17373 	 * Clear hardware checksumming flag as it is currently only
17374 	 * used by TCP and UDP.
17375 	 */
17376 	DB_CKSUMFLAGS(mp) = 0;
17377 
17378 	/* Now we have a complete datagram, destined for this machine. */
17379 	u1 = IPH_HDR_LENGTH(ipha);
17380 	switch (ipha->ipha_protocol) {
17381 	case IPPROTO_ICMP: {
17382 		ire_t		*ire_zone;
17383 		ilm_t		*ilm;
17384 		mblk_t		*mp1;
17385 		zoneid_t	last_zoneid;
17386 
17387 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17388 			ASSERT(ire->ire_type == IRE_BROADCAST);
17389 			/*
17390 			 * In the multicast case, applications may have joined
17391 			 * the group from different zones, so we need to deliver
17392 			 * the packet to each of them. Loop through the
17393 			 * multicast memberships structures (ilm) on the receive
17394 			 * ill and send a copy of the packet up each matching
17395 			 * one. However, we don't do this for multicasts sent on
17396 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17397 			 * they must stay in the sender's zone.
17398 			 *
17399 			 * ilm_add_v6() ensures that ilms in the same zone are
17400 			 * contiguous in the ill_ilm list. We use this property
17401 			 * to avoid sending duplicates needed when two
17402 			 * applications in the same zone join the same group on
17403 			 * different logical interfaces: we ignore the ilm if
17404 			 * its zoneid is the same as the last matching one.
17405 			 * In addition, the sending of the packet for
17406 			 * ire_zoneid is delayed until all of the other ilms
17407 			 * have been exhausted.
17408 			 */
17409 			last_zoneid = -1;
17410 			ILM_WALKER_HOLD(recv_ill);
17411 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17412 			    ilm = ilm->ilm_next) {
17413 				if ((ilm->ilm_flags & ILM_DELETED) ||
17414 				    ipha->ipha_dst != ilm->ilm_addr ||
17415 				    ilm->ilm_zoneid == last_zoneid ||
17416 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17417 				    ilm->ilm_zoneid == ALL_ZONES ||
17418 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17419 					continue;
17420 				mp1 = ip_copymsg(first_mp);
17421 				if (mp1 == NULL)
17422 					continue;
17423 				icmp_inbound(q, mp1, B_TRUE, ill,
17424 				    0, sum, mctl_present, B_TRUE,
17425 				    recv_ill, ilm->ilm_zoneid);
17426 				last_zoneid = ilm->ilm_zoneid;
17427 			}
17428 			ILM_WALKER_RELE(recv_ill);
17429 		} else if (ire->ire_type == IRE_BROADCAST) {
17430 			/*
17431 			 * In the broadcast case, there may be many zones
17432 			 * which need a copy of the packet delivered to them.
17433 			 * There is one IRE_BROADCAST per broadcast address
17434 			 * and per zone; we walk those using a helper function.
17435 			 * In addition, the sending of the packet for ire is
17436 			 * delayed until all of the other ires have been
17437 			 * processed.
17438 			 */
17439 			IRB_REFHOLD(ire->ire_bucket);
17440 			ire_zone = NULL;
17441 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17442 			    ire)) != NULL) {
17443 				mp1 = ip_copymsg(first_mp);
17444 				if (mp1 == NULL)
17445 					continue;
17446 
17447 				UPDATE_IB_PKT_COUNT(ire_zone);
17448 				ire_zone->ire_last_used_time = lbolt;
17449 				icmp_inbound(q, mp1, B_TRUE, ill,
17450 				    0, sum, mctl_present, B_TRUE,
17451 				    recv_ill, ire_zone->ire_zoneid);
17452 			}
17453 			IRB_REFRELE(ire->ire_bucket);
17454 		}
17455 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17456 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17457 		    ire->ire_zoneid);
17458 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17459 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17460 		return;
17461 	}
17462 	case IPPROTO_IGMP:
17463 		/*
17464 		 * If we are not willing to accept IGMP packets in clear,
17465 		 * then check with global policy.
17466 		 */
17467 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17468 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17469 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17470 			if (first_mp == NULL)
17471 				return;
17472 		}
17473 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17474 			freemsg(first_mp);
17475 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17476 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17477 			return;
17478 		}
17479 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17480 			/* Bad packet - discarded by igmp_input */
17481 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17482 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17483 			if (mctl_present)
17484 				freeb(first_mp);
17485 			return;
17486 		}
17487 		/*
17488 		 * igmp_input() may have returned the pulled up message.
17489 		 * So first_mp and ipha need to be reinitialized.
17490 		 */
17491 		ipha = (ipha_t *)mp->b_rptr;
17492 		if (mctl_present)
17493 			first_mp->b_cont = mp;
17494 		else
17495 			first_mp = mp;
17496 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17497 		    connf_head != NULL) {
17498 			/* No user-level listener for IGMP packets */
17499 			goto drop_pkt;
17500 		}
17501 		/* deliver to local raw users */
17502 		break;
17503 	case IPPROTO_PIM:
17504 		/*
17505 		 * If we are not willing to accept PIM packets in clear,
17506 		 * then check with global policy.
17507 		 */
17508 		if (ipst->ips_pim_accept_clear_messages == 0) {
17509 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17510 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17511 			if (first_mp == NULL)
17512 				return;
17513 		}
17514 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17515 			freemsg(first_mp);
17516 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17517 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17518 			return;
17519 		}
17520 		if (pim_input(q, mp, ill) != 0) {
17521 			/* Bad packet - discarded by pim_input */
17522 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17523 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17524 			if (mctl_present)
17525 				freeb(first_mp);
17526 			return;
17527 		}
17528 
17529 		/*
17530 		 * pim_input() may have pulled up the message so ipha needs to
17531 		 * be reinitialized.
17532 		 */
17533 		ipha = (ipha_t *)mp->b_rptr;
17534 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17535 		    connf_head != NULL) {
17536 			/* No user-level listener for PIM packets */
17537 			goto drop_pkt;
17538 		}
17539 		/* deliver to local raw users */
17540 		break;
17541 	case IPPROTO_ENCAP:
17542 		/*
17543 		 * Handle self-encapsulated packets (IP-in-IP where
17544 		 * the inner addresses == the outer addresses).
17545 		 */
17546 		hdr_length = IPH_HDR_LENGTH(ipha);
17547 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17548 		    mp->b_wptr) {
17549 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17550 			    sizeof (ipha_t) - mp->b_rptr)) {
17551 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17552 				freemsg(first_mp);
17553 				return;
17554 			}
17555 			ipha = (ipha_t *)mp->b_rptr;
17556 		}
17557 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17558 		/*
17559 		 * Check the sanity of the inner IP header.
17560 		 */
17561 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17562 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17563 			freemsg(first_mp);
17564 			return;
17565 		}
17566 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17567 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17568 			freemsg(first_mp);
17569 			return;
17570 		}
17571 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17572 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17573 			ipsec_in_t *ii;
17574 
17575 			/*
17576 			 * Self-encapsulated tunnel packet. Remove
17577 			 * the outer IP header and fanout again.
17578 			 * We also need to make sure that the inner
17579 			 * header is pulled up until options.
17580 			 */
17581 			mp->b_rptr = (uchar_t *)inner_ipha;
17582 			ipha = inner_ipha;
17583 			hdr_length = IPH_HDR_LENGTH(ipha);
17584 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17585 				if (!pullupmsg(mp, (uchar_t *)ipha +
17586 				    + hdr_length - mp->b_rptr)) {
17587 					freemsg(first_mp);
17588 					return;
17589 				}
17590 				ipha = (ipha_t *)mp->b_rptr;
17591 			}
17592 			if (!mctl_present) {
17593 				ASSERT(first_mp == mp);
17594 				/*
17595 				 * This means that somebody is sending
17596 				 * Self-encapsualted packets without AH/ESP.
17597 				 * If AH/ESP was present, we would have already
17598 				 * allocated the first_mp.
17599 				 */
17600 				first_mp = ipsec_in_alloc(B_TRUE,
17601 				    ipst->ips_netstack);
17602 				if (first_mp == NULL) {
17603 					ip1dbg(("ip_proto_input: IPSEC_IN "
17604 					    "allocation failure.\n"));
17605 					BUMP_MIB(ill->ill_ip_mib,
17606 					    ipIfStatsInDiscards);
17607 					freemsg(mp);
17608 					return;
17609 				}
17610 				first_mp->b_cont = mp;
17611 			}
17612 			/*
17613 			 * We generally store the ill_index if we need to
17614 			 * do IPSEC processing as we lose the ill queue when
17615 			 * we come back. But in this case, we never should
17616 			 * have to store the ill_index here as it should have
17617 			 * been stored previously when we processed the
17618 			 * AH/ESP header in this routine or for non-ipsec
17619 			 * cases, we still have the queue. But for some bad
17620 			 * packets from the wire, we can get to IPSEC after
17621 			 * this and we better store the index for that case.
17622 			 */
17623 			ill = (ill_t *)q->q_ptr;
17624 			ii = (ipsec_in_t *)first_mp->b_rptr;
17625 			ii->ipsec_in_ill_index =
17626 			    ill->ill_phyint->phyint_ifindex;
17627 			ii->ipsec_in_rill_index =
17628 			    recv_ill->ill_phyint->phyint_ifindex;
17629 			if (ii->ipsec_in_decaps) {
17630 				/*
17631 				 * This packet is self-encapsulated multiple
17632 				 * times. We don't want to recurse infinitely.
17633 				 * To keep it simple, drop the packet.
17634 				 */
17635 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17636 				freemsg(first_mp);
17637 				return;
17638 			}
17639 			ii->ipsec_in_decaps = B_TRUE;
17640 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17641 			    ire);
17642 			return;
17643 		}
17644 		break;
17645 	case IPPROTO_AH:
17646 	case IPPROTO_ESP: {
17647 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17648 
17649 		/*
17650 		 * Fast path for AH/ESP. If this is the first time
17651 		 * we are sending a datagram to AH/ESP, allocate
17652 		 * a IPSEC_IN message and prepend it. Otherwise,
17653 		 * just fanout.
17654 		 */
17655 
17656 		int ipsec_rc;
17657 		ipsec_in_t *ii;
17658 		netstack_t *ns = ipst->ips_netstack;
17659 
17660 		IP_STAT(ipst, ipsec_proto_ahesp);
17661 		if (!mctl_present) {
17662 			ASSERT(first_mp == mp);
17663 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17664 			if (first_mp == NULL) {
17665 				ip1dbg(("ip_proto_input: IPSEC_IN "
17666 				    "allocation failure.\n"));
17667 				freemsg(hada_mp); /* okay ifnull */
17668 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17669 				freemsg(mp);
17670 				return;
17671 			}
17672 			/*
17673 			 * Store the ill_index so that when we come back
17674 			 * from IPSEC we ride on the same queue.
17675 			 */
17676 			ill = (ill_t *)q->q_ptr;
17677 			ii = (ipsec_in_t *)first_mp->b_rptr;
17678 			ii->ipsec_in_ill_index =
17679 			    ill->ill_phyint->phyint_ifindex;
17680 			ii->ipsec_in_rill_index =
17681 			    recv_ill->ill_phyint->phyint_ifindex;
17682 			first_mp->b_cont = mp;
17683 			/*
17684 			 * Cache hardware acceleration info.
17685 			 */
17686 			if (hada_mp != NULL) {
17687 				IPSECHW_DEBUG(IPSECHW_PKT,
17688 				    ("ip_rput_local: caching data attr.\n"));
17689 				ii->ipsec_in_accelerated = B_TRUE;
17690 				ii->ipsec_in_da = hada_mp;
17691 				hada_mp = NULL;
17692 			}
17693 		} else {
17694 			ii = (ipsec_in_t *)first_mp->b_rptr;
17695 		}
17696 
17697 		if (!ipsec_loaded(ipss)) {
17698 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17699 			    ire->ire_zoneid, ipst);
17700 			return;
17701 		}
17702 
17703 		ns = ipst->ips_netstack;
17704 		/* select inbound SA and have IPsec process the pkt */
17705 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17706 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17707 			if (esph == NULL)
17708 				return;
17709 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17710 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17711 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17712 			    first_mp, esph);
17713 		} else {
17714 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17715 			if (ah == NULL)
17716 				return;
17717 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17718 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17719 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17720 			    first_mp, ah);
17721 		}
17722 
17723 		switch (ipsec_rc) {
17724 		case IPSEC_STATUS_SUCCESS:
17725 			break;
17726 		case IPSEC_STATUS_FAILED:
17727 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17728 			/* FALLTHRU */
17729 		case IPSEC_STATUS_PENDING:
17730 			return;
17731 		}
17732 		/* we're done with IPsec processing, send it up */
17733 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17734 		return;
17735 	}
17736 	default:
17737 		break;
17738 	}
17739 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17740 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17741 		    ire->ire_zoneid));
17742 		goto drop_pkt;
17743 	}
17744 	/*
17745 	 * Handle protocols with which IP is less intimate.  There
17746 	 * can be more than one stream bound to a particular
17747 	 * protocol.  When this is the case, each one gets a copy
17748 	 * of any incoming packets.
17749 	 */
17750 	ip_fanout_proto(q, first_mp, ill, ipha,
17751 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17752 	    B_TRUE, recv_ill, ire->ire_zoneid);
17753 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17754 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17755 	return;
17756 
17757 drop_pkt:
17758 	freemsg(first_mp);
17759 	if (hada_mp != NULL)
17760 		freeb(hada_mp);
17761 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17762 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17763 #undef	rptr
17764 #undef  iphs
17765 
17766 }
17767 
17768 /*
17769  * Update any source route, record route or timestamp options.
17770  * Check that we are at end of strict source route.
17771  * The options have already been checked for sanity in ip_rput_options().
17772  */
17773 static boolean_t
17774 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17775     ip_stack_t *ipst)
17776 {
17777 	ipoptp_t	opts;
17778 	uchar_t		*opt;
17779 	uint8_t		optval;
17780 	uint8_t		optlen;
17781 	ipaddr_t	dst;
17782 	uint32_t	ts;
17783 	ire_t		*dst_ire;
17784 	timestruc_t	now;
17785 	zoneid_t	zoneid;
17786 	ill_t		*ill;
17787 
17788 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17789 
17790 	ip2dbg(("ip_rput_local_options\n"));
17791 
17792 	for (optval = ipoptp_first(&opts, ipha);
17793 	    optval != IPOPT_EOL;
17794 	    optval = ipoptp_next(&opts)) {
17795 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17796 		opt = opts.ipoptp_cur;
17797 		optlen = opts.ipoptp_len;
17798 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17799 		    optval, optlen));
17800 		switch (optval) {
17801 			uint32_t off;
17802 		case IPOPT_SSRR:
17803 		case IPOPT_LSRR:
17804 			off = opt[IPOPT_OFFSET];
17805 			off--;
17806 			if (optlen < IP_ADDR_LEN ||
17807 			    off > optlen - IP_ADDR_LEN) {
17808 				/* End of source route */
17809 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17810 				break;
17811 			}
17812 			/*
17813 			 * This will only happen if two consecutive entries
17814 			 * in the source route contains our address or if
17815 			 * it is a packet with a loose source route which
17816 			 * reaches us before consuming the whole source route
17817 			 */
17818 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17819 			if (optval == IPOPT_SSRR) {
17820 				goto bad_src_route;
17821 			}
17822 			/*
17823 			 * Hack: instead of dropping the packet truncate the
17824 			 * source route to what has been used by filling the
17825 			 * rest with IPOPT_NOP.
17826 			 */
17827 			opt[IPOPT_OLEN] = (uint8_t)off;
17828 			while (off < optlen) {
17829 				opt[off++] = IPOPT_NOP;
17830 			}
17831 			break;
17832 		case IPOPT_RR:
17833 			off = opt[IPOPT_OFFSET];
17834 			off--;
17835 			if (optlen < IP_ADDR_LEN ||
17836 			    off > optlen - IP_ADDR_LEN) {
17837 				/* No more room - ignore */
17838 				ip1dbg((
17839 				    "ip_rput_local_options: end of RR\n"));
17840 				break;
17841 			}
17842 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17843 			    IP_ADDR_LEN);
17844 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17845 			break;
17846 		case IPOPT_TS:
17847 			/* Insert timestamp if there is romm */
17848 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17849 			case IPOPT_TS_TSONLY:
17850 				off = IPOPT_TS_TIMELEN;
17851 				break;
17852 			case IPOPT_TS_PRESPEC:
17853 			case IPOPT_TS_PRESPEC_RFC791:
17854 				/* Verify that the address matched */
17855 				off = opt[IPOPT_OFFSET] - 1;
17856 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17857 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17858 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17859 				    ipst);
17860 				if (dst_ire == NULL) {
17861 					/* Not for us */
17862 					break;
17863 				}
17864 				ire_refrele(dst_ire);
17865 				/* FALLTHRU */
17866 			case IPOPT_TS_TSANDADDR:
17867 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17868 				break;
17869 			default:
17870 				/*
17871 				 * ip_*put_options should have already
17872 				 * dropped this packet.
17873 				 */
17874 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17875 				    "unknown IT - bug in ip_rput_options?\n");
17876 				return (B_TRUE);	/* Keep "lint" happy */
17877 			}
17878 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17879 				/* Increase overflow counter */
17880 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17881 				opt[IPOPT_POS_OV_FLG] =
17882 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17883 				    (off << 4));
17884 				break;
17885 			}
17886 			off = opt[IPOPT_OFFSET] - 1;
17887 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17888 			case IPOPT_TS_PRESPEC:
17889 			case IPOPT_TS_PRESPEC_RFC791:
17890 			case IPOPT_TS_TSANDADDR:
17891 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17892 				    IP_ADDR_LEN);
17893 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17894 				/* FALLTHRU */
17895 			case IPOPT_TS_TSONLY:
17896 				off = opt[IPOPT_OFFSET] - 1;
17897 				/* Compute # of milliseconds since midnight */
17898 				gethrestime(&now);
17899 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17900 				    now.tv_nsec / (NANOSEC / MILLISEC);
17901 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17902 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17903 				break;
17904 			}
17905 			break;
17906 		}
17907 	}
17908 	return (B_TRUE);
17909 
17910 bad_src_route:
17911 	q = WR(q);
17912 	if (q->q_next != NULL)
17913 		ill = q->q_ptr;
17914 	else
17915 		ill = NULL;
17916 
17917 	/* make sure we clear any indication of a hardware checksum */
17918 	DB_CKSUMFLAGS(mp) = 0;
17919 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17920 	if (zoneid == ALL_ZONES)
17921 		freemsg(mp);
17922 	else
17923 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17924 	return (B_FALSE);
17925 
17926 }
17927 
17928 /*
17929  * Process IP options in an inbound packet.  If an option affects the
17930  * effective destination address, return the next hop address via dstp.
17931  * Returns -1 if something fails in which case an ICMP error has been sent
17932  * and mp freed.
17933  */
17934 static int
17935 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17936     ip_stack_t *ipst)
17937 {
17938 	ipoptp_t	opts;
17939 	uchar_t		*opt;
17940 	uint8_t		optval;
17941 	uint8_t		optlen;
17942 	ipaddr_t	dst;
17943 	intptr_t	code = 0;
17944 	ire_t		*ire = NULL;
17945 	zoneid_t	zoneid;
17946 	ill_t		*ill;
17947 
17948 	ip2dbg(("ip_rput_options\n"));
17949 	dst = ipha->ipha_dst;
17950 	for (optval = ipoptp_first(&opts, ipha);
17951 	    optval != IPOPT_EOL;
17952 	    optval = ipoptp_next(&opts)) {
17953 		opt = opts.ipoptp_cur;
17954 		optlen = opts.ipoptp_len;
17955 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17956 		    optval, optlen));
17957 		/*
17958 		 * Note: we need to verify the checksum before we
17959 		 * modify anything thus this routine only extracts the next
17960 		 * hop dst from any source route.
17961 		 */
17962 		switch (optval) {
17963 			uint32_t off;
17964 		case IPOPT_SSRR:
17965 		case IPOPT_LSRR:
17966 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17967 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17968 			if (ire == NULL) {
17969 				if (optval == IPOPT_SSRR) {
17970 					ip1dbg(("ip_rput_options: not next"
17971 					    " strict source route 0x%x\n",
17972 					    ntohl(dst)));
17973 					code = (char *)&ipha->ipha_dst -
17974 					    (char *)ipha;
17975 					goto param_prob; /* RouterReq's */
17976 				}
17977 				ip2dbg(("ip_rput_options: "
17978 				    "not next source route 0x%x\n",
17979 				    ntohl(dst)));
17980 				break;
17981 			}
17982 			ire_refrele(ire);
17983 
17984 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17985 				ip1dbg((
17986 				    "ip_rput_options: bad option offset\n"));
17987 				code = (char *)&opt[IPOPT_OLEN] -
17988 				    (char *)ipha;
17989 				goto param_prob;
17990 			}
17991 			off = opt[IPOPT_OFFSET];
17992 			off--;
17993 		redo_srr:
17994 			if (optlen < IP_ADDR_LEN ||
17995 			    off > optlen - IP_ADDR_LEN) {
17996 				/* End of source route */
17997 				ip1dbg(("ip_rput_options: end of SR\n"));
17998 				break;
17999 			}
18000 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
18001 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
18002 			    ntohl(dst)));
18003 
18004 			/*
18005 			 * Check if our address is present more than
18006 			 * once as consecutive hops in source route.
18007 			 * XXX verify per-interface ip_forwarding
18008 			 * for source route?
18009 			 */
18010 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
18011 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
18012 
18013 			if (ire != NULL) {
18014 				ire_refrele(ire);
18015 				off += IP_ADDR_LEN;
18016 				goto redo_srr;
18017 			}
18018 
18019 			if (dst == htonl(INADDR_LOOPBACK)) {
18020 				ip1dbg(("ip_rput_options: loopback addr in "
18021 				    "source route!\n"));
18022 				goto bad_src_route;
18023 			}
18024 			/*
18025 			 * For strict: verify that dst is directly
18026 			 * reachable.
18027 			 */
18028 			if (optval == IPOPT_SSRR) {
18029 				ire = ire_ftable_lookup(dst, 0, 0,
18030 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
18031 				    MBLK_GETLABEL(mp),
18032 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
18033 				if (ire == NULL) {
18034 					ip1dbg(("ip_rput_options: SSRR not "
18035 					    "directly reachable: 0x%x\n",
18036 					    ntohl(dst)));
18037 					goto bad_src_route;
18038 				}
18039 				ire_refrele(ire);
18040 			}
18041 			/*
18042 			 * Defer update of the offset and the record route
18043 			 * until the packet is forwarded.
18044 			 */
18045 			break;
18046 		case IPOPT_RR:
18047 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18048 				ip1dbg((
18049 				    "ip_rput_options: bad option offset\n"));
18050 				code = (char *)&opt[IPOPT_OLEN] -
18051 				    (char *)ipha;
18052 				goto param_prob;
18053 			}
18054 			break;
18055 		case IPOPT_TS:
18056 			/*
18057 			 * Verify that length >= 5 and that there is either
18058 			 * room for another timestamp or that the overflow
18059 			 * counter is not maxed out.
18060 			 */
18061 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18062 			if (optlen < IPOPT_MINLEN_IT) {
18063 				goto param_prob;
18064 			}
18065 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18066 				ip1dbg((
18067 				    "ip_rput_options: bad option offset\n"));
18068 				code = (char *)&opt[IPOPT_OFFSET] -
18069 				    (char *)ipha;
18070 				goto param_prob;
18071 			}
18072 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18073 			case IPOPT_TS_TSONLY:
18074 				off = IPOPT_TS_TIMELEN;
18075 				break;
18076 			case IPOPT_TS_TSANDADDR:
18077 			case IPOPT_TS_PRESPEC:
18078 			case IPOPT_TS_PRESPEC_RFC791:
18079 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18080 				break;
18081 			default:
18082 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18083 				    (char *)ipha;
18084 				goto param_prob;
18085 			}
18086 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18087 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18088 				/*
18089 				 * No room and the overflow counter is 15
18090 				 * already.
18091 				 */
18092 				goto param_prob;
18093 			}
18094 			break;
18095 		}
18096 	}
18097 
18098 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18099 		*dstp = dst;
18100 		return (0);
18101 	}
18102 
18103 	ip1dbg(("ip_rput_options: error processing IP options."));
18104 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18105 
18106 param_prob:
18107 	q = WR(q);
18108 	if (q->q_next != NULL)
18109 		ill = q->q_ptr;
18110 	else
18111 		ill = NULL;
18112 
18113 	/* make sure we clear any indication of a hardware checksum */
18114 	DB_CKSUMFLAGS(mp) = 0;
18115 	/* Don't know whether this is for non-global or global/forwarding */
18116 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18117 	if (zoneid == ALL_ZONES)
18118 		freemsg(mp);
18119 	else
18120 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18121 	return (-1);
18122 
18123 bad_src_route:
18124 	q = WR(q);
18125 	if (q->q_next != NULL)
18126 		ill = q->q_ptr;
18127 	else
18128 		ill = NULL;
18129 
18130 	/* make sure we clear any indication of a hardware checksum */
18131 	DB_CKSUMFLAGS(mp) = 0;
18132 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18133 	if (zoneid == ALL_ZONES)
18134 		freemsg(mp);
18135 	else
18136 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18137 	return (-1);
18138 }
18139 
18140 /*
18141  * IP & ICMP info in >=14 msg's ...
18142  *  - ip fixed part (mib2_ip_t)
18143  *  - icmp fixed part (mib2_icmp_t)
18144  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18145  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18146  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18147  *  - ipRouteAttributeTable (ip 102)	labeled routes
18148  *  - ip multicast membership (ip_member_t)
18149  *  - ip multicast source filtering (ip_grpsrc_t)
18150  *  - igmp fixed part (struct igmpstat)
18151  *  - multicast routing stats (struct mrtstat)
18152  *  - multicast routing vifs (array of struct vifctl)
18153  *  - multicast routing routes (array of struct mfcctl)
18154  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18155  *					One per ill plus one generic
18156  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18157  *					One per ill plus one generic
18158  *  - ipv6RouteEntry			all IPv6 IREs
18159  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18160  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18161  *  - ipv6AddrEntry			all IPv6 ipifs
18162  *  - ipv6 multicast membership (ipv6_member_t)
18163  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18164  *
18165  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18166  *
18167  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18168  * already filled in by the caller.
18169  * Return value of 0 indicates that no messages were sent and caller
18170  * should free mpctl.
18171  */
18172 int
18173 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18174 {
18175 	ip_stack_t *ipst;
18176 	sctp_stack_t *sctps;
18177 
18178 
18179 	if (q->q_next != NULL) {
18180 		ipst = ILLQ_TO_IPST(q);
18181 	} else {
18182 		ipst = CONNQ_TO_IPST(q);
18183 	}
18184 	ASSERT(ipst != NULL);
18185 	sctps = ipst->ips_netstack->netstack_sctp;
18186 
18187 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18188 		return (0);
18189 	}
18190 
18191 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18192 	    ipst)) == NULL) {
18193 		return (1);
18194 	}
18195 
18196 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18197 		return (1);
18198 	}
18199 
18200 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18201 		return (1);
18202 	}
18203 
18204 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18205 		return (1);
18206 	}
18207 
18208 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18209 		return (1);
18210 	}
18211 
18212 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18213 		return (1);
18214 	}
18215 
18216 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18217 		return (1);
18218 	}
18219 
18220 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18221 		return (1);
18222 	}
18223 
18224 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18225 		return (1);
18226 	}
18227 
18228 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18229 		return (1);
18230 	}
18231 
18232 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18233 		return (1);
18234 	}
18235 
18236 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18237 		return (1);
18238 	}
18239 
18240 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18241 		return (1);
18242 	}
18243 
18244 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18245 		return (1);
18246 	}
18247 
18248 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18249 		return (1);
18250 	}
18251 
18252 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18253 	if (mpctl == NULL) {
18254 		return (1);
18255 	}
18256 
18257 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18258 		return (1);
18259 	}
18260 	freemsg(mpctl);
18261 	return (1);
18262 }
18263 
18264 
18265 /* Get global (legacy) IPv4 statistics */
18266 static mblk_t *
18267 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18268     ip_stack_t *ipst)
18269 {
18270 	mib2_ip_t		old_ip_mib;
18271 	struct opthdr		*optp;
18272 	mblk_t			*mp2ctl;
18273 
18274 	/*
18275 	 * make a copy of the original message
18276 	 */
18277 	mp2ctl = copymsg(mpctl);
18278 
18279 	/* fixed length IP structure... */
18280 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18281 	optp->level = MIB2_IP;
18282 	optp->name = 0;
18283 	SET_MIB(old_ip_mib.ipForwarding,
18284 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18285 	SET_MIB(old_ip_mib.ipDefaultTTL,
18286 	    (uint32_t)ipst->ips_ip_def_ttl);
18287 	SET_MIB(old_ip_mib.ipReasmTimeout,
18288 	    ipst->ips_ip_g_frag_timeout);
18289 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18290 	    sizeof (mib2_ipAddrEntry_t));
18291 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18292 	    sizeof (mib2_ipRouteEntry_t));
18293 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18294 	    sizeof (mib2_ipNetToMediaEntry_t));
18295 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18296 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18297 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18298 	    sizeof (mib2_ipAttributeEntry_t));
18299 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18300 
18301 	/*
18302 	 * Grab the statistics from the new IP MIB
18303 	 */
18304 	SET_MIB(old_ip_mib.ipInReceives,
18305 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18306 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18307 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18308 	SET_MIB(old_ip_mib.ipForwDatagrams,
18309 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18310 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18311 	    ipmib->ipIfStatsInUnknownProtos);
18312 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18313 	SET_MIB(old_ip_mib.ipInDelivers,
18314 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18315 	SET_MIB(old_ip_mib.ipOutRequests,
18316 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18317 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18318 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18319 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18320 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18321 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18322 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18323 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18324 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18325 
18326 	/* ipRoutingDiscards is not being used */
18327 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18328 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18329 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18330 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18331 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18332 	    ipmib->ipIfStatsReasmDuplicates);
18333 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18334 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18335 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18336 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18337 	SET_MIB(old_ip_mib.rawipInOverflows,
18338 	    ipmib->rawipIfStatsInOverflows);
18339 
18340 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18341 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18342 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18343 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18344 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18345 	    ipmib->ipIfStatsOutSwitchIPVersion);
18346 
18347 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18348 	    (int)sizeof (old_ip_mib))) {
18349 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18350 		    (uint_t)sizeof (old_ip_mib)));
18351 	}
18352 
18353 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18354 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18355 	    (int)optp->level, (int)optp->name, (int)optp->len));
18356 	qreply(q, mpctl);
18357 	return (mp2ctl);
18358 }
18359 
18360 /* Per interface IPv4 statistics */
18361 static mblk_t *
18362 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18363 {
18364 	struct opthdr		*optp;
18365 	mblk_t			*mp2ctl;
18366 	ill_t			*ill;
18367 	ill_walk_context_t	ctx;
18368 	mblk_t			*mp_tail = NULL;
18369 	mib2_ipIfStatsEntry_t	global_ip_mib;
18370 
18371 	/*
18372 	 * Make a copy of the original message
18373 	 */
18374 	mp2ctl = copymsg(mpctl);
18375 
18376 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18377 	optp->level = MIB2_IP;
18378 	optp->name = MIB2_IP_TRAFFIC_STATS;
18379 	/* Include "unknown interface" ip_mib */
18380 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18381 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18382 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18383 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18384 	    (ipst->ips_ip_g_forward ? 1 : 2));
18385 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18386 	    (uint32_t)ipst->ips_ip_def_ttl);
18387 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18388 	    sizeof (mib2_ipIfStatsEntry_t));
18389 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18390 	    sizeof (mib2_ipAddrEntry_t));
18391 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18392 	    sizeof (mib2_ipRouteEntry_t));
18393 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18394 	    sizeof (mib2_ipNetToMediaEntry_t));
18395 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18396 	    sizeof (ip_member_t));
18397 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18398 	    sizeof (ip_grpsrc_t));
18399 
18400 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18401 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18402 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18403 		    "failed to allocate %u bytes\n",
18404 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18405 	}
18406 
18407 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18408 
18409 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18410 	ill = ILL_START_WALK_V4(&ctx, ipst);
18411 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18412 		ill->ill_ip_mib->ipIfStatsIfIndex =
18413 		    ill->ill_phyint->phyint_ifindex;
18414 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18415 		    (ipst->ips_ip_g_forward ? 1 : 2));
18416 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18417 		    (uint32_t)ipst->ips_ip_def_ttl);
18418 
18419 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18420 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18421 		    (char *)ill->ill_ip_mib,
18422 		    (int)sizeof (*ill->ill_ip_mib))) {
18423 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18424 			    "failed to allocate %u bytes\n",
18425 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18426 		}
18427 	}
18428 	rw_exit(&ipst->ips_ill_g_lock);
18429 
18430 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18431 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18432 	    "level %d, name %d, len %d\n",
18433 	    (int)optp->level, (int)optp->name, (int)optp->len));
18434 	qreply(q, mpctl);
18435 
18436 	if (mp2ctl == NULL)
18437 		return (NULL);
18438 
18439 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18440 }
18441 
18442 /* Global IPv4 ICMP statistics */
18443 static mblk_t *
18444 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18445 {
18446 	struct opthdr		*optp;
18447 	mblk_t			*mp2ctl;
18448 
18449 	/*
18450 	 * Make a copy of the original message
18451 	 */
18452 	mp2ctl = copymsg(mpctl);
18453 
18454 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18455 	optp->level = MIB2_ICMP;
18456 	optp->name = 0;
18457 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18458 	    (int)sizeof (ipst->ips_icmp_mib))) {
18459 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18460 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18461 	}
18462 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18463 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18464 	    (int)optp->level, (int)optp->name, (int)optp->len));
18465 	qreply(q, mpctl);
18466 	return (mp2ctl);
18467 }
18468 
18469 /* Global IPv4 IGMP statistics */
18470 static mblk_t *
18471 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18472 {
18473 	struct opthdr		*optp;
18474 	mblk_t			*mp2ctl;
18475 
18476 	/*
18477 	 * make a copy of the original message
18478 	 */
18479 	mp2ctl = copymsg(mpctl);
18480 
18481 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18482 	optp->level = EXPER_IGMP;
18483 	optp->name = 0;
18484 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18485 	    (int)sizeof (ipst->ips_igmpstat))) {
18486 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18487 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18488 	}
18489 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18490 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18491 	    (int)optp->level, (int)optp->name, (int)optp->len));
18492 	qreply(q, mpctl);
18493 	return (mp2ctl);
18494 }
18495 
18496 /* Global IPv4 Multicast Routing statistics */
18497 static mblk_t *
18498 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18499 {
18500 	struct opthdr		*optp;
18501 	mblk_t			*mp2ctl;
18502 
18503 	/*
18504 	 * make a copy of the original message
18505 	 */
18506 	mp2ctl = copymsg(mpctl);
18507 
18508 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18509 	optp->level = EXPER_DVMRP;
18510 	optp->name = 0;
18511 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18512 		ip0dbg(("ip_mroute_stats: failed\n"));
18513 	}
18514 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18515 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18516 	    (int)optp->level, (int)optp->name, (int)optp->len));
18517 	qreply(q, mpctl);
18518 	return (mp2ctl);
18519 }
18520 
18521 /* IPv4 address information */
18522 static mblk_t *
18523 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18524 {
18525 	struct opthdr		*optp;
18526 	mblk_t			*mp2ctl;
18527 	mblk_t			*mp_tail = NULL;
18528 	ill_t			*ill;
18529 	ipif_t			*ipif;
18530 	uint_t			bitval;
18531 	mib2_ipAddrEntry_t	mae;
18532 	zoneid_t		zoneid;
18533 	ill_walk_context_t ctx;
18534 
18535 	/*
18536 	 * make a copy of the original message
18537 	 */
18538 	mp2ctl = copymsg(mpctl);
18539 
18540 	/* ipAddrEntryTable */
18541 
18542 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18543 	optp->level = MIB2_IP;
18544 	optp->name = MIB2_IP_ADDR;
18545 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18546 
18547 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18548 	ill = ILL_START_WALK_V4(&ctx, ipst);
18549 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18550 		for (ipif = ill->ill_ipif; ipif != NULL;
18551 		    ipif = ipif->ipif_next) {
18552 			if (ipif->ipif_zoneid != zoneid &&
18553 			    ipif->ipif_zoneid != ALL_ZONES)
18554 				continue;
18555 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18556 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18557 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18558 
18559 			(void) ipif_get_name(ipif,
18560 			    mae.ipAdEntIfIndex.o_bytes,
18561 			    OCTET_LENGTH);
18562 			mae.ipAdEntIfIndex.o_length =
18563 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18564 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18565 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18566 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18567 			mae.ipAdEntInfo.ae_subnet_len =
18568 			    ip_mask_to_plen(ipif->ipif_net_mask);
18569 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18570 			for (bitval = 1;
18571 			    bitval &&
18572 			    !(bitval & ipif->ipif_brd_addr);
18573 			    bitval <<= 1)
18574 				noop;
18575 			mae.ipAdEntBcastAddr = bitval;
18576 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18577 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18578 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18579 			mae.ipAdEntInfo.ae_broadcast_addr =
18580 			    ipif->ipif_brd_addr;
18581 			mae.ipAdEntInfo.ae_pp_dst_addr =
18582 			    ipif->ipif_pp_dst_addr;
18583 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18584 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18585 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18586 
18587 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18588 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18589 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18590 				    "allocate %u bytes\n",
18591 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18592 			}
18593 		}
18594 	}
18595 	rw_exit(&ipst->ips_ill_g_lock);
18596 
18597 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18598 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18599 	    (int)optp->level, (int)optp->name, (int)optp->len));
18600 	qreply(q, mpctl);
18601 	return (mp2ctl);
18602 }
18603 
18604 /* IPv6 address information */
18605 static mblk_t *
18606 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18607 {
18608 	struct opthdr		*optp;
18609 	mblk_t			*mp2ctl;
18610 	mblk_t			*mp_tail = NULL;
18611 	ill_t			*ill;
18612 	ipif_t			*ipif;
18613 	mib2_ipv6AddrEntry_t	mae6;
18614 	zoneid_t		zoneid;
18615 	ill_walk_context_t	ctx;
18616 
18617 	/*
18618 	 * make a copy of the original message
18619 	 */
18620 	mp2ctl = copymsg(mpctl);
18621 
18622 	/* ipv6AddrEntryTable */
18623 
18624 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18625 	optp->level = MIB2_IP6;
18626 	optp->name = MIB2_IP6_ADDR;
18627 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18628 
18629 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18630 	ill = ILL_START_WALK_V6(&ctx, ipst);
18631 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18632 		for (ipif = ill->ill_ipif; ipif != NULL;
18633 		    ipif = ipif->ipif_next) {
18634 			if (ipif->ipif_zoneid != zoneid &&
18635 			    ipif->ipif_zoneid != ALL_ZONES)
18636 				continue;
18637 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18638 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18639 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18640 
18641 			(void) ipif_get_name(ipif,
18642 			    mae6.ipv6AddrIfIndex.o_bytes,
18643 			    OCTET_LENGTH);
18644 			mae6.ipv6AddrIfIndex.o_length =
18645 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18646 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18647 			mae6.ipv6AddrPfxLength =
18648 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18649 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18650 			mae6.ipv6AddrInfo.ae_subnet_len =
18651 			    mae6.ipv6AddrPfxLength;
18652 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18653 
18654 			/* Type: stateless(1), stateful(2), unknown(3) */
18655 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18656 				mae6.ipv6AddrType = 1;
18657 			else
18658 				mae6.ipv6AddrType = 2;
18659 			/* Anycast: true(1), false(2) */
18660 			if (ipif->ipif_flags & IPIF_ANYCAST)
18661 				mae6.ipv6AddrAnycastFlag = 1;
18662 			else
18663 				mae6.ipv6AddrAnycastFlag = 2;
18664 
18665 			/*
18666 			 * Address status: preferred(1), deprecated(2),
18667 			 * invalid(3), inaccessible(4), unknown(5)
18668 			 */
18669 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18670 				mae6.ipv6AddrStatus = 3;
18671 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18672 				mae6.ipv6AddrStatus = 2;
18673 			else
18674 				mae6.ipv6AddrStatus = 1;
18675 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18676 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18677 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18678 			    ipif->ipif_v6pp_dst_addr;
18679 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18680 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18681 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18682 			mae6.ipv6AddrIdentifier = ill->ill_token;
18683 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18684 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18685 			mae6.ipv6AddrRetransmitTime =
18686 			    ill->ill_reachable_retrans_time;
18687 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18688 			    (char *)&mae6,
18689 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18690 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18691 				    "allocate %u bytes\n",
18692 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18693 			}
18694 		}
18695 	}
18696 	rw_exit(&ipst->ips_ill_g_lock);
18697 
18698 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18699 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18700 	    (int)optp->level, (int)optp->name, (int)optp->len));
18701 	qreply(q, mpctl);
18702 	return (mp2ctl);
18703 }
18704 
18705 /* IPv4 multicast group membership. */
18706 static mblk_t *
18707 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18708 {
18709 	struct opthdr		*optp;
18710 	mblk_t			*mp2ctl;
18711 	ill_t			*ill;
18712 	ipif_t			*ipif;
18713 	ilm_t			*ilm;
18714 	ip_member_t		ipm;
18715 	mblk_t			*mp_tail = NULL;
18716 	ill_walk_context_t	ctx;
18717 	zoneid_t		zoneid;
18718 
18719 	/*
18720 	 * make a copy of the original message
18721 	 */
18722 	mp2ctl = copymsg(mpctl);
18723 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18724 
18725 	/* ipGroupMember table */
18726 	optp = (struct opthdr *)&mpctl->b_rptr[
18727 	    sizeof (struct T_optmgmt_ack)];
18728 	optp->level = MIB2_IP;
18729 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18730 
18731 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18732 	ill = ILL_START_WALK_V4(&ctx, ipst);
18733 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18734 		ILM_WALKER_HOLD(ill);
18735 		for (ipif = ill->ill_ipif; ipif != NULL;
18736 		    ipif = ipif->ipif_next) {
18737 			if (ipif->ipif_zoneid != zoneid &&
18738 			    ipif->ipif_zoneid != ALL_ZONES)
18739 				continue;	/* not this zone */
18740 			(void) ipif_get_name(ipif,
18741 			    ipm.ipGroupMemberIfIndex.o_bytes,
18742 			    OCTET_LENGTH);
18743 			ipm.ipGroupMemberIfIndex.o_length =
18744 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18745 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18746 				ASSERT(ilm->ilm_ipif != NULL);
18747 				ASSERT(ilm->ilm_ill == NULL);
18748 				if (ilm->ilm_ipif != ipif)
18749 					continue;
18750 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18751 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18752 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18753 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18754 				    (char *)&ipm, (int)sizeof (ipm))) {
18755 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18756 					    "failed to allocate %u bytes\n",
18757 					    (uint_t)sizeof (ipm)));
18758 				}
18759 			}
18760 		}
18761 		ILM_WALKER_RELE(ill);
18762 	}
18763 	rw_exit(&ipst->ips_ill_g_lock);
18764 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18765 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18766 	    (int)optp->level, (int)optp->name, (int)optp->len));
18767 	qreply(q, mpctl);
18768 	return (mp2ctl);
18769 }
18770 
18771 /* IPv6 multicast group membership. */
18772 static mblk_t *
18773 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18774 {
18775 	struct opthdr		*optp;
18776 	mblk_t			*mp2ctl;
18777 	ill_t			*ill;
18778 	ilm_t			*ilm;
18779 	ipv6_member_t		ipm6;
18780 	mblk_t			*mp_tail = NULL;
18781 	ill_walk_context_t	ctx;
18782 	zoneid_t		zoneid;
18783 
18784 	/*
18785 	 * make a copy of the original message
18786 	 */
18787 	mp2ctl = copymsg(mpctl);
18788 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18789 
18790 	/* ip6GroupMember table */
18791 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18792 	optp->level = MIB2_IP6;
18793 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18794 
18795 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18796 	ill = ILL_START_WALK_V6(&ctx, ipst);
18797 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18798 		ILM_WALKER_HOLD(ill);
18799 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18800 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18801 			ASSERT(ilm->ilm_ipif == NULL);
18802 			ASSERT(ilm->ilm_ill != NULL);
18803 			if (ilm->ilm_zoneid != zoneid)
18804 				continue;	/* not this zone */
18805 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18806 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18807 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18808 			if (!snmp_append_data2(mpctl->b_cont,
18809 			    &mp_tail,
18810 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18811 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18812 				    "failed to allocate %u bytes\n",
18813 				    (uint_t)sizeof (ipm6)));
18814 			}
18815 		}
18816 		ILM_WALKER_RELE(ill);
18817 	}
18818 	rw_exit(&ipst->ips_ill_g_lock);
18819 
18820 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18821 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18822 	    (int)optp->level, (int)optp->name, (int)optp->len));
18823 	qreply(q, mpctl);
18824 	return (mp2ctl);
18825 }
18826 
18827 /* IP multicast filtered sources */
18828 static mblk_t *
18829 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18830 {
18831 	struct opthdr		*optp;
18832 	mblk_t			*mp2ctl;
18833 	ill_t			*ill;
18834 	ipif_t			*ipif;
18835 	ilm_t			*ilm;
18836 	ip_grpsrc_t		ips;
18837 	mblk_t			*mp_tail = NULL;
18838 	ill_walk_context_t	ctx;
18839 	zoneid_t		zoneid;
18840 	int			i;
18841 	slist_t			*sl;
18842 
18843 	/*
18844 	 * make a copy of the original message
18845 	 */
18846 	mp2ctl = copymsg(mpctl);
18847 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18848 
18849 	/* ipGroupSource table */
18850 	optp = (struct opthdr *)&mpctl->b_rptr[
18851 	    sizeof (struct T_optmgmt_ack)];
18852 	optp->level = MIB2_IP;
18853 	optp->name = EXPER_IP_GROUP_SOURCES;
18854 
18855 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18856 	ill = ILL_START_WALK_V4(&ctx, ipst);
18857 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18858 		ILM_WALKER_HOLD(ill);
18859 		for (ipif = ill->ill_ipif; ipif != NULL;
18860 		    ipif = ipif->ipif_next) {
18861 			if (ipif->ipif_zoneid != zoneid)
18862 				continue;	/* not this zone */
18863 			(void) ipif_get_name(ipif,
18864 			    ips.ipGroupSourceIfIndex.o_bytes,
18865 			    OCTET_LENGTH);
18866 			ips.ipGroupSourceIfIndex.o_length =
18867 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18868 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18869 				ASSERT(ilm->ilm_ipif != NULL);
18870 				ASSERT(ilm->ilm_ill == NULL);
18871 				sl = ilm->ilm_filter;
18872 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18873 					continue;
18874 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18875 				for (i = 0; i < sl->sl_numsrc; i++) {
18876 					if (!IN6_IS_ADDR_V4MAPPED(
18877 					    &sl->sl_addr[i]))
18878 						continue;
18879 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18880 					    ips.ipGroupSourceAddress);
18881 					if (snmp_append_data2(mpctl->b_cont,
18882 					    &mp_tail, (char *)&ips,
18883 					    (int)sizeof (ips)) == 0) {
18884 						ip1dbg(("ip_snmp_get_mib2_"
18885 						    "ip_group_src: failed to "
18886 						    "allocate %u bytes\n",
18887 						    (uint_t)sizeof (ips)));
18888 					}
18889 				}
18890 			}
18891 		}
18892 		ILM_WALKER_RELE(ill);
18893 	}
18894 	rw_exit(&ipst->ips_ill_g_lock);
18895 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18896 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18897 	    (int)optp->level, (int)optp->name, (int)optp->len));
18898 	qreply(q, mpctl);
18899 	return (mp2ctl);
18900 }
18901 
18902 /* IPv6 multicast filtered sources. */
18903 static mblk_t *
18904 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18905 {
18906 	struct opthdr		*optp;
18907 	mblk_t			*mp2ctl;
18908 	ill_t			*ill;
18909 	ilm_t			*ilm;
18910 	ipv6_grpsrc_t		ips6;
18911 	mblk_t			*mp_tail = NULL;
18912 	ill_walk_context_t	ctx;
18913 	zoneid_t		zoneid;
18914 	int			i;
18915 	slist_t			*sl;
18916 
18917 	/*
18918 	 * make a copy of the original message
18919 	 */
18920 	mp2ctl = copymsg(mpctl);
18921 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18922 
18923 	/* ip6GroupMember table */
18924 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18925 	optp->level = MIB2_IP6;
18926 	optp->name = EXPER_IP6_GROUP_SOURCES;
18927 
18928 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18929 	ill = ILL_START_WALK_V6(&ctx, ipst);
18930 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18931 		ILM_WALKER_HOLD(ill);
18932 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18933 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18934 			ASSERT(ilm->ilm_ipif == NULL);
18935 			ASSERT(ilm->ilm_ill != NULL);
18936 			sl = ilm->ilm_filter;
18937 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18938 				continue;
18939 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18940 			for (i = 0; i < sl->sl_numsrc; i++) {
18941 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18942 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18943 				    (char *)&ips6, (int)sizeof (ips6))) {
18944 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18945 					    "group_src: failed to allocate "
18946 					    "%u bytes\n",
18947 					    (uint_t)sizeof (ips6)));
18948 				}
18949 			}
18950 		}
18951 		ILM_WALKER_RELE(ill);
18952 	}
18953 	rw_exit(&ipst->ips_ill_g_lock);
18954 
18955 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18956 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18957 	    (int)optp->level, (int)optp->name, (int)optp->len));
18958 	qreply(q, mpctl);
18959 	return (mp2ctl);
18960 }
18961 
18962 /* Multicast routing virtual interface table. */
18963 static mblk_t *
18964 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18965 {
18966 	struct opthdr		*optp;
18967 	mblk_t			*mp2ctl;
18968 
18969 	/*
18970 	 * make a copy of the original message
18971 	 */
18972 	mp2ctl = copymsg(mpctl);
18973 
18974 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18975 	optp->level = EXPER_DVMRP;
18976 	optp->name = EXPER_DVMRP_VIF;
18977 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18978 		ip0dbg(("ip_mroute_vif: failed\n"));
18979 	}
18980 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18981 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18982 	    (int)optp->level, (int)optp->name, (int)optp->len));
18983 	qreply(q, mpctl);
18984 	return (mp2ctl);
18985 }
18986 
18987 /* Multicast routing table. */
18988 static mblk_t *
18989 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18990 {
18991 	struct opthdr		*optp;
18992 	mblk_t			*mp2ctl;
18993 
18994 	/*
18995 	 * make a copy of the original message
18996 	 */
18997 	mp2ctl = copymsg(mpctl);
18998 
18999 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19000 	optp->level = EXPER_DVMRP;
19001 	optp->name = EXPER_DVMRP_MRT;
19002 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
19003 		ip0dbg(("ip_mroute_mrt: failed\n"));
19004 	}
19005 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19006 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
19007 	    (int)optp->level, (int)optp->name, (int)optp->len));
19008 	qreply(q, mpctl);
19009 	return (mp2ctl);
19010 }
19011 
19012 /*
19013  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
19014  * in one IRE walk.
19015  */
19016 static mblk_t *
19017 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19018 {
19019 	struct opthdr	*optp;
19020 	mblk_t		*mp2ctl;	/* Returned */
19021 	mblk_t		*mp3ctl;	/* nettomedia */
19022 	mblk_t		*mp4ctl;	/* routeattrs */
19023 	iproutedata_t	ird;
19024 	zoneid_t	zoneid;
19025 
19026 	/*
19027 	 * make copies of the original message
19028 	 *	- mp2ctl is returned unchanged to the caller for his use
19029 	 *	- mpctl is sent upstream as ipRouteEntryTable
19030 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19031 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19032 	 */
19033 	mp2ctl = copymsg(mpctl);
19034 	mp3ctl = copymsg(mpctl);
19035 	mp4ctl = copymsg(mpctl);
19036 	if (mp3ctl == NULL || mp4ctl == NULL) {
19037 		freemsg(mp4ctl);
19038 		freemsg(mp3ctl);
19039 		freemsg(mp2ctl);
19040 		freemsg(mpctl);
19041 		return (NULL);
19042 	}
19043 
19044 	bzero(&ird, sizeof (ird));
19045 
19046 	ird.ird_route.lp_head = mpctl->b_cont;
19047 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19048 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19049 
19050 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19051 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19052 	if (zoneid == GLOBAL_ZONEID) {
19053 		/*
19054 		 * Those IREs are used by Mobile-IP; since mipagent(1M)
19055 		 * requires the sys_net_config or sys_ip_config privilege,
19056 		 * it can only run in the global zone or an exclusive-IP zone,
19057 		 * and both those have a conn_zoneid == GLOBAL_ZONEID.
19058 		 */
19059 		ire_walk_srcif_table_v4(ip_snmp_get2_v4, &ird, ipst);
19060 		ire_walk_ill_mrtun(0, 0, ip_snmp_get2_v4, &ird, NULL, ipst);
19061 	}
19062 
19063 	/* ipRouteEntryTable in mpctl */
19064 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19065 	optp->level = MIB2_IP;
19066 	optp->name = MIB2_IP_ROUTE;
19067 	optp->len = msgdsize(ird.ird_route.lp_head);
19068 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19069 	    (int)optp->level, (int)optp->name, (int)optp->len));
19070 	qreply(q, mpctl);
19071 
19072 	/* ipNetToMediaEntryTable in mp3ctl */
19073 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19074 	optp->level = MIB2_IP;
19075 	optp->name = MIB2_IP_MEDIA;
19076 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19077 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19078 	    (int)optp->level, (int)optp->name, (int)optp->len));
19079 	qreply(q, mp3ctl);
19080 
19081 	/* ipRouteAttributeTable in mp4ctl */
19082 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19083 	optp->level = MIB2_IP;
19084 	optp->name = EXPER_IP_RTATTR;
19085 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19086 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19087 	    (int)optp->level, (int)optp->name, (int)optp->len));
19088 	if (optp->len == 0)
19089 		freemsg(mp4ctl);
19090 	else
19091 		qreply(q, mp4ctl);
19092 
19093 	return (mp2ctl);
19094 }
19095 
19096 /*
19097  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19098  * ipv6NetToMediaEntryTable in an NDP walk.
19099  */
19100 static mblk_t *
19101 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19102 {
19103 	struct opthdr	*optp;
19104 	mblk_t		*mp2ctl;	/* Returned */
19105 	mblk_t		*mp3ctl;	/* nettomedia */
19106 	mblk_t		*mp4ctl;	/* routeattrs */
19107 	iproutedata_t	ird;
19108 	zoneid_t	zoneid;
19109 
19110 	/*
19111 	 * make copies of the original message
19112 	 *	- mp2ctl is returned unchanged to the caller for his use
19113 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19114 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19115 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19116 	 */
19117 	mp2ctl = copymsg(mpctl);
19118 	mp3ctl = copymsg(mpctl);
19119 	mp4ctl = copymsg(mpctl);
19120 	if (mp3ctl == NULL || mp4ctl == NULL) {
19121 		freemsg(mp4ctl);
19122 		freemsg(mp3ctl);
19123 		freemsg(mp2ctl);
19124 		freemsg(mpctl);
19125 		return (NULL);
19126 	}
19127 
19128 	bzero(&ird, sizeof (ird));
19129 
19130 	ird.ird_route.lp_head = mpctl->b_cont;
19131 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19132 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19133 
19134 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19135 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19136 
19137 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19138 	optp->level = MIB2_IP6;
19139 	optp->name = MIB2_IP6_ROUTE;
19140 	optp->len = msgdsize(ird.ird_route.lp_head);
19141 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19142 	    (int)optp->level, (int)optp->name, (int)optp->len));
19143 	qreply(q, mpctl);
19144 
19145 	/* ipv6NetToMediaEntryTable in mp3ctl */
19146 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19147 
19148 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19149 	optp->level = MIB2_IP6;
19150 	optp->name = MIB2_IP6_MEDIA;
19151 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19152 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19153 	    (int)optp->level, (int)optp->name, (int)optp->len));
19154 	qreply(q, mp3ctl);
19155 
19156 	/* ipv6RouteAttributeTable in mp4ctl */
19157 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19158 	optp->level = MIB2_IP6;
19159 	optp->name = EXPER_IP_RTATTR;
19160 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19161 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19162 	    (int)optp->level, (int)optp->name, (int)optp->len));
19163 	if (optp->len == 0)
19164 		freemsg(mp4ctl);
19165 	else
19166 		qreply(q, mp4ctl);
19167 
19168 	return (mp2ctl);
19169 }
19170 
19171 /*
19172  * IPv6 mib: One per ill
19173  */
19174 static mblk_t *
19175 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19176 {
19177 	struct opthdr		*optp;
19178 	mblk_t			*mp2ctl;
19179 	ill_t			*ill;
19180 	ill_walk_context_t	ctx;
19181 	mblk_t			*mp_tail = NULL;
19182 
19183 	/*
19184 	 * Make a copy of the original message
19185 	 */
19186 	mp2ctl = copymsg(mpctl);
19187 
19188 	/* fixed length IPv6 structure ... */
19189 
19190 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19191 	optp->level = MIB2_IP6;
19192 	optp->name = 0;
19193 	/* Include "unknown interface" ip6_mib */
19194 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19195 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19196 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19197 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19198 	    ipst->ips_ipv6_forward ? 1 : 2);
19199 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19200 	    ipst->ips_ipv6_def_hops);
19201 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19202 	    sizeof (mib2_ipIfStatsEntry_t));
19203 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19204 	    sizeof (mib2_ipv6AddrEntry_t));
19205 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19206 	    sizeof (mib2_ipv6RouteEntry_t));
19207 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19208 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19209 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19210 	    sizeof (ipv6_member_t));
19211 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19212 	    sizeof (ipv6_grpsrc_t));
19213 
19214 	/*
19215 	 * Synchronize 64- and 32-bit counters
19216 	 */
19217 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19218 	    ipIfStatsHCInReceives);
19219 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19220 	    ipIfStatsHCInDelivers);
19221 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19222 	    ipIfStatsHCOutRequests);
19223 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19224 	    ipIfStatsHCOutForwDatagrams);
19225 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19226 	    ipIfStatsHCOutMcastPkts);
19227 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19228 	    ipIfStatsHCInMcastPkts);
19229 
19230 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19231 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19232 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19233 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19234 	}
19235 
19236 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19237 	ill = ILL_START_WALK_V6(&ctx, ipst);
19238 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19239 		ill->ill_ip_mib->ipIfStatsIfIndex =
19240 		    ill->ill_phyint->phyint_ifindex;
19241 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19242 		    ipst->ips_ipv6_forward ? 1 : 2);
19243 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19244 		    ill->ill_max_hops);
19245 
19246 		/*
19247 		 * Synchronize 64- and 32-bit counters
19248 		 */
19249 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19250 		    ipIfStatsHCInReceives);
19251 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19252 		    ipIfStatsHCInDelivers);
19253 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19254 		    ipIfStatsHCOutRequests);
19255 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19256 		    ipIfStatsHCOutForwDatagrams);
19257 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19258 		    ipIfStatsHCOutMcastPkts);
19259 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19260 		    ipIfStatsHCInMcastPkts);
19261 
19262 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19263 		    (char *)ill->ill_ip_mib,
19264 		    (int)sizeof (*ill->ill_ip_mib))) {
19265 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19266 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19267 		}
19268 	}
19269 	rw_exit(&ipst->ips_ill_g_lock);
19270 
19271 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19272 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19273 	    (int)optp->level, (int)optp->name, (int)optp->len));
19274 	qreply(q, mpctl);
19275 	return (mp2ctl);
19276 }
19277 
19278 /*
19279  * ICMPv6 mib: One per ill
19280  */
19281 static mblk_t *
19282 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19283 {
19284 	struct opthdr		*optp;
19285 	mblk_t			*mp2ctl;
19286 	ill_t			*ill;
19287 	ill_walk_context_t	ctx;
19288 	mblk_t			*mp_tail = NULL;
19289 	/*
19290 	 * Make a copy of the original message
19291 	 */
19292 	mp2ctl = copymsg(mpctl);
19293 
19294 	/* fixed length ICMPv6 structure ... */
19295 
19296 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19297 	optp->level = MIB2_ICMP6;
19298 	optp->name = 0;
19299 	/* Include "unknown interface" icmp6_mib */
19300 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19301 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19302 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19303 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19304 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19305 	    (char *)&ipst->ips_icmp6_mib,
19306 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19307 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19308 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19309 	}
19310 
19311 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19312 	ill = ILL_START_WALK_V6(&ctx, ipst);
19313 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19314 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19315 		    ill->ill_phyint->phyint_ifindex;
19316 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19317 		    (char *)ill->ill_icmp6_mib,
19318 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19319 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19320 			    "%u bytes\n",
19321 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19322 		}
19323 	}
19324 	rw_exit(&ipst->ips_ill_g_lock);
19325 
19326 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19327 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19328 	    (int)optp->level, (int)optp->name, (int)optp->len));
19329 	qreply(q, mpctl);
19330 	return (mp2ctl);
19331 }
19332 
19333 /*
19334  * ire_walk routine to create both ipRouteEntryTable and
19335  * ipRouteAttributeTable in one IRE walk
19336  */
19337 static void
19338 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19339 {
19340 	ill_t				*ill;
19341 	ipif_t				*ipif;
19342 	mib2_ipRouteEntry_t		*re;
19343 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19344 	ipaddr_t			gw_addr;
19345 	tsol_ire_gw_secattr_t		*attrp;
19346 	tsol_gc_t			*gc = NULL;
19347 	tsol_gcgrp_t			*gcgrp = NULL;
19348 	uint_t				sacnt = 0;
19349 	int				i;
19350 
19351 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19352 
19353 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19354 		return;
19355 
19356 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19357 		mutex_enter(&attrp->igsa_lock);
19358 		if ((gc = attrp->igsa_gc) != NULL) {
19359 			gcgrp = gc->gc_grp;
19360 			ASSERT(gcgrp != NULL);
19361 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19362 			sacnt = 1;
19363 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19364 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19365 			gc = gcgrp->gcgrp_head;
19366 			sacnt = gcgrp->gcgrp_count;
19367 		}
19368 		mutex_exit(&attrp->igsa_lock);
19369 
19370 		/* do nothing if there's no gc to report */
19371 		if (gc == NULL) {
19372 			ASSERT(sacnt == 0);
19373 			if (gcgrp != NULL) {
19374 				/* we might as well drop the lock now */
19375 				rw_exit(&gcgrp->gcgrp_rwlock);
19376 				gcgrp = NULL;
19377 			}
19378 			attrp = NULL;
19379 		}
19380 
19381 		ASSERT(gc == NULL || (gcgrp != NULL &&
19382 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19383 	}
19384 	ASSERT(sacnt == 0 || gc != NULL);
19385 
19386 	if (sacnt != 0 &&
19387 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19388 		kmem_free(re, sizeof (*re));
19389 		rw_exit(&gcgrp->gcgrp_rwlock);
19390 		return;
19391 	}
19392 
19393 	/*
19394 	 * Return all IRE types for route table... let caller pick and choose
19395 	 */
19396 	re->ipRouteDest = ire->ire_addr;
19397 	ipif = ire->ire_ipif;
19398 	re->ipRouteIfIndex.o_length = 0;
19399 	if (ire->ire_type == IRE_CACHE) {
19400 		ill = (ill_t *)ire->ire_stq->q_ptr;
19401 		re->ipRouteIfIndex.o_length =
19402 		    ill->ill_name_length == 0 ? 0 :
19403 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19404 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19405 		    re->ipRouteIfIndex.o_length);
19406 	} else if (ipif != NULL) {
19407 		(void) ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes,
19408 		    OCTET_LENGTH);
19409 		re->ipRouteIfIndex.o_length =
19410 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19411 	}
19412 	re->ipRouteMetric1 = -1;
19413 	re->ipRouteMetric2 = -1;
19414 	re->ipRouteMetric3 = -1;
19415 	re->ipRouteMetric4 = -1;
19416 
19417 	gw_addr = ire->ire_gateway_addr;
19418 
19419 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19420 		re->ipRouteNextHop = ire->ire_src_addr;
19421 	else
19422 		re->ipRouteNextHop = gw_addr;
19423 	/* indirect(4), direct(3), or invalid(2) */
19424 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19425 		re->ipRouteType = 2;
19426 	else
19427 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19428 	re->ipRouteProto = -1;
19429 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19430 	re->ipRouteMask = ire->ire_mask;
19431 	re->ipRouteMetric5 = -1;
19432 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19433 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19434 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19435 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19436 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19437 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19438 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19439 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19440 	re->ipRouteInfo.re_in_ill.o_length = 0;
19441 
19442 	if (ire->ire_flags & RTF_DYNAMIC) {
19443 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19444 	} else {
19445 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19446 	}
19447 
19448 	if (ire->ire_in_ill != NULL) {
19449 		re->ipRouteInfo.re_in_ill.o_length =
19450 		    ire->ire_in_ill->ill_name_length == 0 ? 0 :
19451 		    MIN(OCTET_LENGTH, ire->ire_in_ill->ill_name_length - 1);
19452 		bcopy(ire->ire_in_ill->ill_name,
19453 		    re->ipRouteInfo.re_in_ill.o_bytes,
19454 		    re->ipRouteInfo.re_in_ill.o_length);
19455 	}
19456 	re->ipRouteInfo.re_in_src_addr = ire->ire_in_src_addr;
19457 
19458 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19459 	    (char *)re, (int)sizeof (*re))) {
19460 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19461 		    (uint_t)sizeof (*re)));
19462 	}
19463 
19464 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19465 		iaeptr->iae_routeidx = ird->ird_idx;
19466 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19467 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19468 	}
19469 
19470 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19471 	    (char *)iae, sacnt * sizeof (*iae))) {
19472 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19473 		    (unsigned)(sacnt * sizeof (*iae))));
19474 	}
19475 
19476 	/* bump route index for next pass */
19477 	ird->ird_idx++;
19478 
19479 	kmem_free(re, sizeof (*re));
19480 	if (sacnt != 0)
19481 		kmem_free(iae, sacnt * sizeof (*iae));
19482 
19483 	if (gcgrp != NULL)
19484 		rw_exit(&gcgrp->gcgrp_rwlock);
19485 }
19486 
19487 /*
19488  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19489  */
19490 static void
19491 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19492 {
19493 	ill_t				*ill;
19494 	ipif_t				*ipif;
19495 	mib2_ipv6RouteEntry_t		*re;
19496 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19497 	in6_addr_t			gw_addr_v6;
19498 	tsol_ire_gw_secattr_t		*attrp;
19499 	tsol_gc_t			*gc = NULL;
19500 	tsol_gcgrp_t			*gcgrp = NULL;
19501 	uint_t				sacnt = 0;
19502 	int				i;
19503 
19504 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19505 
19506 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19507 		return;
19508 
19509 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19510 		mutex_enter(&attrp->igsa_lock);
19511 		if ((gc = attrp->igsa_gc) != NULL) {
19512 			gcgrp = gc->gc_grp;
19513 			ASSERT(gcgrp != NULL);
19514 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19515 			sacnt = 1;
19516 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19517 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19518 			gc = gcgrp->gcgrp_head;
19519 			sacnt = gcgrp->gcgrp_count;
19520 		}
19521 		mutex_exit(&attrp->igsa_lock);
19522 
19523 		/* do nothing if there's no gc to report */
19524 		if (gc == NULL) {
19525 			ASSERT(sacnt == 0);
19526 			if (gcgrp != NULL) {
19527 				/* we might as well drop the lock now */
19528 				rw_exit(&gcgrp->gcgrp_rwlock);
19529 				gcgrp = NULL;
19530 			}
19531 			attrp = NULL;
19532 		}
19533 
19534 		ASSERT(gc == NULL || (gcgrp != NULL &&
19535 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19536 	}
19537 	ASSERT(sacnt == 0 || gc != NULL);
19538 
19539 	if (sacnt != 0 &&
19540 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19541 		kmem_free(re, sizeof (*re));
19542 		rw_exit(&gcgrp->gcgrp_rwlock);
19543 		return;
19544 	}
19545 
19546 	/*
19547 	 * Return all IRE types for route table... let caller pick and choose
19548 	 */
19549 	re->ipv6RouteDest = ire->ire_addr_v6;
19550 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19551 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19552 	re->ipv6RouteIfIndex.o_length = 0;
19553 	ipif = ire->ire_ipif;
19554 	if (ire->ire_type == IRE_CACHE) {
19555 		ill = (ill_t *)ire->ire_stq->q_ptr;
19556 		re->ipv6RouteIfIndex.o_length =
19557 		    ill->ill_name_length == 0 ? 0 :
19558 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19559 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19560 		    re->ipv6RouteIfIndex.o_length);
19561 	} else if (ipif != NULL) {
19562 		(void) ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes,
19563 		    OCTET_LENGTH);
19564 		re->ipv6RouteIfIndex.o_length =
19565 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19566 	}
19567 
19568 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19569 
19570 	mutex_enter(&ire->ire_lock);
19571 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19572 	mutex_exit(&ire->ire_lock);
19573 
19574 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19575 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19576 	else
19577 		re->ipv6RouteNextHop = gw_addr_v6;
19578 
19579 	/* remote(4), local(3), or discard(2) */
19580 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19581 		re->ipv6RouteType = 2;
19582 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19583 		re->ipv6RouteType = 3;
19584 	else
19585 		re->ipv6RouteType = 4;
19586 
19587 	re->ipv6RouteProtocol	= -1;
19588 	re->ipv6RoutePolicy	= 0;
19589 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19590 	re->ipv6RouteNextHopRDI	= 0;
19591 	re->ipv6RouteWeight	= 0;
19592 	re->ipv6RouteMetric	= 0;
19593 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19594 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19595 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19596 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19597 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19598 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19599 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19600 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19601 
19602 	if (ire->ire_flags & RTF_DYNAMIC) {
19603 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19604 	} else {
19605 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19606 	}
19607 
19608 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19609 	    (char *)re, (int)sizeof (*re))) {
19610 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19611 		    (uint_t)sizeof (*re)));
19612 	}
19613 
19614 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19615 		iaeptr->iae_routeidx = ird->ird_idx;
19616 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19617 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19618 	}
19619 
19620 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19621 	    (char *)iae, sacnt * sizeof (*iae))) {
19622 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19623 		    (unsigned)(sacnt * sizeof (*iae))));
19624 	}
19625 
19626 	/* bump route index for next pass */
19627 	ird->ird_idx++;
19628 
19629 	kmem_free(re, sizeof (*re));
19630 	if (sacnt != 0)
19631 		kmem_free(iae, sacnt * sizeof (*iae));
19632 
19633 	if (gcgrp != NULL)
19634 		rw_exit(&gcgrp->gcgrp_rwlock);
19635 }
19636 
19637 /*
19638  * ndp_walk routine to create ipv6NetToMediaEntryTable
19639  */
19640 static int
19641 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19642 {
19643 	ill_t				*ill;
19644 	mib2_ipv6NetToMediaEntry_t	ntme;
19645 	dl_unitdata_req_t		*dl;
19646 
19647 	ill = nce->nce_ill;
19648 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19649 		return (0);
19650 
19651 	/*
19652 	 * Neighbor cache entry attached to IRE with on-link
19653 	 * destination.
19654 	 */
19655 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19656 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19657 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19658 	    (nce->nce_res_mp != NULL)) {
19659 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19660 		ntme.ipv6NetToMediaPhysAddress.o_length =
19661 		    dl->dl_dest_addr_length;
19662 	} else {
19663 		ntme.ipv6NetToMediaPhysAddress.o_length =
19664 		    ill->ill_phys_addr_length;
19665 	}
19666 	if (nce->nce_res_mp != NULL) {
19667 		bcopy((char *)nce->nce_res_mp->b_rptr +
19668 		    NCE_LL_ADDR_OFFSET(ill),
19669 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19670 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19671 	} else {
19672 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19673 		    ill->ill_phys_addr_length);
19674 	}
19675 	/*
19676 	 * Note: Returns ND_* states. Should be:
19677 	 * reachable(1), stale(2), delay(3), probe(4),
19678 	 * invalid(5), unknown(6)
19679 	 */
19680 	ntme.ipv6NetToMediaState = nce->nce_state;
19681 	ntme.ipv6NetToMediaLastUpdated = 0;
19682 
19683 	/* other(1), dynamic(2), static(3), local(4) */
19684 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19685 		ntme.ipv6NetToMediaType = 4;
19686 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19687 		ntme.ipv6NetToMediaType = 1;
19688 	} else {
19689 		ntme.ipv6NetToMediaType = 2;
19690 	}
19691 
19692 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19693 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19694 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19695 		    (uint_t)sizeof (ntme)));
19696 	}
19697 	return (0);
19698 }
19699 
19700 /*
19701  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19702  */
19703 /* ARGSUSED */
19704 int
19705 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19706 {
19707 	switch (level) {
19708 	case MIB2_IP:
19709 	case MIB2_ICMP:
19710 		switch (name) {
19711 		default:
19712 			break;
19713 		}
19714 		return (1);
19715 	default:
19716 		return (1);
19717 	}
19718 }
19719 
19720 /*
19721  * When there exists both a 64- and 32-bit counter of a particular type
19722  * (i.e., InReceives), only the 64-bit counters are added.
19723  */
19724 void
19725 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19726 {
19727 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19728 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19729 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19730 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19731 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19732 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19733 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19734 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19735 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19736 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19737 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19738 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19739 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19740 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19741 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19742 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19743 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19744 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19745 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19746 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19747 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19748 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19749 	    o2->ipIfStatsInWrongIPVersion);
19750 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19751 	    o2->ipIfStatsInWrongIPVersion);
19752 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19753 	    o2->ipIfStatsOutSwitchIPVersion);
19754 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19755 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19756 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19757 	    o2->ipIfStatsHCInForwDatagrams);
19758 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19759 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19760 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19761 	    o2->ipIfStatsHCOutForwDatagrams);
19762 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19763 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19764 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19765 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19766 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19767 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19768 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19769 	    o2->ipIfStatsHCOutMcastOctets);
19770 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19771 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19772 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19773 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19774 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19775 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19776 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19777 }
19778 
19779 void
19780 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19781 {
19782 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19783 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19784 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19785 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19786 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19787 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19788 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19789 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19790 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19791 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19792 	    o2->ipv6IfIcmpInRouterSolicits);
19793 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19794 	    o2->ipv6IfIcmpInRouterAdvertisements);
19795 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19796 	    o2->ipv6IfIcmpInNeighborSolicits);
19797 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19798 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19799 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19800 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19801 	    o2->ipv6IfIcmpInGroupMembQueries);
19802 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19803 	    o2->ipv6IfIcmpInGroupMembResponses);
19804 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19805 	    o2->ipv6IfIcmpInGroupMembReductions);
19806 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19807 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19808 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19809 	    o2->ipv6IfIcmpOutDestUnreachs);
19810 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19811 	    o2->ipv6IfIcmpOutAdminProhibs);
19812 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19813 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19814 	    o2->ipv6IfIcmpOutParmProblems);
19815 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19816 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19817 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19818 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19819 	    o2->ipv6IfIcmpOutRouterSolicits);
19820 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19821 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19822 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19823 	    o2->ipv6IfIcmpOutNeighborSolicits);
19824 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19825 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19826 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19827 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19828 	    o2->ipv6IfIcmpOutGroupMembQueries);
19829 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19830 	    o2->ipv6IfIcmpOutGroupMembResponses);
19831 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19832 	    o2->ipv6IfIcmpOutGroupMembReductions);
19833 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19834 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19835 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19836 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19837 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19838 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19839 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19840 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19841 	    o2->ipv6IfIcmpInGroupMembTotal);
19842 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19843 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19844 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19845 	    o2->ipv6IfIcmpInGroupMembBadReports);
19846 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19847 	    o2->ipv6IfIcmpInGroupMembOurReports);
19848 }
19849 
19850 /*
19851  * Called before the options are updated to check if this packet will
19852  * be source routed from here.
19853  * This routine assumes that the options are well formed i.e. that they
19854  * have already been checked.
19855  */
19856 static boolean_t
19857 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19858 {
19859 	ipoptp_t	opts;
19860 	uchar_t		*opt;
19861 	uint8_t		optval;
19862 	uint8_t		optlen;
19863 	ipaddr_t	dst;
19864 	ire_t		*ire;
19865 
19866 	if (IS_SIMPLE_IPH(ipha)) {
19867 		ip2dbg(("not source routed\n"));
19868 		return (B_FALSE);
19869 	}
19870 	dst = ipha->ipha_dst;
19871 	for (optval = ipoptp_first(&opts, ipha);
19872 	    optval != IPOPT_EOL;
19873 	    optval = ipoptp_next(&opts)) {
19874 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19875 		opt = opts.ipoptp_cur;
19876 		optlen = opts.ipoptp_len;
19877 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19878 		    optval, optlen));
19879 		switch (optval) {
19880 			uint32_t off;
19881 		case IPOPT_SSRR:
19882 		case IPOPT_LSRR:
19883 			/*
19884 			 * If dst is one of our addresses and there are some
19885 			 * entries left in the source route return (true).
19886 			 */
19887 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19888 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19889 			if (ire == NULL) {
19890 				ip2dbg(("ip_source_routed: not next"
19891 				    " source route 0x%x\n",
19892 				    ntohl(dst)));
19893 				return (B_FALSE);
19894 			}
19895 			ire_refrele(ire);
19896 			off = opt[IPOPT_OFFSET];
19897 			off--;
19898 			if (optlen < IP_ADDR_LEN ||
19899 			    off > optlen - IP_ADDR_LEN) {
19900 				/* End of source route */
19901 				ip1dbg(("ip_source_routed: end of SR\n"));
19902 				return (B_FALSE);
19903 			}
19904 			return (B_TRUE);
19905 		}
19906 	}
19907 	ip2dbg(("not source routed\n"));
19908 	return (B_FALSE);
19909 }
19910 
19911 /*
19912  * Check if the packet contains any source route.
19913  */
19914 static boolean_t
19915 ip_source_route_included(ipha_t *ipha)
19916 {
19917 	ipoptp_t	opts;
19918 	uint8_t		optval;
19919 
19920 	if (IS_SIMPLE_IPH(ipha))
19921 		return (B_FALSE);
19922 	for (optval = ipoptp_first(&opts, ipha);
19923 	    optval != IPOPT_EOL;
19924 	    optval = ipoptp_next(&opts)) {
19925 		switch (optval) {
19926 		case IPOPT_SSRR:
19927 		case IPOPT_LSRR:
19928 			return (B_TRUE);
19929 		}
19930 	}
19931 	return (B_FALSE);
19932 }
19933 
19934 /*
19935  * Called when the IRE expiration timer fires.
19936  */
19937 void
19938 ip_trash_timer_expire(void *args)
19939 {
19940 	int			flush_flag = 0;
19941 	ire_expire_arg_t	iea;
19942 	ip_stack_t		*ipst = (ip_stack_t *)args;
19943 
19944 	iea.iea_ipst = ipst;	/* No netstack_hold */
19945 
19946 	/*
19947 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19948 	 * This lock makes sure that a new invocation of this function
19949 	 * that occurs due to an almost immediate timer firing will not
19950 	 * progress beyond this point until the current invocation is done
19951 	 */
19952 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19953 	ipst->ips_ip_ire_expire_id = 0;
19954 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19955 
19956 	/* Periodic timer */
19957 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19958 	    ipst->ips_ip_ire_arp_interval) {
19959 		/*
19960 		 * Remove all IRE_CACHE entries since they might
19961 		 * contain arp information.
19962 		 */
19963 		flush_flag |= FLUSH_ARP_TIME;
19964 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19965 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19966 	}
19967 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19968 	    ipst->ips_ip_ire_redir_interval) {
19969 		/* Remove all redirects */
19970 		flush_flag |= FLUSH_REDIRECT_TIME;
19971 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19972 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19973 	}
19974 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19975 	    ipst->ips_ip_ire_pathmtu_interval) {
19976 		/* Increase path mtu */
19977 		flush_flag |= FLUSH_MTU_TIME;
19978 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19979 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19980 	}
19981 
19982 	/*
19983 	 * Optimize for the case when there are no redirects in the
19984 	 * ftable, that is, no need to walk the ftable in that case.
19985 	 */
19986 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19987 		iea.iea_flush_flag = flush_flag;
19988 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19989 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19990 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19991 		    NULL, ALL_ZONES, ipst);
19992 	}
19993 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19994 	    ipst->ips_ip_redirect_cnt > 0) {
19995 		iea.iea_flush_flag = flush_flag;
19996 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19997 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19998 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19999 	}
20000 	if (flush_flag & FLUSH_MTU_TIME) {
20001 		/*
20002 		 * Walk all IPv6 IRE's and update them
20003 		 * Note that ARP and redirect timers are not
20004 		 * needed since NUD handles stale entries.
20005 		 */
20006 		flush_flag = FLUSH_MTU_TIME;
20007 		iea.iea_flush_flag = flush_flag;
20008 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
20009 		    ALL_ZONES, ipst);
20010 	}
20011 
20012 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
20013 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
20014 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
20015 
20016 	/*
20017 	 * Hold the lock to serialize timeout calls and prevent
20018 	 * stale values in ip_ire_expire_id. Otherwise it is possible
20019 	 * for the timer to fire and a new invocation of this function
20020 	 * to start before the return value of timeout has been stored
20021 	 * in ip_ire_expire_id by the current invocation.
20022 	 */
20023 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
20024 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
20025 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
20026 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
20027 }
20028 
20029 /*
20030  * Called by the memory allocator subsystem directly, when the system
20031  * is running low on memory.
20032  */
20033 /* ARGSUSED */
20034 void
20035 ip_trash_ire_reclaim(void *args)
20036 {
20037 	netstack_handle_t nh;
20038 	netstack_t *ns;
20039 
20040 	netstack_next_init(&nh);
20041 	while ((ns = netstack_next(&nh)) != NULL) {
20042 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
20043 		netstack_rele(ns);
20044 	}
20045 	netstack_next_fini(&nh);
20046 }
20047 
20048 static void
20049 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20050 {
20051 	ire_cache_count_t icc;
20052 	ire_cache_reclaim_t icr;
20053 	ncc_cache_count_t ncc;
20054 	nce_cache_reclaim_t ncr;
20055 	uint_t delete_cnt;
20056 	/*
20057 	 * Memory reclaim call back.
20058 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20059 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20060 	 * entries, determine what fraction to free for
20061 	 * each category of IRE_CACHE entries giving absolute priority
20062 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20063 	 * entry will be freed unless all offlink entries are freed).
20064 	 */
20065 	icc.icc_total = 0;
20066 	icc.icc_unused = 0;
20067 	icc.icc_offlink = 0;
20068 	icc.icc_pmtu = 0;
20069 	icc.icc_onlink = 0;
20070 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20071 
20072 	/*
20073 	 * Free NCEs for IPv6 like the onlink ires.
20074 	 */
20075 	ncc.ncc_total = 0;
20076 	ncc.ncc_host = 0;
20077 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20078 
20079 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20080 	    icc.icc_pmtu + icc.icc_onlink);
20081 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20082 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20083 	if (delete_cnt == 0)
20084 		return;
20085 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20086 	/* Always delete all unused offlink entries */
20087 	icr.icr_ipst = ipst;
20088 	icr.icr_unused = 1;
20089 	if (delete_cnt <= icc.icc_unused) {
20090 		/*
20091 		 * Only need to free unused entries.  In other words,
20092 		 * there are enough unused entries to free to meet our
20093 		 * target number of freed ire cache entries.
20094 		 */
20095 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20096 		ncr.ncr_host = 0;
20097 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20098 		/*
20099 		 * Only need to free unused entries, plus a fraction of offlink
20100 		 * entries.  It follows from the first if statement that
20101 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20102 		 */
20103 		delete_cnt -= icc.icc_unused;
20104 		/* Round up # deleted by truncating fraction */
20105 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20106 		icr.icr_pmtu = icr.icr_onlink = 0;
20107 		ncr.ncr_host = 0;
20108 	} else if (delete_cnt <=
20109 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20110 		/*
20111 		 * Free all unused and offlink entries, plus a fraction of
20112 		 * pmtu entries.  It follows from the previous if statement
20113 		 * that icc_pmtu is non-zero, and that
20114 		 * delete_cnt != icc_unused + icc_offlink.
20115 		 */
20116 		icr.icr_offlink = 1;
20117 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20118 		/* Round up # deleted by truncating fraction */
20119 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20120 		icr.icr_onlink = 0;
20121 		ncr.ncr_host = 0;
20122 	} else {
20123 		/*
20124 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20125 		 * of onlink entries.  If we're here, then we know that
20126 		 * icc_onlink is non-zero, and that
20127 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20128 		 */
20129 		icr.icr_offlink = icr.icr_pmtu = 1;
20130 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20131 		    icc.icc_pmtu;
20132 		/* Round up # deleted by truncating fraction */
20133 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20134 		/* Using the same delete fraction as for onlink IREs */
20135 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20136 	}
20137 #ifdef DEBUG
20138 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20139 	    "fractions %d/%d/%d/%d\n",
20140 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20141 	    icc.icc_unused, icc.icc_offlink,
20142 	    icc.icc_pmtu, icc.icc_onlink,
20143 	    icr.icr_unused, icr.icr_offlink,
20144 	    icr.icr_pmtu, icr.icr_onlink));
20145 #endif
20146 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20147 	if (ncr.ncr_host != 0)
20148 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20149 		    (uchar_t *)&ncr, ipst);
20150 #ifdef DEBUG
20151 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20152 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20153 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20154 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20155 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20156 	    icc.icc_pmtu, icc.icc_onlink));
20157 #endif
20158 }
20159 
20160 /*
20161  * ip_unbind is called when a copy of an unbind request is received from the
20162  * upper level protocol.  We remove this conn from any fanout hash list it is
20163  * on, and zero out the bind information.  No reply is expected up above.
20164  */
20165 mblk_t *
20166 ip_unbind(queue_t *q, mblk_t *mp)
20167 {
20168 	conn_t	*connp = Q_TO_CONN(q);
20169 
20170 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20171 
20172 	if (is_system_labeled() && connp->conn_anon_port) {
20173 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20174 		    connp->conn_mlp_type, connp->conn_ulp,
20175 		    ntohs(connp->conn_lport), B_FALSE);
20176 		connp->conn_anon_port = 0;
20177 	}
20178 	connp->conn_mlp_type = mlptSingle;
20179 
20180 	ipcl_hash_remove(connp);
20181 
20182 	ASSERT(mp->b_cont == NULL);
20183 	/*
20184 	 * Convert mp into a T_OK_ACK
20185 	 */
20186 	mp = mi_tpi_ok_ack_alloc(mp);
20187 
20188 	/*
20189 	 * should not happen in practice... T_OK_ACK is smaller than the
20190 	 * original message.
20191 	 */
20192 	if (mp == NULL)
20193 		return (NULL);
20194 
20195 	/*
20196 	 * Don't bzero the ports if its TCP since TCP still needs the
20197 	 * lport to remove it from its own bind hash. TCP will do the
20198 	 * cleanup.
20199 	 */
20200 	if (!IPCL_IS_TCP(connp))
20201 		bzero(&connp->u_port, sizeof (connp->u_port));
20202 
20203 	return (mp);
20204 }
20205 
20206 /*
20207  * Write side put procedure.  Outbound data, IOCTLs, responses from
20208  * resolvers, etc, come down through here.
20209  *
20210  * arg2 is always a queue_t *.
20211  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20212  * the zoneid.
20213  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20214  */
20215 void
20216 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20217 {
20218 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20219 }
20220 
20221 void
20222 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20223     ip_opt_info_t *infop)
20224 {
20225 	conn_t		*connp = NULL;
20226 	queue_t		*q = (queue_t *)arg2;
20227 	ipha_t		*ipha;
20228 #define	rptr	((uchar_t *)ipha)
20229 	ire_t		*ire = NULL;
20230 	ire_t		*sctp_ire = NULL;
20231 	uint32_t	v_hlen_tos_len;
20232 	ipaddr_t	dst;
20233 	mblk_t		*first_mp = NULL;
20234 	boolean_t	mctl_present;
20235 	ipsec_out_t	*io;
20236 	int		match_flags;
20237 	ill_t		*attach_ill = NULL;
20238 					/* Bind to IPIF_NOFAILOVER ill etc. */
20239 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20240 	ipif_t		*dst_ipif;
20241 	boolean_t	multirt_need_resolve = B_FALSE;
20242 	mblk_t		*copy_mp = NULL;
20243 	int		err;
20244 	zoneid_t	zoneid;
20245 	int	adjust;
20246 	uint16_t iplen;
20247 	boolean_t	need_decref = B_FALSE;
20248 	boolean_t	ignore_dontroute = B_FALSE;
20249 	boolean_t	ignore_nexthop = B_FALSE;
20250 	boolean_t	ip_nexthop = B_FALSE;
20251 	ipaddr_t	nexthop_addr;
20252 	ip_stack_t	*ipst;
20253 
20254 #ifdef	_BIG_ENDIAN
20255 #define	V_HLEN	(v_hlen_tos_len >> 24)
20256 #else
20257 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20258 #endif
20259 
20260 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20261 	    "ip_wput_start: q %p", q);
20262 
20263 	/*
20264 	 * ip_wput fast path
20265 	 */
20266 
20267 	/* is packet from ARP ? */
20268 	if (q->q_next != NULL) {
20269 		zoneid = (zoneid_t)(uintptr_t)arg;
20270 		goto qnext;
20271 	}
20272 
20273 	connp = (conn_t *)arg;
20274 	ASSERT(connp != NULL);
20275 	zoneid = connp->conn_zoneid;
20276 	ipst = connp->conn_netstack->netstack_ip;
20277 
20278 	/* is queue flow controlled? */
20279 	if ((q->q_first != NULL || connp->conn_draining) &&
20280 	    (caller == IP_WPUT)) {
20281 		ASSERT(!need_decref);
20282 		(void) putq(q, mp);
20283 		return;
20284 	}
20285 
20286 	/* Multidata transmit? */
20287 	if (DB_TYPE(mp) == M_MULTIDATA) {
20288 		/*
20289 		 * We should never get here, since all Multidata messages
20290 		 * originating from tcp should have been directed over to
20291 		 * tcp_multisend() in the first place.
20292 		 */
20293 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20294 		freemsg(mp);
20295 		return;
20296 	} else if (DB_TYPE(mp) != M_DATA)
20297 		goto notdata;
20298 
20299 	if (mp->b_flag & MSGHASREF) {
20300 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20301 		mp->b_flag &= ~MSGHASREF;
20302 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20303 		need_decref = B_TRUE;
20304 	}
20305 	ipha = (ipha_t *)mp->b_rptr;
20306 
20307 	/* is IP header non-aligned or mblk smaller than basic IP header */
20308 #ifndef SAFETY_BEFORE_SPEED
20309 	if (!OK_32PTR(rptr) ||
20310 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20311 		goto hdrtoosmall;
20312 #endif
20313 
20314 	ASSERT(OK_32PTR(ipha));
20315 
20316 	/*
20317 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20318 	 * wrong version, we'll catch it again in ip_output_v6.
20319 	 *
20320 	 * Note that this is *only* locally-generated output here, and never
20321 	 * forwarded data, and that we need to deal only with transports that
20322 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20323 	 * label.)
20324 	 */
20325 	if (is_system_labeled() &&
20326 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20327 	    !connp->conn_ulp_labeled) {
20328 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20329 		    connp->conn_mac_exempt, ipst);
20330 		ipha = (ipha_t *)mp->b_rptr;
20331 		if (err != 0) {
20332 			first_mp = mp;
20333 			if (err == EINVAL)
20334 				goto icmp_parameter_problem;
20335 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20336 			goto discard_pkt;
20337 		}
20338 		iplen = ntohs(ipha->ipha_length) + adjust;
20339 		ipha->ipha_length = htons(iplen);
20340 	}
20341 
20342 	ASSERT(infop != NULL);
20343 
20344 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20345 		/*
20346 		 * IP_PKTINFO ancillary option is present.
20347 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20348 		 * allows using address of any zone as the source address.
20349 		 */
20350 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20351 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20352 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20353 		if (ire == NULL)
20354 			goto drop_pkt;
20355 		ire_refrele(ire);
20356 		ire = NULL;
20357 	}
20358 
20359 	/*
20360 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20361 	 * ill index passed in IP_PKTINFO.
20362 	 */
20363 	if (infop->ip_opt_ill_index != 0 &&
20364 	    connp->conn_xmit_if_ill == NULL &&
20365 	    connp->conn_nofailover_ill == NULL) {
20366 
20367 		xmit_ill = ill_lookup_on_ifindex(
20368 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20369 		    ipst);
20370 
20371 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20372 			goto drop_pkt;
20373 		/*
20374 		 * check that there is an ipif belonging
20375 		 * to our zone. IPCL_ZONEID is not used because
20376 		 * IP_ALLZONES option is valid only when the ill is
20377 		 * accessible from all zones i.e has a valid ipif in
20378 		 * all zones.
20379 		 */
20380 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20381 			goto drop_pkt;
20382 		}
20383 	}
20384 
20385 	/*
20386 	 * If there is a policy, try to attach an ipsec_out in
20387 	 * the front. At the end, first_mp either points to a
20388 	 * M_DATA message or IPSEC_OUT message linked to a
20389 	 * M_DATA message. We have to do it now as we might
20390 	 * lose the "conn" if we go through ip_newroute.
20391 	 */
20392 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20393 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20394 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20395 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20396 			if (need_decref)
20397 				CONN_DEC_REF(connp);
20398 			return;
20399 		} else {
20400 			ASSERT(mp->b_datap->db_type == M_CTL);
20401 			first_mp = mp;
20402 			mp = mp->b_cont;
20403 			mctl_present = B_TRUE;
20404 		}
20405 	} else {
20406 		first_mp = mp;
20407 		mctl_present = B_FALSE;
20408 	}
20409 
20410 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20411 
20412 	/* is wrong version or IP options present */
20413 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20414 		goto version_hdrlen_check;
20415 	dst = ipha->ipha_dst;
20416 
20417 	if (connp->conn_nofailover_ill != NULL) {
20418 		attach_ill = conn_get_held_ill(connp,
20419 		    &connp->conn_nofailover_ill, &err);
20420 		if (err == ILL_LOOKUP_FAILED) {
20421 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20422 			if (need_decref)
20423 				CONN_DEC_REF(connp);
20424 			freemsg(first_mp);
20425 			return;
20426 		}
20427 	}
20428 
20429 
20430 	/* is packet multicast? */
20431 	if (CLASSD(dst))
20432 		goto multicast;
20433 
20434 	/*
20435 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20436 	 * takes precedence over conn_dontroute and conn_nexthop_set
20437 	 */
20438 	if (xmit_ill != NULL) {
20439 		goto send_from_ill;
20440 	}
20441 
20442 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20443 	    (connp->conn_nexthop_set)) {
20444 		/*
20445 		 * If the destination is a broadcast or a loopback
20446 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20447 		 * through the standard path. But in the case of local
20448 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20449 		 * the standard path not IP_XMIT_IF.
20450 		 */
20451 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20452 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20453 		    (ire->ire_type != IRE_LOOPBACK))) {
20454 			if ((connp->conn_dontroute ||
20455 			    connp->conn_nexthop_set) && (ire != NULL) &&
20456 			    (ire->ire_type == IRE_LOCAL))
20457 				goto standard_path;
20458 
20459 			if (ire != NULL) {
20460 				ire_refrele(ire);
20461 				/* No more access to ire */
20462 				ire = NULL;
20463 			}
20464 			/*
20465 			 * bypass routing checks and go directly to
20466 			 * interface.
20467 			 */
20468 			if (connp->conn_dontroute) {
20469 				goto dontroute;
20470 			} else if (connp->conn_nexthop_set) {
20471 				ip_nexthop = B_TRUE;
20472 				nexthop_addr = connp->conn_nexthop_v4;
20473 				goto send_from_ill;
20474 			}
20475 
20476 			/*
20477 			 * If IP_XMIT_IF socket option is set,
20478 			 * then we allow unicast and multicast
20479 			 * packets to go through the ill. It is
20480 			 * quite possible that the destination
20481 			 * is not in the ire cache table and we
20482 			 * do not want to go to ip_newroute()
20483 			 * instead we call ip_newroute_ipif.
20484 			 */
20485 			xmit_ill = conn_get_held_ill(connp,
20486 			    &connp->conn_xmit_if_ill, &err);
20487 			if (err == ILL_LOOKUP_FAILED) {
20488 				BUMP_MIB(&ipst->ips_ip_mib,
20489 				    ipIfStatsOutDiscards);
20490 				if (attach_ill != NULL)
20491 					ill_refrele(attach_ill);
20492 				if (need_decref)
20493 					CONN_DEC_REF(connp);
20494 				freemsg(first_mp);
20495 				return;
20496 			}
20497 			goto send_from_ill;
20498 		}
20499 standard_path:
20500 		/* Must be a broadcast, a loopback or a local ire */
20501 		if (ire != NULL) {
20502 			ire_refrele(ire);
20503 			/* No more access to ire */
20504 			ire = NULL;
20505 		}
20506 	}
20507 
20508 	if (attach_ill != NULL)
20509 		goto send_from_ill;
20510 
20511 	/*
20512 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20513 	 * this for the tcp global queue and listen end point
20514 	 * as it does not really have a real destination to
20515 	 * talk to.  This is also true for SCTP.
20516 	 */
20517 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20518 	    !connp->conn_fully_bound) {
20519 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20520 		if (ire == NULL)
20521 			goto noirefound;
20522 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20523 		    "ip_wput_end: q %p (%S)", q, "end");
20524 
20525 		/*
20526 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20527 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20528 		 */
20529 		if (ire->ire_flags & RTF_MULTIRT) {
20530 
20531 			/*
20532 			 * Force the TTL of multirouted packets if required.
20533 			 * The TTL of such packets is bounded by the
20534 			 * ip_multirt_ttl ndd variable.
20535 			 */
20536 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20537 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20538 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20539 				    "(was %d), dst 0x%08x\n",
20540 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20541 				    ntohl(ire->ire_addr)));
20542 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20543 			}
20544 			/*
20545 			 * We look at this point if there are pending
20546 			 * unresolved routes. ire_multirt_resolvable()
20547 			 * checks in O(n) that all IRE_OFFSUBNET ire
20548 			 * entries for the packet's destination and
20549 			 * flagged RTF_MULTIRT are currently resolved.
20550 			 * If some remain unresolved, we make a copy
20551 			 * of the current message. It will be used
20552 			 * to initiate additional route resolutions.
20553 			 */
20554 			multirt_need_resolve =
20555 			    ire_multirt_need_resolve(ire->ire_addr,
20556 			    MBLK_GETLABEL(first_mp), ipst);
20557 			ip2dbg(("ip_wput[TCP]: ire %p, "
20558 			    "multirt_need_resolve %d, first_mp %p\n",
20559 			    (void *)ire, multirt_need_resolve,
20560 			    (void *)first_mp));
20561 			if (multirt_need_resolve) {
20562 				copy_mp = copymsg(first_mp);
20563 				if (copy_mp != NULL) {
20564 					MULTIRT_DEBUG_TAG(copy_mp);
20565 				}
20566 			}
20567 		}
20568 
20569 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20570 
20571 		/*
20572 		 * Try to resolve another multiroute if
20573 		 * ire_multirt_need_resolve() deemed it necessary.
20574 		 */
20575 		if (copy_mp != NULL) {
20576 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20577 		}
20578 		if (need_decref)
20579 			CONN_DEC_REF(connp);
20580 		return;
20581 	}
20582 
20583 	/*
20584 	 * Access to conn_ire_cache. (protected by conn_lock)
20585 	 *
20586 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20587 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20588 	 * send a packet or two with the IRE_CACHE that is going away.
20589 	 * Access to the ire requires an ire refhold on the ire prior to
20590 	 * its use since an interface unplumb thread may delete the cached
20591 	 * ire and release the refhold at any time.
20592 	 *
20593 	 * Caching an ire in the conn_ire_cache
20594 	 *
20595 	 * o Caching an ire pointer in the conn requires a strict check for
20596 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20597 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20598 	 * in the conn is done after making sure under the bucket lock that the
20599 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20600 	 * caching an ire after the unplumb thread has cleaned up the conn.
20601 	 * If the conn does not send a packet subsequently the unplumb thread
20602 	 * will be hanging waiting for the ire count to drop to zero.
20603 	 *
20604 	 * o We also need to atomically test for a null conn_ire_cache and
20605 	 * set the conn_ire_cache under the the protection of the conn_lock
20606 	 * to avoid races among concurrent threads trying to simultaneously
20607 	 * cache an ire in the conn_ire_cache.
20608 	 */
20609 	mutex_enter(&connp->conn_lock);
20610 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20611 
20612 	if (ire != NULL && ire->ire_addr == dst &&
20613 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20614 
20615 		IRE_REFHOLD(ire);
20616 		mutex_exit(&connp->conn_lock);
20617 
20618 	} else {
20619 		boolean_t cached = B_FALSE;
20620 		connp->conn_ire_cache = NULL;
20621 		mutex_exit(&connp->conn_lock);
20622 		/* Release the old ire */
20623 		if (ire != NULL && sctp_ire == NULL)
20624 			IRE_REFRELE_NOTR(ire);
20625 
20626 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20627 		if (ire == NULL)
20628 			goto noirefound;
20629 		IRE_REFHOLD_NOTR(ire);
20630 
20631 		mutex_enter(&connp->conn_lock);
20632 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20633 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20634 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20635 				if (connp->conn_ulp == IPPROTO_TCP)
20636 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20637 				connp->conn_ire_cache = ire;
20638 				cached = B_TRUE;
20639 			}
20640 			rw_exit(&ire->ire_bucket->irb_lock);
20641 		}
20642 		mutex_exit(&connp->conn_lock);
20643 
20644 		/*
20645 		 * We can continue to use the ire but since it was
20646 		 * not cached, we should drop the extra reference.
20647 		 */
20648 		if (!cached)
20649 			IRE_REFRELE_NOTR(ire);
20650 	}
20651 
20652 
20653 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20654 	    "ip_wput_end: q %p (%S)", q, "end");
20655 
20656 	/*
20657 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20658 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20659 	 */
20660 	if (ire->ire_flags & RTF_MULTIRT) {
20661 
20662 		/*
20663 		 * Force the TTL of multirouted packets if required.
20664 		 * The TTL of such packets is bounded by the
20665 		 * ip_multirt_ttl ndd variable.
20666 		 */
20667 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20668 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20669 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20670 			    "(was %d), dst 0x%08x\n",
20671 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20672 			    ntohl(ire->ire_addr)));
20673 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20674 		}
20675 
20676 		/*
20677 		 * At this point, we check to see if there are any pending
20678 		 * unresolved routes. ire_multirt_resolvable()
20679 		 * checks in O(n) that all IRE_OFFSUBNET ire
20680 		 * entries for the packet's destination and
20681 		 * flagged RTF_MULTIRT are currently resolved.
20682 		 * If some remain unresolved, we make a copy
20683 		 * of the current message. It will be used
20684 		 * to initiate additional route resolutions.
20685 		 */
20686 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20687 		    MBLK_GETLABEL(first_mp), ipst);
20688 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20689 		    "multirt_need_resolve %d, first_mp %p\n",
20690 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20691 		if (multirt_need_resolve) {
20692 			copy_mp = copymsg(first_mp);
20693 			if (copy_mp != NULL) {
20694 				MULTIRT_DEBUG_TAG(copy_mp);
20695 			}
20696 		}
20697 	}
20698 
20699 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20700 
20701 	/*
20702 	 * Try to resolve another multiroute if
20703 	 * ire_multirt_resolvable() deemed it necessary
20704 	 */
20705 	if (copy_mp != NULL) {
20706 		ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
20707 	}
20708 	if (need_decref)
20709 		CONN_DEC_REF(connp);
20710 	return;
20711 
20712 qnext:
20713 	/*
20714 	 * Upper Level Protocols pass down complete IP datagrams
20715 	 * as M_DATA messages.	Everything else is a sideshow.
20716 	 *
20717 	 * 1) We could be re-entering ip_wput because of ip_neworute
20718 	 *    in which case we could have a IPSEC_OUT message. We
20719 	 *    need to pass through ip_wput like other datagrams and
20720 	 *    hence cannot branch to ip_wput_nondata.
20721 	 *
20722 	 * 2) ARP, AH, ESP, and other clients who are on the module
20723 	 *    instance of IP stream, give us something to deal with.
20724 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20725 	 *
20726 	 * 3) ICMP replies also could come here.
20727 	 */
20728 	ipst = ILLQ_TO_IPST(q);
20729 
20730 	if (DB_TYPE(mp) != M_DATA) {
20731 notdata:
20732 		if (DB_TYPE(mp) == M_CTL) {
20733 			/*
20734 			 * M_CTL messages are used by ARP, AH and ESP to
20735 			 * communicate with IP. We deal with IPSEC_IN and
20736 			 * IPSEC_OUT here. ip_wput_nondata handles other
20737 			 * cases.
20738 			 */
20739 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20740 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20741 				first_mp = mp->b_cont;
20742 				first_mp->b_flag &= ~MSGHASREF;
20743 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20744 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20745 				CONN_DEC_REF(connp);
20746 				connp = NULL;
20747 			}
20748 			if (ii->ipsec_info_type == IPSEC_IN) {
20749 				/*
20750 				 * Either this message goes back to
20751 				 * IPSEC for further processing or to
20752 				 * ULP after policy checks.
20753 				 */
20754 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20755 				return;
20756 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20757 				io = (ipsec_out_t *)ii;
20758 				if (io->ipsec_out_proc_begin) {
20759 					/*
20760 					 * IPSEC processing has already started.
20761 					 * Complete it.
20762 					 * IPQoS notes: We don't care what is
20763 					 * in ipsec_out_ill_index since this
20764 					 * won't be processed for IPQoS policies
20765 					 * in ipsec_out_process.
20766 					 */
20767 					ipsec_out_process(q, mp, NULL,
20768 					    io->ipsec_out_ill_index);
20769 					return;
20770 				} else {
20771 					connp = (q->q_next != NULL) ?
20772 					    NULL : Q_TO_CONN(q);
20773 					first_mp = mp;
20774 					mp = mp->b_cont;
20775 					mctl_present = B_TRUE;
20776 				}
20777 				zoneid = io->ipsec_out_zoneid;
20778 				ASSERT(zoneid != ALL_ZONES);
20779 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20780 				/*
20781 				 * It's an IPsec control message requesting
20782 				 * an SADB update to be sent to the IPsec
20783 				 * hardware acceleration capable ills.
20784 				 */
20785 				ipsec_ctl_t *ipsec_ctl =
20786 				    (ipsec_ctl_t *)mp->b_rptr;
20787 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20788 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20789 				mblk_t *cmp = mp->b_cont;
20790 
20791 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20792 				ASSERT(cmp != NULL);
20793 
20794 				freeb(mp);
20795 				ill_ipsec_capab_send_all(satype, cmp, sa,
20796 				    ipst->ips_netstack);
20797 				return;
20798 			} else {
20799 				/*
20800 				 * This must be ARP or special TSOL signaling.
20801 				 */
20802 				ip_wput_nondata(NULL, q, mp, NULL);
20803 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20804 				    "ip_wput_end: q %p (%S)", q, "nondata");
20805 				return;
20806 			}
20807 		} else {
20808 			/*
20809 			 * This must be non-(ARP/AH/ESP) messages.
20810 			 */
20811 			ASSERT(!need_decref);
20812 			ip_wput_nondata(NULL, q, mp, NULL);
20813 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20814 			    "ip_wput_end: q %p (%S)", q, "nondata");
20815 			return;
20816 		}
20817 	} else {
20818 		first_mp = mp;
20819 		mctl_present = B_FALSE;
20820 	}
20821 
20822 	ASSERT(first_mp != NULL);
20823 	/*
20824 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20825 	 * to make sure that this packet goes out on the same interface it
20826 	 * came in. We handle that here.
20827 	 */
20828 	if (mctl_present) {
20829 		uint_t ifindex;
20830 
20831 		io = (ipsec_out_t *)first_mp->b_rptr;
20832 		if (io->ipsec_out_attach_if ||
20833 		    io->ipsec_out_xmit_if ||
20834 		    io->ipsec_out_ip_nexthop) {
20835 			ill_t	*ill;
20836 
20837 			/*
20838 			 * We may have lost the conn context if we are
20839 			 * coming here from ip_newroute(). Copy the
20840 			 * nexthop information.
20841 			 */
20842 			if (io->ipsec_out_ip_nexthop) {
20843 				ip_nexthop = B_TRUE;
20844 				nexthop_addr = io->ipsec_out_nexthop_addr;
20845 
20846 				ipha = (ipha_t *)mp->b_rptr;
20847 				dst = ipha->ipha_dst;
20848 				goto send_from_ill;
20849 			} else {
20850 				ASSERT(io->ipsec_out_ill_index != 0);
20851 				ifindex = io->ipsec_out_ill_index;
20852 				ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
20853 				    NULL, NULL, NULL, NULL, ipst);
20854 				/*
20855 				 * ipsec_out_xmit_if bit is used to tell
20856 				 * ip_wput to use the ill to send outgoing data
20857 				 * as we have no conn when data comes from ICMP
20858 				 * error msg routines. Currently this feature is
20859 				 * only used by ip_mrtun_forward routine.
20860 				 */
20861 				if (io->ipsec_out_xmit_if) {
20862 					xmit_ill = ill;
20863 					if (xmit_ill == NULL) {
20864 						ip1dbg(("ip_output:bad ifindex "
20865 						    "for xmit_ill %d\n",
20866 						    ifindex));
20867 						freemsg(first_mp);
20868 						BUMP_MIB(&ipst->ips_ip_mib,
20869 						    ipIfStatsOutDiscards);
20870 						ASSERT(!need_decref);
20871 						return;
20872 					}
20873 					/* Free up the ipsec_out_t mblk */
20874 					ASSERT(first_mp->b_cont == mp);
20875 					first_mp->b_cont = NULL;
20876 					freeb(first_mp);
20877 					/* Just send the IP header+ICMP+data */
20878 					first_mp = mp;
20879 					ipha = (ipha_t *)mp->b_rptr;
20880 					dst = ipha->ipha_dst;
20881 					goto send_from_ill;
20882 				} else {
20883 					attach_ill = ill;
20884 				}
20885 
20886 				if (attach_ill == NULL) {
20887 					ASSERT(xmit_ill == NULL);
20888 					ip1dbg(("ip_output: bad ifindex for "
20889 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20890 					    ifindex));
20891 					freemsg(first_mp);
20892 					BUMP_MIB(&ipst->ips_ip_mib,
20893 					    ipIfStatsOutDiscards);
20894 					ASSERT(!need_decref);
20895 					return;
20896 				}
20897 			}
20898 		}
20899 	}
20900 
20901 	ASSERT(xmit_ill == NULL);
20902 
20903 	/* We have a complete IP datagram heading outbound. */
20904 	ipha = (ipha_t *)mp->b_rptr;
20905 
20906 #ifndef SPEED_BEFORE_SAFETY
20907 	/*
20908 	 * Make sure we have a full-word aligned message and that at least
20909 	 * a simple IP header is accessible in the first message.  If not,
20910 	 * try a pullup.
20911 	 */
20912 	if (!OK_32PTR(rptr) ||
20913 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20914 hdrtoosmall:
20915 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20916 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20917 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20918 			if (first_mp == NULL)
20919 				first_mp = mp;
20920 			goto discard_pkt;
20921 		}
20922 
20923 		/* This function assumes that mp points to an IPv4 packet. */
20924 		if (is_system_labeled() && q->q_next == NULL &&
20925 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20926 		    !connp->conn_ulp_labeled) {
20927 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20928 			    &adjust, connp->conn_mac_exempt, ipst);
20929 			ipha = (ipha_t *)mp->b_rptr;
20930 			if (first_mp != NULL)
20931 				first_mp->b_cont = mp;
20932 			if (err != 0) {
20933 				if (first_mp == NULL)
20934 					first_mp = mp;
20935 				if (err == EINVAL)
20936 					goto icmp_parameter_problem;
20937 				ip2dbg(("ip_wput: label check failed (%d)\n",
20938 				    err));
20939 				goto discard_pkt;
20940 			}
20941 			iplen = ntohs(ipha->ipha_length) + adjust;
20942 			ipha->ipha_length = htons(iplen);
20943 		}
20944 
20945 		ipha = (ipha_t *)mp->b_rptr;
20946 		if (first_mp == NULL) {
20947 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20948 			/*
20949 			 * If we got here because of "goto hdrtoosmall"
20950 			 * We need to attach a IPSEC_OUT.
20951 			 */
20952 			if (connp->conn_out_enforce_policy) {
20953 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20954 				    NULL, ipha->ipha_protocol,
20955 				    ipst->ips_netstack)) == NULL)) {
20956 					BUMP_MIB(&ipst->ips_ip_mib,
20957 					    ipIfStatsOutDiscards);
20958 					if (need_decref)
20959 						CONN_DEC_REF(connp);
20960 					return;
20961 				} else {
20962 					ASSERT(mp->b_datap->db_type == M_CTL);
20963 					first_mp = mp;
20964 					mp = mp->b_cont;
20965 					mctl_present = B_TRUE;
20966 				}
20967 			} else {
20968 				first_mp = mp;
20969 				mctl_present = B_FALSE;
20970 			}
20971 		}
20972 	}
20973 #endif
20974 
20975 	/* Most of the code below is written for speed, not readability */
20976 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20977 
20978 	/*
20979 	 * If ip_newroute() fails, we're going to need a full
20980 	 * header for the icmp wraparound.
20981 	 */
20982 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20983 		uint_t	v_hlen;
20984 version_hdrlen_check:
20985 		ASSERT(first_mp != NULL);
20986 		v_hlen = V_HLEN;
20987 		/*
20988 		 * siphon off IPv6 packets coming down from transport
20989 		 * layer modules here.
20990 		 * Note: high-order bit carries NUD reachability confirmation
20991 		 */
20992 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20993 			/*
20994 			 * XXX implement a IPv4 and IPv6 packet counter per
20995 			 * conn and switch when ratio exceeds e.g. 10:1
20996 			 */
20997 #ifdef notyet
20998 			if (q->q_next == NULL) /* Avoid ill queue */
20999 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
21000 #endif
21001 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
21002 			ASSERT(xmit_ill == NULL);
21003 			if (attach_ill != NULL)
21004 				ill_refrele(attach_ill);
21005 			if (need_decref)
21006 				mp->b_flag |= MSGHASREF;
21007 			(void) ip_output_v6(arg, first_mp, arg2, caller);
21008 			return;
21009 		}
21010 
21011 		if ((v_hlen >> 4) != IP_VERSION) {
21012 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21013 			    "ip_wput_end: q %p (%S)", q, "badvers");
21014 			goto discard_pkt;
21015 		}
21016 		/*
21017 		 * Is the header length at least 20 bytes?
21018 		 *
21019 		 * Are there enough bytes accessible in the header?  If
21020 		 * not, try a pullup.
21021 		 */
21022 		v_hlen &= 0xF;
21023 		v_hlen <<= 2;
21024 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
21025 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21026 			    "ip_wput_end: q %p (%S)", q, "badlen");
21027 			goto discard_pkt;
21028 		}
21029 		if (v_hlen > (mp->b_wptr - rptr)) {
21030 			if (!pullupmsg(mp, v_hlen)) {
21031 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21032 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
21033 				goto discard_pkt;
21034 			}
21035 			ipha = (ipha_t *)mp->b_rptr;
21036 		}
21037 		/*
21038 		 * Move first entry from any source route into ipha_dst and
21039 		 * verify the options
21040 		 */
21041 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
21042 		    zoneid, ipst)) {
21043 			ASSERT(xmit_ill == NULL);
21044 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21045 			if (attach_ill != NULL)
21046 				ill_refrele(attach_ill);
21047 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21048 			    "ip_wput_end: q %p (%S)", q, "badopts");
21049 			if (need_decref)
21050 				CONN_DEC_REF(connp);
21051 			return;
21052 		}
21053 	}
21054 	dst = ipha->ipha_dst;
21055 
21056 	/*
21057 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
21058 	 * we have to run the packet through ip_newroute which will take
21059 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
21060 	 * a resolver, or assigning a default gateway, etc.
21061 	 */
21062 	if (CLASSD(dst)) {
21063 		ipif_t	*ipif;
21064 		uint32_t setsrc = 0;
21065 
21066 multicast:
21067 		ASSERT(first_mp != NULL);
21068 		ip2dbg(("ip_wput: CLASSD\n"));
21069 		if (connp == NULL) {
21070 			/*
21071 			 * Use the first good ipif on the ill.
21072 			 * XXX Should this ever happen? (Appears
21073 			 * to show up with just ppp and no ethernet due
21074 			 * to in.rdisc.)
21075 			 * However, ire_send should be able to
21076 			 * call ip_wput_ire directly.
21077 			 *
21078 			 * XXX Also, this can happen for ICMP and other packets
21079 			 * with multicast source addresses.  Perhaps we should
21080 			 * fix things so that we drop the packet in question,
21081 			 * but for now, just run with it.
21082 			 */
21083 			ill_t *ill = (ill_t *)q->q_ptr;
21084 
21085 			/*
21086 			 * Don't honor attach_if for this case. If ill
21087 			 * is part of the group, ipif could belong to
21088 			 * any ill and we cannot maintain attach_ill
21089 			 * and ipif_ill same anymore and the assert
21090 			 * below would fail.
21091 			 */
21092 			if (mctl_present && io->ipsec_out_attach_if) {
21093 				io->ipsec_out_ill_index = 0;
21094 				io->ipsec_out_attach_if = B_FALSE;
21095 				ASSERT(attach_ill != NULL);
21096 				ill_refrele(attach_ill);
21097 				attach_ill = NULL;
21098 			}
21099 
21100 			ASSERT(attach_ill == NULL);
21101 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
21102 			if (ipif == NULL) {
21103 				if (need_decref)
21104 					CONN_DEC_REF(connp);
21105 				freemsg(first_mp);
21106 				return;
21107 			}
21108 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
21109 			    ntohl(dst), ill->ill_name));
21110 		} else {
21111 			/*
21112 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
21113 			 * and IP_MULTICAST_IF.
21114 			 * Block comment above this function explains the
21115 			 * locking mechanism used here
21116 			 */
21117 			if (xmit_ill == NULL) {
21118 				xmit_ill = conn_get_held_ill(connp,
21119 				    &connp->conn_xmit_if_ill, &err);
21120 				if (err == ILL_LOOKUP_FAILED) {
21121 					ip1dbg(("ip_wput: No ill for "
21122 					    "IP_XMIT_IF\n"));
21123 					BUMP_MIB(&ipst->ips_ip_mib,
21124 					    ipIfStatsOutNoRoutes);
21125 					goto drop_pkt;
21126 				}
21127 			}
21128 
21129 			if (xmit_ill == NULL) {
21130 				ipif = conn_get_held_ipif(connp,
21131 				    &connp->conn_multicast_ipif, &err);
21132 				if (err == IPIF_LOOKUP_FAILED) {
21133 					ip1dbg(("ip_wput: No ipif for "
21134 					    "multicast\n"));
21135 					BUMP_MIB(&ipst->ips_ip_mib,
21136 					    ipIfStatsOutNoRoutes);
21137 					goto drop_pkt;
21138 				}
21139 			}
21140 			if (xmit_ill != NULL) {
21141 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21142 				if (ipif == NULL) {
21143 					ip1dbg(("ip_wput: No ipif for "
21144 					    "IP_XMIT_IF\n"));
21145 					BUMP_MIB(&ipst->ips_ip_mib,
21146 					    ipIfStatsOutNoRoutes);
21147 					goto drop_pkt;
21148 				}
21149 			} else if (ipif == NULL || ipif->ipif_isv6) {
21150 				/*
21151 				 * We must do this ipif determination here
21152 				 * else we could pass through ip_newroute
21153 				 * and come back here without the conn context.
21154 				 *
21155 				 * Note: we do late binding i.e. we bind to
21156 				 * the interface when the first packet is sent.
21157 				 * For performance reasons we do not rebind on
21158 				 * each packet but keep the binding until the
21159 				 * next IP_MULTICAST_IF option.
21160 				 *
21161 				 * conn_multicast_{ipif,ill} are shared between
21162 				 * IPv4 and IPv6 and AF_INET6 sockets can
21163 				 * send both IPv4 and IPv6 packets. Hence
21164 				 * we have to check that "isv6" matches above.
21165 				 */
21166 				if (ipif != NULL)
21167 					ipif_refrele(ipif);
21168 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21169 				if (ipif == NULL) {
21170 					ip1dbg(("ip_wput: No ipif for "
21171 					    "multicast\n"));
21172 					BUMP_MIB(&ipst->ips_ip_mib,
21173 					    ipIfStatsOutNoRoutes);
21174 					goto drop_pkt;
21175 				}
21176 				err = conn_set_held_ipif(connp,
21177 				    &connp->conn_multicast_ipif, ipif);
21178 				if (err == IPIF_LOOKUP_FAILED) {
21179 					ipif_refrele(ipif);
21180 					ip1dbg(("ip_wput: No ipif for "
21181 					    "multicast\n"));
21182 					BUMP_MIB(&ipst->ips_ip_mib,
21183 					    ipIfStatsOutNoRoutes);
21184 					goto drop_pkt;
21185 				}
21186 			}
21187 		}
21188 		ASSERT(!ipif->ipif_isv6);
21189 		/*
21190 		 * As we may lose the conn by the time we reach ip_wput_ire,
21191 		 * we copy conn_multicast_loop and conn_dontroute on to an
21192 		 * ipsec_out. In case if this datagram goes out secure,
21193 		 * we need the ill_index also. Copy that also into the
21194 		 * ipsec_out.
21195 		 */
21196 		if (mctl_present) {
21197 			io = (ipsec_out_t *)first_mp->b_rptr;
21198 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21199 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21200 		} else {
21201 			ASSERT(mp == first_mp);
21202 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21203 			    BPRI_HI)) == NULL) {
21204 				ipif_refrele(ipif);
21205 				first_mp = mp;
21206 				goto discard_pkt;
21207 			}
21208 			first_mp->b_datap->db_type = M_CTL;
21209 			first_mp->b_wptr += sizeof (ipsec_info_t);
21210 			/* ipsec_out_secure is B_FALSE now */
21211 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21212 			io = (ipsec_out_t *)first_mp->b_rptr;
21213 			io->ipsec_out_type = IPSEC_OUT;
21214 			io->ipsec_out_len = sizeof (ipsec_out_t);
21215 			io->ipsec_out_use_global_policy = B_TRUE;
21216 			io->ipsec_out_ns = ipst->ips_netstack;
21217 			first_mp->b_cont = mp;
21218 			mctl_present = B_TRUE;
21219 		}
21220 		if (attach_ill != NULL) {
21221 			ASSERT(attach_ill == ipif->ipif_ill);
21222 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21223 
21224 			/*
21225 			 * Check if we need an ire that will not be
21226 			 * looked up by anybody else i.e. HIDDEN.
21227 			 */
21228 			if (ill_is_probeonly(attach_ill)) {
21229 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21230 			}
21231 			io->ipsec_out_ill_index =
21232 			    attach_ill->ill_phyint->phyint_ifindex;
21233 			io->ipsec_out_attach_if = B_TRUE;
21234 		} else {
21235 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21236 			io->ipsec_out_ill_index =
21237 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21238 		}
21239 		if (connp != NULL) {
21240 			io->ipsec_out_multicast_loop =
21241 			    connp->conn_multicast_loop;
21242 			io->ipsec_out_dontroute = connp->conn_dontroute;
21243 			io->ipsec_out_zoneid = connp->conn_zoneid;
21244 		}
21245 		/*
21246 		 * If the application uses IP_MULTICAST_IF with
21247 		 * different logical addresses of the same ILL, we
21248 		 * need to make sure that the soruce address of
21249 		 * the packet matches the logical IP address used
21250 		 * in the option. We do it by initializing ipha_src
21251 		 * here. This should keep IPSEC also happy as
21252 		 * when we return from IPSEC processing, we don't
21253 		 * have to worry about getting the right address on
21254 		 * the packet. Thus it is sufficient to look for
21255 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21256 		 * MATCH_IRE_IPIF.
21257 		 *
21258 		 * NOTE : We need to do it for non-secure case also as
21259 		 * this might go out secure if there is a global policy
21260 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21261 		 * address, the source should be initialized already and
21262 		 * hence we won't be initializing here.
21263 		 *
21264 		 * As we do not have the ire yet, it is possible that
21265 		 * we set the source address here and then later discover
21266 		 * that the ire implies the source address to be assigned
21267 		 * through the RTF_SETSRC flag.
21268 		 * In that case, the setsrc variable will remind us
21269 		 * that overwritting the source address by the one
21270 		 * of the RTF_SETSRC-flagged ire is allowed.
21271 		 */
21272 		if (ipha->ipha_src == INADDR_ANY &&
21273 		    (connp == NULL || !connp->conn_unspec_src)) {
21274 			ipha->ipha_src = ipif->ipif_src_addr;
21275 			setsrc = RTF_SETSRC;
21276 		}
21277 		/*
21278 		 * Find an IRE which matches the destination and the outgoing
21279 		 * queue (i.e. the outgoing interface.)
21280 		 * For loopback use a unicast IP address for
21281 		 * the ire lookup.
21282 		 */
21283 		if (IS_LOOPBACK(ipif->ipif_ill))
21284 			dst = ipif->ipif_lcl_addr;
21285 
21286 		/*
21287 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21288 		 * We don't need to lookup ire in ctable as the packet
21289 		 * needs to be sent to the destination through the specified
21290 		 * ill irrespective of ires in the cache table.
21291 		 */
21292 		ire = NULL;
21293 		if (xmit_ill == NULL) {
21294 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21295 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21296 		}
21297 
21298 		/*
21299 		 * refrele attach_ill as its not needed anymore.
21300 		 */
21301 		if (attach_ill != NULL) {
21302 			ill_refrele(attach_ill);
21303 			attach_ill = NULL;
21304 		}
21305 
21306 		if (ire == NULL) {
21307 			/*
21308 			 * Multicast loopback and multicast forwarding is
21309 			 * done in ip_wput_ire.
21310 			 *
21311 			 * Mark this packet to make it be delivered to
21312 			 * ip_wput_ire after the new ire has been
21313 			 * created.
21314 			 *
21315 			 * The call to ip_newroute_ipif takes into account
21316 			 * the setsrc reminder. In any case, we take care
21317 			 * of the RTF_MULTIRT flag.
21318 			 */
21319 			mp->b_prev = mp->b_next = NULL;
21320 			if (xmit_ill == NULL ||
21321 			    xmit_ill->ill_ipif_up_count > 0) {
21322 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21323 				    setsrc | RTF_MULTIRT, zoneid, infop);
21324 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21325 				    "ip_wput_end: q %p (%S)", q, "noire");
21326 			} else {
21327 				freemsg(first_mp);
21328 			}
21329 			ipif_refrele(ipif);
21330 			if (xmit_ill != NULL)
21331 				ill_refrele(xmit_ill);
21332 			if (need_decref)
21333 				CONN_DEC_REF(connp);
21334 			return;
21335 		}
21336 
21337 		ipif_refrele(ipif);
21338 		ipif = NULL;
21339 		ASSERT(xmit_ill == NULL);
21340 
21341 		/*
21342 		 * Honor the RTF_SETSRC flag for multicast packets,
21343 		 * if allowed by the setsrc reminder.
21344 		 */
21345 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21346 			ipha->ipha_src = ire->ire_src_addr;
21347 		}
21348 
21349 		/*
21350 		 * Unconditionally force the TTL to 1 for
21351 		 * multirouted multicast packets:
21352 		 * multirouted multicast should not cross
21353 		 * multicast routers.
21354 		 */
21355 		if (ire->ire_flags & RTF_MULTIRT) {
21356 			if (ipha->ipha_ttl > 1) {
21357 				ip2dbg(("ip_wput: forcing multicast "
21358 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21359 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21360 				ipha->ipha_ttl = 1;
21361 			}
21362 		}
21363 	} else {
21364 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21365 		if ((ire != NULL) && (ire->ire_type &
21366 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21367 			ignore_dontroute = B_TRUE;
21368 			ignore_nexthop = B_TRUE;
21369 		}
21370 		if (ire != NULL) {
21371 			ire_refrele(ire);
21372 			ire = NULL;
21373 		}
21374 		/*
21375 		 * Guard against coming in from arp in which case conn is NULL.
21376 		 * Also guard against non M_DATA with dontroute set but
21377 		 * destined to local, loopback or broadcast addresses.
21378 		 */
21379 		if (connp != NULL && connp->conn_dontroute &&
21380 		    !ignore_dontroute) {
21381 dontroute:
21382 			/*
21383 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21384 			 * routing protocols from seeing false direct
21385 			 * connectivity.
21386 			 */
21387 			ipha->ipha_ttl = 1;
21388 			/*
21389 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21390 			 * along with SO_DONTROUTE, higher precedence is
21391 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21392 			 */
21393 			if (connp->conn_xmit_if_ill == NULL) {
21394 				/* If suitable ipif not found, drop packet */
21395 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21396 				    ipst);
21397 				if (dst_ipif == NULL) {
21398 					ip1dbg(("ip_wput: no route for "
21399 					    "dst using SO_DONTROUTE\n"));
21400 					BUMP_MIB(&ipst->ips_ip_mib,
21401 					    ipIfStatsOutNoRoutes);
21402 					mp->b_prev = mp->b_next = NULL;
21403 					if (first_mp == NULL)
21404 						first_mp = mp;
21405 					goto drop_pkt;
21406 				} else {
21407 					/*
21408 					 * If suitable ipif has been found, set
21409 					 * xmit_ill to the corresponding
21410 					 * ipif_ill because we'll be following
21411 					 * the IP_XMIT_IF logic.
21412 					 */
21413 					ASSERT(xmit_ill == NULL);
21414 					xmit_ill = dst_ipif->ipif_ill;
21415 					mutex_enter(&xmit_ill->ill_lock);
21416 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21417 						mutex_exit(&xmit_ill->ill_lock);
21418 						xmit_ill = NULL;
21419 						ipif_refrele(dst_ipif);
21420 						ip1dbg(("ip_wput: no route for"
21421 						    " dst using"
21422 						    " 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 					}
21430 					ill_refhold_locked(xmit_ill);
21431 					mutex_exit(&xmit_ill->ill_lock);
21432 					ipif_refrele(dst_ipif);
21433 				}
21434 			}
21435 
21436 		}
21437 		/*
21438 		 * If we are bound to IPIF_NOFAILOVER address, look for
21439 		 * an IRE_CACHE matching the ill.
21440 		 */
21441 send_from_ill:
21442 		if (attach_ill != NULL) {
21443 			ipif_t	*attach_ipif;
21444 
21445 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21446 
21447 			/*
21448 			 * Check if we need an ire that will not be
21449 			 * looked up by anybody else i.e. HIDDEN.
21450 			 */
21451 			if (ill_is_probeonly(attach_ill)) {
21452 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21453 			}
21454 
21455 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21456 			if (attach_ipif == NULL) {
21457 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21458 				goto discard_pkt;
21459 			}
21460 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21461 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21462 			ipif_refrele(attach_ipif);
21463 		} else if (xmit_ill != NULL || (connp != NULL &&
21464 		    connp->conn_xmit_if_ill != NULL)) {
21465 			/*
21466 			 * Mark this packet as originated locally
21467 			 */
21468 			mp->b_prev = mp->b_next = NULL;
21469 			/*
21470 			 * xmit_ill could be NULL if SO_DONTROUTE
21471 			 * is also set.
21472 			 */
21473 			if (xmit_ill == NULL) {
21474 				xmit_ill = conn_get_held_ill(connp,
21475 				    &connp->conn_xmit_if_ill, &err);
21476 				if (err == ILL_LOOKUP_FAILED) {
21477 					BUMP_MIB(&ipst->ips_ip_mib,
21478 					    ipIfStatsOutDiscards);
21479 					if (need_decref)
21480 						CONN_DEC_REF(connp);
21481 					freemsg(first_mp);
21482 					return;
21483 				}
21484 				if (xmit_ill == NULL) {
21485 					if (connp->conn_dontroute)
21486 						goto dontroute;
21487 					goto send_from_ill;
21488 				}
21489 			}
21490 			/*
21491 			 * Could be SO_DONTROUTE case also.
21492 			 * check at least one interface is UP as
21493 			 * specified by this ILL
21494 			 */
21495 			if (xmit_ill->ill_ipif_up_count > 0) {
21496 				ipif_t *ipif;
21497 
21498 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21499 				if (ipif == NULL) {
21500 					ip1dbg(("ip_output: "
21501 					    "xmit_ill NULL ipif\n"));
21502 					goto drop_pkt;
21503 				}
21504 				/*
21505 				 * Look for a ire that is part of the group,
21506 				 * if found use it else call ip_newroute_ipif.
21507 				 * IPCL_ZONEID is not used for matching because
21508 				 * IP_ALLZONES option is valid only when the
21509 				 * ill is accessible from all zones i.e has a
21510 				 * valid ipif in all zones.
21511 				 */
21512 				match_flags = MATCH_IRE_ILL_GROUP |
21513 				    MATCH_IRE_SECATTR;
21514 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21515 				    MBLK_GETLABEL(mp), match_flags, ipst);
21516 				/*
21517 				 * If an ire exists use it or else create
21518 				 * an ire but don't add it to the cache.
21519 				 * Adding an ire may cause issues with
21520 				 * asymmetric routing.
21521 				 * In case of multiroute always act as if
21522 				 * ire does not exist.
21523 				 */
21524 				if (ire == NULL ||
21525 				    ire->ire_flags & RTF_MULTIRT) {
21526 					if (ire != NULL)
21527 						ire_refrele(ire);
21528 					ip_newroute_ipif(q, first_mp, ipif,
21529 					    dst, connp, 0, zoneid, infop);
21530 					ipif_refrele(ipif);
21531 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21532 					ill_refrele(xmit_ill);
21533 					if (need_decref)
21534 						CONN_DEC_REF(connp);
21535 					return;
21536 				}
21537 				ipif_refrele(ipif);
21538 			} else {
21539 				goto drop_pkt;
21540 			}
21541 		} else if (ip_nexthop || (connp != NULL &&
21542 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21543 			if (!ip_nexthop) {
21544 				ip_nexthop = B_TRUE;
21545 				nexthop_addr = connp->conn_nexthop_v4;
21546 			}
21547 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21548 			    MATCH_IRE_GW;
21549 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21550 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21551 		} else {
21552 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21553 			    ipst);
21554 		}
21555 		if (!ire) {
21556 			/*
21557 			 * Make sure we don't load spread if this
21558 			 * is IPIF_NOFAILOVER case.
21559 			 */
21560 			if ((attach_ill != NULL) ||
21561 			    (ip_nexthop && !ignore_nexthop)) {
21562 				if (mctl_present) {
21563 					io = (ipsec_out_t *)first_mp->b_rptr;
21564 					ASSERT(first_mp->b_datap->db_type ==
21565 					    M_CTL);
21566 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21567 				} else {
21568 					ASSERT(mp == first_mp);
21569 					first_mp = allocb(
21570 					    sizeof (ipsec_info_t), BPRI_HI);
21571 					if (first_mp == NULL) {
21572 						first_mp = mp;
21573 						goto discard_pkt;
21574 					}
21575 					first_mp->b_datap->db_type = M_CTL;
21576 					first_mp->b_wptr +=
21577 					    sizeof (ipsec_info_t);
21578 					/* ipsec_out_secure is B_FALSE now */
21579 					bzero(first_mp->b_rptr,
21580 					    sizeof (ipsec_info_t));
21581 					io = (ipsec_out_t *)first_mp->b_rptr;
21582 					io->ipsec_out_type = IPSEC_OUT;
21583 					io->ipsec_out_len =
21584 					    sizeof (ipsec_out_t);
21585 					io->ipsec_out_use_global_policy =
21586 					    B_TRUE;
21587 					io->ipsec_out_ns = ipst->ips_netstack;
21588 					first_mp->b_cont = mp;
21589 					mctl_present = B_TRUE;
21590 				}
21591 				if (attach_ill != NULL) {
21592 					io->ipsec_out_ill_index = attach_ill->
21593 					    ill_phyint->phyint_ifindex;
21594 					io->ipsec_out_attach_if = B_TRUE;
21595 				} else {
21596 					io->ipsec_out_ip_nexthop = ip_nexthop;
21597 					io->ipsec_out_nexthop_addr =
21598 					    nexthop_addr;
21599 				}
21600 			}
21601 noirefound:
21602 			/*
21603 			 * Mark this packet as having originated on
21604 			 * this machine.  This will be noted in
21605 			 * ire_add_then_send, which needs to know
21606 			 * whether to run it back through ip_wput or
21607 			 * ip_rput following successful resolution.
21608 			 */
21609 			mp->b_prev = NULL;
21610 			mp->b_next = NULL;
21611 			ip_newroute(q, first_mp, dst, NULL, connp, zoneid,
21612 			    ipst);
21613 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21614 			    "ip_wput_end: q %p (%S)", q, "newroute");
21615 			if (attach_ill != NULL)
21616 				ill_refrele(attach_ill);
21617 			if (xmit_ill != NULL)
21618 				ill_refrele(xmit_ill);
21619 			if (need_decref)
21620 				CONN_DEC_REF(connp);
21621 			return;
21622 		}
21623 	}
21624 
21625 	/* We now know where we are going with it. */
21626 
21627 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21628 	    "ip_wput_end: q %p (%S)", q, "end");
21629 
21630 	/*
21631 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21632 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21633 	 */
21634 	if (ire->ire_flags & RTF_MULTIRT) {
21635 		/*
21636 		 * Force the TTL of multirouted packets if required.
21637 		 * The TTL of such packets is bounded by the
21638 		 * ip_multirt_ttl ndd variable.
21639 		 */
21640 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21641 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21642 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21643 			    "(was %d), dst 0x%08x\n",
21644 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21645 			    ntohl(ire->ire_addr)));
21646 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21647 		}
21648 		/*
21649 		 * At this point, we check to see if there are any pending
21650 		 * unresolved routes. ire_multirt_resolvable()
21651 		 * checks in O(n) that all IRE_OFFSUBNET ire
21652 		 * entries for the packet's destination and
21653 		 * flagged RTF_MULTIRT are currently resolved.
21654 		 * If some remain unresolved, we make a copy
21655 		 * of the current message. It will be used
21656 		 * to initiate additional route resolutions.
21657 		 */
21658 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21659 		    MBLK_GETLABEL(first_mp), ipst);
21660 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21661 		    "multirt_need_resolve %d, first_mp %p\n",
21662 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21663 		if (multirt_need_resolve) {
21664 			copy_mp = copymsg(first_mp);
21665 			if (copy_mp != NULL) {
21666 				MULTIRT_DEBUG_TAG(copy_mp);
21667 			}
21668 		}
21669 	}
21670 
21671 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21672 	/*
21673 	 * Try to resolve another multiroute if
21674 	 * ire_multirt_resolvable() deemed it necessary.
21675 	 * At this point, we need to distinguish
21676 	 * multicasts from other packets. For multicasts,
21677 	 * we call ip_newroute_ipif() and request that both
21678 	 * multirouting and setsrc flags are checked.
21679 	 */
21680 	if (copy_mp != NULL) {
21681 		if (CLASSD(dst)) {
21682 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21683 			if (ipif) {
21684 				ASSERT(infop->ip_opt_ill_index == 0);
21685 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21686 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21687 				ipif_refrele(ipif);
21688 			} else {
21689 				MULTIRT_DEBUG_UNTAG(copy_mp);
21690 				freemsg(copy_mp);
21691 				copy_mp = NULL;
21692 			}
21693 		} else {
21694 			ip_newroute(q, copy_mp, dst, NULL, connp, zoneid, ipst);
21695 		}
21696 	}
21697 	if (attach_ill != NULL)
21698 		ill_refrele(attach_ill);
21699 	if (xmit_ill != NULL)
21700 		ill_refrele(xmit_ill);
21701 	if (need_decref)
21702 		CONN_DEC_REF(connp);
21703 	return;
21704 
21705 icmp_parameter_problem:
21706 	/* could not have originated externally */
21707 	ASSERT(mp->b_prev == NULL);
21708 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21709 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21710 		/* it's the IP header length that's in trouble */
21711 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21712 		first_mp = NULL;
21713 	}
21714 
21715 discard_pkt:
21716 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21717 drop_pkt:
21718 	ip1dbg(("ip_wput: dropped packet\n"));
21719 	if (ire != NULL)
21720 		ire_refrele(ire);
21721 	if (need_decref)
21722 		CONN_DEC_REF(connp);
21723 	freemsg(first_mp);
21724 	if (attach_ill != NULL)
21725 		ill_refrele(attach_ill);
21726 	if (xmit_ill != NULL)
21727 		ill_refrele(xmit_ill);
21728 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21729 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21730 }
21731 
21732 /*
21733  * If this is a conn_t queue, then we pass in the conn. This includes the
21734  * zoneid.
21735  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21736  * in which case we use the global zoneid since those are all part of
21737  * the global zone.
21738  */
21739 void
21740 ip_wput(queue_t *q, mblk_t *mp)
21741 {
21742 	if (CONN_Q(q))
21743 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21744 	else
21745 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21746 }
21747 
21748 /*
21749  *
21750  * The following rules must be observed when accessing any ipif or ill
21751  * that has been cached in the conn. Typically conn_nofailover_ill,
21752  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21753  *
21754  * Access: The ipif or ill pointed to from the conn can be accessed under
21755  * the protection of the conn_lock or after it has been refheld under the
21756  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21757  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21758  * The reason for this is that a concurrent unplumb could actually be
21759  * cleaning up these cached pointers by walking the conns and might have
21760  * finished cleaning up the conn in question. The macros check that an
21761  * unplumb has not yet started on the ipif or ill.
21762  *
21763  * Caching: An ipif or ill pointer may be cached in the conn only after
21764  * making sure that an unplumb has not started. So the caching is done
21765  * while holding both the conn_lock and the ill_lock and after using the
21766  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21767  * flag before starting the cleanup of conns.
21768  *
21769  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21770  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21771  * or a reference to the ipif or a reference to an ire that references the
21772  * ipif. An ipif does not change its ill except for failover/failback. Since
21773  * failover/failback happens only after bringing down the ipif and making sure
21774  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21775  * the above holds.
21776  */
21777 ipif_t *
21778 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21779 {
21780 	ipif_t	*ipif;
21781 	ill_t	*ill;
21782 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21783 
21784 	*err = 0;
21785 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21786 	mutex_enter(&connp->conn_lock);
21787 	ipif = *ipifp;
21788 	if (ipif != NULL) {
21789 		ill = ipif->ipif_ill;
21790 		mutex_enter(&ill->ill_lock);
21791 		if (IPIF_CAN_LOOKUP(ipif)) {
21792 			ipif_refhold_locked(ipif);
21793 			mutex_exit(&ill->ill_lock);
21794 			mutex_exit(&connp->conn_lock);
21795 			rw_exit(&ipst->ips_ill_g_lock);
21796 			return (ipif);
21797 		} else {
21798 			*err = IPIF_LOOKUP_FAILED;
21799 		}
21800 		mutex_exit(&ill->ill_lock);
21801 	}
21802 	mutex_exit(&connp->conn_lock);
21803 	rw_exit(&ipst->ips_ill_g_lock);
21804 	return (NULL);
21805 }
21806 
21807 ill_t *
21808 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21809 {
21810 	ill_t	*ill;
21811 
21812 	*err = 0;
21813 	mutex_enter(&connp->conn_lock);
21814 	ill = *illp;
21815 	if (ill != NULL) {
21816 		mutex_enter(&ill->ill_lock);
21817 		if (ILL_CAN_LOOKUP(ill)) {
21818 			ill_refhold_locked(ill);
21819 			mutex_exit(&ill->ill_lock);
21820 			mutex_exit(&connp->conn_lock);
21821 			return (ill);
21822 		} else {
21823 			*err = ILL_LOOKUP_FAILED;
21824 		}
21825 		mutex_exit(&ill->ill_lock);
21826 	}
21827 	mutex_exit(&connp->conn_lock);
21828 	return (NULL);
21829 }
21830 
21831 static int
21832 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21833 {
21834 	ill_t	*ill;
21835 
21836 	ill = ipif->ipif_ill;
21837 	mutex_enter(&connp->conn_lock);
21838 	mutex_enter(&ill->ill_lock);
21839 	if (IPIF_CAN_LOOKUP(ipif)) {
21840 		*ipifp = ipif;
21841 		mutex_exit(&ill->ill_lock);
21842 		mutex_exit(&connp->conn_lock);
21843 		return (0);
21844 	}
21845 	mutex_exit(&ill->ill_lock);
21846 	mutex_exit(&connp->conn_lock);
21847 	return (IPIF_LOOKUP_FAILED);
21848 }
21849 
21850 /*
21851  * This is called if the outbound datagram needs fragmentation.
21852  *
21853  * NOTE : This function does not ire_refrele the ire argument passed in.
21854  */
21855 static void
21856 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21857     ip_stack_t *ipst)
21858 {
21859 	ipha_t		*ipha;
21860 	mblk_t		*mp;
21861 	uint32_t	v_hlen_tos_len;
21862 	uint32_t	max_frag;
21863 	uint32_t	frag_flag;
21864 	boolean_t	dont_use;
21865 
21866 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21867 		mp = ipsec_mp->b_cont;
21868 	} else {
21869 		mp = ipsec_mp;
21870 	}
21871 
21872 	ipha = (ipha_t *)mp->b_rptr;
21873 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21874 
21875 #ifdef	_BIG_ENDIAN
21876 #define	V_HLEN	(v_hlen_tos_len >> 24)
21877 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21878 #else
21879 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21880 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21881 #endif
21882 
21883 #ifndef SPEED_BEFORE_SAFETY
21884 	/*
21885 	 * Check that ipha_length is consistent with
21886 	 * the mblk length
21887 	 */
21888 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21889 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21890 		    LENGTH, msgdsize(mp)));
21891 		freemsg(ipsec_mp);
21892 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21893 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21894 		    "packet length mismatch");
21895 		return;
21896 	}
21897 #endif
21898 	/*
21899 	 * Don't use frag_flag if pre-built packet or source
21900 	 * routed or if multicast (since multicast packets do not solicit
21901 	 * ICMP "packet too big" messages). Get the values of
21902 	 * max_frag and frag_flag atomically by acquiring the
21903 	 * ire_lock.
21904 	 */
21905 	mutex_enter(&ire->ire_lock);
21906 	max_frag = ire->ire_max_frag;
21907 	frag_flag = ire->ire_frag_flag;
21908 	mutex_exit(&ire->ire_lock);
21909 
21910 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21911 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21912 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21913 
21914 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21915 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21916 }
21917 
21918 /*
21919  * Used for deciding the MSS size for the upper layer. Thus
21920  * we need to check the outbound policy values in the conn.
21921  */
21922 int
21923 conn_ipsec_length(conn_t *connp)
21924 {
21925 	ipsec_latch_t *ipl;
21926 
21927 	ipl = connp->conn_latch;
21928 	if (ipl == NULL)
21929 		return (0);
21930 
21931 	if (ipl->ipl_out_policy == NULL)
21932 		return (0);
21933 
21934 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21935 }
21936 
21937 /*
21938  * Returns an estimate of the IPSEC headers size. This is used if
21939  * we don't want to call into IPSEC to get the exact size.
21940  */
21941 int
21942 ipsec_out_extra_length(mblk_t *ipsec_mp)
21943 {
21944 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21945 	ipsec_action_t *a;
21946 
21947 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21948 	if (!io->ipsec_out_secure)
21949 		return (0);
21950 
21951 	a = io->ipsec_out_act;
21952 
21953 	if (a == NULL) {
21954 		ASSERT(io->ipsec_out_policy != NULL);
21955 		a = io->ipsec_out_policy->ipsp_act;
21956 	}
21957 	ASSERT(a != NULL);
21958 
21959 	return (a->ipa_ovhd);
21960 }
21961 
21962 /*
21963  * Returns an estimate of the IPSEC headers size. This is used if
21964  * we don't want to call into IPSEC to get the exact size.
21965  */
21966 int
21967 ipsec_in_extra_length(mblk_t *ipsec_mp)
21968 {
21969 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21970 	ipsec_action_t *a;
21971 
21972 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21973 
21974 	a = ii->ipsec_in_action;
21975 	return (a == NULL ? 0 : a->ipa_ovhd);
21976 }
21977 
21978 /*
21979  * If there are any source route options, return the true final
21980  * destination. Otherwise, return the destination.
21981  */
21982 ipaddr_t
21983 ip_get_dst(ipha_t *ipha)
21984 {
21985 	ipoptp_t	opts;
21986 	uchar_t		*opt;
21987 	uint8_t		optval;
21988 	uint8_t		optlen;
21989 	ipaddr_t	dst;
21990 	uint32_t off;
21991 
21992 	dst = ipha->ipha_dst;
21993 
21994 	if (IS_SIMPLE_IPH(ipha))
21995 		return (dst);
21996 
21997 	for (optval = ipoptp_first(&opts, ipha);
21998 	    optval != IPOPT_EOL;
21999 	    optval = ipoptp_next(&opts)) {
22000 		opt = opts.ipoptp_cur;
22001 		optlen = opts.ipoptp_len;
22002 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
22003 		switch (optval) {
22004 		case IPOPT_SSRR:
22005 		case IPOPT_LSRR:
22006 			off = opt[IPOPT_OFFSET];
22007 			/*
22008 			 * If one of the conditions is true, it means
22009 			 * end of options and dst already has the right
22010 			 * value.
22011 			 */
22012 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
22013 				off = optlen - IP_ADDR_LEN;
22014 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
22015 			}
22016 			return (dst);
22017 		default:
22018 			break;
22019 		}
22020 	}
22021 
22022 	return (dst);
22023 }
22024 
22025 mblk_t *
22026 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
22027     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
22028 {
22029 	ipsec_out_t	*io;
22030 	mblk_t		*first_mp;
22031 	boolean_t policy_present;
22032 	ip_stack_t	*ipst;
22033 	ipsec_stack_t	*ipss;
22034 
22035 	ASSERT(ire != NULL);
22036 	ipst = ire->ire_ipst;
22037 	ipss = ipst->ips_netstack->netstack_ipsec;
22038 
22039 	first_mp = mp;
22040 	if (mp->b_datap->db_type == M_CTL) {
22041 		io = (ipsec_out_t *)first_mp->b_rptr;
22042 		/*
22043 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
22044 		 *
22045 		 * 1) There is per-socket policy (including cached global
22046 		 *    policy) or a policy on the IP-in-IP tunnel.
22047 		 * 2) There is no per-socket policy, but it is
22048 		 *    a multicast packet that needs to go out
22049 		 *    on a specific interface. This is the case
22050 		 *    where (ip_wput and ip_wput_multicast) attaches
22051 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
22052 		 *
22053 		 * In case (2) we check with global policy to
22054 		 * see if there is a match and set the ill_index
22055 		 * appropriately so that we can lookup the ire
22056 		 * properly in ip_wput_ipsec_out.
22057 		 */
22058 
22059 		/*
22060 		 * ipsec_out_use_global_policy is set to B_FALSE
22061 		 * in ipsec_in_to_out(). Refer to that function for
22062 		 * details.
22063 		 */
22064 		if ((io->ipsec_out_latch == NULL) &&
22065 		    (io->ipsec_out_use_global_policy)) {
22066 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
22067 			    ire, connp, unspec_src, zoneid));
22068 		}
22069 		if (!io->ipsec_out_secure) {
22070 			/*
22071 			 * If this is not a secure packet, drop
22072 			 * the IPSEC_OUT mp and treat it as a clear
22073 			 * packet. This happens when we are sending
22074 			 * a ICMP reply back to a clear packet. See
22075 			 * ipsec_in_to_out() for details.
22076 			 */
22077 			mp = first_mp->b_cont;
22078 			freeb(first_mp);
22079 		}
22080 		return (mp);
22081 	}
22082 	/*
22083 	 * See whether we need to attach a global policy here. We
22084 	 * don't depend on the conn (as it could be null) for deciding
22085 	 * what policy this datagram should go through because it
22086 	 * should have happened in ip_wput if there was some
22087 	 * policy. This normally happens for connections which are not
22088 	 * fully bound preventing us from caching policies in
22089 	 * ip_bind. Packets coming from the TCP listener/global queue
22090 	 * - which are non-hard_bound - could also be affected by
22091 	 * applying policy here.
22092 	 *
22093 	 * If this packet is coming from tcp global queue or listener,
22094 	 * we will be applying policy here.  This may not be *right*
22095 	 * if these packets are coming from the detached connection as
22096 	 * it could have gone in clear before. This happens only if a
22097 	 * TCP connection started when there is no policy and somebody
22098 	 * added policy before it became detached. Thus packets of the
22099 	 * detached connection could go out secure and the other end
22100 	 * would drop it because it will be expecting in clear. The
22101 	 * converse is not true i.e if somebody starts a TCP
22102 	 * connection and deletes the policy, all the packets will
22103 	 * still go out with the policy that existed before deleting
22104 	 * because ip_unbind sends up policy information which is used
22105 	 * by TCP on subsequent ip_wputs. The right solution is to fix
22106 	 * TCP to attach a dummy IPSEC_OUT and set
22107 	 * ipsec_out_use_global_policy to B_FALSE. As this might
22108 	 * affect performance for normal cases, we are not doing it.
22109 	 * Thus, set policy before starting any TCP connections.
22110 	 *
22111 	 * NOTE - We might apply policy even for a hard bound connection
22112 	 * - for which we cached policy in ip_bind - if somebody added
22113 	 * global policy after we inherited the policy in ip_bind.
22114 	 * This means that the packets that were going out in clear
22115 	 * previously would start going secure and hence get dropped
22116 	 * on the other side. To fix this, TCP attaches a dummy
22117 	 * ipsec_out and make sure that we don't apply global policy.
22118 	 */
22119 	if (ipha != NULL)
22120 		policy_present = ipss->ipsec_outbound_v4_policy_present;
22121 	else
22122 		policy_present = ipss->ipsec_outbound_v6_policy_present;
22123 	if (!policy_present)
22124 		return (mp);
22125 
22126 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
22127 	    zoneid));
22128 }
22129 
22130 ire_t *
22131 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
22132 {
22133 	ipaddr_t addr;
22134 	ire_t *save_ire;
22135 	irb_t *irb;
22136 	ill_group_t *illgrp;
22137 	int	err;
22138 
22139 	save_ire = ire;
22140 	addr = ire->ire_addr;
22141 
22142 	ASSERT(ire->ire_type == IRE_BROADCAST);
22143 
22144 	illgrp = connp->conn_outgoing_ill->ill_group;
22145 	if (illgrp == NULL) {
22146 		*conn_outgoing_ill = conn_get_held_ill(connp,
22147 		    &connp->conn_outgoing_ill, &err);
22148 		if (err == ILL_LOOKUP_FAILED) {
22149 			ire_refrele(save_ire);
22150 			return (NULL);
22151 		}
22152 		return (save_ire);
22153 	}
22154 	/*
22155 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
22156 	 * If it is part of the group, we need to send on the ire
22157 	 * that has been cleared of IRE_MARK_NORECV and that belongs
22158 	 * to this group. This is okay as IP_BOUND_IF really means
22159 	 * any ill in the group. We depend on the fact that the
22160 	 * first ire in the group is always cleared of IRE_MARK_NORECV
22161 	 * if such an ire exists. This is possible only if you have
22162 	 * at least one ill in the group that has not failed.
22163 	 *
22164 	 * First get to the ire that matches the address and group.
22165 	 *
22166 	 * We don't look for an ire with a matching zoneid because a given zone
22167 	 * won't always have broadcast ires on all ills in the group.
22168 	 */
22169 	irb = ire->ire_bucket;
22170 	rw_enter(&irb->irb_lock, RW_READER);
22171 	if (ire->ire_marks & IRE_MARK_NORECV) {
22172 		/*
22173 		 * If the current zone only has an ire broadcast for this
22174 		 * address marked NORECV, the ire we want is ahead in the
22175 		 * bucket, so we look it up deliberately ignoring the zoneid.
22176 		 */
22177 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22178 			if (ire->ire_addr != addr)
22179 				continue;
22180 			/* skip over deleted ires */
22181 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22182 				continue;
22183 		}
22184 	}
22185 	while (ire != NULL) {
22186 		/*
22187 		 * If a new interface is coming up, we could end up
22188 		 * seeing the loopback ire and the non-loopback ire
22189 		 * may not have been added yet. So check for ire_stq
22190 		 */
22191 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22192 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22193 			break;
22194 		}
22195 		ire = ire->ire_next;
22196 	}
22197 	if (ire != NULL && ire->ire_addr == addr &&
22198 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22199 		IRE_REFHOLD(ire);
22200 		rw_exit(&irb->irb_lock);
22201 		ire_refrele(save_ire);
22202 		*conn_outgoing_ill = ire_to_ill(ire);
22203 		/*
22204 		 * Refhold the ill to make the conn_outgoing_ill
22205 		 * independent of the ire. ip_wput_ire goes in a loop
22206 		 * and may refrele the ire. Since we have an ire at this
22207 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22208 		 */
22209 		ill_refhold(*conn_outgoing_ill);
22210 		return (ire);
22211 	}
22212 	rw_exit(&irb->irb_lock);
22213 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22214 	/*
22215 	 * If we can't find a suitable ire, return the original ire.
22216 	 */
22217 	return (save_ire);
22218 }
22219 
22220 /*
22221  * This function does the ire_refrele of the ire passed in as the
22222  * argument. As this function looks up more ires i.e broadcast ires,
22223  * it needs to REFRELE them. Currently, for simplicity we don't
22224  * differentiate the one passed in and looked up here. We always
22225  * REFRELE.
22226  * IPQoS Notes:
22227  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22228  * IPSec packets are done in ipsec_out_process.
22229  *
22230  */
22231 void
22232 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22233     zoneid_t zoneid)
22234 {
22235 	ipha_t		*ipha;
22236 #define	rptr	((uchar_t *)ipha)
22237 	queue_t		*stq;
22238 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22239 	uint32_t	v_hlen_tos_len;
22240 	uint32_t	ttl_protocol;
22241 	ipaddr_t	src;
22242 	ipaddr_t	dst;
22243 	uint32_t	cksum;
22244 	ipaddr_t	orig_src;
22245 	ire_t		*ire1;
22246 	mblk_t		*next_mp;
22247 	uint_t		hlen;
22248 	uint16_t	*up;
22249 	uint32_t	max_frag = ire->ire_max_frag;
22250 	ill_t		*ill = ire_to_ill(ire);
22251 	int		clusterwide;
22252 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22253 	int		ipsec_len;
22254 	mblk_t		*first_mp;
22255 	ipsec_out_t	*io;
22256 	boolean_t	conn_dontroute;		/* conn value for multicast */
22257 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22258 	boolean_t	multicast_forward;	/* Should we forward ? */
22259 	boolean_t	unspec_src;
22260 	ill_t		*conn_outgoing_ill = NULL;
22261 	ill_t		*ire_ill;
22262 	ill_t		*ire1_ill;
22263 	ill_t		*out_ill;
22264 	uint32_t 	ill_index = 0;
22265 	boolean_t	multirt_send = B_FALSE;
22266 	int		err;
22267 	ipxmit_state_t	pktxmit_state;
22268 	ip_stack_t	*ipst = ire->ire_ipst;
22269 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22270 
22271 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22272 	    "ip_wput_ire_start: q %p", q);
22273 
22274 	multicast_forward = B_FALSE;
22275 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22276 
22277 	if (ire->ire_flags & RTF_MULTIRT) {
22278 		/*
22279 		 * Multirouting case. The bucket where ire is stored
22280 		 * probably holds other RTF_MULTIRT flagged ire
22281 		 * to the destination. In this call to ip_wput_ire,
22282 		 * we attempt to send the packet through all
22283 		 * those ires. Thus, we first ensure that ire is the
22284 		 * first RTF_MULTIRT ire in the bucket,
22285 		 * before walking the ire list.
22286 		 */
22287 		ire_t *first_ire;
22288 		irb_t *irb = ire->ire_bucket;
22289 		ASSERT(irb != NULL);
22290 
22291 		/* Make sure we do not omit any multiroute ire. */
22292 		IRB_REFHOLD(irb);
22293 		for (first_ire = irb->irb_ire;
22294 		    first_ire != NULL;
22295 		    first_ire = first_ire->ire_next) {
22296 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22297 			    (first_ire->ire_addr == ire->ire_addr) &&
22298 			    !(first_ire->ire_marks &
22299 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22300 				break;
22301 			}
22302 		}
22303 
22304 		if ((first_ire != NULL) && (first_ire != ire)) {
22305 			IRE_REFHOLD(first_ire);
22306 			ire_refrele(ire);
22307 			ire = first_ire;
22308 			ill = ire_to_ill(ire);
22309 		}
22310 		IRB_REFRELE(irb);
22311 	}
22312 
22313 	/*
22314 	 * conn_outgoing_ill is used only in the broadcast loop.
22315 	 * for performance we don't grab the mutexs in the fastpath
22316 	 */
22317 	if ((connp != NULL) &&
22318 	    (connp->conn_xmit_if_ill == NULL) &&
22319 	    (ire->ire_type == IRE_BROADCAST) &&
22320 	    ((connp->conn_nofailover_ill != NULL) ||
22321 	    (connp->conn_outgoing_ill != NULL))) {
22322 		/*
22323 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22324 		 * option. So, see if this endpoint is bound to a
22325 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22326 		 * that if the interface is failed, we will still send
22327 		 * the packet on the same ill which is what we want.
22328 		 */
22329 		conn_outgoing_ill = conn_get_held_ill(connp,
22330 		    &connp->conn_nofailover_ill, &err);
22331 		if (err == ILL_LOOKUP_FAILED) {
22332 			ire_refrele(ire);
22333 			freemsg(mp);
22334 			return;
22335 		}
22336 		if (conn_outgoing_ill == NULL) {
22337 			/*
22338 			 * Choose a good ill in the group to send the
22339 			 * packets on.
22340 			 */
22341 			ire = conn_set_outgoing_ill(connp, ire,
22342 			    &conn_outgoing_ill);
22343 			if (ire == NULL) {
22344 				freemsg(mp);
22345 				return;
22346 			}
22347 		}
22348 	}
22349 
22350 	if (mp->b_datap->db_type != M_CTL) {
22351 		ipha = (ipha_t *)mp->b_rptr;
22352 	} else {
22353 		io = (ipsec_out_t *)mp->b_rptr;
22354 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22355 		ASSERT(zoneid == io->ipsec_out_zoneid);
22356 		ASSERT(zoneid != ALL_ZONES);
22357 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22358 		dst = ipha->ipha_dst;
22359 		/*
22360 		 * For the multicast case, ipsec_out carries conn_dontroute and
22361 		 * conn_multicast_loop as conn may not be available here. We
22362 		 * need this for multicast loopback and forwarding which is done
22363 		 * later in the code.
22364 		 */
22365 		if (CLASSD(dst)) {
22366 			conn_dontroute = io->ipsec_out_dontroute;
22367 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22368 			/*
22369 			 * If conn_dontroute is not set or conn_multicast_loop
22370 			 * is set, we need to do forwarding/loopback. For
22371 			 * datagrams from ip_wput_multicast, conn_dontroute is
22372 			 * set to B_TRUE and conn_multicast_loop is set to
22373 			 * B_FALSE so that we neither do forwarding nor
22374 			 * loopback.
22375 			 */
22376 			if (!conn_dontroute || conn_multicast_loop)
22377 				multicast_forward = B_TRUE;
22378 		}
22379 	}
22380 
22381 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22382 	    ire->ire_zoneid != ALL_ZONES) {
22383 		/*
22384 		 * When a zone sends a packet to another zone, we try to deliver
22385 		 * the packet under the same conditions as if the destination
22386 		 * was a real node on the network. To do so, we look for a
22387 		 * matching route in the forwarding table.
22388 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22389 		 * ip_newroute() does.
22390 		 * Note that IRE_LOCAL are special, since they are used
22391 		 * when the zoneid doesn't match in some cases. This means that
22392 		 * we need to handle ipha_src differently since ire_src_addr
22393 		 * belongs to the receiving zone instead of the sending zone.
22394 		 * When ip_restrict_interzone_loopback is set, then
22395 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22396 		 * for loopback between zones when the logical "Ethernet" would
22397 		 * have looped them back.
22398 		 */
22399 		ire_t *src_ire;
22400 
22401 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22402 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22403 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22404 		if (src_ire != NULL &&
22405 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22406 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22407 		    ire_local_same_ill_group(ire, src_ire))) {
22408 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22409 				ipha->ipha_src = src_ire->ire_src_addr;
22410 			ire_refrele(src_ire);
22411 		} else {
22412 			ire_refrele(ire);
22413 			if (conn_outgoing_ill != NULL)
22414 				ill_refrele(conn_outgoing_ill);
22415 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22416 			if (src_ire != NULL) {
22417 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22418 					ire_refrele(src_ire);
22419 					freemsg(mp);
22420 					return;
22421 				}
22422 				ire_refrele(src_ire);
22423 			}
22424 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22425 				/* Failed */
22426 				freemsg(mp);
22427 				return;
22428 			}
22429 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22430 			    ipst);
22431 			return;
22432 		}
22433 	}
22434 
22435 	if (mp->b_datap->db_type == M_CTL ||
22436 	    ipss->ipsec_outbound_v4_policy_present) {
22437 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22438 		    unspec_src, zoneid);
22439 		if (mp == NULL) {
22440 			ire_refrele(ire);
22441 			if (conn_outgoing_ill != NULL)
22442 				ill_refrele(conn_outgoing_ill);
22443 			return;
22444 		}
22445 	}
22446 
22447 	first_mp = mp;
22448 	ipsec_len = 0;
22449 
22450 	if (first_mp->b_datap->db_type == M_CTL) {
22451 		io = (ipsec_out_t *)first_mp->b_rptr;
22452 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22453 		mp = first_mp->b_cont;
22454 		ipsec_len = ipsec_out_extra_length(first_mp);
22455 		ASSERT(ipsec_len >= 0);
22456 		/* We already picked up the zoneid from the M_CTL above */
22457 		ASSERT(zoneid == io->ipsec_out_zoneid);
22458 		ASSERT(zoneid != ALL_ZONES);
22459 
22460 		/*
22461 		 * Drop M_CTL here if IPsec processing is not needed.
22462 		 * (Non-IPsec use of M_CTL extracted any information it
22463 		 * needed above).
22464 		 */
22465 		if (ipsec_len == 0) {
22466 			freeb(first_mp);
22467 			first_mp = mp;
22468 		}
22469 	}
22470 
22471 	/*
22472 	 * Fast path for ip_wput_ire
22473 	 */
22474 
22475 	ipha = (ipha_t *)mp->b_rptr;
22476 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22477 	dst = ipha->ipha_dst;
22478 
22479 	/*
22480 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22481 	 * if the socket is a SOCK_RAW type. The transport checksum should
22482 	 * be provided in the pre-built packet, so we don't need to compute it.
22483 	 * Also, other application set flags, like DF, should not be altered.
22484 	 * Other transport MUST pass down zero.
22485 	 */
22486 	ip_hdr_included = ipha->ipha_ident;
22487 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22488 
22489 	if (CLASSD(dst)) {
22490 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22491 		    ntohl(dst),
22492 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22493 		    ntohl(ire->ire_addr)));
22494 	}
22495 
22496 /* Macros to extract header fields from data already in registers */
22497 #ifdef	_BIG_ENDIAN
22498 #define	V_HLEN	(v_hlen_tos_len >> 24)
22499 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22500 #define	PROTO	(ttl_protocol & 0xFF)
22501 #else
22502 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22503 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22504 #define	PROTO	(ttl_protocol >> 8)
22505 #endif
22506 
22507 
22508 	orig_src = src = ipha->ipha_src;
22509 	/* (The loop back to "another" is explained down below.) */
22510 another:;
22511 	/*
22512 	 * Assign an ident value for this packet.  We assign idents on
22513 	 * a per destination basis out of the IRE.  There could be
22514 	 * other threads targeting the same destination, so we have to
22515 	 * arrange for a atomic increment.  Note that we use a 32-bit
22516 	 * atomic add because it has better performance than its
22517 	 * 16-bit sibling.
22518 	 *
22519 	 * If running in cluster mode and if the source address
22520 	 * belongs to a replicated service then vector through
22521 	 * cl_inet_ipident vector to allocate ip identifier
22522 	 * NOTE: This is a contract private interface with the
22523 	 * clustering group.
22524 	 */
22525 	clusterwide = 0;
22526 	if (cl_inet_ipident) {
22527 		ASSERT(cl_inet_isclusterwide);
22528 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22529 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22530 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22531 			    AF_INET, (uint8_t *)(uintptr_t)src,
22532 			    (uint8_t *)(uintptr_t)dst);
22533 			clusterwide = 1;
22534 		}
22535 	}
22536 	if (!clusterwide) {
22537 		ipha->ipha_ident =
22538 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22539 	}
22540 
22541 #ifndef _BIG_ENDIAN
22542 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22543 #endif
22544 
22545 	/*
22546 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22547 	 * This is needed to obey conn_unspec_src when packets go through
22548 	 * ip_newroute + arp.
22549 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22550 	 */
22551 	if (src == INADDR_ANY && !unspec_src) {
22552 		/*
22553 		 * Assign the appropriate source address from the IRE if none
22554 		 * was specified.
22555 		 */
22556 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22557 
22558 		/*
22559 		 * With IP multipathing, broadcast packets are sent on the ire
22560 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22561 		 * the group. However, this ire might not be in the same zone so
22562 		 * we can't always use its source address. We look for a
22563 		 * broadcast ire in the same group and in the right zone.
22564 		 */
22565 		if (ire->ire_type == IRE_BROADCAST &&
22566 		    ire->ire_zoneid != zoneid) {
22567 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22568 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22569 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22570 			if (src_ire != NULL) {
22571 				src = src_ire->ire_src_addr;
22572 				ire_refrele(src_ire);
22573 			} else {
22574 				ire_refrele(ire);
22575 				if (conn_outgoing_ill != NULL)
22576 					ill_refrele(conn_outgoing_ill);
22577 				freemsg(first_mp);
22578 				if (ill != NULL) {
22579 					BUMP_MIB(ill->ill_ip_mib,
22580 					    ipIfStatsOutDiscards);
22581 				} else {
22582 					BUMP_MIB(&ipst->ips_ip_mib,
22583 					    ipIfStatsOutDiscards);
22584 				}
22585 				return;
22586 			}
22587 		} else {
22588 			src = ire->ire_src_addr;
22589 		}
22590 
22591 		if (connp == NULL) {
22592 			ip1dbg(("ip_wput_ire: no connp and no src "
22593 			    "address for dst 0x%x, using src 0x%x\n",
22594 			    ntohl(dst),
22595 			    ntohl(src)));
22596 		}
22597 		ipha->ipha_src = src;
22598 	}
22599 	stq = ire->ire_stq;
22600 
22601 	/*
22602 	 * We only allow ire chains for broadcasts since there will
22603 	 * be multiple IRE_CACHE entries for the same multicast
22604 	 * address (one per ipif).
22605 	 */
22606 	next_mp = NULL;
22607 
22608 	/* broadcast packet */
22609 	if (ire->ire_type == IRE_BROADCAST)
22610 		goto broadcast;
22611 
22612 	/* loopback ? */
22613 	if (stq == NULL)
22614 		goto nullstq;
22615 
22616 	/* The ill_index for outbound ILL */
22617 	ill_index = Q_TO_INDEX(stq);
22618 
22619 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22620 	ttl_protocol = ((uint16_t *)ipha)[4];
22621 
22622 	/* pseudo checksum (do it in parts for IP header checksum) */
22623 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22624 
22625 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22626 		queue_t *dev_q = stq->q_next;
22627 
22628 		/* flow controlled */
22629 		if ((dev_q->q_next || dev_q->q_first) &&
22630 		    !canput(dev_q))
22631 			goto blocked;
22632 		if ((PROTO == IPPROTO_UDP) &&
22633 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22634 			hlen = (V_HLEN & 0xF) << 2;
22635 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22636 			if (*up != 0) {
22637 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22638 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22639 				/* Software checksum? */
22640 				if (DB_CKSUMFLAGS(mp) == 0) {
22641 					IP_STAT(ipst, ip_out_sw_cksum);
22642 					IP_STAT_UPDATE(ipst,
22643 					    ip_udp_out_sw_cksum_bytes,
22644 					    LENGTH - hlen);
22645 				}
22646 			}
22647 		}
22648 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22649 		hlen = (V_HLEN & 0xF) << 2;
22650 		if (PROTO == IPPROTO_TCP) {
22651 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22652 			/*
22653 			 * The packet header is processed once and for all, even
22654 			 * in the multirouting case. We disable hardware
22655 			 * checksum if the packet is multirouted, as it will be
22656 			 * replicated via several interfaces, and not all of
22657 			 * them may have this capability.
22658 			 */
22659 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22660 			    LENGTH, max_frag, ipsec_len, cksum);
22661 			/* Software checksum? */
22662 			if (DB_CKSUMFLAGS(mp) == 0) {
22663 				IP_STAT(ipst, ip_out_sw_cksum);
22664 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22665 				    LENGTH - hlen);
22666 			}
22667 		} else {
22668 			sctp_hdr_t	*sctph;
22669 
22670 			ASSERT(PROTO == IPPROTO_SCTP);
22671 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22672 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22673 			/*
22674 			 * Zero out the checksum field to ensure proper
22675 			 * checksum calculation.
22676 			 */
22677 			sctph->sh_chksum = 0;
22678 #ifdef	DEBUG
22679 			if (!skip_sctp_cksum)
22680 #endif
22681 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22682 		}
22683 	}
22684 
22685 	/*
22686 	 * If this is a multicast packet and originated from ip_wput
22687 	 * we need to do loopback and forwarding checks. If it comes
22688 	 * from ip_wput_multicast, we SHOULD not do this.
22689 	 */
22690 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22691 
22692 	/* checksum */
22693 	cksum += ttl_protocol;
22694 
22695 	/* fragment the packet */
22696 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22697 		goto fragmentit;
22698 	/*
22699 	 * Don't use frag_flag if packet is pre-built or source
22700 	 * routed or if multicast (since multicast packets do
22701 	 * not solicit ICMP "packet too big" messages).
22702 	 */
22703 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22704 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22705 	    !ip_source_route_included(ipha)) &&
22706 	    !CLASSD(ipha->ipha_dst))
22707 		ipha->ipha_fragment_offset_and_flags |=
22708 		    htons(ire->ire_frag_flag);
22709 
22710 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22711 		/* calculate IP header checksum */
22712 		cksum += ipha->ipha_ident;
22713 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22714 		cksum += ipha->ipha_fragment_offset_and_flags;
22715 
22716 		/* IP options present */
22717 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22718 		if (hlen)
22719 			goto checksumoptions;
22720 
22721 		/* calculate hdr checksum */
22722 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22723 		cksum = ~(cksum + (cksum >> 16));
22724 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22725 	}
22726 	if (ipsec_len != 0) {
22727 		/*
22728 		 * We will do the rest of the processing after
22729 		 * we come back from IPSEC in ip_wput_ipsec_out().
22730 		 */
22731 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22732 
22733 		io = (ipsec_out_t *)first_mp->b_rptr;
22734 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22735 		    ill_phyint->phyint_ifindex;
22736 
22737 		ipsec_out_process(q, first_mp, ire, ill_index);
22738 		ire_refrele(ire);
22739 		if (conn_outgoing_ill != NULL)
22740 			ill_refrele(conn_outgoing_ill);
22741 		return;
22742 	}
22743 
22744 	/*
22745 	 * In most cases, the emission loop below is entered only
22746 	 * once. Only in the case where the ire holds the
22747 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22748 	 * flagged ires in the bucket, and send the packet
22749 	 * through all crossed RTF_MULTIRT routes.
22750 	 */
22751 	if (ire->ire_flags & RTF_MULTIRT) {
22752 		multirt_send = B_TRUE;
22753 	}
22754 	do {
22755 		if (multirt_send) {
22756 			irb_t *irb;
22757 			/*
22758 			 * We are in a multiple send case, need to get
22759 			 * the next ire and make a duplicate of the packet.
22760 			 * ire1 holds here the next ire to process in the
22761 			 * bucket. If multirouting is expected,
22762 			 * any non-RTF_MULTIRT ire that has the
22763 			 * right destination address is ignored.
22764 			 */
22765 			irb = ire->ire_bucket;
22766 			ASSERT(irb != NULL);
22767 
22768 			IRB_REFHOLD(irb);
22769 			for (ire1 = ire->ire_next;
22770 			    ire1 != NULL;
22771 			    ire1 = ire1->ire_next) {
22772 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22773 					continue;
22774 				if (ire1->ire_addr != ire->ire_addr)
22775 					continue;
22776 				if (ire1->ire_marks &
22777 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22778 					continue;
22779 
22780 				/* Got one */
22781 				IRE_REFHOLD(ire1);
22782 				break;
22783 			}
22784 			IRB_REFRELE(irb);
22785 
22786 			if (ire1 != NULL) {
22787 				next_mp = copyb(mp);
22788 				if ((next_mp == NULL) ||
22789 				    ((mp->b_cont != NULL) &&
22790 				    ((next_mp->b_cont =
22791 				    dupmsg(mp->b_cont)) == NULL))) {
22792 					freemsg(next_mp);
22793 					next_mp = NULL;
22794 					ire_refrele(ire1);
22795 					ire1 = NULL;
22796 				}
22797 			}
22798 
22799 			/* Last multiroute ire; don't loop anymore. */
22800 			if (ire1 == NULL) {
22801 				multirt_send = B_FALSE;
22802 			}
22803 		}
22804 
22805 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22806 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22807 		    mblk_t *, mp);
22808 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22809 		    ipst->ips_ipv4firewall_physical_out,
22810 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22811 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22812 		if (mp == NULL)
22813 			goto release_ire_and_ill;
22814 
22815 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22816 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22817 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22818 		if ((pktxmit_state == SEND_FAILED) ||
22819 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22820 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22821 			    "- packet dropped\n"));
22822 release_ire_and_ill:
22823 			ire_refrele(ire);
22824 			if (next_mp != NULL) {
22825 				freemsg(next_mp);
22826 				ire_refrele(ire1);
22827 			}
22828 			if (conn_outgoing_ill != NULL)
22829 				ill_refrele(conn_outgoing_ill);
22830 			return;
22831 		}
22832 
22833 		if (CLASSD(dst)) {
22834 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22835 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22836 			    LENGTH);
22837 		}
22838 
22839 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22840 		    "ip_wput_ire_end: q %p (%S)",
22841 		    q, "last copy out");
22842 		IRE_REFRELE(ire);
22843 
22844 		if (multirt_send) {
22845 			ASSERT(ire1);
22846 			/*
22847 			 * Proceed with the next RTF_MULTIRT ire,
22848 			 * Also set up the send-to queue accordingly.
22849 			 */
22850 			ire = ire1;
22851 			ire1 = NULL;
22852 			stq = ire->ire_stq;
22853 			mp = next_mp;
22854 			next_mp = NULL;
22855 			ipha = (ipha_t *)mp->b_rptr;
22856 			ill_index = Q_TO_INDEX(stq);
22857 			ill = (ill_t *)stq->q_ptr;
22858 		}
22859 	} while (multirt_send);
22860 	if (conn_outgoing_ill != NULL)
22861 		ill_refrele(conn_outgoing_ill);
22862 	return;
22863 
22864 	/*
22865 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22866 	 */
22867 broadcast:
22868 	{
22869 		/*
22870 		 * Avoid broadcast storms by setting the ttl to 1
22871 		 * for broadcasts. This parameter can be set
22872 		 * via ndd, so make sure that for the SO_DONTROUTE
22873 		 * case that ipha_ttl is always set to 1.
22874 		 * In the event that we are replying to incoming
22875 		 * ICMP packets, conn could be NULL.
22876 		 */
22877 		if ((connp != NULL) && connp->conn_dontroute)
22878 			ipha->ipha_ttl = 1;
22879 		else
22880 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22881 
22882 		/*
22883 		 * Note that we are not doing a IRB_REFHOLD here.
22884 		 * Actually we don't care if the list changes i.e
22885 		 * if somebody deletes an IRE from the list while
22886 		 * we drop the lock, the next time we come around
22887 		 * ire_next will be NULL and hence we won't send
22888 		 * out multiple copies which is fine.
22889 		 */
22890 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22891 		ire1 = ire->ire_next;
22892 		if (conn_outgoing_ill != NULL) {
22893 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22894 				ASSERT(ire1 == ire->ire_next);
22895 				if (ire1 != NULL && ire1->ire_addr == dst) {
22896 					ire_refrele(ire);
22897 					ire = ire1;
22898 					IRE_REFHOLD(ire);
22899 					ire1 = ire->ire_next;
22900 					continue;
22901 				}
22902 				rw_exit(&ire->ire_bucket->irb_lock);
22903 				/* Did not find a matching ill */
22904 				ip1dbg(("ip_wput_ire: broadcast with no "
22905 				    "matching IP_BOUND_IF ill %s\n",
22906 				    conn_outgoing_ill->ill_name));
22907 				freemsg(first_mp);
22908 				if (ire != NULL)
22909 					ire_refrele(ire);
22910 				ill_refrele(conn_outgoing_ill);
22911 				return;
22912 			}
22913 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22914 			/*
22915 			 * If the next IRE has the same address and is not one
22916 			 * of the two copies that we need to send, try to see
22917 			 * whether this copy should be sent at all. This
22918 			 * assumes that we insert loopbacks first and then
22919 			 * non-loopbacks. This is acheived by inserting the
22920 			 * loopback always before non-loopback.
22921 			 * This is used to send a single copy of a broadcast
22922 			 * packet out all physical interfaces that have an
22923 			 * matching IRE_BROADCAST while also looping
22924 			 * back one copy (to ip_wput_local) for each
22925 			 * matching physical interface. However, we avoid
22926 			 * sending packets out different logical that match by
22927 			 * having ipif_up/ipif_down supress duplicate
22928 			 * IRE_BROADCASTS.
22929 			 *
22930 			 * This feature is currently used to get broadcasts
22931 			 * sent to multiple interfaces, when the broadcast
22932 			 * address being used applies to multiple interfaces.
22933 			 * For example, a whole net broadcast will be
22934 			 * replicated on every connected subnet of
22935 			 * the target net.
22936 			 *
22937 			 * Each zone has its own set of IRE_BROADCASTs, so that
22938 			 * we're able to distribute inbound packets to multiple
22939 			 * zones who share a broadcast address. We avoid looping
22940 			 * back outbound packets in different zones but on the
22941 			 * same ill, as the application would see duplicates.
22942 			 *
22943 			 * If the interfaces are part of the same group,
22944 			 * we would want to send only one copy out for
22945 			 * whole group.
22946 			 *
22947 			 * This logic assumes that ire_add_v4() groups the
22948 			 * IRE_BROADCAST entries so that those with the same
22949 			 * ire_addr and ill_group are kept together.
22950 			 */
22951 			ire_ill = ire->ire_ipif->ipif_ill;
22952 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22953 				if (ire_ill->ill_group != NULL &&
22954 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22955 					/*
22956 					 * If the current zone only has an ire
22957 					 * broadcast for this address marked
22958 					 * NORECV, the ire we want is ahead in
22959 					 * the bucket, so we look it up
22960 					 * deliberately ignoring the zoneid.
22961 					 */
22962 					for (ire1 = ire->ire_bucket->irb_ire;
22963 					    ire1 != NULL;
22964 					    ire1 = ire1->ire_next) {
22965 						ire1_ill =
22966 						    ire1->ire_ipif->ipif_ill;
22967 						if (ire1->ire_addr != dst)
22968 							continue;
22969 						/* skip over the current ire */
22970 						if (ire1 == ire)
22971 							continue;
22972 						/* skip over deleted ires */
22973 						if (ire1->ire_marks &
22974 						    IRE_MARK_CONDEMNED)
22975 							continue;
22976 						/*
22977 						 * non-loopback ire in our
22978 						 * group: use it for the next
22979 						 * pass in the loop
22980 						 */
22981 						if (ire1->ire_stq != NULL &&
22982 						    ire1_ill->ill_group ==
22983 						    ire_ill->ill_group)
22984 							break;
22985 					}
22986 				}
22987 			} else {
22988 				while (ire1 != NULL && ire1->ire_addr == dst) {
22989 					ire1_ill = ire1->ire_ipif->ipif_ill;
22990 					/*
22991 					 * We can have two broadcast ires on the
22992 					 * same ill in different zones; here
22993 					 * we'll send a copy of the packet on
22994 					 * each ill and the fanout code will
22995 					 * call conn_wantpacket() to check that
22996 					 * the zone has the broadcast address
22997 					 * configured on the ill. If the two
22998 					 * ires are in the same group we only
22999 					 * send one copy up.
23000 					 */
23001 					if (ire1_ill != ire_ill &&
23002 					    (ire1_ill->ill_group == NULL ||
23003 					    ire_ill->ill_group == NULL ||
23004 					    ire1_ill->ill_group !=
23005 					    ire_ill->ill_group)) {
23006 						break;
23007 					}
23008 					ire1 = ire1->ire_next;
23009 				}
23010 			}
23011 		}
23012 		ASSERT(multirt_send == B_FALSE);
23013 		if (ire1 != NULL && ire1->ire_addr == dst) {
23014 			if ((ire->ire_flags & RTF_MULTIRT) &&
23015 			    (ire1->ire_flags & RTF_MULTIRT)) {
23016 				/*
23017 				 * We are in the multirouting case.
23018 				 * The message must be sent at least
23019 				 * on both ires. These ires have been
23020 				 * inserted AFTER the standard ones
23021 				 * in ip_rt_add(). There are thus no
23022 				 * other ire entries for the destination
23023 				 * address in the rest of the bucket
23024 				 * that do not have the RTF_MULTIRT
23025 				 * flag. We don't process a copy
23026 				 * of the message here. This will be
23027 				 * done in the final sending loop.
23028 				 */
23029 				multirt_send = B_TRUE;
23030 			} else {
23031 				next_mp = ip_copymsg(first_mp);
23032 				if (next_mp != NULL)
23033 					IRE_REFHOLD(ire1);
23034 			}
23035 		}
23036 		rw_exit(&ire->ire_bucket->irb_lock);
23037 	}
23038 
23039 	if (stq) {
23040 		/*
23041 		 * A non-NULL send-to queue means this packet is going
23042 		 * out of this machine.
23043 		 */
23044 		out_ill = (ill_t *)stq->q_ptr;
23045 
23046 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
23047 		ttl_protocol = ((uint16_t *)ipha)[4];
23048 		/*
23049 		 * We accumulate the pseudo header checksum in cksum.
23050 		 * This is pretty hairy code, so watch close.  One
23051 		 * thing to keep in mind is that UDP and TCP have
23052 		 * stored their respective datagram lengths in their
23053 		 * checksum fields.  This lines things up real nice.
23054 		 */
23055 		cksum = (dst >> 16) + (dst & 0xFFFF) +
23056 		    (src >> 16) + (src & 0xFFFF);
23057 		/*
23058 		 * We assume the udp checksum field contains the
23059 		 * length, so to compute the pseudo header checksum,
23060 		 * all we need is the protocol number and src/dst.
23061 		 */
23062 		/* Provide the checksums for UDP and TCP. */
23063 		if ((PROTO == IPPROTO_TCP) &&
23064 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23065 			/* hlen gets the number of uchar_ts in the IP header */
23066 			hlen = (V_HLEN & 0xF) << 2;
23067 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
23068 			IP_STAT(ipst, ip_out_sw_cksum);
23069 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
23070 			    LENGTH - hlen);
23071 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
23072 		} else if (PROTO == IPPROTO_SCTP &&
23073 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
23074 			sctp_hdr_t	*sctph;
23075 
23076 			hlen = (V_HLEN & 0xF) << 2;
23077 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
23078 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
23079 			sctph->sh_chksum = 0;
23080 #ifdef	DEBUG
23081 			if (!skip_sctp_cksum)
23082 #endif
23083 				sctph->sh_chksum = sctp_cksum(mp, hlen);
23084 		} else {
23085 			queue_t *dev_q = stq->q_next;
23086 
23087 			if ((dev_q->q_next || dev_q->q_first) &&
23088 			    !canput(dev_q)) {
23089 blocked:
23090 				ipha->ipha_ident = ip_hdr_included;
23091 				/*
23092 				 * If we don't have a conn to apply
23093 				 * backpressure, free the message.
23094 				 * In the ire_send path, we don't know
23095 				 * the position to requeue the packet. Rather
23096 				 * than reorder packets, we just drop this
23097 				 * packet.
23098 				 */
23099 				if (ipst->ips_ip_output_queue &&
23100 				    connp != NULL &&
23101 				    caller != IRE_SEND) {
23102 					if (caller == IP_WSRV) {
23103 						connp->conn_did_putbq = 1;
23104 						(void) putbq(connp->conn_wq,
23105 						    first_mp);
23106 						conn_drain_insert(connp);
23107 						/*
23108 						 * This is the service thread,
23109 						 * and the queue is already
23110 						 * noenabled. The check for
23111 						 * canput and the putbq is not
23112 						 * atomic. So we need to check
23113 						 * again.
23114 						 */
23115 						if (canput(stq->q_next))
23116 							connp->conn_did_putbq
23117 							    = 0;
23118 						IP_STAT(ipst, ip_conn_flputbq);
23119 					} else {
23120 						/*
23121 						 * We are not the service proc.
23122 						 * ip_wsrv will be scheduled or
23123 						 * is already running.
23124 						 */
23125 						(void) putq(connp->conn_wq,
23126 						    first_mp);
23127 					}
23128 				} else {
23129 					out_ill = (ill_t *)stq->q_ptr;
23130 					BUMP_MIB(out_ill->ill_ip_mib,
23131 					    ipIfStatsOutDiscards);
23132 					freemsg(first_mp);
23133 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23134 					    "ip_wput_ire_end: q %p (%S)",
23135 					    q, "discard");
23136 				}
23137 				ire_refrele(ire);
23138 				if (next_mp) {
23139 					ire_refrele(ire1);
23140 					freemsg(next_mp);
23141 				}
23142 				if (conn_outgoing_ill != NULL)
23143 					ill_refrele(conn_outgoing_ill);
23144 				return;
23145 			}
23146 			if ((PROTO == IPPROTO_UDP) &&
23147 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
23148 				/*
23149 				 * hlen gets the number of uchar_ts in the
23150 				 * IP header
23151 				 */
23152 				hlen = (V_HLEN & 0xF) << 2;
23153 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
23154 				max_frag = ire->ire_max_frag;
23155 				if (*up != 0) {
23156 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
23157 					    up, PROTO, hlen, LENGTH, max_frag,
23158 					    ipsec_len, cksum);
23159 					/* Software checksum? */
23160 					if (DB_CKSUMFLAGS(mp) == 0) {
23161 						IP_STAT(ipst, ip_out_sw_cksum);
23162 						IP_STAT_UPDATE(ipst,
23163 						    ip_udp_out_sw_cksum_bytes,
23164 						    LENGTH - hlen);
23165 					}
23166 				}
23167 			}
23168 		}
23169 		/*
23170 		 * Need to do this even when fragmenting. The local
23171 		 * loopback can be done without computing checksums
23172 		 * but forwarding out other interface must be done
23173 		 * after the IP checksum (and ULP checksums) have been
23174 		 * computed.
23175 		 *
23176 		 * NOTE : multicast_forward is set only if this packet
23177 		 * originated from ip_wput. For packets originating from
23178 		 * ip_wput_multicast, it is not set.
23179 		 */
23180 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23181 multi_loopback:
23182 			ip2dbg(("ip_wput: multicast, loop %d\n",
23183 			    conn_multicast_loop));
23184 
23185 			/*  Forget header checksum offload */
23186 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23187 
23188 			/*
23189 			 * Local loopback of multicasts?  Check the
23190 			 * ill.
23191 			 *
23192 			 * Note that the loopback function will not come
23193 			 * in through ip_rput - it will only do the
23194 			 * client fanout thus we need to do an mforward
23195 			 * as well.  The is different from the BSD
23196 			 * logic.
23197 			 */
23198 			if (ill != NULL) {
23199 				ilm_t	*ilm;
23200 
23201 				ILM_WALKER_HOLD(ill);
23202 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23203 				    ALL_ZONES);
23204 				ILM_WALKER_RELE(ill);
23205 				if (ilm != NULL) {
23206 					/*
23207 					 * Pass along the virtual output q.
23208 					 * ip_wput_local() will distribute the
23209 					 * packet to all the matching zones,
23210 					 * except the sending zone when
23211 					 * IP_MULTICAST_LOOP is false.
23212 					 */
23213 					ip_multicast_loopback(q, ill, first_mp,
23214 					    conn_multicast_loop ? 0 :
23215 					    IP_FF_NO_MCAST_LOOP, zoneid);
23216 				}
23217 			}
23218 			if (ipha->ipha_ttl == 0) {
23219 				/*
23220 				 * 0 => only to this host i.e. we are
23221 				 * done. We are also done if this was the
23222 				 * loopback interface since it is sufficient
23223 				 * to loopback one copy of a multicast packet.
23224 				 */
23225 				freemsg(first_mp);
23226 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23227 				    "ip_wput_ire_end: q %p (%S)",
23228 				    q, "loopback");
23229 				ire_refrele(ire);
23230 				if (conn_outgoing_ill != NULL)
23231 					ill_refrele(conn_outgoing_ill);
23232 				return;
23233 			}
23234 			/*
23235 			 * ILLF_MULTICAST is checked in ip_newroute
23236 			 * i.e. we don't need to check it here since
23237 			 * all IRE_CACHEs come from ip_newroute.
23238 			 * For multicast traffic, SO_DONTROUTE is interpreted
23239 			 * to mean only send the packet out the interface
23240 			 * (optionally specified with IP_MULTICAST_IF)
23241 			 * and do not forward it out additional interfaces.
23242 			 * RSVP and the rsvp daemon is an example of a
23243 			 * protocol and user level process that
23244 			 * handles it's own routing. Hence, it uses the
23245 			 * SO_DONTROUTE option to accomplish this.
23246 			 */
23247 
23248 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23249 			    ill != NULL) {
23250 				/* Unconditionally redo the checksum */
23251 				ipha->ipha_hdr_checksum = 0;
23252 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23253 
23254 				/*
23255 				 * If this needs to go out secure, we need
23256 				 * to wait till we finish the IPSEC
23257 				 * processing.
23258 				 */
23259 				if (ipsec_len == 0 &&
23260 				    ip_mforward(ill, ipha, mp)) {
23261 					freemsg(first_mp);
23262 					ip1dbg(("ip_wput: mforward failed\n"));
23263 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23264 					    "ip_wput_ire_end: q %p (%S)",
23265 					    q, "mforward failed");
23266 					ire_refrele(ire);
23267 					if (conn_outgoing_ill != NULL)
23268 						ill_refrele(conn_outgoing_ill);
23269 					return;
23270 				}
23271 			}
23272 		}
23273 		max_frag = ire->ire_max_frag;
23274 		cksum += ttl_protocol;
23275 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23276 			/* No fragmentation required for this one. */
23277 			/*
23278 			 * Don't use frag_flag if packet is pre-built or source
23279 			 * routed or if multicast (since multicast packets do
23280 			 * not solicit ICMP "packet too big" messages).
23281 			 */
23282 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23283 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23284 			    !ip_source_route_included(ipha)) &&
23285 			    !CLASSD(ipha->ipha_dst))
23286 				ipha->ipha_fragment_offset_and_flags |=
23287 				    htons(ire->ire_frag_flag);
23288 
23289 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23290 				/* Complete the IP header checksum. */
23291 				cksum += ipha->ipha_ident;
23292 				cksum += (v_hlen_tos_len >> 16)+
23293 				    (v_hlen_tos_len & 0xFFFF);
23294 				cksum += ipha->ipha_fragment_offset_and_flags;
23295 				hlen = (V_HLEN & 0xF) -
23296 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23297 				if (hlen) {
23298 checksumoptions:
23299 					/*
23300 					 * Account for the IP Options in the IP
23301 					 * header checksum.
23302 					 */
23303 					up = (uint16_t *)(rptr+
23304 					    IP_SIMPLE_HDR_LENGTH);
23305 					do {
23306 						cksum += up[0];
23307 						cksum += up[1];
23308 						up += 2;
23309 					} while (--hlen);
23310 				}
23311 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23312 				cksum = ~(cksum + (cksum >> 16));
23313 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23314 			}
23315 			if (ipsec_len != 0) {
23316 				ipsec_out_process(q, first_mp, ire, ill_index);
23317 				if (!next_mp) {
23318 					ire_refrele(ire);
23319 					if (conn_outgoing_ill != NULL)
23320 						ill_refrele(conn_outgoing_ill);
23321 					return;
23322 				}
23323 				goto next;
23324 			}
23325 
23326 			/*
23327 			 * multirt_send has already been handled
23328 			 * for broadcast, but not yet for multicast
23329 			 * or IP options.
23330 			 */
23331 			if (next_mp == NULL) {
23332 				if (ire->ire_flags & RTF_MULTIRT) {
23333 					multirt_send = B_TRUE;
23334 				}
23335 			}
23336 
23337 			/*
23338 			 * In most cases, the emission loop below is
23339 			 * entered only once. Only in the case where
23340 			 * the ire holds the RTF_MULTIRT flag, do we loop
23341 			 * to process all RTF_MULTIRT ires in the bucket,
23342 			 * and send the packet through all crossed
23343 			 * RTF_MULTIRT routes.
23344 			 */
23345 			do {
23346 				if (multirt_send) {
23347 					irb_t *irb;
23348 
23349 					irb = ire->ire_bucket;
23350 					ASSERT(irb != NULL);
23351 					/*
23352 					 * We are in a multiple send case,
23353 					 * need to get the next IRE and make
23354 					 * a duplicate of the packet.
23355 					 */
23356 					IRB_REFHOLD(irb);
23357 					for (ire1 = ire->ire_next;
23358 					    ire1 != NULL;
23359 					    ire1 = ire1->ire_next) {
23360 						if (!(ire1->ire_flags &
23361 						    RTF_MULTIRT)) {
23362 							continue;
23363 						}
23364 						if (ire1->ire_addr !=
23365 						    ire->ire_addr) {
23366 							continue;
23367 						}
23368 						if (ire1->ire_marks &
23369 						    (IRE_MARK_CONDEMNED|
23370 						    IRE_MARK_HIDDEN)) {
23371 							continue;
23372 						}
23373 
23374 						/* Got one */
23375 						IRE_REFHOLD(ire1);
23376 						break;
23377 					}
23378 					IRB_REFRELE(irb);
23379 
23380 					if (ire1 != NULL) {
23381 						next_mp = copyb(mp);
23382 						if ((next_mp == NULL) ||
23383 						    ((mp->b_cont != NULL) &&
23384 						    ((next_mp->b_cont =
23385 						    dupmsg(mp->b_cont))
23386 						    == NULL))) {
23387 							freemsg(next_mp);
23388 							next_mp = NULL;
23389 							ire_refrele(ire1);
23390 							ire1 = NULL;
23391 						}
23392 					}
23393 
23394 					/*
23395 					 * Last multiroute ire; don't loop
23396 					 * anymore. The emission is over
23397 					 * and next_mp is NULL.
23398 					 */
23399 					if (ire1 == NULL) {
23400 						multirt_send = B_FALSE;
23401 					}
23402 				}
23403 
23404 				out_ill = ire->ire_ipif->ipif_ill;
23405 				DTRACE_PROBE4(ip4__physical__out__start,
23406 				    ill_t *, NULL,
23407 				    ill_t *, out_ill,
23408 				    ipha_t *, ipha, mblk_t *, mp);
23409 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23410 				    ipst->ips_ipv4firewall_physical_out,
23411 				    NULL, out_ill, ipha, mp, mp, ipst);
23412 				DTRACE_PROBE1(ip4__physical__out__end,
23413 				    mblk_t *, mp);
23414 				if (mp == NULL)
23415 					goto release_ire_and_ill_2;
23416 
23417 				ASSERT(ipsec_len == 0);
23418 				mp->b_prev =
23419 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23420 				DTRACE_PROBE2(ip__xmit__2,
23421 				    mblk_t *, mp, ire_t *, ire);
23422 				pktxmit_state = ip_xmit_v4(mp, ire,
23423 				    NULL, B_TRUE);
23424 				if ((pktxmit_state == SEND_FAILED) ||
23425 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23426 release_ire_and_ill_2:
23427 					if (next_mp) {
23428 						freemsg(next_mp);
23429 						ire_refrele(ire1);
23430 					}
23431 					ire_refrele(ire);
23432 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23433 					    "ip_wput_ire_end: q %p (%S)",
23434 					    q, "discard MDATA");
23435 					if (conn_outgoing_ill != NULL)
23436 						ill_refrele(conn_outgoing_ill);
23437 					return;
23438 				}
23439 
23440 				if (CLASSD(dst)) {
23441 					BUMP_MIB(out_ill->ill_ip_mib,
23442 					    ipIfStatsHCOutMcastPkts);
23443 					UPDATE_MIB(out_ill->ill_ip_mib,
23444 					    ipIfStatsHCOutMcastOctets,
23445 					    LENGTH);
23446 				} else if (ire->ire_type == IRE_BROADCAST) {
23447 					BUMP_MIB(out_ill->ill_ip_mib,
23448 					    ipIfStatsHCOutBcastPkts);
23449 				}
23450 
23451 				if (multirt_send) {
23452 					/*
23453 					 * We are in a multiple send case,
23454 					 * need to re-enter the sending loop
23455 					 * using the next ire.
23456 					 */
23457 					ire_refrele(ire);
23458 					ire = ire1;
23459 					stq = ire->ire_stq;
23460 					mp = next_mp;
23461 					next_mp = NULL;
23462 					ipha = (ipha_t *)mp->b_rptr;
23463 					ill_index = Q_TO_INDEX(stq);
23464 				}
23465 			} while (multirt_send);
23466 
23467 			if (!next_mp) {
23468 				/*
23469 				 * Last copy going out (the ultra-common
23470 				 * case).  Note that we intentionally replicate
23471 				 * the putnext rather than calling it before
23472 				 * the next_mp check in hopes of a little
23473 				 * tail-call action out of the compiler.
23474 				 */
23475 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23476 				    "ip_wput_ire_end: q %p (%S)",
23477 				    q, "last copy out(1)");
23478 				ire_refrele(ire);
23479 				if (conn_outgoing_ill != NULL)
23480 					ill_refrele(conn_outgoing_ill);
23481 				return;
23482 			}
23483 			/* More copies going out below. */
23484 		} else {
23485 			int offset;
23486 fragmentit:
23487 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23488 			/*
23489 			 * If this would generate a icmp_frag_needed message,
23490 			 * we need to handle it before we do the IPSEC
23491 			 * processing. Otherwise, we need to strip the IPSEC
23492 			 * headers before we send up the message to the ULPs
23493 			 * which becomes messy and difficult.
23494 			 */
23495 			if (ipsec_len != 0) {
23496 				if ((max_frag < (unsigned int)(LENGTH +
23497 				    ipsec_len)) && (offset & IPH_DF)) {
23498 					out_ill = (ill_t *)stq->q_ptr;
23499 					BUMP_MIB(out_ill->ill_ip_mib,
23500 					    ipIfStatsOutFragFails);
23501 					BUMP_MIB(out_ill->ill_ip_mib,
23502 					    ipIfStatsOutFragReqds);
23503 					ipha->ipha_hdr_checksum = 0;
23504 					ipha->ipha_hdr_checksum =
23505 					    (uint16_t)ip_csum_hdr(ipha);
23506 					icmp_frag_needed(ire->ire_stq, first_mp,
23507 					    max_frag, zoneid, ipst);
23508 					if (!next_mp) {
23509 						ire_refrele(ire);
23510 						if (conn_outgoing_ill != NULL) {
23511 							ill_refrele(
23512 							    conn_outgoing_ill);
23513 						}
23514 						return;
23515 					}
23516 				} else {
23517 					/*
23518 					 * This won't cause a icmp_frag_needed
23519 					 * message. to be generated. Send it on
23520 					 * the wire. Note that this could still
23521 					 * cause fragmentation and all we
23522 					 * do is the generation of the message
23523 					 * to the ULP if needed before IPSEC.
23524 					 */
23525 					if (!next_mp) {
23526 						ipsec_out_process(q, first_mp,
23527 						    ire, ill_index);
23528 						TRACE_2(TR_FAC_IP,
23529 						    TR_IP_WPUT_IRE_END,
23530 						    "ip_wput_ire_end: q %p "
23531 						    "(%S)", q,
23532 						    "last ipsec_out_process");
23533 						ire_refrele(ire);
23534 						if (conn_outgoing_ill != NULL) {
23535 							ill_refrele(
23536 							    conn_outgoing_ill);
23537 						}
23538 						return;
23539 					}
23540 					ipsec_out_process(q, first_mp,
23541 					    ire, ill_index);
23542 				}
23543 			} else {
23544 				/*
23545 				 * Initiate IPPF processing. For
23546 				 * fragmentable packets we finish
23547 				 * all QOS packet processing before
23548 				 * calling:
23549 				 * ip_wput_ire_fragmentit->ip_wput_frag
23550 				 */
23551 
23552 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23553 					ip_process(IPP_LOCAL_OUT, &mp,
23554 					    ill_index);
23555 					if (mp == NULL) {
23556 						out_ill = (ill_t *)stq->q_ptr;
23557 						BUMP_MIB(out_ill->ill_ip_mib,
23558 						    ipIfStatsOutDiscards);
23559 						if (next_mp != NULL) {
23560 							freemsg(next_mp);
23561 							ire_refrele(ire1);
23562 						}
23563 						ire_refrele(ire);
23564 						TRACE_2(TR_FAC_IP,
23565 						    TR_IP_WPUT_IRE_END,
23566 						    "ip_wput_ire: q %p (%S)",
23567 						    q, "discard MDATA");
23568 						if (conn_outgoing_ill != NULL) {
23569 							ill_refrele(
23570 							    conn_outgoing_ill);
23571 						}
23572 						return;
23573 					}
23574 				}
23575 				if (!next_mp) {
23576 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23577 					    "ip_wput_ire_end: q %p (%S)",
23578 					    q, "last fragmentation");
23579 					ip_wput_ire_fragmentit(mp, ire,
23580 					    zoneid, ipst);
23581 					ire_refrele(ire);
23582 					if (conn_outgoing_ill != NULL)
23583 						ill_refrele(conn_outgoing_ill);
23584 					return;
23585 				}
23586 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23587 			}
23588 		}
23589 	} else {
23590 nullstq:
23591 		/* A NULL stq means the destination address is local. */
23592 		UPDATE_OB_PKT_COUNT(ire);
23593 		ire->ire_last_used_time = lbolt;
23594 		ASSERT(ire->ire_ipif != NULL);
23595 		if (!next_mp) {
23596 			/*
23597 			 * Is there an "in" and "out" for traffic local
23598 			 * to a host (loopback)?  The code in Solaris doesn't
23599 			 * explicitly draw a line in its code for in vs out,
23600 			 * so we've had to draw a line in the sand: ip_wput_ire
23601 			 * is considered to be the "output" side and
23602 			 * ip_wput_local to be the "input" side.
23603 			 */
23604 			out_ill = ire->ire_ipif->ipif_ill;
23605 
23606 			DTRACE_PROBE4(ip4__loopback__out__start,
23607 			    ill_t *, NULL, ill_t *, out_ill,
23608 			    ipha_t *, ipha, mblk_t *, first_mp);
23609 
23610 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23611 			    ipst->ips_ipv4firewall_loopback_out,
23612 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23613 
23614 			DTRACE_PROBE1(ip4__loopback__out_end,
23615 			    mblk_t *, first_mp);
23616 
23617 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23618 			    "ip_wput_ire_end: q %p (%S)",
23619 			    q, "local address");
23620 
23621 			if (first_mp != NULL)
23622 				ip_wput_local(q, out_ill, ipha,
23623 				    first_mp, ire, 0, ire->ire_zoneid);
23624 			ire_refrele(ire);
23625 			if (conn_outgoing_ill != NULL)
23626 				ill_refrele(conn_outgoing_ill);
23627 			return;
23628 		}
23629 
23630 		out_ill = ire->ire_ipif->ipif_ill;
23631 
23632 		DTRACE_PROBE4(ip4__loopback__out__start,
23633 		    ill_t *, NULL, ill_t *, out_ill,
23634 		    ipha_t *, ipha, mblk_t *, first_mp);
23635 
23636 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23637 		    ipst->ips_ipv4firewall_loopback_out,
23638 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23639 
23640 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23641 
23642 		if (first_mp != NULL)
23643 			ip_wput_local(q, out_ill, ipha,
23644 			    first_mp, ire, 0, ire->ire_zoneid);
23645 	}
23646 next:
23647 	/*
23648 	 * More copies going out to additional interfaces.
23649 	 * ire1 has already been held. We don't need the
23650 	 * "ire" anymore.
23651 	 */
23652 	ire_refrele(ire);
23653 	ire = ire1;
23654 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23655 	mp = next_mp;
23656 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23657 	ill = ire_to_ill(ire);
23658 	first_mp = mp;
23659 	if (ipsec_len != 0) {
23660 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23661 		mp = mp->b_cont;
23662 	}
23663 	dst = ire->ire_addr;
23664 	ipha = (ipha_t *)mp->b_rptr;
23665 	/*
23666 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23667 	 * Restore ipha_ident "no checksum" flag.
23668 	 */
23669 	src = orig_src;
23670 	ipha->ipha_ident = ip_hdr_included;
23671 	goto another;
23672 
23673 #undef	rptr
23674 #undef	Q_TO_INDEX
23675 }
23676 
23677 /*
23678  * Routine to allocate a message that is used to notify the ULP about MDT.
23679  * The caller may provide a pointer to the link-layer MDT capabilities,
23680  * or NULL if MDT is to be disabled on the stream.
23681  */
23682 mblk_t *
23683 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23684 {
23685 	mblk_t *mp;
23686 	ip_mdt_info_t *mdti;
23687 	ill_mdt_capab_t *idst;
23688 
23689 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23690 		DB_TYPE(mp) = M_CTL;
23691 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23692 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23693 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23694 		idst = &(mdti->mdt_capab);
23695 
23696 		/*
23697 		 * If the caller provides us with the capability, copy
23698 		 * it over into our notification message; otherwise
23699 		 * we zero out the capability portion.
23700 		 */
23701 		if (isrc != NULL)
23702 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23703 		else
23704 			bzero((caddr_t)idst, sizeof (*idst));
23705 	}
23706 	return (mp);
23707 }
23708 
23709 /*
23710  * Routine which determines whether MDT can be enabled on the destination
23711  * IRE and IPC combination, and if so, allocates and returns the MDT
23712  * notification mblk that may be used by ULP.  We also check if we need to
23713  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23714  * MDT usage in the past have been lifted.  This gets called during IP
23715  * and ULP binding.
23716  */
23717 mblk_t *
23718 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23719     ill_mdt_capab_t *mdt_cap)
23720 {
23721 	mblk_t *mp;
23722 	boolean_t rc = B_FALSE;
23723 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23724 
23725 	ASSERT(dst_ire != NULL);
23726 	ASSERT(connp != NULL);
23727 	ASSERT(mdt_cap != NULL);
23728 
23729 	/*
23730 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23731 	 * Multidata, which is handled in tcp_multisend().  This
23732 	 * is the reason why we do all these checks here, to ensure
23733 	 * that we don't enable Multidata for the cases which we
23734 	 * can't handle at the moment.
23735 	 */
23736 	do {
23737 		/* Only do TCP at the moment */
23738 		if (connp->conn_ulp != IPPROTO_TCP)
23739 			break;
23740 
23741 		/*
23742 		 * IPSEC outbound policy present?  Note that we get here
23743 		 * after calling ipsec_conn_cache_policy() where the global
23744 		 * policy checking is performed.  conn_latch will be
23745 		 * non-NULL as long as there's a policy defined,
23746 		 * i.e. conn_out_enforce_policy may be NULL in such case
23747 		 * when the connection is non-secure, and hence we check
23748 		 * further if the latch refers to an outbound policy.
23749 		 */
23750 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23751 			break;
23752 
23753 		/* CGTP (multiroute) is enabled? */
23754 		if (dst_ire->ire_flags & RTF_MULTIRT)
23755 			break;
23756 
23757 		/* Outbound IPQoS enabled? */
23758 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23759 			/*
23760 			 * In this case, we disable MDT for this and all
23761 			 * future connections going over the interface.
23762 			 */
23763 			mdt_cap->ill_mdt_on = 0;
23764 			break;
23765 		}
23766 
23767 		/* socket option(s) present? */
23768 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23769 			break;
23770 
23771 		rc = B_TRUE;
23772 	/* CONSTCOND */
23773 	} while (0);
23774 
23775 	/* Remember the result */
23776 	connp->conn_mdt_ok = rc;
23777 
23778 	if (!rc)
23779 		return (NULL);
23780 	else if (!mdt_cap->ill_mdt_on) {
23781 		/*
23782 		 * If MDT has been previously turned off in the past, and we
23783 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23784 		 * then enable it for this interface.
23785 		 */
23786 		mdt_cap->ill_mdt_on = 1;
23787 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23788 		    "interface %s\n", ill_name));
23789 	}
23790 
23791 	/* Allocate the MDT info mblk */
23792 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23793 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23794 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23795 		return (NULL);
23796 	}
23797 	return (mp);
23798 }
23799 
23800 /*
23801  * Routine to allocate a message that is used to notify the ULP about LSO.
23802  * The caller may provide a pointer to the link-layer LSO capabilities,
23803  * or NULL if LSO is to be disabled on the stream.
23804  */
23805 mblk_t *
23806 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23807 {
23808 	mblk_t *mp;
23809 	ip_lso_info_t *lsoi;
23810 	ill_lso_capab_t *idst;
23811 
23812 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23813 		DB_TYPE(mp) = M_CTL;
23814 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23815 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23816 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23817 		idst = &(lsoi->lso_capab);
23818 
23819 		/*
23820 		 * If the caller provides us with the capability, copy
23821 		 * it over into our notification message; otherwise
23822 		 * we zero out the capability portion.
23823 		 */
23824 		if (isrc != NULL)
23825 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23826 		else
23827 			bzero((caddr_t)idst, sizeof (*idst));
23828 	}
23829 	return (mp);
23830 }
23831 
23832 /*
23833  * Routine which determines whether LSO can be enabled on the destination
23834  * IRE and IPC combination, and if so, allocates and returns the LSO
23835  * notification mblk that may be used by ULP.  We also check if we need to
23836  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23837  * LSO usage in the past have been lifted.  This gets called during IP
23838  * and ULP binding.
23839  */
23840 mblk_t *
23841 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23842     ill_lso_capab_t *lso_cap)
23843 {
23844 	mblk_t *mp;
23845 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23846 
23847 	ASSERT(dst_ire != NULL);
23848 	ASSERT(connp != NULL);
23849 	ASSERT(lso_cap != NULL);
23850 
23851 	connp->conn_lso_ok = B_TRUE;
23852 
23853 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23854 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23855 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23856 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23857 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23858 		connp->conn_lso_ok = B_FALSE;
23859 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23860 			/*
23861 			 * Disable LSO for this and all future connections going
23862 			 * over the interface.
23863 			 */
23864 			lso_cap->ill_lso_on = 0;
23865 		}
23866 	}
23867 
23868 	if (!connp->conn_lso_ok)
23869 		return (NULL);
23870 	else if (!lso_cap->ill_lso_on) {
23871 		/*
23872 		 * If LSO has been previously turned off in the past, and we
23873 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23874 		 * then enable it for this interface.
23875 		 */
23876 		lso_cap->ill_lso_on = 1;
23877 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23878 		    ill_name));
23879 	}
23880 
23881 	/* Allocate the LSO info mblk */
23882 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23883 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23884 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23885 
23886 	return (mp);
23887 }
23888 
23889 /*
23890  * Create destination address attribute, and fill it with the physical
23891  * destination address and SAP taken from the template DL_UNITDATA_REQ
23892  * message block.
23893  */
23894 boolean_t
23895 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23896 {
23897 	dl_unitdata_req_t *dlurp;
23898 	pattr_t *pa;
23899 	pattrinfo_t pa_info;
23900 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23901 	uint_t das_len, das_off;
23902 
23903 	ASSERT(dlmp != NULL);
23904 
23905 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23906 	das_len = dlurp->dl_dest_addr_length;
23907 	das_off = dlurp->dl_dest_addr_offset;
23908 
23909 	pa_info.type = PATTR_DSTADDRSAP;
23910 	pa_info.len = sizeof (**das) + das_len - 1;
23911 
23912 	/* create and associate the attribute */
23913 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23914 	if (pa != NULL) {
23915 		ASSERT(*das != NULL);
23916 		(*das)->addr_is_group = 0;
23917 		(*das)->addr_len = (uint8_t)das_len;
23918 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23919 	}
23920 
23921 	return (pa != NULL);
23922 }
23923 
23924 /*
23925  * Create hardware checksum attribute and fill it with the values passed.
23926  */
23927 boolean_t
23928 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23929     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23930 {
23931 	pattr_t *pa;
23932 	pattrinfo_t pa_info;
23933 
23934 	ASSERT(mmd != NULL);
23935 
23936 	pa_info.type = PATTR_HCKSUM;
23937 	pa_info.len = sizeof (pattr_hcksum_t);
23938 
23939 	/* create and associate the attribute */
23940 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23941 	if (pa != NULL) {
23942 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23943 
23944 		hck->hcksum_start_offset = start_offset;
23945 		hck->hcksum_stuff_offset = stuff_offset;
23946 		hck->hcksum_end_offset = end_offset;
23947 		hck->hcksum_flags = flags;
23948 	}
23949 	return (pa != NULL);
23950 }
23951 
23952 /*
23953  * Create zerocopy attribute and fill it with the specified flags
23954  */
23955 boolean_t
23956 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23957 {
23958 	pattr_t *pa;
23959 	pattrinfo_t pa_info;
23960 
23961 	ASSERT(mmd != NULL);
23962 	pa_info.type = PATTR_ZCOPY;
23963 	pa_info.len = sizeof (pattr_zcopy_t);
23964 
23965 	/* create and associate the attribute */
23966 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23967 	if (pa != NULL) {
23968 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23969 
23970 		zcopy->zcopy_flags = flags;
23971 	}
23972 	return (pa != NULL);
23973 }
23974 
23975 /*
23976  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23977  * block chain. We could rewrite to handle arbitrary message block chains but
23978  * that would make the code complicated and slow. Right now there three
23979  * restrictions:
23980  *
23981  *   1. The first message block must contain the complete IP header and
23982  *	at least 1 byte of payload data.
23983  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23984  *	so that we can use a single Multidata message.
23985  *   3. No frag must be distributed over two or more message blocks so
23986  *	that we don't need more than two packet descriptors per frag.
23987  *
23988  * The above restrictions allow us to support userland applications (which
23989  * will send down a single message block) and NFS over UDP (which will
23990  * send down a chain of at most three message blocks).
23991  *
23992  * We also don't use MDT for payloads with less than or equal to
23993  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23994  */
23995 boolean_t
23996 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23997 {
23998 	int	blocks;
23999 	ssize_t	total, missing, size;
24000 
24001 	ASSERT(mp != NULL);
24002 	ASSERT(hdr_len > 0);
24003 
24004 	size = MBLKL(mp) - hdr_len;
24005 	if (size <= 0)
24006 		return (B_FALSE);
24007 
24008 	/* The first mblk contains the header and some payload. */
24009 	blocks = 1;
24010 	total = size;
24011 	size %= len;
24012 	missing = (size == 0) ? 0 : (len - size);
24013 	mp = mp->b_cont;
24014 
24015 	while (mp != NULL) {
24016 		/*
24017 		 * Give up if we encounter a zero length message block.
24018 		 * In practice, this should rarely happen and therefore
24019 		 * not worth the trouble of freeing and re-linking the
24020 		 * mblk from the chain to handle such case.
24021 		 */
24022 		if ((size = MBLKL(mp)) == 0)
24023 			return (B_FALSE);
24024 
24025 		/* Too many payload buffers for a single Multidata message? */
24026 		if (++blocks > MULTIDATA_MAX_PBUFS)
24027 			return (B_FALSE);
24028 
24029 		total += size;
24030 		/* Is a frag distributed over two or more message blocks? */
24031 		if (missing > size)
24032 			return (B_FALSE);
24033 		size -= missing;
24034 
24035 		size %= len;
24036 		missing = (size == 0) ? 0 : (len - size);
24037 
24038 		mp = mp->b_cont;
24039 	}
24040 
24041 	return (total > ip_wput_frag_mdt_min);
24042 }
24043 
24044 /*
24045  * Outbound IPv4 fragmentation routine using MDT.
24046  */
24047 static void
24048 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
24049     uint32_t frag_flag, int offset)
24050 {
24051 	ipha_t		*ipha_orig;
24052 	int		i1, ip_data_end;
24053 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
24054 	mblk_t		*hdr_mp, *md_mp = NULL;
24055 	unsigned char	*hdr_ptr, *pld_ptr;
24056 	multidata_t	*mmd;
24057 	ip_pdescinfo_t	pdi;
24058 	ill_t		*ill;
24059 	ip_stack_t	*ipst = ire->ire_ipst;
24060 
24061 	ASSERT(DB_TYPE(mp) == M_DATA);
24062 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
24063 
24064 	ill = ire_to_ill(ire);
24065 	ASSERT(ill != NULL);
24066 
24067 	ipha_orig = (ipha_t *)mp->b_rptr;
24068 	mp->b_rptr += sizeof (ipha_t);
24069 
24070 	/* Calculate how many packets we will send out */
24071 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
24072 	pkts = (i1 + len - 1) / len;
24073 	ASSERT(pkts > 1);
24074 
24075 	/* Allocate a message block which will hold all the IP Headers. */
24076 	wroff = ipst->ips_ip_wroff_extra;
24077 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
24078 
24079 	i1 = pkts * hdr_chunk_len;
24080 	/*
24081 	 * Create the header buffer, Multidata and destination address
24082 	 * and SAP attribute that should be associated with it.
24083 	 */
24084 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
24085 	    ((hdr_mp->b_wptr += i1),
24086 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
24087 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
24088 		freemsg(mp);
24089 		if (md_mp == NULL) {
24090 			freemsg(hdr_mp);
24091 		} else {
24092 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
24093 			freemsg(md_mp);
24094 		}
24095 		IP_STAT(ipst, ip_frag_mdt_allocfail);
24096 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
24097 		return;
24098 	}
24099 	IP_STAT(ipst, ip_frag_mdt_allocd);
24100 
24101 	/*
24102 	 * Add a payload buffer to the Multidata; this operation must not
24103 	 * fail, or otherwise our logic in this routine is broken.  There
24104 	 * is no memory allocation done by the routine, so any returned
24105 	 * failure simply tells us that we've done something wrong.
24106 	 *
24107 	 * A failure tells us that either we're adding the same payload
24108 	 * buffer more than once, or we're trying to add more buffers than
24109 	 * allowed.  None of the above cases should happen, and we panic
24110 	 * because either there's horrible heap corruption, and/or
24111 	 * programming mistake.
24112 	 */
24113 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24114 		goto pbuf_panic;
24115 
24116 	hdr_ptr = hdr_mp->b_rptr;
24117 	pld_ptr = mp->b_rptr;
24118 
24119 	/* Establish the ending byte offset, based on the starting offset. */
24120 	offset <<= 3;
24121 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
24122 	    IP_SIMPLE_HDR_LENGTH;
24123 
24124 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
24125 
24126 	while (pld_ptr < mp->b_wptr) {
24127 		ipha_t		*ipha;
24128 		uint16_t	offset_and_flags;
24129 		uint16_t	ip_len;
24130 		int		error;
24131 
24132 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
24133 		ipha = (ipha_t *)(hdr_ptr + wroff);
24134 		ASSERT(OK_32PTR(ipha));
24135 		*ipha = *ipha_orig;
24136 
24137 		if (ip_data_end - offset > len) {
24138 			offset_and_flags = IPH_MF;
24139 		} else {
24140 			/*
24141 			 * Last frag. Set len to the length of this last piece.
24142 			 */
24143 			len = ip_data_end - offset;
24144 			/* A frag of a frag might have IPH_MF non-zero */
24145 			offset_and_flags =
24146 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24147 			    IPH_MF;
24148 		}
24149 		offset_and_flags |= (uint16_t)(offset >> 3);
24150 		offset_and_flags |= (uint16_t)frag_flag;
24151 		/* Store the offset and flags in the IP header. */
24152 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24153 
24154 		/* Store the length in the IP header. */
24155 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
24156 		ipha->ipha_length = htons(ip_len);
24157 
24158 		/*
24159 		 * Set the IP header checksum.  Note that mp is just
24160 		 * the header, so this is easy to pass to ip_csum.
24161 		 */
24162 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24163 
24164 		/*
24165 		 * Record offset and size of header and data of the next packet
24166 		 * in the multidata message.
24167 		 */
24168 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24169 		PDESC_PLD_INIT(&pdi);
24170 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24171 		ASSERT(i1 > 0);
24172 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24173 		if (i1 == len) {
24174 			pld_ptr += len;
24175 		} else {
24176 			i1 = len - i1;
24177 			mp = mp->b_cont;
24178 			ASSERT(mp != NULL);
24179 			ASSERT(MBLKL(mp) >= i1);
24180 			/*
24181 			 * Attach the next payload message block to the
24182 			 * multidata message.
24183 			 */
24184 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24185 				goto pbuf_panic;
24186 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24187 			pld_ptr = mp->b_rptr + i1;
24188 		}
24189 
24190 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24191 		    KM_NOSLEEP)) == NULL) {
24192 			/*
24193 			 * Any failure other than ENOMEM indicates that we
24194 			 * have passed in invalid pdesc info or parameters
24195 			 * to mmd_addpdesc, which must not happen.
24196 			 *
24197 			 * EINVAL is a result of failure on boundary checks
24198 			 * against the pdesc info contents.  It should not
24199 			 * happen, and we panic because either there's
24200 			 * horrible heap corruption, and/or programming
24201 			 * mistake.
24202 			 */
24203 			if (error != ENOMEM) {
24204 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24205 				    "pdesc logic error detected for "
24206 				    "mmd %p pinfo %p (%d)\n",
24207 				    (void *)mmd, (void *)&pdi, error);
24208 				/* NOTREACHED */
24209 			}
24210 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24211 			/* Free unattached payload message blocks as well */
24212 			md_mp->b_cont = mp->b_cont;
24213 			goto free_mmd;
24214 		}
24215 
24216 		/* Advance fragment offset. */
24217 		offset += len;
24218 
24219 		/* Advance to location for next header in the buffer. */
24220 		hdr_ptr += hdr_chunk_len;
24221 
24222 		/* Did we reach the next payload message block? */
24223 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24224 			mp = mp->b_cont;
24225 			/*
24226 			 * Attach the next message block with payload
24227 			 * data to the multidata message.
24228 			 */
24229 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24230 				goto pbuf_panic;
24231 			pld_ptr = mp->b_rptr;
24232 		}
24233 	}
24234 
24235 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24236 	ASSERT(mp->b_wptr == pld_ptr);
24237 
24238 	/* Update IP statistics */
24239 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24240 
24241 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24242 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24243 
24244 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24245 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24246 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24247 
24248 	if (pkt_type == OB_PKT) {
24249 		ire->ire_ob_pkt_count += pkts;
24250 		if (ire->ire_ipif != NULL)
24251 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24252 	} else {
24253 		/*
24254 		 * The type is IB_PKT in the forwarding path and in
24255 		 * the mobile IP case when the packet is being reverse-
24256 		 * tunneled to the home agent.
24257 		 */
24258 		ire->ire_ib_pkt_count += pkts;
24259 		ASSERT(!IRE_IS_LOCAL(ire));
24260 		if (ire->ire_type & IRE_BROADCAST) {
24261 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24262 		} else {
24263 			UPDATE_MIB(ill->ill_ip_mib,
24264 			    ipIfStatsHCOutForwDatagrams, pkts);
24265 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24266 		}
24267 	}
24268 	ire->ire_last_used_time = lbolt;
24269 	/* Send it down */
24270 	putnext(ire->ire_stq, md_mp);
24271 	return;
24272 
24273 pbuf_panic:
24274 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24275 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24276 	    pbuf_idx);
24277 	/* NOTREACHED */
24278 }
24279 
24280 /*
24281  * Outbound IP fragmentation routine.
24282  *
24283  * NOTE : This routine does not ire_refrele the ire that is passed in
24284  * as the argument.
24285  */
24286 static void
24287 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24288     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24289 {
24290 	int		i1;
24291 	mblk_t		*ll_hdr_mp;
24292 	int 		ll_hdr_len;
24293 	int		hdr_len;
24294 	mblk_t		*hdr_mp;
24295 	ipha_t		*ipha;
24296 	int		ip_data_end;
24297 	int		len;
24298 	mblk_t		*mp = mp_orig, *mp1;
24299 	int		offset;
24300 	queue_t		*q;
24301 	uint32_t	v_hlen_tos_len;
24302 	mblk_t		*first_mp;
24303 	boolean_t	mctl_present;
24304 	ill_t		*ill;
24305 	ill_t		*out_ill;
24306 	mblk_t		*xmit_mp;
24307 	mblk_t		*carve_mp;
24308 	ire_t		*ire1 = NULL;
24309 	ire_t		*save_ire = NULL;
24310 	mblk_t  	*next_mp = NULL;
24311 	boolean_t	last_frag = B_FALSE;
24312 	boolean_t	multirt_send = B_FALSE;
24313 	ire_t		*first_ire = NULL;
24314 	irb_t		*irb = NULL;
24315 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24316 
24317 	ill = ire_to_ill(ire);
24318 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24319 
24320 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24321 
24322 	if (max_frag == 0) {
24323 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24324 		    " -  dropping packet\n"));
24325 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24326 		freemsg(mp);
24327 		return;
24328 	}
24329 
24330 	/*
24331 	 * IPSEC does not allow hw accelerated packets to be fragmented
24332 	 * This check is made in ip_wput_ipsec_out prior to coming here
24333 	 * via ip_wput_ire_fragmentit.
24334 	 *
24335 	 * If at this point we have an ire whose ARP request has not
24336 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24337 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24338 	 * This packet and all fragmentable packets for this ire will
24339 	 * continue to get dropped while ire_nce->nce_state remains in
24340 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24341 	 * ND_REACHABLE, all subsquent large packets for this ire will
24342 	 * get fragemented and sent out by this function.
24343 	 */
24344 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24345 		/* If nce_state is ND_INITIAL, trigger ARP query */
24346 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24347 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24348 		    " -  dropping packet\n"));
24349 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24350 		freemsg(mp);
24351 		return;
24352 	}
24353 
24354 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24355 	    "ip_wput_frag_start:");
24356 
24357 	if (mp->b_datap->db_type == M_CTL) {
24358 		first_mp = mp;
24359 		mp_orig = mp = mp->b_cont;
24360 		mctl_present = B_TRUE;
24361 	} else {
24362 		first_mp = mp;
24363 		mctl_present = B_FALSE;
24364 	}
24365 
24366 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24367 	ipha = (ipha_t *)mp->b_rptr;
24368 
24369 	/*
24370 	 * If the Don't Fragment flag is on, generate an ICMP destination
24371 	 * unreachable, fragmentation needed.
24372 	 */
24373 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24374 	if (offset & IPH_DF) {
24375 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24376 		if (is_system_labeled()) {
24377 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24378 			    ire->ire_max_frag - max_frag, AF_INET);
24379 		}
24380 		/*
24381 		 * Need to compute hdr checksum if called from ip_wput_ire.
24382 		 * Note that ip_rput_forward verifies the checksum before
24383 		 * calling this routine so in that case this is a noop.
24384 		 */
24385 		ipha->ipha_hdr_checksum = 0;
24386 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24387 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24388 		    ipst);
24389 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24390 		    "ip_wput_frag_end:(%S)",
24391 		    "don't fragment");
24392 		return;
24393 	}
24394 	/*
24395 	 * Labeled systems adjust max_frag if they add a label
24396 	 * to send the correct path mtu.  We need the real mtu since we
24397 	 * are fragmenting the packet after label adjustment.
24398 	 */
24399 	if (is_system_labeled())
24400 		max_frag = ire->ire_max_frag;
24401 	if (mctl_present)
24402 		freeb(first_mp);
24403 	/*
24404 	 * Establish the starting offset.  May not be zero if we are fragging
24405 	 * a fragment that is being forwarded.
24406 	 */
24407 	offset = offset & IPH_OFFSET;
24408 
24409 	/* TODO why is this test needed? */
24410 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24411 	if (((max_frag - LENGTH) & ~7) < 8) {
24412 		/* TODO: notify ulp somehow */
24413 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24414 		freemsg(mp);
24415 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24416 		    "ip_wput_frag_end:(%S)",
24417 		    "len < 8");
24418 		return;
24419 	}
24420 
24421 	hdr_len = (V_HLEN & 0xF) << 2;
24422 
24423 	ipha->ipha_hdr_checksum = 0;
24424 
24425 	/*
24426 	 * Establish the number of bytes maximum per frag, after putting
24427 	 * in the header.
24428 	 */
24429 	len = (max_frag - hdr_len) & ~7;
24430 
24431 	/* Check if we can use MDT to send out the frags. */
24432 	ASSERT(!IRE_IS_LOCAL(ire));
24433 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24434 	    ipst->ips_ip_multidata_outbound &&
24435 	    !(ire->ire_flags & RTF_MULTIRT) &&
24436 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24437 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24438 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24439 		ASSERT(ill->ill_mdt_capab != NULL);
24440 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24441 			/*
24442 			 * If MDT has been previously turned off in the past,
24443 			 * and we currently can do MDT (due to IPQoS policy
24444 			 * removal, etc.) then enable it for this interface.
24445 			 */
24446 			ill->ill_mdt_capab->ill_mdt_on = 1;
24447 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24448 			    ill->ill_name));
24449 		}
24450 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24451 		    offset);
24452 		return;
24453 	}
24454 
24455 	/* Get a copy of the header for the trailing frags */
24456 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24457 	if (!hdr_mp) {
24458 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24459 		freemsg(mp);
24460 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24461 		    "ip_wput_frag_end:(%S)",
24462 		    "couldn't copy hdr");
24463 		return;
24464 	}
24465 	if (DB_CRED(mp) != NULL)
24466 		mblk_setcred(hdr_mp, DB_CRED(mp));
24467 
24468 	/* Store the starting offset, with the MoreFrags flag. */
24469 	i1 = offset | IPH_MF | frag_flag;
24470 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24471 
24472 	/* Establish the ending byte offset, based on the starting offset. */
24473 	offset <<= 3;
24474 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24475 
24476 	/* Store the length of the first fragment in the IP header. */
24477 	i1 = len + hdr_len;
24478 	ASSERT(i1 <= IP_MAXPACKET);
24479 	ipha->ipha_length = htons((uint16_t)i1);
24480 
24481 	/*
24482 	 * Compute the IP header checksum for the first frag.  We have to
24483 	 * watch out that we stop at the end of the header.
24484 	 */
24485 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24486 
24487 	/*
24488 	 * Now carve off the first frag.  Note that this will include the
24489 	 * original IP header.
24490 	 */
24491 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24492 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24493 		freeb(hdr_mp);
24494 		freemsg(mp_orig);
24495 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24496 		    "ip_wput_frag_end:(%S)",
24497 		    "couldn't carve first");
24498 		return;
24499 	}
24500 
24501 	/*
24502 	 * Multirouting case. Each fragment is replicated
24503 	 * via all non-condemned RTF_MULTIRT routes
24504 	 * currently resolved.
24505 	 * We ensure that first_ire is the first RTF_MULTIRT
24506 	 * ire in the bucket.
24507 	 */
24508 	if (ire->ire_flags & RTF_MULTIRT) {
24509 		irb = ire->ire_bucket;
24510 		ASSERT(irb != NULL);
24511 
24512 		multirt_send = B_TRUE;
24513 
24514 		/* Make sure we do not omit any multiroute ire. */
24515 		IRB_REFHOLD(irb);
24516 		for (first_ire = irb->irb_ire;
24517 		    first_ire != NULL;
24518 		    first_ire = first_ire->ire_next) {
24519 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24520 			    (first_ire->ire_addr == ire->ire_addr) &&
24521 			    !(first_ire->ire_marks &
24522 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24523 				break;
24524 			}
24525 		}
24526 
24527 		if (first_ire != NULL) {
24528 			if (first_ire != ire) {
24529 				IRE_REFHOLD(first_ire);
24530 				/*
24531 				 * Do not release the ire passed in
24532 				 * as the argument.
24533 				 */
24534 				ire = first_ire;
24535 			} else {
24536 				first_ire = NULL;
24537 			}
24538 		}
24539 		IRB_REFRELE(irb);
24540 
24541 		/*
24542 		 * Save the first ire; we will need to restore it
24543 		 * for the trailing frags.
24544 		 * We REFHOLD save_ire, as each iterated ire will be
24545 		 * REFRELEd.
24546 		 */
24547 		save_ire = ire;
24548 		IRE_REFHOLD(save_ire);
24549 	}
24550 
24551 	/*
24552 	 * First fragment emission loop.
24553 	 * In most cases, the emission loop below is entered only
24554 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24555 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24556 	 * bucket, and send the fragment through all crossed
24557 	 * RTF_MULTIRT routes.
24558 	 */
24559 	do {
24560 		if (ire->ire_flags & RTF_MULTIRT) {
24561 			/*
24562 			 * We are in a multiple send case, need to get
24563 			 * the next ire and make a copy of the packet.
24564 			 * ire1 holds here the next ire to process in the
24565 			 * bucket. If multirouting is expected,
24566 			 * any non-RTF_MULTIRT ire that has the
24567 			 * right destination address is ignored.
24568 			 *
24569 			 * We have to take into account the MTU of
24570 			 * each walked ire. max_frag is set by the
24571 			 * the caller and generally refers to
24572 			 * the primary ire entry. Here we ensure that
24573 			 * no route with a lower MTU will be used, as
24574 			 * fragments are carved once for all ires,
24575 			 * then replicated.
24576 			 */
24577 			ASSERT(irb != NULL);
24578 			IRB_REFHOLD(irb);
24579 			for (ire1 = ire->ire_next;
24580 			    ire1 != NULL;
24581 			    ire1 = ire1->ire_next) {
24582 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24583 					continue;
24584 				if (ire1->ire_addr != ire->ire_addr)
24585 					continue;
24586 				if (ire1->ire_marks &
24587 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24588 					continue;
24589 				/*
24590 				 * Ensure we do not exceed the MTU
24591 				 * of the next route.
24592 				 */
24593 				if (ire1->ire_max_frag < max_frag) {
24594 					ip_multirt_bad_mtu(ire1, max_frag);
24595 					continue;
24596 				}
24597 
24598 				/* Got one. */
24599 				IRE_REFHOLD(ire1);
24600 				break;
24601 			}
24602 			IRB_REFRELE(irb);
24603 
24604 			if (ire1 != NULL) {
24605 				next_mp = copyb(mp);
24606 				if ((next_mp == NULL) ||
24607 				    ((mp->b_cont != NULL) &&
24608 				    ((next_mp->b_cont =
24609 				    dupmsg(mp->b_cont)) == NULL))) {
24610 					freemsg(next_mp);
24611 					next_mp = NULL;
24612 					ire_refrele(ire1);
24613 					ire1 = NULL;
24614 				}
24615 			}
24616 
24617 			/* Last multiroute ire; don't loop anymore. */
24618 			if (ire1 == NULL) {
24619 				multirt_send = B_FALSE;
24620 			}
24621 		}
24622 
24623 		ll_hdr_len = 0;
24624 		LOCK_IRE_FP_MP(ire);
24625 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24626 		if (ll_hdr_mp != NULL) {
24627 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24628 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24629 		} else {
24630 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24631 		}
24632 
24633 		/* If there is a transmit header, get a copy for this frag. */
24634 		/*
24635 		 * TODO: should check db_ref before calling ip_carve_mp since
24636 		 * it might give us a dup.
24637 		 */
24638 		if (!ll_hdr_mp) {
24639 			/* No xmit header. */
24640 			xmit_mp = mp;
24641 
24642 		/* We have a link-layer header that can fit in our mblk. */
24643 		} else if (mp->b_datap->db_ref == 1 &&
24644 		    ll_hdr_len != 0 &&
24645 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24646 			/* M_DATA fastpath */
24647 			mp->b_rptr -= ll_hdr_len;
24648 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24649 			xmit_mp = mp;
24650 
24651 		/* Corner case if copyb has failed */
24652 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24653 			UNLOCK_IRE_FP_MP(ire);
24654 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24655 			freeb(hdr_mp);
24656 			freemsg(mp);
24657 			freemsg(mp_orig);
24658 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24659 			    "ip_wput_frag_end:(%S)",
24660 			    "discard");
24661 
24662 			if (multirt_send) {
24663 				ASSERT(ire1);
24664 				ASSERT(next_mp);
24665 
24666 				freemsg(next_mp);
24667 				ire_refrele(ire1);
24668 			}
24669 			if (save_ire != NULL)
24670 				IRE_REFRELE(save_ire);
24671 
24672 			if (first_ire != NULL)
24673 				ire_refrele(first_ire);
24674 			return;
24675 
24676 		/*
24677 		 * Case of res_mp OR the fastpath mp can't fit
24678 		 * in the mblk
24679 		 */
24680 		} else {
24681 			xmit_mp->b_cont = mp;
24682 			if (DB_CRED(mp) != NULL)
24683 				mblk_setcred(xmit_mp, DB_CRED(mp));
24684 			/*
24685 			 * Get priority marking, if any.
24686 			 * We propagate the CoS marking from the
24687 			 * original packet that went to QoS processing
24688 			 * in ip_wput_ire to the newly carved mp.
24689 			 */
24690 			if (DB_TYPE(xmit_mp) == M_DATA)
24691 				xmit_mp->b_band = mp->b_band;
24692 		}
24693 		UNLOCK_IRE_FP_MP(ire);
24694 
24695 		q = ire->ire_stq;
24696 		out_ill = (ill_t *)q->q_ptr;
24697 
24698 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24699 
24700 		DTRACE_PROBE4(ip4__physical__out__start,
24701 		    ill_t *, NULL, ill_t *, out_ill,
24702 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24703 
24704 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24705 		    ipst->ips_ipv4firewall_physical_out,
24706 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24707 
24708 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24709 
24710 		if (xmit_mp != NULL) {
24711 			putnext(q, xmit_mp);
24712 
24713 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24714 			UPDATE_MIB(out_ill->ill_ip_mib,
24715 			    ipIfStatsHCOutOctets, i1);
24716 
24717 			if (pkt_type != OB_PKT) {
24718 				/*
24719 				 * Update the packet count and MIB stats
24720 				 * of trailing RTF_MULTIRT ires.
24721 				 */
24722 				UPDATE_OB_PKT_COUNT(ire);
24723 				BUMP_MIB(out_ill->ill_ip_mib,
24724 				    ipIfStatsOutFragReqds);
24725 			}
24726 		}
24727 
24728 		if (multirt_send) {
24729 			/*
24730 			 * We are in a multiple send case; look for
24731 			 * the next ire and re-enter the loop.
24732 			 */
24733 			ASSERT(ire1);
24734 			ASSERT(next_mp);
24735 			/* REFRELE the current ire before looping */
24736 			ire_refrele(ire);
24737 			ire = ire1;
24738 			ire1 = NULL;
24739 			mp = next_mp;
24740 			next_mp = NULL;
24741 		}
24742 	} while (multirt_send);
24743 
24744 	ASSERT(ire1 == NULL);
24745 
24746 	/* Restore the original ire; we need it for the trailing frags */
24747 	if (save_ire != NULL) {
24748 		/* REFRELE the last iterated ire */
24749 		ire_refrele(ire);
24750 		/* save_ire has been REFHOLDed */
24751 		ire = save_ire;
24752 		save_ire = NULL;
24753 		q = ire->ire_stq;
24754 	}
24755 
24756 	if (pkt_type == OB_PKT) {
24757 		UPDATE_OB_PKT_COUNT(ire);
24758 	} else {
24759 		out_ill = (ill_t *)q->q_ptr;
24760 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24761 		UPDATE_IB_PKT_COUNT(ire);
24762 	}
24763 
24764 	/* Advance the offset to the second frag starting point. */
24765 	offset += len;
24766 	/*
24767 	 * Update hdr_len from the copied header - there might be less options
24768 	 * in the later fragments.
24769 	 */
24770 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24771 	/* Loop until done. */
24772 	for (;;) {
24773 		uint16_t	offset_and_flags;
24774 		uint16_t	ip_len;
24775 
24776 		if (ip_data_end - offset > len) {
24777 			/*
24778 			 * Carve off the appropriate amount from the original
24779 			 * datagram.
24780 			 */
24781 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24782 				mp = NULL;
24783 				break;
24784 			}
24785 			/*
24786 			 * More frags after this one.  Get another copy
24787 			 * of the header.
24788 			 */
24789 			if (carve_mp->b_datap->db_ref == 1 &&
24790 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24791 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24792 				/* Inline IP header */
24793 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24794 				    hdr_mp->b_rptr;
24795 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24796 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24797 				mp = carve_mp;
24798 			} else {
24799 				if (!(mp = copyb(hdr_mp))) {
24800 					freemsg(carve_mp);
24801 					break;
24802 				}
24803 				/* Get priority marking, if any. */
24804 				mp->b_band = carve_mp->b_band;
24805 				mp->b_cont = carve_mp;
24806 			}
24807 			ipha = (ipha_t *)mp->b_rptr;
24808 			offset_and_flags = IPH_MF;
24809 		} else {
24810 			/*
24811 			 * Last frag.  Consume the header. Set len to
24812 			 * the length of this last piece.
24813 			 */
24814 			len = ip_data_end - offset;
24815 
24816 			/*
24817 			 * Carve off the appropriate amount from the original
24818 			 * datagram.
24819 			 */
24820 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24821 				mp = NULL;
24822 				break;
24823 			}
24824 			if (carve_mp->b_datap->db_ref == 1 &&
24825 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24826 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24827 				/* Inline IP header */
24828 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24829 				    hdr_mp->b_rptr;
24830 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24831 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24832 				mp = carve_mp;
24833 				freeb(hdr_mp);
24834 				hdr_mp = mp;
24835 			} else {
24836 				mp = hdr_mp;
24837 				/* Get priority marking, if any. */
24838 				mp->b_band = carve_mp->b_band;
24839 				mp->b_cont = carve_mp;
24840 			}
24841 			ipha = (ipha_t *)mp->b_rptr;
24842 			/* A frag of a frag might have IPH_MF non-zero */
24843 			offset_and_flags =
24844 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24845 			    IPH_MF;
24846 		}
24847 		offset_and_flags |= (uint16_t)(offset >> 3);
24848 		offset_and_flags |= (uint16_t)frag_flag;
24849 		/* Store the offset and flags in the IP header. */
24850 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24851 
24852 		/* Store the length in the IP header. */
24853 		ip_len = (uint16_t)(len + hdr_len);
24854 		ipha->ipha_length = htons(ip_len);
24855 
24856 		/*
24857 		 * Set the IP header checksum.	Note that mp is just
24858 		 * the header, so this is easy to pass to ip_csum.
24859 		 */
24860 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24861 
24862 		/* Attach a transmit header, if any, and ship it. */
24863 		if (pkt_type == OB_PKT) {
24864 			UPDATE_OB_PKT_COUNT(ire);
24865 		} else {
24866 			out_ill = (ill_t *)q->q_ptr;
24867 			BUMP_MIB(out_ill->ill_ip_mib,
24868 			    ipIfStatsHCOutForwDatagrams);
24869 			UPDATE_IB_PKT_COUNT(ire);
24870 		}
24871 
24872 		if (ire->ire_flags & RTF_MULTIRT) {
24873 			irb = ire->ire_bucket;
24874 			ASSERT(irb != NULL);
24875 
24876 			multirt_send = B_TRUE;
24877 
24878 			/*
24879 			 * Save the original ire; we will need to restore it
24880 			 * for the tailing frags.
24881 			 */
24882 			save_ire = ire;
24883 			IRE_REFHOLD(save_ire);
24884 		}
24885 		/*
24886 		 * Emission loop for this fragment, similar
24887 		 * to what is done for the first fragment.
24888 		 */
24889 		do {
24890 			if (multirt_send) {
24891 				/*
24892 				 * We are in a multiple send case, need to get
24893 				 * the next ire and make a copy of the packet.
24894 				 */
24895 				ASSERT(irb != NULL);
24896 				IRB_REFHOLD(irb);
24897 				for (ire1 = ire->ire_next;
24898 				    ire1 != NULL;
24899 				    ire1 = ire1->ire_next) {
24900 					if (!(ire1->ire_flags & RTF_MULTIRT))
24901 						continue;
24902 					if (ire1->ire_addr != ire->ire_addr)
24903 						continue;
24904 					if (ire1->ire_marks &
24905 					    (IRE_MARK_CONDEMNED|
24906 					    IRE_MARK_HIDDEN)) {
24907 						continue;
24908 					}
24909 					/*
24910 					 * Ensure we do not exceed the MTU
24911 					 * of the next route.
24912 					 */
24913 					if (ire1->ire_max_frag < max_frag) {
24914 						ip_multirt_bad_mtu(ire1,
24915 						    max_frag);
24916 						continue;
24917 					}
24918 
24919 					/* Got one. */
24920 					IRE_REFHOLD(ire1);
24921 					break;
24922 				}
24923 				IRB_REFRELE(irb);
24924 
24925 				if (ire1 != NULL) {
24926 					next_mp = copyb(mp);
24927 					if ((next_mp == NULL) ||
24928 					    ((mp->b_cont != NULL) &&
24929 					    ((next_mp->b_cont =
24930 					    dupmsg(mp->b_cont)) == NULL))) {
24931 						freemsg(next_mp);
24932 						next_mp = NULL;
24933 						ire_refrele(ire1);
24934 						ire1 = NULL;
24935 					}
24936 				}
24937 
24938 				/* Last multiroute ire; don't loop anymore. */
24939 				if (ire1 == NULL) {
24940 					multirt_send = B_FALSE;
24941 				}
24942 			}
24943 
24944 			/* Update transmit header */
24945 			ll_hdr_len = 0;
24946 			LOCK_IRE_FP_MP(ire);
24947 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24948 			if (ll_hdr_mp != NULL) {
24949 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24950 				ll_hdr_len = MBLKL(ll_hdr_mp);
24951 			} else {
24952 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24953 			}
24954 
24955 			if (!ll_hdr_mp) {
24956 				xmit_mp = mp;
24957 
24958 			/*
24959 			 * We have link-layer header that can fit in
24960 			 * our mblk.
24961 			 */
24962 			} else if (mp->b_datap->db_ref == 1 &&
24963 			    ll_hdr_len != 0 &&
24964 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24965 				/* M_DATA fastpath */
24966 				mp->b_rptr -= ll_hdr_len;
24967 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24968 				    ll_hdr_len);
24969 				xmit_mp = mp;
24970 
24971 			/*
24972 			 * Case of res_mp OR the fastpath mp can't fit
24973 			 * in the mblk
24974 			 */
24975 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24976 				xmit_mp->b_cont = mp;
24977 				if (DB_CRED(mp) != NULL)
24978 					mblk_setcred(xmit_mp, DB_CRED(mp));
24979 				/* Get priority marking, if any. */
24980 				if (DB_TYPE(xmit_mp) == M_DATA)
24981 					xmit_mp->b_band = mp->b_band;
24982 
24983 			/* Corner case if copyb failed */
24984 			} else {
24985 				/*
24986 				 * Exit both the replication and
24987 				 * fragmentation loops.
24988 				 */
24989 				UNLOCK_IRE_FP_MP(ire);
24990 				goto drop_pkt;
24991 			}
24992 			UNLOCK_IRE_FP_MP(ire);
24993 
24994 			mp1 = mp;
24995 			out_ill = (ill_t *)q->q_ptr;
24996 
24997 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24998 
24999 			DTRACE_PROBE4(ip4__physical__out__start,
25000 			    ill_t *, NULL, ill_t *, out_ill,
25001 			    ipha_t *, ipha, mblk_t *, xmit_mp);
25002 
25003 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
25004 			    ipst->ips_ipv4firewall_physical_out,
25005 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
25006 
25007 			DTRACE_PROBE1(ip4__physical__out__end,
25008 			    mblk_t *, xmit_mp);
25009 
25010 			if (mp != mp1 && hdr_mp == mp1)
25011 				hdr_mp = mp;
25012 			if (mp != mp1 && mp_orig == mp1)
25013 				mp_orig = mp;
25014 
25015 			if (xmit_mp != NULL) {
25016 				putnext(q, xmit_mp);
25017 
25018 				BUMP_MIB(out_ill->ill_ip_mib,
25019 				    ipIfStatsHCOutTransmits);
25020 				UPDATE_MIB(out_ill->ill_ip_mib,
25021 				    ipIfStatsHCOutOctets, ip_len);
25022 
25023 				if (pkt_type != OB_PKT) {
25024 					/*
25025 					 * Update the packet count of trailing
25026 					 * RTF_MULTIRT ires.
25027 					 */
25028 					UPDATE_OB_PKT_COUNT(ire);
25029 				}
25030 			}
25031 
25032 			/* All done if we just consumed the hdr_mp. */
25033 			if (mp == hdr_mp) {
25034 				last_frag = B_TRUE;
25035 				BUMP_MIB(out_ill->ill_ip_mib,
25036 				    ipIfStatsOutFragOKs);
25037 			}
25038 
25039 			if (multirt_send) {
25040 				/*
25041 				 * We are in a multiple send case; look for
25042 				 * the next ire and re-enter the loop.
25043 				 */
25044 				ASSERT(ire1);
25045 				ASSERT(next_mp);
25046 				/* REFRELE the current ire before looping */
25047 				ire_refrele(ire);
25048 				ire = ire1;
25049 				ire1 = NULL;
25050 				q = ire->ire_stq;
25051 				mp = next_mp;
25052 				next_mp = NULL;
25053 			}
25054 		} while (multirt_send);
25055 		/*
25056 		 * Restore the original ire; we need it for the
25057 		 * trailing frags
25058 		 */
25059 		if (save_ire != NULL) {
25060 			ASSERT(ire1 == NULL);
25061 			/* REFRELE the last iterated ire */
25062 			ire_refrele(ire);
25063 			/* save_ire has been REFHOLDed */
25064 			ire = save_ire;
25065 			q = ire->ire_stq;
25066 			save_ire = NULL;
25067 		}
25068 
25069 		if (last_frag) {
25070 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25071 			    "ip_wput_frag_end:(%S)",
25072 			    "consumed hdr_mp");
25073 
25074 			if (first_ire != NULL)
25075 				ire_refrele(first_ire);
25076 			return;
25077 		}
25078 		/* Otherwise, advance and loop. */
25079 		offset += len;
25080 	}
25081 
25082 drop_pkt:
25083 	/* Clean up following allocation failure. */
25084 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
25085 	freemsg(mp);
25086 	if (mp != hdr_mp)
25087 		freeb(hdr_mp);
25088 	if (mp != mp_orig)
25089 		freemsg(mp_orig);
25090 
25091 	if (save_ire != NULL)
25092 		IRE_REFRELE(save_ire);
25093 	if (first_ire != NULL)
25094 		ire_refrele(first_ire);
25095 
25096 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
25097 	    "ip_wput_frag_end:(%S)",
25098 	    "end--alloc failure");
25099 }
25100 
25101 /*
25102  * Copy the header plus those options which have the copy bit set
25103  */
25104 static mblk_t *
25105 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
25106 {
25107 	mblk_t	*mp;
25108 	uchar_t	*up;
25109 
25110 	/*
25111 	 * Quick check if we need to look for options without the copy bit
25112 	 * set
25113 	 */
25114 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
25115 	if (!mp)
25116 		return (mp);
25117 	mp->b_rptr += ipst->ips_ip_wroff_extra;
25118 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
25119 		bcopy(rptr, mp->b_rptr, hdr_len);
25120 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
25121 		return (mp);
25122 	}
25123 	up  = mp->b_rptr;
25124 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
25125 	up += IP_SIMPLE_HDR_LENGTH;
25126 	rptr += IP_SIMPLE_HDR_LENGTH;
25127 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
25128 	while (hdr_len > 0) {
25129 		uint32_t optval;
25130 		uint32_t optlen;
25131 
25132 		optval = *rptr;
25133 		if (optval == IPOPT_EOL)
25134 			break;
25135 		if (optval == IPOPT_NOP)
25136 			optlen = 1;
25137 		else
25138 			optlen = rptr[1];
25139 		if (optval & IPOPT_COPY) {
25140 			bcopy(rptr, up, optlen);
25141 			up += optlen;
25142 		}
25143 		rptr += optlen;
25144 		hdr_len -= optlen;
25145 	}
25146 	/*
25147 	 * Make sure that we drop an even number of words by filling
25148 	 * with EOL to the next word boundary.
25149 	 */
25150 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25151 	    hdr_len & 0x3; hdr_len++)
25152 		*up++ = IPOPT_EOL;
25153 	mp->b_wptr = up;
25154 	/* Update header length */
25155 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25156 	return (mp);
25157 }
25158 
25159 /*
25160  * Delivery to local recipients including fanout to multiple recipients.
25161  * Does not do checksumming of UDP/TCP.
25162  * Note: q should be the read side queue for either the ill or conn.
25163  * Note: rq should be the read side q for the lower (ill) stream.
25164  * We don't send packets to IPPF processing, thus the last argument
25165  * to all the fanout calls are B_FALSE.
25166  */
25167 void
25168 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25169     int fanout_flags, zoneid_t zoneid)
25170 {
25171 	uint32_t	protocol;
25172 	mblk_t		*first_mp;
25173 	boolean_t	mctl_present;
25174 	int		ire_type;
25175 #define	rptr	((uchar_t *)ipha)
25176 	ip_stack_t	*ipst = ill->ill_ipst;
25177 
25178 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25179 	    "ip_wput_local_start: q %p", q);
25180 
25181 	if (ire != NULL) {
25182 		ire_type = ire->ire_type;
25183 	} else {
25184 		/*
25185 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25186 		 * packet is not multicast, we can't tell the ire type.
25187 		 */
25188 		ASSERT(CLASSD(ipha->ipha_dst));
25189 		ire_type = IRE_BROADCAST;
25190 	}
25191 
25192 	first_mp = mp;
25193 	if (first_mp->b_datap->db_type == M_CTL) {
25194 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25195 		if (!io->ipsec_out_secure) {
25196 			/*
25197 			 * This ipsec_out_t was allocated in ip_wput
25198 			 * for multicast packets to store the ill_index.
25199 			 * As this is being delivered locally, we don't
25200 			 * need this anymore.
25201 			 */
25202 			mp = first_mp->b_cont;
25203 			freeb(first_mp);
25204 			first_mp = mp;
25205 			mctl_present = B_FALSE;
25206 		} else {
25207 			/*
25208 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25209 			 * security properties for the looped-back packet.
25210 			 */
25211 			mctl_present = B_TRUE;
25212 			mp = first_mp->b_cont;
25213 			ASSERT(mp != NULL);
25214 			ipsec_out_to_in(first_mp);
25215 		}
25216 	} else {
25217 		mctl_present = B_FALSE;
25218 	}
25219 
25220 	DTRACE_PROBE4(ip4__loopback__in__start,
25221 	    ill_t *, ill, ill_t *, NULL,
25222 	    ipha_t *, ipha, mblk_t *, first_mp);
25223 
25224 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25225 	    ipst->ips_ipv4firewall_loopback_in,
25226 	    ill, NULL, ipha, first_mp, mp, ipst);
25227 
25228 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25229 
25230 	if (first_mp == NULL)
25231 		return;
25232 
25233 	ipst->ips_loopback_packets++;
25234 
25235 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25236 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25237 	if (!IS_SIMPLE_IPH(ipha)) {
25238 		ip_wput_local_options(ipha, ipst);
25239 	}
25240 
25241 	protocol = ipha->ipha_protocol;
25242 	switch (protocol) {
25243 	case IPPROTO_ICMP: {
25244 		ire_t		*ire_zone;
25245 		ilm_t		*ilm;
25246 		mblk_t		*mp1;
25247 		zoneid_t	last_zoneid;
25248 
25249 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25250 			ASSERT(ire_type == IRE_BROADCAST);
25251 			/*
25252 			 * In the multicast case, applications may have joined
25253 			 * the group from different zones, so we need to deliver
25254 			 * the packet to each of them. Loop through the
25255 			 * multicast memberships structures (ilm) on the receive
25256 			 * ill and send a copy of the packet up each matching
25257 			 * one. However, we don't do this for multicasts sent on
25258 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25259 			 * they must stay in the sender's zone.
25260 			 *
25261 			 * ilm_add_v6() ensures that ilms in the same zone are
25262 			 * contiguous in the ill_ilm list. We use this property
25263 			 * to avoid sending duplicates needed when two
25264 			 * applications in the same zone join the same group on
25265 			 * different logical interfaces: we ignore the ilm if
25266 			 * it's zoneid is the same as the last matching one.
25267 			 * In addition, the sending of the packet for
25268 			 * ire_zoneid is delayed until all of the other ilms
25269 			 * have been exhausted.
25270 			 */
25271 			last_zoneid = -1;
25272 			ILM_WALKER_HOLD(ill);
25273 			for (ilm = ill->ill_ilm; ilm != NULL;
25274 			    ilm = ilm->ilm_next) {
25275 				if ((ilm->ilm_flags & ILM_DELETED) ||
25276 				    ipha->ipha_dst != ilm->ilm_addr ||
25277 				    ilm->ilm_zoneid == last_zoneid ||
25278 				    ilm->ilm_zoneid == zoneid ||
25279 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25280 					continue;
25281 				mp1 = ip_copymsg(first_mp);
25282 				if (mp1 == NULL)
25283 					continue;
25284 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25285 				    mctl_present, B_FALSE, ill,
25286 				    ilm->ilm_zoneid);
25287 				last_zoneid = ilm->ilm_zoneid;
25288 			}
25289 			ILM_WALKER_RELE(ill);
25290 			/*
25291 			 * Loopback case: the sending endpoint has
25292 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25293 			 * dispatch the multicast packet to the sending zone.
25294 			 */
25295 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25296 				freemsg(first_mp);
25297 				return;
25298 			}
25299 		} else if (ire_type == IRE_BROADCAST) {
25300 			/*
25301 			 * In the broadcast case, there may be many zones
25302 			 * which need a copy of the packet delivered to them.
25303 			 * There is one IRE_BROADCAST per broadcast address
25304 			 * and per zone; we walk those using a helper function.
25305 			 * In addition, the sending of the packet for zoneid is
25306 			 * delayed until all of the other ires have been
25307 			 * processed.
25308 			 */
25309 			IRB_REFHOLD(ire->ire_bucket);
25310 			ire_zone = NULL;
25311 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25312 			    ire)) != NULL) {
25313 				mp1 = ip_copymsg(first_mp);
25314 				if (mp1 == NULL)
25315 					continue;
25316 
25317 				UPDATE_IB_PKT_COUNT(ire_zone);
25318 				ire_zone->ire_last_used_time = lbolt;
25319 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25320 				    mctl_present, B_FALSE, ill,
25321 				    ire_zone->ire_zoneid);
25322 			}
25323 			IRB_REFRELE(ire->ire_bucket);
25324 		}
25325 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25326 		    0, mctl_present, B_FALSE, ill, zoneid);
25327 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25328 		    "ip_wput_local_end: q %p (%S)",
25329 		    q, "icmp");
25330 		return;
25331 	}
25332 	case IPPROTO_IGMP:
25333 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25334 			/* Bad packet - discarded by igmp_input */
25335 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25336 			    "ip_wput_local_end: q %p (%S)",
25337 			    q, "igmp_input--bad packet");
25338 			if (mctl_present)
25339 				freeb(first_mp);
25340 			return;
25341 		}
25342 		/*
25343 		 * igmp_input() may have returned the pulled up message.
25344 		 * So first_mp and ipha need to be reinitialized.
25345 		 */
25346 		ipha = (ipha_t *)mp->b_rptr;
25347 		if (mctl_present)
25348 			first_mp->b_cont = mp;
25349 		else
25350 			first_mp = mp;
25351 		/* deliver to local raw users */
25352 		break;
25353 	case IPPROTO_ENCAP:
25354 		/*
25355 		 * This case is covered by either ip_fanout_proto, or by
25356 		 * the above security processing for self-tunneled packets.
25357 		 */
25358 		break;
25359 	case IPPROTO_UDP: {
25360 		uint16_t	*up;
25361 		uint32_t	ports;
25362 
25363 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25364 		    UDP_PORTS_OFFSET);
25365 		/* Force a 'valid' checksum. */
25366 		up[3] = 0;
25367 
25368 		ports = *(uint32_t *)up;
25369 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25370 		    (ire_type == IRE_BROADCAST),
25371 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25372 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25373 		    ill, zoneid);
25374 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25375 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25376 		return;
25377 	}
25378 	case IPPROTO_TCP: {
25379 
25380 		/*
25381 		 * For TCP, discard broadcast packets.
25382 		 */
25383 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25384 			freemsg(first_mp);
25385 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25386 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25387 			return;
25388 		}
25389 
25390 		if (mp->b_datap->db_type == M_DATA) {
25391 			/*
25392 			 * M_DATA mblk, so init mblk (chain) for no struio().
25393 			 */
25394 			mblk_t	*mp1 = mp;
25395 
25396 			do {
25397 				mp1->b_datap->db_struioflag = 0;
25398 			} while ((mp1 = mp1->b_cont) != NULL);
25399 		}
25400 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25401 		    <= mp->b_wptr);
25402 		ip_fanout_tcp(q, first_mp, ill, ipha,
25403 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25404 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25405 		    mctl_present, B_FALSE, zoneid);
25406 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25407 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25408 		return;
25409 	}
25410 	case IPPROTO_SCTP:
25411 	{
25412 		uint32_t	ports;
25413 
25414 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25415 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25416 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25417 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25418 		return;
25419 	}
25420 
25421 	default:
25422 		break;
25423 	}
25424 	/*
25425 	 * Find a client for some other protocol.  We give
25426 	 * copies to multiple clients, if more than one is
25427 	 * bound.
25428 	 */
25429 	ip_fanout_proto(q, first_mp, ill, ipha,
25430 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25431 	    mctl_present, B_FALSE, ill, zoneid);
25432 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25433 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25434 #undef	rptr
25435 }
25436 
25437 /*
25438  * Update any source route, record route, or timestamp options.
25439  * Check that we are at end of strict source route.
25440  * The options have been sanity checked by ip_wput_options().
25441  */
25442 static void
25443 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25444 {
25445 	ipoptp_t	opts;
25446 	uchar_t		*opt;
25447 	uint8_t		optval;
25448 	uint8_t		optlen;
25449 	ipaddr_t	dst;
25450 	uint32_t	ts;
25451 	ire_t		*ire;
25452 	timestruc_t	now;
25453 
25454 	ip2dbg(("ip_wput_local_options\n"));
25455 	for (optval = ipoptp_first(&opts, ipha);
25456 	    optval != IPOPT_EOL;
25457 	    optval = ipoptp_next(&opts)) {
25458 		opt = opts.ipoptp_cur;
25459 		optlen = opts.ipoptp_len;
25460 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25461 		switch (optval) {
25462 			uint32_t off;
25463 		case IPOPT_SSRR:
25464 		case IPOPT_LSRR:
25465 			off = opt[IPOPT_OFFSET];
25466 			off--;
25467 			if (optlen < IP_ADDR_LEN ||
25468 			    off > optlen - IP_ADDR_LEN) {
25469 				/* End of source route */
25470 				break;
25471 			}
25472 			/*
25473 			 * This will only happen if two consecutive entries
25474 			 * in the source route contains our address or if
25475 			 * it is a packet with a loose source route which
25476 			 * reaches us before consuming the whole source route
25477 			 */
25478 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25479 			if (optval == IPOPT_SSRR) {
25480 				return;
25481 			}
25482 			/*
25483 			 * Hack: instead of dropping the packet truncate the
25484 			 * source route to what has been used by filling the
25485 			 * rest with IPOPT_NOP.
25486 			 */
25487 			opt[IPOPT_OLEN] = (uint8_t)off;
25488 			while (off < optlen) {
25489 				opt[off++] = IPOPT_NOP;
25490 			}
25491 			break;
25492 		case IPOPT_RR:
25493 			off = opt[IPOPT_OFFSET];
25494 			off--;
25495 			if (optlen < IP_ADDR_LEN ||
25496 			    off > optlen - IP_ADDR_LEN) {
25497 				/* No more room - ignore */
25498 				ip1dbg((
25499 				    "ip_wput_forward_options: end of RR\n"));
25500 				break;
25501 			}
25502 			dst = htonl(INADDR_LOOPBACK);
25503 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25504 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25505 			break;
25506 		case IPOPT_TS:
25507 			/* Insert timestamp if there is romm */
25508 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25509 			case IPOPT_TS_TSONLY:
25510 				off = IPOPT_TS_TIMELEN;
25511 				break;
25512 			case IPOPT_TS_PRESPEC:
25513 			case IPOPT_TS_PRESPEC_RFC791:
25514 				/* Verify that the address matched */
25515 				off = opt[IPOPT_OFFSET] - 1;
25516 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25517 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25518 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25519 				    ipst);
25520 				if (ire == NULL) {
25521 					/* Not for us */
25522 					break;
25523 				}
25524 				ire_refrele(ire);
25525 				/* FALLTHRU */
25526 			case IPOPT_TS_TSANDADDR:
25527 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25528 				break;
25529 			default:
25530 				/*
25531 				 * ip_*put_options should have already
25532 				 * dropped this packet.
25533 				 */
25534 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25535 				    "unknown IT - bug in ip_wput_options?\n");
25536 				return;	/* Keep "lint" happy */
25537 			}
25538 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25539 				/* Increase overflow counter */
25540 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25541 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25542 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25543 				    (off << 4);
25544 				break;
25545 			}
25546 			off = opt[IPOPT_OFFSET] - 1;
25547 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25548 			case IPOPT_TS_PRESPEC:
25549 			case IPOPT_TS_PRESPEC_RFC791:
25550 			case IPOPT_TS_TSANDADDR:
25551 				dst = htonl(INADDR_LOOPBACK);
25552 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25553 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25554 				/* FALLTHRU */
25555 			case IPOPT_TS_TSONLY:
25556 				off = opt[IPOPT_OFFSET] - 1;
25557 				/* Compute # of milliseconds since midnight */
25558 				gethrestime(&now);
25559 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25560 				    now.tv_nsec / (NANOSEC / MILLISEC);
25561 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25562 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25563 				break;
25564 			}
25565 			break;
25566 		}
25567 	}
25568 }
25569 
25570 /*
25571  * Send out a multicast packet on interface ipif.
25572  * The sender does not have an conn.
25573  * Caller verifies that this isn't a PHYI_LOOPBACK.
25574  */
25575 void
25576 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25577 {
25578 	ipha_t	*ipha;
25579 	ire_t	*ire;
25580 	ipaddr_t	dst;
25581 	mblk_t		*first_mp;
25582 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25583 
25584 	/* igmp_sendpkt always allocates a ipsec_out_t */
25585 	ASSERT(mp->b_datap->db_type == M_CTL);
25586 	ASSERT(!ipif->ipif_isv6);
25587 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25588 
25589 	first_mp = mp;
25590 	mp = first_mp->b_cont;
25591 	ASSERT(mp->b_datap->db_type == M_DATA);
25592 	ipha = (ipha_t *)mp->b_rptr;
25593 
25594 	/*
25595 	 * Find an IRE which matches the destination and the outgoing
25596 	 * queue (i.e. the outgoing interface.)
25597 	 */
25598 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25599 		dst = ipif->ipif_pp_dst_addr;
25600 	else
25601 		dst = ipha->ipha_dst;
25602 	/*
25603 	 * The source address has already been initialized by the
25604 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25605 	 * be sufficient rather than MATCH_IRE_IPIF.
25606 	 *
25607 	 * This function is used for sending IGMP packets. We need
25608 	 * to make sure that we send the packet out of the interface
25609 	 * (ipif->ipif_ill) where we joined the group. This is to
25610 	 * prevent from switches doing IGMP snooping to send us multicast
25611 	 * packets for a given group on the interface we have joined.
25612 	 * If we can't find an ire, igmp_sendpkt has already initialized
25613 	 * ipsec_out_attach_if so that this will not be load spread in
25614 	 * ip_newroute_ipif.
25615 	 */
25616 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25617 	    MATCH_IRE_ILL, ipst);
25618 	if (!ire) {
25619 		/*
25620 		 * Mark this packet to make it be delivered to
25621 		 * ip_wput_ire after the new ire has been
25622 		 * created.
25623 		 */
25624 		mp->b_prev = NULL;
25625 		mp->b_next = NULL;
25626 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25627 		    zoneid, &zero_info);
25628 		return;
25629 	}
25630 
25631 	/*
25632 	 * Honor the RTF_SETSRC flag; this is the only case
25633 	 * where we force this addr whatever the current src addr is,
25634 	 * because this address is set by igmp_sendpkt(), and
25635 	 * cannot be specified by any user.
25636 	 */
25637 	if (ire->ire_flags & RTF_SETSRC) {
25638 		ipha->ipha_src = ire->ire_src_addr;
25639 	}
25640 
25641 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25642 }
25643 
25644 /*
25645  * NOTE : This function does not ire_refrele the ire argument passed in.
25646  *
25647  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25648  * failure. The nce_fp_mp can vanish any time in the case of IRE_MIPRTUN
25649  * and IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25650  * the ire_lock to access the nce_fp_mp in this case.
25651  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25652  * prepending a fastpath message IPQoS processing must precede it, we also set
25653  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25654  * (IPQoS might have set the b_band for CoS marking).
25655  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25656  * must follow it so that IPQoS can mark the dl_priority field for CoS
25657  * marking, if needed.
25658  */
25659 static mblk_t *
25660 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25661 {
25662 	uint_t	hlen;
25663 	ipha_t *ipha;
25664 	mblk_t *mp1;
25665 	boolean_t qos_done = B_FALSE;
25666 	uchar_t	*ll_hdr;
25667 	ip_stack_t	*ipst = ire->ire_ipst;
25668 
25669 #define	rptr	((uchar_t *)ipha)
25670 
25671 	ipha = (ipha_t *)mp->b_rptr;
25672 	hlen = 0;
25673 	LOCK_IRE_FP_MP(ire);
25674 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25675 		ASSERT(DB_TYPE(mp1) == M_DATA);
25676 		/* Initiate IPPF processing */
25677 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25678 			UNLOCK_IRE_FP_MP(ire);
25679 			ip_process(proc, &mp, ill_index);
25680 			if (mp == NULL)
25681 				return (NULL);
25682 
25683 			ipha = (ipha_t *)mp->b_rptr;
25684 			LOCK_IRE_FP_MP(ire);
25685 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25686 				qos_done = B_TRUE;
25687 				goto no_fp_mp;
25688 			}
25689 			ASSERT(DB_TYPE(mp1) == M_DATA);
25690 		}
25691 		hlen = MBLKL(mp1);
25692 		/*
25693 		 * Check if we have enough room to prepend fastpath
25694 		 * header
25695 		 */
25696 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25697 			ll_hdr = rptr - hlen;
25698 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25699 			/*
25700 			 * Set the b_rptr to the start of the link layer
25701 			 * header
25702 			 */
25703 			mp->b_rptr = ll_hdr;
25704 			mp1 = mp;
25705 		} else {
25706 			mp1 = copyb(mp1);
25707 			if (mp1 == NULL)
25708 				goto unlock_err;
25709 			mp1->b_band = mp->b_band;
25710 			mp1->b_cont = mp;
25711 			/*
25712 			 * certain system generated traffic may not
25713 			 * have cred/label in ip header block. This
25714 			 * is true even for a labeled system. But for
25715 			 * labeled traffic, inherit the label in the
25716 			 * new header.
25717 			 */
25718 			if (DB_CRED(mp) != NULL)
25719 				mblk_setcred(mp1, DB_CRED(mp));
25720 			/*
25721 			 * XXX disable ICK_VALID and compute checksum
25722 			 * here; can happen if nce_fp_mp changes and
25723 			 * it can't be copied now due to insufficient
25724 			 * space. (unlikely, fp mp can change, but it
25725 			 * does not increase in length)
25726 			 */
25727 		}
25728 		UNLOCK_IRE_FP_MP(ire);
25729 	} else {
25730 no_fp_mp:
25731 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25732 		if (mp1 == NULL) {
25733 unlock_err:
25734 			UNLOCK_IRE_FP_MP(ire);
25735 			freemsg(mp);
25736 			return (NULL);
25737 		}
25738 		UNLOCK_IRE_FP_MP(ire);
25739 		mp1->b_cont = mp;
25740 		/*
25741 		 * certain system generated traffic may not
25742 		 * have cred/label in ip header block. This
25743 		 * is true even for a labeled system. But for
25744 		 * labeled traffic, inherit the label in the
25745 		 * new header.
25746 		 */
25747 		if (DB_CRED(mp) != NULL)
25748 			mblk_setcred(mp1, DB_CRED(mp));
25749 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25750 			ip_process(proc, &mp1, ill_index);
25751 			if (mp1 == NULL)
25752 				return (NULL);
25753 		}
25754 	}
25755 	return (mp1);
25756 #undef rptr
25757 }
25758 
25759 /*
25760  * Finish the outbound IPsec processing for an IPv6 packet. This function
25761  * is called from ipsec_out_process() if the IPsec packet was processed
25762  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25763  * asynchronously.
25764  */
25765 void
25766 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25767     ire_t *ire_arg)
25768 {
25769 	in6_addr_t *v6dstp;
25770 	ire_t *ire;
25771 	mblk_t *mp;
25772 	ip6_t *ip6h1;
25773 	uint_t	ill_index;
25774 	ipsec_out_t *io;
25775 	boolean_t attach_if, hwaccel;
25776 	uint32_t flags = IP6_NO_IPPOLICY;
25777 	int match_flags;
25778 	zoneid_t zoneid;
25779 	boolean_t ill_need_rele = B_FALSE;
25780 	boolean_t ire_need_rele = B_FALSE;
25781 	ip_stack_t	*ipst;
25782 
25783 	mp = ipsec_mp->b_cont;
25784 	ip6h1 = (ip6_t *)mp->b_rptr;
25785 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25786 	ASSERT(io->ipsec_out_ns != NULL);
25787 	ipst = io->ipsec_out_ns->netstack_ip;
25788 	ill_index = io->ipsec_out_ill_index;
25789 	if (io->ipsec_out_reachable) {
25790 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25791 	}
25792 	attach_if = io->ipsec_out_attach_if;
25793 	hwaccel = io->ipsec_out_accelerated;
25794 	zoneid = io->ipsec_out_zoneid;
25795 	ASSERT(zoneid != ALL_ZONES);
25796 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25797 	/* Multicast addresses should have non-zero ill_index. */
25798 	v6dstp = &ip6h->ip6_dst;
25799 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25800 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25801 	ASSERT(!attach_if || ill_index != 0);
25802 	if (ill_index != 0) {
25803 		if (ill == NULL) {
25804 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25805 			    B_TRUE, ipst);
25806 
25807 			/* Failure case frees things for us. */
25808 			if (ill == NULL)
25809 				return;
25810 
25811 			ill_need_rele = B_TRUE;
25812 		}
25813 		/*
25814 		 * If this packet needs to go out on a particular interface
25815 		 * honor it.
25816 		 */
25817 		if (attach_if) {
25818 			match_flags = MATCH_IRE_ILL;
25819 
25820 			/*
25821 			 * Check if we need an ire that will not be
25822 			 * looked up by anybody else i.e. HIDDEN.
25823 			 */
25824 			if (ill_is_probeonly(ill)) {
25825 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25826 			}
25827 		}
25828 	}
25829 	ASSERT(mp != NULL);
25830 
25831 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25832 		boolean_t unspec_src;
25833 		ipif_t	*ipif;
25834 
25835 		/*
25836 		 * Use the ill_index to get the right ill.
25837 		 */
25838 		unspec_src = io->ipsec_out_unspec_src;
25839 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25840 		if (ipif == NULL) {
25841 			if (ill_need_rele)
25842 				ill_refrele(ill);
25843 			freemsg(ipsec_mp);
25844 			return;
25845 		}
25846 
25847 		if (ire_arg != NULL) {
25848 			ire = ire_arg;
25849 		} else {
25850 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25851 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25852 			ire_need_rele = B_TRUE;
25853 		}
25854 		if (ire != NULL) {
25855 			ipif_refrele(ipif);
25856 			/*
25857 			 * XXX Do the multicast forwarding now, as the IPSEC
25858 			 * processing has been done.
25859 			 */
25860 			goto send;
25861 		}
25862 
25863 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25864 		mp->b_prev = NULL;
25865 		mp->b_next = NULL;
25866 
25867 		/*
25868 		 * If the IPsec packet was processed asynchronously,
25869 		 * drop it now.
25870 		 */
25871 		if (q == NULL) {
25872 			if (ill_need_rele)
25873 				ill_refrele(ill);
25874 			freemsg(ipsec_mp);
25875 			return;
25876 		}
25877 
25878 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25879 		    unspec_src, zoneid);
25880 		ipif_refrele(ipif);
25881 	} else {
25882 		if (attach_if) {
25883 			ipif_t	*ipif;
25884 
25885 			ipif = ipif_get_next_ipif(NULL, ill);
25886 			if (ipif == NULL) {
25887 				if (ill_need_rele)
25888 					ill_refrele(ill);
25889 				freemsg(ipsec_mp);
25890 				return;
25891 			}
25892 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25893 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25894 			ire_need_rele = B_TRUE;
25895 			ipif_refrele(ipif);
25896 		} else {
25897 			if (ire_arg != NULL) {
25898 				ire = ire_arg;
25899 			} else {
25900 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25901 				    ipst);
25902 				ire_need_rele = B_TRUE;
25903 			}
25904 		}
25905 		if (ire != NULL)
25906 			goto send;
25907 		/*
25908 		 * ire disappeared underneath.
25909 		 *
25910 		 * What we need to do here is the ip_newroute
25911 		 * logic to get the ire without doing the IPSEC
25912 		 * processing. Follow the same old path. But this
25913 		 * time, ip_wput or ire_add_then_send will call us
25914 		 * directly as all the IPSEC operations are done.
25915 		 */
25916 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25917 		mp->b_prev = NULL;
25918 		mp->b_next = NULL;
25919 
25920 		/*
25921 		 * If the IPsec packet was processed asynchronously,
25922 		 * drop it now.
25923 		 */
25924 		if (q == NULL) {
25925 			if (ill_need_rele)
25926 				ill_refrele(ill);
25927 			freemsg(ipsec_mp);
25928 			return;
25929 		}
25930 
25931 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25932 		    zoneid, ipst);
25933 	}
25934 	if (ill != NULL && ill_need_rele)
25935 		ill_refrele(ill);
25936 	return;
25937 send:
25938 	if (ill != NULL && ill_need_rele)
25939 		ill_refrele(ill);
25940 
25941 	/* Local delivery */
25942 	if (ire->ire_stq == NULL) {
25943 		ill_t	*out_ill;
25944 		ASSERT(q != NULL);
25945 
25946 		/* PFHooks: LOOPBACK_OUT */
25947 		out_ill = ire->ire_ipif->ipif_ill;
25948 
25949 		DTRACE_PROBE4(ip6__loopback__out__start,
25950 		    ill_t *, NULL, ill_t *, out_ill,
25951 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25952 
25953 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25954 		    ipst->ips_ipv6firewall_loopback_out,
25955 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25956 
25957 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25958 
25959 		if (ipsec_mp != NULL)
25960 			ip_wput_local_v6(RD(q), out_ill,
25961 			    ip6h, ipsec_mp, ire, 0);
25962 		if (ire_need_rele)
25963 			ire_refrele(ire);
25964 		return;
25965 	}
25966 	/*
25967 	 * Everything is done. Send it out on the wire.
25968 	 * We force the insertion of a fragment header using the
25969 	 * IPH_FRAG_HDR flag in two cases:
25970 	 * - after reception of an ICMPv6 "packet too big" message
25971 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25972 	 * - for multirouted IPv6 packets, so that the receiver can
25973 	 *   discard duplicates according to their fragment identifier
25974 	 */
25975 	/* XXX fix flow control problems. */
25976 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25977 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25978 		if (hwaccel) {
25979 			/*
25980 			 * hardware acceleration does not handle these
25981 			 * "slow path" cases.
25982 			 */
25983 			/* IPsec KSTATS: should bump bean counter here. */
25984 			if (ire_need_rele)
25985 				ire_refrele(ire);
25986 			freemsg(ipsec_mp);
25987 			return;
25988 		}
25989 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25990 		    (mp->b_cont ? msgdsize(mp) :
25991 		    mp->b_wptr - (uchar_t *)ip6h)) {
25992 			/* IPsec KSTATS: should bump bean counter here. */
25993 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25994 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25995 			    msgdsize(mp)));
25996 			if (ire_need_rele)
25997 				ire_refrele(ire);
25998 			freemsg(ipsec_mp);
25999 			return;
26000 		}
26001 		ASSERT(mp->b_prev == NULL);
26002 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
26003 		    ntohs(ip6h->ip6_plen) +
26004 		    IPV6_HDR_LEN, ire->ire_max_frag));
26005 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
26006 		    ire->ire_max_frag);
26007 	} else {
26008 		UPDATE_OB_PKT_COUNT(ire);
26009 		ire->ire_last_used_time = lbolt;
26010 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
26011 	}
26012 	if (ire_need_rele)
26013 		ire_refrele(ire);
26014 	freeb(ipsec_mp);
26015 }
26016 
26017 void
26018 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
26019 {
26020 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
26021 	da_ipsec_t *hada;	/* data attributes */
26022 	ill_t *ill = (ill_t *)q->q_ptr;
26023 
26024 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
26025 
26026 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
26027 		/* IPsec KSTATS: Bump lose counter here! */
26028 		freemsg(mp);
26029 		return;
26030 	}
26031 
26032 	/*
26033 	 * It's an IPsec packet that must be
26034 	 * accelerated by the Provider, and the
26035 	 * outbound ill is IPsec acceleration capable.
26036 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
26037 	 * to the ill.
26038 	 * IPsec KSTATS: should bump packet counter here.
26039 	 */
26040 
26041 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
26042 	if (hada_mp == NULL) {
26043 		/* IPsec KSTATS: should bump packet counter here. */
26044 		freemsg(mp);
26045 		return;
26046 	}
26047 
26048 	hada_mp->b_datap->db_type = M_CTL;
26049 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
26050 	hada_mp->b_cont = mp;
26051 
26052 	hada = (da_ipsec_t *)hada_mp->b_rptr;
26053 	bzero(hada, sizeof (da_ipsec_t));
26054 	hada->da_type = IPHADA_M_CTL;
26055 
26056 	putnext(q, hada_mp);
26057 }
26058 
26059 /*
26060  * Finish the outbound IPsec processing. This function is called from
26061  * ipsec_out_process() if the IPsec packet was processed
26062  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
26063  * asynchronously.
26064  */
26065 void
26066 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
26067     ire_t *ire_arg)
26068 {
26069 	uint32_t v_hlen_tos_len;
26070 	ipaddr_t	dst;
26071 	ipif_t	*ipif = NULL;
26072 	ire_t *ire;
26073 	ire_t *ire1 = NULL;
26074 	mblk_t *next_mp = NULL;
26075 	uint32_t max_frag;
26076 	boolean_t multirt_send = B_FALSE;
26077 	mblk_t *mp;
26078 	mblk_t *mp1;
26079 	ipha_t *ipha1;
26080 	uint_t	ill_index;
26081 	ipsec_out_t *io;
26082 	boolean_t attach_if;
26083 	int match_flags, offset;
26084 	irb_t *irb = NULL;
26085 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
26086 	zoneid_t zoneid;
26087 	uint32_t cksum;
26088 	uint16_t *up;
26089 	ipxmit_state_t	pktxmit_state;
26090 	ip_stack_t	*ipst;
26091 
26092 #ifdef	_BIG_ENDIAN
26093 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
26094 #else
26095 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
26096 #endif
26097 
26098 	mp = ipsec_mp->b_cont;
26099 	ipha1 = (ipha_t *)mp->b_rptr;
26100 	ASSERT(mp != NULL);
26101 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
26102 	dst = ipha->ipha_dst;
26103 
26104 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26105 	ill_index = io->ipsec_out_ill_index;
26106 	attach_if = io->ipsec_out_attach_if;
26107 	zoneid = io->ipsec_out_zoneid;
26108 	ASSERT(zoneid != ALL_ZONES);
26109 	ipst = io->ipsec_out_ns->netstack_ip;
26110 	ASSERT(io->ipsec_out_ns != NULL);
26111 
26112 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
26113 	if (ill_index != 0) {
26114 		if (ill == NULL) {
26115 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
26116 			    ill_index, B_FALSE, ipst);
26117 
26118 			/* Failure case frees things for us. */
26119 			if (ill == NULL)
26120 				return;
26121 
26122 			ill_need_rele = B_TRUE;
26123 		}
26124 		/*
26125 		 * If this packet needs to go out on a particular interface
26126 		 * honor it.
26127 		 */
26128 		if (attach_if) {
26129 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
26130 
26131 			/*
26132 			 * Check if we need an ire that will not be
26133 			 * looked up by anybody else i.e. HIDDEN.
26134 			 */
26135 			if (ill_is_probeonly(ill)) {
26136 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26137 			}
26138 		}
26139 	}
26140 
26141 	if (CLASSD(dst)) {
26142 		boolean_t conn_dontroute;
26143 		/*
26144 		 * Use the ill_index to get the right ipif.
26145 		 */
26146 		conn_dontroute = io->ipsec_out_dontroute;
26147 		if (ill_index == 0)
26148 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26149 		else
26150 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26151 		if (ipif == NULL) {
26152 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26153 			    " multicast\n"));
26154 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26155 			freemsg(ipsec_mp);
26156 			goto done;
26157 		}
26158 		/*
26159 		 * ipha_src has already been intialized with the
26160 		 * value of the ipif in ip_wput. All we need now is
26161 		 * an ire to send this downstream.
26162 		 */
26163 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26164 		    MBLK_GETLABEL(mp), match_flags, ipst);
26165 		if (ire != NULL) {
26166 			ill_t *ill1;
26167 			/*
26168 			 * Do the multicast forwarding now, as the IPSEC
26169 			 * processing has been done.
26170 			 */
26171 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26172 			    (ill1 = ire_to_ill(ire))) {
26173 				if (ip_mforward(ill1, ipha, mp)) {
26174 					freemsg(ipsec_mp);
26175 					ip1dbg(("ip_wput_ipsec_out: mforward "
26176 					    "failed\n"));
26177 					ire_refrele(ire);
26178 					goto done;
26179 				}
26180 			}
26181 			goto send;
26182 		}
26183 
26184 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26185 		mp->b_prev = NULL;
26186 		mp->b_next = NULL;
26187 
26188 		/*
26189 		 * If the IPsec packet was processed asynchronously,
26190 		 * drop it now.
26191 		 */
26192 		if (q == NULL) {
26193 			freemsg(ipsec_mp);
26194 			goto done;
26195 		}
26196 
26197 		/*
26198 		 * We may be using a wrong ipif to create the ire.
26199 		 * But it is okay as the source address is assigned
26200 		 * for the packet already. Next outbound packet would
26201 		 * create the IRE with the right IPIF in ip_wput.
26202 		 *
26203 		 * Also handle RTF_MULTIRT routes.
26204 		 */
26205 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26206 		    zoneid, &zero_info);
26207 	} else {
26208 		if (attach_if) {
26209 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26210 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26211 		} else {
26212 			if (ire_arg != NULL) {
26213 				ire = ire_arg;
26214 				ire_need_rele = B_FALSE;
26215 			} else {
26216 				ire = ire_cache_lookup(dst, zoneid,
26217 				    MBLK_GETLABEL(mp), ipst);
26218 			}
26219 		}
26220 		if (ire != NULL) {
26221 			goto send;
26222 		}
26223 
26224 		/*
26225 		 * ire disappeared underneath.
26226 		 *
26227 		 * What we need to do here is the ip_newroute
26228 		 * logic to get the ire without doing the IPSEC
26229 		 * processing. Follow the same old path. But this
26230 		 * time, ip_wput or ire_add_then_put will call us
26231 		 * directly as all the IPSEC operations are done.
26232 		 */
26233 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26234 		mp->b_prev = NULL;
26235 		mp->b_next = NULL;
26236 
26237 		/*
26238 		 * If the IPsec packet was processed asynchronously,
26239 		 * drop it now.
26240 		 */
26241 		if (q == NULL) {
26242 			freemsg(ipsec_mp);
26243 			goto done;
26244 		}
26245 
26246 		/*
26247 		 * Since we're going through ip_newroute() again, we
26248 		 * need to make sure we don't:
26249 		 *
26250 		 *	1.) Trigger the ASSERT() with the ipha_ident
26251 		 *	    overloading.
26252 		 *	2.) Redo transport-layer checksumming, since we've
26253 		 *	    already done all that to get this far.
26254 		 *
26255 		 * The easiest way not do either of the above is to set
26256 		 * the ipha_ident field to IP_HDR_INCLUDED.
26257 		 */
26258 		ipha->ipha_ident = IP_HDR_INCLUDED;
26259 		ip_newroute(q, ipsec_mp, dst, NULL,
26260 		    (CONN_Q(q) ? Q_TO_CONN(q) : NULL), zoneid, ipst);
26261 	}
26262 	goto done;
26263 send:
26264 	if (ipha->ipha_protocol == IPPROTO_UDP &&
26265 	    udp_compute_checksum(ipst->ips_netstack)) {
26266 		/*
26267 		 * ESP NAT-Traversal packet.
26268 		 *
26269 		 * Just do software checksum for now.
26270 		 */
26271 
26272 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
26273 		IP_STAT(ipst, ip_out_sw_cksum);
26274 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
26275 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
26276 #define	iphs	((uint16_t *)ipha)
26277 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
26278 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
26279 		    IP_SIMPLE_HDR_LENGTH);
26280 #undef iphs
26281 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
26282 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
26283 			if (mp1->b_wptr - mp1->b_rptr >=
26284 			    offset + sizeof (uint16_t)) {
26285 				up = (uint16_t *)(mp1->b_rptr + offset);
26286 				*up = cksum;
26287 				break;	/* out of for loop */
26288 			} else {
26289 				offset -= (mp->b_wptr - mp->b_rptr);
26290 			}
26291 	} /* Otherwise, just keep the all-zero checksum. */
26292 
26293 	if (ire->ire_stq == NULL) {
26294 		ill_t	*out_ill;
26295 		/*
26296 		 * Loopbacks go through ip_wput_local except for one case.
26297 		 * We come here if we generate a icmp_frag_needed message
26298 		 * after IPSEC processing is over. When this function calls
26299 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26300 		 * icmp_frag_needed. The message generated comes back here
26301 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26302 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26303 		 * source address as it is usually set in ip_wput_ire. As
26304 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26305 		 * and we end up here. We can't enter ip_wput_ire once the
26306 		 * IPSEC processing is over and hence we need to do it here.
26307 		 */
26308 		ASSERT(q != NULL);
26309 		UPDATE_OB_PKT_COUNT(ire);
26310 		ire->ire_last_used_time = lbolt;
26311 		if (ipha->ipha_src == 0)
26312 			ipha->ipha_src = ire->ire_src_addr;
26313 
26314 		/* PFHooks: LOOPBACK_OUT */
26315 		out_ill = ire->ire_ipif->ipif_ill;
26316 
26317 		DTRACE_PROBE4(ip4__loopback__out__start,
26318 		    ill_t *, NULL, ill_t *, out_ill,
26319 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26320 
26321 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26322 		    ipst->ips_ipv4firewall_loopback_out,
26323 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26324 
26325 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26326 
26327 		if (ipsec_mp != NULL)
26328 			ip_wput_local(RD(q), out_ill,
26329 			    ipha, ipsec_mp, ire, 0, zoneid);
26330 		if (ire_need_rele)
26331 			ire_refrele(ire);
26332 		goto done;
26333 	}
26334 
26335 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26336 		/*
26337 		 * We are through with IPSEC processing.
26338 		 * Fragment this and send it on the wire.
26339 		 */
26340 		if (io->ipsec_out_accelerated) {
26341 			/*
26342 			 * The packet has been accelerated but must
26343 			 * be fragmented. This should not happen
26344 			 * since AH and ESP must not accelerate
26345 			 * packets that need fragmentation, however
26346 			 * the configuration could have changed
26347 			 * since the AH or ESP processing.
26348 			 * Drop packet.
26349 			 * IPsec KSTATS: bump bean counter here.
26350 			 */
26351 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26352 			    "fragmented accelerated packet!\n"));
26353 			freemsg(ipsec_mp);
26354 		} else {
26355 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26356 		}
26357 		if (ire_need_rele)
26358 			ire_refrele(ire);
26359 		goto done;
26360 	}
26361 
26362 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26363 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26364 	    (void *)ire->ire_ipif, (void *)ipif));
26365 
26366 	/*
26367 	 * Multiroute the secured packet, unless IPsec really
26368 	 * requires the packet to go out only through a particular
26369 	 * interface.
26370 	 */
26371 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26372 		ire_t *first_ire;
26373 		irb = ire->ire_bucket;
26374 		ASSERT(irb != NULL);
26375 		/*
26376 		 * This ire has been looked up as the one that
26377 		 * goes through the given ipif;
26378 		 * make sure we do not omit any other multiroute ire
26379 		 * that may be present in the bucket before this one.
26380 		 */
26381 		IRB_REFHOLD(irb);
26382 		for (first_ire = irb->irb_ire;
26383 		    first_ire != NULL;
26384 		    first_ire = first_ire->ire_next) {
26385 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26386 			    (first_ire->ire_addr == ire->ire_addr) &&
26387 			    !(first_ire->ire_marks &
26388 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26389 				break;
26390 			}
26391 		}
26392 
26393 		if ((first_ire != NULL) && (first_ire != ire)) {
26394 			/*
26395 			 * Don't change the ire if the packet must
26396 			 * be fragmented if sent via this new one.
26397 			 */
26398 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26399 				IRE_REFHOLD(first_ire);
26400 				if (ire_need_rele)
26401 					ire_refrele(ire);
26402 				else
26403 					ire_need_rele = B_TRUE;
26404 				ire = first_ire;
26405 			}
26406 		}
26407 		IRB_REFRELE(irb);
26408 
26409 		multirt_send = B_TRUE;
26410 		max_frag = ire->ire_max_frag;
26411 	} else {
26412 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26413 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26414 			    "flag, attach_if %d\n", attach_if));
26415 		}
26416 	}
26417 
26418 	/*
26419 	 * In most cases, the emission loop below is entered only once.
26420 	 * Only in the case where the ire holds the RTF_MULTIRT
26421 	 * flag, we loop to process all RTF_MULTIRT ires in the
26422 	 * bucket, and send the packet through all crossed
26423 	 * RTF_MULTIRT routes.
26424 	 */
26425 	do {
26426 		if (multirt_send) {
26427 			/*
26428 			 * ire1 holds here the next ire to process in the
26429 			 * bucket. If multirouting is expected,
26430 			 * any non-RTF_MULTIRT ire that has the
26431 			 * right destination address is ignored.
26432 			 */
26433 			ASSERT(irb != NULL);
26434 			IRB_REFHOLD(irb);
26435 			for (ire1 = ire->ire_next;
26436 			    ire1 != NULL;
26437 			    ire1 = ire1->ire_next) {
26438 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26439 					continue;
26440 				if (ire1->ire_addr != ire->ire_addr)
26441 					continue;
26442 				if (ire1->ire_marks &
26443 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26444 					continue;
26445 				/* No loopback here */
26446 				if (ire1->ire_stq == NULL)
26447 					continue;
26448 				/*
26449 				 * Ensure we do not exceed the MTU
26450 				 * of the next route.
26451 				 */
26452 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26453 					ip_multirt_bad_mtu(ire1, max_frag);
26454 					continue;
26455 				}
26456 
26457 				IRE_REFHOLD(ire1);
26458 				break;
26459 			}
26460 			IRB_REFRELE(irb);
26461 			if (ire1 != NULL) {
26462 				/*
26463 				 * We are in a multiple send case, need to
26464 				 * make a copy of the packet.
26465 				 */
26466 				next_mp = copymsg(ipsec_mp);
26467 				if (next_mp == NULL) {
26468 					ire_refrele(ire1);
26469 					ire1 = NULL;
26470 				}
26471 			}
26472 		}
26473 		/*
26474 		 * Everything is done. Send it out on the wire
26475 		 *
26476 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26477 		 * either send it on the wire or, in the case of
26478 		 * HW acceleration, call ipsec_hw_putnext.
26479 		 */
26480 		if (ire->ire_nce &&
26481 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26482 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26483 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26484 			/*
26485 			 * If ire's link-layer is unresolved (this
26486 			 * would only happen if the incomplete ire
26487 			 * was added to cachetable via forwarding path)
26488 			 * don't bother going to ip_xmit_v4. Just drop the
26489 			 * packet.
26490 			 * There is a slight risk here, in that, if we
26491 			 * have the forwarding path create an incomplete
26492 			 * IRE, then until the IRE is completed, any
26493 			 * transmitted IPSEC packets will be dropped
26494 			 * instead of being queued waiting for resolution.
26495 			 *
26496 			 * But the likelihood of a forwarding packet and a wput
26497 			 * packet sending to the same dst at the same time
26498 			 * and there not yet be an ARP entry for it is small.
26499 			 * Furthermore, if this actually happens, it might
26500 			 * be likely that wput would generate multiple
26501 			 * packets (and forwarding would also have a train
26502 			 * of packets) for that destination. If this is
26503 			 * the case, some of them would have been dropped
26504 			 * anyway, since ARP only queues a few packets while
26505 			 * waiting for resolution
26506 			 *
26507 			 * NOTE: We should really call ip_xmit_v4,
26508 			 * and let it queue the packet and send the
26509 			 * ARP query and have ARP come back thus:
26510 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26511 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26512 			 * hw accel work. But it's too complex to get
26513 			 * the IPsec hw  acceleration approach to fit
26514 			 * well with ip_xmit_v4 doing ARP without
26515 			 * doing IPSEC simplification. For now, we just
26516 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26517 			 * that we can continue with the send on the next
26518 			 * attempt.
26519 			 *
26520 			 * XXX THis should be revisited, when
26521 			 * the IPsec/IP interaction is cleaned up
26522 			 */
26523 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26524 			    " - dropping packet\n"));
26525 			freemsg(ipsec_mp);
26526 			/*
26527 			 * Call ip_xmit_v4() to trigger ARP query
26528 			 * in case the nce_state is ND_INITIAL
26529 			 */
26530 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26531 			goto drop_pkt;
26532 		}
26533 
26534 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26535 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26536 		    mblk_t *, ipsec_mp);
26537 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26538 		    ipst->ips_ipv4firewall_physical_out,
26539 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26540 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26541 		if (ipsec_mp == NULL)
26542 			goto drop_pkt;
26543 
26544 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26545 		pktxmit_state = ip_xmit_v4(mp, ire,
26546 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26547 
26548 		if ((pktxmit_state ==  SEND_FAILED) ||
26549 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26550 
26551 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26552 drop_pkt:
26553 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26554 			    ipIfStatsOutDiscards);
26555 			if (ire_need_rele)
26556 				ire_refrele(ire);
26557 			if (ire1 != NULL) {
26558 				ire_refrele(ire1);
26559 				freemsg(next_mp);
26560 			}
26561 			goto done;
26562 		}
26563 
26564 		freeb(ipsec_mp);
26565 		if (ire_need_rele)
26566 			ire_refrele(ire);
26567 
26568 		if (ire1 != NULL) {
26569 			ire = ire1;
26570 			ire_need_rele = B_TRUE;
26571 			ASSERT(next_mp);
26572 			ipsec_mp = next_mp;
26573 			mp = ipsec_mp->b_cont;
26574 			ire1 = NULL;
26575 			next_mp = NULL;
26576 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26577 		} else {
26578 			multirt_send = B_FALSE;
26579 		}
26580 	} while (multirt_send);
26581 done:
26582 	if (ill != NULL && ill_need_rele)
26583 		ill_refrele(ill);
26584 	if (ipif != NULL)
26585 		ipif_refrele(ipif);
26586 }
26587 
26588 /*
26589  * Get the ill corresponding to the specified ire, and compare its
26590  * capabilities with the protocol and algorithms specified by the
26591  * the SA obtained from ipsec_out. If they match, annotate the
26592  * ipsec_out structure to indicate that the packet needs acceleration.
26593  *
26594  *
26595  * A packet is eligible for outbound hardware acceleration if the
26596  * following conditions are satisfied:
26597  *
26598  * 1. the packet will not be fragmented
26599  * 2. the provider supports the algorithm
26600  * 3. there is no pending control message being exchanged
26601  * 4. snoop is not attached
26602  * 5. the destination address is not a broadcast or multicast address.
26603  *
26604  * Rationale:
26605  *	- Hardware drivers do not support fragmentation with
26606  *	  the current interface.
26607  *	- snoop, multicast, and broadcast may result in exposure of
26608  *	  a cleartext datagram.
26609  * We check all five of these conditions here.
26610  *
26611  * XXX would like to nuke "ire_t *" parameter here; problem is that
26612  * IRE is only way to figure out if a v4 address is a broadcast and
26613  * thus ineligible for acceleration...
26614  */
26615 static void
26616 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26617 {
26618 	ipsec_out_t *io;
26619 	mblk_t *data_mp;
26620 	uint_t plen, overhead;
26621 	ip_stack_t	*ipst;
26622 
26623 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26624 		return;
26625 
26626 	if (ill == NULL)
26627 		return;
26628 	ipst = ill->ill_ipst;
26629 	/*
26630 	 * Destination address is a broadcast or multicast.  Punt.
26631 	 */
26632 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26633 	    IRE_LOCAL)))
26634 		return;
26635 
26636 	data_mp = ipsec_mp->b_cont;
26637 
26638 	if (ill->ill_isv6) {
26639 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26640 
26641 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26642 			return;
26643 
26644 		plen = ip6h->ip6_plen;
26645 	} else {
26646 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26647 
26648 		if (CLASSD(ipha->ipha_dst))
26649 			return;
26650 
26651 		plen = ipha->ipha_length;
26652 	}
26653 	/*
26654 	 * Is there a pending DLPI control message being exchanged
26655 	 * between IP/IPsec and the DLS Provider? If there is, it
26656 	 * could be a SADB update, and the state of the DLS Provider
26657 	 * SADB might not be in sync with the SADB maintained by
26658 	 * IPsec. To avoid dropping packets or using the wrong keying
26659 	 * material, we do not accelerate this packet.
26660 	 */
26661 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26662 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26663 		    "ill_dlpi_pending! don't accelerate packet\n"));
26664 		return;
26665 	}
26666 
26667 	/*
26668 	 * Is the Provider in promiscous mode? If it does, we don't
26669 	 * accelerate the packet since it will bounce back up to the
26670 	 * listeners in the clear.
26671 	 */
26672 	if (ill->ill_promisc_on_phys) {
26673 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26674 		    "ill in promiscous mode, don't accelerate packet\n"));
26675 		return;
26676 	}
26677 
26678 	/*
26679 	 * Will the packet require fragmentation?
26680 	 */
26681 
26682 	/*
26683 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26684 	 * as is used elsewhere.
26685 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26686 	 *	+ 2-byte trailer
26687 	 */
26688 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26689 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26690 
26691 	if ((plen + overhead) > ill->ill_max_mtu)
26692 		return;
26693 
26694 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26695 
26696 	/*
26697 	 * Can the ill accelerate this IPsec protocol and algorithm
26698 	 * specified by the SA?
26699 	 */
26700 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26701 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26702 		return;
26703 	}
26704 
26705 	/*
26706 	 * Tell AH or ESP that the outbound ill is capable of
26707 	 * accelerating this packet.
26708 	 */
26709 	io->ipsec_out_is_capab_ill = B_TRUE;
26710 }
26711 
26712 /*
26713  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26714  *
26715  * If this function returns B_TRUE, the requested SA's have been filled
26716  * into the ipsec_out_*_sa pointers.
26717  *
26718  * If the function returns B_FALSE, the packet has been "consumed", most
26719  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26720  *
26721  * The SA references created by the protocol-specific "select"
26722  * function will be released when the ipsec_mp is freed, thanks to the
26723  * ipsec_out_free destructor -- see spd.c.
26724  */
26725 static boolean_t
26726 ipsec_out_select_sa(mblk_t *ipsec_mp)
26727 {
26728 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26729 	ipsec_out_t *io;
26730 	ipsec_policy_t *pp;
26731 	ipsec_action_t *ap;
26732 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26733 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26734 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26735 
26736 	if (!io->ipsec_out_secure) {
26737 		/*
26738 		 * We came here by mistake.
26739 		 * Don't bother with ipsec processing
26740 		 * We should "discourage" this path in the future.
26741 		 */
26742 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26743 		return (B_FALSE);
26744 	}
26745 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26746 	ASSERT((io->ipsec_out_policy != NULL) ||
26747 	    (io->ipsec_out_act != NULL));
26748 
26749 	ASSERT(io->ipsec_out_failed == B_FALSE);
26750 
26751 	/*
26752 	 * IPSEC processing has started.
26753 	 */
26754 	io->ipsec_out_proc_begin = B_TRUE;
26755 	ap = io->ipsec_out_act;
26756 	if (ap == NULL) {
26757 		pp = io->ipsec_out_policy;
26758 		ASSERT(pp != NULL);
26759 		ap = pp->ipsp_act;
26760 		ASSERT(ap != NULL);
26761 	}
26762 
26763 	/*
26764 	 * We have an action.  now, let's select SA's.
26765 	 * (In the future, we can cache this in the conn_t..)
26766 	 */
26767 	if (ap->ipa_want_esp) {
26768 		if (io->ipsec_out_esp_sa == NULL) {
26769 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26770 			    IPPROTO_ESP);
26771 		}
26772 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26773 	}
26774 
26775 	if (ap->ipa_want_ah) {
26776 		if (io->ipsec_out_ah_sa == NULL) {
26777 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26778 			    IPPROTO_AH);
26779 		}
26780 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26781 		/*
26782 		 * The ESP and AH processing order needs to be preserved
26783 		 * when both protocols are required (ESP should be applied
26784 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26785 		 * when both ESP and AH are required, and an AH ACQUIRE
26786 		 * is needed.
26787 		 */
26788 		if (ap->ipa_want_esp && need_ah_acquire)
26789 			need_esp_acquire = B_TRUE;
26790 	}
26791 
26792 	/*
26793 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26794 	 * Release SAs that got referenced, but will not be used until we
26795 	 * acquire _all_ of the SAs we need.
26796 	 */
26797 	if (need_ah_acquire || need_esp_acquire) {
26798 		if (io->ipsec_out_ah_sa != NULL) {
26799 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26800 			io->ipsec_out_ah_sa = NULL;
26801 		}
26802 		if (io->ipsec_out_esp_sa != NULL) {
26803 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26804 			io->ipsec_out_esp_sa = NULL;
26805 		}
26806 
26807 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26808 		return (B_FALSE);
26809 	}
26810 
26811 	return (B_TRUE);
26812 }
26813 
26814 /*
26815  * Process an IPSEC_OUT message and see what you can
26816  * do with it.
26817  * IPQoS Notes:
26818  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26819  * IPSec.
26820  * XXX would like to nuke ire_t.
26821  * XXX ill_index better be "real"
26822  */
26823 void
26824 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26825 {
26826 	ipsec_out_t *io;
26827 	ipsec_policy_t *pp;
26828 	ipsec_action_t *ap;
26829 	ipha_t *ipha;
26830 	ip6_t *ip6h;
26831 	mblk_t *mp;
26832 	ill_t *ill;
26833 	zoneid_t zoneid;
26834 	ipsec_status_t ipsec_rc;
26835 	boolean_t ill_need_rele = B_FALSE;
26836 	ip_stack_t	*ipst;
26837 	ipsec_stack_t	*ipss;
26838 
26839 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26840 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26841 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26842 	ipst = io->ipsec_out_ns->netstack_ip;
26843 	mp = ipsec_mp->b_cont;
26844 
26845 	/*
26846 	 * Initiate IPPF processing. We do it here to account for packets
26847 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26848 	 * We can check for ipsec_out_proc_begin even for such packets, as
26849 	 * they will always be false (asserted below).
26850 	 */
26851 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26852 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26853 		    io->ipsec_out_ill_index : ill_index);
26854 		if (mp == NULL) {
26855 			ip2dbg(("ipsec_out_process: packet dropped "\
26856 			    "during IPPF processing\n"));
26857 			freeb(ipsec_mp);
26858 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26859 			return;
26860 		}
26861 	}
26862 
26863 	if (!io->ipsec_out_secure) {
26864 		/*
26865 		 * We came here by mistake.
26866 		 * Don't bother with ipsec processing
26867 		 * Should "discourage" this path in the future.
26868 		 */
26869 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26870 		goto done;
26871 	}
26872 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26873 	ASSERT((io->ipsec_out_policy != NULL) ||
26874 	    (io->ipsec_out_act != NULL));
26875 	ASSERT(io->ipsec_out_failed == B_FALSE);
26876 
26877 	ipss = ipst->ips_netstack->netstack_ipsec;
26878 	if (!ipsec_loaded(ipss)) {
26879 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26880 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26881 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26882 		} else {
26883 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26884 		}
26885 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26886 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26887 		    &ipss->ipsec_dropper);
26888 		return;
26889 	}
26890 
26891 	/*
26892 	 * IPSEC processing has started.
26893 	 */
26894 	io->ipsec_out_proc_begin = B_TRUE;
26895 	ap = io->ipsec_out_act;
26896 	if (ap == NULL) {
26897 		pp = io->ipsec_out_policy;
26898 		ASSERT(pp != NULL);
26899 		ap = pp->ipsp_act;
26900 		ASSERT(ap != NULL);
26901 	}
26902 
26903 	/*
26904 	 * Save the outbound ill index. When the packet comes back
26905 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26906 	 * before sending it the accelerated packet.
26907 	 */
26908 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26909 		int ifindex;
26910 		ill = ire_to_ill(ire);
26911 		ifindex = ill->ill_phyint->phyint_ifindex;
26912 		io->ipsec_out_capab_ill_index = ifindex;
26913 	}
26914 
26915 	/*
26916 	 * The order of processing is first insert a IP header if needed.
26917 	 * Then insert the ESP header and then the AH header.
26918 	 */
26919 	if ((io->ipsec_out_se_done == B_FALSE) &&
26920 	    (ap->ipa_want_se)) {
26921 		/*
26922 		 * First get the outer IP header before sending
26923 		 * it to ESP.
26924 		 */
26925 		ipha_t *oipha, *iipha;
26926 		mblk_t *outer_mp, *inner_mp;
26927 
26928 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26929 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26930 			    "ipsec_out_process: "
26931 			    "Self-Encapsulation failed: Out of memory\n");
26932 			freemsg(ipsec_mp);
26933 			if (ill != NULL) {
26934 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26935 			} else {
26936 				BUMP_MIB(&ipst->ips_ip_mib,
26937 				    ipIfStatsOutDiscards);
26938 			}
26939 			return;
26940 		}
26941 		inner_mp = ipsec_mp->b_cont;
26942 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26943 		oipha = (ipha_t *)outer_mp->b_rptr;
26944 		iipha = (ipha_t *)inner_mp->b_rptr;
26945 		*oipha = *iipha;
26946 		outer_mp->b_wptr += sizeof (ipha_t);
26947 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26948 		    sizeof (ipha_t));
26949 		oipha->ipha_protocol = IPPROTO_ENCAP;
26950 		oipha->ipha_version_and_hdr_length =
26951 		    IP_SIMPLE_HDR_VERSION;
26952 		oipha->ipha_hdr_checksum = 0;
26953 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26954 		outer_mp->b_cont = inner_mp;
26955 		ipsec_mp->b_cont = outer_mp;
26956 
26957 		io->ipsec_out_se_done = B_TRUE;
26958 		io->ipsec_out_tunnel = B_TRUE;
26959 	}
26960 
26961 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26962 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26963 	    !ipsec_out_select_sa(ipsec_mp))
26964 		return;
26965 
26966 	/*
26967 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26968 	 * to do the heavy lifting.
26969 	 */
26970 	zoneid = io->ipsec_out_zoneid;
26971 	ASSERT(zoneid != ALL_ZONES);
26972 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26973 		ASSERT(io->ipsec_out_esp_sa != NULL);
26974 		io->ipsec_out_esp_done = B_TRUE;
26975 		/*
26976 		 * Note that since hw accel can only apply one transform,
26977 		 * not two, we skip hw accel for ESP if we also have AH
26978 		 * This is an design limitation of the interface
26979 		 * which should be revisited.
26980 		 */
26981 		ASSERT(ire != NULL);
26982 		if (io->ipsec_out_ah_sa == NULL) {
26983 			ill = (ill_t *)ire->ire_stq->q_ptr;
26984 			ipsec_out_is_accelerated(ipsec_mp,
26985 			    io->ipsec_out_esp_sa, ill, ire);
26986 		}
26987 
26988 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26989 		switch (ipsec_rc) {
26990 		case IPSEC_STATUS_SUCCESS:
26991 			break;
26992 		case IPSEC_STATUS_FAILED:
26993 			if (ill != NULL) {
26994 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26995 			} else {
26996 				BUMP_MIB(&ipst->ips_ip_mib,
26997 				    ipIfStatsOutDiscards);
26998 			}
26999 			/* FALLTHRU */
27000 		case IPSEC_STATUS_PENDING:
27001 			return;
27002 		}
27003 	}
27004 
27005 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
27006 		ASSERT(io->ipsec_out_ah_sa != NULL);
27007 		io->ipsec_out_ah_done = B_TRUE;
27008 		if (ire == NULL) {
27009 			int idx = io->ipsec_out_capab_ill_index;
27010 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
27011 			    NULL, NULL, NULL, NULL, ipst);
27012 			ill_need_rele = B_TRUE;
27013 		} else {
27014 			ill = (ill_t *)ire->ire_stq->q_ptr;
27015 		}
27016 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
27017 		    ire);
27018 
27019 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
27020 		switch (ipsec_rc) {
27021 		case IPSEC_STATUS_SUCCESS:
27022 			break;
27023 		case IPSEC_STATUS_FAILED:
27024 			if (ill != NULL) {
27025 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
27026 			} else {
27027 				BUMP_MIB(&ipst->ips_ip_mib,
27028 				    ipIfStatsOutDiscards);
27029 			}
27030 			/* FALLTHRU */
27031 		case IPSEC_STATUS_PENDING:
27032 			if (ill != NULL && ill_need_rele)
27033 				ill_refrele(ill);
27034 			return;
27035 		}
27036 	}
27037 	/*
27038 	 * We are done with IPSEC processing. Send it over
27039 	 * the wire.
27040 	 */
27041 done:
27042 	mp = ipsec_mp->b_cont;
27043 	ipha = (ipha_t *)mp->b_rptr;
27044 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
27045 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
27046 	} else {
27047 		ip6h = (ip6_t *)ipha;
27048 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
27049 	}
27050 	if (ill != NULL && ill_need_rele)
27051 		ill_refrele(ill);
27052 }
27053 
27054 /* ARGSUSED */
27055 void
27056 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
27057 {
27058 	opt_restart_t	*or;
27059 	int	err;
27060 	conn_t	*connp;
27061 
27062 	ASSERT(CONN_Q(q));
27063 	connp = Q_TO_CONN(q);
27064 
27065 	ASSERT(first_mp->b_datap->db_type == M_CTL);
27066 	or = (opt_restart_t *)first_mp->b_rptr;
27067 	/*
27068 	 * We don't need to pass any credentials here since this is just
27069 	 * a restart. The credentials are passed in when svr4_optcom_req
27070 	 * is called the first time (from ip_wput_nondata).
27071 	 */
27072 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
27073 		err = svr4_optcom_req(q, first_mp, NULL,
27074 		    &ip_opt_obj);
27075 	} else {
27076 		ASSERT(or->or_type == T_OPTMGMT_REQ);
27077 		err = tpi_optcom_req(q, first_mp, NULL,
27078 		    &ip_opt_obj);
27079 	}
27080 	if (err != EINPROGRESS) {
27081 		/* operation is done */
27082 		CONN_OPER_PENDING_DONE(connp);
27083 	}
27084 }
27085 
27086 /*
27087  * ioctls that go through a down/up sequence may need to wait for the down
27088  * to complete. This involves waiting for the ire and ipif refcnts to go down
27089  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
27090  */
27091 /* ARGSUSED */
27092 void
27093 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27094 {
27095 	struct iocblk *iocp;
27096 	mblk_t *mp1;
27097 	ip_ioctl_cmd_t *ipip;
27098 	int err;
27099 	sin_t	*sin;
27100 	struct lifreq *lifr;
27101 	struct ifreq *ifr;
27102 
27103 	iocp = (struct iocblk *)mp->b_rptr;
27104 	ASSERT(ipsq != NULL);
27105 	/* Existence of mp1 verified in ip_wput_nondata */
27106 	mp1 = mp->b_cont->b_cont;
27107 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27108 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
27109 		/*
27110 		 * Special case where ipsq_current_ipif is not set:
27111 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
27112 		 * ill could also have become part of a ipmp group in the
27113 		 * process, we are here as were not able to complete the
27114 		 * operation in ipif_set_values because we could not become
27115 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
27116 		 * will not be set so we need to set it.
27117 		 */
27118 		ill_t *ill = q->q_ptr;
27119 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
27120 	}
27121 	ASSERT(ipsq->ipsq_current_ipif != NULL);
27122 
27123 	if (ipip->ipi_cmd_type == IF_CMD) {
27124 		/* This a old style SIOC[GS]IF* command */
27125 		ifr = (struct ifreq *)mp1->b_rptr;
27126 		sin = (sin_t *)&ifr->ifr_addr;
27127 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
27128 		/* This a new style SIOC[GS]LIF* command */
27129 		lifr = (struct lifreq *)mp1->b_rptr;
27130 		sin = (sin_t *)&lifr->lifr_addr;
27131 	} else {
27132 		sin = NULL;
27133 	}
27134 
27135 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
27136 	    ipip, mp1->b_rptr);
27137 
27138 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27139 }
27140 
27141 /*
27142  * ioctl processing
27143  *
27144  * ioctl processing starts with ip_sioctl_copyin_setup which looks up
27145  * the ioctl command in the ioctl tables and determines the copyin data size
27146  * from the ioctl property ipi_copyin_size, and does an mi_copyin() of that
27147  * size.
27148  *
27149  * ioctl processing then continues when the M_IOCDATA makes its way down.
27150  * Now the ioctl is looked up again in the ioctl table, and its properties are
27151  * extracted. The associated 'conn' is then refheld till the end of the ioctl
27152  * and the general ioctl processing function ip_process_ioctl is called.
27153  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27154  * so goes thru the serialization primitive ipsq_try_enter. Then the
27155  * appropriate function to handle the ioctl is called based on the entry in
27156  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27157  * which also refreleases the 'conn' that was refheld at the start of the
27158  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27159  * ip_extract_lifreq_cmn extracts the interface name from the lifreq/ifreq
27160  * struct and looks up the ipif. ip_extract_tunreq handles the case of tunnel.
27161  *
27162  * Many exclusive ioctls go thru an internal down up sequence as part of
27163  * the operation. For example an attempt to change the IP address of an
27164  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27165  * does all the cleanup such as deleting all ires that use this address.
27166  * Then we need to wait till all references to the interface go away.
27167  */
27168 void
27169 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27170 {
27171 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27172 	ip_ioctl_cmd_t *ipip = (ip_ioctl_cmd_t *)arg;
27173 	cmd_info_t ci;
27174 	int err;
27175 	boolean_t entered_ipsq = B_FALSE;
27176 
27177 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27178 
27179 	if (ipip == NULL)
27180 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27181 
27182 	/*
27183 	 * SIOCLIFADDIF needs to go thru a special path since the
27184 	 * ill may not exist yet. This happens in the case of lo0
27185 	 * which is created using this ioctl.
27186 	 */
27187 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27188 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27189 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27190 		return;
27191 	}
27192 
27193 	ci.ci_ipif = NULL;
27194 	switch (ipip->ipi_cmd_type) {
27195 	case IF_CMD:
27196 	case LIF_CMD:
27197 		/*
27198 		 * ioctls that pass in a [l]ifreq appear here.
27199 		 * ip_extract_lifreq_cmn returns a refheld ipif in
27200 		 * ci.ci_ipif
27201 		 */
27202 		err = ip_extract_lifreq_cmn(q, mp, ipip->ipi_cmd_type,
27203 		    ipip->ipi_flags, &ci, ip_process_ioctl);
27204 		if (err != 0) {
27205 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27206 			return;
27207 		}
27208 		ASSERT(ci.ci_ipif != NULL);
27209 		break;
27210 
27211 	case TUN_CMD:
27212 		/*
27213 		 * SIOC[GS]TUNPARAM appear here. ip_extract_tunreq returns
27214 		 * a refheld ipif in ci.ci_ipif
27215 		 */
27216 		err = ip_extract_tunreq(q, mp, &ci.ci_ipif, ip_process_ioctl);
27217 		if (err != 0) {
27218 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27219 			return;
27220 		}
27221 		ASSERT(ci.ci_ipif != NULL);
27222 		break;
27223 
27224 	case MISC_CMD:
27225 		/*
27226 		 * ioctls that neither pass in [l]ifreq or iftun_req come here
27227 		 * For eg. SIOCGLIFCONF will appear here.
27228 		 */
27229 		switch (ipip->ipi_cmd) {
27230 		case IF_UNITSEL:
27231 			/* ioctl comes down the ill */
27232 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27233 			ipif_refhold(ci.ci_ipif);
27234 			break;
27235 		case SIOCGMSFILTER:
27236 		case SIOCSMSFILTER:
27237 		case SIOCGIPMSFILTER:
27238 		case SIOCSIPMSFILTER:
27239 			err = ip_extract_msfilter(q, mp, &ci.ci_ipif,
27240 			    ip_process_ioctl);
27241 			if (err != 0) {
27242 				ip_ioctl_finish(q, mp, err, IPI2MODE(ipip),
27243 				    NULL);
27244 			}
27245 			break;
27246 		}
27247 		err = 0;
27248 		ci.ci_sin = NULL;
27249 		ci.ci_sin6 = NULL;
27250 		ci.ci_lifr = NULL;
27251 		break;
27252 	}
27253 
27254 	/*
27255 	 * If ipsq is non-null, we are already being called exclusively
27256 	 */
27257 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27258 	if (!(ipip->ipi_flags & IPI_WR)) {
27259 		/*
27260 		 * A return value of EINPROGRESS means the ioctl is
27261 		 * either queued and waiting for some reason or has
27262 		 * already completed.
27263 		 */
27264 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27265 		    ci.ci_lifr);
27266 		if (ci.ci_ipif != NULL)
27267 			ipif_refrele(ci.ci_ipif);
27268 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27269 		return;
27270 	}
27271 
27272 	ASSERT(ci.ci_ipif != NULL);
27273 
27274 	if (ipsq == NULL) {
27275 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27276 		    ip_process_ioctl, NEW_OP, B_TRUE);
27277 		entered_ipsq = B_TRUE;
27278 	}
27279 	/*
27280 	 * Release the ipif so that ipif_down and friends that wait for
27281 	 * references to go away are not misled about the current ipif_refcnt
27282 	 * values. We are writer so we can access the ipif even after releasing
27283 	 * the ipif.
27284 	 */
27285 	ipif_refrele(ci.ci_ipif);
27286 	if (ipsq == NULL)
27287 		return;
27288 
27289 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27290 
27291 	/*
27292 	 * For most set ioctls that come here, this serves as a single point
27293 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27294 	 * be any new references to the ipif. This helps functions that go
27295 	 * through this path and end up trying to wait for the refcnts
27296 	 * associated with the ipif to go down to zero. Some exceptions are
27297 	 * Failover, Failback, and Groupname commands that operate on more than
27298 	 * just the ci.ci_ipif. These commands internally determine the
27299 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27300 	 * flags on that set. Another exception is the Removeif command that
27301 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27302 	 * ipif to operate on.
27303 	 */
27304 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27305 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27306 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27307 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27308 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27309 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27310 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27311 
27312 	/*
27313 	 * A return value of EINPROGRESS means the ioctl is
27314 	 * either queued and waiting for some reason or has
27315 	 * already completed.
27316 	 */
27317 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27318 
27319 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27320 
27321 	if (entered_ipsq)
27322 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27323 }
27324 
27325 /*
27326  * Complete the ioctl. Typically ioctls use the mi package and need to
27327  * do mi_copyout/mi_copy_done.
27328  */
27329 void
27330 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27331 {
27332 	conn_t	*connp = NULL;
27333 
27334 	if (err == EINPROGRESS)
27335 		return;
27336 
27337 	if (CONN_Q(q)) {
27338 		connp = Q_TO_CONN(q);
27339 		ASSERT(connp->conn_ref >= 2);
27340 	}
27341 
27342 	switch (mode) {
27343 	case COPYOUT:
27344 		if (err == 0)
27345 			mi_copyout(q, mp);
27346 		else
27347 			mi_copy_done(q, mp, err);
27348 		break;
27349 
27350 	case NO_COPYOUT:
27351 		mi_copy_done(q, mp, err);
27352 		break;
27353 
27354 	default:
27355 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27356 		break;
27357 	}
27358 
27359 	/*
27360 	 * The refhold placed at the start of the ioctl is released here.
27361 	 */
27362 	if (connp != NULL)
27363 		CONN_OPER_PENDING_DONE(connp);
27364 
27365 	if (ipsq != NULL)
27366 		ipsq_current_finish(ipsq);
27367 }
27368 
27369 /*
27370  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27371  */
27372 /* ARGSUSED */
27373 void
27374 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27375 {
27376 	conn_t *connp = arg;
27377 	tcp_t	*tcp;
27378 
27379 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27380 	tcp = connp->conn_tcp;
27381 
27382 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27383 		freemsg(mp);
27384 	else
27385 		tcp_rput_other(tcp, mp);
27386 	CONN_OPER_PENDING_DONE(connp);
27387 }
27388 
27389 /* Called from ip_wput for all non data messages */
27390 /* ARGSUSED */
27391 void
27392 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27393 {
27394 	mblk_t		*mp1;
27395 	ire_t		*ire, *fake_ire;
27396 	ill_t		*ill;
27397 	struct iocblk	*iocp;
27398 	ip_ioctl_cmd_t	*ipip;
27399 	cred_t		*cr;
27400 	conn_t		*connp;
27401 	int		cmd, err;
27402 	nce_t		*nce;
27403 	ipif_t		*ipif;
27404 	ip_stack_t	*ipst;
27405 	char		*proto_str;
27406 
27407 	if (CONN_Q(q)) {
27408 		connp = Q_TO_CONN(q);
27409 		ipst = connp->conn_netstack->netstack_ip;
27410 	} else {
27411 		connp = NULL;
27412 		ipst = ILLQ_TO_IPST(q);
27413 	}
27414 
27415 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27416 
27417 	/* Check if it is a queue to /dev/sctp. */
27418 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27419 	    connp->conn_rq == NULL) {
27420 		sctp_wput(q, mp);
27421 		return;
27422 	}
27423 
27424 	switch (DB_TYPE(mp)) {
27425 	case M_IOCTL:
27426 		/*
27427 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27428 		 * will arrange to copy in associated control structures.
27429 		 */
27430 		ip_sioctl_copyin_setup(q, mp);
27431 		return;
27432 	case M_IOCDATA:
27433 		/*
27434 		 * Ensure that this is associated with one of our trans-
27435 		 * parent ioctls.  If it's not ours, discard it if we're
27436 		 * running as a driver, or pass it on if we're a module.
27437 		 */
27438 		iocp = (struct iocblk *)mp->b_rptr;
27439 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27440 		if (ipip == NULL) {
27441 			if (q->q_next == NULL) {
27442 				goto nak;
27443 			} else {
27444 				putnext(q, mp);
27445 			}
27446 			return;
27447 		} else if ((q->q_next != NULL) &&
27448 		    !(ipip->ipi_flags & IPI_MODOK)) {
27449 			/*
27450 			 * the ioctl is one we recognise, but is not
27451 			 * consumed by IP as a module, pass M_IOCDATA
27452 			 * for processing downstream, but only for
27453 			 * common Streams ioctls.
27454 			 */
27455 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27456 				putnext(q, mp);
27457 				return;
27458 			} else {
27459 				goto nak;
27460 			}
27461 		}
27462 
27463 		/* IOCTL continuation following copyin or copyout. */
27464 		if (mi_copy_state(q, mp, NULL) == -1) {
27465 			/*
27466 			 * The copy operation failed.  mi_copy_state already
27467 			 * cleaned up, so we're out of here.
27468 			 */
27469 			return;
27470 		}
27471 		/*
27472 		 * If we just completed a copy in, we become writer and
27473 		 * continue processing in ip_sioctl_copyin_done.  If it
27474 		 * was a copy out, we call mi_copyout again.  If there is
27475 		 * nothing more to copy out, it will complete the IOCTL.
27476 		 */
27477 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27478 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27479 				mi_copy_done(q, mp, EPROTO);
27480 				return;
27481 			}
27482 			/*
27483 			 * Check for cases that need more copying.  A return
27484 			 * value of 0 means a second copyin has been started,
27485 			 * so we return; a return value of 1 means no more
27486 			 * copying is needed, so we continue.
27487 			 */
27488 			cmd = iocp->ioc_cmd;
27489 			if ((cmd == SIOCGMSFILTER || cmd == SIOCSMSFILTER ||
27490 			    cmd == SIOCGIPMSFILTER || cmd == SIOCSIPMSFILTER) &&
27491 			    MI_COPY_COUNT(mp) == 1) {
27492 				if (ip_copyin_msfilter(q, mp) == 0)
27493 					return;
27494 			}
27495 			/*
27496 			 * Refhold the conn, till the ioctl completes. This is
27497 			 * needed in case the ioctl ends up in the pending mp
27498 			 * list. Every mp in the ill_pending_mp list and
27499 			 * the ipsq_pending_mp must have a refhold on the conn
27500 			 * to resume processing. The refhold is released when
27501 			 * the ioctl completes. (normally or abnormally)
27502 			 * In all cases ip_ioctl_finish is called to finish
27503 			 * the ioctl.
27504 			 */
27505 			if (connp != NULL) {
27506 				/* This is not a reentry */
27507 				ASSERT(ipsq == NULL);
27508 				CONN_INC_REF(connp);
27509 			} else {
27510 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27511 					mi_copy_done(q, mp, EINVAL);
27512 					return;
27513 				}
27514 			}
27515 
27516 			ip_process_ioctl(ipsq, q, mp, ipip);
27517 
27518 		} else {
27519 			mi_copyout(q, mp);
27520 		}
27521 		return;
27522 nak:
27523 		iocp->ioc_error = EINVAL;
27524 		mp->b_datap->db_type = M_IOCNAK;
27525 		iocp->ioc_count = 0;
27526 		qreply(q, mp);
27527 		return;
27528 
27529 	case M_IOCNAK:
27530 		/*
27531 		 * The only way we could get here is if a resolver didn't like
27532 		 * an IOCTL we sent it.	 This shouldn't happen.
27533 		 */
27534 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27535 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27536 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27537 		freemsg(mp);
27538 		return;
27539 	case M_IOCACK:
27540 		/* /dev/ip shouldn't see this */
27541 		if (CONN_Q(q))
27542 			goto nak;
27543 
27544 		/* Finish socket ioctls passed through to ARP. */
27545 		ip_sioctl_iocack(q, mp);
27546 		return;
27547 	case M_FLUSH:
27548 		if (*mp->b_rptr & FLUSHW)
27549 			flushq(q, FLUSHALL);
27550 		if (q->q_next) {
27551 			putnext(q, mp);
27552 			return;
27553 		}
27554 		if (*mp->b_rptr & FLUSHR) {
27555 			*mp->b_rptr &= ~FLUSHW;
27556 			qreply(q, mp);
27557 			return;
27558 		}
27559 		freemsg(mp);
27560 		return;
27561 	case IRE_DB_REQ_TYPE:
27562 		if (connp == NULL) {
27563 			proto_str = "IRE_DB_REQ_TYPE";
27564 			goto protonak;
27565 		}
27566 		/* An Upper Level Protocol wants a copy of an IRE. */
27567 		ip_ire_req(q, mp);
27568 		return;
27569 	case M_CTL:
27570 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27571 			break;
27572 
27573 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27574 		    TUN_HELLO) {
27575 			ASSERT(connp != NULL);
27576 			connp->conn_flags |= IPCL_IPTUN;
27577 			freeb(mp);
27578 			return;
27579 		}
27580 
27581 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27582 		    IP_ULP_OUT_LABELED) {
27583 			out_labeled_t *olp;
27584 
27585 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27586 				break;
27587 			olp = (out_labeled_t *)mp->b_rptr;
27588 			connp->conn_ulp_labeled = olp->out_qnext == q;
27589 			freemsg(mp);
27590 			return;
27591 		}
27592 
27593 		/* M_CTL messages are used by ARP to tell us things. */
27594 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27595 			break;
27596 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27597 		case AR_ENTRY_SQUERY:
27598 			ip_wput_ctl(q, mp);
27599 			return;
27600 		case AR_CLIENT_NOTIFY:
27601 			ip_arp_news(q, mp);
27602 			return;
27603 		case AR_DLPIOP_DONE:
27604 			ASSERT(q->q_next != NULL);
27605 			ill = (ill_t *)q->q_ptr;
27606 			/* qwriter_ip releases the refhold */
27607 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27608 			ill_refhold(ill);
27609 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27610 			return;
27611 		case AR_ARP_CLOSING:
27612 			/*
27613 			 * ARP (above us) is closing. If no ARP bringup is
27614 			 * currently pending, ack the message so that ARP
27615 			 * can complete its close. Also mark ill_arp_closing
27616 			 * so that new ARP bringups will fail. If any
27617 			 * ARP bringup is currently in progress, we will
27618 			 * ack this when the current ARP bringup completes.
27619 			 */
27620 			ASSERT(q->q_next != NULL);
27621 			ill = (ill_t *)q->q_ptr;
27622 			mutex_enter(&ill->ill_lock);
27623 			ill->ill_arp_closing = 1;
27624 			if (!ill->ill_arp_bringup_pending) {
27625 				mutex_exit(&ill->ill_lock);
27626 				qreply(q, mp);
27627 			} else {
27628 				mutex_exit(&ill->ill_lock);
27629 				freemsg(mp);
27630 			}
27631 			return;
27632 		case AR_ARP_EXTEND:
27633 			/*
27634 			 * The ARP module above us is capable of duplicate
27635 			 * address detection.  Old ATM drivers will not send
27636 			 * this message.
27637 			 */
27638 			ASSERT(q->q_next != NULL);
27639 			ill = (ill_t *)q->q_ptr;
27640 			ill->ill_arp_extend = B_TRUE;
27641 			freemsg(mp);
27642 			return;
27643 		default:
27644 			break;
27645 		}
27646 		break;
27647 	case M_PROTO:
27648 	case M_PCPROTO:
27649 		/*
27650 		 * The only PROTO messages we expect are ULP binds and
27651 		 * copies of option negotiation acknowledgements.
27652 		 */
27653 		switch (((union T_primitives *)mp->b_rptr)->type) {
27654 		case O_T_BIND_REQ:
27655 		case T_BIND_REQ: {
27656 			/* Request can get queued in bind */
27657 			if (connp == NULL) {
27658 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27659 				goto protonak;
27660 			}
27661 			/*
27662 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27663 			 * instead of going through this path.  We only get
27664 			 * here in the following cases:
27665 			 *
27666 			 * a. Bind retries, where ipsq is non-NULL.
27667 			 * b. T_BIND_REQ is issued from non TCP/UDP
27668 			 *    transport, e.g. icmp for raw socket,
27669 			 *    in which case ipsq will be NULL.
27670 			 */
27671 			ASSERT(ipsq != NULL ||
27672 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27673 
27674 			/* Don't increment refcnt if this is a re-entry */
27675 			if (ipsq == NULL)
27676 				CONN_INC_REF(connp);
27677 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27678 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27679 			if (mp == NULL)
27680 				return;
27681 			if (IPCL_IS_TCP(connp)) {
27682 				/*
27683 				 * In the case of TCP endpoint we
27684 				 * come here only for bind retries
27685 				 */
27686 				ASSERT(ipsq != NULL);
27687 				CONN_INC_REF(connp);
27688 				squeue_fill(connp->conn_sqp, mp,
27689 				    ip_resume_tcp_bind, connp,
27690 				    SQTAG_BIND_RETRY);
27691 				return;
27692 			} else if (IPCL_IS_UDP(connp)) {
27693 				/*
27694 				 * In the case of UDP endpoint we
27695 				 * come here only for bind retries
27696 				 */
27697 				ASSERT(ipsq != NULL);
27698 				udp_resume_bind(connp, mp);
27699 				return;
27700 			}
27701 			qreply(q, mp);
27702 			CONN_OPER_PENDING_DONE(connp);
27703 			return;
27704 		}
27705 		case T_SVR4_OPTMGMT_REQ:
27706 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27707 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27708 
27709 			if (connp == NULL) {
27710 				proto_str = "T_SVR4_OPTMGMT_REQ";
27711 				goto protonak;
27712 			}
27713 
27714 			if (!snmpcom_req(q, mp, ip_snmp_set,
27715 			    ip_snmp_get, cr)) {
27716 				/*
27717 				 * Call svr4_optcom_req so that it can
27718 				 * generate the ack. We don't come here
27719 				 * if this operation is being restarted.
27720 				 * ip_restart_optmgmt will drop the conn ref.
27721 				 * In the case of ipsec option after the ipsec
27722 				 * load is complete conn_restart_ipsec_waiter
27723 				 * drops the conn ref.
27724 				 */
27725 				ASSERT(ipsq == NULL);
27726 				CONN_INC_REF(connp);
27727 				if (ip_check_for_ipsec_opt(q, mp))
27728 					return;
27729 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27730 				if (err != EINPROGRESS) {
27731 					/* Operation is done */
27732 					CONN_OPER_PENDING_DONE(connp);
27733 				}
27734 			}
27735 			return;
27736 		case T_OPTMGMT_REQ:
27737 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27738 			/*
27739 			 * Note: No snmpcom_req support through new
27740 			 * T_OPTMGMT_REQ.
27741 			 * Call tpi_optcom_req so that it can
27742 			 * generate the ack.
27743 			 */
27744 			if (connp == NULL) {
27745 				proto_str = "T_OPTMGMT_REQ";
27746 				goto protonak;
27747 			}
27748 
27749 			ASSERT(ipsq == NULL);
27750 			/*
27751 			 * We don't come here for restart. ip_restart_optmgmt
27752 			 * will drop the conn ref. In the case of ipsec option
27753 			 * after the ipsec load is complete
27754 			 * conn_restart_ipsec_waiter drops the conn ref.
27755 			 */
27756 			CONN_INC_REF(connp);
27757 			if (ip_check_for_ipsec_opt(q, mp))
27758 				return;
27759 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27760 			if (err != EINPROGRESS) {
27761 				/* Operation is done */
27762 				CONN_OPER_PENDING_DONE(connp);
27763 			}
27764 			return;
27765 		case T_UNBIND_REQ:
27766 			if (connp == NULL) {
27767 				proto_str = "T_UNBIND_REQ";
27768 				goto protonak;
27769 			}
27770 			mp = ip_unbind(q, mp);
27771 			qreply(q, mp);
27772 			return;
27773 		default:
27774 			/*
27775 			 * Have to drop any DLPI messages coming down from
27776 			 * arp (such as an info_req which would cause ip
27777 			 * to receive an extra info_ack if it was passed
27778 			 * through.
27779 			 */
27780 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27781 			    (int)*(uint_t *)mp->b_rptr));
27782 			freemsg(mp);
27783 			return;
27784 		}
27785 		/* NOTREACHED */
27786 	case IRE_DB_TYPE: {
27787 		nce_t		*nce;
27788 		ill_t		*ill;
27789 		in6_addr_t	gw_addr_v6;
27790 
27791 
27792 		/*
27793 		 * This is a response back from a resolver.  It
27794 		 * consists of a message chain containing:
27795 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27796 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27797 		 * The LL_HDR_MBLK is the DLPI header to use to get
27798 		 * the attached packet, and subsequent ones for the
27799 		 * same destination, transmitted.
27800 		 */
27801 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27802 			break;
27803 		/*
27804 		 * First, check to make sure the resolution succeeded.
27805 		 * If it failed, the second mblk will be empty.
27806 		 * If it is, free the chain, dropping the packet.
27807 		 * (We must ire_delete the ire; that frees the ire mblk)
27808 		 * We're doing this now to support PVCs for ATM; it's
27809 		 * a partial xresolv implementation. When we fully implement
27810 		 * xresolv interfaces, instead of freeing everything here
27811 		 * we'll initiate neighbor discovery.
27812 		 *
27813 		 * For v4 (ARP and other external resolvers) the resolver
27814 		 * frees the message, so no check is needed. This check
27815 		 * is required, though, for a full xresolve implementation.
27816 		 * Including this code here now both shows how external
27817 		 * resolvers can NACK a resolution request using an
27818 		 * existing design that has no specific provisions for NACKs,
27819 		 * and also takes into account that the current non-ARP
27820 		 * external resolver has been coded to use this method of
27821 		 * NACKing for all IPv6 (xresolv) cases,
27822 		 * whether our xresolv implementation is complete or not.
27823 		 *
27824 		 */
27825 		ire = (ire_t *)mp->b_rptr;
27826 		ill = ire_to_ill(ire);
27827 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27828 		if (mp1->b_rptr == mp1->b_wptr) {
27829 			if (ire->ire_ipversion == IPV6_VERSION) {
27830 				/*
27831 				 * XRESOLV interface.
27832 				 */
27833 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27834 				mutex_enter(&ire->ire_lock);
27835 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27836 				mutex_exit(&ire->ire_lock);
27837 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27838 					nce = ndp_lookup_v6(ill,
27839 					    &ire->ire_addr_v6, B_FALSE);
27840 				} else {
27841 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27842 					    B_FALSE);
27843 				}
27844 				if (nce != NULL) {
27845 					nce_resolv_failed(nce);
27846 					ndp_delete(nce);
27847 					NCE_REFRELE(nce);
27848 				}
27849 			}
27850 			mp->b_cont = NULL;
27851 			freemsg(mp1);		/* frees the pkt as well */
27852 			ASSERT(ire->ire_nce == NULL);
27853 			ire_delete((ire_t *)mp->b_rptr);
27854 			return;
27855 		}
27856 
27857 		/*
27858 		 * Split them into IRE_MBLK and pkt and feed it into
27859 		 * ire_add_then_send. Then in ire_add_then_send
27860 		 * the IRE will be added, and then the packet will be
27861 		 * run back through ip_wput. This time it will make
27862 		 * it to the wire.
27863 		 */
27864 		mp->b_cont = NULL;
27865 		mp = mp1->b_cont;		/* now, mp points to pkt */
27866 		mp1->b_cont = NULL;
27867 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27868 		if (ire->ire_ipversion == IPV6_VERSION) {
27869 			/*
27870 			 * XRESOLV interface. Find the nce and put a copy
27871 			 * of the dl_unitdata_req in nce_res_mp
27872 			 */
27873 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27874 			mutex_enter(&ire->ire_lock);
27875 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27876 			mutex_exit(&ire->ire_lock);
27877 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27878 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27879 				    B_FALSE);
27880 			} else {
27881 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27882 			}
27883 			if (nce != NULL) {
27884 				/*
27885 				 * We have to protect nce_res_mp here
27886 				 * from being accessed by other threads
27887 				 * while we change the mblk pointer.
27888 				 * Other functions will also lock the nce when
27889 				 * accessing nce_res_mp.
27890 				 *
27891 				 * The reason we change the mblk pointer
27892 				 * here rather than copying the resolved address
27893 				 * into the template is that, unlike with
27894 				 * ethernet, we have no guarantee that the
27895 				 * resolved address length will be
27896 				 * smaller than or equal to the lla length
27897 				 * with which the template was allocated,
27898 				 * (for ethernet, they're equal)
27899 				 * so we have to use the actual resolved
27900 				 * address mblk - which holds the real
27901 				 * dl_unitdata_req with the resolved address.
27902 				 *
27903 				 * Doing this is the same behavior as was
27904 				 * previously used in the v4 ARP case.
27905 				 */
27906 				mutex_enter(&nce->nce_lock);
27907 				if (nce->nce_res_mp != NULL)
27908 					freemsg(nce->nce_res_mp);
27909 				nce->nce_res_mp = mp1;
27910 				mutex_exit(&nce->nce_lock);
27911 				/*
27912 				 * We do a fastpath probe here because
27913 				 * we have resolved the address without
27914 				 * using Neighbor Discovery.
27915 				 * In the non-XRESOLV v6 case, the fastpath
27916 				 * probe is done right after neighbor
27917 				 * discovery completes.
27918 				 */
27919 				if (nce->nce_res_mp != NULL) {
27920 					int res;
27921 					nce_fastpath_list_add(nce);
27922 					res = ill_fastpath_probe(ill,
27923 					    nce->nce_res_mp);
27924 					if (res != 0 && res != EAGAIN)
27925 						nce_fastpath_list_delete(nce);
27926 				}
27927 
27928 				ire_add_then_send(q, ire, mp);
27929 				/*
27930 				 * Now we have to clean out any packets
27931 				 * that may have been queued on the nce
27932 				 * while it was waiting for address resolution
27933 				 * to complete.
27934 				 */
27935 				mutex_enter(&nce->nce_lock);
27936 				mp1 = nce->nce_qd_mp;
27937 				nce->nce_qd_mp = NULL;
27938 				mutex_exit(&nce->nce_lock);
27939 				while (mp1 != NULL) {
27940 					mblk_t *nxt_mp;
27941 					queue_t *fwdq = NULL;
27942 					ill_t   *inbound_ill;
27943 					uint_t ifindex;
27944 
27945 					nxt_mp = mp1->b_next;
27946 					mp1->b_next = NULL;
27947 					/*
27948 					 * Retrieve ifindex stored in
27949 					 * ip_rput_data_v6()
27950 					 */
27951 					ifindex =
27952 					    (uint_t)(uintptr_t)mp1->b_prev;
27953 					inbound_ill =
27954 					    ill_lookup_on_ifindex(ifindex,
27955 					    B_TRUE, NULL, NULL, NULL,
27956 					    NULL, ipst);
27957 					mp1->b_prev = NULL;
27958 					if (inbound_ill != NULL)
27959 						fwdq = inbound_ill->ill_rq;
27960 
27961 					if (fwdq != NULL) {
27962 						put(fwdq, mp1);
27963 						ill_refrele(inbound_ill);
27964 					} else
27965 						put(WR(ill->ill_rq), mp1);
27966 					mp1 = nxt_mp;
27967 				}
27968 				NCE_REFRELE(nce);
27969 			} else {	/* nce is NULL; clean up */
27970 				ire_delete(ire);
27971 				freemsg(mp);
27972 				freemsg(mp1);
27973 				return;
27974 			}
27975 		} else {
27976 			nce_t *arpce;
27977 			/*
27978 			 * Link layer resolution succeeded. Recompute the
27979 			 * ire_nce.
27980 			 */
27981 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27982 			if ((arpce = ndp_lookup_v4(ill,
27983 			    (ire->ire_gateway_addr != INADDR_ANY ?
27984 			    &ire->ire_gateway_addr : &ire->ire_addr),
27985 			    B_FALSE)) == NULL) {
27986 				freeb(ire->ire_mp);
27987 				freeb(mp1);
27988 				freemsg(mp);
27989 				return;
27990 			}
27991 			mutex_enter(&arpce->nce_lock);
27992 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27993 			if (arpce->nce_state == ND_REACHABLE) {
27994 				/*
27995 				 * Someone resolved this before us;
27996 				 * cleanup the res_mp. Since ire has
27997 				 * not been added yet, the call to ire_add_v4
27998 				 * from ire_add_then_send (when a dup is
27999 				 * detected) will clean up the ire.
28000 				 */
28001 				freeb(mp1);
28002 			} else {
28003 				ASSERT(arpce->nce_res_mp == NULL);
28004 				arpce->nce_res_mp = mp1;
28005 				arpce->nce_state = ND_REACHABLE;
28006 			}
28007 			mutex_exit(&arpce->nce_lock);
28008 			if (ire->ire_marks & IRE_MARK_NOADD) {
28009 				/*
28010 				 * this ire will not be added to the ire
28011 				 * cache table, so we can set the ire_nce
28012 				 * here, as there are no atomicity constraints.
28013 				 */
28014 				ire->ire_nce = arpce;
28015 				/*
28016 				 * We are associating this nce with the ire
28017 				 * so change the nce ref taken in
28018 				 * ndp_lookup_v4() from
28019 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
28020 				 */
28021 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
28022 			} else {
28023 				NCE_REFRELE(arpce);
28024 			}
28025 			ire_add_then_send(q, ire, mp);
28026 		}
28027 		return;	/* All is well, the packet has been sent. */
28028 	}
28029 	case IRE_ARPRESOLVE_TYPE: {
28030 
28031 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
28032 			break;
28033 		mp1 = mp->b_cont;		/* dl_unitdata_req */
28034 		mp->b_cont = NULL;
28035 		/*
28036 		 * First, check to make sure the resolution succeeded.
28037 		 * If it failed, the second mblk will be empty.
28038 		 */
28039 		if (mp1->b_rptr == mp1->b_wptr) {
28040 			/* cleanup  the incomplete ire, free queued packets */
28041 			freemsg(mp); /* fake ire */
28042 			freeb(mp1);  /* dl_unitdata response */
28043 			return;
28044 		}
28045 
28046 		/*
28047 		 * update any incomplete nce_t found. we lookup the ctable
28048 		 * and find the nce from the ire->ire_nce because we need
28049 		 * to pass the ire to ip_xmit_v4 later, and can find both
28050 		 * ire and nce in one lookup from the ctable.
28051 		 */
28052 		fake_ire = (ire_t *)mp->b_rptr;
28053 		/*
28054 		 * By the time we come back here from ARP
28055 		 * the logical outgoing interface  of the incomplete ire
28056 		 * we added in ire_forward could have disappeared,
28057 		 * causing the incomplete ire to also have
28058 		 * dissapeared. So we need to retreive the
28059 		 * proper ipif for the ire  before looking
28060 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
28061 		 */
28062 		ill = q->q_ptr;
28063 
28064 		/* Get the outgoing ipif */
28065 		mutex_enter(&ill->ill_lock);
28066 		if (ill->ill_state_flags & ILL_CONDEMNED) {
28067 			mutex_exit(&ill->ill_lock);
28068 			freemsg(mp); /* fake ire */
28069 			freeb(mp1);  /* dl_unitdata response */
28070 			return;
28071 		}
28072 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
28073 
28074 		if (ipif == NULL) {
28075 			mutex_exit(&ill->ill_lock);
28076 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
28077 			freemsg(mp);
28078 			freeb(mp1);
28079 			return;
28080 		}
28081 		ipif_refhold_locked(ipif);
28082 		mutex_exit(&ill->ill_lock);
28083 		ire = ire_ctable_lookup(fake_ire->ire_addr,
28084 		    fake_ire->ire_gateway_addr, IRE_CACHE,
28085 		    ipif, fake_ire->ire_zoneid, NULL,
28086 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
28087 		ipif_refrele(ipif);
28088 		if (ire == NULL) {
28089 			/*
28090 			 * no ire was found; check if there is an nce
28091 			 * for this lookup; if it has no ire's pointing at it
28092 			 * cleanup.
28093 			 */
28094 			if ((nce = ndp_lookup_v4(ill,
28095 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
28096 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
28097 			    B_FALSE)) != NULL) {
28098 				/*
28099 				 * cleanup:
28100 				 * We check for refcnt 2 (one for the nce
28101 				 * hash list + 1 for the ref taken by
28102 				 * ndp_lookup_v4) to check that there are
28103 				 * no ire's pointing at the nce.
28104 				 */
28105 				if (nce->nce_refcnt == 2)
28106 					ndp_delete(nce);
28107 				NCE_REFRELE(nce);
28108 			}
28109 			freeb(mp1);  /* dl_unitdata response */
28110 			freemsg(mp); /* fake ire */
28111 			return;
28112 		}
28113 		nce = ire->ire_nce;
28114 		DTRACE_PROBE2(ire__arpresolve__type,
28115 		    ire_t *, ire, nce_t *, nce);
28116 		ASSERT(nce->nce_state != ND_INITIAL);
28117 		mutex_enter(&nce->nce_lock);
28118 		nce->nce_last = TICK_TO_MSEC(lbolt64);
28119 		if (nce->nce_state == ND_REACHABLE) {
28120 			/*
28121 			 * Someone resolved this before us;
28122 			 * our response is not needed any more.
28123 			 */
28124 			mutex_exit(&nce->nce_lock);
28125 			freeb(mp1);  /* dl_unitdata response */
28126 		} else {
28127 			ASSERT(nce->nce_res_mp == NULL);
28128 			nce->nce_res_mp = mp1;
28129 			nce->nce_state = ND_REACHABLE;
28130 			mutex_exit(&nce->nce_lock);
28131 			nce_fastpath(nce);
28132 		}
28133 		/*
28134 		 * The cached nce_t has been updated to be reachable;
28135 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
28136 		 */
28137 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
28138 		freemsg(mp);
28139 		/*
28140 		 * send out queued packets.
28141 		 */
28142 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
28143 
28144 		IRE_REFRELE(ire);
28145 		return;
28146 	}
28147 	default:
28148 		break;
28149 	}
28150 	if (q->q_next) {
28151 		putnext(q, mp);
28152 	} else
28153 		freemsg(mp);
28154 	return;
28155 
28156 protonak:
28157 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
28158 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
28159 		qreply(q, mp);
28160 }
28161 
28162 /*
28163  * Process IP options in an outbound packet.  Modify the destination if there
28164  * is a source route option.
28165  * Returns non-zero if something fails in which case an ICMP error has been
28166  * sent and mp freed.
28167  */
28168 static int
28169 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
28170     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
28171 {
28172 	ipoptp_t	opts;
28173 	uchar_t		*opt;
28174 	uint8_t		optval;
28175 	uint8_t		optlen;
28176 	ipaddr_t	dst;
28177 	intptr_t	code = 0;
28178 	mblk_t		*mp;
28179 	ire_t		*ire = NULL;
28180 
28181 	ip2dbg(("ip_wput_options\n"));
28182 	mp = ipsec_mp;
28183 	if (mctl_present) {
28184 		mp = ipsec_mp->b_cont;
28185 	}
28186 
28187 	dst = ipha->ipha_dst;
28188 	for (optval = ipoptp_first(&opts, ipha);
28189 	    optval != IPOPT_EOL;
28190 	    optval = ipoptp_next(&opts)) {
28191 		opt = opts.ipoptp_cur;
28192 		optlen = opts.ipoptp_len;
28193 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28194 		    optval, optlen));
28195 		switch (optval) {
28196 			uint32_t off;
28197 		case IPOPT_SSRR:
28198 		case IPOPT_LSRR:
28199 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28200 				ip1dbg((
28201 				    "ip_wput_options: bad option offset\n"));
28202 				code = (char *)&opt[IPOPT_OLEN] -
28203 				    (char *)ipha;
28204 				goto param_prob;
28205 			}
28206 			off = opt[IPOPT_OFFSET];
28207 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28208 			    ntohl(dst)));
28209 			/*
28210 			 * For strict: verify that dst is directly
28211 			 * reachable.
28212 			 */
28213 			if (optval == IPOPT_SSRR) {
28214 				ire = ire_ftable_lookup(dst, 0, 0,
28215 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28216 				    MBLK_GETLABEL(mp),
28217 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28218 				if (ire == NULL) {
28219 					ip1dbg(("ip_wput_options: SSRR not"
28220 					    " directly reachable: 0x%x\n",
28221 					    ntohl(dst)));
28222 					goto bad_src_route;
28223 				}
28224 				ire_refrele(ire);
28225 			}
28226 			break;
28227 		case IPOPT_RR:
28228 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28229 				ip1dbg((
28230 				    "ip_wput_options: bad option offset\n"));
28231 				code = (char *)&opt[IPOPT_OLEN] -
28232 				    (char *)ipha;
28233 				goto param_prob;
28234 			}
28235 			break;
28236 		case IPOPT_TS:
28237 			/*
28238 			 * Verify that length >=5 and that there is either
28239 			 * room for another timestamp or that the overflow
28240 			 * counter is not maxed out.
28241 			 */
28242 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28243 			if (optlen < IPOPT_MINLEN_IT) {
28244 				goto param_prob;
28245 			}
28246 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28247 				ip1dbg((
28248 				    "ip_wput_options: bad option offset\n"));
28249 				code = (char *)&opt[IPOPT_OFFSET] -
28250 				    (char *)ipha;
28251 				goto param_prob;
28252 			}
28253 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28254 			case IPOPT_TS_TSONLY:
28255 				off = IPOPT_TS_TIMELEN;
28256 				break;
28257 			case IPOPT_TS_TSANDADDR:
28258 			case IPOPT_TS_PRESPEC:
28259 			case IPOPT_TS_PRESPEC_RFC791:
28260 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28261 				break;
28262 			default:
28263 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28264 				    (char *)ipha;
28265 				goto param_prob;
28266 			}
28267 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28268 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28269 				/*
28270 				 * No room and the overflow counter is 15
28271 				 * already.
28272 				 */
28273 				goto param_prob;
28274 			}
28275 			break;
28276 		}
28277 	}
28278 
28279 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28280 		return (0);
28281 
28282 	ip1dbg(("ip_wput_options: error processing IP options."));
28283 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28284 
28285 param_prob:
28286 	/*
28287 	 * Since ip_wput() isn't close to finished, we fill
28288 	 * in enough of the header for credible error reporting.
28289 	 */
28290 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28291 		/* Failed */
28292 		freemsg(ipsec_mp);
28293 		return (-1);
28294 	}
28295 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28296 	return (-1);
28297 
28298 bad_src_route:
28299 	/*
28300 	 * Since ip_wput() isn't close to finished, we fill
28301 	 * in enough of the header for credible error reporting.
28302 	 */
28303 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28304 		/* Failed */
28305 		freemsg(ipsec_mp);
28306 		return (-1);
28307 	}
28308 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28309 	return (-1);
28310 }
28311 
28312 /*
28313  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28314  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28315  * thru /etc/system.
28316  */
28317 #define	CONN_MAXDRAINCNT	64
28318 
28319 static void
28320 conn_drain_init(ip_stack_t *ipst)
28321 {
28322 	int i;
28323 
28324 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28325 
28326 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28327 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28328 		/*
28329 		 * Default value of the number of drainers is the
28330 		 * number of cpus, subject to maximum of 8 drainers.
28331 		 */
28332 		if (boot_max_ncpus != -1)
28333 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28334 		else
28335 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28336 	}
28337 
28338 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28339 	    sizeof (idl_t), KM_SLEEP);
28340 
28341 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28342 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28343 		    MUTEX_DEFAULT, NULL);
28344 	}
28345 }
28346 
28347 static void
28348 conn_drain_fini(ip_stack_t *ipst)
28349 {
28350 	int i;
28351 
28352 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28353 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28354 	kmem_free(ipst->ips_conn_drain_list,
28355 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28356 	ipst->ips_conn_drain_list = NULL;
28357 }
28358 
28359 /*
28360  * Note: For an overview of how flowcontrol is handled in IP please see the
28361  * IP Flowcontrol notes at the top of this file.
28362  *
28363  * Flow control has blocked us from proceeding. Insert the given conn in one
28364  * of the conn drain lists. These conn wq's will be qenabled later on when
28365  * STREAMS flow control does a backenable. conn_walk_drain will enable
28366  * the first conn in each of these drain lists. Each of these qenabled conns
28367  * in turn enables the next in the list, after it runs, or when it closes,
28368  * thus sustaining the drain process.
28369  *
28370  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28371  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28372  * running at any time, on a given conn, since there can be only 1 service proc
28373  * running on a queue at any time.
28374  */
28375 void
28376 conn_drain_insert(conn_t *connp)
28377 {
28378 	idl_t	*idl;
28379 	uint_t	index;
28380 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28381 
28382 	mutex_enter(&connp->conn_lock);
28383 	if (connp->conn_state_flags & CONN_CLOSING) {
28384 		/*
28385 		 * The conn is closing as a result of which CONN_CLOSING
28386 		 * is set. Return.
28387 		 */
28388 		mutex_exit(&connp->conn_lock);
28389 		return;
28390 	} else if (connp->conn_idl == NULL) {
28391 		/*
28392 		 * Assign the next drain list round robin. We dont' use
28393 		 * a lock, and thus it may not be strictly round robin.
28394 		 * Atomicity of load/stores is enough to make sure that
28395 		 * conn_drain_list_index is always within bounds.
28396 		 */
28397 		index = ipst->ips_conn_drain_list_index;
28398 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28399 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28400 		index++;
28401 		if (index == ipst->ips_conn_drain_list_cnt)
28402 			index = 0;
28403 		ipst->ips_conn_drain_list_index = index;
28404 	}
28405 	mutex_exit(&connp->conn_lock);
28406 
28407 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28408 	if ((connp->conn_drain_prev != NULL) ||
28409 	    (connp->conn_state_flags & CONN_CLOSING)) {
28410 		/*
28411 		 * The conn is already in the drain list, OR
28412 		 * the conn is closing. We need to check again for
28413 		 * the closing case again since close can happen
28414 		 * after we drop the conn_lock, and before we
28415 		 * acquire the CONN_DRAIN_LIST_LOCK.
28416 		 */
28417 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28418 		return;
28419 	} else {
28420 		idl = connp->conn_idl;
28421 	}
28422 
28423 	/*
28424 	 * The conn is not in the drain list. Insert it at the
28425 	 * tail of the drain list. The drain list is circular
28426 	 * and doubly linked. idl_conn points to the 1st element
28427 	 * in the list.
28428 	 */
28429 	if (idl->idl_conn == NULL) {
28430 		idl->idl_conn = connp;
28431 		connp->conn_drain_next = connp;
28432 		connp->conn_drain_prev = connp;
28433 	} else {
28434 		conn_t *head = idl->idl_conn;
28435 
28436 		connp->conn_drain_next = head;
28437 		connp->conn_drain_prev = head->conn_drain_prev;
28438 		head->conn_drain_prev->conn_drain_next = connp;
28439 		head->conn_drain_prev = connp;
28440 	}
28441 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28442 }
28443 
28444 /*
28445  * This conn is closing, and we are called from ip_close. OR
28446  * This conn has been serviced by ip_wsrv, and we need to do the tail
28447  * processing.
28448  * If this conn is part of the drain list, we may need to sustain the drain
28449  * process by qenabling the next conn in the drain list. We may also need to
28450  * remove this conn from the list, if it is done.
28451  */
28452 static void
28453 conn_drain_tail(conn_t *connp, boolean_t closing)
28454 {
28455 	idl_t *idl;
28456 
28457 	/*
28458 	 * connp->conn_idl is stable at this point, and no lock is needed
28459 	 * to check it. If we are called from ip_close, close has already
28460 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28461 	 * called us only because conn_idl is non-null. If we are called thru
28462 	 * service, conn_idl could be null, but it cannot change because
28463 	 * service is single-threaded per queue, and there cannot be another
28464 	 * instance of service trying to call conn_drain_insert on this conn
28465 	 * now.
28466 	 */
28467 	ASSERT(!closing || (connp->conn_idl != NULL));
28468 
28469 	/*
28470 	 * If connp->conn_idl is null, the conn has not been inserted into any
28471 	 * drain list even once since creation of the conn. Just return.
28472 	 */
28473 	if (connp->conn_idl == NULL)
28474 		return;
28475 
28476 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28477 
28478 	if (connp->conn_drain_prev == NULL) {
28479 		/* This conn is currently not in the drain list.  */
28480 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28481 		return;
28482 	}
28483 	idl = connp->conn_idl;
28484 	if (idl->idl_conn_draining == connp) {
28485 		/*
28486 		 * This conn is the current drainer. If this is the last conn
28487 		 * in the drain list, we need to do more checks, in the 'if'
28488 		 * below. Otherwwise we need to just qenable the next conn,
28489 		 * to sustain the draining, and is handled in the 'else'
28490 		 * below.
28491 		 */
28492 		if (connp->conn_drain_next == idl->idl_conn) {
28493 			/*
28494 			 * This conn is the last in this list. This round
28495 			 * of draining is complete. If idl_repeat is set,
28496 			 * it means another flow enabling has happened from
28497 			 * the driver/streams and we need to another round
28498 			 * of draining.
28499 			 * If there are more than 2 conns in the drain list,
28500 			 * do a left rotate by 1, so that all conns except the
28501 			 * conn at the head move towards the head by 1, and the
28502 			 * the conn at the head goes to the tail. This attempts
28503 			 * a more even share for all queues that are being
28504 			 * drained.
28505 			 */
28506 			if ((connp->conn_drain_next != connp) &&
28507 			    (idl->idl_conn->conn_drain_next != connp)) {
28508 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28509 			}
28510 			if (idl->idl_repeat) {
28511 				qenable(idl->idl_conn->conn_wq);
28512 				idl->idl_conn_draining = idl->idl_conn;
28513 				idl->idl_repeat = 0;
28514 			} else {
28515 				idl->idl_conn_draining = NULL;
28516 			}
28517 		} else {
28518 			/*
28519 			 * If the next queue that we are now qenable'ing,
28520 			 * is closing, it will remove itself from this list
28521 			 * and qenable the subsequent queue in ip_close().
28522 			 * Serialization is acheived thru idl_lock.
28523 			 */
28524 			qenable(connp->conn_drain_next->conn_wq);
28525 			idl->idl_conn_draining = connp->conn_drain_next;
28526 		}
28527 	}
28528 	if (!connp->conn_did_putbq || closing) {
28529 		/*
28530 		 * Remove ourself from the drain list, if we did not do
28531 		 * a putbq, or if the conn is closing.
28532 		 * Note: It is possible that q->q_first is non-null. It means
28533 		 * that these messages landed after we did a enableok() in
28534 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28535 		 * service them.
28536 		 */
28537 		if (connp->conn_drain_next == connp) {
28538 			/* Singleton in the list */
28539 			ASSERT(connp->conn_drain_prev == connp);
28540 			idl->idl_conn = NULL;
28541 			idl->idl_conn_draining = NULL;
28542 		} else {
28543 			connp->conn_drain_prev->conn_drain_next =
28544 			    connp->conn_drain_next;
28545 			connp->conn_drain_next->conn_drain_prev =
28546 			    connp->conn_drain_prev;
28547 			if (idl->idl_conn == connp)
28548 				idl->idl_conn = connp->conn_drain_next;
28549 			ASSERT(idl->idl_conn_draining != connp);
28550 
28551 		}
28552 		connp->conn_drain_next = NULL;
28553 		connp->conn_drain_prev = NULL;
28554 	}
28555 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28556 }
28557 
28558 /*
28559  * Write service routine. Shared perimeter entry point.
28560  * ip_wsrv can be called in any of the following ways.
28561  * 1. The device queue's messages has fallen below the low water mark
28562  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28563  *    the drain lists and backenable the first conn in each list.
28564  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28565  *    qenabled non-tcp upper layers. We start dequeing messages and call
28566  *    ip_wput for each message.
28567  */
28568 
28569 void
28570 ip_wsrv(queue_t *q)
28571 {
28572 	conn_t	*connp;
28573 	ill_t	*ill;
28574 	mblk_t	*mp;
28575 
28576 	if (q->q_next) {
28577 		ill = (ill_t *)q->q_ptr;
28578 		if (ill->ill_state_flags == 0) {
28579 			/*
28580 			 * The device flow control has opened up.
28581 			 * Walk through conn drain lists and qenable the
28582 			 * first conn in each list. This makes sense only
28583 			 * if the stream is fully plumbed and setup.
28584 			 * Hence the if check above.
28585 			 */
28586 			ip1dbg(("ip_wsrv: walking\n"));
28587 			conn_walk_drain(ill->ill_ipst);
28588 		}
28589 		return;
28590 	}
28591 
28592 	connp = Q_TO_CONN(q);
28593 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28594 
28595 	/*
28596 	 * 1. Set conn_draining flag to signal that service is active.
28597 	 *
28598 	 * 2. ip_output determines whether it has been called from service,
28599 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28600 	 *    has been called from service.
28601 	 *
28602 	 * 3. Message ordering is preserved by the following logic.
28603 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28604 	 *    the message at the tail, if conn_draining is set (i.e. service
28605 	 *    is running) or if q->q_first is non-null.
28606 	 *
28607 	 *    ii. If ip_output is called from service, and if ip_output cannot
28608 	 *    putnext due to flow control, it does a putbq.
28609 	 *
28610 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28611 	 *    (causing an infinite loop).
28612 	 */
28613 	ASSERT(!connp->conn_did_putbq);
28614 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28615 		connp->conn_draining = 1;
28616 		noenable(q);
28617 		while ((mp = getq(q)) != NULL) {
28618 			ASSERT(CONN_Q(q));
28619 
28620 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28621 			if (connp->conn_did_putbq) {
28622 				/* ip_wput did a putbq */
28623 				break;
28624 			}
28625 		}
28626 		/*
28627 		 * At this point, a thread coming down from top, calling
28628 		 * ip_wput, may end up queueing the message. We have not yet
28629 		 * enabled the queue, so ip_wsrv won't be called again.
28630 		 * To avoid this race, check q->q_first again (in the loop)
28631 		 * If the other thread queued the message before we call
28632 		 * enableok(), we will catch it in the q->q_first check.
28633 		 * If the other thread queues the message after we call
28634 		 * enableok(), ip_wsrv will be called again by STREAMS.
28635 		 */
28636 		connp->conn_draining = 0;
28637 		enableok(q);
28638 	}
28639 
28640 	/* Enable the next conn for draining */
28641 	conn_drain_tail(connp, B_FALSE);
28642 
28643 	connp->conn_did_putbq = 0;
28644 }
28645 
28646 /*
28647  * Walk the list of all conn's calling the function provided with the
28648  * specified argument for each.	 Note that this only walks conn's that
28649  * have been bound.
28650  * Applies to both IPv4 and IPv6.
28651  */
28652 static void
28653 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28654 {
28655 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28656 	    ipst->ips_ipcl_udp_fanout_size,
28657 	    func, arg, zoneid);
28658 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28659 	    ipst->ips_ipcl_conn_fanout_size,
28660 	    func, arg, zoneid);
28661 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28662 	    ipst->ips_ipcl_bind_fanout_size,
28663 	    func, arg, zoneid);
28664 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28665 	    IPPROTO_MAX, func, arg, zoneid);
28666 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28667 	    IPPROTO_MAX, func, arg, zoneid);
28668 }
28669 
28670 /*
28671  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28672  * of conns that need to be drained, check if drain is already in progress.
28673  * If so set the idl_repeat bit, indicating that the last conn in the list
28674  * needs to reinitiate the drain once again, for the list. If drain is not
28675  * in progress for the list, initiate the draining, by qenabling the 1st
28676  * conn in the list. The drain is self-sustaining, each qenabled conn will
28677  * in turn qenable the next conn, when it is done/blocked/closing.
28678  */
28679 static void
28680 conn_walk_drain(ip_stack_t *ipst)
28681 {
28682 	int i;
28683 	idl_t *idl;
28684 
28685 	IP_STAT(ipst, ip_conn_walk_drain);
28686 
28687 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28688 		idl = &ipst->ips_conn_drain_list[i];
28689 		mutex_enter(&idl->idl_lock);
28690 		if (idl->idl_conn == NULL) {
28691 			mutex_exit(&idl->idl_lock);
28692 			continue;
28693 		}
28694 		/*
28695 		 * If this list is not being drained currently by
28696 		 * an ip_wsrv thread, start the process.
28697 		 */
28698 		if (idl->idl_conn_draining == NULL) {
28699 			ASSERT(idl->idl_repeat == 0);
28700 			qenable(idl->idl_conn->conn_wq);
28701 			idl->idl_conn_draining = idl->idl_conn;
28702 		} else {
28703 			idl->idl_repeat = 1;
28704 		}
28705 		mutex_exit(&idl->idl_lock);
28706 	}
28707 }
28708 
28709 /*
28710  * Walk an conn hash table of `count' buckets, calling func for each entry.
28711  */
28712 static void
28713 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28714     zoneid_t zoneid)
28715 {
28716 	conn_t	*connp;
28717 
28718 	while (count-- > 0) {
28719 		mutex_enter(&connfp->connf_lock);
28720 		for (connp = connfp->connf_head; connp != NULL;
28721 		    connp = connp->conn_next) {
28722 			if (zoneid == GLOBAL_ZONEID ||
28723 			    zoneid == connp->conn_zoneid) {
28724 				CONN_INC_REF(connp);
28725 				mutex_exit(&connfp->connf_lock);
28726 				(*func)(connp, arg);
28727 				mutex_enter(&connfp->connf_lock);
28728 				CONN_DEC_REF(connp);
28729 			}
28730 		}
28731 		mutex_exit(&connfp->connf_lock);
28732 		connfp++;
28733 	}
28734 }
28735 
28736 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28737 static void
28738 conn_report1(conn_t *connp, void *mp)
28739 {
28740 	char	buf1[INET6_ADDRSTRLEN];
28741 	char	buf2[INET6_ADDRSTRLEN];
28742 	uint_t	print_len, buf_len;
28743 
28744 	ASSERT(connp != NULL);
28745 
28746 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28747 	if (buf_len <= 0)
28748 		return;
28749 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28750 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28751 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28752 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28753 	    "%5d %s/%05d %s/%05d\n",
28754 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28755 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28756 	    buf1, connp->conn_lport,
28757 	    buf2, connp->conn_fport);
28758 	if (print_len < buf_len) {
28759 		((mblk_t *)mp)->b_wptr += print_len;
28760 	} else {
28761 		((mblk_t *)mp)->b_wptr += buf_len;
28762 	}
28763 }
28764 
28765 /*
28766  * Named Dispatch routine to produce a formatted report on all conns
28767  * that are listed in one of the fanout tables.
28768  * This report is accessed by using the ndd utility to "get" ND variable
28769  * "ip_conn_status".
28770  */
28771 /* ARGSUSED */
28772 static int
28773 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28774 {
28775 	conn_t *connp = Q_TO_CONN(q);
28776 
28777 	(void) mi_mpprintf(mp,
28778 	    "CONN      " MI_COL_HDRPAD_STR
28779 	    "rfq      " MI_COL_HDRPAD_STR
28780 	    "stq      " MI_COL_HDRPAD_STR
28781 	    " zone local                 remote");
28782 
28783 	/*
28784 	 * Because of the ndd constraint, at most we can have 64K buffer
28785 	 * to put in all conn info.  So to be more efficient, just
28786 	 * allocate a 64K buffer here, assuming we need that large buffer.
28787 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28788 	 */
28789 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28790 		/* The following may work even if we cannot get a large buf. */
28791 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28792 		return (0);
28793 	}
28794 
28795 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28796 	    connp->conn_netstack->netstack_ip);
28797 	return (0);
28798 }
28799 
28800 /*
28801  * Determine if the ill and multicast aspects of that packets
28802  * "matches" the conn.
28803  */
28804 boolean_t
28805 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28806     zoneid_t zoneid)
28807 {
28808 	ill_t *in_ill;
28809 	boolean_t found;
28810 	ipif_t *ipif;
28811 	ire_t *ire;
28812 	ipaddr_t dst, src;
28813 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28814 
28815 	dst = ipha->ipha_dst;
28816 	src = ipha->ipha_src;
28817 
28818 	/*
28819 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28820 	 * unicast, broadcast and multicast reception to
28821 	 * conn_incoming_ill. conn_wantpacket itself is called
28822 	 * only for BROADCAST and multicast.
28823 	 *
28824 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28825 	 *    is part of a group. Hence, we should be receiving
28826 	 *    just one copy of broadcast for the whole group.
28827 	 *    Thus, if it is part of the group the packet could
28828 	 *    come on any ill of the group and hence we need a
28829 	 *    match on the group. Otherwise, match on ill should
28830 	 *    be sufficient.
28831 	 *
28832 	 * 2) ip_rput does not suppress duplicate multicast packets.
28833 	 *    If there are two interfaces in a ill group and we have
28834 	 *    2 applications (conns) joined a multicast group G on
28835 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28836 	 *    will give us two packets because we join G on both the
28837 	 *    interfaces rather than nominating just one interface
28838 	 *    for receiving multicast like broadcast above. So,
28839 	 *    we have to call ilg_lookup_ill to filter out duplicate
28840 	 *    copies, if ill is part of a group.
28841 	 */
28842 	in_ill = connp->conn_incoming_ill;
28843 	if (in_ill != NULL) {
28844 		if (in_ill->ill_group == NULL) {
28845 			if (in_ill != ill)
28846 				return (B_FALSE);
28847 		} else if (in_ill->ill_group != ill->ill_group) {
28848 			return (B_FALSE);
28849 		}
28850 	}
28851 
28852 	if (!CLASSD(dst)) {
28853 		if (IPCL_ZONE_MATCH(connp, zoneid))
28854 			return (B_TRUE);
28855 		/*
28856 		 * The conn is in a different zone; we need to check that this
28857 		 * broadcast address is configured in the application's zone and
28858 		 * on one ill in the group.
28859 		 */
28860 		ipif = ipif_get_next_ipif(NULL, ill);
28861 		if (ipif == NULL)
28862 			return (B_FALSE);
28863 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28864 		    connp->conn_zoneid, NULL,
28865 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28866 		ipif_refrele(ipif);
28867 		if (ire != NULL) {
28868 			ire_refrele(ire);
28869 			return (B_TRUE);
28870 		} else {
28871 			return (B_FALSE);
28872 		}
28873 	}
28874 
28875 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28876 	    connp->conn_zoneid == zoneid) {
28877 		/*
28878 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28879 		 * disabled, therefore we don't dispatch the multicast packet to
28880 		 * the sending zone.
28881 		 */
28882 		return (B_FALSE);
28883 	}
28884 
28885 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28886 		/*
28887 		 * Multicast packet on the loopback interface: we only match
28888 		 * conns who joined the group in the specified zone.
28889 		 */
28890 		return (B_FALSE);
28891 	}
28892 
28893 	if (connp->conn_multi_router) {
28894 		/* multicast packet and multicast router socket: send up */
28895 		return (B_TRUE);
28896 	}
28897 
28898 	mutex_enter(&connp->conn_lock);
28899 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28900 	mutex_exit(&connp->conn_lock);
28901 	return (found);
28902 }
28903 
28904 /*
28905  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28906  */
28907 /* ARGSUSED */
28908 static void
28909 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28910 {
28911 	ill_t *ill = (ill_t *)q->q_ptr;
28912 	mblk_t	*mp1, *mp2;
28913 	ipif_t  *ipif;
28914 	int err = 0;
28915 	conn_t *connp = NULL;
28916 	ipsq_t	*ipsq;
28917 	arc_t	*arc;
28918 
28919 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28920 
28921 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28922 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28923 
28924 	ASSERT(IAM_WRITER_ILL(ill));
28925 	mp2 = mp->b_cont;
28926 	mp->b_cont = NULL;
28927 
28928 	/*
28929 	 * We have now received the arp bringup completion message
28930 	 * from ARP. Mark the arp bringup as done. Also if the arp
28931 	 * stream has already started closing, send up the AR_ARP_CLOSING
28932 	 * ack now since ARP is waiting in close for this ack.
28933 	 */
28934 	mutex_enter(&ill->ill_lock);
28935 	ill->ill_arp_bringup_pending = 0;
28936 	if (ill->ill_arp_closing) {
28937 		mutex_exit(&ill->ill_lock);
28938 		/* Let's reuse the mp for sending the ack */
28939 		arc = (arc_t *)mp->b_rptr;
28940 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28941 		arc->arc_cmd = AR_ARP_CLOSING;
28942 		qreply(q, mp);
28943 	} else {
28944 		mutex_exit(&ill->ill_lock);
28945 		freeb(mp);
28946 	}
28947 
28948 	ipsq = ill->ill_phyint->phyint_ipsq;
28949 	ipif = ipsq->ipsq_pending_ipif;
28950 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28951 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28952 	if (mp1 == NULL) {
28953 		/* bringup was aborted by the user */
28954 		freemsg(mp2);
28955 		return;
28956 	}
28957 
28958 	/*
28959 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28960 	 * must have an associated conn_t.  Otherwise, we're bringing this
28961 	 * interface back up as part of handling an asynchronous event (e.g.,
28962 	 * physical address change).
28963 	 */
28964 	if (ipsq->ipsq_current_ioctl != 0) {
28965 		ASSERT(connp != NULL);
28966 		q = CONNP_TO_WQ(connp);
28967 	} else {
28968 		ASSERT(connp == NULL);
28969 		q = ill->ill_rq;
28970 	}
28971 
28972 	/*
28973 	 * If the DL_BIND_REQ fails, it is noted
28974 	 * in arc_name_offset.
28975 	 */
28976 	err = *((int *)mp2->b_rptr);
28977 	if (err == 0) {
28978 		if (ipif->ipif_isv6) {
28979 			if ((err = ipif_up_done_v6(ipif)) != 0)
28980 				ip0dbg(("ip_arp_done: init failed\n"));
28981 		} else {
28982 			if ((err = ipif_up_done(ipif)) != 0)
28983 				ip0dbg(("ip_arp_done: init failed\n"));
28984 		}
28985 	} else {
28986 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28987 	}
28988 
28989 	freemsg(mp2);
28990 
28991 	if ((err == 0) && (ill->ill_up_ipifs)) {
28992 		err = ill_up_ipifs(ill, q, mp1);
28993 		if (err == EINPROGRESS)
28994 			return;
28995 	}
28996 
28997 	if (ill->ill_up_ipifs)
28998 		ill_group_cleanup(ill);
28999 
29000 	/*
29001 	 * The operation must complete without EINPROGRESS since
29002 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
29003 	 * Otherwise, the operation will be stuck forever in the ipsq.
29004 	 */
29005 	ASSERT(err != EINPROGRESS);
29006 	if (ipsq->ipsq_current_ioctl != 0)
29007 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
29008 	else
29009 		ipsq_current_finish(ipsq);
29010 }
29011 
29012 /* Allocate the private structure */
29013 static int
29014 ip_priv_alloc(void **bufp)
29015 {
29016 	void	*buf;
29017 
29018 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
29019 		return (ENOMEM);
29020 
29021 	*bufp = buf;
29022 	return (0);
29023 }
29024 
29025 /* Function to delete the private structure */
29026 void
29027 ip_priv_free(void *buf)
29028 {
29029 	ASSERT(buf != NULL);
29030 	kmem_free(buf, sizeof (ip_priv_t));
29031 }
29032 
29033 /*
29034  * The entry point for IPPF processing.
29035  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
29036  * routine just returns.
29037  *
29038  * When called, ip_process generates an ipp_packet_t structure
29039  * which holds the state information for this packet and invokes the
29040  * the classifier (via ipp_packet_process). The classification, depending on
29041  * configured filters, results in a list of actions for this packet. Invoking
29042  * an action may cause the packet to be dropped, in which case the resulting
29043  * mblk (*mpp) is NULL. proc indicates the callout position for
29044  * this packet and ill_index is the interface this packet on or will leave
29045  * on (inbound and outbound resp.).
29046  */
29047 void
29048 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
29049 {
29050 	mblk_t		*mp;
29051 	ip_priv_t	*priv;
29052 	ipp_action_id_t	aid;
29053 	int		rc = 0;
29054 	ipp_packet_t	*pp;
29055 #define	IP_CLASS	"ip"
29056 
29057 	/* If the classifier is not loaded, return  */
29058 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
29059 		return;
29060 	}
29061 
29062 	mp = *mpp;
29063 	ASSERT(mp != NULL);
29064 
29065 	/* Allocate the packet structure */
29066 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
29067 	if (rc != 0) {
29068 		*mpp = NULL;
29069 		freemsg(mp);
29070 		return;
29071 	}
29072 
29073 	/* Allocate the private structure */
29074 	rc = ip_priv_alloc((void **)&priv);
29075 	if (rc != 0) {
29076 		*mpp = NULL;
29077 		freemsg(mp);
29078 		ipp_packet_free(pp);
29079 		return;
29080 	}
29081 	priv->proc = proc;
29082 	priv->ill_index = ill_index;
29083 	ipp_packet_set_private(pp, priv, ip_priv_free);
29084 	ipp_packet_set_data(pp, mp);
29085 
29086 	/* Invoke the classifier */
29087 	rc = ipp_packet_process(&pp);
29088 	if (pp != NULL) {
29089 		mp = ipp_packet_get_data(pp);
29090 		ipp_packet_free(pp);
29091 		if (rc != 0) {
29092 			freemsg(mp);
29093 			*mpp = NULL;
29094 		}
29095 	} else {
29096 		*mpp = NULL;
29097 	}
29098 #undef	IP_CLASS
29099 }
29100 
29101 /*
29102  * Propagate a multicast group membership operation (add/drop) on
29103  * all the interfaces crossed by the related multirt routes.
29104  * The call is considered successful if the operation succeeds
29105  * on at least one interface.
29106  */
29107 static int
29108 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
29109     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
29110     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
29111     mblk_t *first_mp)
29112 {
29113 	ire_t		*ire_gw;
29114 	irb_t		*irb;
29115 	int		error = 0;
29116 	opt_restart_t	*or;
29117 	ip_stack_t	*ipst = ire->ire_ipst;
29118 
29119 	irb = ire->ire_bucket;
29120 	ASSERT(irb != NULL);
29121 
29122 	ASSERT(DB_TYPE(first_mp) == M_CTL);
29123 
29124 	or = (opt_restart_t *)first_mp->b_rptr;
29125 	IRB_REFHOLD(irb);
29126 	for (; ire != NULL; ire = ire->ire_next) {
29127 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
29128 			continue;
29129 		if (ire->ire_addr != group)
29130 			continue;
29131 
29132 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
29133 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
29134 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
29135 		/* No resolver exists for the gateway; skip this ire. */
29136 		if (ire_gw == NULL)
29137 			continue;
29138 
29139 		/*
29140 		 * This function can return EINPROGRESS. If so the operation
29141 		 * will be restarted from ip_restart_optmgmt which will
29142 		 * call ip_opt_set and option processing will restart for
29143 		 * this option. So we may end up calling 'fn' more than once.
29144 		 * This requires that 'fn' is idempotent except for the
29145 		 * return value. The operation is considered a success if
29146 		 * it succeeds at least once on any one interface.
29147 		 */
29148 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
29149 		    NULL, fmode, src, first_mp);
29150 		if (error == 0)
29151 			or->or_private = CGTP_MCAST_SUCCESS;
29152 
29153 		if (ip_debug > 0) {
29154 			ulong_t	off;
29155 			char	*ksym;
29156 			ksym = kobj_getsymname((uintptr_t)fn, &off);
29157 			ip2dbg(("ip_multirt_apply_membership: "
29158 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
29159 			    "error %d [success %u]\n",
29160 			    ksym ? ksym : "?",
29161 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
29162 			    error, or->or_private));
29163 		}
29164 
29165 		ire_refrele(ire_gw);
29166 		if (error == EINPROGRESS) {
29167 			IRB_REFRELE(irb);
29168 			return (error);
29169 		}
29170 	}
29171 	IRB_REFRELE(irb);
29172 	/*
29173 	 * Consider the call as successful if we succeeded on at least
29174 	 * one interface. Otherwise, return the last encountered error.
29175 	 */
29176 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29177 }
29178 
29179 
29180 /*
29181  * Issue a warning regarding a route crossing an interface with an
29182  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29183  * amount of time is logged.
29184  */
29185 static void
29186 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29187 {
29188 	hrtime_t	current = gethrtime();
29189 	char		buf[INET_ADDRSTRLEN];
29190 	ip_stack_t	*ipst = ire->ire_ipst;
29191 
29192 	/* Convert interval in ms to hrtime in ns */
29193 	if (ipst->ips_multirt_bad_mtu_last_time +
29194 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29195 	    current) {
29196 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29197 		    "to %s, incorrect MTU %u (expected %u)\n",
29198 		    ip_dot_addr(ire->ire_addr, buf),
29199 		    ire->ire_max_frag, max_frag);
29200 
29201 		ipst->ips_multirt_bad_mtu_last_time = current;
29202 	}
29203 }
29204 
29205 
29206 /*
29207  * Get the CGTP (multirouting) filtering status.
29208  * If 0, the CGTP hooks are transparent.
29209  */
29210 /* ARGSUSED */
29211 static int
29212 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29213 {
29214 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29215 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29216 
29217 	/*
29218 	 * Only applies to the shared stack since the filter_ops
29219 	 * do not carry an ip_stack_t or zoneid.
29220 	 */
29221 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29222 		return (ENOTSUP);
29223 
29224 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29225 	return (0);
29226 }
29227 
29228 
29229 /*
29230  * Set the CGTP (multirouting) filtering status.
29231  * If the status is changed from active to transparent
29232  * or from transparent to active, forward the new status
29233  * to the filtering module (if loaded).
29234  */
29235 /* ARGSUSED */
29236 static int
29237 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29238     cred_t *ioc_cr)
29239 {
29240 	long		new_value;
29241 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29242 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29243 
29244 	if (secpolicy_net_config(ioc_cr, B_FALSE) != 0)
29245 		return (EPERM);
29246 
29247 	/*
29248 	 * Only applies to the shared stack since the filter_ops
29249 	 * do not carry an ip_stack_t or zoneid.
29250 	 */
29251 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
29252 		return (ENOTSUP);
29253 
29254 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29255 	    new_value < 0 || new_value > 1) {
29256 		return (EINVAL);
29257 	}
29258 
29259 	/*
29260 	 * Do not enable CGTP filtering - thus preventing the hooks
29261 	 * from being invoked - if the version number of the
29262 	 * filtering module hooks does not match.
29263 	 */
29264 	if ((ip_cgtp_filter_ops != NULL) &&
29265 	    (ip_cgtp_filter_ops->cfo_filter_rev != CGTP_FILTER_REV)) {
29266 		cmn_err(CE_WARN, "IP: CGTP filtering version mismatch "
29267 		    "(module hooks version %d, expecting %d)\n",
29268 		    ip_cgtp_filter_ops->cfo_filter_rev,
29269 		    CGTP_FILTER_REV);
29270 		return (ENOTSUP);
29271 	}
29272 
29273 	if ((!*ip_cgtp_filter_value) && new_value) {
29274 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29275 		    ip_cgtp_filter_ops == NULL ?
29276 		    " (module not loaded)" : "");
29277 	}
29278 	if (*ip_cgtp_filter_value && (!new_value)) {
29279 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29280 		    ip_cgtp_filter_ops == NULL ?
29281 		    " (module not loaded)" : "");
29282 	}
29283 
29284 	if (ip_cgtp_filter_ops != NULL) {
29285 		int	res;
29286 
29287 		res = ip_cgtp_filter_ops->cfo_change_state(new_value);
29288 		if (res)
29289 			return (res);
29290 	}
29291 
29292 	*ip_cgtp_filter_value = (boolean_t)new_value;
29293 
29294 	return (0);
29295 }
29296 
29297 
29298 /*
29299  * Return the expected CGTP hooks version number.
29300  */
29301 int
29302 ip_cgtp_filter_supported(void)
29303 {
29304 	ip_stack_t *ipst;
29305 	int ret;
29306 
29307 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29308 	if (ipst == NULL)
29309 		return (-1);
29310 	ret = ip_cgtp_filter_rev;
29311 	netstack_rele(ipst->ips_netstack);
29312 	return (ret);
29313 }
29314 
29315 
29316 /*
29317  * CGTP hooks can be registered by directly touching ip_cgtp_filter_ops
29318  * or by invoking this function. In the first case, the version number
29319  * of the registered structure is checked at hooks activation time
29320  * in ip_cgtp_filter_set().
29321  *
29322  * Only applies to the shared stack since the filter_ops
29323  * do not carry an ip_stack_t or zoneid.
29324  */
29325 int
29326 ip_cgtp_filter_register(cgtp_filter_ops_t *ops)
29327 {
29328 	ip_stack_t *ipst;
29329 
29330 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29331 		return (ENOTSUP);
29332 
29333 	ipst = netstack_find_by_stackid(GLOBAL_NETSTACKID)->netstack_ip;
29334 	if (ipst == NULL)
29335 		return (EINVAL);
29336 
29337 	ip_cgtp_filter_ops = ops;
29338 	netstack_rele(ipst->ips_netstack);
29339 	return (0);
29340 }
29341 
29342 static squeue_func_t
29343 ip_squeue_switch(int val)
29344 {
29345 	squeue_func_t rval = squeue_fill;
29346 
29347 	switch (val) {
29348 	case IP_SQUEUE_ENTER_NODRAIN:
29349 		rval = squeue_enter_nodrain;
29350 		break;
29351 	case IP_SQUEUE_ENTER:
29352 		rval = squeue_enter;
29353 		break;
29354 	default:
29355 		break;
29356 	}
29357 	return (rval);
29358 }
29359 
29360 /* ARGSUSED */
29361 static int
29362 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29363     caddr_t addr, cred_t *cr)
29364 {
29365 	int *v = (int *)addr;
29366 	long new_value;
29367 
29368 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29369 		return (EPERM);
29370 
29371 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29372 		return (EINVAL);
29373 
29374 	ip_input_proc = ip_squeue_switch(new_value);
29375 	*v = new_value;
29376 	return (0);
29377 }
29378 
29379 /* ARGSUSED */
29380 static int
29381 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29382     caddr_t addr, cred_t *cr)
29383 {
29384 	int *v = (int *)addr;
29385 	long new_value;
29386 
29387 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29388 		return (EPERM);
29389 
29390 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29391 		return (EINVAL);
29392 
29393 	*v = new_value;
29394 	return (0);
29395 }
29396 
29397 /*
29398  * Handle changes to ipmp_hook_emulation ndd variable.
29399  * Need to update phyint_hook_ifindex.
29400  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29401  */
29402 static void
29403 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29404 {
29405 	phyint_t *phyi;
29406 	phyint_t *phyi_tmp;
29407 	char *groupname;
29408 	int namelen;
29409 	ill_t	*ill;
29410 	boolean_t new_group;
29411 
29412 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29413 	/*
29414 	 * Group indicies are stored in the phyint - a common structure
29415 	 * to both IPv4 and IPv6.
29416 	 */
29417 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29418 	for (; phyi != NULL;
29419 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29420 	    phyi, AVL_AFTER)) {
29421 		/* Ignore the ones that do not have a group */
29422 		if (phyi->phyint_groupname_len == 0)
29423 			continue;
29424 
29425 		/*
29426 		 * Look for other phyint in group.
29427 		 * Clear name/namelen so the lookup doesn't find ourselves.
29428 		 */
29429 		namelen = phyi->phyint_groupname_len;
29430 		groupname = phyi->phyint_groupname;
29431 		phyi->phyint_groupname_len = 0;
29432 		phyi->phyint_groupname = NULL;
29433 
29434 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29435 		/* Restore */
29436 		phyi->phyint_groupname_len = namelen;
29437 		phyi->phyint_groupname = groupname;
29438 
29439 		new_group = B_FALSE;
29440 		if (ipst->ips_ipmp_hook_emulation) {
29441 			/*
29442 			 * If the group already exists and has already
29443 			 * been assigned a group ifindex, we use the existing
29444 			 * group_ifindex, otherwise we pick a new group_ifindex
29445 			 * here.
29446 			 */
29447 			if (phyi_tmp != NULL &&
29448 			    phyi_tmp->phyint_group_ifindex != 0) {
29449 				phyi->phyint_group_ifindex =
29450 				    phyi_tmp->phyint_group_ifindex;
29451 			} else {
29452 				/* XXX We need a recovery strategy here. */
29453 				if (!ip_assign_ifindex(
29454 				    &phyi->phyint_group_ifindex, ipst))
29455 					cmn_err(CE_PANIC,
29456 					    "ip_assign_ifindex() failed");
29457 				new_group = B_TRUE;
29458 			}
29459 		} else {
29460 			phyi->phyint_group_ifindex = 0;
29461 		}
29462 		if (ipst->ips_ipmp_hook_emulation)
29463 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29464 		else
29465 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29466 
29467 		/*
29468 		 * For IP Filter to find out the relationship between
29469 		 * names and interface indicies, we need to generate
29470 		 * a NE_PLUMB event when a new group can appear.
29471 		 * We always generate events when a new interface appears
29472 		 * (even when ipmp_hook_emulation is set) so there
29473 		 * is no need to generate NE_PLUMB events when
29474 		 * ipmp_hook_emulation is turned off.
29475 		 * And since it isn't critical for IP Filter to get
29476 		 * the NE_UNPLUMB events we skip those here.
29477 		 */
29478 		if (new_group) {
29479 			/*
29480 			 * First phyint in group - generate group PLUMB event.
29481 			 * Since we are not running inside the ipsq we do
29482 			 * the dispatch immediately.
29483 			 */
29484 			if (phyi->phyint_illv4 != NULL)
29485 				ill = phyi->phyint_illv4;
29486 			else
29487 				ill = phyi->phyint_illv6;
29488 
29489 			if (ill != NULL) {
29490 				mutex_enter(&ill->ill_lock);
29491 				ill_nic_info_plumb(ill, B_TRUE);
29492 				ill_nic_info_dispatch(ill);
29493 				mutex_exit(&ill->ill_lock);
29494 			}
29495 		}
29496 	}
29497 	rw_exit(&ipst->ips_ill_g_lock);
29498 }
29499 
29500 /* ARGSUSED */
29501 static int
29502 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29503     caddr_t addr, cred_t *cr)
29504 {
29505 	int *v = (int *)addr;
29506 	long new_value;
29507 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29508 
29509 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29510 		return (EINVAL);
29511 
29512 	if (*v != new_value) {
29513 		*v = new_value;
29514 		ipmp_hook_emulation_changed(ipst);
29515 	}
29516 	return (0);
29517 }
29518 
29519 static void *
29520 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29521 {
29522 	kstat_t *ksp;
29523 
29524 	ip_stat_t template = {
29525 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29526 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29527 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29528 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29529 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29530 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29531 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29532 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29533 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29534 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29535 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29536 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29537 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29538 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29539 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29540 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29541 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29542 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29543 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29544 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29545 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29546 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29547 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29548 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29549 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29550 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29551 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29552 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29553 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29554 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29555 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29556 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29557 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29558 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29559 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29560 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29561 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29562 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29563 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29564 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29565 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29566 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29567 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29568 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29569 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29570 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29571 	};
29572 
29573 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29574 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29575 	    KSTAT_FLAG_VIRTUAL, stackid);
29576 
29577 	if (ksp == NULL)
29578 		return (NULL);
29579 
29580 	bcopy(&template, ip_statisticsp, sizeof (template));
29581 	ksp->ks_data = (void *)ip_statisticsp;
29582 	ksp->ks_private = (void *)(uintptr_t)stackid;
29583 
29584 	kstat_install(ksp);
29585 	return (ksp);
29586 }
29587 
29588 static void
29589 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29590 {
29591 	if (ksp != NULL) {
29592 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29593 		kstat_delete_netstack(ksp, stackid);
29594 	}
29595 }
29596 
29597 static void *
29598 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29599 {
29600 	kstat_t	*ksp;
29601 
29602 	ip_named_kstat_t template = {
29603 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29604 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29605 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29606 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29607 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29608 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29609 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29610 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29611 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29612 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29613 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29614 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29615 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29616 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29617 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29618 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29619 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29620 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29621 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29622 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29623 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29624 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29625 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29626 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29627 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29628 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29629 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29630 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29631 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29632 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29633 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29634 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29635 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29636 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29637 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29638 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29639 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29640 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29641 	};
29642 
29643 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29644 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29645 	if (ksp == NULL || ksp->ks_data == NULL)
29646 		return (NULL);
29647 
29648 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29649 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29650 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29651 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29652 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29653 
29654 	template.netToMediaEntrySize.value.i32 =
29655 	    sizeof (mib2_ipNetToMediaEntry_t);
29656 
29657 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29658 
29659 	bcopy(&template, ksp->ks_data, sizeof (template));
29660 	ksp->ks_update = ip_kstat_update;
29661 	ksp->ks_private = (void *)(uintptr_t)stackid;
29662 
29663 	kstat_install(ksp);
29664 	return (ksp);
29665 }
29666 
29667 static void
29668 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29669 {
29670 	if (ksp != NULL) {
29671 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29672 		kstat_delete_netstack(ksp, stackid);
29673 	}
29674 }
29675 
29676 static int
29677 ip_kstat_update(kstat_t *kp, int rw)
29678 {
29679 	ip_named_kstat_t *ipkp;
29680 	mib2_ipIfStatsEntry_t ipmib;
29681 	ill_walk_context_t ctx;
29682 	ill_t *ill;
29683 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29684 	netstack_t	*ns;
29685 	ip_stack_t	*ipst;
29686 
29687 	if (kp == NULL || kp->ks_data == NULL)
29688 		return (EIO);
29689 
29690 	if (rw == KSTAT_WRITE)
29691 		return (EACCES);
29692 
29693 	ns = netstack_find_by_stackid(stackid);
29694 	if (ns == NULL)
29695 		return (-1);
29696 	ipst = ns->netstack_ip;
29697 	if (ipst == NULL) {
29698 		netstack_rele(ns);
29699 		return (-1);
29700 	}
29701 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29702 
29703 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29704 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29705 	ill = ILL_START_WALK_V4(&ctx, ipst);
29706 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29707 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29708 	rw_exit(&ipst->ips_ill_g_lock);
29709 
29710 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29711 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29712 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29713 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29714 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29715 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29716 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29717 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29718 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29719 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29720 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29721 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29722 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29723 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29724 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29725 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29726 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29727 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29728 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29729 
29730 	ipkp->routingDiscards.value.ui32 =	0;
29731 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29732 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29733 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29734 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29735 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29736 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29737 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29738 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29739 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29740 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29741 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29742 
29743 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29744 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29745 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29746 
29747 	netstack_rele(ns);
29748 
29749 	return (0);
29750 }
29751 
29752 static void *
29753 icmp_kstat_init(netstackid_t stackid)
29754 {
29755 	kstat_t	*ksp;
29756 
29757 	icmp_named_kstat_t template = {
29758 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29759 		{ "inErrors",		KSTAT_DATA_UINT32 },
29760 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29761 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29762 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29763 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29764 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29765 		{ "inEchos",		KSTAT_DATA_UINT32 },
29766 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29767 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29768 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29769 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29770 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29771 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29772 		{ "outErrors",		KSTAT_DATA_UINT32 },
29773 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29774 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29775 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29776 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29777 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29778 		{ "outEchos",		KSTAT_DATA_UINT32 },
29779 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29780 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29781 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29782 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29783 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29784 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29785 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29786 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29787 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29788 		{ "outDrops",		KSTAT_DATA_UINT32 },
29789 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29790 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29791 	};
29792 
29793 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29794 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29795 	if (ksp == NULL || ksp->ks_data == NULL)
29796 		return (NULL);
29797 
29798 	bcopy(&template, ksp->ks_data, sizeof (template));
29799 
29800 	ksp->ks_update = icmp_kstat_update;
29801 	ksp->ks_private = (void *)(uintptr_t)stackid;
29802 
29803 	kstat_install(ksp);
29804 	return (ksp);
29805 }
29806 
29807 static void
29808 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29809 {
29810 	if (ksp != NULL) {
29811 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29812 		kstat_delete_netstack(ksp, stackid);
29813 	}
29814 }
29815 
29816 static int
29817 icmp_kstat_update(kstat_t *kp, int rw)
29818 {
29819 	icmp_named_kstat_t *icmpkp;
29820 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29821 	netstack_t	*ns;
29822 	ip_stack_t	*ipst;
29823 
29824 	if ((kp == NULL) || (kp->ks_data == NULL))
29825 		return (EIO);
29826 
29827 	if (rw == KSTAT_WRITE)
29828 		return (EACCES);
29829 
29830 	ns = netstack_find_by_stackid(stackid);
29831 	if (ns == NULL)
29832 		return (-1);
29833 	ipst = ns->netstack_ip;
29834 	if (ipst == NULL) {
29835 		netstack_rele(ns);
29836 		return (-1);
29837 	}
29838 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29839 
29840 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29841 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29842 	icmpkp->inDestUnreachs.value.ui32 =
29843 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29844 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29845 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29846 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29847 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29848 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29849 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29850 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29851 	icmpkp->inTimestampReps.value.ui32 =
29852 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29853 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29854 	icmpkp->inAddrMaskReps.value.ui32 =
29855 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29856 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29857 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29858 	icmpkp->outDestUnreachs.value.ui32 =
29859 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29860 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29861 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29862 	icmpkp->outSrcQuenchs.value.ui32 =
29863 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29864 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29865 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29866 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29867 	icmpkp->outTimestamps.value.ui32 =
29868 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29869 	icmpkp->outTimestampReps.value.ui32 =
29870 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29871 	icmpkp->outAddrMasks.value.ui32 =
29872 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29873 	icmpkp->outAddrMaskReps.value.ui32 =
29874 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29875 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29876 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29877 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29878 	icmpkp->outFragNeeded.value.ui32 =
29879 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29880 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29881 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29882 	icmpkp->inBadRedirects.value.ui32 =
29883 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29884 
29885 	netstack_rele(ns);
29886 	return (0);
29887 }
29888 
29889 /*
29890  * This is the fanout function for raw socket opened for SCTP.  Note
29891  * that it is called after SCTP checks that there is no socket which
29892  * wants a packet.  Then before SCTP handles this out of the blue packet,
29893  * this function is called to see if there is any raw socket for SCTP.
29894  * If there is and it is bound to the correct address, the packet will
29895  * be sent to that socket.  Note that only one raw socket can be bound to
29896  * a port.  This is assured in ipcl_sctp_hash_insert();
29897  */
29898 void
29899 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29900     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29901     zoneid_t zoneid)
29902 {
29903 	conn_t		*connp;
29904 	queue_t		*rq;
29905 	mblk_t		*first_mp;
29906 	boolean_t	secure;
29907 	ip6_t		*ip6h;
29908 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29909 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29910 
29911 	first_mp = mp;
29912 	if (mctl_present) {
29913 		mp = first_mp->b_cont;
29914 		secure = ipsec_in_is_secure(first_mp);
29915 		ASSERT(mp != NULL);
29916 	} else {
29917 		secure = B_FALSE;
29918 	}
29919 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29920 
29921 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29922 	if (connp == NULL) {
29923 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29924 		return;
29925 	}
29926 	rq = connp->conn_rq;
29927 	if (!canputnext(rq)) {
29928 		CONN_DEC_REF(connp);
29929 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29930 		freemsg(first_mp);
29931 		return;
29932 	}
29933 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29934 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29935 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29936 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29937 		if (first_mp == NULL) {
29938 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29939 			CONN_DEC_REF(connp);
29940 			return;
29941 		}
29942 	}
29943 	/*
29944 	 * We probably should not send M_CTL message up to
29945 	 * raw socket.
29946 	 */
29947 	if (mctl_present)
29948 		freeb(first_mp);
29949 
29950 	/* Initiate IPPF processing here if needed. */
29951 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29952 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29953 		ip_process(IPP_LOCAL_IN, &mp,
29954 		    recv_ill->ill_phyint->phyint_ifindex);
29955 		if (mp == NULL) {
29956 			CONN_DEC_REF(connp);
29957 			return;
29958 		}
29959 	}
29960 
29961 	if (connp->conn_recvif || connp->conn_recvslla ||
29962 	    ((connp->conn_ip_recvpktinfo ||
29963 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29964 	    (flags & IP_FF_IPINFO))) {
29965 		int in_flags = 0;
29966 
29967 		/*
29968 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29969 		 * IPF_RECVIF.
29970 		 */
29971 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29972 			in_flags = IPF_RECVIF;
29973 		}
29974 		if (connp->conn_recvslla) {
29975 			in_flags |= IPF_RECVSLLA;
29976 		}
29977 		if (isv4) {
29978 			mp = ip_add_info(mp, recv_ill, in_flags,
29979 			    IPCL_ZONEID(connp), ipst);
29980 		} else {
29981 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29982 			if (mp == NULL) {
29983 				BUMP_MIB(recv_ill->ill_ip_mib,
29984 				    ipIfStatsInDiscards);
29985 				CONN_DEC_REF(connp);
29986 				return;
29987 			}
29988 		}
29989 	}
29990 
29991 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29992 	/*
29993 	 * We are sending the IPSEC_IN message also up. Refer
29994 	 * to comments above this function.
29995 	 */
29996 	putnext(rq, mp);
29997 	CONN_DEC_REF(connp);
29998 }
29999 
30000 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
30001 {									\
30002 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
30003 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
30004 }
30005 /*
30006  * This function should be called only if all packet processing
30007  * including fragmentation is complete. Callers of this function
30008  * must set mp->b_prev to one of these values:
30009  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
30010  * prior to handing over the mp as first argument to this function.
30011  *
30012  * If the ire passed by caller is incomplete, this function
30013  * queues the packet and if necessary, sends ARP request and bails.
30014  * If the ire passed is fully resolved, we simply prepend
30015  * the link-layer header to the packet, do ipsec hw acceleration
30016  * work if necessary, and send the packet out on the wire.
30017  *
30018  * NOTE: IPSEC will only call this function with fully resolved
30019  * ires if hw acceleration is involved.
30020  * TODO list :
30021  * 	a Handle M_MULTIDATA so that
30022  *	  tcp_multisend->tcp_multisend_data can
30023  *	  call ip_xmit_v4 directly
30024  *	b Handle post-ARP work for fragments so that
30025  *	  ip_wput_frag can call this function.
30026  */
30027 ipxmit_state_t
30028 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
30029 {
30030 	nce_t		*arpce;
30031 	queue_t		*q;
30032 	int		ill_index;
30033 	mblk_t		*nxt_mp, *first_mp;
30034 	boolean_t	xmit_drop = B_FALSE;
30035 	ip_proc_t	proc;
30036 	ill_t		*out_ill;
30037 	int		pkt_len;
30038 
30039 	arpce = ire->ire_nce;
30040 	ASSERT(arpce != NULL);
30041 
30042 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
30043 
30044 	mutex_enter(&arpce->nce_lock);
30045 	switch (arpce->nce_state) {
30046 	case ND_REACHABLE:
30047 		/* If there are other queued packets, queue this packet */
30048 		if (arpce->nce_qd_mp != NULL) {
30049 			if (mp != NULL)
30050 				nce_queue_mp_common(arpce, mp, B_FALSE);
30051 			mp = arpce->nce_qd_mp;
30052 		}
30053 		arpce->nce_qd_mp = NULL;
30054 		mutex_exit(&arpce->nce_lock);
30055 
30056 		/*
30057 		 * Flush the queue.  In the common case, where the
30058 		 * ARP is already resolved,  it will go through the
30059 		 * while loop only once.
30060 		 */
30061 		while (mp != NULL) {
30062 
30063 			nxt_mp = mp->b_next;
30064 			mp->b_next = NULL;
30065 			ASSERT(mp->b_datap->db_type != M_CTL);
30066 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
30067 			/*
30068 			 * This info is needed for IPQOS to do COS marking
30069 			 * in ip_wput_attach_llhdr->ip_process.
30070 			 */
30071 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
30072 			mp->b_prev = NULL;
30073 
30074 			/* set up ill index for outbound qos processing */
30075 			out_ill = ire->ire_ipif->ipif_ill;
30076 			ill_index = out_ill->ill_phyint->phyint_ifindex;
30077 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
30078 			    ill_index);
30079 			if (first_mp == NULL) {
30080 				xmit_drop = B_TRUE;
30081 				BUMP_MIB(out_ill->ill_ip_mib,
30082 				    ipIfStatsOutDiscards);
30083 				goto next_mp;
30084 			}
30085 			/* non-ipsec hw accel case */
30086 			if (io == NULL || !io->ipsec_out_accelerated) {
30087 				/* send it */
30088 				q = ire->ire_stq;
30089 				if (proc == IPP_FWD_OUT) {
30090 					UPDATE_IB_PKT_COUNT(ire);
30091 				} else {
30092 					UPDATE_OB_PKT_COUNT(ire);
30093 				}
30094 				ire->ire_last_used_time = lbolt;
30095 
30096 				if (flow_ctl_enabled || canputnext(q)) {
30097 					if (proc == IPP_FWD_OUT) {
30098 
30099 					BUMP_MIB(out_ill->ill_ip_mib,
30100 					    ipIfStatsHCOutForwDatagrams);
30101 
30102 					}
30103 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
30104 					    pkt_len);
30105 
30106 					putnext(q, first_mp);
30107 				} else {
30108 					BUMP_MIB(out_ill->ill_ip_mib,
30109 					    ipIfStatsOutDiscards);
30110 					xmit_drop = B_TRUE;
30111 					freemsg(first_mp);
30112 				}
30113 			} else {
30114 				/*
30115 				 * Safety Pup says: make sure this
30116 				 *  is going to the right interface!
30117 				 */
30118 				ill_t *ill1 =
30119 				    (ill_t *)ire->ire_stq->q_ptr;
30120 				int ifindex =
30121 				    ill1->ill_phyint->phyint_ifindex;
30122 				if (ifindex !=
30123 				    io->ipsec_out_capab_ill_index) {
30124 					xmit_drop = B_TRUE;
30125 					freemsg(mp);
30126 				} else {
30127 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30128 					    pkt_len);
30129 					ipsec_hw_putnext(ire->ire_stq, mp);
30130 				}
30131 			}
30132 next_mp:
30133 			mp = nxt_mp;
30134 		} /* while (mp != NULL) */
30135 		if (xmit_drop)
30136 			return (SEND_FAILED);
30137 		else
30138 			return (SEND_PASSED);
30139 
30140 	case ND_INITIAL:
30141 	case ND_INCOMPLETE:
30142 
30143 		/*
30144 		 * While we do send off packets to dests that
30145 		 * use fully-resolved CGTP routes, we do not
30146 		 * handle unresolved CGTP routes.
30147 		 */
30148 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30149 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30150 
30151 		if (mp != NULL) {
30152 			/* queue the packet */
30153 			nce_queue_mp_common(arpce, mp, B_FALSE);
30154 		}
30155 
30156 		if (arpce->nce_state == ND_INCOMPLETE) {
30157 			mutex_exit(&arpce->nce_lock);
30158 			DTRACE_PROBE3(ip__xmit__incomplete,
30159 			    (ire_t *), ire, (mblk_t *), mp,
30160 			    (ipsec_out_t *), io);
30161 			return (LOOKUP_IN_PROGRESS);
30162 		}
30163 
30164 		arpce->nce_state = ND_INCOMPLETE;
30165 		mutex_exit(&arpce->nce_lock);
30166 		/*
30167 		 * Note that ire_add() (called from ire_forward())
30168 		 * holds a ref on the ire until ARP is completed.
30169 		 */
30170 
30171 		ire_arpresolve(ire, ire_to_ill(ire));
30172 		return (LOOKUP_IN_PROGRESS);
30173 	default:
30174 		ASSERT(0);
30175 		mutex_exit(&arpce->nce_lock);
30176 		return (LLHDR_RESLV_FAILED);
30177 	}
30178 }
30179 
30180 #undef	UPDATE_IP_MIB_OB_COUNTERS
30181 
30182 /*
30183  * Return B_TRUE if the buffers differ in length or content.
30184  * This is used for comparing extension header buffers.
30185  * Note that an extension header would be declared different
30186  * even if all that changed was the next header value in that header i.e.
30187  * what really changed is the next extension header.
30188  */
30189 boolean_t
30190 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30191     uint_t blen)
30192 {
30193 	if (!b_valid)
30194 		blen = 0;
30195 
30196 	if (alen != blen)
30197 		return (B_TRUE);
30198 	if (alen == 0)
30199 		return (B_FALSE);	/* Both zero length */
30200 	return (bcmp(abuf, bbuf, alen));
30201 }
30202 
30203 /*
30204  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30205  * Return B_FALSE if memory allocation fails - don't change any state!
30206  */
30207 boolean_t
30208 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30209     const void *src, uint_t srclen)
30210 {
30211 	void *dst;
30212 
30213 	if (!src_valid)
30214 		srclen = 0;
30215 
30216 	ASSERT(*dstlenp == 0);
30217 	if (src != NULL && srclen != 0) {
30218 		dst = mi_alloc(srclen, BPRI_MED);
30219 		if (dst == NULL)
30220 			return (B_FALSE);
30221 	} else {
30222 		dst = NULL;
30223 	}
30224 	if (*dstp != NULL)
30225 		mi_free(*dstp);
30226 	*dstp = dst;
30227 	*dstlenp = dst == NULL ? 0 : srclen;
30228 	return (B_TRUE);
30229 }
30230 
30231 /*
30232  * Replace what is in *dst, *dstlen with the source.
30233  * Assumes ip_allocbuf has already been called.
30234  */
30235 void
30236 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30237     const void *src, uint_t srclen)
30238 {
30239 	if (!src_valid)
30240 		srclen = 0;
30241 
30242 	ASSERT(*dstlenp == srclen);
30243 	if (src != NULL && srclen != 0)
30244 		bcopy(src, *dstp, srclen);
30245 }
30246 
30247 /*
30248  * Free the storage pointed to by the members of an ip6_pkt_t.
30249  */
30250 void
30251 ip6_pkt_free(ip6_pkt_t *ipp)
30252 {
30253 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30254 
30255 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30256 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30257 		ipp->ipp_hopopts = NULL;
30258 		ipp->ipp_hopoptslen = 0;
30259 	}
30260 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30261 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30262 		ipp->ipp_rtdstopts = NULL;
30263 		ipp->ipp_rtdstoptslen = 0;
30264 	}
30265 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30266 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30267 		ipp->ipp_dstopts = NULL;
30268 		ipp->ipp_dstoptslen = 0;
30269 	}
30270 	if (ipp->ipp_fields & IPPF_RTHDR) {
30271 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30272 		ipp->ipp_rthdr = NULL;
30273 		ipp->ipp_rthdrlen = 0;
30274 	}
30275 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30276 	    IPPF_RTHDR);
30277 }
30278