xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 843e19887f64dde75055cf8842fc4db2171eff45)
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  * It would be nice to have these present only in DEBUG systems, but the
158  * current design of the global symbol checking logic requires them to be
159  * unconditionally present.
160  */
161 uint_t ip_thread_data;			/* TSD key for debug support */
162 krwlock_t ip_thread_rwlock;
163 list_t	ip_thread_list;
164 
165 /*
166  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
167  */
168 
169 struct listptr_s {
170 	mblk_t	*lp_head;	/* pointer to the head of the list */
171 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
172 };
173 
174 typedef struct listptr_s listptr_t;
175 
176 /*
177  * This is used by ip_snmp_get_mib2_ip_route_media and
178  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
179  */
180 typedef struct iproutedata_s {
181 	uint_t		ird_idx;
182 	listptr_t	ird_route;	/* ipRouteEntryTable */
183 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
184 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
185 } iproutedata_t;
186 
187 /*
188  * Cluster specific hooks. These should be NULL when booted as a non-cluster
189  */
190 
191 /*
192  * Hook functions to enable cluster networking
193  * On non-clustered systems these vectors must always be NULL.
194  *
195  * Hook function to Check ip specified ip address is a shared ip address
196  * in the cluster
197  *
198  */
199 int (*cl_inet_isclusterwide)(uint8_t protocol,
200     sa_family_t addr_family, uint8_t *laddrp) = NULL;
201 
202 /*
203  * Hook function to generate cluster wide ip fragment identifier
204  */
205 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
206     uint8_t *laddrp, uint8_t *faddrp) = NULL;
207 
208 /*
209  * Synchronization notes:
210  *
211  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
212  * MT level protection given by STREAMS. IP uses a combination of its own
213  * internal serialization mechanism and standard Solaris locking techniques.
214  * The internal serialization is per phyint (no IPMP) or per IPMP group.
215  * This is used to serialize plumbing operations, IPMP operations, certain
216  * multicast operations, most set ioctls, igmp/mld timers etc.
217  *
218  * Plumbing is a long sequence of operations involving message
219  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
220  * involved in plumbing operations. A natural model is to serialize these
221  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
222  * parallel without any interference. But various set ioctls on hme0 are best
223  * serialized. However if the system uses IPMP, the operations are easier if
224  * they are serialized on a per IPMP group basis since IPMP operations
225  * happen across ill's of a group. Thus the lowest common denominator is to
226  * serialize most set ioctls, multicast join/leave operations, IPMP operations
227  * igmp/mld timer operations, and processing of DLPI control messages received
228  * from drivers on a per IPMP group basis. If the system does not employ
229  * IPMP the serialization is on a per phyint basis. This serialization is
230  * provided by the ipsq_t and primitives operating on this. Details can
231  * be found in ip_if.c above the core primitives operating on ipsq_t.
232  *
233  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
234  * Simiarly lookup of an ire by a thread also returns a refheld ire.
235  * In addition ipif's and ill's referenced by the ire are also indirectly
236  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
237  * the ipif's address or netmask change as long as an ipif is refheld
238  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
239  * address of an ipif has to go through the ipsq_t. This ensures that only
240  * 1 such exclusive operation proceeds at any time on the ipif. It then
241  * deletes all ires associated with this ipif, and waits for all refcnts
242  * associated with this ipif to come down to zero. The address is changed
243  * only after the ipif has been quiesced. Then the ipif is brought up again.
244  * More details are described above the comment in ip_sioctl_flags.
245  *
246  * Packet processing is based mostly on IREs and are fully multi-threaded
247  * using standard Solaris MT techniques.
248  *
249  * There are explicit locks in IP to handle:
250  * - The ip_g_head list maintained by mi_open_link() and friends.
251  *
252  * - The reassembly data structures (one lock per hash bucket)
253  *
254  * - conn_lock is meant to protect conn_t fields. The fields actually
255  *   protected by conn_lock are documented in the conn_t definition.
256  *
257  * - ire_lock to protect some of the fields of the ire, IRE tables
258  *   (one lock per hash bucket). Refer to ip_ire.c for details.
259  *
260  * - ndp_g_lock and nce_lock for protecting NCEs.
261  *
262  * - ill_lock protects fields of the ill and ipif. Details in ip.h
263  *
264  * - ill_g_lock: This is a global reader/writer lock. Protects the following
265  *	* The AVL tree based global multi list of all ills.
266  *	* The linked list of all ipifs of an ill
267  *	* The <ill-ipsq> mapping
268  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
269  *	* The illgroup list threaded by ill_group_next.
270  *	* <ill-phyint> association
271  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
272  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
273  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
274  *   will all have to hold the ill_g_lock as writer for the actual duration
275  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
276  *   may be found in the IPMP section.
277  *
278  * - ill_lock:  This is a per ill mutex.
279  *   It protects some members of the ill and is documented below.
280  *   It also protects the <ill-ipsq> mapping
281  *   It also protects the illgroup list threaded by ill_group_next.
282  *   It also protects the <ill-phyint> assoc.
283  *   It also protects the list of ipifs hanging off the ill.
284  *
285  * - ipsq_lock: This is a per ipsq_t mutex lock.
286  *   This protects all the other members of the ipsq struct except
287  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
288  *
289  * - illgrp_lock: This is a per ill_group mutex lock.
290  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
291  *   which dictates which is the next ill in an ill_group that is to be chosen
292  *   for sending outgoing packets, through creation of an IRE_CACHE that
293  *   references this ill.
294  *
295  * - phyint_lock: This is a per phyint mutex lock. Protects just the
296  *   phyint_flags
297  *
298  * - ip_g_nd_lock: This is a global reader/writer lock.
299  *   Any call to nd_load to load a new parameter to the ND table must hold the
300  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
301  *   as reader.
302  *
303  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
304  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
305  *   uniqueness check also done atomically.
306  *
307  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
308  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
309  *   as a writer when adding or deleting elements from these lists, and
310  *   as a reader when walking these lists to send a SADB update to the
311  *   IPsec capable ills.
312  *
313  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
314  *   group list linked by ill_usesrc_grp_next. It also protects the
315  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
316  *   group is being added or deleted.  This lock is taken as a reader when
317  *   walking the list/group(eg: to get the number of members in a usesrc group).
318  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
319  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
320  *   example, it is not necessary to take this lock in the initial portion
321  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
322  *   ip_sioctl_flags since the these operations are executed exclusively and
323  *   that ensures that the "usesrc group state" cannot change. The "usesrc
324  *   group state" change can happen only in the latter part of
325  *   ip_sioctl_slifusesrc and in ill_delete.
326  *
327  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
328  *
329  * To change the <ill-phyint> association, the ill_g_lock must be held
330  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
331  * must be held.
332  *
333  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
334  * and the ill_lock of the ill in question must be held.
335  *
336  * To change the <ill-illgroup> association the ill_g_lock must be held as
337  * writer and the ill_lock of the ill in question must be held.
338  *
339  * To add or delete an ipif from the list of ipifs hanging off the ill,
340  * ill_g_lock (writer) and ill_lock must be held and the thread must be
341  * a writer on the associated ipsq,.
342  *
343  * To add or delete an ill to the system, the ill_g_lock must be held as
344  * writer and the thread must be a writer on the associated ipsq.
345  *
346  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
347  * must be a writer on the associated ipsq.
348  *
349  * Lock hierarchy
350  *
351  * Some lock hierarchy scenarios are listed below.
352  *
353  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
354  * ill_g_lock -> illgrp_lock -> ill_lock
355  * ill_g_lock -> ill_lock(s) -> phyint_lock
356  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
357  * ill_g_lock -> ip_addr_avail_lock
358  * conn_lock -> irb_lock -> ill_lock -> ire_lock
359  * ill_g_lock -> ip_g_nd_lock
360  *
361  * When more than 1 ill lock is needed to be held, all ill lock addresses
362  * are sorted on address and locked starting from highest addressed lock
363  * downward.
364  *
365  * IPsec scenarios
366  *
367  * ipsa_lock -> ill_g_lock -> ill_lock
368  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
369  * ipsec_capab_ills_lock -> ipsa_lock
370  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
371  *
372  * Trusted Solaris scenarios
373  *
374  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
375  * igsa_lock -> gcdb_lock
376  * gcgrp_rwlock -> ire_lock
377  * gcgrp_rwlock -> gcdb_lock
378  *
379  *
380  * Routing/forwarding table locking notes:
381  *
382  * Lock acquisition order: Radix tree lock, irb_lock.
383  * Requirements:
384  * i.  Walker must not hold any locks during the walker callback.
385  * ii  Walker must not see a truncated tree during the walk because of any node
386  *     deletion.
387  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
388  *     in many places in the code to walk the irb list. Thus even if all the
389  *     ires in a bucket have been deleted, we still can't free the radix node
390  *     until the ires have actually been inactive'd (freed).
391  *
392  * Tree traversal - Need to hold the global tree lock in read mode.
393  * Before dropping the global tree lock, need to either increment the ire_refcnt
394  * to ensure that the radix node can't be deleted.
395  *
396  * Tree add - Need to hold the global tree lock in write mode to add a
397  * radix node. To prevent the node from being deleted, increment the
398  * irb_refcnt, after the node is added to the tree. The ire itself is
399  * added later while holding the irb_lock, but not the tree lock.
400  *
401  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
402  * All associated ires must be inactive (i.e. freed), and irb_refcnt
403  * must be zero.
404  *
405  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
406  * global tree lock (read mode) for traversal.
407  *
408  * IPsec notes :
409  *
410  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
411  * in front of the actual packet. For outbound datagrams, the M_CTL
412  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
413  * information used by the IPsec code for applying the right level of
414  * protection. The information initialized by IP in the ipsec_out_t
415  * is determined by the per-socket policy or global policy in the system.
416  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
417  * ipsec_info.h) which starts out with nothing in it. It gets filled
418  * with the right information if it goes through the AH/ESP code, which
419  * happens if the incoming packet is secure. The information initialized
420  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
421  * the policy requirements needed by per-socket policy or global policy
422  * is met or not.
423  *
424  * If there is both per-socket policy (set using setsockopt) and there
425  * is also global policy match for the 5 tuples of the socket,
426  * ipsec_override_policy() makes the decision of which one to use.
427  *
428  * For fully connected sockets i.e dst, src [addr, port] is known,
429  * conn_policy_cached is set indicating that policy has been cached.
430  * conn_in_enforce_policy may or may not be set depending on whether
431  * there is a global policy match or per-socket policy match.
432  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
433  * Once the right policy is set on the conn_t, policy cannot change for
434  * this socket. This makes life simpler for TCP (UDP ?) where
435  * re-transmissions go out with the same policy. For symmetry, policy
436  * is cached for fully connected UDP sockets also. Thus if policy is cached,
437  * it also implies that policy is latched i.e policy cannot change
438  * on these sockets. As we have the right policy on the conn, we don't
439  * have to lookup global policy for every outbound and inbound datagram
440  * and thus serving as an optimization. Note that a global policy change
441  * does not affect fully connected sockets if they have policy. If fully
442  * connected sockets did not have any policy associated with it, global
443  * policy change may affect them.
444  *
445  * IP Flow control notes:
446  *
447  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
448  * cannot be sent down to the driver by IP, because of a canput failure, IP
449  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
450  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
451  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
452  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
453  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
454  * the queued messages, and removes the conn from the drain list, if all
455  * messages were drained. It also qenables the next conn in the drain list to
456  * continue the drain process.
457  *
458  * In reality the drain list is not a single list, but a configurable number
459  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
460  * list. If the ip_wsrv of the next qenabled conn does not run, because the
461  * stream closes, ip_close takes responsibility to qenable the next conn in
462  * the drain list. The directly called ip_wput path always does a putq, if
463  * it cannot putnext. Thus synchronization problems are handled between
464  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
465  * functions that manipulate this drain list. Furthermore conn_drain_insert
466  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
467  * running on a queue at any time. conn_drain_tail can be simultaneously called
468  * from both ip_wsrv and ip_close.
469  *
470  * IPQOS notes:
471  *
472  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
473  * and IPQoS modules. IPPF includes hooks in IP at different control points
474  * (callout positions) which direct packets to IPQoS modules for policy
475  * processing. Policies, if present, are global.
476  *
477  * The callout positions are located in the following paths:
478  *		o local_in (packets destined for this host)
479  *		o local_out (packets orginating from this host )
480  *		o fwd_in  (packets forwarded by this m/c - inbound)
481  *		o fwd_out (packets forwarded by this m/c - outbound)
482  * Hooks at these callout points can be enabled/disabled using the ndd variable
483  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
484  * By default all the callout positions are enabled.
485  *
486  * Outbound (local_out)
487  * Hooks are placed in ip_wput_ire and ipsec_out_process.
488  *
489  * Inbound (local_in)
490  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
491  * TCP and UDP fanout routines.
492  *
493  * Forwarding (in and out)
494  * Hooks are placed in ip_rput_forward.
495  *
496  * IP Policy Framework processing (IPPF processing)
497  * Policy processing for a packet is initiated by ip_process, which ascertains
498  * that the classifier (ipgpc) is loaded and configured, failing which the
499  * packet resumes normal processing in IP. If the clasifier is present, the
500  * packet is acted upon by one or more IPQoS modules (action instances), per
501  * filters configured in ipgpc and resumes normal IP processing thereafter.
502  * An action instance can drop a packet in course of its processing.
503  *
504  * A boolean variable, ip_policy, is used in all the fanout routines that can
505  * invoke ip_process for a packet. This variable indicates if the packet should
506  * to be sent for policy processing. The variable is set to B_TRUE by default,
507  * i.e. when the routines are invoked in the normal ip procesing path for a
508  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
509  * ip_policy is set to B_FALSE for all the routines called in these two
510  * functions because, in the former case,  we don't process loopback traffic
511  * currently while in the latter, the packets have already been processed in
512  * icmp_inbound.
513  *
514  * Zones notes:
515  *
516  * The partitioning rules for networking are as follows:
517  * 1) Packets coming from a zone must have a source address belonging to that
518  * zone.
519  * 2) Packets coming from a zone can only be sent on a physical interface on
520  * which the zone has an IP address.
521  * 3) Between two zones on the same machine, packet delivery is only allowed if
522  * there's a matching route for the destination and zone in the forwarding
523  * table.
524  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
525  * different zones can bind to the same port with the wildcard address
526  * (INADDR_ANY).
527  *
528  * The granularity of interface partitioning is at the logical interface level.
529  * Therefore, every zone has its own IP addresses, and incoming packets can be
530  * attributed to a zone unambiguously. A logical interface is placed into a zone
531  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
532  * structure. Rule (1) is implemented by modifying the source address selection
533  * algorithm so that the list of eligible addresses is filtered based on the
534  * sending process zone.
535  *
536  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
537  * across all zones, depending on their type. Here is the break-up:
538  *
539  * IRE type				Shared/exclusive
540  * --------				----------------
541  * IRE_BROADCAST			Exclusive
542  * IRE_DEFAULT (default routes)		Shared (*)
543  * IRE_LOCAL				Exclusive (x)
544  * IRE_LOOPBACK				Exclusive
545  * IRE_PREFIX (net routes)		Shared (*)
546  * IRE_CACHE				Exclusive
547  * IRE_IF_NORESOLVER (interface routes)	Exclusive
548  * IRE_IF_RESOLVER (interface routes)	Exclusive
549  * IRE_HOST (host routes)		Shared (*)
550  *
551  * (*) A zone can only use a default or off-subnet route if the gateway is
552  * directly reachable from the zone, that is, if the gateway's address matches
553  * one of the zone's logical interfaces.
554  *
555  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
556  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
557  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
558  * address of the zone itself (the destination). Since IRE_LOCAL is used
559  * for communication between zones, ip_wput_ire has special logic to set
560  * the right source address when sending using an IRE_LOCAL.
561  *
562  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
563  * ire_cache_lookup restricts loopback using an IRE_LOCAL
564  * between zone to the case when L2 would have conceptually looped the packet
565  * back, i.e. the loopback which is required since neither Ethernet drivers
566  * nor Ethernet hardware loops them back. This is the case when the normal
567  * routes (ignoring IREs with different zoneids) would send out the packet on
568  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
569  * associated.
570  *
571  * Multiple zones can share a common broadcast address; typically all zones
572  * share the 255.255.255.255 address. Incoming as well as locally originated
573  * broadcast packets must be dispatched to all the zones on the broadcast
574  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
575  * since some zones may not be on the 10.16.72/24 network. To handle this, each
576  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
577  * sent to every zone that has an IRE_BROADCAST entry for the destination
578  * address on the input ill, see conn_wantpacket().
579  *
580  * Applications in different zones can join the same multicast group address.
581  * For IPv4, group memberships are per-logical interface, so they're already
582  * inherently part of a zone. For IPv6, group memberships are per-physical
583  * interface, so we distinguish IPv6 group memberships based on group address,
584  * interface and zoneid. In both cases, received multicast packets are sent to
585  * every zone for which a group membership entry exists. On IPv6 we need to
586  * check that the target zone still has an address on the receiving physical
587  * interface; it could have been removed since the application issued the
588  * IPV6_JOIN_GROUP.
589  */
590 
591 /*
592  * Squeue Fanout flags:
593  *	0: No fanout.
594  *	1: Fanout across all squeues
595  */
596 boolean_t	ip_squeue_fanout = 0;
597 
598 /*
599  * Maximum dups allowed per packet.
600  */
601 uint_t ip_max_frag_dups = 10;
602 
603 #define	IS_SIMPLE_IPH(ipha)						\
604 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
605 
606 /* RFC1122 Conformance */
607 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
608 
609 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
610 
611 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
612 
613 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
614 
615 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
616 		    ip_stack_t *);
617 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
618 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
619 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
620 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
621 		    mblk_t *, int, ip_stack_t *);
622 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
623 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
624 		    ill_t *, zoneid_t);
625 static void	icmp_options_update(ipha_t *);
626 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
627 		    ip_stack_t *);
628 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
629 		    zoneid_t zoneid, ip_stack_t *);
630 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
631 static void	icmp_redirect(ill_t *, mblk_t *);
632 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
633 		    ip_stack_t *);
634 
635 static void	ip_arp_news(queue_t *, mblk_t *);
636 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
637 		    ip_stack_t *);
638 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
639 char		*ip_dot_addr(ipaddr_t, char *);
640 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
641 int		ip_close(queue_t *, int);
642 static char	*ip_dot_saddr(uchar_t *, char *);
643 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
644 		    boolean_t, boolean_t, ill_t *, zoneid_t);
645 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
646 		    boolean_t, boolean_t, zoneid_t);
647 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
648 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
649 static void	ip_lrput(queue_t *, mblk_t *);
650 ipaddr_t	ip_net_mask(ipaddr_t);
651 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
652 		    ip_stack_t *);
653 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
654 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
655 char		*ip_nv_lookup(nv_t *, int);
656 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
657 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
658 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
659 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
660     ipndp_t *, size_t);
661 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
662 void	ip_rput(queue_t *, mblk_t *);
663 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
664 		    void *dummy_arg);
665 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
666 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
667     ip_stack_t *);
668 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
669 			    ire_t *, ip_stack_t *);
670 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
671 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
672 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
673     ip_stack_t *);
674 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
675 		    uint16_t *);
676 int		ip_snmp_get(queue_t *, mblk_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
678 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
679 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
680 		    ip_stack_t *);
681 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
682 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
703 		    ip_stack_t *ipst);
704 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
705 		    ip_stack_t *ipst);
706 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
707 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
708 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
709 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
710 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
711 static boolean_t	ip_source_route_included(ipha_t *);
712 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
713 
714 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
715 		    zoneid_t, ip_stack_t *);
716 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
717 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
718 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
719 		    zoneid_t, ip_stack_t *);
720 
721 static void	conn_drain_init(ip_stack_t *);
722 static void	conn_drain_fini(ip_stack_t *);
723 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
724 
725 static void	conn_walk_drain(ip_stack_t *);
726 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
727     zoneid_t);
728 
729 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
730 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
731 static void	ip_stack_fini(netstackid_t stackid, void *arg);
732 
733 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
734     zoneid_t);
735 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
736     void *dummy_arg);
737 
738 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
739 
740 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
741     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
742     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
743 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
744 
745 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
746 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
747     caddr_t, cred_t *);
748 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
749     caddr_t cp, cred_t *cr);
750 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
753     caddr_t cp, cred_t *cr);
754 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
755     cred_t *);
756 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
757     cred_t *);
758 static squeue_func_t ip_squeue_switch(int);
759 
760 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
761 static void	ip_kstat_fini(netstackid_t, kstat_t *);
762 static int	ip_kstat_update(kstat_t *kp, int rw);
763 static void	*icmp_kstat_init(netstackid_t);
764 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
765 static int	icmp_kstat_update(kstat_t *kp, int rw);
766 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
767 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
768 
769 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
770 
771 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
772     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
773 
774 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
775     ipha_t *, ill_t *, boolean_t);
776 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
777 
778 /* How long, in seconds, we allow frags to hang around. */
779 #define	IP_FRAG_TIMEOUT	60
780 
781 /*
782  * Threshold which determines whether MDT should be used when
783  * generating IP fragments; payload size must be greater than
784  * this threshold for MDT to take place.
785  */
786 #define	IP_WPUT_FRAG_MDT_MIN	32768
787 
788 /* Setable in /etc/system only */
789 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
790 
791 static long ip_rput_pullups;
792 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
793 
794 vmem_t *ip_minor_arena;
795 
796 int	ip_debug;
797 
798 #ifdef DEBUG
799 uint32_t ipsechw_debug = 0;
800 #endif
801 
802 /*
803  * Multirouting/CGTP stuff
804  */
805 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
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_v6,	NULL,		NULL,
912 	    "ipv6_ire_status" },
913 	{  ip_conn_report,	NULL,		NULL,
914 	    "ip_conn_status" },
915 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
916 	    "ip_rput_pullups" },
917 	{  ndp_report,		NULL,		NULL,
918 	    "ip_ndp_cache_report" },
919 	{  ip_srcid_report,	NULL,		NULL,
920 	    "ip_srcid_status" },
921 	{ ip_param_generic_get, ip_squeue_profile_set,
922 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
923 	{ ip_param_generic_get, ip_squeue_bind_set,
924 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
925 	{ ip_param_generic_get, ip_input_proc_set,
926 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
927 	{ ip_param_generic_get, ip_int_set,
928 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
929 #define	IPNDP_CGTP_FILTER_OFFSET	14
930 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
931 	    "ip_cgtp_filter" },
932 	{ ip_param_generic_get, ip_int_set,
933 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
934 #define	IPNDP_IPMP_HOOK_OFFSET	16
935 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
936 	    "ipmp_hook_emulation" },
937 };
938 
939 /*
940  * Table of IP ioctls encoding the various properties of the ioctl and
941  * indexed based on the last byte of the ioctl command. Occasionally there
942  * is a clash, and there is more than 1 ioctl with the same last byte.
943  * In such a case 1 ioctl is encoded in the ndx table and the remaining
944  * ioctls are encoded in the misc table. An entry in the ndx table is
945  * retrieved by indexing on the last byte of the ioctl command and comparing
946  * the ioctl command with the value in the ndx table. In the event of a
947  * mismatch the misc table is then searched sequentially for the desired
948  * ioctl command.
949  *
950  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
951  */
952 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
953 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
961 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
962 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
963 
964 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
965 			MISC_CMD, ip_siocaddrt, NULL },
966 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
967 			MISC_CMD, ip_siocdelrt, NULL },
968 
969 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
970 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
971 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
972 			IF_CMD, ip_sioctl_get_addr, NULL },
973 
974 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
975 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
976 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
977 			IPI_GET_CMD | IPI_REPL,
978 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
979 
980 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
981 			IPI_PRIV | IPI_WR | IPI_REPL,
982 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
983 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
984 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
985 			IF_CMD, ip_sioctl_get_flags, NULL },
986 
987 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
988 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
989 
990 	/* copyin size cannot be coded for SIOCGIFCONF */
991 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
992 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
993 
994 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
995 			IF_CMD, ip_sioctl_mtu, NULL },
996 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
997 			IF_CMD, ip_sioctl_get_mtu, NULL },
998 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
999 			IPI_GET_CMD | IPI_REPL,
1000 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
1001 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1002 			IF_CMD, ip_sioctl_brdaddr, NULL },
1003 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1004 			IPI_GET_CMD | IPI_REPL,
1005 			IF_CMD, ip_sioctl_get_netmask, NULL },
1006 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1007 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1008 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1009 			IPI_GET_CMD | IPI_REPL,
1010 			IF_CMD, ip_sioctl_get_metric, NULL },
1011 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1012 			IF_CMD, ip_sioctl_metric, NULL },
1013 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1014 
1015 	/* See 166-168 below for extended SIOC*XARP ioctls */
1016 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1017 			ARP_CMD, ip_sioctl_arp, NULL },
1018 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1019 			ARP_CMD, ip_sioctl_arp, NULL },
1020 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1021 			ARP_CMD, ip_sioctl_arp, NULL },
1022 
1023 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 
1045 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1046 			MISC_CMD, if_unitsel, if_unitsel_restart },
1047 
1048 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 
1067 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1068 			IPI_PRIV | IPI_WR | IPI_MODOK,
1069 			IF_CMD, ip_sioctl_sifname, NULL },
1070 
1071 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1082 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1083 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1084 
1085 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1086 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1087 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1088 			IF_CMD, ip_sioctl_get_muxid, NULL },
1089 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1090 			IPI_PRIV | IPI_WR | IPI_REPL,
1091 			IF_CMD, ip_sioctl_muxid, NULL },
1092 
1093 	/* Both if and lif variants share same func */
1094 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1095 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1096 	/* Both if and lif variants share same func */
1097 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1098 			IPI_PRIV | IPI_WR | IPI_REPL,
1099 			IF_CMD, ip_sioctl_slifindex, NULL },
1100 
1101 	/* copyin size cannot be coded for SIOCGIFCONF */
1102 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1103 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1104 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1119 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1120 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1121 
1122 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1123 			IPI_PRIV | IPI_WR | IPI_REPL,
1124 			LIF_CMD, ip_sioctl_removeif,
1125 			ip_sioctl_removeif_restart },
1126 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1127 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1128 			LIF_CMD, ip_sioctl_addif, NULL },
1129 #define	SIOCLIFADDR_NDX 112
1130 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1131 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1132 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1133 			IPI_GET_CMD | IPI_REPL,
1134 			LIF_CMD, ip_sioctl_get_addr, NULL },
1135 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1136 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1137 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1138 			IPI_GET_CMD | IPI_REPL,
1139 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1140 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1141 			IPI_PRIV | IPI_WR | IPI_REPL,
1142 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1143 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1144 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1145 			LIF_CMD, ip_sioctl_get_flags, NULL },
1146 
1147 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1148 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1149 
1150 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1151 			ip_sioctl_get_lifconf, NULL },
1152 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1153 			LIF_CMD, ip_sioctl_mtu, NULL },
1154 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1155 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1156 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1157 			IPI_GET_CMD | IPI_REPL,
1158 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1159 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1160 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1161 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1162 			IPI_GET_CMD | IPI_REPL,
1163 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1164 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1165 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1166 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1167 			IPI_GET_CMD | IPI_REPL,
1168 			LIF_CMD, ip_sioctl_get_metric, NULL },
1169 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1170 			LIF_CMD, ip_sioctl_metric, NULL },
1171 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1172 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1173 			LIF_CMD, ip_sioctl_slifname,
1174 			ip_sioctl_slifname_restart },
1175 
1176 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1177 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1178 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1179 			IPI_GET_CMD | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1181 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1182 			IPI_PRIV | IPI_WR | IPI_REPL,
1183 			LIF_CMD, ip_sioctl_muxid, NULL },
1184 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1185 			IPI_GET_CMD | IPI_REPL,
1186 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1187 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1188 			IPI_PRIV | IPI_WR | IPI_REPL,
1189 			LIF_CMD, ip_sioctl_slifindex, 0 },
1190 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1191 			LIF_CMD, ip_sioctl_token, NULL },
1192 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1193 			IPI_GET_CMD | IPI_REPL,
1194 			LIF_CMD, ip_sioctl_get_token, NULL },
1195 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1196 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1197 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1198 			IPI_GET_CMD | IPI_REPL,
1199 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1200 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1201 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1202 
1203 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1204 			IPI_GET_CMD | IPI_REPL,
1205 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1206 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1207 			LIF_CMD, ip_siocdelndp_v6, NULL },
1208 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1209 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1210 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1211 			LIF_CMD, ip_siocsetndp_v6, NULL },
1212 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1213 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1214 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1215 			MISC_CMD, ip_sioctl_tonlink, NULL },
1216 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1217 			MISC_CMD, ip_sioctl_tmysite, NULL },
1218 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1219 			TUN_CMD, ip_sioctl_tunparam, NULL },
1220 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1221 			IPI_PRIV | IPI_WR,
1222 			TUN_CMD, ip_sioctl_tunparam, NULL },
1223 
1224 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1225 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1226 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1227 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1228 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1229 
1230 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1233 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1234 			IPI_PRIV | IPI_WR | IPI_REPL,
1235 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1236 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1237 			IPI_PRIV | IPI_WR,
1238 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1239 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1240 			IPI_GET_CMD | IPI_REPL,
1241 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1242 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1243 			IPI_GET_CMD | IPI_REPL,
1244 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1245 
1246 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1247 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1248 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1249 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1250 
1251 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1252 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1253 
1254 	/* These are handled in ip_sioctl_copyin_setup itself */
1255 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1256 			MISC_CMD, NULL, NULL },
1257 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1258 			MISC_CMD, NULL, NULL },
1259 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1260 
1261 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1262 			ip_sioctl_get_lifconf, NULL },
1263 
1264 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1265 			XARP_CMD, ip_sioctl_arp, NULL },
1266 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1267 			XARP_CMD, ip_sioctl_arp, NULL },
1268 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1269 			XARP_CMD, ip_sioctl_arp, NULL },
1270 
1271 	/* SIOCPOPSOCKFS is not handled by IP */
1272 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1273 
1274 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1275 			IPI_GET_CMD | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1277 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1278 			IPI_PRIV | IPI_WR | IPI_REPL,
1279 			LIF_CMD, ip_sioctl_slifzone,
1280 			ip_sioctl_slifzone_restart },
1281 	/* 172-174 are SCTP ioctls and not handled by IP */
1282 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1283 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1284 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1285 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1286 			IPI_GET_CMD, LIF_CMD,
1287 			ip_sioctl_get_lifusesrc, 0 },
1288 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1289 			IPI_PRIV | IPI_WR,
1290 			LIF_CMD, ip_sioctl_slifusesrc,
1291 			NULL },
1292 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1293 			ip_sioctl_get_lifsrcof, NULL },
1294 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1295 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1296 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1297 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1298 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1299 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1300 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1301 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1302 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1303 			ip_sioctl_set_ipmpfailback, NULL }
1304 };
1305 
1306 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1307 
1308 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1309 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1310 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1311 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1312 		TUN_CMD, ip_sioctl_tunparam, NULL },
1313 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1319 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1320 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1321 		MISC_CMD, mrt_ioctl},
1322 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1323 		MISC_CMD, mrt_ioctl},
1324 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1325 		MISC_CMD, mrt_ioctl}
1326 };
1327 
1328 int ip_misc_ioctl_count =
1329     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1330 
1331 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1332 					/* Settable in /etc/system */
1333 /* Defined in ip_ire.c */
1334 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1335 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1336 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1337 
1338 static nv_t	ire_nv_arr[] = {
1339 	{ IRE_BROADCAST, "BROADCAST" },
1340 	{ IRE_LOCAL, "LOCAL" },
1341 	{ IRE_LOOPBACK, "LOOPBACK" },
1342 	{ IRE_CACHE, "CACHE" },
1343 	{ IRE_DEFAULT, "DEFAULT" },
1344 	{ IRE_PREFIX, "PREFIX" },
1345 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1346 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1347 	{ IRE_HOST, "HOST" },
1348 	{ 0 }
1349 };
1350 
1351 nv_t	*ire_nv_tbl = ire_nv_arr;
1352 
1353 /* Defined in ip_netinfo.c */
1354 extern ddi_taskq_t	*eventq_queue_nic;
1355 
1356 /* Simple ICMP IP Header Template */
1357 static ipha_t icmp_ipha = {
1358 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1359 };
1360 
1361 struct module_info ip_mod_info = {
1362 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1363 };
1364 
1365 /*
1366  * Duplicate static symbols within a module confuses mdb; so we avoid the
1367  * problem by making the symbols here distinct from those in udp.c.
1368  */
1369 
1370 static struct qinit iprinit = {
1371 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1372 	&ip_mod_info
1373 };
1374 
1375 static struct qinit ipwinit = {
1376 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1377 	&ip_mod_info
1378 };
1379 
1380 static struct qinit iplrinit = {
1381 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1382 	&ip_mod_info
1383 };
1384 
1385 static struct qinit iplwinit = {
1386 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1387 	&ip_mod_info
1388 };
1389 
1390 struct streamtab ipinfo = {
1391 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1392 };
1393 
1394 #ifdef	DEBUG
1395 static boolean_t skip_sctp_cksum = B_FALSE;
1396 #endif
1397 
1398 /*
1399  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1400  * ip_rput_v6(), ip_output(), etc.  If the message
1401  * block already has a M_CTL at the front of it, then simply set the zoneid
1402  * appropriately.
1403  */
1404 mblk_t *
1405 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1406 {
1407 	mblk_t		*first_mp;
1408 	ipsec_out_t	*io;
1409 
1410 	ASSERT(zoneid != ALL_ZONES);
1411 	if (mp->b_datap->db_type == M_CTL) {
1412 		io = (ipsec_out_t *)mp->b_rptr;
1413 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1414 		io->ipsec_out_zoneid = zoneid;
1415 		return (mp);
1416 	}
1417 
1418 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1419 	if (first_mp == NULL)
1420 		return (NULL);
1421 	io = (ipsec_out_t *)first_mp->b_rptr;
1422 	/* This is not a secure packet */
1423 	io->ipsec_out_secure = B_FALSE;
1424 	io->ipsec_out_zoneid = zoneid;
1425 	first_mp->b_cont = mp;
1426 	return (first_mp);
1427 }
1428 
1429 /*
1430  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1431  */
1432 mblk_t *
1433 ip_copymsg(mblk_t *mp)
1434 {
1435 	mblk_t *nmp;
1436 	ipsec_info_t *in;
1437 
1438 	if (mp->b_datap->db_type != M_CTL)
1439 		return (copymsg(mp));
1440 
1441 	in = (ipsec_info_t *)mp->b_rptr;
1442 
1443 	/*
1444 	 * Note that M_CTL is also used for delivering ICMP error messages
1445 	 * upstream to transport layers.
1446 	 */
1447 	if (in->ipsec_info_type != IPSEC_OUT &&
1448 	    in->ipsec_info_type != IPSEC_IN)
1449 		return (copymsg(mp));
1450 
1451 	nmp = copymsg(mp->b_cont);
1452 
1453 	if (in->ipsec_info_type == IPSEC_OUT) {
1454 		return (ipsec_out_tag(mp, nmp,
1455 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1456 	} else {
1457 		return (ipsec_in_tag(mp, nmp,
1458 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1459 	}
1460 }
1461 
1462 /* Generate an ICMP fragmentation needed message. */
1463 static void
1464 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1465     ip_stack_t *ipst)
1466 {
1467 	icmph_t	icmph;
1468 	mblk_t *first_mp;
1469 	boolean_t mctl_present;
1470 
1471 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1472 
1473 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1474 		if (mctl_present)
1475 			freeb(first_mp);
1476 		return;
1477 	}
1478 
1479 	bzero(&icmph, sizeof (icmph_t));
1480 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1481 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1482 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1483 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1484 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1485 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1486 	    ipst);
1487 }
1488 
1489 /*
1490  * icmp_inbound deals with ICMP messages in the following ways.
1491  *
1492  * 1) It needs to send a reply back and possibly delivering it
1493  *    to the "interested" upper clients.
1494  * 2) It needs to send it to the upper clients only.
1495  * 3) It needs to change some values in IP only.
1496  * 4) It needs to change some values in IP and upper layers e.g TCP.
1497  *
1498  * We need to accomodate icmp messages coming in clear until we get
1499  * everything secure from the wire. If icmp_accept_clear_messages
1500  * is zero we check with the global policy and act accordingly. If
1501  * it is non-zero, we accept the message without any checks. But
1502  * *this does not mean* that this will be delivered to the upper
1503  * clients. By accepting we might send replies back, change our MTU
1504  * value etc. but delivery to the ULP/clients depends on their policy
1505  * dispositions.
1506  *
1507  * We handle the above 4 cases in the context of IPsec in the
1508  * following way :
1509  *
1510  * 1) Send the reply back in the same way as the request came in.
1511  *    If it came in encrypted, it goes out encrypted. If it came in
1512  *    clear, it goes out in clear. Thus, this will prevent chosen
1513  *    plain text attack.
1514  * 2) The client may or may not expect things to come in secure.
1515  *    If it comes in secure, the policy constraints are checked
1516  *    before delivering it to the upper layers. If it comes in
1517  *    clear, ipsec_inbound_accept_clear will decide whether to
1518  *    accept this in clear or not. In both the cases, if the returned
1519  *    message (IP header + 8 bytes) that caused the icmp message has
1520  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1521  *    sending up. If there are only 8 bytes of returned message, then
1522  *    upper client will not be notified.
1523  * 3) Check with global policy to see whether it matches the constaints.
1524  *    But this will be done only if icmp_accept_messages_in_clear is
1525  *    zero.
1526  * 4) If we need to change both in IP and ULP, then the decision taken
1527  *    while affecting the values in IP and while delivering up to TCP
1528  *    should be the same.
1529  *
1530  * 	There are two cases.
1531  *
1532  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1533  *	   failed), we will not deliver it to the ULP, even though they
1534  *	   are *willing* to accept in *clear*. This is fine as our global
1535  *	   disposition to icmp messages asks us reject the datagram.
1536  *
1537  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1538  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1539  *	   to deliver it to ULP (policy failed), it can lead to
1540  *	   consistency problems. The cases known at this time are
1541  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1542  *	   values :
1543  *
1544  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1545  *	     and Upper layer rejects. Then the communication will
1546  *	     come to a stop. This is solved by making similar decisions
1547  *	     at both levels. Currently, when we are unable to deliver
1548  *	     to the Upper Layer (due to policy failures) while IP has
1549  *	     adjusted ire_max_frag, the next outbound datagram would
1550  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1551  *	     will be with the right level of protection. Thus the right
1552  *	     value will be communicated even if we are not able to
1553  *	     communicate when we get from the wire initially. But this
1554  *	     assumes there would be at least one outbound datagram after
1555  *	     IP has adjusted its ire_max_frag value. To make things
1556  *	     simpler, we accept in clear after the validation of
1557  *	     AH/ESP headers.
1558  *
1559  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1560  *	     upper layer depending on the level of protection the upper
1561  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1562  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1563  *	     should be accepted in clear when the Upper layer expects secure.
1564  *	     Thus the communication may get aborted by some bad ICMP
1565  *	     packets.
1566  *
1567  * IPQoS Notes:
1568  * The only instance when a packet is sent for processing is when there
1569  * isn't an ICMP client and if we are interested in it.
1570  * If there is a client, IPPF processing will take place in the
1571  * ip_fanout_proto routine.
1572  *
1573  * Zones notes:
1574  * The packet is only processed in the context of the specified zone: typically
1575  * only this zone will reply to an echo request, and only interested clients in
1576  * this zone will receive a copy of the packet. This means that the caller must
1577  * call icmp_inbound() for each relevant zone.
1578  */
1579 static void
1580 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1581     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1582     ill_t *recv_ill, zoneid_t zoneid)
1583 {
1584 	icmph_t	*icmph;
1585 	ipha_t	*ipha;
1586 	int	iph_hdr_length;
1587 	int	hdr_length;
1588 	boolean_t	interested;
1589 	uint32_t	ts;
1590 	uchar_t	*wptr;
1591 	ipif_t	*ipif;
1592 	mblk_t *first_mp;
1593 	ipsec_in_t *ii;
1594 	ire_t *src_ire;
1595 	boolean_t onlink;
1596 	timestruc_t now;
1597 	uint32_t ill_index;
1598 	ip_stack_t *ipst;
1599 
1600 	ASSERT(ill != NULL);
1601 	ipst = ill->ill_ipst;
1602 
1603 	first_mp = mp;
1604 	if (mctl_present) {
1605 		mp = first_mp->b_cont;
1606 		ASSERT(mp != NULL);
1607 	}
1608 
1609 	ipha = (ipha_t *)mp->b_rptr;
1610 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1611 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1612 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1613 		if (first_mp == NULL)
1614 			return;
1615 	}
1616 
1617 	/*
1618 	 * On a labeled system, we have to check whether the zone itself is
1619 	 * permitted to receive raw traffic.
1620 	 */
1621 	if (is_system_labeled()) {
1622 		if (zoneid == ALL_ZONES)
1623 			zoneid = tsol_packet_to_zoneid(mp);
1624 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1625 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1626 			    zoneid));
1627 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1628 			freemsg(first_mp);
1629 			return;
1630 		}
1631 	}
1632 
1633 	/*
1634 	 * We have accepted the ICMP message. It means that we will
1635 	 * respond to the packet if needed. It may not be delivered
1636 	 * to the upper client depending on the policy constraints
1637 	 * and the disposition in ipsec_inbound_accept_clear.
1638 	 */
1639 
1640 	ASSERT(ill != NULL);
1641 
1642 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1643 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1644 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1645 		/* Last chance to get real. */
1646 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1647 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1648 			freemsg(first_mp);
1649 			return;
1650 		}
1651 		/* Refresh iph following the pullup. */
1652 		ipha = (ipha_t *)mp->b_rptr;
1653 	}
1654 	/* ICMP header checksum, including checksum field, should be zero. */
1655 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1656 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1657 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1658 		freemsg(first_mp);
1659 		return;
1660 	}
1661 	/* The IP header will always be a multiple of four bytes */
1662 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1663 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1664 	    icmph->icmph_code));
1665 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1666 	/* We will set "interested" to "true" if we want a copy */
1667 	interested = B_FALSE;
1668 	switch (icmph->icmph_type) {
1669 	case ICMP_ECHO_REPLY:
1670 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1671 		break;
1672 	case ICMP_DEST_UNREACHABLE:
1673 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1674 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1675 		interested = B_TRUE;	/* Pass up to transport */
1676 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1677 		break;
1678 	case ICMP_SOURCE_QUENCH:
1679 		interested = B_TRUE;	/* Pass up to transport */
1680 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1681 		break;
1682 	case ICMP_REDIRECT:
1683 		if (!ipst->ips_ip_ignore_redirect)
1684 			interested = B_TRUE;
1685 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1686 		break;
1687 	case ICMP_ECHO_REQUEST:
1688 		/*
1689 		 * Whether to respond to echo requests that come in as IP
1690 		 * broadcasts or as IP multicast is subject to debate
1691 		 * (what isn't?).  We aim to please, you pick it.
1692 		 * Default is do it.
1693 		 */
1694 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1695 			/* unicast: always respond */
1696 			interested = B_TRUE;
1697 		} else if (CLASSD(ipha->ipha_dst)) {
1698 			/* multicast: respond based on tunable */
1699 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1700 		} else if (broadcast) {
1701 			/* broadcast: respond based on tunable */
1702 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1703 		}
1704 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1705 		break;
1706 	case ICMP_ROUTER_ADVERTISEMENT:
1707 	case ICMP_ROUTER_SOLICITATION:
1708 		break;
1709 	case ICMP_TIME_EXCEEDED:
1710 		interested = B_TRUE;	/* Pass up to transport */
1711 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1712 		break;
1713 	case ICMP_PARAM_PROBLEM:
1714 		interested = B_TRUE;	/* Pass up to transport */
1715 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1716 		break;
1717 	case ICMP_TIME_STAMP_REQUEST:
1718 		/* Response to Time Stamp Requests is local policy. */
1719 		if (ipst->ips_ip_g_resp_to_timestamp &&
1720 		    /* So is whether to respond if it was an IP broadcast. */
1721 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1722 			int tstamp_len = 3 * sizeof (uint32_t);
1723 
1724 			if (wptr +  tstamp_len > mp->b_wptr) {
1725 				if (!pullupmsg(mp, wptr + tstamp_len -
1726 				    mp->b_rptr)) {
1727 					BUMP_MIB(ill->ill_ip_mib,
1728 					    ipIfStatsInDiscards);
1729 					freemsg(first_mp);
1730 					return;
1731 				}
1732 				/* Refresh ipha following the pullup. */
1733 				ipha = (ipha_t *)mp->b_rptr;
1734 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1735 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1736 			}
1737 			interested = B_TRUE;
1738 		}
1739 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1740 		break;
1741 	case ICMP_TIME_STAMP_REPLY:
1742 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1743 		break;
1744 	case ICMP_INFO_REQUEST:
1745 		/* Per RFC 1122 3.2.2.7, ignore this. */
1746 	case ICMP_INFO_REPLY:
1747 		break;
1748 	case ICMP_ADDRESS_MASK_REQUEST:
1749 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1750 		    !broadcast) &&
1751 		    /* TODO m_pullup of complete header? */
1752 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1753 			interested = B_TRUE;
1754 		}
1755 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1756 		break;
1757 	case ICMP_ADDRESS_MASK_REPLY:
1758 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1759 		break;
1760 	default:
1761 		interested = B_TRUE;	/* Pass up to transport */
1762 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1763 		break;
1764 	}
1765 	/* See if there is an ICMP client. */
1766 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1767 		/* If there is an ICMP client and we want one too, copy it. */
1768 		mblk_t *first_mp1;
1769 
1770 		if (!interested) {
1771 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1772 			    ip_policy, recv_ill, zoneid);
1773 			return;
1774 		}
1775 		first_mp1 = ip_copymsg(first_mp);
1776 		if (first_mp1 != NULL) {
1777 			ip_fanout_proto(q, first_mp1, ill, ipha,
1778 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1779 		}
1780 	} else if (!interested) {
1781 		freemsg(first_mp);
1782 		return;
1783 	} else {
1784 		/*
1785 		 * Initiate policy processing for this packet if ip_policy
1786 		 * is true.
1787 		 */
1788 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1789 			ill_index = ill->ill_phyint->phyint_ifindex;
1790 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1791 			if (mp == NULL) {
1792 				if (mctl_present) {
1793 					freeb(first_mp);
1794 				}
1795 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1796 				return;
1797 			}
1798 		}
1799 	}
1800 	/* We want to do something with it. */
1801 	/* Check db_ref to make sure we can modify the packet. */
1802 	if (mp->b_datap->db_ref > 1) {
1803 		mblk_t	*first_mp1;
1804 
1805 		first_mp1 = ip_copymsg(first_mp);
1806 		freemsg(first_mp);
1807 		if (!first_mp1) {
1808 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1809 			return;
1810 		}
1811 		first_mp = first_mp1;
1812 		if (mctl_present) {
1813 			mp = first_mp->b_cont;
1814 			ASSERT(mp != NULL);
1815 		} else {
1816 			mp = first_mp;
1817 		}
1818 		ipha = (ipha_t *)mp->b_rptr;
1819 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1820 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1821 	}
1822 	switch (icmph->icmph_type) {
1823 	case ICMP_ADDRESS_MASK_REQUEST:
1824 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1825 		if (ipif == NULL) {
1826 			freemsg(first_mp);
1827 			return;
1828 		}
1829 		/*
1830 		 * outging interface must be IPv4
1831 		 */
1832 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1833 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1834 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1835 		ipif_refrele(ipif);
1836 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1837 		break;
1838 	case ICMP_ECHO_REQUEST:
1839 		icmph->icmph_type = ICMP_ECHO_REPLY;
1840 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1841 		break;
1842 	case ICMP_TIME_STAMP_REQUEST: {
1843 		uint32_t *tsp;
1844 
1845 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1846 		tsp = (uint32_t *)wptr;
1847 		tsp++;		/* Skip past 'originate time' */
1848 		/* Compute # of milliseconds since midnight */
1849 		gethrestime(&now);
1850 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1851 		    now.tv_nsec / (NANOSEC / MILLISEC);
1852 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1853 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1854 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1855 		break;
1856 	}
1857 	default:
1858 		ipha = (ipha_t *)&icmph[1];
1859 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1860 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1861 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1862 				freemsg(first_mp);
1863 				return;
1864 			}
1865 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1866 			ipha = (ipha_t *)&icmph[1];
1867 		}
1868 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1869 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1870 			freemsg(first_mp);
1871 			return;
1872 		}
1873 		hdr_length = IPH_HDR_LENGTH(ipha);
1874 		if (hdr_length < sizeof (ipha_t)) {
1875 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1876 			freemsg(first_mp);
1877 			return;
1878 		}
1879 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1880 			if (!pullupmsg(mp,
1881 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1882 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1883 				freemsg(first_mp);
1884 				return;
1885 			}
1886 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1887 			ipha = (ipha_t *)&icmph[1];
1888 		}
1889 		switch (icmph->icmph_type) {
1890 		case ICMP_REDIRECT:
1891 			/*
1892 			 * As there is no upper client to deliver, we don't
1893 			 * need the first_mp any more.
1894 			 */
1895 			if (mctl_present) {
1896 				freeb(first_mp);
1897 			}
1898 			icmp_redirect(ill, mp);
1899 			return;
1900 		case ICMP_DEST_UNREACHABLE:
1901 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1902 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1903 				    zoneid, mp, iph_hdr_length, ipst)) {
1904 					freemsg(first_mp);
1905 					return;
1906 				}
1907 				/*
1908 				 * icmp_inbound_too_big() may alter mp.
1909 				 * Resynch ipha and icmph accordingly.
1910 				 */
1911 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1912 				ipha = (ipha_t *)&icmph[1];
1913 			}
1914 			/* FALLTHRU */
1915 		default :
1916 			/*
1917 			 * IPQoS notes: Since we have already done IPQoS
1918 			 * processing we don't want to do it again in
1919 			 * the fanout routines called by
1920 			 * icmp_inbound_error_fanout, hence the last
1921 			 * argument, ip_policy, is B_FALSE.
1922 			 */
1923 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1924 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1925 			    B_FALSE, recv_ill, zoneid);
1926 		}
1927 		return;
1928 	}
1929 	/* Send out an ICMP packet */
1930 	icmph->icmph_checksum = 0;
1931 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1932 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1933 		ipif_t	*ipif_chosen;
1934 		/*
1935 		 * Make it look like it was directed to us, so we don't look
1936 		 * like a fool with a broadcast or multicast source address.
1937 		 */
1938 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1939 		/*
1940 		 * Make sure that we haven't grabbed an interface that's DOWN.
1941 		 */
1942 		if (ipif != NULL) {
1943 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1944 			    ipha->ipha_src, zoneid);
1945 			if (ipif_chosen != NULL) {
1946 				ipif_refrele(ipif);
1947 				ipif = ipif_chosen;
1948 			}
1949 		}
1950 		if (ipif == NULL) {
1951 			ip0dbg(("icmp_inbound: "
1952 			    "No source for broadcast/multicast:\n"
1953 			    "\tsrc 0x%x dst 0x%x ill %p "
1954 			    "ipif_lcl_addr 0x%x\n",
1955 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1956 			    (void *)ill,
1957 			    ill->ill_ipif->ipif_lcl_addr));
1958 			freemsg(first_mp);
1959 			return;
1960 		}
1961 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1962 		ipha->ipha_dst = ipif->ipif_src_addr;
1963 		ipif_refrele(ipif);
1964 	}
1965 	/* Reset time to live. */
1966 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1967 	{
1968 		/* Swap source and destination addresses */
1969 		ipaddr_t tmp;
1970 
1971 		tmp = ipha->ipha_src;
1972 		ipha->ipha_src = ipha->ipha_dst;
1973 		ipha->ipha_dst = tmp;
1974 	}
1975 	ipha->ipha_ident = 0;
1976 	if (!IS_SIMPLE_IPH(ipha))
1977 		icmp_options_update(ipha);
1978 
1979 	/*
1980 	 * ICMP echo replies should go out on the same interface
1981 	 * the request came on as probes used by in.mpathd for detecting
1982 	 * NIC failures are ECHO packets. We turn-off load spreading
1983 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1984 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1985 	 * function. This is in turn handled by ip_wput and ip_newroute
1986 	 * to make sure that the packet goes out on the interface it came
1987 	 * in on. If we don't turnoff load spreading, the packets might get
1988 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1989 	 * to go out and in.mpathd would wrongly detect a failure or
1990 	 * mis-detect a NIC failure for link failure. As load spreading
1991 	 * can happen only if ill_group is not NULL, we do only for
1992 	 * that case and this does not affect the normal case.
1993 	 *
1994 	 * We turn off load spreading only on echo packets that came from
1995 	 * on-link hosts. If the interface route has been deleted, this will
1996 	 * not be enforced as we can't do much. For off-link hosts, as the
1997 	 * default routes in IPv4 does not typically have an ire_ipif
1998 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
1999 	 * Moreover, expecting a default route through this interface may
2000 	 * not be correct. We use ipha_dst because of the swap above.
2001 	 */
2002 	onlink = B_FALSE;
2003 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2004 		/*
2005 		 * First, we need to make sure that it is not one of our
2006 		 * local addresses. If we set onlink when it is one of
2007 		 * our local addresses, we will end up creating IRE_CACHES
2008 		 * for one of our local addresses. Then, we will never
2009 		 * accept packets for them afterwards.
2010 		 */
2011 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2012 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2013 		if (src_ire == NULL) {
2014 			ipif = ipif_get_next_ipif(NULL, ill);
2015 			if (ipif == NULL) {
2016 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2017 				freemsg(mp);
2018 				return;
2019 			}
2020 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2021 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2022 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2023 			ipif_refrele(ipif);
2024 			if (src_ire != NULL) {
2025 				onlink = B_TRUE;
2026 				ire_refrele(src_ire);
2027 			}
2028 		} else {
2029 			ire_refrele(src_ire);
2030 		}
2031 	}
2032 	if (!mctl_present) {
2033 		/*
2034 		 * This packet should go out the same way as it
2035 		 * came in i.e in clear. To make sure that global
2036 		 * policy will not be applied to this in ip_wput_ire,
2037 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2038 		 */
2039 		ASSERT(first_mp == mp);
2040 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2041 		if (first_mp == NULL) {
2042 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2043 			freemsg(mp);
2044 			return;
2045 		}
2046 		ii = (ipsec_in_t *)first_mp->b_rptr;
2047 
2048 		/* This is not a secure packet */
2049 		ii->ipsec_in_secure = B_FALSE;
2050 		if (onlink) {
2051 			ii->ipsec_in_attach_if = B_TRUE;
2052 			ii->ipsec_in_ill_index =
2053 			    ill->ill_phyint->phyint_ifindex;
2054 			ii->ipsec_in_rill_index =
2055 			    recv_ill->ill_phyint->phyint_ifindex;
2056 		}
2057 		first_mp->b_cont = mp;
2058 	} else if (onlink) {
2059 		ii = (ipsec_in_t *)first_mp->b_rptr;
2060 		ii->ipsec_in_attach_if = B_TRUE;
2061 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2062 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2063 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2064 	} else {
2065 		ii = (ipsec_in_t *)first_mp->b_rptr;
2066 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2067 	}
2068 	ii->ipsec_in_zoneid = zoneid;
2069 	ASSERT(zoneid != ALL_ZONES);
2070 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2071 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2072 		return;
2073 	}
2074 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2075 	put(WR(q), first_mp);
2076 }
2077 
2078 static ipaddr_t
2079 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2080 {
2081 	conn_t *connp;
2082 	connf_t *connfp;
2083 	ipaddr_t nexthop_addr = INADDR_ANY;
2084 	int hdr_length = IPH_HDR_LENGTH(ipha);
2085 	uint16_t *up;
2086 	uint32_t ports;
2087 	ip_stack_t *ipst = ill->ill_ipst;
2088 
2089 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2090 	switch (ipha->ipha_protocol) {
2091 		case IPPROTO_TCP:
2092 		{
2093 			tcph_t *tcph;
2094 
2095 			/* do a reverse lookup */
2096 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2097 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2098 			    TCPS_LISTEN, ipst);
2099 			break;
2100 		}
2101 		case IPPROTO_UDP:
2102 		{
2103 			uint32_t dstport, srcport;
2104 
2105 			((uint16_t *)&ports)[0] = up[1];
2106 			((uint16_t *)&ports)[1] = up[0];
2107 
2108 			/* Extract ports in net byte order */
2109 			dstport = htons(ntohl(ports) & 0xFFFF);
2110 			srcport = htons(ntohl(ports) >> 16);
2111 
2112 			connfp = &ipst->ips_ipcl_udp_fanout[
2113 			    IPCL_UDP_HASH(dstport, ipst)];
2114 			mutex_enter(&connfp->connf_lock);
2115 			connp = connfp->connf_head;
2116 
2117 			/* do a reverse lookup */
2118 			while ((connp != NULL) &&
2119 			    (!IPCL_UDP_MATCH(connp, dstport,
2120 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2121 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2122 				connp = connp->conn_next;
2123 			}
2124 			if (connp != NULL)
2125 				CONN_INC_REF(connp);
2126 			mutex_exit(&connfp->connf_lock);
2127 			break;
2128 		}
2129 		case IPPROTO_SCTP:
2130 		{
2131 			in6_addr_t map_src, map_dst;
2132 
2133 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2134 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2135 			((uint16_t *)&ports)[0] = up[1];
2136 			((uint16_t *)&ports)[1] = up[0];
2137 
2138 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2139 			    zoneid, ipst->ips_netstack->netstack_sctp);
2140 			if (connp == NULL) {
2141 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2142 				    zoneid, ports, ipha, ipst);
2143 			} else {
2144 				CONN_INC_REF(connp);
2145 				SCTP_REFRELE(CONN2SCTP(connp));
2146 			}
2147 			break;
2148 		}
2149 		default:
2150 		{
2151 			ipha_t ripha;
2152 
2153 			ripha.ipha_src = ipha->ipha_dst;
2154 			ripha.ipha_dst = ipha->ipha_src;
2155 			ripha.ipha_protocol = ipha->ipha_protocol;
2156 
2157 			connfp = &ipst->ips_ipcl_proto_fanout[
2158 			    ipha->ipha_protocol];
2159 			mutex_enter(&connfp->connf_lock);
2160 			connp = connfp->connf_head;
2161 			for (connp = connfp->connf_head; connp != NULL;
2162 			    connp = connp->conn_next) {
2163 				if (IPCL_PROTO_MATCH(connp,
2164 				    ipha->ipha_protocol, &ripha, ill,
2165 				    0, zoneid)) {
2166 					CONN_INC_REF(connp);
2167 					break;
2168 				}
2169 			}
2170 			mutex_exit(&connfp->connf_lock);
2171 		}
2172 	}
2173 	if (connp != NULL) {
2174 		if (connp->conn_nexthop_set)
2175 			nexthop_addr = connp->conn_nexthop_v4;
2176 		CONN_DEC_REF(connp);
2177 	}
2178 	return (nexthop_addr);
2179 }
2180 
2181 /* Table from RFC 1191 */
2182 static int icmp_frag_size_table[] =
2183 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2184 
2185 /*
2186  * Process received ICMP Packet too big.
2187  * After updating any IRE it does the fanout to any matching transport streams.
2188  * Assumes the message has been pulled up till the IP header that caused
2189  * the error.
2190  *
2191  * Returns B_FALSE on failure and B_TRUE on success.
2192  */
2193 static boolean_t
2194 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2195     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2196     ip_stack_t *ipst)
2197 {
2198 	ire_t	*ire, *first_ire;
2199 	int	mtu;
2200 	int	hdr_length;
2201 	ipaddr_t nexthop_addr;
2202 
2203 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2204 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2205 	ASSERT(ill != NULL);
2206 
2207 	hdr_length = IPH_HDR_LENGTH(ipha);
2208 
2209 	/* Drop if the original packet contained a source route */
2210 	if (ip_source_route_included(ipha)) {
2211 		return (B_FALSE);
2212 	}
2213 	/*
2214 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2215 	 * header.
2216 	 */
2217 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2218 	    mp->b_wptr) {
2219 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2220 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2221 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2222 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2223 			return (B_FALSE);
2224 		}
2225 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2226 		ipha = (ipha_t *)&icmph[1];
2227 	}
2228 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2229 	if (nexthop_addr != INADDR_ANY) {
2230 		/* nexthop set */
2231 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2232 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2233 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2234 	} else {
2235 		/* nexthop not set */
2236 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2237 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2238 	}
2239 
2240 	if (!first_ire) {
2241 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2242 		    ntohl(ipha->ipha_dst)));
2243 		return (B_FALSE);
2244 	}
2245 	/* Check for MTU discovery advice as described in RFC 1191 */
2246 	mtu = ntohs(icmph->icmph_du_mtu);
2247 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2248 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2249 	    ire = ire->ire_next) {
2250 		/*
2251 		 * Look for the connection to which this ICMP message is
2252 		 * directed. If it has the IP_NEXTHOP option set, then the
2253 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2254 		 * option. Else the search is limited to regular IREs.
2255 		 */
2256 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2257 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2258 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2259 		    (nexthop_addr != INADDR_ANY)))
2260 			continue;
2261 
2262 		mutex_enter(&ire->ire_lock);
2263 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2264 			/* Reduce the IRE max frag value as advised. */
2265 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2266 			    mtu, ire->ire_max_frag));
2267 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2268 		} else {
2269 			uint32_t length;
2270 			int	i;
2271 
2272 			/*
2273 			 * Use the table from RFC 1191 to figure out
2274 			 * the next "plateau" based on the length in
2275 			 * the original IP packet.
2276 			 */
2277 			length = ntohs(ipha->ipha_length);
2278 			if (ire->ire_max_frag <= length &&
2279 			    ire->ire_max_frag >= length - hdr_length) {
2280 				/*
2281 				 * Handle broken BSD 4.2 systems that
2282 				 * return the wrong iph_length in ICMP
2283 				 * errors.
2284 				 */
2285 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2286 				    length, ire->ire_max_frag));
2287 				length -= hdr_length;
2288 			}
2289 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2290 				if (length > icmp_frag_size_table[i])
2291 					break;
2292 			}
2293 			if (i == A_CNT(icmp_frag_size_table)) {
2294 				/* Smaller than 68! */
2295 				ip1dbg(("Too big for packet size %d\n",
2296 				    length));
2297 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2298 				ire->ire_frag_flag = 0;
2299 			} else {
2300 				mtu = icmp_frag_size_table[i];
2301 				ip1dbg(("Calculated mtu %d, packet size %d, "
2302 				    "before %d", mtu, length,
2303 				    ire->ire_max_frag));
2304 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2305 				ip1dbg((", after %d\n", ire->ire_max_frag));
2306 			}
2307 			/* Record the new max frag size for the ULP. */
2308 			icmph->icmph_du_zero = 0;
2309 			icmph->icmph_du_mtu =
2310 			    htons((uint16_t)ire->ire_max_frag);
2311 		}
2312 		mutex_exit(&ire->ire_lock);
2313 	}
2314 	rw_exit(&first_ire->ire_bucket->irb_lock);
2315 	ire_refrele(first_ire);
2316 	return (B_TRUE);
2317 }
2318 
2319 /*
2320  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2321  * calls this function.
2322  */
2323 static mblk_t *
2324 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2325 {
2326 	ipha_t *ipha;
2327 	icmph_t *icmph;
2328 	ipha_t *in_ipha;
2329 	int length;
2330 
2331 	ASSERT(mp->b_datap->db_type == M_DATA);
2332 
2333 	/*
2334 	 * For Self-encapsulated packets, we added an extra IP header
2335 	 * without the options. Inner IP header is the one from which
2336 	 * the outer IP header was formed. Thus, we need to remove the
2337 	 * outer IP header. To do this, we pullup the whole message
2338 	 * and overlay whatever follows the outer IP header over the
2339 	 * outer IP header.
2340 	 */
2341 
2342 	if (!pullupmsg(mp, -1))
2343 		return (NULL);
2344 
2345 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2346 	ipha = (ipha_t *)&icmph[1];
2347 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2348 
2349 	/*
2350 	 * The length that we want to overlay is following the inner
2351 	 * IP header. Subtracting the IP header + icmp header + outer
2352 	 * IP header's length should give us the length that we want to
2353 	 * overlay.
2354 	 */
2355 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2356 	    hdr_length;
2357 	/*
2358 	 * Overlay whatever follows the inner header over the
2359 	 * outer header.
2360 	 */
2361 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2362 
2363 	/* Set the wptr to account for the outer header */
2364 	mp->b_wptr -= hdr_length;
2365 	return (mp);
2366 }
2367 
2368 /*
2369  * Try to pass the ICMP message upstream in case the ULP cares.
2370  *
2371  * If the packet that caused the ICMP error is secure, we send
2372  * it to AH/ESP to make sure that the attached packet has a
2373  * valid association. ipha in the code below points to the
2374  * IP header of the packet that caused the error.
2375  *
2376  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2377  * in the context of IPsec. Normally we tell the upper layer
2378  * whenever we send the ire (including ip_bind), the IPsec header
2379  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2380  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2381  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2382  * same thing. As TCP has the IPsec options size that needs to be
2383  * adjusted, we just pass the MTU unchanged.
2384  *
2385  * IFN could have been generated locally or by some router.
2386  *
2387  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2388  *	    This happens because IP adjusted its value of MTU on an
2389  *	    earlier IFN message and could not tell the upper layer,
2390  *	    the new adjusted value of MTU e.g. Packet was encrypted
2391  *	    or there was not enough information to fanout to upper
2392  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2393  *	    generates the IFN, where IPsec processing has *not* been
2394  *	    done.
2395  *
2396  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2397  *	    could have generated this. This happens because ire_max_frag
2398  *	    value in IP was set to a new value, while the IPsec processing
2399  *	    was being done and after we made the fragmentation check in
2400  *	    ip_wput_ire. Thus on return from IPsec processing,
2401  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2402  *	    and generates the IFN. As IPsec processing is over, we fanout
2403  *	    to AH/ESP to remove the header.
2404  *
2405  *	    In both these cases, ipsec_in_loopback will be set indicating
2406  *	    that IFN was generated locally.
2407  *
2408  * ROUTER : IFN could be secure or non-secure.
2409  *
2410  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2411  *	      packet in error has AH/ESP headers to validate the AH/ESP
2412  *	      headers. AH/ESP will verify whether there is a valid SA or
2413  *	      not and send it back. We will fanout again if we have more
2414  *	      data in the packet.
2415  *
2416  *	      If the packet in error does not have AH/ESP, we handle it
2417  *	      like any other case.
2418  *
2419  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2420  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2421  *	      for validation. AH/ESP will verify whether there is a
2422  *	      valid SA or not and send it back. We will fanout again if
2423  *	      we have more data in the packet.
2424  *
2425  *	      If the packet in error does not have AH/ESP, we handle it
2426  *	      like any other case.
2427  */
2428 static void
2429 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2430     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2431     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2432     zoneid_t zoneid)
2433 {
2434 	uint16_t *up;	/* Pointer to ports in ULP header */
2435 	uint32_t ports;	/* reversed ports for fanout */
2436 	ipha_t ripha;	/* With reversed addresses */
2437 	mblk_t *first_mp;
2438 	ipsec_in_t *ii;
2439 	tcph_t	*tcph;
2440 	conn_t	*connp;
2441 	ip_stack_t *ipst;
2442 
2443 	ASSERT(ill != NULL);
2444 
2445 	ASSERT(recv_ill != NULL);
2446 	ipst = recv_ill->ill_ipst;
2447 
2448 	first_mp = mp;
2449 	if (mctl_present) {
2450 		mp = first_mp->b_cont;
2451 		ASSERT(mp != NULL);
2452 
2453 		ii = (ipsec_in_t *)first_mp->b_rptr;
2454 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2455 	} else {
2456 		ii = NULL;
2457 	}
2458 
2459 	switch (ipha->ipha_protocol) {
2460 	case IPPROTO_UDP:
2461 		/*
2462 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2463 		 * transport header.
2464 		 */
2465 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2466 		    mp->b_wptr) {
2467 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2468 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2469 				goto discard_pkt;
2470 			}
2471 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2472 			ipha = (ipha_t *)&icmph[1];
2473 		}
2474 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2475 
2476 		/*
2477 		 * Attempt to find a client stream based on port.
2478 		 * Note that we do a reverse lookup since the header is
2479 		 * in the form we sent it out.
2480 		 * The ripha header is only used for the IP_UDP_MATCH and we
2481 		 * only set the src and dst addresses and protocol.
2482 		 */
2483 		ripha.ipha_src = ipha->ipha_dst;
2484 		ripha.ipha_dst = ipha->ipha_src;
2485 		ripha.ipha_protocol = ipha->ipha_protocol;
2486 		((uint16_t *)&ports)[0] = up[1];
2487 		((uint16_t *)&ports)[1] = up[0];
2488 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2489 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2490 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2491 		    icmph->icmph_type, icmph->icmph_code));
2492 
2493 		/* Have to change db_type after any pullupmsg */
2494 		DB_TYPE(mp) = M_CTL;
2495 
2496 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2497 		    mctl_present, ip_policy, recv_ill, zoneid);
2498 		return;
2499 
2500 	case IPPROTO_TCP:
2501 		/*
2502 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2503 		 * transport header.
2504 		 */
2505 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2506 		    mp->b_wptr) {
2507 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2508 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2509 				goto discard_pkt;
2510 			}
2511 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2512 			ipha = (ipha_t *)&icmph[1];
2513 		}
2514 		/*
2515 		 * Find a TCP client stream for this packet.
2516 		 * Note that we do a reverse lookup since the header is
2517 		 * in the form we sent it out.
2518 		 */
2519 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2520 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2521 		    ipst);
2522 		if (connp == NULL)
2523 			goto discard_pkt;
2524 
2525 		/* Have to change db_type after any pullupmsg */
2526 		DB_TYPE(mp) = M_CTL;
2527 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2528 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2529 		return;
2530 
2531 	case IPPROTO_SCTP:
2532 		/*
2533 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2534 		 * transport header.
2535 		 */
2536 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2537 		    mp->b_wptr) {
2538 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2539 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2540 				goto discard_pkt;
2541 			}
2542 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2543 			ipha = (ipha_t *)&icmph[1];
2544 		}
2545 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2546 		/*
2547 		 * Find a SCTP client stream for this packet.
2548 		 * Note that we do a reverse lookup since the header is
2549 		 * in the form we sent it out.
2550 		 * The ripha header is only used for the matching and we
2551 		 * only set the src and dst addresses, protocol, and version.
2552 		 */
2553 		ripha.ipha_src = ipha->ipha_dst;
2554 		ripha.ipha_dst = ipha->ipha_src;
2555 		ripha.ipha_protocol = ipha->ipha_protocol;
2556 		ripha.ipha_version_and_hdr_length =
2557 		    ipha->ipha_version_and_hdr_length;
2558 		((uint16_t *)&ports)[0] = up[1];
2559 		((uint16_t *)&ports)[1] = up[0];
2560 
2561 		/* Have to change db_type after any pullupmsg */
2562 		DB_TYPE(mp) = M_CTL;
2563 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2564 		    mctl_present, ip_policy, zoneid);
2565 		return;
2566 
2567 	case IPPROTO_ESP:
2568 	case IPPROTO_AH: {
2569 		int ipsec_rc;
2570 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2571 
2572 		/*
2573 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2574 		 * We will re-use the IPSEC_IN if it is already present as
2575 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2576 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2577 		 * one and attach it in the front.
2578 		 */
2579 		if (ii != NULL) {
2580 			/*
2581 			 * ip_fanout_proto_again converts the ICMP errors
2582 			 * that come back from AH/ESP to M_DATA so that
2583 			 * if it is non-AH/ESP and we do a pullupmsg in
2584 			 * this function, it would work. Convert it back
2585 			 * to M_CTL before we send up as this is a ICMP
2586 			 * error. This could have been generated locally or
2587 			 * by some router. Validate the inner IPsec
2588 			 * headers.
2589 			 *
2590 			 * NOTE : ill_index is used by ip_fanout_proto_again
2591 			 * to locate the ill.
2592 			 */
2593 			ASSERT(ill != NULL);
2594 			ii->ipsec_in_ill_index =
2595 			    ill->ill_phyint->phyint_ifindex;
2596 			ii->ipsec_in_rill_index =
2597 			    recv_ill->ill_phyint->phyint_ifindex;
2598 			DB_TYPE(first_mp->b_cont) = M_CTL;
2599 		} else {
2600 			/*
2601 			 * IPSEC_IN is not present. We attach a ipsec_in
2602 			 * message and send up to IPsec for validating
2603 			 * and removing the IPsec headers. Clear
2604 			 * ipsec_in_secure so that when we return
2605 			 * from IPsec, we don't mistakenly think that this
2606 			 * is a secure packet came from the network.
2607 			 *
2608 			 * NOTE : ill_index is used by ip_fanout_proto_again
2609 			 * to locate the ill.
2610 			 */
2611 			ASSERT(first_mp == mp);
2612 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2613 			if (first_mp == NULL) {
2614 				freemsg(mp);
2615 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2616 				return;
2617 			}
2618 			ii = (ipsec_in_t *)first_mp->b_rptr;
2619 
2620 			/* This is not a secure packet */
2621 			ii->ipsec_in_secure = B_FALSE;
2622 			first_mp->b_cont = mp;
2623 			DB_TYPE(mp) = M_CTL;
2624 			ASSERT(ill != NULL);
2625 			ii->ipsec_in_ill_index =
2626 			    ill->ill_phyint->phyint_ifindex;
2627 			ii->ipsec_in_rill_index =
2628 			    recv_ill->ill_phyint->phyint_ifindex;
2629 		}
2630 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2631 
2632 		if (!ipsec_loaded(ipss)) {
2633 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2634 			return;
2635 		}
2636 
2637 		if (ipha->ipha_protocol == IPPROTO_ESP)
2638 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2639 		else
2640 			ipsec_rc = ipsecah_icmp_error(first_mp);
2641 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2642 			return;
2643 
2644 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2645 		return;
2646 	}
2647 	default:
2648 		/*
2649 		 * The ripha header is only used for the lookup and we
2650 		 * only set the src and dst addresses and protocol.
2651 		 */
2652 		ripha.ipha_src = ipha->ipha_dst;
2653 		ripha.ipha_dst = ipha->ipha_src;
2654 		ripha.ipha_protocol = ipha->ipha_protocol;
2655 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2656 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2657 		    ntohl(ipha->ipha_dst),
2658 		    icmph->icmph_type, icmph->icmph_code));
2659 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2660 			ipha_t *in_ipha;
2661 
2662 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2663 			    mp->b_wptr) {
2664 				if (!pullupmsg(mp, (uchar_t *)ipha +
2665 				    hdr_length + sizeof (ipha_t) -
2666 				    mp->b_rptr)) {
2667 					goto discard_pkt;
2668 				}
2669 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2670 				ipha = (ipha_t *)&icmph[1];
2671 			}
2672 			/*
2673 			 * Caller has verified that length has to be
2674 			 * at least the size of IP header.
2675 			 */
2676 			ASSERT(hdr_length >= sizeof (ipha_t));
2677 			/*
2678 			 * Check the sanity of the inner IP header like
2679 			 * we did for the outer header.
2680 			 */
2681 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2682 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2683 				goto discard_pkt;
2684 			}
2685 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2686 				goto discard_pkt;
2687 			}
2688 			/* Check for Self-encapsulated tunnels */
2689 			if (in_ipha->ipha_src == ipha->ipha_src &&
2690 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2691 
2692 				mp = icmp_inbound_self_encap_error(mp,
2693 				    iph_hdr_length, hdr_length);
2694 				if (mp == NULL)
2695 					goto discard_pkt;
2696 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2697 				ipha = (ipha_t *)&icmph[1];
2698 				hdr_length = IPH_HDR_LENGTH(ipha);
2699 				/*
2700 				 * The packet in error is self-encapsualted.
2701 				 * And we are finding it further encapsulated
2702 				 * which we could not have possibly generated.
2703 				 */
2704 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2705 					goto discard_pkt;
2706 				}
2707 				icmp_inbound_error_fanout(q, ill, first_mp,
2708 				    icmph, ipha, iph_hdr_length, hdr_length,
2709 				    mctl_present, ip_policy, recv_ill, zoneid);
2710 				return;
2711 			}
2712 		}
2713 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2714 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2715 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2716 		    ii != NULL &&
2717 		    ii->ipsec_in_loopback &&
2718 		    ii->ipsec_in_secure) {
2719 			/*
2720 			 * For IP tunnels that get a looped-back
2721 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2722 			 * reported new MTU to take into account the IPsec
2723 			 * headers protecting this configured tunnel.
2724 			 *
2725 			 * This allows the tunnel module (tun.c) to blindly
2726 			 * accept the MTU reported in an ICMP "too big"
2727 			 * message.
2728 			 *
2729 			 * Non-looped back ICMP messages will just be
2730 			 * handled by the security protocols (if needed),
2731 			 * and the first subsequent packet will hit this
2732 			 * path.
2733 			 */
2734 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2735 			    ipsec_in_extra_length(first_mp));
2736 		}
2737 		/* Have to change db_type after any pullupmsg */
2738 		DB_TYPE(mp) = M_CTL;
2739 
2740 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2741 		    ip_policy, recv_ill, zoneid);
2742 		return;
2743 	}
2744 	/* NOTREACHED */
2745 discard_pkt:
2746 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2747 drop_pkt:;
2748 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2749 	freemsg(first_mp);
2750 }
2751 
2752 /*
2753  * Common IP options parser.
2754  *
2755  * Setup routine: fill in *optp with options-parsing state, then
2756  * tail-call ipoptp_next to return the first option.
2757  */
2758 uint8_t
2759 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2760 {
2761 	uint32_t totallen; /* total length of all options */
2762 
2763 	totallen = ipha->ipha_version_and_hdr_length -
2764 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2765 	totallen <<= 2;
2766 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2767 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2768 	optp->ipoptp_flags = 0;
2769 	return (ipoptp_next(optp));
2770 }
2771 
2772 /*
2773  * Common IP options parser: extract next option.
2774  */
2775 uint8_t
2776 ipoptp_next(ipoptp_t *optp)
2777 {
2778 	uint8_t *end = optp->ipoptp_end;
2779 	uint8_t *cur = optp->ipoptp_next;
2780 	uint8_t opt, len, pointer;
2781 
2782 	/*
2783 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2784 	 * has been corrupted.
2785 	 */
2786 	ASSERT(cur <= end);
2787 
2788 	if (cur == end)
2789 		return (IPOPT_EOL);
2790 
2791 	opt = cur[IPOPT_OPTVAL];
2792 
2793 	/*
2794 	 * Skip any NOP options.
2795 	 */
2796 	while (opt == IPOPT_NOP) {
2797 		cur++;
2798 		if (cur == end)
2799 			return (IPOPT_EOL);
2800 		opt = cur[IPOPT_OPTVAL];
2801 	}
2802 
2803 	if (opt == IPOPT_EOL)
2804 		return (IPOPT_EOL);
2805 
2806 	/*
2807 	 * Option requiring a length.
2808 	 */
2809 	if ((cur + 1) >= end) {
2810 		optp->ipoptp_flags |= IPOPTP_ERROR;
2811 		return (IPOPT_EOL);
2812 	}
2813 	len = cur[IPOPT_OLEN];
2814 	if (len < 2) {
2815 		optp->ipoptp_flags |= IPOPTP_ERROR;
2816 		return (IPOPT_EOL);
2817 	}
2818 	optp->ipoptp_cur = cur;
2819 	optp->ipoptp_len = len;
2820 	optp->ipoptp_next = cur + len;
2821 	if (cur + len > end) {
2822 		optp->ipoptp_flags |= IPOPTP_ERROR;
2823 		return (IPOPT_EOL);
2824 	}
2825 
2826 	/*
2827 	 * For the options which require a pointer field, make sure
2828 	 * its there, and make sure it points to either something
2829 	 * inside this option, or the end of the option.
2830 	 */
2831 	switch (opt) {
2832 	case IPOPT_RR:
2833 	case IPOPT_TS:
2834 	case IPOPT_LSRR:
2835 	case IPOPT_SSRR:
2836 		if (len <= IPOPT_OFFSET) {
2837 			optp->ipoptp_flags |= IPOPTP_ERROR;
2838 			return (opt);
2839 		}
2840 		pointer = cur[IPOPT_OFFSET];
2841 		if (pointer - 1 > len) {
2842 			optp->ipoptp_flags |= IPOPTP_ERROR;
2843 			return (opt);
2844 		}
2845 		break;
2846 	}
2847 
2848 	/*
2849 	 * Sanity check the pointer field based on the type of the
2850 	 * option.
2851 	 */
2852 	switch (opt) {
2853 	case IPOPT_RR:
2854 	case IPOPT_SSRR:
2855 	case IPOPT_LSRR:
2856 		if (pointer < IPOPT_MINOFF_SR)
2857 			optp->ipoptp_flags |= IPOPTP_ERROR;
2858 		break;
2859 	case IPOPT_TS:
2860 		if (pointer < IPOPT_MINOFF_IT)
2861 			optp->ipoptp_flags |= IPOPTP_ERROR;
2862 		/*
2863 		 * Note that the Internet Timestamp option also
2864 		 * contains two four bit fields (the Overflow field,
2865 		 * and the Flag field), which follow the pointer
2866 		 * field.  We don't need to check that these fields
2867 		 * fall within the length of the option because this
2868 		 * was implicitely done above.  We've checked that the
2869 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2870 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2871 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2872 		 */
2873 		ASSERT(len > IPOPT_POS_OV_FLG);
2874 		break;
2875 	}
2876 
2877 	return (opt);
2878 }
2879 
2880 /*
2881  * Use the outgoing IP header to create an IP_OPTIONS option the way
2882  * it was passed down from the application.
2883  */
2884 int
2885 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2886 {
2887 	ipoptp_t	opts;
2888 	const uchar_t	*opt;
2889 	uint8_t		optval;
2890 	uint8_t		optlen;
2891 	uint32_t	len = 0;
2892 	uchar_t	*buf1 = buf;
2893 
2894 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2895 	len += IP_ADDR_LEN;
2896 	bzero(buf1, IP_ADDR_LEN);
2897 
2898 	/*
2899 	 * OK to cast away const here, as we don't store through the returned
2900 	 * opts.ipoptp_cur pointer.
2901 	 */
2902 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2903 	    optval != IPOPT_EOL;
2904 	    optval = ipoptp_next(&opts)) {
2905 		int	off;
2906 
2907 		opt = opts.ipoptp_cur;
2908 		optlen = opts.ipoptp_len;
2909 		switch (optval) {
2910 		case IPOPT_SSRR:
2911 		case IPOPT_LSRR:
2912 
2913 			/*
2914 			 * Insert ipha_dst as the first entry in the source
2915 			 * route and move down the entries on step.
2916 			 * The last entry gets placed at buf1.
2917 			 */
2918 			buf[IPOPT_OPTVAL] = optval;
2919 			buf[IPOPT_OLEN] = optlen;
2920 			buf[IPOPT_OFFSET] = optlen;
2921 
2922 			off = optlen - IP_ADDR_LEN;
2923 			if (off < 0) {
2924 				/* No entries in source route */
2925 				break;
2926 			}
2927 			/* Last entry in source route */
2928 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2929 			off -= IP_ADDR_LEN;
2930 
2931 			while (off > 0) {
2932 				bcopy(opt + off,
2933 				    buf + off + IP_ADDR_LEN,
2934 				    IP_ADDR_LEN);
2935 				off -= IP_ADDR_LEN;
2936 			}
2937 			/* ipha_dst into first slot */
2938 			bcopy(&ipha->ipha_dst,
2939 			    buf + off + IP_ADDR_LEN,
2940 			    IP_ADDR_LEN);
2941 			buf += optlen;
2942 			len += optlen;
2943 			break;
2944 
2945 		case IPOPT_COMSEC:
2946 		case IPOPT_SECURITY:
2947 			/* if passing up a label is not ok, then remove */
2948 			if (is_system_labeled())
2949 				break;
2950 			/* FALLTHROUGH */
2951 		default:
2952 			bcopy(opt, buf, optlen);
2953 			buf += optlen;
2954 			len += optlen;
2955 			break;
2956 		}
2957 	}
2958 done:
2959 	/* Pad the resulting options */
2960 	while (len & 0x3) {
2961 		*buf++ = IPOPT_EOL;
2962 		len++;
2963 	}
2964 	return (len);
2965 }
2966 
2967 /*
2968  * Update any record route or timestamp options to include this host.
2969  * Reverse any source route option.
2970  * This routine assumes that the options are well formed i.e. that they
2971  * have already been checked.
2972  */
2973 static void
2974 icmp_options_update(ipha_t *ipha)
2975 {
2976 	ipoptp_t	opts;
2977 	uchar_t		*opt;
2978 	uint8_t		optval;
2979 	ipaddr_t	src;		/* Our local address */
2980 	ipaddr_t	dst;
2981 
2982 	ip2dbg(("icmp_options_update\n"));
2983 	src = ipha->ipha_src;
2984 	dst = ipha->ipha_dst;
2985 
2986 	for (optval = ipoptp_first(&opts, ipha);
2987 	    optval != IPOPT_EOL;
2988 	    optval = ipoptp_next(&opts)) {
2989 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2990 		opt = opts.ipoptp_cur;
2991 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2992 		    optval, opts.ipoptp_len));
2993 		switch (optval) {
2994 			int off1, off2;
2995 		case IPOPT_SSRR:
2996 		case IPOPT_LSRR:
2997 			/*
2998 			 * Reverse the source route.  The first entry
2999 			 * should be the next to last one in the current
3000 			 * source route (the last entry is our address).
3001 			 * The last entry should be the final destination.
3002 			 */
3003 			off1 = IPOPT_MINOFF_SR - 1;
3004 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3005 			if (off2 < 0) {
3006 				/* No entries in source route */
3007 				ip1dbg((
3008 				    "icmp_options_update: bad src route\n"));
3009 				break;
3010 			}
3011 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3012 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3013 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3014 			off2 -= IP_ADDR_LEN;
3015 
3016 			while (off1 < off2) {
3017 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3018 				bcopy((char *)opt + off2, (char *)opt + off1,
3019 				    IP_ADDR_LEN);
3020 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3021 				off1 += IP_ADDR_LEN;
3022 				off2 -= IP_ADDR_LEN;
3023 			}
3024 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3025 			break;
3026 		}
3027 	}
3028 }
3029 
3030 /*
3031  * Process received ICMP Redirect messages.
3032  */
3033 static void
3034 icmp_redirect(ill_t *ill, mblk_t *mp)
3035 {
3036 	ipha_t	*ipha;
3037 	int	iph_hdr_length;
3038 	icmph_t	*icmph;
3039 	ipha_t	*ipha_err;
3040 	ire_t	*ire;
3041 	ire_t	*prev_ire;
3042 	ire_t	*save_ire;
3043 	ipaddr_t  src, dst, gateway;
3044 	iulp_t	ulp_info = { 0 };
3045 	int	error;
3046 	ip_stack_t *ipst;
3047 
3048 	ASSERT(ill != NULL);
3049 	ipst = ill->ill_ipst;
3050 
3051 	ipha = (ipha_t *)mp->b_rptr;
3052 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3053 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3054 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3055 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3056 		freemsg(mp);
3057 		return;
3058 	}
3059 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3060 	ipha_err = (ipha_t *)&icmph[1];
3061 	src = ipha->ipha_src;
3062 	dst = ipha_err->ipha_dst;
3063 	gateway = icmph->icmph_rd_gateway;
3064 	/* Make sure the new gateway is reachable somehow. */
3065 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3066 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3067 	/*
3068 	 * Make sure we had a route for the dest in question and that
3069 	 * that route was pointing to the old gateway (the source of the
3070 	 * redirect packet.)
3071 	 */
3072 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3073 	    NULL, MATCH_IRE_GW, ipst);
3074 	/*
3075 	 * Check that
3076 	 *	the redirect was not from ourselves
3077 	 *	the new gateway and the old gateway are directly reachable
3078 	 */
3079 	if (!prev_ire ||
3080 	    !ire ||
3081 	    ire->ire_type == IRE_LOCAL) {
3082 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3083 		freemsg(mp);
3084 		if (ire != NULL)
3085 			ire_refrele(ire);
3086 		if (prev_ire != NULL)
3087 			ire_refrele(prev_ire);
3088 		return;
3089 	}
3090 
3091 	/*
3092 	 * Should we use the old ULP info to create the new gateway?  From
3093 	 * a user's perspective, we should inherit the info so that it
3094 	 * is a "smooth" transition.  If we do not do that, then new
3095 	 * connections going thru the new gateway will have no route metrics,
3096 	 * which is counter-intuitive to user.  From a network point of
3097 	 * view, this may or may not make sense even though the new gateway
3098 	 * is still directly connected to us so the route metrics should not
3099 	 * change much.
3100 	 *
3101 	 * But if the old ire_uinfo is not initialized, we do another
3102 	 * recursive lookup on the dest using the new gateway.  There may
3103 	 * be a route to that.  If so, use it to initialize the redirect
3104 	 * route.
3105 	 */
3106 	if (prev_ire->ire_uinfo.iulp_set) {
3107 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3108 	} else {
3109 		ire_t *tmp_ire;
3110 		ire_t *sire;
3111 
3112 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3113 		    ALL_ZONES, 0, NULL,
3114 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3115 		    ipst);
3116 		if (sire != NULL) {
3117 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3118 			/*
3119 			 * If sire != NULL, ire_ftable_lookup() should not
3120 			 * return a NULL value.
3121 			 */
3122 			ASSERT(tmp_ire != NULL);
3123 			ire_refrele(tmp_ire);
3124 			ire_refrele(sire);
3125 		} else if (tmp_ire != NULL) {
3126 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3127 			    sizeof (iulp_t));
3128 			ire_refrele(tmp_ire);
3129 		}
3130 	}
3131 	if (prev_ire->ire_type == IRE_CACHE)
3132 		ire_delete(prev_ire);
3133 	ire_refrele(prev_ire);
3134 	/*
3135 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3136 	 * require TOS routing
3137 	 */
3138 	switch (icmph->icmph_code) {
3139 	case 0:
3140 	case 1:
3141 		/* TODO: TOS specificity for cases 2 and 3 */
3142 	case 2:
3143 	case 3:
3144 		break;
3145 	default:
3146 		freemsg(mp);
3147 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3148 		ire_refrele(ire);
3149 		return;
3150 	}
3151 	/*
3152 	 * Create a Route Association.  This will allow us to remember that
3153 	 * someone we believe told us to use the particular gateway.
3154 	 */
3155 	save_ire = ire;
3156 	ire = ire_create(
3157 	    (uchar_t *)&dst,			/* dest addr */
3158 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3159 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3160 	    (uchar_t *)&gateway,		/* gateway addr */
3161 	    &save_ire->ire_max_frag,		/* max frag */
3162 	    NULL,				/* no src nce */
3163 	    NULL,				/* no rfq */
3164 	    NULL,				/* no stq */
3165 	    IRE_HOST,
3166 	    NULL,				/* ipif */
3167 	    0,					/* cmask */
3168 	    0,					/* phandle */
3169 	    0,					/* ihandle */
3170 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3171 	    &ulp_info,
3172 	    NULL,				/* tsol_gc_t */
3173 	    NULL,				/* gcgrp */
3174 	    ipst);
3175 
3176 	if (ire == NULL) {
3177 		freemsg(mp);
3178 		ire_refrele(save_ire);
3179 		return;
3180 	}
3181 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3182 	ire_refrele(save_ire);
3183 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3184 
3185 	if (error == 0) {
3186 		ire_refrele(ire);		/* Held in ire_add_v4 */
3187 		/* tell routing sockets that we received a redirect */
3188 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3189 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3190 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3191 	}
3192 
3193 	/*
3194 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3195 	 * This together with the added IRE has the effect of
3196 	 * modifying an existing redirect.
3197 	 */
3198 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3199 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3200 	if (prev_ire != NULL) {
3201 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3202 			ire_delete(prev_ire);
3203 		ire_refrele(prev_ire);
3204 	}
3205 
3206 	freemsg(mp);
3207 }
3208 
3209 /*
3210  * Generate an ICMP parameter problem message.
3211  */
3212 static void
3213 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3214 	ip_stack_t *ipst)
3215 {
3216 	icmph_t	icmph;
3217 	boolean_t mctl_present;
3218 	mblk_t *first_mp;
3219 
3220 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3221 
3222 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3223 		if (mctl_present)
3224 			freeb(first_mp);
3225 		return;
3226 	}
3227 
3228 	bzero(&icmph, sizeof (icmph_t));
3229 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3230 	icmph.icmph_pp_ptr = ptr;
3231 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3232 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3233 	    ipst);
3234 }
3235 
3236 /*
3237  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3238  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3239  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3240  * an icmp error packet can be sent.
3241  * Assigns an appropriate source address to the packet. If ipha_dst is
3242  * one of our addresses use it for source. Otherwise pick a source based
3243  * on a route lookup back to ipha_src.
3244  * Note that ipha_src must be set here since the
3245  * packet is likely to arrive on an ill queue in ip_wput() which will
3246  * not set a source address.
3247  */
3248 static void
3249 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3250     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3251 {
3252 	ipaddr_t dst;
3253 	icmph_t	*icmph;
3254 	ipha_t	*ipha;
3255 	uint_t	len_needed;
3256 	size_t	msg_len;
3257 	mblk_t	*mp1;
3258 	ipaddr_t src;
3259 	ire_t	*ire;
3260 	mblk_t *ipsec_mp;
3261 	ipsec_out_t	*io = NULL;
3262 
3263 	if (mctl_present) {
3264 		/*
3265 		 * If it is :
3266 		 *
3267 		 * 1) a IPSEC_OUT, then this is caused by outbound
3268 		 *    datagram originating on this host. IPsec processing
3269 		 *    may or may not have been done. Refer to comments above
3270 		 *    icmp_inbound_error_fanout for details.
3271 		 *
3272 		 * 2) a IPSEC_IN if we are generating a icmp_message
3273 		 *    for an incoming datagram destined for us i.e called
3274 		 *    from ip_fanout_send_icmp.
3275 		 */
3276 		ipsec_info_t *in;
3277 		ipsec_mp = mp;
3278 		mp = ipsec_mp->b_cont;
3279 
3280 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3281 		ipha = (ipha_t *)mp->b_rptr;
3282 
3283 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3284 		    in->ipsec_info_type == IPSEC_IN);
3285 
3286 		if (in->ipsec_info_type == IPSEC_IN) {
3287 			/*
3288 			 * Convert the IPSEC_IN to IPSEC_OUT.
3289 			 */
3290 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3291 				BUMP_MIB(&ipst->ips_ip_mib,
3292 				    ipIfStatsOutDiscards);
3293 				return;
3294 			}
3295 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3296 		} else {
3297 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3298 			io = (ipsec_out_t *)in;
3299 			/*
3300 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3301 			 * ire lookup.
3302 			 */
3303 			io->ipsec_out_proc_begin = B_FALSE;
3304 		}
3305 		ASSERT(zoneid == io->ipsec_out_zoneid);
3306 		ASSERT(zoneid != ALL_ZONES);
3307 	} else {
3308 		/*
3309 		 * This is in clear. The icmp message we are building
3310 		 * here should go out in clear.
3311 		 *
3312 		 * Pardon the convolution of it all, but it's easier to
3313 		 * allocate a "use cleartext" IPSEC_IN message and convert
3314 		 * it than it is to allocate a new one.
3315 		 */
3316 		ipsec_in_t *ii;
3317 		ASSERT(DB_TYPE(mp) == M_DATA);
3318 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3319 		if (ipsec_mp == NULL) {
3320 			freemsg(mp);
3321 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3322 			return;
3323 		}
3324 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3325 
3326 		/* This is not a secure packet */
3327 		ii->ipsec_in_secure = B_FALSE;
3328 		/*
3329 		 * For trusted extensions using a shared IP address we can
3330 		 * send using any zoneid.
3331 		 */
3332 		if (zoneid == ALL_ZONES)
3333 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3334 		else
3335 			ii->ipsec_in_zoneid = zoneid;
3336 		ipsec_mp->b_cont = mp;
3337 		ipha = (ipha_t *)mp->b_rptr;
3338 		/*
3339 		 * Convert the IPSEC_IN to IPSEC_OUT.
3340 		 */
3341 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3342 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3343 			return;
3344 		}
3345 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3346 	}
3347 
3348 	/* Remember our eventual destination */
3349 	dst = ipha->ipha_src;
3350 
3351 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3352 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3353 	if (ire != NULL &&
3354 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3355 		src = ipha->ipha_dst;
3356 	} else {
3357 		if (ire != NULL)
3358 			ire_refrele(ire);
3359 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3360 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3361 		    ipst);
3362 		if (ire == NULL) {
3363 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3364 			freemsg(ipsec_mp);
3365 			return;
3366 		}
3367 		src = ire->ire_src_addr;
3368 	}
3369 
3370 	if (ire != NULL)
3371 		ire_refrele(ire);
3372 
3373 	/*
3374 	 * Check if we can send back more then 8 bytes in addition to
3375 	 * the IP header.  We try to send 64 bytes of data and the internal
3376 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3377 	 */
3378 	len_needed = IPH_HDR_LENGTH(ipha);
3379 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3380 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3381 
3382 		if (!pullupmsg(mp, -1)) {
3383 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3384 			freemsg(ipsec_mp);
3385 			return;
3386 		}
3387 		ipha = (ipha_t *)mp->b_rptr;
3388 
3389 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3390 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3391 			    len_needed));
3392 		} else {
3393 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3394 
3395 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3396 			len_needed += ip_hdr_length_v6(mp, ip6h);
3397 		}
3398 	}
3399 	len_needed += ipst->ips_ip_icmp_return;
3400 	msg_len = msgdsize(mp);
3401 	if (msg_len > len_needed) {
3402 		(void) adjmsg(mp, len_needed - msg_len);
3403 		msg_len = len_needed;
3404 	}
3405 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3406 	if (mp1 == NULL) {
3407 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3408 		freemsg(ipsec_mp);
3409 		return;
3410 	}
3411 	mp1->b_cont = mp;
3412 	mp = mp1;
3413 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3414 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3415 	    io->ipsec_out_type == IPSEC_OUT);
3416 	ipsec_mp->b_cont = mp;
3417 
3418 	/*
3419 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3420 	 * node generates be accepted in peace by all on-host destinations.
3421 	 * If we do NOT assume that all on-host destinations trust
3422 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3423 	 * (Look for ipsec_out_icmp_loopback).
3424 	 */
3425 	io->ipsec_out_icmp_loopback = B_TRUE;
3426 
3427 	ipha = (ipha_t *)mp->b_rptr;
3428 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3429 	*ipha = icmp_ipha;
3430 	ipha->ipha_src = src;
3431 	ipha->ipha_dst = dst;
3432 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3433 	msg_len += sizeof (icmp_ipha) + len;
3434 	if (msg_len > IP_MAXPACKET) {
3435 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3436 		msg_len = IP_MAXPACKET;
3437 	}
3438 	ipha->ipha_length = htons((uint16_t)msg_len);
3439 	icmph = (icmph_t *)&ipha[1];
3440 	bcopy(stuff, icmph, len);
3441 	icmph->icmph_checksum = 0;
3442 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3443 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3444 	put(q, ipsec_mp);
3445 }
3446 
3447 /*
3448  * Determine if an ICMP error packet can be sent given the rate limit.
3449  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3450  * in milliseconds) and a burst size. Burst size number of packets can
3451  * be sent arbitrarely closely spaced.
3452  * The state is tracked using two variables to implement an approximate
3453  * token bucket filter:
3454  *	icmp_pkt_err_last - lbolt value when the last burst started
3455  *	icmp_pkt_err_sent - number of packets sent in current burst
3456  */
3457 boolean_t
3458 icmp_err_rate_limit(ip_stack_t *ipst)
3459 {
3460 	clock_t now = TICK_TO_MSEC(lbolt);
3461 	uint_t refilled; /* Number of packets refilled in tbf since last */
3462 	/* Guard against changes by loading into local variable */
3463 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3464 
3465 	if (err_interval == 0)
3466 		return (B_FALSE);
3467 
3468 	if (ipst->ips_icmp_pkt_err_last > now) {
3469 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3470 		ipst->ips_icmp_pkt_err_last = 0;
3471 		ipst->ips_icmp_pkt_err_sent = 0;
3472 	}
3473 	/*
3474 	 * If we are in a burst update the token bucket filter.
3475 	 * Update the "last" time to be close to "now" but make sure
3476 	 * we don't loose precision.
3477 	 */
3478 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3479 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3480 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3481 			ipst->ips_icmp_pkt_err_sent = 0;
3482 		} else {
3483 			ipst->ips_icmp_pkt_err_sent -= refilled;
3484 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3485 		}
3486 	}
3487 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3488 		/* Start of new burst */
3489 		ipst->ips_icmp_pkt_err_last = now;
3490 	}
3491 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3492 		ipst->ips_icmp_pkt_err_sent++;
3493 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3494 		    ipst->ips_icmp_pkt_err_sent));
3495 		return (B_FALSE);
3496 	}
3497 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3498 	return (B_TRUE);
3499 }
3500 
3501 /*
3502  * Check if it is ok to send an IPv4 ICMP error packet in
3503  * response to the IPv4 packet in mp.
3504  * Free the message and return null if no
3505  * ICMP error packet should be sent.
3506  */
3507 static mblk_t *
3508 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3509 {
3510 	icmph_t	*icmph;
3511 	ipha_t	*ipha;
3512 	uint_t	len_needed;
3513 	ire_t	*src_ire;
3514 	ire_t	*dst_ire;
3515 
3516 	if (!mp)
3517 		return (NULL);
3518 	ipha = (ipha_t *)mp->b_rptr;
3519 	if (ip_csum_hdr(ipha)) {
3520 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3521 		freemsg(mp);
3522 		return (NULL);
3523 	}
3524 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3525 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3526 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3527 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3528 	if (src_ire != NULL || dst_ire != NULL ||
3529 	    CLASSD(ipha->ipha_dst) ||
3530 	    CLASSD(ipha->ipha_src) ||
3531 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3532 		/* Note: only errors to the fragment with offset 0 */
3533 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3534 		freemsg(mp);
3535 		if (src_ire != NULL)
3536 			ire_refrele(src_ire);
3537 		if (dst_ire != NULL)
3538 			ire_refrele(dst_ire);
3539 		return (NULL);
3540 	}
3541 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3542 		/*
3543 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3544 		 * errors in response to any ICMP errors.
3545 		 */
3546 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3547 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3548 			if (!pullupmsg(mp, len_needed)) {
3549 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3550 				freemsg(mp);
3551 				return (NULL);
3552 			}
3553 			ipha = (ipha_t *)mp->b_rptr;
3554 		}
3555 		icmph = (icmph_t *)
3556 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3557 		switch (icmph->icmph_type) {
3558 		case ICMP_DEST_UNREACHABLE:
3559 		case ICMP_SOURCE_QUENCH:
3560 		case ICMP_TIME_EXCEEDED:
3561 		case ICMP_PARAM_PROBLEM:
3562 		case ICMP_REDIRECT:
3563 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3564 			freemsg(mp);
3565 			return (NULL);
3566 		default:
3567 			break;
3568 		}
3569 	}
3570 	/*
3571 	 * If this is a labeled system, then check to see if we're allowed to
3572 	 * send a response to this particular sender.  If not, then just drop.
3573 	 */
3574 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3575 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3576 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3577 		freemsg(mp);
3578 		return (NULL);
3579 	}
3580 	if (icmp_err_rate_limit(ipst)) {
3581 		/*
3582 		 * Only send ICMP error packets every so often.
3583 		 * This should be done on a per port/source basis,
3584 		 * but for now this will suffice.
3585 		 */
3586 		freemsg(mp);
3587 		return (NULL);
3588 	}
3589 	return (mp);
3590 }
3591 
3592 /*
3593  * Generate an ICMP redirect message.
3594  */
3595 static void
3596 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3597 {
3598 	icmph_t	icmph;
3599 
3600 	/*
3601 	 * We are called from ip_rput where we could
3602 	 * not have attached an IPSEC_IN.
3603 	 */
3604 	ASSERT(mp->b_datap->db_type == M_DATA);
3605 
3606 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3607 		return;
3608 	}
3609 
3610 	bzero(&icmph, sizeof (icmph_t));
3611 	icmph.icmph_type = ICMP_REDIRECT;
3612 	icmph.icmph_code = 1;
3613 	icmph.icmph_rd_gateway = gateway;
3614 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3615 	/* Redirects sent by router, and router is global zone */
3616 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3617 }
3618 
3619 /*
3620  * Generate an ICMP time exceeded message.
3621  */
3622 void
3623 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3624     ip_stack_t *ipst)
3625 {
3626 	icmph_t	icmph;
3627 	boolean_t mctl_present;
3628 	mblk_t *first_mp;
3629 
3630 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3631 
3632 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3633 		if (mctl_present)
3634 			freeb(first_mp);
3635 		return;
3636 	}
3637 
3638 	bzero(&icmph, sizeof (icmph_t));
3639 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3640 	icmph.icmph_code = code;
3641 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3642 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3643 	    ipst);
3644 }
3645 
3646 /*
3647  * Generate an ICMP unreachable message.
3648  */
3649 void
3650 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3651     ip_stack_t *ipst)
3652 {
3653 	icmph_t	icmph;
3654 	mblk_t *first_mp;
3655 	boolean_t mctl_present;
3656 
3657 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3658 
3659 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3660 		if (mctl_present)
3661 			freeb(first_mp);
3662 		return;
3663 	}
3664 
3665 	bzero(&icmph, sizeof (icmph_t));
3666 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3667 	icmph.icmph_code = code;
3668 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3669 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3670 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3671 	    zoneid, ipst);
3672 }
3673 
3674 /*
3675  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3676  * duplicate.  As long as someone else holds the address, the interface will
3677  * stay down.  When that conflict goes away, the interface is brought back up.
3678  * This is done so that accidental shutdowns of addresses aren't made
3679  * permanent.  Your server will recover from a failure.
3680  *
3681  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3682  * user space process (dhcpagent).
3683  *
3684  * Recovery completes if ARP reports that the address is now ours (via
3685  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3686  *
3687  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3688  */
3689 static void
3690 ipif_dup_recovery(void *arg)
3691 {
3692 	ipif_t *ipif = arg;
3693 	ill_t *ill = ipif->ipif_ill;
3694 	mblk_t *arp_add_mp;
3695 	mblk_t *arp_del_mp;
3696 	area_t *area;
3697 	ip_stack_t *ipst = ill->ill_ipst;
3698 
3699 	ipif->ipif_recovery_id = 0;
3700 
3701 	/*
3702 	 * No lock needed for moving or condemned check, as this is just an
3703 	 * optimization.
3704 	 */
3705 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3706 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3707 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3708 		/* No reason to try to bring this address back. */
3709 		return;
3710 	}
3711 
3712 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3713 		goto alloc_fail;
3714 
3715 	if (ipif->ipif_arp_del_mp == NULL) {
3716 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3717 			goto alloc_fail;
3718 		ipif->ipif_arp_del_mp = arp_del_mp;
3719 	}
3720 
3721 	/* Setting the 'unverified' flag restarts DAD */
3722 	area = (area_t *)arp_add_mp->b_rptr;
3723 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3724 	    ACE_F_UNVERIFIED;
3725 	putnext(ill->ill_rq, arp_add_mp);
3726 	return;
3727 
3728 alloc_fail:
3729 	/*
3730 	 * On allocation failure, just restart the timer.  Note that the ipif
3731 	 * is down here, so no other thread could be trying to start a recovery
3732 	 * timer.  The ill_lock protects the condemned flag and the recovery
3733 	 * timer ID.
3734 	 */
3735 	freemsg(arp_add_mp);
3736 	mutex_enter(&ill->ill_lock);
3737 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3738 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3739 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3740 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3741 	}
3742 	mutex_exit(&ill->ill_lock);
3743 }
3744 
3745 /*
3746  * This is for exclusive changes due to ARP.  Either tear down an interface due
3747  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3748  */
3749 /* ARGSUSED */
3750 static void
3751 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3752 {
3753 	ill_t	*ill = rq->q_ptr;
3754 	arh_t *arh;
3755 	ipaddr_t src;
3756 	ipif_t	*ipif;
3757 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3758 	char hbuf[MAC_STR_LEN];
3759 	char sbuf[INET_ADDRSTRLEN];
3760 	const char *failtype;
3761 	boolean_t bring_up;
3762 	ip_stack_t *ipst = ill->ill_ipst;
3763 
3764 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3765 	case AR_CN_READY:
3766 		failtype = NULL;
3767 		bring_up = B_TRUE;
3768 		break;
3769 	case AR_CN_FAILED:
3770 		failtype = "in use";
3771 		bring_up = B_FALSE;
3772 		break;
3773 	default:
3774 		failtype = "claimed";
3775 		bring_up = B_FALSE;
3776 		break;
3777 	}
3778 
3779 	arh = (arh_t *)mp->b_cont->b_rptr;
3780 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3781 
3782 	/* Handle failures due to probes */
3783 	if (src == 0) {
3784 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3785 		    IP_ADDR_LEN);
3786 	}
3787 
3788 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3789 	    sizeof (hbuf));
3790 	(void) ip_dot_addr(src, sbuf);
3791 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3792 
3793 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3794 		    ipif->ipif_lcl_addr != src) {
3795 			continue;
3796 		}
3797 
3798 		/*
3799 		 * If we failed on a recovery probe, then restart the timer to
3800 		 * try again later.
3801 		 */
3802 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3803 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3804 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3805 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3806 		    ipst->ips_ip_dup_recovery > 0 &&
3807 		    ipif->ipif_recovery_id == 0) {
3808 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3809 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3810 			continue;
3811 		}
3812 
3813 		/*
3814 		 * If what we're trying to do has already been done, then do
3815 		 * nothing.
3816 		 */
3817 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3818 			continue;
3819 
3820 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3821 
3822 		if (failtype == NULL) {
3823 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3824 			    ibuf);
3825 		} else {
3826 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3827 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3828 		}
3829 
3830 		if (bring_up) {
3831 			ASSERT(ill->ill_dl_up);
3832 			/*
3833 			 * Free up the ARP delete message so we can allocate
3834 			 * a fresh one through the normal path.
3835 			 */
3836 			freemsg(ipif->ipif_arp_del_mp);
3837 			ipif->ipif_arp_del_mp = NULL;
3838 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3839 			    EINPROGRESS) {
3840 				ipif->ipif_addr_ready = 1;
3841 				(void) ipif_up_done(ipif);
3842 			}
3843 			continue;
3844 		}
3845 
3846 		mutex_enter(&ill->ill_lock);
3847 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3848 		ipif->ipif_flags |= IPIF_DUPLICATE;
3849 		ill->ill_ipif_dup_count++;
3850 		mutex_exit(&ill->ill_lock);
3851 		/*
3852 		 * Already exclusive on the ill; no need to handle deferred
3853 		 * processing here.
3854 		 */
3855 		(void) ipif_down(ipif, NULL, NULL);
3856 		ipif_down_tail(ipif);
3857 		mutex_enter(&ill->ill_lock);
3858 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3859 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3860 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3861 		    ipst->ips_ip_dup_recovery > 0) {
3862 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3863 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3864 		}
3865 		mutex_exit(&ill->ill_lock);
3866 	}
3867 	freemsg(mp);
3868 }
3869 
3870 /* ARGSUSED */
3871 static void
3872 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3873 {
3874 	ill_t	*ill = rq->q_ptr;
3875 	arh_t *arh;
3876 	ipaddr_t src;
3877 	ipif_t	*ipif;
3878 
3879 	arh = (arh_t *)mp->b_cont->b_rptr;
3880 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3881 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3882 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3883 			(void) ipif_resolver_up(ipif, Res_act_defend);
3884 	}
3885 	freemsg(mp);
3886 }
3887 
3888 /*
3889  * News from ARP.  ARP sends notification of interesting events down
3890  * to its clients using M_CTL messages with the interesting ARP packet
3891  * attached via b_cont.
3892  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3893  * queue as opposed to ARP sending the message to all the clients, i.e. all
3894  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3895  * table if a cache IRE is found to delete all the entries for the address in
3896  * the packet.
3897  */
3898 static void
3899 ip_arp_news(queue_t *q, mblk_t *mp)
3900 {
3901 	arcn_t		*arcn;
3902 	arh_t		*arh;
3903 	ire_t		*ire = NULL;
3904 	char		hbuf[MAC_STR_LEN];
3905 	char		sbuf[INET_ADDRSTRLEN];
3906 	ipaddr_t	src;
3907 	in6_addr_t	v6src;
3908 	boolean_t	isv6 = B_FALSE;
3909 	ipif_t		*ipif;
3910 	ill_t		*ill;
3911 	ip_stack_t	*ipst;
3912 
3913 	if (CONN_Q(q)) {
3914 		conn_t *connp = Q_TO_CONN(q);
3915 
3916 		ipst = connp->conn_netstack->netstack_ip;
3917 	} else {
3918 		ill_t *ill = (ill_t *)q->q_ptr;
3919 
3920 		ipst = ill->ill_ipst;
3921 	}
3922 
3923 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3924 		if (q->q_next) {
3925 			putnext(q, mp);
3926 		} else
3927 			freemsg(mp);
3928 		return;
3929 	}
3930 	arh = (arh_t *)mp->b_cont->b_rptr;
3931 	/* Is it one we are interested in? */
3932 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3933 		isv6 = B_TRUE;
3934 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3935 		    IPV6_ADDR_LEN);
3936 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3937 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3938 		    IP_ADDR_LEN);
3939 	} else {
3940 		freemsg(mp);
3941 		return;
3942 	}
3943 
3944 	ill = q->q_ptr;
3945 
3946 	arcn = (arcn_t *)mp->b_rptr;
3947 	switch (arcn->arcn_code) {
3948 	case AR_CN_BOGON:
3949 		/*
3950 		 * Someone is sending ARP packets with a source protocol
3951 		 * address that we have published and for which we believe our
3952 		 * entry is authoritative and (when ill_arp_extend is set)
3953 		 * verified to be unique on the network.
3954 		 *
3955 		 * The ARP module internally handles the cases where the sender
3956 		 * is just probing (for DAD) and where the hardware address of
3957 		 * a non-authoritative entry has changed.  Thus, these are the
3958 		 * real conflicts, and we have to do resolution.
3959 		 *
3960 		 * We back away quickly from the address if it's from DHCP or
3961 		 * otherwise temporary and hasn't been used recently (or at
3962 		 * all).  We'd like to include "deprecated" addresses here as
3963 		 * well (as there's no real reason to defend something we're
3964 		 * discarding), but IPMP "reuses" this flag to mean something
3965 		 * other than the standard meaning.
3966 		 *
3967 		 * If the ARP module above is not extended (meaning that it
3968 		 * doesn't know how to defend the address), then we just log
3969 		 * the problem as we always did and continue on.  It's not
3970 		 * right, but there's little else we can do, and those old ATM
3971 		 * users are going away anyway.
3972 		 */
3973 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3974 		    hbuf, sizeof (hbuf));
3975 		(void) ip_dot_addr(src, sbuf);
3976 		if (isv6) {
3977 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3978 			    ipst);
3979 		} else {
3980 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3981 		}
3982 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3983 			uint32_t now;
3984 			uint32_t maxage;
3985 			clock_t lused;
3986 			uint_t maxdefense;
3987 			uint_t defs;
3988 
3989 			/*
3990 			 * First, figure out if this address hasn't been used
3991 			 * in a while.  If it hasn't, then it's a better
3992 			 * candidate for abandoning.
3993 			 */
3994 			ipif = ire->ire_ipif;
3995 			ASSERT(ipif != NULL);
3996 			now = gethrestime_sec();
3997 			maxage = now - ire->ire_create_time;
3998 			if (maxage > ipst->ips_ip_max_temp_idle)
3999 				maxage = ipst->ips_ip_max_temp_idle;
4000 			lused = drv_hztousec(ddi_get_lbolt() -
4001 			    ire->ire_last_used_time) / MICROSEC + 1;
4002 			if (lused >= maxage && (ipif->ipif_flags &
4003 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4004 				maxdefense = ipst->ips_ip_max_temp_defend;
4005 			else
4006 				maxdefense = ipst->ips_ip_max_defend;
4007 
4008 			/*
4009 			 * Now figure out how many times we've defended
4010 			 * ourselves.  Ignore defenses that happened long in
4011 			 * the past.
4012 			 */
4013 			mutex_enter(&ire->ire_lock);
4014 			if ((defs = ire->ire_defense_count) > 0 &&
4015 			    now - ire->ire_defense_time >
4016 			    ipst->ips_ip_defend_interval) {
4017 				ire->ire_defense_count = defs = 0;
4018 			}
4019 			ire->ire_defense_count++;
4020 			ire->ire_defense_time = now;
4021 			mutex_exit(&ire->ire_lock);
4022 			ill_refhold(ill);
4023 			ire_refrele(ire);
4024 
4025 			/*
4026 			 * If we've defended ourselves too many times already,
4027 			 * then give up and tear down the interface(s) using
4028 			 * this address.  Otherwise, defend by sending out a
4029 			 * gratuitous ARP.
4030 			 */
4031 			if (defs >= maxdefense && ill->ill_arp_extend) {
4032 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4033 				    B_FALSE);
4034 			} else {
4035 				cmn_err(CE_WARN,
4036 				    "node %s is using our IP address %s on %s",
4037 				    hbuf, sbuf, ill->ill_name);
4038 				/*
4039 				 * If this is an old (ATM) ARP module, then
4040 				 * don't try to defend the address.  Remain
4041 				 * compatible with the old behavior.  Defend
4042 				 * only with new ARP.
4043 				 */
4044 				if (ill->ill_arp_extend) {
4045 					qwriter_ip(ill, q, mp, ip_arp_defend,
4046 					    NEW_OP, B_FALSE);
4047 				} else {
4048 					ill_refrele(ill);
4049 				}
4050 			}
4051 			return;
4052 		}
4053 		cmn_err(CE_WARN,
4054 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4055 		    hbuf, sbuf, ill->ill_name);
4056 		if (ire != NULL)
4057 			ire_refrele(ire);
4058 		break;
4059 	case AR_CN_ANNOUNCE:
4060 		if (isv6) {
4061 			/*
4062 			 * For XRESOLV interfaces.
4063 			 * Delete the IRE cache entry and NCE for this
4064 			 * v6 address
4065 			 */
4066 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4067 			/*
4068 			 * If v6src is a non-zero, it's a router address
4069 			 * as below. Do the same sort of thing to clean
4070 			 * out off-net IRE_CACHE entries that go through
4071 			 * the router.
4072 			 */
4073 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4074 				ire_walk_v6(ire_delete_cache_gw_v6,
4075 				    (char *)&v6src, ALL_ZONES, ipst);
4076 			}
4077 		} else {
4078 			nce_hw_map_t hwm;
4079 
4080 			/*
4081 			 * ARP gives us a copy of any packet where it thinks
4082 			 * the address has changed, so that we can update our
4083 			 * caches.  We're responsible for caching known answers
4084 			 * in the current design.  We check whether the
4085 			 * hardware address really has changed in all of our
4086 			 * entries that have cached this mapping, and if so, we
4087 			 * blow them away.  This way we will immediately pick
4088 			 * up the rare case of a host changing hardware
4089 			 * address.
4090 			 */
4091 			if (src == 0)
4092 				break;
4093 			hwm.hwm_addr = src;
4094 			hwm.hwm_hwlen = arh->arh_hlen;
4095 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4096 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4097 			ndp_walk_common(ipst->ips_ndp4, NULL,
4098 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4099 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4100 		}
4101 		break;
4102 	case AR_CN_READY:
4103 		/* No external v6 resolver has a contract to use this */
4104 		if (isv6)
4105 			break;
4106 		/* If the link is down, we'll retry this later */
4107 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4108 			break;
4109 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4110 		    NULL, NULL, ipst);
4111 		if (ipif != NULL) {
4112 			/*
4113 			 * If this is a duplicate recovery, then we now need to
4114 			 * go exclusive to bring this thing back up.
4115 			 */
4116 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4117 			    IPIF_DUPLICATE) {
4118 				ipif_refrele(ipif);
4119 				ill_refhold(ill);
4120 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4121 				    B_FALSE);
4122 				return;
4123 			}
4124 			/*
4125 			 * If this is the first notice that this address is
4126 			 * ready, then let the user know now.
4127 			 */
4128 			if ((ipif->ipif_flags & IPIF_UP) &&
4129 			    !ipif->ipif_addr_ready) {
4130 				ipif_mask_reply(ipif);
4131 				ip_rts_ifmsg(ipif);
4132 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4133 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4134 			}
4135 			ipif->ipif_addr_ready = 1;
4136 			ipif_refrele(ipif);
4137 		}
4138 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4139 		if (ire != NULL) {
4140 			ire->ire_defense_count = 0;
4141 			ire_refrele(ire);
4142 		}
4143 		break;
4144 	case AR_CN_FAILED:
4145 		/* No external v6 resolver has a contract to use this */
4146 		if (isv6)
4147 			break;
4148 		ill_refhold(ill);
4149 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4150 		return;
4151 	}
4152 	freemsg(mp);
4153 }
4154 
4155 /*
4156  * Create a mblk suitable for carrying the interface index and/or source link
4157  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4158  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4159  * application.
4160  */
4161 mblk_t *
4162 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4163     ip_stack_t *ipst)
4164 {
4165 	mblk_t		*mp;
4166 	ip_pktinfo_t	*pinfo;
4167 	ipha_t *ipha;
4168 	struct ether_header *pether;
4169 
4170 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4171 	if (mp == NULL) {
4172 		ip1dbg(("ip_add_info: allocation failure.\n"));
4173 		return (data_mp);
4174 	}
4175 
4176 	ipha	= (ipha_t *)data_mp->b_rptr;
4177 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4178 	bzero(pinfo, sizeof (ip_pktinfo_t));
4179 	pinfo->ip_pkt_flags = (uchar_t)flags;
4180 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4181 
4182 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4183 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4184 	if (flags & IPF_RECVADDR) {
4185 		ipif_t	*ipif;
4186 		ire_t	*ire;
4187 
4188 		/*
4189 		 * Only valid for V4
4190 		 */
4191 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4192 		    (IPV4_VERSION << 4));
4193 
4194 		ipif = ipif_get_next_ipif(NULL, ill);
4195 		if (ipif != NULL) {
4196 			/*
4197 			 * Since a decision has already been made to deliver the
4198 			 * packet, there is no need to test for SECATTR and
4199 			 * ZONEONLY.
4200 			 * When a multicast packet is transmitted
4201 			 * a cache entry is created for the multicast address.
4202 			 * When delivering a copy of the packet or when new
4203 			 * packets are received we do not want to match on the
4204 			 * cached entry so explicitly match on
4205 			 * IRE_LOCAL and IRE_LOOPBACK
4206 			 */
4207 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4208 			    IRE_LOCAL | IRE_LOOPBACK,
4209 			    ipif, zoneid, NULL,
4210 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4211 			if (ire == NULL) {
4212 				/*
4213 				 * packet must have come on a different
4214 				 * interface.
4215 				 * Since a decision has already been made to
4216 				 * deliver the packet, there is no need to test
4217 				 * for SECATTR and ZONEONLY.
4218 				 * Only match on local and broadcast ire's.
4219 				 * See detailed comment above.
4220 				 */
4221 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4222 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4223 				    NULL, MATCH_IRE_TYPE, ipst);
4224 			}
4225 
4226 			if (ire == NULL) {
4227 				/*
4228 				 * This is either a multicast packet or
4229 				 * the address has been removed since
4230 				 * the packet was received.
4231 				 * Return INADDR_ANY so that normal source
4232 				 * selection occurs for the response.
4233 				 */
4234 
4235 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4236 			} else {
4237 				pinfo->ip_pkt_match_addr.s_addr =
4238 				    ire->ire_src_addr;
4239 				ire_refrele(ire);
4240 			}
4241 			ipif_refrele(ipif);
4242 		} else {
4243 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4244 		}
4245 	}
4246 
4247 	pether = (struct ether_header *)((char *)ipha
4248 	    - sizeof (struct ether_header));
4249 	/*
4250 	 * Make sure the interface is an ethernet type, since this option
4251 	 * is currently supported only on this type of interface. Also make
4252 	 * sure we are pointing correctly above db_base.
4253 	 */
4254 
4255 	if ((flags & IPF_RECVSLLA) &&
4256 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4257 	    (ill->ill_type == IFT_ETHER) &&
4258 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4259 
4260 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4261 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4262 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4263 	} else {
4264 		/*
4265 		 * Clear the bit. Indicate to upper layer that IP is not
4266 		 * sending this ancillary info.
4267 		 */
4268 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4269 	}
4270 
4271 	mp->b_datap->db_type = M_CTL;
4272 	mp->b_wptr += sizeof (ip_pktinfo_t);
4273 	mp->b_cont = data_mp;
4274 
4275 	return (mp);
4276 }
4277 
4278 /*
4279  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4280  * part of the bind request.
4281  */
4282 
4283 boolean_t
4284 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4285 {
4286 	ipsec_in_t *ii;
4287 
4288 	ASSERT(policy_mp != NULL);
4289 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4290 
4291 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4292 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4293 
4294 	connp->conn_policy = ii->ipsec_in_policy;
4295 	ii->ipsec_in_policy = NULL;
4296 
4297 	if (ii->ipsec_in_action != NULL) {
4298 		if (connp->conn_latch == NULL) {
4299 			connp->conn_latch = iplatch_create();
4300 			if (connp->conn_latch == NULL)
4301 				return (B_FALSE);
4302 		}
4303 		ipsec_latch_inbound(connp->conn_latch, ii);
4304 	}
4305 	return (B_TRUE);
4306 }
4307 
4308 /*
4309  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4310  * and to arrange for power-fanout assist.  The ULP is identified by
4311  * adding a single byte at the end of the original bind message.
4312  * A ULP other than UDP or TCP that wishes to be recognized passes
4313  * down a bind with a zero length address.
4314  *
4315  * The binding works as follows:
4316  * - A zero byte address means just bind to the protocol.
4317  * - A four byte address is treated as a request to validate
4318  *   that the address is a valid local address, appropriate for
4319  *   an application to bind to. This does not affect any fanout
4320  *   information in IP.
4321  * - A sizeof sin_t byte address is used to bind to only the local address
4322  *   and port.
4323  * - A sizeof ipa_conn_t byte address contains complete fanout information
4324  *   consisting of local and remote addresses and ports.  In
4325  *   this case, the addresses are both validated as appropriate
4326  *   for this operation, and, if so, the information is retained
4327  *   for use in the inbound fanout.
4328  *
4329  * The ULP (except in the zero-length bind) can append an
4330  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4331  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4332  * a copy of the source or destination IRE (source for local bind;
4333  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4334  * policy information contained should be copied on to the conn.
4335  *
4336  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4337  */
4338 mblk_t *
4339 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4340 {
4341 	ssize_t		len;
4342 	struct T_bind_req	*tbr;
4343 	sin_t		*sin;
4344 	ipa_conn_t	*ac;
4345 	uchar_t		*ucp;
4346 	mblk_t		*mp1;
4347 	boolean_t	ire_requested;
4348 	boolean_t	ipsec_policy_set = B_FALSE;
4349 	int		error = 0;
4350 	int		protocol;
4351 	ipa_conn_x_t	*acx;
4352 
4353 	ASSERT(!connp->conn_af_isv6);
4354 	connp->conn_pkt_isv6 = B_FALSE;
4355 
4356 	len = MBLKL(mp);
4357 	if (len < (sizeof (*tbr) + 1)) {
4358 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4359 		    "ip_bind: bogus msg, len %ld", len);
4360 		/* XXX: Need to return something better */
4361 		goto bad_addr;
4362 	}
4363 	/* Back up and extract the protocol identifier. */
4364 	mp->b_wptr--;
4365 	protocol = *mp->b_wptr & 0xFF;
4366 	tbr = (struct T_bind_req *)mp->b_rptr;
4367 	/* Reset the message type in preparation for shipping it back. */
4368 	DB_TYPE(mp) = M_PCPROTO;
4369 
4370 	connp->conn_ulp = (uint8_t)protocol;
4371 
4372 	/*
4373 	 * Check for a zero length address.  This is from a protocol that
4374 	 * wants to register to receive all packets of its type.
4375 	 */
4376 	if (tbr->ADDR_length == 0) {
4377 		/*
4378 		 * These protocols are now intercepted in ip_bind_v6().
4379 		 * Reject protocol-level binds here for now.
4380 		 *
4381 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4382 		 * so that the protocol type cannot be SCTP.
4383 		 */
4384 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4385 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4386 			goto bad_addr;
4387 		}
4388 
4389 		/*
4390 		 *
4391 		 * The udp module never sends down a zero-length address,
4392 		 * and allowing this on a labeled system will break MLP
4393 		 * functionality.
4394 		 */
4395 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4396 			goto bad_addr;
4397 
4398 		if (connp->conn_mac_exempt)
4399 			goto bad_addr;
4400 
4401 		/* No hash here really.  The table is big enough. */
4402 		connp->conn_srcv6 = ipv6_all_zeros;
4403 
4404 		ipcl_proto_insert(connp, protocol);
4405 
4406 		tbr->PRIM_type = T_BIND_ACK;
4407 		return (mp);
4408 	}
4409 
4410 	/* Extract the address pointer from the message. */
4411 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4412 	    tbr->ADDR_length);
4413 	if (ucp == NULL) {
4414 		ip1dbg(("ip_bind: no address\n"));
4415 		goto bad_addr;
4416 	}
4417 	if (!OK_32PTR(ucp)) {
4418 		ip1dbg(("ip_bind: unaligned address\n"));
4419 		goto bad_addr;
4420 	}
4421 	/*
4422 	 * Check for trailing mps.
4423 	 */
4424 
4425 	mp1 = mp->b_cont;
4426 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4427 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4428 
4429 	switch (tbr->ADDR_length) {
4430 	default:
4431 		ip1dbg(("ip_bind: bad address length %d\n",
4432 		    (int)tbr->ADDR_length));
4433 		goto bad_addr;
4434 
4435 	case IP_ADDR_LEN:
4436 		/* Verification of local address only */
4437 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4438 		    ire_requested, ipsec_policy_set, B_FALSE);
4439 		break;
4440 
4441 	case sizeof (sin_t):
4442 		sin = (sin_t *)ucp;
4443 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4444 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4445 		break;
4446 
4447 	case sizeof (ipa_conn_t):
4448 		ac = (ipa_conn_t *)ucp;
4449 		/* For raw socket, the local port is not set. */
4450 		if (ac->ac_lport == 0)
4451 			ac->ac_lport = connp->conn_lport;
4452 		/* Always verify destination reachability. */
4453 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4454 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4455 		    ipsec_policy_set, B_TRUE, B_TRUE);
4456 		break;
4457 
4458 	case sizeof (ipa_conn_x_t):
4459 		acx = (ipa_conn_x_t *)ucp;
4460 		/*
4461 		 * Whether or not to verify destination reachability depends
4462 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4463 		 */
4464 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4465 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4466 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4467 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4468 		break;
4469 	}
4470 	if (error == EINPROGRESS)
4471 		return (NULL);
4472 	else if (error != 0)
4473 		goto bad_addr;
4474 	/*
4475 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4476 	 * We can't do this in ip_bind_insert_ire because the policy
4477 	 * may not have been inherited at that point in time and hence
4478 	 * conn_out_enforce_policy may not be set.
4479 	 */
4480 	mp1 = mp->b_cont;
4481 	if (ire_requested && connp->conn_out_enforce_policy &&
4482 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4483 		ire_t *ire = (ire_t *)mp1->b_rptr;
4484 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4485 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4486 	}
4487 
4488 	/* Send it home. */
4489 	mp->b_datap->db_type = M_PCPROTO;
4490 	tbr->PRIM_type = T_BIND_ACK;
4491 	return (mp);
4492 
4493 bad_addr:
4494 	/*
4495 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4496 	 * a unix errno.
4497 	 */
4498 	if (error > 0)
4499 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4500 	else
4501 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4502 	return (mp);
4503 }
4504 
4505 /*
4506  * Here address is verified to be a valid local address.
4507  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4508  * address is also considered a valid local address.
4509  * In the case of a broadcast/multicast address, however, the
4510  * upper protocol is expected to reset the src address
4511  * to 0 if it sees a IRE_BROADCAST type returned so that
4512  * no packets are emitted with broadcast/multicast address as
4513  * source address (that violates hosts requirements RFC1122)
4514  * The addresses valid for bind are:
4515  *	(1) - INADDR_ANY (0)
4516  *	(2) - IP address of an UP interface
4517  *	(3) - IP address of a DOWN interface
4518  *	(4) - valid local IP broadcast addresses. In this case
4519  *	the conn will only receive packets destined to
4520  *	the specified broadcast address.
4521  *	(5) - a multicast address. In this case
4522  *	the conn will only receive packets destined to
4523  *	the specified multicast address. Note: the
4524  *	application still has to issue an
4525  *	IP_ADD_MEMBERSHIP socket option.
4526  *
4527  * On error, return -1 for TBADADDR otherwise pass the
4528  * errno with TSYSERR reply.
4529  *
4530  * In all the above cases, the bound address must be valid in the current zone.
4531  * When the address is loopback, multicast or broadcast, there might be many
4532  * matching IREs so bind has to look up based on the zone.
4533  *
4534  * Note: lport is in network byte order.
4535  */
4536 int
4537 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4538     boolean_t ire_requested, boolean_t ipsec_policy_set,
4539     boolean_t fanout_insert)
4540 {
4541 	int		error = 0;
4542 	ire_t		*src_ire;
4543 	mblk_t		*policy_mp;
4544 	ipif_t		*ipif;
4545 	zoneid_t	zoneid;
4546 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4547 
4548 	if (ipsec_policy_set) {
4549 		policy_mp = mp->b_cont;
4550 	}
4551 
4552 	/*
4553 	 * If it was previously connected, conn_fully_bound would have
4554 	 * been set.
4555 	 */
4556 	connp->conn_fully_bound = B_FALSE;
4557 
4558 	src_ire = NULL;
4559 	ipif = NULL;
4560 
4561 	zoneid = IPCL_ZONEID(connp);
4562 
4563 	if (src_addr) {
4564 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4565 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4566 		/*
4567 		 * If an address other than 0.0.0.0 is requested,
4568 		 * we verify that it is a valid address for bind
4569 		 * Note: Following code is in if-else-if form for
4570 		 * readability compared to a condition check.
4571 		 */
4572 		/* LINTED - statement has no consequent */
4573 		if (IRE_IS_LOCAL(src_ire)) {
4574 			/*
4575 			 * (2) Bind to address of local UP interface
4576 			 */
4577 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4578 			/*
4579 			 * (4) Bind to broadcast address
4580 			 * Note: permitted only from transports that
4581 			 * request IRE
4582 			 */
4583 			if (!ire_requested)
4584 				error = EADDRNOTAVAIL;
4585 		} else {
4586 			/*
4587 			 * (3) Bind to address of local DOWN interface
4588 			 * (ipif_lookup_addr() looks up all interfaces
4589 			 * but we do not get here for UP interfaces
4590 			 * - case (2) above)
4591 			 * We put the protocol byte back into the mblk
4592 			 * since we may come back via ip_wput_nondata()
4593 			 * later with this mblk if ipif_lookup_addr chooses
4594 			 * to defer processing.
4595 			 */
4596 			*mp->b_wptr++ = (char)connp->conn_ulp;
4597 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4598 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4599 			    &error, ipst)) != NULL) {
4600 				ipif_refrele(ipif);
4601 			} else if (error == EINPROGRESS) {
4602 				if (src_ire != NULL)
4603 					ire_refrele(src_ire);
4604 				return (EINPROGRESS);
4605 			} else if (CLASSD(src_addr)) {
4606 				error = 0;
4607 				if (src_ire != NULL)
4608 					ire_refrele(src_ire);
4609 				/*
4610 				 * (5) bind to multicast address.
4611 				 * Fake out the IRE returned to upper
4612 				 * layer to be a broadcast IRE.
4613 				 */
4614 				src_ire = ire_ctable_lookup(
4615 				    INADDR_BROADCAST, INADDR_ANY,
4616 				    IRE_BROADCAST, NULL, zoneid, NULL,
4617 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4618 				    ipst);
4619 				if (src_ire == NULL || !ire_requested)
4620 					error = EADDRNOTAVAIL;
4621 			} else {
4622 				/*
4623 				 * Not a valid address for bind
4624 				 */
4625 				error = EADDRNOTAVAIL;
4626 			}
4627 			/*
4628 			 * Just to keep it consistent with the processing in
4629 			 * ip_bind_v4()
4630 			 */
4631 			mp->b_wptr--;
4632 		}
4633 		if (error) {
4634 			/* Red Alert!  Attempting to be a bogon! */
4635 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4636 			    ntohl(src_addr)));
4637 			goto bad_addr;
4638 		}
4639 	}
4640 
4641 	/*
4642 	 * Allow setting new policies. For example, disconnects come
4643 	 * down as ipa_t bind. As we would have set conn_policy_cached
4644 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4645 	 * can change after the disconnect.
4646 	 */
4647 	connp->conn_policy_cached = B_FALSE;
4648 
4649 	/*
4650 	 * If not fanout_insert this was just an address verification
4651 	 */
4652 	if (fanout_insert) {
4653 		/*
4654 		 * The addresses have been verified. Time to insert in
4655 		 * the correct fanout list.
4656 		 */
4657 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4658 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4659 		connp->conn_lport = lport;
4660 		connp->conn_fport = 0;
4661 		/*
4662 		 * Do we need to add a check to reject Multicast packets
4663 		 *
4664 		 * We need to make sure that the conn_recv is set to a non-null
4665 		 * value before we insert the conn into the classifier table.
4666 		 * This is to avoid a race with an incoming packet which does an
4667 		 * ipcl_classify().
4668 		 */
4669 		if (*mp->b_wptr == IPPROTO_TCP)
4670 			connp->conn_recv = tcp_conn_request;
4671 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4672 	}
4673 
4674 	if (error == 0) {
4675 		if (ire_requested) {
4676 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4677 				error = -1;
4678 				/* Falls through to bad_addr */
4679 			}
4680 		} else if (ipsec_policy_set) {
4681 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4682 				error = -1;
4683 				/* Falls through to bad_addr */
4684 			}
4685 		}
4686 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4687 		connp->conn_recv = tcp_input;
4688 	}
4689 bad_addr:
4690 	if (error != 0) {
4691 		if (connp->conn_anon_port) {
4692 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4693 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4694 			    B_FALSE);
4695 		}
4696 		connp->conn_mlp_type = mlptSingle;
4697 	}
4698 	if (src_ire != NULL)
4699 		IRE_REFRELE(src_ire);
4700 	if (ipsec_policy_set) {
4701 		ASSERT(policy_mp == mp->b_cont);
4702 		ASSERT(policy_mp != NULL);
4703 		freeb(policy_mp);
4704 		/*
4705 		 * As of now assume that nothing else accompanies
4706 		 * IPSEC_POLICY_SET.
4707 		 */
4708 		mp->b_cont = NULL;
4709 	}
4710 	return (error);
4711 }
4712 
4713 /*
4714  * Verify that both the source and destination addresses
4715  * are valid.  If verify_dst is false, then the destination address may be
4716  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4717  * destination reachability, while tunnels do not.
4718  * Note that we allow connect to broadcast and multicast
4719  * addresses when ire_requested is set. Thus the ULP
4720  * has to check for IRE_BROADCAST and multicast.
4721  *
4722  * Returns zero if ok.
4723  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4724  * (for use with TSYSERR reply).
4725  *
4726  * Note: lport and fport are in network byte order.
4727  */
4728 int
4729 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4730     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4731     boolean_t ire_requested, boolean_t ipsec_policy_set,
4732     boolean_t fanout_insert, boolean_t verify_dst)
4733 {
4734 	ire_t		*src_ire;
4735 	ire_t		*dst_ire;
4736 	int		error = 0;
4737 	int 		protocol;
4738 	mblk_t		*policy_mp;
4739 	ire_t		*sire = NULL;
4740 	ire_t		*md_dst_ire = NULL;
4741 	ire_t		*lso_dst_ire = NULL;
4742 	ill_t		*ill = NULL;
4743 	zoneid_t	zoneid;
4744 	ipaddr_t	src_addr = *src_addrp;
4745 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4746 
4747 	src_ire = dst_ire = NULL;
4748 	protocol = *mp->b_wptr & 0xFF;
4749 
4750 	/*
4751 	 * If we never got a disconnect before, clear it now.
4752 	 */
4753 	connp->conn_fully_bound = B_FALSE;
4754 
4755 	if (ipsec_policy_set) {
4756 		policy_mp = mp->b_cont;
4757 	}
4758 
4759 	zoneid = IPCL_ZONEID(connp);
4760 
4761 	if (CLASSD(dst_addr)) {
4762 		/* Pick up an IRE_BROADCAST */
4763 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4764 		    NULL, zoneid, MBLK_GETLABEL(mp),
4765 		    (MATCH_IRE_RECURSIVE |
4766 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4767 		    MATCH_IRE_SECATTR), ipst);
4768 	} else {
4769 		/*
4770 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4771 		 * and onlink ipif is not found set ENETUNREACH error.
4772 		 */
4773 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4774 			ipif_t *ipif;
4775 
4776 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4777 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4778 			if (ipif == NULL) {
4779 				error = ENETUNREACH;
4780 				goto bad_addr;
4781 			}
4782 			ipif_refrele(ipif);
4783 		}
4784 
4785 		if (connp->conn_nexthop_set) {
4786 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4787 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4788 			    MATCH_IRE_SECATTR, ipst);
4789 		} else {
4790 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4791 			    &sire, zoneid, MBLK_GETLABEL(mp),
4792 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4793 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4794 			    MATCH_IRE_SECATTR), ipst);
4795 		}
4796 	}
4797 	/*
4798 	 * dst_ire can't be a broadcast when not ire_requested.
4799 	 * We also prevent ire's with src address INADDR_ANY to
4800 	 * be used, which are created temporarily for
4801 	 * sending out packets from endpoints that have
4802 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4803 	 * reachable.  If verify_dst is false, the destination needn't be
4804 	 * reachable.
4805 	 *
4806 	 * If we match on a reject or black hole, then we've got a
4807 	 * local failure.  May as well fail out the connect() attempt,
4808 	 * since it's never going to succeed.
4809 	 */
4810 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4811 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4812 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4813 		/*
4814 		 * If we're verifying destination reachability, we always want
4815 		 * to complain here.
4816 		 *
4817 		 * If we're not verifying destination reachability but the
4818 		 * destination has a route, we still want to fail on the
4819 		 * temporary address and broadcast address tests.
4820 		 */
4821 		if (verify_dst || (dst_ire != NULL)) {
4822 			if (ip_debug > 2) {
4823 				pr_addr_dbg("ip_bind_connected: bad connected "
4824 				    "dst %s\n", AF_INET, &dst_addr);
4825 			}
4826 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4827 				error = ENETUNREACH;
4828 			else
4829 				error = EHOSTUNREACH;
4830 			goto bad_addr;
4831 		}
4832 	}
4833 
4834 	/*
4835 	 * We now know that routing will allow us to reach the destination.
4836 	 * Check whether Trusted Solaris policy allows communication with this
4837 	 * host, and pretend that the destination is unreachable if not.
4838 	 *
4839 	 * This is never a problem for TCP, since that transport is known to
4840 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4841 	 * handling.  If the remote is unreachable, it will be detected at that
4842 	 * point, so there's no reason to check it here.
4843 	 *
4844 	 * Note that for sendto (and other datagram-oriented friends), this
4845 	 * check is done as part of the data path label computation instead.
4846 	 * The check here is just to make non-TCP connect() report the right
4847 	 * error.
4848 	 */
4849 	if (dst_ire != NULL && is_system_labeled() &&
4850 	    !IPCL_IS_TCP(connp) &&
4851 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4852 	    connp->conn_mac_exempt, ipst) != 0) {
4853 		error = EHOSTUNREACH;
4854 		if (ip_debug > 2) {
4855 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4856 			    AF_INET, &dst_addr);
4857 		}
4858 		goto bad_addr;
4859 	}
4860 
4861 	/*
4862 	 * If the app does a connect(), it means that it will most likely
4863 	 * send more than 1 packet to the destination.  It makes sense
4864 	 * to clear the temporary flag.
4865 	 */
4866 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4867 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4868 		irb_t *irb = dst_ire->ire_bucket;
4869 
4870 		rw_enter(&irb->irb_lock, RW_WRITER);
4871 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4872 		irb->irb_tmp_ire_cnt--;
4873 		rw_exit(&irb->irb_lock);
4874 	}
4875 
4876 	/*
4877 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4878 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4879 	 * eligibility tests for passive connects are handled separately
4880 	 * through tcp_adapt_ire().  We do this before the source address
4881 	 * selection, because dst_ire may change after a call to
4882 	 * ipif_select_source().  This is a best-effort check, as the
4883 	 * packet for this connection may not actually go through
4884 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4885 	 * calling ip_newroute().  This is why we further check on the
4886 	 * IRE during LSO/Multidata packet transmission in
4887 	 * tcp_lsosend()/tcp_multisend().
4888 	 */
4889 	if (!ipsec_policy_set && dst_ire != NULL &&
4890 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4891 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4892 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4893 			lso_dst_ire = dst_ire;
4894 			IRE_REFHOLD(lso_dst_ire);
4895 		} else if (ipst->ips_ip_multidata_outbound &&
4896 		    ILL_MDT_CAPABLE(ill)) {
4897 			md_dst_ire = dst_ire;
4898 			IRE_REFHOLD(md_dst_ire);
4899 		}
4900 	}
4901 
4902 	if (dst_ire != NULL &&
4903 	    dst_ire->ire_type == IRE_LOCAL &&
4904 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4905 		/*
4906 		 * If the IRE belongs to a different zone, look for a matching
4907 		 * route in the forwarding table and use the source address from
4908 		 * that route.
4909 		 */
4910 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4911 		    zoneid, 0, NULL,
4912 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4913 		    MATCH_IRE_RJ_BHOLE, ipst);
4914 		if (src_ire == NULL) {
4915 			error = EHOSTUNREACH;
4916 			goto bad_addr;
4917 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4918 			if (!(src_ire->ire_type & IRE_HOST))
4919 				error = ENETUNREACH;
4920 			else
4921 				error = EHOSTUNREACH;
4922 			goto bad_addr;
4923 		}
4924 		if (src_addr == INADDR_ANY)
4925 			src_addr = src_ire->ire_src_addr;
4926 		ire_refrele(src_ire);
4927 		src_ire = NULL;
4928 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4929 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4930 			src_addr = sire->ire_src_addr;
4931 			ire_refrele(dst_ire);
4932 			dst_ire = sire;
4933 			sire = NULL;
4934 		} else {
4935 			/*
4936 			 * Pick a source address so that a proper inbound
4937 			 * load spreading would happen.
4938 			 */
4939 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4940 			ipif_t *src_ipif = NULL;
4941 			ire_t *ipif_ire;
4942 
4943 			/*
4944 			 * Supply a local source address such that inbound
4945 			 * load spreading happens.
4946 			 *
4947 			 * Determine the best source address on this ill for
4948 			 * the destination.
4949 			 *
4950 			 * 1) For broadcast, we should return a broadcast ire
4951 			 *    found above so that upper layers know that the
4952 			 *    destination address is a broadcast address.
4953 			 *
4954 			 * 2) If this is part of a group, select a better
4955 			 *    source address so that better inbound load
4956 			 *    balancing happens. Do the same if the ipif
4957 			 *    is DEPRECATED.
4958 			 *
4959 			 * 3) If the outgoing interface is part of a usesrc
4960 			 *    group, then try selecting a source address from
4961 			 *    the usesrc ILL.
4962 			 */
4963 			if ((dst_ire->ire_zoneid != zoneid &&
4964 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4965 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4966 			    ((dst_ill->ill_group != NULL) ||
4967 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4968 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4969 				/*
4970 				 * If the destination is reachable via a
4971 				 * given gateway, the selected source address
4972 				 * should be in the same subnet as the gateway.
4973 				 * Otherwise, the destination is not reachable.
4974 				 *
4975 				 * If there are no interfaces on the same subnet
4976 				 * as the destination, ipif_select_source gives
4977 				 * first non-deprecated interface which might be
4978 				 * on a different subnet than the gateway.
4979 				 * This is not desirable. Hence pass the dst_ire
4980 				 * source address to ipif_select_source.
4981 				 * It is sure that the destination is reachable
4982 				 * with the dst_ire source address subnet.
4983 				 * So passing dst_ire source address to
4984 				 * ipif_select_source will make sure that the
4985 				 * selected source will be on the same subnet
4986 				 * as dst_ire source address.
4987 				 */
4988 				ipaddr_t saddr =
4989 				    dst_ire->ire_ipif->ipif_src_addr;
4990 				src_ipif = ipif_select_source(dst_ill,
4991 				    saddr, zoneid);
4992 				if (src_ipif != NULL) {
4993 					if (IS_VNI(src_ipif->ipif_ill)) {
4994 						/*
4995 						 * For VNI there is no
4996 						 * interface route
4997 						 */
4998 						src_addr =
4999 						    src_ipif->ipif_src_addr;
5000 					} else {
5001 						ipif_ire =
5002 						    ipif_to_ire(src_ipif);
5003 						if (ipif_ire != NULL) {
5004 							IRE_REFRELE(dst_ire);
5005 							dst_ire = ipif_ire;
5006 						}
5007 						src_addr =
5008 						    dst_ire->ire_src_addr;
5009 					}
5010 					ipif_refrele(src_ipif);
5011 				} else {
5012 					src_addr = dst_ire->ire_src_addr;
5013 				}
5014 			} else {
5015 				src_addr = dst_ire->ire_src_addr;
5016 			}
5017 		}
5018 	}
5019 
5020 	/*
5021 	 * We do ire_route_lookup() here (and not
5022 	 * interface lookup as we assert that
5023 	 * src_addr should only come from an
5024 	 * UP interface for hard binding.
5025 	 */
5026 	ASSERT(src_ire == NULL);
5027 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5028 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5029 	/* src_ire must be a local|loopback */
5030 	if (!IRE_IS_LOCAL(src_ire)) {
5031 		if (ip_debug > 2) {
5032 			pr_addr_dbg("ip_bind_connected: bad connected "
5033 			    "src %s\n", AF_INET, &src_addr);
5034 		}
5035 		error = EADDRNOTAVAIL;
5036 		goto bad_addr;
5037 	}
5038 
5039 	/*
5040 	 * If the source address is a loopback address, the
5041 	 * destination had best be local or multicast.
5042 	 * The transports that can't handle multicast will reject
5043 	 * those addresses.
5044 	 */
5045 	if (src_ire->ire_type == IRE_LOOPBACK &&
5046 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5047 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5048 		error = -1;
5049 		goto bad_addr;
5050 	}
5051 
5052 	/*
5053 	 * Allow setting new policies. For example, disconnects come
5054 	 * down as ipa_t bind. As we would have set conn_policy_cached
5055 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5056 	 * can change after the disconnect.
5057 	 */
5058 	connp->conn_policy_cached = B_FALSE;
5059 
5060 	/*
5061 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5062 	 * can handle their passed-in conn's.
5063 	 */
5064 
5065 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5066 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5067 	connp->conn_lport = lport;
5068 	connp->conn_fport = fport;
5069 	*src_addrp = src_addr;
5070 
5071 	ASSERT(!(ipsec_policy_set && ire_requested));
5072 	if (ire_requested) {
5073 		iulp_t *ulp_info = NULL;
5074 
5075 		/*
5076 		 * Note that sire will not be NULL if this is an off-link
5077 		 * connection and there is not cache for that dest yet.
5078 		 *
5079 		 * XXX Because of an existing bug, if there are multiple
5080 		 * default routes, the IRE returned now may not be the actual
5081 		 * default route used (default routes are chosen in a
5082 		 * round robin fashion).  So if the metrics for different
5083 		 * default routes are different, we may return the wrong
5084 		 * metrics.  This will not be a problem if the existing
5085 		 * bug is fixed.
5086 		 */
5087 		if (sire != NULL) {
5088 			ulp_info = &(sire->ire_uinfo);
5089 		}
5090 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5091 			error = -1;
5092 			goto bad_addr;
5093 		}
5094 	} else if (ipsec_policy_set) {
5095 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5096 			error = -1;
5097 			goto bad_addr;
5098 		}
5099 	}
5100 
5101 	/*
5102 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5103 	 * we'll cache that.  If we don't, we'll inherit global policy.
5104 	 *
5105 	 * We can't insert until the conn reflects the policy. Note that
5106 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5107 	 * connections where we don't have a policy. This is to prevent
5108 	 * global policy lookups in the inbound path.
5109 	 *
5110 	 * If we insert before we set conn_policy_cached,
5111 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5112 	 * because global policy cound be non-empty. We normally call
5113 	 * ipsec_check_policy() for conn_policy_cached connections only if
5114 	 * ipc_in_enforce_policy is set. But in this case,
5115 	 * conn_policy_cached can get set anytime since we made the
5116 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5117 	 * called, which will make the above assumption false.  Thus, we
5118 	 * need to insert after we set conn_policy_cached.
5119 	 */
5120 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5121 		goto bad_addr;
5122 
5123 	if (fanout_insert) {
5124 		/*
5125 		 * The addresses have been verified. Time to insert in
5126 		 * the correct fanout list.
5127 		 * We need to make sure that the conn_recv is set to a non-null
5128 		 * value before we insert into the classifier table to avoid a
5129 		 * race with an incoming packet which does an ipcl_classify().
5130 		 */
5131 		if (protocol == IPPROTO_TCP)
5132 			connp->conn_recv = tcp_input;
5133 		error = ipcl_conn_insert(connp, protocol, src_addr,
5134 		    dst_addr, connp->conn_ports);
5135 	}
5136 
5137 	if (error == 0) {
5138 		connp->conn_fully_bound = B_TRUE;
5139 		/*
5140 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5141 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5142 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5143 		 * ip_xxinfo_return(), which performs further checks
5144 		 * against them and upon success, returns the LSO/MDT info
5145 		 * mblk which we will attach to the bind acknowledgment.
5146 		 */
5147 		if (lso_dst_ire != NULL) {
5148 			mblk_t *lsoinfo_mp;
5149 
5150 			ASSERT(ill->ill_lso_capab != NULL);
5151 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5152 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5153 				linkb(mp, lsoinfo_mp);
5154 		} else if (md_dst_ire != NULL) {
5155 			mblk_t *mdinfo_mp;
5156 
5157 			ASSERT(ill->ill_mdt_capab != NULL);
5158 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5159 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5160 				linkb(mp, mdinfo_mp);
5161 		}
5162 	}
5163 bad_addr:
5164 	if (ipsec_policy_set) {
5165 		ASSERT(policy_mp == mp->b_cont);
5166 		ASSERT(policy_mp != NULL);
5167 		freeb(policy_mp);
5168 		/*
5169 		 * As of now assume that nothing else accompanies
5170 		 * IPSEC_POLICY_SET.
5171 		 */
5172 		mp->b_cont = NULL;
5173 	}
5174 	if (src_ire != NULL)
5175 		IRE_REFRELE(src_ire);
5176 	if (dst_ire != NULL)
5177 		IRE_REFRELE(dst_ire);
5178 	if (sire != NULL)
5179 		IRE_REFRELE(sire);
5180 	if (md_dst_ire != NULL)
5181 		IRE_REFRELE(md_dst_ire);
5182 	if (lso_dst_ire != NULL)
5183 		IRE_REFRELE(lso_dst_ire);
5184 	return (error);
5185 }
5186 
5187 /*
5188  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5189  * Prefers dst_ire over src_ire.
5190  */
5191 static boolean_t
5192 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5193 {
5194 	mblk_t	*mp1;
5195 	ire_t *ret_ire = NULL;
5196 
5197 	mp1 = mp->b_cont;
5198 	ASSERT(mp1 != NULL);
5199 
5200 	if (ire != NULL) {
5201 		/*
5202 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5203 		 * appended mblk. Its <upper protocol>'s
5204 		 * job to make sure there is room.
5205 		 */
5206 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5207 			return (0);
5208 
5209 		mp1->b_datap->db_type = IRE_DB_TYPE;
5210 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5211 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5212 		ret_ire = (ire_t *)mp1->b_rptr;
5213 		/*
5214 		 * Pass the latest setting of the ip_path_mtu_discovery and
5215 		 * copy the ulp info if any.
5216 		 */
5217 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5218 		    IPH_DF : 0;
5219 		if (ulp_info != NULL) {
5220 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5221 			    sizeof (iulp_t));
5222 		}
5223 		ret_ire->ire_mp = mp1;
5224 	} else {
5225 		/*
5226 		 * No IRE was found. Remove IRE mblk.
5227 		 */
5228 		mp->b_cont = mp1->b_cont;
5229 		freeb(mp1);
5230 	}
5231 
5232 	return (1);
5233 }
5234 
5235 /*
5236  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5237  * the final piece where we don't.  Return a pointer to the first mblk in the
5238  * result, and update the pointer to the next mblk to chew on.  If anything
5239  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5240  * NULL pointer.
5241  */
5242 mblk_t *
5243 ip_carve_mp(mblk_t **mpp, ssize_t len)
5244 {
5245 	mblk_t	*mp0;
5246 	mblk_t	*mp1;
5247 	mblk_t	*mp2;
5248 
5249 	if (!len || !mpp || !(mp0 = *mpp))
5250 		return (NULL);
5251 	/* If we aren't going to consume the first mblk, we need a dup. */
5252 	if (mp0->b_wptr - mp0->b_rptr > len) {
5253 		mp1 = dupb(mp0);
5254 		if (mp1) {
5255 			/* Partition the data between the two mblks. */
5256 			mp1->b_wptr = mp1->b_rptr + len;
5257 			mp0->b_rptr = mp1->b_wptr;
5258 			/*
5259 			 * after adjustments if mblk not consumed is now
5260 			 * unaligned, try to align it. If this fails free
5261 			 * all messages and let upper layer recover.
5262 			 */
5263 			if (!OK_32PTR(mp0->b_rptr)) {
5264 				if (!pullupmsg(mp0, -1)) {
5265 					freemsg(mp0);
5266 					freemsg(mp1);
5267 					*mpp = NULL;
5268 					return (NULL);
5269 				}
5270 			}
5271 		}
5272 		return (mp1);
5273 	}
5274 	/* Eat through as many mblks as we need to get len bytes. */
5275 	len -= mp0->b_wptr - mp0->b_rptr;
5276 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5277 		if (mp2->b_wptr - mp2->b_rptr > len) {
5278 			/*
5279 			 * We won't consume the entire last mblk.  Like
5280 			 * above, dup and partition it.
5281 			 */
5282 			mp1->b_cont = dupb(mp2);
5283 			mp1 = mp1->b_cont;
5284 			if (!mp1) {
5285 				/*
5286 				 * Trouble.  Rather than go to a lot of
5287 				 * trouble to clean up, we free the messages.
5288 				 * This won't be any worse than losing it on
5289 				 * the wire.
5290 				 */
5291 				freemsg(mp0);
5292 				freemsg(mp2);
5293 				*mpp = NULL;
5294 				return (NULL);
5295 			}
5296 			mp1->b_wptr = mp1->b_rptr + len;
5297 			mp2->b_rptr = mp1->b_wptr;
5298 			/*
5299 			 * after adjustments if mblk not consumed is now
5300 			 * unaligned, try to align it. If this fails free
5301 			 * all messages and let upper layer recover.
5302 			 */
5303 			if (!OK_32PTR(mp2->b_rptr)) {
5304 				if (!pullupmsg(mp2, -1)) {
5305 					freemsg(mp0);
5306 					freemsg(mp2);
5307 					*mpp = NULL;
5308 					return (NULL);
5309 				}
5310 			}
5311 			*mpp = mp2;
5312 			return (mp0);
5313 		}
5314 		/* Decrement len by the amount we just got. */
5315 		len -= mp2->b_wptr - mp2->b_rptr;
5316 	}
5317 	/*
5318 	 * len should be reduced to zero now.  If not our caller has
5319 	 * screwed up.
5320 	 */
5321 	if (len) {
5322 		/* Shouldn't happen! */
5323 		freemsg(mp0);
5324 		*mpp = NULL;
5325 		return (NULL);
5326 	}
5327 	/*
5328 	 * We consumed up to exactly the end of an mblk.  Detach the part
5329 	 * we are returning from the rest of the chain.
5330 	 */
5331 	mp1->b_cont = NULL;
5332 	*mpp = mp2;
5333 	return (mp0);
5334 }
5335 
5336 /* The ill stream is being unplumbed. Called from ip_close */
5337 int
5338 ip_modclose(ill_t *ill)
5339 {
5340 	boolean_t success;
5341 	ipsq_t	*ipsq;
5342 	ipif_t	*ipif;
5343 	queue_t	*q = ill->ill_rq;
5344 	ip_stack_t	*ipst = ill->ill_ipst;
5345 	clock_t timeout;
5346 
5347 	/*
5348 	 * Wait for the ACKs of all deferred control messages to be processed.
5349 	 * In particular, we wait for a potential capability reset initiated
5350 	 * in ip_sioctl_plink() to complete before proceeding.
5351 	 *
5352 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5353 	 * in case the driver never replies.
5354 	 */
5355 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5356 	mutex_enter(&ill->ill_lock);
5357 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5358 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5359 			/* Timeout */
5360 			break;
5361 		}
5362 	}
5363 	mutex_exit(&ill->ill_lock);
5364 
5365 	/*
5366 	 * Forcibly enter the ipsq after some delay. This is to take
5367 	 * care of the case when some ioctl does not complete because
5368 	 * we sent a control message to the driver and it did not
5369 	 * send us a reply. We want to be able to at least unplumb
5370 	 * and replumb rather than force the user to reboot the system.
5371 	 */
5372 	success = ipsq_enter(ill, B_FALSE);
5373 
5374 	/*
5375 	 * Open/close/push/pop is guaranteed to be single threaded
5376 	 * per stream by STREAMS. FS guarantees that all references
5377 	 * from top are gone before close is called. So there can't
5378 	 * be another close thread that has set CONDEMNED on this ill.
5379 	 * and cause ipsq_enter to return failure.
5380 	 */
5381 	ASSERT(success);
5382 	ipsq = ill->ill_phyint->phyint_ipsq;
5383 
5384 	/*
5385 	 * Mark it condemned. No new reference will be made to this ill.
5386 	 * Lookup functions will return an error. Threads that try to
5387 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5388 	 * that the refcnt will drop down to zero.
5389 	 */
5390 	mutex_enter(&ill->ill_lock);
5391 	ill->ill_state_flags |= ILL_CONDEMNED;
5392 	for (ipif = ill->ill_ipif; ipif != NULL;
5393 	    ipif = ipif->ipif_next) {
5394 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5395 	}
5396 	/*
5397 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5398 	 * returns  error if ILL_CONDEMNED is set
5399 	 */
5400 	cv_broadcast(&ill->ill_cv);
5401 	mutex_exit(&ill->ill_lock);
5402 
5403 	/*
5404 	 * Send all the deferred DLPI messages downstream which came in
5405 	 * during the small window right before ipsq_enter(). We do this
5406 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5407 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5408 	 */
5409 	ill_dlpi_send_deferred(ill);
5410 
5411 	/*
5412 	 * Shut down fragmentation reassembly.
5413 	 * ill_frag_timer won't start a timer again.
5414 	 * Now cancel any existing timer
5415 	 */
5416 	(void) untimeout(ill->ill_frag_timer_id);
5417 	(void) ill_frag_timeout(ill, 0);
5418 
5419 	/*
5420 	 * If MOVE was in progress, clear the
5421 	 * move_in_progress fields also.
5422 	 */
5423 	if (ill->ill_move_in_progress) {
5424 		ILL_CLEAR_MOVE(ill);
5425 	}
5426 
5427 	/*
5428 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5429 	 * this ill. Then wait for the refcnts to drop to zero.
5430 	 * ill_is_quiescent checks whether the ill is really quiescent.
5431 	 * Then make sure that threads that are waiting to enter the
5432 	 * ipsq have seen the error returned by ipsq_enter and have
5433 	 * gone away. Then we call ill_delete_tail which does the
5434 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5435 	 */
5436 	ill_delete(ill);
5437 	mutex_enter(&ill->ill_lock);
5438 	while (!ill_is_quiescent(ill))
5439 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5440 	while (ill->ill_waiters)
5441 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5442 
5443 	mutex_exit(&ill->ill_lock);
5444 
5445 	/*
5446 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5447 	 * it held until the end of the function since the cleanup
5448 	 * below needs to be able to use the ip_stack_t.
5449 	 */
5450 	netstack_hold(ipst->ips_netstack);
5451 
5452 	/* qprocsoff is called in ill_delete_tail */
5453 	ill_delete_tail(ill);
5454 	ASSERT(ill->ill_ipst == NULL);
5455 
5456 	/*
5457 	 * Walk through all upper (conn) streams and qenable
5458 	 * those that have queued data.
5459 	 * close synchronization needs this to
5460 	 * be done to ensure that all upper layers blocked
5461 	 * due to flow control to the closing device
5462 	 * get unblocked.
5463 	 */
5464 	ip1dbg(("ip_wsrv: walking\n"));
5465 	conn_walk_drain(ipst);
5466 
5467 	mutex_enter(&ipst->ips_ip_mi_lock);
5468 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5469 	mutex_exit(&ipst->ips_ip_mi_lock);
5470 
5471 	/*
5472 	 * credp could be null if the open didn't succeed and ip_modopen
5473 	 * itself calls ip_close.
5474 	 */
5475 	if (ill->ill_credp != NULL)
5476 		crfree(ill->ill_credp);
5477 
5478 	mutex_enter(&ill->ill_lock);
5479 	ill_nic_info_dispatch(ill);
5480 	mutex_exit(&ill->ill_lock);
5481 
5482 	/*
5483 	 * Now we are done with the module close pieces that
5484 	 * need the netstack_t.
5485 	 */
5486 	netstack_rele(ipst->ips_netstack);
5487 
5488 	mi_close_free((IDP)ill);
5489 	q->q_ptr = WR(q)->q_ptr = NULL;
5490 
5491 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5492 
5493 	return (0);
5494 }
5495 
5496 /*
5497  * This is called as part of close() for both IP and UDP
5498  * in order to quiesce the conn.
5499  */
5500 void
5501 ip_quiesce_conn(conn_t *connp)
5502 {
5503 	boolean_t	drain_cleanup_reqd = B_FALSE;
5504 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5505 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5506 	ip_stack_t	*ipst;
5507 
5508 	ASSERT(!IPCL_IS_TCP(connp));
5509 	ipst = connp->conn_netstack->netstack_ip;
5510 
5511 	/*
5512 	 * Mark the conn as closing, and this conn must not be
5513 	 * inserted in future into any list. Eg. conn_drain_insert(),
5514 	 * won't insert this conn into the conn_drain_list.
5515 	 * Similarly ill_pending_mp_add() will not add any mp to
5516 	 * the pending mp list, after this conn has started closing.
5517 	 *
5518 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5519 	 * cannot get set henceforth.
5520 	 */
5521 	mutex_enter(&connp->conn_lock);
5522 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5523 	connp->conn_state_flags |= CONN_CLOSING;
5524 	if (connp->conn_idl != NULL)
5525 		drain_cleanup_reqd = B_TRUE;
5526 	if (connp->conn_oper_pending_ill != NULL)
5527 		conn_ioctl_cleanup_reqd = B_TRUE;
5528 	if (connp->conn_ilg_inuse != 0)
5529 		ilg_cleanup_reqd = B_TRUE;
5530 	mutex_exit(&connp->conn_lock);
5531 
5532 	if (IPCL_IS_UDP(connp))
5533 		udp_quiesce_conn(connp);
5534 
5535 	if (conn_ioctl_cleanup_reqd)
5536 		conn_ioctl_cleanup(connp);
5537 
5538 	if (is_system_labeled() && connp->conn_anon_port) {
5539 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5540 		    connp->conn_mlp_type, connp->conn_ulp,
5541 		    ntohs(connp->conn_lport), B_FALSE);
5542 		connp->conn_anon_port = 0;
5543 	}
5544 	connp->conn_mlp_type = mlptSingle;
5545 
5546 	/*
5547 	 * Remove this conn from any fanout list it is on.
5548 	 * and then wait for any threads currently operating
5549 	 * on this endpoint to finish
5550 	 */
5551 	ipcl_hash_remove(connp);
5552 
5553 	/*
5554 	 * Remove this conn from the drain list, and do
5555 	 * any other cleanup that may be required.
5556 	 * (Only non-tcp streams may have a non-null conn_idl.
5557 	 * TCP streams are never flow controlled, and
5558 	 * conn_idl will be null)
5559 	 */
5560 	if (drain_cleanup_reqd)
5561 		conn_drain_tail(connp, B_TRUE);
5562 
5563 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5564 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5565 		(void) ip_mrouter_done(NULL, ipst);
5566 
5567 	if (ilg_cleanup_reqd)
5568 		ilg_delete_all(connp);
5569 
5570 	conn_delete_ire(connp, NULL);
5571 
5572 	/*
5573 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5574 	 * callers from write side can't be there now because close
5575 	 * is in progress. The only other caller is ipcl_walk
5576 	 * which checks for the condemned flag.
5577 	 */
5578 	mutex_enter(&connp->conn_lock);
5579 	connp->conn_state_flags |= CONN_CONDEMNED;
5580 	while (connp->conn_ref != 1)
5581 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5582 	connp->conn_state_flags |= CONN_QUIESCED;
5583 	mutex_exit(&connp->conn_lock);
5584 }
5585 
5586 /* ARGSUSED */
5587 int
5588 ip_close(queue_t *q, int flags)
5589 {
5590 	conn_t		*connp;
5591 
5592 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5593 
5594 	/*
5595 	 * Call the appropriate delete routine depending on whether this is
5596 	 * a module or device.
5597 	 */
5598 	if (WR(q)->q_next != NULL) {
5599 		/* This is a module close */
5600 		return (ip_modclose((ill_t *)q->q_ptr));
5601 	}
5602 
5603 	connp = q->q_ptr;
5604 	ip_quiesce_conn(connp);
5605 
5606 	qprocsoff(q);
5607 
5608 	/*
5609 	 * Now we are truly single threaded on this stream, and can
5610 	 * delete the things hanging off the connp, and finally the connp.
5611 	 * We removed this connp from the fanout list, it cannot be
5612 	 * accessed thru the fanouts, and we already waited for the
5613 	 * conn_ref to drop to 0. We are already in close, so
5614 	 * there cannot be any other thread from the top. qprocsoff
5615 	 * has completed, and service has completed or won't run in
5616 	 * future.
5617 	 */
5618 	ASSERT(connp->conn_ref == 1);
5619 
5620 	/*
5621 	 * A conn which was previously marked as IPCL_UDP cannot
5622 	 * retain the flag because it would have been cleared by
5623 	 * udp_close().
5624 	 */
5625 	ASSERT(!IPCL_IS_UDP(connp));
5626 
5627 	if (connp->conn_latch != NULL) {
5628 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5629 		connp->conn_latch = NULL;
5630 	}
5631 	if (connp->conn_policy != NULL) {
5632 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5633 		connp->conn_policy = NULL;
5634 	}
5635 	if (connp->conn_ipsec_opt_mp != NULL) {
5636 		freemsg(connp->conn_ipsec_opt_mp);
5637 		connp->conn_ipsec_opt_mp = NULL;
5638 	}
5639 
5640 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5641 
5642 	connp->conn_ref--;
5643 	ipcl_conn_destroy(connp);
5644 
5645 	q->q_ptr = WR(q)->q_ptr = NULL;
5646 	return (0);
5647 }
5648 
5649 int
5650 ip_snmpmod_close(queue_t *q)
5651 {
5652 	conn_t *connp = Q_TO_CONN(q);
5653 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5654 
5655 	qprocsoff(q);
5656 
5657 	if (connp->conn_flags & IPCL_UDPMOD)
5658 		udp_close_free(connp);
5659 
5660 	if (connp->conn_cred != NULL) {
5661 		crfree(connp->conn_cred);
5662 		connp->conn_cred = NULL;
5663 	}
5664 	CONN_DEC_REF(connp);
5665 	q->q_ptr = WR(q)->q_ptr = NULL;
5666 	return (0);
5667 }
5668 
5669 /*
5670  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5671  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5672  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5673  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5674  * queues as we never enqueue messages there and we don't handle any ioctls.
5675  * Everything else is freed.
5676  */
5677 void
5678 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5679 {
5680 	conn_t	*connp = q->q_ptr;
5681 	pfi_t	setfn;
5682 	pfi_t	getfn;
5683 
5684 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5685 
5686 	switch (DB_TYPE(mp)) {
5687 	case M_PROTO:
5688 	case M_PCPROTO:
5689 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5690 		    ((((union T_primitives *)mp->b_rptr)->type ==
5691 		    T_SVR4_OPTMGMT_REQ) ||
5692 		    (((union T_primitives *)mp->b_rptr)->type ==
5693 		    T_OPTMGMT_REQ))) {
5694 			/*
5695 			 * This is the only TPI primitive supported. Its
5696 			 * handling does not require tcp_t, but it does require
5697 			 * conn_t to check permissions.
5698 			 */
5699 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5700 
5701 			if (connp->conn_flags & IPCL_TCPMOD) {
5702 				setfn = tcp_snmp_set;
5703 				getfn = tcp_snmp_get;
5704 			} else {
5705 				setfn = udp_snmp_set;
5706 				getfn = udp_snmp_get;
5707 			}
5708 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5709 				freemsg(mp);
5710 				return;
5711 			}
5712 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5713 		    != NULL)
5714 			qreply(q, mp);
5715 		break;
5716 	case M_FLUSH:
5717 	case M_IOCTL:
5718 		putnext(q, mp);
5719 		break;
5720 	default:
5721 		freemsg(mp);
5722 		break;
5723 	}
5724 }
5725 
5726 /* Return the IP checksum for the IP header at "iph". */
5727 uint16_t
5728 ip_csum_hdr(ipha_t *ipha)
5729 {
5730 	uint16_t	*uph;
5731 	uint32_t	sum;
5732 	int		opt_len;
5733 
5734 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5735 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5736 	uph = (uint16_t *)ipha;
5737 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5738 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5739 	if (opt_len > 0) {
5740 		do {
5741 			sum += uph[10];
5742 			sum += uph[11];
5743 			uph += 2;
5744 		} while (--opt_len);
5745 	}
5746 	sum = (sum & 0xFFFF) + (sum >> 16);
5747 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5748 	if (sum == 0xffff)
5749 		sum = 0;
5750 	return ((uint16_t)sum);
5751 }
5752 
5753 /*
5754  * Called when the module is about to be unloaded
5755  */
5756 void
5757 ip_ddi_destroy(void)
5758 {
5759 	tnet_fini();
5760 
5761 	sctp_ddi_g_destroy();
5762 	tcp_ddi_g_destroy();
5763 	ipsec_policy_g_destroy();
5764 	ipcl_g_destroy();
5765 	ip_net_g_destroy();
5766 	ip_ire_g_fini();
5767 	inet_minor_destroy(ip_minor_arena);
5768 
5769 #ifdef DEBUG
5770 	list_destroy(&ip_thread_list);
5771 	rw_destroy(&ip_thread_rwlock);
5772 	tsd_destroy(&ip_thread_data);
5773 #endif
5774 
5775 	netstack_unregister(NS_IP);
5776 }
5777 
5778 /*
5779  * First step in cleanup.
5780  */
5781 /* ARGSUSED */
5782 static void
5783 ip_stack_shutdown(netstackid_t stackid, void *arg)
5784 {
5785 	ip_stack_t *ipst = (ip_stack_t *)arg;
5786 
5787 #ifdef NS_DEBUG
5788 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5789 #endif
5790 
5791 	/* Get rid of loopback interfaces and their IREs */
5792 	ip_loopback_cleanup(ipst);
5793 }
5794 
5795 /*
5796  * Free the IP stack instance.
5797  */
5798 static void
5799 ip_stack_fini(netstackid_t stackid, void *arg)
5800 {
5801 	ip_stack_t *ipst = (ip_stack_t *)arg;
5802 	int ret;
5803 
5804 #ifdef NS_DEBUG
5805 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5806 #endif
5807 	ipv4_hook_destroy(ipst);
5808 	ipv6_hook_destroy(ipst);
5809 	ip_net_destroy(ipst);
5810 
5811 	rw_destroy(&ipst->ips_srcid_lock);
5812 
5813 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5814 	ipst->ips_ip_mibkp = NULL;
5815 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5816 	ipst->ips_icmp_mibkp = NULL;
5817 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5818 	ipst->ips_ip_kstat = NULL;
5819 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5820 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5821 	ipst->ips_ip6_kstat = NULL;
5822 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5823 
5824 	nd_free(&ipst->ips_ip_g_nd);
5825 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5826 	ipst->ips_param_arr = NULL;
5827 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5828 	ipst->ips_ndp_arr = NULL;
5829 
5830 	ip_mrouter_stack_destroy(ipst);
5831 
5832 	mutex_destroy(&ipst->ips_ip_mi_lock);
5833 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5834 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5835 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5836 
5837 	ret = untimeout(ipst->ips_igmp_timeout_id);
5838 	if (ret == -1) {
5839 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5840 	} else {
5841 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5842 		ipst->ips_igmp_timeout_id = 0;
5843 	}
5844 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5845 	if (ret == -1) {
5846 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5847 	} else {
5848 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5849 		ipst->ips_igmp_slowtimeout_id = 0;
5850 	}
5851 	ret = untimeout(ipst->ips_mld_timeout_id);
5852 	if (ret == -1) {
5853 		ASSERT(ipst->ips_mld_timeout_id == 0);
5854 	} else {
5855 		ASSERT(ipst->ips_mld_timeout_id != 0);
5856 		ipst->ips_mld_timeout_id = 0;
5857 	}
5858 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5859 	if (ret == -1) {
5860 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5861 	} else {
5862 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5863 		ipst->ips_mld_slowtimeout_id = 0;
5864 	}
5865 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5866 	if (ret == -1) {
5867 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5868 	} else {
5869 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5870 		ipst->ips_ip_ire_expire_id = 0;
5871 	}
5872 
5873 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5874 	mutex_destroy(&ipst->ips_mld_timer_lock);
5875 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5876 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5877 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5878 	rw_destroy(&ipst->ips_ill_g_lock);
5879 
5880 	ip_ire_fini(ipst);
5881 	ip6_asp_free(ipst);
5882 	conn_drain_fini(ipst);
5883 	ipcl_destroy(ipst);
5884 
5885 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5886 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5887 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5888 	ipst->ips_ndp4 = NULL;
5889 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5890 	ipst->ips_ndp6 = NULL;
5891 
5892 	if (ipst->ips_loopback_ksp != NULL) {
5893 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5894 		ipst->ips_loopback_ksp = NULL;
5895 	}
5896 
5897 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5898 	ipst->ips_phyint_g_list = NULL;
5899 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5900 	ipst->ips_ill_g_heads = NULL;
5901 
5902 	kmem_free(ipst, sizeof (*ipst));
5903 }
5904 
5905 /*
5906  * This function is called from the TSD destructor, and is used to debug
5907  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5908  * details.
5909  */
5910 static void
5911 ip_thread_exit(void *phash)
5912 {
5913 	th_hash_t *thh = phash;
5914 
5915 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5916 	list_remove(&ip_thread_list, thh);
5917 	rw_exit(&ip_thread_rwlock);
5918 	mod_hash_destroy_hash(thh->thh_hash);
5919 	kmem_free(thh, sizeof (*thh));
5920 }
5921 
5922 /*
5923  * Called when the IP kernel module is loaded into the kernel
5924  */
5925 void
5926 ip_ddi_init(void)
5927 {
5928 	TCP6_MAJ = ddi_name_to_major(TCP6);
5929 	TCP_MAJ	= ddi_name_to_major(TCP);
5930 	SCTP_MAJ = ddi_name_to_major(SCTP);
5931 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5932 
5933 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5934 
5935 	/*
5936 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5937 	 * initial devices: ip, ip6, tcp, tcp6.
5938 	 */
5939 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5940 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5941 		cmn_err(CE_PANIC,
5942 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5943 	}
5944 
5945 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5946 
5947 	ipcl_g_init();
5948 	ip_ire_g_init();
5949 	ip_net_g_init();
5950 
5951 #ifdef DEBUG
5952 	tsd_create(&ip_thread_data, ip_thread_exit);
5953 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5954 	list_create(&ip_thread_list, sizeof (th_hash_t),
5955 	    offsetof(th_hash_t, thh_link));
5956 #endif
5957 
5958 	/*
5959 	 * We want to be informed each time a stack is created or
5960 	 * destroyed in the kernel, so we can maintain the
5961 	 * set of udp_stack_t's.
5962 	 */
5963 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5964 	    ip_stack_fini);
5965 
5966 	ipsec_policy_g_init();
5967 	tcp_ddi_g_init();
5968 	sctp_ddi_g_init();
5969 
5970 	tnet_init();
5971 }
5972 
5973 /*
5974  * Initialize the IP stack instance.
5975  */
5976 static void *
5977 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5978 {
5979 	ip_stack_t	*ipst;
5980 	ipparam_t	*pa;
5981 	ipndp_t		*na;
5982 
5983 #ifdef NS_DEBUG
5984 	printf("ip_stack_init(stack %d)\n", stackid);
5985 #endif
5986 
5987 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5988 	ipst->ips_netstack = ns;
5989 
5990 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5991 	    KM_SLEEP);
5992 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5993 	    KM_SLEEP);
5994 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5995 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5996 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5997 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5998 
5999 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
6000 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6001 	ipst->ips_igmp_deferred_next = INFINITY;
6002 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
6003 	ipst->ips_mld_deferred_next = INFINITY;
6004 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6005 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
6006 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
6007 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
6008 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
6009 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
6010 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
6011 
6012 	ipcl_init(ipst);
6013 	ip_ire_init(ipst);
6014 	ip6_asp_init(ipst);
6015 	ipif_init(ipst);
6016 	conn_drain_init(ipst);
6017 	ip_mrouter_stack_init(ipst);
6018 
6019 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
6020 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
6021 
6022 	ipst->ips_ip_multirt_log_interval = 1000;
6023 
6024 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
6025 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
6026 	ipst->ips_ill_index = 1;
6027 
6028 	ipst->ips_saved_ip_g_forward = -1;
6029 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
6030 
6031 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
6032 	ipst->ips_param_arr = pa;
6033 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6034 
6035 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6036 	ipst->ips_ndp_arr = na;
6037 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6038 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6039 	    (caddr_t)&ipst->ips_ip_g_forward;
6040 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6041 	    (caddr_t)&ipst->ips_ipv6_forward;
6042 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6043 	    "ip_cgtp_filter") == 0);
6044 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6045 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6046 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6047 	    "ipmp_hook_emulation") == 0);
6048 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6049 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6050 
6051 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6052 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6053 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6054 
6055 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6056 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6057 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6058 	ipst->ips_ip6_kstat =
6059 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6060 
6061 	ipst->ips_ipmp_enable_failback = B_TRUE;
6062 
6063 	ipst->ips_ip_src_id = 1;
6064 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6065 
6066 	ip_net_init(ipst, ns);
6067 	ipv4_hook_init(ipst);
6068 	ipv6_hook_init(ipst);
6069 
6070 	return (ipst);
6071 }
6072 
6073 /*
6074  * Allocate and initialize a DLPI template of the specified length.  (May be
6075  * called as writer.)
6076  */
6077 mblk_t *
6078 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6079 {
6080 	mblk_t	*mp;
6081 
6082 	mp = allocb(len, BPRI_MED);
6083 	if (!mp)
6084 		return (NULL);
6085 
6086 	/*
6087 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6088 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6089 	 * that other DLPI are M_PROTO.
6090 	 */
6091 	if (prim == DL_INFO_REQ) {
6092 		mp->b_datap->db_type = M_PCPROTO;
6093 	} else {
6094 		mp->b_datap->db_type = M_PROTO;
6095 	}
6096 
6097 	mp->b_wptr = mp->b_rptr + len;
6098 	bzero(mp->b_rptr, len);
6099 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6100 	return (mp);
6101 }
6102 
6103 const char *
6104 dlpi_prim_str(int prim)
6105 {
6106 	switch (prim) {
6107 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6108 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6109 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6110 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6111 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6112 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6113 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6114 	case DL_OK_ACK:		return ("DL_OK_ACK");
6115 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6116 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6117 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6118 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6119 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6120 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6121 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6122 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6123 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6124 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6125 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6126 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6127 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6128 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6129 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6130 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6131 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6132 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6133 	default:		return ("<unknown primitive>");
6134 	}
6135 }
6136 
6137 const char *
6138 dlpi_err_str(int err)
6139 {
6140 	switch (err) {
6141 	case DL_ACCESS:		return ("DL_ACCESS");
6142 	case DL_BADADDR:	return ("DL_BADADDR");
6143 	case DL_BADCORR:	return ("DL_BADCORR");
6144 	case DL_BADDATA:	return ("DL_BADDATA");
6145 	case DL_BADPPA:		return ("DL_BADPPA");
6146 	case DL_BADPRIM:	return ("DL_BADPRIM");
6147 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6148 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6149 	case DL_BADSAP:		return ("DL_BADSAP");
6150 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6151 	case DL_BOUND:		return ("DL_BOUND");
6152 	case DL_INITFAILED:	return ("DL_INITFAILED");
6153 	case DL_NOADDR:		return ("DL_NOADDR");
6154 	case DL_NOTINIT:	return ("DL_NOTINIT");
6155 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6156 	case DL_SYSERR:		return ("DL_SYSERR");
6157 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6158 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6159 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6160 	case DL_TOOMANY:	return ("DL_TOOMANY");
6161 	case DL_NOTENAB:	return ("DL_NOTENAB");
6162 	case DL_BUSY:		return ("DL_BUSY");
6163 	case DL_NOAUTO:		return ("DL_NOAUTO");
6164 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6165 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6166 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6167 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6168 	case DL_PENDING:	return ("DL_PENDING");
6169 	default:		return ("<unknown error>");
6170 	}
6171 }
6172 
6173 /*
6174  * Debug formatting routine.  Returns a character string representation of the
6175  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6176  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6177  *
6178  * Once the ndd table-printing interfaces are removed, this can be changed to
6179  * standard dotted-decimal form.
6180  */
6181 char *
6182 ip_dot_addr(ipaddr_t addr, char *buf)
6183 {
6184 	uint8_t *ap = (uint8_t *)&addr;
6185 
6186 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6187 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6188 	return (buf);
6189 }
6190 
6191 /*
6192  * Write the given MAC address as a printable string in the usual colon-
6193  * separated format.
6194  */
6195 const char *
6196 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6197 {
6198 	char *bp;
6199 
6200 	if (alen == 0 || buflen < 4)
6201 		return ("?");
6202 	bp = buf;
6203 	for (;;) {
6204 		/*
6205 		 * If there are more MAC address bytes available, but we won't
6206 		 * have any room to print them, then add "..." to the string
6207 		 * instead.  See below for the 'magic number' explanation.
6208 		 */
6209 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6210 			(void) strcpy(bp, "...");
6211 			break;
6212 		}
6213 		(void) sprintf(bp, "%02x", *addr++);
6214 		bp += 2;
6215 		if (--alen == 0)
6216 			break;
6217 		*bp++ = ':';
6218 		buflen -= 3;
6219 		/*
6220 		 * At this point, based on the first 'if' statement above,
6221 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6222 		 * buflen >= 4.  The first case leaves room for the final "xx"
6223 		 * number and trailing NUL byte.  The second leaves room for at
6224 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6225 		 * that statement.
6226 		 */
6227 	}
6228 	return (buf);
6229 }
6230 
6231 /*
6232  * Send an ICMP error after patching up the packet appropriately.  Returns
6233  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6234  */
6235 static boolean_t
6236 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6237     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6238     zoneid_t zoneid, ip_stack_t *ipst)
6239 {
6240 	ipha_t *ipha;
6241 	mblk_t *first_mp;
6242 	boolean_t secure;
6243 	unsigned char db_type;
6244 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6245 
6246 	first_mp = mp;
6247 	if (mctl_present) {
6248 		mp = mp->b_cont;
6249 		secure = ipsec_in_is_secure(first_mp);
6250 		ASSERT(mp != NULL);
6251 	} else {
6252 		/*
6253 		 * If this is an ICMP error being reported - which goes
6254 		 * up as M_CTLs, we need to convert them to M_DATA till
6255 		 * we finish checking with global policy because
6256 		 * ipsec_check_global_policy() assumes M_DATA as clear
6257 		 * and M_CTL as secure.
6258 		 */
6259 		db_type = DB_TYPE(mp);
6260 		DB_TYPE(mp) = M_DATA;
6261 		secure = B_FALSE;
6262 	}
6263 	/*
6264 	 * We are generating an icmp error for some inbound packet.
6265 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6266 	 * Before we generate an error, check with global policy
6267 	 * to see whether this is allowed to enter the system. As
6268 	 * there is no "conn", we are checking with global policy.
6269 	 */
6270 	ipha = (ipha_t *)mp->b_rptr;
6271 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6272 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6273 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6274 		if (first_mp == NULL)
6275 			return (B_FALSE);
6276 	}
6277 
6278 	if (!mctl_present)
6279 		DB_TYPE(mp) = db_type;
6280 
6281 	if (flags & IP_FF_SEND_ICMP) {
6282 		if (flags & IP_FF_HDR_COMPLETE) {
6283 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6284 				freemsg(first_mp);
6285 				return (B_TRUE);
6286 			}
6287 		}
6288 		if (flags & IP_FF_CKSUM) {
6289 			/*
6290 			 * Have to correct checksum since
6291 			 * the packet might have been
6292 			 * fragmented and the reassembly code in ip_rput
6293 			 * does not restore the IP checksum.
6294 			 */
6295 			ipha->ipha_hdr_checksum = 0;
6296 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6297 		}
6298 		switch (icmp_type) {
6299 		case ICMP_DEST_UNREACHABLE:
6300 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6301 			    ipst);
6302 			break;
6303 		default:
6304 			freemsg(first_mp);
6305 			break;
6306 		}
6307 	} else {
6308 		freemsg(first_mp);
6309 		return (B_FALSE);
6310 	}
6311 
6312 	return (B_TRUE);
6313 }
6314 
6315 /*
6316  * Used to send an ICMP error message when a packet is received for
6317  * a protocol that is not supported. The mblk passed as argument
6318  * is consumed by this function.
6319  */
6320 void
6321 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6322     ip_stack_t *ipst)
6323 {
6324 	mblk_t *mp;
6325 	ipha_t *ipha;
6326 	ill_t *ill;
6327 	ipsec_in_t *ii;
6328 
6329 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6330 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6331 
6332 	mp = ipsec_mp->b_cont;
6333 	ipsec_mp->b_cont = NULL;
6334 	ipha = (ipha_t *)mp->b_rptr;
6335 	/* Get ill from index in ipsec_in_t. */
6336 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6337 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6338 	    ipst);
6339 	if (ill != NULL) {
6340 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6341 			if (ip_fanout_send_icmp(q, mp, flags,
6342 			    ICMP_DEST_UNREACHABLE,
6343 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6344 				BUMP_MIB(ill->ill_ip_mib,
6345 				    ipIfStatsInUnknownProtos);
6346 			}
6347 		} else {
6348 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6349 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6350 			    0, B_FALSE, zoneid, ipst)) {
6351 				BUMP_MIB(ill->ill_ip_mib,
6352 				    ipIfStatsInUnknownProtos);
6353 			}
6354 		}
6355 		ill_refrele(ill);
6356 	} else { /* re-link for the freemsg() below. */
6357 		ipsec_mp->b_cont = mp;
6358 	}
6359 
6360 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6361 	freemsg(ipsec_mp);
6362 }
6363 
6364 /*
6365  * See if the inbound datagram has had IPsec processing applied to it.
6366  */
6367 boolean_t
6368 ipsec_in_is_secure(mblk_t *ipsec_mp)
6369 {
6370 	ipsec_in_t *ii;
6371 
6372 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6373 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6374 
6375 	if (ii->ipsec_in_loopback) {
6376 		return (ii->ipsec_in_secure);
6377 	} else {
6378 		return (ii->ipsec_in_ah_sa != NULL ||
6379 		    ii->ipsec_in_esp_sa != NULL ||
6380 		    ii->ipsec_in_decaps);
6381 	}
6382 }
6383 
6384 /*
6385  * Handle protocols with which IP is less intimate.  There
6386  * can be more than one stream bound to a particular
6387  * protocol.  When this is the case, normally each one gets a copy
6388  * of any incoming packets.
6389  *
6390  * IPsec NOTE :
6391  *
6392  * Don't allow a secure packet going up a non-secure connection.
6393  * We don't allow this because
6394  *
6395  * 1) Reply might go out in clear which will be dropped at
6396  *    the sending side.
6397  * 2) If the reply goes out in clear it will give the
6398  *    adversary enough information for getting the key in
6399  *    most of the cases.
6400  *
6401  * Moreover getting a secure packet when we expect clear
6402  * implies that SA's were added without checking for
6403  * policy on both ends. This should not happen once ISAKMP
6404  * is used to negotiate SAs as SAs will be added only after
6405  * verifying the policy.
6406  *
6407  * NOTE : If the packet was tunneled and not multicast we only send
6408  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6409  * back to delivering packets to AF_INET6 raw sockets.
6410  *
6411  * IPQoS Notes:
6412  * Once we have determined the client, invoke IPPF processing.
6413  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6414  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6415  * ip_policy will be false.
6416  *
6417  * Zones notes:
6418  * Currently only applications in the global zone can create raw sockets for
6419  * protocols other than ICMP. So unlike the broadcast / multicast case of
6420  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6421  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6422  */
6423 static void
6424 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6425     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6426     zoneid_t zoneid)
6427 {
6428 	queue_t	*rq;
6429 	mblk_t	*mp1, *first_mp1;
6430 	uint_t	protocol = ipha->ipha_protocol;
6431 	ipaddr_t dst;
6432 	boolean_t one_only;
6433 	mblk_t *first_mp = mp;
6434 	boolean_t secure;
6435 	uint32_t ill_index;
6436 	conn_t	*connp, *first_connp, *next_connp;
6437 	connf_t	*connfp;
6438 	boolean_t shared_addr;
6439 	mib2_ipIfStatsEntry_t *mibptr;
6440 	ip_stack_t *ipst = recv_ill->ill_ipst;
6441 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6442 
6443 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6444 	if (mctl_present) {
6445 		mp = first_mp->b_cont;
6446 		secure = ipsec_in_is_secure(first_mp);
6447 		ASSERT(mp != NULL);
6448 	} else {
6449 		secure = B_FALSE;
6450 	}
6451 	dst = ipha->ipha_dst;
6452 	/*
6453 	 * If the packet was tunneled and not multicast we only send to it
6454 	 * the first match.
6455 	 */
6456 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6457 	    !CLASSD(dst));
6458 
6459 	shared_addr = (zoneid == ALL_ZONES);
6460 	if (shared_addr) {
6461 		/*
6462 		 * We don't allow multilevel ports for raw IP, so no need to
6463 		 * check for that here.
6464 		 */
6465 		zoneid = tsol_packet_to_zoneid(mp);
6466 	}
6467 
6468 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6469 	mutex_enter(&connfp->connf_lock);
6470 	connp = connfp->connf_head;
6471 	for (connp = connfp->connf_head; connp != NULL;
6472 	    connp = connp->conn_next) {
6473 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6474 		    zoneid) &&
6475 		    (!is_system_labeled() ||
6476 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6477 		    connp))) {
6478 			break;
6479 		}
6480 	}
6481 
6482 	if (connp == NULL || connp->conn_upq == NULL) {
6483 		/*
6484 		 * No one bound to these addresses.  Is
6485 		 * there a client that wants all
6486 		 * unclaimed datagrams?
6487 		 */
6488 		mutex_exit(&connfp->connf_lock);
6489 		/*
6490 		 * Check for IPPROTO_ENCAP...
6491 		 */
6492 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6493 			/*
6494 			 * If an IPsec mblk is here on a multicast
6495 			 * tunnel (using ip_mroute stuff), check policy here,
6496 			 * THEN ship off to ip_mroute_decap().
6497 			 *
6498 			 * BTW,  If I match a configured IP-in-IP
6499 			 * tunnel, this path will not be reached, and
6500 			 * ip_mroute_decap will never be called.
6501 			 */
6502 			first_mp = ipsec_check_global_policy(first_mp, connp,
6503 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6504 			if (first_mp != NULL) {
6505 				if (mctl_present)
6506 					freeb(first_mp);
6507 				ip_mroute_decap(q, mp, ill);
6508 			} /* Else we already freed everything! */
6509 		} else {
6510 			/*
6511 			 * Otherwise send an ICMP protocol unreachable.
6512 			 */
6513 			if (ip_fanout_send_icmp(q, first_mp, flags,
6514 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6515 			    mctl_present, zoneid, ipst)) {
6516 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6517 			}
6518 		}
6519 		return;
6520 	}
6521 	CONN_INC_REF(connp);
6522 	first_connp = connp;
6523 
6524 	/*
6525 	 * Only send message to one tunnel driver by immediately
6526 	 * terminating the loop.
6527 	 */
6528 	connp = one_only ? NULL : connp->conn_next;
6529 
6530 	for (;;) {
6531 		while (connp != NULL) {
6532 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6533 			    flags, zoneid) &&
6534 			    (!is_system_labeled() ||
6535 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6536 			    shared_addr, connp)))
6537 				break;
6538 			connp = connp->conn_next;
6539 		}
6540 
6541 		/*
6542 		 * Copy the packet.
6543 		 */
6544 		if (connp == NULL || connp->conn_upq == NULL ||
6545 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6546 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6547 			/*
6548 			 * No more interested clients or memory
6549 			 * allocation failed
6550 			 */
6551 			connp = first_connp;
6552 			break;
6553 		}
6554 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6555 		CONN_INC_REF(connp);
6556 		mutex_exit(&connfp->connf_lock);
6557 		rq = connp->conn_rq;
6558 		if (!canputnext(rq)) {
6559 			if (flags & IP_FF_RAWIP) {
6560 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6561 			} else {
6562 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6563 			}
6564 
6565 			freemsg(first_mp1);
6566 		} else {
6567 			/*
6568 			 * Don't enforce here if we're an actual tunnel -
6569 			 * let "tun" do it instead.
6570 			 */
6571 			if (!IPCL_IS_IPTUN(connp) &&
6572 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6573 			    secure)) {
6574 				first_mp1 = ipsec_check_inbound_policy
6575 				    (first_mp1, connp, ipha, NULL,
6576 				    mctl_present);
6577 			}
6578 			if (first_mp1 != NULL) {
6579 				int in_flags = 0;
6580 				/*
6581 				 * ip_fanout_proto also gets called from
6582 				 * icmp_inbound_error_fanout, in which case
6583 				 * the msg type is M_CTL.  Don't add info
6584 				 * in this case for the time being. In future
6585 				 * when there is a need for knowing the
6586 				 * inbound iface index for ICMP error msgs,
6587 				 * then this can be changed.
6588 				 */
6589 				if (connp->conn_recvif)
6590 					in_flags = IPF_RECVIF;
6591 				/*
6592 				 * The ULP may support IP_RECVPKTINFO for both
6593 				 * IP v4 and v6 so pass the appropriate argument
6594 				 * based on conn IP version.
6595 				 */
6596 				if (connp->conn_ip_recvpktinfo) {
6597 					if (connp->conn_af_isv6) {
6598 						/*
6599 						 * V6 only needs index
6600 						 */
6601 						in_flags |= IPF_RECVIF;
6602 					} else {
6603 						/*
6604 						 * V4 needs index +
6605 						 * matching address.
6606 						 */
6607 						in_flags |= IPF_RECVADDR;
6608 					}
6609 				}
6610 				if ((in_flags != 0) &&
6611 				    (mp->b_datap->db_type != M_CTL)) {
6612 					/*
6613 					 * the actual data will be
6614 					 * contained in b_cont upon
6615 					 * successful return of the
6616 					 * following call else
6617 					 * original mblk is returned
6618 					 */
6619 					ASSERT(recv_ill != NULL);
6620 					mp1 = ip_add_info(mp1, recv_ill,
6621 					    in_flags, IPCL_ZONEID(connp), ipst);
6622 				}
6623 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6624 				if (mctl_present)
6625 					freeb(first_mp1);
6626 				putnext(rq, mp1);
6627 			}
6628 		}
6629 		mutex_enter(&connfp->connf_lock);
6630 		/* Follow the next pointer before releasing the conn. */
6631 		next_connp = connp->conn_next;
6632 		CONN_DEC_REF(connp);
6633 		connp = next_connp;
6634 	}
6635 
6636 	/* Last one.  Send it upstream. */
6637 	mutex_exit(&connfp->connf_lock);
6638 
6639 	/*
6640 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6641 	 * will be set to false.
6642 	 */
6643 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6644 		ill_index = ill->ill_phyint->phyint_ifindex;
6645 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6646 		if (mp == NULL) {
6647 			CONN_DEC_REF(connp);
6648 			if (mctl_present) {
6649 				freeb(first_mp);
6650 			}
6651 			return;
6652 		}
6653 	}
6654 
6655 	rq = connp->conn_rq;
6656 	if (!canputnext(rq)) {
6657 		if (flags & IP_FF_RAWIP) {
6658 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6659 		} else {
6660 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6661 		}
6662 
6663 		freemsg(first_mp);
6664 	} else {
6665 		if (IPCL_IS_IPTUN(connp)) {
6666 			/*
6667 			 * Tunneled packet.  We enforce policy in the tunnel
6668 			 * module itself.
6669 			 *
6670 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6671 			 * a policy check.
6672 			 */
6673 			putnext(rq, first_mp);
6674 			CONN_DEC_REF(connp);
6675 			return;
6676 		}
6677 
6678 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6679 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6680 			    ipha, NULL, mctl_present);
6681 		}
6682 
6683 		if (first_mp != NULL) {
6684 			int in_flags = 0;
6685 
6686 			/*
6687 			 * ip_fanout_proto also gets called
6688 			 * from icmp_inbound_error_fanout, in
6689 			 * which case the msg type is M_CTL.
6690 			 * Don't add info in this case for time
6691 			 * being. In future when there is a
6692 			 * need for knowing the inbound iface
6693 			 * index for ICMP error msgs, then this
6694 			 * can be changed
6695 			 */
6696 			if (connp->conn_recvif)
6697 				in_flags = IPF_RECVIF;
6698 			if (connp->conn_ip_recvpktinfo) {
6699 				if (connp->conn_af_isv6) {
6700 					/*
6701 					 * V6 only needs index
6702 					 */
6703 					in_flags |= IPF_RECVIF;
6704 				} else {
6705 					/*
6706 					 * V4 needs index +
6707 					 * matching address.
6708 					 */
6709 					in_flags |= IPF_RECVADDR;
6710 				}
6711 			}
6712 			if ((in_flags != 0) &&
6713 			    (mp->b_datap->db_type != M_CTL)) {
6714 
6715 				/*
6716 				 * the actual data will be contained in
6717 				 * b_cont upon successful return
6718 				 * of the following call else original
6719 				 * mblk is returned
6720 				 */
6721 				ASSERT(recv_ill != NULL);
6722 				mp = ip_add_info(mp, recv_ill,
6723 				    in_flags, IPCL_ZONEID(connp), ipst);
6724 			}
6725 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6726 			putnext(rq, mp);
6727 			if (mctl_present)
6728 				freeb(first_mp);
6729 		}
6730 	}
6731 	CONN_DEC_REF(connp);
6732 }
6733 
6734 /*
6735  * Fanout for TCP packets
6736  * The caller puts <fport, lport> in the ports parameter.
6737  *
6738  * IPQoS Notes
6739  * Before sending it to the client, invoke IPPF processing.
6740  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6741  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6742  * ip_policy is false.
6743  */
6744 static void
6745 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6746     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6747 {
6748 	mblk_t  *first_mp;
6749 	boolean_t secure;
6750 	uint32_t ill_index;
6751 	int	ip_hdr_len;
6752 	tcph_t	*tcph;
6753 	boolean_t syn_present = B_FALSE;
6754 	conn_t	*connp;
6755 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6756 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6757 
6758 	ASSERT(recv_ill != NULL);
6759 
6760 	first_mp = mp;
6761 	if (mctl_present) {
6762 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6763 		mp = first_mp->b_cont;
6764 		secure = ipsec_in_is_secure(first_mp);
6765 		ASSERT(mp != NULL);
6766 	} else {
6767 		secure = B_FALSE;
6768 	}
6769 
6770 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6771 
6772 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6773 	    zoneid, ipst)) == NULL) {
6774 		/*
6775 		 * No connected connection or listener. Send a
6776 		 * TH_RST via tcp_xmit_listeners_reset.
6777 		 */
6778 
6779 		/* Initiate IPPf processing, if needed. */
6780 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6781 			uint32_t ill_index;
6782 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6783 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6784 			if (first_mp == NULL)
6785 				return;
6786 		}
6787 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6788 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6789 		    zoneid));
6790 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6791 		    ipst->ips_netstack->netstack_tcp, NULL);
6792 		return;
6793 	}
6794 
6795 	/*
6796 	 * Allocate the SYN for the TCP connection here itself
6797 	 */
6798 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6799 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6800 		if (IPCL_IS_TCP(connp)) {
6801 			squeue_t *sqp;
6802 
6803 			/*
6804 			 * For fused tcp loopback, assign the eager's
6805 			 * squeue to be that of the active connect's.
6806 			 * Note that we don't check for IP_FF_LOOPBACK
6807 			 * here since this routine gets called only
6808 			 * for loopback (unlike the IPv6 counterpart).
6809 			 */
6810 			ASSERT(Q_TO_CONN(q) != NULL);
6811 			if (do_tcp_fusion &&
6812 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6813 			    !secure &&
6814 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6815 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6816 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6817 				sqp = Q_TO_CONN(q)->conn_sqp;
6818 			} else {
6819 				sqp = IP_SQUEUE_GET(lbolt);
6820 			}
6821 
6822 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6823 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6824 			syn_present = B_TRUE;
6825 		}
6826 	}
6827 
6828 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6829 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6830 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6831 		if ((flags & TH_RST) || (flags & TH_URG)) {
6832 			CONN_DEC_REF(connp);
6833 			freemsg(first_mp);
6834 			return;
6835 		}
6836 		if (flags & TH_ACK) {
6837 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6838 			    ipst->ips_netstack->netstack_tcp, connp);
6839 			CONN_DEC_REF(connp);
6840 			return;
6841 		}
6842 
6843 		CONN_DEC_REF(connp);
6844 		freemsg(first_mp);
6845 		return;
6846 	}
6847 
6848 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6849 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6850 		    NULL, mctl_present);
6851 		if (first_mp == NULL) {
6852 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6853 			CONN_DEC_REF(connp);
6854 			return;
6855 		}
6856 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6857 			ASSERT(syn_present);
6858 			if (mctl_present) {
6859 				ASSERT(first_mp != mp);
6860 				first_mp->b_datap->db_struioflag |=
6861 				    STRUIO_POLICY;
6862 			} else {
6863 				ASSERT(first_mp == mp);
6864 				mp->b_datap->db_struioflag &=
6865 				    ~STRUIO_EAGER;
6866 				mp->b_datap->db_struioflag |=
6867 				    STRUIO_POLICY;
6868 			}
6869 		} else {
6870 			/*
6871 			 * Discard first_mp early since we're dealing with a
6872 			 * fully-connected conn_t and tcp doesn't do policy in
6873 			 * this case.
6874 			 */
6875 			if (mctl_present) {
6876 				freeb(first_mp);
6877 				mctl_present = B_FALSE;
6878 			}
6879 			first_mp = mp;
6880 		}
6881 	}
6882 
6883 	/*
6884 	 * Initiate policy processing here if needed. If we get here from
6885 	 * icmp_inbound_error_fanout, ip_policy is false.
6886 	 */
6887 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6888 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6889 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6890 		if (mp == NULL) {
6891 			CONN_DEC_REF(connp);
6892 			if (mctl_present)
6893 				freeb(first_mp);
6894 			return;
6895 		} else if (mctl_present) {
6896 			ASSERT(first_mp != mp);
6897 			first_mp->b_cont = mp;
6898 		} else {
6899 			first_mp = mp;
6900 		}
6901 	}
6902 
6903 
6904 
6905 	/* Handle socket options. */
6906 	if (!syn_present &&
6907 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6908 		/* Add header */
6909 		ASSERT(recv_ill != NULL);
6910 		/*
6911 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6912 		 * IPF_RECVIF.
6913 		 */
6914 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6915 		    ipst);
6916 		if (mp == NULL) {
6917 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6918 			CONN_DEC_REF(connp);
6919 			if (mctl_present)
6920 				freeb(first_mp);
6921 			return;
6922 		} else if (mctl_present) {
6923 			/*
6924 			 * ip_add_info might return a new mp.
6925 			 */
6926 			ASSERT(first_mp != mp);
6927 			first_mp->b_cont = mp;
6928 		} else {
6929 			first_mp = mp;
6930 		}
6931 	}
6932 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6933 	if (IPCL_IS_TCP(connp)) {
6934 		/* do not drain, certain use cases can blow the stack */
6935 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6936 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6937 	} else {
6938 		putnext(connp->conn_rq, first_mp);
6939 		CONN_DEC_REF(connp);
6940 	}
6941 }
6942 
6943 /*
6944  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6945  * pass it along to ESP if the SPI is non-zero.
6946  *
6947  * One of three things can happen, all of which affect the passed-in mblk:
6948  *
6949  * 1.) The packet is stock UDP and has had its zero-SPI stripped.  Return TRUE.
6950  *     (NOTE:  ICMP messages that go through here just get returned.)
6951  *
6952  * 2.) The packet is ESP-in-UDP, has been transformed into an equivalent
6953  *     ESP packet, and is passed along to ESP.  Return FALSE.
6954  *
6955  * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6956  */
6957 static boolean_t
6958 zero_spi_check(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
6959     ill_t *recv_ill, ipsec_stack_t *ipss)
6960 {
6961 	int shift, plen, iph_len = IPH_HDR_LENGTH(ipha);
6962 	udpha_t *udpha;
6963 	uint32_t *spi;
6964 	uint8_t *orptr;
6965 	boolean_t udp_pkt, free_ire;
6966 
6967 	if (DB_TYPE(mp) == M_CTL) {
6968 		/*
6969 		 * ICMP message with UDP inside.  Don't bother stripping, just
6970 		 * send it up.
6971 		 *
6972 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6973 		 * to ignore errors set by ICMP anyway ('cause they might be
6974 		 * forged), but that's the app's decision, not ours.
6975 		 */
6976 
6977 		/* Bunch of reality checks for DEBUG kernels... */
6978 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6979 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6980 		ASSERT((uint8_t *)ipha != mp->b_rptr);
6981 
6982 		return (B_TRUE);
6983 	}
6984 
6985 	ASSERT((uint8_t *)ipha == mp->b_rptr);
6986 	plen = ntohs(ipha->ipha_length);
6987 
6988 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6989 		/*
6990 		 * Most likely a keepalive for the benefit of an intervening
6991 		 * NAT.  These aren't for us, per se, so drop it.
6992 		 *
6993 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6994 		 * byte packets (keepalives are 1-byte), but we'll drop them
6995 		 * also.
6996 		 */
6997 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6998 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6999 		return (B_FALSE);
7000 	}
7001 
7002 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7003 		mblk_t *tmp = msgpullup(mp, -1);
7004 
7005 		/* might as well pull it all up - it might be ESP. */
7006 		if (tmp == NULL) {
7007 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7008 			    DROPPER(ipss, ipds_esp_nomem),
7009 			    &ipss->ipsec_dropper);
7010 			return (B_FALSE);
7011 		}
7012 		freemsg(mp);
7013 		mp = tmp;
7014 	}
7015 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7016 	if (*spi == 0) {
7017 		/* UDP packet - remove 0-spi. */
7018 		shift = sizeof (uint32_t);
7019 	} else {
7020 		/* ESP-in-UDP packet - reduce to ESP. */
7021 		ipha->ipha_protocol = IPPROTO_ESP;
7022 		shift = sizeof (udpha_t);
7023 	}
7024 
7025 	/* Fix IP header */
7026 	ipha->ipha_length = htons(plen - shift);
7027 	ipha->ipha_hdr_checksum = 0;
7028 
7029 	orptr = mp->b_rptr;
7030 	mp->b_rptr += shift;
7031 
7032 	if (*spi == 0) {
7033 		ASSERT((uint8_t *)ipha == orptr);
7034 		udpha = (udpha_t *)(orptr + iph_len);
7035 		udpha->uha_length = htons(plen - shift - iph_len);
7036 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7037 		udp_pkt = B_TRUE;
7038 	} else {
7039 		udp_pkt = B_FALSE;
7040 	}
7041 	ovbcopy(orptr, orptr + shift, iph_len);
7042 	if (!udp_pkt) /* Punt up for ESP processing. */ {
7043 		ipha = (ipha_t *)(orptr + shift);
7044 
7045 		free_ire = (ire == NULL);
7046 		if (free_ire) {
7047 			/* Re-acquire ire. */
7048 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7049 			    ipss->ipsec_netstack->netstack_ip);
7050 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7051 				if (ire != NULL)
7052 					ire_refrele(ire);
7053 				/*
7054 				 * Do a regular freemsg(), as this is an IP
7055 				 * error (no local route) not an IPsec one.
7056 				 */
7057 				freemsg(mp);
7058 			}
7059 		}
7060 
7061 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
7062 		if (free_ire)
7063 			ire_refrele(ire);
7064 	}
7065 
7066 	return (udp_pkt);
7067 }
7068 
7069 /*
7070  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7071  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7072  * Caller is responsible for dropping references to the conn, and freeing
7073  * first_mp.
7074  *
7075  * IPQoS Notes
7076  * Before sending it to the client, invoke IPPF processing. Policy processing
7077  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7078  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7079  * ip_wput_local, ip_policy is false.
7080  */
7081 static void
7082 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7083     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7084     boolean_t ip_policy)
7085 {
7086 	boolean_t	mctl_present = (first_mp != NULL);
7087 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7088 	uint32_t	ill_index;
7089 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7090 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7091 
7092 	ASSERT(ill != NULL);
7093 
7094 	if (mctl_present)
7095 		first_mp->b_cont = mp;
7096 	else
7097 		first_mp = mp;
7098 
7099 	if (CONN_UDP_FLOWCTLD(connp)) {
7100 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7101 		freemsg(first_mp);
7102 		return;
7103 	}
7104 
7105 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7106 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7107 		    NULL, mctl_present);
7108 		if (first_mp == NULL) {
7109 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7110 			return;	/* Freed by ipsec_check_inbound_policy(). */
7111 		}
7112 	}
7113 	if (mctl_present)
7114 		freeb(first_mp);
7115 
7116 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7117 	if (connp->conn_udp->udp_nat_t_endpoint) {
7118 		if (mctl_present) {
7119 			/* mctl_present *shouldn't* happen. */
7120 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7121 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7122 			    &ipss->ipsec_dropper);
7123 			return;
7124 		}
7125 
7126 		if (!zero_spi_check(ill->ill_rq, mp, ipha, NULL, recv_ill,
7127 		    ipss)) {
7128 			return;
7129 		}
7130 	}
7131 
7132 	/* Handle options. */
7133 	if (connp->conn_recvif)
7134 		in_flags = IPF_RECVIF;
7135 	/*
7136 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7137 	 * passed to ip_add_info is based on IP version of connp.
7138 	 */
7139 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7140 		if (connp->conn_af_isv6) {
7141 			/*
7142 			 * V6 only needs index
7143 			 */
7144 			in_flags |= IPF_RECVIF;
7145 		} else {
7146 			/*
7147 			 * V4 needs index + matching address.
7148 			 */
7149 			in_flags |= IPF_RECVADDR;
7150 		}
7151 	}
7152 
7153 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7154 		in_flags |= IPF_RECVSLLA;
7155 
7156 	/*
7157 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7158 	 * freed if the packet is dropped. The caller will do so.
7159 	 */
7160 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7161 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7162 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7163 		if (mp == NULL) {
7164 			return;
7165 		}
7166 	}
7167 	if ((in_flags != 0) &&
7168 	    (mp->b_datap->db_type != M_CTL)) {
7169 		/*
7170 		 * The actual data will be contained in b_cont
7171 		 * upon successful return of the following call
7172 		 * else original mblk is returned
7173 		 */
7174 		ASSERT(recv_ill != NULL);
7175 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7176 		    ipst);
7177 	}
7178 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7179 	/* Send it upstream */
7180 	CONN_UDP_RECV(connp, mp);
7181 }
7182 
7183 /*
7184  * Fanout for UDP packets.
7185  * The caller puts <fport, lport> in the ports parameter.
7186  *
7187  * If SO_REUSEADDR is set all multicast and broadcast packets
7188  * will be delivered to all streams bound to the same port.
7189  *
7190  * Zones notes:
7191  * Multicast and broadcast packets will be distributed to streams in all zones.
7192  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7193  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7194  * packets. To maintain this behavior with multiple zones, the conns are grouped
7195  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7196  * each zone. If unset, all the following conns in the same zone are skipped.
7197  */
7198 static void
7199 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7200     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7201     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7202 {
7203 	uint32_t	dstport, srcport;
7204 	ipaddr_t	dst;
7205 	mblk_t		*first_mp;
7206 	boolean_t	secure;
7207 	in6_addr_t	v6src;
7208 	conn_t		*connp;
7209 	connf_t		*connfp;
7210 	conn_t		*first_connp;
7211 	conn_t		*next_connp;
7212 	mblk_t		*mp1, *first_mp1;
7213 	ipaddr_t	src;
7214 	zoneid_t	last_zoneid;
7215 	boolean_t	reuseaddr;
7216 	boolean_t	shared_addr;
7217 	ip_stack_t	*ipst;
7218 
7219 	ASSERT(recv_ill != NULL);
7220 	ipst = recv_ill->ill_ipst;
7221 
7222 	first_mp = mp;
7223 	if (mctl_present) {
7224 		mp = first_mp->b_cont;
7225 		first_mp->b_cont = NULL;
7226 		secure = ipsec_in_is_secure(first_mp);
7227 		ASSERT(mp != NULL);
7228 	} else {
7229 		first_mp = NULL;
7230 		secure = B_FALSE;
7231 	}
7232 
7233 	/* Extract ports in net byte order */
7234 	dstport = htons(ntohl(ports) & 0xFFFF);
7235 	srcport = htons(ntohl(ports) >> 16);
7236 	dst = ipha->ipha_dst;
7237 	src = ipha->ipha_src;
7238 
7239 	shared_addr = (zoneid == ALL_ZONES);
7240 	if (shared_addr) {
7241 		/*
7242 		 * No need to handle exclusive-stack zones since ALL_ZONES
7243 		 * only applies to the shared stack.
7244 		 */
7245 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7246 		if (zoneid == ALL_ZONES)
7247 			zoneid = tsol_packet_to_zoneid(mp);
7248 	}
7249 
7250 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7251 	mutex_enter(&connfp->connf_lock);
7252 	connp = connfp->connf_head;
7253 	if (!broadcast && !CLASSD(dst)) {
7254 		/*
7255 		 * Not broadcast or multicast. Send to the one (first)
7256 		 * client we find. No need to check conn_wantpacket()
7257 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7258 		 * IPv4 unicast packets.
7259 		 */
7260 		while ((connp != NULL) &&
7261 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7262 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7263 			connp = connp->conn_next;
7264 		}
7265 
7266 		if (connp == NULL || connp->conn_upq == NULL)
7267 			goto notfound;
7268 
7269 		if (is_system_labeled() &&
7270 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7271 		    connp))
7272 			goto notfound;
7273 
7274 		CONN_INC_REF(connp);
7275 		mutex_exit(&connfp->connf_lock);
7276 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7277 		    flags, recv_ill, ip_policy);
7278 		IP_STAT(ipst, ip_udp_fannorm);
7279 		CONN_DEC_REF(connp);
7280 		return;
7281 	}
7282 
7283 	/*
7284 	 * Broadcast and multicast case
7285 	 *
7286 	 * Need to check conn_wantpacket().
7287 	 * If SO_REUSEADDR has been set on the first we send the
7288 	 * packet to all clients that have joined the group and
7289 	 * match the port.
7290 	 */
7291 
7292 	while (connp != NULL) {
7293 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7294 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7295 		    (!is_system_labeled() ||
7296 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7297 		    connp)))
7298 			break;
7299 		connp = connp->conn_next;
7300 	}
7301 
7302 	if (connp == NULL || connp->conn_upq == NULL)
7303 		goto notfound;
7304 
7305 	first_connp = connp;
7306 	/*
7307 	 * When SO_REUSEADDR is not set, send the packet only to the first
7308 	 * matching connection in its zone by keeping track of the zoneid.
7309 	 */
7310 	reuseaddr = first_connp->conn_reuseaddr;
7311 	last_zoneid = first_connp->conn_zoneid;
7312 
7313 	CONN_INC_REF(connp);
7314 	connp = connp->conn_next;
7315 	for (;;) {
7316 		while (connp != NULL) {
7317 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7318 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7319 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7320 			    (!is_system_labeled() ||
7321 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7322 			    shared_addr, connp)))
7323 				break;
7324 			connp = connp->conn_next;
7325 		}
7326 		/*
7327 		 * Just copy the data part alone. The mctl part is
7328 		 * needed just for verifying policy and it is never
7329 		 * sent up.
7330 		 */
7331 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7332 		    ((mp1 = copymsg(mp)) == NULL))) {
7333 			/*
7334 			 * No more interested clients or memory
7335 			 * allocation failed
7336 			 */
7337 			connp = first_connp;
7338 			break;
7339 		}
7340 		if (connp->conn_zoneid != last_zoneid) {
7341 			/*
7342 			 * Update the zoneid so that the packet isn't sent to
7343 			 * any more conns in the same zone unless SO_REUSEADDR
7344 			 * is set.
7345 			 */
7346 			reuseaddr = connp->conn_reuseaddr;
7347 			last_zoneid = connp->conn_zoneid;
7348 		}
7349 		if (first_mp != NULL) {
7350 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7351 			    ipsec_info_type == IPSEC_IN);
7352 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7353 			    ipst->ips_netstack);
7354 			if (first_mp1 == NULL) {
7355 				freemsg(mp1);
7356 				connp = first_connp;
7357 				break;
7358 			}
7359 		} else {
7360 			first_mp1 = NULL;
7361 		}
7362 		CONN_INC_REF(connp);
7363 		mutex_exit(&connfp->connf_lock);
7364 		/*
7365 		 * IPQoS notes: We don't send the packet for policy
7366 		 * processing here, will do it for the last one (below).
7367 		 * i.e. we do it per-packet now, but if we do policy
7368 		 * processing per-conn, then we would need to do it
7369 		 * here too.
7370 		 */
7371 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7372 		    ipha, flags, recv_ill, B_FALSE);
7373 		mutex_enter(&connfp->connf_lock);
7374 		/* Follow the next pointer before releasing the conn. */
7375 		next_connp = connp->conn_next;
7376 		IP_STAT(ipst, ip_udp_fanmb);
7377 		CONN_DEC_REF(connp);
7378 		connp = next_connp;
7379 	}
7380 
7381 	/* Last one.  Send it upstream. */
7382 	mutex_exit(&connfp->connf_lock);
7383 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7384 	    recv_ill, ip_policy);
7385 	IP_STAT(ipst, ip_udp_fanmb);
7386 	CONN_DEC_REF(connp);
7387 	return;
7388 
7389 notfound:
7390 
7391 	mutex_exit(&connfp->connf_lock);
7392 	IP_STAT(ipst, ip_udp_fanothers);
7393 	/*
7394 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7395 	 * have already been matched above, since they live in the IPv4
7396 	 * fanout tables. This implies we only need to
7397 	 * check for IPv6 in6addr_any endpoints here.
7398 	 * Thus we compare using ipv6_all_zeros instead of the destination
7399 	 * address, except for the multicast group membership lookup which
7400 	 * uses the IPv4 destination.
7401 	 */
7402 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7403 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7404 	mutex_enter(&connfp->connf_lock);
7405 	connp = connfp->connf_head;
7406 	if (!broadcast && !CLASSD(dst)) {
7407 		while (connp != NULL) {
7408 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7409 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7410 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7411 			    !connp->conn_ipv6_v6only)
7412 				break;
7413 			connp = connp->conn_next;
7414 		}
7415 
7416 		if (connp != NULL && is_system_labeled() &&
7417 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7418 		    connp))
7419 			connp = NULL;
7420 
7421 		if (connp == NULL || connp->conn_upq == NULL) {
7422 			/*
7423 			 * No one bound to this port.  Is
7424 			 * there a client that wants all
7425 			 * unclaimed datagrams?
7426 			 */
7427 			mutex_exit(&connfp->connf_lock);
7428 
7429 			if (mctl_present)
7430 				first_mp->b_cont = mp;
7431 			else
7432 				first_mp = mp;
7433 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7434 			    connf_head != NULL) {
7435 				ip_fanout_proto(q, first_mp, ill, ipha,
7436 				    flags | IP_FF_RAWIP, mctl_present,
7437 				    ip_policy, recv_ill, zoneid);
7438 			} else {
7439 				if (ip_fanout_send_icmp(q, first_mp, flags,
7440 				    ICMP_DEST_UNREACHABLE,
7441 				    ICMP_PORT_UNREACHABLE,
7442 				    mctl_present, zoneid, ipst)) {
7443 					BUMP_MIB(ill->ill_ip_mib,
7444 					    udpIfStatsNoPorts);
7445 				}
7446 			}
7447 			return;
7448 		}
7449 
7450 		CONN_INC_REF(connp);
7451 		mutex_exit(&connfp->connf_lock);
7452 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7453 		    flags, recv_ill, ip_policy);
7454 		CONN_DEC_REF(connp);
7455 		return;
7456 	}
7457 	/*
7458 	 * IPv4 multicast packet being delivered to an AF_INET6
7459 	 * in6addr_any endpoint.
7460 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7461 	 * and not conn_wantpacket_v6() since any multicast membership is
7462 	 * for an IPv4-mapped multicast address.
7463 	 * The packet is sent to all clients in all zones that have joined the
7464 	 * group and match the port.
7465 	 */
7466 	while (connp != NULL) {
7467 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7468 		    srcport, v6src) &&
7469 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7470 		    (!is_system_labeled() ||
7471 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7472 		    connp)))
7473 			break;
7474 		connp = connp->conn_next;
7475 	}
7476 
7477 	if (connp == NULL || connp->conn_upq == NULL) {
7478 		/*
7479 		 * No one bound to this port.  Is
7480 		 * there a client that wants all
7481 		 * unclaimed datagrams?
7482 		 */
7483 		mutex_exit(&connfp->connf_lock);
7484 
7485 		if (mctl_present)
7486 			first_mp->b_cont = mp;
7487 		else
7488 			first_mp = mp;
7489 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7490 		    NULL) {
7491 			ip_fanout_proto(q, first_mp, ill, ipha,
7492 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7493 			    recv_ill, zoneid);
7494 		} else {
7495 			/*
7496 			 * We used to attempt to send an icmp error here, but
7497 			 * since this is known to be a multicast packet
7498 			 * and we don't send icmp errors in response to
7499 			 * multicast, just drop the packet and give up sooner.
7500 			 */
7501 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7502 			freemsg(first_mp);
7503 		}
7504 		return;
7505 	}
7506 
7507 	first_connp = connp;
7508 
7509 	CONN_INC_REF(connp);
7510 	connp = connp->conn_next;
7511 	for (;;) {
7512 		while (connp != NULL) {
7513 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7514 			    ipv6_all_zeros, srcport, v6src) &&
7515 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7516 			    (!is_system_labeled() ||
7517 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7518 			    shared_addr, connp)))
7519 				break;
7520 			connp = connp->conn_next;
7521 		}
7522 		/*
7523 		 * Just copy the data part alone. The mctl part is
7524 		 * needed just for verifying policy and it is never
7525 		 * sent up.
7526 		 */
7527 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7528 		    ((mp1 = copymsg(mp)) == NULL))) {
7529 			/*
7530 			 * No more intested clients or memory
7531 			 * allocation failed
7532 			 */
7533 			connp = first_connp;
7534 			break;
7535 		}
7536 		if (first_mp != NULL) {
7537 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7538 			    ipsec_info_type == IPSEC_IN);
7539 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7540 			    ipst->ips_netstack);
7541 			if (first_mp1 == NULL) {
7542 				freemsg(mp1);
7543 				connp = first_connp;
7544 				break;
7545 			}
7546 		} else {
7547 			first_mp1 = NULL;
7548 		}
7549 		CONN_INC_REF(connp);
7550 		mutex_exit(&connfp->connf_lock);
7551 		/*
7552 		 * IPQoS notes: We don't send the packet for policy
7553 		 * processing here, will do it for the last one (below).
7554 		 * i.e. we do it per-packet now, but if we do policy
7555 		 * processing per-conn, then we would need to do it
7556 		 * here too.
7557 		 */
7558 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7559 		    ipha, flags, recv_ill, B_FALSE);
7560 		mutex_enter(&connfp->connf_lock);
7561 		/* Follow the next pointer before releasing the conn. */
7562 		next_connp = connp->conn_next;
7563 		CONN_DEC_REF(connp);
7564 		connp = next_connp;
7565 	}
7566 
7567 	/* Last one.  Send it upstream. */
7568 	mutex_exit(&connfp->connf_lock);
7569 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7570 	    recv_ill, ip_policy);
7571 	CONN_DEC_REF(connp);
7572 }
7573 
7574 /*
7575  * Complete the ip_wput header so that it
7576  * is possible to generate ICMP
7577  * errors.
7578  */
7579 int
7580 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7581 {
7582 	ire_t *ire;
7583 
7584 	if (ipha->ipha_src == INADDR_ANY) {
7585 		ire = ire_lookup_local(zoneid, ipst);
7586 		if (ire == NULL) {
7587 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7588 			return (1);
7589 		}
7590 		ipha->ipha_src = ire->ire_addr;
7591 		ire_refrele(ire);
7592 	}
7593 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7594 	ipha->ipha_hdr_checksum = 0;
7595 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7596 	return (0);
7597 }
7598 
7599 /*
7600  * Nobody should be sending
7601  * packets up this stream
7602  */
7603 static void
7604 ip_lrput(queue_t *q, mblk_t *mp)
7605 {
7606 	mblk_t *mp1;
7607 
7608 	switch (mp->b_datap->db_type) {
7609 	case M_FLUSH:
7610 		/* Turn around */
7611 		if (*mp->b_rptr & FLUSHW) {
7612 			*mp->b_rptr &= ~FLUSHR;
7613 			qreply(q, mp);
7614 			return;
7615 		}
7616 		break;
7617 	}
7618 	/* Could receive messages that passed through ar_rput */
7619 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7620 		mp1->b_prev = mp1->b_next = NULL;
7621 	freemsg(mp);
7622 }
7623 
7624 /* Nobody should be sending packets down this stream */
7625 /* ARGSUSED */
7626 void
7627 ip_lwput(queue_t *q, mblk_t *mp)
7628 {
7629 	freemsg(mp);
7630 }
7631 
7632 /*
7633  * Move the first hop in any source route to ipha_dst and remove that part of
7634  * the source route.  Called by other protocols.  Errors in option formatting
7635  * are ignored - will be handled by ip_wput_options Return the final
7636  * destination (either ipha_dst or the last entry in a source route.)
7637  */
7638 ipaddr_t
7639 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7640 {
7641 	ipoptp_t	opts;
7642 	uchar_t		*opt;
7643 	uint8_t		optval;
7644 	uint8_t		optlen;
7645 	ipaddr_t	dst;
7646 	int		i;
7647 	ire_t		*ire;
7648 	ip_stack_t	*ipst = ns->netstack_ip;
7649 
7650 	ip2dbg(("ip_massage_options\n"));
7651 	dst = ipha->ipha_dst;
7652 	for (optval = ipoptp_first(&opts, ipha);
7653 	    optval != IPOPT_EOL;
7654 	    optval = ipoptp_next(&opts)) {
7655 		opt = opts.ipoptp_cur;
7656 		switch (optval) {
7657 			uint8_t off;
7658 		case IPOPT_SSRR:
7659 		case IPOPT_LSRR:
7660 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7661 				ip1dbg(("ip_massage_options: bad src route\n"));
7662 				break;
7663 			}
7664 			optlen = opts.ipoptp_len;
7665 			off = opt[IPOPT_OFFSET];
7666 			off--;
7667 		redo_srr:
7668 			if (optlen < IP_ADDR_LEN ||
7669 			    off > optlen - IP_ADDR_LEN) {
7670 				/* End of source route */
7671 				ip1dbg(("ip_massage_options: end of SR\n"));
7672 				break;
7673 			}
7674 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7675 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7676 			    ntohl(dst)));
7677 			/*
7678 			 * Check if our address is present more than
7679 			 * once as consecutive hops in source route.
7680 			 * XXX verify per-interface ip_forwarding
7681 			 * for source route?
7682 			 */
7683 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7684 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7685 			if (ire != NULL) {
7686 				ire_refrele(ire);
7687 				off += IP_ADDR_LEN;
7688 				goto redo_srr;
7689 			}
7690 			if (dst == htonl(INADDR_LOOPBACK)) {
7691 				ip1dbg(("ip_massage_options: loopback addr in "
7692 				    "source route!\n"));
7693 				break;
7694 			}
7695 			/*
7696 			 * Update ipha_dst to be the first hop and remove the
7697 			 * first hop from the source route (by overwriting
7698 			 * part of the option with NOP options).
7699 			 */
7700 			ipha->ipha_dst = dst;
7701 			/* Put the last entry in dst */
7702 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7703 			    3;
7704 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7705 
7706 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7707 			    ntohl(dst)));
7708 			/* Move down and overwrite */
7709 			opt[IP_ADDR_LEN] = opt[0];
7710 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7711 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7712 			for (i = 0; i < IP_ADDR_LEN; i++)
7713 				opt[i] = IPOPT_NOP;
7714 			break;
7715 		}
7716 	}
7717 	return (dst);
7718 }
7719 
7720 /*
7721  * Return the network mask
7722  * associated with the specified address.
7723  */
7724 ipaddr_t
7725 ip_net_mask(ipaddr_t addr)
7726 {
7727 	uchar_t	*up = (uchar_t *)&addr;
7728 	ipaddr_t mask = 0;
7729 	uchar_t	*maskp = (uchar_t *)&mask;
7730 
7731 #if defined(__i386) || defined(__amd64)
7732 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7733 #endif
7734 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7735 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7736 #endif
7737 	if (CLASSD(addr)) {
7738 		maskp[0] = 0xF0;
7739 		return (mask);
7740 	}
7741 	if (addr == 0)
7742 		return (0);
7743 	maskp[0] = 0xFF;
7744 	if ((up[0] & 0x80) == 0)
7745 		return (mask);
7746 
7747 	maskp[1] = 0xFF;
7748 	if ((up[0] & 0xC0) == 0x80)
7749 		return (mask);
7750 
7751 	maskp[2] = 0xFF;
7752 	if ((up[0] & 0xE0) == 0xC0)
7753 		return (mask);
7754 
7755 	/* Must be experimental or multicast, indicate as much */
7756 	return ((ipaddr_t)0);
7757 }
7758 
7759 /*
7760  * Select an ill for the packet by considering load spreading across
7761  * a different ill in the group if dst_ill is part of some group.
7762  */
7763 ill_t *
7764 ip_newroute_get_dst_ill(ill_t *dst_ill)
7765 {
7766 	ill_t *ill;
7767 
7768 	/*
7769 	 * We schedule irrespective of whether the source address is
7770 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7771 	 */
7772 	ill = illgrp_scheduler(dst_ill);
7773 	if (ill == NULL)
7774 		return (NULL);
7775 
7776 	/*
7777 	 * For groups with names ip_sioctl_groupname ensures that all
7778 	 * ills are of same type. For groups without names, ifgrp_insert
7779 	 * ensures this.
7780 	 */
7781 	ASSERT(dst_ill->ill_type == ill->ill_type);
7782 
7783 	return (ill);
7784 }
7785 
7786 /*
7787  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7788  */
7789 ill_t *
7790 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7791     ip_stack_t *ipst)
7792 {
7793 	ill_t *ret_ill;
7794 
7795 	ASSERT(ifindex != 0);
7796 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7797 	    ipst);
7798 	if (ret_ill == NULL ||
7799 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7800 		if (isv6) {
7801 			if (ill != NULL) {
7802 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7803 			} else {
7804 				BUMP_MIB(&ipst->ips_ip6_mib,
7805 				    ipIfStatsOutDiscards);
7806 			}
7807 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7808 			    "bad ifindex %d.\n", ifindex));
7809 		} else {
7810 			if (ill != NULL) {
7811 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7812 			} else {
7813 				BUMP_MIB(&ipst->ips_ip_mib,
7814 				    ipIfStatsOutDiscards);
7815 			}
7816 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7817 			    "bad ifindex %d.\n", ifindex));
7818 		}
7819 		if (ret_ill != NULL)
7820 			ill_refrele(ret_ill);
7821 		freemsg(first_mp);
7822 		return (NULL);
7823 	}
7824 
7825 	return (ret_ill);
7826 }
7827 
7828 /*
7829  * IPv4 -
7830  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7831  * out a packet to a destination address for which we do not have specific
7832  * (or sufficient) routing information.
7833  *
7834  * NOTE : These are the scopes of some of the variables that point at IRE,
7835  *	  which needs to be followed while making any future modifications
7836  *	  to avoid memory leaks.
7837  *
7838  *	- ire and sire are the entries looked up initially by
7839  *	  ire_ftable_lookup.
7840  *	- ipif_ire is used to hold the interface ire associated with
7841  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7842  *	  it before branching out to error paths.
7843  *	- save_ire is initialized before ire_create, so that ire returned
7844  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7845  *	  before breaking out of the switch.
7846  *
7847  *	Thus on failures, we have to REFRELE only ire and sire, if they
7848  *	are not NULL.
7849  */
7850 void
7851 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7852     zoneid_t zoneid, ip_stack_t *ipst)
7853 {
7854 	areq_t	*areq;
7855 	ipaddr_t gw = 0;
7856 	ire_t	*ire = NULL;
7857 	mblk_t	*res_mp;
7858 	ipaddr_t *addrp;
7859 	ipaddr_t nexthop_addr;
7860 	ipif_t  *src_ipif = NULL;
7861 	ill_t	*dst_ill = NULL;
7862 	ipha_t  *ipha;
7863 	ire_t	*sire = NULL;
7864 	mblk_t	*first_mp;
7865 	ire_t	*save_ire;
7866 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7867 	ushort_t ire_marks = 0;
7868 	boolean_t mctl_present;
7869 	ipsec_out_t *io;
7870 	mblk_t	*saved_mp;
7871 	ire_t	*first_sire = NULL;
7872 	mblk_t	*copy_mp = NULL;
7873 	mblk_t	*xmit_mp = NULL;
7874 	ipaddr_t save_dst;
7875 	uint32_t multirt_flags =
7876 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7877 	boolean_t multirt_is_resolvable;
7878 	boolean_t multirt_resolve_next;
7879 	boolean_t do_attach_ill = B_FALSE;
7880 	boolean_t ip_nexthop = B_FALSE;
7881 	tsol_ire_gw_secattr_t *attrp = NULL;
7882 	tsol_gcgrp_t *gcgrp = NULL;
7883 	tsol_gcgrp_addr_t ga;
7884 
7885 	if (ip_debug > 2) {
7886 		/* ip1dbg */
7887 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7888 	}
7889 
7890 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7891 	if (mctl_present) {
7892 		io = (ipsec_out_t *)first_mp->b_rptr;
7893 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7894 		ASSERT(zoneid == io->ipsec_out_zoneid);
7895 		ASSERT(zoneid != ALL_ZONES);
7896 	}
7897 
7898 	ipha = (ipha_t *)mp->b_rptr;
7899 
7900 	/* All multicast lookups come through ip_newroute_ipif() */
7901 	if (CLASSD(dst)) {
7902 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7903 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7904 		freemsg(first_mp);
7905 		return;
7906 	}
7907 
7908 	if (mctl_present && io->ipsec_out_attach_if) {
7909 		/* ip_grab_attach_ill returns a held ill */
7910 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7911 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7912 
7913 		/* Failure case frees things for us. */
7914 		if (attach_ill == NULL)
7915 			return;
7916 
7917 		/*
7918 		 * Check if we need an ire that will not be
7919 		 * looked up by anybody else i.e. HIDDEN.
7920 		 */
7921 		if (ill_is_probeonly(attach_ill))
7922 			ire_marks = IRE_MARK_HIDDEN;
7923 	}
7924 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7925 		ip_nexthop = B_TRUE;
7926 		nexthop_addr = io->ipsec_out_nexthop_addr;
7927 	}
7928 	/*
7929 	 * If this IRE is created for forwarding or it is not for
7930 	 * traffic for congestion controlled protocols, mark it as temporary.
7931 	 */
7932 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7933 		ire_marks |= IRE_MARK_TEMPORARY;
7934 
7935 	/*
7936 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7937 	 * chain until it gets the most specific information available.
7938 	 * For example, we know that there is no IRE_CACHE for this dest,
7939 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7940 	 * ire_ftable_lookup will look up the gateway, etc.
7941 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7942 	 * to the destination, of equal netmask length in the forward table,
7943 	 * will be recursively explored. If no information is available
7944 	 * for the final gateway of that route, we force the returned ire
7945 	 * to be equal to sire using MATCH_IRE_PARENT.
7946 	 * At least, in this case we have a starting point (in the buckets)
7947 	 * to look for other routes to the destination in the forward table.
7948 	 * This is actually used only for multirouting, where a list
7949 	 * of routes has to be processed in sequence.
7950 	 *
7951 	 * In the process of coming up with the most specific information,
7952 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7953 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7954 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7955 	 * Two caveats when handling incomplete ire's in ip_newroute:
7956 	 * - we should be careful when accessing its ire_nce (specifically
7957 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7958 	 * - not all legacy code path callers are prepared to handle
7959 	 *   incomplete ire's, so we should not create/add incomplete
7960 	 *   ire_cache entries here. (See discussion about temporary solution
7961 	 *   further below).
7962 	 *
7963 	 * In order to minimize packet dropping, and to preserve existing
7964 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7965 	 * gateway, and instead use the IF_RESOLVER ire to send out
7966 	 * another request to ARP (this is achieved by passing the
7967 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7968 	 * arp response comes back in ip_wput_nondata, we will create
7969 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7970 	 *
7971 	 * Note that this is a temporary solution; the correct solution is
7972 	 * to create an incomplete  per-dst ire_cache entry, and send the
7973 	 * packet out when the gw's nce is resolved. In order to achieve this,
7974 	 * all packet processing must have been completed prior to calling
7975 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7976 	 * to be modified to accomodate this solution.
7977 	 */
7978 	if (ip_nexthop) {
7979 		/*
7980 		 * The first time we come here, we look for an IRE_INTERFACE
7981 		 * entry for the specified nexthop, set the dst to be the
7982 		 * nexthop address and create an IRE_CACHE entry for the
7983 		 * nexthop. The next time around, we are able to find an
7984 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7985 		 * nexthop address and create an IRE_CACHE entry for the
7986 		 * destination address via the specified nexthop.
7987 		 */
7988 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7989 		    MBLK_GETLABEL(mp), ipst);
7990 		if (ire != NULL) {
7991 			gw = nexthop_addr;
7992 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7993 		} else {
7994 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7995 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7996 			    MBLK_GETLABEL(mp),
7997 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7998 			    ipst);
7999 			if (ire != NULL) {
8000 				dst = nexthop_addr;
8001 			}
8002 		}
8003 	} else if (attach_ill == NULL) {
8004 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8005 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8006 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8007 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8008 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8009 		    ipst);
8010 	} else {
8011 		/*
8012 		 * attach_ill is set only for communicating with
8013 		 * on-link hosts. So, don't look for DEFAULT.
8014 		 */
8015 		ipif_t	*attach_ipif;
8016 
8017 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8018 		if (attach_ipif == NULL) {
8019 			ill_refrele(attach_ill);
8020 			goto icmp_err_ret;
8021 		}
8022 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8023 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8024 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8025 		    MATCH_IRE_SECATTR, ipst);
8026 		ipif_refrele(attach_ipif);
8027 	}
8028 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8029 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8030 
8031 	/*
8032 	 * This loop is run only once in most cases.
8033 	 * We loop to resolve further routes only when the destination
8034 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8035 	 */
8036 	do {
8037 		/* Clear the previous iteration's values */
8038 		if (src_ipif != NULL) {
8039 			ipif_refrele(src_ipif);
8040 			src_ipif = NULL;
8041 		}
8042 		if (dst_ill != NULL) {
8043 			ill_refrele(dst_ill);
8044 			dst_ill = NULL;
8045 		}
8046 
8047 		multirt_resolve_next = B_FALSE;
8048 		/*
8049 		 * We check if packets have to be multirouted.
8050 		 * In this case, given the current <ire, sire> couple,
8051 		 * we look for the next suitable <ire, sire>.
8052 		 * This check is done in ire_multirt_lookup(),
8053 		 * which applies various criteria to find the next route
8054 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8055 		 * unchanged if it detects it has not been tried yet.
8056 		 */
8057 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8058 			ip3dbg(("ip_newroute: starting next_resolution "
8059 			    "with first_mp %p, tag %d\n",
8060 			    (void *)first_mp,
8061 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8062 
8063 			ASSERT(sire != NULL);
8064 			multirt_is_resolvable =
8065 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8066 			    MBLK_GETLABEL(mp), ipst);
8067 
8068 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8069 			    "ire %p, sire %p\n",
8070 			    multirt_is_resolvable,
8071 			    (void *)ire, (void *)sire));
8072 
8073 			if (!multirt_is_resolvable) {
8074 				/*
8075 				 * No more multirt route to resolve; give up
8076 				 * (all routes resolved or no more
8077 				 * resolvable routes).
8078 				 */
8079 				if (ire != NULL) {
8080 					ire_refrele(ire);
8081 					ire = NULL;
8082 				}
8083 			} else {
8084 				ASSERT(sire != NULL);
8085 				ASSERT(ire != NULL);
8086 				/*
8087 				 * We simply use first_sire as a flag that
8088 				 * indicates if a resolvable multirt route
8089 				 * has already been found.
8090 				 * If it is not the case, we may have to send
8091 				 * an ICMP error to report that the
8092 				 * destination is unreachable.
8093 				 * We do not IRE_REFHOLD first_sire.
8094 				 */
8095 				if (first_sire == NULL) {
8096 					first_sire = sire;
8097 				}
8098 			}
8099 		}
8100 		if (ire == NULL) {
8101 			if (ip_debug > 3) {
8102 				/* ip2dbg */
8103 				pr_addr_dbg("ip_newroute: "
8104 				    "can't resolve %s\n", AF_INET, &dst);
8105 			}
8106 			ip3dbg(("ip_newroute: "
8107 			    "ire %p, sire %p, first_sire %p\n",
8108 			    (void *)ire, (void *)sire, (void *)first_sire));
8109 
8110 			if (sire != NULL) {
8111 				ire_refrele(sire);
8112 				sire = NULL;
8113 			}
8114 
8115 			if (first_sire != NULL) {
8116 				/*
8117 				 * At least one multirt route has been found
8118 				 * in the same call to ip_newroute();
8119 				 * there is no need to report an ICMP error.
8120 				 * first_sire was not IRE_REFHOLDed.
8121 				 */
8122 				MULTIRT_DEBUG_UNTAG(first_mp);
8123 				freemsg(first_mp);
8124 				return;
8125 			}
8126 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8127 			    RTA_DST, ipst);
8128 			if (attach_ill != NULL)
8129 				ill_refrele(attach_ill);
8130 			goto icmp_err_ret;
8131 		}
8132 
8133 		/*
8134 		 * Verify that the returned IRE does not have either
8135 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8136 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8137 		 */
8138 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8139 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8140 			if (attach_ill != NULL)
8141 				ill_refrele(attach_ill);
8142 			goto icmp_err_ret;
8143 		}
8144 		/*
8145 		 * Increment the ire_ob_pkt_count field for ire if it is an
8146 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8147 		 * increment the same for the parent IRE, sire, if it is some
8148 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8149 		 */
8150 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8151 			UPDATE_OB_PKT_COUNT(ire);
8152 			ire->ire_last_used_time = lbolt;
8153 		}
8154 
8155 		if (sire != NULL) {
8156 			gw = sire->ire_gateway_addr;
8157 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8158 			    IRE_INTERFACE)) == 0);
8159 			UPDATE_OB_PKT_COUNT(sire);
8160 			sire->ire_last_used_time = lbolt;
8161 		}
8162 		/*
8163 		 * We have a route to reach the destination.
8164 		 *
8165 		 * 1) If the interface is part of ill group, try to get a new
8166 		 *    ill taking load spreading into account.
8167 		 *
8168 		 * 2) After selecting the ill, get a source address that
8169 		 *    might create good inbound load spreading.
8170 		 *    ipif_select_source does this for us.
8171 		 *
8172 		 * If the application specified the ill (ifindex), we still
8173 		 * load spread. Only if the packets needs to go out
8174 		 * specifically on a given ill e.g. binding to
8175 		 * IPIF_NOFAILOVER address, then we don't try to use a
8176 		 * different ill for load spreading.
8177 		 */
8178 		if (attach_ill == NULL) {
8179 			/*
8180 			 * Don't perform outbound load spreading in the
8181 			 * case of an RTF_MULTIRT route, as we actually
8182 			 * typically want to replicate outgoing packets
8183 			 * through particular interfaces.
8184 			 */
8185 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8186 				dst_ill = ire->ire_ipif->ipif_ill;
8187 				/* for uniformity */
8188 				ill_refhold(dst_ill);
8189 			} else {
8190 				/*
8191 				 * If we are here trying to create an IRE_CACHE
8192 				 * for an offlink destination and have the
8193 				 * IRE_CACHE for the next hop and the latter is
8194 				 * using virtual IP source address selection i.e
8195 				 * it's ire->ire_ipif is pointing to a virtual
8196 				 * network interface (vni) then
8197 				 * ip_newroute_get_dst_ll() will return the vni
8198 				 * interface as the dst_ill. Since the vni is
8199 				 * virtual i.e not associated with any physical
8200 				 * interface, it cannot be the dst_ill, hence
8201 				 * in such a case call ip_newroute_get_dst_ll()
8202 				 * with the stq_ill instead of the ire_ipif ILL.
8203 				 * The function returns a refheld ill.
8204 				 */
8205 				if ((ire->ire_type == IRE_CACHE) &&
8206 				    IS_VNI(ire->ire_ipif->ipif_ill))
8207 					dst_ill = ip_newroute_get_dst_ill(
8208 					    ire->ire_stq->q_ptr);
8209 				else
8210 					dst_ill = ip_newroute_get_dst_ill(
8211 					    ire->ire_ipif->ipif_ill);
8212 			}
8213 			if (dst_ill == NULL) {
8214 				if (ip_debug > 2) {
8215 					pr_addr_dbg("ip_newroute: "
8216 					    "no dst ill for dst"
8217 					    " %s\n", AF_INET, &dst);
8218 				}
8219 				goto icmp_err_ret;
8220 			}
8221 		} else {
8222 			dst_ill = ire->ire_ipif->ipif_ill;
8223 			/* for uniformity */
8224 			ill_refhold(dst_ill);
8225 			/*
8226 			 * We should have found a route matching ill as we
8227 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8228 			 * Rather than asserting, when there is a mismatch,
8229 			 * we just drop the packet.
8230 			 */
8231 			if (dst_ill != attach_ill) {
8232 				ip0dbg(("ip_newroute: Packet dropped as "
8233 				    "IPIF_NOFAILOVER ill is %s, "
8234 				    "ire->ire_ipif->ipif_ill is %s\n",
8235 				    attach_ill->ill_name,
8236 				    dst_ill->ill_name));
8237 				ill_refrele(attach_ill);
8238 				goto icmp_err_ret;
8239 			}
8240 		}
8241 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8242 		if (attach_ill != NULL) {
8243 			ill_refrele(attach_ill);
8244 			attach_ill = NULL;
8245 			do_attach_ill = B_TRUE;
8246 		}
8247 		ASSERT(dst_ill != NULL);
8248 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8249 
8250 		/*
8251 		 * Pick the best source address from dst_ill.
8252 		 *
8253 		 * 1) If it is part of a multipathing group, we would
8254 		 *    like to spread the inbound packets across different
8255 		 *    interfaces. ipif_select_source picks a random source
8256 		 *    across the different ills in the group.
8257 		 *
8258 		 * 2) If it is not part of a multipathing group, we try
8259 		 *    to pick the source address from the destination
8260 		 *    route. Clustering assumes that when we have multiple
8261 		 *    prefixes hosted on an interface, the prefix of the
8262 		 *    source address matches the prefix of the destination
8263 		 *    route. We do this only if the address is not
8264 		 *    DEPRECATED.
8265 		 *
8266 		 * 3) If the conn is in a different zone than the ire, we
8267 		 *    need to pick a source address from the right zone.
8268 		 *
8269 		 * NOTE : If we hit case (1) above, the prefix of the source
8270 		 *	  address picked may not match the prefix of the
8271 		 *	  destination routes prefix as ipif_select_source
8272 		 *	  does not look at "dst" while picking a source
8273 		 *	  address.
8274 		 *	  If we want the same behavior as (2), we will need
8275 		 *	  to change the behavior of ipif_select_source.
8276 		 */
8277 		ASSERT(src_ipif == NULL);
8278 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8279 			/*
8280 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8281 			 * Check that the ipif matching the requested source
8282 			 * address still exists.
8283 			 */
8284 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8285 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8286 		}
8287 		if (src_ipif == NULL) {
8288 			ire_marks |= IRE_MARK_USESRC_CHECK;
8289 			if ((dst_ill->ill_group != NULL) ||
8290 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8291 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8292 			    ire->ire_zoneid != ALL_ZONES) ||
8293 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8294 				/*
8295 				 * If the destination is reachable via a
8296 				 * given gateway, the selected source address
8297 				 * should be in the same subnet as the gateway.
8298 				 * Otherwise, the destination is not reachable.
8299 				 *
8300 				 * If there are no interfaces on the same subnet
8301 				 * as the destination, ipif_select_source gives
8302 				 * first non-deprecated interface which might be
8303 				 * on a different subnet than the gateway.
8304 				 * This is not desirable. Hence pass the dst_ire
8305 				 * source address to ipif_select_source.
8306 				 * It is sure that the destination is reachable
8307 				 * with the dst_ire source address subnet.
8308 				 * So passing dst_ire source address to
8309 				 * ipif_select_source will make sure that the
8310 				 * selected source will be on the same subnet
8311 				 * as dst_ire source address.
8312 				 */
8313 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8314 				src_ipif = ipif_select_source(dst_ill, saddr,
8315 				    zoneid);
8316 				if (src_ipif == NULL) {
8317 					if (ip_debug > 2) {
8318 						pr_addr_dbg("ip_newroute: "
8319 						    "no src for dst %s ",
8320 						    AF_INET, &dst);
8321 						printf("through interface %s\n",
8322 						    dst_ill->ill_name);
8323 					}
8324 					goto icmp_err_ret;
8325 				}
8326 			} else {
8327 				src_ipif = ire->ire_ipif;
8328 				ASSERT(src_ipif != NULL);
8329 				/* hold src_ipif for uniformity */
8330 				ipif_refhold(src_ipif);
8331 			}
8332 		}
8333 
8334 		/*
8335 		 * Assign a source address while we have the conn.
8336 		 * We can't have ip_wput_ire pick a source address when the
8337 		 * packet returns from arp since we need to look at
8338 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8339 		 * going through arp.
8340 		 *
8341 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8342 		 *	  it uses ip6i to store this information.
8343 		 */
8344 		if (ipha->ipha_src == INADDR_ANY &&
8345 		    (connp == NULL || !connp->conn_unspec_src)) {
8346 			ipha->ipha_src = src_ipif->ipif_src_addr;
8347 		}
8348 		if (ip_debug > 3) {
8349 			/* ip2dbg */
8350 			pr_addr_dbg("ip_newroute: first hop %s\n",
8351 			    AF_INET, &gw);
8352 		}
8353 		ip2dbg(("\tire type %s (%d)\n",
8354 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8355 
8356 		/*
8357 		 * The TTL of multirouted packets is bounded by the
8358 		 * ip_multirt_ttl ndd variable.
8359 		 */
8360 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8361 			/* Force TTL of multirouted packets */
8362 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8363 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8364 				ip2dbg(("ip_newroute: forcing multirt TTL "
8365 				    "to %d (was %d), dst 0x%08x\n",
8366 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8367 				    ntohl(sire->ire_addr)));
8368 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8369 			}
8370 		}
8371 		/*
8372 		 * At this point in ip_newroute(), ire is either the
8373 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8374 		 * destination or an IRE_INTERFACE type that should be used
8375 		 * to resolve an on-subnet destination or an on-subnet
8376 		 * next-hop gateway.
8377 		 *
8378 		 * In the IRE_CACHE case, we have the following :
8379 		 *
8380 		 * 1) src_ipif - used for getting a source address.
8381 		 *
8382 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8383 		 *    means packets using this IRE_CACHE will go out on
8384 		 *    dst_ill.
8385 		 *
8386 		 * 3) The IRE sire will point to the prefix that is the
8387 		 *    longest  matching route for the destination. These
8388 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8389 		 *
8390 		 *    The newly created IRE_CACHE entry for the off-subnet
8391 		 *    destination is tied to both the prefix route and the
8392 		 *    interface route used to resolve the next-hop gateway
8393 		 *    via the ire_phandle and ire_ihandle fields,
8394 		 *    respectively.
8395 		 *
8396 		 * In the IRE_INTERFACE case, we have the following :
8397 		 *
8398 		 * 1) src_ipif - used for getting a source address.
8399 		 *
8400 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8401 		 *    means packets using the IRE_CACHE that we will build
8402 		 *    here will go out on dst_ill.
8403 		 *
8404 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8405 		 *    to be created will only be tied to the IRE_INTERFACE
8406 		 *    that was derived from the ire_ihandle field.
8407 		 *
8408 		 *    If sire is non-NULL, it means the destination is
8409 		 *    off-link and we will first create the IRE_CACHE for the
8410 		 *    gateway. Next time through ip_newroute, we will create
8411 		 *    the IRE_CACHE for the final destination as described
8412 		 *    above.
8413 		 *
8414 		 * In both cases, after the current resolution has been
8415 		 * completed (or possibly initialised, in the IRE_INTERFACE
8416 		 * case), the loop may be re-entered to attempt the resolution
8417 		 * of another RTF_MULTIRT route.
8418 		 *
8419 		 * When an IRE_CACHE entry for the off-subnet destination is
8420 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8421 		 * for further processing in emission loops.
8422 		 */
8423 		save_ire = ire;
8424 		switch (ire->ire_type) {
8425 		case IRE_CACHE: {
8426 			ire_t	*ipif_ire;
8427 
8428 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8429 			if (gw == 0)
8430 				gw = ire->ire_gateway_addr;
8431 			/*
8432 			 * We need 3 ire's to create a new cache ire for an
8433 			 * off-link destination from the cache ire of the
8434 			 * gateway.
8435 			 *
8436 			 *	1. The prefix ire 'sire' (Note that this does
8437 			 *	   not apply to the conn_nexthop_set case)
8438 			 *	2. The cache ire of the gateway 'ire'
8439 			 *	3. The interface ire 'ipif_ire'
8440 			 *
8441 			 * We have (1) and (2). We lookup (3) below.
8442 			 *
8443 			 * If there is no interface route to the gateway,
8444 			 * it is a race condition, where we found the cache
8445 			 * but the interface route has been deleted.
8446 			 */
8447 			if (ip_nexthop) {
8448 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8449 			} else {
8450 				ipif_ire =
8451 				    ire_ihandle_lookup_offlink(ire, sire);
8452 			}
8453 			if (ipif_ire == NULL) {
8454 				ip1dbg(("ip_newroute: "
8455 				    "ire_ihandle_lookup_offlink failed\n"));
8456 				goto icmp_err_ret;
8457 			}
8458 
8459 			/*
8460 			 * Check cached gateway IRE for any security
8461 			 * attributes; if found, associate the gateway
8462 			 * credentials group to the destination IRE.
8463 			 */
8464 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8465 				mutex_enter(&attrp->igsa_lock);
8466 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8467 					GCGRP_REFHOLD(gcgrp);
8468 				mutex_exit(&attrp->igsa_lock);
8469 			}
8470 
8471 			/*
8472 			 * XXX For the source of the resolver mp,
8473 			 * we are using the same DL_UNITDATA_REQ
8474 			 * (from save_ire->ire_nce->nce_res_mp)
8475 			 * though the save_ire is not pointing at the same ill.
8476 			 * This is incorrect. We need to send it up to the
8477 			 * resolver to get the right res_mp. For ethernets
8478 			 * this may be okay (ill_type == DL_ETHER).
8479 			 */
8480 
8481 			ire = ire_create(
8482 			    (uchar_t *)&dst,		/* dest address */
8483 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8484 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8485 			    (uchar_t *)&gw,		/* gateway address */
8486 			    &save_ire->ire_max_frag,
8487 			    save_ire->ire_nce,		/* src nce */
8488 			    dst_ill->ill_rq,		/* recv-from queue */
8489 			    dst_ill->ill_wq,		/* send-to queue */
8490 			    IRE_CACHE,			/* IRE type */
8491 			    src_ipif,
8492 			    (sire != NULL) ?
8493 			    sire->ire_mask : 0, 	/* Parent mask */
8494 			    (sire != NULL) ?
8495 			    sire->ire_phandle : 0,	/* Parent handle */
8496 			    ipif_ire->ire_ihandle,	/* Interface handle */
8497 			    (sire != NULL) ? (sire->ire_flags &
8498 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8499 			    (sire != NULL) ?
8500 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8501 			    NULL,
8502 			    gcgrp,
8503 			    ipst);
8504 
8505 			if (ire == NULL) {
8506 				if (gcgrp != NULL) {
8507 					GCGRP_REFRELE(gcgrp);
8508 					gcgrp = NULL;
8509 				}
8510 				ire_refrele(ipif_ire);
8511 				ire_refrele(save_ire);
8512 				break;
8513 			}
8514 
8515 			/* reference now held by IRE */
8516 			gcgrp = NULL;
8517 
8518 			ire->ire_marks |= ire_marks;
8519 
8520 			/*
8521 			 * Prevent sire and ipif_ire from getting deleted.
8522 			 * The newly created ire is tied to both of them via
8523 			 * the phandle and ihandle respectively.
8524 			 */
8525 			if (sire != NULL) {
8526 				IRB_REFHOLD(sire->ire_bucket);
8527 				/* Has it been removed already ? */
8528 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8529 					IRB_REFRELE(sire->ire_bucket);
8530 					ire_refrele(ipif_ire);
8531 					ire_refrele(save_ire);
8532 					break;
8533 				}
8534 			}
8535 
8536 			IRB_REFHOLD(ipif_ire->ire_bucket);
8537 			/* Has it been removed already ? */
8538 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8539 				IRB_REFRELE(ipif_ire->ire_bucket);
8540 				if (sire != NULL)
8541 					IRB_REFRELE(sire->ire_bucket);
8542 				ire_refrele(ipif_ire);
8543 				ire_refrele(save_ire);
8544 				break;
8545 			}
8546 
8547 			xmit_mp = first_mp;
8548 			/*
8549 			 * In the case of multirouting, a copy
8550 			 * of the packet is done before its sending.
8551 			 * The copy is used to attempt another
8552 			 * route resolution, in a next loop.
8553 			 */
8554 			if (ire->ire_flags & RTF_MULTIRT) {
8555 				copy_mp = copymsg(first_mp);
8556 				if (copy_mp != NULL) {
8557 					xmit_mp = copy_mp;
8558 					MULTIRT_DEBUG_TAG(first_mp);
8559 				}
8560 			}
8561 			ire_add_then_send(q, ire, xmit_mp);
8562 			ire_refrele(save_ire);
8563 
8564 			/* Assert that sire is not deleted yet. */
8565 			if (sire != NULL) {
8566 				ASSERT(sire->ire_ptpn != NULL);
8567 				IRB_REFRELE(sire->ire_bucket);
8568 			}
8569 
8570 			/* Assert that ipif_ire is not deleted yet. */
8571 			ASSERT(ipif_ire->ire_ptpn != NULL);
8572 			IRB_REFRELE(ipif_ire->ire_bucket);
8573 			ire_refrele(ipif_ire);
8574 
8575 			/*
8576 			 * If copy_mp is not NULL, multirouting was
8577 			 * requested. We loop to initiate a next
8578 			 * route resolution attempt, starting from sire.
8579 			 */
8580 			if (copy_mp != NULL) {
8581 				/*
8582 				 * Search for the next unresolved
8583 				 * multirt route.
8584 				 */
8585 				copy_mp = NULL;
8586 				ipif_ire = NULL;
8587 				ire = NULL;
8588 				multirt_resolve_next = B_TRUE;
8589 				continue;
8590 			}
8591 			if (sire != NULL)
8592 				ire_refrele(sire);
8593 			ipif_refrele(src_ipif);
8594 			ill_refrele(dst_ill);
8595 			return;
8596 		}
8597 		case IRE_IF_NORESOLVER: {
8598 
8599 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8600 			    dst_ill->ill_resolver_mp == NULL) {
8601 				ip1dbg(("ip_newroute: dst_ill %p "
8602 				    "for IRE_IF_NORESOLVER ire %p has "
8603 				    "no ill_resolver_mp\n",
8604 				    (void *)dst_ill, (void *)ire));
8605 				break;
8606 			}
8607 
8608 			/*
8609 			 * TSol note: We are creating the ire cache for the
8610 			 * destination 'dst'. If 'dst' is offlink, going
8611 			 * through the first hop 'gw', the security attributes
8612 			 * of 'dst' must be set to point to the gateway
8613 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8614 			 * is possible that 'dst' is a potential gateway that is
8615 			 * referenced by some route that has some security
8616 			 * attributes. Thus in the former case, we need to do a
8617 			 * gcgrp_lookup of 'gw' while in the latter case we
8618 			 * need to do gcgrp_lookup of 'dst' itself.
8619 			 */
8620 			ga.ga_af = AF_INET;
8621 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8622 			    &ga.ga_addr);
8623 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8624 
8625 			ire = ire_create(
8626 			    (uchar_t *)&dst,		/* dest address */
8627 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8628 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8629 			    (uchar_t *)&gw,		/* gateway address */
8630 			    &save_ire->ire_max_frag,
8631 			    NULL,			/* no src nce */
8632 			    dst_ill->ill_rq,		/* recv-from queue */
8633 			    dst_ill->ill_wq,		/* send-to queue */
8634 			    IRE_CACHE,
8635 			    src_ipif,
8636 			    save_ire->ire_mask,		/* Parent mask */
8637 			    (sire != NULL) ?		/* Parent handle */
8638 			    sire->ire_phandle : 0,
8639 			    save_ire->ire_ihandle,	/* Interface handle */
8640 			    (sire != NULL) ? sire->ire_flags &
8641 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8642 			    &(save_ire->ire_uinfo),
8643 			    NULL,
8644 			    gcgrp,
8645 			    ipst);
8646 
8647 			if (ire == NULL) {
8648 				if (gcgrp != NULL) {
8649 					GCGRP_REFRELE(gcgrp);
8650 					gcgrp = NULL;
8651 				}
8652 				ire_refrele(save_ire);
8653 				break;
8654 			}
8655 
8656 			/* reference now held by IRE */
8657 			gcgrp = NULL;
8658 
8659 			ire->ire_marks |= ire_marks;
8660 
8661 			/* Prevent save_ire from getting deleted */
8662 			IRB_REFHOLD(save_ire->ire_bucket);
8663 			/* Has it been removed already ? */
8664 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8665 				IRB_REFRELE(save_ire->ire_bucket);
8666 				ire_refrele(save_ire);
8667 				break;
8668 			}
8669 
8670 			/*
8671 			 * In the case of multirouting, a copy
8672 			 * of the packet is made before it is sent.
8673 			 * The copy is used in the next
8674 			 * loop to attempt another resolution.
8675 			 */
8676 			xmit_mp = first_mp;
8677 			if ((sire != NULL) &&
8678 			    (sire->ire_flags & RTF_MULTIRT)) {
8679 				copy_mp = copymsg(first_mp);
8680 				if (copy_mp != NULL) {
8681 					xmit_mp = copy_mp;
8682 					MULTIRT_DEBUG_TAG(first_mp);
8683 				}
8684 			}
8685 			ire_add_then_send(q, ire, xmit_mp);
8686 
8687 			/* Assert that it is not deleted yet. */
8688 			ASSERT(save_ire->ire_ptpn != NULL);
8689 			IRB_REFRELE(save_ire->ire_bucket);
8690 			ire_refrele(save_ire);
8691 
8692 			if (copy_mp != NULL) {
8693 				/*
8694 				 * If we found a (no)resolver, we ignore any
8695 				 * trailing top priority IRE_CACHE in further
8696 				 * loops. This ensures that we do not omit any
8697 				 * (no)resolver.
8698 				 * This IRE_CACHE, if any, will be processed
8699 				 * by another thread entering ip_newroute().
8700 				 * IRE_CACHE entries, if any, will be processed
8701 				 * by another thread entering ip_newroute(),
8702 				 * (upon resolver response, for instance).
8703 				 * This aims to force parallel multirt
8704 				 * resolutions as soon as a packet must be sent.
8705 				 * In the best case, after the tx of only one
8706 				 * packet, all reachable routes are resolved.
8707 				 * Otherwise, the resolution of all RTF_MULTIRT
8708 				 * routes would require several emissions.
8709 				 */
8710 				multirt_flags &= ~MULTIRT_CACHEGW;
8711 
8712 				/*
8713 				 * Search for the next unresolved multirt
8714 				 * route.
8715 				 */
8716 				copy_mp = NULL;
8717 				save_ire = NULL;
8718 				ire = NULL;
8719 				multirt_resolve_next = B_TRUE;
8720 				continue;
8721 			}
8722 
8723 			/*
8724 			 * Don't need sire anymore
8725 			 */
8726 			if (sire != NULL)
8727 				ire_refrele(sire);
8728 
8729 			ipif_refrele(src_ipif);
8730 			ill_refrele(dst_ill);
8731 			return;
8732 		}
8733 		case IRE_IF_RESOLVER:
8734 			/*
8735 			 * We can't build an IRE_CACHE yet, but at least we
8736 			 * found a resolver that can help.
8737 			 */
8738 			res_mp = dst_ill->ill_resolver_mp;
8739 			if (!OK_RESOLVER_MP(res_mp))
8740 				break;
8741 
8742 			/*
8743 			 * To be at this point in the code with a non-zero gw
8744 			 * means that dst is reachable through a gateway that
8745 			 * we have never resolved.  By changing dst to the gw
8746 			 * addr we resolve the gateway first.
8747 			 * When ire_add_then_send() tries to put the IP dg
8748 			 * to dst, it will reenter ip_newroute() at which
8749 			 * time we will find the IRE_CACHE for the gw and
8750 			 * create another IRE_CACHE in case IRE_CACHE above.
8751 			 */
8752 			if (gw != INADDR_ANY) {
8753 				/*
8754 				 * The source ipif that was determined above was
8755 				 * relative to the destination address, not the
8756 				 * gateway's. If src_ipif was not taken out of
8757 				 * the IRE_IF_RESOLVER entry, we'll need to call
8758 				 * ipif_select_source() again.
8759 				 */
8760 				if (src_ipif != ire->ire_ipif) {
8761 					ipif_refrele(src_ipif);
8762 					src_ipif = ipif_select_source(dst_ill,
8763 					    gw, zoneid);
8764 					if (src_ipif == NULL) {
8765 						if (ip_debug > 2) {
8766 							pr_addr_dbg(
8767 							    "ip_newroute: no "
8768 							    "src for gw %s ",
8769 							    AF_INET, &gw);
8770 							printf("through "
8771 							    "interface %s\n",
8772 							    dst_ill->ill_name);
8773 						}
8774 						goto icmp_err_ret;
8775 					}
8776 				}
8777 				save_dst = dst;
8778 				dst = gw;
8779 				gw = INADDR_ANY;
8780 			}
8781 
8782 			/*
8783 			 * We obtain a partial IRE_CACHE which we will pass
8784 			 * along with the resolver query.  When the response
8785 			 * comes back it will be there ready for us to add.
8786 			 * The ire_max_frag is atomically set under the
8787 			 * irebucket lock in ire_add_v[46].
8788 			 */
8789 
8790 			ire = ire_create_mp(
8791 			    (uchar_t *)&dst,		/* dest address */
8792 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8793 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8794 			    (uchar_t *)&gw,		/* gateway address */
8795 			    NULL,			/* ire_max_frag */
8796 			    NULL,			/* no src nce */
8797 			    dst_ill->ill_rq,		/* recv-from queue */
8798 			    dst_ill->ill_wq,		/* send-to queue */
8799 			    IRE_CACHE,
8800 			    src_ipif,			/* Interface ipif */
8801 			    save_ire->ire_mask,		/* Parent mask */
8802 			    0,
8803 			    save_ire->ire_ihandle,	/* Interface handle */
8804 			    0,				/* flags if any */
8805 			    &(save_ire->ire_uinfo),
8806 			    NULL,
8807 			    NULL,
8808 			    ipst);
8809 
8810 			if (ire == NULL) {
8811 				ire_refrele(save_ire);
8812 				break;
8813 			}
8814 
8815 			if ((sire != NULL) &&
8816 			    (sire->ire_flags & RTF_MULTIRT)) {
8817 				copy_mp = copymsg(first_mp);
8818 				if (copy_mp != NULL)
8819 					MULTIRT_DEBUG_TAG(copy_mp);
8820 			}
8821 
8822 			ire->ire_marks |= ire_marks;
8823 
8824 			/*
8825 			 * Construct message chain for the resolver
8826 			 * of the form:
8827 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8828 			 * Packet could contain a IPSEC_OUT mp.
8829 			 *
8830 			 * NOTE : ire will be added later when the response
8831 			 * comes back from ARP. If the response does not
8832 			 * come back, ARP frees the packet. For this reason,
8833 			 * we can't REFHOLD the bucket of save_ire to prevent
8834 			 * deletions. We may not be able to REFRELE the bucket
8835 			 * if the response never comes back. Thus, before
8836 			 * adding the ire, ire_add_v4 will make sure that the
8837 			 * interface route does not get deleted. This is the
8838 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8839 			 * where we can always prevent deletions because of
8840 			 * the synchronous nature of adding IRES i.e
8841 			 * ire_add_then_send is called after creating the IRE.
8842 			 */
8843 			ASSERT(ire->ire_mp != NULL);
8844 			ire->ire_mp->b_cont = first_mp;
8845 			/* Have saved_mp handy, for cleanup if canput fails */
8846 			saved_mp = mp;
8847 			mp = copyb(res_mp);
8848 			if (mp == NULL) {
8849 				/* Prepare for cleanup */
8850 				mp = saved_mp; /* pkt */
8851 				ire_delete(ire); /* ire_mp */
8852 				ire = NULL;
8853 				ire_refrele(save_ire);
8854 				if (copy_mp != NULL) {
8855 					MULTIRT_DEBUG_UNTAG(copy_mp);
8856 					freemsg(copy_mp);
8857 					copy_mp = NULL;
8858 				}
8859 				break;
8860 			}
8861 			linkb(mp, ire->ire_mp);
8862 
8863 			/*
8864 			 * Fill in the source and dest addrs for the resolver.
8865 			 * NOTE: this depends on memory layouts imposed by
8866 			 * ill_init().
8867 			 */
8868 			areq = (areq_t *)mp->b_rptr;
8869 			addrp = (ipaddr_t *)((char *)areq +
8870 			    areq->areq_sender_addr_offset);
8871 			if (do_attach_ill) {
8872 				/*
8873 				 * This is bind to no failover case.
8874 				 * arp packet also must go out on attach_ill.
8875 				 */
8876 				ASSERT(ipha->ipha_src != NULL);
8877 				*addrp = ipha->ipha_src;
8878 			} else {
8879 				*addrp = save_ire->ire_src_addr;
8880 			}
8881 
8882 			ire_refrele(save_ire);
8883 			addrp = (ipaddr_t *)((char *)areq +
8884 			    areq->areq_target_addr_offset);
8885 			*addrp = dst;
8886 			/* Up to the resolver. */
8887 			if (canputnext(dst_ill->ill_rq) &&
8888 			    !(dst_ill->ill_arp_closing)) {
8889 				putnext(dst_ill->ill_rq, mp);
8890 				ire = NULL;
8891 				if (copy_mp != NULL) {
8892 					/*
8893 					 * If we found a resolver, we ignore
8894 					 * any trailing top priority IRE_CACHE
8895 					 * in the further loops. This ensures
8896 					 * that we do not omit any resolver.
8897 					 * IRE_CACHE entries, if any, will be
8898 					 * processed next time we enter
8899 					 * ip_newroute().
8900 					 */
8901 					multirt_flags &= ~MULTIRT_CACHEGW;
8902 					/*
8903 					 * Search for the next unresolved
8904 					 * multirt route.
8905 					 */
8906 					first_mp = copy_mp;
8907 					copy_mp = NULL;
8908 					/* Prepare the next resolution loop. */
8909 					mp = first_mp;
8910 					EXTRACT_PKT_MP(mp, first_mp,
8911 					    mctl_present);
8912 					if (mctl_present)
8913 						io = (ipsec_out_t *)
8914 						    first_mp->b_rptr;
8915 					ipha = (ipha_t *)mp->b_rptr;
8916 
8917 					ASSERT(sire != NULL);
8918 
8919 					dst = save_dst;
8920 					multirt_resolve_next = B_TRUE;
8921 					continue;
8922 				}
8923 
8924 				if (sire != NULL)
8925 					ire_refrele(sire);
8926 
8927 				/*
8928 				 * The response will come back in ip_wput
8929 				 * with db_type IRE_DB_TYPE.
8930 				 */
8931 				ipif_refrele(src_ipif);
8932 				ill_refrele(dst_ill);
8933 				return;
8934 			} else {
8935 				/* Prepare for cleanup */
8936 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8937 				    mp);
8938 				mp->b_cont = NULL;
8939 				freeb(mp); /* areq */
8940 				/*
8941 				 * this is an ire that is not added to the
8942 				 * cache. ire_freemblk will handle the release
8943 				 * of any resources associated with the ire.
8944 				 */
8945 				ire_delete(ire); /* ire_mp */
8946 				mp = saved_mp; /* pkt */
8947 				ire = NULL;
8948 				if (copy_mp != NULL) {
8949 					MULTIRT_DEBUG_UNTAG(copy_mp);
8950 					freemsg(copy_mp);
8951 					copy_mp = NULL;
8952 				}
8953 				break;
8954 			}
8955 		default:
8956 			break;
8957 		}
8958 	} while (multirt_resolve_next);
8959 
8960 	ip1dbg(("ip_newroute: dropped\n"));
8961 	/* Did this packet originate externally? */
8962 	if (mp->b_prev) {
8963 		mp->b_next = NULL;
8964 		mp->b_prev = NULL;
8965 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8966 	} else {
8967 		if (dst_ill != NULL) {
8968 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8969 		} else {
8970 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8971 		}
8972 	}
8973 	ASSERT(copy_mp == NULL);
8974 	MULTIRT_DEBUG_UNTAG(first_mp);
8975 	freemsg(first_mp);
8976 	if (ire != NULL)
8977 		ire_refrele(ire);
8978 	if (sire != NULL)
8979 		ire_refrele(sire);
8980 	if (src_ipif != NULL)
8981 		ipif_refrele(src_ipif);
8982 	if (dst_ill != NULL)
8983 		ill_refrele(dst_ill);
8984 	return;
8985 
8986 icmp_err_ret:
8987 	ip1dbg(("ip_newroute: no route\n"));
8988 	if (src_ipif != NULL)
8989 		ipif_refrele(src_ipif);
8990 	if (dst_ill != NULL)
8991 		ill_refrele(dst_ill);
8992 	if (sire != NULL)
8993 		ire_refrele(sire);
8994 	/* Did this packet originate externally? */
8995 	if (mp->b_prev) {
8996 		mp->b_next = NULL;
8997 		mp->b_prev = NULL;
8998 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8999 		q = WR(q);
9000 	} else {
9001 		/*
9002 		 * There is no outgoing ill, so just increment the
9003 		 * system MIB.
9004 		 */
9005 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9006 		/*
9007 		 * Since ip_wput() isn't close to finished, we fill
9008 		 * in enough of the header for credible error reporting.
9009 		 */
9010 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9011 			/* Failed */
9012 			MULTIRT_DEBUG_UNTAG(first_mp);
9013 			freemsg(first_mp);
9014 			if (ire != NULL)
9015 				ire_refrele(ire);
9016 			return;
9017 		}
9018 	}
9019 
9020 	/*
9021 	 * At this point we will have ire only if RTF_BLACKHOLE
9022 	 * or RTF_REJECT flags are set on the IRE. It will not
9023 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9024 	 */
9025 	if (ire != NULL) {
9026 		if (ire->ire_flags & RTF_BLACKHOLE) {
9027 			ire_refrele(ire);
9028 			MULTIRT_DEBUG_UNTAG(first_mp);
9029 			freemsg(first_mp);
9030 			return;
9031 		}
9032 		ire_refrele(ire);
9033 	}
9034 	if (ip_source_routed(ipha, ipst)) {
9035 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9036 		    zoneid, ipst);
9037 		return;
9038 	}
9039 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9040 }
9041 
9042 ip_opt_info_t zero_info;
9043 
9044 /*
9045  * IPv4 -
9046  * ip_newroute_ipif is called by ip_wput_multicast and
9047  * ip_rput_forward_multicast whenever we need to send
9048  * out a packet to a destination address for which we do not have specific
9049  * routing information. It is used when the packet will be sent out
9050  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9051  * socket option is set or icmp error message wants to go out on a particular
9052  * interface for a unicast packet.
9053  *
9054  * In most cases, the destination address is resolved thanks to the ipif
9055  * intrinsic resolver. However, there are some cases where the call to
9056  * ip_newroute_ipif must take into account the potential presence of
9057  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9058  * that uses the interface. This is specified through flags,
9059  * which can be a combination of:
9060  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9061  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9062  *   and flags. Additionally, the packet source address has to be set to
9063  *   the specified address. The caller is thus expected to set this flag
9064  *   if the packet has no specific source address yet.
9065  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9066  *   flag, the resulting ire will inherit the flag. All unresolved routes
9067  *   to the destination must be explored in the same call to
9068  *   ip_newroute_ipif().
9069  */
9070 static void
9071 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9072     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9073 {
9074 	areq_t	*areq;
9075 	ire_t	*ire = NULL;
9076 	mblk_t	*res_mp;
9077 	ipaddr_t *addrp;
9078 	mblk_t *first_mp;
9079 	ire_t	*save_ire = NULL;
9080 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9081 	ipif_t	*src_ipif = NULL;
9082 	ushort_t ire_marks = 0;
9083 	ill_t	*dst_ill = NULL;
9084 	boolean_t mctl_present;
9085 	ipsec_out_t *io;
9086 	ipha_t *ipha;
9087 	int	ihandle = 0;
9088 	mblk_t	*saved_mp;
9089 	ire_t   *fire = NULL;
9090 	mblk_t  *copy_mp = NULL;
9091 	boolean_t multirt_resolve_next;
9092 	ipaddr_t ipha_dst;
9093 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9094 
9095 	/*
9096 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9097 	 * here for uniformity
9098 	 */
9099 	ipif_refhold(ipif);
9100 
9101 	/*
9102 	 * This loop is run only once in most cases.
9103 	 * We loop to resolve further routes only when the destination
9104 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9105 	 */
9106 	do {
9107 		if (dst_ill != NULL) {
9108 			ill_refrele(dst_ill);
9109 			dst_ill = NULL;
9110 		}
9111 		if (src_ipif != NULL) {
9112 			ipif_refrele(src_ipif);
9113 			src_ipif = NULL;
9114 		}
9115 		multirt_resolve_next = B_FALSE;
9116 
9117 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9118 		    ipif->ipif_ill->ill_name));
9119 
9120 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9121 		if (mctl_present)
9122 			io = (ipsec_out_t *)first_mp->b_rptr;
9123 
9124 		ipha = (ipha_t *)mp->b_rptr;
9125 
9126 		/*
9127 		 * Save the packet destination address, we may need it after
9128 		 * the packet has been consumed.
9129 		 */
9130 		ipha_dst = ipha->ipha_dst;
9131 
9132 		/*
9133 		 * If the interface is a pt-pt interface we look for an
9134 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9135 		 * local_address and the pt-pt destination address. Otherwise
9136 		 * we just match the local address.
9137 		 * NOTE: dst could be different than ipha->ipha_dst in case
9138 		 * of sending igmp multicast packets over a point-to-point
9139 		 * connection.
9140 		 * Thus we must be careful enough to check ipha_dst to be a
9141 		 * multicast address, otherwise it will take xmit_if path for
9142 		 * multicast packets resulting into kernel stack overflow by
9143 		 * repeated calls to ip_newroute_ipif from ire_send().
9144 		 */
9145 		if (CLASSD(ipha_dst) &&
9146 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9147 			goto err_ret;
9148 		}
9149 
9150 		/*
9151 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9152 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9153 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9154 		 * propagate its flags to the new ire.
9155 		 */
9156 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9157 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9158 			ip2dbg(("ip_newroute_ipif: "
9159 			    "ipif_lookup_multi_ire("
9160 			    "ipif %p, dst %08x) = fire %p\n",
9161 			    (void *)ipif, ntohl(dst), (void *)fire));
9162 		}
9163 
9164 		if (mctl_present && io->ipsec_out_attach_if) {
9165 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9166 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9167 
9168 			/* Failure case frees things for us. */
9169 			if (attach_ill == NULL) {
9170 				ipif_refrele(ipif);
9171 				if (fire != NULL)
9172 					ire_refrele(fire);
9173 				return;
9174 			}
9175 
9176 			/*
9177 			 * Check if we need an ire that will not be
9178 			 * looked up by anybody else i.e. HIDDEN.
9179 			 */
9180 			if (ill_is_probeonly(attach_ill)) {
9181 				ire_marks = IRE_MARK_HIDDEN;
9182 			}
9183 			/*
9184 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9185 			 * case.
9186 			 */
9187 			dst_ill = ipif->ipif_ill;
9188 			/* attach_ill has been refheld by ip_grab_attach_ill */
9189 			ASSERT(dst_ill == attach_ill);
9190 		} else {
9191 			/*
9192 			 * If this is set by IP_XMIT_IF, then make sure that
9193 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9194 			 * specified ill.
9195 			 */
9196 			ASSERT((connp == NULL) ||
9197 			    (connp->conn_xmit_if_ill == NULL) ||
9198 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9199 			/*
9200 			 * If the interface belongs to an interface group,
9201 			 * make sure the next possible interface in the group
9202 			 * is used.  This encourages load spreading among
9203 			 * peers in an interface group.
9204 			 * Note: load spreading is disabled for RTF_MULTIRT
9205 			 * routes.
9206 			 */
9207 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9208 			    (fire->ire_flags & RTF_MULTIRT)) {
9209 				/*
9210 				 * Don't perform outbound load spreading
9211 				 * in the case of an RTF_MULTIRT issued route,
9212 				 * we actually typically want to replicate
9213 				 * outgoing packets through particular
9214 				 * interfaces.
9215 				 */
9216 				dst_ill = ipif->ipif_ill;
9217 				ill_refhold(dst_ill);
9218 			} else {
9219 				dst_ill = ip_newroute_get_dst_ill(
9220 				    ipif->ipif_ill);
9221 			}
9222 			if (dst_ill == NULL) {
9223 				if (ip_debug > 2) {
9224 					pr_addr_dbg("ip_newroute_ipif: "
9225 					    "no dst ill for dst %s\n",
9226 					    AF_INET, &dst);
9227 				}
9228 				goto err_ret;
9229 			}
9230 		}
9231 
9232 		/*
9233 		 * Pick a source address preferring non-deprecated ones.
9234 		 * Unlike ip_newroute, we don't do any source address
9235 		 * selection here since for multicast it really does not help
9236 		 * in inbound load spreading as in the unicast case.
9237 		 */
9238 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9239 		    (fire->ire_flags & RTF_SETSRC)) {
9240 			/*
9241 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9242 			 * on that interface. This ire has RTF_SETSRC flag, so
9243 			 * the source address of the packet must be changed.
9244 			 * Check that the ipif matching the requested source
9245 			 * address still exists.
9246 			 */
9247 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9248 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9249 		}
9250 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9251 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9252 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9253 		    (src_ipif == NULL)) {
9254 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9255 			if (src_ipif == NULL) {
9256 				if (ip_debug > 2) {
9257 					/* ip1dbg */
9258 					pr_addr_dbg("ip_newroute_ipif: "
9259 					    "no src for dst %s",
9260 					    AF_INET, &dst);
9261 				}
9262 				ip1dbg((" through interface %s\n",
9263 				    dst_ill->ill_name));
9264 				goto err_ret;
9265 			}
9266 			ipif_refrele(ipif);
9267 			ipif = src_ipif;
9268 			ipif_refhold(ipif);
9269 		}
9270 		if (src_ipif == NULL) {
9271 			src_ipif = ipif;
9272 			ipif_refhold(src_ipif);
9273 		}
9274 
9275 		/*
9276 		 * Assign a source address while we have the conn.
9277 		 * We can't have ip_wput_ire pick a source address when the
9278 		 * packet returns from arp since conn_unspec_src might be set
9279 		 * and we loose the conn when going through arp.
9280 		 */
9281 		if (ipha->ipha_src == INADDR_ANY &&
9282 		    (connp == NULL || !connp->conn_unspec_src)) {
9283 			ipha->ipha_src = src_ipif->ipif_src_addr;
9284 		}
9285 
9286 		/*
9287 		 * In the case of IP_XMIT_IF, it is possible that the
9288 		 * outgoing interface does not have an interface ire.
9289 		 */
9290 		if (CLASSD(ipha_dst) && (connp == NULL ||
9291 		    connp->conn_xmit_if_ill == NULL) &&
9292 		    infop->ip_opt_ill_index == 0) {
9293 			/* ipif_to_ire returns an held ire */
9294 			ire = ipif_to_ire(ipif);
9295 			if (ire == NULL)
9296 				goto err_ret;
9297 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9298 				goto err_ret;
9299 			/*
9300 			 * ihandle is needed when the ire is added to
9301 			 * cache table.
9302 			 */
9303 			save_ire = ire;
9304 			ihandle = save_ire->ire_ihandle;
9305 
9306 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9307 			    "flags %04x\n",
9308 			    (void *)ire, (void *)ipif, flags));
9309 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9310 			    (fire->ire_flags & RTF_MULTIRT)) {
9311 				/*
9312 				 * As requested by flags, an IRE_OFFSUBNET was
9313 				 * looked up on that interface. This ire has
9314 				 * RTF_MULTIRT flag, so the resolution loop will
9315 				 * be re-entered to resolve additional routes on
9316 				 * other interfaces. For that purpose, a copy of
9317 				 * the packet is performed at this point.
9318 				 */
9319 				fire->ire_last_used_time = lbolt;
9320 				copy_mp = copymsg(first_mp);
9321 				if (copy_mp) {
9322 					MULTIRT_DEBUG_TAG(copy_mp);
9323 				}
9324 			}
9325 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9326 			    (fire->ire_flags & RTF_SETSRC)) {
9327 				/*
9328 				 * As requested by flags, an IRE_OFFSUBET was
9329 				 * looked up on that interface. This ire has
9330 				 * RTF_SETSRC flag, so the source address of the
9331 				 * packet must be changed.
9332 				 */
9333 				ipha->ipha_src = fire->ire_src_addr;
9334 			}
9335 		} else {
9336 			ASSERT((connp == NULL) ||
9337 			    (connp->conn_xmit_if_ill != NULL) ||
9338 			    (connp->conn_dontroute) ||
9339 			    infop->ip_opt_ill_index != 0);
9340 			/*
9341 			 * The only ways we can come here are:
9342 			 * 1) IP_XMIT_IF socket option is set
9343 			 * 2) SO_DONTROUTE socket option is set
9344 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9345 			 * In all cases, the new ire will not be added
9346 			 * into cache table.
9347 			 */
9348 			ire_marks |= IRE_MARK_NOADD;
9349 		}
9350 
9351 		switch (ipif->ipif_net_type) {
9352 		case IRE_IF_NORESOLVER: {
9353 			/* We have what we need to build an IRE_CACHE. */
9354 
9355 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9356 			    (dst_ill->ill_resolver_mp == NULL)) {
9357 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9358 				    "for IRE_IF_NORESOLVER ire %p has "
9359 				    "no ill_resolver_mp\n",
9360 				    (void *)dst_ill, (void *)ire));
9361 				break;
9362 			}
9363 
9364 			/*
9365 			 * The new ire inherits the IRE_OFFSUBNET flags
9366 			 * and source address, if this was requested.
9367 			 */
9368 			ire = ire_create(
9369 			    (uchar_t *)&dst,		/* dest address */
9370 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9371 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9372 			    NULL,			/* gateway address */
9373 			    &ipif->ipif_mtu,
9374 			    NULL,			/* no src nce */
9375 			    dst_ill->ill_rq,		/* recv-from queue */
9376 			    dst_ill->ill_wq,		/* send-to queue */
9377 			    IRE_CACHE,
9378 			    src_ipif,
9379 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9380 			    (fire != NULL) ?		/* Parent handle */
9381 			    fire->ire_phandle : 0,
9382 			    ihandle,			/* Interface handle */
9383 			    (fire != NULL) ?
9384 			    (fire->ire_flags &
9385 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9386 			    (save_ire == NULL ? &ire_uinfo_null :
9387 			    &save_ire->ire_uinfo),
9388 			    NULL,
9389 			    NULL,
9390 			    ipst);
9391 
9392 			if (ire == NULL) {
9393 				if (save_ire != NULL)
9394 					ire_refrele(save_ire);
9395 				break;
9396 			}
9397 
9398 			ire->ire_marks |= ire_marks;
9399 
9400 			/*
9401 			 * If IRE_MARK_NOADD is set then we need to convert
9402 			 * the max_fragp to a useable value now. This is
9403 			 * normally done in ire_add_v[46]. We also need to
9404 			 * associate the ire with an nce (normally would be
9405 			 * done in ip_wput_nondata()).
9406 			 *
9407 			 * Note that IRE_MARK_NOADD packets created here
9408 			 * do not have a non-null ire_mp pointer. The null
9409 			 * value of ire_bucket indicates that they were
9410 			 * never added.
9411 			 */
9412 			if (ire->ire_marks & IRE_MARK_NOADD) {
9413 				uint_t  max_frag;
9414 
9415 				max_frag = *ire->ire_max_fragp;
9416 				ire->ire_max_fragp = NULL;
9417 				ire->ire_max_frag = max_frag;
9418 
9419 				if ((ire->ire_nce = ndp_lookup_v4(
9420 				    ire_to_ill(ire),
9421 				    (ire->ire_gateway_addr != INADDR_ANY ?
9422 				    &ire->ire_gateway_addr : &ire->ire_addr),
9423 				    B_FALSE)) == NULL) {
9424 					if (save_ire != NULL)
9425 						ire_refrele(save_ire);
9426 					break;
9427 				}
9428 				ASSERT(ire->ire_nce->nce_state ==
9429 				    ND_REACHABLE);
9430 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9431 			}
9432 
9433 			/* Prevent save_ire from getting deleted */
9434 			if (save_ire != NULL) {
9435 				IRB_REFHOLD(save_ire->ire_bucket);
9436 				/* Has it been removed already ? */
9437 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9438 					IRB_REFRELE(save_ire->ire_bucket);
9439 					ire_refrele(save_ire);
9440 					break;
9441 				}
9442 			}
9443 
9444 			ire_add_then_send(q, ire, first_mp);
9445 
9446 			/* Assert that save_ire is not deleted yet. */
9447 			if (save_ire != NULL) {
9448 				ASSERT(save_ire->ire_ptpn != NULL);
9449 				IRB_REFRELE(save_ire->ire_bucket);
9450 				ire_refrele(save_ire);
9451 				save_ire = NULL;
9452 			}
9453 			if (fire != NULL) {
9454 				ire_refrele(fire);
9455 				fire = NULL;
9456 			}
9457 
9458 			/*
9459 			 * the resolution loop is re-entered if this
9460 			 * was requested through flags and if we
9461 			 * actually are in a multirouting case.
9462 			 */
9463 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9464 				boolean_t need_resolve =
9465 				    ire_multirt_need_resolve(ipha_dst,
9466 				    MBLK_GETLABEL(copy_mp), ipst);
9467 				if (!need_resolve) {
9468 					MULTIRT_DEBUG_UNTAG(copy_mp);
9469 					freemsg(copy_mp);
9470 					copy_mp = NULL;
9471 				} else {
9472 					/*
9473 					 * ipif_lookup_group() calls
9474 					 * ire_lookup_multi() that uses
9475 					 * ire_ftable_lookup() to find
9476 					 * an IRE_INTERFACE for the group.
9477 					 * In the multirt case,
9478 					 * ire_lookup_multi() then invokes
9479 					 * ire_multirt_lookup() to find
9480 					 * the next resolvable ire.
9481 					 * As a result, we obtain an new
9482 					 * interface, derived from the
9483 					 * next ire.
9484 					 */
9485 					ipif_refrele(ipif);
9486 					ipif = ipif_lookup_group(ipha_dst,
9487 					    zoneid, ipst);
9488 					ip2dbg(("ip_newroute_ipif: "
9489 					    "multirt dst %08x, ipif %p\n",
9490 					    htonl(dst), (void *)ipif));
9491 					if (ipif != NULL) {
9492 						mp = copy_mp;
9493 						copy_mp = NULL;
9494 						multirt_resolve_next = B_TRUE;
9495 						continue;
9496 					} else {
9497 						freemsg(copy_mp);
9498 					}
9499 				}
9500 			}
9501 			if (ipif != NULL)
9502 				ipif_refrele(ipif);
9503 			ill_refrele(dst_ill);
9504 			ipif_refrele(src_ipif);
9505 			return;
9506 		}
9507 		case IRE_IF_RESOLVER:
9508 			/*
9509 			 * We can't build an IRE_CACHE yet, but at least
9510 			 * we found a resolver that can help.
9511 			 */
9512 			res_mp = dst_ill->ill_resolver_mp;
9513 			if (!OK_RESOLVER_MP(res_mp))
9514 				break;
9515 
9516 			/*
9517 			 * We obtain a partial IRE_CACHE which we will pass
9518 			 * along with the resolver query.  When the response
9519 			 * comes back it will be there ready for us to add.
9520 			 * The new ire inherits the IRE_OFFSUBNET flags
9521 			 * and source address, if this was requested.
9522 			 * The ire_max_frag is atomically set under the
9523 			 * irebucket lock in ire_add_v[46]. Only in the
9524 			 * case of IRE_MARK_NOADD, we set it here itself.
9525 			 */
9526 			ire = ire_create_mp(
9527 			    (uchar_t *)&dst,		/* dest address */
9528 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9529 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9530 			    NULL,			/* gateway address */
9531 			    (ire_marks & IRE_MARK_NOADD) ?
9532 			    ipif->ipif_mtu : 0,		/* max_frag */
9533 			    NULL,			/* no src nce */
9534 			    dst_ill->ill_rq,		/* recv-from queue */
9535 			    dst_ill->ill_wq,		/* send-to queue */
9536 			    IRE_CACHE,
9537 			    src_ipif,
9538 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9539 			    (fire != NULL) ?		/* Parent handle */
9540 			    fire->ire_phandle : 0,
9541 			    ihandle,			/* Interface handle */
9542 			    (fire != NULL) ?		/* flags if any */
9543 			    (fire->ire_flags &
9544 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9545 			    (save_ire == NULL ? &ire_uinfo_null :
9546 			    &save_ire->ire_uinfo),
9547 			    NULL,
9548 			    NULL,
9549 			    ipst);
9550 
9551 			if (save_ire != NULL) {
9552 				ire_refrele(save_ire);
9553 				save_ire = NULL;
9554 			}
9555 			if (ire == NULL)
9556 				break;
9557 
9558 			ire->ire_marks |= ire_marks;
9559 			/*
9560 			 * Construct message chain for the resolver of the
9561 			 * form:
9562 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9563 			 *
9564 			 * NOTE : ire will be added later when the response
9565 			 * comes back from ARP. If the response does not
9566 			 * come back, ARP frees the packet. For this reason,
9567 			 * we can't REFHOLD the bucket of save_ire to prevent
9568 			 * deletions. We may not be able to REFRELE the
9569 			 * bucket if the response never comes back.
9570 			 * Thus, before adding the ire, ire_add_v4 will make
9571 			 * sure that the interface route does not get deleted.
9572 			 * This is the only case unlike ip_newroute_v6,
9573 			 * ip_newroute_ipif_v6 where we can always prevent
9574 			 * deletions because ire_add_then_send is called after
9575 			 * creating the IRE.
9576 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9577 			 * does not add this IRE into the IRE CACHE.
9578 			 */
9579 			ASSERT(ire->ire_mp != NULL);
9580 			ire->ire_mp->b_cont = first_mp;
9581 			/* Have saved_mp handy, for cleanup if canput fails */
9582 			saved_mp = mp;
9583 			mp = copyb(res_mp);
9584 			if (mp == NULL) {
9585 				/* Prepare for cleanup */
9586 				mp = saved_mp; /* pkt */
9587 				ire_delete(ire); /* ire_mp */
9588 				ire = NULL;
9589 				if (copy_mp != NULL) {
9590 					MULTIRT_DEBUG_UNTAG(copy_mp);
9591 					freemsg(copy_mp);
9592 					copy_mp = NULL;
9593 				}
9594 				break;
9595 			}
9596 			linkb(mp, ire->ire_mp);
9597 
9598 			/*
9599 			 * Fill in the source and dest addrs for the resolver.
9600 			 * NOTE: this depends on memory layouts imposed by
9601 			 * ill_init().
9602 			 */
9603 			areq = (areq_t *)mp->b_rptr;
9604 			addrp = (ipaddr_t *)((char *)areq +
9605 			    areq->areq_sender_addr_offset);
9606 			*addrp = ire->ire_src_addr;
9607 			addrp = (ipaddr_t *)((char *)areq +
9608 			    areq->areq_target_addr_offset);
9609 			*addrp = dst;
9610 			/* Up to the resolver. */
9611 			if (canputnext(dst_ill->ill_rq) &&
9612 			    !(dst_ill->ill_arp_closing)) {
9613 				putnext(dst_ill->ill_rq, mp);
9614 				/*
9615 				 * The response will come back in ip_wput
9616 				 * with db_type IRE_DB_TYPE.
9617 				 */
9618 			} else {
9619 				mp->b_cont = NULL;
9620 				freeb(mp); /* areq */
9621 				ire_delete(ire); /* ire_mp */
9622 				saved_mp->b_next = NULL;
9623 				saved_mp->b_prev = NULL;
9624 				freemsg(first_mp); /* pkt */
9625 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9626 			}
9627 
9628 			if (fire != NULL) {
9629 				ire_refrele(fire);
9630 				fire = NULL;
9631 			}
9632 
9633 
9634 			/*
9635 			 * The resolution loop is re-entered if this was
9636 			 * requested through flags and we actually are
9637 			 * in a multirouting case.
9638 			 */
9639 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9640 				boolean_t need_resolve =
9641 				    ire_multirt_need_resolve(ipha_dst,
9642 				    MBLK_GETLABEL(copy_mp), ipst);
9643 				if (!need_resolve) {
9644 					MULTIRT_DEBUG_UNTAG(copy_mp);
9645 					freemsg(copy_mp);
9646 					copy_mp = NULL;
9647 				} else {
9648 					/*
9649 					 * ipif_lookup_group() calls
9650 					 * ire_lookup_multi() that uses
9651 					 * ire_ftable_lookup() to find
9652 					 * an IRE_INTERFACE for the group.
9653 					 * In the multirt case,
9654 					 * ire_lookup_multi() then invokes
9655 					 * ire_multirt_lookup() to find
9656 					 * the next resolvable ire.
9657 					 * As a result, we obtain an new
9658 					 * interface, derived from the
9659 					 * next ire.
9660 					 */
9661 					ipif_refrele(ipif);
9662 					ipif = ipif_lookup_group(ipha_dst,
9663 					    zoneid, ipst);
9664 					if (ipif != NULL) {
9665 						mp = copy_mp;
9666 						copy_mp = NULL;
9667 						multirt_resolve_next = B_TRUE;
9668 						continue;
9669 					} else {
9670 						freemsg(copy_mp);
9671 					}
9672 				}
9673 			}
9674 			if (ipif != NULL)
9675 				ipif_refrele(ipif);
9676 			ill_refrele(dst_ill);
9677 			ipif_refrele(src_ipif);
9678 			return;
9679 		default:
9680 			break;
9681 		}
9682 	} while (multirt_resolve_next);
9683 
9684 err_ret:
9685 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9686 	if (fire != NULL)
9687 		ire_refrele(fire);
9688 	ipif_refrele(ipif);
9689 	/* Did this packet originate externally? */
9690 	if (dst_ill != NULL)
9691 		ill_refrele(dst_ill);
9692 	if (src_ipif != NULL)
9693 		ipif_refrele(src_ipif);
9694 	if (mp->b_prev || mp->b_next) {
9695 		mp->b_next = NULL;
9696 		mp->b_prev = NULL;
9697 	} else {
9698 		/*
9699 		 * Since ip_wput() isn't close to finished, we fill
9700 		 * in enough of the header for credible error reporting.
9701 		 */
9702 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9703 			/* Failed */
9704 			freemsg(first_mp);
9705 			if (ire != NULL)
9706 				ire_refrele(ire);
9707 			return;
9708 		}
9709 	}
9710 	/*
9711 	 * At this point we will have ire only if RTF_BLACKHOLE
9712 	 * or RTF_REJECT flags are set on the IRE. It will not
9713 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9714 	 */
9715 	if (ire != NULL) {
9716 		if (ire->ire_flags & RTF_BLACKHOLE) {
9717 			ire_refrele(ire);
9718 			freemsg(first_mp);
9719 			return;
9720 		}
9721 		ire_refrele(ire);
9722 	}
9723 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9724 }
9725 
9726 /* Name/Value Table Lookup Routine */
9727 char *
9728 ip_nv_lookup(nv_t *nv, int value)
9729 {
9730 	if (!nv)
9731 		return (NULL);
9732 	for (; nv->nv_name; nv++) {
9733 		if (nv->nv_value == value)
9734 			return (nv->nv_name);
9735 	}
9736 	return ("unknown");
9737 }
9738 
9739 /*
9740  * This is a module open, i.e. this is a control stream for access
9741  * to a DLPI device.  We allocate an ill_t as the instance data in
9742  * this case.
9743  */
9744 int
9745 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9746 {
9747 	ill_t	*ill;
9748 	int	err;
9749 	zoneid_t zoneid;
9750 	netstack_t *ns;
9751 	ip_stack_t *ipst;
9752 
9753 	/*
9754 	 * Prevent unprivileged processes from pushing IP so that
9755 	 * they can't send raw IP.
9756 	 */
9757 	if (secpolicy_net_rawaccess(credp) != 0)
9758 		return (EPERM);
9759 
9760 	ns = netstack_find_by_cred(credp);
9761 	ASSERT(ns != NULL);
9762 	ipst = ns->netstack_ip;
9763 	ASSERT(ipst != NULL);
9764 
9765 	/*
9766 	 * For exclusive stacks we set the zoneid to zero
9767 	 * to make IP operate as if in the global zone.
9768 	 */
9769 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9770 		zoneid = GLOBAL_ZONEID;
9771 	else
9772 		zoneid = crgetzoneid(credp);
9773 
9774 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9775 	q->q_ptr = WR(q)->q_ptr = ill;
9776 	ill->ill_ipst = ipst;
9777 	ill->ill_zoneid = zoneid;
9778 
9779 	/*
9780 	 * ill_init initializes the ill fields and then sends down
9781 	 * down a DL_INFO_REQ after calling qprocson.
9782 	 */
9783 	err = ill_init(q, ill);
9784 	if (err != 0) {
9785 		mi_free(ill);
9786 		netstack_rele(ipst->ips_netstack);
9787 		q->q_ptr = NULL;
9788 		WR(q)->q_ptr = NULL;
9789 		return (err);
9790 	}
9791 
9792 	/* ill_init initializes the ipsq marking this thread as writer */
9793 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9794 	/* Wait for the DL_INFO_ACK */
9795 	mutex_enter(&ill->ill_lock);
9796 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9797 		/*
9798 		 * Return value of 0 indicates a pending signal.
9799 		 */
9800 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9801 		if (err == 0) {
9802 			mutex_exit(&ill->ill_lock);
9803 			(void) ip_close(q, 0);
9804 			return (EINTR);
9805 		}
9806 	}
9807 	mutex_exit(&ill->ill_lock);
9808 
9809 	/*
9810 	 * ip_rput_other could have set an error  in ill_error on
9811 	 * receipt of M_ERROR.
9812 	 */
9813 
9814 	err = ill->ill_error;
9815 	if (err != 0) {
9816 		(void) ip_close(q, 0);
9817 		return (err);
9818 	}
9819 
9820 	ill->ill_credp = credp;
9821 	crhold(credp);
9822 
9823 	mutex_enter(&ipst->ips_ip_mi_lock);
9824 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9825 	    credp);
9826 	mutex_exit(&ipst->ips_ip_mi_lock);
9827 	if (err) {
9828 		(void) ip_close(q, 0);
9829 		return (err);
9830 	}
9831 	return (0);
9832 }
9833 
9834 /* IP open routine. */
9835 int
9836 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9837 {
9838 	conn_t 		*connp;
9839 	major_t		maj;
9840 	zoneid_t	zoneid;
9841 	netstack_t	*ns;
9842 	ip_stack_t	*ipst;
9843 
9844 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9845 
9846 	/* Allow reopen. */
9847 	if (q->q_ptr != NULL)
9848 		return (0);
9849 
9850 	if (sflag & MODOPEN) {
9851 		/* This is a module open */
9852 		return (ip_modopen(q, devp, flag, sflag, credp));
9853 	}
9854 
9855 	ns = netstack_find_by_cred(credp);
9856 	ASSERT(ns != NULL);
9857 	ipst = ns->netstack_ip;
9858 	ASSERT(ipst != NULL);
9859 
9860 	/*
9861 	 * For exclusive stacks we set the zoneid to zero
9862 	 * to make IP operate as if in the global zone.
9863 	 */
9864 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9865 		zoneid = GLOBAL_ZONEID;
9866 	else
9867 		zoneid = crgetzoneid(credp);
9868 
9869 	/*
9870 	 * We are opening as a device. This is an IP client stream, and we
9871 	 * allocate an conn_t as the instance data.
9872 	 */
9873 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9874 
9875 	/*
9876 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9877 	 * done by netstack_find_by_cred()
9878 	 */
9879 	netstack_rele(ipst->ips_netstack);
9880 
9881 	connp->conn_zoneid = zoneid;
9882 
9883 	connp->conn_upq = q;
9884 	q->q_ptr = WR(q)->q_ptr = connp;
9885 
9886 	if (flag & SO_SOCKSTR)
9887 		connp->conn_flags |= IPCL_SOCKET;
9888 
9889 	/* Minor tells us which /dev entry was opened */
9890 	if (geteminor(*devp) == IPV6_MINOR) {
9891 		connp->conn_flags |= IPCL_ISV6;
9892 		connp->conn_af_isv6 = B_TRUE;
9893 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
9894 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9895 	} else {
9896 		connp->conn_af_isv6 = B_FALSE;
9897 		connp->conn_pkt_isv6 = B_FALSE;
9898 	}
9899 
9900 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9901 		/* CONN_DEC_REF takes care of netstack_rele() */
9902 		q->q_ptr = WR(q)->q_ptr = NULL;
9903 		CONN_DEC_REF(connp);
9904 		return (EBUSY);
9905 	}
9906 
9907 	maj = getemajor(*devp);
9908 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9909 
9910 	/*
9911 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9912 	 */
9913 	connp->conn_cred = credp;
9914 	crhold(connp->conn_cred);
9915 
9916 	/*
9917 	 * If the caller has the process-wide flag set, then default to MAC
9918 	 * exempt mode.  This allows read-down to unlabeled hosts.
9919 	 */
9920 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9921 		connp->conn_mac_exempt = B_TRUE;
9922 
9923 	/*
9924 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9925 	 * administrative ops.  In these cases, we just need a normal conn_t
9926 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9927 	 * an error will be returned.
9928 	 */
9929 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9930 		connp->conn_rq = q;
9931 		connp->conn_wq = WR(q);
9932 	} else {
9933 		connp->conn_ulp = IPPROTO_SCTP;
9934 		connp->conn_rq = connp->conn_wq = NULL;
9935 	}
9936 	/* Non-zero default values */
9937 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9938 
9939 	/*
9940 	 * Make the conn globally visible to walkers
9941 	 */
9942 	ASSERT(connp->conn_ref == 1);
9943 	mutex_enter(&connp->conn_lock);
9944 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9945 	mutex_exit(&connp->conn_lock);
9946 
9947 	qprocson(q);
9948 
9949 	return (0);
9950 }
9951 
9952 /*
9953  * Change q_qinfo based on the value of isv6.
9954  * This can not called on an ill queue.
9955  * Note that there is no race since either q_qinfo works for conn queues - it
9956  * is just an optimization to enter the best wput routine directly.
9957  */
9958 void
9959 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
9960 {
9961 	ASSERT(q->q_flag & QREADR);
9962 	ASSERT(WR(q)->q_next == NULL);
9963 	ASSERT(q->q_ptr != NULL);
9964 
9965 	if (minor == IPV6_MINOR)  {
9966 		if (bump_mib) {
9967 			BUMP_MIB(&ipst->ips_ip6_mib,
9968 			    ipIfStatsOutSwitchIPVersion);
9969 		}
9970 		q->q_qinfo = &rinit_ipv6;
9971 		WR(q)->q_qinfo = &winit_ipv6;
9972 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9973 	} else {
9974 		if (bump_mib) {
9975 			BUMP_MIB(&ipst->ips_ip_mib,
9976 			    ipIfStatsOutSwitchIPVersion);
9977 		}
9978 		q->q_qinfo = &iprinit;
9979 		WR(q)->q_qinfo = &ipwinit;
9980 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9981 	}
9982 
9983 }
9984 
9985 /*
9986  * See if IPsec needs loading because of the options in mp.
9987  */
9988 static boolean_t
9989 ipsec_opt_present(mblk_t *mp)
9990 {
9991 	uint8_t *optcp, *next_optcp, *opt_endcp;
9992 	struct opthdr *opt;
9993 	struct T_opthdr *topt;
9994 	int opthdr_len;
9995 	t_uscalar_t optname, optlevel;
9996 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9997 	ipsec_req_t *ipsr;
9998 
9999 	/*
10000 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10001 	 * return TRUE.
10002 	 */
10003 
10004 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10005 	opt_endcp = optcp + tor->OPT_length;
10006 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10007 		opthdr_len = sizeof (struct T_opthdr);
10008 	} else {		/* O_OPTMGMT_REQ */
10009 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10010 		opthdr_len = sizeof (struct opthdr);
10011 	}
10012 	for (; optcp < opt_endcp; optcp = next_optcp) {
10013 		if (optcp + opthdr_len > opt_endcp)
10014 			return (B_FALSE);	/* Not enough option header. */
10015 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10016 			topt = (struct T_opthdr *)optcp;
10017 			optlevel = topt->level;
10018 			optname = topt->name;
10019 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10020 		} else {
10021 			opt = (struct opthdr *)optcp;
10022 			optlevel = opt->level;
10023 			optname = opt->name;
10024 			next_optcp = optcp + opthdr_len +
10025 			    _TPI_ALIGN_OPT(opt->len);
10026 		}
10027 		if ((next_optcp < optcp) || /* wraparound pointer space */
10028 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10029 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10030 			return (B_FALSE); /* bad option buffer */
10031 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10032 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10033 			/*
10034 			 * Check to see if it's an all-bypass or all-zeroes
10035 			 * IPsec request.  Don't bother loading IPsec if
10036 			 * the socket doesn't want to use it.  (A good example
10037 			 * is a bypass request.)
10038 			 *
10039 			 * Basically, if any of the non-NEVER bits are set,
10040 			 * load IPsec.
10041 			 */
10042 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10043 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10044 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10045 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10046 			    != 0)
10047 				return (B_TRUE);
10048 		}
10049 	}
10050 	return (B_FALSE);
10051 }
10052 
10053 /*
10054  * If conn is is waiting for ipsec to finish loading, kick it.
10055  */
10056 /* ARGSUSED */
10057 static void
10058 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10059 {
10060 	t_scalar_t	optreq_prim;
10061 	mblk_t		*mp;
10062 	cred_t		*cr;
10063 	int		err = 0;
10064 
10065 	/*
10066 	 * This function is called, after ipsec loading is complete.
10067 	 * Since IP checks exclusively and atomically (i.e it prevents
10068 	 * ipsec load from completing until ip_optcom_req completes)
10069 	 * whether ipsec load is complete, there cannot be a race with IP
10070 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10071 	 */
10072 	mutex_enter(&connp->conn_lock);
10073 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10074 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10075 		mp = connp->conn_ipsec_opt_mp;
10076 		connp->conn_ipsec_opt_mp = NULL;
10077 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10078 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10079 		mutex_exit(&connp->conn_lock);
10080 
10081 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10082 
10083 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10084 		if (optreq_prim == T_OPTMGMT_REQ) {
10085 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10086 			    &ip_opt_obj);
10087 		} else {
10088 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10089 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10090 			    &ip_opt_obj);
10091 		}
10092 		if (err != EINPROGRESS)
10093 			CONN_OPER_PENDING_DONE(connp);
10094 		return;
10095 	}
10096 	mutex_exit(&connp->conn_lock);
10097 }
10098 
10099 /*
10100  * Called from the ipsec_loader thread, outside any perimeter, to tell
10101  * ip qenable any of the queues waiting for the ipsec loader to
10102  * complete.
10103  */
10104 void
10105 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10106 {
10107 	netstack_t *ns = ipss->ipsec_netstack;
10108 
10109 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10110 }
10111 
10112 /*
10113  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10114  * determines the grp on which it has to become exclusive, queues the mp
10115  * and sq draining restarts the optmgmt
10116  */
10117 static boolean_t
10118 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10119 {
10120 	conn_t *connp = Q_TO_CONN(q);
10121 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10122 
10123 	/*
10124 	 * Take IPsec requests and treat them special.
10125 	 */
10126 	if (ipsec_opt_present(mp)) {
10127 		/* First check if IPsec is loaded. */
10128 		mutex_enter(&ipss->ipsec_loader_lock);
10129 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10130 			mutex_exit(&ipss->ipsec_loader_lock);
10131 			return (B_FALSE);
10132 		}
10133 		mutex_enter(&connp->conn_lock);
10134 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10135 
10136 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10137 		connp->conn_ipsec_opt_mp = mp;
10138 		mutex_exit(&connp->conn_lock);
10139 		mutex_exit(&ipss->ipsec_loader_lock);
10140 
10141 		ipsec_loader_loadnow(ipss);
10142 		return (B_TRUE);
10143 	}
10144 	return (B_FALSE);
10145 }
10146 
10147 /*
10148  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10149  * all of them are copied to the conn_t. If the req is "zero", the policy is
10150  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10151  * fields.
10152  * We keep only the latest setting of the policy and thus policy setting
10153  * is not incremental/cumulative.
10154  *
10155  * Requests to set policies with multiple alternative actions will
10156  * go through a different API.
10157  */
10158 int
10159 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10160 {
10161 	uint_t ah_req = 0;
10162 	uint_t esp_req = 0;
10163 	uint_t se_req = 0;
10164 	ipsec_selkey_t sel;
10165 	ipsec_act_t *actp = NULL;
10166 	uint_t nact;
10167 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10168 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10169 	ipsec_policy_root_t *pr;
10170 	ipsec_policy_head_t *ph;
10171 	int fam;
10172 	boolean_t is_pol_reset;
10173 	int error = 0;
10174 	netstack_t	*ns = connp->conn_netstack;
10175 	ip_stack_t	*ipst = ns->netstack_ip;
10176 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10177 
10178 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10179 
10180 	/*
10181 	 * The IP_SEC_OPT option does not allow variable length parameters,
10182 	 * hence a request cannot be NULL.
10183 	 */
10184 	if (req == NULL)
10185 		return (EINVAL);
10186 
10187 	ah_req = req->ipsr_ah_req;
10188 	esp_req = req->ipsr_esp_req;
10189 	se_req = req->ipsr_self_encap_req;
10190 
10191 	/*
10192 	 * Are we dealing with a request to reset the policy (i.e.
10193 	 * zero requests).
10194 	 */
10195 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10196 	    (esp_req & REQ_MASK) == 0 &&
10197 	    (se_req & REQ_MASK) == 0);
10198 
10199 	if (!is_pol_reset) {
10200 		/*
10201 		 * If we couldn't load IPsec, fail with "protocol
10202 		 * not supported".
10203 		 * IPsec may not have been loaded for a request with zero
10204 		 * policies, so we don't fail in this case.
10205 		 */
10206 		mutex_enter(&ipss->ipsec_loader_lock);
10207 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10208 			mutex_exit(&ipss->ipsec_loader_lock);
10209 			return (EPROTONOSUPPORT);
10210 		}
10211 		mutex_exit(&ipss->ipsec_loader_lock);
10212 
10213 		/*
10214 		 * Test for valid requests. Invalid algorithms
10215 		 * need to be tested by IPsec code because new
10216 		 * algorithms can be added dynamically.
10217 		 */
10218 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10219 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10220 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10221 			return (EINVAL);
10222 		}
10223 
10224 		/*
10225 		 * Only privileged users can issue these
10226 		 * requests.
10227 		 */
10228 		if (((ah_req & IPSEC_PREF_NEVER) ||
10229 		    (esp_req & IPSEC_PREF_NEVER) ||
10230 		    (se_req & IPSEC_PREF_NEVER)) &&
10231 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10232 			return (EPERM);
10233 		}
10234 
10235 		/*
10236 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10237 		 * are mutually exclusive.
10238 		 */
10239 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10240 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10241 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10242 			/* Both of them are set */
10243 			return (EINVAL);
10244 		}
10245 	}
10246 
10247 	mutex_enter(&connp->conn_lock);
10248 
10249 	/*
10250 	 * If we have already cached policies in ip_bind_connected*(), don't
10251 	 * let them change now. We cache policies for connections
10252 	 * whose src,dst [addr, port] is known.
10253 	 */
10254 	if (connp->conn_policy_cached) {
10255 		mutex_exit(&connp->conn_lock);
10256 		return (EINVAL);
10257 	}
10258 
10259 	/*
10260 	 * We have a zero policies, reset the connection policy if already
10261 	 * set. This will cause the connection to inherit the
10262 	 * global policy, if any.
10263 	 */
10264 	if (is_pol_reset) {
10265 		if (connp->conn_policy != NULL) {
10266 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10267 			connp->conn_policy = NULL;
10268 		}
10269 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10270 		connp->conn_in_enforce_policy = B_FALSE;
10271 		connp->conn_out_enforce_policy = B_FALSE;
10272 		mutex_exit(&connp->conn_lock);
10273 		return (0);
10274 	}
10275 
10276 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10277 	    ipst->ips_netstack);
10278 	if (ph == NULL)
10279 		goto enomem;
10280 
10281 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10282 	if (actp == NULL)
10283 		goto enomem;
10284 
10285 	/*
10286 	 * Always allocate IPv4 policy entries, since they can also
10287 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10288 	 */
10289 	bzero(&sel, sizeof (sel));
10290 	sel.ipsl_valid = IPSL_IPV4;
10291 
10292 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10293 	    ipst->ips_netstack);
10294 	if (pin4 == NULL)
10295 		goto enomem;
10296 
10297 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10298 	    ipst->ips_netstack);
10299 	if (pout4 == NULL)
10300 		goto enomem;
10301 
10302 	if (connp->conn_pkt_isv6) {
10303 		/*
10304 		 * We're looking at a v6 socket, also allocate the
10305 		 * v6-specific entries...
10306 		 */
10307 		sel.ipsl_valid = IPSL_IPV6;
10308 		pin6 = ipsec_policy_create(&sel, actp, nact,
10309 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10310 		if (pin6 == NULL)
10311 			goto enomem;
10312 
10313 		pout6 = ipsec_policy_create(&sel, actp, nact,
10314 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10315 		if (pout6 == NULL)
10316 			goto enomem;
10317 
10318 		/*
10319 		 * .. and file them away in the right place.
10320 		 */
10321 		fam = IPSEC_AF_V6;
10322 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10323 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10324 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10325 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10326 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10327 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10328 	}
10329 
10330 	ipsec_actvec_free(actp, nact);
10331 
10332 	/*
10333 	 * File the v4 policies.
10334 	 */
10335 	fam = IPSEC_AF_V4;
10336 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10337 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10338 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10339 
10340 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10341 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10342 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10343 
10344 	/*
10345 	 * If the requests need security, set enforce_policy.
10346 	 * If the requests are IPSEC_PREF_NEVER, one should
10347 	 * still set conn_out_enforce_policy so that an ipsec_out
10348 	 * gets attached in ip_wput. This is needed so that
10349 	 * for connections that we don't cache policy in ip_bind,
10350 	 * if global policy matches in ip_wput_attach_policy, we
10351 	 * don't wrongly inherit global policy. Similarly, we need
10352 	 * to set conn_in_enforce_policy also so that we don't verify
10353 	 * policy wrongly.
10354 	 */
10355 	if ((ah_req & REQ_MASK) != 0 ||
10356 	    (esp_req & REQ_MASK) != 0 ||
10357 	    (se_req & REQ_MASK) != 0) {
10358 		connp->conn_in_enforce_policy = B_TRUE;
10359 		connp->conn_out_enforce_policy = B_TRUE;
10360 		connp->conn_flags |= IPCL_CHECK_POLICY;
10361 	}
10362 
10363 	mutex_exit(&connp->conn_lock);
10364 	return (error);
10365 #undef REQ_MASK
10366 
10367 	/*
10368 	 * Common memory-allocation-failure exit path.
10369 	 */
10370 enomem:
10371 	mutex_exit(&connp->conn_lock);
10372 	if (actp != NULL)
10373 		ipsec_actvec_free(actp, nact);
10374 	if (pin4 != NULL)
10375 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10376 	if (pout4 != NULL)
10377 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10378 	if (pin6 != NULL)
10379 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10380 	if (pout6 != NULL)
10381 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10382 	return (ENOMEM);
10383 }
10384 
10385 /*
10386  * Only for options that pass in an IP addr. Currently only V4 options
10387  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10388  * So this function assumes level is IPPROTO_IP
10389  */
10390 int
10391 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10392     mblk_t *first_mp)
10393 {
10394 	ipif_t *ipif = NULL;
10395 	int error;
10396 	ill_t *ill;
10397 	int zoneid;
10398 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10399 
10400 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10401 
10402 	if (addr != INADDR_ANY || checkonly) {
10403 		ASSERT(connp != NULL);
10404 		zoneid = IPCL_ZONEID(connp);
10405 		if (option == IP_NEXTHOP) {
10406 			ipif = ipif_lookup_onlink_addr(addr,
10407 			    connp->conn_zoneid, ipst);
10408 		} else {
10409 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10410 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10411 			    &error, ipst);
10412 		}
10413 		if (ipif == NULL) {
10414 			if (error == EINPROGRESS)
10415 				return (error);
10416 			else if ((option == IP_MULTICAST_IF) ||
10417 			    (option == IP_NEXTHOP))
10418 				return (EHOSTUNREACH);
10419 			else
10420 				return (EINVAL);
10421 		} else if (checkonly) {
10422 			if (option == IP_MULTICAST_IF) {
10423 				ill = ipif->ipif_ill;
10424 				/* not supported by the virtual network iface */
10425 				if (IS_VNI(ill)) {
10426 					ipif_refrele(ipif);
10427 					return (EINVAL);
10428 				}
10429 			}
10430 			ipif_refrele(ipif);
10431 			return (0);
10432 		}
10433 		ill = ipif->ipif_ill;
10434 		mutex_enter(&connp->conn_lock);
10435 		mutex_enter(&ill->ill_lock);
10436 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10437 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10438 			mutex_exit(&ill->ill_lock);
10439 			mutex_exit(&connp->conn_lock);
10440 			ipif_refrele(ipif);
10441 			return (option == IP_MULTICAST_IF ?
10442 			    EHOSTUNREACH : EINVAL);
10443 		}
10444 	} else {
10445 		mutex_enter(&connp->conn_lock);
10446 	}
10447 
10448 	/* None of the options below are supported on the VNI */
10449 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10450 		mutex_exit(&ill->ill_lock);
10451 		mutex_exit(&connp->conn_lock);
10452 		ipif_refrele(ipif);
10453 		return (EINVAL);
10454 	}
10455 
10456 	switch (option) {
10457 	case IP_DONTFAILOVER_IF:
10458 		/*
10459 		 * This option is used by in.mpathd to ensure
10460 		 * that IPMP probe packets only go out on the
10461 		 * test interfaces. in.mpathd sets this option
10462 		 * on the non-failover interfaces.
10463 		 * For backward compatibility, this option
10464 		 * implicitly sets IP_MULTICAST_IF, as used
10465 		 * be done in bind(), so that ip_wput gets
10466 		 * this ipif to send mcast packets.
10467 		 */
10468 		if (ipif != NULL) {
10469 			ASSERT(addr != INADDR_ANY);
10470 			connp->conn_nofailover_ill = ipif->ipif_ill;
10471 			connp->conn_multicast_ipif = ipif;
10472 		} else {
10473 			ASSERT(addr == INADDR_ANY);
10474 			connp->conn_nofailover_ill = NULL;
10475 			connp->conn_multicast_ipif = NULL;
10476 		}
10477 		break;
10478 
10479 	case IP_MULTICAST_IF:
10480 		connp->conn_multicast_ipif = ipif;
10481 		break;
10482 	case IP_NEXTHOP:
10483 		connp->conn_nexthop_v4 = addr;
10484 		connp->conn_nexthop_set = B_TRUE;
10485 		break;
10486 	}
10487 
10488 	if (ipif != NULL) {
10489 		mutex_exit(&ill->ill_lock);
10490 		mutex_exit(&connp->conn_lock);
10491 		ipif_refrele(ipif);
10492 		return (0);
10493 	}
10494 	mutex_exit(&connp->conn_lock);
10495 	/* We succeded in cleared the option */
10496 	return (0);
10497 }
10498 
10499 /*
10500  * For options that pass in an ifindex specifying the ill. V6 options always
10501  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10502  */
10503 int
10504 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10505     int level, int option, mblk_t *first_mp)
10506 {
10507 	ill_t *ill = NULL;
10508 	int error = 0;
10509 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10510 
10511 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10512 	if (ifindex != 0) {
10513 		ASSERT(connp != NULL);
10514 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10515 		    first_mp, ip_restart_optmgmt, &error, ipst);
10516 		if (ill != NULL) {
10517 			if (checkonly) {
10518 				/* not supported by the virtual network iface */
10519 				if (IS_VNI(ill)) {
10520 					ill_refrele(ill);
10521 					return (EINVAL);
10522 				}
10523 				ill_refrele(ill);
10524 				return (0);
10525 			}
10526 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10527 			    0, NULL)) {
10528 				ill_refrele(ill);
10529 				ill = NULL;
10530 				mutex_enter(&connp->conn_lock);
10531 				goto setit;
10532 			}
10533 			mutex_enter(&connp->conn_lock);
10534 			mutex_enter(&ill->ill_lock);
10535 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10536 				mutex_exit(&ill->ill_lock);
10537 				mutex_exit(&connp->conn_lock);
10538 				ill_refrele(ill);
10539 				ill = NULL;
10540 				mutex_enter(&connp->conn_lock);
10541 			}
10542 			goto setit;
10543 		} else if (error == EINPROGRESS) {
10544 			return (error);
10545 		} else {
10546 			error = 0;
10547 		}
10548 	}
10549 	mutex_enter(&connp->conn_lock);
10550 setit:
10551 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10552 
10553 	/*
10554 	 * The options below assume that the ILL (if any) transmits and/or
10555 	 * receives traffic. Neither of which is true for the virtual network
10556 	 * interface, so fail setting these on a VNI.
10557 	 */
10558 	if (IS_VNI(ill)) {
10559 		ASSERT(ill != NULL);
10560 		mutex_exit(&ill->ill_lock);
10561 		mutex_exit(&connp->conn_lock);
10562 		ill_refrele(ill);
10563 		return (EINVAL);
10564 	}
10565 
10566 	if (level == IPPROTO_IP) {
10567 		switch (option) {
10568 		case IP_BOUND_IF:
10569 			connp->conn_incoming_ill = ill;
10570 			connp->conn_outgoing_ill = ill;
10571 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10572 			    0 : ifindex;
10573 			break;
10574 
10575 		case IP_XMIT_IF:
10576 			/*
10577 			 * Similar to IP_BOUND_IF, but this only
10578 			 * determines the outgoing interface for
10579 			 * unicast packets. Also no IRE_CACHE entry
10580 			 * is added for the destination of the
10581 			 * outgoing packets.
10582 			 */
10583 			connp->conn_xmit_if_ill = ill;
10584 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10585 			    0 : ifindex;
10586 			break;
10587 
10588 		case IP_MULTICAST_IF:
10589 			/*
10590 			 * This option is an internal special. The socket
10591 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10592 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10593 			 * specifies an ifindex and we try first on V6 ill's.
10594 			 * If we don't find one, we they try using on v4 ill's
10595 			 * intenally and we come here.
10596 			 */
10597 			if (!checkonly && ill != NULL) {
10598 				ipif_t	*ipif;
10599 				ipif = ill->ill_ipif;
10600 
10601 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10602 					mutex_exit(&ill->ill_lock);
10603 					mutex_exit(&connp->conn_lock);
10604 					ill_refrele(ill);
10605 					ill = NULL;
10606 					mutex_enter(&connp->conn_lock);
10607 				} else {
10608 					connp->conn_multicast_ipif = ipif;
10609 				}
10610 			}
10611 			break;
10612 		}
10613 	} else {
10614 		switch (option) {
10615 		case IPV6_BOUND_IF:
10616 			connp->conn_incoming_ill = ill;
10617 			connp->conn_outgoing_ill = ill;
10618 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10619 			    0 : ifindex;
10620 			break;
10621 
10622 		case IPV6_BOUND_PIF:
10623 			/*
10624 			 * Limit all transmit to this ill.
10625 			 * Unlike IPV6_BOUND_IF, using this option
10626 			 * prevents load spreading and failover from
10627 			 * happening when the interface is part of the
10628 			 * group. That's why we don't need to remember
10629 			 * the ifindex in orig_bound_ifindex as in
10630 			 * IPV6_BOUND_IF.
10631 			 */
10632 			connp->conn_outgoing_pill = ill;
10633 			break;
10634 
10635 		case IPV6_DONTFAILOVER_IF:
10636 			/*
10637 			 * This option is used by in.mpathd to ensure
10638 			 * that IPMP probe packets only go out on the
10639 			 * test interfaces. in.mpathd sets this option
10640 			 * on the non-failover interfaces.
10641 			 */
10642 			connp->conn_nofailover_ill = ill;
10643 			/*
10644 			 * For backward compatibility, this option
10645 			 * implicitly sets ip_multicast_ill as used in
10646 			 * IP_MULTICAST_IF so that ip_wput gets
10647 			 * this ipif to send mcast packets.
10648 			 */
10649 			connp->conn_multicast_ill = ill;
10650 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10651 			    0 : ifindex;
10652 			break;
10653 
10654 		case IPV6_MULTICAST_IF:
10655 			/*
10656 			 * Set conn_multicast_ill to be the IPv6 ill.
10657 			 * Set conn_multicast_ipif to be an IPv4 ipif
10658 			 * for ifindex to make IPv4 mapped addresses
10659 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10660 			 * Even if no IPv6 ill exists for the ifindex
10661 			 * we need to check for an IPv4 ifindex in order
10662 			 * for this to work with mapped addresses. In that
10663 			 * case only set conn_multicast_ipif.
10664 			 */
10665 			if (!checkonly) {
10666 				if (ifindex == 0) {
10667 					connp->conn_multicast_ill = NULL;
10668 					connp->conn_orig_multicast_ifindex = 0;
10669 					connp->conn_multicast_ipif = NULL;
10670 				} else if (ill != NULL) {
10671 					connp->conn_multicast_ill = ill;
10672 					connp->conn_orig_multicast_ifindex =
10673 					    ifindex;
10674 				}
10675 			}
10676 			break;
10677 		}
10678 	}
10679 
10680 	if (ill != NULL) {
10681 		mutex_exit(&ill->ill_lock);
10682 		mutex_exit(&connp->conn_lock);
10683 		ill_refrele(ill);
10684 		return (0);
10685 	}
10686 	mutex_exit(&connp->conn_lock);
10687 	/*
10688 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10689 	 * locate the ill and could not set the option (ifindex != 0)
10690 	 */
10691 	return (ifindex == 0 ? 0 : EINVAL);
10692 }
10693 
10694 /* This routine sets socket options. */
10695 /* ARGSUSED */
10696 int
10697 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10698     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10699     void *dummy, cred_t *cr, mblk_t *first_mp)
10700 {
10701 	int		*i1 = (int *)invalp;
10702 	conn_t		*connp = Q_TO_CONN(q);
10703 	int		error = 0;
10704 	boolean_t	checkonly;
10705 	ire_t		*ire;
10706 	boolean_t	found;
10707 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10708 
10709 	switch (optset_context) {
10710 
10711 	case SETFN_OPTCOM_CHECKONLY:
10712 		checkonly = B_TRUE;
10713 		/*
10714 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10715 		 * inlen != 0 implies value supplied and
10716 		 * 	we have to "pretend" to set it.
10717 		 * inlen == 0 implies that there is no
10718 		 * 	value part in T_CHECK request and just validation
10719 		 * done elsewhere should be enough, we just return here.
10720 		 */
10721 		if (inlen == 0) {
10722 			*outlenp = 0;
10723 			return (0);
10724 		}
10725 		break;
10726 	case SETFN_OPTCOM_NEGOTIATE:
10727 	case SETFN_UD_NEGOTIATE:
10728 	case SETFN_CONN_NEGOTIATE:
10729 		checkonly = B_FALSE;
10730 		break;
10731 	default:
10732 		/*
10733 		 * We should never get here
10734 		 */
10735 		*outlenp = 0;
10736 		return (EINVAL);
10737 	}
10738 
10739 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10740 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10741 
10742 	/*
10743 	 * For fixed length options, no sanity check
10744 	 * of passed in length is done. It is assumed *_optcom_req()
10745 	 * routines do the right thing.
10746 	 */
10747 
10748 	switch (level) {
10749 	case SOL_SOCKET:
10750 		/*
10751 		 * conn_lock protects the bitfields, and is used to
10752 		 * set the fields atomically.
10753 		 */
10754 		switch (name) {
10755 		case SO_BROADCAST:
10756 			if (!checkonly) {
10757 				/* TODO: use value someplace? */
10758 				mutex_enter(&connp->conn_lock);
10759 				connp->conn_broadcast = *i1 ? 1 : 0;
10760 				mutex_exit(&connp->conn_lock);
10761 			}
10762 			break;	/* goto sizeof (int) option return */
10763 		case SO_USELOOPBACK:
10764 			if (!checkonly) {
10765 				/* TODO: use value someplace? */
10766 				mutex_enter(&connp->conn_lock);
10767 				connp->conn_loopback = *i1 ? 1 : 0;
10768 				mutex_exit(&connp->conn_lock);
10769 			}
10770 			break;	/* goto sizeof (int) option return */
10771 		case SO_DONTROUTE:
10772 			if (!checkonly) {
10773 				mutex_enter(&connp->conn_lock);
10774 				connp->conn_dontroute = *i1 ? 1 : 0;
10775 				mutex_exit(&connp->conn_lock);
10776 			}
10777 			break;	/* goto sizeof (int) option return */
10778 		case SO_REUSEADDR:
10779 			if (!checkonly) {
10780 				mutex_enter(&connp->conn_lock);
10781 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10782 				mutex_exit(&connp->conn_lock);
10783 			}
10784 			break;	/* goto sizeof (int) option return */
10785 		case SO_PROTOTYPE:
10786 			if (!checkonly) {
10787 				mutex_enter(&connp->conn_lock);
10788 				connp->conn_proto = *i1;
10789 				mutex_exit(&connp->conn_lock);
10790 			}
10791 			break;	/* goto sizeof (int) option return */
10792 		case SO_ALLZONES:
10793 			if (!checkonly) {
10794 				mutex_enter(&connp->conn_lock);
10795 				if (IPCL_IS_BOUND(connp)) {
10796 					mutex_exit(&connp->conn_lock);
10797 					return (EINVAL);
10798 				}
10799 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10800 				mutex_exit(&connp->conn_lock);
10801 			}
10802 			break;	/* goto sizeof (int) option return */
10803 		case SO_ANON_MLP:
10804 			if (!checkonly) {
10805 				mutex_enter(&connp->conn_lock);
10806 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10807 				mutex_exit(&connp->conn_lock);
10808 			}
10809 			break;	/* goto sizeof (int) option return */
10810 		case SO_MAC_EXEMPT:
10811 			if (secpolicy_net_mac_aware(cr) != 0 ||
10812 			    IPCL_IS_BOUND(connp))
10813 				return (EACCES);
10814 			if (!checkonly) {
10815 				mutex_enter(&connp->conn_lock);
10816 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10817 				mutex_exit(&connp->conn_lock);
10818 			}
10819 			break;	/* goto sizeof (int) option return */
10820 		default:
10821 			/*
10822 			 * "soft" error (negative)
10823 			 * option not handled at this level
10824 			 * Note: Do not modify *outlenp
10825 			 */
10826 			return (-EINVAL);
10827 		}
10828 		break;
10829 	case IPPROTO_IP:
10830 		switch (name) {
10831 		case IP_NEXTHOP:
10832 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10833 				return (EPERM);
10834 			/* FALLTHRU */
10835 		case IP_MULTICAST_IF:
10836 		case IP_DONTFAILOVER_IF: {
10837 			ipaddr_t addr = *i1;
10838 
10839 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10840 			    first_mp);
10841 			if (error != 0)
10842 				return (error);
10843 			break;	/* goto sizeof (int) option return */
10844 		}
10845 
10846 		case IP_MULTICAST_TTL:
10847 			/* Recorded in transport above IP */
10848 			*outvalp = *invalp;
10849 			*outlenp = sizeof (uchar_t);
10850 			return (0);
10851 		case IP_MULTICAST_LOOP:
10852 			if (!checkonly) {
10853 				mutex_enter(&connp->conn_lock);
10854 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10855 				mutex_exit(&connp->conn_lock);
10856 			}
10857 			*outvalp = *invalp;
10858 			*outlenp = sizeof (uchar_t);
10859 			return (0);
10860 		case IP_ADD_MEMBERSHIP:
10861 		case MCAST_JOIN_GROUP:
10862 		case IP_DROP_MEMBERSHIP:
10863 		case MCAST_LEAVE_GROUP: {
10864 			struct ip_mreq *mreqp;
10865 			struct group_req *greqp;
10866 			ire_t *ire;
10867 			boolean_t done = B_FALSE;
10868 			ipaddr_t group, ifaddr;
10869 			struct sockaddr_in *sin;
10870 			uint32_t *ifindexp;
10871 			boolean_t mcast_opt = B_TRUE;
10872 			mcast_record_t fmode;
10873 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10874 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10875 
10876 			switch (name) {
10877 			case IP_ADD_MEMBERSHIP:
10878 				mcast_opt = B_FALSE;
10879 				/* FALLTHRU */
10880 			case MCAST_JOIN_GROUP:
10881 				fmode = MODE_IS_EXCLUDE;
10882 				optfn = ip_opt_add_group;
10883 				break;
10884 
10885 			case IP_DROP_MEMBERSHIP:
10886 				mcast_opt = B_FALSE;
10887 				/* FALLTHRU */
10888 			case MCAST_LEAVE_GROUP:
10889 				fmode = MODE_IS_INCLUDE;
10890 				optfn = ip_opt_delete_group;
10891 				break;
10892 			}
10893 
10894 			if (mcast_opt) {
10895 				greqp = (struct group_req *)i1;
10896 				sin = (struct sockaddr_in *)&greqp->gr_group;
10897 				if (sin->sin_family != AF_INET) {
10898 					*outlenp = 0;
10899 					return (ENOPROTOOPT);
10900 				}
10901 				group = (ipaddr_t)sin->sin_addr.s_addr;
10902 				ifaddr = INADDR_ANY;
10903 				ifindexp = &greqp->gr_interface;
10904 			} else {
10905 				mreqp = (struct ip_mreq *)i1;
10906 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10907 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10908 				ifindexp = NULL;
10909 			}
10910 
10911 			/*
10912 			 * In the multirouting case, we need to replicate
10913 			 * the request on all interfaces that will take part
10914 			 * in replication.  We do so because multirouting is
10915 			 * reflective, thus we will probably receive multi-
10916 			 * casts on those interfaces.
10917 			 * The ip_multirt_apply_membership() succeeds if the
10918 			 * operation succeeds on at least one interface.
10919 			 */
10920 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10921 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10922 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10923 			if (ire != NULL) {
10924 				if (ire->ire_flags & RTF_MULTIRT) {
10925 					error = ip_multirt_apply_membership(
10926 					    optfn, ire, connp, checkonly, group,
10927 					    fmode, INADDR_ANY, first_mp);
10928 					done = B_TRUE;
10929 				}
10930 				ire_refrele(ire);
10931 			}
10932 			if (!done) {
10933 				error = optfn(connp, checkonly, group, ifaddr,
10934 				    ifindexp, fmode, INADDR_ANY, first_mp);
10935 			}
10936 			if (error) {
10937 				/*
10938 				 * EINPROGRESS is a soft error, needs retry
10939 				 * so don't make *outlenp zero.
10940 				 */
10941 				if (error != EINPROGRESS)
10942 					*outlenp = 0;
10943 				return (error);
10944 			}
10945 			/* OK return - copy input buffer into output buffer */
10946 			if (invalp != outvalp) {
10947 				/* don't trust bcopy for identical src/dst */
10948 				bcopy(invalp, outvalp, inlen);
10949 			}
10950 			*outlenp = inlen;
10951 			return (0);
10952 		}
10953 		case IP_BLOCK_SOURCE:
10954 		case IP_UNBLOCK_SOURCE:
10955 		case IP_ADD_SOURCE_MEMBERSHIP:
10956 		case IP_DROP_SOURCE_MEMBERSHIP:
10957 		case MCAST_BLOCK_SOURCE:
10958 		case MCAST_UNBLOCK_SOURCE:
10959 		case MCAST_JOIN_SOURCE_GROUP:
10960 		case MCAST_LEAVE_SOURCE_GROUP: {
10961 			struct ip_mreq_source *imreqp;
10962 			struct group_source_req *gsreqp;
10963 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10964 			uint32_t ifindex = 0;
10965 			mcast_record_t fmode;
10966 			struct sockaddr_in *sin;
10967 			ire_t *ire;
10968 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10969 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10970 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10971 
10972 			switch (name) {
10973 			case IP_BLOCK_SOURCE:
10974 				mcast_opt = B_FALSE;
10975 				/* FALLTHRU */
10976 			case MCAST_BLOCK_SOURCE:
10977 				fmode = MODE_IS_EXCLUDE;
10978 				optfn = ip_opt_add_group;
10979 				break;
10980 
10981 			case IP_UNBLOCK_SOURCE:
10982 				mcast_opt = B_FALSE;
10983 				/* FALLTHRU */
10984 			case MCAST_UNBLOCK_SOURCE:
10985 				fmode = MODE_IS_EXCLUDE;
10986 				optfn = ip_opt_delete_group;
10987 				break;
10988 
10989 			case IP_ADD_SOURCE_MEMBERSHIP:
10990 				mcast_opt = B_FALSE;
10991 				/* FALLTHRU */
10992 			case MCAST_JOIN_SOURCE_GROUP:
10993 				fmode = MODE_IS_INCLUDE;
10994 				optfn = ip_opt_add_group;
10995 				break;
10996 
10997 			case IP_DROP_SOURCE_MEMBERSHIP:
10998 				mcast_opt = B_FALSE;
10999 				/* FALLTHRU */
11000 			case MCAST_LEAVE_SOURCE_GROUP:
11001 				fmode = MODE_IS_INCLUDE;
11002 				optfn = ip_opt_delete_group;
11003 				break;
11004 			}
11005 
11006 			if (mcast_opt) {
11007 				gsreqp = (struct group_source_req *)i1;
11008 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11009 					*outlenp = 0;
11010 					return (ENOPROTOOPT);
11011 				}
11012 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11013 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11014 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11015 				src = (ipaddr_t)sin->sin_addr.s_addr;
11016 				ifindex = gsreqp->gsr_interface;
11017 			} else {
11018 				imreqp = (struct ip_mreq_source *)i1;
11019 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11020 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11021 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11022 			}
11023 
11024 			/*
11025 			 * In the multirouting case, we need to replicate
11026 			 * the request as noted in the mcast cases above.
11027 			 */
11028 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11029 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11030 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11031 			if (ire != NULL) {
11032 				if (ire->ire_flags & RTF_MULTIRT) {
11033 					error = ip_multirt_apply_membership(
11034 					    optfn, ire, connp, checkonly, grp,
11035 					    fmode, src, first_mp);
11036 					done = B_TRUE;
11037 				}
11038 				ire_refrele(ire);
11039 			}
11040 			if (!done) {
11041 				error = optfn(connp, checkonly, grp, ifaddr,
11042 				    &ifindex, fmode, src, first_mp);
11043 			}
11044 			if (error != 0) {
11045 				/*
11046 				 * EINPROGRESS is a soft error, needs retry
11047 				 * so don't make *outlenp zero.
11048 				 */
11049 				if (error != EINPROGRESS)
11050 					*outlenp = 0;
11051 				return (error);
11052 			}
11053 			/* OK return - copy input buffer into output buffer */
11054 			if (invalp != outvalp) {
11055 				bcopy(invalp, outvalp, inlen);
11056 			}
11057 			*outlenp = inlen;
11058 			return (0);
11059 		}
11060 		case IP_SEC_OPT:
11061 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11062 			if (error != 0) {
11063 				*outlenp = 0;
11064 				return (error);
11065 			}
11066 			break;
11067 		case IP_HDRINCL:
11068 		case IP_OPTIONS:
11069 		case T_IP_OPTIONS:
11070 		case IP_TOS:
11071 		case T_IP_TOS:
11072 		case IP_TTL:
11073 		case IP_RECVDSTADDR:
11074 		case IP_RECVOPTS:
11075 			/* OK return - copy input buffer into output buffer */
11076 			if (invalp != outvalp) {
11077 				/* don't trust bcopy for identical src/dst */
11078 				bcopy(invalp, outvalp, inlen);
11079 			}
11080 			*outlenp = inlen;
11081 			return (0);
11082 		case IP_RECVIF:
11083 			/* Retrieve the inbound interface index */
11084 			if (!checkonly) {
11085 				mutex_enter(&connp->conn_lock);
11086 				connp->conn_recvif = *i1 ? 1 : 0;
11087 				mutex_exit(&connp->conn_lock);
11088 			}
11089 			break;	/* goto sizeof (int) option return */
11090 		case IP_RECVPKTINFO:
11091 			if (!checkonly) {
11092 				mutex_enter(&connp->conn_lock);
11093 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11094 				mutex_exit(&connp->conn_lock);
11095 			}
11096 			break;	/* goto sizeof (int) option return */
11097 		case IP_RECVSLLA:
11098 			/* Retrieve the source link layer address */
11099 			if (!checkonly) {
11100 				mutex_enter(&connp->conn_lock);
11101 				connp->conn_recvslla = *i1 ? 1 : 0;
11102 				mutex_exit(&connp->conn_lock);
11103 			}
11104 			break;	/* goto sizeof (int) option return */
11105 		case MRT_INIT:
11106 		case MRT_DONE:
11107 		case MRT_ADD_VIF:
11108 		case MRT_DEL_VIF:
11109 		case MRT_ADD_MFC:
11110 		case MRT_DEL_MFC:
11111 		case MRT_ASSERT:
11112 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11113 				*outlenp = 0;
11114 				return (error);
11115 			}
11116 			error = ip_mrouter_set((int)name, q, checkonly,
11117 			    (uchar_t *)invalp, inlen, first_mp);
11118 			if (error) {
11119 				*outlenp = 0;
11120 				return (error);
11121 			}
11122 			/* OK return - copy input buffer into output buffer */
11123 			if (invalp != outvalp) {
11124 				/* don't trust bcopy for identical src/dst */
11125 				bcopy(invalp, outvalp, inlen);
11126 			}
11127 			*outlenp = inlen;
11128 			return (0);
11129 		case IP_BOUND_IF:
11130 		case IP_XMIT_IF:
11131 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11132 			    level, name, first_mp);
11133 			if (error != 0)
11134 				return (error);
11135 			break; 		/* goto sizeof (int) option return */
11136 
11137 		case IP_UNSPEC_SRC:
11138 			/* Allow sending with a zero source address */
11139 			if (!checkonly) {
11140 				mutex_enter(&connp->conn_lock);
11141 				connp->conn_unspec_src = *i1 ? 1 : 0;
11142 				mutex_exit(&connp->conn_lock);
11143 			}
11144 			break;	/* goto sizeof (int) option return */
11145 		default:
11146 			/*
11147 			 * "soft" error (negative)
11148 			 * option not handled at this level
11149 			 * Note: Do not modify *outlenp
11150 			 */
11151 			return (-EINVAL);
11152 		}
11153 		break;
11154 	case IPPROTO_IPV6:
11155 		switch (name) {
11156 		case IPV6_BOUND_IF:
11157 		case IPV6_BOUND_PIF:
11158 		case IPV6_DONTFAILOVER_IF:
11159 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11160 			    level, name, first_mp);
11161 			if (error != 0)
11162 				return (error);
11163 			break; 		/* goto sizeof (int) option return */
11164 
11165 		case IPV6_MULTICAST_IF:
11166 			/*
11167 			 * The only possible errors are EINPROGRESS and
11168 			 * EINVAL. EINPROGRESS will be restarted and is not
11169 			 * a hard error. We call this option on both V4 and V6
11170 			 * If both return EINVAL, then this call returns
11171 			 * EINVAL. If at least one of them succeeds we
11172 			 * return success.
11173 			 */
11174 			found = B_FALSE;
11175 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11176 			    level, name, first_mp);
11177 			if (error == EINPROGRESS)
11178 				return (error);
11179 			if (error == 0)
11180 				found = B_TRUE;
11181 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11182 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11183 			if (error == 0)
11184 				found = B_TRUE;
11185 			if (!found)
11186 				return (error);
11187 			break; 		/* goto sizeof (int) option return */
11188 
11189 		case IPV6_MULTICAST_HOPS:
11190 			/* Recorded in transport above IP */
11191 			break;	/* goto sizeof (int) option return */
11192 		case IPV6_MULTICAST_LOOP:
11193 			if (!checkonly) {
11194 				mutex_enter(&connp->conn_lock);
11195 				connp->conn_multicast_loop = *i1;
11196 				mutex_exit(&connp->conn_lock);
11197 			}
11198 			break;	/* goto sizeof (int) option return */
11199 		case IPV6_JOIN_GROUP:
11200 		case MCAST_JOIN_GROUP:
11201 		case IPV6_LEAVE_GROUP:
11202 		case MCAST_LEAVE_GROUP: {
11203 			struct ipv6_mreq *ip_mreqp;
11204 			struct group_req *greqp;
11205 			ire_t *ire;
11206 			boolean_t done = B_FALSE;
11207 			in6_addr_t groupv6;
11208 			uint32_t ifindex;
11209 			boolean_t mcast_opt = B_TRUE;
11210 			mcast_record_t fmode;
11211 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11212 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11213 
11214 			switch (name) {
11215 			case IPV6_JOIN_GROUP:
11216 				mcast_opt = B_FALSE;
11217 				/* FALLTHRU */
11218 			case MCAST_JOIN_GROUP:
11219 				fmode = MODE_IS_EXCLUDE;
11220 				optfn = ip_opt_add_group_v6;
11221 				break;
11222 
11223 			case IPV6_LEAVE_GROUP:
11224 				mcast_opt = B_FALSE;
11225 				/* FALLTHRU */
11226 			case MCAST_LEAVE_GROUP:
11227 				fmode = MODE_IS_INCLUDE;
11228 				optfn = ip_opt_delete_group_v6;
11229 				break;
11230 			}
11231 
11232 			if (mcast_opt) {
11233 				struct sockaddr_in *sin;
11234 				struct sockaddr_in6 *sin6;
11235 				greqp = (struct group_req *)i1;
11236 				if (greqp->gr_group.ss_family == AF_INET) {
11237 					sin = (struct sockaddr_in *)
11238 					    &(greqp->gr_group);
11239 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11240 					    &groupv6);
11241 				} else {
11242 					sin6 = (struct sockaddr_in6 *)
11243 					    &(greqp->gr_group);
11244 					groupv6 = sin6->sin6_addr;
11245 				}
11246 				ifindex = greqp->gr_interface;
11247 			} else {
11248 				ip_mreqp = (struct ipv6_mreq *)i1;
11249 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11250 				ifindex = ip_mreqp->ipv6mr_interface;
11251 			}
11252 			/*
11253 			 * In the multirouting case, we need to replicate
11254 			 * the request on all interfaces that will take part
11255 			 * in replication.  We do so because multirouting is
11256 			 * reflective, thus we will probably receive multi-
11257 			 * casts on those interfaces.
11258 			 * The ip_multirt_apply_membership_v6() succeeds if
11259 			 * the operation succeeds on at least one interface.
11260 			 */
11261 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11262 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11263 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11264 			if (ire != NULL) {
11265 				if (ire->ire_flags & RTF_MULTIRT) {
11266 					error = ip_multirt_apply_membership_v6(
11267 					    optfn, ire, connp, checkonly,
11268 					    &groupv6, fmode, &ipv6_all_zeros,
11269 					    first_mp);
11270 					done = B_TRUE;
11271 				}
11272 				ire_refrele(ire);
11273 			}
11274 			if (!done) {
11275 				error = optfn(connp, checkonly, &groupv6,
11276 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11277 			}
11278 			if (error) {
11279 				/*
11280 				 * EINPROGRESS is a soft error, needs retry
11281 				 * so don't make *outlenp zero.
11282 				 */
11283 				if (error != EINPROGRESS)
11284 					*outlenp = 0;
11285 				return (error);
11286 			}
11287 			/* OK return - copy input buffer into output buffer */
11288 			if (invalp != outvalp) {
11289 				/* don't trust bcopy for identical src/dst */
11290 				bcopy(invalp, outvalp, inlen);
11291 			}
11292 			*outlenp = inlen;
11293 			return (0);
11294 		}
11295 		case MCAST_BLOCK_SOURCE:
11296 		case MCAST_UNBLOCK_SOURCE:
11297 		case MCAST_JOIN_SOURCE_GROUP:
11298 		case MCAST_LEAVE_SOURCE_GROUP: {
11299 			struct group_source_req *gsreqp;
11300 			in6_addr_t v6grp, v6src;
11301 			uint32_t ifindex;
11302 			mcast_record_t fmode;
11303 			ire_t *ire;
11304 			boolean_t done = B_FALSE;
11305 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11306 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11307 
11308 			switch (name) {
11309 			case MCAST_BLOCK_SOURCE:
11310 				fmode = MODE_IS_EXCLUDE;
11311 				optfn = ip_opt_add_group_v6;
11312 				break;
11313 			case MCAST_UNBLOCK_SOURCE:
11314 				fmode = MODE_IS_EXCLUDE;
11315 				optfn = ip_opt_delete_group_v6;
11316 				break;
11317 			case MCAST_JOIN_SOURCE_GROUP:
11318 				fmode = MODE_IS_INCLUDE;
11319 				optfn = ip_opt_add_group_v6;
11320 				break;
11321 			case MCAST_LEAVE_SOURCE_GROUP:
11322 				fmode = MODE_IS_INCLUDE;
11323 				optfn = ip_opt_delete_group_v6;
11324 				break;
11325 			}
11326 
11327 			gsreqp = (struct group_source_req *)i1;
11328 			ifindex = gsreqp->gsr_interface;
11329 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11330 				struct sockaddr_in *s;
11331 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11332 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11333 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11334 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11335 			} else {
11336 				struct sockaddr_in6 *s6;
11337 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11338 				v6grp = s6->sin6_addr;
11339 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11340 				v6src = s6->sin6_addr;
11341 			}
11342 
11343 			/*
11344 			 * In the multirouting case, we need to replicate
11345 			 * the request as noted in the mcast cases above.
11346 			 */
11347 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11348 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11349 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11350 			if (ire != NULL) {
11351 				if (ire->ire_flags & RTF_MULTIRT) {
11352 					error = ip_multirt_apply_membership_v6(
11353 					    optfn, ire, connp, checkonly,
11354 					    &v6grp, fmode, &v6src, first_mp);
11355 					done = B_TRUE;
11356 				}
11357 				ire_refrele(ire);
11358 			}
11359 			if (!done) {
11360 				error = optfn(connp, checkonly, &v6grp,
11361 				    ifindex, fmode, &v6src, first_mp);
11362 			}
11363 			if (error != 0) {
11364 				/*
11365 				 * EINPROGRESS is a soft error, needs retry
11366 				 * so don't make *outlenp zero.
11367 				 */
11368 				if (error != EINPROGRESS)
11369 					*outlenp = 0;
11370 				return (error);
11371 			}
11372 			/* OK return - copy input buffer into output buffer */
11373 			if (invalp != outvalp) {
11374 				bcopy(invalp, outvalp, inlen);
11375 			}
11376 			*outlenp = inlen;
11377 			return (0);
11378 		}
11379 		case IPV6_UNICAST_HOPS:
11380 			/* Recorded in transport above IP */
11381 			break;	/* goto sizeof (int) option return */
11382 		case IPV6_UNSPEC_SRC:
11383 			/* Allow sending with a zero source address */
11384 			if (!checkonly) {
11385 				mutex_enter(&connp->conn_lock);
11386 				connp->conn_unspec_src = *i1 ? 1 : 0;
11387 				mutex_exit(&connp->conn_lock);
11388 			}
11389 			break;	/* goto sizeof (int) option return */
11390 		case IPV6_RECVPKTINFO:
11391 			if (!checkonly) {
11392 				mutex_enter(&connp->conn_lock);
11393 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11394 				mutex_exit(&connp->conn_lock);
11395 			}
11396 			break;	/* goto sizeof (int) option return */
11397 		case IPV6_RECVTCLASS:
11398 			if (!checkonly) {
11399 				if (*i1 < 0 || *i1 > 1) {
11400 					return (EINVAL);
11401 				}
11402 				mutex_enter(&connp->conn_lock);
11403 				connp->conn_ipv6_recvtclass = *i1;
11404 				mutex_exit(&connp->conn_lock);
11405 			}
11406 			break;
11407 		case IPV6_RECVPATHMTU:
11408 			if (!checkonly) {
11409 				if (*i1 < 0 || *i1 > 1) {
11410 					return (EINVAL);
11411 				}
11412 				mutex_enter(&connp->conn_lock);
11413 				connp->conn_ipv6_recvpathmtu = *i1;
11414 				mutex_exit(&connp->conn_lock);
11415 			}
11416 			break;
11417 		case IPV6_RECVHOPLIMIT:
11418 			if (!checkonly) {
11419 				mutex_enter(&connp->conn_lock);
11420 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11421 				mutex_exit(&connp->conn_lock);
11422 			}
11423 			break;	/* goto sizeof (int) option return */
11424 		case IPV6_RECVHOPOPTS:
11425 			if (!checkonly) {
11426 				mutex_enter(&connp->conn_lock);
11427 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11428 				mutex_exit(&connp->conn_lock);
11429 			}
11430 			break;	/* goto sizeof (int) option return */
11431 		case IPV6_RECVDSTOPTS:
11432 			if (!checkonly) {
11433 				mutex_enter(&connp->conn_lock);
11434 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11435 				mutex_exit(&connp->conn_lock);
11436 			}
11437 			break;	/* goto sizeof (int) option return */
11438 		case IPV6_RECVRTHDR:
11439 			if (!checkonly) {
11440 				mutex_enter(&connp->conn_lock);
11441 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11442 				mutex_exit(&connp->conn_lock);
11443 			}
11444 			break;	/* goto sizeof (int) option return */
11445 		case IPV6_RECVRTHDRDSTOPTS:
11446 			if (!checkonly) {
11447 				mutex_enter(&connp->conn_lock);
11448 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11449 				mutex_exit(&connp->conn_lock);
11450 			}
11451 			break;	/* goto sizeof (int) option return */
11452 		case IPV6_PKTINFO:
11453 			if (inlen == 0)
11454 				return (-EINVAL);	/* clearing option */
11455 			error = ip6_set_pktinfo(cr, connp,
11456 			    (struct in6_pktinfo *)invalp, first_mp);
11457 			if (error != 0)
11458 				*outlenp = 0;
11459 			else
11460 				*outlenp = inlen;
11461 			return (error);
11462 		case IPV6_NEXTHOP: {
11463 			struct sockaddr_in6 *sin6;
11464 
11465 			/* Verify that the nexthop is reachable */
11466 			if (inlen == 0)
11467 				return (-EINVAL);	/* clearing option */
11468 
11469 			sin6 = (struct sockaddr_in6 *)invalp;
11470 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11471 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11472 			    NULL, MATCH_IRE_DEFAULT, ipst);
11473 
11474 			if (ire == NULL) {
11475 				*outlenp = 0;
11476 				return (EHOSTUNREACH);
11477 			}
11478 			ire_refrele(ire);
11479 			return (-EINVAL);
11480 		}
11481 		case IPV6_SEC_OPT:
11482 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11483 			if (error != 0) {
11484 				*outlenp = 0;
11485 				return (error);
11486 			}
11487 			break;
11488 		case IPV6_SRC_PREFERENCES: {
11489 			/*
11490 			 * This is implemented strictly in the ip module
11491 			 * (here and in tcp_opt_*() to accomodate tcp
11492 			 * sockets).  Modules above ip pass this option
11493 			 * down here since ip is the only one that needs to
11494 			 * be aware of source address preferences.
11495 			 *
11496 			 * This socket option only affects connected
11497 			 * sockets that haven't already bound to a specific
11498 			 * IPv6 address.  In other words, sockets that
11499 			 * don't call bind() with an address other than the
11500 			 * unspecified address and that call connect().
11501 			 * ip_bind_connected_v6() passes these preferences
11502 			 * to the ipif_select_source_v6() function.
11503 			 */
11504 			if (inlen != sizeof (uint32_t))
11505 				return (EINVAL);
11506 			error = ip6_set_src_preferences(connp,
11507 			    *(uint32_t *)invalp);
11508 			if (error != 0) {
11509 				*outlenp = 0;
11510 				return (error);
11511 			} else {
11512 				*outlenp = sizeof (uint32_t);
11513 			}
11514 			break;
11515 		}
11516 		case IPV6_V6ONLY:
11517 			if (*i1 < 0 || *i1 > 1) {
11518 				return (EINVAL);
11519 			}
11520 			mutex_enter(&connp->conn_lock);
11521 			connp->conn_ipv6_v6only = *i1;
11522 			mutex_exit(&connp->conn_lock);
11523 			break;
11524 		default:
11525 			return (-EINVAL);
11526 		}
11527 		break;
11528 	default:
11529 		/*
11530 		 * "soft" error (negative)
11531 		 * option not handled at this level
11532 		 * Note: Do not modify *outlenp
11533 		 */
11534 		return (-EINVAL);
11535 	}
11536 	/*
11537 	 * Common case of return from an option that is sizeof (int)
11538 	 */
11539 	*(int *)outvalp = *i1;
11540 	*outlenp = sizeof (int);
11541 	return (0);
11542 }
11543 
11544 /*
11545  * This routine gets default values of certain options whose default
11546  * values are maintained by protocol specific code
11547  */
11548 /* ARGSUSED */
11549 int
11550 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11551 {
11552 	int *i1 = (int *)ptr;
11553 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11554 
11555 	switch (level) {
11556 	case IPPROTO_IP:
11557 		switch (name) {
11558 		case IP_MULTICAST_TTL:
11559 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11560 			return (sizeof (uchar_t));
11561 		case IP_MULTICAST_LOOP:
11562 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11563 			return (sizeof (uchar_t));
11564 		default:
11565 			return (-1);
11566 		}
11567 	case IPPROTO_IPV6:
11568 		switch (name) {
11569 		case IPV6_UNICAST_HOPS:
11570 			*i1 = ipst->ips_ipv6_def_hops;
11571 			return (sizeof (int));
11572 		case IPV6_MULTICAST_HOPS:
11573 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11574 			return (sizeof (int));
11575 		case IPV6_MULTICAST_LOOP:
11576 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11577 			return (sizeof (int));
11578 		case IPV6_V6ONLY:
11579 			*i1 = 1;
11580 			return (sizeof (int));
11581 		default:
11582 			return (-1);
11583 		}
11584 	default:
11585 		return (-1);
11586 	}
11587 	/* NOTREACHED */
11588 }
11589 
11590 /*
11591  * Given a destination address and a pointer to where to put the information
11592  * this routine fills in the mtuinfo.
11593  */
11594 int
11595 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11596     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11597 {
11598 	ire_t *ire;
11599 	ip_stack_t	*ipst = ns->netstack_ip;
11600 
11601 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11602 		return (-1);
11603 
11604 	bzero(mtuinfo, sizeof (*mtuinfo));
11605 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11606 	mtuinfo->ip6m_addr.sin6_port = port;
11607 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11608 
11609 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11610 	if (ire != NULL) {
11611 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11612 		ire_refrele(ire);
11613 	} else {
11614 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11615 	}
11616 	return (sizeof (struct ip6_mtuinfo));
11617 }
11618 
11619 /*
11620  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11621  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11622  * isn't.  This doesn't matter as the error checking is done properly for the
11623  * other MRT options coming in through ip_opt_set.
11624  */
11625 int
11626 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11627 {
11628 	conn_t		*connp = Q_TO_CONN(q);
11629 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11630 
11631 	switch (level) {
11632 	case IPPROTO_IP:
11633 		switch (name) {
11634 		case MRT_VERSION:
11635 		case MRT_ASSERT:
11636 			(void) ip_mrouter_get(name, q, ptr);
11637 			return (sizeof (int));
11638 		case IP_SEC_OPT:
11639 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11640 		case IP_NEXTHOP:
11641 			if (connp->conn_nexthop_set) {
11642 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11643 				return (sizeof (ipaddr_t));
11644 			} else
11645 				return (0);
11646 		case IP_RECVPKTINFO:
11647 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11648 			return (sizeof (int));
11649 		default:
11650 			break;
11651 		}
11652 		break;
11653 	case IPPROTO_IPV6:
11654 		switch (name) {
11655 		case IPV6_SEC_OPT:
11656 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11657 		case IPV6_SRC_PREFERENCES: {
11658 			return (ip6_get_src_preferences(connp,
11659 			    (uint32_t *)ptr));
11660 		}
11661 		case IPV6_V6ONLY:
11662 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11663 			return (sizeof (int));
11664 		case IPV6_PATHMTU:
11665 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11666 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11667 		default:
11668 			break;
11669 		}
11670 		break;
11671 	default:
11672 		break;
11673 	}
11674 	return (-1);
11675 }
11676 
11677 /* Named Dispatch routine to get a current value out of our parameter table. */
11678 /* ARGSUSED */
11679 static int
11680 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11681 {
11682 	ipparam_t *ippa = (ipparam_t *)cp;
11683 
11684 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11685 	return (0);
11686 }
11687 
11688 /* ARGSUSED */
11689 static int
11690 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11691 {
11692 
11693 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11694 	return (0);
11695 }
11696 
11697 /*
11698  * Set ip{,6}_forwarding values.  This means walking through all of the
11699  * ill's and toggling their forwarding values.
11700  */
11701 /* ARGSUSED */
11702 static int
11703 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11704 {
11705 	long new_value;
11706 	int *forwarding_value = (int *)cp;
11707 	ill_t *ill;
11708 	boolean_t isv6;
11709 	ill_walk_context_t ctx;
11710 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11711 
11712 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11713 
11714 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11715 	    new_value < 0 || new_value > 1) {
11716 		return (EINVAL);
11717 	}
11718 
11719 	*forwarding_value = new_value;
11720 
11721 	/*
11722 	 * Regardless of the current value of ip_forwarding, set all per-ill
11723 	 * values of ip_forwarding to the value being set.
11724 	 *
11725 	 * Bring all the ill's up to date with the new global value.
11726 	 */
11727 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11728 
11729 	if (isv6)
11730 		ill = ILL_START_WALK_V6(&ctx, ipst);
11731 	else
11732 		ill = ILL_START_WALK_V4(&ctx, ipst);
11733 
11734 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11735 		(void) ill_forward_set(ill, new_value != 0);
11736 
11737 	rw_exit(&ipst->ips_ill_g_lock);
11738 	return (0);
11739 }
11740 
11741 /*
11742  * Walk through the param array specified registering each element with the
11743  * Named Dispatch handler. This is called only during init. So it is ok
11744  * not to acquire any locks
11745  */
11746 static boolean_t
11747 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11748     ipndp_t *ipnd, size_t ipnd_cnt)
11749 {
11750 	for (; ippa_cnt-- > 0; ippa++) {
11751 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11752 			if (!nd_load(ndp, ippa->ip_param_name,
11753 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11754 				nd_free(ndp);
11755 				return (B_FALSE);
11756 			}
11757 		}
11758 	}
11759 
11760 	for (; ipnd_cnt-- > 0; ipnd++) {
11761 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11762 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11763 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11764 			    ipnd->ip_ndp_data)) {
11765 				nd_free(ndp);
11766 				return (B_FALSE);
11767 			}
11768 		}
11769 	}
11770 
11771 	return (B_TRUE);
11772 }
11773 
11774 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11775 /* ARGSUSED */
11776 static int
11777 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11778 {
11779 	long		new_value;
11780 	ipparam_t	*ippa = (ipparam_t *)cp;
11781 
11782 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11783 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11784 		return (EINVAL);
11785 	}
11786 	ippa->ip_param_value = new_value;
11787 	return (0);
11788 }
11789 
11790 /*
11791  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11792  * When an ipf is passed here for the first time, if
11793  * we already have in-order fragments on the queue, we convert from the fast-
11794  * path reassembly scheme to the hard-case scheme.  From then on, additional
11795  * fragments are reassembled here.  We keep track of the start and end offsets
11796  * of each piece, and the number of holes in the chain.  When the hole count
11797  * goes to zero, we are done!
11798  *
11799  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11800  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11801  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11802  * after the call to ip_reassemble().
11803  */
11804 int
11805 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11806     size_t msg_len)
11807 {
11808 	uint_t	end;
11809 	mblk_t	*next_mp;
11810 	mblk_t	*mp1;
11811 	uint_t	offset;
11812 	boolean_t incr_dups = B_TRUE;
11813 	boolean_t offset_zero_seen = B_FALSE;
11814 	boolean_t pkt_boundary_checked = B_FALSE;
11815 
11816 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11817 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11818 
11819 	/* Add in byte count */
11820 	ipf->ipf_count += msg_len;
11821 	if (ipf->ipf_end) {
11822 		/*
11823 		 * We were part way through in-order reassembly, but now there
11824 		 * is a hole.  We walk through messages already queued, and
11825 		 * mark them for hard case reassembly.  We know that up till
11826 		 * now they were in order starting from offset zero.
11827 		 */
11828 		offset = 0;
11829 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11830 			IP_REASS_SET_START(mp1, offset);
11831 			if (offset == 0) {
11832 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11833 				offset = -ipf->ipf_nf_hdr_len;
11834 			}
11835 			offset += mp1->b_wptr - mp1->b_rptr;
11836 			IP_REASS_SET_END(mp1, offset);
11837 		}
11838 		/* One hole at the end. */
11839 		ipf->ipf_hole_cnt = 1;
11840 		/* Brand it as a hard case, forever. */
11841 		ipf->ipf_end = 0;
11842 	}
11843 	/* Walk through all the new pieces. */
11844 	do {
11845 		end = start + (mp->b_wptr - mp->b_rptr);
11846 		/*
11847 		 * If start is 0, decrease 'end' only for the first mblk of
11848 		 * the fragment. Otherwise 'end' can get wrong value in the
11849 		 * second pass of the loop if first mblk is exactly the
11850 		 * size of ipf_nf_hdr_len.
11851 		 */
11852 		if (start == 0 && !offset_zero_seen) {
11853 			/* First segment */
11854 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11855 			end -= ipf->ipf_nf_hdr_len;
11856 			offset_zero_seen = B_TRUE;
11857 		}
11858 		next_mp = mp->b_cont;
11859 		/*
11860 		 * We are checking to see if there is any interesing data
11861 		 * to process.  If there isn't and the mblk isn't the
11862 		 * one which carries the unfragmentable header then we
11863 		 * drop it.  It's possible to have just the unfragmentable
11864 		 * header come through without any data.  That needs to be
11865 		 * saved.
11866 		 *
11867 		 * If the assert at the top of this function holds then the
11868 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11869 		 * is infrequently traveled enough that the test is left in
11870 		 * to protect against future code changes which break that
11871 		 * invariant.
11872 		 */
11873 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11874 			/* Empty.  Blast it. */
11875 			IP_REASS_SET_START(mp, 0);
11876 			IP_REASS_SET_END(mp, 0);
11877 			/*
11878 			 * If the ipf points to the mblk we are about to free,
11879 			 * update ipf to point to the next mblk (or NULL
11880 			 * if none).
11881 			 */
11882 			if (ipf->ipf_mp->b_cont == mp)
11883 				ipf->ipf_mp->b_cont = next_mp;
11884 			freeb(mp);
11885 			continue;
11886 		}
11887 		mp->b_cont = NULL;
11888 		IP_REASS_SET_START(mp, start);
11889 		IP_REASS_SET_END(mp, end);
11890 		if (!ipf->ipf_tail_mp) {
11891 			ipf->ipf_tail_mp = mp;
11892 			ipf->ipf_mp->b_cont = mp;
11893 			if (start == 0 || !more) {
11894 				ipf->ipf_hole_cnt = 1;
11895 				/*
11896 				 * if the first fragment comes in more than one
11897 				 * mblk, this loop will be executed for each
11898 				 * mblk. Need to adjust hole count so exiting
11899 				 * this routine will leave hole count at 1.
11900 				 */
11901 				if (next_mp)
11902 					ipf->ipf_hole_cnt++;
11903 			} else
11904 				ipf->ipf_hole_cnt = 2;
11905 			continue;
11906 		} else if (ipf->ipf_last_frag_seen && !more &&
11907 		    !pkt_boundary_checked) {
11908 			/*
11909 			 * We check datagram boundary only if this fragment
11910 			 * claims to be the last fragment and we have seen a
11911 			 * last fragment in the past too. We do this only
11912 			 * once for a given fragment.
11913 			 *
11914 			 * start cannot be 0 here as fragments with start=0
11915 			 * and MF=0 gets handled as a complete packet. These
11916 			 * fragments should not reach here.
11917 			 */
11918 
11919 			if (start + msgdsize(mp) !=
11920 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11921 				/*
11922 				 * We have two fragments both of which claim
11923 				 * to be the last fragment but gives conflicting
11924 				 * information about the whole datagram size.
11925 				 * Something fishy is going on. Drop the
11926 				 * fragment and free up the reassembly list.
11927 				 */
11928 				return (IP_REASS_FAILED);
11929 			}
11930 
11931 			/*
11932 			 * We shouldn't come to this code block again for this
11933 			 * particular fragment.
11934 			 */
11935 			pkt_boundary_checked = B_TRUE;
11936 		}
11937 
11938 		/* New stuff at or beyond tail? */
11939 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11940 		if (start >= offset) {
11941 			if (ipf->ipf_last_frag_seen) {
11942 				/* current fragment is beyond last fragment */
11943 				return (IP_REASS_FAILED);
11944 			}
11945 			/* Link it on end. */
11946 			ipf->ipf_tail_mp->b_cont = mp;
11947 			ipf->ipf_tail_mp = mp;
11948 			if (more) {
11949 				if (start != offset)
11950 					ipf->ipf_hole_cnt++;
11951 			} else if (start == offset && next_mp == NULL)
11952 					ipf->ipf_hole_cnt--;
11953 			continue;
11954 		}
11955 		mp1 = ipf->ipf_mp->b_cont;
11956 		offset = IP_REASS_START(mp1);
11957 		/* New stuff at the front? */
11958 		if (start < offset) {
11959 			if (start == 0) {
11960 				if (end >= offset) {
11961 					/* Nailed the hole at the begining. */
11962 					ipf->ipf_hole_cnt--;
11963 				}
11964 			} else if (end < offset) {
11965 				/*
11966 				 * A hole, stuff, and a hole where there used
11967 				 * to be just a hole.
11968 				 */
11969 				ipf->ipf_hole_cnt++;
11970 			}
11971 			mp->b_cont = mp1;
11972 			/* Check for overlap. */
11973 			while (end > offset) {
11974 				if (end < IP_REASS_END(mp1)) {
11975 					mp->b_wptr -= end - offset;
11976 					IP_REASS_SET_END(mp, offset);
11977 					BUMP_MIB(ill->ill_ip_mib,
11978 					    ipIfStatsReasmPartDups);
11979 					break;
11980 				}
11981 				/* Did we cover another hole? */
11982 				if ((mp1->b_cont &&
11983 				    IP_REASS_END(mp1) !=
11984 				    IP_REASS_START(mp1->b_cont) &&
11985 				    end >= IP_REASS_START(mp1->b_cont)) ||
11986 				    (!ipf->ipf_last_frag_seen && !more)) {
11987 					ipf->ipf_hole_cnt--;
11988 				}
11989 				/* Clip out mp1. */
11990 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11991 					/*
11992 					 * After clipping out mp1, this guy
11993 					 * is now hanging off the end.
11994 					 */
11995 					ipf->ipf_tail_mp = mp;
11996 				}
11997 				IP_REASS_SET_START(mp1, 0);
11998 				IP_REASS_SET_END(mp1, 0);
11999 				/* Subtract byte count */
12000 				ipf->ipf_count -= mp1->b_datap->db_lim -
12001 				    mp1->b_datap->db_base;
12002 				freeb(mp1);
12003 				BUMP_MIB(ill->ill_ip_mib,
12004 				    ipIfStatsReasmPartDups);
12005 				mp1 = mp->b_cont;
12006 				if (!mp1)
12007 					break;
12008 				offset = IP_REASS_START(mp1);
12009 			}
12010 			ipf->ipf_mp->b_cont = mp;
12011 			continue;
12012 		}
12013 		/*
12014 		 * The new piece starts somewhere between the start of the head
12015 		 * and before the end of the tail.
12016 		 */
12017 		for (; mp1; mp1 = mp1->b_cont) {
12018 			offset = IP_REASS_END(mp1);
12019 			if (start < offset) {
12020 				if (end <= offset) {
12021 					/* Nothing new. */
12022 					IP_REASS_SET_START(mp, 0);
12023 					IP_REASS_SET_END(mp, 0);
12024 					/* Subtract byte count */
12025 					ipf->ipf_count -= mp->b_datap->db_lim -
12026 					    mp->b_datap->db_base;
12027 					if (incr_dups) {
12028 						ipf->ipf_num_dups++;
12029 						incr_dups = B_FALSE;
12030 					}
12031 					freeb(mp);
12032 					BUMP_MIB(ill->ill_ip_mib,
12033 					    ipIfStatsReasmDuplicates);
12034 					break;
12035 				}
12036 				/*
12037 				 * Trim redundant stuff off beginning of new
12038 				 * piece.
12039 				 */
12040 				IP_REASS_SET_START(mp, offset);
12041 				mp->b_rptr += offset - start;
12042 				BUMP_MIB(ill->ill_ip_mib,
12043 				    ipIfStatsReasmPartDups);
12044 				start = offset;
12045 				if (!mp1->b_cont) {
12046 					/*
12047 					 * After trimming, this guy is now
12048 					 * hanging off the end.
12049 					 */
12050 					mp1->b_cont = mp;
12051 					ipf->ipf_tail_mp = mp;
12052 					if (!more) {
12053 						ipf->ipf_hole_cnt--;
12054 					}
12055 					break;
12056 				}
12057 			}
12058 			if (start >= IP_REASS_START(mp1->b_cont))
12059 				continue;
12060 			/* Fill a hole */
12061 			if (start > offset)
12062 				ipf->ipf_hole_cnt++;
12063 			mp->b_cont = mp1->b_cont;
12064 			mp1->b_cont = mp;
12065 			mp1 = mp->b_cont;
12066 			offset = IP_REASS_START(mp1);
12067 			if (end >= offset) {
12068 				ipf->ipf_hole_cnt--;
12069 				/* Check for overlap. */
12070 				while (end > offset) {
12071 					if (end < IP_REASS_END(mp1)) {
12072 						mp->b_wptr -= end - offset;
12073 						IP_REASS_SET_END(mp, offset);
12074 						/*
12075 						 * TODO we might bump
12076 						 * this up twice if there is
12077 						 * overlap at both ends.
12078 						 */
12079 						BUMP_MIB(ill->ill_ip_mib,
12080 						    ipIfStatsReasmPartDups);
12081 						break;
12082 					}
12083 					/* Did we cover another hole? */
12084 					if ((mp1->b_cont &&
12085 					    IP_REASS_END(mp1)
12086 					    != IP_REASS_START(mp1->b_cont) &&
12087 					    end >=
12088 					    IP_REASS_START(mp1->b_cont)) ||
12089 					    (!ipf->ipf_last_frag_seen &&
12090 					    !more)) {
12091 						ipf->ipf_hole_cnt--;
12092 					}
12093 					/* Clip out mp1. */
12094 					if ((mp->b_cont = mp1->b_cont) ==
12095 					    NULL) {
12096 						/*
12097 						 * After clipping out mp1,
12098 						 * this guy is now hanging
12099 						 * off the end.
12100 						 */
12101 						ipf->ipf_tail_mp = mp;
12102 					}
12103 					IP_REASS_SET_START(mp1, 0);
12104 					IP_REASS_SET_END(mp1, 0);
12105 					/* Subtract byte count */
12106 					ipf->ipf_count -=
12107 					    mp1->b_datap->db_lim -
12108 					    mp1->b_datap->db_base;
12109 					freeb(mp1);
12110 					BUMP_MIB(ill->ill_ip_mib,
12111 					    ipIfStatsReasmPartDups);
12112 					mp1 = mp->b_cont;
12113 					if (!mp1)
12114 						break;
12115 					offset = IP_REASS_START(mp1);
12116 				}
12117 			}
12118 			break;
12119 		}
12120 	} while (start = end, mp = next_mp);
12121 
12122 	/* Fragment just processed could be the last one. Remember this fact */
12123 	if (!more)
12124 		ipf->ipf_last_frag_seen = B_TRUE;
12125 
12126 	/* Still got holes? */
12127 	if (ipf->ipf_hole_cnt)
12128 		return (IP_REASS_PARTIAL);
12129 	/* Clean up overloaded fields to avoid upstream disasters. */
12130 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12131 		IP_REASS_SET_START(mp1, 0);
12132 		IP_REASS_SET_END(mp1, 0);
12133 	}
12134 	return (IP_REASS_COMPLETE);
12135 }
12136 
12137 /*
12138  * ipsec processing for the fast path, used for input UDP Packets
12139  * Returns true if ready for passup to UDP.
12140  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12141  * was an ESP-in-UDP packet, etc.).
12142  */
12143 static boolean_t
12144 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12145     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12146 {
12147 	uint32_t	ill_index;
12148 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12149 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12150 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12151 	udp_t		*udp = connp->conn_udp;
12152 
12153 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12154 	/* The ill_index of the incoming ILL */
12155 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12156 
12157 	/* pass packet up to the transport */
12158 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12159 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12160 		    NULL, mctl_present);
12161 		if (*first_mpp == NULL) {
12162 			return (B_FALSE);
12163 		}
12164 	}
12165 
12166 	/* Initiate IPPF processing for fastpath UDP */
12167 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12168 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12169 		if (*mpp == NULL) {
12170 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12171 			    "deferred/dropped during IPPF processing\n"));
12172 			return (B_FALSE);
12173 		}
12174 	}
12175 	/*
12176 	 * Remove 0-spi if it's 0, or move everything behind
12177 	 * the UDP header over it and forward to ESP via
12178 	 * ip_proto_input().
12179 	 */
12180 	if (udp->udp_nat_t_endpoint) {
12181 		if (mctl_present) {
12182 			/* mctl_present *shouldn't* happen. */
12183 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12184 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12185 			    &ipss->ipsec_dropper);
12186 			*first_mpp = NULL;
12187 			return (B_FALSE);
12188 		}
12189 
12190 		/* "ill" is "recv_ill" in actuality. */
12191 		if (!zero_spi_check(q, *mpp, ipha, ire, ill, ipss))
12192 			return (B_FALSE);
12193 
12194 		/* Else continue like a normal UDP packet. */
12195 	}
12196 
12197 	/*
12198 	 * We make the checks as below since we are in the fast path
12199 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12200 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12201 	 */
12202 	if (connp->conn_recvif || connp->conn_recvslla ||
12203 	    connp->conn_ip_recvpktinfo) {
12204 		if (connp->conn_recvif) {
12205 			in_flags = IPF_RECVIF;
12206 		}
12207 		/*
12208 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12209 		 * so the flag passed to ip_add_info is based on IP version
12210 		 * of connp.
12211 		 */
12212 		if (connp->conn_ip_recvpktinfo) {
12213 			if (connp->conn_af_isv6) {
12214 				/*
12215 				 * V6 only needs index
12216 				 */
12217 				in_flags |= IPF_RECVIF;
12218 			} else {
12219 				/*
12220 				 * V4 needs index + matching address.
12221 				 */
12222 				in_flags |= IPF_RECVADDR;
12223 			}
12224 		}
12225 		if (connp->conn_recvslla) {
12226 			in_flags |= IPF_RECVSLLA;
12227 		}
12228 		/*
12229 		 * since in_flags are being set ill will be
12230 		 * referenced in ip_add_info, so it better not
12231 		 * be NULL.
12232 		 */
12233 		/*
12234 		 * the actual data will be contained in b_cont
12235 		 * upon successful return of the following call.
12236 		 * If the call fails then the original mblk is
12237 		 * returned.
12238 		 */
12239 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12240 		    ipst);
12241 	}
12242 
12243 	return (B_TRUE);
12244 }
12245 
12246 /*
12247  * Fragmentation reassembly.  Each ILL has a hash table for
12248  * queuing packets undergoing reassembly for all IPIFs
12249  * associated with the ILL.  The hash is based on the packet
12250  * IP ident field.  The ILL frag hash table was allocated
12251  * as a timer block at the time the ILL was created.  Whenever
12252  * there is anything on the reassembly queue, the timer will
12253  * be running.  Returns B_TRUE if successful else B_FALSE;
12254  * frees mp on failure.
12255  */
12256 static boolean_t
12257 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12258     uint32_t *cksum_val, uint16_t *cksum_flags)
12259 {
12260 	uint32_t	frag_offset_flags;
12261 	ill_t		*ill = (ill_t *)q->q_ptr;
12262 	mblk_t		*mp = *mpp;
12263 	mblk_t		*t_mp;
12264 	ipaddr_t	dst;
12265 	uint8_t		proto = ipha->ipha_protocol;
12266 	uint32_t	sum_val;
12267 	uint16_t	sum_flags;
12268 	ipf_t		*ipf;
12269 	ipf_t		**ipfp;
12270 	ipfb_t		*ipfb;
12271 	uint16_t	ident;
12272 	uint32_t	offset;
12273 	ipaddr_t	src;
12274 	uint_t		hdr_length;
12275 	uint32_t	end;
12276 	mblk_t		*mp1;
12277 	mblk_t		*tail_mp;
12278 	size_t		count;
12279 	size_t		msg_len;
12280 	uint8_t		ecn_info = 0;
12281 	uint32_t	packet_size;
12282 	boolean_t	pruned = B_FALSE;
12283 	ip_stack_t *ipst = ill->ill_ipst;
12284 
12285 	if (cksum_val != NULL)
12286 		*cksum_val = 0;
12287 	if (cksum_flags != NULL)
12288 		*cksum_flags = 0;
12289 
12290 	/*
12291 	 * Drop the fragmented as early as possible, if
12292 	 * we don't have resource(s) to re-assemble.
12293 	 */
12294 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12295 		freemsg(mp);
12296 		return (B_FALSE);
12297 	}
12298 
12299 	/* Check for fragmentation offset; return if there's none */
12300 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12301 	    (IPH_MF | IPH_OFFSET)) == 0)
12302 		return (B_TRUE);
12303 
12304 	/*
12305 	 * We utilize hardware computed checksum info only for UDP since
12306 	 * IP fragmentation is a normal occurence for the protocol.  In
12307 	 * addition, checksum offload support for IP fragments carrying
12308 	 * UDP payload is commonly implemented across network adapters.
12309 	 */
12310 	ASSERT(ill != NULL);
12311 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12312 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12313 		mblk_t *mp1 = mp->b_cont;
12314 		int32_t len;
12315 
12316 		/* Record checksum information from the packet */
12317 		sum_val = (uint32_t)DB_CKSUM16(mp);
12318 		sum_flags = DB_CKSUMFLAGS(mp);
12319 
12320 		/* IP payload offset from beginning of mblk */
12321 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12322 
12323 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12324 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12325 		    offset >= DB_CKSUMSTART(mp) &&
12326 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12327 			uint32_t adj;
12328 			/*
12329 			 * Partial checksum has been calculated by hardware
12330 			 * and attached to the packet; in addition, any
12331 			 * prepended extraneous data is even byte aligned.
12332 			 * If any such data exists, we adjust the checksum;
12333 			 * this would also handle any postpended data.
12334 			 */
12335 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12336 			    mp, mp1, len, adj);
12337 
12338 			/* One's complement subtract extraneous checksum */
12339 			if (adj >= sum_val)
12340 				sum_val = ~(adj - sum_val) & 0xFFFF;
12341 			else
12342 				sum_val -= adj;
12343 		}
12344 	} else {
12345 		sum_val = 0;
12346 		sum_flags = 0;
12347 	}
12348 
12349 	/* Clear hardware checksumming flag */
12350 	DB_CKSUMFLAGS(mp) = 0;
12351 
12352 	ident = ipha->ipha_ident;
12353 	offset = (frag_offset_flags << 3) & 0xFFFF;
12354 	src = ipha->ipha_src;
12355 	dst = ipha->ipha_dst;
12356 	hdr_length = IPH_HDR_LENGTH(ipha);
12357 	end = ntohs(ipha->ipha_length) - hdr_length;
12358 
12359 	/* If end == 0 then we have a packet with no data, so just free it */
12360 	if (end == 0) {
12361 		freemsg(mp);
12362 		return (B_FALSE);
12363 	}
12364 
12365 	/* Record the ECN field info. */
12366 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12367 	if (offset != 0) {
12368 		/*
12369 		 * If this isn't the first piece, strip the header, and
12370 		 * add the offset to the end value.
12371 		 */
12372 		mp->b_rptr += hdr_length;
12373 		end += offset;
12374 	}
12375 
12376 	msg_len = MBLKSIZE(mp);
12377 	tail_mp = mp;
12378 	while (tail_mp->b_cont != NULL) {
12379 		tail_mp = tail_mp->b_cont;
12380 		msg_len += MBLKSIZE(tail_mp);
12381 	}
12382 
12383 	/* If the reassembly list for this ILL will get too big, prune it */
12384 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12385 	    ipst->ips_ip_reass_queue_bytes) {
12386 		ill_frag_prune(ill,
12387 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12388 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12389 		pruned = B_TRUE;
12390 	}
12391 
12392 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12393 	mutex_enter(&ipfb->ipfb_lock);
12394 
12395 	ipfp = &ipfb->ipfb_ipf;
12396 	/* Try to find an existing fragment queue for this packet. */
12397 	for (;;) {
12398 		ipf = ipfp[0];
12399 		if (ipf != NULL) {
12400 			/*
12401 			 * It has to match on ident and src/dst address.
12402 			 */
12403 			if (ipf->ipf_ident == ident &&
12404 			    ipf->ipf_src == src &&
12405 			    ipf->ipf_dst == dst &&
12406 			    ipf->ipf_protocol == proto) {
12407 				/*
12408 				 * If we have received too many
12409 				 * duplicate fragments for this packet
12410 				 * free it.
12411 				 */
12412 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12413 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12414 					freemsg(mp);
12415 					mutex_exit(&ipfb->ipfb_lock);
12416 					return (B_FALSE);
12417 				}
12418 				/* Found it. */
12419 				break;
12420 			}
12421 			ipfp = &ipf->ipf_hash_next;
12422 			continue;
12423 		}
12424 
12425 		/*
12426 		 * If we pruned the list, do we want to store this new
12427 		 * fragment?. We apply an optimization here based on the
12428 		 * fact that most fragments will be received in order.
12429 		 * So if the offset of this incoming fragment is zero,
12430 		 * it is the first fragment of a new packet. We will
12431 		 * keep it.  Otherwise drop the fragment, as we have
12432 		 * probably pruned the packet already (since the
12433 		 * packet cannot be found).
12434 		 */
12435 		if (pruned && offset != 0) {
12436 			mutex_exit(&ipfb->ipfb_lock);
12437 			freemsg(mp);
12438 			return (B_FALSE);
12439 		}
12440 
12441 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12442 			/*
12443 			 * Too many fragmented packets in this hash
12444 			 * bucket. Free the oldest.
12445 			 */
12446 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12447 		}
12448 
12449 		/* New guy.  Allocate a frag message. */
12450 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12451 		if (mp1 == NULL) {
12452 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12453 			freemsg(mp);
12454 reass_done:
12455 			mutex_exit(&ipfb->ipfb_lock);
12456 			return (B_FALSE);
12457 		}
12458 
12459 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12460 		mp1->b_cont = mp;
12461 
12462 		/* Initialize the fragment header. */
12463 		ipf = (ipf_t *)mp1->b_rptr;
12464 		ipf->ipf_mp = mp1;
12465 		ipf->ipf_ptphn = ipfp;
12466 		ipfp[0] = ipf;
12467 		ipf->ipf_hash_next = NULL;
12468 		ipf->ipf_ident = ident;
12469 		ipf->ipf_protocol = proto;
12470 		ipf->ipf_src = src;
12471 		ipf->ipf_dst = dst;
12472 		ipf->ipf_nf_hdr_len = 0;
12473 		/* Record reassembly start time. */
12474 		ipf->ipf_timestamp = gethrestime_sec();
12475 		/* Record ipf generation and account for frag header */
12476 		ipf->ipf_gen = ill->ill_ipf_gen++;
12477 		ipf->ipf_count = MBLKSIZE(mp1);
12478 		ipf->ipf_last_frag_seen = B_FALSE;
12479 		ipf->ipf_ecn = ecn_info;
12480 		ipf->ipf_num_dups = 0;
12481 		ipfb->ipfb_frag_pkts++;
12482 		ipf->ipf_checksum = 0;
12483 		ipf->ipf_checksum_flags = 0;
12484 
12485 		/* Store checksum value in fragment header */
12486 		if (sum_flags != 0) {
12487 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12488 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12489 			ipf->ipf_checksum = sum_val;
12490 			ipf->ipf_checksum_flags = sum_flags;
12491 		}
12492 
12493 		/*
12494 		 * We handle reassembly two ways.  In the easy case,
12495 		 * where all the fragments show up in order, we do
12496 		 * minimal bookkeeping, and just clip new pieces on
12497 		 * the end.  If we ever see a hole, then we go off
12498 		 * to ip_reassemble which has to mark the pieces and
12499 		 * keep track of the number of holes, etc.  Obviously,
12500 		 * the point of having both mechanisms is so we can
12501 		 * handle the easy case as efficiently as possible.
12502 		 */
12503 		if (offset == 0) {
12504 			/* Easy case, in-order reassembly so far. */
12505 			ipf->ipf_count += msg_len;
12506 			ipf->ipf_tail_mp = tail_mp;
12507 			/*
12508 			 * Keep track of next expected offset in
12509 			 * ipf_end.
12510 			 */
12511 			ipf->ipf_end = end;
12512 			ipf->ipf_nf_hdr_len = hdr_length;
12513 		} else {
12514 			/* Hard case, hole at the beginning. */
12515 			ipf->ipf_tail_mp = NULL;
12516 			/*
12517 			 * ipf_end == 0 means that we have given up
12518 			 * on easy reassembly.
12519 			 */
12520 			ipf->ipf_end = 0;
12521 
12522 			/* Forget checksum offload from now on */
12523 			ipf->ipf_checksum_flags = 0;
12524 
12525 			/*
12526 			 * ipf_hole_cnt is set by ip_reassemble.
12527 			 * ipf_count is updated by ip_reassemble.
12528 			 * No need to check for return value here
12529 			 * as we don't expect reassembly to complete
12530 			 * or fail for the first fragment itself.
12531 			 */
12532 			(void) ip_reassemble(mp, ipf,
12533 			    (frag_offset_flags & IPH_OFFSET) << 3,
12534 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12535 		}
12536 		/* Update per ipfb and ill byte counts */
12537 		ipfb->ipfb_count += ipf->ipf_count;
12538 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12539 		ill->ill_frag_count += ipf->ipf_count;
12540 		/* If the frag timer wasn't already going, start it. */
12541 		mutex_enter(&ill->ill_lock);
12542 		ill_frag_timer_start(ill);
12543 		mutex_exit(&ill->ill_lock);
12544 		goto reass_done;
12545 	}
12546 
12547 	/*
12548 	 * If the packet's flag has changed (it could be coming up
12549 	 * from an interface different than the previous, therefore
12550 	 * possibly different checksum capability), then forget about
12551 	 * any stored checksum states.  Otherwise add the value to
12552 	 * the existing one stored in the fragment header.
12553 	 */
12554 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12555 		sum_val += ipf->ipf_checksum;
12556 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12557 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12558 		ipf->ipf_checksum = sum_val;
12559 	} else if (ipf->ipf_checksum_flags != 0) {
12560 		/* Forget checksum offload from now on */
12561 		ipf->ipf_checksum_flags = 0;
12562 	}
12563 
12564 	/*
12565 	 * We have a new piece of a datagram which is already being
12566 	 * reassembled.  Update the ECN info if all IP fragments
12567 	 * are ECN capable.  If there is one which is not, clear
12568 	 * all the info.  If there is at least one which has CE
12569 	 * code point, IP needs to report that up to transport.
12570 	 */
12571 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12572 		if (ecn_info == IPH_ECN_CE)
12573 			ipf->ipf_ecn = IPH_ECN_CE;
12574 	} else {
12575 		ipf->ipf_ecn = IPH_ECN_NECT;
12576 	}
12577 	if (offset && ipf->ipf_end == offset) {
12578 		/* The new fragment fits at the end */
12579 		ipf->ipf_tail_mp->b_cont = mp;
12580 		/* Update the byte count */
12581 		ipf->ipf_count += msg_len;
12582 		/* Update per ipfb and ill byte counts */
12583 		ipfb->ipfb_count += msg_len;
12584 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12585 		ill->ill_frag_count += msg_len;
12586 		if (frag_offset_flags & IPH_MF) {
12587 			/* More to come. */
12588 			ipf->ipf_end = end;
12589 			ipf->ipf_tail_mp = tail_mp;
12590 			goto reass_done;
12591 		}
12592 	} else {
12593 		/* Go do the hard cases. */
12594 		int ret;
12595 
12596 		if (offset == 0)
12597 			ipf->ipf_nf_hdr_len = hdr_length;
12598 
12599 		/* Save current byte count */
12600 		count = ipf->ipf_count;
12601 		ret = ip_reassemble(mp, ipf,
12602 		    (frag_offset_flags & IPH_OFFSET) << 3,
12603 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12604 		/* Count of bytes added and subtracted (freeb()ed) */
12605 		count = ipf->ipf_count - count;
12606 		if (count) {
12607 			/* Update per ipfb and ill byte counts */
12608 			ipfb->ipfb_count += count;
12609 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12610 			ill->ill_frag_count += count;
12611 		}
12612 		if (ret == IP_REASS_PARTIAL) {
12613 			goto reass_done;
12614 		} else if (ret == IP_REASS_FAILED) {
12615 			/* Reassembly failed. Free up all resources */
12616 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12617 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12618 				IP_REASS_SET_START(t_mp, 0);
12619 				IP_REASS_SET_END(t_mp, 0);
12620 			}
12621 			freemsg(mp);
12622 			goto reass_done;
12623 		}
12624 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12625 	}
12626 	/*
12627 	 * We have completed reassembly.  Unhook the frag header from
12628 	 * the reassembly list.
12629 	 *
12630 	 * Before we free the frag header, record the ECN info
12631 	 * to report back to the transport.
12632 	 */
12633 	ecn_info = ipf->ipf_ecn;
12634 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12635 	ipfp = ipf->ipf_ptphn;
12636 
12637 	/* We need to supply these to caller */
12638 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12639 		sum_val = ipf->ipf_checksum;
12640 	else
12641 		sum_val = 0;
12642 
12643 	mp1 = ipf->ipf_mp;
12644 	count = ipf->ipf_count;
12645 	ipf = ipf->ipf_hash_next;
12646 	if (ipf != NULL)
12647 		ipf->ipf_ptphn = ipfp;
12648 	ipfp[0] = ipf;
12649 	ill->ill_frag_count -= count;
12650 	ASSERT(ipfb->ipfb_count >= count);
12651 	ipfb->ipfb_count -= count;
12652 	ipfb->ipfb_frag_pkts--;
12653 	mutex_exit(&ipfb->ipfb_lock);
12654 	/* Ditch the frag header. */
12655 	mp = mp1->b_cont;
12656 
12657 	freeb(mp1);
12658 
12659 	/* Restore original IP length in header. */
12660 	packet_size = (uint32_t)msgdsize(mp);
12661 	if (packet_size > IP_MAXPACKET) {
12662 		freemsg(mp);
12663 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12664 		return (B_FALSE);
12665 	}
12666 
12667 	if (DB_REF(mp) > 1) {
12668 		mblk_t *mp2 = copymsg(mp);
12669 
12670 		freemsg(mp);
12671 		if (mp2 == NULL) {
12672 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12673 			return (B_FALSE);
12674 		}
12675 		mp = mp2;
12676 	}
12677 	ipha = (ipha_t *)mp->b_rptr;
12678 
12679 	ipha->ipha_length = htons((uint16_t)packet_size);
12680 	/* We're now complete, zip the frag state */
12681 	ipha->ipha_fragment_offset_and_flags = 0;
12682 	/* Record the ECN info. */
12683 	ipha->ipha_type_of_service &= 0xFC;
12684 	ipha->ipha_type_of_service |= ecn_info;
12685 	*mpp = mp;
12686 
12687 	/* Reassembly is successful; return checksum information if needed */
12688 	if (cksum_val != NULL)
12689 		*cksum_val = sum_val;
12690 	if (cksum_flags != NULL)
12691 		*cksum_flags = sum_flags;
12692 
12693 	return (B_TRUE);
12694 }
12695 
12696 /*
12697  * Perform ip header check sum update local options.
12698  * return B_TRUE if all is well, else return B_FALSE and release
12699  * the mp. caller is responsible for decrementing ire ref cnt.
12700  */
12701 static boolean_t
12702 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12703     ip_stack_t *ipst)
12704 {
12705 	mblk_t		*first_mp;
12706 	boolean_t	mctl_present;
12707 	uint16_t	sum;
12708 
12709 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12710 	/*
12711 	 * Don't do the checksum if it has gone through AH/ESP
12712 	 * processing.
12713 	 */
12714 	if (!mctl_present) {
12715 		sum = ip_csum_hdr(ipha);
12716 		if (sum != 0) {
12717 			if (ill != NULL) {
12718 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12719 			} else {
12720 				BUMP_MIB(&ipst->ips_ip_mib,
12721 				    ipIfStatsInCksumErrs);
12722 			}
12723 			freemsg(first_mp);
12724 			return (B_FALSE);
12725 		}
12726 	}
12727 
12728 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12729 		if (mctl_present)
12730 			freeb(first_mp);
12731 		return (B_FALSE);
12732 	}
12733 
12734 	return (B_TRUE);
12735 }
12736 
12737 /*
12738  * All udp packet are delivered to the local host via this routine.
12739  */
12740 void
12741 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12742     ill_t *recv_ill)
12743 {
12744 	uint32_t	sum;
12745 	uint32_t	u1;
12746 	boolean_t	mctl_present;
12747 	conn_t		*connp;
12748 	mblk_t		*first_mp;
12749 	uint16_t	*up;
12750 	ill_t		*ill = (ill_t *)q->q_ptr;
12751 	uint16_t	reass_hck_flags = 0;
12752 	ip_stack_t	*ipst;
12753 
12754 	ASSERT(recv_ill != NULL);
12755 	ipst = recv_ill->ill_ipst;
12756 
12757 #define	rptr    ((uchar_t *)ipha)
12758 
12759 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12760 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12761 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12762 	ASSERT(ill != NULL);
12763 
12764 	/*
12765 	 * FAST PATH for udp packets
12766 	 */
12767 
12768 	/* u1 is # words of IP options */
12769 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12770 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12771 
12772 	/* IP options present */
12773 	if (u1 != 0)
12774 		goto ipoptions;
12775 
12776 	/* Check the IP header checksum.  */
12777 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12778 		/* Clear the IP header h/w cksum flag */
12779 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12780 	} else if (!mctl_present) {
12781 		/*
12782 		 * Don't verify header checksum if this packet is coming
12783 		 * back from AH/ESP as we already did it.
12784 		 */
12785 #define	uph	((uint16_t *)ipha)
12786 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12787 		    uph[6] + uph[7] + uph[8] + uph[9];
12788 #undef	uph
12789 		/* finish doing IP checksum */
12790 		sum = (sum & 0xFFFF) + (sum >> 16);
12791 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12792 		if (sum != 0 && sum != 0xFFFF) {
12793 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12794 			freemsg(first_mp);
12795 			return;
12796 		}
12797 	}
12798 
12799 	/*
12800 	 * Count for SNMP of inbound packets for ire.
12801 	 * if mctl is present this might be a secure packet and
12802 	 * has already been counted for in ip_proto_input().
12803 	 */
12804 	if (!mctl_present) {
12805 		UPDATE_IB_PKT_COUNT(ire);
12806 		ire->ire_last_used_time = lbolt;
12807 	}
12808 
12809 	/* packet part of fragmented IP packet? */
12810 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12811 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12812 		goto fragmented;
12813 	}
12814 
12815 	/* u1 = IP header length (20 bytes) */
12816 	u1 = IP_SIMPLE_HDR_LENGTH;
12817 
12818 	/* packet does not contain complete IP & UDP headers */
12819 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12820 		goto udppullup;
12821 
12822 	/* up points to UDP header */
12823 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12824 #define	iphs    ((uint16_t *)ipha)
12825 
12826 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12827 	if (up[3] != 0) {
12828 		mblk_t *mp1 = mp->b_cont;
12829 		boolean_t cksum_err;
12830 		uint16_t hck_flags = 0;
12831 
12832 		/* Pseudo-header checksum */
12833 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12834 		    iphs[9] + up[2];
12835 
12836 		/*
12837 		 * Revert to software checksum calculation if the interface
12838 		 * isn't capable of checksum offload or if IPsec is present.
12839 		 */
12840 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12841 			hck_flags = DB_CKSUMFLAGS(mp);
12842 
12843 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12844 			IP_STAT(ipst, ip_in_sw_cksum);
12845 
12846 		IP_CKSUM_RECV(hck_flags, u1,
12847 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12848 		    (int32_t)((uchar_t *)up - rptr),
12849 		    mp, mp1, cksum_err);
12850 
12851 		if (cksum_err) {
12852 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12853 			if (hck_flags & HCK_FULLCKSUM)
12854 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12855 			else if (hck_flags & HCK_PARTIALCKSUM)
12856 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12857 			else
12858 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12859 
12860 			freemsg(first_mp);
12861 			return;
12862 		}
12863 	}
12864 
12865 	/* Non-fragmented broadcast or multicast packet? */
12866 	if (ire->ire_type == IRE_BROADCAST)
12867 		goto udpslowpath;
12868 
12869 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12870 	    ire->ire_zoneid, ipst)) != NULL) {
12871 		ASSERT(connp->conn_upq != NULL);
12872 		IP_STAT(ipst, ip_udp_fast_path);
12873 
12874 		if (CONN_UDP_FLOWCTLD(connp)) {
12875 			freemsg(mp);
12876 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12877 		} else {
12878 			if (!mctl_present) {
12879 				BUMP_MIB(ill->ill_ip_mib,
12880 				    ipIfStatsHCInDelivers);
12881 			}
12882 			/*
12883 			 * mp and first_mp can change.
12884 			 */
12885 			if (ip_udp_check(q, connp, recv_ill,
12886 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12887 				/* Send it upstream */
12888 				CONN_UDP_RECV(connp, mp);
12889 			}
12890 		}
12891 		/*
12892 		 * freeb() cannot deal with null mblk being passed
12893 		 * in and first_mp can be set to null in the call
12894 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12895 		 */
12896 		if (mctl_present && first_mp != NULL) {
12897 			freeb(first_mp);
12898 		}
12899 		CONN_DEC_REF(connp);
12900 		return;
12901 	}
12902 
12903 	/*
12904 	 * if we got here we know the packet is not fragmented and
12905 	 * has no options. The classifier could not find a conn_t and
12906 	 * most likely its an icmp packet so send it through slow path.
12907 	 */
12908 
12909 	goto udpslowpath;
12910 
12911 ipoptions:
12912 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12913 		goto slow_done;
12914 	}
12915 
12916 	UPDATE_IB_PKT_COUNT(ire);
12917 	ire->ire_last_used_time = lbolt;
12918 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12919 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12920 fragmented:
12921 		/*
12922 		 * "sum" and "reass_hck_flags" are non-zero if the
12923 		 * reassembled packet has a valid hardware computed
12924 		 * checksum information associated with it.
12925 		 */
12926 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12927 			goto slow_done;
12928 		/*
12929 		 * Make sure that first_mp points back to mp as
12930 		 * the mp we came in with could have changed in
12931 		 * ip_rput_fragment().
12932 		 */
12933 		ASSERT(!mctl_present);
12934 		ipha = (ipha_t *)mp->b_rptr;
12935 		first_mp = mp;
12936 	}
12937 
12938 	/* Now we have a complete datagram, destined for this machine. */
12939 	u1 = IPH_HDR_LENGTH(ipha);
12940 	/* Pull up the UDP header, if necessary. */
12941 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12942 udppullup:
12943 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12944 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12945 			freemsg(first_mp);
12946 			goto slow_done;
12947 		}
12948 		ipha = (ipha_t *)mp->b_rptr;
12949 	}
12950 
12951 	/*
12952 	 * Validate the checksum for the reassembled packet; for the
12953 	 * pullup case we calculate the payload checksum in software.
12954 	 */
12955 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12956 	if (up[3] != 0) {
12957 		boolean_t cksum_err;
12958 
12959 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12960 			IP_STAT(ipst, ip_in_sw_cksum);
12961 
12962 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12963 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12964 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12965 		    iphs[9] + up[2], sum, cksum_err);
12966 
12967 		if (cksum_err) {
12968 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12969 
12970 			if (reass_hck_flags & HCK_FULLCKSUM)
12971 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12972 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12973 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12974 			else
12975 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12976 
12977 			freemsg(first_mp);
12978 			goto slow_done;
12979 		}
12980 	}
12981 udpslowpath:
12982 
12983 	/* Clear hardware checksum flag to be safe */
12984 	DB_CKSUMFLAGS(mp) = 0;
12985 
12986 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12987 	    (ire->ire_type == IRE_BROADCAST),
12988 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12989 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12990 
12991 slow_done:
12992 	IP_STAT(ipst, ip_udp_slow_path);
12993 	return;
12994 
12995 #undef  iphs
12996 #undef  rptr
12997 }
12998 
12999 /* ARGSUSED */
13000 static mblk_t *
13001 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13002     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13003     ill_rx_ring_t *ill_ring)
13004 {
13005 	conn_t		*connp;
13006 	uint32_t	sum;
13007 	uint32_t	u1;
13008 	uint16_t	*up;
13009 	int		offset;
13010 	ssize_t		len;
13011 	mblk_t		*mp1;
13012 	boolean_t	syn_present = B_FALSE;
13013 	tcph_t		*tcph;
13014 	uint_t		ip_hdr_len;
13015 	ill_t		*ill = (ill_t *)q->q_ptr;
13016 	zoneid_t	zoneid = ire->ire_zoneid;
13017 	boolean_t	cksum_err;
13018 	uint16_t	hck_flags = 0;
13019 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13020 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13021 
13022 #define	rptr	((uchar_t *)ipha)
13023 
13024 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13025 	ASSERT(ill != NULL);
13026 
13027 	/*
13028 	 * FAST PATH for tcp packets
13029 	 */
13030 
13031 	/* u1 is # words of IP options */
13032 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13033 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13034 
13035 	/* IP options present */
13036 	if (u1) {
13037 		goto ipoptions;
13038 	} else if (!mctl_present) {
13039 		/* Check the IP header checksum.  */
13040 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13041 			/* Clear the IP header h/w cksum flag */
13042 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13043 		} else if (!mctl_present) {
13044 			/*
13045 			 * Don't verify header checksum if this packet
13046 			 * is coming back from AH/ESP as we already did it.
13047 			 */
13048 #define	uph	((uint16_t *)ipha)
13049 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13050 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13051 #undef	uph
13052 			/* finish doing IP checksum */
13053 			sum = (sum & 0xFFFF) + (sum >> 16);
13054 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13055 			if (sum != 0 && sum != 0xFFFF) {
13056 				BUMP_MIB(ill->ill_ip_mib,
13057 				    ipIfStatsInCksumErrs);
13058 				goto error;
13059 			}
13060 		}
13061 	}
13062 
13063 	if (!mctl_present) {
13064 		UPDATE_IB_PKT_COUNT(ire);
13065 		ire->ire_last_used_time = lbolt;
13066 	}
13067 
13068 	/* packet part of fragmented IP packet? */
13069 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13070 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13071 		goto fragmented;
13072 	}
13073 
13074 	/* u1 = IP header length (20 bytes) */
13075 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13076 
13077 	/* does packet contain IP+TCP headers? */
13078 	len = mp->b_wptr - rptr;
13079 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13080 		IP_STAT(ipst, ip_tcppullup);
13081 		goto tcppullup;
13082 	}
13083 
13084 	/* TCP options present? */
13085 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13086 
13087 	/*
13088 	 * If options need to be pulled up, then goto tcpoptions.
13089 	 * otherwise we are still in the fast path
13090 	 */
13091 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13092 		IP_STAT(ipst, ip_tcpoptions);
13093 		goto tcpoptions;
13094 	}
13095 
13096 	/* multiple mblks of tcp data? */
13097 	if ((mp1 = mp->b_cont) != NULL) {
13098 		/* more then two? */
13099 		if (mp1->b_cont != NULL) {
13100 			IP_STAT(ipst, ip_multipkttcp);
13101 			goto multipkttcp;
13102 		}
13103 		len += mp1->b_wptr - mp1->b_rptr;
13104 	}
13105 
13106 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13107 
13108 	/* part of pseudo checksum */
13109 
13110 	/* TCP datagram length */
13111 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13112 
13113 #define	iphs    ((uint16_t *)ipha)
13114 
13115 #ifdef	_BIG_ENDIAN
13116 	u1 += IPPROTO_TCP;
13117 #else
13118 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13119 #endif
13120 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13121 
13122 	/*
13123 	 * Revert to software checksum calculation if the interface
13124 	 * isn't capable of checksum offload or if IPsec is present.
13125 	 */
13126 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13127 		hck_flags = DB_CKSUMFLAGS(mp);
13128 
13129 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13130 		IP_STAT(ipst, ip_in_sw_cksum);
13131 
13132 	IP_CKSUM_RECV(hck_flags, u1,
13133 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13134 	    (int32_t)((uchar_t *)up - rptr),
13135 	    mp, mp1, cksum_err);
13136 
13137 	if (cksum_err) {
13138 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13139 
13140 		if (hck_flags & HCK_FULLCKSUM)
13141 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13142 		else if (hck_flags & HCK_PARTIALCKSUM)
13143 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13144 		else
13145 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13146 
13147 		goto error;
13148 	}
13149 
13150 try_again:
13151 
13152 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13153 	    zoneid, ipst)) == NULL) {
13154 		/* Send the TH_RST */
13155 		goto no_conn;
13156 	}
13157 
13158 	/*
13159 	 * TCP FAST PATH for AF_INET socket.
13160 	 *
13161 	 * TCP fast path to avoid extra work. An AF_INET socket type
13162 	 * does not have facility to receive extra information via
13163 	 * ip_process or ip_add_info. Also, when the connection was
13164 	 * established, we made a check if this connection is impacted
13165 	 * by any global IPsec policy or per connection policy (a
13166 	 * policy that comes in effect later will not apply to this
13167 	 * connection). Since all this can be determined at the
13168 	 * connection establishment time, a quick check of flags
13169 	 * can avoid extra work.
13170 	 */
13171 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13172 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13173 		ASSERT(first_mp == mp);
13174 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13175 		SET_SQUEUE(mp, tcp_rput_data, connp);
13176 		return (mp);
13177 	}
13178 
13179 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13180 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13181 		if (IPCL_IS_TCP(connp)) {
13182 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13183 			DB_CKSUMSTART(mp) =
13184 			    (intptr_t)ip_squeue_get(ill_ring);
13185 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13186 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13187 				BUMP_MIB(ill->ill_ip_mib,
13188 				    ipIfStatsHCInDelivers);
13189 				SET_SQUEUE(mp, connp->conn_recv, connp);
13190 				return (mp);
13191 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13192 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13193 				BUMP_MIB(ill->ill_ip_mib,
13194 				    ipIfStatsHCInDelivers);
13195 				ip_squeue_enter_unbound++;
13196 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13197 				    connp);
13198 				return (mp);
13199 			}
13200 			syn_present = B_TRUE;
13201 		}
13202 
13203 	}
13204 
13205 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13206 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13207 
13208 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13209 		/* No need to send this packet to TCP */
13210 		if ((flags & TH_RST) || (flags & TH_URG)) {
13211 			CONN_DEC_REF(connp);
13212 			freemsg(first_mp);
13213 			return (NULL);
13214 		}
13215 		if (flags & TH_ACK) {
13216 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13217 			    ipst->ips_netstack->netstack_tcp, connp);
13218 			CONN_DEC_REF(connp);
13219 			return (NULL);
13220 		}
13221 
13222 		CONN_DEC_REF(connp);
13223 		freemsg(first_mp);
13224 		return (NULL);
13225 	}
13226 
13227 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13228 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13229 		    ipha, NULL, mctl_present);
13230 		if (first_mp == NULL) {
13231 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13232 			CONN_DEC_REF(connp);
13233 			return (NULL);
13234 		}
13235 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13236 			ASSERT(syn_present);
13237 			if (mctl_present) {
13238 				ASSERT(first_mp != mp);
13239 				first_mp->b_datap->db_struioflag |=
13240 				    STRUIO_POLICY;
13241 			} else {
13242 				ASSERT(first_mp == mp);
13243 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13244 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13245 			}
13246 		} else {
13247 			/*
13248 			 * Discard first_mp early since we're dealing with a
13249 			 * fully-connected conn_t and tcp doesn't do policy in
13250 			 * this case.
13251 			 */
13252 			if (mctl_present) {
13253 				freeb(first_mp);
13254 				mctl_present = B_FALSE;
13255 			}
13256 			first_mp = mp;
13257 		}
13258 	}
13259 
13260 	/* Initiate IPPF processing for fastpath */
13261 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13262 		uint32_t	ill_index;
13263 
13264 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13265 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13266 		if (mp == NULL) {
13267 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13268 			    "deferred/dropped during IPPF processing\n"));
13269 			CONN_DEC_REF(connp);
13270 			if (mctl_present)
13271 				freeb(first_mp);
13272 			return (NULL);
13273 		} else if (mctl_present) {
13274 			/*
13275 			 * ip_process might return a new mp.
13276 			 */
13277 			ASSERT(first_mp != mp);
13278 			first_mp->b_cont = mp;
13279 		} else {
13280 			first_mp = mp;
13281 		}
13282 
13283 	}
13284 
13285 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13286 		/*
13287 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13288 		 * make sure IPF_RECVIF is passed to ip_add_info.
13289 		 */
13290 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13291 		    IPCL_ZONEID(connp), ipst);
13292 		if (mp == NULL) {
13293 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13294 			CONN_DEC_REF(connp);
13295 			if (mctl_present)
13296 				freeb(first_mp);
13297 			return (NULL);
13298 		} else if (mctl_present) {
13299 			/*
13300 			 * ip_add_info might return a new mp.
13301 			 */
13302 			ASSERT(first_mp != mp);
13303 			first_mp->b_cont = mp;
13304 		} else {
13305 			first_mp = mp;
13306 		}
13307 	}
13308 
13309 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13310 	if (IPCL_IS_TCP(connp)) {
13311 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13312 		return (first_mp);
13313 	} else {
13314 		putnext(connp->conn_rq, first_mp);
13315 		CONN_DEC_REF(connp);
13316 		return (NULL);
13317 	}
13318 
13319 no_conn:
13320 	/* Initiate IPPf processing, if needed. */
13321 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13322 		uint32_t ill_index;
13323 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13324 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13325 		if (first_mp == NULL) {
13326 			return (NULL);
13327 		}
13328 	}
13329 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13330 
13331 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13332 	    ipst->ips_netstack->netstack_tcp, NULL);
13333 	return (NULL);
13334 ipoptions:
13335 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13336 		goto slow_done;
13337 	}
13338 
13339 	UPDATE_IB_PKT_COUNT(ire);
13340 	ire->ire_last_used_time = lbolt;
13341 
13342 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13343 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13344 fragmented:
13345 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13346 			if (mctl_present)
13347 				freeb(first_mp);
13348 			goto slow_done;
13349 		}
13350 		/*
13351 		 * Make sure that first_mp points back to mp as
13352 		 * the mp we came in with could have changed in
13353 		 * ip_rput_fragment().
13354 		 */
13355 		ASSERT(!mctl_present);
13356 		ipha = (ipha_t *)mp->b_rptr;
13357 		first_mp = mp;
13358 	}
13359 
13360 	/* Now we have a complete datagram, destined for this machine. */
13361 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13362 
13363 	len = mp->b_wptr - mp->b_rptr;
13364 	/* Pull up a minimal TCP header, if necessary. */
13365 	if (len < (u1 + 20)) {
13366 tcppullup:
13367 		if (!pullupmsg(mp, u1 + 20)) {
13368 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13369 			goto error;
13370 		}
13371 		ipha = (ipha_t *)mp->b_rptr;
13372 		len = mp->b_wptr - mp->b_rptr;
13373 	}
13374 
13375 	/*
13376 	 * Extract the offset field from the TCP header.  As usual, we
13377 	 * try to help the compiler more than the reader.
13378 	 */
13379 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13380 	if (offset != 5) {
13381 tcpoptions:
13382 		if (offset < 5) {
13383 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13384 			goto error;
13385 		}
13386 		/*
13387 		 * There must be TCP options.
13388 		 * Make sure we can grab them.
13389 		 */
13390 		offset <<= 2;
13391 		offset += u1;
13392 		if (len < offset) {
13393 			if (!pullupmsg(mp, offset)) {
13394 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13395 				goto error;
13396 			}
13397 			ipha = (ipha_t *)mp->b_rptr;
13398 			len = mp->b_wptr - rptr;
13399 		}
13400 	}
13401 
13402 	/* Get the total packet length in len, including headers. */
13403 	if (mp->b_cont) {
13404 multipkttcp:
13405 		len = msgdsize(mp);
13406 	}
13407 
13408 	/*
13409 	 * Check the TCP checksum by pulling together the pseudo-
13410 	 * header checksum, and passing it to ip_csum to be added in
13411 	 * with the TCP datagram.
13412 	 *
13413 	 * Since we are not using the hwcksum if available we must
13414 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13415 	 * If either of these fails along the way the mblk is freed.
13416 	 * If this logic ever changes and mblk is reused to say send
13417 	 * ICMP's back, then this flag may need to be cleared in
13418 	 * other places as well.
13419 	 */
13420 	DB_CKSUMFLAGS(mp) = 0;
13421 
13422 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13423 
13424 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13425 #ifdef	_BIG_ENDIAN
13426 	u1 += IPPROTO_TCP;
13427 #else
13428 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13429 #endif
13430 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13431 	/*
13432 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13433 	 */
13434 	IP_STAT(ipst, ip_in_sw_cksum);
13435 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13436 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13437 		goto error;
13438 	}
13439 
13440 	IP_STAT(ipst, ip_tcp_slow_path);
13441 	goto try_again;
13442 #undef  iphs
13443 #undef  rptr
13444 
13445 error:
13446 	freemsg(first_mp);
13447 slow_done:
13448 	return (NULL);
13449 }
13450 
13451 /* ARGSUSED */
13452 static void
13453 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13454     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13455 {
13456 	conn_t		*connp;
13457 	uint32_t	sum;
13458 	uint32_t	u1;
13459 	ssize_t		len;
13460 	sctp_hdr_t	*sctph;
13461 	zoneid_t	zoneid = ire->ire_zoneid;
13462 	uint32_t	pktsum;
13463 	uint32_t	calcsum;
13464 	uint32_t	ports;
13465 	in6_addr_t	map_src, map_dst;
13466 	ill_t		*ill = (ill_t *)q->q_ptr;
13467 	ip_stack_t	*ipst;
13468 	sctp_stack_t	*sctps;
13469 
13470 	ASSERT(recv_ill != NULL);
13471 	ipst = recv_ill->ill_ipst;
13472 	sctps = ipst->ips_netstack->netstack_sctp;
13473 
13474 #define	rptr	((uchar_t *)ipha)
13475 
13476 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13477 	ASSERT(ill != NULL);
13478 
13479 	/* u1 is # words of IP options */
13480 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13481 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13482 
13483 	/* IP options present */
13484 	if (u1 > 0) {
13485 		goto ipoptions;
13486 	} else {
13487 		/* Check the IP header checksum.  */
13488 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13489 		    !mctl_present) {
13490 #define	uph	((uint16_t *)ipha)
13491 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13492 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13493 #undef	uph
13494 			/* finish doing IP checksum */
13495 			sum = (sum & 0xFFFF) + (sum >> 16);
13496 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13497 			/*
13498 			 * Don't verify header checksum if this packet
13499 			 * is coming back from AH/ESP as we already did it.
13500 			 */
13501 			if (sum != 0 && sum != 0xFFFF) {
13502 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13503 				goto error;
13504 			}
13505 		}
13506 		/*
13507 		 * Since there is no SCTP h/w cksum support yet, just
13508 		 * clear the flag.
13509 		 */
13510 		DB_CKSUMFLAGS(mp) = 0;
13511 	}
13512 
13513 	/*
13514 	 * Don't verify header checksum if this packet is coming
13515 	 * back from AH/ESP as we already did it.
13516 	 */
13517 	if (!mctl_present) {
13518 		UPDATE_IB_PKT_COUNT(ire);
13519 		ire->ire_last_used_time = lbolt;
13520 	}
13521 
13522 	/* packet part of fragmented IP packet? */
13523 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13524 	if (u1 & (IPH_MF | IPH_OFFSET))
13525 		goto fragmented;
13526 
13527 	/* u1 = IP header length (20 bytes) */
13528 	u1 = IP_SIMPLE_HDR_LENGTH;
13529 
13530 find_sctp_client:
13531 	/* Pullup if we don't have the sctp common header. */
13532 	len = MBLKL(mp);
13533 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13534 		if (mp->b_cont == NULL ||
13535 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13536 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13537 			goto error;
13538 		}
13539 		ipha = (ipha_t *)mp->b_rptr;
13540 		len = MBLKL(mp);
13541 	}
13542 
13543 	sctph = (sctp_hdr_t *)(rptr + u1);
13544 #ifdef	DEBUG
13545 	if (!skip_sctp_cksum) {
13546 #endif
13547 		pktsum = sctph->sh_chksum;
13548 		sctph->sh_chksum = 0;
13549 		calcsum = sctp_cksum(mp, u1);
13550 		if (calcsum != pktsum) {
13551 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13552 			goto error;
13553 		}
13554 		sctph->sh_chksum = pktsum;
13555 #ifdef	DEBUG	/* skip_sctp_cksum */
13556 	}
13557 #endif
13558 	/* get the ports */
13559 	ports = *(uint32_t *)&sctph->sh_sport;
13560 
13561 	IRE_REFRELE(ire);
13562 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13563 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13564 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13565 	    sctps)) == NULL) {
13566 		/* Check for raw socket or OOTB handling */
13567 		goto no_conn;
13568 	}
13569 
13570 	/* Found a client; up it goes */
13571 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13572 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13573 	return;
13574 
13575 no_conn:
13576 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13577 	    ports, mctl_present, flags, B_TRUE, zoneid);
13578 	return;
13579 
13580 ipoptions:
13581 	DB_CKSUMFLAGS(mp) = 0;
13582 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13583 		goto slow_done;
13584 
13585 	UPDATE_IB_PKT_COUNT(ire);
13586 	ire->ire_last_used_time = lbolt;
13587 
13588 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13589 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13590 fragmented:
13591 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13592 			goto slow_done;
13593 		/*
13594 		 * Make sure that first_mp points back to mp as
13595 		 * the mp we came in with could have changed in
13596 		 * ip_rput_fragment().
13597 		 */
13598 		ASSERT(!mctl_present);
13599 		ipha = (ipha_t *)mp->b_rptr;
13600 		first_mp = mp;
13601 	}
13602 
13603 	/* Now we have a complete datagram, destined for this machine. */
13604 	u1 = IPH_HDR_LENGTH(ipha);
13605 	goto find_sctp_client;
13606 #undef  iphs
13607 #undef  rptr
13608 
13609 error:
13610 	freemsg(first_mp);
13611 slow_done:
13612 	IRE_REFRELE(ire);
13613 }
13614 
13615 #define	VER_BITS	0xF0
13616 #define	VERSION_6	0x60
13617 
13618 static boolean_t
13619 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13620     ipaddr_t *dstp, ip_stack_t *ipst)
13621 {
13622 	uint_t	opt_len;
13623 	ipha_t *ipha;
13624 	ssize_t len;
13625 	uint_t	pkt_len;
13626 
13627 	ASSERT(ill != NULL);
13628 	IP_STAT(ipst, ip_ipoptions);
13629 	ipha = *iphapp;
13630 
13631 #define	rptr    ((uchar_t *)ipha)
13632 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13633 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13634 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13635 		freemsg(mp);
13636 		return (B_FALSE);
13637 	}
13638 
13639 	/* multiple mblk or too short */
13640 	pkt_len = ntohs(ipha->ipha_length);
13641 
13642 	/* Get the number of words of IP options in the IP header. */
13643 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13644 	if (opt_len) {
13645 		/* IP Options present!  Validate and process. */
13646 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13647 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13648 			goto done;
13649 		}
13650 		/*
13651 		 * Recompute complete header length and make sure we
13652 		 * have access to all of it.
13653 		 */
13654 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13655 		if (len > (mp->b_wptr - rptr)) {
13656 			if (len > pkt_len) {
13657 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13658 				goto done;
13659 			}
13660 			if (!pullupmsg(mp, len)) {
13661 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13662 				goto done;
13663 			}
13664 			ipha = (ipha_t *)mp->b_rptr;
13665 		}
13666 		/*
13667 		 * Go off to ip_rput_options which returns the next hop
13668 		 * destination address, which may have been affected
13669 		 * by source routing.
13670 		 */
13671 		IP_STAT(ipst, ip_opt);
13672 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13673 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13674 			return (B_FALSE);
13675 		}
13676 	}
13677 	*iphapp = ipha;
13678 	return (B_TRUE);
13679 done:
13680 	/* clear b_prev - used by ip_mroute_decap */
13681 	mp->b_prev = NULL;
13682 	freemsg(mp);
13683 	return (B_FALSE);
13684 #undef  rptr
13685 }
13686 
13687 /*
13688  * Deal with the fact that there is no ire for the destination.
13689  */
13690 static ire_t *
13691 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13692 {
13693 	ipha_t	*ipha;
13694 	ill_t	*ill;
13695 	ire_t	*ire;
13696 	boolean_t	check_multirt = B_FALSE;
13697 	ip_stack_t *ipst;
13698 
13699 	ipha = (ipha_t *)mp->b_rptr;
13700 	ill = (ill_t *)q->q_ptr;
13701 
13702 	ASSERT(ill != NULL);
13703 	ipst = ill->ill_ipst;
13704 
13705 	/*
13706 	 * No IRE for this destination, so it can't be for us.
13707 	 * Unless we are forwarding, drop the packet.
13708 	 * We have to let source routed packets through
13709 	 * since we don't yet know if they are 'ping -l'
13710 	 * packets i.e. if they will go out over the
13711 	 * same interface as they came in on.
13712 	 */
13713 	if (ll_multicast) {
13714 		freemsg(mp);
13715 		return (NULL);
13716 	}
13717 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13718 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13719 		freemsg(mp);
13720 		return (NULL);
13721 	}
13722 
13723 	/*
13724 	 * Mark this packet as having originated externally.
13725 	 *
13726 	 * For non-forwarding code path, ire_send later double
13727 	 * checks this interface to see if it is still exists
13728 	 * post-ARP resolution.
13729 	 *
13730 	 * Also, IPQOS uses this to differentiate between
13731 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13732 	 * QOS packet processing in ip_wput_attach_llhdr().
13733 	 * The QoS module can mark the b_band for a fastpath message
13734 	 * or the dl_priority field in a unitdata_req header for
13735 	 * CoS marking. This info can only be found in
13736 	 * ip_wput_attach_llhdr().
13737 	 */
13738 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13739 	/*
13740 	 * Clear the indication that this may have a hardware checksum
13741 	 * as we are not using it
13742 	 */
13743 	DB_CKSUMFLAGS(mp) = 0;
13744 
13745 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13746 	    MBLK_GETLABEL(mp), ipst);
13747 
13748 	if (ire == NULL && check_multirt) {
13749 		/* Let ip_newroute handle CGTP  */
13750 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13751 		return (NULL);
13752 	}
13753 
13754 	if (ire != NULL)
13755 		return (ire);
13756 
13757 	mp->b_prev = mp->b_next = 0;
13758 	/* send icmp unreachable */
13759 	q = WR(q);
13760 	/* Sent by forwarding path, and router is global zone */
13761 	if (ip_source_routed(ipha, ipst)) {
13762 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13763 		    GLOBAL_ZONEID, ipst);
13764 	} else {
13765 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13766 		    ipst);
13767 	}
13768 
13769 	return (NULL);
13770 
13771 }
13772 
13773 /*
13774  * check ip header length and align it.
13775  */
13776 static boolean_t
13777 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13778 {
13779 	ssize_t len;
13780 	ill_t *ill;
13781 	ipha_t	*ipha;
13782 
13783 	len = MBLKL(mp);
13784 
13785 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13786 		ill = (ill_t *)q->q_ptr;
13787 
13788 		if (!OK_32PTR(mp->b_rptr))
13789 			IP_STAT(ipst, ip_notaligned1);
13790 		else
13791 			IP_STAT(ipst, ip_notaligned2);
13792 		/* Guard against bogus device drivers */
13793 		if (len < 0) {
13794 			/* clear b_prev - used by ip_mroute_decap */
13795 			mp->b_prev = NULL;
13796 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13797 			freemsg(mp);
13798 			return (B_FALSE);
13799 		}
13800 
13801 		if (ip_rput_pullups++ == 0) {
13802 			ipha = (ipha_t *)mp->b_rptr;
13803 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13804 			    "ip_check_and_align_header: %s forced us to "
13805 			    " pullup pkt, hdr len %ld, hdr addr %p",
13806 			    ill->ill_name, len, ipha);
13807 		}
13808 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13809 			/* clear b_prev - used by ip_mroute_decap */
13810 			mp->b_prev = NULL;
13811 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13812 			freemsg(mp);
13813 			return (B_FALSE);
13814 		}
13815 	}
13816 	return (B_TRUE);
13817 }
13818 
13819 ire_t *
13820 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13821 {
13822 	ire_t		*new_ire;
13823 	ill_t		*ire_ill;
13824 	uint_t		ifindex;
13825 	ip_stack_t	*ipst = ill->ill_ipst;
13826 	boolean_t	strict_check = B_FALSE;
13827 
13828 	/*
13829 	 * This packet came in on an interface other than the one associated
13830 	 * with the first ire we found for the destination address. We do
13831 	 * another ire lookup here, using the ingress ill, to see if the
13832 	 * interface is in an interface group.
13833 	 * As long as the ills belong to the same group, we don't consider
13834 	 * them to be arriving on the wrong interface. Thus, if the switch
13835 	 * is doing inbound load spreading, we won't drop packets when the
13836 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13837 	 * for 'usesrc groups' where the destination address may belong to
13838 	 * another interface to allow multipathing to happen.
13839 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13840 	 * where the local address may not be unique. In this case we were
13841 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13842 	 * actually returned. The new lookup, which is more specific, should
13843 	 * only find the IRE_LOCAL associated with the ingress ill if one
13844 	 * exists.
13845 	 */
13846 
13847 	if (ire->ire_ipversion == IPV4_VERSION) {
13848 		if (ipst->ips_ip_strict_dst_multihoming)
13849 			strict_check = B_TRUE;
13850 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13851 		    ill->ill_ipif, ALL_ZONES, NULL,
13852 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13853 	} else {
13854 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13855 		if (ipst->ips_ipv6_strict_dst_multihoming)
13856 			strict_check = B_TRUE;
13857 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13858 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13859 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13860 	}
13861 	/*
13862 	 * If the same ire that was returned in ip_input() is found then this
13863 	 * is an indication that interface groups are in use. The packet
13864 	 * arrived on a different ill in the group than the one associated with
13865 	 * the destination address.  If a different ire was found then the same
13866 	 * IP address must be hosted on multiple ills. This is possible with
13867 	 * unnumbered point2point interfaces. We switch to use this new ire in
13868 	 * order to have accurate interface statistics.
13869 	 */
13870 	if (new_ire != NULL) {
13871 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13872 			ire_refrele(ire);
13873 			ire = new_ire;
13874 		} else {
13875 			ire_refrele(new_ire);
13876 		}
13877 		return (ire);
13878 	} else if ((ire->ire_rfq == NULL) &&
13879 	    (ire->ire_ipversion == IPV4_VERSION)) {
13880 		/*
13881 		 * The best match could have been the original ire which
13882 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13883 		 * the strict multihoming checks are irrelevant as we consider
13884 		 * local addresses hosted on lo0 to be interface agnostic. We
13885 		 * only expect a null ire_rfq on IREs which are associated with
13886 		 * lo0 hence we can return now.
13887 		 */
13888 		return (ire);
13889 	}
13890 
13891 	/*
13892 	 * Chase pointers once and store locally.
13893 	 */
13894 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13895 	    (ill_t *)(ire->ire_rfq->q_ptr);
13896 	ifindex = ill->ill_usesrc_ifindex;
13897 
13898 	/*
13899 	 * Check if it's a legal address on the 'usesrc' interface.
13900 	 */
13901 	if ((ifindex != 0) && (ire_ill != NULL) &&
13902 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13903 		return (ire);
13904 	}
13905 
13906 	/*
13907 	 * If the ip*_strict_dst_multihoming switch is on then we can
13908 	 * only accept this packet if the interface is marked as routing.
13909 	 */
13910 	if (!(strict_check))
13911 		return (ire);
13912 
13913 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13914 	    ILLF_ROUTER) != 0) {
13915 		return (ire);
13916 	}
13917 
13918 	ire_refrele(ire);
13919 	return (NULL);
13920 }
13921 
13922 ire_t *
13923 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13924 {
13925 	ipha_t	*ipha;
13926 	ipaddr_t ip_dst, ip_src;
13927 	ire_t	*src_ire = NULL;
13928 	ill_t	*stq_ill;
13929 	uint_t	hlen;
13930 	uint_t	pkt_len;
13931 	uint32_t sum;
13932 	queue_t	*dev_q;
13933 	boolean_t check_multirt = B_FALSE;
13934 	ip_stack_t *ipst = ill->ill_ipst;
13935 
13936 	ipha = (ipha_t *)mp->b_rptr;
13937 
13938 	/*
13939 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13940 	 * The loopback address check for both src and dst has already
13941 	 * been checked in ip_input
13942 	 */
13943 	ip_dst = ntohl(dst);
13944 	ip_src = ntohl(ipha->ipha_src);
13945 
13946 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13947 	    IN_CLASSD(ip_src)) {
13948 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13949 		goto drop;
13950 	}
13951 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13952 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13953 
13954 	if (src_ire != NULL) {
13955 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13956 		goto drop;
13957 	}
13958 
13959 
13960 	/* No ire cache of nexthop. So first create one  */
13961 	if (ire == NULL) {
13962 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13963 		/*
13964 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13965 		 * is not set. So upon return from ire_forward
13966 		 * check_multirt should remain as false.
13967 		 */
13968 		ASSERT(!check_multirt);
13969 		if (ire == NULL) {
13970 			/* An attempt was made to forward the packet */
13971 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13972 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13973 			mp->b_prev = mp->b_next = 0;
13974 			/* send icmp unreachable */
13975 			/* Sent by forwarding path, and router is global zone */
13976 			if (ip_source_routed(ipha, ipst)) {
13977 				icmp_unreachable(ill->ill_wq, mp,
13978 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13979 				    ipst);
13980 			} else {
13981 				icmp_unreachable(ill->ill_wq, mp,
13982 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13983 				    ipst);
13984 			}
13985 			return (ire);
13986 		}
13987 	}
13988 
13989 	/*
13990 	 * Forwarding fastpath exception case:
13991 	 * If either of the follwoing case is true, we take
13992 	 * the slowpath
13993 	 *	o forwarding is not enabled
13994 	 *	o incoming and outgoing interface are the same, or the same
13995 	 *	  IPMP group
13996 	 *	o corresponding ire is in incomplete state
13997 	 *	o packet needs fragmentation
13998 	 *
13999 	 * The codeflow from here on is thus:
14000 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14001 	 */
14002 	pkt_len = ntohs(ipha->ipha_length);
14003 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14004 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14005 	    !(ill->ill_flags & ILLF_ROUTER) ||
14006 	    (ill == stq_ill) ||
14007 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14008 	    (ire->ire_nce == NULL) ||
14009 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14010 	    (pkt_len > ire->ire_max_frag) ||
14011 	    ipha->ipha_ttl <= 1) {
14012 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14013 		    ipha, ill, B_FALSE);
14014 		return (ire);
14015 	}
14016 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14017 
14018 	DTRACE_PROBE4(ip4__forwarding__start,
14019 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14020 
14021 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14022 	    ipst->ips_ipv4firewall_forwarding,
14023 	    ill, stq_ill, ipha, mp, mp, ipst);
14024 
14025 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14026 
14027 	if (mp == NULL)
14028 		goto drop;
14029 
14030 	mp->b_datap->db_struioun.cksum.flags = 0;
14031 	/* Adjust the checksum to reflect the ttl decrement. */
14032 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14033 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14034 	ipha->ipha_ttl--;
14035 
14036 	dev_q = ire->ire_stq->q_next;
14037 	if ((dev_q->q_next != NULL ||
14038 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14039 		goto indiscard;
14040 	}
14041 
14042 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14043 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14044 
14045 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14046 		mblk_t *mpip = mp;
14047 
14048 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14049 		if (mp != NULL) {
14050 			DTRACE_PROBE4(ip4__physical__out__start,
14051 			    ill_t *, NULL, ill_t *, stq_ill,
14052 			    ipha_t *, ipha, mblk_t *, mp);
14053 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14054 			    ipst->ips_ipv4firewall_physical_out,
14055 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14056 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14057 			    mp);
14058 			if (mp == NULL)
14059 				goto drop;
14060 
14061 			UPDATE_IB_PKT_COUNT(ire);
14062 			ire->ire_last_used_time = lbolt;
14063 			BUMP_MIB(stq_ill->ill_ip_mib,
14064 			    ipIfStatsHCOutForwDatagrams);
14065 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14066 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14067 			    pkt_len);
14068 			putnext(ire->ire_stq, mp);
14069 			return (ire);
14070 		}
14071 	}
14072 
14073 indiscard:
14074 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14075 drop:
14076 	if (mp != NULL)
14077 		freemsg(mp);
14078 	if (src_ire != NULL)
14079 		ire_refrele(src_ire);
14080 	return (ire);
14081 
14082 }
14083 
14084 /*
14085  * This function is called in the forwarding slowpath, when
14086  * either the ire lacks the link-layer address, or the packet needs
14087  * further processing(eg. fragmentation), before transmission.
14088  */
14089 
14090 static void
14091 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14092     ill_t *ill, boolean_t ll_multicast)
14093 {
14094 	ill_group_t	*ill_group;
14095 	ill_group_t	*ire_group;
14096 	queue_t		*dev_q;
14097 	ire_t		*src_ire;
14098 	ip_stack_t	*ipst = ill->ill_ipst;
14099 
14100 	ASSERT(ire->ire_stq != NULL);
14101 
14102 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14103 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14104 
14105 	if (ll_multicast != 0) {
14106 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14107 		goto drop_pkt;
14108 	}
14109 
14110 	/*
14111 	 * check if ipha_src is a broadcast address. Note that this
14112 	 * check is redundant when we get here from ip_fast_forward()
14113 	 * which has already done this check. However, since we can
14114 	 * also get here from ip_rput_process_broadcast() or, for
14115 	 * for the slow path through ip_fast_forward(), we perform
14116 	 * the check again for code-reusability
14117 	 */
14118 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14119 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14120 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14121 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14122 		if (src_ire != NULL)
14123 			ire_refrele(src_ire);
14124 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14125 		ip2dbg(("ip_rput_process_forward: Received packet with"
14126 		    " bad src/dst address on %s\n", ill->ill_name));
14127 		goto drop_pkt;
14128 	}
14129 
14130 	ill_group = ill->ill_group;
14131 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14132 	/*
14133 	 * Check if we want to forward this one at this time.
14134 	 * We allow source routed packets on a host provided that
14135 	 * they go out the same interface or same interface group
14136 	 * as they came in on.
14137 	 *
14138 	 * XXX To be quicker, we may wish to not chase pointers to
14139 	 * get the ILLF_ROUTER flag and instead store the
14140 	 * forwarding policy in the ire.  An unfortunate
14141 	 * side-effect of that would be requiring an ire flush
14142 	 * whenever the ILLF_ROUTER flag changes.
14143 	 */
14144 	if (((ill->ill_flags &
14145 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14146 	    ILLF_ROUTER) == 0) &&
14147 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14148 	    (ill_group != NULL && ill_group == ire_group)))) {
14149 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14150 		if (ip_source_routed(ipha, ipst)) {
14151 			q = WR(q);
14152 			/*
14153 			 * Clear the indication that this may have
14154 			 * hardware checksum as we are not using it.
14155 			 */
14156 			DB_CKSUMFLAGS(mp) = 0;
14157 			/* Sent by forwarding path, and router is global zone */
14158 			icmp_unreachable(q, mp,
14159 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14160 			return;
14161 		}
14162 		goto drop_pkt;
14163 	}
14164 
14165 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14166 
14167 	/* Packet is being forwarded. Turning off hwcksum flag. */
14168 	DB_CKSUMFLAGS(mp) = 0;
14169 	if (ipst->ips_ip_g_send_redirects) {
14170 		/*
14171 		 * Check whether the incoming interface and outgoing
14172 		 * interface is part of the same group. If so,
14173 		 * send redirects.
14174 		 *
14175 		 * Check the source address to see if it originated
14176 		 * on the same logical subnet it is going back out on.
14177 		 * If so, we should be able to send it a redirect.
14178 		 * Avoid sending a redirect if the destination
14179 		 * is directly connected (i.e., ipha_dst is the same
14180 		 * as ire_gateway_addr or the ire_addr of the
14181 		 * nexthop IRE_CACHE ), or if the packet was source
14182 		 * routed out this interface.
14183 		 */
14184 		ipaddr_t src, nhop;
14185 		mblk_t	*mp1;
14186 		ire_t	*nhop_ire = NULL;
14187 
14188 		/*
14189 		 * Check whether ire_rfq and q are from the same ill
14190 		 * or if they are not same, they at least belong
14191 		 * to the same group. If so, send redirects.
14192 		 */
14193 		if ((ire->ire_rfq == q ||
14194 		    (ill_group != NULL && ill_group == ire_group)) &&
14195 		    !ip_source_routed(ipha, ipst)) {
14196 
14197 			nhop = (ire->ire_gateway_addr != 0 ?
14198 			    ire->ire_gateway_addr : ire->ire_addr);
14199 
14200 			if (ipha->ipha_dst == nhop) {
14201 				/*
14202 				 * We avoid sending a redirect if the
14203 				 * destination is directly connected
14204 				 * because it is possible that multiple
14205 				 * IP subnets may have been configured on
14206 				 * the link, and the source may not
14207 				 * be on the same subnet as ip destination,
14208 				 * even though they are on the same
14209 				 * physical link.
14210 				 */
14211 				goto sendit;
14212 			}
14213 
14214 			src = ipha->ipha_src;
14215 
14216 			/*
14217 			 * We look up the interface ire for the nexthop,
14218 			 * to see if ipha_src is in the same subnet
14219 			 * as the nexthop.
14220 			 *
14221 			 * Note that, if, in the future, IRE_CACHE entries
14222 			 * are obsoleted,  this lookup will not be needed,
14223 			 * as the ire passed to this function will be the
14224 			 * same as the nhop_ire computed below.
14225 			 */
14226 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14227 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14228 			    0, NULL, MATCH_IRE_TYPE, ipst);
14229 
14230 			if (nhop_ire != NULL) {
14231 				if ((src & nhop_ire->ire_mask) ==
14232 				    (nhop & nhop_ire->ire_mask)) {
14233 					/*
14234 					 * The source is directly connected.
14235 					 * Just copy the ip header (which is
14236 					 * in the first mblk)
14237 					 */
14238 					mp1 = copyb(mp);
14239 					if (mp1 != NULL) {
14240 						icmp_send_redirect(WR(q), mp1,
14241 						    nhop, ipst);
14242 					}
14243 				}
14244 				ire_refrele(nhop_ire);
14245 			}
14246 		}
14247 	}
14248 sendit:
14249 	dev_q = ire->ire_stq->q_next;
14250 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14251 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14252 		freemsg(mp);
14253 		return;
14254 	}
14255 
14256 	ip_rput_forward(ire, ipha, mp, ill);
14257 	return;
14258 
14259 drop_pkt:
14260 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14261 	freemsg(mp);
14262 }
14263 
14264 ire_t *
14265 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14266     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14267 {
14268 	queue_t		*q;
14269 	uint16_t	hcksumflags;
14270 	ip_stack_t	*ipst = ill->ill_ipst;
14271 
14272 	q = *qp;
14273 
14274 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14275 
14276 	/*
14277 	 * Clear the indication that this may have hardware
14278 	 * checksum as we are not using it for forwarding.
14279 	 */
14280 	hcksumflags = DB_CKSUMFLAGS(mp);
14281 	DB_CKSUMFLAGS(mp) = 0;
14282 
14283 	/*
14284 	 * Directed broadcast forwarding: if the packet came in over a
14285 	 * different interface then it is routed out over we can forward it.
14286 	 */
14287 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14288 		ire_refrele(ire);
14289 		freemsg(mp);
14290 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14291 		return (NULL);
14292 	}
14293 	/*
14294 	 * For multicast we have set dst to be INADDR_BROADCAST
14295 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14296 	 * only for broadcast packets.
14297 	 */
14298 	if (!CLASSD(ipha->ipha_dst)) {
14299 		ire_t *new_ire;
14300 		ipif_t *ipif;
14301 		/*
14302 		 * For ill groups, as the switch duplicates broadcasts
14303 		 * across all the ports, we need to filter out and
14304 		 * send up only one copy. There is one copy for every
14305 		 * broadcast address on each ill. Thus, we look for a
14306 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14307 		 * later to see whether this ill is eligible to receive
14308 		 * them or not. ill_nominate_bcast_rcv() nominates only
14309 		 * one set of IREs for receiving.
14310 		 */
14311 
14312 		ipif = ipif_get_next_ipif(NULL, ill);
14313 		if (ipif == NULL) {
14314 			ire_refrele(ire);
14315 			freemsg(mp);
14316 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14317 			return (NULL);
14318 		}
14319 		new_ire = ire_ctable_lookup(dst, 0, 0,
14320 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14321 		ipif_refrele(ipif);
14322 
14323 		if (new_ire != NULL) {
14324 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14325 				ire_refrele(ire);
14326 				ire_refrele(new_ire);
14327 				freemsg(mp);
14328 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14329 				return (NULL);
14330 			}
14331 			/*
14332 			 * In the special case of multirouted broadcast
14333 			 * packets, we unconditionally need to "gateway"
14334 			 * them to the appropriate interface here.
14335 			 * In the normal case, this cannot happen, because
14336 			 * there is no broadcast IRE tagged with the
14337 			 * RTF_MULTIRT flag.
14338 			 */
14339 			if (new_ire->ire_flags & RTF_MULTIRT) {
14340 				ire_refrele(new_ire);
14341 				if (ire->ire_rfq != NULL) {
14342 					q = ire->ire_rfq;
14343 					*qp = q;
14344 				}
14345 			} else {
14346 				ire_refrele(ire);
14347 				ire = new_ire;
14348 			}
14349 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14350 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14351 				/*
14352 				 * Free the message if
14353 				 * ip_g_forward_directed_bcast is turned
14354 				 * off for non-local broadcast.
14355 				 */
14356 				ire_refrele(ire);
14357 				freemsg(mp);
14358 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14359 				return (NULL);
14360 			}
14361 		} else {
14362 			/*
14363 			 * This CGTP packet successfully passed the
14364 			 * CGTP filter, but the related CGTP
14365 			 * broadcast IRE has not been found,
14366 			 * meaning that the redundant ipif is
14367 			 * probably down. However, if we discarded
14368 			 * this packet, its duplicate would be
14369 			 * filtered out by the CGTP filter so none
14370 			 * of them would get through. So we keep
14371 			 * going with this one.
14372 			 */
14373 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14374 			if (ire->ire_rfq != NULL) {
14375 				q = ire->ire_rfq;
14376 				*qp = q;
14377 			}
14378 		}
14379 	}
14380 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14381 		/*
14382 		 * Verify that there are not more then one
14383 		 * IRE_BROADCAST with this broadcast address which
14384 		 * has ire_stq set.
14385 		 * TODO: simplify, loop over all IRE's
14386 		 */
14387 		ire_t	*ire1;
14388 		int	num_stq = 0;
14389 		mblk_t	*mp1;
14390 
14391 		/* Find the first one with ire_stq set */
14392 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14393 		for (ire1 = ire; ire1 &&
14394 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14395 		    ire1 = ire1->ire_next)
14396 			;
14397 		if (ire1) {
14398 			ire_refrele(ire);
14399 			ire = ire1;
14400 			IRE_REFHOLD(ire);
14401 		}
14402 
14403 		/* Check if there are additional ones with stq set */
14404 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14405 			if (ire->ire_addr != ire1->ire_addr)
14406 				break;
14407 			if (ire1->ire_stq) {
14408 				num_stq++;
14409 				break;
14410 			}
14411 		}
14412 		rw_exit(&ire->ire_bucket->irb_lock);
14413 		if (num_stq == 1 && ire->ire_stq != NULL) {
14414 			ip1dbg(("ip_rput_process_broadcast: directed "
14415 			    "broadcast to 0x%x\n",
14416 			    ntohl(ire->ire_addr)));
14417 			mp1 = copymsg(mp);
14418 			if (mp1) {
14419 				switch (ipha->ipha_protocol) {
14420 				case IPPROTO_UDP:
14421 					ip_udp_input(q, mp1, ipha, ire, ill);
14422 					break;
14423 				default:
14424 					ip_proto_input(q, mp1, ipha, ire, ill,
14425 					    B_FALSE);
14426 					break;
14427 				}
14428 			}
14429 			/*
14430 			 * Adjust ttl to 2 (1+1 - the forward engine
14431 			 * will decrement it by one.
14432 			 */
14433 			if (ip_csum_hdr(ipha)) {
14434 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14435 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14436 				freemsg(mp);
14437 				ire_refrele(ire);
14438 				return (NULL);
14439 			}
14440 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14441 			ipha->ipha_hdr_checksum = 0;
14442 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14443 			ip_rput_process_forward(q, mp, ire, ipha,
14444 			    ill, ll_multicast);
14445 			ire_refrele(ire);
14446 			return (NULL);
14447 		}
14448 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14449 		    ntohl(ire->ire_addr)));
14450 	}
14451 
14452 
14453 	/* Restore any hardware checksum flags */
14454 	DB_CKSUMFLAGS(mp) = hcksumflags;
14455 	return (ire);
14456 }
14457 
14458 /* ARGSUSED */
14459 static boolean_t
14460 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14461     int *ll_multicast, ipaddr_t *dstp)
14462 {
14463 	ip_stack_t	*ipst = ill->ill_ipst;
14464 
14465 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14466 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14467 	    ntohs(ipha->ipha_length));
14468 
14469 	/*
14470 	 * Forward packets only if we have joined the allmulti
14471 	 * group on this interface.
14472 	 */
14473 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14474 		int retval;
14475 
14476 		/*
14477 		 * Clear the indication that this may have hardware
14478 		 * checksum as we are not using it.
14479 		 */
14480 		DB_CKSUMFLAGS(mp) = 0;
14481 		retval = ip_mforward(ill, ipha, mp);
14482 		/* ip_mforward updates mib variables if needed */
14483 		/* clear b_prev - used by ip_mroute_decap */
14484 		mp->b_prev = NULL;
14485 
14486 		switch (retval) {
14487 		case 0:
14488 			/*
14489 			 * pkt is okay and arrived on phyint.
14490 			 *
14491 			 * If we are running as a multicast router
14492 			 * we need to see all IGMP and/or PIM packets.
14493 			 */
14494 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14495 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14496 				goto done;
14497 			}
14498 			break;
14499 		case -1:
14500 			/* pkt is mal-formed, toss it */
14501 			goto drop_pkt;
14502 		case 1:
14503 			/* pkt is okay and arrived on a tunnel */
14504 			/*
14505 			 * If we are running a multicast router
14506 			 *  we need to see all igmp packets.
14507 			 */
14508 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14509 				*dstp = INADDR_BROADCAST;
14510 				*ll_multicast = 1;
14511 				return (B_FALSE);
14512 			}
14513 
14514 			goto drop_pkt;
14515 		}
14516 	}
14517 
14518 	ILM_WALKER_HOLD(ill);
14519 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14520 		/*
14521 		 * This might just be caused by the fact that
14522 		 * multiple IP Multicast addresses map to the same
14523 		 * link layer multicast - no need to increment counter!
14524 		 */
14525 		ILM_WALKER_RELE(ill);
14526 		freemsg(mp);
14527 		return (B_TRUE);
14528 	}
14529 	ILM_WALKER_RELE(ill);
14530 done:
14531 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14532 	/*
14533 	 * This assumes the we deliver to all streams for multicast
14534 	 * and broadcast packets.
14535 	 */
14536 	*dstp = INADDR_BROADCAST;
14537 	*ll_multicast = 1;
14538 	return (B_FALSE);
14539 drop_pkt:
14540 	ip2dbg(("ip_rput: drop pkt\n"));
14541 	freemsg(mp);
14542 	return (B_TRUE);
14543 }
14544 
14545 static boolean_t
14546 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14547     int *ll_multicast, mblk_t **mpp)
14548 {
14549 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14550 	boolean_t must_copy = B_FALSE;
14551 	struct iocblk   *iocp;
14552 	ipha_t		*ipha;
14553 	ip_stack_t	*ipst = ill->ill_ipst;
14554 
14555 #define	rptr    ((uchar_t *)ipha)
14556 
14557 	first_mp = *first_mpp;
14558 	mp = *mpp;
14559 
14560 	ASSERT(first_mp == mp);
14561 
14562 	/*
14563 	 * if db_ref > 1 then copymsg and free original. Packet may be
14564 	 * changed and do not want other entity who has a reference to this
14565 	 * message to trip over the changes. This is a blind change because
14566 	 * trying to catch all places that might change packet is too
14567 	 * difficult (since it may be a module above this one)
14568 	 *
14569 	 * This corresponds to the non-fast path case. We walk down the full
14570 	 * chain in this case, and check the db_ref count of all the dblks,
14571 	 * and do a copymsg if required. It is possible that the db_ref counts
14572 	 * of the data blocks in the mblk chain can be different.
14573 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14574 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14575 	 * 'snoop' is running.
14576 	 */
14577 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14578 		if (mp1->b_datap->db_ref > 1) {
14579 			must_copy = B_TRUE;
14580 			break;
14581 		}
14582 	}
14583 
14584 	if (must_copy) {
14585 		mp1 = copymsg(mp);
14586 		if (mp1 == NULL) {
14587 			for (mp1 = mp; mp1 != NULL;
14588 			    mp1 = mp1->b_cont) {
14589 				mp1->b_next = NULL;
14590 				mp1->b_prev = NULL;
14591 			}
14592 			freemsg(mp);
14593 			if (ill != NULL) {
14594 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14595 			} else {
14596 				BUMP_MIB(&ipst->ips_ip_mib,
14597 				    ipIfStatsInDiscards);
14598 			}
14599 			return (B_TRUE);
14600 		}
14601 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14602 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14603 			/* Copy b_prev - used by ip_mroute_decap */
14604 			to_mp->b_prev = from_mp->b_prev;
14605 			from_mp->b_prev = NULL;
14606 		}
14607 		*first_mpp = first_mp = mp1;
14608 		freemsg(mp);
14609 		mp = mp1;
14610 		*mpp = mp1;
14611 	}
14612 
14613 	ipha = (ipha_t *)mp->b_rptr;
14614 
14615 	/*
14616 	 * previous code has a case for M_DATA.
14617 	 * We want to check how that happens.
14618 	 */
14619 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14620 	switch (first_mp->b_datap->db_type) {
14621 	case M_PROTO:
14622 	case M_PCPROTO:
14623 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14624 		    DL_UNITDATA_IND) {
14625 			/* Go handle anything other than data elsewhere. */
14626 			ip_rput_dlpi(q, mp);
14627 			return (B_TRUE);
14628 		}
14629 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14630 		/* Ditch the DLPI header. */
14631 		mp1 = mp->b_cont;
14632 		ASSERT(first_mp == mp);
14633 		*first_mpp = mp1;
14634 		freeb(mp);
14635 		*mpp = mp1;
14636 		return (B_FALSE);
14637 	case M_IOCACK:
14638 		ip1dbg(("got iocack "));
14639 		iocp = (struct iocblk *)mp->b_rptr;
14640 		switch (iocp->ioc_cmd) {
14641 		case DL_IOC_HDR_INFO:
14642 			ill = (ill_t *)q->q_ptr;
14643 			ill_fastpath_ack(ill, mp);
14644 			return (B_TRUE);
14645 		case SIOCSTUNPARAM:
14646 		case OSIOCSTUNPARAM:
14647 			/* Go through qwriter_ip */
14648 			break;
14649 		case SIOCGTUNPARAM:
14650 		case OSIOCGTUNPARAM:
14651 			ip_rput_other(NULL, q, mp, NULL);
14652 			return (B_TRUE);
14653 		default:
14654 			putnext(q, mp);
14655 			return (B_TRUE);
14656 		}
14657 		/* FALLTHRU */
14658 	case M_ERROR:
14659 	case M_HANGUP:
14660 		/*
14661 		 * Since this is on the ill stream we unconditionally
14662 		 * bump up the refcount
14663 		 */
14664 		ill_refhold(ill);
14665 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14666 		return (B_TRUE);
14667 	case M_CTL:
14668 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14669 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14670 		    IPHADA_M_CTL)) {
14671 			/*
14672 			 * It's an IPsec accelerated packet.
14673 			 * Make sure that the ill from which we received the
14674 			 * packet has enabled IPsec hardware acceleration.
14675 			 */
14676 			if (!(ill->ill_capabilities &
14677 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14678 				/* IPsec kstats: bean counter */
14679 				freemsg(mp);
14680 				return (B_TRUE);
14681 			}
14682 
14683 			/*
14684 			 * Make mp point to the mblk following the M_CTL,
14685 			 * then process according to type of mp.
14686 			 * After this processing, first_mp will point to
14687 			 * the data-attributes and mp to the pkt following
14688 			 * the M_CTL.
14689 			 */
14690 			mp = first_mp->b_cont;
14691 			if (mp == NULL) {
14692 				freemsg(first_mp);
14693 				return (B_TRUE);
14694 			}
14695 			/*
14696 			 * A Hardware Accelerated packet can only be M_DATA
14697 			 * ESP or AH packet.
14698 			 */
14699 			if (mp->b_datap->db_type != M_DATA) {
14700 				/* non-M_DATA IPsec accelerated packet */
14701 				IPSECHW_DEBUG(IPSECHW_PKT,
14702 				    ("non-M_DATA IPsec accelerated pkt\n"));
14703 				freemsg(first_mp);
14704 				return (B_TRUE);
14705 			}
14706 			ipha = (ipha_t *)mp->b_rptr;
14707 			if (ipha->ipha_protocol != IPPROTO_AH &&
14708 			    ipha->ipha_protocol != IPPROTO_ESP) {
14709 				IPSECHW_DEBUG(IPSECHW_PKT,
14710 				    ("non-M_DATA IPsec accelerated pkt\n"));
14711 				freemsg(first_mp);
14712 				return (B_TRUE);
14713 			}
14714 			*mpp = mp;
14715 			return (B_FALSE);
14716 		}
14717 		putnext(q, mp);
14718 		return (B_TRUE);
14719 	case M_IOCNAK:
14720 		ip1dbg(("got iocnak "));
14721 		iocp = (struct iocblk *)mp->b_rptr;
14722 		switch (iocp->ioc_cmd) {
14723 		case SIOCSTUNPARAM:
14724 		case OSIOCSTUNPARAM:
14725 			/*
14726 			 * Since this is on the ill stream we unconditionally
14727 			 * bump up the refcount
14728 			 */
14729 			ill_refhold(ill);
14730 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14731 			return (B_TRUE);
14732 		case DL_IOC_HDR_INFO:
14733 		case SIOCGTUNPARAM:
14734 		case OSIOCGTUNPARAM:
14735 			ip_rput_other(NULL, q, mp, NULL);
14736 			return (B_TRUE);
14737 		default:
14738 			break;
14739 		}
14740 		/* FALLTHRU */
14741 	default:
14742 		putnext(q, mp);
14743 		return (B_TRUE);
14744 	}
14745 }
14746 
14747 /* Read side put procedure.  Packets coming from the wire arrive here. */
14748 void
14749 ip_rput(queue_t *q, mblk_t *mp)
14750 {
14751 	ill_t	*ill;
14752 	union DL_primitives *dl;
14753 
14754 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14755 
14756 	ill = (ill_t *)q->q_ptr;
14757 
14758 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14759 		/*
14760 		 * If things are opening or closing, only accept high-priority
14761 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14762 		 * created; on close, things hanging off the ill may have been
14763 		 * freed already.)
14764 		 */
14765 		dl = (union DL_primitives *)mp->b_rptr;
14766 		if (DB_TYPE(mp) != M_PCPROTO ||
14767 		    dl->dl_primitive == DL_UNITDATA_IND) {
14768 			/*
14769 			 * SIOC[GS]TUNPARAM ioctls can come here.
14770 			 */
14771 			inet_freemsg(mp);
14772 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14773 			    "ip_rput_end: q %p (%S)", q, "uninit");
14774 			return;
14775 		}
14776 	}
14777 
14778 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14779 	    "ip_rput_end: q %p (%S)", q, "end");
14780 
14781 	ip_input(ill, NULL, mp, NULL);
14782 }
14783 
14784 static mblk_t *
14785 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14786 {
14787 	mblk_t *mp1;
14788 	boolean_t adjusted = B_FALSE;
14789 	ip_stack_t *ipst = ill->ill_ipst;
14790 
14791 	IP_STAT(ipst, ip_db_ref);
14792 	/*
14793 	 * The IP_RECVSLLA option depends on having the
14794 	 * link layer header. First check that:
14795 	 * a> the underlying device is of type ether,
14796 	 * since this option is currently supported only
14797 	 * over ethernet.
14798 	 * b> there is enough room to copy over the link
14799 	 * layer header.
14800 	 *
14801 	 * Once the checks are done, adjust rptr so that
14802 	 * the link layer header will be copied via
14803 	 * copymsg. Note that, IFT_ETHER may be returned
14804 	 * by some non-ethernet drivers but in this case
14805 	 * the second check will fail.
14806 	 */
14807 	if (ill->ill_type == IFT_ETHER &&
14808 	    (mp->b_rptr - mp->b_datap->db_base) >=
14809 	    sizeof (struct ether_header)) {
14810 		mp->b_rptr -= sizeof (struct ether_header);
14811 		adjusted = B_TRUE;
14812 	}
14813 	mp1 = copymsg(mp);
14814 
14815 	if (mp1 == NULL) {
14816 		mp->b_next = NULL;
14817 		/* clear b_prev - used by ip_mroute_decap */
14818 		mp->b_prev = NULL;
14819 		freemsg(mp);
14820 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14821 		return (NULL);
14822 	}
14823 
14824 	if (adjusted) {
14825 		/*
14826 		 * Copy is done. Restore the pointer in
14827 		 * the _new_ mblk
14828 		 */
14829 		mp1->b_rptr += sizeof (struct ether_header);
14830 	}
14831 
14832 	/* Copy b_prev - used by ip_mroute_decap */
14833 	mp1->b_prev = mp->b_prev;
14834 	mp->b_prev = NULL;
14835 
14836 	/* preserve the hardware checksum flags and data, if present */
14837 	if (DB_CKSUMFLAGS(mp) != 0) {
14838 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14839 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14840 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14841 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14842 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14843 	}
14844 
14845 	freemsg(mp);
14846 	return (mp1);
14847 }
14848 
14849 /*
14850  * Direct read side procedure capable of dealing with chains. GLDv3 based
14851  * drivers call this function directly with mblk chains while STREAMS
14852  * read side procedure ip_rput() calls this for single packet with ip_ring
14853  * set to NULL to process one packet at a time.
14854  *
14855  * The ill will always be valid if this function is called directly from
14856  * the driver.
14857  *
14858  * If ip_input() is called from GLDv3:
14859  *
14860  *   - This must be a non-VLAN IP stream.
14861  *   - 'mp' is either an untagged or a special priority-tagged packet.
14862  *   - Any VLAN tag that was in the MAC header has been stripped.
14863  *
14864  * If the IP header in packet is not 32-bit aligned, every message in the
14865  * chain will be aligned before further operations. This is required on SPARC
14866  * platform.
14867  */
14868 /* ARGSUSED */
14869 void
14870 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14871     struct mac_header_info_s *mhip)
14872 {
14873 	ipaddr_t		dst = NULL;
14874 	ipaddr_t		prev_dst;
14875 	ire_t			*ire = NULL;
14876 	ipha_t			*ipha;
14877 	uint_t			pkt_len;
14878 	ssize_t			len;
14879 	uint_t			opt_len;
14880 	int			ll_multicast;
14881 	int			cgtp_flt_pkt;
14882 	queue_t			*q = ill->ill_rq;
14883 	squeue_t		*curr_sqp = NULL;
14884 	mblk_t 			*head = NULL;
14885 	mblk_t			*tail = NULL;
14886 	mblk_t			*first_mp;
14887 	mblk_t 			*mp;
14888 	mblk_t			*dmp;
14889 	int			cnt = 0;
14890 	ip_stack_t		*ipst = ill->ill_ipst;
14891 
14892 	ASSERT(mp_chain != NULL);
14893 	ASSERT(ill != NULL);
14894 
14895 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14896 
14897 #define	rptr	((uchar_t *)ipha)
14898 
14899 	while (mp_chain != NULL) {
14900 		first_mp = mp = mp_chain;
14901 		mp_chain = mp_chain->b_next;
14902 		mp->b_next = NULL;
14903 		ll_multicast = 0;
14904 
14905 		/*
14906 		 * We do ire caching from one iteration to
14907 		 * another. In the event the packet chain contains
14908 		 * all packets from the same dst, this caching saves
14909 		 * an ire_cache_lookup for each of the succeeding
14910 		 * packets in a packet chain.
14911 		 */
14912 		prev_dst = dst;
14913 
14914 		/*
14915 		 * if db_ref > 1 then copymsg and free original. Packet
14916 		 * may be changed and we do not want the other entity
14917 		 * who has a reference to this message to trip over the
14918 		 * changes. This is a blind change because trying to
14919 		 * catch all places that might change the packet is too
14920 		 * difficult.
14921 		 *
14922 		 * This corresponds to the fast path case, where we have
14923 		 * a chain of M_DATA mblks.  We check the db_ref count
14924 		 * of only the 1st data block in the mblk chain. There
14925 		 * doesn't seem to be a reason why a device driver would
14926 		 * send up data with varying db_ref counts in the mblk
14927 		 * chain. In any case the Fast path is a private
14928 		 * interface, and our drivers don't do such a thing.
14929 		 * Given the above assumption, there is no need to walk
14930 		 * down the entire mblk chain (which could have a
14931 		 * potential performance problem)
14932 		 */
14933 
14934 		if (DB_REF(mp) > 1) {
14935 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14936 				continue;
14937 		}
14938 
14939 		/*
14940 		 * Check and align the IP header.
14941 		 */
14942 		first_mp = mp;
14943 		if (DB_TYPE(mp) == M_DATA) {
14944 			dmp = mp;
14945 		} else if (DB_TYPE(mp) == M_PROTO &&
14946 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14947 			dmp = mp->b_cont;
14948 		} else {
14949 			dmp = NULL;
14950 		}
14951 		if (dmp != NULL) {
14952 			/*
14953 			 * IP header ptr not aligned?
14954 			 * OR IP header not complete in first mblk
14955 			 */
14956 			if (!OK_32PTR(dmp->b_rptr) ||
14957 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14958 				if (!ip_check_and_align_header(q, dmp, ipst))
14959 					continue;
14960 			}
14961 		}
14962 
14963 		/*
14964 		 * ip_input fast path
14965 		 */
14966 
14967 		/* mblk type is not M_DATA */
14968 		if (DB_TYPE(mp) != M_DATA) {
14969 			if (ip_rput_process_notdata(q, &first_mp, ill,
14970 			    &ll_multicast, &mp))
14971 				continue;
14972 		}
14973 
14974 		/* Make sure its an M_DATA and that its aligned */
14975 		ASSERT(DB_TYPE(mp) == M_DATA);
14976 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14977 
14978 		ipha = (ipha_t *)mp->b_rptr;
14979 		len = mp->b_wptr - rptr;
14980 		pkt_len = ntohs(ipha->ipha_length);
14981 
14982 		/*
14983 		 * We must count all incoming packets, even if they end
14984 		 * up being dropped later on.
14985 		 */
14986 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14987 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14988 
14989 		/* multiple mblk or too short */
14990 		len -= pkt_len;
14991 		if (len != 0) {
14992 			/*
14993 			 * Make sure we have data length consistent
14994 			 * with the IP header.
14995 			 */
14996 			if (mp->b_cont == NULL) {
14997 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14998 					BUMP_MIB(ill->ill_ip_mib,
14999 					    ipIfStatsInHdrErrors);
15000 					ip2dbg(("ip_input: drop pkt\n"));
15001 					freemsg(mp);
15002 					continue;
15003 				}
15004 				mp->b_wptr = rptr + pkt_len;
15005 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15006 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15007 					BUMP_MIB(ill->ill_ip_mib,
15008 					    ipIfStatsInHdrErrors);
15009 					ip2dbg(("ip_input: drop pkt\n"));
15010 					freemsg(mp);
15011 					continue;
15012 				}
15013 				(void) adjmsg(mp, -len);
15014 				IP_STAT(ipst, ip_multimblk3);
15015 			}
15016 		}
15017 
15018 		/* Obtain the dst of the current packet */
15019 		dst = ipha->ipha_dst;
15020 
15021 		if (IP_LOOPBACK_ADDR(dst) ||
15022 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15023 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15024 			cmn_err(CE_CONT, "dst %X src %X\n",
15025 			    dst, ipha->ipha_src);
15026 			freemsg(mp);
15027 			continue;
15028 		}
15029 
15030 		/*
15031 		 * The event for packets being received from a 'physical'
15032 		 * interface is placed after validation of the source and/or
15033 		 * destination address as being local so that packets can be
15034 		 * redirected to loopback addresses using ipnat.
15035 		 */
15036 		DTRACE_PROBE4(ip4__physical__in__start,
15037 		    ill_t *, ill, ill_t *, NULL,
15038 		    ipha_t *, ipha, mblk_t *, first_mp);
15039 
15040 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15041 		    ipst->ips_ipv4firewall_physical_in,
15042 		    ill, NULL, ipha, first_mp, mp, ipst);
15043 
15044 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15045 
15046 		if (first_mp == NULL) {
15047 			continue;
15048 		}
15049 		dst = ipha->ipha_dst;
15050 
15051 		/*
15052 		 * Attach any necessary label information to
15053 		 * this packet
15054 		 */
15055 		if (is_system_labeled() &&
15056 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15057 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15058 			freemsg(mp);
15059 			continue;
15060 		}
15061 
15062 		/*
15063 		 * Reuse the cached ire only if the ipha_dst of the previous
15064 		 * packet is the same as the current packet AND it is not
15065 		 * INADDR_ANY.
15066 		 */
15067 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15068 		    (ire != NULL)) {
15069 			ire_refrele(ire);
15070 			ire = NULL;
15071 		}
15072 		opt_len = ipha->ipha_version_and_hdr_length -
15073 		    IP_SIMPLE_HDR_VERSION;
15074 
15075 		/*
15076 		 * Check to see if we can take the fastpath.
15077 		 * That is possible if the following conditions are met
15078 		 *	o Tsol disabled
15079 		 *	o CGTP disabled
15080 		 *	o ipp_action_count is 0
15081 		 *	o no options in the packet
15082 		 *	o not a RSVP packet
15083 		 * 	o not a multicast packet
15084 		 */
15085 		if (!is_system_labeled() &&
15086 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15087 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15088 		    !ll_multicast && !CLASSD(dst)) {
15089 			if (ire == NULL)
15090 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15091 				    ipst);
15092 
15093 			/* incoming packet is for forwarding */
15094 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15095 				ire = ip_fast_forward(ire, dst, ill, mp);
15096 				continue;
15097 			}
15098 			/* incoming packet is for local consumption */
15099 			if (ire->ire_type & IRE_LOCAL)
15100 				goto local;
15101 		}
15102 
15103 		/*
15104 		 * Disable ire caching for anything more complex
15105 		 * than the simple fast path case we checked for above.
15106 		 */
15107 		if (ire != NULL) {
15108 			ire_refrele(ire);
15109 			ire = NULL;
15110 		}
15111 
15112 		/* Full-blown slow path */
15113 		if (opt_len != 0) {
15114 			if (len != 0)
15115 				IP_STAT(ipst, ip_multimblk4);
15116 			else
15117 				IP_STAT(ipst, ip_ipoptions);
15118 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15119 			    &dst, ipst))
15120 				continue;
15121 		}
15122 
15123 		/*
15124 		 * Invoke the CGTP (multirouting) filtering module to process
15125 		 * the incoming packet. Packets identified as duplicates
15126 		 * must be discarded. Filtering is active only if the
15127 		 * the ip_cgtp_filter ndd variable is non-zero.
15128 		 */
15129 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15130 		if (ipst->ips_ip_cgtp_filter &&
15131 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15132 			netstackid_t stackid;
15133 
15134 			stackid = ipst->ips_netstack->netstack_stackid;
15135 			cgtp_flt_pkt =
15136 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15137 			    ill->ill_phyint->phyint_ifindex, mp);
15138 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15139 				freemsg(first_mp);
15140 				continue;
15141 			}
15142 		}
15143 
15144 		/*
15145 		 * If rsvpd is running, let RSVP daemon handle its processing
15146 		 * and forwarding of RSVP multicast/unicast packets.
15147 		 * If rsvpd is not running but mrouted is running, RSVP
15148 		 * multicast packets are forwarded as multicast traffic
15149 		 * and RSVP unicast packets are forwarded by unicast router.
15150 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15151 		 * packets are not forwarded, but the unicast packets are
15152 		 * forwarded like unicast traffic.
15153 		 */
15154 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15155 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15156 		    NULL) {
15157 			/* RSVP packet and rsvpd running. Treat as ours */
15158 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15159 			/*
15160 			 * This assumes that we deliver to all streams for
15161 			 * multicast and broadcast packets.
15162 			 * We have to force ll_multicast to 1 to handle the
15163 			 * M_DATA messages passed in from ip_mroute_decap.
15164 			 */
15165 			dst = INADDR_BROADCAST;
15166 			ll_multicast = 1;
15167 		} else if (CLASSD(dst)) {
15168 			/* packet is multicast */
15169 			mp->b_next = NULL;
15170 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15171 			    &ll_multicast, &dst))
15172 				continue;
15173 		}
15174 
15175 		if (ire == NULL) {
15176 			ire = ire_cache_lookup(dst, ALL_ZONES,
15177 			    MBLK_GETLABEL(mp), ipst);
15178 		}
15179 
15180 		if (ire == NULL) {
15181 			/*
15182 			 * No IRE for this destination, so it can't be for us.
15183 			 * Unless we are forwarding, drop the packet.
15184 			 * We have to let source routed packets through
15185 			 * since we don't yet know if they are 'ping -l'
15186 			 * packets i.e. if they will go out over the
15187 			 * same interface as they came in on.
15188 			 */
15189 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15190 			if (ire == NULL)
15191 				continue;
15192 		}
15193 
15194 		/*
15195 		 * Broadcast IRE may indicate either broadcast or
15196 		 * multicast packet
15197 		 */
15198 		if (ire->ire_type == IRE_BROADCAST) {
15199 			/*
15200 			 * Skip broadcast checks if packet is UDP multicast;
15201 			 * we'd rather not enter ip_rput_process_broadcast()
15202 			 * unless the packet is broadcast for real, since
15203 			 * that routine is a no-op for multicast.
15204 			 */
15205 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15206 			    !CLASSD(ipha->ipha_dst)) {
15207 				ire = ip_rput_process_broadcast(&q, mp,
15208 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15209 				    ll_multicast);
15210 				if (ire == NULL)
15211 					continue;
15212 			}
15213 		} else if (ire->ire_stq != NULL) {
15214 			/* fowarding? */
15215 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15216 			    ll_multicast);
15217 			/* ip_rput_process_forward consumed the packet */
15218 			continue;
15219 		}
15220 
15221 local:
15222 		/*
15223 		 * If the queue in the ire is different to the ingress queue
15224 		 * then we need to check to see if we can accept the packet.
15225 		 * Note that for multicast packets and broadcast packets sent
15226 		 * to a broadcast address which is shared between multiple
15227 		 * interfaces we should not do this since we just got a random
15228 		 * broadcast ire.
15229 		 */
15230 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15231 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15232 			    ill)) == NULL) {
15233 				/* Drop packet */
15234 				BUMP_MIB(ill->ill_ip_mib,
15235 				    ipIfStatsForwProhibits);
15236 				freemsg(mp);
15237 				continue;
15238 			}
15239 			if (ire->ire_rfq != NULL)
15240 				q = ire->ire_rfq;
15241 		}
15242 
15243 		switch (ipha->ipha_protocol) {
15244 		case IPPROTO_TCP:
15245 			ASSERT(first_mp == mp);
15246 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15247 			    mp, 0, q, ip_ring)) != NULL) {
15248 				if (curr_sqp == NULL) {
15249 					curr_sqp = GET_SQUEUE(mp);
15250 					ASSERT(cnt == 0);
15251 					cnt++;
15252 					head = tail = mp;
15253 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15254 					ASSERT(tail != NULL);
15255 					cnt++;
15256 					tail->b_next = mp;
15257 					tail = mp;
15258 				} else {
15259 					/*
15260 					 * A different squeue. Send the
15261 					 * chain for the previous squeue on
15262 					 * its way. This shouldn't happen
15263 					 * often unless interrupt binding
15264 					 * changes.
15265 					 */
15266 					IP_STAT(ipst, ip_input_multi_squeue);
15267 					squeue_enter_chain(curr_sqp, head,
15268 					    tail, cnt, SQTAG_IP_INPUT);
15269 					curr_sqp = GET_SQUEUE(mp);
15270 					head = mp;
15271 					tail = mp;
15272 					cnt = 1;
15273 				}
15274 			}
15275 			continue;
15276 		case IPPROTO_UDP:
15277 			ASSERT(first_mp == mp);
15278 			ip_udp_input(q, mp, ipha, ire, ill);
15279 			continue;
15280 		case IPPROTO_SCTP:
15281 			ASSERT(first_mp == mp);
15282 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15283 			    q, dst);
15284 			/* ire has been released by ip_sctp_input */
15285 			ire = NULL;
15286 			continue;
15287 		default:
15288 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15289 			continue;
15290 		}
15291 	}
15292 
15293 	if (ire != NULL)
15294 		ire_refrele(ire);
15295 
15296 	if (head != NULL)
15297 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15298 
15299 	/*
15300 	 * This code is there just to make netperf/ttcp look good.
15301 	 *
15302 	 * Its possible that after being in polling mode (and having cleared
15303 	 * the backlog), squeues have turned the interrupt frequency higher
15304 	 * to improve latency at the expense of more CPU utilization (less
15305 	 * packets per interrupts or more number of interrupts). Workloads
15306 	 * like ttcp/netperf do manage to tickle polling once in a while
15307 	 * but for the remaining time, stay in higher interrupt mode since
15308 	 * their packet arrival rate is pretty uniform and this shows up
15309 	 * as higher CPU utilization. Since people care about CPU utilization
15310 	 * while running netperf/ttcp, turn the interrupt frequency back to
15311 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15312 	 */
15313 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15314 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15315 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15316 			ip_ring->rr_blank(ip_ring->rr_handle,
15317 			    ip_ring->rr_normal_blank_time,
15318 			    ip_ring->rr_normal_pkt_cnt);
15319 		}
15320 		}
15321 
15322 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15323 	    "ip_input_end: q %p (%S)", q, "end");
15324 #undef  rptr
15325 }
15326 
15327 static void
15328 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15329     t_uscalar_t err)
15330 {
15331 	if (dl_err == DL_SYSERR) {
15332 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15333 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15334 		    ill->ill_name, dlpi_prim_str(prim), err);
15335 		return;
15336 	}
15337 
15338 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15339 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15340 	    dlpi_err_str(dl_err));
15341 }
15342 
15343 /*
15344  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15345  * than DL_UNITDATA_IND messages. If we need to process this message
15346  * exclusively, we call qwriter_ip, in which case we also need to call
15347  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15348  */
15349 void
15350 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15351 {
15352 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15353 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15354 	ill_t		*ill = (ill_t *)q->q_ptr;
15355 	boolean_t	pending;
15356 
15357 	ip1dbg(("ip_rput_dlpi"));
15358 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15359 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15360 		    "%s (0x%x), unix %u\n", ill->ill_name,
15361 		    dlpi_prim_str(dlea->dl_error_primitive),
15362 		    dlea->dl_error_primitive,
15363 		    dlpi_err_str(dlea->dl_errno),
15364 		    dlea->dl_errno,
15365 		    dlea->dl_unix_errno));
15366 	}
15367 
15368 	/*
15369 	 * If we received an ACK but didn't send a request for it, then it
15370 	 * can't be part of any pending operation; discard up-front.
15371 	 */
15372 	switch (dloa->dl_primitive) {
15373 	case DL_NOTIFY_IND:
15374 		pending = B_TRUE;
15375 		break;
15376 	case DL_ERROR_ACK:
15377 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15378 		break;
15379 	case DL_OK_ACK:
15380 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15381 		break;
15382 	case DL_INFO_ACK:
15383 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15384 		break;
15385 	case DL_BIND_ACK:
15386 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15387 		break;
15388 	case DL_PHYS_ADDR_ACK:
15389 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15390 		break;
15391 	case DL_NOTIFY_ACK:
15392 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15393 		break;
15394 	case DL_CONTROL_ACK:
15395 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15396 		break;
15397 	case DL_CAPABILITY_ACK:
15398 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15399 		break;
15400 	default:
15401 		/* Not a DLPI message we support or were expecting */
15402 		freemsg(mp);
15403 		return;
15404 	}
15405 
15406 	if (!pending) {
15407 		freemsg(mp);
15408 		return;
15409 	}
15410 
15411 	switch (dloa->dl_primitive) {
15412 	case DL_ERROR_ACK:
15413 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15414 			mutex_enter(&ill->ill_lock);
15415 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15416 			cv_signal(&ill->ill_cv);
15417 			mutex_exit(&ill->ill_lock);
15418 		}
15419 		break;
15420 
15421 	case DL_OK_ACK:
15422 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15423 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15424 		switch (dloa->dl_correct_primitive) {
15425 		case DL_UNBIND_REQ:
15426 			mutex_enter(&ill->ill_lock);
15427 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15428 			cv_signal(&ill->ill_cv);
15429 			mutex_exit(&ill->ill_lock);
15430 			break;
15431 
15432 		case DL_ENABMULTI_REQ:
15433 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15434 				ill->ill_dlpi_multicast_state = IDS_OK;
15435 			break;
15436 		}
15437 		break;
15438 	default:
15439 		break;
15440 	}
15441 
15442 	/*
15443 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15444 	 * and we need to become writer to continue to process it. If it's not
15445 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15446 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15447 	 * some work as part of the current exclusive operation that actually
15448 	 * is not part of it -- which is wrong, but better than the
15449 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15450 	 * should track which DLPI requests have ACKs that we wait on
15451 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15452 	 *
15453 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15454 	 * Since this is on the ill stream we unconditionally bump up the
15455 	 * refcount without doing ILL_CAN_LOOKUP().
15456 	 */
15457 	ill_refhold(ill);
15458 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15459 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15460 	else
15461 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15462 }
15463 
15464 /*
15465  * Handling of DLPI messages that require exclusive access to the ipsq.
15466  *
15467  * Need to do ill_pending_mp_release on ioctl completion, which could
15468  * happen here. (along with mi_copy_done)
15469  */
15470 /* ARGSUSED */
15471 static void
15472 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15473 {
15474 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15475 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15476 	int		err = 0;
15477 	ill_t		*ill;
15478 	ipif_t		*ipif = NULL;
15479 	mblk_t		*mp1 = NULL;
15480 	conn_t		*connp = NULL;
15481 	t_uscalar_t	paddrreq;
15482 	mblk_t		*mp_hw;
15483 	boolean_t	success;
15484 	boolean_t	ioctl_aborted = B_FALSE;
15485 	boolean_t	log = B_TRUE;
15486 	hook_nic_event_t	*info;
15487 	ip_stack_t		*ipst;
15488 
15489 	ip1dbg(("ip_rput_dlpi_writer .."));
15490 	ill = (ill_t *)q->q_ptr;
15491 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15492 
15493 	ASSERT(IAM_WRITER_ILL(ill));
15494 
15495 	ipst = ill->ill_ipst;
15496 
15497 	/*
15498 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15499 	 * both are null or non-null. However we can assert that only
15500 	 * after grabbing the ipsq_lock. So we don't make any assertion
15501 	 * here and in other places in the code.
15502 	 */
15503 	ipif = ipsq->ipsq_pending_ipif;
15504 	/*
15505 	 * The current ioctl could have been aborted by the user and a new
15506 	 * ioctl to bring up another ill could have started. We could still
15507 	 * get a response from the driver later.
15508 	 */
15509 	if (ipif != NULL && ipif->ipif_ill != ill)
15510 		ioctl_aborted = B_TRUE;
15511 
15512 	switch (dloa->dl_primitive) {
15513 	case DL_ERROR_ACK:
15514 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15515 		    dlpi_prim_str(dlea->dl_error_primitive)));
15516 
15517 		switch (dlea->dl_error_primitive) {
15518 		case DL_PROMISCON_REQ:
15519 		case DL_PROMISCOFF_REQ:
15520 		case DL_DISABMULTI_REQ:
15521 		case DL_UNBIND_REQ:
15522 		case DL_ATTACH_REQ:
15523 		case DL_INFO_REQ:
15524 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15525 			break;
15526 		case DL_NOTIFY_REQ:
15527 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15528 			log = B_FALSE;
15529 			break;
15530 		case DL_PHYS_ADDR_REQ:
15531 			/*
15532 			 * For IPv6 only, there are two additional
15533 			 * phys_addr_req's sent to the driver to get the
15534 			 * IPv6 token and lla. This allows IP to acquire
15535 			 * the hardware address format for a given interface
15536 			 * without having built in knowledge of the hardware
15537 			 * address. ill_phys_addr_pend keeps track of the last
15538 			 * DL_PAR sent so we know which response we are
15539 			 * dealing with. ill_dlpi_done will update
15540 			 * ill_phys_addr_pend when it sends the next req.
15541 			 * We don't complete the IOCTL until all three DL_PARs
15542 			 * have been attempted, so set *_len to 0 and break.
15543 			 */
15544 			paddrreq = ill->ill_phys_addr_pend;
15545 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15546 			if (paddrreq == DL_IPV6_TOKEN) {
15547 				ill->ill_token_length = 0;
15548 				log = B_FALSE;
15549 				break;
15550 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15551 				ill->ill_nd_lla_len = 0;
15552 				log = B_FALSE;
15553 				break;
15554 			}
15555 			/*
15556 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15557 			 * We presumably have an IOCTL hanging out waiting
15558 			 * for completion. Find it and complete the IOCTL
15559 			 * with the error noted.
15560 			 * However, ill_dl_phys was called on an ill queue
15561 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15562 			 * set. But the ioctl is known to be pending on ill_wq.
15563 			 */
15564 			if (!ill->ill_ifname_pending)
15565 				break;
15566 			ill->ill_ifname_pending = 0;
15567 			if (!ioctl_aborted)
15568 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15569 			if (mp1 != NULL) {
15570 				/*
15571 				 * This operation (SIOCSLIFNAME) must have
15572 				 * happened on the ill. Assert there is no conn
15573 				 */
15574 				ASSERT(connp == NULL);
15575 				q = ill->ill_wq;
15576 			}
15577 			break;
15578 		case DL_BIND_REQ:
15579 			ill_dlpi_done(ill, DL_BIND_REQ);
15580 			if (ill->ill_ifname_pending)
15581 				break;
15582 			/*
15583 			 * Something went wrong with the bind.  We presumably
15584 			 * have an IOCTL hanging out waiting for completion.
15585 			 * Find it, take down the interface that was coming
15586 			 * up, and complete the IOCTL with the error noted.
15587 			 */
15588 			if (!ioctl_aborted)
15589 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15590 			if (mp1 != NULL) {
15591 				/*
15592 				 * This operation (SIOCSLIFFLAGS) must have
15593 				 * happened from a conn.
15594 				 */
15595 				ASSERT(connp != NULL);
15596 				q = CONNP_TO_WQ(connp);
15597 				if (ill->ill_move_in_progress) {
15598 					ILL_CLEAR_MOVE(ill);
15599 				}
15600 				(void) ipif_down(ipif, NULL, NULL);
15601 				/* error is set below the switch */
15602 			}
15603 			break;
15604 		case DL_ENABMULTI_REQ:
15605 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15606 
15607 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15608 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15609 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15610 				ipif_t *ipif;
15611 
15612 				printf("ip: joining multicasts failed (%d)"
15613 				    " on %s - will use link layer "
15614 				    "broadcasts for multicast\n",
15615 				    dlea->dl_errno, ill->ill_name);
15616 
15617 				/*
15618 				 * Set up the multicast mapping alone.
15619 				 * writer, so ok to access ill->ill_ipif
15620 				 * without any lock.
15621 				 */
15622 				ipif = ill->ill_ipif;
15623 				mutex_enter(&ill->ill_phyint->phyint_lock);
15624 				ill->ill_phyint->phyint_flags |=
15625 				    PHYI_MULTI_BCAST;
15626 				mutex_exit(&ill->ill_phyint->phyint_lock);
15627 
15628 				if (!ill->ill_isv6) {
15629 					(void) ipif_arp_setup_multicast(ipif,
15630 					    NULL);
15631 				} else {
15632 					(void) ipif_ndp_setup_multicast(ipif,
15633 					    NULL);
15634 				}
15635 			}
15636 			freemsg(mp);	/* Don't want to pass this up */
15637 			return;
15638 
15639 		case DL_CAPABILITY_REQ:
15640 		case DL_CONTROL_REQ:
15641 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15642 			ill->ill_dlpi_capab_state = IDS_FAILED;
15643 			freemsg(mp);
15644 			return;
15645 		}
15646 		/*
15647 		 * Note the error for IOCTL completion (mp1 is set when
15648 		 * ready to complete ioctl). If ill_ifname_pending_err is
15649 		 * set, an error occured during plumbing (ill_ifname_pending),
15650 		 * so we want to report that error.
15651 		 *
15652 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15653 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15654 		 * expected to get errack'd if the driver doesn't support
15655 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15656 		 * if these error conditions are encountered.
15657 		 */
15658 		if (mp1 != NULL) {
15659 			if (ill->ill_ifname_pending_err != 0)  {
15660 				err = ill->ill_ifname_pending_err;
15661 				ill->ill_ifname_pending_err = 0;
15662 			} else {
15663 				err = dlea->dl_unix_errno ?
15664 				    dlea->dl_unix_errno : ENXIO;
15665 			}
15666 		/*
15667 		 * If we're plumbing an interface and an error hasn't already
15668 		 * been saved, set ill_ifname_pending_err to the error passed
15669 		 * up. Ignore the error if log is B_FALSE (see comment above).
15670 		 */
15671 		} else if (log && ill->ill_ifname_pending &&
15672 		    ill->ill_ifname_pending_err == 0) {
15673 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15674 			    dlea->dl_unix_errno : ENXIO;
15675 		}
15676 
15677 		if (log)
15678 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15679 			    dlea->dl_errno, dlea->dl_unix_errno);
15680 		break;
15681 	case DL_CAPABILITY_ACK: {
15682 		boolean_t reneg_flag = B_FALSE;
15683 		/* Call a routine to handle this one. */
15684 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15685 		/*
15686 		 * Check if the ACK is due to renegotiation case since we
15687 		 * will need to send a new CAPABILITY_REQ later.
15688 		 */
15689 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15690 			/* This is the ack for a renogiation case */
15691 			reneg_flag = B_TRUE;
15692 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15693 		}
15694 		ill_capability_ack(ill, mp);
15695 		if (reneg_flag)
15696 			ill_capability_probe(ill);
15697 		break;
15698 	}
15699 	case DL_CONTROL_ACK:
15700 		/* We treat all of these as "fire and forget" */
15701 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15702 		break;
15703 	case DL_INFO_ACK:
15704 		/* Call a routine to handle this one. */
15705 		ill_dlpi_done(ill, DL_INFO_REQ);
15706 		ip_ll_subnet_defaults(ill, mp);
15707 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15708 		return;
15709 	case DL_BIND_ACK:
15710 		/*
15711 		 * We should have an IOCTL waiting on this unless
15712 		 * sent by ill_dl_phys, in which case just return
15713 		 */
15714 		ill_dlpi_done(ill, DL_BIND_REQ);
15715 		if (ill->ill_ifname_pending)
15716 			break;
15717 
15718 		if (!ioctl_aborted)
15719 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15720 		if (mp1 == NULL)
15721 			break;
15722 		/*
15723 		 * Because mp1 was added by ill_dl_up(), and it always
15724 		 * passes a valid connp, connp must be valid here.
15725 		 */
15726 		ASSERT(connp != NULL);
15727 		q = CONNP_TO_WQ(connp);
15728 
15729 		/*
15730 		 * We are exclusive. So nothing can change even after
15731 		 * we get the pending mp. If need be we can put it back
15732 		 * and restart, as in calling ipif_arp_up()  below.
15733 		 */
15734 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15735 
15736 		mutex_enter(&ill->ill_lock);
15737 
15738 		ill->ill_dl_up = 1;
15739 
15740 		if ((info = ill->ill_nic_event_info) != NULL) {
15741 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15742 			    "attached for %s\n", info->hne_event,
15743 			    ill->ill_name));
15744 			if (info->hne_data != NULL)
15745 				kmem_free(info->hne_data, info->hne_datalen);
15746 			kmem_free(info, sizeof (hook_nic_event_t));
15747 		}
15748 
15749 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15750 		if (info != NULL) {
15751 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15752 			info->hne_lif = 0;
15753 			info->hne_event = NE_UP;
15754 			info->hne_data = NULL;
15755 			info->hne_datalen = 0;
15756 			info->hne_family = ill->ill_isv6 ?
15757 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15758 		} else
15759 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15760 			    "event information for %s (ENOMEM)\n",
15761 			    ill->ill_name));
15762 
15763 		ill->ill_nic_event_info = info;
15764 
15765 		mutex_exit(&ill->ill_lock);
15766 
15767 		/*
15768 		 * Now bring up the resolver; when that is complete, we'll
15769 		 * create IREs.  Note that we intentionally mirror what
15770 		 * ipif_up() would have done, because we got here by way of
15771 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15772 		 */
15773 		if (ill->ill_isv6) {
15774 			/*
15775 			 * v6 interfaces.
15776 			 * Unlike ARP which has to do another bind
15777 			 * and attach, once we get here we are
15778 			 * done with NDP. Except in the case of
15779 			 * ILLF_XRESOLV, in which case we send an
15780 			 * AR_INTERFACE_UP to the external resolver.
15781 			 * If all goes well, the ioctl will complete
15782 			 * in ip_rput(). If there's an error, we
15783 			 * complete it here.
15784 			 */
15785 			if ((err = ipif_ndp_up(ipif)) == 0) {
15786 				if (ill->ill_flags & ILLF_XRESOLV) {
15787 					mutex_enter(&connp->conn_lock);
15788 					mutex_enter(&ill->ill_lock);
15789 					success = ipsq_pending_mp_add(
15790 					    connp, ipif, q, mp1, 0);
15791 					mutex_exit(&ill->ill_lock);
15792 					mutex_exit(&connp->conn_lock);
15793 					if (success) {
15794 						err = ipif_resolver_up(ipif,
15795 						    Res_act_initial);
15796 						if (err == EINPROGRESS) {
15797 							freemsg(mp);
15798 							return;
15799 						}
15800 						ASSERT(err != 0);
15801 						mp1 = ipsq_pending_mp_get(ipsq,
15802 						    &connp);
15803 						ASSERT(mp1 != NULL);
15804 					} else {
15805 						/* conn has started closing */
15806 						err = EINTR;
15807 					}
15808 				} else { /* Non XRESOLV interface */
15809 					(void) ipif_resolver_up(ipif,
15810 					    Res_act_initial);
15811 					err = ipif_up_done_v6(ipif);
15812 				}
15813 			}
15814 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15815 			/*
15816 			 * ARP and other v4 external resolvers.
15817 			 * Leave the pending mblk intact so that
15818 			 * the ioctl completes in ip_rput().
15819 			 */
15820 			mutex_enter(&connp->conn_lock);
15821 			mutex_enter(&ill->ill_lock);
15822 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15823 			mutex_exit(&ill->ill_lock);
15824 			mutex_exit(&connp->conn_lock);
15825 			if (success) {
15826 				err = ipif_resolver_up(ipif, Res_act_initial);
15827 				if (err == EINPROGRESS) {
15828 					freemsg(mp);
15829 					return;
15830 				}
15831 				ASSERT(err != 0);
15832 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15833 			} else {
15834 				/* The conn has started closing */
15835 				err = EINTR;
15836 			}
15837 		} else {
15838 			/*
15839 			 * This one is complete. Reply to pending ioctl.
15840 			 */
15841 			(void) ipif_resolver_up(ipif, Res_act_initial);
15842 			err = ipif_up_done(ipif);
15843 		}
15844 
15845 		if ((err == 0) && (ill->ill_up_ipifs)) {
15846 			err = ill_up_ipifs(ill, q, mp1);
15847 			if (err == EINPROGRESS) {
15848 				freemsg(mp);
15849 				return;
15850 			}
15851 		}
15852 
15853 		if (ill->ill_up_ipifs) {
15854 			ill_group_cleanup(ill);
15855 		}
15856 
15857 		break;
15858 	case DL_NOTIFY_IND: {
15859 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15860 		ire_t *ire;
15861 		boolean_t need_ire_walk_v4 = B_FALSE;
15862 		boolean_t need_ire_walk_v6 = B_FALSE;
15863 
15864 		switch (notify->dl_notification) {
15865 		case DL_NOTE_PHYS_ADDR:
15866 			err = ill_set_phys_addr(ill, mp);
15867 			break;
15868 
15869 		case DL_NOTE_FASTPATH_FLUSH:
15870 			ill_fastpath_flush(ill);
15871 			break;
15872 
15873 		case DL_NOTE_SDU_SIZE:
15874 			/*
15875 			 * Change the MTU size of the interface, of all
15876 			 * attached ipif's, and of all relevant ire's.  The
15877 			 * new value's a uint32_t at notify->dl_data.
15878 			 * Mtu change Vs. new ire creation - protocol below.
15879 			 *
15880 			 * a Mark the ipif as IPIF_CHANGING.
15881 			 * b Set the new mtu in the ipif.
15882 			 * c Change the ire_max_frag on all affected ires
15883 			 * d Unmark the IPIF_CHANGING
15884 			 *
15885 			 * To see how the protocol works, assume an interface
15886 			 * route is also being added simultaneously by
15887 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15888 			 * the ire. If the ire is created before step a,
15889 			 * it will be cleaned up by step c. If the ire is
15890 			 * created after step d, it will see the new value of
15891 			 * ipif_mtu. Any attempt to create the ire between
15892 			 * steps a to d will fail because of the IPIF_CHANGING
15893 			 * flag. Note that ire_create() is passed a pointer to
15894 			 * the ipif_mtu, and not the value. During ire_add
15895 			 * under the bucket lock, the ire_max_frag of the
15896 			 * new ire being created is set from the ipif/ire from
15897 			 * which it is being derived.
15898 			 */
15899 			mutex_enter(&ill->ill_lock);
15900 			ill->ill_max_frag = (uint_t)notify->dl_data;
15901 
15902 			/*
15903 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15904 			 * leave it alone
15905 			 */
15906 			if (ill->ill_mtu_userspecified) {
15907 				mutex_exit(&ill->ill_lock);
15908 				break;
15909 			}
15910 			ill->ill_max_mtu = ill->ill_max_frag;
15911 			if (ill->ill_isv6) {
15912 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15913 					ill->ill_max_mtu = IPV6_MIN_MTU;
15914 			} else {
15915 				if (ill->ill_max_mtu < IP_MIN_MTU)
15916 					ill->ill_max_mtu = IP_MIN_MTU;
15917 			}
15918 			for (ipif = ill->ill_ipif; ipif != NULL;
15919 			    ipif = ipif->ipif_next) {
15920 				/*
15921 				 * Don't override the mtu if the user
15922 				 * has explicitly set it.
15923 				 */
15924 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15925 					continue;
15926 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15927 				if (ipif->ipif_isv6)
15928 					ire = ipif_to_ire_v6(ipif);
15929 				else
15930 					ire = ipif_to_ire(ipif);
15931 				if (ire != NULL) {
15932 					ire->ire_max_frag = ipif->ipif_mtu;
15933 					ire_refrele(ire);
15934 				}
15935 				if (ipif->ipif_flags & IPIF_UP) {
15936 					if (ill->ill_isv6)
15937 						need_ire_walk_v6 = B_TRUE;
15938 					else
15939 						need_ire_walk_v4 = B_TRUE;
15940 				}
15941 			}
15942 			mutex_exit(&ill->ill_lock);
15943 			if (need_ire_walk_v4)
15944 				ire_walk_v4(ill_mtu_change, (char *)ill,
15945 				    ALL_ZONES, ipst);
15946 			if (need_ire_walk_v6)
15947 				ire_walk_v6(ill_mtu_change, (char *)ill,
15948 				    ALL_ZONES, ipst);
15949 			break;
15950 		case DL_NOTE_LINK_UP:
15951 		case DL_NOTE_LINK_DOWN: {
15952 			/*
15953 			 * We are writer. ill / phyint / ipsq assocs stable.
15954 			 * The RUNNING flag reflects the state of the link.
15955 			 */
15956 			phyint_t *phyint = ill->ill_phyint;
15957 			uint64_t new_phyint_flags;
15958 			boolean_t changed = B_FALSE;
15959 			boolean_t went_up;
15960 
15961 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15962 			mutex_enter(&phyint->phyint_lock);
15963 			new_phyint_flags = went_up ?
15964 			    phyint->phyint_flags | PHYI_RUNNING :
15965 			    phyint->phyint_flags & ~PHYI_RUNNING;
15966 			if (new_phyint_flags != phyint->phyint_flags) {
15967 				phyint->phyint_flags = new_phyint_flags;
15968 				changed = B_TRUE;
15969 			}
15970 			mutex_exit(&phyint->phyint_lock);
15971 			/*
15972 			 * ill_restart_dad handles the DAD restart and routing
15973 			 * socket notification logic.
15974 			 */
15975 			if (changed) {
15976 				ill_restart_dad(phyint->phyint_illv4, went_up);
15977 				ill_restart_dad(phyint->phyint_illv6, went_up);
15978 			}
15979 			break;
15980 		}
15981 		case DL_NOTE_PROMISC_ON_PHYS:
15982 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15983 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15984 			mutex_enter(&ill->ill_lock);
15985 			ill->ill_promisc_on_phys = B_TRUE;
15986 			mutex_exit(&ill->ill_lock);
15987 			break;
15988 		case DL_NOTE_PROMISC_OFF_PHYS:
15989 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15990 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15991 			mutex_enter(&ill->ill_lock);
15992 			ill->ill_promisc_on_phys = B_FALSE;
15993 			mutex_exit(&ill->ill_lock);
15994 			break;
15995 		case DL_NOTE_CAPAB_RENEG:
15996 			/*
15997 			 * Something changed on the driver side.
15998 			 * It wants us to renegotiate the capabilities
15999 			 * on this ill. The most likely cause is the
16000 			 * aggregation interface under us where a
16001 			 * port got added or went away.
16002 			 *
16003 			 * We reset the capabilities and set the
16004 			 * state to IDS_RENG so that when the ack
16005 			 * comes back, we can start the
16006 			 * renegotiation process.
16007 			 */
16008 			ill_capability_reset(ill);
16009 			ill->ill_dlpi_capab_state = IDS_RENEG;
16010 			break;
16011 		default:
16012 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16013 			    "type 0x%x for DL_NOTIFY_IND\n",
16014 			    notify->dl_notification));
16015 			break;
16016 		}
16017 
16018 		/*
16019 		 * As this is an asynchronous operation, we
16020 		 * should not call ill_dlpi_done
16021 		 */
16022 		break;
16023 	}
16024 	case DL_NOTIFY_ACK: {
16025 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16026 
16027 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16028 			ill->ill_note_link = 1;
16029 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16030 		break;
16031 	}
16032 	case DL_PHYS_ADDR_ACK: {
16033 		/*
16034 		 * As part of plumbing the interface via SIOCSLIFNAME,
16035 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16036 		 * whose answers we receive here.  As each answer is received,
16037 		 * we call ill_dlpi_done() to dispatch the next request as
16038 		 * we're processing the current one.  Once all answers have
16039 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16040 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16041 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16042 		 * available, but we know the ioctl is pending on ill_wq.)
16043 		 */
16044 		uint_t paddrlen, paddroff;
16045 
16046 		paddrreq = ill->ill_phys_addr_pend;
16047 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16048 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16049 
16050 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16051 		if (paddrreq == DL_IPV6_TOKEN) {
16052 			/*
16053 			 * bcopy to low-order bits of ill_token
16054 			 *
16055 			 * XXX Temporary hack - currently, all known tokens
16056 			 * are 64 bits, so I'll cheat for the moment.
16057 			 */
16058 			bcopy(mp->b_rptr + paddroff,
16059 			    &ill->ill_token.s6_addr32[2], paddrlen);
16060 			ill->ill_token_length = paddrlen;
16061 			break;
16062 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16063 			ASSERT(ill->ill_nd_lla_mp == NULL);
16064 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16065 			mp = NULL;
16066 			break;
16067 		}
16068 
16069 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16070 		ASSERT(ill->ill_phys_addr_mp == NULL);
16071 		if (!ill->ill_ifname_pending)
16072 			break;
16073 		ill->ill_ifname_pending = 0;
16074 		if (!ioctl_aborted)
16075 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16076 		if (mp1 != NULL) {
16077 			ASSERT(connp == NULL);
16078 			q = ill->ill_wq;
16079 		}
16080 		/*
16081 		 * If any error acks received during the plumbing sequence,
16082 		 * ill_ifname_pending_err will be set. Break out and send up
16083 		 * the error to the pending ioctl.
16084 		 */
16085 		if (ill->ill_ifname_pending_err != 0) {
16086 			err = ill->ill_ifname_pending_err;
16087 			ill->ill_ifname_pending_err = 0;
16088 			break;
16089 		}
16090 
16091 		ill->ill_phys_addr_mp = mp;
16092 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16093 		mp = NULL;
16094 
16095 		/*
16096 		 * If paddrlen is zero, the DLPI provider doesn't support
16097 		 * physical addresses.  The other two tests were historical
16098 		 * workarounds for bugs in our former PPP implementation, but
16099 		 * now other things have grown dependencies on them -- e.g.,
16100 		 * the tun module specifies a dl_addr_length of zero in its
16101 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16102 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16103 		 * but only after careful testing ensures that all dependent
16104 		 * broken DLPI providers have been fixed.
16105 		 */
16106 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16107 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16108 			ill->ill_phys_addr = NULL;
16109 		} else if (paddrlen != ill->ill_phys_addr_length) {
16110 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16111 			    paddrlen, ill->ill_phys_addr_length));
16112 			err = EINVAL;
16113 			break;
16114 		}
16115 
16116 		if (ill->ill_nd_lla_mp == NULL) {
16117 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16118 				err = ENOMEM;
16119 				break;
16120 			}
16121 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16122 		}
16123 
16124 		/*
16125 		 * Set the interface token.  If the zeroth interface address
16126 		 * is unspecified, then set it to the link local address.
16127 		 */
16128 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16129 			(void) ill_setdefaulttoken(ill);
16130 
16131 		ASSERT(ill->ill_ipif->ipif_id == 0);
16132 		if (ipif != NULL &&
16133 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16134 			(void) ipif_setlinklocal(ipif);
16135 		}
16136 		break;
16137 	}
16138 	case DL_OK_ACK:
16139 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16140 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16141 		    dloa->dl_correct_primitive));
16142 		switch (dloa->dl_correct_primitive) {
16143 		case DL_PROMISCON_REQ:
16144 		case DL_PROMISCOFF_REQ:
16145 		case DL_ENABMULTI_REQ:
16146 		case DL_DISABMULTI_REQ:
16147 		case DL_UNBIND_REQ:
16148 		case DL_ATTACH_REQ:
16149 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16150 			break;
16151 		}
16152 		break;
16153 	default:
16154 		break;
16155 	}
16156 
16157 	freemsg(mp);
16158 	if (mp1 != NULL) {
16159 		/*
16160 		 * The operation must complete without EINPROGRESS
16161 		 * since ipsq_pending_mp_get() has removed the mblk
16162 		 * from ipsq_pending_mp.  Otherwise, the operation
16163 		 * will be stuck forever in the ipsq.
16164 		 */
16165 		ASSERT(err != EINPROGRESS);
16166 
16167 		switch (ipsq->ipsq_current_ioctl) {
16168 		case 0:
16169 			ipsq_current_finish(ipsq);
16170 			break;
16171 
16172 		case SIOCLIFADDIF:
16173 		case SIOCSLIFNAME:
16174 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16175 			break;
16176 
16177 		default:
16178 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16179 			break;
16180 		}
16181 	}
16182 }
16183 
16184 /*
16185  * ip_rput_other is called by ip_rput to handle messages modifying the global
16186  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16187  */
16188 /* ARGSUSED */
16189 void
16190 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16191 {
16192 	ill_t		*ill;
16193 	struct iocblk	*iocp;
16194 	mblk_t		*mp1;
16195 	conn_t		*connp = NULL;
16196 
16197 	ip1dbg(("ip_rput_other "));
16198 	ill = (ill_t *)q->q_ptr;
16199 	/*
16200 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16201 	 * in which case ipsq is NULL.
16202 	 */
16203 	if (ipsq != NULL) {
16204 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16205 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16206 	}
16207 
16208 	switch (mp->b_datap->db_type) {
16209 	case M_ERROR:
16210 	case M_HANGUP:
16211 		/*
16212 		 * The device has a problem.  We force the ILL down.  It can
16213 		 * be brought up again manually using SIOCSIFFLAGS (via
16214 		 * ifconfig or equivalent).
16215 		 */
16216 		ASSERT(ipsq != NULL);
16217 		if (mp->b_rptr < mp->b_wptr)
16218 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16219 		if (ill->ill_error == 0)
16220 			ill->ill_error = ENXIO;
16221 		if (!ill_down_start(q, mp))
16222 			return;
16223 		ipif_all_down_tail(ipsq, q, mp, NULL);
16224 		break;
16225 	case M_IOCACK:
16226 		iocp = (struct iocblk *)mp->b_rptr;
16227 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16228 		switch (iocp->ioc_cmd) {
16229 		case SIOCSTUNPARAM:
16230 		case OSIOCSTUNPARAM:
16231 			ASSERT(ipsq != NULL);
16232 			/*
16233 			 * Finish socket ioctl passed through to tun.
16234 			 * We should have an IOCTL waiting on this.
16235 			 */
16236 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16237 			if (ill->ill_isv6) {
16238 				struct iftun_req *ta;
16239 
16240 				/*
16241 				 * if a source or destination is
16242 				 * being set, try and set the link
16243 				 * local address for the tunnel
16244 				 */
16245 				ta = (struct iftun_req *)mp->b_cont->
16246 				    b_cont->b_rptr;
16247 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16248 					ipif_set_tun_llink(ill, ta);
16249 				}
16250 
16251 			}
16252 			if (mp1 != NULL) {
16253 				/*
16254 				 * Now copy back the b_next/b_prev used by
16255 				 * mi code for the mi_copy* functions.
16256 				 * See ip_sioctl_tunparam() for the reason.
16257 				 * Also protect against missing b_cont.
16258 				 */
16259 				if (mp->b_cont != NULL) {
16260 					mp->b_cont->b_next =
16261 					    mp1->b_cont->b_next;
16262 					mp->b_cont->b_prev =
16263 					    mp1->b_cont->b_prev;
16264 				}
16265 				inet_freemsg(mp1);
16266 				ASSERT(connp != NULL);
16267 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16268 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16269 			} else {
16270 				ASSERT(connp == NULL);
16271 				putnext(q, mp);
16272 			}
16273 			break;
16274 		case SIOCGTUNPARAM:
16275 		case OSIOCGTUNPARAM:
16276 			/*
16277 			 * This is really M_IOCDATA from the tunnel driver.
16278 			 * convert back and complete the ioctl.
16279 			 * We should have an IOCTL waiting on this.
16280 			 */
16281 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16282 			if (mp1) {
16283 				/*
16284 				 * Now copy back the b_next/b_prev used by
16285 				 * mi code for the mi_copy* functions.
16286 				 * See ip_sioctl_tunparam() for the reason.
16287 				 * Also protect against missing b_cont.
16288 				 */
16289 				if (mp->b_cont != NULL) {
16290 					mp->b_cont->b_next =
16291 					    mp1->b_cont->b_next;
16292 					mp->b_cont->b_prev =
16293 					    mp1->b_cont->b_prev;
16294 				}
16295 				inet_freemsg(mp1);
16296 				if (iocp->ioc_error == 0)
16297 					mp->b_datap->db_type = M_IOCDATA;
16298 				ASSERT(connp != NULL);
16299 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16300 				    iocp->ioc_error, COPYOUT, NULL);
16301 			} else {
16302 				ASSERT(connp == NULL);
16303 				putnext(q, mp);
16304 			}
16305 			break;
16306 		default:
16307 			break;
16308 		}
16309 		break;
16310 	case M_IOCNAK:
16311 		iocp = (struct iocblk *)mp->b_rptr;
16312 
16313 		switch (iocp->ioc_cmd) {
16314 		int mode;
16315 
16316 		case DL_IOC_HDR_INFO:
16317 			/*
16318 			 * If this was the first attempt turn of the
16319 			 * fastpath probing.
16320 			 */
16321 			mutex_enter(&ill->ill_lock);
16322 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16323 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16324 				mutex_exit(&ill->ill_lock);
16325 				ill_fastpath_nack(ill);
16326 				ip1dbg(("ip_rput: DLPI fastpath off on "
16327 				    "interface %s\n",
16328 				    ill->ill_name));
16329 			} else {
16330 				mutex_exit(&ill->ill_lock);
16331 			}
16332 			freemsg(mp);
16333 			break;
16334 		case SIOCSTUNPARAM:
16335 		case OSIOCSTUNPARAM:
16336 			ASSERT(ipsq != NULL);
16337 			/*
16338 			 * Finish socket ioctl passed through to tun
16339 			 * We should have an IOCTL waiting on this.
16340 			 */
16341 			/* FALLTHRU */
16342 		case SIOCGTUNPARAM:
16343 		case OSIOCGTUNPARAM:
16344 			/*
16345 			 * This is really M_IOCDATA from the tunnel driver.
16346 			 * convert back and complete the ioctl.
16347 			 * We should have an IOCTL waiting on this.
16348 			 */
16349 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16350 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16351 				mp1 = ill_pending_mp_get(ill, &connp,
16352 				    iocp->ioc_id);
16353 				mode = COPYOUT;
16354 				ipsq = NULL;
16355 			} else {
16356 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16357 				mode = NO_COPYOUT;
16358 			}
16359 			if (mp1 != NULL) {
16360 				/*
16361 				 * Now copy back the b_next/b_prev used by
16362 				 * mi code for the mi_copy* functions.
16363 				 * See ip_sioctl_tunparam() for the reason.
16364 				 * Also protect against missing b_cont.
16365 				 */
16366 				if (mp->b_cont != NULL) {
16367 					mp->b_cont->b_next =
16368 					    mp1->b_cont->b_next;
16369 					mp->b_cont->b_prev =
16370 					    mp1->b_cont->b_prev;
16371 				}
16372 				inet_freemsg(mp1);
16373 				if (iocp->ioc_error == 0)
16374 					iocp->ioc_error = EINVAL;
16375 				ASSERT(connp != NULL);
16376 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16377 				    iocp->ioc_error, mode, ipsq);
16378 			} else {
16379 				ASSERT(connp == NULL);
16380 				putnext(q, mp);
16381 			}
16382 			break;
16383 		default:
16384 			break;
16385 		}
16386 	default:
16387 		break;
16388 	}
16389 }
16390 
16391 /*
16392  * NOTE : This function does not ire_refrele the ire argument passed in.
16393  *
16394  * IPQoS notes
16395  * IP policy is invoked twice for a forwarded packet, once on the read side
16396  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16397  * enabled. An additional parameter, in_ill, has been added for this purpose.
16398  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16399  * because ip_mroute drops this information.
16400  *
16401  */
16402 void
16403 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16404 {
16405 	uint32_t	old_pkt_len;
16406 	uint32_t	pkt_len;
16407 	queue_t	*q;
16408 	uint32_t	sum;
16409 #define	rptr	((uchar_t *)ipha)
16410 	uint32_t	max_frag;
16411 	uint32_t	ill_index;
16412 	ill_t		*out_ill;
16413 	mib2_ipIfStatsEntry_t *mibptr;
16414 	ip_stack_t	*ipst = in_ill->ill_ipst;
16415 
16416 	/* Get the ill_index of the incoming ILL */
16417 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16418 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16419 
16420 	/* Initiate Read side IPPF processing */
16421 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16422 		ip_process(IPP_FWD_IN, &mp, ill_index);
16423 		if (mp == NULL) {
16424 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16425 			    "during IPPF processing\n"));
16426 			return;
16427 		}
16428 	}
16429 
16430 	/* Adjust the checksum to reflect the ttl decrement. */
16431 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16432 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16433 
16434 	if (ipha->ipha_ttl-- <= 1) {
16435 		if (ip_csum_hdr(ipha)) {
16436 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16437 			goto drop_pkt;
16438 		}
16439 		/*
16440 		 * Note: ire_stq this will be NULL for multicast
16441 		 * datagrams using the long path through arp (the IRE
16442 		 * is not an IRE_CACHE). This should not cause
16443 		 * problems since we don't generate ICMP errors for
16444 		 * multicast packets.
16445 		 */
16446 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16447 		q = ire->ire_stq;
16448 		if (q != NULL) {
16449 			/* Sent by forwarding path, and router is global zone */
16450 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16451 			    GLOBAL_ZONEID, ipst);
16452 		} else
16453 			freemsg(mp);
16454 		return;
16455 	}
16456 
16457 	/*
16458 	 * Don't forward if the interface is down
16459 	 */
16460 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16461 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16462 		ip2dbg(("ip_rput_forward:interface is down\n"));
16463 		goto drop_pkt;
16464 	}
16465 
16466 	/* Get the ill_index of the outgoing ILL */
16467 	out_ill = ire_to_ill(ire);
16468 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16469 
16470 	DTRACE_PROBE4(ip4__forwarding__start,
16471 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16472 
16473 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16474 	    ipst->ips_ipv4firewall_forwarding,
16475 	    in_ill, out_ill, ipha, mp, mp, ipst);
16476 
16477 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16478 
16479 	if (mp == NULL)
16480 		return;
16481 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16482 
16483 	if (is_system_labeled()) {
16484 		mblk_t *mp1;
16485 
16486 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16487 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16488 			goto drop_pkt;
16489 		}
16490 		/* Size may have changed */
16491 		mp = mp1;
16492 		ipha = (ipha_t *)mp->b_rptr;
16493 		pkt_len = ntohs(ipha->ipha_length);
16494 	}
16495 
16496 	/* Check if there are options to update */
16497 	if (!IS_SIMPLE_IPH(ipha)) {
16498 		if (ip_csum_hdr(ipha)) {
16499 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16500 			goto drop_pkt;
16501 		}
16502 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16503 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16504 			return;
16505 		}
16506 
16507 		ipha->ipha_hdr_checksum = 0;
16508 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16509 	}
16510 	max_frag = ire->ire_max_frag;
16511 	if (pkt_len > max_frag) {
16512 		/*
16513 		 * It needs fragging on its way out.  We haven't
16514 		 * verified the header checksum yet.  Since we
16515 		 * are going to put a surely good checksum in the
16516 		 * outgoing header, we have to make sure that it
16517 		 * was good coming in.
16518 		 */
16519 		if (ip_csum_hdr(ipha)) {
16520 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16521 			goto drop_pkt;
16522 		}
16523 		/* Initiate Write side IPPF processing */
16524 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16525 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16526 			if (mp == NULL) {
16527 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16528 				    " during IPPF processing\n"));
16529 				return;
16530 			}
16531 		}
16532 		/*
16533 		 * Handle labeled packet resizing.
16534 		 *
16535 		 * If we have added a label, inform ip_wput_frag() of its
16536 		 * effect on the MTU for ICMP messages.
16537 		 */
16538 		if (pkt_len > old_pkt_len) {
16539 			uint32_t secopt_size;
16540 
16541 			secopt_size = pkt_len - old_pkt_len;
16542 			if (secopt_size < max_frag)
16543 				max_frag -= secopt_size;
16544 		}
16545 
16546 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16547 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16548 		return;
16549 	}
16550 
16551 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16552 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16553 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16554 	    ipst->ips_ipv4firewall_physical_out,
16555 	    NULL, out_ill, ipha, mp, mp, ipst);
16556 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16557 	if (mp == NULL)
16558 		return;
16559 
16560 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16561 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16562 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16563 	/* ip_xmit_v4 always consumes the packet */
16564 	return;
16565 
16566 drop_pkt:;
16567 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16568 	freemsg(mp);
16569 #undef	rptr
16570 }
16571 
16572 void
16573 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16574 {
16575 	ire_t	*ire;
16576 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16577 
16578 	ASSERT(!ipif->ipif_isv6);
16579 	/*
16580 	 * Find an IRE which matches the destination and the outgoing
16581 	 * queue in the cache table. All we need is an IRE_CACHE which
16582 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16583 	 * then it is enough to have some IRE_CACHE in the group.
16584 	 */
16585 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16586 		dst = ipif->ipif_pp_dst_addr;
16587 
16588 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16589 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16590 	if (ire == NULL) {
16591 		/*
16592 		 * Mark this packet to make it be delivered to
16593 		 * ip_rput_forward after the new ire has been
16594 		 * created.
16595 		 */
16596 		mp->b_prev = NULL;
16597 		mp->b_next = mp;
16598 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16599 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16600 	} else {
16601 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16602 		IRE_REFRELE(ire);
16603 	}
16604 }
16605 
16606 /* Update any source route, record route or timestamp options */
16607 static int
16608 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16609 {
16610 	ipoptp_t	opts;
16611 	uchar_t		*opt;
16612 	uint8_t		optval;
16613 	uint8_t		optlen;
16614 	ipaddr_t	dst;
16615 	uint32_t	ts;
16616 	ire_t		*dst_ire = NULL;
16617 	ire_t		*tmp_ire = NULL;
16618 	timestruc_t	now;
16619 
16620 	ip2dbg(("ip_rput_forward_options\n"));
16621 	dst = ipha->ipha_dst;
16622 	for (optval = ipoptp_first(&opts, ipha);
16623 	    optval != IPOPT_EOL;
16624 	    optval = ipoptp_next(&opts)) {
16625 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16626 		opt = opts.ipoptp_cur;
16627 		optlen = opts.ipoptp_len;
16628 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16629 		    optval, opts.ipoptp_len));
16630 		switch (optval) {
16631 			uint32_t off;
16632 		case IPOPT_SSRR:
16633 		case IPOPT_LSRR:
16634 			/* Check if adminstratively disabled */
16635 			if (!ipst->ips_ip_forward_src_routed) {
16636 				if (ire->ire_stq != NULL) {
16637 					/*
16638 					 * Sent by forwarding path, and router
16639 					 * is global zone
16640 					 */
16641 					icmp_unreachable(ire->ire_stq, mp,
16642 					    ICMP_SOURCE_ROUTE_FAILED,
16643 					    GLOBAL_ZONEID, ipst);
16644 				} else {
16645 					ip0dbg(("ip_rput_forward_options: "
16646 					    "unable to send unreach\n"));
16647 					freemsg(mp);
16648 				}
16649 				return (-1);
16650 			}
16651 
16652 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16653 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16654 			if (dst_ire == NULL) {
16655 				/*
16656 				 * Must be partial since ip_rput_options
16657 				 * checked for strict.
16658 				 */
16659 				break;
16660 			}
16661 			off = opt[IPOPT_OFFSET];
16662 			off--;
16663 		redo_srr:
16664 			if (optlen < IP_ADDR_LEN ||
16665 			    off > optlen - IP_ADDR_LEN) {
16666 				/* End of source route */
16667 				ip1dbg((
16668 				    "ip_rput_forward_options: end of SR\n"));
16669 				ire_refrele(dst_ire);
16670 				break;
16671 			}
16672 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16673 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16674 			    IP_ADDR_LEN);
16675 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16676 			    ntohl(dst)));
16677 
16678 			/*
16679 			 * Check if our address is present more than
16680 			 * once as consecutive hops in source route.
16681 			 */
16682 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16683 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16684 			if (tmp_ire != NULL) {
16685 				ire_refrele(tmp_ire);
16686 				off += IP_ADDR_LEN;
16687 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16688 				goto redo_srr;
16689 			}
16690 			ipha->ipha_dst = dst;
16691 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16692 			ire_refrele(dst_ire);
16693 			break;
16694 		case IPOPT_RR:
16695 			off = opt[IPOPT_OFFSET];
16696 			off--;
16697 			if (optlen < IP_ADDR_LEN ||
16698 			    off > optlen - IP_ADDR_LEN) {
16699 				/* No more room - ignore */
16700 				ip1dbg((
16701 				    "ip_rput_forward_options: end of RR\n"));
16702 				break;
16703 			}
16704 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16705 			    IP_ADDR_LEN);
16706 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16707 			break;
16708 		case IPOPT_TS:
16709 			/* Insert timestamp if there is room */
16710 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16711 			case IPOPT_TS_TSONLY:
16712 				off = IPOPT_TS_TIMELEN;
16713 				break;
16714 			case IPOPT_TS_PRESPEC:
16715 			case IPOPT_TS_PRESPEC_RFC791:
16716 				/* Verify that the address matched */
16717 				off = opt[IPOPT_OFFSET] - 1;
16718 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16719 				dst_ire = ire_ctable_lookup(dst, 0,
16720 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16721 				    MATCH_IRE_TYPE, ipst);
16722 				if (dst_ire == NULL) {
16723 					/* Not for us */
16724 					break;
16725 				}
16726 				ire_refrele(dst_ire);
16727 				/* FALLTHRU */
16728 			case IPOPT_TS_TSANDADDR:
16729 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16730 				break;
16731 			default:
16732 				/*
16733 				 * ip_*put_options should have already
16734 				 * dropped this packet.
16735 				 */
16736 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16737 				    "unknown IT - bug in ip_rput_options?\n");
16738 				return (0);	/* Keep "lint" happy */
16739 			}
16740 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16741 				/* Increase overflow counter */
16742 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16743 				opt[IPOPT_POS_OV_FLG] =
16744 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16745 				    (off << 4));
16746 				break;
16747 			}
16748 			off = opt[IPOPT_OFFSET] - 1;
16749 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16750 			case IPOPT_TS_PRESPEC:
16751 			case IPOPT_TS_PRESPEC_RFC791:
16752 			case IPOPT_TS_TSANDADDR:
16753 				bcopy(&ire->ire_src_addr,
16754 				    (char *)opt + off, IP_ADDR_LEN);
16755 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16756 				/* FALLTHRU */
16757 			case IPOPT_TS_TSONLY:
16758 				off = opt[IPOPT_OFFSET] - 1;
16759 				/* Compute # of milliseconds since midnight */
16760 				gethrestime(&now);
16761 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16762 				    now.tv_nsec / (NANOSEC / MILLISEC);
16763 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16764 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16765 				break;
16766 			}
16767 			break;
16768 		}
16769 	}
16770 	return (0);
16771 }
16772 
16773 /*
16774  * This is called after processing at least one of AH/ESP headers.
16775  *
16776  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16777  * the actual, physical interface on which the packet was received,
16778  * but, when ip_strict_dst_multihoming is set to 1, could be the
16779  * interface which had the ipha_dst configured when the packet went
16780  * through ip_rput. The ill_index corresponding to the recv_ill
16781  * is saved in ipsec_in_rill_index
16782  *
16783  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16784  * cannot assume "ire" points to valid data for any IPv6 cases.
16785  */
16786 void
16787 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16788 {
16789 	mblk_t *mp;
16790 	ipaddr_t dst;
16791 	in6_addr_t *v6dstp;
16792 	ipha_t *ipha;
16793 	ip6_t *ip6h;
16794 	ipsec_in_t *ii;
16795 	boolean_t ill_need_rele = B_FALSE;
16796 	boolean_t rill_need_rele = B_FALSE;
16797 	boolean_t ire_need_rele = B_FALSE;
16798 	netstack_t	*ns;
16799 	ip_stack_t	*ipst;
16800 
16801 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16802 	ASSERT(ii->ipsec_in_ill_index != 0);
16803 	ns = ii->ipsec_in_ns;
16804 	ASSERT(ii->ipsec_in_ns != NULL);
16805 	ipst = ns->netstack_ip;
16806 
16807 	mp = ipsec_mp->b_cont;
16808 	ASSERT(mp != NULL);
16809 
16810 
16811 	if (ill == NULL) {
16812 		ASSERT(recv_ill == NULL);
16813 		/*
16814 		 * We need to get the original queue on which ip_rput_local
16815 		 * or ip_rput_data_v6 was called.
16816 		 */
16817 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16818 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16819 		ill_need_rele = B_TRUE;
16820 
16821 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16822 			recv_ill = ill_lookup_on_ifindex(
16823 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16824 			    NULL, NULL, NULL, NULL, ipst);
16825 			rill_need_rele = B_TRUE;
16826 		} else {
16827 			recv_ill = ill;
16828 		}
16829 
16830 		if ((ill == NULL) || (recv_ill == NULL)) {
16831 			ip0dbg(("ip_fanout_proto_again: interface "
16832 			    "disappeared\n"));
16833 			if (ill != NULL)
16834 				ill_refrele(ill);
16835 			if (recv_ill != NULL)
16836 				ill_refrele(recv_ill);
16837 			freemsg(ipsec_mp);
16838 			return;
16839 		}
16840 	}
16841 
16842 	ASSERT(ill != NULL && recv_ill != NULL);
16843 
16844 	if (mp->b_datap->db_type == M_CTL) {
16845 		/*
16846 		 * AH/ESP is returning the ICMP message after
16847 		 * removing their headers. Fanout again till
16848 		 * it gets to the right protocol.
16849 		 */
16850 		if (ii->ipsec_in_v4) {
16851 			icmph_t *icmph;
16852 			int iph_hdr_length;
16853 			int hdr_length;
16854 
16855 			ipha = (ipha_t *)mp->b_rptr;
16856 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16857 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16858 			ipha = (ipha_t *)&icmph[1];
16859 			hdr_length = IPH_HDR_LENGTH(ipha);
16860 			/*
16861 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16862 			 * Reset the type to M_DATA.
16863 			 */
16864 			mp->b_datap->db_type = M_DATA;
16865 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16866 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16867 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16868 		} else {
16869 			icmp6_t *icmp6;
16870 			int hdr_length;
16871 
16872 			ip6h = (ip6_t *)mp->b_rptr;
16873 			/* Don't call hdr_length_v6() unless you have to. */
16874 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16875 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16876 			else
16877 				hdr_length = IPV6_HDR_LEN;
16878 
16879 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16880 			/*
16881 			 * icmp_inbound_error_fanout_v6 may need to do
16882 			 * pullupmsg.  Reset the type to M_DATA.
16883 			 */
16884 			mp->b_datap->db_type = M_DATA;
16885 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16886 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16887 		}
16888 		if (ill_need_rele)
16889 			ill_refrele(ill);
16890 		if (rill_need_rele)
16891 			ill_refrele(recv_ill);
16892 		return;
16893 	}
16894 
16895 	if (ii->ipsec_in_v4) {
16896 		ipha = (ipha_t *)mp->b_rptr;
16897 		dst = ipha->ipha_dst;
16898 		if (CLASSD(dst)) {
16899 			/*
16900 			 * Multicast has to be delivered to all streams.
16901 			 */
16902 			dst = INADDR_BROADCAST;
16903 		}
16904 
16905 		if (ire == NULL) {
16906 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16907 			    MBLK_GETLABEL(mp), ipst);
16908 			if (ire == NULL) {
16909 				if (ill_need_rele)
16910 					ill_refrele(ill);
16911 				if (rill_need_rele)
16912 					ill_refrele(recv_ill);
16913 				ip1dbg(("ip_fanout_proto_again: "
16914 				    "IRE not found"));
16915 				freemsg(ipsec_mp);
16916 				return;
16917 			}
16918 			ire_need_rele = B_TRUE;
16919 		}
16920 
16921 		switch (ipha->ipha_protocol) {
16922 			case IPPROTO_UDP:
16923 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16924 				    recv_ill);
16925 				if (ire_need_rele)
16926 					ire_refrele(ire);
16927 				break;
16928 			case IPPROTO_TCP:
16929 				if (!ire_need_rele)
16930 					IRE_REFHOLD(ire);
16931 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16932 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16933 				IRE_REFRELE(ire);
16934 				if (mp != NULL)
16935 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16936 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16937 				break;
16938 			case IPPROTO_SCTP:
16939 				if (!ire_need_rele)
16940 					IRE_REFHOLD(ire);
16941 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16942 				    ipsec_mp, 0, ill->ill_rq, dst);
16943 				break;
16944 			default:
16945 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16946 				    recv_ill, B_FALSE);
16947 				if (ire_need_rele)
16948 					ire_refrele(ire);
16949 				break;
16950 		}
16951 	} else {
16952 		uint32_t rput_flags = 0;
16953 
16954 		ip6h = (ip6_t *)mp->b_rptr;
16955 		v6dstp = &ip6h->ip6_dst;
16956 		/*
16957 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16958 		 * address.
16959 		 *
16960 		 * Currently, we don't store that state in the IPSEC_IN
16961 		 * message, and we may need to.
16962 		 */
16963 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16964 		    IP6_IN_LLMCAST : 0);
16965 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16966 		    NULL, NULL);
16967 	}
16968 	if (ill_need_rele)
16969 		ill_refrele(ill);
16970 	if (rill_need_rele)
16971 		ill_refrele(recv_ill);
16972 }
16973 
16974 /*
16975  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16976  * returns 'true' if there are still fragments left on the queue, in
16977  * which case we restart the timer.
16978  */
16979 void
16980 ill_frag_timer(void *arg)
16981 {
16982 	ill_t	*ill = (ill_t *)arg;
16983 	boolean_t frag_pending;
16984 	ip_stack_t	*ipst = ill->ill_ipst;
16985 
16986 	mutex_enter(&ill->ill_lock);
16987 	ASSERT(!ill->ill_fragtimer_executing);
16988 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16989 		ill->ill_frag_timer_id = 0;
16990 		mutex_exit(&ill->ill_lock);
16991 		return;
16992 	}
16993 	ill->ill_fragtimer_executing = 1;
16994 	mutex_exit(&ill->ill_lock);
16995 
16996 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16997 
16998 	/*
16999 	 * Restart the timer, if we have fragments pending or if someone
17000 	 * wanted us to be scheduled again.
17001 	 */
17002 	mutex_enter(&ill->ill_lock);
17003 	ill->ill_fragtimer_executing = 0;
17004 	ill->ill_frag_timer_id = 0;
17005 	if (frag_pending || ill->ill_fragtimer_needrestart)
17006 		ill_frag_timer_start(ill);
17007 	mutex_exit(&ill->ill_lock);
17008 }
17009 
17010 void
17011 ill_frag_timer_start(ill_t *ill)
17012 {
17013 	ip_stack_t	*ipst = ill->ill_ipst;
17014 
17015 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17016 
17017 	/* If the ill is closing or opening don't proceed */
17018 	if (ill->ill_state_flags & ILL_CONDEMNED)
17019 		return;
17020 
17021 	if (ill->ill_fragtimer_executing) {
17022 		/*
17023 		 * ill_frag_timer is currently executing. Just record the
17024 		 * the fact that we want the timer to be restarted.
17025 		 * ill_frag_timer will post a timeout before it returns,
17026 		 * ensuring it will be called again.
17027 		 */
17028 		ill->ill_fragtimer_needrestart = 1;
17029 		return;
17030 	}
17031 
17032 	if (ill->ill_frag_timer_id == 0) {
17033 		/*
17034 		 * The timer is neither running nor is the timeout handler
17035 		 * executing. Post a timeout so that ill_frag_timer will be
17036 		 * called
17037 		 */
17038 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17039 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17040 		ill->ill_fragtimer_needrestart = 0;
17041 	}
17042 }
17043 
17044 /*
17045  * This routine is needed for loopback when forwarding multicasts.
17046  *
17047  * IPQoS Notes:
17048  * IPPF processing is done in fanout routines.
17049  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17050  * processing for IPsec packets is done when it comes back in clear.
17051  * NOTE : The callers of this function need to do the ire_refrele for the
17052  *	  ire that is being passed in.
17053  */
17054 void
17055 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17056     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17057 {
17058 	ill_t	*ill = (ill_t *)q->q_ptr;
17059 	uint32_t	sum;
17060 	uint32_t	u1;
17061 	uint32_t	u2;
17062 	int		hdr_length;
17063 	boolean_t	mctl_present;
17064 	mblk_t		*first_mp = mp;
17065 	mblk_t		*hada_mp = NULL;
17066 	ipha_t		*inner_ipha;
17067 	ip_stack_t	*ipst;
17068 
17069 	ASSERT(recv_ill != NULL);
17070 	ipst = recv_ill->ill_ipst;
17071 
17072 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17073 	    "ip_rput_locl_start: q %p", q);
17074 
17075 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17076 	ASSERT(ill != NULL);
17077 
17078 
17079 #define	rptr	((uchar_t *)ipha)
17080 #define	iphs	((uint16_t *)ipha)
17081 
17082 	/*
17083 	 * no UDP or TCP packet should come here anymore.
17084 	 */
17085 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17086 	    ipha->ipha_protocol != IPPROTO_UDP);
17087 
17088 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17089 	if (mctl_present &&
17090 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17091 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17092 
17093 		/*
17094 		 * It's an IPsec accelerated packet.
17095 		 * Keep a pointer to the data attributes around until
17096 		 * we allocate the ipsec_info_t.
17097 		 */
17098 		IPSECHW_DEBUG(IPSECHW_PKT,
17099 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17100 		hada_mp = first_mp;
17101 		hada_mp->b_cont = NULL;
17102 		/*
17103 		 * Since it is accelerated, it comes directly from
17104 		 * the ill and the data attributes is followed by
17105 		 * the packet data.
17106 		 */
17107 		ASSERT(mp->b_datap->db_type != M_CTL);
17108 		first_mp = mp;
17109 		mctl_present = B_FALSE;
17110 	}
17111 
17112 	/*
17113 	 * IF M_CTL is not present, then ipsec_in_is_secure
17114 	 * should return B_TRUE. There is a case where loopback
17115 	 * packets has an M_CTL in the front with all the
17116 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17117 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17118 	 * packets never comes here, it is safe to ASSERT the
17119 	 * following.
17120 	 */
17121 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17122 
17123 	/*
17124 	 * Also, we should never have an mctl_present if this is an
17125 	 * ESP-in-UDP packet.
17126 	 */
17127 	ASSERT(!mctl_present || !esp_in_udp_packet);
17128 
17129 
17130 	/* u1 is # words of IP options */
17131 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17132 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17133 
17134 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17135 		if (u1) {
17136 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17137 				if (hada_mp != NULL)
17138 					freemsg(hada_mp);
17139 				return;
17140 			}
17141 		} else {
17142 			/* Check the IP header checksum.  */
17143 #define	uph	((uint16_t *)ipha)
17144 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17145 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17146 #undef  uph
17147 			/* finish doing IP checksum */
17148 			sum = (sum & 0xFFFF) + (sum >> 16);
17149 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17150 			if (sum && sum != 0xFFFF) {
17151 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17152 				goto drop_pkt;
17153 			}
17154 		}
17155 	}
17156 
17157 	/*
17158 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17159 	 * might be called more than once for secure packets, count only
17160 	 * the first time.
17161 	 */
17162 	if (!mctl_present) {
17163 		UPDATE_IB_PKT_COUNT(ire);
17164 		ire->ire_last_used_time = lbolt;
17165 	}
17166 
17167 	/* Check for fragmentation offset. */
17168 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17169 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17170 	if (u1) {
17171 		/*
17172 		 * We re-assemble fragments before we do the AH/ESP
17173 		 * processing. Thus, M_CTL should not be present
17174 		 * while we are re-assembling.
17175 		 */
17176 		ASSERT(!mctl_present);
17177 		ASSERT(first_mp == mp);
17178 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17179 			return;
17180 		}
17181 		/*
17182 		 * Make sure that first_mp points back to mp as
17183 		 * the mp we came in with could have changed in
17184 		 * ip_rput_fragment().
17185 		 */
17186 		ipha = (ipha_t *)mp->b_rptr;
17187 		first_mp = mp;
17188 	}
17189 
17190 	/*
17191 	 * Clear hardware checksumming flag as it is currently only
17192 	 * used by TCP and UDP.
17193 	 */
17194 	DB_CKSUMFLAGS(mp) = 0;
17195 
17196 	/* Now we have a complete datagram, destined for this machine. */
17197 	u1 = IPH_HDR_LENGTH(ipha);
17198 	switch (ipha->ipha_protocol) {
17199 	case IPPROTO_ICMP: {
17200 		ire_t		*ire_zone;
17201 		ilm_t		*ilm;
17202 		mblk_t		*mp1;
17203 		zoneid_t	last_zoneid;
17204 
17205 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17206 			ASSERT(ire->ire_type == IRE_BROADCAST);
17207 			/*
17208 			 * In the multicast case, applications may have joined
17209 			 * the group from different zones, so we need to deliver
17210 			 * the packet to each of them. Loop through the
17211 			 * multicast memberships structures (ilm) on the receive
17212 			 * ill and send a copy of the packet up each matching
17213 			 * one. However, we don't do this for multicasts sent on
17214 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17215 			 * they must stay in the sender's zone.
17216 			 *
17217 			 * ilm_add_v6() ensures that ilms in the same zone are
17218 			 * contiguous in the ill_ilm list. We use this property
17219 			 * to avoid sending duplicates needed when two
17220 			 * applications in the same zone join the same group on
17221 			 * different logical interfaces: we ignore the ilm if
17222 			 * its zoneid is the same as the last matching one.
17223 			 * In addition, the sending of the packet for
17224 			 * ire_zoneid is delayed until all of the other ilms
17225 			 * have been exhausted.
17226 			 */
17227 			last_zoneid = -1;
17228 			ILM_WALKER_HOLD(recv_ill);
17229 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17230 			    ilm = ilm->ilm_next) {
17231 				if ((ilm->ilm_flags & ILM_DELETED) ||
17232 				    ipha->ipha_dst != ilm->ilm_addr ||
17233 				    ilm->ilm_zoneid == last_zoneid ||
17234 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17235 				    ilm->ilm_zoneid == ALL_ZONES ||
17236 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17237 					continue;
17238 				mp1 = ip_copymsg(first_mp);
17239 				if (mp1 == NULL)
17240 					continue;
17241 				icmp_inbound(q, mp1, B_TRUE, ill,
17242 				    0, sum, mctl_present, B_TRUE,
17243 				    recv_ill, ilm->ilm_zoneid);
17244 				last_zoneid = ilm->ilm_zoneid;
17245 			}
17246 			ILM_WALKER_RELE(recv_ill);
17247 		} else if (ire->ire_type == IRE_BROADCAST) {
17248 			/*
17249 			 * In the broadcast case, there may be many zones
17250 			 * which need a copy of the packet delivered to them.
17251 			 * There is one IRE_BROADCAST per broadcast address
17252 			 * and per zone; we walk those using a helper function.
17253 			 * In addition, the sending of the packet for ire is
17254 			 * delayed until all of the other ires have been
17255 			 * processed.
17256 			 */
17257 			IRB_REFHOLD(ire->ire_bucket);
17258 			ire_zone = NULL;
17259 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17260 			    ire)) != NULL) {
17261 				mp1 = ip_copymsg(first_mp);
17262 				if (mp1 == NULL)
17263 					continue;
17264 
17265 				UPDATE_IB_PKT_COUNT(ire_zone);
17266 				ire_zone->ire_last_used_time = lbolt;
17267 				icmp_inbound(q, mp1, B_TRUE, ill,
17268 				    0, sum, mctl_present, B_TRUE,
17269 				    recv_ill, ire_zone->ire_zoneid);
17270 			}
17271 			IRB_REFRELE(ire->ire_bucket);
17272 		}
17273 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17274 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17275 		    ire->ire_zoneid);
17276 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17277 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17278 		return;
17279 	}
17280 	case IPPROTO_IGMP:
17281 		/*
17282 		 * If we are not willing to accept IGMP packets in clear,
17283 		 * then check with global policy.
17284 		 */
17285 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17286 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17287 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17288 			if (first_mp == NULL)
17289 				return;
17290 		}
17291 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17292 			freemsg(first_mp);
17293 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17294 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17295 			return;
17296 		}
17297 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17298 			/* Bad packet - discarded by igmp_input */
17299 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17300 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17301 			if (mctl_present)
17302 				freeb(first_mp);
17303 			return;
17304 		}
17305 		/*
17306 		 * igmp_input() may have returned the pulled up message.
17307 		 * So first_mp and ipha need to be reinitialized.
17308 		 */
17309 		ipha = (ipha_t *)mp->b_rptr;
17310 		if (mctl_present)
17311 			first_mp->b_cont = mp;
17312 		else
17313 			first_mp = mp;
17314 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17315 		    connf_head != NULL) {
17316 			/* No user-level listener for IGMP packets */
17317 			goto drop_pkt;
17318 		}
17319 		/* deliver to local raw users */
17320 		break;
17321 	case IPPROTO_PIM:
17322 		/*
17323 		 * If we are not willing to accept PIM packets in clear,
17324 		 * then check with global policy.
17325 		 */
17326 		if (ipst->ips_pim_accept_clear_messages == 0) {
17327 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17328 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17329 			if (first_mp == NULL)
17330 				return;
17331 		}
17332 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17333 			freemsg(first_mp);
17334 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17335 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17336 			return;
17337 		}
17338 		if (pim_input(q, mp, ill) != 0) {
17339 			/* Bad packet - discarded by pim_input */
17340 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17341 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17342 			if (mctl_present)
17343 				freeb(first_mp);
17344 			return;
17345 		}
17346 
17347 		/*
17348 		 * pim_input() may have pulled up the message so ipha needs to
17349 		 * be reinitialized.
17350 		 */
17351 		ipha = (ipha_t *)mp->b_rptr;
17352 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17353 		    connf_head != NULL) {
17354 			/* No user-level listener for PIM packets */
17355 			goto drop_pkt;
17356 		}
17357 		/* deliver to local raw users */
17358 		break;
17359 	case IPPROTO_ENCAP:
17360 		/*
17361 		 * Handle self-encapsulated packets (IP-in-IP where
17362 		 * the inner addresses == the outer addresses).
17363 		 */
17364 		hdr_length = IPH_HDR_LENGTH(ipha);
17365 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17366 		    mp->b_wptr) {
17367 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17368 			    sizeof (ipha_t) - mp->b_rptr)) {
17369 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17370 				freemsg(first_mp);
17371 				return;
17372 			}
17373 			ipha = (ipha_t *)mp->b_rptr;
17374 		}
17375 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17376 		/*
17377 		 * Check the sanity of the inner IP header.
17378 		 */
17379 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17380 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17381 			freemsg(first_mp);
17382 			return;
17383 		}
17384 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17385 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17386 			freemsg(first_mp);
17387 			return;
17388 		}
17389 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17390 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17391 			ipsec_in_t *ii;
17392 
17393 			/*
17394 			 * Self-encapsulated tunnel packet. Remove
17395 			 * the outer IP header and fanout again.
17396 			 * We also need to make sure that the inner
17397 			 * header is pulled up until options.
17398 			 */
17399 			mp->b_rptr = (uchar_t *)inner_ipha;
17400 			ipha = inner_ipha;
17401 			hdr_length = IPH_HDR_LENGTH(ipha);
17402 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17403 				if (!pullupmsg(mp, (uchar_t *)ipha +
17404 				    + hdr_length - mp->b_rptr)) {
17405 					freemsg(first_mp);
17406 					return;
17407 				}
17408 				ipha = (ipha_t *)mp->b_rptr;
17409 			}
17410 			if (!mctl_present) {
17411 				ASSERT(first_mp == mp);
17412 				/*
17413 				 * This means that somebody is sending
17414 				 * Self-encapsualted packets without AH/ESP.
17415 				 * If AH/ESP was present, we would have already
17416 				 * allocated the first_mp.
17417 				 */
17418 				first_mp = ipsec_in_alloc(B_TRUE,
17419 				    ipst->ips_netstack);
17420 				if (first_mp == NULL) {
17421 					ip1dbg(("ip_proto_input: IPSEC_IN "
17422 					    "allocation failure.\n"));
17423 					BUMP_MIB(ill->ill_ip_mib,
17424 					    ipIfStatsInDiscards);
17425 					freemsg(mp);
17426 					return;
17427 				}
17428 				first_mp->b_cont = mp;
17429 			}
17430 			/*
17431 			 * We generally store the ill_index if we need to
17432 			 * do IPsec processing as we lose the ill queue when
17433 			 * we come back. But in this case, we never should
17434 			 * have to store the ill_index here as it should have
17435 			 * been stored previously when we processed the
17436 			 * AH/ESP header in this routine or for non-ipsec
17437 			 * cases, we still have the queue. But for some bad
17438 			 * packets from the wire, we can get to IPsec after
17439 			 * this and we better store the index for that case.
17440 			 */
17441 			ill = (ill_t *)q->q_ptr;
17442 			ii = (ipsec_in_t *)first_mp->b_rptr;
17443 			ii->ipsec_in_ill_index =
17444 			    ill->ill_phyint->phyint_ifindex;
17445 			ii->ipsec_in_rill_index =
17446 			    recv_ill->ill_phyint->phyint_ifindex;
17447 			if (ii->ipsec_in_decaps) {
17448 				/*
17449 				 * This packet is self-encapsulated multiple
17450 				 * times. We don't want to recurse infinitely.
17451 				 * To keep it simple, drop the packet.
17452 				 */
17453 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17454 				freemsg(first_mp);
17455 				return;
17456 			}
17457 			ii->ipsec_in_decaps = B_TRUE;
17458 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17459 			    ire);
17460 			return;
17461 		}
17462 		break;
17463 	case IPPROTO_AH:
17464 	case IPPROTO_ESP: {
17465 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17466 
17467 		/*
17468 		 * Fast path for AH/ESP. If this is the first time
17469 		 * we are sending a datagram to AH/ESP, allocate
17470 		 * a IPSEC_IN message and prepend it. Otherwise,
17471 		 * just fanout.
17472 		 */
17473 
17474 		int ipsec_rc;
17475 		ipsec_in_t *ii;
17476 		netstack_t *ns = ipst->ips_netstack;
17477 
17478 		IP_STAT(ipst, ipsec_proto_ahesp);
17479 		if (!mctl_present) {
17480 			ASSERT(first_mp == mp);
17481 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17482 			if (first_mp == NULL) {
17483 				ip1dbg(("ip_proto_input: IPSEC_IN "
17484 				    "allocation failure.\n"));
17485 				freemsg(hada_mp); /* okay ifnull */
17486 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17487 				freemsg(mp);
17488 				return;
17489 			}
17490 			/*
17491 			 * Store the ill_index so that when we come back
17492 			 * from IPsec we ride on the same queue.
17493 			 */
17494 			ill = (ill_t *)q->q_ptr;
17495 			ii = (ipsec_in_t *)first_mp->b_rptr;
17496 			ii->ipsec_in_ill_index =
17497 			    ill->ill_phyint->phyint_ifindex;
17498 			ii->ipsec_in_rill_index =
17499 			    recv_ill->ill_phyint->phyint_ifindex;
17500 			first_mp->b_cont = mp;
17501 			/*
17502 			 * Cache hardware acceleration info.
17503 			 */
17504 			if (hada_mp != NULL) {
17505 				IPSECHW_DEBUG(IPSECHW_PKT,
17506 				    ("ip_rput_local: caching data attr.\n"));
17507 				ii->ipsec_in_accelerated = B_TRUE;
17508 				ii->ipsec_in_da = hada_mp;
17509 				hada_mp = NULL;
17510 			}
17511 		} else {
17512 			ii = (ipsec_in_t *)first_mp->b_rptr;
17513 		}
17514 
17515 		if (!ipsec_loaded(ipss)) {
17516 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17517 			    ire->ire_zoneid, ipst);
17518 			return;
17519 		}
17520 
17521 		ns = ipst->ips_netstack;
17522 		/* select inbound SA and have IPsec process the pkt */
17523 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17524 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17525 			boolean_t esp_in_udp_sa;
17526 			if (esph == NULL)
17527 				return;
17528 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17529 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17530 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17531 			    IPSA_F_NATT) != 0);
17532 			/*
17533 			 * The following is a fancy, but quick, way of saying:
17534 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17535 			 *    OR
17536 			 * ESP SA and ESP-in-UDP packet --> drop
17537 			 */
17538 			if (esp_in_udp_sa != esp_in_udp_packet) {
17539 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17540 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17541 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17542 				    &ns->netstack_ipsec->ipsec_dropper);
17543 				return;
17544 			}
17545 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17546 			    first_mp, esph);
17547 		} else {
17548 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17549 			if (ah == NULL)
17550 				return;
17551 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17552 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17553 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17554 			    first_mp, ah);
17555 		}
17556 
17557 		switch (ipsec_rc) {
17558 		case IPSEC_STATUS_SUCCESS:
17559 			break;
17560 		case IPSEC_STATUS_FAILED:
17561 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17562 			/* FALLTHRU */
17563 		case IPSEC_STATUS_PENDING:
17564 			return;
17565 		}
17566 		/* we're done with IPsec processing, send it up */
17567 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17568 		return;
17569 	}
17570 	default:
17571 		break;
17572 	}
17573 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17574 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17575 		    ire->ire_zoneid));
17576 		goto drop_pkt;
17577 	}
17578 	/*
17579 	 * Handle protocols with which IP is less intimate.  There
17580 	 * can be more than one stream bound to a particular
17581 	 * protocol.  When this is the case, each one gets a copy
17582 	 * of any incoming packets.
17583 	 */
17584 	ip_fanout_proto(q, first_mp, ill, ipha,
17585 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17586 	    B_TRUE, recv_ill, ire->ire_zoneid);
17587 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17588 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17589 	return;
17590 
17591 drop_pkt:
17592 	freemsg(first_mp);
17593 	if (hada_mp != NULL)
17594 		freeb(hada_mp);
17595 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17596 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17597 #undef	rptr
17598 #undef  iphs
17599 
17600 }
17601 
17602 /*
17603  * Update any source route, record route or timestamp options.
17604  * Check that we are at end of strict source route.
17605  * The options have already been checked for sanity in ip_rput_options().
17606  */
17607 static boolean_t
17608 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17609     ip_stack_t *ipst)
17610 {
17611 	ipoptp_t	opts;
17612 	uchar_t		*opt;
17613 	uint8_t		optval;
17614 	uint8_t		optlen;
17615 	ipaddr_t	dst;
17616 	uint32_t	ts;
17617 	ire_t		*dst_ire;
17618 	timestruc_t	now;
17619 	zoneid_t	zoneid;
17620 	ill_t		*ill;
17621 
17622 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17623 
17624 	ip2dbg(("ip_rput_local_options\n"));
17625 
17626 	for (optval = ipoptp_first(&opts, ipha);
17627 	    optval != IPOPT_EOL;
17628 	    optval = ipoptp_next(&opts)) {
17629 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17630 		opt = opts.ipoptp_cur;
17631 		optlen = opts.ipoptp_len;
17632 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17633 		    optval, optlen));
17634 		switch (optval) {
17635 			uint32_t off;
17636 		case IPOPT_SSRR:
17637 		case IPOPT_LSRR:
17638 			off = opt[IPOPT_OFFSET];
17639 			off--;
17640 			if (optlen < IP_ADDR_LEN ||
17641 			    off > optlen - IP_ADDR_LEN) {
17642 				/* End of source route */
17643 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17644 				break;
17645 			}
17646 			/*
17647 			 * This will only happen if two consecutive entries
17648 			 * in the source route contains our address or if
17649 			 * it is a packet with a loose source route which
17650 			 * reaches us before consuming the whole source route
17651 			 */
17652 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17653 			if (optval == IPOPT_SSRR) {
17654 				goto bad_src_route;
17655 			}
17656 			/*
17657 			 * Hack: instead of dropping the packet truncate the
17658 			 * source route to what has been used by filling the
17659 			 * rest with IPOPT_NOP.
17660 			 */
17661 			opt[IPOPT_OLEN] = (uint8_t)off;
17662 			while (off < optlen) {
17663 				opt[off++] = IPOPT_NOP;
17664 			}
17665 			break;
17666 		case IPOPT_RR:
17667 			off = opt[IPOPT_OFFSET];
17668 			off--;
17669 			if (optlen < IP_ADDR_LEN ||
17670 			    off > optlen - IP_ADDR_LEN) {
17671 				/* No more room - ignore */
17672 				ip1dbg((
17673 				    "ip_rput_local_options: end of RR\n"));
17674 				break;
17675 			}
17676 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17677 			    IP_ADDR_LEN);
17678 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17679 			break;
17680 		case IPOPT_TS:
17681 			/* Insert timestamp if there is romm */
17682 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17683 			case IPOPT_TS_TSONLY:
17684 				off = IPOPT_TS_TIMELEN;
17685 				break;
17686 			case IPOPT_TS_PRESPEC:
17687 			case IPOPT_TS_PRESPEC_RFC791:
17688 				/* Verify that the address matched */
17689 				off = opt[IPOPT_OFFSET] - 1;
17690 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17691 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17692 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17693 				    ipst);
17694 				if (dst_ire == NULL) {
17695 					/* Not for us */
17696 					break;
17697 				}
17698 				ire_refrele(dst_ire);
17699 				/* FALLTHRU */
17700 			case IPOPT_TS_TSANDADDR:
17701 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17702 				break;
17703 			default:
17704 				/*
17705 				 * ip_*put_options should have already
17706 				 * dropped this packet.
17707 				 */
17708 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17709 				    "unknown IT - bug in ip_rput_options?\n");
17710 				return (B_TRUE);	/* Keep "lint" happy */
17711 			}
17712 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17713 				/* Increase overflow counter */
17714 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17715 				opt[IPOPT_POS_OV_FLG] =
17716 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17717 				    (off << 4));
17718 				break;
17719 			}
17720 			off = opt[IPOPT_OFFSET] - 1;
17721 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17722 			case IPOPT_TS_PRESPEC:
17723 			case IPOPT_TS_PRESPEC_RFC791:
17724 			case IPOPT_TS_TSANDADDR:
17725 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17726 				    IP_ADDR_LEN);
17727 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17728 				/* FALLTHRU */
17729 			case IPOPT_TS_TSONLY:
17730 				off = opt[IPOPT_OFFSET] - 1;
17731 				/* Compute # of milliseconds since midnight */
17732 				gethrestime(&now);
17733 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17734 				    now.tv_nsec / (NANOSEC / MILLISEC);
17735 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17736 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17737 				break;
17738 			}
17739 			break;
17740 		}
17741 	}
17742 	return (B_TRUE);
17743 
17744 bad_src_route:
17745 	q = WR(q);
17746 	if (q->q_next != NULL)
17747 		ill = q->q_ptr;
17748 	else
17749 		ill = NULL;
17750 
17751 	/* make sure we clear any indication of a hardware checksum */
17752 	DB_CKSUMFLAGS(mp) = 0;
17753 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17754 	if (zoneid == ALL_ZONES)
17755 		freemsg(mp);
17756 	else
17757 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17758 	return (B_FALSE);
17759 
17760 }
17761 
17762 /*
17763  * Process IP options in an inbound packet.  If an option affects the
17764  * effective destination address, return the next hop address via dstp.
17765  * Returns -1 if something fails in which case an ICMP error has been sent
17766  * and mp freed.
17767  */
17768 static int
17769 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17770     ip_stack_t *ipst)
17771 {
17772 	ipoptp_t	opts;
17773 	uchar_t		*opt;
17774 	uint8_t		optval;
17775 	uint8_t		optlen;
17776 	ipaddr_t	dst;
17777 	intptr_t	code = 0;
17778 	ire_t		*ire = NULL;
17779 	zoneid_t	zoneid;
17780 	ill_t		*ill;
17781 
17782 	ip2dbg(("ip_rput_options\n"));
17783 	dst = ipha->ipha_dst;
17784 	for (optval = ipoptp_first(&opts, ipha);
17785 	    optval != IPOPT_EOL;
17786 	    optval = ipoptp_next(&opts)) {
17787 		opt = opts.ipoptp_cur;
17788 		optlen = opts.ipoptp_len;
17789 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17790 		    optval, optlen));
17791 		/*
17792 		 * Note: we need to verify the checksum before we
17793 		 * modify anything thus this routine only extracts the next
17794 		 * hop dst from any source route.
17795 		 */
17796 		switch (optval) {
17797 			uint32_t off;
17798 		case IPOPT_SSRR:
17799 		case IPOPT_LSRR:
17800 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17801 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17802 			if (ire == NULL) {
17803 				if (optval == IPOPT_SSRR) {
17804 					ip1dbg(("ip_rput_options: not next"
17805 					    " strict source route 0x%x\n",
17806 					    ntohl(dst)));
17807 					code = (char *)&ipha->ipha_dst -
17808 					    (char *)ipha;
17809 					goto param_prob; /* RouterReq's */
17810 				}
17811 				ip2dbg(("ip_rput_options: "
17812 				    "not next source route 0x%x\n",
17813 				    ntohl(dst)));
17814 				break;
17815 			}
17816 			ire_refrele(ire);
17817 
17818 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17819 				ip1dbg((
17820 				    "ip_rput_options: bad option offset\n"));
17821 				code = (char *)&opt[IPOPT_OLEN] -
17822 				    (char *)ipha;
17823 				goto param_prob;
17824 			}
17825 			off = opt[IPOPT_OFFSET];
17826 			off--;
17827 		redo_srr:
17828 			if (optlen < IP_ADDR_LEN ||
17829 			    off > optlen - IP_ADDR_LEN) {
17830 				/* End of source route */
17831 				ip1dbg(("ip_rput_options: end of SR\n"));
17832 				break;
17833 			}
17834 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17835 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17836 			    ntohl(dst)));
17837 
17838 			/*
17839 			 * Check if our address is present more than
17840 			 * once as consecutive hops in source route.
17841 			 * XXX verify per-interface ip_forwarding
17842 			 * for source route?
17843 			 */
17844 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17845 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17846 
17847 			if (ire != NULL) {
17848 				ire_refrele(ire);
17849 				off += IP_ADDR_LEN;
17850 				goto redo_srr;
17851 			}
17852 
17853 			if (dst == htonl(INADDR_LOOPBACK)) {
17854 				ip1dbg(("ip_rput_options: loopback addr in "
17855 				    "source route!\n"));
17856 				goto bad_src_route;
17857 			}
17858 			/*
17859 			 * For strict: verify that dst is directly
17860 			 * reachable.
17861 			 */
17862 			if (optval == IPOPT_SSRR) {
17863 				ire = ire_ftable_lookup(dst, 0, 0,
17864 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17865 				    MBLK_GETLABEL(mp),
17866 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17867 				if (ire == NULL) {
17868 					ip1dbg(("ip_rput_options: SSRR not "
17869 					    "directly reachable: 0x%x\n",
17870 					    ntohl(dst)));
17871 					goto bad_src_route;
17872 				}
17873 				ire_refrele(ire);
17874 			}
17875 			/*
17876 			 * Defer update of the offset and the record route
17877 			 * until the packet is forwarded.
17878 			 */
17879 			break;
17880 		case IPOPT_RR:
17881 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17882 				ip1dbg((
17883 				    "ip_rput_options: bad option offset\n"));
17884 				code = (char *)&opt[IPOPT_OLEN] -
17885 				    (char *)ipha;
17886 				goto param_prob;
17887 			}
17888 			break;
17889 		case IPOPT_TS:
17890 			/*
17891 			 * Verify that length >= 5 and that there is either
17892 			 * room for another timestamp or that the overflow
17893 			 * counter is not maxed out.
17894 			 */
17895 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17896 			if (optlen < IPOPT_MINLEN_IT) {
17897 				goto param_prob;
17898 			}
17899 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17900 				ip1dbg((
17901 				    "ip_rput_options: bad option offset\n"));
17902 				code = (char *)&opt[IPOPT_OFFSET] -
17903 				    (char *)ipha;
17904 				goto param_prob;
17905 			}
17906 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17907 			case IPOPT_TS_TSONLY:
17908 				off = IPOPT_TS_TIMELEN;
17909 				break;
17910 			case IPOPT_TS_TSANDADDR:
17911 			case IPOPT_TS_PRESPEC:
17912 			case IPOPT_TS_PRESPEC_RFC791:
17913 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17914 				break;
17915 			default:
17916 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17917 				    (char *)ipha;
17918 				goto param_prob;
17919 			}
17920 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17921 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17922 				/*
17923 				 * No room and the overflow counter is 15
17924 				 * already.
17925 				 */
17926 				goto param_prob;
17927 			}
17928 			break;
17929 		}
17930 	}
17931 
17932 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17933 		*dstp = dst;
17934 		return (0);
17935 	}
17936 
17937 	ip1dbg(("ip_rput_options: error processing IP options."));
17938 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17939 
17940 param_prob:
17941 	q = WR(q);
17942 	if (q->q_next != NULL)
17943 		ill = q->q_ptr;
17944 	else
17945 		ill = NULL;
17946 
17947 	/* make sure we clear any indication of a hardware checksum */
17948 	DB_CKSUMFLAGS(mp) = 0;
17949 	/* Don't know whether this is for non-global or global/forwarding */
17950 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17951 	if (zoneid == ALL_ZONES)
17952 		freemsg(mp);
17953 	else
17954 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17955 	return (-1);
17956 
17957 bad_src_route:
17958 	q = WR(q);
17959 	if (q->q_next != NULL)
17960 		ill = q->q_ptr;
17961 	else
17962 		ill = NULL;
17963 
17964 	/* make sure we clear any indication of a hardware checksum */
17965 	DB_CKSUMFLAGS(mp) = 0;
17966 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17967 	if (zoneid == ALL_ZONES)
17968 		freemsg(mp);
17969 	else
17970 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17971 	return (-1);
17972 }
17973 
17974 /*
17975  * IP & ICMP info in >=14 msg's ...
17976  *  - ip fixed part (mib2_ip_t)
17977  *  - icmp fixed part (mib2_icmp_t)
17978  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17979  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17980  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17981  *  - ipRouteAttributeTable (ip 102)	labeled routes
17982  *  - ip multicast membership (ip_member_t)
17983  *  - ip multicast source filtering (ip_grpsrc_t)
17984  *  - igmp fixed part (struct igmpstat)
17985  *  - multicast routing stats (struct mrtstat)
17986  *  - multicast routing vifs (array of struct vifctl)
17987  *  - multicast routing routes (array of struct mfcctl)
17988  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17989  *					One per ill plus one generic
17990  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17991  *					One per ill plus one generic
17992  *  - ipv6RouteEntry			all IPv6 IREs
17993  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17994  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17995  *  - ipv6AddrEntry			all IPv6 ipifs
17996  *  - ipv6 multicast membership (ipv6_member_t)
17997  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17998  *
17999  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18000  *
18001  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18002  * already filled in by the caller.
18003  * Return value of 0 indicates that no messages were sent and caller
18004  * should free mpctl.
18005  */
18006 int
18007 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18008 {
18009 	ip_stack_t *ipst;
18010 	sctp_stack_t *sctps;
18011 
18012 
18013 	if (q->q_next != NULL) {
18014 		ipst = ILLQ_TO_IPST(q);
18015 	} else {
18016 		ipst = CONNQ_TO_IPST(q);
18017 	}
18018 	ASSERT(ipst != NULL);
18019 	sctps = ipst->ips_netstack->netstack_sctp;
18020 
18021 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18022 		return (0);
18023 	}
18024 
18025 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18026 	    ipst)) == NULL) {
18027 		return (1);
18028 	}
18029 
18030 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18031 		return (1);
18032 	}
18033 
18034 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18035 		return (1);
18036 	}
18037 
18038 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18039 		return (1);
18040 	}
18041 
18042 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18043 		return (1);
18044 	}
18045 
18046 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18047 		return (1);
18048 	}
18049 
18050 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18051 		return (1);
18052 	}
18053 
18054 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18055 		return (1);
18056 	}
18057 
18058 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18059 		return (1);
18060 	}
18061 
18062 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18063 		return (1);
18064 	}
18065 
18066 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18067 		return (1);
18068 	}
18069 
18070 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18071 		return (1);
18072 	}
18073 
18074 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18075 		return (1);
18076 	}
18077 
18078 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18079 		return (1);
18080 	}
18081 
18082 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18083 		return (1);
18084 	}
18085 
18086 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18087 	if (mpctl == NULL) {
18088 		return (1);
18089 	}
18090 
18091 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18092 		return (1);
18093 	}
18094 	freemsg(mpctl);
18095 	return (1);
18096 }
18097 
18098 
18099 /* Get global (legacy) IPv4 statistics */
18100 static mblk_t *
18101 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18102     ip_stack_t *ipst)
18103 {
18104 	mib2_ip_t		old_ip_mib;
18105 	struct opthdr		*optp;
18106 	mblk_t			*mp2ctl;
18107 
18108 	/*
18109 	 * make a copy of the original message
18110 	 */
18111 	mp2ctl = copymsg(mpctl);
18112 
18113 	/* fixed length IP structure... */
18114 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18115 	optp->level = MIB2_IP;
18116 	optp->name = 0;
18117 	SET_MIB(old_ip_mib.ipForwarding,
18118 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18119 	SET_MIB(old_ip_mib.ipDefaultTTL,
18120 	    (uint32_t)ipst->ips_ip_def_ttl);
18121 	SET_MIB(old_ip_mib.ipReasmTimeout,
18122 	    ipst->ips_ip_g_frag_timeout);
18123 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18124 	    sizeof (mib2_ipAddrEntry_t));
18125 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18126 	    sizeof (mib2_ipRouteEntry_t));
18127 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18128 	    sizeof (mib2_ipNetToMediaEntry_t));
18129 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18130 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18131 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18132 	    sizeof (mib2_ipAttributeEntry_t));
18133 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18134 
18135 	/*
18136 	 * Grab the statistics from the new IP MIB
18137 	 */
18138 	SET_MIB(old_ip_mib.ipInReceives,
18139 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18140 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18141 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18142 	SET_MIB(old_ip_mib.ipForwDatagrams,
18143 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18144 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18145 	    ipmib->ipIfStatsInUnknownProtos);
18146 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18147 	SET_MIB(old_ip_mib.ipInDelivers,
18148 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18149 	SET_MIB(old_ip_mib.ipOutRequests,
18150 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18151 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18152 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18153 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18154 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18155 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18156 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18157 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18158 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18159 
18160 	/* ipRoutingDiscards is not being used */
18161 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18162 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18163 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18164 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18165 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18166 	    ipmib->ipIfStatsReasmDuplicates);
18167 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18168 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18169 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18170 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18171 	SET_MIB(old_ip_mib.rawipInOverflows,
18172 	    ipmib->rawipIfStatsInOverflows);
18173 
18174 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18175 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18176 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18177 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18178 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18179 	    ipmib->ipIfStatsOutSwitchIPVersion);
18180 
18181 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18182 	    (int)sizeof (old_ip_mib))) {
18183 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18184 		    (uint_t)sizeof (old_ip_mib)));
18185 	}
18186 
18187 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18188 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18189 	    (int)optp->level, (int)optp->name, (int)optp->len));
18190 	qreply(q, mpctl);
18191 	return (mp2ctl);
18192 }
18193 
18194 /* Per interface IPv4 statistics */
18195 static mblk_t *
18196 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18197 {
18198 	struct opthdr		*optp;
18199 	mblk_t			*mp2ctl;
18200 	ill_t			*ill;
18201 	ill_walk_context_t	ctx;
18202 	mblk_t			*mp_tail = NULL;
18203 	mib2_ipIfStatsEntry_t	global_ip_mib;
18204 
18205 	/*
18206 	 * Make a copy of the original message
18207 	 */
18208 	mp2ctl = copymsg(mpctl);
18209 
18210 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18211 	optp->level = MIB2_IP;
18212 	optp->name = MIB2_IP_TRAFFIC_STATS;
18213 	/* Include "unknown interface" ip_mib */
18214 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18215 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18216 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18217 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18218 	    (ipst->ips_ip_g_forward ? 1 : 2));
18219 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18220 	    (uint32_t)ipst->ips_ip_def_ttl);
18221 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18222 	    sizeof (mib2_ipIfStatsEntry_t));
18223 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18224 	    sizeof (mib2_ipAddrEntry_t));
18225 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18226 	    sizeof (mib2_ipRouteEntry_t));
18227 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18228 	    sizeof (mib2_ipNetToMediaEntry_t));
18229 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18230 	    sizeof (ip_member_t));
18231 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18232 	    sizeof (ip_grpsrc_t));
18233 
18234 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18235 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18236 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18237 		    "failed to allocate %u bytes\n",
18238 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18239 	}
18240 
18241 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18242 
18243 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18244 	ill = ILL_START_WALK_V4(&ctx, ipst);
18245 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18246 		ill->ill_ip_mib->ipIfStatsIfIndex =
18247 		    ill->ill_phyint->phyint_ifindex;
18248 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18249 		    (ipst->ips_ip_g_forward ? 1 : 2));
18250 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18251 		    (uint32_t)ipst->ips_ip_def_ttl);
18252 
18253 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18254 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18255 		    (char *)ill->ill_ip_mib,
18256 		    (int)sizeof (*ill->ill_ip_mib))) {
18257 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18258 			    "failed to allocate %u bytes\n",
18259 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18260 		}
18261 	}
18262 	rw_exit(&ipst->ips_ill_g_lock);
18263 
18264 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18265 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18266 	    "level %d, name %d, len %d\n",
18267 	    (int)optp->level, (int)optp->name, (int)optp->len));
18268 	qreply(q, mpctl);
18269 
18270 	if (mp2ctl == NULL)
18271 		return (NULL);
18272 
18273 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18274 }
18275 
18276 /* Global IPv4 ICMP statistics */
18277 static mblk_t *
18278 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18279 {
18280 	struct opthdr		*optp;
18281 	mblk_t			*mp2ctl;
18282 
18283 	/*
18284 	 * Make a copy of the original message
18285 	 */
18286 	mp2ctl = copymsg(mpctl);
18287 
18288 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18289 	optp->level = MIB2_ICMP;
18290 	optp->name = 0;
18291 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18292 	    (int)sizeof (ipst->ips_icmp_mib))) {
18293 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18294 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18295 	}
18296 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18297 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18298 	    (int)optp->level, (int)optp->name, (int)optp->len));
18299 	qreply(q, mpctl);
18300 	return (mp2ctl);
18301 }
18302 
18303 /* Global IPv4 IGMP statistics */
18304 static mblk_t *
18305 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18306 {
18307 	struct opthdr		*optp;
18308 	mblk_t			*mp2ctl;
18309 
18310 	/*
18311 	 * make a copy of the original message
18312 	 */
18313 	mp2ctl = copymsg(mpctl);
18314 
18315 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18316 	optp->level = EXPER_IGMP;
18317 	optp->name = 0;
18318 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18319 	    (int)sizeof (ipst->ips_igmpstat))) {
18320 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18321 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18322 	}
18323 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18324 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18325 	    (int)optp->level, (int)optp->name, (int)optp->len));
18326 	qreply(q, mpctl);
18327 	return (mp2ctl);
18328 }
18329 
18330 /* Global IPv4 Multicast Routing statistics */
18331 static mblk_t *
18332 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18333 {
18334 	struct opthdr		*optp;
18335 	mblk_t			*mp2ctl;
18336 
18337 	/*
18338 	 * make a copy of the original message
18339 	 */
18340 	mp2ctl = copymsg(mpctl);
18341 
18342 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18343 	optp->level = EXPER_DVMRP;
18344 	optp->name = 0;
18345 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18346 		ip0dbg(("ip_mroute_stats: failed\n"));
18347 	}
18348 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18349 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18350 	    (int)optp->level, (int)optp->name, (int)optp->len));
18351 	qreply(q, mpctl);
18352 	return (mp2ctl);
18353 }
18354 
18355 /* IPv4 address information */
18356 static mblk_t *
18357 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18358 {
18359 	struct opthdr		*optp;
18360 	mblk_t			*mp2ctl;
18361 	mblk_t			*mp_tail = NULL;
18362 	ill_t			*ill;
18363 	ipif_t			*ipif;
18364 	uint_t			bitval;
18365 	mib2_ipAddrEntry_t	mae;
18366 	zoneid_t		zoneid;
18367 	ill_walk_context_t ctx;
18368 
18369 	/*
18370 	 * make a copy of the original message
18371 	 */
18372 	mp2ctl = copymsg(mpctl);
18373 
18374 	/* ipAddrEntryTable */
18375 
18376 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18377 	optp->level = MIB2_IP;
18378 	optp->name = MIB2_IP_ADDR;
18379 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18380 
18381 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18382 	ill = ILL_START_WALK_V4(&ctx, ipst);
18383 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18384 		for (ipif = ill->ill_ipif; ipif != NULL;
18385 		    ipif = ipif->ipif_next) {
18386 			if (ipif->ipif_zoneid != zoneid &&
18387 			    ipif->ipif_zoneid != ALL_ZONES)
18388 				continue;
18389 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18390 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18391 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18392 
18393 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18394 			    OCTET_LENGTH);
18395 			mae.ipAdEntIfIndex.o_length =
18396 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18397 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18398 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18399 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18400 			mae.ipAdEntInfo.ae_subnet_len =
18401 			    ip_mask_to_plen(ipif->ipif_net_mask);
18402 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18403 			for (bitval = 1;
18404 			    bitval &&
18405 			    !(bitval & ipif->ipif_brd_addr);
18406 			    bitval <<= 1)
18407 				noop;
18408 			mae.ipAdEntBcastAddr = bitval;
18409 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18410 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18411 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18412 			mae.ipAdEntInfo.ae_broadcast_addr =
18413 			    ipif->ipif_brd_addr;
18414 			mae.ipAdEntInfo.ae_pp_dst_addr =
18415 			    ipif->ipif_pp_dst_addr;
18416 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18417 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18418 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18419 
18420 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18421 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18422 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18423 				    "allocate %u bytes\n",
18424 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18425 			}
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_addr: level %d, name %d, len %d\n",
18432 	    (int)optp->level, (int)optp->name, (int)optp->len));
18433 	qreply(q, mpctl);
18434 	return (mp2ctl);
18435 }
18436 
18437 /* IPv6 address information */
18438 static mblk_t *
18439 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18440 {
18441 	struct opthdr		*optp;
18442 	mblk_t			*mp2ctl;
18443 	mblk_t			*mp_tail = NULL;
18444 	ill_t			*ill;
18445 	ipif_t			*ipif;
18446 	mib2_ipv6AddrEntry_t	mae6;
18447 	zoneid_t		zoneid;
18448 	ill_walk_context_t	ctx;
18449 
18450 	/*
18451 	 * make a copy of the original message
18452 	 */
18453 	mp2ctl = copymsg(mpctl);
18454 
18455 	/* ipv6AddrEntryTable */
18456 
18457 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18458 	optp->level = MIB2_IP6;
18459 	optp->name = MIB2_IP6_ADDR;
18460 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18461 
18462 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18463 	ill = ILL_START_WALK_V6(&ctx, ipst);
18464 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18465 		for (ipif = ill->ill_ipif; ipif != NULL;
18466 		    ipif = ipif->ipif_next) {
18467 			if (ipif->ipif_zoneid != zoneid &&
18468 			    ipif->ipif_zoneid != ALL_ZONES)
18469 				continue;
18470 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18471 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18472 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18473 
18474 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18475 			    OCTET_LENGTH);
18476 			mae6.ipv6AddrIfIndex.o_length =
18477 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18478 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18479 			mae6.ipv6AddrPfxLength =
18480 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18481 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18482 			mae6.ipv6AddrInfo.ae_subnet_len =
18483 			    mae6.ipv6AddrPfxLength;
18484 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18485 
18486 			/* Type: stateless(1), stateful(2), unknown(3) */
18487 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18488 				mae6.ipv6AddrType = 1;
18489 			else
18490 				mae6.ipv6AddrType = 2;
18491 			/* Anycast: true(1), false(2) */
18492 			if (ipif->ipif_flags & IPIF_ANYCAST)
18493 				mae6.ipv6AddrAnycastFlag = 1;
18494 			else
18495 				mae6.ipv6AddrAnycastFlag = 2;
18496 
18497 			/*
18498 			 * Address status: preferred(1), deprecated(2),
18499 			 * invalid(3), inaccessible(4), unknown(5)
18500 			 */
18501 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18502 				mae6.ipv6AddrStatus = 3;
18503 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18504 				mae6.ipv6AddrStatus = 2;
18505 			else
18506 				mae6.ipv6AddrStatus = 1;
18507 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18508 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18509 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18510 			    ipif->ipif_v6pp_dst_addr;
18511 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18512 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18513 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18514 			mae6.ipv6AddrIdentifier = ill->ill_token;
18515 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18516 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18517 			mae6.ipv6AddrRetransmitTime =
18518 			    ill->ill_reachable_retrans_time;
18519 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18520 			    (char *)&mae6,
18521 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18522 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18523 				    "allocate %u bytes\n",
18524 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18525 			}
18526 		}
18527 	}
18528 	rw_exit(&ipst->ips_ill_g_lock);
18529 
18530 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18531 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18532 	    (int)optp->level, (int)optp->name, (int)optp->len));
18533 	qreply(q, mpctl);
18534 	return (mp2ctl);
18535 }
18536 
18537 /* IPv4 multicast group membership. */
18538 static mblk_t *
18539 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18540 {
18541 	struct opthdr		*optp;
18542 	mblk_t			*mp2ctl;
18543 	ill_t			*ill;
18544 	ipif_t			*ipif;
18545 	ilm_t			*ilm;
18546 	ip_member_t		ipm;
18547 	mblk_t			*mp_tail = NULL;
18548 	ill_walk_context_t	ctx;
18549 	zoneid_t		zoneid;
18550 
18551 	/*
18552 	 * make a copy of the original message
18553 	 */
18554 	mp2ctl = copymsg(mpctl);
18555 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18556 
18557 	/* ipGroupMember table */
18558 	optp = (struct opthdr *)&mpctl->b_rptr[
18559 	    sizeof (struct T_optmgmt_ack)];
18560 	optp->level = MIB2_IP;
18561 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18562 
18563 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18564 	ill = ILL_START_WALK_V4(&ctx, ipst);
18565 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18566 		ILM_WALKER_HOLD(ill);
18567 		for (ipif = ill->ill_ipif; ipif != NULL;
18568 		    ipif = ipif->ipif_next) {
18569 			if (ipif->ipif_zoneid != zoneid &&
18570 			    ipif->ipif_zoneid != ALL_ZONES)
18571 				continue;	/* not this zone */
18572 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18573 			    OCTET_LENGTH);
18574 			ipm.ipGroupMemberIfIndex.o_length =
18575 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18576 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18577 				ASSERT(ilm->ilm_ipif != NULL);
18578 				ASSERT(ilm->ilm_ill == NULL);
18579 				if (ilm->ilm_ipif != ipif)
18580 					continue;
18581 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18582 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18583 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18584 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18585 				    (char *)&ipm, (int)sizeof (ipm))) {
18586 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18587 					    "failed to allocate %u bytes\n",
18588 					    (uint_t)sizeof (ipm)));
18589 				}
18590 			}
18591 		}
18592 		ILM_WALKER_RELE(ill);
18593 	}
18594 	rw_exit(&ipst->ips_ill_g_lock);
18595 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18596 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18597 	    (int)optp->level, (int)optp->name, (int)optp->len));
18598 	qreply(q, mpctl);
18599 	return (mp2ctl);
18600 }
18601 
18602 /* IPv6 multicast group membership. */
18603 static mblk_t *
18604 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18605 {
18606 	struct opthdr		*optp;
18607 	mblk_t			*mp2ctl;
18608 	ill_t			*ill;
18609 	ilm_t			*ilm;
18610 	ipv6_member_t		ipm6;
18611 	mblk_t			*mp_tail = NULL;
18612 	ill_walk_context_t	ctx;
18613 	zoneid_t		zoneid;
18614 
18615 	/*
18616 	 * make a copy of the original message
18617 	 */
18618 	mp2ctl = copymsg(mpctl);
18619 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18620 
18621 	/* ip6GroupMember table */
18622 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18623 	optp->level = MIB2_IP6;
18624 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18625 
18626 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18627 	ill = ILL_START_WALK_V6(&ctx, ipst);
18628 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18629 		ILM_WALKER_HOLD(ill);
18630 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18631 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18632 			ASSERT(ilm->ilm_ipif == NULL);
18633 			ASSERT(ilm->ilm_ill != NULL);
18634 			if (ilm->ilm_zoneid != zoneid)
18635 				continue;	/* not this zone */
18636 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18637 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18638 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18639 			if (!snmp_append_data2(mpctl->b_cont,
18640 			    &mp_tail,
18641 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18642 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18643 				    "failed to allocate %u bytes\n",
18644 				    (uint_t)sizeof (ipm6)));
18645 			}
18646 		}
18647 		ILM_WALKER_RELE(ill);
18648 	}
18649 	rw_exit(&ipst->ips_ill_g_lock);
18650 
18651 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18652 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18653 	    (int)optp->level, (int)optp->name, (int)optp->len));
18654 	qreply(q, mpctl);
18655 	return (mp2ctl);
18656 }
18657 
18658 /* IP multicast filtered sources */
18659 static mblk_t *
18660 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18661 {
18662 	struct opthdr		*optp;
18663 	mblk_t			*mp2ctl;
18664 	ill_t			*ill;
18665 	ipif_t			*ipif;
18666 	ilm_t			*ilm;
18667 	ip_grpsrc_t		ips;
18668 	mblk_t			*mp_tail = NULL;
18669 	ill_walk_context_t	ctx;
18670 	zoneid_t		zoneid;
18671 	int			i;
18672 	slist_t			*sl;
18673 
18674 	/*
18675 	 * make a copy of the original message
18676 	 */
18677 	mp2ctl = copymsg(mpctl);
18678 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18679 
18680 	/* ipGroupSource table */
18681 	optp = (struct opthdr *)&mpctl->b_rptr[
18682 	    sizeof (struct T_optmgmt_ack)];
18683 	optp->level = MIB2_IP;
18684 	optp->name = EXPER_IP_GROUP_SOURCES;
18685 
18686 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18687 	ill = ILL_START_WALK_V4(&ctx, ipst);
18688 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18689 		ILM_WALKER_HOLD(ill);
18690 		for (ipif = ill->ill_ipif; ipif != NULL;
18691 		    ipif = ipif->ipif_next) {
18692 			if (ipif->ipif_zoneid != zoneid)
18693 				continue;	/* not this zone */
18694 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18695 			    OCTET_LENGTH);
18696 			ips.ipGroupSourceIfIndex.o_length =
18697 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18698 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18699 				ASSERT(ilm->ilm_ipif != NULL);
18700 				ASSERT(ilm->ilm_ill == NULL);
18701 				sl = ilm->ilm_filter;
18702 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18703 					continue;
18704 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18705 				for (i = 0; i < sl->sl_numsrc; i++) {
18706 					if (!IN6_IS_ADDR_V4MAPPED(
18707 					    &sl->sl_addr[i]))
18708 						continue;
18709 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18710 					    ips.ipGroupSourceAddress);
18711 					if (snmp_append_data2(mpctl->b_cont,
18712 					    &mp_tail, (char *)&ips,
18713 					    (int)sizeof (ips)) == 0) {
18714 						ip1dbg(("ip_snmp_get_mib2_"
18715 						    "ip_group_src: failed to "
18716 						    "allocate %u bytes\n",
18717 						    (uint_t)sizeof (ips)));
18718 					}
18719 				}
18720 			}
18721 		}
18722 		ILM_WALKER_RELE(ill);
18723 	}
18724 	rw_exit(&ipst->ips_ill_g_lock);
18725 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18726 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18727 	    (int)optp->level, (int)optp->name, (int)optp->len));
18728 	qreply(q, mpctl);
18729 	return (mp2ctl);
18730 }
18731 
18732 /* IPv6 multicast filtered sources. */
18733 static mblk_t *
18734 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18735 {
18736 	struct opthdr		*optp;
18737 	mblk_t			*mp2ctl;
18738 	ill_t			*ill;
18739 	ilm_t			*ilm;
18740 	ipv6_grpsrc_t		ips6;
18741 	mblk_t			*mp_tail = NULL;
18742 	ill_walk_context_t	ctx;
18743 	zoneid_t		zoneid;
18744 	int			i;
18745 	slist_t			*sl;
18746 
18747 	/*
18748 	 * make a copy of the original message
18749 	 */
18750 	mp2ctl = copymsg(mpctl);
18751 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18752 
18753 	/* ip6GroupMember table */
18754 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18755 	optp->level = MIB2_IP6;
18756 	optp->name = EXPER_IP6_GROUP_SOURCES;
18757 
18758 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18759 	ill = ILL_START_WALK_V6(&ctx, ipst);
18760 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18761 		ILM_WALKER_HOLD(ill);
18762 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18763 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18764 			ASSERT(ilm->ilm_ipif == NULL);
18765 			ASSERT(ilm->ilm_ill != NULL);
18766 			sl = ilm->ilm_filter;
18767 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18768 				continue;
18769 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18770 			for (i = 0; i < sl->sl_numsrc; i++) {
18771 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18772 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18773 				    (char *)&ips6, (int)sizeof (ips6))) {
18774 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18775 					    "group_src: failed to allocate "
18776 					    "%u bytes\n",
18777 					    (uint_t)sizeof (ips6)));
18778 				}
18779 			}
18780 		}
18781 		ILM_WALKER_RELE(ill);
18782 	}
18783 	rw_exit(&ipst->ips_ill_g_lock);
18784 
18785 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18786 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18787 	    (int)optp->level, (int)optp->name, (int)optp->len));
18788 	qreply(q, mpctl);
18789 	return (mp2ctl);
18790 }
18791 
18792 /* Multicast routing virtual interface table. */
18793 static mblk_t *
18794 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18795 {
18796 	struct opthdr		*optp;
18797 	mblk_t			*mp2ctl;
18798 
18799 	/*
18800 	 * make a copy of the original message
18801 	 */
18802 	mp2ctl = copymsg(mpctl);
18803 
18804 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18805 	optp->level = EXPER_DVMRP;
18806 	optp->name = EXPER_DVMRP_VIF;
18807 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18808 		ip0dbg(("ip_mroute_vif: failed\n"));
18809 	}
18810 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18811 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18812 	    (int)optp->level, (int)optp->name, (int)optp->len));
18813 	qreply(q, mpctl);
18814 	return (mp2ctl);
18815 }
18816 
18817 /* Multicast routing table. */
18818 static mblk_t *
18819 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18820 {
18821 	struct opthdr		*optp;
18822 	mblk_t			*mp2ctl;
18823 
18824 	/*
18825 	 * make a copy of the original message
18826 	 */
18827 	mp2ctl = copymsg(mpctl);
18828 
18829 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18830 	optp->level = EXPER_DVMRP;
18831 	optp->name = EXPER_DVMRP_MRT;
18832 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18833 		ip0dbg(("ip_mroute_mrt: failed\n"));
18834 	}
18835 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18836 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18837 	    (int)optp->level, (int)optp->name, (int)optp->len));
18838 	qreply(q, mpctl);
18839 	return (mp2ctl);
18840 }
18841 
18842 /*
18843  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18844  * in one IRE walk.
18845  */
18846 static mblk_t *
18847 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18848 {
18849 	struct opthdr	*optp;
18850 	mblk_t		*mp2ctl;	/* Returned */
18851 	mblk_t		*mp3ctl;	/* nettomedia */
18852 	mblk_t		*mp4ctl;	/* routeattrs */
18853 	iproutedata_t	ird;
18854 	zoneid_t	zoneid;
18855 
18856 	/*
18857 	 * make copies of the original message
18858 	 *	- mp2ctl is returned unchanged to the caller for his use
18859 	 *	- mpctl is sent upstream as ipRouteEntryTable
18860 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18861 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18862 	 */
18863 	mp2ctl = copymsg(mpctl);
18864 	mp3ctl = copymsg(mpctl);
18865 	mp4ctl = copymsg(mpctl);
18866 	if (mp3ctl == NULL || mp4ctl == NULL) {
18867 		freemsg(mp4ctl);
18868 		freemsg(mp3ctl);
18869 		freemsg(mp2ctl);
18870 		freemsg(mpctl);
18871 		return (NULL);
18872 	}
18873 
18874 	bzero(&ird, sizeof (ird));
18875 
18876 	ird.ird_route.lp_head = mpctl->b_cont;
18877 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18878 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18879 
18880 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18881 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18882 
18883 	/* ipRouteEntryTable in mpctl */
18884 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18885 	optp->level = MIB2_IP;
18886 	optp->name = MIB2_IP_ROUTE;
18887 	optp->len = msgdsize(ird.ird_route.lp_head);
18888 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18889 	    (int)optp->level, (int)optp->name, (int)optp->len));
18890 	qreply(q, mpctl);
18891 
18892 	/* ipNetToMediaEntryTable in mp3ctl */
18893 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18894 	optp->level = MIB2_IP;
18895 	optp->name = MIB2_IP_MEDIA;
18896 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18897 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18898 	    (int)optp->level, (int)optp->name, (int)optp->len));
18899 	qreply(q, mp3ctl);
18900 
18901 	/* ipRouteAttributeTable in mp4ctl */
18902 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18903 	optp->level = MIB2_IP;
18904 	optp->name = EXPER_IP_RTATTR;
18905 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18906 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18907 	    (int)optp->level, (int)optp->name, (int)optp->len));
18908 	if (optp->len == 0)
18909 		freemsg(mp4ctl);
18910 	else
18911 		qreply(q, mp4ctl);
18912 
18913 	return (mp2ctl);
18914 }
18915 
18916 /*
18917  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18918  * ipv6NetToMediaEntryTable in an NDP walk.
18919  */
18920 static mblk_t *
18921 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18922 {
18923 	struct opthdr	*optp;
18924 	mblk_t		*mp2ctl;	/* Returned */
18925 	mblk_t		*mp3ctl;	/* nettomedia */
18926 	mblk_t		*mp4ctl;	/* routeattrs */
18927 	iproutedata_t	ird;
18928 	zoneid_t	zoneid;
18929 
18930 	/*
18931 	 * make copies of the original message
18932 	 *	- mp2ctl is returned unchanged to the caller for his use
18933 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18934 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18935 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18936 	 */
18937 	mp2ctl = copymsg(mpctl);
18938 	mp3ctl = copymsg(mpctl);
18939 	mp4ctl = copymsg(mpctl);
18940 	if (mp3ctl == NULL || mp4ctl == NULL) {
18941 		freemsg(mp4ctl);
18942 		freemsg(mp3ctl);
18943 		freemsg(mp2ctl);
18944 		freemsg(mpctl);
18945 		return (NULL);
18946 	}
18947 
18948 	bzero(&ird, sizeof (ird));
18949 
18950 	ird.ird_route.lp_head = mpctl->b_cont;
18951 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18952 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18953 
18954 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18955 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18956 
18957 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18958 	optp->level = MIB2_IP6;
18959 	optp->name = MIB2_IP6_ROUTE;
18960 	optp->len = msgdsize(ird.ird_route.lp_head);
18961 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18962 	    (int)optp->level, (int)optp->name, (int)optp->len));
18963 	qreply(q, mpctl);
18964 
18965 	/* ipv6NetToMediaEntryTable in mp3ctl */
18966 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18967 
18968 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18969 	optp->level = MIB2_IP6;
18970 	optp->name = MIB2_IP6_MEDIA;
18971 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18972 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18973 	    (int)optp->level, (int)optp->name, (int)optp->len));
18974 	qreply(q, mp3ctl);
18975 
18976 	/* ipv6RouteAttributeTable in mp4ctl */
18977 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18978 	optp->level = MIB2_IP6;
18979 	optp->name = EXPER_IP_RTATTR;
18980 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18981 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18982 	    (int)optp->level, (int)optp->name, (int)optp->len));
18983 	if (optp->len == 0)
18984 		freemsg(mp4ctl);
18985 	else
18986 		qreply(q, mp4ctl);
18987 
18988 	return (mp2ctl);
18989 }
18990 
18991 /*
18992  * IPv6 mib: One per ill
18993  */
18994 static mblk_t *
18995 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18996 {
18997 	struct opthdr		*optp;
18998 	mblk_t			*mp2ctl;
18999 	ill_t			*ill;
19000 	ill_walk_context_t	ctx;
19001 	mblk_t			*mp_tail = NULL;
19002 
19003 	/*
19004 	 * Make a copy of the original message
19005 	 */
19006 	mp2ctl = copymsg(mpctl);
19007 
19008 	/* fixed length IPv6 structure ... */
19009 
19010 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19011 	optp->level = MIB2_IP6;
19012 	optp->name = 0;
19013 	/* Include "unknown interface" ip6_mib */
19014 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19015 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19016 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19017 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19018 	    ipst->ips_ipv6_forward ? 1 : 2);
19019 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19020 	    ipst->ips_ipv6_def_hops);
19021 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19022 	    sizeof (mib2_ipIfStatsEntry_t));
19023 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19024 	    sizeof (mib2_ipv6AddrEntry_t));
19025 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19026 	    sizeof (mib2_ipv6RouteEntry_t));
19027 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19028 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19029 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19030 	    sizeof (ipv6_member_t));
19031 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19032 	    sizeof (ipv6_grpsrc_t));
19033 
19034 	/*
19035 	 * Synchronize 64- and 32-bit counters
19036 	 */
19037 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19038 	    ipIfStatsHCInReceives);
19039 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19040 	    ipIfStatsHCInDelivers);
19041 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19042 	    ipIfStatsHCOutRequests);
19043 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19044 	    ipIfStatsHCOutForwDatagrams);
19045 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19046 	    ipIfStatsHCOutMcastPkts);
19047 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19048 	    ipIfStatsHCInMcastPkts);
19049 
19050 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19051 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19052 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19053 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19054 	}
19055 
19056 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19057 	ill = ILL_START_WALK_V6(&ctx, ipst);
19058 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19059 		ill->ill_ip_mib->ipIfStatsIfIndex =
19060 		    ill->ill_phyint->phyint_ifindex;
19061 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19062 		    ipst->ips_ipv6_forward ? 1 : 2);
19063 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19064 		    ill->ill_max_hops);
19065 
19066 		/*
19067 		 * Synchronize 64- and 32-bit counters
19068 		 */
19069 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19070 		    ipIfStatsHCInReceives);
19071 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19072 		    ipIfStatsHCInDelivers);
19073 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19074 		    ipIfStatsHCOutRequests);
19075 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19076 		    ipIfStatsHCOutForwDatagrams);
19077 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19078 		    ipIfStatsHCOutMcastPkts);
19079 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19080 		    ipIfStatsHCInMcastPkts);
19081 
19082 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19083 		    (char *)ill->ill_ip_mib,
19084 		    (int)sizeof (*ill->ill_ip_mib))) {
19085 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19086 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19087 		}
19088 	}
19089 	rw_exit(&ipst->ips_ill_g_lock);
19090 
19091 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19092 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19093 	    (int)optp->level, (int)optp->name, (int)optp->len));
19094 	qreply(q, mpctl);
19095 	return (mp2ctl);
19096 }
19097 
19098 /*
19099  * ICMPv6 mib: One per ill
19100  */
19101 static mblk_t *
19102 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19103 {
19104 	struct opthdr		*optp;
19105 	mblk_t			*mp2ctl;
19106 	ill_t			*ill;
19107 	ill_walk_context_t	ctx;
19108 	mblk_t			*mp_tail = NULL;
19109 	/*
19110 	 * Make a copy of the original message
19111 	 */
19112 	mp2ctl = copymsg(mpctl);
19113 
19114 	/* fixed length ICMPv6 structure ... */
19115 
19116 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19117 	optp->level = MIB2_ICMP6;
19118 	optp->name = 0;
19119 	/* Include "unknown interface" icmp6_mib */
19120 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19121 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19122 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19123 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19124 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19125 	    (char *)&ipst->ips_icmp6_mib,
19126 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19127 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19128 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19129 	}
19130 
19131 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19132 	ill = ILL_START_WALK_V6(&ctx, ipst);
19133 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19134 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19135 		    ill->ill_phyint->phyint_ifindex;
19136 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19137 		    (char *)ill->ill_icmp6_mib,
19138 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19139 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19140 			    "%u bytes\n",
19141 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19142 		}
19143 	}
19144 	rw_exit(&ipst->ips_ill_g_lock);
19145 
19146 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19147 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19148 	    (int)optp->level, (int)optp->name, (int)optp->len));
19149 	qreply(q, mpctl);
19150 	return (mp2ctl);
19151 }
19152 
19153 /*
19154  * ire_walk routine to create both ipRouteEntryTable and
19155  * ipRouteAttributeTable in one IRE walk
19156  */
19157 static void
19158 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19159 {
19160 	ill_t				*ill;
19161 	ipif_t				*ipif;
19162 	mib2_ipRouteEntry_t		*re;
19163 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19164 	ipaddr_t			gw_addr;
19165 	tsol_ire_gw_secattr_t		*attrp;
19166 	tsol_gc_t			*gc = NULL;
19167 	tsol_gcgrp_t			*gcgrp = NULL;
19168 	uint_t				sacnt = 0;
19169 	int				i;
19170 
19171 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19172 
19173 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19174 		return;
19175 
19176 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19177 		mutex_enter(&attrp->igsa_lock);
19178 		if ((gc = attrp->igsa_gc) != NULL) {
19179 			gcgrp = gc->gc_grp;
19180 			ASSERT(gcgrp != NULL);
19181 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19182 			sacnt = 1;
19183 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19184 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19185 			gc = gcgrp->gcgrp_head;
19186 			sacnt = gcgrp->gcgrp_count;
19187 		}
19188 		mutex_exit(&attrp->igsa_lock);
19189 
19190 		/* do nothing if there's no gc to report */
19191 		if (gc == NULL) {
19192 			ASSERT(sacnt == 0);
19193 			if (gcgrp != NULL) {
19194 				/* we might as well drop the lock now */
19195 				rw_exit(&gcgrp->gcgrp_rwlock);
19196 				gcgrp = NULL;
19197 			}
19198 			attrp = NULL;
19199 		}
19200 
19201 		ASSERT(gc == NULL || (gcgrp != NULL &&
19202 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19203 	}
19204 	ASSERT(sacnt == 0 || gc != NULL);
19205 
19206 	if (sacnt != 0 &&
19207 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19208 		kmem_free(re, sizeof (*re));
19209 		rw_exit(&gcgrp->gcgrp_rwlock);
19210 		return;
19211 	}
19212 
19213 	/*
19214 	 * Return all IRE types for route table... let caller pick and choose
19215 	 */
19216 	re->ipRouteDest = ire->ire_addr;
19217 	ipif = ire->ire_ipif;
19218 	re->ipRouteIfIndex.o_length = 0;
19219 	if (ire->ire_type == IRE_CACHE) {
19220 		ill = (ill_t *)ire->ire_stq->q_ptr;
19221 		re->ipRouteIfIndex.o_length =
19222 		    ill->ill_name_length == 0 ? 0 :
19223 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19224 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19225 		    re->ipRouteIfIndex.o_length);
19226 	} else if (ipif != NULL) {
19227 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19228 		re->ipRouteIfIndex.o_length =
19229 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19230 	}
19231 	re->ipRouteMetric1 = -1;
19232 	re->ipRouteMetric2 = -1;
19233 	re->ipRouteMetric3 = -1;
19234 	re->ipRouteMetric4 = -1;
19235 
19236 	gw_addr = ire->ire_gateway_addr;
19237 
19238 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19239 		re->ipRouteNextHop = ire->ire_src_addr;
19240 	else
19241 		re->ipRouteNextHop = gw_addr;
19242 	/* indirect(4), direct(3), or invalid(2) */
19243 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19244 		re->ipRouteType = 2;
19245 	else
19246 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19247 	re->ipRouteProto = -1;
19248 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19249 	re->ipRouteMask = ire->ire_mask;
19250 	re->ipRouteMetric5 = -1;
19251 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19252 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19253 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19254 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19255 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19256 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19257 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19258 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19259 
19260 	if (ire->ire_flags & RTF_DYNAMIC) {
19261 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19262 	} else {
19263 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19264 	}
19265 
19266 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19267 	    (char *)re, (int)sizeof (*re))) {
19268 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19269 		    (uint_t)sizeof (*re)));
19270 	}
19271 
19272 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19273 		iaeptr->iae_routeidx = ird->ird_idx;
19274 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19275 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19276 	}
19277 
19278 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19279 	    (char *)iae, sacnt * sizeof (*iae))) {
19280 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19281 		    (unsigned)(sacnt * sizeof (*iae))));
19282 	}
19283 
19284 	/* bump route index for next pass */
19285 	ird->ird_idx++;
19286 
19287 	kmem_free(re, sizeof (*re));
19288 	if (sacnt != 0)
19289 		kmem_free(iae, sacnt * sizeof (*iae));
19290 
19291 	if (gcgrp != NULL)
19292 		rw_exit(&gcgrp->gcgrp_rwlock);
19293 }
19294 
19295 /*
19296  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19297  */
19298 static void
19299 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19300 {
19301 	ill_t				*ill;
19302 	ipif_t				*ipif;
19303 	mib2_ipv6RouteEntry_t		*re;
19304 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19305 	in6_addr_t			gw_addr_v6;
19306 	tsol_ire_gw_secattr_t		*attrp;
19307 	tsol_gc_t			*gc = NULL;
19308 	tsol_gcgrp_t			*gcgrp = NULL;
19309 	uint_t				sacnt = 0;
19310 	int				i;
19311 
19312 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19313 
19314 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19315 		return;
19316 
19317 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19318 		mutex_enter(&attrp->igsa_lock);
19319 		if ((gc = attrp->igsa_gc) != NULL) {
19320 			gcgrp = gc->gc_grp;
19321 			ASSERT(gcgrp != NULL);
19322 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19323 			sacnt = 1;
19324 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19325 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19326 			gc = gcgrp->gcgrp_head;
19327 			sacnt = gcgrp->gcgrp_count;
19328 		}
19329 		mutex_exit(&attrp->igsa_lock);
19330 
19331 		/* do nothing if there's no gc to report */
19332 		if (gc == NULL) {
19333 			ASSERT(sacnt == 0);
19334 			if (gcgrp != NULL) {
19335 				/* we might as well drop the lock now */
19336 				rw_exit(&gcgrp->gcgrp_rwlock);
19337 				gcgrp = NULL;
19338 			}
19339 			attrp = NULL;
19340 		}
19341 
19342 		ASSERT(gc == NULL || (gcgrp != NULL &&
19343 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19344 	}
19345 	ASSERT(sacnt == 0 || gc != NULL);
19346 
19347 	if (sacnt != 0 &&
19348 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19349 		kmem_free(re, sizeof (*re));
19350 		rw_exit(&gcgrp->gcgrp_rwlock);
19351 		return;
19352 	}
19353 
19354 	/*
19355 	 * Return all IRE types for route table... let caller pick and choose
19356 	 */
19357 	re->ipv6RouteDest = ire->ire_addr_v6;
19358 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19359 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19360 	re->ipv6RouteIfIndex.o_length = 0;
19361 	ipif = ire->ire_ipif;
19362 	if (ire->ire_type == IRE_CACHE) {
19363 		ill = (ill_t *)ire->ire_stq->q_ptr;
19364 		re->ipv6RouteIfIndex.o_length =
19365 		    ill->ill_name_length == 0 ? 0 :
19366 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19367 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19368 		    re->ipv6RouteIfIndex.o_length);
19369 	} else if (ipif != NULL) {
19370 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19371 		re->ipv6RouteIfIndex.o_length =
19372 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19373 	}
19374 
19375 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19376 
19377 	mutex_enter(&ire->ire_lock);
19378 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19379 	mutex_exit(&ire->ire_lock);
19380 
19381 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19382 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19383 	else
19384 		re->ipv6RouteNextHop = gw_addr_v6;
19385 
19386 	/* remote(4), local(3), or discard(2) */
19387 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19388 		re->ipv6RouteType = 2;
19389 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19390 		re->ipv6RouteType = 3;
19391 	else
19392 		re->ipv6RouteType = 4;
19393 
19394 	re->ipv6RouteProtocol	= -1;
19395 	re->ipv6RoutePolicy	= 0;
19396 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19397 	re->ipv6RouteNextHopRDI	= 0;
19398 	re->ipv6RouteWeight	= 0;
19399 	re->ipv6RouteMetric	= 0;
19400 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19401 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19402 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19403 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19404 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19405 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19406 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19407 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19408 
19409 	if (ire->ire_flags & RTF_DYNAMIC) {
19410 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19411 	} else {
19412 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19413 	}
19414 
19415 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19416 	    (char *)re, (int)sizeof (*re))) {
19417 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19418 		    (uint_t)sizeof (*re)));
19419 	}
19420 
19421 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19422 		iaeptr->iae_routeidx = ird->ird_idx;
19423 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19424 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19425 	}
19426 
19427 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19428 	    (char *)iae, sacnt * sizeof (*iae))) {
19429 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19430 		    (unsigned)(sacnt * sizeof (*iae))));
19431 	}
19432 
19433 	/* bump route index for next pass */
19434 	ird->ird_idx++;
19435 
19436 	kmem_free(re, sizeof (*re));
19437 	if (sacnt != 0)
19438 		kmem_free(iae, sacnt * sizeof (*iae));
19439 
19440 	if (gcgrp != NULL)
19441 		rw_exit(&gcgrp->gcgrp_rwlock);
19442 }
19443 
19444 /*
19445  * ndp_walk routine to create ipv6NetToMediaEntryTable
19446  */
19447 static int
19448 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19449 {
19450 	ill_t				*ill;
19451 	mib2_ipv6NetToMediaEntry_t	ntme;
19452 	dl_unitdata_req_t		*dl;
19453 
19454 	ill = nce->nce_ill;
19455 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19456 		return (0);
19457 
19458 	/*
19459 	 * Neighbor cache entry attached to IRE with on-link
19460 	 * destination.
19461 	 */
19462 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19463 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19464 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19465 	    (nce->nce_res_mp != NULL)) {
19466 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19467 		ntme.ipv6NetToMediaPhysAddress.o_length =
19468 		    dl->dl_dest_addr_length;
19469 	} else {
19470 		ntme.ipv6NetToMediaPhysAddress.o_length =
19471 		    ill->ill_phys_addr_length;
19472 	}
19473 	if (nce->nce_res_mp != NULL) {
19474 		bcopy((char *)nce->nce_res_mp->b_rptr +
19475 		    NCE_LL_ADDR_OFFSET(ill),
19476 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19477 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19478 	} else {
19479 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19480 		    ill->ill_phys_addr_length);
19481 	}
19482 	/*
19483 	 * Note: Returns ND_* states. Should be:
19484 	 * reachable(1), stale(2), delay(3), probe(4),
19485 	 * invalid(5), unknown(6)
19486 	 */
19487 	ntme.ipv6NetToMediaState = nce->nce_state;
19488 	ntme.ipv6NetToMediaLastUpdated = 0;
19489 
19490 	/* other(1), dynamic(2), static(3), local(4) */
19491 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19492 		ntme.ipv6NetToMediaType = 4;
19493 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19494 		ntme.ipv6NetToMediaType = 1;
19495 	} else {
19496 		ntme.ipv6NetToMediaType = 2;
19497 	}
19498 
19499 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19500 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19501 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19502 		    (uint_t)sizeof (ntme)));
19503 	}
19504 	return (0);
19505 }
19506 
19507 /*
19508  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19509  */
19510 /* ARGSUSED */
19511 int
19512 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19513 {
19514 	switch (level) {
19515 	case MIB2_IP:
19516 	case MIB2_ICMP:
19517 		switch (name) {
19518 		default:
19519 			break;
19520 		}
19521 		return (1);
19522 	default:
19523 		return (1);
19524 	}
19525 }
19526 
19527 /*
19528  * When there exists both a 64- and 32-bit counter of a particular type
19529  * (i.e., InReceives), only the 64-bit counters are added.
19530  */
19531 void
19532 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19533 {
19534 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19535 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19536 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19537 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19538 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19539 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19540 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19541 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19542 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19543 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19544 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19545 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19546 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19547 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19548 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19549 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19550 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19551 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19552 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19553 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19554 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19555 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19556 	    o2->ipIfStatsInWrongIPVersion);
19557 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19558 	    o2->ipIfStatsInWrongIPVersion);
19559 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19560 	    o2->ipIfStatsOutSwitchIPVersion);
19561 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19562 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19563 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19564 	    o2->ipIfStatsHCInForwDatagrams);
19565 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19566 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19567 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19568 	    o2->ipIfStatsHCOutForwDatagrams);
19569 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19570 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19571 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19572 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19573 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19574 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19575 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19576 	    o2->ipIfStatsHCOutMcastOctets);
19577 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19578 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19579 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19580 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19581 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19582 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19583 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19584 }
19585 
19586 void
19587 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19588 {
19589 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19590 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19591 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19592 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19593 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19594 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19595 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19596 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19597 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19598 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19599 	    o2->ipv6IfIcmpInRouterSolicits);
19600 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19601 	    o2->ipv6IfIcmpInRouterAdvertisements);
19602 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19603 	    o2->ipv6IfIcmpInNeighborSolicits);
19604 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19605 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19606 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19607 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19608 	    o2->ipv6IfIcmpInGroupMembQueries);
19609 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19610 	    o2->ipv6IfIcmpInGroupMembResponses);
19611 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19612 	    o2->ipv6IfIcmpInGroupMembReductions);
19613 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19614 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19615 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19616 	    o2->ipv6IfIcmpOutDestUnreachs);
19617 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19618 	    o2->ipv6IfIcmpOutAdminProhibs);
19619 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19620 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19621 	    o2->ipv6IfIcmpOutParmProblems);
19622 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19623 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19624 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19625 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19626 	    o2->ipv6IfIcmpOutRouterSolicits);
19627 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19628 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19629 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19630 	    o2->ipv6IfIcmpOutNeighborSolicits);
19631 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19632 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19633 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19634 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19635 	    o2->ipv6IfIcmpOutGroupMembQueries);
19636 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19637 	    o2->ipv6IfIcmpOutGroupMembResponses);
19638 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19639 	    o2->ipv6IfIcmpOutGroupMembReductions);
19640 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19641 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19642 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19643 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19644 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19645 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19646 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19647 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19648 	    o2->ipv6IfIcmpInGroupMembTotal);
19649 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19650 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19651 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19652 	    o2->ipv6IfIcmpInGroupMembBadReports);
19653 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19654 	    o2->ipv6IfIcmpInGroupMembOurReports);
19655 }
19656 
19657 /*
19658  * Called before the options are updated to check if this packet will
19659  * be source routed from here.
19660  * This routine assumes that the options are well formed i.e. that they
19661  * have already been checked.
19662  */
19663 static boolean_t
19664 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19665 {
19666 	ipoptp_t	opts;
19667 	uchar_t		*opt;
19668 	uint8_t		optval;
19669 	uint8_t		optlen;
19670 	ipaddr_t	dst;
19671 	ire_t		*ire;
19672 
19673 	if (IS_SIMPLE_IPH(ipha)) {
19674 		ip2dbg(("not source routed\n"));
19675 		return (B_FALSE);
19676 	}
19677 	dst = ipha->ipha_dst;
19678 	for (optval = ipoptp_first(&opts, ipha);
19679 	    optval != IPOPT_EOL;
19680 	    optval = ipoptp_next(&opts)) {
19681 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19682 		opt = opts.ipoptp_cur;
19683 		optlen = opts.ipoptp_len;
19684 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19685 		    optval, optlen));
19686 		switch (optval) {
19687 			uint32_t off;
19688 		case IPOPT_SSRR:
19689 		case IPOPT_LSRR:
19690 			/*
19691 			 * If dst is one of our addresses and there are some
19692 			 * entries left in the source route return (true).
19693 			 */
19694 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19695 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19696 			if (ire == NULL) {
19697 				ip2dbg(("ip_source_routed: not next"
19698 				    " source route 0x%x\n",
19699 				    ntohl(dst)));
19700 				return (B_FALSE);
19701 			}
19702 			ire_refrele(ire);
19703 			off = opt[IPOPT_OFFSET];
19704 			off--;
19705 			if (optlen < IP_ADDR_LEN ||
19706 			    off > optlen - IP_ADDR_LEN) {
19707 				/* End of source route */
19708 				ip1dbg(("ip_source_routed: end of SR\n"));
19709 				return (B_FALSE);
19710 			}
19711 			return (B_TRUE);
19712 		}
19713 	}
19714 	ip2dbg(("not source routed\n"));
19715 	return (B_FALSE);
19716 }
19717 
19718 /*
19719  * Check if the packet contains any source route.
19720  */
19721 static boolean_t
19722 ip_source_route_included(ipha_t *ipha)
19723 {
19724 	ipoptp_t	opts;
19725 	uint8_t		optval;
19726 
19727 	if (IS_SIMPLE_IPH(ipha))
19728 		return (B_FALSE);
19729 	for (optval = ipoptp_first(&opts, ipha);
19730 	    optval != IPOPT_EOL;
19731 	    optval = ipoptp_next(&opts)) {
19732 		switch (optval) {
19733 		case IPOPT_SSRR:
19734 		case IPOPT_LSRR:
19735 			return (B_TRUE);
19736 		}
19737 	}
19738 	return (B_FALSE);
19739 }
19740 
19741 /*
19742  * Called when the IRE expiration timer fires.
19743  */
19744 void
19745 ip_trash_timer_expire(void *args)
19746 {
19747 	int			flush_flag = 0;
19748 	ire_expire_arg_t	iea;
19749 	ip_stack_t		*ipst = (ip_stack_t *)args;
19750 
19751 	iea.iea_ipst = ipst;	/* No netstack_hold */
19752 
19753 	/*
19754 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19755 	 * This lock makes sure that a new invocation of this function
19756 	 * that occurs due to an almost immediate timer firing will not
19757 	 * progress beyond this point until the current invocation is done
19758 	 */
19759 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19760 	ipst->ips_ip_ire_expire_id = 0;
19761 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19762 
19763 	/* Periodic timer */
19764 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19765 	    ipst->ips_ip_ire_arp_interval) {
19766 		/*
19767 		 * Remove all IRE_CACHE entries since they might
19768 		 * contain arp information.
19769 		 */
19770 		flush_flag |= FLUSH_ARP_TIME;
19771 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19772 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19773 	}
19774 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19775 	    ipst->ips_ip_ire_redir_interval) {
19776 		/* Remove all redirects */
19777 		flush_flag |= FLUSH_REDIRECT_TIME;
19778 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19779 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19780 	}
19781 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19782 	    ipst->ips_ip_ire_pathmtu_interval) {
19783 		/* Increase path mtu */
19784 		flush_flag |= FLUSH_MTU_TIME;
19785 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19786 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19787 	}
19788 
19789 	/*
19790 	 * Optimize for the case when there are no redirects in the
19791 	 * ftable, that is, no need to walk the ftable in that case.
19792 	 */
19793 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19794 		iea.iea_flush_flag = flush_flag;
19795 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19796 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19797 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19798 		    NULL, ALL_ZONES, ipst);
19799 	}
19800 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19801 	    ipst->ips_ip_redirect_cnt > 0) {
19802 		iea.iea_flush_flag = flush_flag;
19803 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19804 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19805 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19806 	}
19807 	if (flush_flag & FLUSH_MTU_TIME) {
19808 		/*
19809 		 * Walk all IPv6 IRE's and update them
19810 		 * Note that ARP and redirect timers are not
19811 		 * needed since NUD handles stale entries.
19812 		 */
19813 		flush_flag = FLUSH_MTU_TIME;
19814 		iea.iea_flush_flag = flush_flag;
19815 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19816 		    ALL_ZONES, ipst);
19817 	}
19818 
19819 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19820 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19821 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19822 
19823 	/*
19824 	 * Hold the lock to serialize timeout calls and prevent
19825 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19826 	 * for the timer to fire and a new invocation of this function
19827 	 * to start before the return value of timeout has been stored
19828 	 * in ip_ire_expire_id by the current invocation.
19829 	 */
19830 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19831 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19832 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19833 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19834 }
19835 
19836 /*
19837  * Called by the memory allocator subsystem directly, when the system
19838  * is running low on memory.
19839  */
19840 /* ARGSUSED */
19841 void
19842 ip_trash_ire_reclaim(void *args)
19843 {
19844 	netstack_handle_t nh;
19845 	netstack_t *ns;
19846 
19847 	netstack_next_init(&nh);
19848 	while ((ns = netstack_next(&nh)) != NULL) {
19849 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19850 		netstack_rele(ns);
19851 	}
19852 	netstack_next_fini(&nh);
19853 }
19854 
19855 static void
19856 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19857 {
19858 	ire_cache_count_t icc;
19859 	ire_cache_reclaim_t icr;
19860 	ncc_cache_count_t ncc;
19861 	nce_cache_reclaim_t ncr;
19862 	uint_t delete_cnt;
19863 	/*
19864 	 * Memory reclaim call back.
19865 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19866 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19867 	 * entries, determine what fraction to free for
19868 	 * each category of IRE_CACHE entries giving absolute priority
19869 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19870 	 * entry will be freed unless all offlink entries are freed).
19871 	 */
19872 	icc.icc_total = 0;
19873 	icc.icc_unused = 0;
19874 	icc.icc_offlink = 0;
19875 	icc.icc_pmtu = 0;
19876 	icc.icc_onlink = 0;
19877 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19878 
19879 	/*
19880 	 * Free NCEs for IPv6 like the onlink ires.
19881 	 */
19882 	ncc.ncc_total = 0;
19883 	ncc.ncc_host = 0;
19884 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19885 
19886 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19887 	    icc.icc_pmtu + icc.icc_onlink);
19888 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19889 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19890 	if (delete_cnt == 0)
19891 		return;
19892 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19893 	/* Always delete all unused offlink entries */
19894 	icr.icr_ipst = ipst;
19895 	icr.icr_unused = 1;
19896 	if (delete_cnt <= icc.icc_unused) {
19897 		/*
19898 		 * Only need to free unused entries.  In other words,
19899 		 * there are enough unused entries to free to meet our
19900 		 * target number of freed ire cache entries.
19901 		 */
19902 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19903 		ncr.ncr_host = 0;
19904 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19905 		/*
19906 		 * Only need to free unused entries, plus a fraction of offlink
19907 		 * entries.  It follows from the first if statement that
19908 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19909 		 */
19910 		delete_cnt -= icc.icc_unused;
19911 		/* Round up # deleted by truncating fraction */
19912 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19913 		icr.icr_pmtu = icr.icr_onlink = 0;
19914 		ncr.ncr_host = 0;
19915 	} else if (delete_cnt <=
19916 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19917 		/*
19918 		 * Free all unused and offlink entries, plus a fraction of
19919 		 * pmtu entries.  It follows from the previous if statement
19920 		 * that icc_pmtu is non-zero, and that
19921 		 * delete_cnt != icc_unused + icc_offlink.
19922 		 */
19923 		icr.icr_offlink = 1;
19924 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19925 		/* Round up # deleted by truncating fraction */
19926 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19927 		icr.icr_onlink = 0;
19928 		ncr.ncr_host = 0;
19929 	} else {
19930 		/*
19931 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19932 		 * of onlink entries.  If we're here, then we know that
19933 		 * icc_onlink is non-zero, and that
19934 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19935 		 */
19936 		icr.icr_offlink = icr.icr_pmtu = 1;
19937 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19938 		    icc.icc_pmtu;
19939 		/* Round up # deleted by truncating fraction */
19940 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19941 		/* Using the same delete fraction as for onlink IREs */
19942 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19943 	}
19944 #ifdef DEBUG
19945 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19946 	    "fractions %d/%d/%d/%d\n",
19947 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19948 	    icc.icc_unused, icc.icc_offlink,
19949 	    icc.icc_pmtu, icc.icc_onlink,
19950 	    icr.icr_unused, icr.icr_offlink,
19951 	    icr.icr_pmtu, icr.icr_onlink));
19952 #endif
19953 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19954 	if (ncr.ncr_host != 0)
19955 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19956 		    (uchar_t *)&ncr, ipst);
19957 #ifdef DEBUG
19958 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19959 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19960 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19961 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19962 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19963 	    icc.icc_pmtu, icc.icc_onlink));
19964 #endif
19965 }
19966 
19967 /*
19968  * ip_unbind is called when a copy of an unbind request is received from the
19969  * upper level protocol.  We remove this conn from any fanout hash list it is
19970  * on, and zero out the bind information.  No reply is expected up above.
19971  */
19972 mblk_t *
19973 ip_unbind(queue_t *q, mblk_t *mp)
19974 {
19975 	conn_t	*connp = Q_TO_CONN(q);
19976 
19977 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19978 
19979 	if (is_system_labeled() && connp->conn_anon_port) {
19980 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19981 		    connp->conn_mlp_type, connp->conn_ulp,
19982 		    ntohs(connp->conn_lport), B_FALSE);
19983 		connp->conn_anon_port = 0;
19984 	}
19985 	connp->conn_mlp_type = mlptSingle;
19986 
19987 	ipcl_hash_remove(connp);
19988 
19989 	ASSERT(mp->b_cont == NULL);
19990 	/*
19991 	 * Convert mp into a T_OK_ACK
19992 	 */
19993 	mp = mi_tpi_ok_ack_alloc(mp);
19994 
19995 	/*
19996 	 * should not happen in practice... T_OK_ACK is smaller than the
19997 	 * original message.
19998 	 */
19999 	if (mp == NULL)
20000 		return (NULL);
20001 
20002 	/*
20003 	 * Don't bzero the ports if its TCP since TCP still needs the
20004 	 * lport to remove it from its own bind hash. TCP will do the
20005 	 * cleanup.
20006 	 */
20007 	if (!IPCL_IS_TCP(connp))
20008 		bzero(&connp->u_port, sizeof (connp->u_port));
20009 
20010 	return (mp);
20011 }
20012 
20013 /*
20014  * Write side put procedure.  Outbound data, IOCTLs, responses from
20015  * resolvers, etc, come down through here.
20016  *
20017  * arg2 is always a queue_t *.
20018  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20019  * the zoneid.
20020  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20021  */
20022 void
20023 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20024 {
20025 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20026 }
20027 
20028 void
20029 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20030     ip_opt_info_t *infop)
20031 {
20032 	conn_t		*connp = NULL;
20033 	queue_t		*q = (queue_t *)arg2;
20034 	ipha_t		*ipha;
20035 #define	rptr	((uchar_t *)ipha)
20036 	ire_t		*ire = NULL;
20037 	ire_t		*sctp_ire = NULL;
20038 	uint32_t	v_hlen_tos_len;
20039 	ipaddr_t	dst;
20040 	mblk_t		*first_mp = NULL;
20041 	boolean_t	mctl_present;
20042 	ipsec_out_t	*io;
20043 	int		match_flags;
20044 	ill_t		*attach_ill = NULL;
20045 					/* Bind to IPIF_NOFAILOVER ill etc. */
20046 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20047 	ipif_t		*dst_ipif;
20048 	boolean_t	multirt_need_resolve = B_FALSE;
20049 	mblk_t		*copy_mp = NULL;
20050 	int		err;
20051 	zoneid_t	zoneid;
20052 	int	adjust;
20053 	uint16_t iplen;
20054 	boolean_t	need_decref = B_FALSE;
20055 	boolean_t	ignore_dontroute = B_FALSE;
20056 	boolean_t	ignore_nexthop = B_FALSE;
20057 	boolean_t	ip_nexthop = B_FALSE;
20058 	ipaddr_t	nexthop_addr;
20059 	ip_stack_t	*ipst;
20060 
20061 #ifdef	_BIG_ENDIAN
20062 #define	V_HLEN	(v_hlen_tos_len >> 24)
20063 #else
20064 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20065 #endif
20066 
20067 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20068 	    "ip_wput_start: q %p", q);
20069 
20070 	/*
20071 	 * ip_wput fast path
20072 	 */
20073 
20074 	/* is packet from ARP ? */
20075 	if (q->q_next != NULL) {
20076 		zoneid = (zoneid_t)(uintptr_t)arg;
20077 		goto qnext;
20078 	}
20079 
20080 	connp = (conn_t *)arg;
20081 	ASSERT(connp != NULL);
20082 	zoneid = connp->conn_zoneid;
20083 	ipst = connp->conn_netstack->netstack_ip;
20084 
20085 	/* is queue flow controlled? */
20086 	if ((q->q_first != NULL || connp->conn_draining) &&
20087 	    (caller == IP_WPUT)) {
20088 		ASSERT(!need_decref);
20089 		(void) putq(q, mp);
20090 		return;
20091 	}
20092 
20093 	/* Multidata transmit? */
20094 	if (DB_TYPE(mp) == M_MULTIDATA) {
20095 		/*
20096 		 * We should never get here, since all Multidata messages
20097 		 * originating from tcp should have been directed over to
20098 		 * tcp_multisend() in the first place.
20099 		 */
20100 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20101 		freemsg(mp);
20102 		return;
20103 	} else if (DB_TYPE(mp) != M_DATA)
20104 		goto notdata;
20105 
20106 	if (mp->b_flag & MSGHASREF) {
20107 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20108 		mp->b_flag &= ~MSGHASREF;
20109 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20110 		need_decref = B_TRUE;
20111 	}
20112 	ipha = (ipha_t *)mp->b_rptr;
20113 
20114 	/* is IP header non-aligned or mblk smaller than basic IP header */
20115 #ifndef SAFETY_BEFORE_SPEED
20116 	if (!OK_32PTR(rptr) ||
20117 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20118 		goto hdrtoosmall;
20119 #endif
20120 
20121 	ASSERT(OK_32PTR(ipha));
20122 
20123 	/*
20124 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20125 	 * wrong version, we'll catch it again in ip_output_v6.
20126 	 *
20127 	 * Note that this is *only* locally-generated output here, and never
20128 	 * forwarded data, and that we need to deal only with transports that
20129 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20130 	 * label.)
20131 	 */
20132 	if (is_system_labeled() &&
20133 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20134 	    !connp->conn_ulp_labeled) {
20135 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20136 		    connp->conn_mac_exempt, ipst);
20137 		ipha = (ipha_t *)mp->b_rptr;
20138 		if (err != 0) {
20139 			first_mp = mp;
20140 			if (err == EINVAL)
20141 				goto icmp_parameter_problem;
20142 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20143 			goto discard_pkt;
20144 		}
20145 		iplen = ntohs(ipha->ipha_length) + adjust;
20146 		ipha->ipha_length = htons(iplen);
20147 	}
20148 
20149 	ASSERT(infop != NULL);
20150 
20151 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20152 		/*
20153 		 * IP_PKTINFO ancillary option is present.
20154 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20155 		 * allows using address of any zone as the source address.
20156 		 */
20157 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20158 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20159 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20160 		if (ire == NULL)
20161 			goto drop_pkt;
20162 		ire_refrele(ire);
20163 		ire = NULL;
20164 	}
20165 
20166 	/*
20167 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20168 	 * ill index passed in IP_PKTINFO.
20169 	 */
20170 	if (infop->ip_opt_ill_index != 0 &&
20171 	    connp->conn_xmit_if_ill == NULL &&
20172 	    connp->conn_nofailover_ill == NULL) {
20173 
20174 		xmit_ill = ill_lookup_on_ifindex(
20175 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20176 		    ipst);
20177 
20178 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20179 			goto drop_pkt;
20180 		/*
20181 		 * check that there is an ipif belonging
20182 		 * to our zone. IPCL_ZONEID is not used because
20183 		 * IP_ALLZONES option is valid only when the ill is
20184 		 * accessible from all zones i.e has a valid ipif in
20185 		 * all zones.
20186 		 */
20187 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20188 			goto drop_pkt;
20189 		}
20190 	}
20191 
20192 	/*
20193 	 * If there is a policy, try to attach an ipsec_out in
20194 	 * the front. At the end, first_mp either points to a
20195 	 * M_DATA message or IPSEC_OUT message linked to a
20196 	 * M_DATA message. We have to do it now as we might
20197 	 * lose the "conn" if we go through ip_newroute.
20198 	 */
20199 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20200 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20201 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20202 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20203 			if (need_decref)
20204 				CONN_DEC_REF(connp);
20205 			return;
20206 		} else {
20207 			ASSERT(mp->b_datap->db_type == M_CTL);
20208 			first_mp = mp;
20209 			mp = mp->b_cont;
20210 			mctl_present = B_TRUE;
20211 		}
20212 	} else {
20213 		first_mp = mp;
20214 		mctl_present = B_FALSE;
20215 	}
20216 
20217 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20218 
20219 	/* is wrong version or IP options present */
20220 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20221 		goto version_hdrlen_check;
20222 	dst = ipha->ipha_dst;
20223 
20224 	if (connp->conn_nofailover_ill != NULL) {
20225 		attach_ill = conn_get_held_ill(connp,
20226 		    &connp->conn_nofailover_ill, &err);
20227 		if (err == ILL_LOOKUP_FAILED) {
20228 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20229 			if (need_decref)
20230 				CONN_DEC_REF(connp);
20231 			freemsg(first_mp);
20232 			return;
20233 		}
20234 	}
20235 
20236 
20237 	/* is packet multicast? */
20238 	if (CLASSD(dst))
20239 		goto multicast;
20240 
20241 	/*
20242 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20243 	 * takes precedence over conn_dontroute and conn_nexthop_set
20244 	 */
20245 	if (xmit_ill != NULL) {
20246 		goto send_from_ill;
20247 	}
20248 
20249 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20250 	    (connp->conn_nexthop_set)) {
20251 		/*
20252 		 * If the destination is a broadcast or a loopback
20253 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20254 		 * through the standard path. But in the case of local
20255 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20256 		 * the standard path not IP_XMIT_IF.
20257 		 */
20258 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20259 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20260 		    (ire->ire_type != IRE_LOOPBACK))) {
20261 			if ((connp->conn_dontroute ||
20262 			    connp->conn_nexthop_set) && (ire != NULL) &&
20263 			    (ire->ire_type == IRE_LOCAL))
20264 				goto standard_path;
20265 
20266 			if (ire != NULL) {
20267 				ire_refrele(ire);
20268 				/* No more access to ire */
20269 				ire = NULL;
20270 			}
20271 			/*
20272 			 * bypass routing checks and go directly to
20273 			 * interface.
20274 			 */
20275 			if (connp->conn_dontroute) {
20276 				goto dontroute;
20277 			} else if (connp->conn_nexthop_set) {
20278 				ip_nexthop = B_TRUE;
20279 				nexthop_addr = connp->conn_nexthop_v4;
20280 				goto send_from_ill;
20281 			}
20282 
20283 			/*
20284 			 * If IP_XMIT_IF socket option is set,
20285 			 * then we allow unicast and multicast
20286 			 * packets to go through the ill. It is
20287 			 * quite possible that the destination
20288 			 * is not in the ire cache table and we
20289 			 * do not want to go to ip_newroute()
20290 			 * instead we call ip_newroute_ipif.
20291 			 */
20292 			xmit_ill = conn_get_held_ill(connp,
20293 			    &connp->conn_xmit_if_ill, &err);
20294 			if (err == ILL_LOOKUP_FAILED) {
20295 				BUMP_MIB(&ipst->ips_ip_mib,
20296 				    ipIfStatsOutDiscards);
20297 				if (attach_ill != NULL)
20298 					ill_refrele(attach_ill);
20299 				if (need_decref)
20300 					CONN_DEC_REF(connp);
20301 				freemsg(first_mp);
20302 				return;
20303 			}
20304 			goto send_from_ill;
20305 		}
20306 standard_path:
20307 		/* Must be a broadcast, a loopback or a local ire */
20308 		if (ire != NULL) {
20309 			ire_refrele(ire);
20310 			/* No more access to ire */
20311 			ire = NULL;
20312 		}
20313 	}
20314 
20315 	if (attach_ill != NULL)
20316 		goto send_from_ill;
20317 
20318 	/*
20319 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20320 	 * this for the tcp global queue and listen end point
20321 	 * as it does not really have a real destination to
20322 	 * talk to.  This is also true for SCTP.
20323 	 */
20324 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20325 	    !connp->conn_fully_bound) {
20326 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20327 		if (ire == NULL)
20328 			goto noirefound;
20329 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20330 		    "ip_wput_end: q %p (%S)", q, "end");
20331 
20332 		/*
20333 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20334 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20335 		 */
20336 		if (ire->ire_flags & RTF_MULTIRT) {
20337 
20338 			/*
20339 			 * Force the TTL of multirouted packets if required.
20340 			 * The TTL of such packets is bounded by the
20341 			 * ip_multirt_ttl ndd variable.
20342 			 */
20343 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20344 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20345 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20346 				    "(was %d), dst 0x%08x\n",
20347 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20348 				    ntohl(ire->ire_addr)));
20349 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20350 			}
20351 			/*
20352 			 * We look at this point if there are pending
20353 			 * unresolved routes. ire_multirt_resolvable()
20354 			 * checks in O(n) that all IRE_OFFSUBNET ire
20355 			 * entries for the packet's destination and
20356 			 * flagged RTF_MULTIRT are currently resolved.
20357 			 * If some remain unresolved, we make a copy
20358 			 * of the current message. It will be used
20359 			 * to initiate additional route resolutions.
20360 			 */
20361 			multirt_need_resolve =
20362 			    ire_multirt_need_resolve(ire->ire_addr,
20363 			    MBLK_GETLABEL(first_mp), ipst);
20364 			ip2dbg(("ip_wput[TCP]: ire %p, "
20365 			    "multirt_need_resolve %d, first_mp %p\n",
20366 			    (void *)ire, multirt_need_resolve,
20367 			    (void *)first_mp));
20368 			if (multirt_need_resolve) {
20369 				copy_mp = copymsg(first_mp);
20370 				if (copy_mp != NULL) {
20371 					MULTIRT_DEBUG_TAG(copy_mp);
20372 				}
20373 			}
20374 		}
20375 
20376 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20377 
20378 		/*
20379 		 * Try to resolve another multiroute if
20380 		 * ire_multirt_need_resolve() deemed it necessary.
20381 		 */
20382 		if (copy_mp != NULL)
20383 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20384 		if (need_decref)
20385 			CONN_DEC_REF(connp);
20386 		return;
20387 	}
20388 
20389 	/*
20390 	 * Access to conn_ire_cache. (protected by conn_lock)
20391 	 *
20392 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20393 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20394 	 * send a packet or two with the IRE_CACHE that is going away.
20395 	 * Access to the ire requires an ire refhold on the ire prior to
20396 	 * its use since an interface unplumb thread may delete the cached
20397 	 * ire and release the refhold at any time.
20398 	 *
20399 	 * Caching an ire in the conn_ire_cache
20400 	 *
20401 	 * o Caching an ire pointer in the conn requires a strict check for
20402 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20403 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20404 	 * in the conn is done after making sure under the bucket lock that the
20405 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20406 	 * caching an ire after the unplumb thread has cleaned up the conn.
20407 	 * If the conn does not send a packet subsequently the unplumb thread
20408 	 * will be hanging waiting for the ire count to drop to zero.
20409 	 *
20410 	 * o We also need to atomically test for a null conn_ire_cache and
20411 	 * set the conn_ire_cache under the the protection of the conn_lock
20412 	 * to avoid races among concurrent threads trying to simultaneously
20413 	 * cache an ire in the conn_ire_cache.
20414 	 */
20415 	mutex_enter(&connp->conn_lock);
20416 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20417 
20418 	if (ire != NULL && ire->ire_addr == dst &&
20419 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20420 
20421 		IRE_REFHOLD(ire);
20422 		mutex_exit(&connp->conn_lock);
20423 
20424 	} else {
20425 		boolean_t cached = B_FALSE;
20426 		connp->conn_ire_cache = NULL;
20427 		mutex_exit(&connp->conn_lock);
20428 		/* Release the old ire */
20429 		if (ire != NULL && sctp_ire == NULL)
20430 			IRE_REFRELE_NOTR(ire);
20431 
20432 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20433 		if (ire == NULL)
20434 			goto noirefound;
20435 		IRE_REFHOLD_NOTR(ire);
20436 
20437 		mutex_enter(&connp->conn_lock);
20438 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20439 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20440 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20441 				if (connp->conn_ulp == IPPROTO_TCP)
20442 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20443 				connp->conn_ire_cache = ire;
20444 				cached = B_TRUE;
20445 			}
20446 			rw_exit(&ire->ire_bucket->irb_lock);
20447 		}
20448 		mutex_exit(&connp->conn_lock);
20449 
20450 		/*
20451 		 * We can continue to use the ire but since it was
20452 		 * not cached, we should drop the extra reference.
20453 		 */
20454 		if (!cached)
20455 			IRE_REFRELE_NOTR(ire);
20456 	}
20457 
20458 
20459 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20460 	    "ip_wput_end: q %p (%S)", q, "end");
20461 
20462 	/*
20463 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20464 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20465 	 */
20466 	if (ire->ire_flags & RTF_MULTIRT) {
20467 
20468 		/*
20469 		 * Force the TTL of multirouted packets if required.
20470 		 * The TTL of such packets is bounded by the
20471 		 * ip_multirt_ttl ndd variable.
20472 		 */
20473 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20474 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20475 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20476 			    "(was %d), dst 0x%08x\n",
20477 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20478 			    ntohl(ire->ire_addr)));
20479 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20480 		}
20481 
20482 		/*
20483 		 * At this point, we check to see if there are any pending
20484 		 * unresolved routes. ire_multirt_resolvable()
20485 		 * checks in O(n) that all IRE_OFFSUBNET ire
20486 		 * entries for the packet's destination and
20487 		 * flagged RTF_MULTIRT are currently resolved.
20488 		 * If some remain unresolved, we make a copy
20489 		 * of the current message. It will be used
20490 		 * to initiate additional route resolutions.
20491 		 */
20492 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20493 		    MBLK_GETLABEL(first_mp), ipst);
20494 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20495 		    "multirt_need_resolve %d, first_mp %p\n",
20496 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20497 		if (multirt_need_resolve) {
20498 			copy_mp = copymsg(first_mp);
20499 			if (copy_mp != NULL) {
20500 				MULTIRT_DEBUG_TAG(copy_mp);
20501 			}
20502 		}
20503 	}
20504 
20505 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20506 
20507 	/*
20508 	 * Try to resolve another multiroute if
20509 	 * ire_multirt_resolvable() deemed it necessary
20510 	 */
20511 	if (copy_mp != NULL)
20512 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20513 	if (need_decref)
20514 		CONN_DEC_REF(connp);
20515 	return;
20516 
20517 qnext:
20518 	/*
20519 	 * Upper Level Protocols pass down complete IP datagrams
20520 	 * as M_DATA messages.	Everything else is a sideshow.
20521 	 *
20522 	 * 1) We could be re-entering ip_wput because of ip_neworute
20523 	 *    in which case we could have a IPSEC_OUT message. We
20524 	 *    need to pass through ip_wput like other datagrams and
20525 	 *    hence cannot branch to ip_wput_nondata.
20526 	 *
20527 	 * 2) ARP, AH, ESP, and other clients who are on the module
20528 	 *    instance of IP stream, give us something to deal with.
20529 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20530 	 *
20531 	 * 3) ICMP replies also could come here.
20532 	 */
20533 	ipst = ILLQ_TO_IPST(q);
20534 
20535 	if (DB_TYPE(mp) != M_DATA) {
20536 notdata:
20537 		if (DB_TYPE(mp) == M_CTL) {
20538 			/*
20539 			 * M_CTL messages are used by ARP, AH and ESP to
20540 			 * communicate with IP. We deal with IPSEC_IN and
20541 			 * IPSEC_OUT here. ip_wput_nondata handles other
20542 			 * cases.
20543 			 */
20544 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20545 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20546 				first_mp = mp->b_cont;
20547 				first_mp->b_flag &= ~MSGHASREF;
20548 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20549 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20550 				CONN_DEC_REF(connp);
20551 				connp = NULL;
20552 			}
20553 			if (ii->ipsec_info_type == IPSEC_IN) {
20554 				/*
20555 				 * Either this message goes back to
20556 				 * IPsec for further processing or to
20557 				 * ULP after policy checks.
20558 				 */
20559 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20560 				return;
20561 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20562 				io = (ipsec_out_t *)ii;
20563 				if (io->ipsec_out_proc_begin) {
20564 					/*
20565 					 * IPsec processing has already started.
20566 					 * Complete it.
20567 					 * IPQoS notes: We don't care what is
20568 					 * in ipsec_out_ill_index since this
20569 					 * won't be processed for IPQoS policies
20570 					 * in ipsec_out_process.
20571 					 */
20572 					ipsec_out_process(q, mp, NULL,
20573 					    io->ipsec_out_ill_index);
20574 					return;
20575 				} else {
20576 					connp = (q->q_next != NULL) ?
20577 					    NULL : Q_TO_CONN(q);
20578 					first_mp = mp;
20579 					mp = mp->b_cont;
20580 					mctl_present = B_TRUE;
20581 				}
20582 				zoneid = io->ipsec_out_zoneid;
20583 				ASSERT(zoneid != ALL_ZONES);
20584 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20585 				/*
20586 				 * It's an IPsec control message requesting
20587 				 * an SADB update to be sent to the IPsec
20588 				 * hardware acceleration capable ills.
20589 				 */
20590 				ipsec_ctl_t *ipsec_ctl =
20591 				    (ipsec_ctl_t *)mp->b_rptr;
20592 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20593 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20594 				mblk_t *cmp = mp->b_cont;
20595 
20596 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20597 				ASSERT(cmp != NULL);
20598 
20599 				freeb(mp);
20600 				ill_ipsec_capab_send_all(satype, cmp, sa,
20601 				    ipst->ips_netstack);
20602 				return;
20603 			} else {
20604 				/*
20605 				 * This must be ARP or special TSOL signaling.
20606 				 */
20607 				ip_wput_nondata(NULL, q, mp, NULL);
20608 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20609 				    "ip_wput_end: q %p (%S)", q, "nondata");
20610 				return;
20611 			}
20612 		} else {
20613 			/*
20614 			 * This must be non-(ARP/AH/ESP) messages.
20615 			 */
20616 			ASSERT(!need_decref);
20617 			ip_wput_nondata(NULL, q, mp, NULL);
20618 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20619 			    "ip_wput_end: q %p (%S)", q, "nondata");
20620 			return;
20621 		}
20622 	} else {
20623 		first_mp = mp;
20624 		mctl_present = B_FALSE;
20625 	}
20626 
20627 	ASSERT(first_mp != NULL);
20628 	/*
20629 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20630 	 * to make sure that this packet goes out on the same interface it
20631 	 * came in. We handle that here.
20632 	 */
20633 	if (mctl_present) {
20634 		uint_t ifindex;
20635 
20636 		io = (ipsec_out_t *)first_mp->b_rptr;
20637 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20638 			/*
20639 			 * We may have lost the conn context if we are
20640 			 * coming here from ip_newroute(). Copy the
20641 			 * nexthop information.
20642 			 */
20643 			if (io->ipsec_out_ip_nexthop) {
20644 				ip_nexthop = B_TRUE;
20645 				nexthop_addr = io->ipsec_out_nexthop_addr;
20646 
20647 				ipha = (ipha_t *)mp->b_rptr;
20648 				dst = ipha->ipha_dst;
20649 				goto send_from_ill;
20650 			} else {
20651 				ASSERT(io->ipsec_out_ill_index != 0);
20652 				ifindex = io->ipsec_out_ill_index;
20653 				attach_ill = ill_lookup_on_ifindex(ifindex,
20654 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20655 				if (attach_ill == NULL) {
20656 					ASSERT(xmit_ill == NULL);
20657 					ip1dbg(("ip_output: bad ifindex for "
20658 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20659 					    ifindex));
20660 					freemsg(first_mp);
20661 					BUMP_MIB(&ipst->ips_ip_mib,
20662 					    ipIfStatsOutDiscards);
20663 					ASSERT(!need_decref);
20664 					return;
20665 				}
20666 			}
20667 		}
20668 	}
20669 
20670 	ASSERT(xmit_ill == NULL);
20671 
20672 	/* We have a complete IP datagram heading outbound. */
20673 	ipha = (ipha_t *)mp->b_rptr;
20674 
20675 #ifndef SPEED_BEFORE_SAFETY
20676 	/*
20677 	 * Make sure we have a full-word aligned message and that at least
20678 	 * a simple IP header is accessible in the first message.  If not,
20679 	 * try a pullup.
20680 	 */
20681 	if (!OK_32PTR(rptr) ||
20682 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20683 hdrtoosmall:
20684 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20685 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20686 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20687 			if (first_mp == NULL)
20688 				first_mp = mp;
20689 			goto discard_pkt;
20690 		}
20691 
20692 		/* This function assumes that mp points to an IPv4 packet. */
20693 		if (is_system_labeled() && q->q_next == NULL &&
20694 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20695 		    !connp->conn_ulp_labeled) {
20696 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20697 			    &adjust, connp->conn_mac_exempt, ipst);
20698 			ipha = (ipha_t *)mp->b_rptr;
20699 			if (first_mp != NULL)
20700 				first_mp->b_cont = mp;
20701 			if (err != 0) {
20702 				if (first_mp == NULL)
20703 					first_mp = mp;
20704 				if (err == EINVAL)
20705 					goto icmp_parameter_problem;
20706 				ip2dbg(("ip_wput: label check failed (%d)\n",
20707 				    err));
20708 				goto discard_pkt;
20709 			}
20710 			iplen = ntohs(ipha->ipha_length) + adjust;
20711 			ipha->ipha_length = htons(iplen);
20712 		}
20713 
20714 		ipha = (ipha_t *)mp->b_rptr;
20715 		if (first_mp == NULL) {
20716 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20717 			/*
20718 			 * If we got here because of "goto hdrtoosmall"
20719 			 * We need to attach a IPSEC_OUT.
20720 			 */
20721 			if (connp->conn_out_enforce_policy) {
20722 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20723 				    NULL, ipha->ipha_protocol,
20724 				    ipst->ips_netstack)) == NULL)) {
20725 					BUMP_MIB(&ipst->ips_ip_mib,
20726 					    ipIfStatsOutDiscards);
20727 					if (need_decref)
20728 						CONN_DEC_REF(connp);
20729 					return;
20730 				} else {
20731 					ASSERT(mp->b_datap->db_type == M_CTL);
20732 					first_mp = mp;
20733 					mp = mp->b_cont;
20734 					mctl_present = B_TRUE;
20735 				}
20736 			} else {
20737 				first_mp = mp;
20738 				mctl_present = B_FALSE;
20739 			}
20740 		}
20741 	}
20742 #endif
20743 
20744 	/* Most of the code below is written for speed, not readability */
20745 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20746 
20747 	/*
20748 	 * If ip_newroute() fails, we're going to need a full
20749 	 * header for the icmp wraparound.
20750 	 */
20751 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20752 		uint_t	v_hlen;
20753 version_hdrlen_check:
20754 		ASSERT(first_mp != NULL);
20755 		v_hlen = V_HLEN;
20756 		/*
20757 		 * siphon off IPv6 packets coming down from transport
20758 		 * layer modules here.
20759 		 * Note: high-order bit carries NUD reachability confirmation
20760 		 */
20761 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20762 			/*
20763 			 * XXX implement a IPv4 and IPv6 packet counter per
20764 			 * conn and switch when ratio exceeds e.g. 10:1
20765 			 */
20766 #ifdef notyet
20767 			if (q->q_next == NULL) /* Avoid ill queue */
20768 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
20769 #endif
20770 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20771 			ASSERT(xmit_ill == NULL);
20772 			if (attach_ill != NULL)
20773 				ill_refrele(attach_ill);
20774 			if (need_decref)
20775 				mp->b_flag |= MSGHASREF;
20776 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20777 			return;
20778 		}
20779 
20780 		if ((v_hlen >> 4) != IP_VERSION) {
20781 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20782 			    "ip_wput_end: q %p (%S)", q, "badvers");
20783 			goto discard_pkt;
20784 		}
20785 		/*
20786 		 * Is the header length at least 20 bytes?
20787 		 *
20788 		 * Are there enough bytes accessible in the header?  If
20789 		 * not, try a pullup.
20790 		 */
20791 		v_hlen &= 0xF;
20792 		v_hlen <<= 2;
20793 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20794 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20795 			    "ip_wput_end: q %p (%S)", q, "badlen");
20796 			goto discard_pkt;
20797 		}
20798 		if (v_hlen > (mp->b_wptr - rptr)) {
20799 			if (!pullupmsg(mp, v_hlen)) {
20800 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20801 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20802 				goto discard_pkt;
20803 			}
20804 			ipha = (ipha_t *)mp->b_rptr;
20805 		}
20806 		/*
20807 		 * Move first entry from any source route into ipha_dst and
20808 		 * verify the options
20809 		 */
20810 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20811 		    zoneid, ipst)) {
20812 			ASSERT(xmit_ill == NULL);
20813 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20814 			if (attach_ill != NULL)
20815 				ill_refrele(attach_ill);
20816 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20817 			    "ip_wput_end: q %p (%S)", q, "badopts");
20818 			if (need_decref)
20819 				CONN_DEC_REF(connp);
20820 			return;
20821 		}
20822 	}
20823 	dst = ipha->ipha_dst;
20824 
20825 	/*
20826 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20827 	 * we have to run the packet through ip_newroute which will take
20828 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20829 	 * a resolver, or assigning a default gateway, etc.
20830 	 */
20831 	if (CLASSD(dst)) {
20832 		ipif_t	*ipif;
20833 		uint32_t setsrc = 0;
20834 
20835 multicast:
20836 		ASSERT(first_mp != NULL);
20837 		ip2dbg(("ip_wput: CLASSD\n"));
20838 		if (connp == NULL) {
20839 			/*
20840 			 * Use the first good ipif on the ill.
20841 			 * XXX Should this ever happen? (Appears
20842 			 * to show up with just ppp and no ethernet due
20843 			 * to in.rdisc.)
20844 			 * However, ire_send should be able to
20845 			 * call ip_wput_ire directly.
20846 			 *
20847 			 * XXX Also, this can happen for ICMP and other packets
20848 			 * with multicast source addresses.  Perhaps we should
20849 			 * fix things so that we drop the packet in question,
20850 			 * but for now, just run with it.
20851 			 */
20852 			ill_t *ill = (ill_t *)q->q_ptr;
20853 
20854 			/*
20855 			 * Don't honor attach_if for this case. If ill
20856 			 * is part of the group, ipif could belong to
20857 			 * any ill and we cannot maintain attach_ill
20858 			 * and ipif_ill same anymore and the assert
20859 			 * below would fail.
20860 			 */
20861 			if (mctl_present && io->ipsec_out_attach_if) {
20862 				io->ipsec_out_ill_index = 0;
20863 				io->ipsec_out_attach_if = B_FALSE;
20864 				ASSERT(attach_ill != NULL);
20865 				ill_refrele(attach_ill);
20866 				attach_ill = NULL;
20867 			}
20868 
20869 			ASSERT(attach_ill == NULL);
20870 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20871 			if (ipif == NULL) {
20872 				if (need_decref)
20873 					CONN_DEC_REF(connp);
20874 				freemsg(first_mp);
20875 				return;
20876 			}
20877 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20878 			    ntohl(dst), ill->ill_name));
20879 		} else {
20880 			/*
20881 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20882 			 * and IP_MULTICAST_IF.
20883 			 * Block comment above this function explains the
20884 			 * locking mechanism used here
20885 			 */
20886 			if (xmit_ill == NULL) {
20887 				xmit_ill = conn_get_held_ill(connp,
20888 				    &connp->conn_xmit_if_ill, &err);
20889 				if (err == ILL_LOOKUP_FAILED) {
20890 					ip1dbg(("ip_wput: No ill for "
20891 					    "IP_XMIT_IF\n"));
20892 					BUMP_MIB(&ipst->ips_ip_mib,
20893 					    ipIfStatsOutNoRoutes);
20894 					goto drop_pkt;
20895 				}
20896 			}
20897 
20898 			if (xmit_ill == NULL) {
20899 				ipif = conn_get_held_ipif(connp,
20900 				    &connp->conn_multicast_ipif, &err);
20901 				if (err == IPIF_LOOKUP_FAILED) {
20902 					ip1dbg(("ip_wput: No ipif for "
20903 					    "multicast\n"));
20904 					BUMP_MIB(&ipst->ips_ip_mib,
20905 					    ipIfStatsOutNoRoutes);
20906 					goto drop_pkt;
20907 				}
20908 			}
20909 			if (xmit_ill != NULL) {
20910 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20911 				if (ipif == NULL) {
20912 					ip1dbg(("ip_wput: No ipif for "
20913 					    "IP_XMIT_IF\n"));
20914 					BUMP_MIB(&ipst->ips_ip_mib,
20915 					    ipIfStatsOutNoRoutes);
20916 					goto drop_pkt;
20917 				}
20918 			} else if (ipif == NULL || ipif->ipif_isv6) {
20919 				/*
20920 				 * We must do this ipif determination here
20921 				 * else we could pass through ip_newroute
20922 				 * and come back here without the conn context.
20923 				 *
20924 				 * Note: we do late binding i.e. we bind to
20925 				 * the interface when the first packet is sent.
20926 				 * For performance reasons we do not rebind on
20927 				 * each packet but keep the binding until the
20928 				 * next IP_MULTICAST_IF option.
20929 				 *
20930 				 * conn_multicast_{ipif,ill} are shared between
20931 				 * IPv4 and IPv6 and AF_INET6 sockets can
20932 				 * send both IPv4 and IPv6 packets. Hence
20933 				 * we have to check that "isv6" matches above.
20934 				 */
20935 				if (ipif != NULL)
20936 					ipif_refrele(ipif);
20937 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20938 				if (ipif == NULL) {
20939 					ip1dbg(("ip_wput: No ipif for "
20940 					    "multicast\n"));
20941 					BUMP_MIB(&ipst->ips_ip_mib,
20942 					    ipIfStatsOutNoRoutes);
20943 					goto drop_pkt;
20944 				}
20945 				err = conn_set_held_ipif(connp,
20946 				    &connp->conn_multicast_ipif, ipif);
20947 				if (err == IPIF_LOOKUP_FAILED) {
20948 					ipif_refrele(ipif);
20949 					ip1dbg(("ip_wput: No ipif for "
20950 					    "multicast\n"));
20951 					BUMP_MIB(&ipst->ips_ip_mib,
20952 					    ipIfStatsOutNoRoutes);
20953 					goto drop_pkt;
20954 				}
20955 			}
20956 		}
20957 		ASSERT(!ipif->ipif_isv6);
20958 		/*
20959 		 * As we may lose the conn by the time we reach ip_wput_ire,
20960 		 * we copy conn_multicast_loop and conn_dontroute on to an
20961 		 * ipsec_out. In case if this datagram goes out secure,
20962 		 * we need the ill_index also. Copy that also into the
20963 		 * ipsec_out.
20964 		 */
20965 		if (mctl_present) {
20966 			io = (ipsec_out_t *)first_mp->b_rptr;
20967 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20968 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20969 		} else {
20970 			ASSERT(mp == first_mp);
20971 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20972 			    BPRI_HI)) == NULL) {
20973 				ipif_refrele(ipif);
20974 				first_mp = mp;
20975 				goto discard_pkt;
20976 			}
20977 			first_mp->b_datap->db_type = M_CTL;
20978 			first_mp->b_wptr += sizeof (ipsec_info_t);
20979 			/* ipsec_out_secure is B_FALSE now */
20980 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20981 			io = (ipsec_out_t *)first_mp->b_rptr;
20982 			io->ipsec_out_type = IPSEC_OUT;
20983 			io->ipsec_out_len = sizeof (ipsec_out_t);
20984 			io->ipsec_out_use_global_policy = B_TRUE;
20985 			io->ipsec_out_ns = ipst->ips_netstack;
20986 			first_mp->b_cont = mp;
20987 			mctl_present = B_TRUE;
20988 		}
20989 		if (attach_ill != NULL) {
20990 			ASSERT(attach_ill == ipif->ipif_ill);
20991 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20992 
20993 			/*
20994 			 * Check if we need an ire that will not be
20995 			 * looked up by anybody else i.e. HIDDEN.
20996 			 */
20997 			if (ill_is_probeonly(attach_ill)) {
20998 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20999 			}
21000 			io->ipsec_out_ill_index =
21001 			    attach_ill->ill_phyint->phyint_ifindex;
21002 			io->ipsec_out_attach_if = B_TRUE;
21003 		} else {
21004 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21005 			io->ipsec_out_ill_index =
21006 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21007 		}
21008 		if (connp != NULL) {
21009 			io->ipsec_out_multicast_loop =
21010 			    connp->conn_multicast_loop;
21011 			io->ipsec_out_dontroute = connp->conn_dontroute;
21012 			io->ipsec_out_zoneid = connp->conn_zoneid;
21013 		}
21014 		/*
21015 		 * If the application uses IP_MULTICAST_IF with
21016 		 * different logical addresses of the same ILL, we
21017 		 * need to make sure that the soruce address of
21018 		 * the packet matches the logical IP address used
21019 		 * in the option. We do it by initializing ipha_src
21020 		 * here. This should keep IPsec also happy as
21021 		 * when we return from IPsec processing, we don't
21022 		 * have to worry about getting the right address on
21023 		 * the packet. Thus it is sufficient to look for
21024 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21025 		 * MATCH_IRE_IPIF.
21026 		 *
21027 		 * NOTE : We need to do it for non-secure case also as
21028 		 * this might go out secure if there is a global policy
21029 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21030 		 * address, the source should be initialized already and
21031 		 * hence we won't be initializing here.
21032 		 *
21033 		 * As we do not have the ire yet, it is possible that
21034 		 * we set the source address here and then later discover
21035 		 * that the ire implies the source address to be assigned
21036 		 * through the RTF_SETSRC flag.
21037 		 * In that case, the setsrc variable will remind us
21038 		 * that overwritting the source address by the one
21039 		 * of the RTF_SETSRC-flagged ire is allowed.
21040 		 */
21041 		if (ipha->ipha_src == INADDR_ANY &&
21042 		    (connp == NULL || !connp->conn_unspec_src)) {
21043 			ipha->ipha_src = ipif->ipif_src_addr;
21044 			setsrc = RTF_SETSRC;
21045 		}
21046 		/*
21047 		 * Find an IRE which matches the destination and the outgoing
21048 		 * queue (i.e. the outgoing interface.)
21049 		 * For loopback use a unicast IP address for
21050 		 * the ire lookup.
21051 		 */
21052 		if (IS_LOOPBACK(ipif->ipif_ill))
21053 			dst = ipif->ipif_lcl_addr;
21054 
21055 		/*
21056 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21057 		 * We don't need to lookup ire in ctable as the packet
21058 		 * needs to be sent to the destination through the specified
21059 		 * ill irrespective of ires in the cache table.
21060 		 */
21061 		ire = NULL;
21062 		if (xmit_ill == NULL) {
21063 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21064 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21065 		}
21066 
21067 		/*
21068 		 * refrele attach_ill as its not needed anymore.
21069 		 */
21070 		if (attach_ill != NULL) {
21071 			ill_refrele(attach_ill);
21072 			attach_ill = NULL;
21073 		}
21074 
21075 		if (ire == NULL) {
21076 			/*
21077 			 * Multicast loopback and multicast forwarding is
21078 			 * done in ip_wput_ire.
21079 			 *
21080 			 * Mark this packet to make it be delivered to
21081 			 * ip_wput_ire after the new ire has been
21082 			 * created.
21083 			 *
21084 			 * The call to ip_newroute_ipif takes into account
21085 			 * the setsrc reminder. In any case, we take care
21086 			 * of the RTF_MULTIRT flag.
21087 			 */
21088 			mp->b_prev = mp->b_next = NULL;
21089 			if (xmit_ill == NULL ||
21090 			    xmit_ill->ill_ipif_up_count > 0) {
21091 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21092 				    setsrc | RTF_MULTIRT, zoneid, infop);
21093 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21094 				    "ip_wput_end: q %p (%S)", q, "noire");
21095 			} else {
21096 				freemsg(first_mp);
21097 			}
21098 			ipif_refrele(ipif);
21099 			if (xmit_ill != NULL)
21100 				ill_refrele(xmit_ill);
21101 			if (need_decref)
21102 				CONN_DEC_REF(connp);
21103 			return;
21104 		}
21105 
21106 		ipif_refrele(ipif);
21107 		ipif = NULL;
21108 		ASSERT(xmit_ill == NULL);
21109 
21110 		/*
21111 		 * Honor the RTF_SETSRC flag for multicast packets,
21112 		 * if allowed by the setsrc reminder.
21113 		 */
21114 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21115 			ipha->ipha_src = ire->ire_src_addr;
21116 		}
21117 
21118 		/*
21119 		 * Unconditionally force the TTL to 1 for
21120 		 * multirouted multicast packets:
21121 		 * multirouted multicast should not cross
21122 		 * multicast routers.
21123 		 */
21124 		if (ire->ire_flags & RTF_MULTIRT) {
21125 			if (ipha->ipha_ttl > 1) {
21126 				ip2dbg(("ip_wput: forcing multicast "
21127 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21128 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21129 				ipha->ipha_ttl = 1;
21130 			}
21131 		}
21132 	} else {
21133 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21134 		if ((ire != NULL) && (ire->ire_type &
21135 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21136 			ignore_dontroute = B_TRUE;
21137 			ignore_nexthop = B_TRUE;
21138 		}
21139 		if (ire != NULL) {
21140 			ire_refrele(ire);
21141 			ire = NULL;
21142 		}
21143 		/*
21144 		 * Guard against coming in from arp in which case conn is NULL.
21145 		 * Also guard against non M_DATA with dontroute set but
21146 		 * destined to local, loopback or broadcast addresses.
21147 		 */
21148 		if (connp != NULL && connp->conn_dontroute &&
21149 		    !ignore_dontroute) {
21150 dontroute:
21151 			/*
21152 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21153 			 * routing protocols from seeing false direct
21154 			 * connectivity.
21155 			 */
21156 			ipha->ipha_ttl = 1;
21157 			/*
21158 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21159 			 * along with SO_DONTROUTE, higher precedence is
21160 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21161 			 */
21162 			if (connp->conn_xmit_if_ill == NULL) {
21163 				/* If suitable ipif not found, drop packet */
21164 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21165 				    ipst);
21166 				if (dst_ipif == NULL) {
21167 					ip1dbg(("ip_wput: no route for "
21168 					    "dst using SO_DONTROUTE\n"));
21169 					BUMP_MIB(&ipst->ips_ip_mib,
21170 					    ipIfStatsOutNoRoutes);
21171 					mp->b_prev = mp->b_next = NULL;
21172 					if (first_mp == NULL)
21173 						first_mp = mp;
21174 					goto drop_pkt;
21175 				} else {
21176 					/*
21177 					 * If suitable ipif has been found, set
21178 					 * xmit_ill to the corresponding
21179 					 * ipif_ill because we'll be following
21180 					 * the IP_XMIT_IF logic.
21181 					 */
21182 					ASSERT(xmit_ill == NULL);
21183 					xmit_ill = dst_ipif->ipif_ill;
21184 					mutex_enter(&xmit_ill->ill_lock);
21185 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21186 						mutex_exit(&xmit_ill->ill_lock);
21187 						xmit_ill = NULL;
21188 						ipif_refrele(dst_ipif);
21189 						ip1dbg(("ip_wput: no route for"
21190 						    " dst using"
21191 						    " SO_DONTROUTE\n"));
21192 						BUMP_MIB(&ipst->ips_ip_mib,
21193 						    ipIfStatsOutNoRoutes);
21194 						mp->b_prev = mp->b_next = NULL;
21195 						if (first_mp == NULL)
21196 							first_mp = mp;
21197 						goto drop_pkt;
21198 					}
21199 					ill_refhold_locked(xmit_ill);
21200 					mutex_exit(&xmit_ill->ill_lock);
21201 					ipif_refrele(dst_ipif);
21202 				}
21203 			}
21204 
21205 		}
21206 		/*
21207 		 * If we are bound to IPIF_NOFAILOVER address, look for
21208 		 * an IRE_CACHE matching the ill.
21209 		 */
21210 send_from_ill:
21211 		if (attach_ill != NULL) {
21212 			ipif_t	*attach_ipif;
21213 
21214 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21215 
21216 			/*
21217 			 * Check if we need an ire that will not be
21218 			 * looked up by anybody else i.e. HIDDEN.
21219 			 */
21220 			if (ill_is_probeonly(attach_ill)) {
21221 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21222 			}
21223 
21224 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21225 			if (attach_ipif == NULL) {
21226 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21227 				goto discard_pkt;
21228 			}
21229 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21230 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21231 			ipif_refrele(attach_ipif);
21232 		} else if (xmit_ill != NULL || (connp != NULL &&
21233 		    connp->conn_xmit_if_ill != NULL)) {
21234 			/*
21235 			 * Mark this packet as originated locally
21236 			 */
21237 			mp->b_prev = mp->b_next = NULL;
21238 			/*
21239 			 * xmit_ill could be NULL if SO_DONTROUTE
21240 			 * is also set.
21241 			 */
21242 			if (xmit_ill == NULL) {
21243 				xmit_ill = conn_get_held_ill(connp,
21244 				    &connp->conn_xmit_if_ill, &err);
21245 				if (err == ILL_LOOKUP_FAILED) {
21246 					BUMP_MIB(&ipst->ips_ip_mib,
21247 					    ipIfStatsOutDiscards);
21248 					if (need_decref)
21249 						CONN_DEC_REF(connp);
21250 					freemsg(first_mp);
21251 					return;
21252 				}
21253 				if (xmit_ill == NULL) {
21254 					if (connp->conn_dontroute)
21255 						goto dontroute;
21256 					goto send_from_ill;
21257 				}
21258 			}
21259 			/*
21260 			 * Could be SO_DONTROUTE case also.
21261 			 * check at least one interface is UP as
21262 			 * specified by this ILL
21263 			 */
21264 			if (xmit_ill->ill_ipif_up_count > 0) {
21265 				ipif_t *ipif;
21266 
21267 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21268 				if (ipif == NULL) {
21269 					ip1dbg(("ip_output: "
21270 					    "xmit_ill NULL ipif\n"));
21271 					goto drop_pkt;
21272 				}
21273 				/*
21274 				 * Look for a ire that is part of the group,
21275 				 * if found use it else call ip_newroute_ipif.
21276 				 * IPCL_ZONEID is not used for matching because
21277 				 * IP_ALLZONES option is valid only when the
21278 				 * ill is accessible from all zones i.e has a
21279 				 * valid ipif in all zones.
21280 				 */
21281 				match_flags = MATCH_IRE_ILL_GROUP |
21282 				    MATCH_IRE_SECATTR;
21283 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21284 				    MBLK_GETLABEL(mp), match_flags, ipst);
21285 				/*
21286 				 * If an ire exists use it or else create
21287 				 * an ire but don't add it to the cache.
21288 				 * Adding an ire may cause issues with
21289 				 * asymmetric routing.
21290 				 * In case of multiroute always act as if
21291 				 * ire does not exist.
21292 				 */
21293 				if (ire == NULL ||
21294 				    ire->ire_flags & RTF_MULTIRT) {
21295 					if (ire != NULL)
21296 						ire_refrele(ire);
21297 					ip_newroute_ipif(q, first_mp, ipif,
21298 					    dst, connp, 0, zoneid, infop);
21299 					ipif_refrele(ipif);
21300 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21301 					ill_refrele(xmit_ill);
21302 					if (need_decref)
21303 						CONN_DEC_REF(connp);
21304 					return;
21305 				}
21306 				ipif_refrele(ipif);
21307 			} else {
21308 				goto drop_pkt;
21309 			}
21310 		} else if (ip_nexthop || (connp != NULL &&
21311 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21312 			if (!ip_nexthop) {
21313 				ip_nexthop = B_TRUE;
21314 				nexthop_addr = connp->conn_nexthop_v4;
21315 			}
21316 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21317 			    MATCH_IRE_GW;
21318 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21319 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21320 		} else {
21321 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21322 			    ipst);
21323 		}
21324 		if (!ire) {
21325 			/*
21326 			 * Make sure we don't load spread if this
21327 			 * is IPIF_NOFAILOVER case.
21328 			 */
21329 			if ((attach_ill != NULL) ||
21330 			    (ip_nexthop && !ignore_nexthop)) {
21331 				if (mctl_present) {
21332 					io = (ipsec_out_t *)first_mp->b_rptr;
21333 					ASSERT(first_mp->b_datap->db_type ==
21334 					    M_CTL);
21335 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21336 				} else {
21337 					ASSERT(mp == first_mp);
21338 					first_mp = allocb(
21339 					    sizeof (ipsec_info_t), BPRI_HI);
21340 					if (first_mp == NULL) {
21341 						first_mp = mp;
21342 						goto discard_pkt;
21343 					}
21344 					first_mp->b_datap->db_type = M_CTL;
21345 					first_mp->b_wptr +=
21346 					    sizeof (ipsec_info_t);
21347 					/* ipsec_out_secure is B_FALSE now */
21348 					bzero(first_mp->b_rptr,
21349 					    sizeof (ipsec_info_t));
21350 					io = (ipsec_out_t *)first_mp->b_rptr;
21351 					io->ipsec_out_type = IPSEC_OUT;
21352 					io->ipsec_out_len =
21353 					    sizeof (ipsec_out_t);
21354 					io->ipsec_out_use_global_policy =
21355 					    B_TRUE;
21356 					io->ipsec_out_ns = ipst->ips_netstack;
21357 					first_mp->b_cont = mp;
21358 					mctl_present = B_TRUE;
21359 				}
21360 				if (attach_ill != NULL) {
21361 					io->ipsec_out_ill_index = attach_ill->
21362 					    ill_phyint->phyint_ifindex;
21363 					io->ipsec_out_attach_if = B_TRUE;
21364 				} else {
21365 					io->ipsec_out_ip_nexthop = ip_nexthop;
21366 					io->ipsec_out_nexthop_addr =
21367 					    nexthop_addr;
21368 				}
21369 			}
21370 noirefound:
21371 			/*
21372 			 * Mark this packet as having originated on
21373 			 * this machine.  This will be noted in
21374 			 * ire_add_then_send, which needs to know
21375 			 * whether to run it back through ip_wput or
21376 			 * ip_rput following successful resolution.
21377 			 */
21378 			mp->b_prev = NULL;
21379 			mp->b_next = NULL;
21380 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21381 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21382 			    "ip_wput_end: q %p (%S)", q, "newroute");
21383 			if (attach_ill != NULL)
21384 				ill_refrele(attach_ill);
21385 			if (xmit_ill != NULL)
21386 				ill_refrele(xmit_ill);
21387 			if (need_decref)
21388 				CONN_DEC_REF(connp);
21389 			return;
21390 		}
21391 	}
21392 
21393 	/* We now know where we are going with it. */
21394 
21395 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21396 	    "ip_wput_end: q %p (%S)", q, "end");
21397 
21398 	/*
21399 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21400 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21401 	 */
21402 	if (ire->ire_flags & RTF_MULTIRT) {
21403 		/*
21404 		 * Force the TTL of multirouted packets if required.
21405 		 * The TTL of such packets is bounded by the
21406 		 * ip_multirt_ttl ndd variable.
21407 		 */
21408 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21409 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21410 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21411 			    "(was %d), dst 0x%08x\n",
21412 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21413 			    ntohl(ire->ire_addr)));
21414 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21415 		}
21416 		/*
21417 		 * At this point, we check to see if there are any pending
21418 		 * unresolved routes. ire_multirt_resolvable()
21419 		 * checks in O(n) that all IRE_OFFSUBNET ire
21420 		 * entries for the packet's destination and
21421 		 * flagged RTF_MULTIRT are currently resolved.
21422 		 * If some remain unresolved, we make a copy
21423 		 * of the current message. It will be used
21424 		 * to initiate additional route resolutions.
21425 		 */
21426 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21427 		    MBLK_GETLABEL(first_mp), ipst);
21428 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21429 		    "multirt_need_resolve %d, first_mp %p\n",
21430 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21431 		if (multirt_need_resolve) {
21432 			copy_mp = copymsg(first_mp);
21433 			if (copy_mp != NULL) {
21434 				MULTIRT_DEBUG_TAG(copy_mp);
21435 			}
21436 		}
21437 	}
21438 
21439 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21440 	/*
21441 	 * Try to resolve another multiroute if
21442 	 * ire_multirt_resolvable() deemed it necessary.
21443 	 * At this point, we need to distinguish
21444 	 * multicasts from other packets. For multicasts,
21445 	 * we call ip_newroute_ipif() and request that both
21446 	 * multirouting and setsrc flags are checked.
21447 	 */
21448 	if (copy_mp != NULL) {
21449 		if (CLASSD(dst)) {
21450 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21451 			if (ipif) {
21452 				ASSERT(infop->ip_opt_ill_index == 0);
21453 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21454 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21455 				ipif_refrele(ipif);
21456 			} else {
21457 				MULTIRT_DEBUG_UNTAG(copy_mp);
21458 				freemsg(copy_mp);
21459 				copy_mp = NULL;
21460 			}
21461 		} else {
21462 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21463 		}
21464 	}
21465 	if (attach_ill != NULL)
21466 		ill_refrele(attach_ill);
21467 	if (xmit_ill != NULL)
21468 		ill_refrele(xmit_ill);
21469 	if (need_decref)
21470 		CONN_DEC_REF(connp);
21471 	return;
21472 
21473 icmp_parameter_problem:
21474 	/* could not have originated externally */
21475 	ASSERT(mp->b_prev == NULL);
21476 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21477 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21478 		/* it's the IP header length that's in trouble */
21479 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21480 		first_mp = NULL;
21481 	}
21482 
21483 discard_pkt:
21484 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21485 drop_pkt:
21486 	ip1dbg(("ip_wput: dropped packet\n"));
21487 	if (ire != NULL)
21488 		ire_refrele(ire);
21489 	if (need_decref)
21490 		CONN_DEC_REF(connp);
21491 	freemsg(first_mp);
21492 	if (attach_ill != NULL)
21493 		ill_refrele(attach_ill);
21494 	if (xmit_ill != NULL)
21495 		ill_refrele(xmit_ill);
21496 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21497 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21498 }
21499 
21500 /*
21501  * If this is a conn_t queue, then we pass in the conn. This includes the
21502  * zoneid.
21503  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21504  * in which case we use the global zoneid since those are all part of
21505  * the global zone.
21506  */
21507 void
21508 ip_wput(queue_t *q, mblk_t *mp)
21509 {
21510 	if (CONN_Q(q))
21511 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21512 	else
21513 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21514 }
21515 
21516 /*
21517  *
21518  * The following rules must be observed when accessing any ipif or ill
21519  * that has been cached in the conn. Typically conn_nofailover_ill,
21520  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21521  *
21522  * Access: The ipif or ill pointed to from the conn can be accessed under
21523  * the protection of the conn_lock or after it has been refheld under the
21524  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21525  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21526  * The reason for this is that a concurrent unplumb could actually be
21527  * cleaning up these cached pointers by walking the conns and might have
21528  * finished cleaning up the conn in question. The macros check that an
21529  * unplumb has not yet started on the ipif or ill.
21530  *
21531  * Caching: An ipif or ill pointer may be cached in the conn only after
21532  * making sure that an unplumb has not started. So the caching is done
21533  * while holding both the conn_lock and the ill_lock and after using the
21534  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21535  * flag before starting the cleanup of conns.
21536  *
21537  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21538  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21539  * or a reference to the ipif or a reference to an ire that references the
21540  * ipif. An ipif does not change its ill except for failover/failback. Since
21541  * failover/failback happens only after bringing down the ipif and making sure
21542  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21543  * the above holds.
21544  */
21545 ipif_t *
21546 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21547 {
21548 	ipif_t	*ipif;
21549 	ill_t	*ill;
21550 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21551 
21552 	*err = 0;
21553 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21554 	mutex_enter(&connp->conn_lock);
21555 	ipif = *ipifp;
21556 	if (ipif != NULL) {
21557 		ill = ipif->ipif_ill;
21558 		mutex_enter(&ill->ill_lock);
21559 		if (IPIF_CAN_LOOKUP(ipif)) {
21560 			ipif_refhold_locked(ipif);
21561 			mutex_exit(&ill->ill_lock);
21562 			mutex_exit(&connp->conn_lock);
21563 			rw_exit(&ipst->ips_ill_g_lock);
21564 			return (ipif);
21565 		} else {
21566 			*err = IPIF_LOOKUP_FAILED;
21567 		}
21568 		mutex_exit(&ill->ill_lock);
21569 	}
21570 	mutex_exit(&connp->conn_lock);
21571 	rw_exit(&ipst->ips_ill_g_lock);
21572 	return (NULL);
21573 }
21574 
21575 ill_t *
21576 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21577 {
21578 	ill_t	*ill;
21579 
21580 	*err = 0;
21581 	mutex_enter(&connp->conn_lock);
21582 	ill = *illp;
21583 	if (ill != NULL) {
21584 		mutex_enter(&ill->ill_lock);
21585 		if (ILL_CAN_LOOKUP(ill)) {
21586 			ill_refhold_locked(ill);
21587 			mutex_exit(&ill->ill_lock);
21588 			mutex_exit(&connp->conn_lock);
21589 			return (ill);
21590 		} else {
21591 			*err = ILL_LOOKUP_FAILED;
21592 		}
21593 		mutex_exit(&ill->ill_lock);
21594 	}
21595 	mutex_exit(&connp->conn_lock);
21596 	return (NULL);
21597 }
21598 
21599 static int
21600 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21601 {
21602 	ill_t	*ill;
21603 
21604 	ill = ipif->ipif_ill;
21605 	mutex_enter(&connp->conn_lock);
21606 	mutex_enter(&ill->ill_lock);
21607 	if (IPIF_CAN_LOOKUP(ipif)) {
21608 		*ipifp = ipif;
21609 		mutex_exit(&ill->ill_lock);
21610 		mutex_exit(&connp->conn_lock);
21611 		return (0);
21612 	}
21613 	mutex_exit(&ill->ill_lock);
21614 	mutex_exit(&connp->conn_lock);
21615 	return (IPIF_LOOKUP_FAILED);
21616 }
21617 
21618 /*
21619  * This is called if the outbound datagram needs fragmentation.
21620  *
21621  * NOTE : This function does not ire_refrele the ire argument passed in.
21622  */
21623 static void
21624 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21625     ip_stack_t *ipst)
21626 {
21627 	ipha_t		*ipha;
21628 	mblk_t		*mp;
21629 	uint32_t	v_hlen_tos_len;
21630 	uint32_t	max_frag;
21631 	uint32_t	frag_flag;
21632 	boolean_t	dont_use;
21633 
21634 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21635 		mp = ipsec_mp->b_cont;
21636 	} else {
21637 		mp = ipsec_mp;
21638 	}
21639 
21640 	ipha = (ipha_t *)mp->b_rptr;
21641 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21642 
21643 #ifdef	_BIG_ENDIAN
21644 #define	V_HLEN	(v_hlen_tos_len >> 24)
21645 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21646 #else
21647 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21648 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21649 #endif
21650 
21651 #ifndef SPEED_BEFORE_SAFETY
21652 	/*
21653 	 * Check that ipha_length is consistent with
21654 	 * the mblk length
21655 	 */
21656 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21657 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21658 		    LENGTH, msgdsize(mp)));
21659 		freemsg(ipsec_mp);
21660 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21661 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21662 		    "packet length mismatch");
21663 		return;
21664 	}
21665 #endif
21666 	/*
21667 	 * Don't use frag_flag if pre-built packet or source
21668 	 * routed or if multicast (since multicast packets do not solicit
21669 	 * ICMP "packet too big" messages). Get the values of
21670 	 * max_frag and frag_flag atomically by acquiring the
21671 	 * ire_lock.
21672 	 */
21673 	mutex_enter(&ire->ire_lock);
21674 	max_frag = ire->ire_max_frag;
21675 	frag_flag = ire->ire_frag_flag;
21676 	mutex_exit(&ire->ire_lock);
21677 
21678 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21679 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21680 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21681 
21682 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21683 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21684 }
21685 
21686 /*
21687  * Used for deciding the MSS size for the upper layer. Thus
21688  * we need to check the outbound policy values in the conn.
21689  */
21690 int
21691 conn_ipsec_length(conn_t *connp)
21692 {
21693 	ipsec_latch_t *ipl;
21694 
21695 	ipl = connp->conn_latch;
21696 	if (ipl == NULL)
21697 		return (0);
21698 
21699 	if (ipl->ipl_out_policy == NULL)
21700 		return (0);
21701 
21702 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21703 }
21704 
21705 /*
21706  * Returns an estimate of the IPsec headers size. This is used if
21707  * we don't want to call into IPsec to get the exact size.
21708  */
21709 int
21710 ipsec_out_extra_length(mblk_t *ipsec_mp)
21711 {
21712 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21713 	ipsec_action_t *a;
21714 
21715 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21716 	if (!io->ipsec_out_secure)
21717 		return (0);
21718 
21719 	a = io->ipsec_out_act;
21720 
21721 	if (a == NULL) {
21722 		ASSERT(io->ipsec_out_policy != NULL);
21723 		a = io->ipsec_out_policy->ipsp_act;
21724 	}
21725 	ASSERT(a != NULL);
21726 
21727 	return (a->ipa_ovhd);
21728 }
21729 
21730 /*
21731  * Returns an estimate of the IPsec headers size. This is used if
21732  * we don't want to call into IPsec to get the exact size.
21733  */
21734 int
21735 ipsec_in_extra_length(mblk_t *ipsec_mp)
21736 {
21737 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21738 	ipsec_action_t *a;
21739 
21740 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21741 
21742 	a = ii->ipsec_in_action;
21743 	return (a == NULL ? 0 : a->ipa_ovhd);
21744 }
21745 
21746 /*
21747  * If there are any source route options, return the true final
21748  * destination. Otherwise, return the destination.
21749  */
21750 ipaddr_t
21751 ip_get_dst(ipha_t *ipha)
21752 {
21753 	ipoptp_t	opts;
21754 	uchar_t		*opt;
21755 	uint8_t		optval;
21756 	uint8_t		optlen;
21757 	ipaddr_t	dst;
21758 	uint32_t off;
21759 
21760 	dst = ipha->ipha_dst;
21761 
21762 	if (IS_SIMPLE_IPH(ipha))
21763 		return (dst);
21764 
21765 	for (optval = ipoptp_first(&opts, ipha);
21766 	    optval != IPOPT_EOL;
21767 	    optval = ipoptp_next(&opts)) {
21768 		opt = opts.ipoptp_cur;
21769 		optlen = opts.ipoptp_len;
21770 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21771 		switch (optval) {
21772 		case IPOPT_SSRR:
21773 		case IPOPT_LSRR:
21774 			off = opt[IPOPT_OFFSET];
21775 			/*
21776 			 * If one of the conditions is true, it means
21777 			 * end of options and dst already has the right
21778 			 * value.
21779 			 */
21780 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21781 				off = optlen - IP_ADDR_LEN;
21782 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21783 			}
21784 			return (dst);
21785 		default:
21786 			break;
21787 		}
21788 	}
21789 
21790 	return (dst);
21791 }
21792 
21793 mblk_t *
21794 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21795     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21796 {
21797 	ipsec_out_t	*io;
21798 	mblk_t		*first_mp;
21799 	boolean_t policy_present;
21800 	ip_stack_t	*ipst;
21801 	ipsec_stack_t	*ipss;
21802 
21803 	ASSERT(ire != NULL);
21804 	ipst = ire->ire_ipst;
21805 	ipss = ipst->ips_netstack->netstack_ipsec;
21806 
21807 	first_mp = mp;
21808 	if (mp->b_datap->db_type == M_CTL) {
21809 		io = (ipsec_out_t *)first_mp->b_rptr;
21810 		/*
21811 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21812 		 *
21813 		 * 1) There is per-socket policy (including cached global
21814 		 *    policy) or a policy on the IP-in-IP tunnel.
21815 		 * 2) There is no per-socket policy, but it is
21816 		 *    a multicast packet that needs to go out
21817 		 *    on a specific interface. This is the case
21818 		 *    where (ip_wput and ip_wput_multicast) attaches
21819 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21820 		 *
21821 		 * In case (2) we check with global policy to
21822 		 * see if there is a match and set the ill_index
21823 		 * appropriately so that we can lookup the ire
21824 		 * properly in ip_wput_ipsec_out.
21825 		 */
21826 
21827 		/*
21828 		 * ipsec_out_use_global_policy is set to B_FALSE
21829 		 * in ipsec_in_to_out(). Refer to that function for
21830 		 * details.
21831 		 */
21832 		if ((io->ipsec_out_latch == NULL) &&
21833 		    (io->ipsec_out_use_global_policy)) {
21834 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21835 			    ire, connp, unspec_src, zoneid));
21836 		}
21837 		if (!io->ipsec_out_secure) {
21838 			/*
21839 			 * If this is not a secure packet, drop
21840 			 * the IPSEC_OUT mp and treat it as a clear
21841 			 * packet. This happens when we are sending
21842 			 * a ICMP reply back to a clear packet. See
21843 			 * ipsec_in_to_out() for details.
21844 			 */
21845 			mp = first_mp->b_cont;
21846 			freeb(first_mp);
21847 		}
21848 		return (mp);
21849 	}
21850 	/*
21851 	 * See whether we need to attach a global policy here. We
21852 	 * don't depend on the conn (as it could be null) for deciding
21853 	 * what policy this datagram should go through because it
21854 	 * should have happened in ip_wput if there was some
21855 	 * policy. This normally happens for connections which are not
21856 	 * fully bound preventing us from caching policies in
21857 	 * ip_bind. Packets coming from the TCP listener/global queue
21858 	 * - which are non-hard_bound - could also be affected by
21859 	 * applying policy here.
21860 	 *
21861 	 * If this packet is coming from tcp global queue or listener,
21862 	 * we will be applying policy here.  This may not be *right*
21863 	 * if these packets are coming from the detached connection as
21864 	 * it could have gone in clear before. This happens only if a
21865 	 * TCP connection started when there is no policy and somebody
21866 	 * added policy before it became detached. Thus packets of the
21867 	 * detached connection could go out secure and the other end
21868 	 * would drop it because it will be expecting in clear. The
21869 	 * converse is not true i.e if somebody starts a TCP
21870 	 * connection and deletes the policy, all the packets will
21871 	 * still go out with the policy that existed before deleting
21872 	 * because ip_unbind sends up policy information which is used
21873 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21874 	 * TCP to attach a dummy IPSEC_OUT and set
21875 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21876 	 * affect performance for normal cases, we are not doing it.
21877 	 * Thus, set policy before starting any TCP connections.
21878 	 *
21879 	 * NOTE - We might apply policy even for a hard bound connection
21880 	 * - for which we cached policy in ip_bind - if somebody added
21881 	 * global policy after we inherited the policy in ip_bind.
21882 	 * This means that the packets that were going out in clear
21883 	 * previously would start going secure and hence get dropped
21884 	 * on the other side. To fix this, TCP attaches a dummy
21885 	 * ipsec_out and make sure that we don't apply global policy.
21886 	 */
21887 	if (ipha != NULL)
21888 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21889 	else
21890 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21891 	if (!policy_present)
21892 		return (mp);
21893 
21894 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21895 	    zoneid));
21896 }
21897 
21898 ire_t *
21899 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21900 {
21901 	ipaddr_t addr;
21902 	ire_t *save_ire;
21903 	irb_t *irb;
21904 	ill_group_t *illgrp;
21905 	int	err;
21906 
21907 	save_ire = ire;
21908 	addr = ire->ire_addr;
21909 
21910 	ASSERT(ire->ire_type == IRE_BROADCAST);
21911 
21912 	illgrp = connp->conn_outgoing_ill->ill_group;
21913 	if (illgrp == NULL) {
21914 		*conn_outgoing_ill = conn_get_held_ill(connp,
21915 		    &connp->conn_outgoing_ill, &err);
21916 		if (err == ILL_LOOKUP_FAILED) {
21917 			ire_refrele(save_ire);
21918 			return (NULL);
21919 		}
21920 		return (save_ire);
21921 	}
21922 	/*
21923 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21924 	 * If it is part of the group, we need to send on the ire
21925 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21926 	 * to this group. This is okay as IP_BOUND_IF really means
21927 	 * any ill in the group. We depend on the fact that the
21928 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21929 	 * if such an ire exists. This is possible only if you have
21930 	 * at least one ill in the group that has not failed.
21931 	 *
21932 	 * First get to the ire that matches the address and group.
21933 	 *
21934 	 * We don't look for an ire with a matching zoneid because a given zone
21935 	 * won't always have broadcast ires on all ills in the group.
21936 	 */
21937 	irb = ire->ire_bucket;
21938 	rw_enter(&irb->irb_lock, RW_READER);
21939 	if (ire->ire_marks & IRE_MARK_NORECV) {
21940 		/*
21941 		 * If the current zone only has an ire broadcast for this
21942 		 * address marked NORECV, the ire we want is ahead in the
21943 		 * bucket, so we look it up deliberately ignoring the zoneid.
21944 		 */
21945 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21946 			if (ire->ire_addr != addr)
21947 				continue;
21948 			/* skip over deleted ires */
21949 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21950 				continue;
21951 		}
21952 	}
21953 	while (ire != NULL) {
21954 		/*
21955 		 * If a new interface is coming up, we could end up
21956 		 * seeing the loopback ire and the non-loopback ire
21957 		 * may not have been added yet. So check for ire_stq
21958 		 */
21959 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21960 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21961 			break;
21962 		}
21963 		ire = ire->ire_next;
21964 	}
21965 	if (ire != NULL && ire->ire_addr == addr &&
21966 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21967 		IRE_REFHOLD(ire);
21968 		rw_exit(&irb->irb_lock);
21969 		ire_refrele(save_ire);
21970 		*conn_outgoing_ill = ire_to_ill(ire);
21971 		/*
21972 		 * Refhold the ill to make the conn_outgoing_ill
21973 		 * independent of the ire. ip_wput_ire goes in a loop
21974 		 * and may refrele the ire. Since we have an ire at this
21975 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21976 		 */
21977 		ill_refhold(*conn_outgoing_ill);
21978 		return (ire);
21979 	}
21980 	rw_exit(&irb->irb_lock);
21981 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21982 	/*
21983 	 * If we can't find a suitable ire, return the original ire.
21984 	 */
21985 	return (save_ire);
21986 }
21987 
21988 /*
21989  * This function does the ire_refrele of the ire passed in as the
21990  * argument. As this function looks up more ires i.e broadcast ires,
21991  * it needs to REFRELE them. Currently, for simplicity we don't
21992  * differentiate the one passed in and looked up here. We always
21993  * REFRELE.
21994  * IPQoS Notes:
21995  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21996  * IPsec packets are done in ipsec_out_process.
21997  *
21998  */
21999 void
22000 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22001     zoneid_t zoneid)
22002 {
22003 	ipha_t		*ipha;
22004 #define	rptr	((uchar_t *)ipha)
22005 	queue_t		*stq;
22006 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22007 	uint32_t	v_hlen_tos_len;
22008 	uint32_t	ttl_protocol;
22009 	ipaddr_t	src;
22010 	ipaddr_t	dst;
22011 	uint32_t	cksum;
22012 	ipaddr_t	orig_src;
22013 	ire_t		*ire1;
22014 	mblk_t		*next_mp;
22015 	uint_t		hlen;
22016 	uint16_t	*up;
22017 	uint32_t	max_frag = ire->ire_max_frag;
22018 	ill_t		*ill = ire_to_ill(ire);
22019 	int		clusterwide;
22020 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22021 	int		ipsec_len;
22022 	mblk_t		*first_mp;
22023 	ipsec_out_t	*io;
22024 	boolean_t	conn_dontroute;		/* conn value for multicast */
22025 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22026 	boolean_t	multicast_forward;	/* Should we forward ? */
22027 	boolean_t	unspec_src;
22028 	ill_t		*conn_outgoing_ill = NULL;
22029 	ill_t		*ire_ill;
22030 	ill_t		*ire1_ill;
22031 	ill_t		*out_ill;
22032 	uint32_t 	ill_index = 0;
22033 	boolean_t	multirt_send = B_FALSE;
22034 	int		err;
22035 	ipxmit_state_t	pktxmit_state;
22036 	ip_stack_t	*ipst = ire->ire_ipst;
22037 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22038 
22039 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22040 	    "ip_wput_ire_start: q %p", q);
22041 
22042 	multicast_forward = B_FALSE;
22043 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22044 
22045 	if (ire->ire_flags & RTF_MULTIRT) {
22046 		/*
22047 		 * Multirouting case. The bucket where ire is stored
22048 		 * probably holds other RTF_MULTIRT flagged ire
22049 		 * to the destination. In this call to ip_wput_ire,
22050 		 * we attempt to send the packet through all
22051 		 * those ires. Thus, we first ensure that ire is the
22052 		 * first RTF_MULTIRT ire in the bucket,
22053 		 * before walking the ire list.
22054 		 */
22055 		ire_t *first_ire;
22056 		irb_t *irb = ire->ire_bucket;
22057 		ASSERT(irb != NULL);
22058 
22059 		/* Make sure we do not omit any multiroute ire. */
22060 		IRB_REFHOLD(irb);
22061 		for (first_ire = irb->irb_ire;
22062 		    first_ire != NULL;
22063 		    first_ire = first_ire->ire_next) {
22064 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22065 			    (first_ire->ire_addr == ire->ire_addr) &&
22066 			    !(first_ire->ire_marks &
22067 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22068 				break;
22069 			}
22070 		}
22071 
22072 		if ((first_ire != NULL) && (first_ire != ire)) {
22073 			IRE_REFHOLD(first_ire);
22074 			ire_refrele(ire);
22075 			ire = first_ire;
22076 			ill = ire_to_ill(ire);
22077 		}
22078 		IRB_REFRELE(irb);
22079 	}
22080 
22081 	/*
22082 	 * conn_outgoing_ill is used only in the broadcast loop.
22083 	 * for performance we don't grab the mutexs in the fastpath
22084 	 */
22085 	if ((connp != NULL) &&
22086 	    (connp->conn_xmit_if_ill == NULL) &&
22087 	    (ire->ire_type == IRE_BROADCAST) &&
22088 	    ((connp->conn_nofailover_ill != NULL) ||
22089 	    (connp->conn_outgoing_ill != NULL))) {
22090 		/*
22091 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22092 		 * option. So, see if this endpoint is bound to a
22093 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22094 		 * that if the interface is failed, we will still send
22095 		 * the packet on the same ill which is what we want.
22096 		 */
22097 		conn_outgoing_ill = conn_get_held_ill(connp,
22098 		    &connp->conn_nofailover_ill, &err);
22099 		if (err == ILL_LOOKUP_FAILED) {
22100 			ire_refrele(ire);
22101 			freemsg(mp);
22102 			return;
22103 		}
22104 		if (conn_outgoing_ill == NULL) {
22105 			/*
22106 			 * Choose a good ill in the group to send the
22107 			 * packets on.
22108 			 */
22109 			ire = conn_set_outgoing_ill(connp, ire,
22110 			    &conn_outgoing_ill);
22111 			if (ire == NULL) {
22112 				freemsg(mp);
22113 				return;
22114 			}
22115 		}
22116 	}
22117 
22118 	if (mp->b_datap->db_type != M_CTL) {
22119 		ipha = (ipha_t *)mp->b_rptr;
22120 	} else {
22121 		io = (ipsec_out_t *)mp->b_rptr;
22122 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22123 		ASSERT(zoneid == io->ipsec_out_zoneid);
22124 		ASSERT(zoneid != ALL_ZONES);
22125 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22126 		dst = ipha->ipha_dst;
22127 		/*
22128 		 * For the multicast case, ipsec_out carries conn_dontroute and
22129 		 * conn_multicast_loop as conn may not be available here. We
22130 		 * need this for multicast loopback and forwarding which is done
22131 		 * later in the code.
22132 		 */
22133 		if (CLASSD(dst)) {
22134 			conn_dontroute = io->ipsec_out_dontroute;
22135 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22136 			/*
22137 			 * If conn_dontroute is not set or conn_multicast_loop
22138 			 * is set, we need to do forwarding/loopback. For
22139 			 * datagrams from ip_wput_multicast, conn_dontroute is
22140 			 * set to B_TRUE and conn_multicast_loop is set to
22141 			 * B_FALSE so that we neither do forwarding nor
22142 			 * loopback.
22143 			 */
22144 			if (!conn_dontroute || conn_multicast_loop)
22145 				multicast_forward = B_TRUE;
22146 		}
22147 	}
22148 
22149 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22150 	    ire->ire_zoneid != ALL_ZONES) {
22151 		/*
22152 		 * When a zone sends a packet to another zone, we try to deliver
22153 		 * the packet under the same conditions as if the destination
22154 		 * was a real node on the network. To do so, we look for a
22155 		 * matching route in the forwarding table.
22156 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22157 		 * ip_newroute() does.
22158 		 * Note that IRE_LOCAL are special, since they are used
22159 		 * when the zoneid doesn't match in some cases. This means that
22160 		 * we need to handle ipha_src differently since ire_src_addr
22161 		 * belongs to the receiving zone instead of the sending zone.
22162 		 * When ip_restrict_interzone_loopback is set, then
22163 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22164 		 * for loopback between zones when the logical "Ethernet" would
22165 		 * have looped them back.
22166 		 */
22167 		ire_t *src_ire;
22168 
22169 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22170 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22171 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22172 		if (src_ire != NULL &&
22173 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22174 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22175 		    ire_local_same_ill_group(ire, src_ire))) {
22176 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22177 				ipha->ipha_src = src_ire->ire_src_addr;
22178 			ire_refrele(src_ire);
22179 		} else {
22180 			ire_refrele(ire);
22181 			if (conn_outgoing_ill != NULL)
22182 				ill_refrele(conn_outgoing_ill);
22183 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22184 			if (src_ire != NULL) {
22185 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22186 					ire_refrele(src_ire);
22187 					freemsg(mp);
22188 					return;
22189 				}
22190 				ire_refrele(src_ire);
22191 			}
22192 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22193 				/* Failed */
22194 				freemsg(mp);
22195 				return;
22196 			}
22197 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22198 			    ipst);
22199 			return;
22200 		}
22201 	}
22202 
22203 	if (mp->b_datap->db_type == M_CTL ||
22204 	    ipss->ipsec_outbound_v4_policy_present) {
22205 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22206 		    unspec_src, zoneid);
22207 		if (mp == NULL) {
22208 			ire_refrele(ire);
22209 			if (conn_outgoing_ill != NULL)
22210 				ill_refrele(conn_outgoing_ill);
22211 			return;
22212 		}
22213 	}
22214 
22215 	first_mp = mp;
22216 	ipsec_len = 0;
22217 
22218 	if (first_mp->b_datap->db_type == M_CTL) {
22219 		io = (ipsec_out_t *)first_mp->b_rptr;
22220 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22221 		mp = first_mp->b_cont;
22222 		ipsec_len = ipsec_out_extra_length(first_mp);
22223 		ASSERT(ipsec_len >= 0);
22224 		/* We already picked up the zoneid from the M_CTL above */
22225 		ASSERT(zoneid == io->ipsec_out_zoneid);
22226 		ASSERT(zoneid != ALL_ZONES);
22227 
22228 		/*
22229 		 * Drop M_CTL here if IPsec processing is not needed.
22230 		 * (Non-IPsec use of M_CTL extracted any information it
22231 		 * needed above).
22232 		 */
22233 		if (ipsec_len == 0) {
22234 			freeb(first_mp);
22235 			first_mp = mp;
22236 		}
22237 	}
22238 
22239 	/*
22240 	 * Fast path for ip_wput_ire
22241 	 */
22242 
22243 	ipha = (ipha_t *)mp->b_rptr;
22244 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22245 	dst = ipha->ipha_dst;
22246 
22247 	/*
22248 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22249 	 * if the socket is a SOCK_RAW type. The transport checksum should
22250 	 * be provided in the pre-built packet, so we don't need to compute it.
22251 	 * Also, other application set flags, like DF, should not be altered.
22252 	 * Other transport MUST pass down zero.
22253 	 */
22254 	ip_hdr_included = ipha->ipha_ident;
22255 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22256 
22257 	if (CLASSD(dst)) {
22258 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22259 		    ntohl(dst),
22260 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22261 		    ntohl(ire->ire_addr)));
22262 	}
22263 
22264 /* Macros to extract header fields from data already in registers */
22265 #ifdef	_BIG_ENDIAN
22266 #define	V_HLEN	(v_hlen_tos_len >> 24)
22267 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22268 #define	PROTO	(ttl_protocol & 0xFF)
22269 #else
22270 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22271 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22272 #define	PROTO	(ttl_protocol >> 8)
22273 #endif
22274 
22275 
22276 	orig_src = src = ipha->ipha_src;
22277 	/* (The loop back to "another" is explained down below.) */
22278 another:;
22279 	/*
22280 	 * Assign an ident value for this packet.  We assign idents on
22281 	 * a per destination basis out of the IRE.  There could be
22282 	 * other threads targeting the same destination, so we have to
22283 	 * arrange for a atomic increment.  Note that we use a 32-bit
22284 	 * atomic add because it has better performance than its
22285 	 * 16-bit sibling.
22286 	 *
22287 	 * If running in cluster mode and if the source address
22288 	 * belongs to a replicated service then vector through
22289 	 * cl_inet_ipident vector to allocate ip identifier
22290 	 * NOTE: This is a contract private interface with the
22291 	 * clustering group.
22292 	 */
22293 	clusterwide = 0;
22294 	if (cl_inet_ipident) {
22295 		ASSERT(cl_inet_isclusterwide);
22296 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22297 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22298 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22299 			    AF_INET, (uint8_t *)(uintptr_t)src,
22300 			    (uint8_t *)(uintptr_t)dst);
22301 			clusterwide = 1;
22302 		}
22303 	}
22304 	if (!clusterwide) {
22305 		ipha->ipha_ident =
22306 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22307 	}
22308 
22309 #ifndef _BIG_ENDIAN
22310 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22311 #endif
22312 
22313 	/*
22314 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22315 	 * This is needed to obey conn_unspec_src when packets go through
22316 	 * ip_newroute + arp.
22317 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22318 	 */
22319 	if (src == INADDR_ANY && !unspec_src) {
22320 		/*
22321 		 * Assign the appropriate source address from the IRE if none
22322 		 * was specified.
22323 		 */
22324 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22325 
22326 		/*
22327 		 * With IP multipathing, broadcast packets are sent on the ire
22328 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22329 		 * the group. However, this ire might not be in the same zone so
22330 		 * we can't always use its source address. We look for a
22331 		 * broadcast ire in the same group and in the right zone.
22332 		 */
22333 		if (ire->ire_type == IRE_BROADCAST &&
22334 		    ire->ire_zoneid != zoneid) {
22335 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22336 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22337 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22338 			if (src_ire != NULL) {
22339 				src = src_ire->ire_src_addr;
22340 				ire_refrele(src_ire);
22341 			} else {
22342 				ire_refrele(ire);
22343 				if (conn_outgoing_ill != NULL)
22344 					ill_refrele(conn_outgoing_ill);
22345 				freemsg(first_mp);
22346 				if (ill != NULL) {
22347 					BUMP_MIB(ill->ill_ip_mib,
22348 					    ipIfStatsOutDiscards);
22349 				} else {
22350 					BUMP_MIB(&ipst->ips_ip_mib,
22351 					    ipIfStatsOutDiscards);
22352 				}
22353 				return;
22354 			}
22355 		} else {
22356 			src = ire->ire_src_addr;
22357 		}
22358 
22359 		if (connp == NULL) {
22360 			ip1dbg(("ip_wput_ire: no connp and no src "
22361 			    "address for dst 0x%x, using src 0x%x\n",
22362 			    ntohl(dst),
22363 			    ntohl(src)));
22364 		}
22365 		ipha->ipha_src = src;
22366 	}
22367 	stq = ire->ire_stq;
22368 
22369 	/*
22370 	 * We only allow ire chains for broadcasts since there will
22371 	 * be multiple IRE_CACHE entries for the same multicast
22372 	 * address (one per ipif).
22373 	 */
22374 	next_mp = NULL;
22375 
22376 	/* broadcast packet */
22377 	if (ire->ire_type == IRE_BROADCAST)
22378 		goto broadcast;
22379 
22380 	/* loopback ? */
22381 	if (stq == NULL)
22382 		goto nullstq;
22383 
22384 	/* The ill_index for outbound ILL */
22385 	ill_index = Q_TO_INDEX(stq);
22386 
22387 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22388 	ttl_protocol = ((uint16_t *)ipha)[4];
22389 
22390 	/* pseudo checksum (do it in parts for IP header checksum) */
22391 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22392 
22393 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22394 		queue_t *dev_q = stq->q_next;
22395 
22396 		/* flow controlled */
22397 		if ((dev_q->q_next || dev_q->q_first) &&
22398 		    !canput(dev_q))
22399 			goto blocked;
22400 		if ((PROTO == IPPROTO_UDP) &&
22401 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22402 			hlen = (V_HLEN & 0xF) << 2;
22403 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22404 			if (*up != 0) {
22405 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22406 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22407 				/* Software checksum? */
22408 				if (DB_CKSUMFLAGS(mp) == 0) {
22409 					IP_STAT(ipst, ip_out_sw_cksum);
22410 					IP_STAT_UPDATE(ipst,
22411 					    ip_udp_out_sw_cksum_bytes,
22412 					    LENGTH - hlen);
22413 				}
22414 			}
22415 		}
22416 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22417 		hlen = (V_HLEN & 0xF) << 2;
22418 		if (PROTO == IPPROTO_TCP) {
22419 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22420 			/*
22421 			 * The packet header is processed once and for all, even
22422 			 * in the multirouting case. We disable hardware
22423 			 * checksum if the packet is multirouted, as it will be
22424 			 * replicated via several interfaces, and not all of
22425 			 * them may have this capability.
22426 			 */
22427 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22428 			    LENGTH, max_frag, ipsec_len, cksum);
22429 			/* Software checksum? */
22430 			if (DB_CKSUMFLAGS(mp) == 0) {
22431 				IP_STAT(ipst, ip_out_sw_cksum);
22432 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22433 				    LENGTH - hlen);
22434 			}
22435 		} else {
22436 			sctp_hdr_t	*sctph;
22437 
22438 			ASSERT(PROTO == IPPROTO_SCTP);
22439 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22440 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22441 			/*
22442 			 * Zero out the checksum field to ensure proper
22443 			 * checksum calculation.
22444 			 */
22445 			sctph->sh_chksum = 0;
22446 #ifdef	DEBUG
22447 			if (!skip_sctp_cksum)
22448 #endif
22449 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22450 		}
22451 	}
22452 
22453 	/*
22454 	 * If this is a multicast packet and originated from ip_wput
22455 	 * we need to do loopback and forwarding checks. If it comes
22456 	 * from ip_wput_multicast, we SHOULD not do this.
22457 	 */
22458 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22459 
22460 	/* checksum */
22461 	cksum += ttl_protocol;
22462 
22463 	/* fragment the packet */
22464 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22465 		goto fragmentit;
22466 	/*
22467 	 * Don't use frag_flag if packet is pre-built or source
22468 	 * routed or if multicast (since multicast packets do
22469 	 * not solicit ICMP "packet too big" messages).
22470 	 */
22471 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22472 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22473 	    !ip_source_route_included(ipha)) &&
22474 	    !CLASSD(ipha->ipha_dst))
22475 		ipha->ipha_fragment_offset_and_flags |=
22476 		    htons(ire->ire_frag_flag);
22477 
22478 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22479 		/* calculate IP header checksum */
22480 		cksum += ipha->ipha_ident;
22481 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22482 		cksum += ipha->ipha_fragment_offset_and_flags;
22483 
22484 		/* IP options present */
22485 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22486 		if (hlen)
22487 			goto checksumoptions;
22488 
22489 		/* calculate hdr checksum */
22490 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22491 		cksum = ~(cksum + (cksum >> 16));
22492 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22493 	}
22494 	if (ipsec_len != 0) {
22495 		/*
22496 		 * We will do the rest of the processing after
22497 		 * we come back from IPsec in ip_wput_ipsec_out().
22498 		 */
22499 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22500 
22501 		io = (ipsec_out_t *)first_mp->b_rptr;
22502 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22503 		    ill_phyint->phyint_ifindex;
22504 
22505 		ipsec_out_process(q, first_mp, ire, ill_index);
22506 		ire_refrele(ire);
22507 		if (conn_outgoing_ill != NULL)
22508 			ill_refrele(conn_outgoing_ill);
22509 		return;
22510 	}
22511 
22512 	/*
22513 	 * In most cases, the emission loop below is entered only
22514 	 * once. Only in the case where the ire holds the
22515 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22516 	 * flagged ires in the bucket, and send the packet
22517 	 * through all crossed RTF_MULTIRT routes.
22518 	 */
22519 	if (ire->ire_flags & RTF_MULTIRT) {
22520 		multirt_send = B_TRUE;
22521 	}
22522 	do {
22523 		if (multirt_send) {
22524 			irb_t *irb;
22525 			/*
22526 			 * We are in a multiple send case, need to get
22527 			 * the next ire and make a duplicate of the packet.
22528 			 * ire1 holds here the next ire to process in the
22529 			 * bucket. If multirouting is expected,
22530 			 * any non-RTF_MULTIRT ire that has the
22531 			 * right destination address is ignored.
22532 			 */
22533 			irb = ire->ire_bucket;
22534 			ASSERT(irb != NULL);
22535 
22536 			IRB_REFHOLD(irb);
22537 			for (ire1 = ire->ire_next;
22538 			    ire1 != NULL;
22539 			    ire1 = ire1->ire_next) {
22540 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22541 					continue;
22542 				if (ire1->ire_addr != ire->ire_addr)
22543 					continue;
22544 				if (ire1->ire_marks &
22545 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22546 					continue;
22547 
22548 				/* Got one */
22549 				IRE_REFHOLD(ire1);
22550 				break;
22551 			}
22552 			IRB_REFRELE(irb);
22553 
22554 			if (ire1 != NULL) {
22555 				next_mp = copyb(mp);
22556 				if ((next_mp == NULL) ||
22557 				    ((mp->b_cont != NULL) &&
22558 				    ((next_mp->b_cont =
22559 				    dupmsg(mp->b_cont)) == NULL))) {
22560 					freemsg(next_mp);
22561 					next_mp = NULL;
22562 					ire_refrele(ire1);
22563 					ire1 = NULL;
22564 				}
22565 			}
22566 
22567 			/* Last multiroute ire; don't loop anymore. */
22568 			if (ire1 == NULL) {
22569 				multirt_send = B_FALSE;
22570 			}
22571 		}
22572 
22573 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22574 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22575 		    mblk_t *, mp);
22576 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22577 		    ipst->ips_ipv4firewall_physical_out,
22578 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22579 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22580 		if (mp == NULL)
22581 			goto release_ire_and_ill;
22582 
22583 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22584 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22585 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22586 		if ((pktxmit_state == SEND_FAILED) ||
22587 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22588 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22589 			    "- packet dropped\n"));
22590 release_ire_and_ill:
22591 			ire_refrele(ire);
22592 			if (next_mp != NULL) {
22593 				freemsg(next_mp);
22594 				ire_refrele(ire1);
22595 			}
22596 			if (conn_outgoing_ill != NULL)
22597 				ill_refrele(conn_outgoing_ill);
22598 			return;
22599 		}
22600 
22601 		if (CLASSD(dst)) {
22602 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22603 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22604 			    LENGTH);
22605 		}
22606 
22607 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22608 		    "ip_wput_ire_end: q %p (%S)",
22609 		    q, "last copy out");
22610 		IRE_REFRELE(ire);
22611 
22612 		if (multirt_send) {
22613 			ASSERT(ire1);
22614 			/*
22615 			 * Proceed with the next RTF_MULTIRT ire,
22616 			 * Also set up the send-to queue accordingly.
22617 			 */
22618 			ire = ire1;
22619 			ire1 = NULL;
22620 			stq = ire->ire_stq;
22621 			mp = next_mp;
22622 			next_mp = NULL;
22623 			ipha = (ipha_t *)mp->b_rptr;
22624 			ill_index = Q_TO_INDEX(stq);
22625 			ill = (ill_t *)stq->q_ptr;
22626 		}
22627 	} while (multirt_send);
22628 	if (conn_outgoing_ill != NULL)
22629 		ill_refrele(conn_outgoing_ill);
22630 	return;
22631 
22632 	/*
22633 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22634 	 */
22635 broadcast:
22636 	{
22637 		/*
22638 		 * Avoid broadcast storms by setting the ttl to 1
22639 		 * for broadcasts. This parameter can be set
22640 		 * via ndd, so make sure that for the SO_DONTROUTE
22641 		 * case that ipha_ttl is always set to 1.
22642 		 * In the event that we are replying to incoming
22643 		 * ICMP packets, conn could be NULL.
22644 		 */
22645 		if ((connp != NULL) && connp->conn_dontroute)
22646 			ipha->ipha_ttl = 1;
22647 		else
22648 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22649 
22650 		/*
22651 		 * Note that we are not doing a IRB_REFHOLD here.
22652 		 * Actually we don't care if the list changes i.e
22653 		 * if somebody deletes an IRE from the list while
22654 		 * we drop the lock, the next time we come around
22655 		 * ire_next will be NULL and hence we won't send
22656 		 * out multiple copies which is fine.
22657 		 */
22658 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22659 		ire1 = ire->ire_next;
22660 		if (conn_outgoing_ill != NULL) {
22661 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22662 				ASSERT(ire1 == ire->ire_next);
22663 				if (ire1 != NULL && ire1->ire_addr == dst) {
22664 					ire_refrele(ire);
22665 					ire = ire1;
22666 					IRE_REFHOLD(ire);
22667 					ire1 = ire->ire_next;
22668 					continue;
22669 				}
22670 				rw_exit(&ire->ire_bucket->irb_lock);
22671 				/* Did not find a matching ill */
22672 				ip1dbg(("ip_wput_ire: broadcast with no "
22673 				    "matching IP_BOUND_IF ill %s\n",
22674 				    conn_outgoing_ill->ill_name));
22675 				freemsg(first_mp);
22676 				if (ire != NULL)
22677 					ire_refrele(ire);
22678 				ill_refrele(conn_outgoing_ill);
22679 				return;
22680 			}
22681 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22682 			/*
22683 			 * If the next IRE has the same address and is not one
22684 			 * of the two copies that we need to send, try to see
22685 			 * whether this copy should be sent at all. This
22686 			 * assumes that we insert loopbacks first and then
22687 			 * non-loopbacks. This is acheived by inserting the
22688 			 * loopback always before non-loopback.
22689 			 * This is used to send a single copy of a broadcast
22690 			 * packet out all physical interfaces that have an
22691 			 * matching IRE_BROADCAST while also looping
22692 			 * back one copy (to ip_wput_local) for each
22693 			 * matching physical interface. However, we avoid
22694 			 * sending packets out different logical that match by
22695 			 * having ipif_up/ipif_down supress duplicate
22696 			 * IRE_BROADCASTS.
22697 			 *
22698 			 * This feature is currently used to get broadcasts
22699 			 * sent to multiple interfaces, when the broadcast
22700 			 * address being used applies to multiple interfaces.
22701 			 * For example, a whole net broadcast will be
22702 			 * replicated on every connected subnet of
22703 			 * the target net.
22704 			 *
22705 			 * Each zone has its own set of IRE_BROADCASTs, so that
22706 			 * we're able to distribute inbound packets to multiple
22707 			 * zones who share a broadcast address. We avoid looping
22708 			 * back outbound packets in different zones but on the
22709 			 * same ill, as the application would see duplicates.
22710 			 *
22711 			 * If the interfaces are part of the same group,
22712 			 * we would want to send only one copy out for
22713 			 * whole group.
22714 			 *
22715 			 * This logic assumes that ire_add_v4() groups the
22716 			 * IRE_BROADCAST entries so that those with the same
22717 			 * ire_addr and ill_group are kept together.
22718 			 */
22719 			ire_ill = ire->ire_ipif->ipif_ill;
22720 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22721 				if (ire_ill->ill_group != NULL &&
22722 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22723 					/*
22724 					 * If the current zone only has an ire
22725 					 * broadcast for this address marked
22726 					 * NORECV, the ire we want is ahead in
22727 					 * the bucket, so we look it up
22728 					 * deliberately ignoring the zoneid.
22729 					 */
22730 					for (ire1 = ire->ire_bucket->irb_ire;
22731 					    ire1 != NULL;
22732 					    ire1 = ire1->ire_next) {
22733 						ire1_ill =
22734 						    ire1->ire_ipif->ipif_ill;
22735 						if (ire1->ire_addr != dst)
22736 							continue;
22737 						/* skip over the current ire */
22738 						if (ire1 == ire)
22739 							continue;
22740 						/* skip over deleted ires */
22741 						if (ire1->ire_marks &
22742 						    IRE_MARK_CONDEMNED)
22743 							continue;
22744 						/*
22745 						 * non-loopback ire in our
22746 						 * group: use it for the next
22747 						 * pass in the loop
22748 						 */
22749 						if (ire1->ire_stq != NULL &&
22750 						    ire1_ill->ill_group ==
22751 						    ire_ill->ill_group)
22752 							break;
22753 					}
22754 				}
22755 			} else {
22756 				while (ire1 != NULL && ire1->ire_addr == dst) {
22757 					ire1_ill = ire1->ire_ipif->ipif_ill;
22758 					/*
22759 					 * We can have two broadcast ires on the
22760 					 * same ill in different zones; here
22761 					 * we'll send a copy of the packet on
22762 					 * each ill and the fanout code will
22763 					 * call conn_wantpacket() to check that
22764 					 * the zone has the broadcast address
22765 					 * configured on the ill. If the two
22766 					 * ires are in the same group we only
22767 					 * send one copy up.
22768 					 */
22769 					if (ire1_ill != ire_ill &&
22770 					    (ire1_ill->ill_group == NULL ||
22771 					    ire_ill->ill_group == NULL ||
22772 					    ire1_ill->ill_group !=
22773 					    ire_ill->ill_group)) {
22774 						break;
22775 					}
22776 					ire1 = ire1->ire_next;
22777 				}
22778 			}
22779 		}
22780 		ASSERT(multirt_send == B_FALSE);
22781 		if (ire1 != NULL && ire1->ire_addr == dst) {
22782 			if ((ire->ire_flags & RTF_MULTIRT) &&
22783 			    (ire1->ire_flags & RTF_MULTIRT)) {
22784 				/*
22785 				 * We are in the multirouting case.
22786 				 * The message must be sent at least
22787 				 * on both ires. These ires have been
22788 				 * inserted AFTER the standard ones
22789 				 * in ip_rt_add(). There are thus no
22790 				 * other ire entries for the destination
22791 				 * address in the rest of the bucket
22792 				 * that do not have the RTF_MULTIRT
22793 				 * flag. We don't process a copy
22794 				 * of the message here. This will be
22795 				 * done in the final sending loop.
22796 				 */
22797 				multirt_send = B_TRUE;
22798 			} else {
22799 				next_mp = ip_copymsg(first_mp);
22800 				if (next_mp != NULL)
22801 					IRE_REFHOLD(ire1);
22802 			}
22803 		}
22804 		rw_exit(&ire->ire_bucket->irb_lock);
22805 	}
22806 
22807 	if (stq) {
22808 		/*
22809 		 * A non-NULL send-to queue means this packet is going
22810 		 * out of this machine.
22811 		 */
22812 		out_ill = (ill_t *)stq->q_ptr;
22813 
22814 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22815 		ttl_protocol = ((uint16_t *)ipha)[4];
22816 		/*
22817 		 * We accumulate the pseudo header checksum in cksum.
22818 		 * This is pretty hairy code, so watch close.  One
22819 		 * thing to keep in mind is that UDP and TCP have
22820 		 * stored their respective datagram lengths in their
22821 		 * checksum fields.  This lines things up real nice.
22822 		 */
22823 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22824 		    (src >> 16) + (src & 0xFFFF);
22825 		/*
22826 		 * We assume the udp checksum field contains the
22827 		 * length, so to compute the pseudo header checksum,
22828 		 * all we need is the protocol number and src/dst.
22829 		 */
22830 		/* Provide the checksums for UDP and TCP. */
22831 		if ((PROTO == IPPROTO_TCP) &&
22832 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22833 			/* hlen gets the number of uchar_ts in the IP header */
22834 			hlen = (V_HLEN & 0xF) << 2;
22835 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22836 			IP_STAT(ipst, ip_out_sw_cksum);
22837 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22838 			    LENGTH - hlen);
22839 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22840 		} else if (PROTO == IPPROTO_SCTP &&
22841 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22842 			sctp_hdr_t	*sctph;
22843 
22844 			hlen = (V_HLEN & 0xF) << 2;
22845 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22846 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22847 			sctph->sh_chksum = 0;
22848 #ifdef	DEBUG
22849 			if (!skip_sctp_cksum)
22850 #endif
22851 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22852 		} else {
22853 			queue_t *dev_q = stq->q_next;
22854 
22855 			if ((dev_q->q_next || dev_q->q_first) &&
22856 			    !canput(dev_q)) {
22857 blocked:
22858 				ipha->ipha_ident = ip_hdr_included;
22859 				/*
22860 				 * If we don't have a conn to apply
22861 				 * backpressure, free the message.
22862 				 * In the ire_send path, we don't know
22863 				 * the position to requeue the packet. Rather
22864 				 * than reorder packets, we just drop this
22865 				 * packet.
22866 				 */
22867 				if (ipst->ips_ip_output_queue &&
22868 				    connp != NULL &&
22869 				    caller != IRE_SEND) {
22870 					if (caller == IP_WSRV) {
22871 						connp->conn_did_putbq = 1;
22872 						(void) putbq(connp->conn_wq,
22873 						    first_mp);
22874 						conn_drain_insert(connp);
22875 						/*
22876 						 * This is the service thread,
22877 						 * and the queue is already
22878 						 * noenabled. The check for
22879 						 * canput and the putbq is not
22880 						 * atomic. So we need to check
22881 						 * again.
22882 						 */
22883 						if (canput(stq->q_next))
22884 							connp->conn_did_putbq
22885 							    = 0;
22886 						IP_STAT(ipst, ip_conn_flputbq);
22887 					} else {
22888 						/*
22889 						 * We are not the service proc.
22890 						 * ip_wsrv will be scheduled or
22891 						 * is already running.
22892 						 */
22893 						(void) putq(connp->conn_wq,
22894 						    first_mp);
22895 					}
22896 				} else {
22897 					out_ill = (ill_t *)stq->q_ptr;
22898 					BUMP_MIB(out_ill->ill_ip_mib,
22899 					    ipIfStatsOutDiscards);
22900 					freemsg(first_mp);
22901 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22902 					    "ip_wput_ire_end: q %p (%S)",
22903 					    q, "discard");
22904 				}
22905 				ire_refrele(ire);
22906 				if (next_mp) {
22907 					ire_refrele(ire1);
22908 					freemsg(next_mp);
22909 				}
22910 				if (conn_outgoing_ill != NULL)
22911 					ill_refrele(conn_outgoing_ill);
22912 				return;
22913 			}
22914 			if ((PROTO == IPPROTO_UDP) &&
22915 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22916 				/*
22917 				 * hlen gets the number of uchar_ts in the
22918 				 * IP header
22919 				 */
22920 				hlen = (V_HLEN & 0xF) << 2;
22921 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22922 				max_frag = ire->ire_max_frag;
22923 				if (*up != 0) {
22924 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22925 					    up, PROTO, hlen, LENGTH, max_frag,
22926 					    ipsec_len, cksum);
22927 					/* Software checksum? */
22928 					if (DB_CKSUMFLAGS(mp) == 0) {
22929 						IP_STAT(ipst, ip_out_sw_cksum);
22930 						IP_STAT_UPDATE(ipst,
22931 						    ip_udp_out_sw_cksum_bytes,
22932 						    LENGTH - hlen);
22933 					}
22934 				}
22935 			}
22936 		}
22937 		/*
22938 		 * Need to do this even when fragmenting. The local
22939 		 * loopback can be done without computing checksums
22940 		 * but forwarding out other interface must be done
22941 		 * after the IP checksum (and ULP checksums) have been
22942 		 * computed.
22943 		 *
22944 		 * NOTE : multicast_forward is set only if this packet
22945 		 * originated from ip_wput. For packets originating from
22946 		 * ip_wput_multicast, it is not set.
22947 		 */
22948 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22949 multi_loopback:
22950 			ip2dbg(("ip_wput: multicast, loop %d\n",
22951 			    conn_multicast_loop));
22952 
22953 			/*  Forget header checksum offload */
22954 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22955 
22956 			/*
22957 			 * Local loopback of multicasts?  Check the
22958 			 * ill.
22959 			 *
22960 			 * Note that the loopback function will not come
22961 			 * in through ip_rput - it will only do the
22962 			 * client fanout thus we need to do an mforward
22963 			 * as well.  The is different from the BSD
22964 			 * logic.
22965 			 */
22966 			if (ill != NULL) {
22967 				ilm_t	*ilm;
22968 
22969 				ILM_WALKER_HOLD(ill);
22970 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22971 				    ALL_ZONES);
22972 				ILM_WALKER_RELE(ill);
22973 				if (ilm != NULL) {
22974 					/*
22975 					 * Pass along the virtual output q.
22976 					 * ip_wput_local() will distribute the
22977 					 * packet to all the matching zones,
22978 					 * except the sending zone when
22979 					 * IP_MULTICAST_LOOP is false.
22980 					 */
22981 					ip_multicast_loopback(q, ill, first_mp,
22982 					    conn_multicast_loop ? 0 :
22983 					    IP_FF_NO_MCAST_LOOP, zoneid);
22984 				}
22985 			}
22986 			if (ipha->ipha_ttl == 0) {
22987 				/*
22988 				 * 0 => only to this host i.e. we are
22989 				 * done. We are also done if this was the
22990 				 * loopback interface since it is sufficient
22991 				 * to loopback one copy of a multicast packet.
22992 				 */
22993 				freemsg(first_mp);
22994 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22995 				    "ip_wput_ire_end: q %p (%S)",
22996 				    q, "loopback");
22997 				ire_refrele(ire);
22998 				if (conn_outgoing_ill != NULL)
22999 					ill_refrele(conn_outgoing_ill);
23000 				return;
23001 			}
23002 			/*
23003 			 * ILLF_MULTICAST is checked in ip_newroute
23004 			 * i.e. we don't need to check it here since
23005 			 * all IRE_CACHEs come from ip_newroute.
23006 			 * For multicast traffic, SO_DONTROUTE is interpreted
23007 			 * to mean only send the packet out the interface
23008 			 * (optionally specified with IP_MULTICAST_IF)
23009 			 * and do not forward it out additional interfaces.
23010 			 * RSVP and the rsvp daemon is an example of a
23011 			 * protocol and user level process that
23012 			 * handles it's own routing. Hence, it uses the
23013 			 * SO_DONTROUTE option to accomplish this.
23014 			 */
23015 
23016 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23017 			    ill != NULL) {
23018 				/* Unconditionally redo the checksum */
23019 				ipha->ipha_hdr_checksum = 0;
23020 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23021 
23022 				/*
23023 				 * If this needs to go out secure, we need
23024 				 * to wait till we finish the IPsec
23025 				 * processing.
23026 				 */
23027 				if (ipsec_len == 0 &&
23028 				    ip_mforward(ill, ipha, mp)) {
23029 					freemsg(first_mp);
23030 					ip1dbg(("ip_wput: mforward failed\n"));
23031 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23032 					    "ip_wput_ire_end: q %p (%S)",
23033 					    q, "mforward failed");
23034 					ire_refrele(ire);
23035 					if (conn_outgoing_ill != NULL)
23036 						ill_refrele(conn_outgoing_ill);
23037 					return;
23038 				}
23039 			}
23040 		}
23041 		max_frag = ire->ire_max_frag;
23042 		cksum += ttl_protocol;
23043 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23044 			/* No fragmentation required for this one. */
23045 			/*
23046 			 * Don't use frag_flag if packet is pre-built or source
23047 			 * routed or if multicast (since multicast packets do
23048 			 * not solicit ICMP "packet too big" messages).
23049 			 */
23050 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23051 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23052 			    !ip_source_route_included(ipha)) &&
23053 			    !CLASSD(ipha->ipha_dst))
23054 				ipha->ipha_fragment_offset_and_flags |=
23055 				    htons(ire->ire_frag_flag);
23056 
23057 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23058 				/* Complete the IP header checksum. */
23059 				cksum += ipha->ipha_ident;
23060 				cksum += (v_hlen_tos_len >> 16)+
23061 				    (v_hlen_tos_len & 0xFFFF);
23062 				cksum += ipha->ipha_fragment_offset_and_flags;
23063 				hlen = (V_HLEN & 0xF) -
23064 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23065 				if (hlen) {
23066 checksumoptions:
23067 					/*
23068 					 * Account for the IP Options in the IP
23069 					 * header checksum.
23070 					 */
23071 					up = (uint16_t *)(rptr+
23072 					    IP_SIMPLE_HDR_LENGTH);
23073 					do {
23074 						cksum += up[0];
23075 						cksum += up[1];
23076 						up += 2;
23077 					} while (--hlen);
23078 				}
23079 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23080 				cksum = ~(cksum + (cksum >> 16));
23081 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23082 			}
23083 			if (ipsec_len != 0) {
23084 				ipsec_out_process(q, first_mp, ire, ill_index);
23085 				if (!next_mp) {
23086 					ire_refrele(ire);
23087 					if (conn_outgoing_ill != NULL)
23088 						ill_refrele(conn_outgoing_ill);
23089 					return;
23090 				}
23091 				goto next;
23092 			}
23093 
23094 			/*
23095 			 * multirt_send has already been handled
23096 			 * for broadcast, but not yet for multicast
23097 			 * or IP options.
23098 			 */
23099 			if (next_mp == NULL) {
23100 				if (ire->ire_flags & RTF_MULTIRT) {
23101 					multirt_send = B_TRUE;
23102 				}
23103 			}
23104 
23105 			/*
23106 			 * In most cases, the emission loop below is
23107 			 * entered only once. Only in the case where
23108 			 * the ire holds the RTF_MULTIRT flag, do we loop
23109 			 * to process all RTF_MULTIRT ires in the bucket,
23110 			 * and send the packet through all crossed
23111 			 * RTF_MULTIRT routes.
23112 			 */
23113 			do {
23114 				if (multirt_send) {
23115 					irb_t *irb;
23116 
23117 					irb = ire->ire_bucket;
23118 					ASSERT(irb != NULL);
23119 					/*
23120 					 * We are in a multiple send case,
23121 					 * need to get the next IRE and make
23122 					 * a duplicate of the packet.
23123 					 */
23124 					IRB_REFHOLD(irb);
23125 					for (ire1 = ire->ire_next;
23126 					    ire1 != NULL;
23127 					    ire1 = ire1->ire_next) {
23128 						if (!(ire1->ire_flags &
23129 						    RTF_MULTIRT)) {
23130 							continue;
23131 						}
23132 						if (ire1->ire_addr !=
23133 						    ire->ire_addr) {
23134 							continue;
23135 						}
23136 						if (ire1->ire_marks &
23137 						    (IRE_MARK_CONDEMNED|
23138 						    IRE_MARK_HIDDEN)) {
23139 							continue;
23140 						}
23141 
23142 						/* Got one */
23143 						IRE_REFHOLD(ire1);
23144 						break;
23145 					}
23146 					IRB_REFRELE(irb);
23147 
23148 					if (ire1 != NULL) {
23149 						next_mp = copyb(mp);
23150 						if ((next_mp == NULL) ||
23151 						    ((mp->b_cont != NULL) &&
23152 						    ((next_mp->b_cont =
23153 						    dupmsg(mp->b_cont))
23154 						    == NULL))) {
23155 							freemsg(next_mp);
23156 							next_mp = NULL;
23157 							ire_refrele(ire1);
23158 							ire1 = NULL;
23159 						}
23160 					}
23161 
23162 					/*
23163 					 * Last multiroute ire; don't loop
23164 					 * anymore. The emission is over
23165 					 * and next_mp is NULL.
23166 					 */
23167 					if (ire1 == NULL) {
23168 						multirt_send = B_FALSE;
23169 					}
23170 				}
23171 
23172 				out_ill = ire_to_ill(ire);
23173 				DTRACE_PROBE4(ip4__physical__out__start,
23174 				    ill_t *, NULL,
23175 				    ill_t *, out_ill,
23176 				    ipha_t *, ipha, mblk_t *, mp);
23177 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23178 				    ipst->ips_ipv4firewall_physical_out,
23179 				    NULL, out_ill, ipha, mp, mp, ipst);
23180 				DTRACE_PROBE1(ip4__physical__out__end,
23181 				    mblk_t *, mp);
23182 				if (mp == NULL)
23183 					goto release_ire_and_ill_2;
23184 
23185 				ASSERT(ipsec_len == 0);
23186 				mp->b_prev =
23187 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23188 				DTRACE_PROBE2(ip__xmit__2,
23189 				    mblk_t *, mp, ire_t *, ire);
23190 				pktxmit_state = ip_xmit_v4(mp, ire,
23191 				    NULL, B_TRUE);
23192 				if ((pktxmit_state == SEND_FAILED) ||
23193 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23194 release_ire_and_ill_2:
23195 					if (next_mp) {
23196 						freemsg(next_mp);
23197 						ire_refrele(ire1);
23198 					}
23199 					ire_refrele(ire);
23200 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23201 					    "ip_wput_ire_end: q %p (%S)",
23202 					    q, "discard MDATA");
23203 					if (conn_outgoing_ill != NULL)
23204 						ill_refrele(conn_outgoing_ill);
23205 					return;
23206 				}
23207 
23208 				if (CLASSD(dst)) {
23209 					BUMP_MIB(out_ill->ill_ip_mib,
23210 					    ipIfStatsHCOutMcastPkts);
23211 					UPDATE_MIB(out_ill->ill_ip_mib,
23212 					    ipIfStatsHCOutMcastOctets,
23213 					    LENGTH);
23214 				} else if (ire->ire_type == IRE_BROADCAST) {
23215 					BUMP_MIB(out_ill->ill_ip_mib,
23216 					    ipIfStatsHCOutBcastPkts);
23217 				}
23218 
23219 				if (multirt_send) {
23220 					/*
23221 					 * We are in a multiple send case,
23222 					 * need to re-enter the sending loop
23223 					 * using the next ire.
23224 					 */
23225 					ire_refrele(ire);
23226 					ire = ire1;
23227 					stq = ire->ire_stq;
23228 					mp = next_mp;
23229 					next_mp = NULL;
23230 					ipha = (ipha_t *)mp->b_rptr;
23231 					ill_index = Q_TO_INDEX(stq);
23232 				}
23233 			} while (multirt_send);
23234 
23235 			if (!next_mp) {
23236 				/*
23237 				 * Last copy going out (the ultra-common
23238 				 * case).  Note that we intentionally replicate
23239 				 * the putnext rather than calling it before
23240 				 * the next_mp check in hopes of a little
23241 				 * tail-call action out of the compiler.
23242 				 */
23243 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23244 				    "ip_wput_ire_end: q %p (%S)",
23245 				    q, "last copy out(1)");
23246 				ire_refrele(ire);
23247 				if (conn_outgoing_ill != NULL)
23248 					ill_refrele(conn_outgoing_ill);
23249 				return;
23250 			}
23251 			/* More copies going out below. */
23252 		} else {
23253 			int offset;
23254 fragmentit:
23255 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23256 			/*
23257 			 * If this would generate a icmp_frag_needed message,
23258 			 * we need to handle it before we do the IPsec
23259 			 * processing. Otherwise, we need to strip the IPsec
23260 			 * headers before we send up the message to the ULPs
23261 			 * which becomes messy and difficult.
23262 			 */
23263 			if (ipsec_len != 0) {
23264 				if ((max_frag < (unsigned int)(LENGTH +
23265 				    ipsec_len)) && (offset & IPH_DF)) {
23266 					out_ill = (ill_t *)stq->q_ptr;
23267 					BUMP_MIB(out_ill->ill_ip_mib,
23268 					    ipIfStatsOutFragFails);
23269 					BUMP_MIB(out_ill->ill_ip_mib,
23270 					    ipIfStatsOutFragReqds);
23271 					ipha->ipha_hdr_checksum = 0;
23272 					ipha->ipha_hdr_checksum =
23273 					    (uint16_t)ip_csum_hdr(ipha);
23274 					icmp_frag_needed(ire->ire_stq, first_mp,
23275 					    max_frag, zoneid, ipst);
23276 					if (!next_mp) {
23277 						ire_refrele(ire);
23278 						if (conn_outgoing_ill != NULL) {
23279 							ill_refrele(
23280 							    conn_outgoing_ill);
23281 						}
23282 						return;
23283 					}
23284 				} else {
23285 					/*
23286 					 * This won't cause a icmp_frag_needed
23287 					 * message. to be generated. Send it on
23288 					 * the wire. Note that this could still
23289 					 * cause fragmentation and all we
23290 					 * do is the generation of the message
23291 					 * to the ULP if needed before IPsec.
23292 					 */
23293 					if (!next_mp) {
23294 						ipsec_out_process(q, first_mp,
23295 						    ire, ill_index);
23296 						TRACE_2(TR_FAC_IP,
23297 						    TR_IP_WPUT_IRE_END,
23298 						    "ip_wput_ire_end: q %p "
23299 						    "(%S)", q,
23300 						    "last ipsec_out_process");
23301 						ire_refrele(ire);
23302 						if (conn_outgoing_ill != NULL) {
23303 							ill_refrele(
23304 							    conn_outgoing_ill);
23305 						}
23306 						return;
23307 					}
23308 					ipsec_out_process(q, first_mp,
23309 					    ire, ill_index);
23310 				}
23311 			} else {
23312 				/*
23313 				 * Initiate IPPF processing. For
23314 				 * fragmentable packets we finish
23315 				 * all QOS packet processing before
23316 				 * calling:
23317 				 * ip_wput_ire_fragmentit->ip_wput_frag
23318 				 */
23319 
23320 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23321 					ip_process(IPP_LOCAL_OUT, &mp,
23322 					    ill_index);
23323 					if (mp == NULL) {
23324 						out_ill = (ill_t *)stq->q_ptr;
23325 						BUMP_MIB(out_ill->ill_ip_mib,
23326 						    ipIfStatsOutDiscards);
23327 						if (next_mp != NULL) {
23328 							freemsg(next_mp);
23329 							ire_refrele(ire1);
23330 						}
23331 						ire_refrele(ire);
23332 						TRACE_2(TR_FAC_IP,
23333 						    TR_IP_WPUT_IRE_END,
23334 						    "ip_wput_ire: q %p (%S)",
23335 						    q, "discard MDATA");
23336 						if (conn_outgoing_ill != NULL) {
23337 							ill_refrele(
23338 							    conn_outgoing_ill);
23339 						}
23340 						return;
23341 					}
23342 				}
23343 				if (!next_mp) {
23344 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23345 					    "ip_wput_ire_end: q %p (%S)",
23346 					    q, "last fragmentation");
23347 					ip_wput_ire_fragmentit(mp, ire,
23348 					    zoneid, ipst);
23349 					ire_refrele(ire);
23350 					if (conn_outgoing_ill != NULL)
23351 						ill_refrele(conn_outgoing_ill);
23352 					return;
23353 				}
23354 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23355 			}
23356 		}
23357 	} else {
23358 nullstq:
23359 		/* A NULL stq means the destination address is local. */
23360 		UPDATE_OB_PKT_COUNT(ire);
23361 		ire->ire_last_used_time = lbolt;
23362 		ASSERT(ire->ire_ipif != NULL);
23363 		if (!next_mp) {
23364 			/*
23365 			 * Is there an "in" and "out" for traffic local
23366 			 * to a host (loopback)?  The code in Solaris doesn't
23367 			 * explicitly draw a line in its code for in vs out,
23368 			 * so we've had to draw a line in the sand: ip_wput_ire
23369 			 * is considered to be the "output" side and
23370 			 * ip_wput_local to be the "input" side.
23371 			 */
23372 			out_ill = ire_to_ill(ire);
23373 
23374 			DTRACE_PROBE4(ip4__loopback__out__start,
23375 			    ill_t *, NULL, ill_t *, out_ill,
23376 			    ipha_t *, ipha, mblk_t *, first_mp);
23377 
23378 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23379 			    ipst->ips_ipv4firewall_loopback_out,
23380 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23381 
23382 			DTRACE_PROBE1(ip4__loopback__out_end,
23383 			    mblk_t *, first_mp);
23384 
23385 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23386 			    "ip_wput_ire_end: q %p (%S)",
23387 			    q, "local address");
23388 
23389 			if (first_mp != NULL)
23390 				ip_wput_local(q, out_ill, ipha,
23391 				    first_mp, ire, 0, ire->ire_zoneid);
23392 			ire_refrele(ire);
23393 			if (conn_outgoing_ill != NULL)
23394 				ill_refrele(conn_outgoing_ill);
23395 			return;
23396 		}
23397 
23398 		out_ill = ire_to_ill(ire);
23399 
23400 		DTRACE_PROBE4(ip4__loopback__out__start,
23401 		    ill_t *, NULL, ill_t *, out_ill,
23402 		    ipha_t *, ipha, mblk_t *, first_mp);
23403 
23404 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23405 		    ipst->ips_ipv4firewall_loopback_out,
23406 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23407 
23408 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23409 
23410 		if (first_mp != NULL)
23411 			ip_wput_local(q, out_ill, ipha,
23412 			    first_mp, ire, 0, ire->ire_zoneid);
23413 	}
23414 next:
23415 	/*
23416 	 * More copies going out to additional interfaces.
23417 	 * ire1 has already been held. We don't need the
23418 	 * "ire" anymore.
23419 	 */
23420 	ire_refrele(ire);
23421 	ire = ire1;
23422 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23423 	mp = next_mp;
23424 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23425 	ill = ire_to_ill(ire);
23426 	first_mp = mp;
23427 	if (ipsec_len != 0) {
23428 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23429 		mp = mp->b_cont;
23430 	}
23431 	dst = ire->ire_addr;
23432 	ipha = (ipha_t *)mp->b_rptr;
23433 	/*
23434 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23435 	 * Restore ipha_ident "no checksum" flag.
23436 	 */
23437 	src = orig_src;
23438 	ipha->ipha_ident = ip_hdr_included;
23439 	goto another;
23440 
23441 #undef	rptr
23442 #undef	Q_TO_INDEX
23443 }
23444 
23445 /*
23446  * Routine to allocate a message that is used to notify the ULP about MDT.
23447  * The caller may provide a pointer to the link-layer MDT capabilities,
23448  * or NULL if MDT is to be disabled on the stream.
23449  */
23450 mblk_t *
23451 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23452 {
23453 	mblk_t *mp;
23454 	ip_mdt_info_t *mdti;
23455 	ill_mdt_capab_t *idst;
23456 
23457 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23458 		DB_TYPE(mp) = M_CTL;
23459 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23460 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23461 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23462 		idst = &(mdti->mdt_capab);
23463 
23464 		/*
23465 		 * If the caller provides us with the capability, copy
23466 		 * it over into our notification message; otherwise
23467 		 * we zero out the capability portion.
23468 		 */
23469 		if (isrc != NULL)
23470 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23471 		else
23472 			bzero((caddr_t)idst, sizeof (*idst));
23473 	}
23474 	return (mp);
23475 }
23476 
23477 /*
23478  * Routine which determines whether MDT can be enabled on the destination
23479  * IRE and IPC combination, and if so, allocates and returns the MDT
23480  * notification mblk that may be used by ULP.  We also check if we need to
23481  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23482  * MDT usage in the past have been lifted.  This gets called during IP
23483  * and ULP binding.
23484  */
23485 mblk_t *
23486 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23487     ill_mdt_capab_t *mdt_cap)
23488 {
23489 	mblk_t *mp;
23490 	boolean_t rc = B_FALSE;
23491 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23492 
23493 	ASSERT(dst_ire != NULL);
23494 	ASSERT(connp != NULL);
23495 	ASSERT(mdt_cap != NULL);
23496 
23497 	/*
23498 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23499 	 * Multidata, which is handled in tcp_multisend().  This
23500 	 * is the reason why we do all these checks here, to ensure
23501 	 * that we don't enable Multidata for the cases which we
23502 	 * can't handle at the moment.
23503 	 */
23504 	do {
23505 		/* Only do TCP at the moment */
23506 		if (connp->conn_ulp != IPPROTO_TCP)
23507 			break;
23508 
23509 		/*
23510 		 * IPsec outbound policy present?  Note that we get here
23511 		 * after calling ipsec_conn_cache_policy() where the global
23512 		 * policy checking is performed.  conn_latch will be
23513 		 * non-NULL as long as there's a policy defined,
23514 		 * i.e. conn_out_enforce_policy may be NULL in such case
23515 		 * when the connection is non-secure, and hence we check
23516 		 * further if the latch refers to an outbound policy.
23517 		 */
23518 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23519 			break;
23520 
23521 		/* CGTP (multiroute) is enabled? */
23522 		if (dst_ire->ire_flags & RTF_MULTIRT)
23523 			break;
23524 
23525 		/* Outbound IPQoS enabled? */
23526 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23527 			/*
23528 			 * In this case, we disable MDT for this and all
23529 			 * future connections going over the interface.
23530 			 */
23531 			mdt_cap->ill_mdt_on = 0;
23532 			break;
23533 		}
23534 
23535 		/* socket option(s) present? */
23536 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23537 			break;
23538 
23539 		rc = B_TRUE;
23540 	/* CONSTCOND */
23541 	} while (0);
23542 
23543 	/* Remember the result */
23544 	connp->conn_mdt_ok = rc;
23545 
23546 	if (!rc)
23547 		return (NULL);
23548 	else if (!mdt_cap->ill_mdt_on) {
23549 		/*
23550 		 * If MDT has been previously turned off in the past, and we
23551 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23552 		 * then enable it for this interface.
23553 		 */
23554 		mdt_cap->ill_mdt_on = 1;
23555 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23556 		    "interface %s\n", ill_name));
23557 	}
23558 
23559 	/* Allocate the MDT info mblk */
23560 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23561 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23562 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23563 		return (NULL);
23564 	}
23565 	return (mp);
23566 }
23567 
23568 /*
23569  * Routine to allocate a message that is used to notify the ULP about LSO.
23570  * The caller may provide a pointer to the link-layer LSO capabilities,
23571  * or NULL if LSO is to be disabled on the stream.
23572  */
23573 mblk_t *
23574 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23575 {
23576 	mblk_t *mp;
23577 	ip_lso_info_t *lsoi;
23578 	ill_lso_capab_t *idst;
23579 
23580 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23581 		DB_TYPE(mp) = M_CTL;
23582 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23583 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23584 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23585 		idst = &(lsoi->lso_capab);
23586 
23587 		/*
23588 		 * If the caller provides us with the capability, copy
23589 		 * it over into our notification message; otherwise
23590 		 * we zero out the capability portion.
23591 		 */
23592 		if (isrc != NULL)
23593 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23594 		else
23595 			bzero((caddr_t)idst, sizeof (*idst));
23596 	}
23597 	return (mp);
23598 }
23599 
23600 /*
23601  * Routine which determines whether LSO can be enabled on the destination
23602  * IRE and IPC combination, and if so, allocates and returns the LSO
23603  * notification mblk that may be used by ULP.  We also check if we need to
23604  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23605  * LSO usage in the past have been lifted.  This gets called during IP
23606  * and ULP binding.
23607  */
23608 mblk_t *
23609 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23610     ill_lso_capab_t *lso_cap)
23611 {
23612 	mblk_t *mp;
23613 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23614 
23615 	ASSERT(dst_ire != NULL);
23616 	ASSERT(connp != NULL);
23617 	ASSERT(lso_cap != NULL);
23618 
23619 	connp->conn_lso_ok = B_TRUE;
23620 
23621 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23622 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23623 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23624 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23625 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23626 		connp->conn_lso_ok = B_FALSE;
23627 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23628 			/*
23629 			 * Disable LSO for this and all future connections going
23630 			 * over the interface.
23631 			 */
23632 			lso_cap->ill_lso_on = 0;
23633 		}
23634 	}
23635 
23636 	if (!connp->conn_lso_ok)
23637 		return (NULL);
23638 	else if (!lso_cap->ill_lso_on) {
23639 		/*
23640 		 * If LSO has been previously turned off in the past, and we
23641 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23642 		 * then enable it for this interface.
23643 		 */
23644 		lso_cap->ill_lso_on = 1;
23645 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23646 		    ill_name));
23647 	}
23648 
23649 	/* Allocate the LSO info mblk */
23650 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23651 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23652 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23653 
23654 	return (mp);
23655 }
23656 
23657 /*
23658  * Create destination address attribute, and fill it with the physical
23659  * destination address and SAP taken from the template DL_UNITDATA_REQ
23660  * message block.
23661  */
23662 boolean_t
23663 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23664 {
23665 	dl_unitdata_req_t *dlurp;
23666 	pattr_t *pa;
23667 	pattrinfo_t pa_info;
23668 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23669 	uint_t das_len, das_off;
23670 
23671 	ASSERT(dlmp != NULL);
23672 
23673 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23674 	das_len = dlurp->dl_dest_addr_length;
23675 	das_off = dlurp->dl_dest_addr_offset;
23676 
23677 	pa_info.type = PATTR_DSTADDRSAP;
23678 	pa_info.len = sizeof (**das) + das_len - 1;
23679 
23680 	/* create and associate the attribute */
23681 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23682 	if (pa != NULL) {
23683 		ASSERT(*das != NULL);
23684 		(*das)->addr_is_group = 0;
23685 		(*das)->addr_len = (uint8_t)das_len;
23686 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23687 	}
23688 
23689 	return (pa != NULL);
23690 }
23691 
23692 /*
23693  * Create hardware checksum attribute and fill it with the values passed.
23694  */
23695 boolean_t
23696 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23697     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23698 {
23699 	pattr_t *pa;
23700 	pattrinfo_t pa_info;
23701 
23702 	ASSERT(mmd != NULL);
23703 
23704 	pa_info.type = PATTR_HCKSUM;
23705 	pa_info.len = sizeof (pattr_hcksum_t);
23706 
23707 	/* create and associate the attribute */
23708 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23709 	if (pa != NULL) {
23710 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23711 
23712 		hck->hcksum_start_offset = start_offset;
23713 		hck->hcksum_stuff_offset = stuff_offset;
23714 		hck->hcksum_end_offset = end_offset;
23715 		hck->hcksum_flags = flags;
23716 	}
23717 	return (pa != NULL);
23718 }
23719 
23720 /*
23721  * Create zerocopy attribute and fill it with the specified flags
23722  */
23723 boolean_t
23724 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23725 {
23726 	pattr_t *pa;
23727 	pattrinfo_t pa_info;
23728 
23729 	ASSERT(mmd != NULL);
23730 	pa_info.type = PATTR_ZCOPY;
23731 	pa_info.len = sizeof (pattr_zcopy_t);
23732 
23733 	/* create and associate the attribute */
23734 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23735 	if (pa != NULL) {
23736 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23737 
23738 		zcopy->zcopy_flags = flags;
23739 	}
23740 	return (pa != NULL);
23741 }
23742 
23743 /*
23744  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23745  * block chain. We could rewrite to handle arbitrary message block chains but
23746  * that would make the code complicated and slow. Right now there three
23747  * restrictions:
23748  *
23749  *   1. The first message block must contain the complete IP header and
23750  *	at least 1 byte of payload data.
23751  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23752  *	so that we can use a single Multidata message.
23753  *   3. No frag must be distributed over two or more message blocks so
23754  *	that we don't need more than two packet descriptors per frag.
23755  *
23756  * The above restrictions allow us to support userland applications (which
23757  * will send down a single message block) and NFS over UDP (which will
23758  * send down a chain of at most three message blocks).
23759  *
23760  * We also don't use MDT for payloads with less than or equal to
23761  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23762  */
23763 boolean_t
23764 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23765 {
23766 	int	blocks;
23767 	ssize_t	total, missing, size;
23768 
23769 	ASSERT(mp != NULL);
23770 	ASSERT(hdr_len > 0);
23771 
23772 	size = MBLKL(mp) - hdr_len;
23773 	if (size <= 0)
23774 		return (B_FALSE);
23775 
23776 	/* The first mblk contains the header and some payload. */
23777 	blocks = 1;
23778 	total = size;
23779 	size %= len;
23780 	missing = (size == 0) ? 0 : (len - size);
23781 	mp = mp->b_cont;
23782 
23783 	while (mp != NULL) {
23784 		/*
23785 		 * Give up if we encounter a zero length message block.
23786 		 * In practice, this should rarely happen and therefore
23787 		 * not worth the trouble of freeing and re-linking the
23788 		 * mblk from the chain to handle such case.
23789 		 */
23790 		if ((size = MBLKL(mp)) == 0)
23791 			return (B_FALSE);
23792 
23793 		/* Too many payload buffers for a single Multidata message? */
23794 		if (++blocks > MULTIDATA_MAX_PBUFS)
23795 			return (B_FALSE);
23796 
23797 		total += size;
23798 		/* Is a frag distributed over two or more message blocks? */
23799 		if (missing > size)
23800 			return (B_FALSE);
23801 		size -= missing;
23802 
23803 		size %= len;
23804 		missing = (size == 0) ? 0 : (len - size);
23805 
23806 		mp = mp->b_cont;
23807 	}
23808 
23809 	return (total > ip_wput_frag_mdt_min);
23810 }
23811 
23812 /*
23813  * Outbound IPv4 fragmentation routine using MDT.
23814  */
23815 static void
23816 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23817     uint32_t frag_flag, int offset)
23818 {
23819 	ipha_t		*ipha_orig;
23820 	int		i1, ip_data_end;
23821 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23822 	mblk_t		*hdr_mp, *md_mp = NULL;
23823 	unsigned char	*hdr_ptr, *pld_ptr;
23824 	multidata_t	*mmd;
23825 	ip_pdescinfo_t	pdi;
23826 	ill_t		*ill;
23827 	ip_stack_t	*ipst = ire->ire_ipst;
23828 
23829 	ASSERT(DB_TYPE(mp) == M_DATA);
23830 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23831 
23832 	ill = ire_to_ill(ire);
23833 	ASSERT(ill != NULL);
23834 
23835 	ipha_orig = (ipha_t *)mp->b_rptr;
23836 	mp->b_rptr += sizeof (ipha_t);
23837 
23838 	/* Calculate how many packets we will send out */
23839 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23840 	pkts = (i1 + len - 1) / len;
23841 	ASSERT(pkts > 1);
23842 
23843 	/* Allocate a message block which will hold all the IP Headers. */
23844 	wroff = ipst->ips_ip_wroff_extra;
23845 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23846 
23847 	i1 = pkts * hdr_chunk_len;
23848 	/*
23849 	 * Create the header buffer, Multidata and destination address
23850 	 * and SAP attribute that should be associated with it.
23851 	 */
23852 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23853 	    ((hdr_mp->b_wptr += i1),
23854 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23855 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23856 		freemsg(mp);
23857 		if (md_mp == NULL) {
23858 			freemsg(hdr_mp);
23859 		} else {
23860 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23861 			freemsg(md_mp);
23862 		}
23863 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23864 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23865 		return;
23866 	}
23867 	IP_STAT(ipst, ip_frag_mdt_allocd);
23868 
23869 	/*
23870 	 * Add a payload buffer to the Multidata; this operation must not
23871 	 * fail, or otherwise our logic in this routine is broken.  There
23872 	 * is no memory allocation done by the routine, so any returned
23873 	 * failure simply tells us that we've done something wrong.
23874 	 *
23875 	 * A failure tells us that either we're adding the same payload
23876 	 * buffer more than once, or we're trying to add more buffers than
23877 	 * allowed.  None of the above cases should happen, and we panic
23878 	 * because either there's horrible heap corruption, and/or
23879 	 * programming mistake.
23880 	 */
23881 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23882 		goto pbuf_panic;
23883 
23884 	hdr_ptr = hdr_mp->b_rptr;
23885 	pld_ptr = mp->b_rptr;
23886 
23887 	/* Establish the ending byte offset, based on the starting offset. */
23888 	offset <<= 3;
23889 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23890 	    IP_SIMPLE_HDR_LENGTH;
23891 
23892 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23893 
23894 	while (pld_ptr < mp->b_wptr) {
23895 		ipha_t		*ipha;
23896 		uint16_t	offset_and_flags;
23897 		uint16_t	ip_len;
23898 		int		error;
23899 
23900 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23901 		ipha = (ipha_t *)(hdr_ptr + wroff);
23902 		ASSERT(OK_32PTR(ipha));
23903 		*ipha = *ipha_orig;
23904 
23905 		if (ip_data_end - offset > len) {
23906 			offset_and_flags = IPH_MF;
23907 		} else {
23908 			/*
23909 			 * Last frag. Set len to the length of this last piece.
23910 			 */
23911 			len = ip_data_end - offset;
23912 			/* A frag of a frag might have IPH_MF non-zero */
23913 			offset_and_flags =
23914 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23915 			    IPH_MF;
23916 		}
23917 		offset_and_flags |= (uint16_t)(offset >> 3);
23918 		offset_and_flags |= (uint16_t)frag_flag;
23919 		/* Store the offset and flags in the IP header. */
23920 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23921 
23922 		/* Store the length in the IP header. */
23923 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23924 		ipha->ipha_length = htons(ip_len);
23925 
23926 		/*
23927 		 * Set the IP header checksum.  Note that mp is just
23928 		 * the header, so this is easy to pass to ip_csum.
23929 		 */
23930 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23931 
23932 		/*
23933 		 * Record offset and size of header and data of the next packet
23934 		 * in the multidata message.
23935 		 */
23936 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23937 		PDESC_PLD_INIT(&pdi);
23938 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23939 		ASSERT(i1 > 0);
23940 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23941 		if (i1 == len) {
23942 			pld_ptr += len;
23943 		} else {
23944 			i1 = len - i1;
23945 			mp = mp->b_cont;
23946 			ASSERT(mp != NULL);
23947 			ASSERT(MBLKL(mp) >= i1);
23948 			/*
23949 			 * Attach the next payload message block to the
23950 			 * multidata message.
23951 			 */
23952 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23953 				goto pbuf_panic;
23954 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23955 			pld_ptr = mp->b_rptr + i1;
23956 		}
23957 
23958 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23959 		    KM_NOSLEEP)) == NULL) {
23960 			/*
23961 			 * Any failure other than ENOMEM indicates that we
23962 			 * have passed in invalid pdesc info or parameters
23963 			 * to mmd_addpdesc, which must not happen.
23964 			 *
23965 			 * EINVAL is a result of failure on boundary checks
23966 			 * against the pdesc info contents.  It should not
23967 			 * happen, and we panic because either there's
23968 			 * horrible heap corruption, and/or programming
23969 			 * mistake.
23970 			 */
23971 			if (error != ENOMEM) {
23972 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23973 				    "pdesc logic error detected for "
23974 				    "mmd %p pinfo %p (%d)\n",
23975 				    (void *)mmd, (void *)&pdi, error);
23976 				/* NOTREACHED */
23977 			}
23978 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23979 			/* Free unattached payload message blocks as well */
23980 			md_mp->b_cont = mp->b_cont;
23981 			goto free_mmd;
23982 		}
23983 
23984 		/* Advance fragment offset. */
23985 		offset += len;
23986 
23987 		/* Advance to location for next header in the buffer. */
23988 		hdr_ptr += hdr_chunk_len;
23989 
23990 		/* Did we reach the next payload message block? */
23991 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23992 			mp = mp->b_cont;
23993 			/*
23994 			 * Attach the next message block with payload
23995 			 * data to the multidata message.
23996 			 */
23997 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23998 				goto pbuf_panic;
23999 			pld_ptr = mp->b_rptr;
24000 		}
24001 	}
24002 
24003 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24004 	ASSERT(mp->b_wptr == pld_ptr);
24005 
24006 	/* Update IP statistics */
24007 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24008 
24009 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24010 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24011 
24012 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24013 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24014 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24015 
24016 	if (pkt_type == OB_PKT) {
24017 		ire->ire_ob_pkt_count += pkts;
24018 		if (ire->ire_ipif != NULL)
24019 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24020 	} else {
24021 		/* The type is IB_PKT in the forwarding path. */
24022 		ire->ire_ib_pkt_count += pkts;
24023 		ASSERT(!IRE_IS_LOCAL(ire));
24024 		if (ire->ire_type & IRE_BROADCAST) {
24025 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24026 		} else {
24027 			UPDATE_MIB(ill->ill_ip_mib,
24028 			    ipIfStatsHCOutForwDatagrams, pkts);
24029 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24030 		}
24031 	}
24032 	ire->ire_last_used_time = lbolt;
24033 	/* Send it down */
24034 	putnext(ire->ire_stq, md_mp);
24035 	return;
24036 
24037 pbuf_panic:
24038 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24039 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24040 	    pbuf_idx);
24041 	/* NOTREACHED */
24042 }
24043 
24044 /*
24045  * Outbound IP fragmentation routine.
24046  *
24047  * NOTE : This routine does not ire_refrele the ire that is passed in
24048  * as the argument.
24049  */
24050 static void
24051 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24052     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24053 {
24054 	int		i1;
24055 	mblk_t		*ll_hdr_mp;
24056 	int 		ll_hdr_len;
24057 	int		hdr_len;
24058 	mblk_t		*hdr_mp;
24059 	ipha_t		*ipha;
24060 	int		ip_data_end;
24061 	int		len;
24062 	mblk_t		*mp = mp_orig, *mp1;
24063 	int		offset;
24064 	queue_t		*q;
24065 	uint32_t	v_hlen_tos_len;
24066 	mblk_t		*first_mp;
24067 	boolean_t	mctl_present;
24068 	ill_t		*ill;
24069 	ill_t		*out_ill;
24070 	mblk_t		*xmit_mp;
24071 	mblk_t		*carve_mp;
24072 	ire_t		*ire1 = NULL;
24073 	ire_t		*save_ire = NULL;
24074 	mblk_t  	*next_mp = NULL;
24075 	boolean_t	last_frag = B_FALSE;
24076 	boolean_t	multirt_send = B_FALSE;
24077 	ire_t		*first_ire = NULL;
24078 	irb_t		*irb = NULL;
24079 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24080 
24081 	ill = ire_to_ill(ire);
24082 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24083 
24084 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24085 
24086 	if (max_frag == 0) {
24087 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24088 		    " -  dropping packet\n"));
24089 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24090 		freemsg(mp);
24091 		return;
24092 	}
24093 
24094 	/*
24095 	 * IPsec does not allow hw accelerated packets to be fragmented
24096 	 * This check is made in ip_wput_ipsec_out prior to coming here
24097 	 * via ip_wput_ire_fragmentit.
24098 	 *
24099 	 * If at this point we have an ire whose ARP request has not
24100 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24101 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24102 	 * This packet and all fragmentable packets for this ire will
24103 	 * continue to get dropped while ire_nce->nce_state remains in
24104 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24105 	 * ND_REACHABLE, all subsquent large packets for this ire will
24106 	 * get fragemented and sent out by this function.
24107 	 */
24108 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24109 		/* If nce_state is ND_INITIAL, trigger ARP query */
24110 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24111 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24112 		    " -  dropping packet\n"));
24113 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24114 		freemsg(mp);
24115 		return;
24116 	}
24117 
24118 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24119 	    "ip_wput_frag_start:");
24120 
24121 	if (mp->b_datap->db_type == M_CTL) {
24122 		first_mp = mp;
24123 		mp_orig = mp = mp->b_cont;
24124 		mctl_present = B_TRUE;
24125 	} else {
24126 		first_mp = mp;
24127 		mctl_present = B_FALSE;
24128 	}
24129 
24130 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24131 	ipha = (ipha_t *)mp->b_rptr;
24132 
24133 	/*
24134 	 * If the Don't Fragment flag is on, generate an ICMP destination
24135 	 * unreachable, fragmentation needed.
24136 	 */
24137 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24138 	if (offset & IPH_DF) {
24139 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24140 		if (is_system_labeled()) {
24141 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24142 			    ire->ire_max_frag - max_frag, AF_INET);
24143 		}
24144 		/*
24145 		 * Need to compute hdr checksum if called from ip_wput_ire.
24146 		 * Note that ip_rput_forward verifies the checksum before
24147 		 * calling this routine so in that case this is a noop.
24148 		 */
24149 		ipha->ipha_hdr_checksum = 0;
24150 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24151 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24152 		    ipst);
24153 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24154 		    "ip_wput_frag_end:(%S)",
24155 		    "don't fragment");
24156 		return;
24157 	}
24158 	/*
24159 	 * Labeled systems adjust max_frag if they add a label
24160 	 * to send the correct path mtu.  We need the real mtu since we
24161 	 * are fragmenting the packet after label adjustment.
24162 	 */
24163 	if (is_system_labeled())
24164 		max_frag = ire->ire_max_frag;
24165 	if (mctl_present)
24166 		freeb(first_mp);
24167 	/*
24168 	 * Establish the starting offset.  May not be zero if we are fragging
24169 	 * a fragment that is being forwarded.
24170 	 */
24171 	offset = offset & IPH_OFFSET;
24172 
24173 	/* TODO why is this test needed? */
24174 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24175 	if (((max_frag - LENGTH) & ~7) < 8) {
24176 		/* TODO: notify ulp somehow */
24177 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24178 		freemsg(mp);
24179 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24180 		    "ip_wput_frag_end:(%S)",
24181 		    "len < 8");
24182 		return;
24183 	}
24184 
24185 	hdr_len = (V_HLEN & 0xF) << 2;
24186 
24187 	ipha->ipha_hdr_checksum = 0;
24188 
24189 	/*
24190 	 * Establish the number of bytes maximum per frag, after putting
24191 	 * in the header.
24192 	 */
24193 	len = (max_frag - hdr_len) & ~7;
24194 
24195 	/* Check if we can use MDT to send out the frags. */
24196 	ASSERT(!IRE_IS_LOCAL(ire));
24197 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24198 	    ipst->ips_ip_multidata_outbound &&
24199 	    !(ire->ire_flags & RTF_MULTIRT) &&
24200 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24201 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24202 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24203 		ASSERT(ill->ill_mdt_capab != NULL);
24204 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24205 			/*
24206 			 * If MDT has been previously turned off in the past,
24207 			 * and we currently can do MDT (due to IPQoS policy
24208 			 * removal, etc.) then enable it for this interface.
24209 			 */
24210 			ill->ill_mdt_capab->ill_mdt_on = 1;
24211 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24212 			    ill->ill_name));
24213 		}
24214 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24215 		    offset);
24216 		return;
24217 	}
24218 
24219 	/* Get a copy of the header for the trailing frags */
24220 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24221 	if (!hdr_mp) {
24222 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24223 		freemsg(mp);
24224 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24225 		    "ip_wput_frag_end:(%S)",
24226 		    "couldn't copy hdr");
24227 		return;
24228 	}
24229 	if (DB_CRED(mp) != NULL)
24230 		mblk_setcred(hdr_mp, DB_CRED(mp));
24231 
24232 	/* Store the starting offset, with the MoreFrags flag. */
24233 	i1 = offset | IPH_MF | frag_flag;
24234 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24235 
24236 	/* Establish the ending byte offset, based on the starting offset. */
24237 	offset <<= 3;
24238 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24239 
24240 	/* Store the length of the first fragment in the IP header. */
24241 	i1 = len + hdr_len;
24242 	ASSERT(i1 <= IP_MAXPACKET);
24243 	ipha->ipha_length = htons((uint16_t)i1);
24244 
24245 	/*
24246 	 * Compute the IP header checksum for the first frag.  We have to
24247 	 * watch out that we stop at the end of the header.
24248 	 */
24249 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24250 
24251 	/*
24252 	 * Now carve off the first frag.  Note that this will include the
24253 	 * original IP header.
24254 	 */
24255 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24256 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24257 		freeb(hdr_mp);
24258 		freemsg(mp_orig);
24259 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24260 		    "ip_wput_frag_end:(%S)",
24261 		    "couldn't carve first");
24262 		return;
24263 	}
24264 
24265 	/*
24266 	 * Multirouting case. Each fragment is replicated
24267 	 * via all non-condemned RTF_MULTIRT routes
24268 	 * currently resolved.
24269 	 * We ensure that first_ire is the first RTF_MULTIRT
24270 	 * ire in the bucket.
24271 	 */
24272 	if (ire->ire_flags & RTF_MULTIRT) {
24273 		irb = ire->ire_bucket;
24274 		ASSERT(irb != NULL);
24275 
24276 		multirt_send = B_TRUE;
24277 
24278 		/* Make sure we do not omit any multiroute ire. */
24279 		IRB_REFHOLD(irb);
24280 		for (first_ire = irb->irb_ire;
24281 		    first_ire != NULL;
24282 		    first_ire = first_ire->ire_next) {
24283 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24284 			    (first_ire->ire_addr == ire->ire_addr) &&
24285 			    !(first_ire->ire_marks &
24286 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24287 				break;
24288 			}
24289 		}
24290 
24291 		if (first_ire != NULL) {
24292 			if (first_ire != ire) {
24293 				IRE_REFHOLD(first_ire);
24294 				/*
24295 				 * Do not release the ire passed in
24296 				 * as the argument.
24297 				 */
24298 				ire = first_ire;
24299 			} else {
24300 				first_ire = NULL;
24301 			}
24302 		}
24303 		IRB_REFRELE(irb);
24304 
24305 		/*
24306 		 * Save the first ire; we will need to restore it
24307 		 * for the trailing frags.
24308 		 * We REFHOLD save_ire, as each iterated ire will be
24309 		 * REFRELEd.
24310 		 */
24311 		save_ire = ire;
24312 		IRE_REFHOLD(save_ire);
24313 	}
24314 
24315 	/*
24316 	 * First fragment emission loop.
24317 	 * In most cases, the emission loop below is entered only
24318 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24319 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24320 	 * bucket, and send the fragment through all crossed
24321 	 * RTF_MULTIRT routes.
24322 	 */
24323 	do {
24324 		if (ire->ire_flags & RTF_MULTIRT) {
24325 			/*
24326 			 * We are in a multiple send case, need to get
24327 			 * the next ire and make a copy of the packet.
24328 			 * ire1 holds here the next ire to process in the
24329 			 * bucket. If multirouting is expected,
24330 			 * any non-RTF_MULTIRT ire that has the
24331 			 * right destination address is ignored.
24332 			 *
24333 			 * We have to take into account the MTU of
24334 			 * each walked ire. max_frag is set by the
24335 			 * the caller and generally refers to
24336 			 * the primary ire entry. Here we ensure that
24337 			 * no route with a lower MTU will be used, as
24338 			 * fragments are carved once for all ires,
24339 			 * then replicated.
24340 			 */
24341 			ASSERT(irb != NULL);
24342 			IRB_REFHOLD(irb);
24343 			for (ire1 = ire->ire_next;
24344 			    ire1 != NULL;
24345 			    ire1 = ire1->ire_next) {
24346 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24347 					continue;
24348 				if (ire1->ire_addr != ire->ire_addr)
24349 					continue;
24350 				if (ire1->ire_marks &
24351 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24352 					continue;
24353 				/*
24354 				 * Ensure we do not exceed the MTU
24355 				 * of the next route.
24356 				 */
24357 				if (ire1->ire_max_frag < max_frag) {
24358 					ip_multirt_bad_mtu(ire1, max_frag);
24359 					continue;
24360 				}
24361 
24362 				/* Got one. */
24363 				IRE_REFHOLD(ire1);
24364 				break;
24365 			}
24366 			IRB_REFRELE(irb);
24367 
24368 			if (ire1 != NULL) {
24369 				next_mp = copyb(mp);
24370 				if ((next_mp == NULL) ||
24371 				    ((mp->b_cont != NULL) &&
24372 				    ((next_mp->b_cont =
24373 				    dupmsg(mp->b_cont)) == NULL))) {
24374 					freemsg(next_mp);
24375 					next_mp = NULL;
24376 					ire_refrele(ire1);
24377 					ire1 = NULL;
24378 				}
24379 			}
24380 
24381 			/* Last multiroute ire; don't loop anymore. */
24382 			if (ire1 == NULL) {
24383 				multirt_send = B_FALSE;
24384 			}
24385 		}
24386 
24387 		ll_hdr_len = 0;
24388 		LOCK_IRE_FP_MP(ire);
24389 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24390 		if (ll_hdr_mp != NULL) {
24391 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24392 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24393 		} else {
24394 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24395 		}
24396 
24397 		/* If there is a transmit header, get a copy for this frag. */
24398 		/*
24399 		 * TODO: should check db_ref before calling ip_carve_mp since
24400 		 * it might give us a dup.
24401 		 */
24402 		if (!ll_hdr_mp) {
24403 			/* No xmit header. */
24404 			xmit_mp = mp;
24405 
24406 		/* We have a link-layer header that can fit in our mblk. */
24407 		} else if (mp->b_datap->db_ref == 1 &&
24408 		    ll_hdr_len != 0 &&
24409 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24410 			/* M_DATA fastpath */
24411 			mp->b_rptr -= ll_hdr_len;
24412 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24413 			xmit_mp = mp;
24414 
24415 		/* Corner case if copyb has failed */
24416 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24417 			UNLOCK_IRE_FP_MP(ire);
24418 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24419 			freeb(hdr_mp);
24420 			freemsg(mp);
24421 			freemsg(mp_orig);
24422 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24423 			    "ip_wput_frag_end:(%S)",
24424 			    "discard");
24425 
24426 			if (multirt_send) {
24427 				ASSERT(ire1);
24428 				ASSERT(next_mp);
24429 
24430 				freemsg(next_mp);
24431 				ire_refrele(ire1);
24432 			}
24433 			if (save_ire != NULL)
24434 				IRE_REFRELE(save_ire);
24435 
24436 			if (first_ire != NULL)
24437 				ire_refrele(first_ire);
24438 			return;
24439 
24440 		/*
24441 		 * Case of res_mp OR the fastpath mp can't fit
24442 		 * in the mblk
24443 		 */
24444 		} else {
24445 			xmit_mp->b_cont = mp;
24446 			if (DB_CRED(mp) != NULL)
24447 				mblk_setcred(xmit_mp, DB_CRED(mp));
24448 			/*
24449 			 * Get priority marking, if any.
24450 			 * We propagate the CoS marking from the
24451 			 * original packet that went to QoS processing
24452 			 * in ip_wput_ire to the newly carved mp.
24453 			 */
24454 			if (DB_TYPE(xmit_mp) == M_DATA)
24455 				xmit_mp->b_band = mp->b_band;
24456 		}
24457 		UNLOCK_IRE_FP_MP(ire);
24458 
24459 		q = ire->ire_stq;
24460 		out_ill = (ill_t *)q->q_ptr;
24461 
24462 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24463 
24464 		DTRACE_PROBE4(ip4__physical__out__start,
24465 		    ill_t *, NULL, ill_t *, out_ill,
24466 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24467 
24468 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24469 		    ipst->ips_ipv4firewall_physical_out,
24470 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24471 
24472 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24473 
24474 		if (xmit_mp != NULL) {
24475 			putnext(q, xmit_mp);
24476 
24477 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24478 			UPDATE_MIB(out_ill->ill_ip_mib,
24479 			    ipIfStatsHCOutOctets, i1);
24480 
24481 			if (pkt_type != OB_PKT) {
24482 				/*
24483 				 * Update the packet count and MIB stats
24484 				 * of trailing RTF_MULTIRT ires.
24485 				 */
24486 				UPDATE_OB_PKT_COUNT(ire);
24487 				BUMP_MIB(out_ill->ill_ip_mib,
24488 				    ipIfStatsOutFragReqds);
24489 			}
24490 		}
24491 
24492 		if (multirt_send) {
24493 			/*
24494 			 * We are in a multiple send case; look for
24495 			 * the next ire and re-enter the loop.
24496 			 */
24497 			ASSERT(ire1);
24498 			ASSERT(next_mp);
24499 			/* REFRELE the current ire before looping */
24500 			ire_refrele(ire);
24501 			ire = ire1;
24502 			ire1 = NULL;
24503 			mp = next_mp;
24504 			next_mp = NULL;
24505 		}
24506 	} while (multirt_send);
24507 
24508 	ASSERT(ire1 == NULL);
24509 
24510 	/* Restore the original ire; we need it for the trailing frags */
24511 	if (save_ire != NULL) {
24512 		/* REFRELE the last iterated ire */
24513 		ire_refrele(ire);
24514 		/* save_ire has been REFHOLDed */
24515 		ire = save_ire;
24516 		save_ire = NULL;
24517 		q = ire->ire_stq;
24518 	}
24519 
24520 	if (pkt_type == OB_PKT) {
24521 		UPDATE_OB_PKT_COUNT(ire);
24522 	} else {
24523 		out_ill = (ill_t *)q->q_ptr;
24524 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24525 		UPDATE_IB_PKT_COUNT(ire);
24526 	}
24527 
24528 	/* Advance the offset to the second frag starting point. */
24529 	offset += len;
24530 	/*
24531 	 * Update hdr_len from the copied header - there might be less options
24532 	 * in the later fragments.
24533 	 */
24534 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24535 	/* Loop until done. */
24536 	for (;;) {
24537 		uint16_t	offset_and_flags;
24538 		uint16_t	ip_len;
24539 
24540 		if (ip_data_end - offset > len) {
24541 			/*
24542 			 * Carve off the appropriate amount from the original
24543 			 * datagram.
24544 			 */
24545 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24546 				mp = NULL;
24547 				break;
24548 			}
24549 			/*
24550 			 * More frags after this one.  Get another copy
24551 			 * of the header.
24552 			 */
24553 			if (carve_mp->b_datap->db_ref == 1 &&
24554 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24555 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24556 				/* Inline IP header */
24557 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24558 				    hdr_mp->b_rptr;
24559 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24560 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24561 				mp = carve_mp;
24562 			} else {
24563 				if (!(mp = copyb(hdr_mp))) {
24564 					freemsg(carve_mp);
24565 					break;
24566 				}
24567 				/* Get priority marking, if any. */
24568 				mp->b_band = carve_mp->b_band;
24569 				mp->b_cont = carve_mp;
24570 			}
24571 			ipha = (ipha_t *)mp->b_rptr;
24572 			offset_and_flags = IPH_MF;
24573 		} else {
24574 			/*
24575 			 * Last frag.  Consume the header. Set len to
24576 			 * the length of this last piece.
24577 			 */
24578 			len = ip_data_end - offset;
24579 
24580 			/*
24581 			 * Carve off the appropriate amount from the original
24582 			 * datagram.
24583 			 */
24584 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24585 				mp = NULL;
24586 				break;
24587 			}
24588 			if (carve_mp->b_datap->db_ref == 1 &&
24589 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24590 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24591 				/* Inline IP header */
24592 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24593 				    hdr_mp->b_rptr;
24594 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24595 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24596 				mp = carve_mp;
24597 				freeb(hdr_mp);
24598 				hdr_mp = mp;
24599 			} else {
24600 				mp = hdr_mp;
24601 				/* Get priority marking, if any. */
24602 				mp->b_band = carve_mp->b_band;
24603 				mp->b_cont = carve_mp;
24604 			}
24605 			ipha = (ipha_t *)mp->b_rptr;
24606 			/* A frag of a frag might have IPH_MF non-zero */
24607 			offset_and_flags =
24608 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24609 			    IPH_MF;
24610 		}
24611 		offset_and_flags |= (uint16_t)(offset >> 3);
24612 		offset_and_flags |= (uint16_t)frag_flag;
24613 		/* Store the offset and flags in the IP header. */
24614 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24615 
24616 		/* Store the length in the IP header. */
24617 		ip_len = (uint16_t)(len + hdr_len);
24618 		ipha->ipha_length = htons(ip_len);
24619 
24620 		/*
24621 		 * Set the IP header checksum.	Note that mp is just
24622 		 * the header, so this is easy to pass to ip_csum.
24623 		 */
24624 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24625 
24626 		/* Attach a transmit header, if any, and ship it. */
24627 		if (pkt_type == OB_PKT) {
24628 			UPDATE_OB_PKT_COUNT(ire);
24629 		} else {
24630 			out_ill = (ill_t *)q->q_ptr;
24631 			BUMP_MIB(out_ill->ill_ip_mib,
24632 			    ipIfStatsHCOutForwDatagrams);
24633 			UPDATE_IB_PKT_COUNT(ire);
24634 		}
24635 
24636 		if (ire->ire_flags & RTF_MULTIRT) {
24637 			irb = ire->ire_bucket;
24638 			ASSERT(irb != NULL);
24639 
24640 			multirt_send = B_TRUE;
24641 
24642 			/*
24643 			 * Save the original ire; we will need to restore it
24644 			 * for the tailing frags.
24645 			 */
24646 			save_ire = ire;
24647 			IRE_REFHOLD(save_ire);
24648 		}
24649 		/*
24650 		 * Emission loop for this fragment, similar
24651 		 * to what is done for the first fragment.
24652 		 */
24653 		do {
24654 			if (multirt_send) {
24655 				/*
24656 				 * We are in a multiple send case, need to get
24657 				 * the next ire and make a copy of the packet.
24658 				 */
24659 				ASSERT(irb != NULL);
24660 				IRB_REFHOLD(irb);
24661 				for (ire1 = ire->ire_next;
24662 				    ire1 != NULL;
24663 				    ire1 = ire1->ire_next) {
24664 					if (!(ire1->ire_flags & RTF_MULTIRT))
24665 						continue;
24666 					if (ire1->ire_addr != ire->ire_addr)
24667 						continue;
24668 					if (ire1->ire_marks &
24669 					    (IRE_MARK_CONDEMNED|
24670 					    IRE_MARK_HIDDEN)) {
24671 						continue;
24672 					}
24673 					/*
24674 					 * Ensure we do not exceed the MTU
24675 					 * of the next route.
24676 					 */
24677 					if (ire1->ire_max_frag < max_frag) {
24678 						ip_multirt_bad_mtu(ire1,
24679 						    max_frag);
24680 						continue;
24681 					}
24682 
24683 					/* Got one. */
24684 					IRE_REFHOLD(ire1);
24685 					break;
24686 				}
24687 				IRB_REFRELE(irb);
24688 
24689 				if (ire1 != NULL) {
24690 					next_mp = copyb(mp);
24691 					if ((next_mp == NULL) ||
24692 					    ((mp->b_cont != NULL) &&
24693 					    ((next_mp->b_cont =
24694 					    dupmsg(mp->b_cont)) == NULL))) {
24695 						freemsg(next_mp);
24696 						next_mp = NULL;
24697 						ire_refrele(ire1);
24698 						ire1 = NULL;
24699 					}
24700 				}
24701 
24702 				/* Last multiroute ire; don't loop anymore. */
24703 				if (ire1 == NULL) {
24704 					multirt_send = B_FALSE;
24705 				}
24706 			}
24707 
24708 			/* Update transmit header */
24709 			ll_hdr_len = 0;
24710 			LOCK_IRE_FP_MP(ire);
24711 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24712 			if (ll_hdr_mp != NULL) {
24713 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24714 				ll_hdr_len = MBLKL(ll_hdr_mp);
24715 			} else {
24716 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24717 			}
24718 
24719 			if (!ll_hdr_mp) {
24720 				xmit_mp = mp;
24721 
24722 			/*
24723 			 * We have link-layer header that can fit in
24724 			 * our mblk.
24725 			 */
24726 			} else if (mp->b_datap->db_ref == 1 &&
24727 			    ll_hdr_len != 0 &&
24728 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24729 				/* M_DATA fastpath */
24730 				mp->b_rptr -= ll_hdr_len;
24731 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24732 				    ll_hdr_len);
24733 				xmit_mp = mp;
24734 
24735 			/*
24736 			 * Case of res_mp OR the fastpath mp can't fit
24737 			 * in the mblk
24738 			 */
24739 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24740 				xmit_mp->b_cont = mp;
24741 				if (DB_CRED(mp) != NULL)
24742 					mblk_setcred(xmit_mp, DB_CRED(mp));
24743 				/* Get priority marking, if any. */
24744 				if (DB_TYPE(xmit_mp) == M_DATA)
24745 					xmit_mp->b_band = mp->b_band;
24746 
24747 			/* Corner case if copyb failed */
24748 			} else {
24749 				/*
24750 				 * Exit both the replication and
24751 				 * fragmentation loops.
24752 				 */
24753 				UNLOCK_IRE_FP_MP(ire);
24754 				goto drop_pkt;
24755 			}
24756 			UNLOCK_IRE_FP_MP(ire);
24757 
24758 			mp1 = mp;
24759 			out_ill = (ill_t *)q->q_ptr;
24760 
24761 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24762 
24763 			DTRACE_PROBE4(ip4__physical__out__start,
24764 			    ill_t *, NULL, ill_t *, out_ill,
24765 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24766 
24767 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24768 			    ipst->ips_ipv4firewall_physical_out,
24769 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24770 
24771 			DTRACE_PROBE1(ip4__physical__out__end,
24772 			    mblk_t *, xmit_mp);
24773 
24774 			if (mp != mp1 && hdr_mp == mp1)
24775 				hdr_mp = mp;
24776 			if (mp != mp1 && mp_orig == mp1)
24777 				mp_orig = mp;
24778 
24779 			if (xmit_mp != NULL) {
24780 				putnext(q, xmit_mp);
24781 
24782 				BUMP_MIB(out_ill->ill_ip_mib,
24783 				    ipIfStatsHCOutTransmits);
24784 				UPDATE_MIB(out_ill->ill_ip_mib,
24785 				    ipIfStatsHCOutOctets, ip_len);
24786 
24787 				if (pkt_type != OB_PKT) {
24788 					/*
24789 					 * Update the packet count of trailing
24790 					 * RTF_MULTIRT ires.
24791 					 */
24792 					UPDATE_OB_PKT_COUNT(ire);
24793 				}
24794 			}
24795 
24796 			/* All done if we just consumed the hdr_mp. */
24797 			if (mp == hdr_mp) {
24798 				last_frag = B_TRUE;
24799 				BUMP_MIB(out_ill->ill_ip_mib,
24800 				    ipIfStatsOutFragOKs);
24801 			}
24802 
24803 			if (multirt_send) {
24804 				/*
24805 				 * We are in a multiple send case; look for
24806 				 * the next ire and re-enter the loop.
24807 				 */
24808 				ASSERT(ire1);
24809 				ASSERT(next_mp);
24810 				/* REFRELE the current ire before looping */
24811 				ire_refrele(ire);
24812 				ire = ire1;
24813 				ire1 = NULL;
24814 				q = ire->ire_stq;
24815 				mp = next_mp;
24816 				next_mp = NULL;
24817 			}
24818 		} while (multirt_send);
24819 		/*
24820 		 * Restore the original ire; we need it for the
24821 		 * trailing frags
24822 		 */
24823 		if (save_ire != NULL) {
24824 			ASSERT(ire1 == NULL);
24825 			/* REFRELE the last iterated ire */
24826 			ire_refrele(ire);
24827 			/* save_ire has been REFHOLDed */
24828 			ire = save_ire;
24829 			q = ire->ire_stq;
24830 			save_ire = NULL;
24831 		}
24832 
24833 		if (last_frag) {
24834 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24835 			    "ip_wput_frag_end:(%S)",
24836 			    "consumed hdr_mp");
24837 
24838 			if (first_ire != NULL)
24839 				ire_refrele(first_ire);
24840 			return;
24841 		}
24842 		/* Otherwise, advance and loop. */
24843 		offset += len;
24844 	}
24845 
24846 drop_pkt:
24847 	/* Clean up following allocation failure. */
24848 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24849 	freemsg(mp);
24850 	if (mp != hdr_mp)
24851 		freeb(hdr_mp);
24852 	if (mp != mp_orig)
24853 		freemsg(mp_orig);
24854 
24855 	if (save_ire != NULL)
24856 		IRE_REFRELE(save_ire);
24857 	if (first_ire != NULL)
24858 		ire_refrele(first_ire);
24859 
24860 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24861 	    "ip_wput_frag_end:(%S)",
24862 	    "end--alloc failure");
24863 }
24864 
24865 /*
24866  * Copy the header plus those options which have the copy bit set
24867  */
24868 static mblk_t *
24869 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24870 {
24871 	mblk_t	*mp;
24872 	uchar_t	*up;
24873 
24874 	/*
24875 	 * Quick check if we need to look for options without the copy bit
24876 	 * set
24877 	 */
24878 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24879 	if (!mp)
24880 		return (mp);
24881 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24882 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24883 		bcopy(rptr, mp->b_rptr, hdr_len);
24884 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24885 		return (mp);
24886 	}
24887 	up  = mp->b_rptr;
24888 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24889 	up += IP_SIMPLE_HDR_LENGTH;
24890 	rptr += IP_SIMPLE_HDR_LENGTH;
24891 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24892 	while (hdr_len > 0) {
24893 		uint32_t optval;
24894 		uint32_t optlen;
24895 
24896 		optval = *rptr;
24897 		if (optval == IPOPT_EOL)
24898 			break;
24899 		if (optval == IPOPT_NOP)
24900 			optlen = 1;
24901 		else
24902 			optlen = rptr[1];
24903 		if (optval & IPOPT_COPY) {
24904 			bcopy(rptr, up, optlen);
24905 			up += optlen;
24906 		}
24907 		rptr += optlen;
24908 		hdr_len -= optlen;
24909 	}
24910 	/*
24911 	 * Make sure that we drop an even number of words by filling
24912 	 * with EOL to the next word boundary.
24913 	 */
24914 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24915 	    hdr_len & 0x3; hdr_len++)
24916 		*up++ = IPOPT_EOL;
24917 	mp->b_wptr = up;
24918 	/* Update header length */
24919 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24920 	return (mp);
24921 }
24922 
24923 /*
24924  * Delivery to local recipients including fanout to multiple recipients.
24925  * Does not do checksumming of UDP/TCP.
24926  * Note: q should be the read side queue for either the ill or conn.
24927  * Note: rq should be the read side q for the lower (ill) stream.
24928  * We don't send packets to IPPF processing, thus the last argument
24929  * to all the fanout calls are B_FALSE.
24930  */
24931 void
24932 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24933     int fanout_flags, zoneid_t zoneid)
24934 {
24935 	uint32_t	protocol;
24936 	mblk_t		*first_mp;
24937 	boolean_t	mctl_present;
24938 	int		ire_type;
24939 #define	rptr	((uchar_t *)ipha)
24940 	ip_stack_t	*ipst = ill->ill_ipst;
24941 
24942 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24943 	    "ip_wput_local_start: q %p", q);
24944 
24945 	if (ire != NULL) {
24946 		ire_type = ire->ire_type;
24947 	} else {
24948 		/*
24949 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24950 		 * packet is not multicast, we can't tell the ire type.
24951 		 */
24952 		ASSERT(CLASSD(ipha->ipha_dst));
24953 		ire_type = IRE_BROADCAST;
24954 	}
24955 
24956 	first_mp = mp;
24957 	if (first_mp->b_datap->db_type == M_CTL) {
24958 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24959 		if (!io->ipsec_out_secure) {
24960 			/*
24961 			 * This ipsec_out_t was allocated in ip_wput
24962 			 * for multicast packets to store the ill_index.
24963 			 * As this is being delivered locally, we don't
24964 			 * need this anymore.
24965 			 */
24966 			mp = first_mp->b_cont;
24967 			freeb(first_mp);
24968 			first_mp = mp;
24969 			mctl_present = B_FALSE;
24970 		} else {
24971 			/*
24972 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24973 			 * security properties for the looped-back packet.
24974 			 */
24975 			mctl_present = B_TRUE;
24976 			mp = first_mp->b_cont;
24977 			ASSERT(mp != NULL);
24978 			ipsec_out_to_in(first_mp);
24979 		}
24980 	} else {
24981 		mctl_present = B_FALSE;
24982 	}
24983 
24984 	DTRACE_PROBE4(ip4__loopback__in__start,
24985 	    ill_t *, ill, ill_t *, NULL,
24986 	    ipha_t *, ipha, mblk_t *, first_mp);
24987 
24988 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24989 	    ipst->ips_ipv4firewall_loopback_in,
24990 	    ill, NULL, ipha, first_mp, mp, ipst);
24991 
24992 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24993 
24994 	if (first_mp == NULL)
24995 		return;
24996 
24997 	ipst->ips_loopback_packets++;
24998 
24999 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25000 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25001 	if (!IS_SIMPLE_IPH(ipha)) {
25002 		ip_wput_local_options(ipha, ipst);
25003 	}
25004 
25005 	protocol = ipha->ipha_protocol;
25006 	switch (protocol) {
25007 	case IPPROTO_ICMP: {
25008 		ire_t		*ire_zone;
25009 		ilm_t		*ilm;
25010 		mblk_t		*mp1;
25011 		zoneid_t	last_zoneid;
25012 
25013 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25014 			ASSERT(ire_type == IRE_BROADCAST);
25015 			/*
25016 			 * In the multicast case, applications may have joined
25017 			 * the group from different zones, so we need to deliver
25018 			 * the packet to each of them. Loop through the
25019 			 * multicast memberships structures (ilm) on the receive
25020 			 * ill and send a copy of the packet up each matching
25021 			 * one. However, we don't do this for multicasts sent on
25022 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25023 			 * they must stay in the sender's zone.
25024 			 *
25025 			 * ilm_add_v6() ensures that ilms in the same zone are
25026 			 * contiguous in the ill_ilm list. We use this property
25027 			 * to avoid sending duplicates needed when two
25028 			 * applications in the same zone join the same group on
25029 			 * different logical interfaces: we ignore the ilm if
25030 			 * it's zoneid is the same as the last matching one.
25031 			 * In addition, the sending of the packet for
25032 			 * ire_zoneid is delayed until all of the other ilms
25033 			 * have been exhausted.
25034 			 */
25035 			last_zoneid = -1;
25036 			ILM_WALKER_HOLD(ill);
25037 			for (ilm = ill->ill_ilm; ilm != NULL;
25038 			    ilm = ilm->ilm_next) {
25039 				if ((ilm->ilm_flags & ILM_DELETED) ||
25040 				    ipha->ipha_dst != ilm->ilm_addr ||
25041 				    ilm->ilm_zoneid == last_zoneid ||
25042 				    ilm->ilm_zoneid == zoneid ||
25043 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25044 					continue;
25045 				mp1 = ip_copymsg(first_mp);
25046 				if (mp1 == NULL)
25047 					continue;
25048 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25049 				    mctl_present, B_FALSE, ill,
25050 				    ilm->ilm_zoneid);
25051 				last_zoneid = ilm->ilm_zoneid;
25052 			}
25053 			ILM_WALKER_RELE(ill);
25054 			/*
25055 			 * Loopback case: the sending endpoint has
25056 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25057 			 * dispatch the multicast packet to the sending zone.
25058 			 */
25059 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25060 				freemsg(first_mp);
25061 				return;
25062 			}
25063 		} else if (ire_type == IRE_BROADCAST) {
25064 			/*
25065 			 * In the broadcast case, there may be many zones
25066 			 * which need a copy of the packet delivered to them.
25067 			 * There is one IRE_BROADCAST per broadcast address
25068 			 * and per zone; we walk those using a helper function.
25069 			 * In addition, the sending of the packet for zoneid is
25070 			 * delayed until all of the other ires have been
25071 			 * processed.
25072 			 */
25073 			IRB_REFHOLD(ire->ire_bucket);
25074 			ire_zone = NULL;
25075 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25076 			    ire)) != NULL) {
25077 				mp1 = ip_copymsg(first_mp);
25078 				if (mp1 == NULL)
25079 					continue;
25080 
25081 				UPDATE_IB_PKT_COUNT(ire_zone);
25082 				ire_zone->ire_last_used_time = lbolt;
25083 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25084 				    mctl_present, B_FALSE, ill,
25085 				    ire_zone->ire_zoneid);
25086 			}
25087 			IRB_REFRELE(ire->ire_bucket);
25088 		}
25089 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25090 		    0, mctl_present, B_FALSE, ill, zoneid);
25091 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25092 		    "ip_wput_local_end: q %p (%S)",
25093 		    q, "icmp");
25094 		return;
25095 	}
25096 	case IPPROTO_IGMP:
25097 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25098 			/* Bad packet - discarded by igmp_input */
25099 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25100 			    "ip_wput_local_end: q %p (%S)",
25101 			    q, "igmp_input--bad packet");
25102 			if (mctl_present)
25103 				freeb(first_mp);
25104 			return;
25105 		}
25106 		/*
25107 		 * igmp_input() may have returned the pulled up message.
25108 		 * So first_mp and ipha need to be reinitialized.
25109 		 */
25110 		ipha = (ipha_t *)mp->b_rptr;
25111 		if (mctl_present)
25112 			first_mp->b_cont = mp;
25113 		else
25114 			first_mp = mp;
25115 		/* deliver to local raw users */
25116 		break;
25117 	case IPPROTO_ENCAP:
25118 		/*
25119 		 * This case is covered by either ip_fanout_proto, or by
25120 		 * the above security processing for self-tunneled packets.
25121 		 */
25122 		break;
25123 	case IPPROTO_UDP: {
25124 		uint16_t	*up;
25125 		uint32_t	ports;
25126 
25127 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25128 		    UDP_PORTS_OFFSET);
25129 		/* Force a 'valid' checksum. */
25130 		up[3] = 0;
25131 
25132 		ports = *(uint32_t *)up;
25133 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25134 		    (ire_type == IRE_BROADCAST),
25135 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25136 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25137 		    ill, zoneid);
25138 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25139 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25140 		return;
25141 	}
25142 	case IPPROTO_TCP: {
25143 
25144 		/*
25145 		 * For TCP, discard broadcast packets.
25146 		 */
25147 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25148 			freemsg(first_mp);
25149 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25150 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25151 			return;
25152 		}
25153 
25154 		if (mp->b_datap->db_type == M_DATA) {
25155 			/*
25156 			 * M_DATA mblk, so init mblk (chain) for no struio().
25157 			 */
25158 			mblk_t	*mp1 = mp;
25159 
25160 			do {
25161 				mp1->b_datap->db_struioflag = 0;
25162 			} while ((mp1 = mp1->b_cont) != NULL);
25163 		}
25164 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25165 		    <= mp->b_wptr);
25166 		ip_fanout_tcp(q, first_mp, ill, ipha,
25167 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25168 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25169 		    mctl_present, B_FALSE, zoneid);
25170 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25171 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25172 		return;
25173 	}
25174 	case IPPROTO_SCTP:
25175 	{
25176 		uint32_t	ports;
25177 
25178 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25179 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25180 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25181 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25182 		return;
25183 	}
25184 
25185 	default:
25186 		break;
25187 	}
25188 	/*
25189 	 * Find a client for some other protocol.  We give
25190 	 * copies to multiple clients, if more than one is
25191 	 * bound.
25192 	 */
25193 	ip_fanout_proto(q, first_mp, ill, ipha,
25194 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25195 	    mctl_present, B_FALSE, ill, zoneid);
25196 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25197 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25198 #undef	rptr
25199 }
25200 
25201 /*
25202  * Update any source route, record route, or timestamp options.
25203  * Check that we are at end of strict source route.
25204  * The options have been sanity checked by ip_wput_options().
25205  */
25206 static void
25207 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25208 {
25209 	ipoptp_t	opts;
25210 	uchar_t		*opt;
25211 	uint8_t		optval;
25212 	uint8_t		optlen;
25213 	ipaddr_t	dst;
25214 	uint32_t	ts;
25215 	ire_t		*ire;
25216 	timestruc_t	now;
25217 
25218 	ip2dbg(("ip_wput_local_options\n"));
25219 	for (optval = ipoptp_first(&opts, ipha);
25220 	    optval != IPOPT_EOL;
25221 	    optval = ipoptp_next(&opts)) {
25222 		opt = opts.ipoptp_cur;
25223 		optlen = opts.ipoptp_len;
25224 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25225 		switch (optval) {
25226 			uint32_t off;
25227 		case IPOPT_SSRR:
25228 		case IPOPT_LSRR:
25229 			off = opt[IPOPT_OFFSET];
25230 			off--;
25231 			if (optlen < IP_ADDR_LEN ||
25232 			    off > optlen - IP_ADDR_LEN) {
25233 				/* End of source route */
25234 				break;
25235 			}
25236 			/*
25237 			 * This will only happen if two consecutive entries
25238 			 * in the source route contains our address or if
25239 			 * it is a packet with a loose source route which
25240 			 * reaches us before consuming the whole source route
25241 			 */
25242 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25243 			if (optval == IPOPT_SSRR) {
25244 				return;
25245 			}
25246 			/*
25247 			 * Hack: instead of dropping the packet truncate the
25248 			 * source route to what has been used by filling the
25249 			 * rest with IPOPT_NOP.
25250 			 */
25251 			opt[IPOPT_OLEN] = (uint8_t)off;
25252 			while (off < optlen) {
25253 				opt[off++] = IPOPT_NOP;
25254 			}
25255 			break;
25256 		case IPOPT_RR:
25257 			off = opt[IPOPT_OFFSET];
25258 			off--;
25259 			if (optlen < IP_ADDR_LEN ||
25260 			    off > optlen - IP_ADDR_LEN) {
25261 				/* No more room - ignore */
25262 				ip1dbg((
25263 				    "ip_wput_forward_options: end of RR\n"));
25264 				break;
25265 			}
25266 			dst = htonl(INADDR_LOOPBACK);
25267 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25268 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25269 			break;
25270 		case IPOPT_TS:
25271 			/* Insert timestamp if there is romm */
25272 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25273 			case IPOPT_TS_TSONLY:
25274 				off = IPOPT_TS_TIMELEN;
25275 				break;
25276 			case IPOPT_TS_PRESPEC:
25277 			case IPOPT_TS_PRESPEC_RFC791:
25278 				/* Verify that the address matched */
25279 				off = opt[IPOPT_OFFSET] - 1;
25280 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25281 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25282 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25283 				    ipst);
25284 				if (ire == NULL) {
25285 					/* Not for us */
25286 					break;
25287 				}
25288 				ire_refrele(ire);
25289 				/* FALLTHRU */
25290 			case IPOPT_TS_TSANDADDR:
25291 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25292 				break;
25293 			default:
25294 				/*
25295 				 * ip_*put_options should have already
25296 				 * dropped this packet.
25297 				 */
25298 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25299 				    "unknown IT - bug in ip_wput_options?\n");
25300 				return;	/* Keep "lint" happy */
25301 			}
25302 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25303 				/* Increase overflow counter */
25304 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25305 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25306 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25307 				    (off << 4);
25308 				break;
25309 			}
25310 			off = opt[IPOPT_OFFSET] - 1;
25311 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25312 			case IPOPT_TS_PRESPEC:
25313 			case IPOPT_TS_PRESPEC_RFC791:
25314 			case IPOPT_TS_TSANDADDR:
25315 				dst = htonl(INADDR_LOOPBACK);
25316 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25317 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25318 				/* FALLTHRU */
25319 			case IPOPT_TS_TSONLY:
25320 				off = opt[IPOPT_OFFSET] - 1;
25321 				/* Compute # of milliseconds since midnight */
25322 				gethrestime(&now);
25323 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25324 				    now.tv_nsec / (NANOSEC / MILLISEC);
25325 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25326 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25327 				break;
25328 			}
25329 			break;
25330 		}
25331 	}
25332 }
25333 
25334 /*
25335  * Send out a multicast packet on interface ipif.
25336  * The sender does not have an conn.
25337  * Caller verifies that this isn't a PHYI_LOOPBACK.
25338  */
25339 void
25340 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25341 {
25342 	ipha_t	*ipha;
25343 	ire_t	*ire;
25344 	ipaddr_t	dst;
25345 	mblk_t		*first_mp;
25346 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25347 
25348 	/* igmp_sendpkt always allocates a ipsec_out_t */
25349 	ASSERT(mp->b_datap->db_type == M_CTL);
25350 	ASSERT(!ipif->ipif_isv6);
25351 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25352 
25353 	first_mp = mp;
25354 	mp = first_mp->b_cont;
25355 	ASSERT(mp->b_datap->db_type == M_DATA);
25356 	ipha = (ipha_t *)mp->b_rptr;
25357 
25358 	/*
25359 	 * Find an IRE which matches the destination and the outgoing
25360 	 * queue (i.e. the outgoing interface.)
25361 	 */
25362 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25363 		dst = ipif->ipif_pp_dst_addr;
25364 	else
25365 		dst = ipha->ipha_dst;
25366 	/*
25367 	 * The source address has already been initialized by the
25368 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25369 	 * be sufficient rather than MATCH_IRE_IPIF.
25370 	 *
25371 	 * This function is used for sending IGMP packets. We need
25372 	 * to make sure that we send the packet out of the interface
25373 	 * (ipif->ipif_ill) where we joined the group. This is to
25374 	 * prevent from switches doing IGMP snooping to send us multicast
25375 	 * packets for a given group on the interface we have joined.
25376 	 * If we can't find an ire, igmp_sendpkt has already initialized
25377 	 * ipsec_out_attach_if so that this will not be load spread in
25378 	 * ip_newroute_ipif.
25379 	 */
25380 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25381 	    MATCH_IRE_ILL, ipst);
25382 	if (!ire) {
25383 		/*
25384 		 * Mark this packet to make it be delivered to
25385 		 * ip_wput_ire after the new ire has been
25386 		 * created.
25387 		 */
25388 		mp->b_prev = NULL;
25389 		mp->b_next = NULL;
25390 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25391 		    zoneid, &zero_info);
25392 		return;
25393 	}
25394 
25395 	/*
25396 	 * Honor the RTF_SETSRC flag; this is the only case
25397 	 * where we force this addr whatever the current src addr is,
25398 	 * because this address is set by igmp_sendpkt(), and
25399 	 * cannot be specified by any user.
25400 	 */
25401 	if (ire->ire_flags & RTF_SETSRC) {
25402 		ipha->ipha_src = ire->ire_src_addr;
25403 	}
25404 
25405 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25406 }
25407 
25408 /*
25409  * NOTE : This function does not ire_refrele the ire argument passed in.
25410  *
25411  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25412  * failure. The nce_fp_mp can vanish any time in the case of
25413  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25414  * the ire_lock to access the nce_fp_mp in this case.
25415  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25416  * prepending a fastpath message IPQoS processing must precede it, we also set
25417  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25418  * (IPQoS might have set the b_band for CoS marking).
25419  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25420  * must follow it so that IPQoS can mark the dl_priority field for CoS
25421  * marking, if needed.
25422  */
25423 static mblk_t *
25424 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25425 {
25426 	uint_t	hlen;
25427 	ipha_t *ipha;
25428 	mblk_t *mp1;
25429 	boolean_t qos_done = B_FALSE;
25430 	uchar_t	*ll_hdr;
25431 	ip_stack_t	*ipst = ire->ire_ipst;
25432 
25433 #define	rptr	((uchar_t *)ipha)
25434 
25435 	ipha = (ipha_t *)mp->b_rptr;
25436 	hlen = 0;
25437 	LOCK_IRE_FP_MP(ire);
25438 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25439 		ASSERT(DB_TYPE(mp1) == M_DATA);
25440 		/* Initiate IPPF processing */
25441 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25442 			UNLOCK_IRE_FP_MP(ire);
25443 			ip_process(proc, &mp, ill_index);
25444 			if (mp == NULL)
25445 				return (NULL);
25446 
25447 			ipha = (ipha_t *)mp->b_rptr;
25448 			LOCK_IRE_FP_MP(ire);
25449 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25450 				qos_done = B_TRUE;
25451 				goto no_fp_mp;
25452 			}
25453 			ASSERT(DB_TYPE(mp1) == M_DATA);
25454 		}
25455 		hlen = MBLKL(mp1);
25456 		/*
25457 		 * Check if we have enough room to prepend fastpath
25458 		 * header
25459 		 */
25460 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25461 			ll_hdr = rptr - hlen;
25462 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25463 			/*
25464 			 * Set the b_rptr to the start of the link layer
25465 			 * header
25466 			 */
25467 			mp->b_rptr = ll_hdr;
25468 			mp1 = mp;
25469 		} else {
25470 			mp1 = copyb(mp1);
25471 			if (mp1 == NULL)
25472 				goto unlock_err;
25473 			mp1->b_band = mp->b_band;
25474 			mp1->b_cont = mp;
25475 			/*
25476 			 * certain system generated traffic may not
25477 			 * have cred/label in ip header block. This
25478 			 * is true even for a labeled system. But for
25479 			 * labeled traffic, inherit the label in the
25480 			 * new header.
25481 			 */
25482 			if (DB_CRED(mp) != NULL)
25483 				mblk_setcred(mp1, DB_CRED(mp));
25484 			/*
25485 			 * XXX disable ICK_VALID and compute checksum
25486 			 * here; can happen if nce_fp_mp changes and
25487 			 * it can't be copied now due to insufficient
25488 			 * space. (unlikely, fp mp can change, but it
25489 			 * does not increase in length)
25490 			 */
25491 		}
25492 		UNLOCK_IRE_FP_MP(ire);
25493 	} else {
25494 no_fp_mp:
25495 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25496 		if (mp1 == NULL) {
25497 unlock_err:
25498 			UNLOCK_IRE_FP_MP(ire);
25499 			freemsg(mp);
25500 			return (NULL);
25501 		}
25502 		UNLOCK_IRE_FP_MP(ire);
25503 		mp1->b_cont = mp;
25504 		/*
25505 		 * certain system generated traffic may not
25506 		 * have cred/label in ip header block. This
25507 		 * is true even for a labeled system. But for
25508 		 * labeled traffic, inherit the label in the
25509 		 * new header.
25510 		 */
25511 		if (DB_CRED(mp) != NULL)
25512 			mblk_setcred(mp1, DB_CRED(mp));
25513 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25514 			ip_process(proc, &mp1, ill_index);
25515 			if (mp1 == NULL)
25516 				return (NULL);
25517 		}
25518 	}
25519 	return (mp1);
25520 #undef rptr
25521 }
25522 
25523 /*
25524  * Finish the outbound IPsec processing for an IPv6 packet. This function
25525  * is called from ipsec_out_process() if the IPsec packet was processed
25526  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25527  * asynchronously.
25528  */
25529 void
25530 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25531     ire_t *ire_arg)
25532 {
25533 	in6_addr_t *v6dstp;
25534 	ire_t *ire;
25535 	mblk_t *mp;
25536 	ip6_t *ip6h1;
25537 	uint_t	ill_index;
25538 	ipsec_out_t *io;
25539 	boolean_t attach_if, hwaccel;
25540 	uint32_t flags = IP6_NO_IPPOLICY;
25541 	int match_flags;
25542 	zoneid_t zoneid;
25543 	boolean_t ill_need_rele = B_FALSE;
25544 	boolean_t ire_need_rele = B_FALSE;
25545 	ip_stack_t	*ipst;
25546 
25547 	mp = ipsec_mp->b_cont;
25548 	ip6h1 = (ip6_t *)mp->b_rptr;
25549 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25550 	ASSERT(io->ipsec_out_ns != NULL);
25551 	ipst = io->ipsec_out_ns->netstack_ip;
25552 	ill_index = io->ipsec_out_ill_index;
25553 	if (io->ipsec_out_reachable) {
25554 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25555 	}
25556 	attach_if = io->ipsec_out_attach_if;
25557 	hwaccel = io->ipsec_out_accelerated;
25558 	zoneid = io->ipsec_out_zoneid;
25559 	ASSERT(zoneid != ALL_ZONES);
25560 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25561 	/* Multicast addresses should have non-zero ill_index. */
25562 	v6dstp = &ip6h->ip6_dst;
25563 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25564 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25565 	ASSERT(!attach_if || ill_index != 0);
25566 	if (ill_index != 0) {
25567 		if (ill == NULL) {
25568 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25569 			    B_TRUE, ipst);
25570 
25571 			/* Failure case frees things for us. */
25572 			if (ill == NULL)
25573 				return;
25574 
25575 			ill_need_rele = B_TRUE;
25576 		}
25577 		/*
25578 		 * If this packet needs to go out on a particular interface
25579 		 * honor it.
25580 		 */
25581 		if (attach_if) {
25582 			match_flags = MATCH_IRE_ILL;
25583 
25584 			/*
25585 			 * Check if we need an ire that will not be
25586 			 * looked up by anybody else i.e. HIDDEN.
25587 			 */
25588 			if (ill_is_probeonly(ill)) {
25589 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25590 			}
25591 		}
25592 	}
25593 	ASSERT(mp != NULL);
25594 
25595 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25596 		boolean_t unspec_src;
25597 		ipif_t	*ipif;
25598 
25599 		/*
25600 		 * Use the ill_index to get the right ill.
25601 		 */
25602 		unspec_src = io->ipsec_out_unspec_src;
25603 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25604 		if (ipif == NULL) {
25605 			if (ill_need_rele)
25606 				ill_refrele(ill);
25607 			freemsg(ipsec_mp);
25608 			return;
25609 		}
25610 
25611 		if (ire_arg != NULL) {
25612 			ire = ire_arg;
25613 		} else {
25614 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25615 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25616 			ire_need_rele = B_TRUE;
25617 		}
25618 		if (ire != NULL) {
25619 			ipif_refrele(ipif);
25620 			/*
25621 			 * XXX Do the multicast forwarding now, as the IPsec
25622 			 * processing has been done.
25623 			 */
25624 			goto send;
25625 		}
25626 
25627 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25628 		mp->b_prev = NULL;
25629 		mp->b_next = NULL;
25630 
25631 		/*
25632 		 * If the IPsec packet was processed asynchronously,
25633 		 * drop it now.
25634 		 */
25635 		if (q == NULL) {
25636 			if (ill_need_rele)
25637 				ill_refrele(ill);
25638 			freemsg(ipsec_mp);
25639 			return;
25640 		}
25641 
25642 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25643 		    unspec_src, zoneid);
25644 		ipif_refrele(ipif);
25645 	} else {
25646 		if (attach_if) {
25647 			ipif_t	*ipif;
25648 
25649 			ipif = ipif_get_next_ipif(NULL, ill);
25650 			if (ipif == NULL) {
25651 				if (ill_need_rele)
25652 					ill_refrele(ill);
25653 				freemsg(ipsec_mp);
25654 				return;
25655 			}
25656 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25657 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25658 			ire_need_rele = B_TRUE;
25659 			ipif_refrele(ipif);
25660 		} else {
25661 			if (ire_arg != NULL) {
25662 				ire = ire_arg;
25663 			} else {
25664 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25665 				    ipst);
25666 				ire_need_rele = B_TRUE;
25667 			}
25668 		}
25669 		if (ire != NULL)
25670 			goto send;
25671 		/*
25672 		 * ire disappeared underneath.
25673 		 *
25674 		 * What we need to do here is the ip_newroute
25675 		 * logic to get the ire without doing the IPsec
25676 		 * processing. Follow the same old path. But this
25677 		 * time, ip_wput or ire_add_then_send will call us
25678 		 * directly as all the IPsec operations are done.
25679 		 */
25680 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25681 		mp->b_prev = NULL;
25682 		mp->b_next = NULL;
25683 
25684 		/*
25685 		 * If the IPsec packet was processed asynchronously,
25686 		 * drop it now.
25687 		 */
25688 		if (q == NULL) {
25689 			if (ill_need_rele)
25690 				ill_refrele(ill);
25691 			freemsg(ipsec_mp);
25692 			return;
25693 		}
25694 
25695 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25696 		    zoneid, ipst);
25697 	}
25698 	if (ill != NULL && ill_need_rele)
25699 		ill_refrele(ill);
25700 	return;
25701 send:
25702 	if (ill != NULL && ill_need_rele)
25703 		ill_refrele(ill);
25704 
25705 	/* Local delivery */
25706 	if (ire->ire_stq == NULL) {
25707 		ill_t	*out_ill;
25708 		ASSERT(q != NULL);
25709 
25710 		/* PFHooks: LOOPBACK_OUT */
25711 		out_ill = ire_to_ill(ire);
25712 
25713 		DTRACE_PROBE4(ip6__loopback__out__start,
25714 		    ill_t *, NULL, ill_t *, out_ill,
25715 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25716 
25717 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25718 		    ipst->ips_ipv6firewall_loopback_out,
25719 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25720 
25721 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25722 
25723 		if (ipsec_mp != NULL)
25724 			ip_wput_local_v6(RD(q), out_ill,
25725 			    ip6h, ipsec_mp, ire, 0);
25726 		if (ire_need_rele)
25727 			ire_refrele(ire);
25728 		return;
25729 	}
25730 	/*
25731 	 * Everything is done. Send it out on the wire.
25732 	 * We force the insertion of a fragment header using the
25733 	 * IPH_FRAG_HDR flag in two cases:
25734 	 * - after reception of an ICMPv6 "packet too big" message
25735 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25736 	 * - for multirouted IPv6 packets, so that the receiver can
25737 	 *   discard duplicates according to their fragment identifier
25738 	 */
25739 	/* XXX fix flow control problems. */
25740 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25741 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25742 		if (hwaccel) {
25743 			/*
25744 			 * hardware acceleration does not handle these
25745 			 * "slow path" cases.
25746 			 */
25747 			/* IPsec KSTATS: should bump bean counter here. */
25748 			if (ire_need_rele)
25749 				ire_refrele(ire);
25750 			freemsg(ipsec_mp);
25751 			return;
25752 		}
25753 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25754 		    (mp->b_cont ? msgdsize(mp) :
25755 		    mp->b_wptr - (uchar_t *)ip6h)) {
25756 			/* IPsec KSTATS: should bump bean counter here. */
25757 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25758 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25759 			    msgdsize(mp)));
25760 			if (ire_need_rele)
25761 				ire_refrele(ire);
25762 			freemsg(ipsec_mp);
25763 			return;
25764 		}
25765 		ASSERT(mp->b_prev == NULL);
25766 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25767 		    ntohs(ip6h->ip6_plen) +
25768 		    IPV6_HDR_LEN, ire->ire_max_frag));
25769 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25770 		    ire->ire_max_frag);
25771 	} else {
25772 		UPDATE_OB_PKT_COUNT(ire);
25773 		ire->ire_last_used_time = lbolt;
25774 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25775 	}
25776 	if (ire_need_rele)
25777 		ire_refrele(ire);
25778 	freeb(ipsec_mp);
25779 }
25780 
25781 void
25782 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25783 {
25784 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25785 	da_ipsec_t *hada;	/* data attributes */
25786 	ill_t *ill = (ill_t *)q->q_ptr;
25787 
25788 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25789 
25790 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25791 		/* IPsec KSTATS: Bump lose counter here! */
25792 		freemsg(mp);
25793 		return;
25794 	}
25795 
25796 	/*
25797 	 * It's an IPsec packet that must be
25798 	 * accelerated by the Provider, and the
25799 	 * outbound ill is IPsec acceleration capable.
25800 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25801 	 * to the ill.
25802 	 * IPsec KSTATS: should bump packet counter here.
25803 	 */
25804 
25805 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25806 	if (hada_mp == NULL) {
25807 		/* IPsec KSTATS: should bump packet counter here. */
25808 		freemsg(mp);
25809 		return;
25810 	}
25811 
25812 	hada_mp->b_datap->db_type = M_CTL;
25813 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25814 	hada_mp->b_cont = mp;
25815 
25816 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25817 	bzero(hada, sizeof (da_ipsec_t));
25818 	hada->da_type = IPHADA_M_CTL;
25819 
25820 	putnext(q, hada_mp);
25821 }
25822 
25823 /*
25824  * Finish the outbound IPsec processing. This function is called from
25825  * ipsec_out_process() if the IPsec packet was processed
25826  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25827  * asynchronously.
25828  */
25829 void
25830 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25831     ire_t *ire_arg)
25832 {
25833 	uint32_t v_hlen_tos_len;
25834 	ipaddr_t	dst;
25835 	ipif_t	*ipif = NULL;
25836 	ire_t *ire;
25837 	ire_t *ire1 = NULL;
25838 	mblk_t *next_mp = NULL;
25839 	uint32_t max_frag;
25840 	boolean_t multirt_send = B_FALSE;
25841 	mblk_t *mp;
25842 	ipha_t *ipha1;
25843 	uint_t	ill_index;
25844 	ipsec_out_t *io;
25845 	boolean_t attach_if;
25846 	int match_flags;
25847 	irb_t *irb = NULL;
25848 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25849 	zoneid_t zoneid;
25850 	ipxmit_state_t	pktxmit_state;
25851 	ip_stack_t	*ipst;
25852 
25853 #ifdef	_BIG_ENDIAN
25854 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25855 #else
25856 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25857 #endif
25858 
25859 	mp = ipsec_mp->b_cont;
25860 	ipha1 = (ipha_t *)mp->b_rptr;
25861 	ASSERT(mp != NULL);
25862 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25863 	dst = ipha->ipha_dst;
25864 
25865 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25866 	ill_index = io->ipsec_out_ill_index;
25867 	attach_if = io->ipsec_out_attach_if;
25868 	zoneid = io->ipsec_out_zoneid;
25869 	ASSERT(zoneid != ALL_ZONES);
25870 	ipst = io->ipsec_out_ns->netstack_ip;
25871 	ASSERT(io->ipsec_out_ns != NULL);
25872 
25873 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25874 	if (ill_index != 0) {
25875 		if (ill == NULL) {
25876 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25877 			    ill_index, B_FALSE, ipst);
25878 
25879 			/* Failure case frees things for us. */
25880 			if (ill == NULL)
25881 				return;
25882 
25883 			ill_need_rele = B_TRUE;
25884 		}
25885 		/*
25886 		 * If this packet needs to go out on a particular interface
25887 		 * honor it.
25888 		 */
25889 		if (attach_if) {
25890 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25891 
25892 			/*
25893 			 * Check if we need an ire that will not be
25894 			 * looked up by anybody else i.e. HIDDEN.
25895 			 */
25896 			if (ill_is_probeonly(ill)) {
25897 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25898 			}
25899 		}
25900 	}
25901 
25902 	if (CLASSD(dst)) {
25903 		boolean_t conn_dontroute;
25904 		/*
25905 		 * Use the ill_index to get the right ipif.
25906 		 */
25907 		conn_dontroute = io->ipsec_out_dontroute;
25908 		if (ill_index == 0)
25909 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25910 		else
25911 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25912 		if (ipif == NULL) {
25913 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25914 			    " multicast\n"));
25915 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25916 			freemsg(ipsec_mp);
25917 			goto done;
25918 		}
25919 		/*
25920 		 * ipha_src has already been intialized with the
25921 		 * value of the ipif in ip_wput. All we need now is
25922 		 * an ire to send this downstream.
25923 		 */
25924 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25925 		    MBLK_GETLABEL(mp), match_flags, ipst);
25926 		if (ire != NULL) {
25927 			ill_t *ill1;
25928 			/*
25929 			 * Do the multicast forwarding now, as the IPsec
25930 			 * processing has been done.
25931 			 */
25932 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25933 			    (ill1 = ire_to_ill(ire))) {
25934 				if (ip_mforward(ill1, ipha, mp)) {
25935 					freemsg(ipsec_mp);
25936 					ip1dbg(("ip_wput_ipsec_out: mforward "
25937 					    "failed\n"));
25938 					ire_refrele(ire);
25939 					goto done;
25940 				}
25941 			}
25942 			goto send;
25943 		}
25944 
25945 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25946 		mp->b_prev = NULL;
25947 		mp->b_next = NULL;
25948 
25949 		/*
25950 		 * If the IPsec packet was processed asynchronously,
25951 		 * drop it now.
25952 		 */
25953 		if (q == NULL) {
25954 			freemsg(ipsec_mp);
25955 			goto done;
25956 		}
25957 
25958 		/*
25959 		 * We may be using a wrong ipif to create the ire.
25960 		 * But it is okay as the source address is assigned
25961 		 * for the packet already. Next outbound packet would
25962 		 * create the IRE with the right IPIF in ip_wput.
25963 		 *
25964 		 * Also handle RTF_MULTIRT routes.
25965 		 */
25966 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25967 		    zoneid, &zero_info);
25968 	} else {
25969 		if (attach_if) {
25970 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25971 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25972 		} else {
25973 			if (ire_arg != NULL) {
25974 				ire = ire_arg;
25975 				ire_need_rele = B_FALSE;
25976 			} else {
25977 				ire = ire_cache_lookup(dst, zoneid,
25978 				    MBLK_GETLABEL(mp), ipst);
25979 			}
25980 		}
25981 		if (ire != NULL) {
25982 			goto send;
25983 		}
25984 
25985 		/*
25986 		 * ire disappeared underneath.
25987 		 *
25988 		 * What we need to do here is the ip_newroute
25989 		 * logic to get the ire without doing the IPsec
25990 		 * processing. Follow the same old path. But this
25991 		 * time, ip_wput or ire_add_then_put will call us
25992 		 * directly as all the IPsec operations are done.
25993 		 */
25994 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25995 		mp->b_prev = NULL;
25996 		mp->b_next = NULL;
25997 
25998 		/*
25999 		 * If the IPsec packet was processed asynchronously,
26000 		 * drop it now.
26001 		 */
26002 		if (q == NULL) {
26003 			freemsg(ipsec_mp);
26004 			goto done;
26005 		}
26006 
26007 		/*
26008 		 * Since we're going through ip_newroute() again, we
26009 		 * need to make sure we don't:
26010 		 *
26011 		 *	1.) Trigger the ASSERT() with the ipha_ident
26012 		 *	    overloading.
26013 		 *	2.) Redo transport-layer checksumming, since we've
26014 		 *	    already done all that to get this far.
26015 		 *
26016 		 * The easiest way not do either of the above is to set
26017 		 * the ipha_ident field to IP_HDR_INCLUDED.
26018 		 */
26019 		ipha->ipha_ident = IP_HDR_INCLUDED;
26020 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26021 		    zoneid, ipst);
26022 	}
26023 	goto done;
26024 send:
26025 	if (ire->ire_stq == NULL) {
26026 		ill_t	*out_ill;
26027 		/*
26028 		 * Loopbacks go through ip_wput_local except for one case.
26029 		 * We come here if we generate a icmp_frag_needed message
26030 		 * after IPsec processing is over. When this function calls
26031 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26032 		 * icmp_frag_needed. The message generated comes back here
26033 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26034 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26035 		 * source address as it is usually set in ip_wput_ire. As
26036 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26037 		 * and we end up here. We can't enter ip_wput_ire once the
26038 		 * IPsec processing is over and hence we need to do it here.
26039 		 */
26040 		ASSERT(q != NULL);
26041 		UPDATE_OB_PKT_COUNT(ire);
26042 		ire->ire_last_used_time = lbolt;
26043 		if (ipha->ipha_src == 0)
26044 			ipha->ipha_src = ire->ire_src_addr;
26045 
26046 		/* PFHooks: LOOPBACK_OUT */
26047 		out_ill = ire_to_ill(ire);
26048 
26049 		DTRACE_PROBE4(ip4__loopback__out__start,
26050 		    ill_t *, NULL, ill_t *, out_ill,
26051 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26052 
26053 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26054 		    ipst->ips_ipv4firewall_loopback_out,
26055 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26056 
26057 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26058 
26059 		if (ipsec_mp != NULL)
26060 			ip_wput_local(RD(q), out_ill,
26061 			    ipha, ipsec_mp, ire, 0, zoneid);
26062 		if (ire_need_rele)
26063 			ire_refrele(ire);
26064 		goto done;
26065 	}
26066 
26067 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26068 		/*
26069 		 * We are through with IPsec processing.
26070 		 * Fragment this and send it on the wire.
26071 		 */
26072 		if (io->ipsec_out_accelerated) {
26073 			/*
26074 			 * The packet has been accelerated but must
26075 			 * be fragmented. This should not happen
26076 			 * since AH and ESP must not accelerate
26077 			 * packets that need fragmentation, however
26078 			 * the configuration could have changed
26079 			 * since the AH or ESP processing.
26080 			 * Drop packet.
26081 			 * IPsec KSTATS: bump bean counter here.
26082 			 */
26083 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26084 			    "fragmented accelerated packet!\n"));
26085 			freemsg(ipsec_mp);
26086 		} else {
26087 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26088 		}
26089 		if (ire_need_rele)
26090 			ire_refrele(ire);
26091 		goto done;
26092 	}
26093 
26094 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26095 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26096 	    (void *)ire->ire_ipif, (void *)ipif));
26097 
26098 	/*
26099 	 * Multiroute the secured packet, unless IPsec really
26100 	 * requires the packet to go out only through a particular
26101 	 * interface.
26102 	 */
26103 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26104 		ire_t *first_ire;
26105 		irb = ire->ire_bucket;
26106 		ASSERT(irb != NULL);
26107 		/*
26108 		 * This ire has been looked up as the one that
26109 		 * goes through the given ipif;
26110 		 * make sure we do not omit any other multiroute ire
26111 		 * that may be present in the bucket before this one.
26112 		 */
26113 		IRB_REFHOLD(irb);
26114 		for (first_ire = irb->irb_ire;
26115 		    first_ire != NULL;
26116 		    first_ire = first_ire->ire_next) {
26117 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26118 			    (first_ire->ire_addr == ire->ire_addr) &&
26119 			    !(first_ire->ire_marks &
26120 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26121 				break;
26122 			}
26123 		}
26124 
26125 		if ((first_ire != NULL) && (first_ire != ire)) {
26126 			/*
26127 			 * Don't change the ire if the packet must
26128 			 * be fragmented if sent via this new one.
26129 			 */
26130 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26131 				IRE_REFHOLD(first_ire);
26132 				if (ire_need_rele)
26133 					ire_refrele(ire);
26134 				else
26135 					ire_need_rele = B_TRUE;
26136 				ire = first_ire;
26137 			}
26138 		}
26139 		IRB_REFRELE(irb);
26140 
26141 		multirt_send = B_TRUE;
26142 		max_frag = ire->ire_max_frag;
26143 	} else {
26144 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26145 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26146 			    "flag, attach_if %d\n", attach_if));
26147 		}
26148 	}
26149 
26150 	/*
26151 	 * In most cases, the emission loop below is entered only once.
26152 	 * Only in the case where the ire holds the RTF_MULTIRT
26153 	 * flag, we loop to process all RTF_MULTIRT ires in the
26154 	 * bucket, and send the packet through all crossed
26155 	 * RTF_MULTIRT routes.
26156 	 */
26157 	do {
26158 		if (multirt_send) {
26159 			/*
26160 			 * ire1 holds here the next ire to process in the
26161 			 * bucket. If multirouting is expected,
26162 			 * any non-RTF_MULTIRT ire that has the
26163 			 * right destination address is ignored.
26164 			 */
26165 			ASSERT(irb != NULL);
26166 			IRB_REFHOLD(irb);
26167 			for (ire1 = ire->ire_next;
26168 			    ire1 != NULL;
26169 			    ire1 = ire1->ire_next) {
26170 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26171 					continue;
26172 				if (ire1->ire_addr != ire->ire_addr)
26173 					continue;
26174 				if (ire1->ire_marks &
26175 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26176 					continue;
26177 				/* No loopback here */
26178 				if (ire1->ire_stq == NULL)
26179 					continue;
26180 				/*
26181 				 * Ensure we do not exceed the MTU
26182 				 * of the next route.
26183 				 */
26184 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26185 					ip_multirt_bad_mtu(ire1, max_frag);
26186 					continue;
26187 				}
26188 
26189 				IRE_REFHOLD(ire1);
26190 				break;
26191 			}
26192 			IRB_REFRELE(irb);
26193 			if (ire1 != NULL) {
26194 				/*
26195 				 * We are in a multiple send case, need to
26196 				 * make a copy of the packet.
26197 				 */
26198 				next_mp = copymsg(ipsec_mp);
26199 				if (next_mp == NULL) {
26200 					ire_refrele(ire1);
26201 					ire1 = NULL;
26202 				}
26203 			}
26204 		}
26205 		/*
26206 		 * Everything is done. Send it out on the wire
26207 		 *
26208 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26209 		 * either send it on the wire or, in the case of
26210 		 * HW acceleration, call ipsec_hw_putnext.
26211 		 */
26212 		if (ire->ire_nce &&
26213 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26214 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26215 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26216 			/*
26217 			 * If ire's link-layer is unresolved (this
26218 			 * would only happen if the incomplete ire
26219 			 * was added to cachetable via forwarding path)
26220 			 * don't bother going to ip_xmit_v4. Just drop the
26221 			 * packet.
26222 			 * There is a slight risk here, in that, if we
26223 			 * have the forwarding path create an incomplete
26224 			 * IRE, then until the IRE is completed, any
26225 			 * transmitted IPsec packets will be dropped
26226 			 * instead of being queued waiting for resolution.
26227 			 *
26228 			 * But the likelihood of a forwarding packet and a wput
26229 			 * packet sending to the same dst at the same time
26230 			 * and there not yet be an ARP entry for it is small.
26231 			 * Furthermore, if this actually happens, it might
26232 			 * be likely that wput would generate multiple
26233 			 * packets (and forwarding would also have a train
26234 			 * of packets) for that destination. If this is
26235 			 * the case, some of them would have been dropped
26236 			 * anyway, since ARP only queues a few packets while
26237 			 * waiting for resolution
26238 			 *
26239 			 * NOTE: We should really call ip_xmit_v4,
26240 			 * and let it queue the packet and send the
26241 			 * ARP query and have ARP come back thus:
26242 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26243 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26244 			 * hw accel work. But it's too complex to get
26245 			 * the IPsec hw  acceleration approach to fit
26246 			 * well with ip_xmit_v4 doing ARP without
26247 			 * doing IPsec simplification. For now, we just
26248 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26249 			 * that we can continue with the send on the next
26250 			 * attempt.
26251 			 *
26252 			 * XXX THis should be revisited, when
26253 			 * the IPsec/IP interaction is cleaned up
26254 			 */
26255 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26256 			    " - dropping packet\n"));
26257 			freemsg(ipsec_mp);
26258 			/*
26259 			 * Call ip_xmit_v4() to trigger ARP query
26260 			 * in case the nce_state is ND_INITIAL
26261 			 */
26262 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26263 			goto drop_pkt;
26264 		}
26265 
26266 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26267 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26268 		    mblk_t *, ipsec_mp);
26269 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26270 		    ipst->ips_ipv4firewall_physical_out,
26271 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26272 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26273 		if (ipsec_mp == NULL)
26274 			goto drop_pkt;
26275 
26276 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26277 		pktxmit_state = ip_xmit_v4(mp, ire,
26278 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26279 
26280 		if ((pktxmit_state ==  SEND_FAILED) ||
26281 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26282 
26283 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26284 drop_pkt:
26285 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26286 			    ipIfStatsOutDiscards);
26287 			if (ire_need_rele)
26288 				ire_refrele(ire);
26289 			if (ire1 != NULL) {
26290 				ire_refrele(ire1);
26291 				freemsg(next_mp);
26292 			}
26293 			goto done;
26294 		}
26295 
26296 		freeb(ipsec_mp);
26297 		if (ire_need_rele)
26298 			ire_refrele(ire);
26299 
26300 		if (ire1 != NULL) {
26301 			ire = ire1;
26302 			ire_need_rele = B_TRUE;
26303 			ASSERT(next_mp);
26304 			ipsec_mp = next_mp;
26305 			mp = ipsec_mp->b_cont;
26306 			ire1 = NULL;
26307 			next_mp = NULL;
26308 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26309 		} else {
26310 			multirt_send = B_FALSE;
26311 		}
26312 	} while (multirt_send);
26313 done:
26314 	if (ill != NULL && ill_need_rele)
26315 		ill_refrele(ill);
26316 	if (ipif != NULL)
26317 		ipif_refrele(ipif);
26318 }
26319 
26320 /*
26321  * Get the ill corresponding to the specified ire, and compare its
26322  * capabilities with the protocol and algorithms specified by the
26323  * the SA obtained from ipsec_out. If they match, annotate the
26324  * ipsec_out structure to indicate that the packet needs acceleration.
26325  *
26326  *
26327  * A packet is eligible for outbound hardware acceleration if the
26328  * following conditions are satisfied:
26329  *
26330  * 1. the packet will not be fragmented
26331  * 2. the provider supports the algorithm
26332  * 3. there is no pending control message being exchanged
26333  * 4. snoop is not attached
26334  * 5. the destination address is not a broadcast or multicast address.
26335  *
26336  * Rationale:
26337  *	- Hardware drivers do not support fragmentation with
26338  *	  the current interface.
26339  *	- snoop, multicast, and broadcast may result in exposure of
26340  *	  a cleartext datagram.
26341  * We check all five of these conditions here.
26342  *
26343  * XXX would like to nuke "ire_t *" parameter here; problem is that
26344  * IRE is only way to figure out if a v4 address is a broadcast and
26345  * thus ineligible for acceleration...
26346  */
26347 static void
26348 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26349 {
26350 	ipsec_out_t *io;
26351 	mblk_t *data_mp;
26352 	uint_t plen, overhead;
26353 	ip_stack_t	*ipst;
26354 
26355 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26356 		return;
26357 
26358 	if (ill == NULL)
26359 		return;
26360 	ipst = ill->ill_ipst;
26361 	/*
26362 	 * Destination address is a broadcast or multicast.  Punt.
26363 	 */
26364 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26365 	    IRE_LOCAL)))
26366 		return;
26367 
26368 	data_mp = ipsec_mp->b_cont;
26369 
26370 	if (ill->ill_isv6) {
26371 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26372 
26373 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26374 			return;
26375 
26376 		plen = ip6h->ip6_plen;
26377 	} else {
26378 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26379 
26380 		if (CLASSD(ipha->ipha_dst))
26381 			return;
26382 
26383 		plen = ipha->ipha_length;
26384 	}
26385 	/*
26386 	 * Is there a pending DLPI control message being exchanged
26387 	 * between IP/IPsec and the DLS Provider? If there is, it
26388 	 * could be a SADB update, and the state of the DLS Provider
26389 	 * SADB might not be in sync with the SADB maintained by
26390 	 * IPsec. To avoid dropping packets or using the wrong keying
26391 	 * material, we do not accelerate this packet.
26392 	 */
26393 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26394 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26395 		    "ill_dlpi_pending! don't accelerate packet\n"));
26396 		return;
26397 	}
26398 
26399 	/*
26400 	 * Is the Provider in promiscous mode? If it does, we don't
26401 	 * accelerate the packet since it will bounce back up to the
26402 	 * listeners in the clear.
26403 	 */
26404 	if (ill->ill_promisc_on_phys) {
26405 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26406 		    "ill in promiscous mode, don't accelerate packet\n"));
26407 		return;
26408 	}
26409 
26410 	/*
26411 	 * Will the packet require fragmentation?
26412 	 */
26413 
26414 	/*
26415 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26416 	 * as is used elsewhere.
26417 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26418 	 *	+ 2-byte trailer
26419 	 */
26420 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26421 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26422 
26423 	if ((plen + overhead) > ill->ill_max_mtu)
26424 		return;
26425 
26426 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26427 
26428 	/*
26429 	 * Can the ill accelerate this IPsec protocol and algorithm
26430 	 * specified by the SA?
26431 	 */
26432 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26433 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26434 		return;
26435 	}
26436 
26437 	/*
26438 	 * Tell AH or ESP that the outbound ill is capable of
26439 	 * accelerating this packet.
26440 	 */
26441 	io->ipsec_out_is_capab_ill = B_TRUE;
26442 }
26443 
26444 /*
26445  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26446  *
26447  * If this function returns B_TRUE, the requested SA's have been filled
26448  * into the ipsec_out_*_sa pointers.
26449  *
26450  * If the function returns B_FALSE, the packet has been "consumed", most
26451  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26452  *
26453  * The SA references created by the protocol-specific "select"
26454  * function will be released when the ipsec_mp is freed, thanks to the
26455  * ipsec_out_free destructor -- see spd.c.
26456  */
26457 static boolean_t
26458 ipsec_out_select_sa(mblk_t *ipsec_mp)
26459 {
26460 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26461 	ipsec_out_t *io;
26462 	ipsec_policy_t *pp;
26463 	ipsec_action_t *ap;
26464 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26465 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26466 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26467 
26468 	if (!io->ipsec_out_secure) {
26469 		/*
26470 		 * We came here by mistake.
26471 		 * Don't bother with ipsec processing
26472 		 * We should "discourage" this path in the future.
26473 		 */
26474 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26475 		return (B_FALSE);
26476 	}
26477 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26478 	ASSERT((io->ipsec_out_policy != NULL) ||
26479 	    (io->ipsec_out_act != NULL));
26480 
26481 	ASSERT(io->ipsec_out_failed == B_FALSE);
26482 
26483 	/*
26484 	 * IPsec processing has started.
26485 	 */
26486 	io->ipsec_out_proc_begin = B_TRUE;
26487 	ap = io->ipsec_out_act;
26488 	if (ap == NULL) {
26489 		pp = io->ipsec_out_policy;
26490 		ASSERT(pp != NULL);
26491 		ap = pp->ipsp_act;
26492 		ASSERT(ap != NULL);
26493 	}
26494 
26495 	/*
26496 	 * We have an action.  now, let's select SA's.
26497 	 * (In the future, we can cache this in the conn_t..)
26498 	 */
26499 	if (ap->ipa_want_esp) {
26500 		if (io->ipsec_out_esp_sa == NULL) {
26501 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26502 			    IPPROTO_ESP);
26503 		}
26504 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26505 	}
26506 
26507 	if (ap->ipa_want_ah) {
26508 		if (io->ipsec_out_ah_sa == NULL) {
26509 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26510 			    IPPROTO_AH);
26511 		}
26512 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26513 		/*
26514 		 * The ESP and AH processing order needs to be preserved
26515 		 * when both protocols are required (ESP should be applied
26516 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26517 		 * when both ESP and AH are required, and an AH ACQUIRE
26518 		 * is needed.
26519 		 */
26520 		if (ap->ipa_want_esp && need_ah_acquire)
26521 			need_esp_acquire = B_TRUE;
26522 	}
26523 
26524 	/*
26525 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26526 	 * Release SAs that got referenced, but will not be used until we
26527 	 * acquire _all_ of the SAs we need.
26528 	 */
26529 	if (need_ah_acquire || need_esp_acquire) {
26530 		if (io->ipsec_out_ah_sa != NULL) {
26531 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26532 			io->ipsec_out_ah_sa = NULL;
26533 		}
26534 		if (io->ipsec_out_esp_sa != NULL) {
26535 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26536 			io->ipsec_out_esp_sa = NULL;
26537 		}
26538 
26539 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26540 		return (B_FALSE);
26541 	}
26542 
26543 	return (B_TRUE);
26544 }
26545 
26546 /*
26547  * Process an IPSEC_OUT message and see what you can
26548  * do with it.
26549  * IPQoS Notes:
26550  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26551  * IPsec.
26552  * XXX would like to nuke ire_t.
26553  * XXX ill_index better be "real"
26554  */
26555 void
26556 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26557 {
26558 	ipsec_out_t *io;
26559 	ipsec_policy_t *pp;
26560 	ipsec_action_t *ap;
26561 	ipha_t *ipha;
26562 	ip6_t *ip6h;
26563 	mblk_t *mp;
26564 	ill_t *ill;
26565 	zoneid_t zoneid;
26566 	ipsec_status_t ipsec_rc;
26567 	boolean_t ill_need_rele = B_FALSE;
26568 	ip_stack_t	*ipst;
26569 	ipsec_stack_t	*ipss;
26570 
26571 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26572 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26573 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26574 	ipst = io->ipsec_out_ns->netstack_ip;
26575 	mp = ipsec_mp->b_cont;
26576 
26577 	/*
26578 	 * Initiate IPPF processing. We do it here to account for packets
26579 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26580 	 * We can check for ipsec_out_proc_begin even for such packets, as
26581 	 * they will always be false (asserted below).
26582 	 */
26583 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26584 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26585 		    io->ipsec_out_ill_index : ill_index);
26586 		if (mp == NULL) {
26587 			ip2dbg(("ipsec_out_process: packet dropped "\
26588 			    "during IPPF processing\n"));
26589 			freeb(ipsec_mp);
26590 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26591 			return;
26592 		}
26593 	}
26594 
26595 	if (!io->ipsec_out_secure) {
26596 		/*
26597 		 * We came here by mistake.
26598 		 * Don't bother with ipsec processing
26599 		 * Should "discourage" this path in the future.
26600 		 */
26601 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26602 		goto done;
26603 	}
26604 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26605 	ASSERT((io->ipsec_out_policy != NULL) ||
26606 	    (io->ipsec_out_act != NULL));
26607 	ASSERT(io->ipsec_out_failed == B_FALSE);
26608 
26609 	ipss = ipst->ips_netstack->netstack_ipsec;
26610 	if (!ipsec_loaded(ipss)) {
26611 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26612 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26613 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26614 		} else {
26615 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26616 		}
26617 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26618 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26619 		    &ipss->ipsec_dropper);
26620 		return;
26621 	}
26622 
26623 	/*
26624 	 * IPsec processing has started.
26625 	 */
26626 	io->ipsec_out_proc_begin = B_TRUE;
26627 	ap = io->ipsec_out_act;
26628 	if (ap == NULL) {
26629 		pp = io->ipsec_out_policy;
26630 		ASSERT(pp != NULL);
26631 		ap = pp->ipsp_act;
26632 		ASSERT(ap != NULL);
26633 	}
26634 
26635 	/*
26636 	 * Save the outbound ill index. When the packet comes back
26637 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26638 	 * before sending it the accelerated packet.
26639 	 */
26640 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26641 		int ifindex;
26642 		ill = ire_to_ill(ire);
26643 		ifindex = ill->ill_phyint->phyint_ifindex;
26644 		io->ipsec_out_capab_ill_index = ifindex;
26645 	}
26646 
26647 	/*
26648 	 * The order of processing is first insert a IP header if needed.
26649 	 * Then insert the ESP header and then the AH header.
26650 	 */
26651 	if ((io->ipsec_out_se_done == B_FALSE) &&
26652 	    (ap->ipa_want_se)) {
26653 		/*
26654 		 * First get the outer IP header before sending
26655 		 * it to ESP.
26656 		 */
26657 		ipha_t *oipha, *iipha;
26658 		mblk_t *outer_mp, *inner_mp;
26659 
26660 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26661 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26662 			    "ipsec_out_process: "
26663 			    "Self-Encapsulation failed: Out of memory\n");
26664 			freemsg(ipsec_mp);
26665 			if (ill != NULL) {
26666 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26667 			} else {
26668 				BUMP_MIB(&ipst->ips_ip_mib,
26669 				    ipIfStatsOutDiscards);
26670 			}
26671 			return;
26672 		}
26673 		inner_mp = ipsec_mp->b_cont;
26674 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26675 		oipha = (ipha_t *)outer_mp->b_rptr;
26676 		iipha = (ipha_t *)inner_mp->b_rptr;
26677 		*oipha = *iipha;
26678 		outer_mp->b_wptr += sizeof (ipha_t);
26679 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26680 		    sizeof (ipha_t));
26681 		oipha->ipha_protocol = IPPROTO_ENCAP;
26682 		oipha->ipha_version_and_hdr_length =
26683 		    IP_SIMPLE_HDR_VERSION;
26684 		oipha->ipha_hdr_checksum = 0;
26685 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26686 		outer_mp->b_cont = inner_mp;
26687 		ipsec_mp->b_cont = outer_mp;
26688 
26689 		io->ipsec_out_se_done = B_TRUE;
26690 		io->ipsec_out_tunnel = B_TRUE;
26691 	}
26692 
26693 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26694 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26695 	    !ipsec_out_select_sa(ipsec_mp))
26696 		return;
26697 
26698 	/*
26699 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26700 	 * to do the heavy lifting.
26701 	 */
26702 	zoneid = io->ipsec_out_zoneid;
26703 	ASSERT(zoneid != ALL_ZONES);
26704 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26705 		ASSERT(io->ipsec_out_esp_sa != NULL);
26706 		io->ipsec_out_esp_done = B_TRUE;
26707 		/*
26708 		 * Note that since hw accel can only apply one transform,
26709 		 * not two, we skip hw accel for ESP if we also have AH
26710 		 * This is an design limitation of the interface
26711 		 * which should be revisited.
26712 		 */
26713 		ASSERT(ire != NULL);
26714 		if (io->ipsec_out_ah_sa == NULL) {
26715 			ill = (ill_t *)ire->ire_stq->q_ptr;
26716 			ipsec_out_is_accelerated(ipsec_mp,
26717 			    io->ipsec_out_esp_sa, ill, ire);
26718 		}
26719 
26720 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26721 		switch (ipsec_rc) {
26722 		case IPSEC_STATUS_SUCCESS:
26723 			break;
26724 		case IPSEC_STATUS_FAILED:
26725 			if (ill != NULL) {
26726 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26727 			} else {
26728 				BUMP_MIB(&ipst->ips_ip_mib,
26729 				    ipIfStatsOutDiscards);
26730 			}
26731 			/* FALLTHRU */
26732 		case IPSEC_STATUS_PENDING:
26733 			return;
26734 		}
26735 	}
26736 
26737 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26738 		ASSERT(io->ipsec_out_ah_sa != NULL);
26739 		io->ipsec_out_ah_done = B_TRUE;
26740 		if (ire == NULL) {
26741 			int idx = io->ipsec_out_capab_ill_index;
26742 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26743 			    NULL, NULL, NULL, NULL, ipst);
26744 			ill_need_rele = B_TRUE;
26745 		} else {
26746 			ill = (ill_t *)ire->ire_stq->q_ptr;
26747 		}
26748 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26749 		    ire);
26750 
26751 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26752 		switch (ipsec_rc) {
26753 		case IPSEC_STATUS_SUCCESS:
26754 			break;
26755 		case IPSEC_STATUS_FAILED:
26756 			if (ill != NULL) {
26757 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26758 			} else {
26759 				BUMP_MIB(&ipst->ips_ip_mib,
26760 				    ipIfStatsOutDiscards);
26761 			}
26762 			/* FALLTHRU */
26763 		case IPSEC_STATUS_PENDING:
26764 			if (ill != NULL && ill_need_rele)
26765 				ill_refrele(ill);
26766 			return;
26767 		}
26768 	}
26769 	/*
26770 	 * We are done with IPsec processing. Send it over
26771 	 * the wire.
26772 	 */
26773 done:
26774 	mp = ipsec_mp->b_cont;
26775 	ipha = (ipha_t *)mp->b_rptr;
26776 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26777 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26778 	} else {
26779 		ip6h = (ip6_t *)ipha;
26780 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26781 	}
26782 	if (ill != NULL && ill_need_rele)
26783 		ill_refrele(ill);
26784 }
26785 
26786 /* ARGSUSED */
26787 void
26788 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26789 {
26790 	opt_restart_t	*or;
26791 	int	err;
26792 	conn_t	*connp;
26793 
26794 	ASSERT(CONN_Q(q));
26795 	connp = Q_TO_CONN(q);
26796 
26797 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26798 	or = (opt_restart_t *)first_mp->b_rptr;
26799 	/*
26800 	 * We don't need to pass any credentials here since this is just
26801 	 * a restart. The credentials are passed in when svr4_optcom_req
26802 	 * is called the first time (from ip_wput_nondata).
26803 	 */
26804 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26805 		err = svr4_optcom_req(q, first_mp, NULL,
26806 		    &ip_opt_obj);
26807 	} else {
26808 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26809 		err = tpi_optcom_req(q, first_mp, NULL,
26810 		    &ip_opt_obj);
26811 	}
26812 	if (err != EINPROGRESS) {
26813 		/* operation is done */
26814 		CONN_OPER_PENDING_DONE(connp);
26815 	}
26816 }
26817 
26818 /*
26819  * ioctls that go through a down/up sequence may need to wait for the down
26820  * to complete. This involves waiting for the ire and ipif refcnts to go down
26821  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26822  */
26823 /* ARGSUSED */
26824 void
26825 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26826 {
26827 	struct iocblk *iocp;
26828 	mblk_t *mp1;
26829 	ip_ioctl_cmd_t *ipip;
26830 	int err;
26831 	sin_t	*sin;
26832 	struct lifreq *lifr;
26833 	struct ifreq *ifr;
26834 
26835 	iocp = (struct iocblk *)mp->b_rptr;
26836 	ASSERT(ipsq != NULL);
26837 	/* Existence of mp1 verified in ip_wput_nondata */
26838 	mp1 = mp->b_cont->b_cont;
26839 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26840 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26841 		/*
26842 		 * Special case where ipsq_current_ipif is not set:
26843 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26844 		 * ill could also have become part of a ipmp group in the
26845 		 * process, we are here as were not able to complete the
26846 		 * operation in ipif_set_values because we could not become
26847 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26848 		 * will not be set so we need to set it.
26849 		 */
26850 		ill_t *ill = q->q_ptr;
26851 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26852 	}
26853 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26854 
26855 	if (ipip->ipi_cmd_type == IF_CMD) {
26856 		/* This a old style SIOC[GS]IF* command */
26857 		ifr = (struct ifreq *)mp1->b_rptr;
26858 		sin = (sin_t *)&ifr->ifr_addr;
26859 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26860 		/* This a new style SIOC[GS]LIF* command */
26861 		lifr = (struct lifreq *)mp1->b_rptr;
26862 		sin = (sin_t *)&lifr->lifr_addr;
26863 	} else {
26864 		sin = NULL;
26865 	}
26866 
26867 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26868 	    ipip, mp1->b_rptr);
26869 
26870 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26871 }
26872 
26873 /*
26874  * ioctl processing
26875  *
26876  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26877  * the ioctl command in the ioctl tables, determines the copyin data size
26878  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26879  *
26880  * ioctl processing then continues when the M_IOCDATA makes its way down to
26881  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26882  * associated 'conn' is refheld till the end of the ioctl and the general
26883  * ioctl processing function ip_process_ioctl() is called to extract the
26884  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26885  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26886  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26887  * is used to extract the ioctl's arguments.
26888  *
26889  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26890  * so goes thru the serialization primitive ipsq_try_enter. Then the
26891  * appropriate function to handle the ioctl is called based on the entry in
26892  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26893  * which also refreleases the 'conn' that was refheld at the start of the
26894  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26895  *
26896  * Many exclusive ioctls go thru an internal down up sequence as part of
26897  * the operation. For example an attempt to change the IP address of an
26898  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26899  * does all the cleanup such as deleting all ires that use this address.
26900  * Then we need to wait till all references to the interface go away.
26901  */
26902 void
26903 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26904 {
26905 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26906 	ip_ioctl_cmd_t *ipip = arg;
26907 	ip_extract_func_t *extract_funcp;
26908 	cmd_info_t ci;
26909 	int err;
26910 	boolean_t entered_ipsq = B_FALSE;
26911 
26912 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26913 
26914 	if (ipip == NULL)
26915 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26916 
26917 	/*
26918 	 * SIOCLIFADDIF needs to go thru a special path since the
26919 	 * ill may not exist yet. This happens in the case of lo0
26920 	 * which is created using this ioctl.
26921 	 */
26922 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26923 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26924 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26925 		return;
26926 	}
26927 
26928 	ci.ci_ipif = NULL;
26929 	if (ipip->ipi_cmd_type == MISC_CMD) {
26930 		/*
26931 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26932 		 */
26933 		if (ipip->ipi_cmd == IF_UNITSEL) {
26934 			/* ioctl comes down the ill */
26935 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26936 			ipif_refhold(ci.ci_ipif);
26937 		}
26938 		err = 0;
26939 		ci.ci_sin = NULL;
26940 		ci.ci_sin6 = NULL;
26941 		ci.ci_lifr = NULL;
26942 	} else {
26943 		switch (ipip->ipi_cmd_type) {
26944 		case IF_CMD:
26945 		case LIF_CMD:
26946 			extract_funcp = ip_extract_lifreq;
26947 			break;
26948 
26949 		case ARP_CMD:
26950 		case XARP_CMD:
26951 			extract_funcp = ip_extract_arpreq;
26952 			break;
26953 
26954 		case TUN_CMD:
26955 			extract_funcp = ip_extract_tunreq;
26956 			break;
26957 
26958 		case MSFILT_CMD:
26959 			extract_funcp = ip_extract_msfilter;
26960 			break;
26961 
26962 		default:
26963 			ASSERT(0);
26964 		}
26965 
26966 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26967 		if (err != 0) {
26968 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26969 			return;
26970 		}
26971 
26972 		/*
26973 		 * All of the extraction functions return a refheld ipif.
26974 		 */
26975 		ASSERT(ci.ci_ipif != NULL);
26976 	}
26977 
26978 	/*
26979 	 * If ipsq is non-null, we are already being called exclusively
26980 	 */
26981 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26982 	if (!(ipip->ipi_flags & IPI_WR)) {
26983 		/*
26984 		 * A return value of EINPROGRESS means the ioctl is
26985 		 * either queued and waiting for some reason or has
26986 		 * already completed.
26987 		 */
26988 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26989 		    ci.ci_lifr);
26990 		if (ci.ci_ipif != NULL)
26991 			ipif_refrele(ci.ci_ipif);
26992 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26993 		return;
26994 	}
26995 
26996 	ASSERT(ci.ci_ipif != NULL);
26997 
26998 	if (ipsq == NULL) {
26999 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27000 		    ip_process_ioctl, NEW_OP, B_TRUE);
27001 		entered_ipsq = B_TRUE;
27002 	}
27003 	/*
27004 	 * Release the ipif so that ipif_down and friends that wait for
27005 	 * references to go away are not misled about the current ipif_refcnt
27006 	 * values. We are writer so we can access the ipif even after releasing
27007 	 * the ipif.
27008 	 */
27009 	ipif_refrele(ci.ci_ipif);
27010 	if (ipsq == NULL)
27011 		return;
27012 
27013 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27014 
27015 	/*
27016 	 * For most set ioctls that come here, this serves as a single point
27017 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27018 	 * be any new references to the ipif. This helps functions that go
27019 	 * through this path and end up trying to wait for the refcnts
27020 	 * associated with the ipif to go down to zero. Some exceptions are
27021 	 * Failover, Failback, and Groupname commands that operate on more than
27022 	 * just the ci.ci_ipif. These commands internally determine the
27023 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27024 	 * flags on that set. Another exception is the Removeif command that
27025 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27026 	 * ipif to operate on.
27027 	 */
27028 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27029 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27030 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27031 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27032 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27033 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27034 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27035 
27036 	/*
27037 	 * A return value of EINPROGRESS means the ioctl is
27038 	 * either queued and waiting for some reason or has
27039 	 * already completed.
27040 	 */
27041 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27042 
27043 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27044 
27045 	if (entered_ipsq)
27046 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27047 }
27048 
27049 /*
27050  * Complete the ioctl. Typically ioctls use the mi package and need to
27051  * do mi_copyout/mi_copy_done.
27052  */
27053 void
27054 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27055 {
27056 	conn_t	*connp = NULL;
27057 
27058 	if (err == EINPROGRESS)
27059 		return;
27060 
27061 	if (CONN_Q(q)) {
27062 		connp = Q_TO_CONN(q);
27063 		ASSERT(connp->conn_ref >= 2);
27064 	}
27065 
27066 	switch (mode) {
27067 	case COPYOUT:
27068 		if (err == 0)
27069 			mi_copyout(q, mp);
27070 		else
27071 			mi_copy_done(q, mp, err);
27072 		break;
27073 
27074 	case NO_COPYOUT:
27075 		mi_copy_done(q, mp, err);
27076 		break;
27077 
27078 	default:
27079 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27080 		break;
27081 	}
27082 
27083 	/*
27084 	 * The refhold placed at the start of the ioctl is released here.
27085 	 */
27086 	if (connp != NULL)
27087 		CONN_OPER_PENDING_DONE(connp);
27088 
27089 	if (ipsq != NULL)
27090 		ipsq_current_finish(ipsq);
27091 }
27092 
27093 /*
27094  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27095  */
27096 /* ARGSUSED */
27097 void
27098 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27099 {
27100 	conn_t *connp = arg;
27101 	tcp_t	*tcp;
27102 
27103 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27104 	tcp = connp->conn_tcp;
27105 
27106 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27107 		freemsg(mp);
27108 	else
27109 		tcp_rput_other(tcp, mp);
27110 	CONN_OPER_PENDING_DONE(connp);
27111 }
27112 
27113 /* Called from ip_wput for all non data messages */
27114 /* ARGSUSED */
27115 void
27116 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27117 {
27118 	mblk_t		*mp1;
27119 	ire_t		*ire, *fake_ire;
27120 	ill_t		*ill;
27121 	struct iocblk	*iocp;
27122 	ip_ioctl_cmd_t	*ipip;
27123 	cred_t		*cr;
27124 	conn_t		*connp;
27125 	int		err;
27126 	nce_t		*nce;
27127 	ipif_t		*ipif;
27128 	ip_stack_t	*ipst;
27129 	char		*proto_str;
27130 
27131 	if (CONN_Q(q)) {
27132 		connp = Q_TO_CONN(q);
27133 		ipst = connp->conn_netstack->netstack_ip;
27134 	} else {
27135 		connp = NULL;
27136 		ipst = ILLQ_TO_IPST(q);
27137 	}
27138 
27139 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27140 
27141 	/* Check if it is a queue to /dev/sctp. */
27142 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27143 	    connp->conn_rq == NULL) {
27144 		sctp_wput(q, mp);
27145 		return;
27146 	}
27147 
27148 	switch (DB_TYPE(mp)) {
27149 	case M_IOCTL:
27150 		/*
27151 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27152 		 * will arrange to copy in associated control structures.
27153 		 */
27154 		ip_sioctl_copyin_setup(q, mp);
27155 		return;
27156 	case M_IOCDATA:
27157 		/*
27158 		 * Ensure that this is associated with one of our trans-
27159 		 * parent ioctls.  If it's not ours, discard it if we're
27160 		 * running as a driver, or pass it on if we're a module.
27161 		 */
27162 		iocp = (struct iocblk *)mp->b_rptr;
27163 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27164 		if (ipip == NULL) {
27165 			if (q->q_next == NULL) {
27166 				goto nak;
27167 			} else {
27168 				putnext(q, mp);
27169 			}
27170 			return;
27171 		}
27172 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27173 			/*
27174 			 * the ioctl is one we recognise, but is not
27175 			 * consumed by IP as a module, pass M_IOCDATA
27176 			 * for processing downstream, but only for
27177 			 * common Streams ioctls.
27178 			 */
27179 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27180 				putnext(q, mp);
27181 				return;
27182 			} else {
27183 				goto nak;
27184 			}
27185 		}
27186 
27187 		/* IOCTL continuation following copyin or copyout. */
27188 		if (mi_copy_state(q, mp, NULL) == -1) {
27189 			/*
27190 			 * The copy operation failed.  mi_copy_state already
27191 			 * cleaned up, so we're out of here.
27192 			 */
27193 			return;
27194 		}
27195 		/*
27196 		 * If we just completed a copy in, we become writer and
27197 		 * continue processing in ip_sioctl_copyin_done.  If it
27198 		 * was a copy out, we call mi_copyout again.  If there is
27199 		 * nothing more to copy out, it will complete the IOCTL.
27200 		 */
27201 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27202 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27203 				mi_copy_done(q, mp, EPROTO);
27204 				return;
27205 			}
27206 			/*
27207 			 * Check for cases that need more copying.  A return
27208 			 * value of 0 means a second copyin has been started,
27209 			 * so we return; a return value of 1 means no more
27210 			 * copying is needed, so we continue.
27211 			 */
27212 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27213 			    MI_COPY_COUNT(mp) == 1) {
27214 				if (ip_copyin_msfilter(q, mp) == 0)
27215 					return;
27216 			}
27217 			/*
27218 			 * Refhold the conn, till the ioctl completes. This is
27219 			 * needed in case the ioctl ends up in the pending mp
27220 			 * list. Every mp in the ill_pending_mp list and
27221 			 * the ipsq_pending_mp must have a refhold on the conn
27222 			 * to resume processing. The refhold is released when
27223 			 * the ioctl completes. (normally or abnormally)
27224 			 * In all cases ip_ioctl_finish is called to finish
27225 			 * the ioctl.
27226 			 */
27227 			if (connp != NULL) {
27228 				/* This is not a reentry */
27229 				ASSERT(ipsq == NULL);
27230 				CONN_INC_REF(connp);
27231 			} else {
27232 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27233 					mi_copy_done(q, mp, EINVAL);
27234 					return;
27235 				}
27236 			}
27237 
27238 			ip_process_ioctl(ipsq, q, mp, ipip);
27239 
27240 		} else {
27241 			mi_copyout(q, mp);
27242 		}
27243 		return;
27244 nak:
27245 		iocp->ioc_error = EINVAL;
27246 		mp->b_datap->db_type = M_IOCNAK;
27247 		iocp->ioc_count = 0;
27248 		qreply(q, mp);
27249 		return;
27250 
27251 	case M_IOCNAK:
27252 		/*
27253 		 * The only way we could get here is if a resolver didn't like
27254 		 * an IOCTL we sent it.	 This shouldn't happen.
27255 		 */
27256 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27257 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27258 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27259 		freemsg(mp);
27260 		return;
27261 	case M_IOCACK:
27262 		/* /dev/ip shouldn't see this */
27263 		if (CONN_Q(q))
27264 			goto nak;
27265 
27266 		/* Finish socket ioctls passed through to ARP. */
27267 		ip_sioctl_iocack(q, mp);
27268 		return;
27269 	case M_FLUSH:
27270 		if (*mp->b_rptr & FLUSHW)
27271 			flushq(q, FLUSHALL);
27272 		if (q->q_next) {
27273 			putnext(q, mp);
27274 			return;
27275 		}
27276 		if (*mp->b_rptr & FLUSHR) {
27277 			*mp->b_rptr &= ~FLUSHW;
27278 			qreply(q, mp);
27279 			return;
27280 		}
27281 		freemsg(mp);
27282 		return;
27283 	case IRE_DB_REQ_TYPE:
27284 		if (connp == NULL) {
27285 			proto_str = "IRE_DB_REQ_TYPE";
27286 			goto protonak;
27287 		}
27288 		/* An Upper Level Protocol wants a copy of an IRE. */
27289 		ip_ire_req(q, mp);
27290 		return;
27291 	case M_CTL:
27292 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27293 			break;
27294 
27295 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27296 		    TUN_HELLO) {
27297 			ASSERT(connp != NULL);
27298 			connp->conn_flags |= IPCL_IPTUN;
27299 			freeb(mp);
27300 			return;
27301 		}
27302 
27303 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27304 		    IP_ULP_OUT_LABELED) {
27305 			out_labeled_t *olp;
27306 
27307 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27308 				break;
27309 			olp = (out_labeled_t *)mp->b_rptr;
27310 			connp->conn_ulp_labeled = olp->out_qnext == q;
27311 			freemsg(mp);
27312 			return;
27313 		}
27314 
27315 		/* M_CTL messages are used by ARP to tell us things. */
27316 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27317 			break;
27318 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27319 		case AR_ENTRY_SQUERY:
27320 			ip_wput_ctl(q, mp);
27321 			return;
27322 		case AR_CLIENT_NOTIFY:
27323 			ip_arp_news(q, mp);
27324 			return;
27325 		case AR_DLPIOP_DONE:
27326 			ASSERT(q->q_next != NULL);
27327 			ill = (ill_t *)q->q_ptr;
27328 			/* qwriter_ip releases the refhold */
27329 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27330 			ill_refhold(ill);
27331 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27332 			return;
27333 		case AR_ARP_CLOSING:
27334 			/*
27335 			 * ARP (above us) is closing. If no ARP bringup is
27336 			 * currently pending, ack the message so that ARP
27337 			 * can complete its close. Also mark ill_arp_closing
27338 			 * so that new ARP bringups will fail. If any
27339 			 * ARP bringup is currently in progress, we will
27340 			 * ack this when the current ARP bringup completes.
27341 			 */
27342 			ASSERT(q->q_next != NULL);
27343 			ill = (ill_t *)q->q_ptr;
27344 			mutex_enter(&ill->ill_lock);
27345 			ill->ill_arp_closing = 1;
27346 			if (!ill->ill_arp_bringup_pending) {
27347 				mutex_exit(&ill->ill_lock);
27348 				qreply(q, mp);
27349 			} else {
27350 				mutex_exit(&ill->ill_lock);
27351 				freemsg(mp);
27352 			}
27353 			return;
27354 		case AR_ARP_EXTEND:
27355 			/*
27356 			 * The ARP module above us is capable of duplicate
27357 			 * address detection.  Old ATM drivers will not send
27358 			 * this message.
27359 			 */
27360 			ASSERT(q->q_next != NULL);
27361 			ill = (ill_t *)q->q_ptr;
27362 			ill->ill_arp_extend = B_TRUE;
27363 			freemsg(mp);
27364 			return;
27365 		default:
27366 			break;
27367 		}
27368 		break;
27369 	case M_PROTO:
27370 	case M_PCPROTO:
27371 		/*
27372 		 * The only PROTO messages we expect are ULP binds and
27373 		 * copies of option negotiation acknowledgements.
27374 		 */
27375 		switch (((union T_primitives *)mp->b_rptr)->type) {
27376 		case O_T_BIND_REQ:
27377 		case T_BIND_REQ: {
27378 			/* Request can get queued in bind */
27379 			if (connp == NULL) {
27380 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27381 				goto protonak;
27382 			}
27383 			/*
27384 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27385 			 * instead of going through this path.  We only get
27386 			 * here in the following cases:
27387 			 *
27388 			 * a. Bind retries, where ipsq is non-NULL.
27389 			 * b. T_BIND_REQ is issued from non TCP/UDP
27390 			 *    transport, e.g. icmp for raw socket,
27391 			 *    in which case ipsq will be NULL.
27392 			 */
27393 			ASSERT(ipsq != NULL ||
27394 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27395 
27396 			/* Don't increment refcnt if this is a re-entry */
27397 			if (ipsq == NULL)
27398 				CONN_INC_REF(connp);
27399 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27400 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27401 			if (mp == NULL)
27402 				return;
27403 			if (IPCL_IS_TCP(connp)) {
27404 				/*
27405 				 * In the case of TCP endpoint we
27406 				 * come here only for bind retries
27407 				 */
27408 				ASSERT(ipsq != NULL);
27409 				CONN_INC_REF(connp);
27410 				squeue_fill(connp->conn_sqp, mp,
27411 				    ip_resume_tcp_bind, connp,
27412 				    SQTAG_BIND_RETRY);
27413 				return;
27414 			} else if (IPCL_IS_UDP(connp)) {
27415 				/*
27416 				 * In the case of UDP endpoint we
27417 				 * come here only for bind retries
27418 				 */
27419 				ASSERT(ipsq != NULL);
27420 				udp_resume_bind(connp, mp);
27421 				return;
27422 			}
27423 			qreply(q, mp);
27424 			CONN_OPER_PENDING_DONE(connp);
27425 			return;
27426 		}
27427 		case T_SVR4_OPTMGMT_REQ:
27428 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27429 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27430 
27431 			if (connp == NULL) {
27432 				proto_str = "T_SVR4_OPTMGMT_REQ";
27433 				goto protonak;
27434 			}
27435 
27436 			if (!snmpcom_req(q, mp, ip_snmp_set,
27437 			    ip_snmp_get, cr)) {
27438 				/*
27439 				 * Call svr4_optcom_req so that it can
27440 				 * generate the ack. We don't come here
27441 				 * if this operation is being restarted.
27442 				 * ip_restart_optmgmt will drop the conn ref.
27443 				 * In the case of ipsec option after the ipsec
27444 				 * load is complete conn_restart_ipsec_waiter
27445 				 * drops the conn ref.
27446 				 */
27447 				ASSERT(ipsq == NULL);
27448 				CONN_INC_REF(connp);
27449 				if (ip_check_for_ipsec_opt(q, mp))
27450 					return;
27451 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27452 				if (err != EINPROGRESS) {
27453 					/* Operation is done */
27454 					CONN_OPER_PENDING_DONE(connp);
27455 				}
27456 			}
27457 			return;
27458 		case T_OPTMGMT_REQ:
27459 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27460 			/*
27461 			 * Note: No snmpcom_req support through new
27462 			 * T_OPTMGMT_REQ.
27463 			 * Call tpi_optcom_req so that it can
27464 			 * generate the ack.
27465 			 */
27466 			if (connp == NULL) {
27467 				proto_str = "T_OPTMGMT_REQ";
27468 				goto protonak;
27469 			}
27470 
27471 			ASSERT(ipsq == NULL);
27472 			/*
27473 			 * We don't come here for restart. ip_restart_optmgmt
27474 			 * will drop the conn ref. In the case of ipsec option
27475 			 * after the ipsec load is complete
27476 			 * conn_restart_ipsec_waiter drops the conn ref.
27477 			 */
27478 			CONN_INC_REF(connp);
27479 			if (ip_check_for_ipsec_opt(q, mp))
27480 				return;
27481 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27482 			if (err != EINPROGRESS) {
27483 				/* Operation is done */
27484 				CONN_OPER_PENDING_DONE(connp);
27485 			}
27486 			return;
27487 		case T_UNBIND_REQ:
27488 			if (connp == NULL) {
27489 				proto_str = "T_UNBIND_REQ";
27490 				goto protonak;
27491 			}
27492 			mp = ip_unbind(q, mp);
27493 			qreply(q, mp);
27494 			return;
27495 		default:
27496 			/*
27497 			 * Have to drop any DLPI messages coming down from
27498 			 * arp (such as an info_req which would cause ip
27499 			 * to receive an extra info_ack if it was passed
27500 			 * through.
27501 			 */
27502 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27503 			    (int)*(uint_t *)mp->b_rptr));
27504 			freemsg(mp);
27505 			return;
27506 		}
27507 		/* NOTREACHED */
27508 	case IRE_DB_TYPE: {
27509 		nce_t		*nce;
27510 		ill_t		*ill;
27511 		in6_addr_t	gw_addr_v6;
27512 
27513 
27514 		/*
27515 		 * This is a response back from a resolver.  It
27516 		 * consists of a message chain containing:
27517 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27518 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27519 		 * The LL_HDR_MBLK is the DLPI header to use to get
27520 		 * the attached packet, and subsequent ones for the
27521 		 * same destination, transmitted.
27522 		 */
27523 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27524 			break;
27525 		/*
27526 		 * First, check to make sure the resolution succeeded.
27527 		 * If it failed, the second mblk will be empty.
27528 		 * If it is, free the chain, dropping the packet.
27529 		 * (We must ire_delete the ire; that frees the ire mblk)
27530 		 * We're doing this now to support PVCs for ATM; it's
27531 		 * a partial xresolv implementation. When we fully implement
27532 		 * xresolv interfaces, instead of freeing everything here
27533 		 * we'll initiate neighbor discovery.
27534 		 *
27535 		 * For v4 (ARP and other external resolvers) the resolver
27536 		 * frees the message, so no check is needed. This check
27537 		 * is required, though, for a full xresolve implementation.
27538 		 * Including this code here now both shows how external
27539 		 * resolvers can NACK a resolution request using an
27540 		 * existing design that has no specific provisions for NACKs,
27541 		 * and also takes into account that the current non-ARP
27542 		 * external resolver has been coded to use this method of
27543 		 * NACKing for all IPv6 (xresolv) cases,
27544 		 * whether our xresolv implementation is complete or not.
27545 		 *
27546 		 */
27547 		ire = (ire_t *)mp->b_rptr;
27548 		ill = ire_to_ill(ire);
27549 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27550 		if (mp1->b_rptr == mp1->b_wptr) {
27551 			if (ire->ire_ipversion == IPV6_VERSION) {
27552 				/*
27553 				 * XRESOLV interface.
27554 				 */
27555 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27556 				mutex_enter(&ire->ire_lock);
27557 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27558 				mutex_exit(&ire->ire_lock);
27559 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27560 					nce = ndp_lookup_v6(ill,
27561 					    &ire->ire_addr_v6, B_FALSE);
27562 				} else {
27563 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27564 					    B_FALSE);
27565 				}
27566 				if (nce != NULL) {
27567 					nce_resolv_failed(nce);
27568 					ndp_delete(nce);
27569 					NCE_REFRELE(nce);
27570 				}
27571 			}
27572 			mp->b_cont = NULL;
27573 			freemsg(mp1);		/* frees the pkt as well */
27574 			ASSERT(ire->ire_nce == NULL);
27575 			ire_delete((ire_t *)mp->b_rptr);
27576 			return;
27577 		}
27578 
27579 		/*
27580 		 * Split them into IRE_MBLK and pkt and feed it into
27581 		 * ire_add_then_send. Then in ire_add_then_send
27582 		 * the IRE will be added, and then the packet will be
27583 		 * run back through ip_wput. This time it will make
27584 		 * it to the wire.
27585 		 */
27586 		mp->b_cont = NULL;
27587 		mp = mp1->b_cont;		/* now, mp points to pkt */
27588 		mp1->b_cont = NULL;
27589 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27590 		if (ire->ire_ipversion == IPV6_VERSION) {
27591 			/*
27592 			 * XRESOLV interface. Find the nce and put a copy
27593 			 * of the dl_unitdata_req in nce_res_mp
27594 			 */
27595 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27596 			mutex_enter(&ire->ire_lock);
27597 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27598 			mutex_exit(&ire->ire_lock);
27599 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27600 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27601 				    B_FALSE);
27602 			} else {
27603 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27604 			}
27605 			if (nce != NULL) {
27606 				/*
27607 				 * We have to protect nce_res_mp here
27608 				 * from being accessed by other threads
27609 				 * while we change the mblk pointer.
27610 				 * Other functions will also lock the nce when
27611 				 * accessing nce_res_mp.
27612 				 *
27613 				 * The reason we change the mblk pointer
27614 				 * here rather than copying the resolved address
27615 				 * into the template is that, unlike with
27616 				 * ethernet, we have no guarantee that the
27617 				 * resolved address length will be
27618 				 * smaller than or equal to the lla length
27619 				 * with which the template was allocated,
27620 				 * (for ethernet, they're equal)
27621 				 * so we have to use the actual resolved
27622 				 * address mblk - which holds the real
27623 				 * dl_unitdata_req with the resolved address.
27624 				 *
27625 				 * Doing this is the same behavior as was
27626 				 * previously used in the v4 ARP case.
27627 				 */
27628 				mutex_enter(&nce->nce_lock);
27629 				if (nce->nce_res_mp != NULL)
27630 					freemsg(nce->nce_res_mp);
27631 				nce->nce_res_mp = mp1;
27632 				mutex_exit(&nce->nce_lock);
27633 				/*
27634 				 * We do a fastpath probe here because
27635 				 * we have resolved the address without
27636 				 * using Neighbor Discovery.
27637 				 * In the non-XRESOLV v6 case, the fastpath
27638 				 * probe is done right after neighbor
27639 				 * discovery completes.
27640 				 */
27641 				if (nce->nce_res_mp != NULL) {
27642 					int res;
27643 					nce_fastpath_list_add(nce);
27644 					res = ill_fastpath_probe(ill,
27645 					    nce->nce_res_mp);
27646 					if (res != 0 && res != EAGAIN)
27647 						nce_fastpath_list_delete(nce);
27648 				}
27649 
27650 				ire_add_then_send(q, ire, mp);
27651 				/*
27652 				 * Now we have to clean out any packets
27653 				 * that may have been queued on the nce
27654 				 * while it was waiting for address resolution
27655 				 * to complete.
27656 				 */
27657 				mutex_enter(&nce->nce_lock);
27658 				mp1 = nce->nce_qd_mp;
27659 				nce->nce_qd_mp = NULL;
27660 				mutex_exit(&nce->nce_lock);
27661 				while (mp1 != NULL) {
27662 					mblk_t *nxt_mp;
27663 					queue_t *fwdq = NULL;
27664 					ill_t   *inbound_ill;
27665 					uint_t ifindex;
27666 
27667 					nxt_mp = mp1->b_next;
27668 					mp1->b_next = NULL;
27669 					/*
27670 					 * Retrieve ifindex stored in
27671 					 * ip_rput_data_v6()
27672 					 */
27673 					ifindex =
27674 					    (uint_t)(uintptr_t)mp1->b_prev;
27675 					inbound_ill =
27676 					    ill_lookup_on_ifindex(ifindex,
27677 					    B_TRUE, NULL, NULL, NULL,
27678 					    NULL, ipst);
27679 					mp1->b_prev = NULL;
27680 					if (inbound_ill != NULL)
27681 						fwdq = inbound_ill->ill_rq;
27682 
27683 					if (fwdq != NULL) {
27684 						put(fwdq, mp1);
27685 						ill_refrele(inbound_ill);
27686 					} else
27687 						put(WR(ill->ill_rq), mp1);
27688 					mp1 = nxt_mp;
27689 				}
27690 				NCE_REFRELE(nce);
27691 			} else {	/* nce is NULL; clean up */
27692 				ire_delete(ire);
27693 				freemsg(mp);
27694 				freemsg(mp1);
27695 				return;
27696 			}
27697 		} else {
27698 			nce_t *arpce;
27699 			/*
27700 			 * Link layer resolution succeeded. Recompute the
27701 			 * ire_nce.
27702 			 */
27703 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27704 			if ((arpce = ndp_lookup_v4(ill,
27705 			    (ire->ire_gateway_addr != INADDR_ANY ?
27706 			    &ire->ire_gateway_addr : &ire->ire_addr),
27707 			    B_FALSE)) == NULL) {
27708 				freeb(ire->ire_mp);
27709 				freeb(mp1);
27710 				freemsg(mp);
27711 				return;
27712 			}
27713 			mutex_enter(&arpce->nce_lock);
27714 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27715 			if (arpce->nce_state == ND_REACHABLE) {
27716 				/*
27717 				 * Someone resolved this before us;
27718 				 * cleanup the res_mp. Since ire has
27719 				 * not been added yet, the call to ire_add_v4
27720 				 * from ire_add_then_send (when a dup is
27721 				 * detected) will clean up the ire.
27722 				 */
27723 				freeb(mp1);
27724 			} else {
27725 				ASSERT(arpce->nce_res_mp == NULL);
27726 				arpce->nce_res_mp = mp1;
27727 				arpce->nce_state = ND_REACHABLE;
27728 			}
27729 			mutex_exit(&arpce->nce_lock);
27730 			if (ire->ire_marks & IRE_MARK_NOADD) {
27731 				/*
27732 				 * this ire will not be added to the ire
27733 				 * cache table, so we can set the ire_nce
27734 				 * here, as there are no atomicity constraints.
27735 				 */
27736 				ire->ire_nce = arpce;
27737 				/*
27738 				 * We are associating this nce with the ire
27739 				 * so change the nce ref taken in
27740 				 * ndp_lookup_v4() from
27741 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27742 				 */
27743 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27744 			} else {
27745 				NCE_REFRELE(arpce);
27746 			}
27747 			ire_add_then_send(q, ire, mp);
27748 		}
27749 		return;	/* All is well, the packet has been sent. */
27750 	}
27751 	case IRE_ARPRESOLVE_TYPE: {
27752 
27753 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27754 			break;
27755 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27756 		mp->b_cont = NULL;
27757 		/*
27758 		 * First, check to make sure the resolution succeeded.
27759 		 * If it failed, the second mblk will be empty.
27760 		 */
27761 		if (mp1->b_rptr == mp1->b_wptr) {
27762 			/* cleanup  the incomplete ire, free queued packets */
27763 			freemsg(mp); /* fake ire */
27764 			freeb(mp1);  /* dl_unitdata response */
27765 			return;
27766 		}
27767 
27768 		/*
27769 		 * update any incomplete nce_t found. we lookup the ctable
27770 		 * and find the nce from the ire->ire_nce because we need
27771 		 * to pass the ire to ip_xmit_v4 later, and can find both
27772 		 * ire and nce in one lookup from the ctable.
27773 		 */
27774 		fake_ire = (ire_t *)mp->b_rptr;
27775 		/*
27776 		 * By the time we come back here from ARP
27777 		 * the logical outgoing interface  of the incomplete ire
27778 		 * we added in ire_forward could have disappeared,
27779 		 * causing the incomplete ire to also have
27780 		 * dissapeared. So we need to retreive the
27781 		 * proper ipif for the ire  before looking
27782 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27783 		 */
27784 		ill = q->q_ptr;
27785 
27786 		/* Get the outgoing ipif */
27787 		mutex_enter(&ill->ill_lock);
27788 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27789 			mutex_exit(&ill->ill_lock);
27790 			freemsg(mp); /* fake ire */
27791 			freeb(mp1);  /* dl_unitdata response */
27792 			return;
27793 		}
27794 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27795 
27796 		if (ipif == NULL) {
27797 			mutex_exit(&ill->ill_lock);
27798 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27799 			freemsg(mp);
27800 			freeb(mp1);
27801 			return;
27802 		}
27803 		ipif_refhold_locked(ipif);
27804 		mutex_exit(&ill->ill_lock);
27805 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27806 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27807 		    ipif, fake_ire->ire_zoneid, NULL,
27808 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27809 		ipif_refrele(ipif);
27810 		if (ire == NULL) {
27811 			/*
27812 			 * no ire was found; check if there is an nce
27813 			 * for this lookup; if it has no ire's pointing at it
27814 			 * cleanup.
27815 			 */
27816 			if ((nce = ndp_lookup_v4(ill,
27817 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27818 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27819 			    B_FALSE)) != NULL) {
27820 				/*
27821 				 * cleanup:
27822 				 * We check for refcnt 2 (one for the nce
27823 				 * hash list + 1 for the ref taken by
27824 				 * ndp_lookup_v4) to check that there are
27825 				 * no ire's pointing at the nce.
27826 				 */
27827 				if (nce->nce_refcnt == 2)
27828 					ndp_delete(nce);
27829 				NCE_REFRELE(nce);
27830 			}
27831 			freeb(mp1);  /* dl_unitdata response */
27832 			freemsg(mp); /* fake ire */
27833 			return;
27834 		}
27835 		nce = ire->ire_nce;
27836 		DTRACE_PROBE2(ire__arpresolve__type,
27837 		    ire_t *, ire, nce_t *, nce);
27838 		ASSERT(nce->nce_state != ND_INITIAL);
27839 		mutex_enter(&nce->nce_lock);
27840 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27841 		if (nce->nce_state == ND_REACHABLE) {
27842 			/*
27843 			 * Someone resolved this before us;
27844 			 * our response is not needed any more.
27845 			 */
27846 			mutex_exit(&nce->nce_lock);
27847 			freeb(mp1);  /* dl_unitdata response */
27848 		} else {
27849 			ASSERT(nce->nce_res_mp == NULL);
27850 			nce->nce_res_mp = mp1;
27851 			nce->nce_state = ND_REACHABLE;
27852 			mutex_exit(&nce->nce_lock);
27853 			nce_fastpath(nce);
27854 		}
27855 		/*
27856 		 * The cached nce_t has been updated to be reachable;
27857 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27858 		 */
27859 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27860 		freemsg(mp);
27861 		/*
27862 		 * send out queued packets.
27863 		 */
27864 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27865 
27866 		IRE_REFRELE(ire);
27867 		return;
27868 	}
27869 	default:
27870 		break;
27871 	}
27872 	if (q->q_next) {
27873 		putnext(q, mp);
27874 	} else
27875 		freemsg(mp);
27876 	return;
27877 
27878 protonak:
27879 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27880 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27881 		qreply(q, mp);
27882 }
27883 
27884 /*
27885  * Process IP options in an outbound packet.  Modify the destination if there
27886  * is a source route option.
27887  * Returns non-zero if something fails in which case an ICMP error has been
27888  * sent and mp freed.
27889  */
27890 static int
27891 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27892     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27893 {
27894 	ipoptp_t	opts;
27895 	uchar_t		*opt;
27896 	uint8_t		optval;
27897 	uint8_t		optlen;
27898 	ipaddr_t	dst;
27899 	intptr_t	code = 0;
27900 	mblk_t		*mp;
27901 	ire_t		*ire = NULL;
27902 
27903 	ip2dbg(("ip_wput_options\n"));
27904 	mp = ipsec_mp;
27905 	if (mctl_present) {
27906 		mp = ipsec_mp->b_cont;
27907 	}
27908 
27909 	dst = ipha->ipha_dst;
27910 	for (optval = ipoptp_first(&opts, ipha);
27911 	    optval != IPOPT_EOL;
27912 	    optval = ipoptp_next(&opts)) {
27913 		opt = opts.ipoptp_cur;
27914 		optlen = opts.ipoptp_len;
27915 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27916 		    optval, optlen));
27917 		switch (optval) {
27918 			uint32_t off;
27919 		case IPOPT_SSRR:
27920 		case IPOPT_LSRR:
27921 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27922 				ip1dbg((
27923 				    "ip_wput_options: bad option offset\n"));
27924 				code = (char *)&opt[IPOPT_OLEN] -
27925 				    (char *)ipha;
27926 				goto param_prob;
27927 			}
27928 			off = opt[IPOPT_OFFSET];
27929 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27930 			    ntohl(dst)));
27931 			/*
27932 			 * For strict: verify that dst is directly
27933 			 * reachable.
27934 			 */
27935 			if (optval == IPOPT_SSRR) {
27936 				ire = ire_ftable_lookup(dst, 0, 0,
27937 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27938 				    MBLK_GETLABEL(mp),
27939 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27940 				if (ire == NULL) {
27941 					ip1dbg(("ip_wput_options: SSRR not"
27942 					    " directly reachable: 0x%x\n",
27943 					    ntohl(dst)));
27944 					goto bad_src_route;
27945 				}
27946 				ire_refrele(ire);
27947 			}
27948 			break;
27949 		case IPOPT_RR:
27950 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27951 				ip1dbg((
27952 				    "ip_wput_options: bad option offset\n"));
27953 				code = (char *)&opt[IPOPT_OLEN] -
27954 				    (char *)ipha;
27955 				goto param_prob;
27956 			}
27957 			break;
27958 		case IPOPT_TS:
27959 			/*
27960 			 * Verify that length >=5 and that there is either
27961 			 * room for another timestamp or that the overflow
27962 			 * counter is not maxed out.
27963 			 */
27964 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27965 			if (optlen < IPOPT_MINLEN_IT) {
27966 				goto param_prob;
27967 			}
27968 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27969 				ip1dbg((
27970 				    "ip_wput_options: bad option offset\n"));
27971 				code = (char *)&opt[IPOPT_OFFSET] -
27972 				    (char *)ipha;
27973 				goto param_prob;
27974 			}
27975 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27976 			case IPOPT_TS_TSONLY:
27977 				off = IPOPT_TS_TIMELEN;
27978 				break;
27979 			case IPOPT_TS_TSANDADDR:
27980 			case IPOPT_TS_PRESPEC:
27981 			case IPOPT_TS_PRESPEC_RFC791:
27982 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27983 				break;
27984 			default:
27985 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27986 				    (char *)ipha;
27987 				goto param_prob;
27988 			}
27989 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27990 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27991 				/*
27992 				 * No room and the overflow counter is 15
27993 				 * already.
27994 				 */
27995 				goto param_prob;
27996 			}
27997 			break;
27998 		}
27999 	}
28000 
28001 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28002 		return (0);
28003 
28004 	ip1dbg(("ip_wput_options: error processing IP options."));
28005 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28006 
28007 param_prob:
28008 	/*
28009 	 * Since ip_wput() isn't close to finished, we fill
28010 	 * in enough of the header for credible error reporting.
28011 	 */
28012 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28013 		/* Failed */
28014 		freemsg(ipsec_mp);
28015 		return (-1);
28016 	}
28017 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28018 	return (-1);
28019 
28020 bad_src_route:
28021 	/*
28022 	 * Since ip_wput() isn't close to finished, we fill
28023 	 * in enough of the header for credible error reporting.
28024 	 */
28025 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28026 		/* Failed */
28027 		freemsg(ipsec_mp);
28028 		return (-1);
28029 	}
28030 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28031 	return (-1);
28032 }
28033 
28034 /*
28035  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28036  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28037  * thru /etc/system.
28038  */
28039 #define	CONN_MAXDRAINCNT	64
28040 
28041 static void
28042 conn_drain_init(ip_stack_t *ipst)
28043 {
28044 	int i;
28045 
28046 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28047 
28048 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28049 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28050 		/*
28051 		 * Default value of the number of drainers is the
28052 		 * number of cpus, subject to maximum of 8 drainers.
28053 		 */
28054 		if (boot_max_ncpus != -1)
28055 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28056 		else
28057 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28058 	}
28059 
28060 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28061 	    sizeof (idl_t), KM_SLEEP);
28062 
28063 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28064 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28065 		    MUTEX_DEFAULT, NULL);
28066 	}
28067 }
28068 
28069 static void
28070 conn_drain_fini(ip_stack_t *ipst)
28071 {
28072 	int i;
28073 
28074 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28075 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28076 	kmem_free(ipst->ips_conn_drain_list,
28077 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28078 	ipst->ips_conn_drain_list = NULL;
28079 }
28080 
28081 /*
28082  * Note: For an overview of how flowcontrol is handled in IP please see the
28083  * IP Flowcontrol notes at the top of this file.
28084  *
28085  * Flow control has blocked us from proceeding. Insert the given conn in one
28086  * of the conn drain lists. These conn wq's will be qenabled later on when
28087  * STREAMS flow control does a backenable. conn_walk_drain will enable
28088  * the first conn in each of these drain lists. Each of these qenabled conns
28089  * in turn enables the next in the list, after it runs, or when it closes,
28090  * thus sustaining the drain process.
28091  *
28092  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28093  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28094  * running at any time, on a given conn, since there can be only 1 service proc
28095  * running on a queue at any time.
28096  */
28097 void
28098 conn_drain_insert(conn_t *connp)
28099 {
28100 	idl_t	*idl;
28101 	uint_t	index;
28102 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28103 
28104 	mutex_enter(&connp->conn_lock);
28105 	if (connp->conn_state_flags & CONN_CLOSING) {
28106 		/*
28107 		 * The conn is closing as a result of which CONN_CLOSING
28108 		 * is set. Return.
28109 		 */
28110 		mutex_exit(&connp->conn_lock);
28111 		return;
28112 	} else if (connp->conn_idl == NULL) {
28113 		/*
28114 		 * Assign the next drain list round robin. We dont' use
28115 		 * a lock, and thus it may not be strictly round robin.
28116 		 * Atomicity of load/stores is enough to make sure that
28117 		 * conn_drain_list_index is always within bounds.
28118 		 */
28119 		index = ipst->ips_conn_drain_list_index;
28120 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28121 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28122 		index++;
28123 		if (index == ipst->ips_conn_drain_list_cnt)
28124 			index = 0;
28125 		ipst->ips_conn_drain_list_index = index;
28126 	}
28127 	mutex_exit(&connp->conn_lock);
28128 
28129 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28130 	if ((connp->conn_drain_prev != NULL) ||
28131 	    (connp->conn_state_flags & CONN_CLOSING)) {
28132 		/*
28133 		 * The conn is already in the drain list, OR
28134 		 * the conn is closing. We need to check again for
28135 		 * the closing case again since close can happen
28136 		 * after we drop the conn_lock, and before we
28137 		 * acquire the CONN_DRAIN_LIST_LOCK.
28138 		 */
28139 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28140 		return;
28141 	} else {
28142 		idl = connp->conn_idl;
28143 	}
28144 
28145 	/*
28146 	 * The conn is not in the drain list. Insert it at the
28147 	 * tail of the drain list. The drain list is circular
28148 	 * and doubly linked. idl_conn points to the 1st element
28149 	 * in the list.
28150 	 */
28151 	if (idl->idl_conn == NULL) {
28152 		idl->idl_conn = connp;
28153 		connp->conn_drain_next = connp;
28154 		connp->conn_drain_prev = connp;
28155 	} else {
28156 		conn_t *head = idl->idl_conn;
28157 
28158 		connp->conn_drain_next = head;
28159 		connp->conn_drain_prev = head->conn_drain_prev;
28160 		head->conn_drain_prev->conn_drain_next = connp;
28161 		head->conn_drain_prev = connp;
28162 	}
28163 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28164 }
28165 
28166 /*
28167  * This conn is closing, and we are called from ip_close. OR
28168  * This conn has been serviced by ip_wsrv, and we need to do the tail
28169  * processing.
28170  * If this conn is part of the drain list, we may need to sustain the drain
28171  * process by qenabling the next conn in the drain list. We may also need to
28172  * remove this conn from the list, if it is done.
28173  */
28174 static void
28175 conn_drain_tail(conn_t *connp, boolean_t closing)
28176 {
28177 	idl_t *idl;
28178 
28179 	/*
28180 	 * connp->conn_idl is stable at this point, and no lock is needed
28181 	 * to check it. If we are called from ip_close, close has already
28182 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28183 	 * called us only because conn_idl is non-null. If we are called thru
28184 	 * service, conn_idl could be null, but it cannot change because
28185 	 * service is single-threaded per queue, and there cannot be another
28186 	 * instance of service trying to call conn_drain_insert on this conn
28187 	 * now.
28188 	 */
28189 	ASSERT(!closing || (connp->conn_idl != NULL));
28190 
28191 	/*
28192 	 * If connp->conn_idl is null, the conn has not been inserted into any
28193 	 * drain list even once since creation of the conn. Just return.
28194 	 */
28195 	if (connp->conn_idl == NULL)
28196 		return;
28197 
28198 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28199 
28200 	if (connp->conn_drain_prev == NULL) {
28201 		/* This conn is currently not in the drain list.  */
28202 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28203 		return;
28204 	}
28205 	idl = connp->conn_idl;
28206 	if (idl->idl_conn_draining == connp) {
28207 		/*
28208 		 * This conn is the current drainer. If this is the last conn
28209 		 * in the drain list, we need to do more checks, in the 'if'
28210 		 * below. Otherwwise we need to just qenable the next conn,
28211 		 * to sustain the draining, and is handled in the 'else'
28212 		 * below.
28213 		 */
28214 		if (connp->conn_drain_next == idl->idl_conn) {
28215 			/*
28216 			 * This conn is the last in this list. This round
28217 			 * of draining is complete. If idl_repeat is set,
28218 			 * it means another flow enabling has happened from
28219 			 * the driver/streams and we need to another round
28220 			 * of draining.
28221 			 * If there are more than 2 conns in the drain list,
28222 			 * do a left rotate by 1, so that all conns except the
28223 			 * conn at the head move towards the head by 1, and the
28224 			 * the conn at the head goes to the tail. This attempts
28225 			 * a more even share for all queues that are being
28226 			 * drained.
28227 			 */
28228 			if ((connp->conn_drain_next != connp) &&
28229 			    (idl->idl_conn->conn_drain_next != connp)) {
28230 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28231 			}
28232 			if (idl->idl_repeat) {
28233 				qenable(idl->idl_conn->conn_wq);
28234 				idl->idl_conn_draining = idl->idl_conn;
28235 				idl->idl_repeat = 0;
28236 			} else {
28237 				idl->idl_conn_draining = NULL;
28238 			}
28239 		} else {
28240 			/*
28241 			 * If the next queue that we are now qenable'ing,
28242 			 * is closing, it will remove itself from this list
28243 			 * and qenable the subsequent queue in ip_close().
28244 			 * Serialization is acheived thru idl_lock.
28245 			 */
28246 			qenable(connp->conn_drain_next->conn_wq);
28247 			idl->idl_conn_draining = connp->conn_drain_next;
28248 		}
28249 	}
28250 	if (!connp->conn_did_putbq || closing) {
28251 		/*
28252 		 * Remove ourself from the drain list, if we did not do
28253 		 * a putbq, or if the conn is closing.
28254 		 * Note: It is possible that q->q_first is non-null. It means
28255 		 * that these messages landed after we did a enableok() in
28256 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28257 		 * service them.
28258 		 */
28259 		if (connp->conn_drain_next == connp) {
28260 			/* Singleton in the list */
28261 			ASSERT(connp->conn_drain_prev == connp);
28262 			idl->idl_conn = NULL;
28263 			idl->idl_conn_draining = NULL;
28264 		} else {
28265 			connp->conn_drain_prev->conn_drain_next =
28266 			    connp->conn_drain_next;
28267 			connp->conn_drain_next->conn_drain_prev =
28268 			    connp->conn_drain_prev;
28269 			if (idl->idl_conn == connp)
28270 				idl->idl_conn = connp->conn_drain_next;
28271 			ASSERT(idl->idl_conn_draining != connp);
28272 
28273 		}
28274 		connp->conn_drain_next = NULL;
28275 		connp->conn_drain_prev = NULL;
28276 	}
28277 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28278 }
28279 
28280 /*
28281  * Write service routine. Shared perimeter entry point.
28282  * ip_wsrv can be called in any of the following ways.
28283  * 1. The device queue's messages has fallen below the low water mark
28284  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28285  *    the drain lists and backenable the first conn in each list.
28286  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28287  *    qenabled non-tcp upper layers. We start dequeing messages and call
28288  *    ip_wput for each message.
28289  */
28290 
28291 void
28292 ip_wsrv(queue_t *q)
28293 {
28294 	conn_t	*connp;
28295 	ill_t	*ill;
28296 	mblk_t	*mp;
28297 
28298 	if (q->q_next) {
28299 		ill = (ill_t *)q->q_ptr;
28300 		if (ill->ill_state_flags == 0) {
28301 			/*
28302 			 * The device flow control has opened up.
28303 			 * Walk through conn drain lists and qenable the
28304 			 * first conn in each list. This makes sense only
28305 			 * if the stream is fully plumbed and setup.
28306 			 * Hence the if check above.
28307 			 */
28308 			ip1dbg(("ip_wsrv: walking\n"));
28309 			conn_walk_drain(ill->ill_ipst);
28310 		}
28311 		return;
28312 	}
28313 
28314 	connp = Q_TO_CONN(q);
28315 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28316 
28317 	/*
28318 	 * 1. Set conn_draining flag to signal that service is active.
28319 	 *
28320 	 * 2. ip_output determines whether it has been called from service,
28321 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28322 	 *    has been called from service.
28323 	 *
28324 	 * 3. Message ordering is preserved by the following logic.
28325 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28326 	 *    the message at the tail, if conn_draining is set (i.e. service
28327 	 *    is running) or if q->q_first is non-null.
28328 	 *
28329 	 *    ii. If ip_output is called from service, and if ip_output cannot
28330 	 *    putnext due to flow control, it does a putbq.
28331 	 *
28332 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28333 	 *    (causing an infinite loop).
28334 	 */
28335 	ASSERT(!connp->conn_did_putbq);
28336 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28337 		connp->conn_draining = 1;
28338 		noenable(q);
28339 		while ((mp = getq(q)) != NULL) {
28340 			ASSERT(CONN_Q(q));
28341 
28342 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28343 			if (connp->conn_did_putbq) {
28344 				/* ip_wput did a putbq */
28345 				break;
28346 			}
28347 		}
28348 		/*
28349 		 * At this point, a thread coming down from top, calling
28350 		 * ip_wput, may end up queueing the message. We have not yet
28351 		 * enabled the queue, so ip_wsrv won't be called again.
28352 		 * To avoid this race, check q->q_first again (in the loop)
28353 		 * If the other thread queued the message before we call
28354 		 * enableok(), we will catch it in the q->q_first check.
28355 		 * If the other thread queues the message after we call
28356 		 * enableok(), ip_wsrv will be called again by STREAMS.
28357 		 */
28358 		connp->conn_draining = 0;
28359 		enableok(q);
28360 	}
28361 
28362 	/* Enable the next conn for draining */
28363 	conn_drain_tail(connp, B_FALSE);
28364 
28365 	connp->conn_did_putbq = 0;
28366 }
28367 
28368 /*
28369  * Walk the list of all conn's calling the function provided with the
28370  * specified argument for each.	 Note that this only walks conn's that
28371  * have been bound.
28372  * Applies to both IPv4 and IPv6.
28373  */
28374 static void
28375 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28376 {
28377 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28378 	    ipst->ips_ipcl_udp_fanout_size,
28379 	    func, arg, zoneid);
28380 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28381 	    ipst->ips_ipcl_conn_fanout_size,
28382 	    func, arg, zoneid);
28383 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28384 	    ipst->ips_ipcl_bind_fanout_size,
28385 	    func, arg, zoneid);
28386 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28387 	    IPPROTO_MAX, func, arg, zoneid);
28388 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28389 	    IPPROTO_MAX, func, arg, zoneid);
28390 }
28391 
28392 /*
28393  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28394  * of conns that need to be drained, check if drain is already in progress.
28395  * If so set the idl_repeat bit, indicating that the last conn in the list
28396  * needs to reinitiate the drain once again, for the list. If drain is not
28397  * in progress for the list, initiate the draining, by qenabling the 1st
28398  * conn in the list. The drain is self-sustaining, each qenabled conn will
28399  * in turn qenable the next conn, when it is done/blocked/closing.
28400  */
28401 static void
28402 conn_walk_drain(ip_stack_t *ipst)
28403 {
28404 	int i;
28405 	idl_t *idl;
28406 
28407 	IP_STAT(ipst, ip_conn_walk_drain);
28408 
28409 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28410 		idl = &ipst->ips_conn_drain_list[i];
28411 		mutex_enter(&idl->idl_lock);
28412 		if (idl->idl_conn == NULL) {
28413 			mutex_exit(&idl->idl_lock);
28414 			continue;
28415 		}
28416 		/*
28417 		 * If this list is not being drained currently by
28418 		 * an ip_wsrv thread, start the process.
28419 		 */
28420 		if (idl->idl_conn_draining == NULL) {
28421 			ASSERT(idl->idl_repeat == 0);
28422 			qenable(idl->idl_conn->conn_wq);
28423 			idl->idl_conn_draining = idl->idl_conn;
28424 		} else {
28425 			idl->idl_repeat = 1;
28426 		}
28427 		mutex_exit(&idl->idl_lock);
28428 	}
28429 }
28430 
28431 /*
28432  * Walk an conn hash table of `count' buckets, calling func for each entry.
28433  */
28434 static void
28435 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28436     zoneid_t zoneid)
28437 {
28438 	conn_t	*connp;
28439 
28440 	while (count-- > 0) {
28441 		mutex_enter(&connfp->connf_lock);
28442 		for (connp = connfp->connf_head; connp != NULL;
28443 		    connp = connp->conn_next) {
28444 			if (zoneid == GLOBAL_ZONEID ||
28445 			    zoneid == connp->conn_zoneid) {
28446 				CONN_INC_REF(connp);
28447 				mutex_exit(&connfp->connf_lock);
28448 				(*func)(connp, arg);
28449 				mutex_enter(&connfp->connf_lock);
28450 				CONN_DEC_REF(connp);
28451 			}
28452 		}
28453 		mutex_exit(&connfp->connf_lock);
28454 		connfp++;
28455 	}
28456 }
28457 
28458 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28459 static void
28460 conn_report1(conn_t *connp, void *mp)
28461 {
28462 	char	buf1[INET6_ADDRSTRLEN];
28463 	char	buf2[INET6_ADDRSTRLEN];
28464 	uint_t	print_len, buf_len;
28465 
28466 	ASSERT(connp != NULL);
28467 
28468 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28469 	if (buf_len <= 0)
28470 		return;
28471 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28472 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28473 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28474 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28475 	    "%5d %s/%05d %s/%05d\n",
28476 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28477 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28478 	    buf1, connp->conn_lport,
28479 	    buf2, connp->conn_fport);
28480 	if (print_len < buf_len) {
28481 		((mblk_t *)mp)->b_wptr += print_len;
28482 	} else {
28483 		((mblk_t *)mp)->b_wptr += buf_len;
28484 	}
28485 }
28486 
28487 /*
28488  * Named Dispatch routine to produce a formatted report on all conns
28489  * that are listed in one of the fanout tables.
28490  * This report is accessed by using the ndd utility to "get" ND variable
28491  * "ip_conn_status".
28492  */
28493 /* ARGSUSED */
28494 static int
28495 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28496 {
28497 	conn_t *connp = Q_TO_CONN(q);
28498 
28499 	(void) mi_mpprintf(mp,
28500 	    "CONN      " MI_COL_HDRPAD_STR
28501 	    "rfq      " MI_COL_HDRPAD_STR
28502 	    "stq      " MI_COL_HDRPAD_STR
28503 	    " zone local                 remote");
28504 
28505 	/*
28506 	 * Because of the ndd constraint, at most we can have 64K buffer
28507 	 * to put in all conn info.  So to be more efficient, just
28508 	 * allocate a 64K buffer here, assuming we need that large buffer.
28509 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28510 	 */
28511 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28512 		/* The following may work even if we cannot get a large buf. */
28513 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28514 		return (0);
28515 	}
28516 
28517 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28518 	    connp->conn_netstack->netstack_ip);
28519 	return (0);
28520 }
28521 
28522 /*
28523  * Determine if the ill and multicast aspects of that packets
28524  * "matches" the conn.
28525  */
28526 boolean_t
28527 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28528     zoneid_t zoneid)
28529 {
28530 	ill_t *in_ill;
28531 	boolean_t found;
28532 	ipif_t *ipif;
28533 	ire_t *ire;
28534 	ipaddr_t dst, src;
28535 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28536 
28537 	dst = ipha->ipha_dst;
28538 	src = ipha->ipha_src;
28539 
28540 	/*
28541 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28542 	 * unicast, broadcast and multicast reception to
28543 	 * conn_incoming_ill. conn_wantpacket itself is called
28544 	 * only for BROADCAST and multicast.
28545 	 *
28546 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28547 	 *    is part of a group. Hence, we should be receiving
28548 	 *    just one copy of broadcast for the whole group.
28549 	 *    Thus, if it is part of the group the packet could
28550 	 *    come on any ill of the group and hence we need a
28551 	 *    match on the group. Otherwise, match on ill should
28552 	 *    be sufficient.
28553 	 *
28554 	 * 2) ip_rput does not suppress duplicate multicast packets.
28555 	 *    If there are two interfaces in a ill group and we have
28556 	 *    2 applications (conns) joined a multicast group G on
28557 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28558 	 *    will give us two packets because we join G on both the
28559 	 *    interfaces rather than nominating just one interface
28560 	 *    for receiving multicast like broadcast above. So,
28561 	 *    we have to call ilg_lookup_ill to filter out duplicate
28562 	 *    copies, if ill is part of a group.
28563 	 */
28564 	in_ill = connp->conn_incoming_ill;
28565 	if (in_ill != NULL) {
28566 		if (in_ill->ill_group == NULL) {
28567 			if (in_ill != ill)
28568 				return (B_FALSE);
28569 		} else if (in_ill->ill_group != ill->ill_group) {
28570 			return (B_FALSE);
28571 		}
28572 	}
28573 
28574 	if (!CLASSD(dst)) {
28575 		if (IPCL_ZONE_MATCH(connp, zoneid))
28576 			return (B_TRUE);
28577 		/*
28578 		 * The conn is in a different zone; we need to check that this
28579 		 * broadcast address is configured in the application's zone and
28580 		 * on one ill in the group.
28581 		 */
28582 		ipif = ipif_get_next_ipif(NULL, ill);
28583 		if (ipif == NULL)
28584 			return (B_FALSE);
28585 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28586 		    connp->conn_zoneid, NULL,
28587 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28588 		ipif_refrele(ipif);
28589 		if (ire != NULL) {
28590 			ire_refrele(ire);
28591 			return (B_TRUE);
28592 		} else {
28593 			return (B_FALSE);
28594 		}
28595 	}
28596 
28597 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28598 	    connp->conn_zoneid == zoneid) {
28599 		/*
28600 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28601 		 * disabled, therefore we don't dispatch the multicast packet to
28602 		 * the sending zone.
28603 		 */
28604 		return (B_FALSE);
28605 	}
28606 
28607 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28608 		/*
28609 		 * Multicast packet on the loopback interface: we only match
28610 		 * conns who joined the group in the specified zone.
28611 		 */
28612 		return (B_FALSE);
28613 	}
28614 
28615 	if (connp->conn_multi_router) {
28616 		/* multicast packet and multicast router socket: send up */
28617 		return (B_TRUE);
28618 	}
28619 
28620 	mutex_enter(&connp->conn_lock);
28621 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28622 	mutex_exit(&connp->conn_lock);
28623 	return (found);
28624 }
28625 
28626 /*
28627  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28628  */
28629 /* ARGSUSED */
28630 static void
28631 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28632 {
28633 	ill_t *ill = (ill_t *)q->q_ptr;
28634 	mblk_t	*mp1, *mp2;
28635 	ipif_t  *ipif;
28636 	int err = 0;
28637 	conn_t *connp = NULL;
28638 	ipsq_t	*ipsq;
28639 	arc_t	*arc;
28640 
28641 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28642 
28643 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28644 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28645 
28646 	ASSERT(IAM_WRITER_ILL(ill));
28647 	mp2 = mp->b_cont;
28648 	mp->b_cont = NULL;
28649 
28650 	/*
28651 	 * We have now received the arp bringup completion message
28652 	 * from ARP. Mark the arp bringup as done. Also if the arp
28653 	 * stream has already started closing, send up the AR_ARP_CLOSING
28654 	 * ack now since ARP is waiting in close for this ack.
28655 	 */
28656 	mutex_enter(&ill->ill_lock);
28657 	ill->ill_arp_bringup_pending = 0;
28658 	if (ill->ill_arp_closing) {
28659 		mutex_exit(&ill->ill_lock);
28660 		/* Let's reuse the mp for sending the ack */
28661 		arc = (arc_t *)mp->b_rptr;
28662 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28663 		arc->arc_cmd = AR_ARP_CLOSING;
28664 		qreply(q, mp);
28665 	} else {
28666 		mutex_exit(&ill->ill_lock);
28667 		freeb(mp);
28668 	}
28669 
28670 	ipsq = ill->ill_phyint->phyint_ipsq;
28671 	ipif = ipsq->ipsq_pending_ipif;
28672 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28673 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28674 	if (mp1 == NULL) {
28675 		/* bringup was aborted by the user */
28676 		freemsg(mp2);
28677 		return;
28678 	}
28679 
28680 	/*
28681 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28682 	 * must have an associated conn_t.  Otherwise, we're bringing this
28683 	 * interface back up as part of handling an asynchronous event (e.g.,
28684 	 * physical address change).
28685 	 */
28686 	if (ipsq->ipsq_current_ioctl != 0) {
28687 		ASSERT(connp != NULL);
28688 		q = CONNP_TO_WQ(connp);
28689 	} else {
28690 		ASSERT(connp == NULL);
28691 		q = ill->ill_rq;
28692 	}
28693 
28694 	/*
28695 	 * If the DL_BIND_REQ fails, it is noted
28696 	 * in arc_name_offset.
28697 	 */
28698 	err = *((int *)mp2->b_rptr);
28699 	if (err == 0) {
28700 		if (ipif->ipif_isv6) {
28701 			if ((err = ipif_up_done_v6(ipif)) != 0)
28702 				ip0dbg(("ip_arp_done: init failed\n"));
28703 		} else {
28704 			if ((err = ipif_up_done(ipif)) != 0)
28705 				ip0dbg(("ip_arp_done: init failed\n"));
28706 		}
28707 	} else {
28708 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28709 	}
28710 
28711 	freemsg(mp2);
28712 
28713 	if ((err == 0) && (ill->ill_up_ipifs)) {
28714 		err = ill_up_ipifs(ill, q, mp1);
28715 		if (err == EINPROGRESS)
28716 			return;
28717 	}
28718 
28719 	if (ill->ill_up_ipifs)
28720 		ill_group_cleanup(ill);
28721 
28722 	/*
28723 	 * The operation must complete without EINPROGRESS since
28724 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28725 	 * Otherwise, the operation will be stuck forever in the ipsq.
28726 	 */
28727 	ASSERT(err != EINPROGRESS);
28728 	if (ipsq->ipsq_current_ioctl != 0)
28729 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28730 	else
28731 		ipsq_current_finish(ipsq);
28732 }
28733 
28734 /* Allocate the private structure */
28735 static int
28736 ip_priv_alloc(void **bufp)
28737 {
28738 	void	*buf;
28739 
28740 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28741 		return (ENOMEM);
28742 
28743 	*bufp = buf;
28744 	return (0);
28745 }
28746 
28747 /* Function to delete the private structure */
28748 void
28749 ip_priv_free(void *buf)
28750 {
28751 	ASSERT(buf != NULL);
28752 	kmem_free(buf, sizeof (ip_priv_t));
28753 }
28754 
28755 /*
28756  * The entry point for IPPF processing.
28757  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28758  * routine just returns.
28759  *
28760  * When called, ip_process generates an ipp_packet_t structure
28761  * which holds the state information for this packet and invokes the
28762  * the classifier (via ipp_packet_process). The classification, depending on
28763  * configured filters, results in a list of actions for this packet. Invoking
28764  * an action may cause the packet to be dropped, in which case the resulting
28765  * mblk (*mpp) is NULL. proc indicates the callout position for
28766  * this packet and ill_index is the interface this packet on or will leave
28767  * on (inbound and outbound resp.).
28768  */
28769 void
28770 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28771 {
28772 	mblk_t		*mp;
28773 	ip_priv_t	*priv;
28774 	ipp_action_id_t	aid;
28775 	int		rc = 0;
28776 	ipp_packet_t	*pp;
28777 #define	IP_CLASS	"ip"
28778 
28779 	/* If the classifier is not loaded, return  */
28780 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28781 		return;
28782 	}
28783 
28784 	mp = *mpp;
28785 	ASSERT(mp != NULL);
28786 
28787 	/* Allocate the packet structure */
28788 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28789 	if (rc != 0) {
28790 		*mpp = NULL;
28791 		freemsg(mp);
28792 		return;
28793 	}
28794 
28795 	/* Allocate the private structure */
28796 	rc = ip_priv_alloc((void **)&priv);
28797 	if (rc != 0) {
28798 		*mpp = NULL;
28799 		freemsg(mp);
28800 		ipp_packet_free(pp);
28801 		return;
28802 	}
28803 	priv->proc = proc;
28804 	priv->ill_index = ill_index;
28805 	ipp_packet_set_private(pp, priv, ip_priv_free);
28806 	ipp_packet_set_data(pp, mp);
28807 
28808 	/* Invoke the classifier */
28809 	rc = ipp_packet_process(&pp);
28810 	if (pp != NULL) {
28811 		mp = ipp_packet_get_data(pp);
28812 		ipp_packet_free(pp);
28813 		if (rc != 0) {
28814 			freemsg(mp);
28815 			*mpp = NULL;
28816 		}
28817 	} else {
28818 		*mpp = NULL;
28819 	}
28820 #undef	IP_CLASS
28821 }
28822 
28823 /*
28824  * Propagate a multicast group membership operation (add/drop) on
28825  * all the interfaces crossed by the related multirt routes.
28826  * The call is considered successful if the operation succeeds
28827  * on at least one interface.
28828  */
28829 static int
28830 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28831     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28832     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28833     mblk_t *first_mp)
28834 {
28835 	ire_t		*ire_gw;
28836 	irb_t		*irb;
28837 	int		error = 0;
28838 	opt_restart_t	*or;
28839 	ip_stack_t	*ipst = ire->ire_ipst;
28840 
28841 	irb = ire->ire_bucket;
28842 	ASSERT(irb != NULL);
28843 
28844 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28845 
28846 	or = (opt_restart_t *)first_mp->b_rptr;
28847 	IRB_REFHOLD(irb);
28848 	for (; ire != NULL; ire = ire->ire_next) {
28849 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28850 			continue;
28851 		if (ire->ire_addr != group)
28852 			continue;
28853 
28854 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28855 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28856 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28857 		/* No resolver exists for the gateway; skip this ire. */
28858 		if (ire_gw == NULL)
28859 			continue;
28860 
28861 		/*
28862 		 * This function can return EINPROGRESS. If so the operation
28863 		 * will be restarted from ip_restart_optmgmt which will
28864 		 * call ip_opt_set and option processing will restart for
28865 		 * this option. So we may end up calling 'fn' more than once.
28866 		 * This requires that 'fn' is idempotent except for the
28867 		 * return value. The operation is considered a success if
28868 		 * it succeeds at least once on any one interface.
28869 		 */
28870 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28871 		    NULL, fmode, src, first_mp);
28872 		if (error == 0)
28873 			or->or_private = CGTP_MCAST_SUCCESS;
28874 
28875 		if (ip_debug > 0) {
28876 			ulong_t	off;
28877 			char	*ksym;
28878 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28879 			ip2dbg(("ip_multirt_apply_membership: "
28880 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28881 			    "error %d [success %u]\n",
28882 			    ksym ? ksym : "?",
28883 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28884 			    error, or->or_private));
28885 		}
28886 
28887 		ire_refrele(ire_gw);
28888 		if (error == EINPROGRESS) {
28889 			IRB_REFRELE(irb);
28890 			return (error);
28891 		}
28892 	}
28893 	IRB_REFRELE(irb);
28894 	/*
28895 	 * Consider the call as successful if we succeeded on at least
28896 	 * one interface. Otherwise, return the last encountered error.
28897 	 */
28898 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28899 }
28900 
28901 
28902 /*
28903  * Issue a warning regarding a route crossing an interface with an
28904  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28905  * amount of time is logged.
28906  */
28907 static void
28908 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28909 {
28910 	hrtime_t	current = gethrtime();
28911 	char		buf[INET_ADDRSTRLEN];
28912 	ip_stack_t	*ipst = ire->ire_ipst;
28913 
28914 	/* Convert interval in ms to hrtime in ns */
28915 	if (ipst->ips_multirt_bad_mtu_last_time +
28916 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28917 	    current) {
28918 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28919 		    "to %s, incorrect MTU %u (expected %u)\n",
28920 		    ip_dot_addr(ire->ire_addr, buf),
28921 		    ire->ire_max_frag, max_frag);
28922 
28923 		ipst->ips_multirt_bad_mtu_last_time = current;
28924 	}
28925 }
28926 
28927 
28928 /*
28929  * Get the CGTP (multirouting) filtering status.
28930  * If 0, the CGTP hooks are transparent.
28931  */
28932 /* ARGSUSED */
28933 static int
28934 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28935 {
28936 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28937 
28938 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28939 	return (0);
28940 }
28941 
28942 
28943 /*
28944  * Set the CGTP (multirouting) filtering status.
28945  * If the status is changed from active to transparent
28946  * or from transparent to active, forward the new status
28947  * to the filtering module (if loaded).
28948  */
28949 /* ARGSUSED */
28950 static int
28951 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28952     cred_t *ioc_cr)
28953 {
28954 	long		new_value;
28955 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28956 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28957 
28958 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28959 		return (EPERM);
28960 
28961 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28962 	    new_value < 0 || new_value > 1) {
28963 		return (EINVAL);
28964 	}
28965 
28966 	if ((!*ip_cgtp_filter_value) && new_value) {
28967 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28968 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28969 		    " (module not loaded)" : "");
28970 	}
28971 	if (*ip_cgtp_filter_value && (!new_value)) {
28972 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28973 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28974 		    " (module not loaded)" : "");
28975 	}
28976 
28977 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28978 		int	res;
28979 		netstackid_t stackid;
28980 
28981 		stackid = ipst->ips_netstack->netstack_stackid;
28982 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28983 		    new_value);
28984 		if (res)
28985 			return (res);
28986 	}
28987 
28988 	*ip_cgtp_filter_value = (boolean_t)new_value;
28989 
28990 	return (0);
28991 }
28992 
28993 
28994 /*
28995  * Return the expected CGTP hooks version number.
28996  */
28997 int
28998 ip_cgtp_filter_supported(void)
28999 {
29000 	return (ip_cgtp_filter_rev);
29001 }
29002 
29003 
29004 /*
29005  * CGTP hooks can be registered by invoking this function.
29006  * Checks that the version number matches.
29007  */
29008 int
29009 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29010 {
29011 	netstack_t *ns;
29012 	ip_stack_t *ipst;
29013 
29014 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29015 		return (ENOTSUP);
29016 
29017 	ns = netstack_find_by_stackid(stackid);
29018 	if (ns == NULL)
29019 		return (EINVAL);
29020 	ipst = ns->netstack_ip;
29021 	ASSERT(ipst != NULL);
29022 
29023 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29024 		netstack_rele(ns);
29025 		return (EALREADY);
29026 	}
29027 
29028 	ipst->ips_ip_cgtp_filter_ops = ops;
29029 	netstack_rele(ns);
29030 	return (0);
29031 }
29032 
29033 /*
29034  * CGTP hooks can be unregistered by invoking this function.
29035  * Returns ENXIO if there was no registration.
29036  * Returns EBUSY if the ndd variable has not been turned off.
29037  */
29038 int
29039 ip_cgtp_filter_unregister(netstackid_t stackid)
29040 {
29041 	netstack_t *ns;
29042 	ip_stack_t *ipst;
29043 
29044 	ns = netstack_find_by_stackid(stackid);
29045 	if (ns == NULL)
29046 		return (EINVAL);
29047 	ipst = ns->netstack_ip;
29048 	ASSERT(ipst != NULL);
29049 
29050 	if (ipst->ips_ip_cgtp_filter) {
29051 		netstack_rele(ns);
29052 		return (EBUSY);
29053 	}
29054 
29055 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29056 		netstack_rele(ns);
29057 		return (ENXIO);
29058 	}
29059 	ipst->ips_ip_cgtp_filter_ops = NULL;
29060 	netstack_rele(ns);
29061 	return (0);
29062 }
29063 
29064 /*
29065  * Check whether there is a CGTP filter registration.
29066  * Returns non-zero if there is a registration, otherwise returns zero.
29067  * Note: returns zero if bad stackid.
29068  */
29069 int
29070 ip_cgtp_filter_is_registered(netstackid_t stackid)
29071 {
29072 	netstack_t *ns;
29073 	ip_stack_t *ipst;
29074 	int ret;
29075 
29076 	ns = netstack_find_by_stackid(stackid);
29077 	if (ns == NULL)
29078 		return (0);
29079 	ipst = ns->netstack_ip;
29080 	ASSERT(ipst != NULL);
29081 
29082 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29083 		ret = 1;
29084 	else
29085 		ret = 0;
29086 
29087 	netstack_rele(ns);
29088 	return (ret);
29089 }
29090 
29091 static squeue_func_t
29092 ip_squeue_switch(int val)
29093 {
29094 	squeue_func_t rval = squeue_fill;
29095 
29096 	switch (val) {
29097 	case IP_SQUEUE_ENTER_NODRAIN:
29098 		rval = squeue_enter_nodrain;
29099 		break;
29100 	case IP_SQUEUE_ENTER:
29101 		rval = squeue_enter;
29102 		break;
29103 	default:
29104 		break;
29105 	}
29106 	return (rval);
29107 }
29108 
29109 /* ARGSUSED */
29110 static int
29111 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29112     caddr_t addr, cred_t *cr)
29113 {
29114 	int *v = (int *)addr;
29115 	long new_value;
29116 
29117 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29118 		return (EPERM);
29119 
29120 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29121 		return (EINVAL);
29122 
29123 	ip_input_proc = ip_squeue_switch(new_value);
29124 	*v = new_value;
29125 	return (0);
29126 }
29127 
29128 /* ARGSUSED */
29129 static int
29130 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29131     caddr_t addr, cred_t *cr)
29132 {
29133 	int *v = (int *)addr;
29134 	long new_value;
29135 
29136 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29137 		return (EPERM);
29138 
29139 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29140 		return (EINVAL);
29141 
29142 	*v = new_value;
29143 	return (0);
29144 }
29145 
29146 /*
29147  * Handle changes to ipmp_hook_emulation ndd variable.
29148  * Need to update phyint_hook_ifindex.
29149  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29150  */
29151 static void
29152 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29153 {
29154 	phyint_t *phyi;
29155 	phyint_t *phyi_tmp;
29156 	char *groupname;
29157 	int namelen;
29158 	ill_t	*ill;
29159 	boolean_t new_group;
29160 
29161 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29162 	/*
29163 	 * Group indicies are stored in the phyint - a common structure
29164 	 * to both IPv4 and IPv6.
29165 	 */
29166 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29167 	for (; phyi != NULL;
29168 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29169 	    phyi, AVL_AFTER)) {
29170 		/* Ignore the ones that do not have a group */
29171 		if (phyi->phyint_groupname_len == 0)
29172 			continue;
29173 
29174 		/*
29175 		 * Look for other phyint in group.
29176 		 * Clear name/namelen so the lookup doesn't find ourselves.
29177 		 */
29178 		namelen = phyi->phyint_groupname_len;
29179 		groupname = phyi->phyint_groupname;
29180 		phyi->phyint_groupname_len = 0;
29181 		phyi->phyint_groupname = NULL;
29182 
29183 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29184 		/* Restore */
29185 		phyi->phyint_groupname_len = namelen;
29186 		phyi->phyint_groupname = groupname;
29187 
29188 		new_group = B_FALSE;
29189 		if (ipst->ips_ipmp_hook_emulation) {
29190 			/*
29191 			 * If the group already exists and has already
29192 			 * been assigned a group ifindex, we use the existing
29193 			 * group_ifindex, otherwise we pick a new group_ifindex
29194 			 * here.
29195 			 */
29196 			if (phyi_tmp != NULL &&
29197 			    phyi_tmp->phyint_group_ifindex != 0) {
29198 				phyi->phyint_group_ifindex =
29199 				    phyi_tmp->phyint_group_ifindex;
29200 			} else {
29201 				/* XXX We need a recovery strategy here. */
29202 				if (!ip_assign_ifindex(
29203 				    &phyi->phyint_group_ifindex, ipst))
29204 					cmn_err(CE_PANIC,
29205 					    "ip_assign_ifindex() failed");
29206 				new_group = B_TRUE;
29207 			}
29208 		} else {
29209 			phyi->phyint_group_ifindex = 0;
29210 		}
29211 		if (ipst->ips_ipmp_hook_emulation)
29212 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29213 		else
29214 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29215 
29216 		/*
29217 		 * For IP Filter to find out the relationship between
29218 		 * names and interface indicies, we need to generate
29219 		 * a NE_PLUMB event when a new group can appear.
29220 		 * We always generate events when a new interface appears
29221 		 * (even when ipmp_hook_emulation is set) so there
29222 		 * is no need to generate NE_PLUMB events when
29223 		 * ipmp_hook_emulation is turned off.
29224 		 * And since it isn't critical for IP Filter to get
29225 		 * the NE_UNPLUMB events we skip those here.
29226 		 */
29227 		if (new_group) {
29228 			/*
29229 			 * First phyint in group - generate group PLUMB event.
29230 			 * Since we are not running inside the ipsq we do
29231 			 * the dispatch immediately.
29232 			 */
29233 			if (phyi->phyint_illv4 != NULL)
29234 				ill = phyi->phyint_illv4;
29235 			else
29236 				ill = phyi->phyint_illv6;
29237 
29238 			if (ill != NULL) {
29239 				mutex_enter(&ill->ill_lock);
29240 				ill_nic_info_plumb(ill, B_TRUE);
29241 				ill_nic_info_dispatch(ill);
29242 				mutex_exit(&ill->ill_lock);
29243 			}
29244 		}
29245 	}
29246 	rw_exit(&ipst->ips_ill_g_lock);
29247 }
29248 
29249 /* ARGSUSED */
29250 static int
29251 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29252     caddr_t addr, cred_t *cr)
29253 {
29254 	int *v = (int *)addr;
29255 	long new_value;
29256 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29257 
29258 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29259 		return (EINVAL);
29260 
29261 	if (*v != new_value) {
29262 		*v = new_value;
29263 		ipmp_hook_emulation_changed(ipst);
29264 	}
29265 	return (0);
29266 }
29267 
29268 static void *
29269 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29270 {
29271 	kstat_t *ksp;
29272 
29273 	ip_stat_t template = {
29274 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29275 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29276 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29277 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29278 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29279 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29280 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29281 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29282 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29283 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29284 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29285 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29286 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29287 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29288 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29289 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29290 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29291 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29292 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29293 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29294 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29295 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29296 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29297 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29298 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29299 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29300 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29301 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29302 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29303 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29304 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29305 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29306 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29307 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29308 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29309 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29310 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29311 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29312 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29313 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29314 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29315 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29316 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29317 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29318 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29319 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29320 	};
29321 
29322 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29323 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29324 	    KSTAT_FLAG_VIRTUAL, stackid);
29325 
29326 	if (ksp == NULL)
29327 		return (NULL);
29328 
29329 	bcopy(&template, ip_statisticsp, sizeof (template));
29330 	ksp->ks_data = (void *)ip_statisticsp;
29331 	ksp->ks_private = (void *)(uintptr_t)stackid;
29332 
29333 	kstat_install(ksp);
29334 	return (ksp);
29335 }
29336 
29337 static void
29338 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29339 {
29340 	if (ksp != NULL) {
29341 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29342 		kstat_delete_netstack(ksp, stackid);
29343 	}
29344 }
29345 
29346 static void *
29347 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29348 {
29349 	kstat_t	*ksp;
29350 
29351 	ip_named_kstat_t template = {
29352 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29353 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29354 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29355 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29356 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29357 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29358 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29359 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29360 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29361 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29362 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29363 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29364 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29365 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29366 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29367 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29368 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29369 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29370 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29371 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29372 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29373 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29374 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29375 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29376 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29377 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29378 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29379 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29380 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29381 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29382 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29383 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29384 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29385 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29386 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29387 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29388 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29389 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29390 	};
29391 
29392 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29393 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29394 	if (ksp == NULL || ksp->ks_data == NULL)
29395 		return (NULL);
29396 
29397 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29398 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29399 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29400 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29401 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29402 
29403 	template.netToMediaEntrySize.value.i32 =
29404 	    sizeof (mib2_ipNetToMediaEntry_t);
29405 
29406 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29407 
29408 	bcopy(&template, ksp->ks_data, sizeof (template));
29409 	ksp->ks_update = ip_kstat_update;
29410 	ksp->ks_private = (void *)(uintptr_t)stackid;
29411 
29412 	kstat_install(ksp);
29413 	return (ksp);
29414 }
29415 
29416 static void
29417 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29418 {
29419 	if (ksp != NULL) {
29420 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29421 		kstat_delete_netstack(ksp, stackid);
29422 	}
29423 }
29424 
29425 static int
29426 ip_kstat_update(kstat_t *kp, int rw)
29427 {
29428 	ip_named_kstat_t *ipkp;
29429 	mib2_ipIfStatsEntry_t ipmib;
29430 	ill_walk_context_t ctx;
29431 	ill_t *ill;
29432 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29433 	netstack_t	*ns;
29434 	ip_stack_t	*ipst;
29435 
29436 	if (kp == NULL || kp->ks_data == NULL)
29437 		return (EIO);
29438 
29439 	if (rw == KSTAT_WRITE)
29440 		return (EACCES);
29441 
29442 	ns = netstack_find_by_stackid(stackid);
29443 	if (ns == NULL)
29444 		return (-1);
29445 	ipst = ns->netstack_ip;
29446 	if (ipst == NULL) {
29447 		netstack_rele(ns);
29448 		return (-1);
29449 	}
29450 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29451 
29452 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29453 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29454 	ill = ILL_START_WALK_V4(&ctx, ipst);
29455 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29456 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29457 	rw_exit(&ipst->ips_ill_g_lock);
29458 
29459 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29460 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29461 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29462 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29463 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29464 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29465 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29466 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29467 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29468 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29469 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29470 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29471 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29472 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29473 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29474 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29475 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29476 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29477 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29478 
29479 	ipkp->routingDiscards.value.ui32 =	0;
29480 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29481 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29482 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29483 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29484 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29485 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29486 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29487 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29488 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29489 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29490 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29491 
29492 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29493 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29494 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29495 
29496 	netstack_rele(ns);
29497 
29498 	return (0);
29499 }
29500 
29501 static void *
29502 icmp_kstat_init(netstackid_t stackid)
29503 {
29504 	kstat_t	*ksp;
29505 
29506 	icmp_named_kstat_t template = {
29507 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29508 		{ "inErrors",		KSTAT_DATA_UINT32 },
29509 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29510 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29511 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29512 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29513 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29514 		{ "inEchos",		KSTAT_DATA_UINT32 },
29515 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29516 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29517 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29518 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29519 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29520 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29521 		{ "outErrors",		KSTAT_DATA_UINT32 },
29522 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29523 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29524 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29525 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29526 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29527 		{ "outEchos",		KSTAT_DATA_UINT32 },
29528 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29529 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29530 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29531 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29532 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29533 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29534 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29535 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29536 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29537 		{ "outDrops",		KSTAT_DATA_UINT32 },
29538 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29539 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29540 	};
29541 
29542 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29543 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29544 	if (ksp == NULL || ksp->ks_data == NULL)
29545 		return (NULL);
29546 
29547 	bcopy(&template, ksp->ks_data, sizeof (template));
29548 
29549 	ksp->ks_update = icmp_kstat_update;
29550 	ksp->ks_private = (void *)(uintptr_t)stackid;
29551 
29552 	kstat_install(ksp);
29553 	return (ksp);
29554 }
29555 
29556 static void
29557 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29558 {
29559 	if (ksp != NULL) {
29560 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29561 		kstat_delete_netstack(ksp, stackid);
29562 	}
29563 }
29564 
29565 static int
29566 icmp_kstat_update(kstat_t *kp, int rw)
29567 {
29568 	icmp_named_kstat_t *icmpkp;
29569 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29570 	netstack_t	*ns;
29571 	ip_stack_t	*ipst;
29572 
29573 	if ((kp == NULL) || (kp->ks_data == NULL))
29574 		return (EIO);
29575 
29576 	if (rw == KSTAT_WRITE)
29577 		return (EACCES);
29578 
29579 	ns = netstack_find_by_stackid(stackid);
29580 	if (ns == NULL)
29581 		return (-1);
29582 	ipst = ns->netstack_ip;
29583 	if (ipst == NULL) {
29584 		netstack_rele(ns);
29585 		return (-1);
29586 	}
29587 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29588 
29589 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29590 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29591 	icmpkp->inDestUnreachs.value.ui32 =
29592 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29593 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29594 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29595 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29596 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29597 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29598 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29599 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29600 	icmpkp->inTimestampReps.value.ui32 =
29601 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29602 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29603 	icmpkp->inAddrMaskReps.value.ui32 =
29604 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29605 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29606 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29607 	icmpkp->outDestUnreachs.value.ui32 =
29608 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29609 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29610 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29611 	icmpkp->outSrcQuenchs.value.ui32 =
29612 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29613 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29614 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29615 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29616 	icmpkp->outTimestamps.value.ui32 =
29617 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29618 	icmpkp->outTimestampReps.value.ui32 =
29619 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29620 	icmpkp->outAddrMasks.value.ui32 =
29621 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29622 	icmpkp->outAddrMaskReps.value.ui32 =
29623 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29624 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29625 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29626 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29627 	icmpkp->outFragNeeded.value.ui32 =
29628 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29629 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29630 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29631 	icmpkp->inBadRedirects.value.ui32 =
29632 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29633 
29634 	netstack_rele(ns);
29635 	return (0);
29636 }
29637 
29638 /*
29639  * This is the fanout function for raw socket opened for SCTP.  Note
29640  * that it is called after SCTP checks that there is no socket which
29641  * wants a packet.  Then before SCTP handles this out of the blue packet,
29642  * this function is called to see if there is any raw socket for SCTP.
29643  * If there is and it is bound to the correct address, the packet will
29644  * be sent to that socket.  Note that only one raw socket can be bound to
29645  * a port.  This is assured in ipcl_sctp_hash_insert();
29646  */
29647 void
29648 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29649     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29650     zoneid_t zoneid)
29651 {
29652 	conn_t		*connp;
29653 	queue_t		*rq;
29654 	mblk_t		*first_mp;
29655 	boolean_t	secure;
29656 	ip6_t		*ip6h;
29657 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29658 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29659 
29660 	first_mp = mp;
29661 	if (mctl_present) {
29662 		mp = first_mp->b_cont;
29663 		secure = ipsec_in_is_secure(first_mp);
29664 		ASSERT(mp != NULL);
29665 	} else {
29666 		secure = B_FALSE;
29667 	}
29668 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29669 
29670 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29671 	if (connp == NULL) {
29672 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29673 		return;
29674 	}
29675 	rq = connp->conn_rq;
29676 	if (!canputnext(rq)) {
29677 		CONN_DEC_REF(connp);
29678 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29679 		freemsg(first_mp);
29680 		return;
29681 	}
29682 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29683 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29684 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29685 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29686 		if (first_mp == NULL) {
29687 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29688 			CONN_DEC_REF(connp);
29689 			return;
29690 		}
29691 	}
29692 	/*
29693 	 * We probably should not send M_CTL message up to
29694 	 * raw socket.
29695 	 */
29696 	if (mctl_present)
29697 		freeb(first_mp);
29698 
29699 	/* Initiate IPPF processing here if needed. */
29700 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29701 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29702 		ip_process(IPP_LOCAL_IN, &mp,
29703 		    recv_ill->ill_phyint->phyint_ifindex);
29704 		if (mp == NULL) {
29705 			CONN_DEC_REF(connp);
29706 			return;
29707 		}
29708 	}
29709 
29710 	if (connp->conn_recvif || connp->conn_recvslla ||
29711 	    ((connp->conn_ip_recvpktinfo ||
29712 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29713 	    (flags & IP_FF_IPINFO))) {
29714 		int in_flags = 0;
29715 
29716 		/*
29717 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29718 		 * IPF_RECVIF.
29719 		 */
29720 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29721 			in_flags = IPF_RECVIF;
29722 		}
29723 		if (connp->conn_recvslla) {
29724 			in_flags |= IPF_RECVSLLA;
29725 		}
29726 		if (isv4) {
29727 			mp = ip_add_info(mp, recv_ill, in_flags,
29728 			    IPCL_ZONEID(connp), ipst);
29729 		} else {
29730 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29731 			if (mp == NULL) {
29732 				BUMP_MIB(recv_ill->ill_ip_mib,
29733 				    ipIfStatsInDiscards);
29734 				CONN_DEC_REF(connp);
29735 				return;
29736 			}
29737 		}
29738 	}
29739 
29740 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29741 	/*
29742 	 * We are sending the IPSEC_IN message also up. Refer
29743 	 * to comments above this function.
29744 	 */
29745 	putnext(rq, mp);
29746 	CONN_DEC_REF(connp);
29747 }
29748 
29749 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29750 {									\
29751 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29752 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29753 }
29754 /*
29755  * This function should be called only if all packet processing
29756  * including fragmentation is complete. Callers of this function
29757  * must set mp->b_prev to one of these values:
29758  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29759  * prior to handing over the mp as first argument to this function.
29760  *
29761  * If the ire passed by caller is incomplete, this function
29762  * queues the packet and if necessary, sends ARP request and bails.
29763  * If the ire passed is fully resolved, we simply prepend
29764  * the link-layer header to the packet, do ipsec hw acceleration
29765  * work if necessary, and send the packet out on the wire.
29766  *
29767  * NOTE: IPsec will only call this function with fully resolved
29768  * ires if hw acceleration is involved.
29769  * TODO list :
29770  * 	a Handle M_MULTIDATA so that
29771  *	  tcp_multisend->tcp_multisend_data can
29772  *	  call ip_xmit_v4 directly
29773  *	b Handle post-ARP work for fragments so that
29774  *	  ip_wput_frag can call this function.
29775  */
29776 ipxmit_state_t
29777 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29778 {
29779 	nce_t		*arpce;
29780 	queue_t		*q;
29781 	int		ill_index;
29782 	mblk_t		*nxt_mp, *first_mp;
29783 	boolean_t	xmit_drop = B_FALSE;
29784 	ip_proc_t	proc;
29785 	ill_t		*out_ill;
29786 	int		pkt_len;
29787 
29788 	arpce = ire->ire_nce;
29789 	ASSERT(arpce != NULL);
29790 
29791 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29792 
29793 	mutex_enter(&arpce->nce_lock);
29794 	switch (arpce->nce_state) {
29795 	case ND_REACHABLE:
29796 		/* If there are other queued packets, queue this packet */
29797 		if (arpce->nce_qd_mp != NULL) {
29798 			if (mp != NULL)
29799 				nce_queue_mp_common(arpce, mp, B_FALSE);
29800 			mp = arpce->nce_qd_mp;
29801 		}
29802 		arpce->nce_qd_mp = NULL;
29803 		mutex_exit(&arpce->nce_lock);
29804 
29805 		/*
29806 		 * Flush the queue.  In the common case, where the
29807 		 * ARP is already resolved,  it will go through the
29808 		 * while loop only once.
29809 		 */
29810 		while (mp != NULL) {
29811 
29812 			nxt_mp = mp->b_next;
29813 			mp->b_next = NULL;
29814 			ASSERT(mp->b_datap->db_type != M_CTL);
29815 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29816 			/*
29817 			 * This info is needed for IPQOS to do COS marking
29818 			 * in ip_wput_attach_llhdr->ip_process.
29819 			 */
29820 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29821 			mp->b_prev = NULL;
29822 
29823 			/* set up ill index for outbound qos processing */
29824 			out_ill = ire_to_ill(ire);
29825 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29826 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29827 			    ill_index);
29828 			if (first_mp == NULL) {
29829 				xmit_drop = B_TRUE;
29830 				BUMP_MIB(out_ill->ill_ip_mib,
29831 				    ipIfStatsOutDiscards);
29832 				goto next_mp;
29833 			}
29834 			/* non-ipsec hw accel case */
29835 			if (io == NULL || !io->ipsec_out_accelerated) {
29836 				/* send it */
29837 				q = ire->ire_stq;
29838 				if (proc == IPP_FWD_OUT) {
29839 					UPDATE_IB_PKT_COUNT(ire);
29840 				} else {
29841 					UPDATE_OB_PKT_COUNT(ire);
29842 				}
29843 				ire->ire_last_used_time = lbolt;
29844 
29845 				if (flow_ctl_enabled || canputnext(q)) {
29846 					if (proc == IPP_FWD_OUT) {
29847 
29848 					BUMP_MIB(out_ill->ill_ip_mib,
29849 					    ipIfStatsHCOutForwDatagrams);
29850 
29851 					}
29852 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29853 					    pkt_len);
29854 
29855 					putnext(q, first_mp);
29856 				} else {
29857 					BUMP_MIB(out_ill->ill_ip_mib,
29858 					    ipIfStatsOutDiscards);
29859 					xmit_drop = B_TRUE;
29860 					freemsg(first_mp);
29861 				}
29862 			} else {
29863 				/*
29864 				 * Safety Pup says: make sure this
29865 				 *  is going to the right interface!
29866 				 */
29867 				ill_t *ill1 =
29868 				    (ill_t *)ire->ire_stq->q_ptr;
29869 				int ifindex =
29870 				    ill1->ill_phyint->phyint_ifindex;
29871 				if (ifindex !=
29872 				    io->ipsec_out_capab_ill_index) {
29873 					xmit_drop = B_TRUE;
29874 					freemsg(mp);
29875 				} else {
29876 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29877 					    pkt_len);
29878 					ipsec_hw_putnext(ire->ire_stq, mp);
29879 				}
29880 			}
29881 next_mp:
29882 			mp = nxt_mp;
29883 		} /* while (mp != NULL) */
29884 		if (xmit_drop)
29885 			return (SEND_FAILED);
29886 		else
29887 			return (SEND_PASSED);
29888 
29889 	case ND_INITIAL:
29890 	case ND_INCOMPLETE:
29891 
29892 		/*
29893 		 * While we do send off packets to dests that
29894 		 * use fully-resolved CGTP routes, we do not
29895 		 * handle unresolved CGTP routes.
29896 		 */
29897 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29898 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29899 
29900 		if (mp != NULL) {
29901 			/* queue the packet */
29902 			nce_queue_mp_common(arpce, mp, B_FALSE);
29903 		}
29904 
29905 		if (arpce->nce_state == ND_INCOMPLETE) {
29906 			mutex_exit(&arpce->nce_lock);
29907 			DTRACE_PROBE3(ip__xmit__incomplete,
29908 			    (ire_t *), ire, (mblk_t *), mp,
29909 			    (ipsec_out_t *), io);
29910 			return (LOOKUP_IN_PROGRESS);
29911 		}
29912 
29913 		arpce->nce_state = ND_INCOMPLETE;
29914 		mutex_exit(&arpce->nce_lock);
29915 		/*
29916 		 * Note that ire_add() (called from ire_forward())
29917 		 * holds a ref on the ire until ARP is completed.
29918 		 */
29919 
29920 		ire_arpresolve(ire, ire_to_ill(ire));
29921 		return (LOOKUP_IN_PROGRESS);
29922 	default:
29923 		ASSERT(0);
29924 		mutex_exit(&arpce->nce_lock);
29925 		return (LLHDR_RESLV_FAILED);
29926 	}
29927 }
29928 
29929 #undef	UPDATE_IP_MIB_OB_COUNTERS
29930 
29931 /*
29932  * Return B_TRUE if the buffers differ in length or content.
29933  * This is used for comparing extension header buffers.
29934  * Note that an extension header would be declared different
29935  * even if all that changed was the next header value in that header i.e.
29936  * what really changed is the next extension header.
29937  */
29938 boolean_t
29939 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29940     uint_t blen)
29941 {
29942 	if (!b_valid)
29943 		blen = 0;
29944 
29945 	if (alen != blen)
29946 		return (B_TRUE);
29947 	if (alen == 0)
29948 		return (B_FALSE);	/* Both zero length */
29949 	return (bcmp(abuf, bbuf, alen));
29950 }
29951 
29952 /*
29953  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29954  * Return B_FALSE if memory allocation fails - don't change any state!
29955  */
29956 boolean_t
29957 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29958     const void *src, uint_t srclen)
29959 {
29960 	void *dst;
29961 
29962 	if (!src_valid)
29963 		srclen = 0;
29964 
29965 	ASSERT(*dstlenp == 0);
29966 	if (src != NULL && srclen != 0) {
29967 		dst = mi_alloc(srclen, BPRI_MED);
29968 		if (dst == NULL)
29969 			return (B_FALSE);
29970 	} else {
29971 		dst = NULL;
29972 	}
29973 	if (*dstp != NULL)
29974 		mi_free(*dstp);
29975 	*dstp = dst;
29976 	*dstlenp = dst == NULL ? 0 : srclen;
29977 	return (B_TRUE);
29978 }
29979 
29980 /*
29981  * Replace what is in *dst, *dstlen with the source.
29982  * Assumes ip_allocbuf has already been called.
29983  */
29984 void
29985 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29986     const void *src, uint_t srclen)
29987 {
29988 	if (!src_valid)
29989 		srclen = 0;
29990 
29991 	ASSERT(*dstlenp == srclen);
29992 	if (src != NULL && srclen != 0)
29993 		bcopy(src, *dstp, srclen);
29994 }
29995 
29996 /*
29997  * Free the storage pointed to by the members of an ip6_pkt_t.
29998  */
29999 void
30000 ip6_pkt_free(ip6_pkt_t *ipp)
30001 {
30002 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30003 
30004 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30005 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30006 		ipp->ipp_hopopts = NULL;
30007 		ipp->ipp_hopoptslen = 0;
30008 	}
30009 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30010 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30011 		ipp->ipp_rtdstopts = NULL;
30012 		ipp->ipp_rtdstoptslen = 0;
30013 	}
30014 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30015 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30016 		ipp->ipp_dstopts = NULL;
30017 		ipp->ipp_dstoptslen = 0;
30018 	}
30019 	if (ipp->ipp_fields & IPPF_RTHDR) {
30020 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30021 		ipp->ipp_rthdr = NULL;
30022 		ipp->ipp_rthdrlen = 0;
30023 	}
30024 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30025 	    IPPF_RTHDR);
30026 }
30027