xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision 0c0f26573765ff45142b50287a74dcc85c332e8d)
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.  Returns TRUE if the mblk
6946  * is not consumed.
6947  *
6948  * One of four things can happen, all of which affect the passed-in mblk:
6949  *
6950  * 1.) ICMP messages that go through here just get returned TRUE.
6951  *
6952  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6953  *
6954  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6955  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6956  *
6957  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6958  */
6959 static boolean_t
6960 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6961     ipsec_stack_t *ipss)
6962 {
6963 	int shift, plen, iph_len;
6964 	ipha_t *ipha;
6965 	udpha_t *udpha;
6966 	uint32_t *spi;
6967 	uint8_t *orptr;
6968 	boolean_t udp_pkt, free_ire;
6969 
6970 	if (DB_TYPE(mp) == M_CTL) {
6971 		/*
6972 		 * ICMP message with UDP inside.  Don't bother stripping, just
6973 		 * send it up.
6974 		 *
6975 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6976 		 * to ignore errors set by ICMP anyway ('cause they might be
6977 		 * forged), but that's the app's decision, not ours.
6978 		 */
6979 
6980 		/* Bunch of reality checks for DEBUG kernels... */
6981 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6982 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6983 
6984 		return (B_TRUE);
6985 	}
6986 
6987 	ipha = (ipha_t *)mp->b_rptr;
6988 	iph_len = IPH_HDR_LENGTH(ipha);
6989 	plen = ntohs(ipha->ipha_length);
6990 
6991 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6992 		/*
6993 		 * Most likely a keepalive for the benefit of an intervening
6994 		 * NAT.  These aren't for us, per se, so drop it.
6995 		 *
6996 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6997 		 * byte packets (keepalives are 1-byte), but we'll drop them
6998 		 * also.
6999 		 */
7000 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7001 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
7002 		return (B_FALSE);
7003 	}
7004 
7005 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
7006 		/* might as well pull it all up - it might be ESP. */
7007 		if (!pullupmsg(mp, -1)) {
7008 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
7009 			    DROPPER(ipss, ipds_esp_nomem),
7010 			    &ipss->ipsec_dropper);
7011 			return (B_FALSE);
7012 		}
7013 
7014 		ipha = (ipha_t *)mp->b_rptr;
7015 	}
7016 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
7017 	if (*spi == 0) {
7018 		/* UDP packet - remove 0-spi. */
7019 		shift = sizeof (uint32_t);
7020 	} else {
7021 		/* ESP-in-UDP packet - reduce to ESP. */
7022 		ipha->ipha_protocol = IPPROTO_ESP;
7023 		shift = sizeof (udpha_t);
7024 	}
7025 
7026 	/* Fix IP header */
7027 	ipha->ipha_length = htons(plen - shift);
7028 	ipha->ipha_hdr_checksum = 0;
7029 
7030 	orptr = mp->b_rptr;
7031 	mp->b_rptr += shift;
7032 
7033 	if (*spi == 0) {
7034 		ASSERT((uint8_t *)ipha == orptr);
7035 		udpha = (udpha_t *)(orptr + iph_len);
7036 		udpha->uha_length = htons(plen - shift - iph_len);
7037 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
7038 		udp_pkt = B_TRUE;
7039 	} else {
7040 		udp_pkt = B_FALSE;
7041 	}
7042 	ovbcopy(orptr, orptr + shift, iph_len);
7043 	if (!udp_pkt) /* Punt up for ESP processing. */ {
7044 		ipha = (ipha_t *)(orptr + shift);
7045 
7046 		free_ire = (ire == NULL);
7047 		if (free_ire) {
7048 			/* Re-acquire ire. */
7049 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7050 			    ipss->ipsec_netstack->netstack_ip);
7051 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7052 				if (ire != NULL)
7053 					ire_refrele(ire);
7054 				/*
7055 				 * Do a regular freemsg(), as this is an IP
7056 				 * error (no local route) not an IPsec one.
7057 				 */
7058 				freemsg(mp);
7059 			}
7060 		}
7061 
7062 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
7063 		if (free_ire)
7064 			ire_refrele(ire);
7065 	}
7066 
7067 	return (udp_pkt);
7068 }
7069 
7070 /*
7071  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7072  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7073  * Caller is responsible for dropping references to the conn, and freeing
7074  * first_mp.
7075  *
7076  * IPQoS Notes
7077  * Before sending it to the client, invoke IPPF processing. Policy processing
7078  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7079  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7080  * ip_wput_local, ip_policy is false.
7081  */
7082 static void
7083 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7084     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7085     boolean_t ip_policy)
7086 {
7087 	boolean_t	mctl_present = (first_mp != NULL);
7088 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7089 	uint32_t	ill_index;
7090 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7091 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7092 
7093 	ASSERT(ill != NULL);
7094 
7095 	if (mctl_present)
7096 		first_mp->b_cont = mp;
7097 	else
7098 		first_mp = mp;
7099 
7100 	if (CONN_UDP_FLOWCTLD(connp)) {
7101 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7102 		freemsg(first_mp);
7103 		return;
7104 	}
7105 
7106 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7107 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7108 		    NULL, mctl_present);
7109 		if (first_mp == NULL) {
7110 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7111 			return;	/* Freed by ipsec_check_inbound_policy(). */
7112 		}
7113 	}
7114 	if (mctl_present)
7115 		freeb(first_mp);
7116 
7117 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7118 	if (connp->conn_udp->udp_nat_t_endpoint) {
7119 		if (mctl_present) {
7120 			/* mctl_present *shouldn't* happen. */
7121 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7122 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7123 			    &ipss->ipsec_dropper);
7124 			return;
7125 		}
7126 
7127 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7128 			return;
7129 	}
7130 
7131 	/* Handle options. */
7132 	if (connp->conn_recvif)
7133 		in_flags = IPF_RECVIF;
7134 	/*
7135 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7136 	 * passed to ip_add_info is based on IP version of connp.
7137 	 */
7138 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7139 		if (connp->conn_af_isv6) {
7140 			/*
7141 			 * V6 only needs index
7142 			 */
7143 			in_flags |= IPF_RECVIF;
7144 		} else {
7145 			/*
7146 			 * V4 needs index + matching address.
7147 			 */
7148 			in_flags |= IPF_RECVADDR;
7149 		}
7150 	}
7151 
7152 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7153 		in_flags |= IPF_RECVSLLA;
7154 
7155 	/*
7156 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7157 	 * freed if the packet is dropped. The caller will do so.
7158 	 */
7159 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7160 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7161 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7162 		if (mp == NULL) {
7163 			return;
7164 		}
7165 	}
7166 	if ((in_flags != 0) &&
7167 	    (mp->b_datap->db_type != M_CTL)) {
7168 		/*
7169 		 * The actual data will be contained in b_cont
7170 		 * upon successful return of the following call
7171 		 * else original mblk is returned
7172 		 */
7173 		ASSERT(recv_ill != NULL);
7174 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7175 		    ipst);
7176 	}
7177 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7178 	/* Send it upstream */
7179 	CONN_UDP_RECV(connp, mp);
7180 }
7181 
7182 /*
7183  * Fanout for UDP packets.
7184  * The caller puts <fport, lport> in the ports parameter.
7185  *
7186  * If SO_REUSEADDR is set all multicast and broadcast packets
7187  * will be delivered to all streams bound to the same port.
7188  *
7189  * Zones notes:
7190  * Multicast and broadcast packets will be distributed to streams in all zones.
7191  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7192  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7193  * packets. To maintain this behavior with multiple zones, the conns are grouped
7194  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7195  * each zone. If unset, all the following conns in the same zone are skipped.
7196  */
7197 static void
7198 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7199     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7200     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7201 {
7202 	uint32_t	dstport, srcport;
7203 	ipaddr_t	dst;
7204 	mblk_t		*first_mp;
7205 	boolean_t	secure;
7206 	in6_addr_t	v6src;
7207 	conn_t		*connp;
7208 	connf_t		*connfp;
7209 	conn_t		*first_connp;
7210 	conn_t		*next_connp;
7211 	mblk_t		*mp1, *first_mp1;
7212 	ipaddr_t	src;
7213 	zoneid_t	last_zoneid;
7214 	boolean_t	reuseaddr;
7215 	boolean_t	shared_addr;
7216 	ip_stack_t	*ipst;
7217 
7218 	ASSERT(recv_ill != NULL);
7219 	ipst = recv_ill->ill_ipst;
7220 
7221 	first_mp = mp;
7222 	if (mctl_present) {
7223 		mp = first_mp->b_cont;
7224 		first_mp->b_cont = NULL;
7225 		secure = ipsec_in_is_secure(first_mp);
7226 		ASSERT(mp != NULL);
7227 	} else {
7228 		first_mp = NULL;
7229 		secure = B_FALSE;
7230 	}
7231 
7232 	/* Extract ports in net byte order */
7233 	dstport = htons(ntohl(ports) & 0xFFFF);
7234 	srcport = htons(ntohl(ports) >> 16);
7235 	dst = ipha->ipha_dst;
7236 	src = ipha->ipha_src;
7237 
7238 	shared_addr = (zoneid == ALL_ZONES);
7239 	if (shared_addr) {
7240 		/*
7241 		 * No need to handle exclusive-stack zones since ALL_ZONES
7242 		 * only applies to the shared stack.
7243 		 */
7244 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7245 		if (zoneid == ALL_ZONES)
7246 			zoneid = tsol_packet_to_zoneid(mp);
7247 	}
7248 
7249 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7250 	mutex_enter(&connfp->connf_lock);
7251 	connp = connfp->connf_head;
7252 	if (!broadcast && !CLASSD(dst)) {
7253 		/*
7254 		 * Not broadcast or multicast. Send to the one (first)
7255 		 * client we find. No need to check conn_wantpacket()
7256 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7257 		 * IPv4 unicast packets.
7258 		 */
7259 		while ((connp != NULL) &&
7260 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7261 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7262 			connp = connp->conn_next;
7263 		}
7264 
7265 		if (connp == NULL || connp->conn_upq == NULL)
7266 			goto notfound;
7267 
7268 		if (is_system_labeled() &&
7269 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7270 		    connp))
7271 			goto notfound;
7272 
7273 		CONN_INC_REF(connp);
7274 		mutex_exit(&connfp->connf_lock);
7275 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7276 		    flags, recv_ill, ip_policy);
7277 		IP_STAT(ipst, ip_udp_fannorm);
7278 		CONN_DEC_REF(connp);
7279 		return;
7280 	}
7281 
7282 	/*
7283 	 * Broadcast and multicast case
7284 	 *
7285 	 * Need to check conn_wantpacket().
7286 	 * If SO_REUSEADDR has been set on the first we send the
7287 	 * packet to all clients that have joined the group and
7288 	 * match the port.
7289 	 */
7290 
7291 	while (connp != NULL) {
7292 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7293 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7294 		    (!is_system_labeled() ||
7295 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7296 		    connp)))
7297 			break;
7298 		connp = connp->conn_next;
7299 	}
7300 
7301 	if (connp == NULL || connp->conn_upq == NULL)
7302 		goto notfound;
7303 
7304 	first_connp = connp;
7305 	/*
7306 	 * When SO_REUSEADDR is not set, send the packet only to the first
7307 	 * matching connection in its zone by keeping track of the zoneid.
7308 	 */
7309 	reuseaddr = first_connp->conn_reuseaddr;
7310 	last_zoneid = first_connp->conn_zoneid;
7311 
7312 	CONN_INC_REF(connp);
7313 	connp = connp->conn_next;
7314 	for (;;) {
7315 		while (connp != NULL) {
7316 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7317 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7318 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7319 			    (!is_system_labeled() ||
7320 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7321 			    shared_addr, connp)))
7322 				break;
7323 			connp = connp->conn_next;
7324 		}
7325 		/*
7326 		 * Just copy the data part alone. The mctl part is
7327 		 * needed just for verifying policy and it is never
7328 		 * sent up.
7329 		 */
7330 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7331 		    ((mp1 = copymsg(mp)) == NULL))) {
7332 			/*
7333 			 * No more interested clients or memory
7334 			 * allocation failed
7335 			 */
7336 			connp = first_connp;
7337 			break;
7338 		}
7339 		if (connp->conn_zoneid != last_zoneid) {
7340 			/*
7341 			 * Update the zoneid so that the packet isn't sent to
7342 			 * any more conns in the same zone unless SO_REUSEADDR
7343 			 * is set.
7344 			 */
7345 			reuseaddr = connp->conn_reuseaddr;
7346 			last_zoneid = connp->conn_zoneid;
7347 		}
7348 		if (first_mp != NULL) {
7349 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7350 			    ipsec_info_type == IPSEC_IN);
7351 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7352 			    ipst->ips_netstack);
7353 			if (first_mp1 == NULL) {
7354 				freemsg(mp1);
7355 				connp = first_connp;
7356 				break;
7357 			}
7358 		} else {
7359 			first_mp1 = NULL;
7360 		}
7361 		CONN_INC_REF(connp);
7362 		mutex_exit(&connfp->connf_lock);
7363 		/*
7364 		 * IPQoS notes: We don't send the packet for policy
7365 		 * processing here, will do it for the last one (below).
7366 		 * i.e. we do it per-packet now, but if we do policy
7367 		 * processing per-conn, then we would need to do it
7368 		 * here too.
7369 		 */
7370 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7371 		    ipha, flags, recv_ill, B_FALSE);
7372 		mutex_enter(&connfp->connf_lock);
7373 		/* Follow the next pointer before releasing the conn. */
7374 		next_connp = connp->conn_next;
7375 		IP_STAT(ipst, ip_udp_fanmb);
7376 		CONN_DEC_REF(connp);
7377 		connp = next_connp;
7378 	}
7379 
7380 	/* Last one.  Send it upstream. */
7381 	mutex_exit(&connfp->connf_lock);
7382 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7383 	    recv_ill, ip_policy);
7384 	IP_STAT(ipst, ip_udp_fanmb);
7385 	CONN_DEC_REF(connp);
7386 	return;
7387 
7388 notfound:
7389 
7390 	mutex_exit(&connfp->connf_lock);
7391 	IP_STAT(ipst, ip_udp_fanothers);
7392 	/*
7393 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7394 	 * have already been matched above, since they live in the IPv4
7395 	 * fanout tables. This implies we only need to
7396 	 * check for IPv6 in6addr_any endpoints here.
7397 	 * Thus we compare using ipv6_all_zeros instead of the destination
7398 	 * address, except for the multicast group membership lookup which
7399 	 * uses the IPv4 destination.
7400 	 */
7401 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7402 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7403 	mutex_enter(&connfp->connf_lock);
7404 	connp = connfp->connf_head;
7405 	if (!broadcast && !CLASSD(dst)) {
7406 		while (connp != NULL) {
7407 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7408 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7409 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7410 			    !connp->conn_ipv6_v6only)
7411 				break;
7412 			connp = connp->conn_next;
7413 		}
7414 
7415 		if (connp != NULL && is_system_labeled() &&
7416 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7417 		    connp))
7418 			connp = NULL;
7419 
7420 		if (connp == NULL || connp->conn_upq == NULL) {
7421 			/*
7422 			 * No one bound to this port.  Is
7423 			 * there a client that wants all
7424 			 * unclaimed datagrams?
7425 			 */
7426 			mutex_exit(&connfp->connf_lock);
7427 
7428 			if (mctl_present)
7429 				first_mp->b_cont = mp;
7430 			else
7431 				first_mp = mp;
7432 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7433 			    connf_head != NULL) {
7434 				ip_fanout_proto(q, first_mp, ill, ipha,
7435 				    flags | IP_FF_RAWIP, mctl_present,
7436 				    ip_policy, recv_ill, zoneid);
7437 			} else {
7438 				if (ip_fanout_send_icmp(q, first_mp, flags,
7439 				    ICMP_DEST_UNREACHABLE,
7440 				    ICMP_PORT_UNREACHABLE,
7441 				    mctl_present, zoneid, ipst)) {
7442 					BUMP_MIB(ill->ill_ip_mib,
7443 					    udpIfStatsNoPorts);
7444 				}
7445 			}
7446 			return;
7447 		}
7448 
7449 		CONN_INC_REF(connp);
7450 		mutex_exit(&connfp->connf_lock);
7451 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7452 		    flags, recv_ill, ip_policy);
7453 		CONN_DEC_REF(connp);
7454 		return;
7455 	}
7456 	/*
7457 	 * IPv4 multicast packet being delivered to an AF_INET6
7458 	 * in6addr_any endpoint.
7459 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7460 	 * and not conn_wantpacket_v6() since any multicast membership is
7461 	 * for an IPv4-mapped multicast address.
7462 	 * The packet is sent to all clients in all zones that have joined the
7463 	 * group and match the port.
7464 	 */
7465 	while (connp != NULL) {
7466 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7467 		    srcport, v6src) &&
7468 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7469 		    (!is_system_labeled() ||
7470 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7471 		    connp)))
7472 			break;
7473 		connp = connp->conn_next;
7474 	}
7475 
7476 	if (connp == NULL || connp->conn_upq == NULL) {
7477 		/*
7478 		 * No one bound to this port.  Is
7479 		 * there a client that wants all
7480 		 * unclaimed datagrams?
7481 		 */
7482 		mutex_exit(&connfp->connf_lock);
7483 
7484 		if (mctl_present)
7485 			first_mp->b_cont = mp;
7486 		else
7487 			first_mp = mp;
7488 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7489 		    NULL) {
7490 			ip_fanout_proto(q, first_mp, ill, ipha,
7491 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7492 			    recv_ill, zoneid);
7493 		} else {
7494 			/*
7495 			 * We used to attempt to send an icmp error here, but
7496 			 * since this is known to be a multicast packet
7497 			 * and we don't send icmp errors in response to
7498 			 * multicast, just drop the packet and give up sooner.
7499 			 */
7500 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7501 			freemsg(first_mp);
7502 		}
7503 		return;
7504 	}
7505 
7506 	first_connp = connp;
7507 
7508 	CONN_INC_REF(connp);
7509 	connp = connp->conn_next;
7510 	for (;;) {
7511 		while (connp != NULL) {
7512 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7513 			    ipv6_all_zeros, srcport, v6src) &&
7514 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7515 			    (!is_system_labeled() ||
7516 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7517 			    shared_addr, connp)))
7518 				break;
7519 			connp = connp->conn_next;
7520 		}
7521 		/*
7522 		 * Just copy the data part alone. The mctl part is
7523 		 * needed just for verifying policy and it is never
7524 		 * sent up.
7525 		 */
7526 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7527 		    ((mp1 = copymsg(mp)) == NULL))) {
7528 			/*
7529 			 * No more intested clients or memory
7530 			 * allocation failed
7531 			 */
7532 			connp = first_connp;
7533 			break;
7534 		}
7535 		if (first_mp != NULL) {
7536 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7537 			    ipsec_info_type == IPSEC_IN);
7538 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7539 			    ipst->ips_netstack);
7540 			if (first_mp1 == NULL) {
7541 				freemsg(mp1);
7542 				connp = first_connp;
7543 				break;
7544 			}
7545 		} else {
7546 			first_mp1 = NULL;
7547 		}
7548 		CONN_INC_REF(connp);
7549 		mutex_exit(&connfp->connf_lock);
7550 		/*
7551 		 * IPQoS notes: We don't send the packet for policy
7552 		 * processing here, will do it for the last one (below).
7553 		 * i.e. we do it per-packet now, but if we do policy
7554 		 * processing per-conn, then we would need to do it
7555 		 * here too.
7556 		 */
7557 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7558 		    ipha, flags, recv_ill, B_FALSE);
7559 		mutex_enter(&connfp->connf_lock);
7560 		/* Follow the next pointer before releasing the conn. */
7561 		next_connp = connp->conn_next;
7562 		CONN_DEC_REF(connp);
7563 		connp = next_connp;
7564 	}
7565 
7566 	/* Last one.  Send it upstream. */
7567 	mutex_exit(&connfp->connf_lock);
7568 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7569 	    recv_ill, ip_policy);
7570 	CONN_DEC_REF(connp);
7571 }
7572 
7573 /*
7574  * Complete the ip_wput header so that it
7575  * is possible to generate ICMP
7576  * errors.
7577  */
7578 int
7579 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7580 {
7581 	ire_t *ire;
7582 
7583 	if (ipha->ipha_src == INADDR_ANY) {
7584 		ire = ire_lookup_local(zoneid, ipst);
7585 		if (ire == NULL) {
7586 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7587 			return (1);
7588 		}
7589 		ipha->ipha_src = ire->ire_addr;
7590 		ire_refrele(ire);
7591 	}
7592 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7593 	ipha->ipha_hdr_checksum = 0;
7594 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7595 	return (0);
7596 }
7597 
7598 /*
7599  * Nobody should be sending
7600  * packets up this stream
7601  */
7602 static void
7603 ip_lrput(queue_t *q, mblk_t *mp)
7604 {
7605 	mblk_t *mp1;
7606 
7607 	switch (mp->b_datap->db_type) {
7608 	case M_FLUSH:
7609 		/* Turn around */
7610 		if (*mp->b_rptr & FLUSHW) {
7611 			*mp->b_rptr &= ~FLUSHR;
7612 			qreply(q, mp);
7613 			return;
7614 		}
7615 		break;
7616 	}
7617 	/* Could receive messages that passed through ar_rput */
7618 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7619 		mp1->b_prev = mp1->b_next = NULL;
7620 	freemsg(mp);
7621 }
7622 
7623 /* Nobody should be sending packets down this stream */
7624 /* ARGSUSED */
7625 void
7626 ip_lwput(queue_t *q, mblk_t *mp)
7627 {
7628 	freemsg(mp);
7629 }
7630 
7631 /*
7632  * Move the first hop in any source route to ipha_dst and remove that part of
7633  * the source route.  Called by other protocols.  Errors in option formatting
7634  * are ignored - will be handled by ip_wput_options Return the final
7635  * destination (either ipha_dst or the last entry in a source route.)
7636  */
7637 ipaddr_t
7638 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7639 {
7640 	ipoptp_t	opts;
7641 	uchar_t		*opt;
7642 	uint8_t		optval;
7643 	uint8_t		optlen;
7644 	ipaddr_t	dst;
7645 	int		i;
7646 	ire_t		*ire;
7647 	ip_stack_t	*ipst = ns->netstack_ip;
7648 
7649 	ip2dbg(("ip_massage_options\n"));
7650 	dst = ipha->ipha_dst;
7651 	for (optval = ipoptp_first(&opts, ipha);
7652 	    optval != IPOPT_EOL;
7653 	    optval = ipoptp_next(&opts)) {
7654 		opt = opts.ipoptp_cur;
7655 		switch (optval) {
7656 			uint8_t off;
7657 		case IPOPT_SSRR:
7658 		case IPOPT_LSRR:
7659 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7660 				ip1dbg(("ip_massage_options: bad src route\n"));
7661 				break;
7662 			}
7663 			optlen = opts.ipoptp_len;
7664 			off = opt[IPOPT_OFFSET];
7665 			off--;
7666 		redo_srr:
7667 			if (optlen < IP_ADDR_LEN ||
7668 			    off > optlen - IP_ADDR_LEN) {
7669 				/* End of source route */
7670 				ip1dbg(("ip_massage_options: end of SR\n"));
7671 				break;
7672 			}
7673 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7674 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7675 			    ntohl(dst)));
7676 			/*
7677 			 * Check if our address is present more than
7678 			 * once as consecutive hops in source route.
7679 			 * XXX verify per-interface ip_forwarding
7680 			 * for source route?
7681 			 */
7682 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7683 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7684 			if (ire != NULL) {
7685 				ire_refrele(ire);
7686 				off += IP_ADDR_LEN;
7687 				goto redo_srr;
7688 			}
7689 			if (dst == htonl(INADDR_LOOPBACK)) {
7690 				ip1dbg(("ip_massage_options: loopback addr in "
7691 				    "source route!\n"));
7692 				break;
7693 			}
7694 			/*
7695 			 * Update ipha_dst to be the first hop and remove the
7696 			 * first hop from the source route (by overwriting
7697 			 * part of the option with NOP options).
7698 			 */
7699 			ipha->ipha_dst = dst;
7700 			/* Put the last entry in dst */
7701 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7702 			    3;
7703 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7704 
7705 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7706 			    ntohl(dst)));
7707 			/* Move down and overwrite */
7708 			opt[IP_ADDR_LEN] = opt[0];
7709 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7710 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7711 			for (i = 0; i < IP_ADDR_LEN; i++)
7712 				opt[i] = IPOPT_NOP;
7713 			break;
7714 		}
7715 	}
7716 	return (dst);
7717 }
7718 
7719 /*
7720  * Return the network mask
7721  * associated with the specified address.
7722  */
7723 ipaddr_t
7724 ip_net_mask(ipaddr_t addr)
7725 {
7726 	uchar_t	*up = (uchar_t *)&addr;
7727 	ipaddr_t mask = 0;
7728 	uchar_t	*maskp = (uchar_t *)&mask;
7729 
7730 #if defined(__i386) || defined(__amd64)
7731 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7732 #endif
7733 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7734 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7735 #endif
7736 	if (CLASSD(addr)) {
7737 		maskp[0] = 0xF0;
7738 		return (mask);
7739 	}
7740 	if (addr == 0)
7741 		return (0);
7742 	maskp[0] = 0xFF;
7743 	if ((up[0] & 0x80) == 0)
7744 		return (mask);
7745 
7746 	maskp[1] = 0xFF;
7747 	if ((up[0] & 0xC0) == 0x80)
7748 		return (mask);
7749 
7750 	maskp[2] = 0xFF;
7751 	if ((up[0] & 0xE0) == 0xC0)
7752 		return (mask);
7753 
7754 	/* Must be experimental or multicast, indicate as much */
7755 	return ((ipaddr_t)0);
7756 }
7757 
7758 /*
7759  * Select an ill for the packet by considering load spreading across
7760  * a different ill in the group if dst_ill is part of some group.
7761  */
7762 ill_t *
7763 ip_newroute_get_dst_ill(ill_t *dst_ill)
7764 {
7765 	ill_t *ill;
7766 
7767 	/*
7768 	 * We schedule irrespective of whether the source address is
7769 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7770 	 */
7771 	ill = illgrp_scheduler(dst_ill);
7772 	if (ill == NULL)
7773 		return (NULL);
7774 
7775 	/*
7776 	 * For groups with names ip_sioctl_groupname ensures that all
7777 	 * ills are of same type. For groups without names, ifgrp_insert
7778 	 * ensures this.
7779 	 */
7780 	ASSERT(dst_ill->ill_type == ill->ill_type);
7781 
7782 	return (ill);
7783 }
7784 
7785 /*
7786  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7787  */
7788 ill_t *
7789 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7790     ip_stack_t *ipst)
7791 {
7792 	ill_t *ret_ill;
7793 
7794 	ASSERT(ifindex != 0);
7795 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7796 	    ipst);
7797 	if (ret_ill == NULL ||
7798 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7799 		if (isv6) {
7800 			if (ill != NULL) {
7801 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7802 			} else {
7803 				BUMP_MIB(&ipst->ips_ip6_mib,
7804 				    ipIfStatsOutDiscards);
7805 			}
7806 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7807 			    "bad ifindex %d.\n", ifindex));
7808 		} else {
7809 			if (ill != NULL) {
7810 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7811 			} else {
7812 				BUMP_MIB(&ipst->ips_ip_mib,
7813 				    ipIfStatsOutDiscards);
7814 			}
7815 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7816 			    "bad ifindex %d.\n", ifindex));
7817 		}
7818 		if (ret_ill != NULL)
7819 			ill_refrele(ret_ill);
7820 		freemsg(first_mp);
7821 		return (NULL);
7822 	}
7823 
7824 	return (ret_ill);
7825 }
7826 
7827 /*
7828  * IPv4 -
7829  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7830  * out a packet to a destination address for which we do not have specific
7831  * (or sufficient) routing information.
7832  *
7833  * NOTE : These are the scopes of some of the variables that point at IRE,
7834  *	  which needs to be followed while making any future modifications
7835  *	  to avoid memory leaks.
7836  *
7837  *	- ire and sire are the entries looked up initially by
7838  *	  ire_ftable_lookup.
7839  *	- ipif_ire is used to hold the interface ire associated with
7840  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7841  *	  it before branching out to error paths.
7842  *	- save_ire is initialized before ire_create, so that ire returned
7843  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7844  *	  before breaking out of the switch.
7845  *
7846  *	Thus on failures, we have to REFRELE only ire and sire, if they
7847  *	are not NULL.
7848  */
7849 void
7850 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7851     zoneid_t zoneid, ip_stack_t *ipst)
7852 {
7853 	areq_t	*areq;
7854 	ipaddr_t gw = 0;
7855 	ire_t	*ire = NULL;
7856 	mblk_t	*res_mp;
7857 	ipaddr_t *addrp;
7858 	ipaddr_t nexthop_addr;
7859 	ipif_t  *src_ipif = NULL;
7860 	ill_t	*dst_ill = NULL;
7861 	ipha_t  *ipha;
7862 	ire_t	*sire = NULL;
7863 	mblk_t	*first_mp;
7864 	ire_t	*save_ire;
7865 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7866 	ushort_t ire_marks = 0;
7867 	boolean_t mctl_present;
7868 	ipsec_out_t *io;
7869 	mblk_t	*saved_mp;
7870 	ire_t	*first_sire = NULL;
7871 	mblk_t	*copy_mp = NULL;
7872 	mblk_t	*xmit_mp = NULL;
7873 	ipaddr_t save_dst;
7874 	uint32_t multirt_flags =
7875 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7876 	boolean_t multirt_is_resolvable;
7877 	boolean_t multirt_resolve_next;
7878 	boolean_t do_attach_ill = B_FALSE;
7879 	boolean_t ip_nexthop = B_FALSE;
7880 	tsol_ire_gw_secattr_t *attrp = NULL;
7881 	tsol_gcgrp_t *gcgrp = NULL;
7882 	tsol_gcgrp_addr_t ga;
7883 
7884 	if (ip_debug > 2) {
7885 		/* ip1dbg */
7886 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7887 	}
7888 
7889 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7890 	if (mctl_present) {
7891 		io = (ipsec_out_t *)first_mp->b_rptr;
7892 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7893 		ASSERT(zoneid == io->ipsec_out_zoneid);
7894 		ASSERT(zoneid != ALL_ZONES);
7895 	}
7896 
7897 	ipha = (ipha_t *)mp->b_rptr;
7898 
7899 	/* All multicast lookups come through ip_newroute_ipif() */
7900 	if (CLASSD(dst)) {
7901 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7902 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7903 		freemsg(first_mp);
7904 		return;
7905 	}
7906 
7907 	if (mctl_present && io->ipsec_out_attach_if) {
7908 		/* ip_grab_attach_ill returns a held ill */
7909 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7910 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7911 
7912 		/* Failure case frees things for us. */
7913 		if (attach_ill == NULL)
7914 			return;
7915 
7916 		/*
7917 		 * Check if we need an ire that will not be
7918 		 * looked up by anybody else i.e. HIDDEN.
7919 		 */
7920 		if (ill_is_probeonly(attach_ill))
7921 			ire_marks = IRE_MARK_HIDDEN;
7922 	}
7923 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7924 		ip_nexthop = B_TRUE;
7925 		nexthop_addr = io->ipsec_out_nexthop_addr;
7926 	}
7927 	/*
7928 	 * If this IRE is created for forwarding or it is not for
7929 	 * traffic for congestion controlled protocols, mark it as temporary.
7930 	 */
7931 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7932 		ire_marks |= IRE_MARK_TEMPORARY;
7933 
7934 	/*
7935 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7936 	 * chain until it gets the most specific information available.
7937 	 * For example, we know that there is no IRE_CACHE for this dest,
7938 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7939 	 * ire_ftable_lookup will look up the gateway, etc.
7940 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7941 	 * to the destination, of equal netmask length in the forward table,
7942 	 * will be recursively explored. If no information is available
7943 	 * for the final gateway of that route, we force the returned ire
7944 	 * to be equal to sire using MATCH_IRE_PARENT.
7945 	 * At least, in this case we have a starting point (in the buckets)
7946 	 * to look for other routes to the destination in the forward table.
7947 	 * This is actually used only for multirouting, where a list
7948 	 * of routes has to be processed in sequence.
7949 	 *
7950 	 * In the process of coming up with the most specific information,
7951 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7952 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7953 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7954 	 * Two caveats when handling incomplete ire's in ip_newroute:
7955 	 * - we should be careful when accessing its ire_nce (specifically
7956 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7957 	 * - not all legacy code path callers are prepared to handle
7958 	 *   incomplete ire's, so we should not create/add incomplete
7959 	 *   ire_cache entries here. (See discussion about temporary solution
7960 	 *   further below).
7961 	 *
7962 	 * In order to minimize packet dropping, and to preserve existing
7963 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7964 	 * gateway, and instead use the IF_RESOLVER ire to send out
7965 	 * another request to ARP (this is achieved by passing the
7966 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7967 	 * arp response comes back in ip_wput_nondata, we will create
7968 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7969 	 *
7970 	 * Note that this is a temporary solution; the correct solution is
7971 	 * to create an incomplete  per-dst ire_cache entry, and send the
7972 	 * packet out when the gw's nce is resolved. In order to achieve this,
7973 	 * all packet processing must have been completed prior to calling
7974 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7975 	 * to be modified to accomodate this solution.
7976 	 */
7977 	if (ip_nexthop) {
7978 		/*
7979 		 * The first time we come here, we look for an IRE_INTERFACE
7980 		 * entry for the specified nexthop, set the dst to be the
7981 		 * nexthop address and create an IRE_CACHE entry for the
7982 		 * nexthop. The next time around, we are able to find an
7983 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7984 		 * nexthop address and create an IRE_CACHE entry for the
7985 		 * destination address via the specified nexthop.
7986 		 */
7987 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7988 		    MBLK_GETLABEL(mp), ipst);
7989 		if (ire != NULL) {
7990 			gw = nexthop_addr;
7991 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7992 		} else {
7993 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7994 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7995 			    MBLK_GETLABEL(mp),
7996 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7997 			    ipst);
7998 			if (ire != NULL) {
7999 				dst = nexthop_addr;
8000 			}
8001 		}
8002 	} else if (attach_ill == NULL) {
8003 		ire = ire_ftable_lookup(dst, 0, 0, 0,
8004 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
8005 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
8006 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
8007 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
8008 		    ipst);
8009 	} else {
8010 		/*
8011 		 * attach_ill is set only for communicating with
8012 		 * on-link hosts. So, don't look for DEFAULT.
8013 		 */
8014 		ipif_t	*attach_ipif;
8015 
8016 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
8017 		if (attach_ipif == NULL) {
8018 			ill_refrele(attach_ill);
8019 			goto icmp_err_ret;
8020 		}
8021 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
8022 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
8023 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
8024 		    MATCH_IRE_SECATTR, ipst);
8025 		ipif_refrele(attach_ipif);
8026 	}
8027 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
8028 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
8029 
8030 	/*
8031 	 * This loop is run only once in most cases.
8032 	 * We loop to resolve further routes only when the destination
8033 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8034 	 */
8035 	do {
8036 		/* Clear the previous iteration's values */
8037 		if (src_ipif != NULL) {
8038 			ipif_refrele(src_ipif);
8039 			src_ipif = NULL;
8040 		}
8041 		if (dst_ill != NULL) {
8042 			ill_refrele(dst_ill);
8043 			dst_ill = NULL;
8044 		}
8045 
8046 		multirt_resolve_next = B_FALSE;
8047 		/*
8048 		 * We check if packets have to be multirouted.
8049 		 * In this case, given the current <ire, sire> couple,
8050 		 * we look for the next suitable <ire, sire>.
8051 		 * This check is done in ire_multirt_lookup(),
8052 		 * which applies various criteria to find the next route
8053 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8054 		 * unchanged if it detects it has not been tried yet.
8055 		 */
8056 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8057 			ip3dbg(("ip_newroute: starting next_resolution "
8058 			    "with first_mp %p, tag %d\n",
8059 			    (void *)first_mp,
8060 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8061 
8062 			ASSERT(sire != NULL);
8063 			multirt_is_resolvable =
8064 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8065 			    MBLK_GETLABEL(mp), ipst);
8066 
8067 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8068 			    "ire %p, sire %p\n",
8069 			    multirt_is_resolvable,
8070 			    (void *)ire, (void *)sire));
8071 
8072 			if (!multirt_is_resolvable) {
8073 				/*
8074 				 * No more multirt route to resolve; give up
8075 				 * (all routes resolved or no more
8076 				 * resolvable routes).
8077 				 */
8078 				if (ire != NULL) {
8079 					ire_refrele(ire);
8080 					ire = NULL;
8081 				}
8082 			} else {
8083 				ASSERT(sire != NULL);
8084 				ASSERT(ire != NULL);
8085 				/*
8086 				 * We simply use first_sire as a flag that
8087 				 * indicates if a resolvable multirt route
8088 				 * has already been found.
8089 				 * If it is not the case, we may have to send
8090 				 * an ICMP error to report that the
8091 				 * destination is unreachable.
8092 				 * We do not IRE_REFHOLD first_sire.
8093 				 */
8094 				if (first_sire == NULL) {
8095 					first_sire = sire;
8096 				}
8097 			}
8098 		}
8099 		if (ire == NULL) {
8100 			if (ip_debug > 3) {
8101 				/* ip2dbg */
8102 				pr_addr_dbg("ip_newroute: "
8103 				    "can't resolve %s\n", AF_INET, &dst);
8104 			}
8105 			ip3dbg(("ip_newroute: "
8106 			    "ire %p, sire %p, first_sire %p\n",
8107 			    (void *)ire, (void *)sire, (void *)first_sire));
8108 
8109 			if (sire != NULL) {
8110 				ire_refrele(sire);
8111 				sire = NULL;
8112 			}
8113 
8114 			if (first_sire != NULL) {
8115 				/*
8116 				 * At least one multirt route has been found
8117 				 * in the same call to ip_newroute();
8118 				 * there is no need to report an ICMP error.
8119 				 * first_sire was not IRE_REFHOLDed.
8120 				 */
8121 				MULTIRT_DEBUG_UNTAG(first_mp);
8122 				freemsg(first_mp);
8123 				return;
8124 			}
8125 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8126 			    RTA_DST, ipst);
8127 			if (attach_ill != NULL)
8128 				ill_refrele(attach_ill);
8129 			goto icmp_err_ret;
8130 		}
8131 
8132 		/*
8133 		 * Verify that the returned IRE does not have either
8134 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8135 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8136 		 */
8137 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8138 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8139 			if (attach_ill != NULL)
8140 				ill_refrele(attach_ill);
8141 			goto icmp_err_ret;
8142 		}
8143 		/*
8144 		 * Increment the ire_ob_pkt_count field for ire if it is an
8145 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8146 		 * increment the same for the parent IRE, sire, if it is some
8147 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8148 		 */
8149 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8150 			UPDATE_OB_PKT_COUNT(ire);
8151 			ire->ire_last_used_time = lbolt;
8152 		}
8153 
8154 		if (sire != NULL) {
8155 			gw = sire->ire_gateway_addr;
8156 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8157 			    IRE_INTERFACE)) == 0);
8158 			UPDATE_OB_PKT_COUNT(sire);
8159 			sire->ire_last_used_time = lbolt;
8160 		}
8161 		/*
8162 		 * We have a route to reach the destination.
8163 		 *
8164 		 * 1) If the interface is part of ill group, try to get a new
8165 		 *    ill taking load spreading into account.
8166 		 *
8167 		 * 2) After selecting the ill, get a source address that
8168 		 *    might create good inbound load spreading.
8169 		 *    ipif_select_source does this for us.
8170 		 *
8171 		 * If the application specified the ill (ifindex), we still
8172 		 * load spread. Only if the packets needs to go out
8173 		 * specifically on a given ill e.g. binding to
8174 		 * IPIF_NOFAILOVER address, then we don't try to use a
8175 		 * different ill for load spreading.
8176 		 */
8177 		if (attach_ill == NULL) {
8178 			/*
8179 			 * Don't perform outbound load spreading in the
8180 			 * case of an RTF_MULTIRT route, as we actually
8181 			 * typically want to replicate outgoing packets
8182 			 * through particular interfaces.
8183 			 */
8184 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8185 				dst_ill = ire->ire_ipif->ipif_ill;
8186 				/* for uniformity */
8187 				ill_refhold(dst_ill);
8188 			} else {
8189 				/*
8190 				 * If we are here trying to create an IRE_CACHE
8191 				 * for an offlink destination and have the
8192 				 * IRE_CACHE for the next hop and the latter is
8193 				 * using virtual IP source address selection i.e
8194 				 * it's ire->ire_ipif is pointing to a virtual
8195 				 * network interface (vni) then
8196 				 * ip_newroute_get_dst_ll() will return the vni
8197 				 * interface as the dst_ill. Since the vni is
8198 				 * virtual i.e not associated with any physical
8199 				 * interface, it cannot be the dst_ill, hence
8200 				 * in such a case call ip_newroute_get_dst_ll()
8201 				 * with the stq_ill instead of the ire_ipif ILL.
8202 				 * The function returns a refheld ill.
8203 				 */
8204 				if ((ire->ire_type == IRE_CACHE) &&
8205 				    IS_VNI(ire->ire_ipif->ipif_ill))
8206 					dst_ill = ip_newroute_get_dst_ill(
8207 					    ire->ire_stq->q_ptr);
8208 				else
8209 					dst_ill = ip_newroute_get_dst_ill(
8210 					    ire->ire_ipif->ipif_ill);
8211 			}
8212 			if (dst_ill == NULL) {
8213 				if (ip_debug > 2) {
8214 					pr_addr_dbg("ip_newroute: "
8215 					    "no dst ill for dst"
8216 					    " %s\n", AF_INET, &dst);
8217 				}
8218 				goto icmp_err_ret;
8219 			}
8220 		} else {
8221 			dst_ill = ire->ire_ipif->ipif_ill;
8222 			/* for uniformity */
8223 			ill_refhold(dst_ill);
8224 			/*
8225 			 * We should have found a route matching ill as we
8226 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8227 			 * Rather than asserting, when there is a mismatch,
8228 			 * we just drop the packet.
8229 			 */
8230 			if (dst_ill != attach_ill) {
8231 				ip0dbg(("ip_newroute: Packet dropped as "
8232 				    "IPIF_NOFAILOVER ill is %s, "
8233 				    "ire->ire_ipif->ipif_ill is %s\n",
8234 				    attach_ill->ill_name,
8235 				    dst_ill->ill_name));
8236 				ill_refrele(attach_ill);
8237 				goto icmp_err_ret;
8238 			}
8239 		}
8240 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8241 		if (attach_ill != NULL) {
8242 			ill_refrele(attach_ill);
8243 			attach_ill = NULL;
8244 			do_attach_ill = B_TRUE;
8245 		}
8246 		ASSERT(dst_ill != NULL);
8247 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8248 
8249 		/*
8250 		 * Pick the best source address from dst_ill.
8251 		 *
8252 		 * 1) If it is part of a multipathing group, we would
8253 		 *    like to spread the inbound packets across different
8254 		 *    interfaces. ipif_select_source picks a random source
8255 		 *    across the different ills in the group.
8256 		 *
8257 		 * 2) If it is not part of a multipathing group, we try
8258 		 *    to pick the source address from the destination
8259 		 *    route. Clustering assumes that when we have multiple
8260 		 *    prefixes hosted on an interface, the prefix of the
8261 		 *    source address matches the prefix of the destination
8262 		 *    route. We do this only if the address is not
8263 		 *    DEPRECATED.
8264 		 *
8265 		 * 3) If the conn is in a different zone than the ire, we
8266 		 *    need to pick a source address from the right zone.
8267 		 *
8268 		 * NOTE : If we hit case (1) above, the prefix of the source
8269 		 *	  address picked may not match the prefix of the
8270 		 *	  destination routes prefix as ipif_select_source
8271 		 *	  does not look at "dst" while picking a source
8272 		 *	  address.
8273 		 *	  If we want the same behavior as (2), we will need
8274 		 *	  to change the behavior of ipif_select_source.
8275 		 */
8276 		ASSERT(src_ipif == NULL);
8277 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8278 			/*
8279 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8280 			 * Check that the ipif matching the requested source
8281 			 * address still exists.
8282 			 */
8283 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8284 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8285 		}
8286 		if (src_ipif == NULL) {
8287 			ire_marks |= IRE_MARK_USESRC_CHECK;
8288 			if ((dst_ill->ill_group != NULL) ||
8289 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8290 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8291 			    ire->ire_zoneid != ALL_ZONES) ||
8292 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8293 				/*
8294 				 * If the destination is reachable via a
8295 				 * given gateway, the selected source address
8296 				 * should be in the same subnet as the gateway.
8297 				 * Otherwise, the destination is not reachable.
8298 				 *
8299 				 * If there are no interfaces on the same subnet
8300 				 * as the destination, ipif_select_source gives
8301 				 * first non-deprecated interface which might be
8302 				 * on a different subnet than the gateway.
8303 				 * This is not desirable. Hence pass the dst_ire
8304 				 * source address to ipif_select_source.
8305 				 * It is sure that the destination is reachable
8306 				 * with the dst_ire source address subnet.
8307 				 * So passing dst_ire source address to
8308 				 * ipif_select_source will make sure that the
8309 				 * selected source will be on the same subnet
8310 				 * as dst_ire source address.
8311 				 */
8312 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8313 				src_ipif = ipif_select_source(dst_ill, saddr,
8314 				    zoneid);
8315 				if (src_ipif == NULL) {
8316 					if (ip_debug > 2) {
8317 						pr_addr_dbg("ip_newroute: "
8318 						    "no src for dst %s ",
8319 						    AF_INET, &dst);
8320 						printf("through interface %s\n",
8321 						    dst_ill->ill_name);
8322 					}
8323 					goto icmp_err_ret;
8324 				}
8325 			} else {
8326 				src_ipif = ire->ire_ipif;
8327 				ASSERT(src_ipif != NULL);
8328 				/* hold src_ipif for uniformity */
8329 				ipif_refhold(src_ipif);
8330 			}
8331 		}
8332 
8333 		/*
8334 		 * Assign a source address while we have the conn.
8335 		 * We can't have ip_wput_ire pick a source address when the
8336 		 * packet returns from arp since we need to look at
8337 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8338 		 * going through arp.
8339 		 *
8340 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8341 		 *	  it uses ip6i to store this information.
8342 		 */
8343 		if (ipha->ipha_src == INADDR_ANY &&
8344 		    (connp == NULL || !connp->conn_unspec_src)) {
8345 			ipha->ipha_src = src_ipif->ipif_src_addr;
8346 		}
8347 		if (ip_debug > 3) {
8348 			/* ip2dbg */
8349 			pr_addr_dbg("ip_newroute: first hop %s\n",
8350 			    AF_INET, &gw);
8351 		}
8352 		ip2dbg(("\tire type %s (%d)\n",
8353 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8354 
8355 		/*
8356 		 * The TTL of multirouted packets is bounded by the
8357 		 * ip_multirt_ttl ndd variable.
8358 		 */
8359 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8360 			/* Force TTL of multirouted packets */
8361 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8362 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8363 				ip2dbg(("ip_newroute: forcing multirt TTL "
8364 				    "to %d (was %d), dst 0x%08x\n",
8365 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8366 				    ntohl(sire->ire_addr)));
8367 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8368 			}
8369 		}
8370 		/*
8371 		 * At this point in ip_newroute(), ire is either the
8372 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8373 		 * destination or an IRE_INTERFACE type that should be used
8374 		 * to resolve an on-subnet destination or an on-subnet
8375 		 * next-hop gateway.
8376 		 *
8377 		 * In the IRE_CACHE case, we have the following :
8378 		 *
8379 		 * 1) src_ipif - used for getting a source address.
8380 		 *
8381 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8382 		 *    means packets using this IRE_CACHE will go out on
8383 		 *    dst_ill.
8384 		 *
8385 		 * 3) The IRE sire will point to the prefix that is the
8386 		 *    longest  matching route for the destination. These
8387 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8388 		 *
8389 		 *    The newly created IRE_CACHE entry for the off-subnet
8390 		 *    destination is tied to both the prefix route and the
8391 		 *    interface route used to resolve the next-hop gateway
8392 		 *    via the ire_phandle and ire_ihandle fields,
8393 		 *    respectively.
8394 		 *
8395 		 * In the IRE_INTERFACE case, we have the following :
8396 		 *
8397 		 * 1) src_ipif - used for getting a source address.
8398 		 *
8399 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8400 		 *    means packets using the IRE_CACHE that we will build
8401 		 *    here will go out on dst_ill.
8402 		 *
8403 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8404 		 *    to be created will only be tied to the IRE_INTERFACE
8405 		 *    that was derived from the ire_ihandle field.
8406 		 *
8407 		 *    If sire is non-NULL, it means the destination is
8408 		 *    off-link and we will first create the IRE_CACHE for the
8409 		 *    gateway. Next time through ip_newroute, we will create
8410 		 *    the IRE_CACHE for the final destination as described
8411 		 *    above.
8412 		 *
8413 		 * In both cases, after the current resolution has been
8414 		 * completed (or possibly initialised, in the IRE_INTERFACE
8415 		 * case), the loop may be re-entered to attempt the resolution
8416 		 * of another RTF_MULTIRT route.
8417 		 *
8418 		 * When an IRE_CACHE entry for the off-subnet destination is
8419 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8420 		 * for further processing in emission loops.
8421 		 */
8422 		save_ire = ire;
8423 		switch (ire->ire_type) {
8424 		case IRE_CACHE: {
8425 			ire_t	*ipif_ire;
8426 
8427 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8428 			if (gw == 0)
8429 				gw = ire->ire_gateway_addr;
8430 			/*
8431 			 * We need 3 ire's to create a new cache ire for an
8432 			 * off-link destination from the cache ire of the
8433 			 * gateway.
8434 			 *
8435 			 *	1. The prefix ire 'sire' (Note that this does
8436 			 *	   not apply to the conn_nexthop_set case)
8437 			 *	2. The cache ire of the gateway 'ire'
8438 			 *	3. The interface ire 'ipif_ire'
8439 			 *
8440 			 * We have (1) and (2). We lookup (3) below.
8441 			 *
8442 			 * If there is no interface route to the gateway,
8443 			 * it is a race condition, where we found the cache
8444 			 * but the interface route has been deleted.
8445 			 */
8446 			if (ip_nexthop) {
8447 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8448 			} else {
8449 				ipif_ire =
8450 				    ire_ihandle_lookup_offlink(ire, sire);
8451 			}
8452 			if (ipif_ire == NULL) {
8453 				ip1dbg(("ip_newroute: "
8454 				    "ire_ihandle_lookup_offlink failed\n"));
8455 				goto icmp_err_ret;
8456 			}
8457 
8458 			/*
8459 			 * Check cached gateway IRE for any security
8460 			 * attributes; if found, associate the gateway
8461 			 * credentials group to the destination IRE.
8462 			 */
8463 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8464 				mutex_enter(&attrp->igsa_lock);
8465 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8466 					GCGRP_REFHOLD(gcgrp);
8467 				mutex_exit(&attrp->igsa_lock);
8468 			}
8469 
8470 			/*
8471 			 * XXX For the source of the resolver mp,
8472 			 * we are using the same DL_UNITDATA_REQ
8473 			 * (from save_ire->ire_nce->nce_res_mp)
8474 			 * though the save_ire is not pointing at the same ill.
8475 			 * This is incorrect. We need to send it up to the
8476 			 * resolver to get the right res_mp. For ethernets
8477 			 * this may be okay (ill_type == DL_ETHER).
8478 			 */
8479 
8480 			ire = ire_create(
8481 			    (uchar_t *)&dst,		/* dest address */
8482 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8483 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8484 			    (uchar_t *)&gw,		/* gateway address */
8485 			    &save_ire->ire_max_frag,
8486 			    save_ire->ire_nce,		/* src nce */
8487 			    dst_ill->ill_rq,		/* recv-from queue */
8488 			    dst_ill->ill_wq,		/* send-to queue */
8489 			    IRE_CACHE,			/* IRE type */
8490 			    src_ipif,
8491 			    (sire != NULL) ?
8492 			    sire->ire_mask : 0, 	/* Parent mask */
8493 			    (sire != NULL) ?
8494 			    sire->ire_phandle : 0,	/* Parent handle */
8495 			    ipif_ire->ire_ihandle,	/* Interface handle */
8496 			    (sire != NULL) ? (sire->ire_flags &
8497 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8498 			    (sire != NULL) ?
8499 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8500 			    NULL,
8501 			    gcgrp,
8502 			    ipst);
8503 
8504 			if (ire == NULL) {
8505 				if (gcgrp != NULL) {
8506 					GCGRP_REFRELE(gcgrp);
8507 					gcgrp = NULL;
8508 				}
8509 				ire_refrele(ipif_ire);
8510 				ire_refrele(save_ire);
8511 				break;
8512 			}
8513 
8514 			/* reference now held by IRE */
8515 			gcgrp = NULL;
8516 
8517 			ire->ire_marks |= ire_marks;
8518 
8519 			/*
8520 			 * Prevent sire and ipif_ire from getting deleted.
8521 			 * The newly created ire is tied to both of them via
8522 			 * the phandle and ihandle respectively.
8523 			 */
8524 			if (sire != NULL) {
8525 				IRB_REFHOLD(sire->ire_bucket);
8526 				/* Has it been removed already ? */
8527 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8528 					IRB_REFRELE(sire->ire_bucket);
8529 					ire_refrele(ipif_ire);
8530 					ire_refrele(save_ire);
8531 					break;
8532 				}
8533 			}
8534 
8535 			IRB_REFHOLD(ipif_ire->ire_bucket);
8536 			/* Has it been removed already ? */
8537 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8538 				IRB_REFRELE(ipif_ire->ire_bucket);
8539 				if (sire != NULL)
8540 					IRB_REFRELE(sire->ire_bucket);
8541 				ire_refrele(ipif_ire);
8542 				ire_refrele(save_ire);
8543 				break;
8544 			}
8545 
8546 			xmit_mp = first_mp;
8547 			/*
8548 			 * In the case of multirouting, a copy
8549 			 * of the packet is done before its sending.
8550 			 * The copy is used to attempt another
8551 			 * route resolution, in a next loop.
8552 			 */
8553 			if (ire->ire_flags & RTF_MULTIRT) {
8554 				copy_mp = copymsg(first_mp);
8555 				if (copy_mp != NULL) {
8556 					xmit_mp = copy_mp;
8557 					MULTIRT_DEBUG_TAG(first_mp);
8558 				}
8559 			}
8560 			ire_add_then_send(q, ire, xmit_mp);
8561 			ire_refrele(save_ire);
8562 
8563 			/* Assert that sire is not deleted yet. */
8564 			if (sire != NULL) {
8565 				ASSERT(sire->ire_ptpn != NULL);
8566 				IRB_REFRELE(sire->ire_bucket);
8567 			}
8568 
8569 			/* Assert that ipif_ire is not deleted yet. */
8570 			ASSERT(ipif_ire->ire_ptpn != NULL);
8571 			IRB_REFRELE(ipif_ire->ire_bucket);
8572 			ire_refrele(ipif_ire);
8573 
8574 			/*
8575 			 * If copy_mp is not NULL, multirouting was
8576 			 * requested. We loop to initiate a next
8577 			 * route resolution attempt, starting from sire.
8578 			 */
8579 			if (copy_mp != NULL) {
8580 				/*
8581 				 * Search for the next unresolved
8582 				 * multirt route.
8583 				 */
8584 				copy_mp = NULL;
8585 				ipif_ire = NULL;
8586 				ire = NULL;
8587 				multirt_resolve_next = B_TRUE;
8588 				continue;
8589 			}
8590 			if (sire != NULL)
8591 				ire_refrele(sire);
8592 			ipif_refrele(src_ipif);
8593 			ill_refrele(dst_ill);
8594 			return;
8595 		}
8596 		case IRE_IF_NORESOLVER: {
8597 
8598 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8599 			    dst_ill->ill_resolver_mp == NULL) {
8600 				ip1dbg(("ip_newroute: dst_ill %p "
8601 				    "for IRE_IF_NORESOLVER ire %p has "
8602 				    "no ill_resolver_mp\n",
8603 				    (void *)dst_ill, (void *)ire));
8604 				break;
8605 			}
8606 
8607 			/*
8608 			 * TSol note: We are creating the ire cache for the
8609 			 * destination 'dst'. If 'dst' is offlink, going
8610 			 * through the first hop 'gw', the security attributes
8611 			 * of 'dst' must be set to point to the gateway
8612 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8613 			 * is possible that 'dst' is a potential gateway that is
8614 			 * referenced by some route that has some security
8615 			 * attributes. Thus in the former case, we need to do a
8616 			 * gcgrp_lookup of 'gw' while in the latter case we
8617 			 * need to do gcgrp_lookup of 'dst' itself.
8618 			 */
8619 			ga.ga_af = AF_INET;
8620 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8621 			    &ga.ga_addr);
8622 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8623 
8624 			ire = ire_create(
8625 			    (uchar_t *)&dst,		/* dest address */
8626 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8627 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8628 			    (uchar_t *)&gw,		/* gateway address */
8629 			    &save_ire->ire_max_frag,
8630 			    NULL,			/* no src nce */
8631 			    dst_ill->ill_rq,		/* recv-from queue */
8632 			    dst_ill->ill_wq,		/* send-to queue */
8633 			    IRE_CACHE,
8634 			    src_ipif,
8635 			    save_ire->ire_mask,		/* Parent mask */
8636 			    (sire != NULL) ?		/* Parent handle */
8637 			    sire->ire_phandle : 0,
8638 			    save_ire->ire_ihandle,	/* Interface handle */
8639 			    (sire != NULL) ? sire->ire_flags &
8640 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8641 			    &(save_ire->ire_uinfo),
8642 			    NULL,
8643 			    gcgrp,
8644 			    ipst);
8645 
8646 			if (ire == NULL) {
8647 				if (gcgrp != NULL) {
8648 					GCGRP_REFRELE(gcgrp);
8649 					gcgrp = NULL;
8650 				}
8651 				ire_refrele(save_ire);
8652 				break;
8653 			}
8654 
8655 			/* reference now held by IRE */
8656 			gcgrp = NULL;
8657 
8658 			ire->ire_marks |= ire_marks;
8659 
8660 			/* Prevent save_ire from getting deleted */
8661 			IRB_REFHOLD(save_ire->ire_bucket);
8662 			/* Has it been removed already ? */
8663 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8664 				IRB_REFRELE(save_ire->ire_bucket);
8665 				ire_refrele(save_ire);
8666 				break;
8667 			}
8668 
8669 			/*
8670 			 * In the case of multirouting, a copy
8671 			 * of the packet is made before it is sent.
8672 			 * The copy is used in the next
8673 			 * loop to attempt another resolution.
8674 			 */
8675 			xmit_mp = first_mp;
8676 			if ((sire != NULL) &&
8677 			    (sire->ire_flags & RTF_MULTIRT)) {
8678 				copy_mp = copymsg(first_mp);
8679 				if (copy_mp != NULL) {
8680 					xmit_mp = copy_mp;
8681 					MULTIRT_DEBUG_TAG(first_mp);
8682 				}
8683 			}
8684 			ire_add_then_send(q, ire, xmit_mp);
8685 
8686 			/* Assert that it is not deleted yet. */
8687 			ASSERT(save_ire->ire_ptpn != NULL);
8688 			IRB_REFRELE(save_ire->ire_bucket);
8689 			ire_refrele(save_ire);
8690 
8691 			if (copy_mp != NULL) {
8692 				/*
8693 				 * If we found a (no)resolver, we ignore any
8694 				 * trailing top priority IRE_CACHE in further
8695 				 * loops. This ensures that we do not omit any
8696 				 * (no)resolver.
8697 				 * This IRE_CACHE, if any, will be processed
8698 				 * by another thread entering ip_newroute().
8699 				 * IRE_CACHE entries, if any, will be processed
8700 				 * by another thread entering ip_newroute(),
8701 				 * (upon resolver response, for instance).
8702 				 * This aims to force parallel multirt
8703 				 * resolutions as soon as a packet must be sent.
8704 				 * In the best case, after the tx of only one
8705 				 * packet, all reachable routes are resolved.
8706 				 * Otherwise, the resolution of all RTF_MULTIRT
8707 				 * routes would require several emissions.
8708 				 */
8709 				multirt_flags &= ~MULTIRT_CACHEGW;
8710 
8711 				/*
8712 				 * Search for the next unresolved multirt
8713 				 * route.
8714 				 */
8715 				copy_mp = NULL;
8716 				save_ire = NULL;
8717 				ire = NULL;
8718 				multirt_resolve_next = B_TRUE;
8719 				continue;
8720 			}
8721 
8722 			/*
8723 			 * Don't need sire anymore
8724 			 */
8725 			if (sire != NULL)
8726 				ire_refrele(sire);
8727 
8728 			ipif_refrele(src_ipif);
8729 			ill_refrele(dst_ill);
8730 			return;
8731 		}
8732 		case IRE_IF_RESOLVER:
8733 			/*
8734 			 * We can't build an IRE_CACHE yet, but at least we
8735 			 * found a resolver that can help.
8736 			 */
8737 			res_mp = dst_ill->ill_resolver_mp;
8738 			if (!OK_RESOLVER_MP(res_mp))
8739 				break;
8740 
8741 			/*
8742 			 * To be at this point in the code with a non-zero gw
8743 			 * means that dst is reachable through a gateway that
8744 			 * we have never resolved.  By changing dst to the gw
8745 			 * addr we resolve the gateway first.
8746 			 * When ire_add_then_send() tries to put the IP dg
8747 			 * to dst, it will reenter ip_newroute() at which
8748 			 * time we will find the IRE_CACHE for the gw and
8749 			 * create another IRE_CACHE in case IRE_CACHE above.
8750 			 */
8751 			if (gw != INADDR_ANY) {
8752 				/*
8753 				 * The source ipif that was determined above was
8754 				 * relative to the destination address, not the
8755 				 * gateway's. If src_ipif was not taken out of
8756 				 * the IRE_IF_RESOLVER entry, we'll need to call
8757 				 * ipif_select_source() again.
8758 				 */
8759 				if (src_ipif != ire->ire_ipif) {
8760 					ipif_refrele(src_ipif);
8761 					src_ipif = ipif_select_source(dst_ill,
8762 					    gw, zoneid);
8763 					if (src_ipif == NULL) {
8764 						if (ip_debug > 2) {
8765 							pr_addr_dbg(
8766 							    "ip_newroute: no "
8767 							    "src for gw %s ",
8768 							    AF_INET, &gw);
8769 							printf("through "
8770 							    "interface %s\n",
8771 							    dst_ill->ill_name);
8772 						}
8773 						goto icmp_err_ret;
8774 					}
8775 				}
8776 				save_dst = dst;
8777 				dst = gw;
8778 				gw = INADDR_ANY;
8779 			}
8780 
8781 			/*
8782 			 * We obtain a partial IRE_CACHE which we will pass
8783 			 * along with the resolver query.  When the response
8784 			 * comes back it will be there ready for us to add.
8785 			 * The ire_max_frag is atomically set under the
8786 			 * irebucket lock in ire_add_v[46].
8787 			 */
8788 
8789 			ire = ire_create_mp(
8790 			    (uchar_t *)&dst,		/* dest address */
8791 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8792 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8793 			    (uchar_t *)&gw,		/* gateway address */
8794 			    NULL,			/* ire_max_frag */
8795 			    NULL,			/* no src nce */
8796 			    dst_ill->ill_rq,		/* recv-from queue */
8797 			    dst_ill->ill_wq,		/* send-to queue */
8798 			    IRE_CACHE,
8799 			    src_ipif,			/* Interface ipif */
8800 			    save_ire->ire_mask,		/* Parent mask */
8801 			    0,
8802 			    save_ire->ire_ihandle,	/* Interface handle */
8803 			    0,				/* flags if any */
8804 			    &(save_ire->ire_uinfo),
8805 			    NULL,
8806 			    NULL,
8807 			    ipst);
8808 
8809 			if (ire == NULL) {
8810 				ire_refrele(save_ire);
8811 				break;
8812 			}
8813 
8814 			if ((sire != NULL) &&
8815 			    (sire->ire_flags & RTF_MULTIRT)) {
8816 				copy_mp = copymsg(first_mp);
8817 				if (copy_mp != NULL)
8818 					MULTIRT_DEBUG_TAG(copy_mp);
8819 			}
8820 
8821 			ire->ire_marks |= ire_marks;
8822 
8823 			/*
8824 			 * Construct message chain for the resolver
8825 			 * of the form:
8826 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8827 			 * Packet could contain a IPSEC_OUT mp.
8828 			 *
8829 			 * NOTE : ire will be added later when the response
8830 			 * comes back from ARP. If the response does not
8831 			 * come back, ARP frees the packet. For this reason,
8832 			 * we can't REFHOLD the bucket of save_ire to prevent
8833 			 * deletions. We may not be able to REFRELE the bucket
8834 			 * if the response never comes back. Thus, before
8835 			 * adding the ire, ire_add_v4 will make sure that the
8836 			 * interface route does not get deleted. This is the
8837 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8838 			 * where we can always prevent deletions because of
8839 			 * the synchronous nature of adding IRES i.e
8840 			 * ire_add_then_send is called after creating the IRE.
8841 			 */
8842 			ASSERT(ire->ire_mp != NULL);
8843 			ire->ire_mp->b_cont = first_mp;
8844 			/* Have saved_mp handy, for cleanup if canput fails */
8845 			saved_mp = mp;
8846 			mp = copyb(res_mp);
8847 			if (mp == NULL) {
8848 				/* Prepare for cleanup */
8849 				mp = saved_mp; /* pkt */
8850 				ire_delete(ire); /* ire_mp */
8851 				ire = NULL;
8852 				ire_refrele(save_ire);
8853 				if (copy_mp != NULL) {
8854 					MULTIRT_DEBUG_UNTAG(copy_mp);
8855 					freemsg(copy_mp);
8856 					copy_mp = NULL;
8857 				}
8858 				break;
8859 			}
8860 			linkb(mp, ire->ire_mp);
8861 
8862 			/*
8863 			 * Fill in the source and dest addrs for the resolver.
8864 			 * NOTE: this depends on memory layouts imposed by
8865 			 * ill_init().
8866 			 */
8867 			areq = (areq_t *)mp->b_rptr;
8868 			addrp = (ipaddr_t *)((char *)areq +
8869 			    areq->areq_sender_addr_offset);
8870 			if (do_attach_ill) {
8871 				/*
8872 				 * This is bind to no failover case.
8873 				 * arp packet also must go out on attach_ill.
8874 				 */
8875 				ASSERT(ipha->ipha_src != NULL);
8876 				*addrp = ipha->ipha_src;
8877 			} else {
8878 				*addrp = save_ire->ire_src_addr;
8879 			}
8880 
8881 			ire_refrele(save_ire);
8882 			addrp = (ipaddr_t *)((char *)areq +
8883 			    areq->areq_target_addr_offset);
8884 			*addrp = dst;
8885 			/* Up to the resolver. */
8886 			if (canputnext(dst_ill->ill_rq) &&
8887 			    !(dst_ill->ill_arp_closing)) {
8888 				putnext(dst_ill->ill_rq, mp);
8889 				ire = NULL;
8890 				if (copy_mp != NULL) {
8891 					/*
8892 					 * If we found a resolver, we ignore
8893 					 * any trailing top priority IRE_CACHE
8894 					 * in the further loops. This ensures
8895 					 * that we do not omit any resolver.
8896 					 * IRE_CACHE entries, if any, will be
8897 					 * processed next time we enter
8898 					 * ip_newroute().
8899 					 */
8900 					multirt_flags &= ~MULTIRT_CACHEGW;
8901 					/*
8902 					 * Search for the next unresolved
8903 					 * multirt route.
8904 					 */
8905 					first_mp = copy_mp;
8906 					copy_mp = NULL;
8907 					/* Prepare the next resolution loop. */
8908 					mp = first_mp;
8909 					EXTRACT_PKT_MP(mp, first_mp,
8910 					    mctl_present);
8911 					if (mctl_present)
8912 						io = (ipsec_out_t *)
8913 						    first_mp->b_rptr;
8914 					ipha = (ipha_t *)mp->b_rptr;
8915 
8916 					ASSERT(sire != NULL);
8917 
8918 					dst = save_dst;
8919 					multirt_resolve_next = B_TRUE;
8920 					continue;
8921 				}
8922 
8923 				if (sire != NULL)
8924 					ire_refrele(sire);
8925 
8926 				/*
8927 				 * The response will come back in ip_wput
8928 				 * with db_type IRE_DB_TYPE.
8929 				 */
8930 				ipif_refrele(src_ipif);
8931 				ill_refrele(dst_ill);
8932 				return;
8933 			} else {
8934 				/* Prepare for cleanup */
8935 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8936 				    mp);
8937 				mp->b_cont = NULL;
8938 				freeb(mp); /* areq */
8939 				/*
8940 				 * this is an ire that is not added to the
8941 				 * cache. ire_freemblk will handle the release
8942 				 * of any resources associated with the ire.
8943 				 */
8944 				ire_delete(ire); /* ire_mp */
8945 				mp = saved_mp; /* pkt */
8946 				ire = NULL;
8947 				if (copy_mp != NULL) {
8948 					MULTIRT_DEBUG_UNTAG(copy_mp);
8949 					freemsg(copy_mp);
8950 					copy_mp = NULL;
8951 				}
8952 				break;
8953 			}
8954 		default:
8955 			break;
8956 		}
8957 	} while (multirt_resolve_next);
8958 
8959 	ip1dbg(("ip_newroute: dropped\n"));
8960 	/* Did this packet originate externally? */
8961 	if (mp->b_prev) {
8962 		mp->b_next = NULL;
8963 		mp->b_prev = NULL;
8964 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8965 	} else {
8966 		if (dst_ill != NULL) {
8967 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8968 		} else {
8969 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8970 		}
8971 	}
8972 	ASSERT(copy_mp == NULL);
8973 	MULTIRT_DEBUG_UNTAG(first_mp);
8974 	freemsg(first_mp);
8975 	if (ire != NULL)
8976 		ire_refrele(ire);
8977 	if (sire != NULL)
8978 		ire_refrele(sire);
8979 	if (src_ipif != NULL)
8980 		ipif_refrele(src_ipif);
8981 	if (dst_ill != NULL)
8982 		ill_refrele(dst_ill);
8983 	return;
8984 
8985 icmp_err_ret:
8986 	ip1dbg(("ip_newroute: no route\n"));
8987 	if (src_ipif != NULL)
8988 		ipif_refrele(src_ipif);
8989 	if (dst_ill != NULL)
8990 		ill_refrele(dst_ill);
8991 	if (sire != NULL)
8992 		ire_refrele(sire);
8993 	/* Did this packet originate externally? */
8994 	if (mp->b_prev) {
8995 		mp->b_next = NULL;
8996 		mp->b_prev = NULL;
8997 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8998 		q = WR(q);
8999 	} else {
9000 		/*
9001 		 * There is no outgoing ill, so just increment the
9002 		 * system MIB.
9003 		 */
9004 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
9005 		/*
9006 		 * Since ip_wput() isn't close to finished, we fill
9007 		 * in enough of the header for credible error reporting.
9008 		 */
9009 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
9010 			/* Failed */
9011 			MULTIRT_DEBUG_UNTAG(first_mp);
9012 			freemsg(first_mp);
9013 			if (ire != NULL)
9014 				ire_refrele(ire);
9015 			return;
9016 		}
9017 	}
9018 
9019 	/*
9020 	 * At this point we will have ire only if RTF_BLACKHOLE
9021 	 * or RTF_REJECT flags are set on the IRE. It will not
9022 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9023 	 */
9024 	if (ire != NULL) {
9025 		if (ire->ire_flags & RTF_BLACKHOLE) {
9026 			ire_refrele(ire);
9027 			MULTIRT_DEBUG_UNTAG(first_mp);
9028 			freemsg(first_mp);
9029 			return;
9030 		}
9031 		ire_refrele(ire);
9032 	}
9033 	if (ip_source_routed(ipha, ipst)) {
9034 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
9035 		    zoneid, ipst);
9036 		return;
9037 	}
9038 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9039 }
9040 
9041 ip_opt_info_t zero_info;
9042 
9043 /*
9044  * IPv4 -
9045  * ip_newroute_ipif is called by ip_wput_multicast and
9046  * ip_rput_forward_multicast whenever we need to send
9047  * out a packet to a destination address for which we do not have specific
9048  * routing information. It is used when the packet will be sent out
9049  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
9050  * socket option is set or icmp error message wants to go out on a particular
9051  * interface for a unicast packet.
9052  *
9053  * In most cases, the destination address is resolved thanks to the ipif
9054  * intrinsic resolver. However, there are some cases where the call to
9055  * ip_newroute_ipif must take into account the potential presence of
9056  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9057  * that uses the interface. This is specified through flags,
9058  * which can be a combination of:
9059  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9060  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9061  *   and flags. Additionally, the packet source address has to be set to
9062  *   the specified address. The caller is thus expected to set this flag
9063  *   if the packet has no specific source address yet.
9064  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9065  *   flag, the resulting ire will inherit the flag. All unresolved routes
9066  *   to the destination must be explored in the same call to
9067  *   ip_newroute_ipif().
9068  */
9069 static void
9070 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9071     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9072 {
9073 	areq_t	*areq;
9074 	ire_t	*ire = NULL;
9075 	mblk_t	*res_mp;
9076 	ipaddr_t *addrp;
9077 	mblk_t *first_mp;
9078 	ire_t	*save_ire = NULL;
9079 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9080 	ipif_t	*src_ipif = NULL;
9081 	ushort_t ire_marks = 0;
9082 	ill_t	*dst_ill = NULL;
9083 	boolean_t mctl_present;
9084 	ipsec_out_t *io;
9085 	ipha_t *ipha;
9086 	int	ihandle = 0;
9087 	mblk_t	*saved_mp;
9088 	ire_t   *fire = NULL;
9089 	mblk_t  *copy_mp = NULL;
9090 	boolean_t multirt_resolve_next;
9091 	ipaddr_t ipha_dst;
9092 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9093 
9094 	/*
9095 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9096 	 * here for uniformity
9097 	 */
9098 	ipif_refhold(ipif);
9099 
9100 	/*
9101 	 * This loop is run only once in most cases.
9102 	 * We loop to resolve further routes only when the destination
9103 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9104 	 */
9105 	do {
9106 		if (dst_ill != NULL) {
9107 			ill_refrele(dst_ill);
9108 			dst_ill = NULL;
9109 		}
9110 		if (src_ipif != NULL) {
9111 			ipif_refrele(src_ipif);
9112 			src_ipif = NULL;
9113 		}
9114 		multirt_resolve_next = B_FALSE;
9115 
9116 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9117 		    ipif->ipif_ill->ill_name));
9118 
9119 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9120 		if (mctl_present)
9121 			io = (ipsec_out_t *)first_mp->b_rptr;
9122 
9123 		ipha = (ipha_t *)mp->b_rptr;
9124 
9125 		/*
9126 		 * Save the packet destination address, we may need it after
9127 		 * the packet has been consumed.
9128 		 */
9129 		ipha_dst = ipha->ipha_dst;
9130 
9131 		/*
9132 		 * If the interface is a pt-pt interface we look for an
9133 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9134 		 * local_address and the pt-pt destination address. Otherwise
9135 		 * we just match the local address.
9136 		 * NOTE: dst could be different than ipha->ipha_dst in case
9137 		 * of sending igmp multicast packets over a point-to-point
9138 		 * connection.
9139 		 * Thus we must be careful enough to check ipha_dst to be a
9140 		 * multicast address, otherwise it will take xmit_if path for
9141 		 * multicast packets resulting into kernel stack overflow by
9142 		 * repeated calls to ip_newroute_ipif from ire_send().
9143 		 */
9144 		if (CLASSD(ipha_dst) &&
9145 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9146 			goto err_ret;
9147 		}
9148 
9149 		/*
9150 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9151 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9152 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9153 		 * propagate its flags to the new ire.
9154 		 */
9155 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9156 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9157 			ip2dbg(("ip_newroute_ipif: "
9158 			    "ipif_lookup_multi_ire("
9159 			    "ipif %p, dst %08x) = fire %p\n",
9160 			    (void *)ipif, ntohl(dst), (void *)fire));
9161 		}
9162 
9163 		if (mctl_present && io->ipsec_out_attach_if) {
9164 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9165 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9166 
9167 			/* Failure case frees things for us. */
9168 			if (attach_ill == NULL) {
9169 				ipif_refrele(ipif);
9170 				if (fire != NULL)
9171 					ire_refrele(fire);
9172 				return;
9173 			}
9174 
9175 			/*
9176 			 * Check if we need an ire that will not be
9177 			 * looked up by anybody else i.e. HIDDEN.
9178 			 */
9179 			if (ill_is_probeonly(attach_ill)) {
9180 				ire_marks = IRE_MARK_HIDDEN;
9181 			}
9182 			/*
9183 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9184 			 * case.
9185 			 */
9186 			dst_ill = ipif->ipif_ill;
9187 			/* attach_ill has been refheld by ip_grab_attach_ill */
9188 			ASSERT(dst_ill == attach_ill);
9189 		} else {
9190 			/*
9191 			 * If this is set by IP_XMIT_IF, then make sure that
9192 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9193 			 * specified ill.
9194 			 */
9195 			ASSERT((connp == NULL) ||
9196 			    (connp->conn_xmit_if_ill == NULL) ||
9197 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9198 			/*
9199 			 * If the interface belongs to an interface group,
9200 			 * make sure the next possible interface in the group
9201 			 * is used.  This encourages load spreading among
9202 			 * peers in an interface group.
9203 			 * Note: load spreading is disabled for RTF_MULTIRT
9204 			 * routes.
9205 			 */
9206 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9207 			    (fire->ire_flags & RTF_MULTIRT)) {
9208 				/*
9209 				 * Don't perform outbound load spreading
9210 				 * in the case of an RTF_MULTIRT issued route,
9211 				 * we actually typically want to replicate
9212 				 * outgoing packets through particular
9213 				 * interfaces.
9214 				 */
9215 				dst_ill = ipif->ipif_ill;
9216 				ill_refhold(dst_ill);
9217 			} else {
9218 				dst_ill = ip_newroute_get_dst_ill(
9219 				    ipif->ipif_ill);
9220 			}
9221 			if (dst_ill == NULL) {
9222 				if (ip_debug > 2) {
9223 					pr_addr_dbg("ip_newroute_ipif: "
9224 					    "no dst ill for dst %s\n",
9225 					    AF_INET, &dst);
9226 				}
9227 				goto err_ret;
9228 			}
9229 		}
9230 
9231 		/*
9232 		 * Pick a source address preferring non-deprecated ones.
9233 		 * Unlike ip_newroute, we don't do any source address
9234 		 * selection here since for multicast it really does not help
9235 		 * in inbound load spreading as in the unicast case.
9236 		 */
9237 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9238 		    (fire->ire_flags & RTF_SETSRC)) {
9239 			/*
9240 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9241 			 * on that interface. This ire has RTF_SETSRC flag, so
9242 			 * the source address of the packet must be changed.
9243 			 * Check that the ipif matching the requested source
9244 			 * address still exists.
9245 			 */
9246 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9247 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9248 		}
9249 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9250 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9251 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9252 		    (src_ipif == NULL)) {
9253 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9254 			if (src_ipif == NULL) {
9255 				if (ip_debug > 2) {
9256 					/* ip1dbg */
9257 					pr_addr_dbg("ip_newroute_ipif: "
9258 					    "no src for dst %s",
9259 					    AF_INET, &dst);
9260 				}
9261 				ip1dbg((" through interface %s\n",
9262 				    dst_ill->ill_name));
9263 				goto err_ret;
9264 			}
9265 			ipif_refrele(ipif);
9266 			ipif = src_ipif;
9267 			ipif_refhold(ipif);
9268 		}
9269 		if (src_ipif == NULL) {
9270 			src_ipif = ipif;
9271 			ipif_refhold(src_ipif);
9272 		}
9273 
9274 		/*
9275 		 * Assign a source address while we have the conn.
9276 		 * We can't have ip_wput_ire pick a source address when the
9277 		 * packet returns from arp since conn_unspec_src might be set
9278 		 * and we loose the conn when going through arp.
9279 		 */
9280 		if (ipha->ipha_src == INADDR_ANY &&
9281 		    (connp == NULL || !connp->conn_unspec_src)) {
9282 			ipha->ipha_src = src_ipif->ipif_src_addr;
9283 		}
9284 
9285 		/*
9286 		 * In the case of IP_XMIT_IF, it is possible that the
9287 		 * outgoing interface does not have an interface ire.
9288 		 */
9289 		if (CLASSD(ipha_dst) && (connp == NULL ||
9290 		    connp->conn_xmit_if_ill == NULL) &&
9291 		    infop->ip_opt_ill_index == 0) {
9292 			/* ipif_to_ire returns an held ire */
9293 			ire = ipif_to_ire(ipif);
9294 			if (ire == NULL)
9295 				goto err_ret;
9296 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9297 				goto err_ret;
9298 			/*
9299 			 * ihandle is needed when the ire is added to
9300 			 * cache table.
9301 			 */
9302 			save_ire = ire;
9303 			ihandle = save_ire->ire_ihandle;
9304 
9305 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9306 			    "flags %04x\n",
9307 			    (void *)ire, (void *)ipif, flags));
9308 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9309 			    (fire->ire_flags & RTF_MULTIRT)) {
9310 				/*
9311 				 * As requested by flags, an IRE_OFFSUBNET was
9312 				 * looked up on that interface. This ire has
9313 				 * RTF_MULTIRT flag, so the resolution loop will
9314 				 * be re-entered to resolve additional routes on
9315 				 * other interfaces. For that purpose, a copy of
9316 				 * the packet is performed at this point.
9317 				 */
9318 				fire->ire_last_used_time = lbolt;
9319 				copy_mp = copymsg(first_mp);
9320 				if (copy_mp) {
9321 					MULTIRT_DEBUG_TAG(copy_mp);
9322 				}
9323 			}
9324 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9325 			    (fire->ire_flags & RTF_SETSRC)) {
9326 				/*
9327 				 * As requested by flags, an IRE_OFFSUBET was
9328 				 * looked up on that interface. This ire has
9329 				 * RTF_SETSRC flag, so the source address of the
9330 				 * packet must be changed.
9331 				 */
9332 				ipha->ipha_src = fire->ire_src_addr;
9333 			}
9334 		} else {
9335 			ASSERT((connp == NULL) ||
9336 			    (connp->conn_xmit_if_ill != NULL) ||
9337 			    (connp->conn_dontroute) ||
9338 			    infop->ip_opt_ill_index != 0);
9339 			/*
9340 			 * The only ways we can come here are:
9341 			 * 1) IP_XMIT_IF socket option is set
9342 			 * 2) SO_DONTROUTE socket option is set
9343 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9344 			 * In all cases, the new ire will not be added
9345 			 * into cache table.
9346 			 */
9347 			ire_marks |= IRE_MARK_NOADD;
9348 		}
9349 
9350 		switch (ipif->ipif_net_type) {
9351 		case IRE_IF_NORESOLVER: {
9352 			/* We have what we need to build an IRE_CACHE. */
9353 
9354 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9355 			    (dst_ill->ill_resolver_mp == NULL)) {
9356 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9357 				    "for IRE_IF_NORESOLVER ire %p has "
9358 				    "no ill_resolver_mp\n",
9359 				    (void *)dst_ill, (void *)ire));
9360 				break;
9361 			}
9362 
9363 			/*
9364 			 * The new ire inherits the IRE_OFFSUBNET flags
9365 			 * and source address, if this was requested.
9366 			 */
9367 			ire = ire_create(
9368 			    (uchar_t *)&dst,		/* dest address */
9369 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9370 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9371 			    NULL,			/* gateway address */
9372 			    &ipif->ipif_mtu,
9373 			    NULL,			/* no src nce */
9374 			    dst_ill->ill_rq,		/* recv-from queue */
9375 			    dst_ill->ill_wq,		/* send-to queue */
9376 			    IRE_CACHE,
9377 			    src_ipif,
9378 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9379 			    (fire != NULL) ?		/* Parent handle */
9380 			    fire->ire_phandle : 0,
9381 			    ihandle,			/* Interface handle */
9382 			    (fire != NULL) ?
9383 			    (fire->ire_flags &
9384 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9385 			    (save_ire == NULL ? &ire_uinfo_null :
9386 			    &save_ire->ire_uinfo),
9387 			    NULL,
9388 			    NULL,
9389 			    ipst);
9390 
9391 			if (ire == NULL) {
9392 				if (save_ire != NULL)
9393 					ire_refrele(save_ire);
9394 				break;
9395 			}
9396 
9397 			ire->ire_marks |= ire_marks;
9398 
9399 			/*
9400 			 * If IRE_MARK_NOADD is set then we need to convert
9401 			 * the max_fragp to a useable value now. This is
9402 			 * normally done in ire_add_v[46]. We also need to
9403 			 * associate the ire with an nce (normally would be
9404 			 * done in ip_wput_nondata()).
9405 			 *
9406 			 * Note that IRE_MARK_NOADD packets created here
9407 			 * do not have a non-null ire_mp pointer. The null
9408 			 * value of ire_bucket indicates that they were
9409 			 * never added.
9410 			 */
9411 			if (ire->ire_marks & IRE_MARK_NOADD) {
9412 				uint_t  max_frag;
9413 
9414 				max_frag = *ire->ire_max_fragp;
9415 				ire->ire_max_fragp = NULL;
9416 				ire->ire_max_frag = max_frag;
9417 
9418 				if ((ire->ire_nce = ndp_lookup_v4(
9419 				    ire_to_ill(ire),
9420 				    (ire->ire_gateway_addr != INADDR_ANY ?
9421 				    &ire->ire_gateway_addr : &ire->ire_addr),
9422 				    B_FALSE)) == NULL) {
9423 					if (save_ire != NULL)
9424 						ire_refrele(save_ire);
9425 					break;
9426 				}
9427 				ASSERT(ire->ire_nce->nce_state ==
9428 				    ND_REACHABLE);
9429 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9430 			}
9431 
9432 			/* Prevent save_ire from getting deleted */
9433 			if (save_ire != NULL) {
9434 				IRB_REFHOLD(save_ire->ire_bucket);
9435 				/* Has it been removed already ? */
9436 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9437 					IRB_REFRELE(save_ire->ire_bucket);
9438 					ire_refrele(save_ire);
9439 					break;
9440 				}
9441 			}
9442 
9443 			ire_add_then_send(q, ire, first_mp);
9444 
9445 			/* Assert that save_ire is not deleted yet. */
9446 			if (save_ire != NULL) {
9447 				ASSERT(save_ire->ire_ptpn != NULL);
9448 				IRB_REFRELE(save_ire->ire_bucket);
9449 				ire_refrele(save_ire);
9450 				save_ire = NULL;
9451 			}
9452 			if (fire != NULL) {
9453 				ire_refrele(fire);
9454 				fire = NULL;
9455 			}
9456 
9457 			/*
9458 			 * the resolution loop is re-entered if this
9459 			 * was requested through flags and if we
9460 			 * actually are in a multirouting case.
9461 			 */
9462 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9463 				boolean_t need_resolve =
9464 				    ire_multirt_need_resolve(ipha_dst,
9465 				    MBLK_GETLABEL(copy_mp), ipst);
9466 				if (!need_resolve) {
9467 					MULTIRT_DEBUG_UNTAG(copy_mp);
9468 					freemsg(copy_mp);
9469 					copy_mp = NULL;
9470 				} else {
9471 					/*
9472 					 * ipif_lookup_group() calls
9473 					 * ire_lookup_multi() that uses
9474 					 * ire_ftable_lookup() to find
9475 					 * an IRE_INTERFACE for the group.
9476 					 * In the multirt case,
9477 					 * ire_lookup_multi() then invokes
9478 					 * ire_multirt_lookup() to find
9479 					 * the next resolvable ire.
9480 					 * As a result, we obtain an new
9481 					 * interface, derived from the
9482 					 * next ire.
9483 					 */
9484 					ipif_refrele(ipif);
9485 					ipif = ipif_lookup_group(ipha_dst,
9486 					    zoneid, ipst);
9487 					ip2dbg(("ip_newroute_ipif: "
9488 					    "multirt dst %08x, ipif %p\n",
9489 					    htonl(dst), (void *)ipif));
9490 					if (ipif != NULL) {
9491 						mp = copy_mp;
9492 						copy_mp = NULL;
9493 						multirt_resolve_next = B_TRUE;
9494 						continue;
9495 					} else {
9496 						freemsg(copy_mp);
9497 					}
9498 				}
9499 			}
9500 			if (ipif != NULL)
9501 				ipif_refrele(ipif);
9502 			ill_refrele(dst_ill);
9503 			ipif_refrele(src_ipif);
9504 			return;
9505 		}
9506 		case IRE_IF_RESOLVER:
9507 			/*
9508 			 * We can't build an IRE_CACHE yet, but at least
9509 			 * we found a resolver that can help.
9510 			 */
9511 			res_mp = dst_ill->ill_resolver_mp;
9512 			if (!OK_RESOLVER_MP(res_mp))
9513 				break;
9514 
9515 			/*
9516 			 * We obtain a partial IRE_CACHE which we will pass
9517 			 * along with the resolver query.  When the response
9518 			 * comes back it will be there ready for us to add.
9519 			 * The new ire inherits the IRE_OFFSUBNET flags
9520 			 * and source address, if this was requested.
9521 			 * The ire_max_frag is atomically set under the
9522 			 * irebucket lock in ire_add_v[46]. Only in the
9523 			 * case of IRE_MARK_NOADD, we set it here itself.
9524 			 */
9525 			ire = ire_create_mp(
9526 			    (uchar_t *)&dst,		/* dest address */
9527 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9528 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9529 			    NULL,			/* gateway address */
9530 			    (ire_marks & IRE_MARK_NOADD) ?
9531 			    ipif->ipif_mtu : 0,		/* max_frag */
9532 			    NULL,			/* no src nce */
9533 			    dst_ill->ill_rq,		/* recv-from queue */
9534 			    dst_ill->ill_wq,		/* send-to queue */
9535 			    IRE_CACHE,
9536 			    src_ipif,
9537 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9538 			    (fire != NULL) ?		/* Parent handle */
9539 			    fire->ire_phandle : 0,
9540 			    ihandle,			/* Interface handle */
9541 			    (fire != NULL) ?		/* flags if any */
9542 			    (fire->ire_flags &
9543 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9544 			    (save_ire == NULL ? &ire_uinfo_null :
9545 			    &save_ire->ire_uinfo),
9546 			    NULL,
9547 			    NULL,
9548 			    ipst);
9549 
9550 			if (save_ire != NULL) {
9551 				ire_refrele(save_ire);
9552 				save_ire = NULL;
9553 			}
9554 			if (ire == NULL)
9555 				break;
9556 
9557 			ire->ire_marks |= ire_marks;
9558 			/*
9559 			 * Construct message chain for the resolver of the
9560 			 * form:
9561 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9562 			 *
9563 			 * NOTE : ire will be added later when the response
9564 			 * comes back from ARP. If the response does not
9565 			 * come back, ARP frees the packet. For this reason,
9566 			 * we can't REFHOLD the bucket of save_ire to prevent
9567 			 * deletions. We may not be able to REFRELE the
9568 			 * bucket if the response never comes back.
9569 			 * Thus, before adding the ire, ire_add_v4 will make
9570 			 * sure that the interface route does not get deleted.
9571 			 * This is the only case unlike ip_newroute_v6,
9572 			 * ip_newroute_ipif_v6 where we can always prevent
9573 			 * deletions because ire_add_then_send is called after
9574 			 * creating the IRE.
9575 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9576 			 * does not add this IRE into the IRE CACHE.
9577 			 */
9578 			ASSERT(ire->ire_mp != NULL);
9579 			ire->ire_mp->b_cont = first_mp;
9580 			/* Have saved_mp handy, for cleanup if canput fails */
9581 			saved_mp = mp;
9582 			mp = copyb(res_mp);
9583 			if (mp == NULL) {
9584 				/* Prepare for cleanup */
9585 				mp = saved_mp; /* pkt */
9586 				ire_delete(ire); /* ire_mp */
9587 				ire = NULL;
9588 				if (copy_mp != NULL) {
9589 					MULTIRT_DEBUG_UNTAG(copy_mp);
9590 					freemsg(copy_mp);
9591 					copy_mp = NULL;
9592 				}
9593 				break;
9594 			}
9595 			linkb(mp, ire->ire_mp);
9596 
9597 			/*
9598 			 * Fill in the source and dest addrs for the resolver.
9599 			 * NOTE: this depends on memory layouts imposed by
9600 			 * ill_init().
9601 			 */
9602 			areq = (areq_t *)mp->b_rptr;
9603 			addrp = (ipaddr_t *)((char *)areq +
9604 			    areq->areq_sender_addr_offset);
9605 			*addrp = ire->ire_src_addr;
9606 			addrp = (ipaddr_t *)((char *)areq +
9607 			    areq->areq_target_addr_offset);
9608 			*addrp = dst;
9609 			/* Up to the resolver. */
9610 			if (canputnext(dst_ill->ill_rq) &&
9611 			    !(dst_ill->ill_arp_closing)) {
9612 				putnext(dst_ill->ill_rq, mp);
9613 				/*
9614 				 * The response will come back in ip_wput
9615 				 * with db_type IRE_DB_TYPE.
9616 				 */
9617 			} else {
9618 				mp->b_cont = NULL;
9619 				freeb(mp); /* areq */
9620 				ire_delete(ire); /* ire_mp */
9621 				saved_mp->b_next = NULL;
9622 				saved_mp->b_prev = NULL;
9623 				freemsg(first_mp); /* pkt */
9624 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9625 			}
9626 
9627 			if (fire != NULL) {
9628 				ire_refrele(fire);
9629 				fire = NULL;
9630 			}
9631 
9632 
9633 			/*
9634 			 * The resolution loop is re-entered if this was
9635 			 * requested through flags and we actually are
9636 			 * in a multirouting case.
9637 			 */
9638 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9639 				boolean_t need_resolve =
9640 				    ire_multirt_need_resolve(ipha_dst,
9641 				    MBLK_GETLABEL(copy_mp), ipst);
9642 				if (!need_resolve) {
9643 					MULTIRT_DEBUG_UNTAG(copy_mp);
9644 					freemsg(copy_mp);
9645 					copy_mp = NULL;
9646 				} else {
9647 					/*
9648 					 * ipif_lookup_group() calls
9649 					 * ire_lookup_multi() that uses
9650 					 * ire_ftable_lookup() to find
9651 					 * an IRE_INTERFACE for the group.
9652 					 * In the multirt case,
9653 					 * ire_lookup_multi() then invokes
9654 					 * ire_multirt_lookup() to find
9655 					 * the next resolvable ire.
9656 					 * As a result, we obtain an new
9657 					 * interface, derived from the
9658 					 * next ire.
9659 					 */
9660 					ipif_refrele(ipif);
9661 					ipif = ipif_lookup_group(ipha_dst,
9662 					    zoneid, ipst);
9663 					if (ipif != NULL) {
9664 						mp = copy_mp;
9665 						copy_mp = NULL;
9666 						multirt_resolve_next = B_TRUE;
9667 						continue;
9668 					} else {
9669 						freemsg(copy_mp);
9670 					}
9671 				}
9672 			}
9673 			if (ipif != NULL)
9674 				ipif_refrele(ipif);
9675 			ill_refrele(dst_ill);
9676 			ipif_refrele(src_ipif);
9677 			return;
9678 		default:
9679 			break;
9680 		}
9681 	} while (multirt_resolve_next);
9682 
9683 err_ret:
9684 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9685 	if (fire != NULL)
9686 		ire_refrele(fire);
9687 	ipif_refrele(ipif);
9688 	/* Did this packet originate externally? */
9689 	if (dst_ill != NULL)
9690 		ill_refrele(dst_ill);
9691 	if (src_ipif != NULL)
9692 		ipif_refrele(src_ipif);
9693 	if (mp->b_prev || mp->b_next) {
9694 		mp->b_next = NULL;
9695 		mp->b_prev = NULL;
9696 	} else {
9697 		/*
9698 		 * Since ip_wput() isn't close to finished, we fill
9699 		 * in enough of the header for credible error reporting.
9700 		 */
9701 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9702 			/* Failed */
9703 			freemsg(first_mp);
9704 			if (ire != NULL)
9705 				ire_refrele(ire);
9706 			return;
9707 		}
9708 	}
9709 	/*
9710 	 * At this point we will have ire only if RTF_BLACKHOLE
9711 	 * or RTF_REJECT flags are set on the IRE. It will not
9712 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9713 	 */
9714 	if (ire != NULL) {
9715 		if (ire->ire_flags & RTF_BLACKHOLE) {
9716 			ire_refrele(ire);
9717 			freemsg(first_mp);
9718 			return;
9719 		}
9720 		ire_refrele(ire);
9721 	}
9722 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9723 }
9724 
9725 /* Name/Value Table Lookup Routine */
9726 char *
9727 ip_nv_lookup(nv_t *nv, int value)
9728 {
9729 	if (!nv)
9730 		return (NULL);
9731 	for (; nv->nv_name; nv++) {
9732 		if (nv->nv_value == value)
9733 			return (nv->nv_name);
9734 	}
9735 	return ("unknown");
9736 }
9737 
9738 /*
9739  * This is a module open, i.e. this is a control stream for access
9740  * to a DLPI device.  We allocate an ill_t as the instance data in
9741  * this case.
9742  */
9743 int
9744 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9745 {
9746 	ill_t	*ill;
9747 	int	err;
9748 	zoneid_t zoneid;
9749 	netstack_t *ns;
9750 	ip_stack_t *ipst;
9751 
9752 	/*
9753 	 * Prevent unprivileged processes from pushing IP so that
9754 	 * they can't send raw IP.
9755 	 */
9756 	if (secpolicy_net_rawaccess(credp) != 0)
9757 		return (EPERM);
9758 
9759 	ns = netstack_find_by_cred(credp);
9760 	ASSERT(ns != NULL);
9761 	ipst = ns->netstack_ip;
9762 	ASSERT(ipst != NULL);
9763 
9764 	/*
9765 	 * For exclusive stacks we set the zoneid to zero
9766 	 * to make IP operate as if in the global zone.
9767 	 */
9768 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9769 		zoneid = GLOBAL_ZONEID;
9770 	else
9771 		zoneid = crgetzoneid(credp);
9772 
9773 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9774 	q->q_ptr = WR(q)->q_ptr = ill;
9775 	ill->ill_ipst = ipst;
9776 	ill->ill_zoneid = zoneid;
9777 
9778 	/*
9779 	 * ill_init initializes the ill fields and then sends down
9780 	 * down a DL_INFO_REQ after calling qprocson.
9781 	 */
9782 	err = ill_init(q, ill);
9783 	if (err != 0) {
9784 		mi_free(ill);
9785 		netstack_rele(ipst->ips_netstack);
9786 		q->q_ptr = NULL;
9787 		WR(q)->q_ptr = NULL;
9788 		return (err);
9789 	}
9790 
9791 	/* ill_init initializes the ipsq marking this thread as writer */
9792 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9793 	/* Wait for the DL_INFO_ACK */
9794 	mutex_enter(&ill->ill_lock);
9795 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9796 		/*
9797 		 * Return value of 0 indicates a pending signal.
9798 		 */
9799 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9800 		if (err == 0) {
9801 			mutex_exit(&ill->ill_lock);
9802 			(void) ip_close(q, 0);
9803 			return (EINTR);
9804 		}
9805 	}
9806 	mutex_exit(&ill->ill_lock);
9807 
9808 	/*
9809 	 * ip_rput_other could have set an error  in ill_error on
9810 	 * receipt of M_ERROR.
9811 	 */
9812 
9813 	err = ill->ill_error;
9814 	if (err != 0) {
9815 		(void) ip_close(q, 0);
9816 		return (err);
9817 	}
9818 
9819 	ill->ill_credp = credp;
9820 	crhold(credp);
9821 
9822 	mutex_enter(&ipst->ips_ip_mi_lock);
9823 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9824 	    credp);
9825 	mutex_exit(&ipst->ips_ip_mi_lock);
9826 	if (err) {
9827 		(void) ip_close(q, 0);
9828 		return (err);
9829 	}
9830 	return (0);
9831 }
9832 
9833 /* IP open routine. */
9834 int
9835 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9836 {
9837 	conn_t 		*connp;
9838 	major_t		maj;
9839 	zoneid_t	zoneid;
9840 	netstack_t	*ns;
9841 	ip_stack_t	*ipst;
9842 
9843 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9844 
9845 	/* Allow reopen. */
9846 	if (q->q_ptr != NULL)
9847 		return (0);
9848 
9849 	if (sflag & MODOPEN) {
9850 		/* This is a module open */
9851 		return (ip_modopen(q, devp, flag, sflag, credp));
9852 	}
9853 
9854 	ns = netstack_find_by_cred(credp);
9855 	ASSERT(ns != NULL);
9856 	ipst = ns->netstack_ip;
9857 	ASSERT(ipst != NULL);
9858 
9859 	/*
9860 	 * For exclusive stacks we set the zoneid to zero
9861 	 * to make IP operate as if in the global zone.
9862 	 */
9863 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9864 		zoneid = GLOBAL_ZONEID;
9865 	else
9866 		zoneid = crgetzoneid(credp);
9867 
9868 	/*
9869 	 * We are opening as a device. This is an IP client stream, and we
9870 	 * allocate an conn_t as the instance data.
9871 	 */
9872 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9873 
9874 	/*
9875 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9876 	 * done by netstack_find_by_cred()
9877 	 */
9878 	netstack_rele(ipst->ips_netstack);
9879 
9880 	connp->conn_zoneid = zoneid;
9881 
9882 	connp->conn_upq = q;
9883 	q->q_ptr = WR(q)->q_ptr = connp;
9884 
9885 	if (flag & SO_SOCKSTR)
9886 		connp->conn_flags |= IPCL_SOCKET;
9887 
9888 	/* Minor tells us which /dev entry was opened */
9889 	if (geteminor(*devp) == IPV6_MINOR) {
9890 		connp->conn_flags |= IPCL_ISV6;
9891 		connp->conn_af_isv6 = B_TRUE;
9892 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
9893 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9894 	} else {
9895 		connp->conn_af_isv6 = B_FALSE;
9896 		connp->conn_pkt_isv6 = B_FALSE;
9897 	}
9898 
9899 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9900 		/* CONN_DEC_REF takes care of netstack_rele() */
9901 		q->q_ptr = WR(q)->q_ptr = NULL;
9902 		CONN_DEC_REF(connp);
9903 		return (EBUSY);
9904 	}
9905 
9906 	maj = getemajor(*devp);
9907 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9908 
9909 	/*
9910 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9911 	 */
9912 	connp->conn_cred = credp;
9913 	crhold(connp->conn_cred);
9914 
9915 	/*
9916 	 * If the caller has the process-wide flag set, then default to MAC
9917 	 * exempt mode.  This allows read-down to unlabeled hosts.
9918 	 */
9919 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9920 		connp->conn_mac_exempt = B_TRUE;
9921 
9922 	/*
9923 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9924 	 * administrative ops.  In these cases, we just need a normal conn_t
9925 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9926 	 * an error will be returned.
9927 	 */
9928 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9929 		connp->conn_rq = q;
9930 		connp->conn_wq = WR(q);
9931 	} else {
9932 		connp->conn_ulp = IPPROTO_SCTP;
9933 		connp->conn_rq = connp->conn_wq = NULL;
9934 	}
9935 	/* Non-zero default values */
9936 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9937 
9938 	/*
9939 	 * Make the conn globally visible to walkers
9940 	 */
9941 	ASSERT(connp->conn_ref == 1);
9942 	mutex_enter(&connp->conn_lock);
9943 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9944 	mutex_exit(&connp->conn_lock);
9945 
9946 	qprocson(q);
9947 
9948 	return (0);
9949 }
9950 
9951 /*
9952  * Change q_qinfo based on the value of isv6.
9953  * This can not called on an ill queue.
9954  * Note that there is no race since either q_qinfo works for conn queues - it
9955  * is just an optimization to enter the best wput routine directly.
9956  */
9957 void
9958 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
9959 {
9960 	ASSERT(q->q_flag & QREADR);
9961 	ASSERT(WR(q)->q_next == NULL);
9962 	ASSERT(q->q_ptr != NULL);
9963 
9964 	if (minor == IPV6_MINOR)  {
9965 		if (bump_mib) {
9966 			BUMP_MIB(&ipst->ips_ip6_mib,
9967 			    ipIfStatsOutSwitchIPVersion);
9968 		}
9969 		q->q_qinfo = &rinit_ipv6;
9970 		WR(q)->q_qinfo = &winit_ipv6;
9971 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9972 	} else {
9973 		if (bump_mib) {
9974 			BUMP_MIB(&ipst->ips_ip_mib,
9975 			    ipIfStatsOutSwitchIPVersion);
9976 		}
9977 		q->q_qinfo = &iprinit;
9978 		WR(q)->q_qinfo = &ipwinit;
9979 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9980 	}
9981 
9982 }
9983 
9984 /*
9985  * See if IPsec needs loading because of the options in mp.
9986  */
9987 static boolean_t
9988 ipsec_opt_present(mblk_t *mp)
9989 {
9990 	uint8_t *optcp, *next_optcp, *opt_endcp;
9991 	struct opthdr *opt;
9992 	struct T_opthdr *topt;
9993 	int opthdr_len;
9994 	t_uscalar_t optname, optlevel;
9995 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9996 	ipsec_req_t *ipsr;
9997 
9998 	/*
9999 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
10000 	 * return TRUE.
10001 	 */
10002 
10003 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
10004 	opt_endcp = optcp + tor->OPT_length;
10005 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
10006 		opthdr_len = sizeof (struct T_opthdr);
10007 	} else {		/* O_OPTMGMT_REQ */
10008 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
10009 		opthdr_len = sizeof (struct opthdr);
10010 	}
10011 	for (; optcp < opt_endcp; optcp = next_optcp) {
10012 		if (optcp + opthdr_len > opt_endcp)
10013 			return (B_FALSE);	/* Not enough option header. */
10014 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
10015 			topt = (struct T_opthdr *)optcp;
10016 			optlevel = topt->level;
10017 			optname = topt->name;
10018 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
10019 		} else {
10020 			opt = (struct opthdr *)optcp;
10021 			optlevel = opt->level;
10022 			optname = opt->name;
10023 			next_optcp = optcp + opthdr_len +
10024 			    _TPI_ALIGN_OPT(opt->len);
10025 		}
10026 		if ((next_optcp < optcp) || /* wraparound pointer space */
10027 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10028 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10029 			return (B_FALSE); /* bad option buffer */
10030 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10031 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10032 			/*
10033 			 * Check to see if it's an all-bypass or all-zeroes
10034 			 * IPsec request.  Don't bother loading IPsec if
10035 			 * the socket doesn't want to use it.  (A good example
10036 			 * is a bypass request.)
10037 			 *
10038 			 * Basically, if any of the non-NEVER bits are set,
10039 			 * load IPsec.
10040 			 */
10041 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10042 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10043 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10044 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10045 			    != 0)
10046 				return (B_TRUE);
10047 		}
10048 	}
10049 	return (B_FALSE);
10050 }
10051 
10052 /*
10053  * If conn is is waiting for ipsec to finish loading, kick it.
10054  */
10055 /* ARGSUSED */
10056 static void
10057 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10058 {
10059 	t_scalar_t	optreq_prim;
10060 	mblk_t		*mp;
10061 	cred_t		*cr;
10062 	int		err = 0;
10063 
10064 	/*
10065 	 * This function is called, after ipsec loading is complete.
10066 	 * Since IP checks exclusively and atomically (i.e it prevents
10067 	 * ipsec load from completing until ip_optcom_req completes)
10068 	 * whether ipsec load is complete, there cannot be a race with IP
10069 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10070 	 */
10071 	mutex_enter(&connp->conn_lock);
10072 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10073 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10074 		mp = connp->conn_ipsec_opt_mp;
10075 		connp->conn_ipsec_opt_mp = NULL;
10076 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10077 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10078 		mutex_exit(&connp->conn_lock);
10079 
10080 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10081 
10082 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10083 		if (optreq_prim == T_OPTMGMT_REQ) {
10084 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10085 			    &ip_opt_obj);
10086 		} else {
10087 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10088 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10089 			    &ip_opt_obj);
10090 		}
10091 		if (err != EINPROGRESS)
10092 			CONN_OPER_PENDING_DONE(connp);
10093 		return;
10094 	}
10095 	mutex_exit(&connp->conn_lock);
10096 }
10097 
10098 /*
10099  * Called from the ipsec_loader thread, outside any perimeter, to tell
10100  * ip qenable any of the queues waiting for the ipsec loader to
10101  * complete.
10102  */
10103 void
10104 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10105 {
10106 	netstack_t *ns = ipss->ipsec_netstack;
10107 
10108 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10109 }
10110 
10111 /*
10112  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10113  * determines the grp on which it has to become exclusive, queues the mp
10114  * and sq draining restarts the optmgmt
10115  */
10116 static boolean_t
10117 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10118 {
10119 	conn_t *connp = Q_TO_CONN(q);
10120 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10121 
10122 	/*
10123 	 * Take IPsec requests and treat them special.
10124 	 */
10125 	if (ipsec_opt_present(mp)) {
10126 		/* First check if IPsec is loaded. */
10127 		mutex_enter(&ipss->ipsec_loader_lock);
10128 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10129 			mutex_exit(&ipss->ipsec_loader_lock);
10130 			return (B_FALSE);
10131 		}
10132 		mutex_enter(&connp->conn_lock);
10133 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10134 
10135 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10136 		connp->conn_ipsec_opt_mp = mp;
10137 		mutex_exit(&connp->conn_lock);
10138 		mutex_exit(&ipss->ipsec_loader_lock);
10139 
10140 		ipsec_loader_loadnow(ipss);
10141 		return (B_TRUE);
10142 	}
10143 	return (B_FALSE);
10144 }
10145 
10146 /*
10147  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10148  * all of them are copied to the conn_t. If the req is "zero", the policy is
10149  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10150  * fields.
10151  * We keep only the latest setting of the policy and thus policy setting
10152  * is not incremental/cumulative.
10153  *
10154  * Requests to set policies with multiple alternative actions will
10155  * go through a different API.
10156  */
10157 int
10158 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10159 {
10160 	uint_t ah_req = 0;
10161 	uint_t esp_req = 0;
10162 	uint_t se_req = 0;
10163 	ipsec_selkey_t sel;
10164 	ipsec_act_t *actp = NULL;
10165 	uint_t nact;
10166 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10167 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10168 	ipsec_policy_root_t *pr;
10169 	ipsec_policy_head_t *ph;
10170 	int fam;
10171 	boolean_t is_pol_reset;
10172 	int error = 0;
10173 	netstack_t	*ns = connp->conn_netstack;
10174 	ip_stack_t	*ipst = ns->netstack_ip;
10175 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10176 
10177 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10178 
10179 	/*
10180 	 * The IP_SEC_OPT option does not allow variable length parameters,
10181 	 * hence a request cannot be NULL.
10182 	 */
10183 	if (req == NULL)
10184 		return (EINVAL);
10185 
10186 	ah_req = req->ipsr_ah_req;
10187 	esp_req = req->ipsr_esp_req;
10188 	se_req = req->ipsr_self_encap_req;
10189 
10190 	/*
10191 	 * Are we dealing with a request to reset the policy (i.e.
10192 	 * zero requests).
10193 	 */
10194 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10195 	    (esp_req & REQ_MASK) == 0 &&
10196 	    (se_req & REQ_MASK) == 0);
10197 
10198 	if (!is_pol_reset) {
10199 		/*
10200 		 * If we couldn't load IPsec, fail with "protocol
10201 		 * not supported".
10202 		 * IPsec may not have been loaded for a request with zero
10203 		 * policies, so we don't fail in this case.
10204 		 */
10205 		mutex_enter(&ipss->ipsec_loader_lock);
10206 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10207 			mutex_exit(&ipss->ipsec_loader_lock);
10208 			return (EPROTONOSUPPORT);
10209 		}
10210 		mutex_exit(&ipss->ipsec_loader_lock);
10211 
10212 		/*
10213 		 * Test for valid requests. Invalid algorithms
10214 		 * need to be tested by IPsec code because new
10215 		 * algorithms can be added dynamically.
10216 		 */
10217 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10218 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10219 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10220 			return (EINVAL);
10221 		}
10222 
10223 		/*
10224 		 * Only privileged users can issue these
10225 		 * requests.
10226 		 */
10227 		if (((ah_req & IPSEC_PREF_NEVER) ||
10228 		    (esp_req & IPSEC_PREF_NEVER) ||
10229 		    (se_req & IPSEC_PREF_NEVER)) &&
10230 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10231 			return (EPERM);
10232 		}
10233 
10234 		/*
10235 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10236 		 * are mutually exclusive.
10237 		 */
10238 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10239 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10240 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10241 			/* Both of them are set */
10242 			return (EINVAL);
10243 		}
10244 	}
10245 
10246 	mutex_enter(&connp->conn_lock);
10247 
10248 	/*
10249 	 * If we have already cached policies in ip_bind_connected*(), don't
10250 	 * let them change now. We cache policies for connections
10251 	 * whose src,dst [addr, port] is known.
10252 	 */
10253 	if (connp->conn_policy_cached) {
10254 		mutex_exit(&connp->conn_lock);
10255 		return (EINVAL);
10256 	}
10257 
10258 	/*
10259 	 * We have a zero policies, reset the connection policy if already
10260 	 * set. This will cause the connection to inherit the
10261 	 * global policy, if any.
10262 	 */
10263 	if (is_pol_reset) {
10264 		if (connp->conn_policy != NULL) {
10265 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10266 			connp->conn_policy = NULL;
10267 		}
10268 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10269 		connp->conn_in_enforce_policy = B_FALSE;
10270 		connp->conn_out_enforce_policy = B_FALSE;
10271 		mutex_exit(&connp->conn_lock);
10272 		return (0);
10273 	}
10274 
10275 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10276 	    ipst->ips_netstack);
10277 	if (ph == NULL)
10278 		goto enomem;
10279 
10280 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10281 	if (actp == NULL)
10282 		goto enomem;
10283 
10284 	/*
10285 	 * Always allocate IPv4 policy entries, since they can also
10286 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10287 	 */
10288 	bzero(&sel, sizeof (sel));
10289 	sel.ipsl_valid = IPSL_IPV4;
10290 
10291 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10292 	    ipst->ips_netstack);
10293 	if (pin4 == NULL)
10294 		goto enomem;
10295 
10296 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10297 	    ipst->ips_netstack);
10298 	if (pout4 == NULL)
10299 		goto enomem;
10300 
10301 	if (connp->conn_pkt_isv6) {
10302 		/*
10303 		 * We're looking at a v6 socket, also allocate the
10304 		 * v6-specific entries...
10305 		 */
10306 		sel.ipsl_valid = IPSL_IPV6;
10307 		pin6 = ipsec_policy_create(&sel, actp, nact,
10308 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10309 		if (pin6 == NULL)
10310 			goto enomem;
10311 
10312 		pout6 = ipsec_policy_create(&sel, actp, nact,
10313 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10314 		if (pout6 == NULL)
10315 			goto enomem;
10316 
10317 		/*
10318 		 * .. and file them away in the right place.
10319 		 */
10320 		fam = IPSEC_AF_V6;
10321 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10322 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10323 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10324 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10325 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10326 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10327 	}
10328 
10329 	ipsec_actvec_free(actp, nact);
10330 
10331 	/*
10332 	 * File the v4 policies.
10333 	 */
10334 	fam = IPSEC_AF_V4;
10335 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10336 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10337 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10338 
10339 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10340 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10341 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10342 
10343 	/*
10344 	 * If the requests need security, set enforce_policy.
10345 	 * If the requests are IPSEC_PREF_NEVER, one should
10346 	 * still set conn_out_enforce_policy so that an ipsec_out
10347 	 * gets attached in ip_wput. This is needed so that
10348 	 * for connections that we don't cache policy in ip_bind,
10349 	 * if global policy matches in ip_wput_attach_policy, we
10350 	 * don't wrongly inherit global policy. Similarly, we need
10351 	 * to set conn_in_enforce_policy also so that we don't verify
10352 	 * policy wrongly.
10353 	 */
10354 	if ((ah_req & REQ_MASK) != 0 ||
10355 	    (esp_req & REQ_MASK) != 0 ||
10356 	    (se_req & REQ_MASK) != 0) {
10357 		connp->conn_in_enforce_policy = B_TRUE;
10358 		connp->conn_out_enforce_policy = B_TRUE;
10359 		connp->conn_flags |= IPCL_CHECK_POLICY;
10360 	}
10361 
10362 	mutex_exit(&connp->conn_lock);
10363 	return (error);
10364 #undef REQ_MASK
10365 
10366 	/*
10367 	 * Common memory-allocation-failure exit path.
10368 	 */
10369 enomem:
10370 	mutex_exit(&connp->conn_lock);
10371 	if (actp != NULL)
10372 		ipsec_actvec_free(actp, nact);
10373 	if (pin4 != NULL)
10374 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10375 	if (pout4 != NULL)
10376 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10377 	if (pin6 != NULL)
10378 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10379 	if (pout6 != NULL)
10380 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10381 	return (ENOMEM);
10382 }
10383 
10384 /*
10385  * Only for options that pass in an IP addr. Currently only V4 options
10386  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10387  * So this function assumes level is IPPROTO_IP
10388  */
10389 int
10390 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10391     mblk_t *first_mp)
10392 {
10393 	ipif_t *ipif = NULL;
10394 	int error;
10395 	ill_t *ill;
10396 	int zoneid;
10397 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10398 
10399 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10400 
10401 	if (addr != INADDR_ANY || checkonly) {
10402 		ASSERT(connp != NULL);
10403 		zoneid = IPCL_ZONEID(connp);
10404 		if (option == IP_NEXTHOP) {
10405 			ipif = ipif_lookup_onlink_addr(addr,
10406 			    connp->conn_zoneid, ipst);
10407 		} else {
10408 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10409 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10410 			    &error, ipst);
10411 		}
10412 		if (ipif == NULL) {
10413 			if (error == EINPROGRESS)
10414 				return (error);
10415 			else if ((option == IP_MULTICAST_IF) ||
10416 			    (option == IP_NEXTHOP))
10417 				return (EHOSTUNREACH);
10418 			else
10419 				return (EINVAL);
10420 		} else if (checkonly) {
10421 			if (option == IP_MULTICAST_IF) {
10422 				ill = ipif->ipif_ill;
10423 				/* not supported by the virtual network iface */
10424 				if (IS_VNI(ill)) {
10425 					ipif_refrele(ipif);
10426 					return (EINVAL);
10427 				}
10428 			}
10429 			ipif_refrele(ipif);
10430 			return (0);
10431 		}
10432 		ill = ipif->ipif_ill;
10433 		mutex_enter(&connp->conn_lock);
10434 		mutex_enter(&ill->ill_lock);
10435 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10436 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10437 			mutex_exit(&ill->ill_lock);
10438 			mutex_exit(&connp->conn_lock);
10439 			ipif_refrele(ipif);
10440 			return (option == IP_MULTICAST_IF ?
10441 			    EHOSTUNREACH : EINVAL);
10442 		}
10443 	} else {
10444 		mutex_enter(&connp->conn_lock);
10445 	}
10446 
10447 	/* None of the options below are supported on the VNI */
10448 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10449 		mutex_exit(&ill->ill_lock);
10450 		mutex_exit(&connp->conn_lock);
10451 		ipif_refrele(ipif);
10452 		return (EINVAL);
10453 	}
10454 
10455 	switch (option) {
10456 	case IP_DONTFAILOVER_IF:
10457 		/*
10458 		 * This option is used by in.mpathd to ensure
10459 		 * that IPMP probe packets only go out on the
10460 		 * test interfaces. in.mpathd sets this option
10461 		 * on the non-failover interfaces.
10462 		 * For backward compatibility, this option
10463 		 * implicitly sets IP_MULTICAST_IF, as used
10464 		 * be done in bind(), so that ip_wput gets
10465 		 * this ipif to send mcast packets.
10466 		 */
10467 		if (ipif != NULL) {
10468 			ASSERT(addr != INADDR_ANY);
10469 			connp->conn_nofailover_ill = ipif->ipif_ill;
10470 			connp->conn_multicast_ipif = ipif;
10471 		} else {
10472 			ASSERT(addr == INADDR_ANY);
10473 			connp->conn_nofailover_ill = NULL;
10474 			connp->conn_multicast_ipif = NULL;
10475 		}
10476 		break;
10477 
10478 	case IP_MULTICAST_IF:
10479 		connp->conn_multicast_ipif = ipif;
10480 		break;
10481 	case IP_NEXTHOP:
10482 		connp->conn_nexthop_v4 = addr;
10483 		connp->conn_nexthop_set = B_TRUE;
10484 		break;
10485 	}
10486 
10487 	if (ipif != NULL) {
10488 		mutex_exit(&ill->ill_lock);
10489 		mutex_exit(&connp->conn_lock);
10490 		ipif_refrele(ipif);
10491 		return (0);
10492 	}
10493 	mutex_exit(&connp->conn_lock);
10494 	/* We succeded in cleared the option */
10495 	return (0);
10496 }
10497 
10498 /*
10499  * For options that pass in an ifindex specifying the ill. V6 options always
10500  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10501  */
10502 int
10503 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10504     int level, int option, mblk_t *first_mp)
10505 {
10506 	ill_t *ill = NULL;
10507 	int error = 0;
10508 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10509 
10510 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10511 	if (ifindex != 0) {
10512 		ASSERT(connp != NULL);
10513 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10514 		    first_mp, ip_restart_optmgmt, &error, ipst);
10515 		if (ill != NULL) {
10516 			if (checkonly) {
10517 				/* not supported by the virtual network iface */
10518 				if (IS_VNI(ill)) {
10519 					ill_refrele(ill);
10520 					return (EINVAL);
10521 				}
10522 				ill_refrele(ill);
10523 				return (0);
10524 			}
10525 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10526 			    0, NULL)) {
10527 				ill_refrele(ill);
10528 				ill = NULL;
10529 				mutex_enter(&connp->conn_lock);
10530 				goto setit;
10531 			}
10532 			mutex_enter(&connp->conn_lock);
10533 			mutex_enter(&ill->ill_lock);
10534 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10535 				mutex_exit(&ill->ill_lock);
10536 				mutex_exit(&connp->conn_lock);
10537 				ill_refrele(ill);
10538 				ill = NULL;
10539 				mutex_enter(&connp->conn_lock);
10540 			}
10541 			goto setit;
10542 		} else if (error == EINPROGRESS) {
10543 			return (error);
10544 		} else {
10545 			error = 0;
10546 		}
10547 	}
10548 	mutex_enter(&connp->conn_lock);
10549 setit:
10550 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10551 
10552 	/*
10553 	 * The options below assume that the ILL (if any) transmits and/or
10554 	 * receives traffic. Neither of which is true for the virtual network
10555 	 * interface, so fail setting these on a VNI.
10556 	 */
10557 	if (IS_VNI(ill)) {
10558 		ASSERT(ill != NULL);
10559 		mutex_exit(&ill->ill_lock);
10560 		mutex_exit(&connp->conn_lock);
10561 		ill_refrele(ill);
10562 		return (EINVAL);
10563 	}
10564 
10565 	if (level == IPPROTO_IP) {
10566 		switch (option) {
10567 		case IP_BOUND_IF:
10568 			connp->conn_incoming_ill = ill;
10569 			connp->conn_outgoing_ill = ill;
10570 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10571 			    0 : ifindex;
10572 			break;
10573 
10574 		case IP_XMIT_IF:
10575 			/*
10576 			 * Similar to IP_BOUND_IF, but this only
10577 			 * determines the outgoing interface for
10578 			 * unicast packets. Also no IRE_CACHE entry
10579 			 * is added for the destination of the
10580 			 * outgoing packets.
10581 			 */
10582 			connp->conn_xmit_if_ill = ill;
10583 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10584 			    0 : ifindex;
10585 			break;
10586 
10587 		case IP_MULTICAST_IF:
10588 			/*
10589 			 * This option is an internal special. The socket
10590 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10591 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10592 			 * specifies an ifindex and we try first on V6 ill's.
10593 			 * If we don't find one, we they try using on v4 ill's
10594 			 * intenally and we come here.
10595 			 */
10596 			if (!checkonly && ill != NULL) {
10597 				ipif_t	*ipif;
10598 				ipif = ill->ill_ipif;
10599 
10600 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10601 					mutex_exit(&ill->ill_lock);
10602 					mutex_exit(&connp->conn_lock);
10603 					ill_refrele(ill);
10604 					ill = NULL;
10605 					mutex_enter(&connp->conn_lock);
10606 				} else {
10607 					connp->conn_multicast_ipif = ipif;
10608 				}
10609 			}
10610 			break;
10611 		}
10612 	} else {
10613 		switch (option) {
10614 		case IPV6_BOUND_IF:
10615 			connp->conn_incoming_ill = ill;
10616 			connp->conn_outgoing_ill = ill;
10617 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10618 			    0 : ifindex;
10619 			break;
10620 
10621 		case IPV6_BOUND_PIF:
10622 			/*
10623 			 * Limit all transmit to this ill.
10624 			 * Unlike IPV6_BOUND_IF, using this option
10625 			 * prevents load spreading and failover from
10626 			 * happening when the interface is part of the
10627 			 * group. That's why we don't need to remember
10628 			 * the ifindex in orig_bound_ifindex as in
10629 			 * IPV6_BOUND_IF.
10630 			 */
10631 			connp->conn_outgoing_pill = ill;
10632 			break;
10633 
10634 		case IPV6_DONTFAILOVER_IF:
10635 			/*
10636 			 * This option is used by in.mpathd to ensure
10637 			 * that IPMP probe packets only go out on the
10638 			 * test interfaces. in.mpathd sets this option
10639 			 * on the non-failover interfaces.
10640 			 */
10641 			connp->conn_nofailover_ill = ill;
10642 			/*
10643 			 * For backward compatibility, this option
10644 			 * implicitly sets ip_multicast_ill as used in
10645 			 * IP_MULTICAST_IF so that ip_wput gets
10646 			 * this ipif to send mcast packets.
10647 			 */
10648 			connp->conn_multicast_ill = ill;
10649 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10650 			    0 : ifindex;
10651 			break;
10652 
10653 		case IPV6_MULTICAST_IF:
10654 			/*
10655 			 * Set conn_multicast_ill to be the IPv6 ill.
10656 			 * Set conn_multicast_ipif to be an IPv4 ipif
10657 			 * for ifindex to make IPv4 mapped addresses
10658 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10659 			 * Even if no IPv6 ill exists for the ifindex
10660 			 * we need to check for an IPv4 ifindex in order
10661 			 * for this to work with mapped addresses. In that
10662 			 * case only set conn_multicast_ipif.
10663 			 */
10664 			if (!checkonly) {
10665 				if (ifindex == 0) {
10666 					connp->conn_multicast_ill = NULL;
10667 					connp->conn_orig_multicast_ifindex = 0;
10668 					connp->conn_multicast_ipif = NULL;
10669 				} else if (ill != NULL) {
10670 					connp->conn_multicast_ill = ill;
10671 					connp->conn_orig_multicast_ifindex =
10672 					    ifindex;
10673 				}
10674 			}
10675 			break;
10676 		}
10677 	}
10678 
10679 	if (ill != NULL) {
10680 		mutex_exit(&ill->ill_lock);
10681 		mutex_exit(&connp->conn_lock);
10682 		ill_refrele(ill);
10683 		return (0);
10684 	}
10685 	mutex_exit(&connp->conn_lock);
10686 	/*
10687 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10688 	 * locate the ill and could not set the option (ifindex != 0)
10689 	 */
10690 	return (ifindex == 0 ? 0 : EINVAL);
10691 }
10692 
10693 /* This routine sets socket options. */
10694 /* ARGSUSED */
10695 int
10696 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10697     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10698     void *dummy, cred_t *cr, mblk_t *first_mp)
10699 {
10700 	int		*i1 = (int *)invalp;
10701 	conn_t		*connp = Q_TO_CONN(q);
10702 	int		error = 0;
10703 	boolean_t	checkonly;
10704 	ire_t		*ire;
10705 	boolean_t	found;
10706 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10707 
10708 	switch (optset_context) {
10709 
10710 	case SETFN_OPTCOM_CHECKONLY:
10711 		checkonly = B_TRUE;
10712 		/*
10713 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10714 		 * inlen != 0 implies value supplied and
10715 		 * 	we have to "pretend" to set it.
10716 		 * inlen == 0 implies that there is no
10717 		 * 	value part in T_CHECK request and just validation
10718 		 * done elsewhere should be enough, we just return here.
10719 		 */
10720 		if (inlen == 0) {
10721 			*outlenp = 0;
10722 			return (0);
10723 		}
10724 		break;
10725 	case SETFN_OPTCOM_NEGOTIATE:
10726 	case SETFN_UD_NEGOTIATE:
10727 	case SETFN_CONN_NEGOTIATE:
10728 		checkonly = B_FALSE;
10729 		break;
10730 	default:
10731 		/*
10732 		 * We should never get here
10733 		 */
10734 		*outlenp = 0;
10735 		return (EINVAL);
10736 	}
10737 
10738 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10739 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10740 
10741 	/*
10742 	 * For fixed length options, no sanity check
10743 	 * of passed in length is done. It is assumed *_optcom_req()
10744 	 * routines do the right thing.
10745 	 */
10746 
10747 	switch (level) {
10748 	case SOL_SOCKET:
10749 		/*
10750 		 * conn_lock protects the bitfields, and is used to
10751 		 * set the fields atomically.
10752 		 */
10753 		switch (name) {
10754 		case SO_BROADCAST:
10755 			if (!checkonly) {
10756 				/* TODO: use value someplace? */
10757 				mutex_enter(&connp->conn_lock);
10758 				connp->conn_broadcast = *i1 ? 1 : 0;
10759 				mutex_exit(&connp->conn_lock);
10760 			}
10761 			break;	/* goto sizeof (int) option return */
10762 		case SO_USELOOPBACK:
10763 			if (!checkonly) {
10764 				/* TODO: use value someplace? */
10765 				mutex_enter(&connp->conn_lock);
10766 				connp->conn_loopback = *i1 ? 1 : 0;
10767 				mutex_exit(&connp->conn_lock);
10768 			}
10769 			break;	/* goto sizeof (int) option return */
10770 		case SO_DONTROUTE:
10771 			if (!checkonly) {
10772 				mutex_enter(&connp->conn_lock);
10773 				connp->conn_dontroute = *i1 ? 1 : 0;
10774 				mutex_exit(&connp->conn_lock);
10775 			}
10776 			break;	/* goto sizeof (int) option return */
10777 		case SO_REUSEADDR:
10778 			if (!checkonly) {
10779 				mutex_enter(&connp->conn_lock);
10780 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10781 				mutex_exit(&connp->conn_lock);
10782 			}
10783 			break;	/* goto sizeof (int) option return */
10784 		case SO_PROTOTYPE:
10785 			if (!checkonly) {
10786 				mutex_enter(&connp->conn_lock);
10787 				connp->conn_proto = *i1;
10788 				mutex_exit(&connp->conn_lock);
10789 			}
10790 			break;	/* goto sizeof (int) option return */
10791 		case SO_ALLZONES:
10792 			if (!checkonly) {
10793 				mutex_enter(&connp->conn_lock);
10794 				if (IPCL_IS_BOUND(connp)) {
10795 					mutex_exit(&connp->conn_lock);
10796 					return (EINVAL);
10797 				}
10798 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10799 				mutex_exit(&connp->conn_lock);
10800 			}
10801 			break;	/* goto sizeof (int) option return */
10802 		case SO_ANON_MLP:
10803 			if (!checkonly) {
10804 				mutex_enter(&connp->conn_lock);
10805 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10806 				mutex_exit(&connp->conn_lock);
10807 			}
10808 			break;	/* goto sizeof (int) option return */
10809 		case SO_MAC_EXEMPT:
10810 			if (secpolicy_net_mac_aware(cr) != 0 ||
10811 			    IPCL_IS_BOUND(connp))
10812 				return (EACCES);
10813 			if (!checkonly) {
10814 				mutex_enter(&connp->conn_lock);
10815 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10816 				mutex_exit(&connp->conn_lock);
10817 			}
10818 			break;	/* goto sizeof (int) option return */
10819 		default:
10820 			/*
10821 			 * "soft" error (negative)
10822 			 * option not handled at this level
10823 			 * Note: Do not modify *outlenp
10824 			 */
10825 			return (-EINVAL);
10826 		}
10827 		break;
10828 	case IPPROTO_IP:
10829 		switch (name) {
10830 		case IP_NEXTHOP:
10831 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10832 				return (EPERM);
10833 			/* FALLTHRU */
10834 		case IP_MULTICAST_IF:
10835 		case IP_DONTFAILOVER_IF: {
10836 			ipaddr_t addr = *i1;
10837 
10838 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10839 			    first_mp);
10840 			if (error != 0)
10841 				return (error);
10842 			break;	/* goto sizeof (int) option return */
10843 		}
10844 
10845 		case IP_MULTICAST_TTL:
10846 			/* Recorded in transport above IP */
10847 			*outvalp = *invalp;
10848 			*outlenp = sizeof (uchar_t);
10849 			return (0);
10850 		case IP_MULTICAST_LOOP:
10851 			if (!checkonly) {
10852 				mutex_enter(&connp->conn_lock);
10853 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10854 				mutex_exit(&connp->conn_lock);
10855 			}
10856 			*outvalp = *invalp;
10857 			*outlenp = sizeof (uchar_t);
10858 			return (0);
10859 		case IP_ADD_MEMBERSHIP:
10860 		case MCAST_JOIN_GROUP:
10861 		case IP_DROP_MEMBERSHIP:
10862 		case MCAST_LEAVE_GROUP: {
10863 			struct ip_mreq *mreqp;
10864 			struct group_req *greqp;
10865 			ire_t *ire;
10866 			boolean_t done = B_FALSE;
10867 			ipaddr_t group, ifaddr;
10868 			struct sockaddr_in *sin;
10869 			uint32_t *ifindexp;
10870 			boolean_t mcast_opt = B_TRUE;
10871 			mcast_record_t fmode;
10872 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10873 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10874 
10875 			switch (name) {
10876 			case IP_ADD_MEMBERSHIP:
10877 				mcast_opt = B_FALSE;
10878 				/* FALLTHRU */
10879 			case MCAST_JOIN_GROUP:
10880 				fmode = MODE_IS_EXCLUDE;
10881 				optfn = ip_opt_add_group;
10882 				break;
10883 
10884 			case IP_DROP_MEMBERSHIP:
10885 				mcast_opt = B_FALSE;
10886 				/* FALLTHRU */
10887 			case MCAST_LEAVE_GROUP:
10888 				fmode = MODE_IS_INCLUDE;
10889 				optfn = ip_opt_delete_group;
10890 				break;
10891 			}
10892 
10893 			if (mcast_opt) {
10894 				greqp = (struct group_req *)i1;
10895 				sin = (struct sockaddr_in *)&greqp->gr_group;
10896 				if (sin->sin_family != AF_INET) {
10897 					*outlenp = 0;
10898 					return (ENOPROTOOPT);
10899 				}
10900 				group = (ipaddr_t)sin->sin_addr.s_addr;
10901 				ifaddr = INADDR_ANY;
10902 				ifindexp = &greqp->gr_interface;
10903 			} else {
10904 				mreqp = (struct ip_mreq *)i1;
10905 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10906 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10907 				ifindexp = NULL;
10908 			}
10909 
10910 			/*
10911 			 * In the multirouting case, we need to replicate
10912 			 * the request on all interfaces that will take part
10913 			 * in replication.  We do so because multirouting is
10914 			 * reflective, thus we will probably receive multi-
10915 			 * casts on those interfaces.
10916 			 * The ip_multirt_apply_membership() succeeds if the
10917 			 * operation succeeds on at least one interface.
10918 			 */
10919 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10920 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10921 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10922 			if (ire != NULL) {
10923 				if (ire->ire_flags & RTF_MULTIRT) {
10924 					error = ip_multirt_apply_membership(
10925 					    optfn, ire, connp, checkonly, group,
10926 					    fmode, INADDR_ANY, first_mp);
10927 					done = B_TRUE;
10928 				}
10929 				ire_refrele(ire);
10930 			}
10931 			if (!done) {
10932 				error = optfn(connp, checkonly, group, ifaddr,
10933 				    ifindexp, fmode, INADDR_ANY, first_mp);
10934 			}
10935 			if (error) {
10936 				/*
10937 				 * EINPROGRESS is a soft error, needs retry
10938 				 * so don't make *outlenp zero.
10939 				 */
10940 				if (error != EINPROGRESS)
10941 					*outlenp = 0;
10942 				return (error);
10943 			}
10944 			/* OK return - copy input buffer into output buffer */
10945 			if (invalp != outvalp) {
10946 				/* don't trust bcopy for identical src/dst */
10947 				bcopy(invalp, outvalp, inlen);
10948 			}
10949 			*outlenp = inlen;
10950 			return (0);
10951 		}
10952 		case IP_BLOCK_SOURCE:
10953 		case IP_UNBLOCK_SOURCE:
10954 		case IP_ADD_SOURCE_MEMBERSHIP:
10955 		case IP_DROP_SOURCE_MEMBERSHIP:
10956 		case MCAST_BLOCK_SOURCE:
10957 		case MCAST_UNBLOCK_SOURCE:
10958 		case MCAST_JOIN_SOURCE_GROUP:
10959 		case MCAST_LEAVE_SOURCE_GROUP: {
10960 			struct ip_mreq_source *imreqp;
10961 			struct group_source_req *gsreqp;
10962 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10963 			uint32_t ifindex = 0;
10964 			mcast_record_t fmode;
10965 			struct sockaddr_in *sin;
10966 			ire_t *ire;
10967 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10968 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10969 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10970 
10971 			switch (name) {
10972 			case IP_BLOCK_SOURCE:
10973 				mcast_opt = B_FALSE;
10974 				/* FALLTHRU */
10975 			case MCAST_BLOCK_SOURCE:
10976 				fmode = MODE_IS_EXCLUDE;
10977 				optfn = ip_opt_add_group;
10978 				break;
10979 
10980 			case IP_UNBLOCK_SOURCE:
10981 				mcast_opt = B_FALSE;
10982 				/* FALLTHRU */
10983 			case MCAST_UNBLOCK_SOURCE:
10984 				fmode = MODE_IS_EXCLUDE;
10985 				optfn = ip_opt_delete_group;
10986 				break;
10987 
10988 			case IP_ADD_SOURCE_MEMBERSHIP:
10989 				mcast_opt = B_FALSE;
10990 				/* FALLTHRU */
10991 			case MCAST_JOIN_SOURCE_GROUP:
10992 				fmode = MODE_IS_INCLUDE;
10993 				optfn = ip_opt_add_group;
10994 				break;
10995 
10996 			case IP_DROP_SOURCE_MEMBERSHIP:
10997 				mcast_opt = B_FALSE;
10998 				/* FALLTHRU */
10999 			case MCAST_LEAVE_SOURCE_GROUP:
11000 				fmode = MODE_IS_INCLUDE;
11001 				optfn = ip_opt_delete_group;
11002 				break;
11003 			}
11004 
11005 			if (mcast_opt) {
11006 				gsreqp = (struct group_source_req *)i1;
11007 				if (gsreqp->gsr_group.ss_family != AF_INET) {
11008 					*outlenp = 0;
11009 					return (ENOPROTOOPT);
11010 				}
11011 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
11012 				grp = (ipaddr_t)sin->sin_addr.s_addr;
11013 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
11014 				src = (ipaddr_t)sin->sin_addr.s_addr;
11015 				ifindex = gsreqp->gsr_interface;
11016 			} else {
11017 				imreqp = (struct ip_mreq_source *)i1;
11018 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11019 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11020 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11021 			}
11022 
11023 			/*
11024 			 * In the multirouting case, we need to replicate
11025 			 * the request as noted in the mcast cases above.
11026 			 */
11027 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11028 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11029 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11030 			if (ire != NULL) {
11031 				if (ire->ire_flags & RTF_MULTIRT) {
11032 					error = ip_multirt_apply_membership(
11033 					    optfn, ire, connp, checkonly, grp,
11034 					    fmode, src, first_mp);
11035 					done = B_TRUE;
11036 				}
11037 				ire_refrele(ire);
11038 			}
11039 			if (!done) {
11040 				error = optfn(connp, checkonly, grp, ifaddr,
11041 				    &ifindex, fmode, src, first_mp);
11042 			}
11043 			if (error != 0) {
11044 				/*
11045 				 * EINPROGRESS is a soft error, needs retry
11046 				 * so don't make *outlenp zero.
11047 				 */
11048 				if (error != EINPROGRESS)
11049 					*outlenp = 0;
11050 				return (error);
11051 			}
11052 			/* OK return - copy input buffer into output buffer */
11053 			if (invalp != outvalp) {
11054 				bcopy(invalp, outvalp, inlen);
11055 			}
11056 			*outlenp = inlen;
11057 			return (0);
11058 		}
11059 		case IP_SEC_OPT:
11060 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11061 			if (error != 0) {
11062 				*outlenp = 0;
11063 				return (error);
11064 			}
11065 			break;
11066 		case IP_HDRINCL:
11067 		case IP_OPTIONS:
11068 		case T_IP_OPTIONS:
11069 		case IP_TOS:
11070 		case T_IP_TOS:
11071 		case IP_TTL:
11072 		case IP_RECVDSTADDR:
11073 		case IP_RECVOPTS:
11074 			/* OK return - copy input buffer into output buffer */
11075 			if (invalp != outvalp) {
11076 				/* don't trust bcopy for identical src/dst */
11077 				bcopy(invalp, outvalp, inlen);
11078 			}
11079 			*outlenp = inlen;
11080 			return (0);
11081 		case IP_RECVIF:
11082 			/* Retrieve the inbound interface index */
11083 			if (!checkonly) {
11084 				mutex_enter(&connp->conn_lock);
11085 				connp->conn_recvif = *i1 ? 1 : 0;
11086 				mutex_exit(&connp->conn_lock);
11087 			}
11088 			break;	/* goto sizeof (int) option return */
11089 		case IP_RECVPKTINFO:
11090 			if (!checkonly) {
11091 				mutex_enter(&connp->conn_lock);
11092 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11093 				mutex_exit(&connp->conn_lock);
11094 			}
11095 			break;	/* goto sizeof (int) option return */
11096 		case IP_RECVSLLA:
11097 			/* Retrieve the source link layer address */
11098 			if (!checkonly) {
11099 				mutex_enter(&connp->conn_lock);
11100 				connp->conn_recvslla = *i1 ? 1 : 0;
11101 				mutex_exit(&connp->conn_lock);
11102 			}
11103 			break;	/* goto sizeof (int) option return */
11104 		case MRT_INIT:
11105 		case MRT_DONE:
11106 		case MRT_ADD_VIF:
11107 		case MRT_DEL_VIF:
11108 		case MRT_ADD_MFC:
11109 		case MRT_DEL_MFC:
11110 		case MRT_ASSERT:
11111 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11112 				*outlenp = 0;
11113 				return (error);
11114 			}
11115 			error = ip_mrouter_set((int)name, q, checkonly,
11116 			    (uchar_t *)invalp, inlen, first_mp);
11117 			if (error) {
11118 				*outlenp = 0;
11119 				return (error);
11120 			}
11121 			/* OK return - copy input buffer into output buffer */
11122 			if (invalp != outvalp) {
11123 				/* don't trust bcopy for identical src/dst */
11124 				bcopy(invalp, outvalp, inlen);
11125 			}
11126 			*outlenp = inlen;
11127 			return (0);
11128 		case IP_BOUND_IF:
11129 		case IP_XMIT_IF:
11130 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11131 			    level, name, first_mp);
11132 			if (error != 0)
11133 				return (error);
11134 			break; 		/* goto sizeof (int) option return */
11135 
11136 		case IP_UNSPEC_SRC:
11137 			/* Allow sending with a zero source address */
11138 			if (!checkonly) {
11139 				mutex_enter(&connp->conn_lock);
11140 				connp->conn_unspec_src = *i1 ? 1 : 0;
11141 				mutex_exit(&connp->conn_lock);
11142 			}
11143 			break;	/* goto sizeof (int) option return */
11144 		default:
11145 			/*
11146 			 * "soft" error (negative)
11147 			 * option not handled at this level
11148 			 * Note: Do not modify *outlenp
11149 			 */
11150 			return (-EINVAL);
11151 		}
11152 		break;
11153 	case IPPROTO_IPV6:
11154 		switch (name) {
11155 		case IPV6_BOUND_IF:
11156 		case IPV6_BOUND_PIF:
11157 		case IPV6_DONTFAILOVER_IF:
11158 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11159 			    level, name, first_mp);
11160 			if (error != 0)
11161 				return (error);
11162 			break; 		/* goto sizeof (int) option return */
11163 
11164 		case IPV6_MULTICAST_IF:
11165 			/*
11166 			 * The only possible errors are EINPROGRESS and
11167 			 * EINVAL. EINPROGRESS will be restarted and is not
11168 			 * a hard error. We call this option on both V4 and V6
11169 			 * If both return EINVAL, then this call returns
11170 			 * EINVAL. If at least one of them succeeds we
11171 			 * return success.
11172 			 */
11173 			found = B_FALSE;
11174 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11175 			    level, name, first_mp);
11176 			if (error == EINPROGRESS)
11177 				return (error);
11178 			if (error == 0)
11179 				found = B_TRUE;
11180 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11181 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11182 			if (error == 0)
11183 				found = B_TRUE;
11184 			if (!found)
11185 				return (error);
11186 			break; 		/* goto sizeof (int) option return */
11187 
11188 		case IPV6_MULTICAST_HOPS:
11189 			/* Recorded in transport above IP */
11190 			break;	/* goto sizeof (int) option return */
11191 		case IPV6_MULTICAST_LOOP:
11192 			if (!checkonly) {
11193 				mutex_enter(&connp->conn_lock);
11194 				connp->conn_multicast_loop = *i1;
11195 				mutex_exit(&connp->conn_lock);
11196 			}
11197 			break;	/* goto sizeof (int) option return */
11198 		case IPV6_JOIN_GROUP:
11199 		case MCAST_JOIN_GROUP:
11200 		case IPV6_LEAVE_GROUP:
11201 		case MCAST_LEAVE_GROUP: {
11202 			struct ipv6_mreq *ip_mreqp;
11203 			struct group_req *greqp;
11204 			ire_t *ire;
11205 			boolean_t done = B_FALSE;
11206 			in6_addr_t groupv6;
11207 			uint32_t ifindex;
11208 			boolean_t mcast_opt = B_TRUE;
11209 			mcast_record_t fmode;
11210 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11211 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11212 
11213 			switch (name) {
11214 			case IPV6_JOIN_GROUP:
11215 				mcast_opt = B_FALSE;
11216 				/* FALLTHRU */
11217 			case MCAST_JOIN_GROUP:
11218 				fmode = MODE_IS_EXCLUDE;
11219 				optfn = ip_opt_add_group_v6;
11220 				break;
11221 
11222 			case IPV6_LEAVE_GROUP:
11223 				mcast_opt = B_FALSE;
11224 				/* FALLTHRU */
11225 			case MCAST_LEAVE_GROUP:
11226 				fmode = MODE_IS_INCLUDE;
11227 				optfn = ip_opt_delete_group_v6;
11228 				break;
11229 			}
11230 
11231 			if (mcast_opt) {
11232 				struct sockaddr_in *sin;
11233 				struct sockaddr_in6 *sin6;
11234 				greqp = (struct group_req *)i1;
11235 				if (greqp->gr_group.ss_family == AF_INET) {
11236 					sin = (struct sockaddr_in *)
11237 					    &(greqp->gr_group);
11238 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11239 					    &groupv6);
11240 				} else {
11241 					sin6 = (struct sockaddr_in6 *)
11242 					    &(greqp->gr_group);
11243 					groupv6 = sin6->sin6_addr;
11244 				}
11245 				ifindex = greqp->gr_interface;
11246 			} else {
11247 				ip_mreqp = (struct ipv6_mreq *)i1;
11248 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11249 				ifindex = ip_mreqp->ipv6mr_interface;
11250 			}
11251 			/*
11252 			 * In the multirouting case, we need to replicate
11253 			 * the request on all interfaces that will take part
11254 			 * in replication.  We do so because multirouting is
11255 			 * reflective, thus we will probably receive multi-
11256 			 * casts on those interfaces.
11257 			 * The ip_multirt_apply_membership_v6() succeeds if
11258 			 * the operation succeeds on at least one interface.
11259 			 */
11260 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11261 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11262 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11263 			if (ire != NULL) {
11264 				if (ire->ire_flags & RTF_MULTIRT) {
11265 					error = ip_multirt_apply_membership_v6(
11266 					    optfn, ire, connp, checkonly,
11267 					    &groupv6, fmode, &ipv6_all_zeros,
11268 					    first_mp);
11269 					done = B_TRUE;
11270 				}
11271 				ire_refrele(ire);
11272 			}
11273 			if (!done) {
11274 				error = optfn(connp, checkonly, &groupv6,
11275 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11276 			}
11277 			if (error) {
11278 				/*
11279 				 * EINPROGRESS is a soft error, needs retry
11280 				 * so don't make *outlenp zero.
11281 				 */
11282 				if (error != EINPROGRESS)
11283 					*outlenp = 0;
11284 				return (error);
11285 			}
11286 			/* OK return - copy input buffer into output buffer */
11287 			if (invalp != outvalp) {
11288 				/* don't trust bcopy for identical src/dst */
11289 				bcopy(invalp, outvalp, inlen);
11290 			}
11291 			*outlenp = inlen;
11292 			return (0);
11293 		}
11294 		case MCAST_BLOCK_SOURCE:
11295 		case MCAST_UNBLOCK_SOURCE:
11296 		case MCAST_JOIN_SOURCE_GROUP:
11297 		case MCAST_LEAVE_SOURCE_GROUP: {
11298 			struct group_source_req *gsreqp;
11299 			in6_addr_t v6grp, v6src;
11300 			uint32_t ifindex;
11301 			mcast_record_t fmode;
11302 			ire_t *ire;
11303 			boolean_t done = B_FALSE;
11304 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11305 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11306 
11307 			switch (name) {
11308 			case MCAST_BLOCK_SOURCE:
11309 				fmode = MODE_IS_EXCLUDE;
11310 				optfn = ip_opt_add_group_v6;
11311 				break;
11312 			case MCAST_UNBLOCK_SOURCE:
11313 				fmode = MODE_IS_EXCLUDE;
11314 				optfn = ip_opt_delete_group_v6;
11315 				break;
11316 			case MCAST_JOIN_SOURCE_GROUP:
11317 				fmode = MODE_IS_INCLUDE;
11318 				optfn = ip_opt_add_group_v6;
11319 				break;
11320 			case MCAST_LEAVE_SOURCE_GROUP:
11321 				fmode = MODE_IS_INCLUDE;
11322 				optfn = ip_opt_delete_group_v6;
11323 				break;
11324 			}
11325 
11326 			gsreqp = (struct group_source_req *)i1;
11327 			ifindex = gsreqp->gsr_interface;
11328 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11329 				struct sockaddr_in *s;
11330 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11331 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11332 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11333 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11334 			} else {
11335 				struct sockaddr_in6 *s6;
11336 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11337 				v6grp = s6->sin6_addr;
11338 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11339 				v6src = s6->sin6_addr;
11340 			}
11341 
11342 			/*
11343 			 * In the multirouting case, we need to replicate
11344 			 * the request as noted in the mcast cases above.
11345 			 */
11346 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11347 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11348 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11349 			if (ire != NULL) {
11350 				if (ire->ire_flags & RTF_MULTIRT) {
11351 					error = ip_multirt_apply_membership_v6(
11352 					    optfn, ire, connp, checkonly,
11353 					    &v6grp, fmode, &v6src, first_mp);
11354 					done = B_TRUE;
11355 				}
11356 				ire_refrele(ire);
11357 			}
11358 			if (!done) {
11359 				error = optfn(connp, checkonly, &v6grp,
11360 				    ifindex, fmode, &v6src, first_mp);
11361 			}
11362 			if (error != 0) {
11363 				/*
11364 				 * EINPROGRESS is a soft error, needs retry
11365 				 * so don't make *outlenp zero.
11366 				 */
11367 				if (error != EINPROGRESS)
11368 					*outlenp = 0;
11369 				return (error);
11370 			}
11371 			/* OK return - copy input buffer into output buffer */
11372 			if (invalp != outvalp) {
11373 				bcopy(invalp, outvalp, inlen);
11374 			}
11375 			*outlenp = inlen;
11376 			return (0);
11377 		}
11378 		case IPV6_UNICAST_HOPS:
11379 			/* Recorded in transport above IP */
11380 			break;	/* goto sizeof (int) option return */
11381 		case IPV6_UNSPEC_SRC:
11382 			/* Allow sending with a zero source address */
11383 			if (!checkonly) {
11384 				mutex_enter(&connp->conn_lock);
11385 				connp->conn_unspec_src = *i1 ? 1 : 0;
11386 				mutex_exit(&connp->conn_lock);
11387 			}
11388 			break;	/* goto sizeof (int) option return */
11389 		case IPV6_RECVPKTINFO:
11390 			if (!checkonly) {
11391 				mutex_enter(&connp->conn_lock);
11392 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11393 				mutex_exit(&connp->conn_lock);
11394 			}
11395 			break;	/* goto sizeof (int) option return */
11396 		case IPV6_RECVTCLASS:
11397 			if (!checkonly) {
11398 				if (*i1 < 0 || *i1 > 1) {
11399 					return (EINVAL);
11400 				}
11401 				mutex_enter(&connp->conn_lock);
11402 				connp->conn_ipv6_recvtclass = *i1;
11403 				mutex_exit(&connp->conn_lock);
11404 			}
11405 			break;
11406 		case IPV6_RECVPATHMTU:
11407 			if (!checkonly) {
11408 				if (*i1 < 0 || *i1 > 1) {
11409 					return (EINVAL);
11410 				}
11411 				mutex_enter(&connp->conn_lock);
11412 				connp->conn_ipv6_recvpathmtu = *i1;
11413 				mutex_exit(&connp->conn_lock);
11414 			}
11415 			break;
11416 		case IPV6_RECVHOPLIMIT:
11417 			if (!checkonly) {
11418 				mutex_enter(&connp->conn_lock);
11419 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11420 				mutex_exit(&connp->conn_lock);
11421 			}
11422 			break;	/* goto sizeof (int) option return */
11423 		case IPV6_RECVHOPOPTS:
11424 			if (!checkonly) {
11425 				mutex_enter(&connp->conn_lock);
11426 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11427 				mutex_exit(&connp->conn_lock);
11428 			}
11429 			break;	/* goto sizeof (int) option return */
11430 		case IPV6_RECVDSTOPTS:
11431 			if (!checkonly) {
11432 				mutex_enter(&connp->conn_lock);
11433 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11434 				mutex_exit(&connp->conn_lock);
11435 			}
11436 			break;	/* goto sizeof (int) option return */
11437 		case IPV6_RECVRTHDR:
11438 			if (!checkonly) {
11439 				mutex_enter(&connp->conn_lock);
11440 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11441 				mutex_exit(&connp->conn_lock);
11442 			}
11443 			break;	/* goto sizeof (int) option return */
11444 		case IPV6_RECVRTHDRDSTOPTS:
11445 			if (!checkonly) {
11446 				mutex_enter(&connp->conn_lock);
11447 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11448 				mutex_exit(&connp->conn_lock);
11449 			}
11450 			break;	/* goto sizeof (int) option return */
11451 		case IPV6_PKTINFO:
11452 			if (inlen == 0)
11453 				return (-EINVAL);	/* clearing option */
11454 			error = ip6_set_pktinfo(cr, connp,
11455 			    (struct in6_pktinfo *)invalp, first_mp);
11456 			if (error != 0)
11457 				*outlenp = 0;
11458 			else
11459 				*outlenp = inlen;
11460 			return (error);
11461 		case IPV6_NEXTHOP: {
11462 			struct sockaddr_in6 *sin6;
11463 
11464 			/* Verify that the nexthop is reachable */
11465 			if (inlen == 0)
11466 				return (-EINVAL);	/* clearing option */
11467 
11468 			sin6 = (struct sockaddr_in6 *)invalp;
11469 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11470 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11471 			    NULL, MATCH_IRE_DEFAULT, ipst);
11472 
11473 			if (ire == NULL) {
11474 				*outlenp = 0;
11475 				return (EHOSTUNREACH);
11476 			}
11477 			ire_refrele(ire);
11478 			return (-EINVAL);
11479 		}
11480 		case IPV6_SEC_OPT:
11481 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11482 			if (error != 0) {
11483 				*outlenp = 0;
11484 				return (error);
11485 			}
11486 			break;
11487 		case IPV6_SRC_PREFERENCES: {
11488 			/*
11489 			 * This is implemented strictly in the ip module
11490 			 * (here and in tcp_opt_*() to accomodate tcp
11491 			 * sockets).  Modules above ip pass this option
11492 			 * down here since ip is the only one that needs to
11493 			 * be aware of source address preferences.
11494 			 *
11495 			 * This socket option only affects connected
11496 			 * sockets that haven't already bound to a specific
11497 			 * IPv6 address.  In other words, sockets that
11498 			 * don't call bind() with an address other than the
11499 			 * unspecified address and that call connect().
11500 			 * ip_bind_connected_v6() passes these preferences
11501 			 * to the ipif_select_source_v6() function.
11502 			 */
11503 			if (inlen != sizeof (uint32_t))
11504 				return (EINVAL);
11505 			error = ip6_set_src_preferences(connp,
11506 			    *(uint32_t *)invalp);
11507 			if (error != 0) {
11508 				*outlenp = 0;
11509 				return (error);
11510 			} else {
11511 				*outlenp = sizeof (uint32_t);
11512 			}
11513 			break;
11514 		}
11515 		case IPV6_V6ONLY:
11516 			if (*i1 < 0 || *i1 > 1) {
11517 				return (EINVAL);
11518 			}
11519 			mutex_enter(&connp->conn_lock);
11520 			connp->conn_ipv6_v6only = *i1;
11521 			mutex_exit(&connp->conn_lock);
11522 			break;
11523 		default:
11524 			return (-EINVAL);
11525 		}
11526 		break;
11527 	default:
11528 		/*
11529 		 * "soft" error (negative)
11530 		 * option not handled at this level
11531 		 * Note: Do not modify *outlenp
11532 		 */
11533 		return (-EINVAL);
11534 	}
11535 	/*
11536 	 * Common case of return from an option that is sizeof (int)
11537 	 */
11538 	*(int *)outvalp = *i1;
11539 	*outlenp = sizeof (int);
11540 	return (0);
11541 }
11542 
11543 /*
11544  * This routine gets default values of certain options whose default
11545  * values are maintained by protocol specific code
11546  */
11547 /* ARGSUSED */
11548 int
11549 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11550 {
11551 	int *i1 = (int *)ptr;
11552 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11553 
11554 	switch (level) {
11555 	case IPPROTO_IP:
11556 		switch (name) {
11557 		case IP_MULTICAST_TTL:
11558 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11559 			return (sizeof (uchar_t));
11560 		case IP_MULTICAST_LOOP:
11561 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11562 			return (sizeof (uchar_t));
11563 		default:
11564 			return (-1);
11565 		}
11566 	case IPPROTO_IPV6:
11567 		switch (name) {
11568 		case IPV6_UNICAST_HOPS:
11569 			*i1 = ipst->ips_ipv6_def_hops;
11570 			return (sizeof (int));
11571 		case IPV6_MULTICAST_HOPS:
11572 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11573 			return (sizeof (int));
11574 		case IPV6_MULTICAST_LOOP:
11575 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11576 			return (sizeof (int));
11577 		case IPV6_V6ONLY:
11578 			*i1 = 1;
11579 			return (sizeof (int));
11580 		default:
11581 			return (-1);
11582 		}
11583 	default:
11584 		return (-1);
11585 	}
11586 	/* NOTREACHED */
11587 }
11588 
11589 /*
11590  * Given a destination address and a pointer to where to put the information
11591  * this routine fills in the mtuinfo.
11592  */
11593 int
11594 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11595     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11596 {
11597 	ire_t *ire;
11598 	ip_stack_t	*ipst = ns->netstack_ip;
11599 
11600 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11601 		return (-1);
11602 
11603 	bzero(mtuinfo, sizeof (*mtuinfo));
11604 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11605 	mtuinfo->ip6m_addr.sin6_port = port;
11606 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11607 
11608 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11609 	if (ire != NULL) {
11610 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11611 		ire_refrele(ire);
11612 	} else {
11613 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11614 	}
11615 	return (sizeof (struct ip6_mtuinfo));
11616 }
11617 
11618 /*
11619  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11620  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11621  * isn't.  This doesn't matter as the error checking is done properly for the
11622  * other MRT options coming in through ip_opt_set.
11623  */
11624 int
11625 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11626 {
11627 	conn_t		*connp = Q_TO_CONN(q);
11628 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11629 
11630 	switch (level) {
11631 	case IPPROTO_IP:
11632 		switch (name) {
11633 		case MRT_VERSION:
11634 		case MRT_ASSERT:
11635 			(void) ip_mrouter_get(name, q, ptr);
11636 			return (sizeof (int));
11637 		case IP_SEC_OPT:
11638 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11639 		case IP_NEXTHOP:
11640 			if (connp->conn_nexthop_set) {
11641 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11642 				return (sizeof (ipaddr_t));
11643 			} else
11644 				return (0);
11645 		case IP_RECVPKTINFO:
11646 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11647 			return (sizeof (int));
11648 		default:
11649 			break;
11650 		}
11651 		break;
11652 	case IPPROTO_IPV6:
11653 		switch (name) {
11654 		case IPV6_SEC_OPT:
11655 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11656 		case IPV6_SRC_PREFERENCES: {
11657 			return (ip6_get_src_preferences(connp,
11658 			    (uint32_t *)ptr));
11659 		}
11660 		case IPV6_V6ONLY:
11661 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11662 			return (sizeof (int));
11663 		case IPV6_PATHMTU:
11664 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11665 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11666 		default:
11667 			break;
11668 		}
11669 		break;
11670 	default:
11671 		break;
11672 	}
11673 	return (-1);
11674 }
11675 
11676 /* Named Dispatch routine to get a current value out of our parameter table. */
11677 /* ARGSUSED */
11678 static int
11679 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11680 {
11681 	ipparam_t *ippa = (ipparam_t *)cp;
11682 
11683 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11684 	return (0);
11685 }
11686 
11687 /* ARGSUSED */
11688 static int
11689 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11690 {
11691 
11692 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11693 	return (0);
11694 }
11695 
11696 /*
11697  * Set ip{,6}_forwarding values.  This means walking through all of the
11698  * ill's and toggling their forwarding values.
11699  */
11700 /* ARGSUSED */
11701 static int
11702 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11703 {
11704 	long new_value;
11705 	int *forwarding_value = (int *)cp;
11706 	ill_t *ill;
11707 	boolean_t isv6;
11708 	ill_walk_context_t ctx;
11709 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11710 
11711 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11712 
11713 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11714 	    new_value < 0 || new_value > 1) {
11715 		return (EINVAL);
11716 	}
11717 
11718 	*forwarding_value = new_value;
11719 
11720 	/*
11721 	 * Regardless of the current value of ip_forwarding, set all per-ill
11722 	 * values of ip_forwarding to the value being set.
11723 	 *
11724 	 * Bring all the ill's up to date with the new global value.
11725 	 */
11726 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11727 
11728 	if (isv6)
11729 		ill = ILL_START_WALK_V6(&ctx, ipst);
11730 	else
11731 		ill = ILL_START_WALK_V4(&ctx, ipst);
11732 
11733 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11734 		(void) ill_forward_set(ill, new_value != 0);
11735 
11736 	rw_exit(&ipst->ips_ill_g_lock);
11737 	return (0);
11738 }
11739 
11740 /*
11741  * Walk through the param array specified registering each element with the
11742  * Named Dispatch handler. This is called only during init. So it is ok
11743  * not to acquire any locks
11744  */
11745 static boolean_t
11746 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11747     ipndp_t *ipnd, size_t ipnd_cnt)
11748 {
11749 	for (; ippa_cnt-- > 0; ippa++) {
11750 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11751 			if (!nd_load(ndp, ippa->ip_param_name,
11752 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11753 				nd_free(ndp);
11754 				return (B_FALSE);
11755 			}
11756 		}
11757 	}
11758 
11759 	for (; ipnd_cnt-- > 0; ipnd++) {
11760 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11761 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11762 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11763 			    ipnd->ip_ndp_data)) {
11764 				nd_free(ndp);
11765 				return (B_FALSE);
11766 			}
11767 		}
11768 	}
11769 
11770 	return (B_TRUE);
11771 }
11772 
11773 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11774 /* ARGSUSED */
11775 static int
11776 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11777 {
11778 	long		new_value;
11779 	ipparam_t	*ippa = (ipparam_t *)cp;
11780 
11781 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11782 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11783 		return (EINVAL);
11784 	}
11785 	ippa->ip_param_value = new_value;
11786 	return (0);
11787 }
11788 
11789 /*
11790  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11791  * When an ipf is passed here for the first time, if
11792  * we already have in-order fragments on the queue, we convert from the fast-
11793  * path reassembly scheme to the hard-case scheme.  From then on, additional
11794  * fragments are reassembled here.  We keep track of the start and end offsets
11795  * of each piece, and the number of holes in the chain.  When the hole count
11796  * goes to zero, we are done!
11797  *
11798  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11799  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11800  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11801  * after the call to ip_reassemble().
11802  */
11803 int
11804 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11805     size_t msg_len)
11806 {
11807 	uint_t	end;
11808 	mblk_t	*next_mp;
11809 	mblk_t	*mp1;
11810 	uint_t	offset;
11811 	boolean_t incr_dups = B_TRUE;
11812 	boolean_t offset_zero_seen = B_FALSE;
11813 	boolean_t pkt_boundary_checked = B_FALSE;
11814 
11815 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11816 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11817 
11818 	/* Add in byte count */
11819 	ipf->ipf_count += msg_len;
11820 	if (ipf->ipf_end) {
11821 		/*
11822 		 * We were part way through in-order reassembly, but now there
11823 		 * is a hole.  We walk through messages already queued, and
11824 		 * mark them for hard case reassembly.  We know that up till
11825 		 * now they were in order starting from offset zero.
11826 		 */
11827 		offset = 0;
11828 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11829 			IP_REASS_SET_START(mp1, offset);
11830 			if (offset == 0) {
11831 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11832 				offset = -ipf->ipf_nf_hdr_len;
11833 			}
11834 			offset += mp1->b_wptr - mp1->b_rptr;
11835 			IP_REASS_SET_END(mp1, offset);
11836 		}
11837 		/* One hole at the end. */
11838 		ipf->ipf_hole_cnt = 1;
11839 		/* Brand it as a hard case, forever. */
11840 		ipf->ipf_end = 0;
11841 	}
11842 	/* Walk through all the new pieces. */
11843 	do {
11844 		end = start + (mp->b_wptr - mp->b_rptr);
11845 		/*
11846 		 * If start is 0, decrease 'end' only for the first mblk of
11847 		 * the fragment. Otherwise 'end' can get wrong value in the
11848 		 * second pass of the loop if first mblk is exactly the
11849 		 * size of ipf_nf_hdr_len.
11850 		 */
11851 		if (start == 0 && !offset_zero_seen) {
11852 			/* First segment */
11853 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11854 			end -= ipf->ipf_nf_hdr_len;
11855 			offset_zero_seen = B_TRUE;
11856 		}
11857 		next_mp = mp->b_cont;
11858 		/*
11859 		 * We are checking to see if there is any interesing data
11860 		 * to process.  If there isn't and the mblk isn't the
11861 		 * one which carries the unfragmentable header then we
11862 		 * drop it.  It's possible to have just the unfragmentable
11863 		 * header come through without any data.  That needs to be
11864 		 * saved.
11865 		 *
11866 		 * If the assert at the top of this function holds then the
11867 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11868 		 * is infrequently traveled enough that the test is left in
11869 		 * to protect against future code changes which break that
11870 		 * invariant.
11871 		 */
11872 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11873 			/* Empty.  Blast it. */
11874 			IP_REASS_SET_START(mp, 0);
11875 			IP_REASS_SET_END(mp, 0);
11876 			/*
11877 			 * If the ipf points to the mblk we are about to free,
11878 			 * update ipf to point to the next mblk (or NULL
11879 			 * if none).
11880 			 */
11881 			if (ipf->ipf_mp->b_cont == mp)
11882 				ipf->ipf_mp->b_cont = next_mp;
11883 			freeb(mp);
11884 			continue;
11885 		}
11886 		mp->b_cont = NULL;
11887 		IP_REASS_SET_START(mp, start);
11888 		IP_REASS_SET_END(mp, end);
11889 		if (!ipf->ipf_tail_mp) {
11890 			ipf->ipf_tail_mp = mp;
11891 			ipf->ipf_mp->b_cont = mp;
11892 			if (start == 0 || !more) {
11893 				ipf->ipf_hole_cnt = 1;
11894 				/*
11895 				 * if the first fragment comes in more than one
11896 				 * mblk, this loop will be executed for each
11897 				 * mblk. Need to adjust hole count so exiting
11898 				 * this routine will leave hole count at 1.
11899 				 */
11900 				if (next_mp)
11901 					ipf->ipf_hole_cnt++;
11902 			} else
11903 				ipf->ipf_hole_cnt = 2;
11904 			continue;
11905 		} else if (ipf->ipf_last_frag_seen && !more &&
11906 		    !pkt_boundary_checked) {
11907 			/*
11908 			 * We check datagram boundary only if this fragment
11909 			 * claims to be the last fragment and we have seen a
11910 			 * last fragment in the past too. We do this only
11911 			 * once for a given fragment.
11912 			 *
11913 			 * start cannot be 0 here as fragments with start=0
11914 			 * and MF=0 gets handled as a complete packet. These
11915 			 * fragments should not reach here.
11916 			 */
11917 
11918 			if (start + msgdsize(mp) !=
11919 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11920 				/*
11921 				 * We have two fragments both of which claim
11922 				 * to be the last fragment but gives conflicting
11923 				 * information about the whole datagram size.
11924 				 * Something fishy is going on. Drop the
11925 				 * fragment and free up the reassembly list.
11926 				 */
11927 				return (IP_REASS_FAILED);
11928 			}
11929 
11930 			/*
11931 			 * We shouldn't come to this code block again for this
11932 			 * particular fragment.
11933 			 */
11934 			pkt_boundary_checked = B_TRUE;
11935 		}
11936 
11937 		/* New stuff at or beyond tail? */
11938 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11939 		if (start >= offset) {
11940 			if (ipf->ipf_last_frag_seen) {
11941 				/* current fragment is beyond last fragment */
11942 				return (IP_REASS_FAILED);
11943 			}
11944 			/* Link it on end. */
11945 			ipf->ipf_tail_mp->b_cont = mp;
11946 			ipf->ipf_tail_mp = mp;
11947 			if (more) {
11948 				if (start != offset)
11949 					ipf->ipf_hole_cnt++;
11950 			} else if (start == offset && next_mp == NULL)
11951 					ipf->ipf_hole_cnt--;
11952 			continue;
11953 		}
11954 		mp1 = ipf->ipf_mp->b_cont;
11955 		offset = IP_REASS_START(mp1);
11956 		/* New stuff at the front? */
11957 		if (start < offset) {
11958 			if (start == 0) {
11959 				if (end >= offset) {
11960 					/* Nailed the hole at the begining. */
11961 					ipf->ipf_hole_cnt--;
11962 				}
11963 			} else if (end < offset) {
11964 				/*
11965 				 * A hole, stuff, and a hole where there used
11966 				 * to be just a hole.
11967 				 */
11968 				ipf->ipf_hole_cnt++;
11969 			}
11970 			mp->b_cont = mp1;
11971 			/* Check for overlap. */
11972 			while (end > offset) {
11973 				if (end < IP_REASS_END(mp1)) {
11974 					mp->b_wptr -= end - offset;
11975 					IP_REASS_SET_END(mp, offset);
11976 					BUMP_MIB(ill->ill_ip_mib,
11977 					    ipIfStatsReasmPartDups);
11978 					break;
11979 				}
11980 				/* Did we cover another hole? */
11981 				if ((mp1->b_cont &&
11982 				    IP_REASS_END(mp1) !=
11983 				    IP_REASS_START(mp1->b_cont) &&
11984 				    end >= IP_REASS_START(mp1->b_cont)) ||
11985 				    (!ipf->ipf_last_frag_seen && !more)) {
11986 					ipf->ipf_hole_cnt--;
11987 				}
11988 				/* Clip out mp1. */
11989 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11990 					/*
11991 					 * After clipping out mp1, this guy
11992 					 * is now hanging off the end.
11993 					 */
11994 					ipf->ipf_tail_mp = mp;
11995 				}
11996 				IP_REASS_SET_START(mp1, 0);
11997 				IP_REASS_SET_END(mp1, 0);
11998 				/* Subtract byte count */
11999 				ipf->ipf_count -= mp1->b_datap->db_lim -
12000 				    mp1->b_datap->db_base;
12001 				freeb(mp1);
12002 				BUMP_MIB(ill->ill_ip_mib,
12003 				    ipIfStatsReasmPartDups);
12004 				mp1 = mp->b_cont;
12005 				if (!mp1)
12006 					break;
12007 				offset = IP_REASS_START(mp1);
12008 			}
12009 			ipf->ipf_mp->b_cont = mp;
12010 			continue;
12011 		}
12012 		/*
12013 		 * The new piece starts somewhere between the start of the head
12014 		 * and before the end of the tail.
12015 		 */
12016 		for (; mp1; mp1 = mp1->b_cont) {
12017 			offset = IP_REASS_END(mp1);
12018 			if (start < offset) {
12019 				if (end <= offset) {
12020 					/* Nothing new. */
12021 					IP_REASS_SET_START(mp, 0);
12022 					IP_REASS_SET_END(mp, 0);
12023 					/* Subtract byte count */
12024 					ipf->ipf_count -= mp->b_datap->db_lim -
12025 					    mp->b_datap->db_base;
12026 					if (incr_dups) {
12027 						ipf->ipf_num_dups++;
12028 						incr_dups = B_FALSE;
12029 					}
12030 					freeb(mp);
12031 					BUMP_MIB(ill->ill_ip_mib,
12032 					    ipIfStatsReasmDuplicates);
12033 					break;
12034 				}
12035 				/*
12036 				 * Trim redundant stuff off beginning of new
12037 				 * piece.
12038 				 */
12039 				IP_REASS_SET_START(mp, offset);
12040 				mp->b_rptr += offset - start;
12041 				BUMP_MIB(ill->ill_ip_mib,
12042 				    ipIfStatsReasmPartDups);
12043 				start = offset;
12044 				if (!mp1->b_cont) {
12045 					/*
12046 					 * After trimming, this guy is now
12047 					 * hanging off the end.
12048 					 */
12049 					mp1->b_cont = mp;
12050 					ipf->ipf_tail_mp = mp;
12051 					if (!more) {
12052 						ipf->ipf_hole_cnt--;
12053 					}
12054 					break;
12055 				}
12056 			}
12057 			if (start >= IP_REASS_START(mp1->b_cont))
12058 				continue;
12059 			/* Fill a hole */
12060 			if (start > offset)
12061 				ipf->ipf_hole_cnt++;
12062 			mp->b_cont = mp1->b_cont;
12063 			mp1->b_cont = mp;
12064 			mp1 = mp->b_cont;
12065 			offset = IP_REASS_START(mp1);
12066 			if (end >= offset) {
12067 				ipf->ipf_hole_cnt--;
12068 				/* Check for overlap. */
12069 				while (end > offset) {
12070 					if (end < IP_REASS_END(mp1)) {
12071 						mp->b_wptr -= end - offset;
12072 						IP_REASS_SET_END(mp, offset);
12073 						/*
12074 						 * TODO we might bump
12075 						 * this up twice if there is
12076 						 * overlap at both ends.
12077 						 */
12078 						BUMP_MIB(ill->ill_ip_mib,
12079 						    ipIfStatsReasmPartDups);
12080 						break;
12081 					}
12082 					/* Did we cover another hole? */
12083 					if ((mp1->b_cont &&
12084 					    IP_REASS_END(mp1)
12085 					    != IP_REASS_START(mp1->b_cont) &&
12086 					    end >=
12087 					    IP_REASS_START(mp1->b_cont)) ||
12088 					    (!ipf->ipf_last_frag_seen &&
12089 					    !more)) {
12090 						ipf->ipf_hole_cnt--;
12091 					}
12092 					/* Clip out mp1. */
12093 					if ((mp->b_cont = mp1->b_cont) ==
12094 					    NULL) {
12095 						/*
12096 						 * After clipping out mp1,
12097 						 * this guy is now hanging
12098 						 * off the end.
12099 						 */
12100 						ipf->ipf_tail_mp = mp;
12101 					}
12102 					IP_REASS_SET_START(mp1, 0);
12103 					IP_REASS_SET_END(mp1, 0);
12104 					/* Subtract byte count */
12105 					ipf->ipf_count -=
12106 					    mp1->b_datap->db_lim -
12107 					    mp1->b_datap->db_base;
12108 					freeb(mp1);
12109 					BUMP_MIB(ill->ill_ip_mib,
12110 					    ipIfStatsReasmPartDups);
12111 					mp1 = mp->b_cont;
12112 					if (!mp1)
12113 						break;
12114 					offset = IP_REASS_START(mp1);
12115 				}
12116 			}
12117 			break;
12118 		}
12119 	} while (start = end, mp = next_mp);
12120 
12121 	/* Fragment just processed could be the last one. Remember this fact */
12122 	if (!more)
12123 		ipf->ipf_last_frag_seen = B_TRUE;
12124 
12125 	/* Still got holes? */
12126 	if (ipf->ipf_hole_cnt)
12127 		return (IP_REASS_PARTIAL);
12128 	/* Clean up overloaded fields to avoid upstream disasters. */
12129 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12130 		IP_REASS_SET_START(mp1, 0);
12131 		IP_REASS_SET_END(mp1, 0);
12132 	}
12133 	return (IP_REASS_COMPLETE);
12134 }
12135 
12136 /*
12137  * ipsec processing for the fast path, used for input UDP Packets
12138  * Returns true if ready for passup to UDP.
12139  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12140  * was an ESP-in-UDP packet, etc.).
12141  */
12142 static boolean_t
12143 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12144     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12145 {
12146 	uint32_t	ill_index;
12147 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12148 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12149 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12150 	udp_t		*udp = connp->conn_udp;
12151 
12152 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12153 	/* The ill_index of the incoming ILL */
12154 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12155 
12156 	/* pass packet up to the transport */
12157 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12158 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12159 		    NULL, mctl_present);
12160 		if (*first_mpp == NULL) {
12161 			return (B_FALSE);
12162 		}
12163 	}
12164 
12165 	/* Initiate IPPF processing for fastpath UDP */
12166 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12167 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12168 		if (*mpp == NULL) {
12169 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12170 			    "deferred/dropped during IPPF processing\n"));
12171 			return (B_FALSE);
12172 		}
12173 	}
12174 	/*
12175 	 * Remove 0-spi if it's 0, or move everything behind
12176 	 * the UDP header over it and forward to ESP via
12177 	 * ip_proto_input().
12178 	 */
12179 	if (udp->udp_nat_t_endpoint) {
12180 		if (mctl_present) {
12181 			/* mctl_present *shouldn't* happen. */
12182 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12183 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12184 			    &ipss->ipsec_dropper);
12185 			*first_mpp = NULL;
12186 			return (B_FALSE);
12187 		}
12188 
12189 		/* "ill" is "recv_ill" in actuality. */
12190 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12191 			return (B_FALSE);
12192 
12193 		/* Else continue like a normal UDP packet. */
12194 	}
12195 
12196 	/*
12197 	 * We make the checks as below since we are in the fast path
12198 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12199 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12200 	 */
12201 	if (connp->conn_recvif || connp->conn_recvslla ||
12202 	    connp->conn_ip_recvpktinfo) {
12203 		if (connp->conn_recvif) {
12204 			in_flags = IPF_RECVIF;
12205 		}
12206 		/*
12207 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12208 		 * so the flag passed to ip_add_info is based on IP version
12209 		 * of connp.
12210 		 */
12211 		if (connp->conn_ip_recvpktinfo) {
12212 			if (connp->conn_af_isv6) {
12213 				/*
12214 				 * V6 only needs index
12215 				 */
12216 				in_flags |= IPF_RECVIF;
12217 			} else {
12218 				/*
12219 				 * V4 needs index + matching address.
12220 				 */
12221 				in_flags |= IPF_RECVADDR;
12222 			}
12223 		}
12224 		if (connp->conn_recvslla) {
12225 			in_flags |= IPF_RECVSLLA;
12226 		}
12227 		/*
12228 		 * since in_flags are being set ill will be
12229 		 * referenced in ip_add_info, so it better not
12230 		 * be NULL.
12231 		 */
12232 		/*
12233 		 * the actual data will be contained in b_cont
12234 		 * upon successful return of the following call.
12235 		 * If the call fails then the original mblk is
12236 		 * returned.
12237 		 */
12238 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12239 		    ipst);
12240 	}
12241 
12242 	return (B_TRUE);
12243 }
12244 
12245 /*
12246  * Fragmentation reassembly.  Each ILL has a hash table for
12247  * queuing packets undergoing reassembly for all IPIFs
12248  * associated with the ILL.  The hash is based on the packet
12249  * IP ident field.  The ILL frag hash table was allocated
12250  * as a timer block at the time the ILL was created.  Whenever
12251  * there is anything on the reassembly queue, the timer will
12252  * be running.  Returns B_TRUE if successful else B_FALSE;
12253  * frees mp on failure.
12254  */
12255 static boolean_t
12256 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12257     uint32_t *cksum_val, uint16_t *cksum_flags)
12258 {
12259 	uint32_t	frag_offset_flags;
12260 	ill_t		*ill = (ill_t *)q->q_ptr;
12261 	mblk_t		*mp = *mpp;
12262 	mblk_t		*t_mp;
12263 	ipaddr_t	dst;
12264 	uint8_t		proto = ipha->ipha_protocol;
12265 	uint32_t	sum_val;
12266 	uint16_t	sum_flags;
12267 	ipf_t		*ipf;
12268 	ipf_t		**ipfp;
12269 	ipfb_t		*ipfb;
12270 	uint16_t	ident;
12271 	uint32_t	offset;
12272 	ipaddr_t	src;
12273 	uint_t		hdr_length;
12274 	uint32_t	end;
12275 	mblk_t		*mp1;
12276 	mblk_t		*tail_mp;
12277 	size_t		count;
12278 	size_t		msg_len;
12279 	uint8_t		ecn_info = 0;
12280 	uint32_t	packet_size;
12281 	boolean_t	pruned = B_FALSE;
12282 	ip_stack_t *ipst = ill->ill_ipst;
12283 
12284 	if (cksum_val != NULL)
12285 		*cksum_val = 0;
12286 	if (cksum_flags != NULL)
12287 		*cksum_flags = 0;
12288 
12289 	/*
12290 	 * Drop the fragmented as early as possible, if
12291 	 * we don't have resource(s) to re-assemble.
12292 	 */
12293 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12294 		freemsg(mp);
12295 		return (B_FALSE);
12296 	}
12297 
12298 	/* Check for fragmentation offset; return if there's none */
12299 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12300 	    (IPH_MF | IPH_OFFSET)) == 0)
12301 		return (B_TRUE);
12302 
12303 	/*
12304 	 * We utilize hardware computed checksum info only for UDP since
12305 	 * IP fragmentation is a normal occurence for the protocol.  In
12306 	 * addition, checksum offload support for IP fragments carrying
12307 	 * UDP payload is commonly implemented across network adapters.
12308 	 */
12309 	ASSERT(ill != NULL);
12310 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12311 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12312 		mblk_t *mp1 = mp->b_cont;
12313 		int32_t len;
12314 
12315 		/* Record checksum information from the packet */
12316 		sum_val = (uint32_t)DB_CKSUM16(mp);
12317 		sum_flags = DB_CKSUMFLAGS(mp);
12318 
12319 		/* IP payload offset from beginning of mblk */
12320 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12321 
12322 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12323 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12324 		    offset >= DB_CKSUMSTART(mp) &&
12325 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12326 			uint32_t adj;
12327 			/*
12328 			 * Partial checksum has been calculated by hardware
12329 			 * and attached to the packet; in addition, any
12330 			 * prepended extraneous data is even byte aligned.
12331 			 * If any such data exists, we adjust the checksum;
12332 			 * this would also handle any postpended data.
12333 			 */
12334 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12335 			    mp, mp1, len, adj);
12336 
12337 			/* One's complement subtract extraneous checksum */
12338 			if (adj >= sum_val)
12339 				sum_val = ~(adj - sum_val) & 0xFFFF;
12340 			else
12341 				sum_val -= adj;
12342 		}
12343 	} else {
12344 		sum_val = 0;
12345 		sum_flags = 0;
12346 	}
12347 
12348 	/* Clear hardware checksumming flag */
12349 	DB_CKSUMFLAGS(mp) = 0;
12350 
12351 	ident = ipha->ipha_ident;
12352 	offset = (frag_offset_flags << 3) & 0xFFFF;
12353 	src = ipha->ipha_src;
12354 	dst = ipha->ipha_dst;
12355 	hdr_length = IPH_HDR_LENGTH(ipha);
12356 	end = ntohs(ipha->ipha_length) - hdr_length;
12357 
12358 	/* If end == 0 then we have a packet with no data, so just free it */
12359 	if (end == 0) {
12360 		freemsg(mp);
12361 		return (B_FALSE);
12362 	}
12363 
12364 	/* Record the ECN field info. */
12365 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12366 	if (offset != 0) {
12367 		/*
12368 		 * If this isn't the first piece, strip the header, and
12369 		 * add the offset to the end value.
12370 		 */
12371 		mp->b_rptr += hdr_length;
12372 		end += offset;
12373 	}
12374 
12375 	msg_len = MBLKSIZE(mp);
12376 	tail_mp = mp;
12377 	while (tail_mp->b_cont != NULL) {
12378 		tail_mp = tail_mp->b_cont;
12379 		msg_len += MBLKSIZE(tail_mp);
12380 	}
12381 
12382 	/* If the reassembly list for this ILL will get too big, prune it */
12383 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12384 	    ipst->ips_ip_reass_queue_bytes) {
12385 		ill_frag_prune(ill,
12386 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12387 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12388 		pruned = B_TRUE;
12389 	}
12390 
12391 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12392 	mutex_enter(&ipfb->ipfb_lock);
12393 
12394 	ipfp = &ipfb->ipfb_ipf;
12395 	/* Try to find an existing fragment queue for this packet. */
12396 	for (;;) {
12397 		ipf = ipfp[0];
12398 		if (ipf != NULL) {
12399 			/*
12400 			 * It has to match on ident and src/dst address.
12401 			 */
12402 			if (ipf->ipf_ident == ident &&
12403 			    ipf->ipf_src == src &&
12404 			    ipf->ipf_dst == dst &&
12405 			    ipf->ipf_protocol == proto) {
12406 				/*
12407 				 * If we have received too many
12408 				 * duplicate fragments for this packet
12409 				 * free it.
12410 				 */
12411 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12412 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12413 					freemsg(mp);
12414 					mutex_exit(&ipfb->ipfb_lock);
12415 					return (B_FALSE);
12416 				}
12417 				/* Found it. */
12418 				break;
12419 			}
12420 			ipfp = &ipf->ipf_hash_next;
12421 			continue;
12422 		}
12423 
12424 		/*
12425 		 * If we pruned the list, do we want to store this new
12426 		 * fragment?. We apply an optimization here based on the
12427 		 * fact that most fragments will be received in order.
12428 		 * So if the offset of this incoming fragment is zero,
12429 		 * it is the first fragment of a new packet. We will
12430 		 * keep it.  Otherwise drop the fragment, as we have
12431 		 * probably pruned the packet already (since the
12432 		 * packet cannot be found).
12433 		 */
12434 		if (pruned && offset != 0) {
12435 			mutex_exit(&ipfb->ipfb_lock);
12436 			freemsg(mp);
12437 			return (B_FALSE);
12438 		}
12439 
12440 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12441 			/*
12442 			 * Too many fragmented packets in this hash
12443 			 * bucket. Free the oldest.
12444 			 */
12445 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12446 		}
12447 
12448 		/* New guy.  Allocate a frag message. */
12449 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12450 		if (mp1 == NULL) {
12451 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12452 			freemsg(mp);
12453 reass_done:
12454 			mutex_exit(&ipfb->ipfb_lock);
12455 			return (B_FALSE);
12456 		}
12457 
12458 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12459 		mp1->b_cont = mp;
12460 
12461 		/* Initialize the fragment header. */
12462 		ipf = (ipf_t *)mp1->b_rptr;
12463 		ipf->ipf_mp = mp1;
12464 		ipf->ipf_ptphn = ipfp;
12465 		ipfp[0] = ipf;
12466 		ipf->ipf_hash_next = NULL;
12467 		ipf->ipf_ident = ident;
12468 		ipf->ipf_protocol = proto;
12469 		ipf->ipf_src = src;
12470 		ipf->ipf_dst = dst;
12471 		ipf->ipf_nf_hdr_len = 0;
12472 		/* Record reassembly start time. */
12473 		ipf->ipf_timestamp = gethrestime_sec();
12474 		/* Record ipf generation and account for frag header */
12475 		ipf->ipf_gen = ill->ill_ipf_gen++;
12476 		ipf->ipf_count = MBLKSIZE(mp1);
12477 		ipf->ipf_last_frag_seen = B_FALSE;
12478 		ipf->ipf_ecn = ecn_info;
12479 		ipf->ipf_num_dups = 0;
12480 		ipfb->ipfb_frag_pkts++;
12481 		ipf->ipf_checksum = 0;
12482 		ipf->ipf_checksum_flags = 0;
12483 
12484 		/* Store checksum value in fragment header */
12485 		if (sum_flags != 0) {
12486 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12487 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12488 			ipf->ipf_checksum = sum_val;
12489 			ipf->ipf_checksum_flags = sum_flags;
12490 		}
12491 
12492 		/*
12493 		 * We handle reassembly two ways.  In the easy case,
12494 		 * where all the fragments show up in order, we do
12495 		 * minimal bookkeeping, and just clip new pieces on
12496 		 * the end.  If we ever see a hole, then we go off
12497 		 * to ip_reassemble which has to mark the pieces and
12498 		 * keep track of the number of holes, etc.  Obviously,
12499 		 * the point of having both mechanisms is so we can
12500 		 * handle the easy case as efficiently as possible.
12501 		 */
12502 		if (offset == 0) {
12503 			/* Easy case, in-order reassembly so far. */
12504 			ipf->ipf_count += msg_len;
12505 			ipf->ipf_tail_mp = tail_mp;
12506 			/*
12507 			 * Keep track of next expected offset in
12508 			 * ipf_end.
12509 			 */
12510 			ipf->ipf_end = end;
12511 			ipf->ipf_nf_hdr_len = hdr_length;
12512 		} else {
12513 			/* Hard case, hole at the beginning. */
12514 			ipf->ipf_tail_mp = NULL;
12515 			/*
12516 			 * ipf_end == 0 means that we have given up
12517 			 * on easy reassembly.
12518 			 */
12519 			ipf->ipf_end = 0;
12520 
12521 			/* Forget checksum offload from now on */
12522 			ipf->ipf_checksum_flags = 0;
12523 
12524 			/*
12525 			 * ipf_hole_cnt is set by ip_reassemble.
12526 			 * ipf_count is updated by ip_reassemble.
12527 			 * No need to check for return value here
12528 			 * as we don't expect reassembly to complete
12529 			 * or fail for the first fragment itself.
12530 			 */
12531 			(void) ip_reassemble(mp, ipf,
12532 			    (frag_offset_flags & IPH_OFFSET) << 3,
12533 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12534 		}
12535 		/* Update per ipfb and ill byte counts */
12536 		ipfb->ipfb_count += ipf->ipf_count;
12537 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12538 		ill->ill_frag_count += ipf->ipf_count;
12539 		/* If the frag timer wasn't already going, start it. */
12540 		mutex_enter(&ill->ill_lock);
12541 		ill_frag_timer_start(ill);
12542 		mutex_exit(&ill->ill_lock);
12543 		goto reass_done;
12544 	}
12545 
12546 	/*
12547 	 * If the packet's flag has changed (it could be coming up
12548 	 * from an interface different than the previous, therefore
12549 	 * possibly different checksum capability), then forget about
12550 	 * any stored checksum states.  Otherwise add the value to
12551 	 * the existing one stored in the fragment header.
12552 	 */
12553 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12554 		sum_val += ipf->ipf_checksum;
12555 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12556 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12557 		ipf->ipf_checksum = sum_val;
12558 	} else if (ipf->ipf_checksum_flags != 0) {
12559 		/* Forget checksum offload from now on */
12560 		ipf->ipf_checksum_flags = 0;
12561 	}
12562 
12563 	/*
12564 	 * We have a new piece of a datagram which is already being
12565 	 * reassembled.  Update the ECN info if all IP fragments
12566 	 * are ECN capable.  If there is one which is not, clear
12567 	 * all the info.  If there is at least one which has CE
12568 	 * code point, IP needs to report that up to transport.
12569 	 */
12570 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12571 		if (ecn_info == IPH_ECN_CE)
12572 			ipf->ipf_ecn = IPH_ECN_CE;
12573 	} else {
12574 		ipf->ipf_ecn = IPH_ECN_NECT;
12575 	}
12576 	if (offset && ipf->ipf_end == offset) {
12577 		/* The new fragment fits at the end */
12578 		ipf->ipf_tail_mp->b_cont = mp;
12579 		/* Update the byte count */
12580 		ipf->ipf_count += msg_len;
12581 		/* Update per ipfb and ill byte counts */
12582 		ipfb->ipfb_count += msg_len;
12583 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12584 		ill->ill_frag_count += msg_len;
12585 		if (frag_offset_flags & IPH_MF) {
12586 			/* More to come. */
12587 			ipf->ipf_end = end;
12588 			ipf->ipf_tail_mp = tail_mp;
12589 			goto reass_done;
12590 		}
12591 	} else {
12592 		/* Go do the hard cases. */
12593 		int ret;
12594 
12595 		if (offset == 0)
12596 			ipf->ipf_nf_hdr_len = hdr_length;
12597 
12598 		/* Save current byte count */
12599 		count = ipf->ipf_count;
12600 		ret = ip_reassemble(mp, ipf,
12601 		    (frag_offset_flags & IPH_OFFSET) << 3,
12602 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12603 		/* Count of bytes added and subtracted (freeb()ed) */
12604 		count = ipf->ipf_count - count;
12605 		if (count) {
12606 			/* Update per ipfb and ill byte counts */
12607 			ipfb->ipfb_count += count;
12608 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12609 			ill->ill_frag_count += count;
12610 		}
12611 		if (ret == IP_REASS_PARTIAL) {
12612 			goto reass_done;
12613 		} else if (ret == IP_REASS_FAILED) {
12614 			/* Reassembly failed. Free up all resources */
12615 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12616 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12617 				IP_REASS_SET_START(t_mp, 0);
12618 				IP_REASS_SET_END(t_mp, 0);
12619 			}
12620 			freemsg(mp);
12621 			goto reass_done;
12622 		}
12623 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12624 	}
12625 	/*
12626 	 * We have completed reassembly.  Unhook the frag header from
12627 	 * the reassembly list.
12628 	 *
12629 	 * Before we free the frag header, record the ECN info
12630 	 * to report back to the transport.
12631 	 */
12632 	ecn_info = ipf->ipf_ecn;
12633 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12634 	ipfp = ipf->ipf_ptphn;
12635 
12636 	/* We need to supply these to caller */
12637 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12638 		sum_val = ipf->ipf_checksum;
12639 	else
12640 		sum_val = 0;
12641 
12642 	mp1 = ipf->ipf_mp;
12643 	count = ipf->ipf_count;
12644 	ipf = ipf->ipf_hash_next;
12645 	if (ipf != NULL)
12646 		ipf->ipf_ptphn = ipfp;
12647 	ipfp[0] = ipf;
12648 	ill->ill_frag_count -= count;
12649 	ASSERT(ipfb->ipfb_count >= count);
12650 	ipfb->ipfb_count -= count;
12651 	ipfb->ipfb_frag_pkts--;
12652 	mutex_exit(&ipfb->ipfb_lock);
12653 	/* Ditch the frag header. */
12654 	mp = mp1->b_cont;
12655 
12656 	freeb(mp1);
12657 
12658 	/* Restore original IP length in header. */
12659 	packet_size = (uint32_t)msgdsize(mp);
12660 	if (packet_size > IP_MAXPACKET) {
12661 		freemsg(mp);
12662 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12663 		return (B_FALSE);
12664 	}
12665 
12666 	if (DB_REF(mp) > 1) {
12667 		mblk_t *mp2 = copymsg(mp);
12668 
12669 		freemsg(mp);
12670 		if (mp2 == NULL) {
12671 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12672 			return (B_FALSE);
12673 		}
12674 		mp = mp2;
12675 	}
12676 	ipha = (ipha_t *)mp->b_rptr;
12677 
12678 	ipha->ipha_length = htons((uint16_t)packet_size);
12679 	/* We're now complete, zip the frag state */
12680 	ipha->ipha_fragment_offset_and_flags = 0;
12681 	/* Record the ECN info. */
12682 	ipha->ipha_type_of_service &= 0xFC;
12683 	ipha->ipha_type_of_service |= ecn_info;
12684 	*mpp = mp;
12685 
12686 	/* Reassembly is successful; return checksum information if needed */
12687 	if (cksum_val != NULL)
12688 		*cksum_val = sum_val;
12689 	if (cksum_flags != NULL)
12690 		*cksum_flags = sum_flags;
12691 
12692 	return (B_TRUE);
12693 }
12694 
12695 /*
12696  * Perform ip header check sum update local options.
12697  * return B_TRUE if all is well, else return B_FALSE and release
12698  * the mp. caller is responsible for decrementing ire ref cnt.
12699  */
12700 static boolean_t
12701 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12702     ip_stack_t *ipst)
12703 {
12704 	mblk_t		*first_mp;
12705 	boolean_t	mctl_present;
12706 	uint16_t	sum;
12707 
12708 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12709 	/*
12710 	 * Don't do the checksum if it has gone through AH/ESP
12711 	 * processing.
12712 	 */
12713 	if (!mctl_present) {
12714 		sum = ip_csum_hdr(ipha);
12715 		if (sum != 0) {
12716 			if (ill != NULL) {
12717 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12718 			} else {
12719 				BUMP_MIB(&ipst->ips_ip_mib,
12720 				    ipIfStatsInCksumErrs);
12721 			}
12722 			freemsg(first_mp);
12723 			return (B_FALSE);
12724 		}
12725 	}
12726 
12727 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12728 		if (mctl_present)
12729 			freeb(first_mp);
12730 		return (B_FALSE);
12731 	}
12732 
12733 	return (B_TRUE);
12734 }
12735 
12736 /*
12737  * All udp packet are delivered to the local host via this routine.
12738  */
12739 void
12740 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12741     ill_t *recv_ill)
12742 {
12743 	uint32_t	sum;
12744 	uint32_t	u1;
12745 	boolean_t	mctl_present;
12746 	conn_t		*connp;
12747 	mblk_t		*first_mp;
12748 	uint16_t	*up;
12749 	ill_t		*ill = (ill_t *)q->q_ptr;
12750 	uint16_t	reass_hck_flags = 0;
12751 	ip_stack_t	*ipst;
12752 
12753 	ASSERT(recv_ill != NULL);
12754 	ipst = recv_ill->ill_ipst;
12755 
12756 #define	rptr    ((uchar_t *)ipha)
12757 
12758 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12759 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12760 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12761 	ASSERT(ill != NULL);
12762 
12763 	/*
12764 	 * FAST PATH for udp packets
12765 	 */
12766 
12767 	/* u1 is # words of IP options */
12768 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12769 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12770 
12771 	/* IP options present */
12772 	if (u1 != 0)
12773 		goto ipoptions;
12774 
12775 	/* Check the IP header checksum.  */
12776 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12777 		/* Clear the IP header h/w cksum flag */
12778 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12779 	} else if (!mctl_present) {
12780 		/*
12781 		 * Don't verify header checksum if this packet is coming
12782 		 * back from AH/ESP as we already did it.
12783 		 */
12784 #define	uph	((uint16_t *)ipha)
12785 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12786 		    uph[6] + uph[7] + uph[8] + uph[9];
12787 #undef	uph
12788 		/* finish doing IP checksum */
12789 		sum = (sum & 0xFFFF) + (sum >> 16);
12790 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12791 		if (sum != 0 && sum != 0xFFFF) {
12792 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12793 			freemsg(first_mp);
12794 			return;
12795 		}
12796 	}
12797 
12798 	/*
12799 	 * Count for SNMP of inbound packets for ire.
12800 	 * if mctl is present this might be a secure packet and
12801 	 * has already been counted for in ip_proto_input().
12802 	 */
12803 	if (!mctl_present) {
12804 		UPDATE_IB_PKT_COUNT(ire);
12805 		ire->ire_last_used_time = lbolt;
12806 	}
12807 
12808 	/* packet part of fragmented IP packet? */
12809 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12810 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12811 		goto fragmented;
12812 	}
12813 
12814 	/* u1 = IP header length (20 bytes) */
12815 	u1 = IP_SIMPLE_HDR_LENGTH;
12816 
12817 	/* packet does not contain complete IP & UDP headers */
12818 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12819 		goto udppullup;
12820 
12821 	/* up points to UDP header */
12822 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12823 #define	iphs    ((uint16_t *)ipha)
12824 
12825 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12826 	if (up[3] != 0) {
12827 		mblk_t *mp1 = mp->b_cont;
12828 		boolean_t cksum_err;
12829 		uint16_t hck_flags = 0;
12830 
12831 		/* Pseudo-header checksum */
12832 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12833 		    iphs[9] + up[2];
12834 
12835 		/*
12836 		 * Revert to software checksum calculation if the interface
12837 		 * isn't capable of checksum offload or if IPsec is present.
12838 		 */
12839 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12840 			hck_flags = DB_CKSUMFLAGS(mp);
12841 
12842 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12843 			IP_STAT(ipst, ip_in_sw_cksum);
12844 
12845 		IP_CKSUM_RECV(hck_flags, u1,
12846 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12847 		    (int32_t)((uchar_t *)up - rptr),
12848 		    mp, mp1, cksum_err);
12849 
12850 		if (cksum_err) {
12851 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12852 			if (hck_flags & HCK_FULLCKSUM)
12853 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12854 			else if (hck_flags & HCK_PARTIALCKSUM)
12855 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12856 			else
12857 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12858 
12859 			freemsg(first_mp);
12860 			return;
12861 		}
12862 	}
12863 
12864 	/* Non-fragmented broadcast or multicast packet? */
12865 	if (ire->ire_type == IRE_BROADCAST)
12866 		goto udpslowpath;
12867 
12868 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12869 	    ire->ire_zoneid, ipst)) != NULL) {
12870 		ASSERT(connp->conn_upq != NULL);
12871 		IP_STAT(ipst, ip_udp_fast_path);
12872 
12873 		if (CONN_UDP_FLOWCTLD(connp)) {
12874 			freemsg(mp);
12875 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12876 		} else {
12877 			if (!mctl_present) {
12878 				BUMP_MIB(ill->ill_ip_mib,
12879 				    ipIfStatsHCInDelivers);
12880 			}
12881 			/*
12882 			 * mp and first_mp can change.
12883 			 */
12884 			if (ip_udp_check(q, connp, recv_ill,
12885 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12886 				/* Send it upstream */
12887 				CONN_UDP_RECV(connp, mp);
12888 			}
12889 		}
12890 		/*
12891 		 * freeb() cannot deal with null mblk being passed
12892 		 * in and first_mp can be set to null in the call
12893 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12894 		 */
12895 		if (mctl_present && first_mp != NULL) {
12896 			freeb(first_mp);
12897 		}
12898 		CONN_DEC_REF(connp);
12899 		return;
12900 	}
12901 
12902 	/*
12903 	 * if we got here we know the packet is not fragmented and
12904 	 * has no options. The classifier could not find a conn_t and
12905 	 * most likely its an icmp packet so send it through slow path.
12906 	 */
12907 
12908 	goto udpslowpath;
12909 
12910 ipoptions:
12911 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12912 		goto slow_done;
12913 	}
12914 
12915 	UPDATE_IB_PKT_COUNT(ire);
12916 	ire->ire_last_used_time = lbolt;
12917 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12918 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12919 fragmented:
12920 		/*
12921 		 * "sum" and "reass_hck_flags" are non-zero if the
12922 		 * reassembled packet has a valid hardware computed
12923 		 * checksum information associated with it.
12924 		 */
12925 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12926 			goto slow_done;
12927 		/*
12928 		 * Make sure that first_mp points back to mp as
12929 		 * the mp we came in with could have changed in
12930 		 * ip_rput_fragment().
12931 		 */
12932 		ASSERT(!mctl_present);
12933 		ipha = (ipha_t *)mp->b_rptr;
12934 		first_mp = mp;
12935 	}
12936 
12937 	/* Now we have a complete datagram, destined for this machine. */
12938 	u1 = IPH_HDR_LENGTH(ipha);
12939 	/* Pull up the UDP header, if necessary. */
12940 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12941 udppullup:
12942 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12943 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12944 			freemsg(first_mp);
12945 			goto slow_done;
12946 		}
12947 		ipha = (ipha_t *)mp->b_rptr;
12948 	}
12949 
12950 	/*
12951 	 * Validate the checksum for the reassembled packet; for the
12952 	 * pullup case we calculate the payload checksum in software.
12953 	 */
12954 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12955 	if (up[3] != 0) {
12956 		boolean_t cksum_err;
12957 
12958 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12959 			IP_STAT(ipst, ip_in_sw_cksum);
12960 
12961 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12962 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12963 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12964 		    iphs[9] + up[2], sum, cksum_err);
12965 
12966 		if (cksum_err) {
12967 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12968 
12969 			if (reass_hck_flags & HCK_FULLCKSUM)
12970 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12971 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12972 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12973 			else
12974 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12975 
12976 			freemsg(first_mp);
12977 			goto slow_done;
12978 		}
12979 	}
12980 udpslowpath:
12981 
12982 	/* Clear hardware checksum flag to be safe */
12983 	DB_CKSUMFLAGS(mp) = 0;
12984 
12985 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12986 	    (ire->ire_type == IRE_BROADCAST),
12987 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12988 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12989 
12990 slow_done:
12991 	IP_STAT(ipst, ip_udp_slow_path);
12992 	return;
12993 
12994 #undef  iphs
12995 #undef  rptr
12996 }
12997 
12998 /* ARGSUSED */
12999 static mblk_t *
13000 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13001     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
13002     ill_rx_ring_t *ill_ring)
13003 {
13004 	conn_t		*connp;
13005 	uint32_t	sum;
13006 	uint32_t	u1;
13007 	uint16_t	*up;
13008 	int		offset;
13009 	ssize_t		len;
13010 	mblk_t		*mp1;
13011 	boolean_t	syn_present = B_FALSE;
13012 	tcph_t		*tcph;
13013 	uint_t		ip_hdr_len;
13014 	ill_t		*ill = (ill_t *)q->q_ptr;
13015 	zoneid_t	zoneid = ire->ire_zoneid;
13016 	boolean_t	cksum_err;
13017 	uint16_t	hck_flags = 0;
13018 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13019 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13020 
13021 #define	rptr	((uchar_t *)ipha)
13022 
13023 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13024 	ASSERT(ill != NULL);
13025 
13026 	/*
13027 	 * FAST PATH for tcp packets
13028 	 */
13029 
13030 	/* u1 is # words of IP options */
13031 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13032 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13033 
13034 	/* IP options present */
13035 	if (u1) {
13036 		goto ipoptions;
13037 	} else if (!mctl_present) {
13038 		/* Check the IP header checksum.  */
13039 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13040 			/* Clear the IP header h/w cksum flag */
13041 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13042 		} else if (!mctl_present) {
13043 			/*
13044 			 * Don't verify header checksum if this packet
13045 			 * is coming back from AH/ESP as we already did it.
13046 			 */
13047 #define	uph	((uint16_t *)ipha)
13048 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13049 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13050 #undef	uph
13051 			/* finish doing IP checksum */
13052 			sum = (sum & 0xFFFF) + (sum >> 16);
13053 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13054 			if (sum != 0 && sum != 0xFFFF) {
13055 				BUMP_MIB(ill->ill_ip_mib,
13056 				    ipIfStatsInCksumErrs);
13057 				goto error;
13058 			}
13059 		}
13060 	}
13061 
13062 	if (!mctl_present) {
13063 		UPDATE_IB_PKT_COUNT(ire);
13064 		ire->ire_last_used_time = lbolt;
13065 	}
13066 
13067 	/* packet part of fragmented IP packet? */
13068 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13069 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13070 		goto fragmented;
13071 	}
13072 
13073 	/* u1 = IP header length (20 bytes) */
13074 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13075 
13076 	/* does packet contain IP+TCP headers? */
13077 	len = mp->b_wptr - rptr;
13078 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13079 		IP_STAT(ipst, ip_tcppullup);
13080 		goto tcppullup;
13081 	}
13082 
13083 	/* TCP options present? */
13084 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13085 
13086 	/*
13087 	 * If options need to be pulled up, then goto tcpoptions.
13088 	 * otherwise we are still in the fast path
13089 	 */
13090 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13091 		IP_STAT(ipst, ip_tcpoptions);
13092 		goto tcpoptions;
13093 	}
13094 
13095 	/* multiple mblks of tcp data? */
13096 	if ((mp1 = mp->b_cont) != NULL) {
13097 		/* more then two? */
13098 		if (mp1->b_cont != NULL) {
13099 			IP_STAT(ipst, ip_multipkttcp);
13100 			goto multipkttcp;
13101 		}
13102 		len += mp1->b_wptr - mp1->b_rptr;
13103 	}
13104 
13105 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13106 
13107 	/* part of pseudo checksum */
13108 
13109 	/* TCP datagram length */
13110 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13111 
13112 #define	iphs    ((uint16_t *)ipha)
13113 
13114 #ifdef	_BIG_ENDIAN
13115 	u1 += IPPROTO_TCP;
13116 #else
13117 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13118 #endif
13119 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13120 
13121 	/*
13122 	 * Revert to software checksum calculation if the interface
13123 	 * isn't capable of checksum offload or if IPsec is present.
13124 	 */
13125 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13126 		hck_flags = DB_CKSUMFLAGS(mp);
13127 
13128 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13129 		IP_STAT(ipst, ip_in_sw_cksum);
13130 
13131 	IP_CKSUM_RECV(hck_flags, u1,
13132 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13133 	    (int32_t)((uchar_t *)up - rptr),
13134 	    mp, mp1, cksum_err);
13135 
13136 	if (cksum_err) {
13137 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13138 
13139 		if (hck_flags & HCK_FULLCKSUM)
13140 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13141 		else if (hck_flags & HCK_PARTIALCKSUM)
13142 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13143 		else
13144 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13145 
13146 		goto error;
13147 	}
13148 
13149 try_again:
13150 
13151 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13152 	    zoneid, ipst)) == NULL) {
13153 		/* Send the TH_RST */
13154 		goto no_conn;
13155 	}
13156 
13157 	/*
13158 	 * TCP FAST PATH for AF_INET socket.
13159 	 *
13160 	 * TCP fast path to avoid extra work. An AF_INET socket type
13161 	 * does not have facility to receive extra information via
13162 	 * ip_process or ip_add_info. Also, when the connection was
13163 	 * established, we made a check if this connection is impacted
13164 	 * by any global IPsec policy or per connection policy (a
13165 	 * policy that comes in effect later will not apply to this
13166 	 * connection). Since all this can be determined at the
13167 	 * connection establishment time, a quick check of flags
13168 	 * can avoid extra work.
13169 	 */
13170 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13171 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13172 		ASSERT(first_mp == mp);
13173 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13174 		SET_SQUEUE(mp, tcp_rput_data, connp);
13175 		return (mp);
13176 	}
13177 
13178 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13179 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13180 		if (IPCL_IS_TCP(connp)) {
13181 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13182 			DB_CKSUMSTART(mp) =
13183 			    (intptr_t)ip_squeue_get(ill_ring);
13184 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13185 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13186 				BUMP_MIB(ill->ill_ip_mib,
13187 				    ipIfStatsHCInDelivers);
13188 				SET_SQUEUE(mp, connp->conn_recv, connp);
13189 				return (mp);
13190 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13191 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13192 				BUMP_MIB(ill->ill_ip_mib,
13193 				    ipIfStatsHCInDelivers);
13194 				ip_squeue_enter_unbound++;
13195 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13196 				    connp);
13197 				return (mp);
13198 			}
13199 			syn_present = B_TRUE;
13200 		}
13201 
13202 	}
13203 
13204 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13205 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13206 
13207 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13208 		/* No need to send this packet to TCP */
13209 		if ((flags & TH_RST) || (flags & TH_URG)) {
13210 			CONN_DEC_REF(connp);
13211 			freemsg(first_mp);
13212 			return (NULL);
13213 		}
13214 		if (flags & TH_ACK) {
13215 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13216 			    ipst->ips_netstack->netstack_tcp, connp);
13217 			CONN_DEC_REF(connp);
13218 			return (NULL);
13219 		}
13220 
13221 		CONN_DEC_REF(connp);
13222 		freemsg(first_mp);
13223 		return (NULL);
13224 	}
13225 
13226 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13227 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13228 		    ipha, NULL, mctl_present);
13229 		if (first_mp == NULL) {
13230 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13231 			CONN_DEC_REF(connp);
13232 			return (NULL);
13233 		}
13234 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13235 			ASSERT(syn_present);
13236 			if (mctl_present) {
13237 				ASSERT(first_mp != mp);
13238 				first_mp->b_datap->db_struioflag |=
13239 				    STRUIO_POLICY;
13240 			} else {
13241 				ASSERT(first_mp == mp);
13242 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13243 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13244 			}
13245 		} else {
13246 			/*
13247 			 * Discard first_mp early since we're dealing with a
13248 			 * fully-connected conn_t and tcp doesn't do policy in
13249 			 * this case.
13250 			 */
13251 			if (mctl_present) {
13252 				freeb(first_mp);
13253 				mctl_present = B_FALSE;
13254 			}
13255 			first_mp = mp;
13256 		}
13257 	}
13258 
13259 	/* Initiate IPPF processing for fastpath */
13260 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13261 		uint32_t	ill_index;
13262 
13263 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13264 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13265 		if (mp == NULL) {
13266 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13267 			    "deferred/dropped during IPPF processing\n"));
13268 			CONN_DEC_REF(connp);
13269 			if (mctl_present)
13270 				freeb(first_mp);
13271 			return (NULL);
13272 		} else if (mctl_present) {
13273 			/*
13274 			 * ip_process might return a new mp.
13275 			 */
13276 			ASSERT(first_mp != mp);
13277 			first_mp->b_cont = mp;
13278 		} else {
13279 			first_mp = mp;
13280 		}
13281 
13282 	}
13283 
13284 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13285 		/*
13286 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13287 		 * make sure IPF_RECVIF is passed to ip_add_info.
13288 		 */
13289 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13290 		    IPCL_ZONEID(connp), ipst);
13291 		if (mp == NULL) {
13292 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13293 			CONN_DEC_REF(connp);
13294 			if (mctl_present)
13295 				freeb(first_mp);
13296 			return (NULL);
13297 		} else if (mctl_present) {
13298 			/*
13299 			 * ip_add_info might return a new mp.
13300 			 */
13301 			ASSERT(first_mp != mp);
13302 			first_mp->b_cont = mp;
13303 		} else {
13304 			first_mp = mp;
13305 		}
13306 	}
13307 
13308 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13309 	if (IPCL_IS_TCP(connp)) {
13310 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13311 		return (first_mp);
13312 	} else {
13313 		putnext(connp->conn_rq, first_mp);
13314 		CONN_DEC_REF(connp);
13315 		return (NULL);
13316 	}
13317 
13318 no_conn:
13319 	/* Initiate IPPf processing, if needed. */
13320 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13321 		uint32_t ill_index;
13322 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13323 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13324 		if (first_mp == NULL) {
13325 			return (NULL);
13326 		}
13327 	}
13328 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13329 
13330 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13331 	    ipst->ips_netstack->netstack_tcp, NULL);
13332 	return (NULL);
13333 ipoptions:
13334 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13335 		goto slow_done;
13336 	}
13337 
13338 	UPDATE_IB_PKT_COUNT(ire);
13339 	ire->ire_last_used_time = lbolt;
13340 
13341 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13342 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13343 fragmented:
13344 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13345 			if (mctl_present)
13346 				freeb(first_mp);
13347 			goto slow_done;
13348 		}
13349 		/*
13350 		 * Make sure that first_mp points back to mp as
13351 		 * the mp we came in with could have changed in
13352 		 * ip_rput_fragment().
13353 		 */
13354 		ASSERT(!mctl_present);
13355 		ipha = (ipha_t *)mp->b_rptr;
13356 		first_mp = mp;
13357 	}
13358 
13359 	/* Now we have a complete datagram, destined for this machine. */
13360 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13361 
13362 	len = mp->b_wptr - mp->b_rptr;
13363 	/* Pull up a minimal TCP header, if necessary. */
13364 	if (len < (u1 + 20)) {
13365 tcppullup:
13366 		if (!pullupmsg(mp, u1 + 20)) {
13367 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13368 			goto error;
13369 		}
13370 		ipha = (ipha_t *)mp->b_rptr;
13371 		len = mp->b_wptr - mp->b_rptr;
13372 	}
13373 
13374 	/*
13375 	 * Extract the offset field from the TCP header.  As usual, we
13376 	 * try to help the compiler more than the reader.
13377 	 */
13378 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13379 	if (offset != 5) {
13380 tcpoptions:
13381 		if (offset < 5) {
13382 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13383 			goto error;
13384 		}
13385 		/*
13386 		 * There must be TCP options.
13387 		 * Make sure we can grab them.
13388 		 */
13389 		offset <<= 2;
13390 		offset += u1;
13391 		if (len < offset) {
13392 			if (!pullupmsg(mp, offset)) {
13393 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13394 				goto error;
13395 			}
13396 			ipha = (ipha_t *)mp->b_rptr;
13397 			len = mp->b_wptr - rptr;
13398 		}
13399 	}
13400 
13401 	/* Get the total packet length in len, including headers. */
13402 	if (mp->b_cont) {
13403 multipkttcp:
13404 		len = msgdsize(mp);
13405 	}
13406 
13407 	/*
13408 	 * Check the TCP checksum by pulling together the pseudo-
13409 	 * header checksum, and passing it to ip_csum to be added in
13410 	 * with the TCP datagram.
13411 	 *
13412 	 * Since we are not using the hwcksum if available we must
13413 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13414 	 * If either of these fails along the way the mblk is freed.
13415 	 * If this logic ever changes and mblk is reused to say send
13416 	 * ICMP's back, then this flag may need to be cleared in
13417 	 * other places as well.
13418 	 */
13419 	DB_CKSUMFLAGS(mp) = 0;
13420 
13421 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13422 
13423 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13424 #ifdef	_BIG_ENDIAN
13425 	u1 += IPPROTO_TCP;
13426 #else
13427 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13428 #endif
13429 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13430 	/*
13431 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13432 	 */
13433 	IP_STAT(ipst, ip_in_sw_cksum);
13434 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13435 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13436 		goto error;
13437 	}
13438 
13439 	IP_STAT(ipst, ip_tcp_slow_path);
13440 	goto try_again;
13441 #undef  iphs
13442 #undef  rptr
13443 
13444 error:
13445 	freemsg(first_mp);
13446 slow_done:
13447 	return (NULL);
13448 }
13449 
13450 /* ARGSUSED */
13451 static void
13452 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13453     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13454 {
13455 	conn_t		*connp;
13456 	uint32_t	sum;
13457 	uint32_t	u1;
13458 	ssize_t		len;
13459 	sctp_hdr_t	*sctph;
13460 	zoneid_t	zoneid = ire->ire_zoneid;
13461 	uint32_t	pktsum;
13462 	uint32_t	calcsum;
13463 	uint32_t	ports;
13464 	in6_addr_t	map_src, map_dst;
13465 	ill_t		*ill = (ill_t *)q->q_ptr;
13466 	ip_stack_t	*ipst;
13467 	sctp_stack_t	*sctps;
13468 
13469 	ASSERT(recv_ill != NULL);
13470 	ipst = recv_ill->ill_ipst;
13471 	sctps = ipst->ips_netstack->netstack_sctp;
13472 
13473 #define	rptr	((uchar_t *)ipha)
13474 
13475 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13476 	ASSERT(ill != NULL);
13477 
13478 	/* u1 is # words of IP options */
13479 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13480 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13481 
13482 	/* IP options present */
13483 	if (u1 > 0) {
13484 		goto ipoptions;
13485 	} else {
13486 		/* Check the IP header checksum.  */
13487 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13488 		    !mctl_present) {
13489 #define	uph	((uint16_t *)ipha)
13490 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13491 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13492 #undef	uph
13493 			/* finish doing IP checksum */
13494 			sum = (sum & 0xFFFF) + (sum >> 16);
13495 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13496 			/*
13497 			 * Don't verify header checksum if this packet
13498 			 * is coming back from AH/ESP as we already did it.
13499 			 */
13500 			if (sum != 0 && sum != 0xFFFF) {
13501 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13502 				goto error;
13503 			}
13504 		}
13505 		/*
13506 		 * Since there is no SCTP h/w cksum support yet, just
13507 		 * clear the flag.
13508 		 */
13509 		DB_CKSUMFLAGS(mp) = 0;
13510 	}
13511 
13512 	/*
13513 	 * Don't verify header checksum if this packet is coming
13514 	 * back from AH/ESP as we already did it.
13515 	 */
13516 	if (!mctl_present) {
13517 		UPDATE_IB_PKT_COUNT(ire);
13518 		ire->ire_last_used_time = lbolt;
13519 	}
13520 
13521 	/* packet part of fragmented IP packet? */
13522 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13523 	if (u1 & (IPH_MF | IPH_OFFSET))
13524 		goto fragmented;
13525 
13526 	/* u1 = IP header length (20 bytes) */
13527 	u1 = IP_SIMPLE_HDR_LENGTH;
13528 
13529 find_sctp_client:
13530 	/* Pullup if we don't have the sctp common header. */
13531 	len = MBLKL(mp);
13532 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13533 		if (mp->b_cont == NULL ||
13534 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13535 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13536 			goto error;
13537 		}
13538 		ipha = (ipha_t *)mp->b_rptr;
13539 		len = MBLKL(mp);
13540 	}
13541 
13542 	sctph = (sctp_hdr_t *)(rptr + u1);
13543 #ifdef	DEBUG
13544 	if (!skip_sctp_cksum) {
13545 #endif
13546 		pktsum = sctph->sh_chksum;
13547 		sctph->sh_chksum = 0;
13548 		calcsum = sctp_cksum(mp, u1);
13549 		if (calcsum != pktsum) {
13550 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13551 			goto error;
13552 		}
13553 		sctph->sh_chksum = pktsum;
13554 #ifdef	DEBUG	/* skip_sctp_cksum */
13555 	}
13556 #endif
13557 	/* get the ports */
13558 	ports = *(uint32_t *)&sctph->sh_sport;
13559 
13560 	IRE_REFRELE(ire);
13561 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13562 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13563 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13564 	    sctps)) == NULL) {
13565 		/* Check for raw socket or OOTB handling */
13566 		goto no_conn;
13567 	}
13568 
13569 	/* Found a client; up it goes */
13570 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13571 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13572 	return;
13573 
13574 no_conn:
13575 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13576 	    ports, mctl_present, flags, B_TRUE, zoneid);
13577 	return;
13578 
13579 ipoptions:
13580 	DB_CKSUMFLAGS(mp) = 0;
13581 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13582 		goto slow_done;
13583 
13584 	UPDATE_IB_PKT_COUNT(ire);
13585 	ire->ire_last_used_time = lbolt;
13586 
13587 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13588 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13589 fragmented:
13590 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13591 			goto slow_done;
13592 		/*
13593 		 * Make sure that first_mp points back to mp as
13594 		 * the mp we came in with could have changed in
13595 		 * ip_rput_fragment().
13596 		 */
13597 		ASSERT(!mctl_present);
13598 		ipha = (ipha_t *)mp->b_rptr;
13599 		first_mp = mp;
13600 	}
13601 
13602 	/* Now we have a complete datagram, destined for this machine. */
13603 	u1 = IPH_HDR_LENGTH(ipha);
13604 	goto find_sctp_client;
13605 #undef  iphs
13606 #undef  rptr
13607 
13608 error:
13609 	freemsg(first_mp);
13610 slow_done:
13611 	IRE_REFRELE(ire);
13612 }
13613 
13614 #define	VER_BITS	0xF0
13615 #define	VERSION_6	0x60
13616 
13617 static boolean_t
13618 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13619     ipaddr_t *dstp, ip_stack_t *ipst)
13620 {
13621 	uint_t	opt_len;
13622 	ipha_t *ipha;
13623 	ssize_t len;
13624 	uint_t	pkt_len;
13625 
13626 	ASSERT(ill != NULL);
13627 	IP_STAT(ipst, ip_ipoptions);
13628 	ipha = *iphapp;
13629 
13630 #define	rptr    ((uchar_t *)ipha)
13631 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13632 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13633 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13634 		freemsg(mp);
13635 		return (B_FALSE);
13636 	}
13637 
13638 	/* multiple mblk or too short */
13639 	pkt_len = ntohs(ipha->ipha_length);
13640 
13641 	/* Get the number of words of IP options in the IP header. */
13642 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13643 	if (opt_len) {
13644 		/* IP Options present!  Validate and process. */
13645 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13646 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13647 			goto done;
13648 		}
13649 		/*
13650 		 * Recompute complete header length and make sure we
13651 		 * have access to all of it.
13652 		 */
13653 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13654 		if (len > (mp->b_wptr - rptr)) {
13655 			if (len > pkt_len) {
13656 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13657 				goto done;
13658 			}
13659 			if (!pullupmsg(mp, len)) {
13660 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13661 				goto done;
13662 			}
13663 			ipha = (ipha_t *)mp->b_rptr;
13664 		}
13665 		/*
13666 		 * Go off to ip_rput_options which returns the next hop
13667 		 * destination address, which may have been affected
13668 		 * by source routing.
13669 		 */
13670 		IP_STAT(ipst, ip_opt);
13671 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13672 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13673 			return (B_FALSE);
13674 		}
13675 	}
13676 	*iphapp = ipha;
13677 	return (B_TRUE);
13678 done:
13679 	/* clear b_prev - used by ip_mroute_decap */
13680 	mp->b_prev = NULL;
13681 	freemsg(mp);
13682 	return (B_FALSE);
13683 #undef  rptr
13684 }
13685 
13686 /*
13687  * Deal with the fact that there is no ire for the destination.
13688  */
13689 static ire_t *
13690 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13691 {
13692 	ipha_t	*ipha;
13693 	ill_t	*ill;
13694 	ire_t	*ire;
13695 	boolean_t	check_multirt = B_FALSE;
13696 	ip_stack_t *ipst;
13697 
13698 	ipha = (ipha_t *)mp->b_rptr;
13699 	ill = (ill_t *)q->q_ptr;
13700 
13701 	ASSERT(ill != NULL);
13702 	ipst = ill->ill_ipst;
13703 
13704 	/*
13705 	 * No IRE for this destination, so it can't be for us.
13706 	 * Unless we are forwarding, drop the packet.
13707 	 * We have to let source routed packets through
13708 	 * since we don't yet know if they are 'ping -l'
13709 	 * packets i.e. if they will go out over the
13710 	 * same interface as they came in on.
13711 	 */
13712 	if (ll_multicast) {
13713 		freemsg(mp);
13714 		return (NULL);
13715 	}
13716 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13717 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13718 		freemsg(mp);
13719 		return (NULL);
13720 	}
13721 
13722 	/*
13723 	 * Mark this packet as having originated externally.
13724 	 *
13725 	 * For non-forwarding code path, ire_send later double
13726 	 * checks this interface to see if it is still exists
13727 	 * post-ARP resolution.
13728 	 *
13729 	 * Also, IPQOS uses this to differentiate between
13730 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13731 	 * QOS packet processing in ip_wput_attach_llhdr().
13732 	 * The QoS module can mark the b_band for a fastpath message
13733 	 * or the dl_priority field in a unitdata_req header for
13734 	 * CoS marking. This info can only be found in
13735 	 * ip_wput_attach_llhdr().
13736 	 */
13737 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13738 	/*
13739 	 * Clear the indication that this may have a hardware checksum
13740 	 * as we are not using it
13741 	 */
13742 	DB_CKSUMFLAGS(mp) = 0;
13743 
13744 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13745 	    MBLK_GETLABEL(mp), ipst);
13746 
13747 	if (ire == NULL && check_multirt) {
13748 		/* Let ip_newroute handle CGTP  */
13749 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13750 		return (NULL);
13751 	}
13752 
13753 	if (ire != NULL)
13754 		return (ire);
13755 
13756 	mp->b_prev = mp->b_next = 0;
13757 	/* send icmp unreachable */
13758 	q = WR(q);
13759 	/* Sent by forwarding path, and router is global zone */
13760 	if (ip_source_routed(ipha, ipst)) {
13761 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13762 		    GLOBAL_ZONEID, ipst);
13763 	} else {
13764 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13765 		    ipst);
13766 	}
13767 
13768 	return (NULL);
13769 
13770 }
13771 
13772 /*
13773  * check ip header length and align it.
13774  */
13775 static boolean_t
13776 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13777 {
13778 	ssize_t len;
13779 	ill_t *ill;
13780 	ipha_t	*ipha;
13781 
13782 	len = MBLKL(mp);
13783 
13784 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13785 		ill = (ill_t *)q->q_ptr;
13786 
13787 		if (!OK_32PTR(mp->b_rptr))
13788 			IP_STAT(ipst, ip_notaligned1);
13789 		else
13790 			IP_STAT(ipst, ip_notaligned2);
13791 		/* Guard against bogus device drivers */
13792 		if (len < 0) {
13793 			/* clear b_prev - used by ip_mroute_decap */
13794 			mp->b_prev = NULL;
13795 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13796 			freemsg(mp);
13797 			return (B_FALSE);
13798 		}
13799 
13800 		if (ip_rput_pullups++ == 0) {
13801 			ipha = (ipha_t *)mp->b_rptr;
13802 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13803 			    "ip_check_and_align_header: %s forced us to "
13804 			    " pullup pkt, hdr len %ld, hdr addr %p",
13805 			    ill->ill_name, len, ipha);
13806 		}
13807 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13808 			/* clear b_prev - used by ip_mroute_decap */
13809 			mp->b_prev = NULL;
13810 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13811 			freemsg(mp);
13812 			return (B_FALSE);
13813 		}
13814 	}
13815 	return (B_TRUE);
13816 }
13817 
13818 ire_t *
13819 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13820 {
13821 	ire_t		*new_ire;
13822 	ill_t		*ire_ill;
13823 	uint_t		ifindex;
13824 	ip_stack_t	*ipst = ill->ill_ipst;
13825 	boolean_t	strict_check = B_FALSE;
13826 
13827 	/*
13828 	 * This packet came in on an interface other than the one associated
13829 	 * with the first ire we found for the destination address. We do
13830 	 * another ire lookup here, using the ingress ill, to see if the
13831 	 * interface is in an interface group.
13832 	 * As long as the ills belong to the same group, we don't consider
13833 	 * them to be arriving on the wrong interface. Thus, if the switch
13834 	 * is doing inbound load spreading, we won't drop packets when the
13835 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13836 	 * for 'usesrc groups' where the destination address may belong to
13837 	 * another interface to allow multipathing to happen.
13838 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13839 	 * where the local address may not be unique. In this case we were
13840 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13841 	 * actually returned. The new lookup, which is more specific, should
13842 	 * only find the IRE_LOCAL associated with the ingress ill if one
13843 	 * exists.
13844 	 */
13845 
13846 	if (ire->ire_ipversion == IPV4_VERSION) {
13847 		if (ipst->ips_ip_strict_dst_multihoming)
13848 			strict_check = B_TRUE;
13849 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13850 		    ill->ill_ipif, ALL_ZONES, NULL,
13851 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13852 	} else {
13853 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13854 		if (ipst->ips_ipv6_strict_dst_multihoming)
13855 			strict_check = B_TRUE;
13856 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13857 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13858 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13859 	}
13860 	/*
13861 	 * If the same ire that was returned in ip_input() is found then this
13862 	 * is an indication that interface groups are in use. The packet
13863 	 * arrived on a different ill in the group than the one associated with
13864 	 * the destination address.  If a different ire was found then the same
13865 	 * IP address must be hosted on multiple ills. This is possible with
13866 	 * unnumbered point2point interfaces. We switch to use this new ire in
13867 	 * order to have accurate interface statistics.
13868 	 */
13869 	if (new_ire != NULL) {
13870 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13871 			ire_refrele(ire);
13872 			ire = new_ire;
13873 		} else {
13874 			ire_refrele(new_ire);
13875 		}
13876 		return (ire);
13877 	} else if ((ire->ire_rfq == NULL) &&
13878 	    (ire->ire_ipversion == IPV4_VERSION)) {
13879 		/*
13880 		 * The best match could have been the original ire which
13881 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13882 		 * the strict multihoming checks are irrelevant as we consider
13883 		 * local addresses hosted on lo0 to be interface agnostic. We
13884 		 * only expect a null ire_rfq on IREs which are associated with
13885 		 * lo0 hence we can return now.
13886 		 */
13887 		return (ire);
13888 	}
13889 
13890 	/*
13891 	 * Chase pointers once and store locally.
13892 	 */
13893 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13894 	    (ill_t *)(ire->ire_rfq->q_ptr);
13895 	ifindex = ill->ill_usesrc_ifindex;
13896 
13897 	/*
13898 	 * Check if it's a legal address on the 'usesrc' interface.
13899 	 */
13900 	if ((ifindex != 0) && (ire_ill != NULL) &&
13901 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13902 		return (ire);
13903 	}
13904 
13905 	/*
13906 	 * If the ip*_strict_dst_multihoming switch is on then we can
13907 	 * only accept this packet if the interface is marked as routing.
13908 	 */
13909 	if (!(strict_check))
13910 		return (ire);
13911 
13912 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13913 	    ILLF_ROUTER) != 0) {
13914 		return (ire);
13915 	}
13916 
13917 	ire_refrele(ire);
13918 	return (NULL);
13919 }
13920 
13921 ire_t *
13922 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13923 {
13924 	ipha_t	*ipha;
13925 	ipaddr_t ip_dst, ip_src;
13926 	ire_t	*src_ire = NULL;
13927 	ill_t	*stq_ill;
13928 	uint_t	hlen;
13929 	uint_t	pkt_len;
13930 	uint32_t sum;
13931 	queue_t	*dev_q;
13932 	boolean_t check_multirt = B_FALSE;
13933 	ip_stack_t *ipst = ill->ill_ipst;
13934 
13935 	ipha = (ipha_t *)mp->b_rptr;
13936 
13937 	/*
13938 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13939 	 * The loopback address check for both src and dst has already
13940 	 * been checked in ip_input
13941 	 */
13942 	ip_dst = ntohl(dst);
13943 	ip_src = ntohl(ipha->ipha_src);
13944 
13945 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13946 	    IN_CLASSD(ip_src)) {
13947 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13948 		goto drop;
13949 	}
13950 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13951 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13952 
13953 	if (src_ire != NULL) {
13954 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13955 		goto drop;
13956 	}
13957 
13958 
13959 	/* No ire cache of nexthop. So first create one  */
13960 	if (ire == NULL) {
13961 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13962 		/*
13963 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13964 		 * is not set. So upon return from ire_forward
13965 		 * check_multirt should remain as false.
13966 		 */
13967 		ASSERT(!check_multirt);
13968 		if (ire == NULL) {
13969 			/* An attempt was made to forward the packet */
13970 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13971 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13972 			mp->b_prev = mp->b_next = 0;
13973 			/* send icmp unreachable */
13974 			/* Sent by forwarding path, and router is global zone */
13975 			if (ip_source_routed(ipha, ipst)) {
13976 				icmp_unreachable(ill->ill_wq, mp,
13977 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13978 				    ipst);
13979 			} else {
13980 				icmp_unreachable(ill->ill_wq, mp,
13981 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13982 				    ipst);
13983 			}
13984 			return (ire);
13985 		}
13986 	}
13987 
13988 	/*
13989 	 * Forwarding fastpath exception case:
13990 	 * If either of the follwoing case is true, we take
13991 	 * the slowpath
13992 	 *	o forwarding is not enabled
13993 	 *	o incoming and outgoing interface are the same, or the same
13994 	 *	  IPMP group
13995 	 *	o corresponding ire is in incomplete state
13996 	 *	o packet needs fragmentation
13997 	 *
13998 	 * The codeflow from here on is thus:
13999 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
14000 	 */
14001 	pkt_len = ntohs(ipha->ipha_length);
14002 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
14003 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14004 	    !(ill->ill_flags & ILLF_ROUTER) ||
14005 	    (ill == stq_ill) ||
14006 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14007 	    (ire->ire_nce == NULL) ||
14008 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
14009 	    (pkt_len > ire->ire_max_frag) ||
14010 	    ipha->ipha_ttl <= 1) {
14011 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14012 		    ipha, ill, B_FALSE);
14013 		return (ire);
14014 	}
14015 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14016 
14017 	DTRACE_PROBE4(ip4__forwarding__start,
14018 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14019 
14020 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14021 	    ipst->ips_ipv4firewall_forwarding,
14022 	    ill, stq_ill, ipha, mp, mp, ipst);
14023 
14024 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14025 
14026 	if (mp == NULL)
14027 		goto drop;
14028 
14029 	mp->b_datap->db_struioun.cksum.flags = 0;
14030 	/* Adjust the checksum to reflect the ttl decrement. */
14031 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14032 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14033 	ipha->ipha_ttl--;
14034 
14035 	dev_q = ire->ire_stq->q_next;
14036 	if ((dev_q->q_next != NULL ||
14037 	    dev_q->q_first != NULL) && !canput(dev_q)) {
14038 		goto indiscard;
14039 	}
14040 
14041 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
14042 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
14043 
14044 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
14045 		mblk_t *mpip = mp;
14046 
14047 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
14048 		if (mp != NULL) {
14049 			DTRACE_PROBE4(ip4__physical__out__start,
14050 			    ill_t *, NULL, ill_t *, stq_ill,
14051 			    ipha_t *, ipha, mblk_t *, mp);
14052 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
14053 			    ipst->ips_ipv4firewall_physical_out,
14054 			    NULL, stq_ill, ipha, mp, mpip, ipst);
14055 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
14056 			    mp);
14057 			if (mp == NULL)
14058 				goto drop;
14059 
14060 			UPDATE_IB_PKT_COUNT(ire);
14061 			ire->ire_last_used_time = lbolt;
14062 			BUMP_MIB(stq_ill->ill_ip_mib,
14063 			    ipIfStatsHCOutForwDatagrams);
14064 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14065 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
14066 			    pkt_len);
14067 			putnext(ire->ire_stq, mp);
14068 			return (ire);
14069 		}
14070 	}
14071 
14072 indiscard:
14073 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14074 drop:
14075 	if (mp != NULL)
14076 		freemsg(mp);
14077 	if (src_ire != NULL)
14078 		ire_refrele(src_ire);
14079 	return (ire);
14080 
14081 }
14082 
14083 /*
14084  * This function is called in the forwarding slowpath, when
14085  * either the ire lacks the link-layer address, or the packet needs
14086  * further processing(eg. fragmentation), before transmission.
14087  */
14088 
14089 static void
14090 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14091     ill_t *ill, boolean_t ll_multicast)
14092 {
14093 	ill_group_t	*ill_group;
14094 	ill_group_t	*ire_group;
14095 	queue_t		*dev_q;
14096 	ire_t		*src_ire;
14097 	ip_stack_t	*ipst = ill->ill_ipst;
14098 
14099 	ASSERT(ire->ire_stq != NULL);
14100 
14101 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14102 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14103 
14104 	if (ll_multicast != 0) {
14105 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14106 		goto drop_pkt;
14107 	}
14108 
14109 	/*
14110 	 * check if ipha_src is a broadcast address. Note that this
14111 	 * check is redundant when we get here from ip_fast_forward()
14112 	 * which has already done this check. However, since we can
14113 	 * also get here from ip_rput_process_broadcast() or, for
14114 	 * for the slow path through ip_fast_forward(), we perform
14115 	 * the check again for code-reusability
14116 	 */
14117 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14118 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14119 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
14120 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
14121 		if (src_ire != NULL)
14122 			ire_refrele(src_ire);
14123 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14124 		ip2dbg(("ip_rput_process_forward: Received packet with"
14125 		    " bad src/dst address on %s\n", ill->ill_name));
14126 		goto drop_pkt;
14127 	}
14128 
14129 	ill_group = ill->ill_group;
14130 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14131 	/*
14132 	 * Check if we want to forward this one at this time.
14133 	 * We allow source routed packets on a host provided that
14134 	 * they go out the same interface or same interface group
14135 	 * as they came in on.
14136 	 *
14137 	 * XXX To be quicker, we may wish to not chase pointers to
14138 	 * get the ILLF_ROUTER flag and instead store the
14139 	 * forwarding policy in the ire.  An unfortunate
14140 	 * side-effect of that would be requiring an ire flush
14141 	 * whenever the ILLF_ROUTER flag changes.
14142 	 */
14143 	if (((ill->ill_flags &
14144 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14145 	    ILLF_ROUTER) == 0) &&
14146 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14147 	    (ill_group != NULL && ill_group == ire_group)))) {
14148 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14149 		if (ip_source_routed(ipha, ipst)) {
14150 			q = WR(q);
14151 			/*
14152 			 * Clear the indication that this may have
14153 			 * hardware checksum as we are not using it.
14154 			 */
14155 			DB_CKSUMFLAGS(mp) = 0;
14156 			/* Sent by forwarding path, and router is global zone */
14157 			icmp_unreachable(q, mp,
14158 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14159 			return;
14160 		}
14161 		goto drop_pkt;
14162 	}
14163 
14164 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14165 
14166 	/* Packet is being forwarded. Turning off hwcksum flag. */
14167 	DB_CKSUMFLAGS(mp) = 0;
14168 	if (ipst->ips_ip_g_send_redirects) {
14169 		/*
14170 		 * Check whether the incoming interface and outgoing
14171 		 * interface is part of the same group. If so,
14172 		 * send redirects.
14173 		 *
14174 		 * Check the source address to see if it originated
14175 		 * on the same logical subnet it is going back out on.
14176 		 * If so, we should be able to send it a redirect.
14177 		 * Avoid sending a redirect if the destination
14178 		 * is directly connected (i.e., ipha_dst is the same
14179 		 * as ire_gateway_addr or the ire_addr of the
14180 		 * nexthop IRE_CACHE ), or if the packet was source
14181 		 * routed out this interface.
14182 		 */
14183 		ipaddr_t src, nhop;
14184 		mblk_t	*mp1;
14185 		ire_t	*nhop_ire = NULL;
14186 
14187 		/*
14188 		 * Check whether ire_rfq and q are from the same ill
14189 		 * or if they are not same, they at least belong
14190 		 * to the same group. If so, send redirects.
14191 		 */
14192 		if ((ire->ire_rfq == q ||
14193 		    (ill_group != NULL && ill_group == ire_group)) &&
14194 		    !ip_source_routed(ipha, ipst)) {
14195 
14196 			nhop = (ire->ire_gateway_addr != 0 ?
14197 			    ire->ire_gateway_addr : ire->ire_addr);
14198 
14199 			if (ipha->ipha_dst == nhop) {
14200 				/*
14201 				 * We avoid sending a redirect if the
14202 				 * destination is directly connected
14203 				 * because it is possible that multiple
14204 				 * IP subnets may have been configured on
14205 				 * the link, and the source may not
14206 				 * be on the same subnet as ip destination,
14207 				 * even though they are on the same
14208 				 * physical link.
14209 				 */
14210 				goto sendit;
14211 			}
14212 
14213 			src = ipha->ipha_src;
14214 
14215 			/*
14216 			 * We look up the interface ire for the nexthop,
14217 			 * to see if ipha_src is in the same subnet
14218 			 * as the nexthop.
14219 			 *
14220 			 * Note that, if, in the future, IRE_CACHE entries
14221 			 * are obsoleted,  this lookup will not be needed,
14222 			 * as the ire passed to this function will be the
14223 			 * same as the nhop_ire computed below.
14224 			 */
14225 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14226 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14227 			    0, NULL, MATCH_IRE_TYPE, ipst);
14228 
14229 			if (nhop_ire != NULL) {
14230 				if ((src & nhop_ire->ire_mask) ==
14231 				    (nhop & nhop_ire->ire_mask)) {
14232 					/*
14233 					 * The source is directly connected.
14234 					 * Just copy the ip header (which is
14235 					 * in the first mblk)
14236 					 */
14237 					mp1 = copyb(mp);
14238 					if (mp1 != NULL) {
14239 						icmp_send_redirect(WR(q), mp1,
14240 						    nhop, ipst);
14241 					}
14242 				}
14243 				ire_refrele(nhop_ire);
14244 			}
14245 		}
14246 	}
14247 sendit:
14248 	dev_q = ire->ire_stq->q_next;
14249 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14250 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14251 		freemsg(mp);
14252 		return;
14253 	}
14254 
14255 	ip_rput_forward(ire, ipha, mp, ill);
14256 	return;
14257 
14258 drop_pkt:
14259 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14260 	freemsg(mp);
14261 }
14262 
14263 ire_t *
14264 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14265     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14266 {
14267 	queue_t		*q;
14268 	uint16_t	hcksumflags;
14269 	ip_stack_t	*ipst = ill->ill_ipst;
14270 
14271 	q = *qp;
14272 
14273 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14274 
14275 	/*
14276 	 * Clear the indication that this may have hardware
14277 	 * checksum as we are not using it for forwarding.
14278 	 */
14279 	hcksumflags = DB_CKSUMFLAGS(mp);
14280 	DB_CKSUMFLAGS(mp) = 0;
14281 
14282 	/*
14283 	 * Directed broadcast forwarding: if the packet came in over a
14284 	 * different interface then it is routed out over we can forward it.
14285 	 */
14286 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14287 		ire_refrele(ire);
14288 		freemsg(mp);
14289 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14290 		return (NULL);
14291 	}
14292 	/*
14293 	 * For multicast we have set dst to be INADDR_BROADCAST
14294 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14295 	 * only for broadcast packets.
14296 	 */
14297 	if (!CLASSD(ipha->ipha_dst)) {
14298 		ire_t *new_ire;
14299 		ipif_t *ipif;
14300 		/*
14301 		 * For ill groups, as the switch duplicates broadcasts
14302 		 * across all the ports, we need to filter out and
14303 		 * send up only one copy. There is one copy for every
14304 		 * broadcast address on each ill. Thus, we look for a
14305 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14306 		 * later to see whether this ill is eligible to receive
14307 		 * them or not. ill_nominate_bcast_rcv() nominates only
14308 		 * one set of IREs for receiving.
14309 		 */
14310 
14311 		ipif = ipif_get_next_ipif(NULL, ill);
14312 		if (ipif == NULL) {
14313 			ire_refrele(ire);
14314 			freemsg(mp);
14315 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14316 			return (NULL);
14317 		}
14318 		new_ire = ire_ctable_lookup(dst, 0, 0,
14319 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14320 		ipif_refrele(ipif);
14321 
14322 		if (new_ire != NULL) {
14323 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14324 				ire_refrele(ire);
14325 				ire_refrele(new_ire);
14326 				freemsg(mp);
14327 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14328 				return (NULL);
14329 			}
14330 			/*
14331 			 * In the special case of multirouted broadcast
14332 			 * packets, we unconditionally need to "gateway"
14333 			 * them to the appropriate interface here.
14334 			 * In the normal case, this cannot happen, because
14335 			 * there is no broadcast IRE tagged with the
14336 			 * RTF_MULTIRT flag.
14337 			 */
14338 			if (new_ire->ire_flags & RTF_MULTIRT) {
14339 				ire_refrele(new_ire);
14340 				if (ire->ire_rfq != NULL) {
14341 					q = ire->ire_rfq;
14342 					*qp = q;
14343 				}
14344 			} else {
14345 				ire_refrele(ire);
14346 				ire = new_ire;
14347 			}
14348 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14349 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14350 				/*
14351 				 * Free the message if
14352 				 * ip_g_forward_directed_bcast is turned
14353 				 * off for non-local broadcast.
14354 				 */
14355 				ire_refrele(ire);
14356 				freemsg(mp);
14357 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14358 				return (NULL);
14359 			}
14360 		} else {
14361 			/*
14362 			 * This CGTP packet successfully passed the
14363 			 * CGTP filter, but the related CGTP
14364 			 * broadcast IRE has not been found,
14365 			 * meaning that the redundant ipif is
14366 			 * probably down. However, if we discarded
14367 			 * this packet, its duplicate would be
14368 			 * filtered out by the CGTP filter so none
14369 			 * of them would get through. So we keep
14370 			 * going with this one.
14371 			 */
14372 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14373 			if (ire->ire_rfq != NULL) {
14374 				q = ire->ire_rfq;
14375 				*qp = q;
14376 			}
14377 		}
14378 	}
14379 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14380 		/*
14381 		 * Verify that there are not more then one
14382 		 * IRE_BROADCAST with this broadcast address which
14383 		 * has ire_stq set.
14384 		 * TODO: simplify, loop over all IRE's
14385 		 */
14386 		ire_t	*ire1;
14387 		int	num_stq = 0;
14388 		mblk_t	*mp1;
14389 
14390 		/* Find the first one with ire_stq set */
14391 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14392 		for (ire1 = ire; ire1 &&
14393 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14394 		    ire1 = ire1->ire_next)
14395 			;
14396 		if (ire1) {
14397 			ire_refrele(ire);
14398 			ire = ire1;
14399 			IRE_REFHOLD(ire);
14400 		}
14401 
14402 		/* Check if there are additional ones with stq set */
14403 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14404 			if (ire->ire_addr != ire1->ire_addr)
14405 				break;
14406 			if (ire1->ire_stq) {
14407 				num_stq++;
14408 				break;
14409 			}
14410 		}
14411 		rw_exit(&ire->ire_bucket->irb_lock);
14412 		if (num_stq == 1 && ire->ire_stq != NULL) {
14413 			ip1dbg(("ip_rput_process_broadcast: directed "
14414 			    "broadcast to 0x%x\n",
14415 			    ntohl(ire->ire_addr)));
14416 			mp1 = copymsg(mp);
14417 			if (mp1) {
14418 				switch (ipha->ipha_protocol) {
14419 				case IPPROTO_UDP:
14420 					ip_udp_input(q, mp1, ipha, ire, ill);
14421 					break;
14422 				default:
14423 					ip_proto_input(q, mp1, ipha, ire, ill,
14424 					    B_FALSE);
14425 					break;
14426 				}
14427 			}
14428 			/*
14429 			 * Adjust ttl to 2 (1+1 - the forward engine
14430 			 * will decrement it by one.
14431 			 */
14432 			if (ip_csum_hdr(ipha)) {
14433 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14434 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14435 				freemsg(mp);
14436 				ire_refrele(ire);
14437 				return (NULL);
14438 			}
14439 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14440 			ipha->ipha_hdr_checksum = 0;
14441 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14442 			ip_rput_process_forward(q, mp, ire, ipha,
14443 			    ill, ll_multicast);
14444 			ire_refrele(ire);
14445 			return (NULL);
14446 		}
14447 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14448 		    ntohl(ire->ire_addr)));
14449 	}
14450 
14451 
14452 	/* Restore any hardware checksum flags */
14453 	DB_CKSUMFLAGS(mp) = hcksumflags;
14454 	return (ire);
14455 }
14456 
14457 /* ARGSUSED */
14458 static boolean_t
14459 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14460     int *ll_multicast, ipaddr_t *dstp)
14461 {
14462 	ip_stack_t	*ipst = ill->ill_ipst;
14463 
14464 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14465 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14466 	    ntohs(ipha->ipha_length));
14467 
14468 	/*
14469 	 * Forward packets only if we have joined the allmulti
14470 	 * group on this interface.
14471 	 */
14472 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14473 		int retval;
14474 
14475 		/*
14476 		 * Clear the indication that this may have hardware
14477 		 * checksum as we are not using it.
14478 		 */
14479 		DB_CKSUMFLAGS(mp) = 0;
14480 		retval = ip_mforward(ill, ipha, mp);
14481 		/* ip_mforward updates mib variables if needed */
14482 		/* clear b_prev - used by ip_mroute_decap */
14483 		mp->b_prev = NULL;
14484 
14485 		switch (retval) {
14486 		case 0:
14487 			/*
14488 			 * pkt is okay and arrived on phyint.
14489 			 *
14490 			 * If we are running as a multicast router
14491 			 * we need to see all IGMP and/or PIM packets.
14492 			 */
14493 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14494 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14495 				goto done;
14496 			}
14497 			break;
14498 		case -1:
14499 			/* pkt is mal-formed, toss it */
14500 			goto drop_pkt;
14501 		case 1:
14502 			/* pkt is okay and arrived on a tunnel */
14503 			/*
14504 			 * If we are running a multicast router
14505 			 *  we need to see all igmp packets.
14506 			 */
14507 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14508 				*dstp = INADDR_BROADCAST;
14509 				*ll_multicast = 1;
14510 				return (B_FALSE);
14511 			}
14512 
14513 			goto drop_pkt;
14514 		}
14515 	}
14516 
14517 	ILM_WALKER_HOLD(ill);
14518 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14519 		/*
14520 		 * This might just be caused by the fact that
14521 		 * multiple IP Multicast addresses map to the same
14522 		 * link layer multicast - no need to increment counter!
14523 		 */
14524 		ILM_WALKER_RELE(ill);
14525 		freemsg(mp);
14526 		return (B_TRUE);
14527 	}
14528 	ILM_WALKER_RELE(ill);
14529 done:
14530 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14531 	/*
14532 	 * This assumes the we deliver to all streams for multicast
14533 	 * and broadcast packets.
14534 	 */
14535 	*dstp = INADDR_BROADCAST;
14536 	*ll_multicast = 1;
14537 	return (B_FALSE);
14538 drop_pkt:
14539 	ip2dbg(("ip_rput: drop pkt\n"));
14540 	freemsg(mp);
14541 	return (B_TRUE);
14542 }
14543 
14544 static boolean_t
14545 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14546     int *ll_multicast, mblk_t **mpp)
14547 {
14548 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14549 	boolean_t must_copy = B_FALSE;
14550 	struct iocblk   *iocp;
14551 	ipha_t		*ipha;
14552 	ip_stack_t	*ipst = ill->ill_ipst;
14553 
14554 #define	rptr    ((uchar_t *)ipha)
14555 
14556 	first_mp = *first_mpp;
14557 	mp = *mpp;
14558 
14559 	ASSERT(first_mp == mp);
14560 
14561 	/*
14562 	 * if db_ref > 1 then copymsg and free original. Packet may be
14563 	 * changed and do not want other entity who has a reference to this
14564 	 * message to trip over the changes. This is a blind change because
14565 	 * trying to catch all places that might change packet is too
14566 	 * difficult (since it may be a module above this one)
14567 	 *
14568 	 * This corresponds to the non-fast path case. We walk down the full
14569 	 * chain in this case, and check the db_ref count of all the dblks,
14570 	 * and do a copymsg if required. It is possible that the db_ref counts
14571 	 * of the data blocks in the mblk chain can be different.
14572 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14573 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14574 	 * 'snoop' is running.
14575 	 */
14576 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14577 		if (mp1->b_datap->db_ref > 1) {
14578 			must_copy = B_TRUE;
14579 			break;
14580 		}
14581 	}
14582 
14583 	if (must_copy) {
14584 		mp1 = copymsg(mp);
14585 		if (mp1 == NULL) {
14586 			for (mp1 = mp; mp1 != NULL;
14587 			    mp1 = mp1->b_cont) {
14588 				mp1->b_next = NULL;
14589 				mp1->b_prev = NULL;
14590 			}
14591 			freemsg(mp);
14592 			if (ill != NULL) {
14593 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14594 			} else {
14595 				BUMP_MIB(&ipst->ips_ip_mib,
14596 				    ipIfStatsInDiscards);
14597 			}
14598 			return (B_TRUE);
14599 		}
14600 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14601 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14602 			/* Copy b_prev - used by ip_mroute_decap */
14603 			to_mp->b_prev = from_mp->b_prev;
14604 			from_mp->b_prev = NULL;
14605 		}
14606 		*first_mpp = first_mp = mp1;
14607 		freemsg(mp);
14608 		mp = mp1;
14609 		*mpp = mp1;
14610 	}
14611 
14612 	ipha = (ipha_t *)mp->b_rptr;
14613 
14614 	/*
14615 	 * previous code has a case for M_DATA.
14616 	 * We want to check how that happens.
14617 	 */
14618 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14619 	switch (first_mp->b_datap->db_type) {
14620 	case M_PROTO:
14621 	case M_PCPROTO:
14622 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14623 		    DL_UNITDATA_IND) {
14624 			/* Go handle anything other than data elsewhere. */
14625 			ip_rput_dlpi(q, mp);
14626 			return (B_TRUE);
14627 		}
14628 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14629 		/* Ditch the DLPI header. */
14630 		mp1 = mp->b_cont;
14631 		ASSERT(first_mp == mp);
14632 		*first_mpp = mp1;
14633 		freeb(mp);
14634 		*mpp = mp1;
14635 		return (B_FALSE);
14636 	case M_IOCACK:
14637 		ip1dbg(("got iocack "));
14638 		iocp = (struct iocblk *)mp->b_rptr;
14639 		switch (iocp->ioc_cmd) {
14640 		case DL_IOC_HDR_INFO:
14641 			ill = (ill_t *)q->q_ptr;
14642 			ill_fastpath_ack(ill, mp);
14643 			return (B_TRUE);
14644 		case SIOCSTUNPARAM:
14645 		case OSIOCSTUNPARAM:
14646 			/* Go through qwriter_ip */
14647 			break;
14648 		case SIOCGTUNPARAM:
14649 		case OSIOCGTUNPARAM:
14650 			ip_rput_other(NULL, q, mp, NULL);
14651 			return (B_TRUE);
14652 		default:
14653 			putnext(q, mp);
14654 			return (B_TRUE);
14655 		}
14656 		/* FALLTHRU */
14657 	case M_ERROR:
14658 	case M_HANGUP:
14659 		/*
14660 		 * Since this is on the ill stream we unconditionally
14661 		 * bump up the refcount
14662 		 */
14663 		ill_refhold(ill);
14664 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14665 		return (B_TRUE);
14666 	case M_CTL:
14667 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14668 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14669 		    IPHADA_M_CTL)) {
14670 			/*
14671 			 * It's an IPsec accelerated packet.
14672 			 * Make sure that the ill from which we received the
14673 			 * packet has enabled IPsec hardware acceleration.
14674 			 */
14675 			if (!(ill->ill_capabilities &
14676 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14677 				/* IPsec kstats: bean counter */
14678 				freemsg(mp);
14679 				return (B_TRUE);
14680 			}
14681 
14682 			/*
14683 			 * Make mp point to the mblk following the M_CTL,
14684 			 * then process according to type of mp.
14685 			 * After this processing, first_mp will point to
14686 			 * the data-attributes and mp to the pkt following
14687 			 * the M_CTL.
14688 			 */
14689 			mp = first_mp->b_cont;
14690 			if (mp == NULL) {
14691 				freemsg(first_mp);
14692 				return (B_TRUE);
14693 			}
14694 			/*
14695 			 * A Hardware Accelerated packet can only be M_DATA
14696 			 * ESP or AH packet.
14697 			 */
14698 			if (mp->b_datap->db_type != M_DATA) {
14699 				/* non-M_DATA IPsec accelerated packet */
14700 				IPSECHW_DEBUG(IPSECHW_PKT,
14701 				    ("non-M_DATA IPsec accelerated pkt\n"));
14702 				freemsg(first_mp);
14703 				return (B_TRUE);
14704 			}
14705 			ipha = (ipha_t *)mp->b_rptr;
14706 			if (ipha->ipha_protocol != IPPROTO_AH &&
14707 			    ipha->ipha_protocol != IPPROTO_ESP) {
14708 				IPSECHW_DEBUG(IPSECHW_PKT,
14709 				    ("non-M_DATA IPsec accelerated pkt\n"));
14710 				freemsg(first_mp);
14711 				return (B_TRUE);
14712 			}
14713 			*mpp = mp;
14714 			return (B_FALSE);
14715 		}
14716 		putnext(q, mp);
14717 		return (B_TRUE);
14718 	case M_IOCNAK:
14719 		ip1dbg(("got iocnak "));
14720 		iocp = (struct iocblk *)mp->b_rptr;
14721 		switch (iocp->ioc_cmd) {
14722 		case SIOCSTUNPARAM:
14723 		case OSIOCSTUNPARAM:
14724 			/*
14725 			 * Since this is on the ill stream we unconditionally
14726 			 * bump up the refcount
14727 			 */
14728 			ill_refhold(ill);
14729 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14730 			return (B_TRUE);
14731 		case DL_IOC_HDR_INFO:
14732 		case SIOCGTUNPARAM:
14733 		case OSIOCGTUNPARAM:
14734 			ip_rput_other(NULL, q, mp, NULL);
14735 			return (B_TRUE);
14736 		default:
14737 			break;
14738 		}
14739 		/* FALLTHRU */
14740 	default:
14741 		putnext(q, mp);
14742 		return (B_TRUE);
14743 	}
14744 }
14745 
14746 /* Read side put procedure.  Packets coming from the wire arrive here. */
14747 void
14748 ip_rput(queue_t *q, mblk_t *mp)
14749 {
14750 	ill_t	*ill;
14751 	union DL_primitives *dl;
14752 
14753 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14754 
14755 	ill = (ill_t *)q->q_ptr;
14756 
14757 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14758 		/*
14759 		 * If things are opening or closing, only accept high-priority
14760 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14761 		 * created; on close, things hanging off the ill may have been
14762 		 * freed already.)
14763 		 */
14764 		dl = (union DL_primitives *)mp->b_rptr;
14765 		if (DB_TYPE(mp) != M_PCPROTO ||
14766 		    dl->dl_primitive == DL_UNITDATA_IND) {
14767 			/*
14768 			 * SIOC[GS]TUNPARAM ioctls can come here.
14769 			 */
14770 			inet_freemsg(mp);
14771 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14772 			    "ip_rput_end: q %p (%S)", q, "uninit");
14773 			return;
14774 		}
14775 	}
14776 
14777 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14778 	    "ip_rput_end: q %p (%S)", q, "end");
14779 
14780 	ip_input(ill, NULL, mp, NULL);
14781 }
14782 
14783 static mblk_t *
14784 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14785 {
14786 	mblk_t *mp1;
14787 	boolean_t adjusted = B_FALSE;
14788 	ip_stack_t *ipst = ill->ill_ipst;
14789 
14790 	IP_STAT(ipst, ip_db_ref);
14791 	/*
14792 	 * The IP_RECVSLLA option depends on having the
14793 	 * link layer header. First check that:
14794 	 * a> the underlying device is of type ether,
14795 	 * since this option is currently supported only
14796 	 * over ethernet.
14797 	 * b> there is enough room to copy over the link
14798 	 * layer header.
14799 	 *
14800 	 * Once the checks are done, adjust rptr so that
14801 	 * the link layer header will be copied via
14802 	 * copymsg. Note that, IFT_ETHER may be returned
14803 	 * by some non-ethernet drivers but in this case
14804 	 * the second check will fail.
14805 	 */
14806 	if (ill->ill_type == IFT_ETHER &&
14807 	    (mp->b_rptr - mp->b_datap->db_base) >=
14808 	    sizeof (struct ether_header)) {
14809 		mp->b_rptr -= sizeof (struct ether_header);
14810 		adjusted = B_TRUE;
14811 	}
14812 	mp1 = copymsg(mp);
14813 
14814 	if (mp1 == NULL) {
14815 		mp->b_next = NULL;
14816 		/* clear b_prev - used by ip_mroute_decap */
14817 		mp->b_prev = NULL;
14818 		freemsg(mp);
14819 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14820 		return (NULL);
14821 	}
14822 
14823 	if (adjusted) {
14824 		/*
14825 		 * Copy is done. Restore the pointer in
14826 		 * the _new_ mblk
14827 		 */
14828 		mp1->b_rptr += sizeof (struct ether_header);
14829 	}
14830 
14831 	/* Copy b_prev - used by ip_mroute_decap */
14832 	mp1->b_prev = mp->b_prev;
14833 	mp->b_prev = NULL;
14834 
14835 	/* preserve the hardware checksum flags and data, if present */
14836 	if (DB_CKSUMFLAGS(mp) != 0) {
14837 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14838 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14839 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14840 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14841 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14842 	}
14843 
14844 	freemsg(mp);
14845 	return (mp1);
14846 }
14847 
14848 /*
14849  * Direct read side procedure capable of dealing with chains. GLDv3 based
14850  * drivers call this function directly with mblk chains while STREAMS
14851  * read side procedure ip_rput() calls this for single packet with ip_ring
14852  * set to NULL to process one packet at a time.
14853  *
14854  * The ill will always be valid if this function is called directly from
14855  * the driver.
14856  *
14857  * If ip_input() is called from GLDv3:
14858  *
14859  *   - This must be a non-VLAN IP stream.
14860  *   - 'mp' is either an untagged or a special priority-tagged packet.
14861  *   - Any VLAN tag that was in the MAC header has been stripped.
14862  *
14863  * If the IP header in packet is not 32-bit aligned, every message in the
14864  * chain will be aligned before further operations. This is required on SPARC
14865  * platform.
14866  */
14867 /* ARGSUSED */
14868 void
14869 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14870     struct mac_header_info_s *mhip)
14871 {
14872 	ipaddr_t		dst = NULL;
14873 	ipaddr_t		prev_dst;
14874 	ire_t			*ire = NULL;
14875 	ipha_t			*ipha;
14876 	uint_t			pkt_len;
14877 	ssize_t			len;
14878 	uint_t			opt_len;
14879 	int			ll_multicast;
14880 	int			cgtp_flt_pkt;
14881 	queue_t			*q = ill->ill_rq;
14882 	squeue_t		*curr_sqp = NULL;
14883 	mblk_t 			*head = NULL;
14884 	mblk_t			*tail = NULL;
14885 	mblk_t			*first_mp;
14886 	mblk_t 			*mp;
14887 	mblk_t			*dmp;
14888 	int			cnt = 0;
14889 	ip_stack_t		*ipst = ill->ill_ipst;
14890 
14891 	ASSERT(mp_chain != NULL);
14892 	ASSERT(ill != NULL);
14893 
14894 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14895 
14896 #define	rptr	((uchar_t *)ipha)
14897 
14898 	while (mp_chain != NULL) {
14899 		first_mp = mp = mp_chain;
14900 		mp_chain = mp_chain->b_next;
14901 		mp->b_next = NULL;
14902 		ll_multicast = 0;
14903 
14904 		/*
14905 		 * We do ire caching from one iteration to
14906 		 * another. In the event the packet chain contains
14907 		 * all packets from the same dst, this caching saves
14908 		 * an ire_cache_lookup for each of the succeeding
14909 		 * packets in a packet chain.
14910 		 */
14911 		prev_dst = dst;
14912 
14913 		/*
14914 		 * if db_ref > 1 then copymsg and free original. Packet
14915 		 * may be changed and we do not want the other entity
14916 		 * who has a reference to this message to trip over the
14917 		 * changes. This is a blind change because trying to
14918 		 * catch all places that might change the packet is too
14919 		 * difficult.
14920 		 *
14921 		 * This corresponds to the fast path case, where we have
14922 		 * a chain of M_DATA mblks.  We check the db_ref count
14923 		 * of only the 1st data block in the mblk chain. There
14924 		 * doesn't seem to be a reason why a device driver would
14925 		 * send up data with varying db_ref counts in the mblk
14926 		 * chain. In any case the Fast path is a private
14927 		 * interface, and our drivers don't do such a thing.
14928 		 * Given the above assumption, there is no need to walk
14929 		 * down the entire mblk chain (which could have a
14930 		 * potential performance problem)
14931 		 */
14932 
14933 		if (DB_REF(mp) > 1) {
14934 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14935 				continue;
14936 		}
14937 
14938 		/*
14939 		 * Check and align the IP header.
14940 		 */
14941 		first_mp = mp;
14942 		if (DB_TYPE(mp) == M_DATA) {
14943 			dmp = mp;
14944 		} else if (DB_TYPE(mp) == M_PROTO &&
14945 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14946 			dmp = mp->b_cont;
14947 		} else {
14948 			dmp = NULL;
14949 		}
14950 		if (dmp != NULL) {
14951 			/*
14952 			 * IP header ptr not aligned?
14953 			 * OR IP header not complete in first mblk
14954 			 */
14955 			if (!OK_32PTR(dmp->b_rptr) ||
14956 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14957 				if (!ip_check_and_align_header(q, dmp, ipst))
14958 					continue;
14959 			}
14960 		}
14961 
14962 		/*
14963 		 * ip_input fast path
14964 		 */
14965 
14966 		/* mblk type is not M_DATA */
14967 		if (DB_TYPE(mp) != M_DATA) {
14968 			if (ip_rput_process_notdata(q, &first_mp, ill,
14969 			    &ll_multicast, &mp))
14970 				continue;
14971 		}
14972 
14973 		/* Make sure its an M_DATA and that its aligned */
14974 		ASSERT(DB_TYPE(mp) == M_DATA);
14975 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14976 
14977 		ipha = (ipha_t *)mp->b_rptr;
14978 		len = mp->b_wptr - rptr;
14979 		pkt_len = ntohs(ipha->ipha_length);
14980 
14981 		/*
14982 		 * We must count all incoming packets, even if they end
14983 		 * up being dropped later on.
14984 		 */
14985 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14986 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14987 
14988 		/* multiple mblk or too short */
14989 		len -= pkt_len;
14990 		if (len != 0) {
14991 			/*
14992 			 * Make sure we have data length consistent
14993 			 * with the IP header.
14994 			 */
14995 			if (mp->b_cont == NULL) {
14996 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14997 					BUMP_MIB(ill->ill_ip_mib,
14998 					    ipIfStatsInHdrErrors);
14999 					ip2dbg(("ip_input: drop pkt\n"));
15000 					freemsg(mp);
15001 					continue;
15002 				}
15003 				mp->b_wptr = rptr + pkt_len;
15004 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15005 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15006 					BUMP_MIB(ill->ill_ip_mib,
15007 					    ipIfStatsInHdrErrors);
15008 					ip2dbg(("ip_input: drop pkt\n"));
15009 					freemsg(mp);
15010 					continue;
15011 				}
15012 				(void) adjmsg(mp, -len);
15013 				IP_STAT(ipst, ip_multimblk3);
15014 			}
15015 		}
15016 
15017 		/* Obtain the dst of the current packet */
15018 		dst = ipha->ipha_dst;
15019 
15020 		if (IP_LOOPBACK_ADDR(dst) ||
15021 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
15022 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15023 			cmn_err(CE_CONT, "dst %X src %X\n",
15024 			    dst, ipha->ipha_src);
15025 			freemsg(mp);
15026 			continue;
15027 		}
15028 
15029 		/*
15030 		 * The event for packets being received from a 'physical'
15031 		 * interface is placed after validation of the source and/or
15032 		 * destination address as being local so that packets can be
15033 		 * redirected to loopback addresses using ipnat.
15034 		 */
15035 		DTRACE_PROBE4(ip4__physical__in__start,
15036 		    ill_t *, ill, ill_t *, NULL,
15037 		    ipha_t *, ipha, mblk_t *, first_mp);
15038 
15039 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15040 		    ipst->ips_ipv4firewall_physical_in,
15041 		    ill, NULL, ipha, first_mp, mp, ipst);
15042 
15043 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15044 
15045 		if (first_mp == NULL) {
15046 			continue;
15047 		}
15048 		dst = ipha->ipha_dst;
15049 
15050 		/*
15051 		 * Attach any necessary label information to
15052 		 * this packet
15053 		 */
15054 		if (is_system_labeled() &&
15055 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15056 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15057 			freemsg(mp);
15058 			continue;
15059 		}
15060 
15061 		/*
15062 		 * Reuse the cached ire only if the ipha_dst of the previous
15063 		 * packet is the same as the current packet AND it is not
15064 		 * INADDR_ANY.
15065 		 */
15066 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15067 		    (ire != NULL)) {
15068 			ire_refrele(ire);
15069 			ire = NULL;
15070 		}
15071 		opt_len = ipha->ipha_version_and_hdr_length -
15072 		    IP_SIMPLE_HDR_VERSION;
15073 
15074 		/*
15075 		 * Check to see if we can take the fastpath.
15076 		 * That is possible if the following conditions are met
15077 		 *	o Tsol disabled
15078 		 *	o CGTP disabled
15079 		 *	o ipp_action_count is 0
15080 		 *	o no options in the packet
15081 		 *	o not a RSVP packet
15082 		 * 	o not a multicast packet
15083 		 */
15084 		if (!is_system_labeled() &&
15085 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15086 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15087 		    !ll_multicast && !CLASSD(dst)) {
15088 			if (ire == NULL)
15089 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15090 				    ipst);
15091 
15092 			/* incoming packet is for forwarding */
15093 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15094 				ire = ip_fast_forward(ire, dst, ill, mp);
15095 				continue;
15096 			}
15097 			/* incoming packet is for local consumption */
15098 			if (ire->ire_type & IRE_LOCAL)
15099 				goto local;
15100 		}
15101 
15102 		/*
15103 		 * Disable ire caching for anything more complex
15104 		 * than the simple fast path case we checked for above.
15105 		 */
15106 		if (ire != NULL) {
15107 			ire_refrele(ire);
15108 			ire = NULL;
15109 		}
15110 
15111 		/* Full-blown slow path */
15112 		if (opt_len != 0) {
15113 			if (len != 0)
15114 				IP_STAT(ipst, ip_multimblk4);
15115 			else
15116 				IP_STAT(ipst, ip_ipoptions);
15117 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15118 			    &dst, ipst))
15119 				continue;
15120 		}
15121 
15122 		/*
15123 		 * Invoke the CGTP (multirouting) filtering module to process
15124 		 * the incoming packet. Packets identified as duplicates
15125 		 * must be discarded. Filtering is active only if the
15126 		 * the ip_cgtp_filter ndd variable is non-zero.
15127 		 */
15128 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15129 		if (ipst->ips_ip_cgtp_filter &&
15130 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15131 			netstackid_t stackid;
15132 
15133 			stackid = ipst->ips_netstack->netstack_stackid;
15134 			cgtp_flt_pkt =
15135 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15136 			    ill->ill_phyint->phyint_ifindex, mp);
15137 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15138 				freemsg(first_mp);
15139 				continue;
15140 			}
15141 		}
15142 
15143 		/*
15144 		 * If rsvpd is running, let RSVP daemon handle its processing
15145 		 * and forwarding of RSVP multicast/unicast packets.
15146 		 * If rsvpd is not running but mrouted is running, RSVP
15147 		 * multicast packets are forwarded as multicast traffic
15148 		 * and RSVP unicast packets are forwarded by unicast router.
15149 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15150 		 * packets are not forwarded, but the unicast packets are
15151 		 * forwarded like unicast traffic.
15152 		 */
15153 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15154 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15155 		    NULL) {
15156 			/* RSVP packet and rsvpd running. Treat as ours */
15157 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15158 			/*
15159 			 * This assumes that we deliver to all streams for
15160 			 * multicast and broadcast packets.
15161 			 * We have to force ll_multicast to 1 to handle the
15162 			 * M_DATA messages passed in from ip_mroute_decap.
15163 			 */
15164 			dst = INADDR_BROADCAST;
15165 			ll_multicast = 1;
15166 		} else if (CLASSD(dst)) {
15167 			/* packet is multicast */
15168 			mp->b_next = NULL;
15169 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15170 			    &ll_multicast, &dst))
15171 				continue;
15172 		}
15173 
15174 		if (ire == NULL) {
15175 			ire = ire_cache_lookup(dst, ALL_ZONES,
15176 			    MBLK_GETLABEL(mp), ipst);
15177 		}
15178 
15179 		if (ire == NULL) {
15180 			/*
15181 			 * No IRE for this destination, so it can't be for us.
15182 			 * Unless we are forwarding, drop the packet.
15183 			 * We have to let source routed packets through
15184 			 * since we don't yet know if they are 'ping -l'
15185 			 * packets i.e. if they will go out over the
15186 			 * same interface as they came in on.
15187 			 */
15188 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15189 			if (ire == NULL)
15190 				continue;
15191 		}
15192 
15193 		/*
15194 		 * Broadcast IRE may indicate either broadcast or
15195 		 * multicast packet
15196 		 */
15197 		if (ire->ire_type == IRE_BROADCAST) {
15198 			/*
15199 			 * Skip broadcast checks if packet is UDP multicast;
15200 			 * we'd rather not enter ip_rput_process_broadcast()
15201 			 * unless the packet is broadcast for real, since
15202 			 * that routine is a no-op for multicast.
15203 			 */
15204 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15205 			    !CLASSD(ipha->ipha_dst)) {
15206 				ire = ip_rput_process_broadcast(&q, mp,
15207 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15208 				    ll_multicast);
15209 				if (ire == NULL)
15210 					continue;
15211 			}
15212 		} else if (ire->ire_stq != NULL) {
15213 			/* fowarding? */
15214 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15215 			    ll_multicast);
15216 			/* ip_rput_process_forward consumed the packet */
15217 			continue;
15218 		}
15219 
15220 local:
15221 		/*
15222 		 * If the queue in the ire is different to the ingress queue
15223 		 * then we need to check to see if we can accept the packet.
15224 		 * Note that for multicast packets and broadcast packets sent
15225 		 * to a broadcast address which is shared between multiple
15226 		 * interfaces we should not do this since we just got a random
15227 		 * broadcast ire.
15228 		 */
15229 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15230 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15231 			    ill)) == NULL) {
15232 				/* Drop packet */
15233 				BUMP_MIB(ill->ill_ip_mib,
15234 				    ipIfStatsForwProhibits);
15235 				freemsg(mp);
15236 				continue;
15237 			}
15238 			if (ire->ire_rfq != NULL)
15239 				q = ire->ire_rfq;
15240 		}
15241 
15242 		switch (ipha->ipha_protocol) {
15243 		case IPPROTO_TCP:
15244 			ASSERT(first_mp == mp);
15245 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15246 			    mp, 0, q, ip_ring)) != NULL) {
15247 				if (curr_sqp == NULL) {
15248 					curr_sqp = GET_SQUEUE(mp);
15249 					ASSERT(cnt == 0);
15250 					cnt++;
15251 					head = tail = mp;
15252 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15253 					ASSERT(tail != NULL);
15254 					cnt++;
15255 					tail->b_next = mp;
15256 					tail = mp;
15257 				} else {
15258 					/*
15259 					 * A different squeue. Send the
15260 					 * chain for the previous squeue on
15261 					 * its way. This shouldn't happen
15262 					 * often unless interrupt binding
15263 					 * changes.
15264 					 */
15265 					IP_STAT(ipst, ip_input_multi_squeue);
15266 					squeue_enter_chain(curr_sqp, head,
15267 					    tail, cnt, SQTAG_IP_INPUT);
15268 					curr_sqp = GET_SQUEUE(mp);
15269 					head = mp;
15270 					tail = mp;
15271 					cnt = 1;
15272 				}
15273 			}
15274 			continue;
15275 		case IPPROTO_UDP:
15276 			ASSERT(first_mp == mp);
15277 			ip_udp_input(q, mp, ipha, ire, ill);
15278 			continue;
15279 		case IPPROTO_SCTP:
15280 			ASSERT(first_mp == mp);
15281 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15282 			    q, dst);
15283 			/* ire has been released by ip_sctp_input */
15284 			ire = NULL;
15285 			continue;
15286 		default:
15287 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15288 			continue;
15289 		}
15290 	}
15291 
15292 	if (ire != NULL)
15293 		ire_refrele(ire);
15294 
15295 	if (head != NULL)
15296 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15297 
15298 	/*
15299 	 * This code is there just to make netperf/ttcp look good.
15300 	 *
15301 	 * Its possible that after being in polling mode (and having cleared
15302 	 * the backlog), squeues have turned the interrupt frequency higher
15303 	 * to improve latency at the expense of more CPU utilization (less
15304 	 * packets per interrupts or more number of interrupts). Workloads
15305 	 * like ttcp/netperf do manage to tickle polling once in a while
15306 	 * but for the remaining time, stay in higher interrupt mode since
15307 	 * their packet arrival rate is pretty uniform and this shows up
15308 	 * as higher CPU utilization. Since people care about CPU utilization
15309 	 * while running netperf/ttcp, turn the interrupt frequency back to
15310 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15311 	 */
15312 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15313 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15314 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15315 			ip_ring->rr_blank(ip_ring->rr_handle,
15316 			    ip_ring->rr_normal_blank_time,
15317 			    ip_ring->rr_normal_pkt_cnt);
15318 		}
15319 		}
15320 
15321 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15322 	    "ip_input_end: q %p (%S)", q, "end");
15323 #undef  rptr
15324 }
15325 
15326 static void
15327 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15328     t_uscalar_t err)
15329 {
15330 	if (dl_err == DL_SYSERR) {
15331 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15332 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15333 		    ill->ill_name, dlpi_prim_str(prim), err);
15334 		return;
15335 	}
15336 
15337 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15338 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15339 	    dlpi_err_str(dl_err));
15340 }
15341 
15342 /*
15343  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15344  * than DL_UNITDATA_IND messages. If we need to process this message
15345  * exclusively, we call qwriter_ip, in which case we also need to call
15346  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15347  */
15348 void
15349 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15350 {
15351 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15352 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15353 	ill_t		*ill = (ill_t *)q->q_ptr;
15354 	boolean_t	pending;
15355 
15356 	ip1dbg(("ip_rput_dlpi"));
15357 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15358 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15359 		    "%s (0x%x), unix %u\n", ill->ill_name,
15360 		    dlpi_prim_str(dlea->dl_error_primitive),
15361 		    dlea->dl_error_primitive,
15362 		    dlpi_err_str(dlea->dl_errno),
15363 		    dlea->dl_errno,
15364 		    dlea->dl_unix_errno));
15365 	}
15366 
15367 	/*
15368 	 * If we received an ACK but didn't send a request for it, then it
15369 	 * can't be part of any pending operation; discard up-front.
15370 	 */
15371 	switch (dloa->dl_primitive) {
15372 	case DL_NOTIFY_IND:
15373 		pending = B_TRUE;
15374 		break;
15375 	case DL_ERROR_ACK:
15376 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15377 		break;
15378 	case DL_OK_ACK:
15379 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15380 		break;
15381 	case DL_INFO_ACK:
15382 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15383 		break;
15384 	case DL_BIND_ACK:
15385 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15386 		break;
15387 	case DL_PHYS_ADDR_ACK:
15388 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15389 		break;
15390 	case DL_NOTIFY_ACK:
15391 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15392 		break;
15393 	case DL_CONTROL_ACK:
15394 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15395 		break;
15396 	case DL_CAPABILITY_ACK:
15397 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15398 		break;
15399 	default:
15400 		/* Not a DLPI message we support or were expecting */
15401 		freemsg(mp);
15402 		return;
15403 	}
15404 
15405 	if (!pending) {
15406 		freemsg(mp);
15407 		return;
15408 	}
15409 
15410 	switch (dloa->dl_primitive) {
15411 	case DL_ERROR_ACK:
15412 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15413 			mutex_enter(&ill->ill_lock);
15414 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15415 			cv_signal(&ill->ill_cv);
15416 			mutex_exit(&ill->ill_lock);
15417 		}
15418 		break;
15419 
15420 	case DL_OK_ACK:
15421 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15422 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15423 		switch (dloa->dl_correct_primitive) {
15424 		case DL_UNBIND_REQ:
15425 			mutex_enter(&ill->ill_lock);
15426 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15427 			cv_signal(&ill->ill_cv);
15428 			mutex_exit(&ill->ill_lock);
15429 			break;
15430 
15431 		case DL_ENABMULTI_REQ:
15432 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15433 				ill->ill_dlpi_multicast_state = IDS_OK;
15434 			break;
15435 		}
15436 		break;
15437 	default:
15438 		break;
15439 	}
15440 
15441 	/*
15442 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15443 	 * and we need to become writer to continue to process it. If it's not
15444 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15445 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15446 	 * some work as part of the current exclusive operation that actually
15447 	 * is not part of it -- which is wrong, but better than the
15448 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15449 	 * should track which DLPI requests have ACKs that we wait on
15450 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15451 	 *
15452 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15453 	 * Since this is on the ill stream we unconditionally bump up the
15454 	 * refcount without doing ILL_CAN_LOOKUP().
15455 	 */
15456 	ill_refhold(ill);
15457 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15458 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15459 	else
15460 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15461 }
15462 
15463 /*
15464  * Handling of DLPI messages that require exclusive access to the ipsq.
15465  *
15466  * Need to do ill_pending_mp_release on ioctl completion, which could
15467  * happen here. (along with mi_copy_done)
15468  */
15469 /* ARGSUSED */
15470 static void
15471 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15472 {
15473 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15474 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15475 	int		err = 0;
15476 	ill_t		*ill;
15477 	ipif_t		*ipif = NULL;
15478 	mblk_t		*mp1 = NULL;
15479 	conn_t		*connp = NULL;
15480 	t_uscalar_t	paddrreq;
15481 	mblk_t		*mp_hw;
15482 	boolean_t	success;
15483 	boolean_t	ioctl_aborted = B_FALSE;
15484 	boolean_t	log = B_TRUE;
15485 	hook_nic_event_t	*info;
15486 	ip_stack_t		*ipst;
15487 
15488 	ip1dbg(("ip_rput_dlpi_writer .."));
15489 	ill = (ill_t *)q->q_ptr;
15490 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15491 
15492 	ASSERT(IAM_WRITER_ILL(ill));
15493 
15494 	ipst = ill->ill_ipst;
15495 
15496 	/*
15497 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15498 	 * both are null or non-null. However we can assert that only
15499 	 * after grabbing the ipsq_lock. So we don't make any assertion
15500 	 * here and in other places in the code.
15501 	 */
15502 	ipif = ipsq->ipsq_pending_ipif;
15503 	/*
15504 	 * The current ioctl could have been aborted by the user and a new
15505 	 * ioctl to bring up another ill could have started. We could still
15506 	 * get a response from the driver later.
15507 	 */
15508 	if (ipif != NULL && ipif->ipif_ill != ill)
15509 		ioctl_aborted = B_TRUE;
15510 
15511 	switch (dloa->dl_primitive) {
15512 	case DL_ERROR_ACK:
15513 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15514 		    dlpi_prim_str(dlea->dl_error_primitive)));
15515 
15516 		switch (dlea->dl_error_primitive) {
15517 		case DL_PROMISCON_REQ:
15518 		case DL_PROMISCOFF_REQ:
15519 		case DL_DISABMULTI_REQ:
15520 		case DL_UNBIND_REQ:
15521 		case DL_ATTACH_REQ:
15522 		case DL_INFO_REQ:
15523 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15524 			break;
15525 		case DL_NOTIFY_REQ:
15526 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15527 			log = B_FALSE;
15528 			break;
15529 		case DL_PHYS_ADDR_REQ:
15530 			/*
15531 			 * For IPv6 only, there are two additional
15532 			 * phys_addr_req's sent to the driver to get the
15533 			 * IPv6 token and lla. This allows IP to acquire
15534 			 * the hardware address format for a given interface
15535 			 * without having built in knowledge of the hardware
15536 			 * address. ill_phys_addr_pend keeps track of the last
15537 			 * DL_PAR sent so we know which response we are
15538 			 * dealing with. ill_dlpi_done will update
15539 			 * ill_phys_addr_pend when it sends the next req.
15540 			 * We don't complete the IOCTL until all three DL_PARs
15541 			 * have been attempted, so set *_len to 0 and break.
15542 			 */
15543 			paddrreq = ill->ill_phys_addr_pend;
15544 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15545 			if (paddrreq == DL_IPV6_TOKEN) {
15546 				ill->ill_token_length = 0;
15547 				log = B_FALSE;
15548 				break;
15549 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15550 				ill->ill_nd_lla_len = 0;
15551 				log = B_FALSE;
15552 				break;
15553 			}
15554 			/*
15555 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15556 			 * We presumably have an IOCTL hanging out waiting
15557 			 * for completion. Find it and complete the IOCTL
15558 			 * with the error noted.
15559 			 * However, ill_dl_phys was called on an ill queue
15560 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15561 			 * set. But the ioctl is known to be pending on ill_wq.
15562 			 */
15563 			if (!ill->ill_ifname_pending)
15564 				break;
15565 			ill->ill_ifname_pending = 0;
15566 			if (!ioctl_aborted)
15567 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15568 			if (mp1 != NULL) {
15569 				/*
15570 				 * This operation (SIOCSLIFNAME) must have
15571 				 * happened on the ill. Assert there is no conn
15572 				 */
15573 				ASSERT(connp == NULL);
15574 				q = ill->ill_wq;
15575 			}
15576 			break;
15577 		case DL_BIND_REQ:
15578 			ill_dlpi_done(ill, DL_BIND_REQ);
15579 			if (ill->ill_ifname_pending)
15580 				break;
15581 			/*
15582 			 * Something went wrong with the bind.  We presumably
15583 			 * have an IOCTL hanging out waiting for completion.
15584 			 * Find it, take down the interface that was coming
15585 			 * up, and complete the IOCTL with the error noted.
15586 			 */
15587 			if (!ioctl_aborted)
15588 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15589 			if (mp1 != NULL) {
15590 				/*
15591 				 * This operation (SIOCSLIFFLAGS) must have
15592 				 * happened from a conn.
15593 				 */
15594 				ASSERT(connp != NULL);
15595 				q = CONNP_TO_WQ(connp);
15596 				if (ill->ill_move_in_progress) {
15597 					ILL_CLEAR_MOVE(ill);
15598 				}
15599 				(void) ipif_down(ipif, NULL, NULL);
15600 				/* error is set below the switch */
15601 			}
15602 			break;
15603 		case DL_ENABMULTI_REQ:
15604 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15605 
15606 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15607 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15608 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15609 				ipif_t *ipif;
15610 
15611 				printf("ip: joining multicasts failed (%d)"
15612 				    " on %s - will use link layer "
15613 				    "broadcasts for multicast\n",
15614 				    dlea->dl_errno, ill->ill_name);
15615 
15616 				/*
15617 				 * Set up the multicast mapping alone.
15618 				 * writer, so ok to access ill->ill_ipif
15619 				 * without any lock.
15620 				 */
15621 				ipif = ill->ill_ipif;
15622 				mutex_enter(&ill->ill_phyint->phyint_lock);
15623 				ill->ill_phyint->phyint_flags |=
15624 				    PHYI_MULTI_BCAST;
15625 				mutex_exit(&ill->ill_phyint->phyint_lock);
15626 
15627 				if (!ill->ill_isv6) {
15628 					(void) ipif_arp_setup_multicast(ipif,
15629 					    NULL);
15630 				} else {
15631 					(void) ipif_ndp_setup_multicast(ipif,
15632 					    NULL);
15633 				}
15634 			}
15635 			freemsg(mp);	/* Don't want to pass this up */
15636 			return;
15637 
15638 		case DL_CAPABILITY_REQ:
15639 		case DL_CONTROL_REQ:
15640 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15641 			ill->ill_dlpi_capab_state = IDS_FAILED;
15642 			freemsg(mp);
15643 			return;
15644 		}
15645 		/*
15646 		 * Note the error for IOCTL completion (mp1 is set when
15647 		 * ready to complete ioctl). If ill_ifname_pending_err is
15648 		 * set, an error occured during plumbing (ill_ifname_pending),
15649 		 * so we want to report that error.
15650 		 *
15651 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15652 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15653 		 * expected to get errack'd if the driver doesn't support
15654 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15655 		 * if these error conditions are encountered.
15656 		 */
15657 		if (mp1 != NULL) {
15658 			if (ill->ill_ifname_pending_err != 0)  {
15659 				err = ill->ill_ifname_pending_err;
15660 				ill->ill_ifname_pending_err = 0;
15661 			} else {
15662 				err = dlea->dl_unix_errno ?
15663 				    dlea->dl_unix_errno : ENXIO;
15664 			}
15665 		/*
15666 		 * If we're plumbing an interface and an error hasn't already
15667 		 * been saved, set ill_ifname_pending_err to the error passed
15668 		 * up. Ignore the error if log is B_FALSE (see comment above).
15669 		 */
15670 		} else if (log && ill->ill_ifname_pending &&
15671 		    ill->ill_ifname_pending_err == 0) {
15672 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15673 			    dlea->dl_unix_errno : ENXIO;
15674 		}
15675 
15676 		if (log)
15677 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15678 			    dlea->dl_errno, dlea->dl_unix_errno);
15679 		break;
15680 	case DL_CAPABILITY_ACK:
15681 		/* Call a routine to handle this one. */
15682 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15683 		ill_capability_ack(ill, mp);
15684 
15685 		/*
15686 		 * If the ack is due to renegotiation, we will need to send
15687 		 * a new CAPABILITY_REQ to start the renegotiation.
15688 		 */
15689 		if (ill->ill_capab_reneg) {
15690 			ill->ill_capab_reneg = B_FALSE;
15691 			ill_capability_probe(ill);
15692 		}
15693 		break;
15694 	case DL_CONTROL_ACK:
15695 		/* We treat all of these as "fire and forget" */
15696 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15697 		break;
15698 	case DL_INFO_ACK:
15699 		/* Call a routine to handle this one. */
15700 		ill_dlpi_done(ill, DL_INFO_REQ);
15701 		ip_ll_subnet_defaults(ill, mp);
15702 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15703 		return;
15704 	case DL_BIND_ACK:
15705 		/*
15706 		 * We should have an IOCTL waiting on this unless
15707 		 * sent by ill_dl_phys, in which case just return
15708 		 */
15709 		ill_dlpi_done(ill, DL_BIND_REQ);
15710 		if (ill->ill_ifname_pending)
15711 			break;
15712 
15713 		if (!ioctl_aborted)
15714 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15715 		if (mp1 == NULL)
15716 			break;
15717 		/*
15718 		 * Because mp1 was added by ill_dl_up(), and it always
15719 		 * passes a valid connp, connp must be valid here.
15720 		 */
15721 		ASSERT(connp != NULL);
15722 		q = CONNP_TO_WQ(connp);
15723 
15724 		/*
15725 		 * We are exclusive. So nothing can change even after
15726 		 * we get the pending mp. If need be we can put it back
15727 		 * and restart, as in calling ipif_arp_up()  below.
15728 		 */
15729 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15730 
15731 		mutex_enter(&ill->ill_lock);
15732 
15733 		ill->ill_dl_up = 1;
15734 
15735 		if ((info = ill->ill_nic_event_info) != NULL) {
15736 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15737 			    "attached for %s\n", info->hne_event,
15738 			    ill->ill_name));
15739 			if (info->hne_data != NULL)
15740 				kmem_free(info->hne_data, info->hne_datalen);
15741 			kmem_free(info, sizeof (hook_nic_event_t));
15742 		}
15743 
15744 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15745 		if (info != NULL) {
15746 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15747 			info->hne_lif = 0;
15748 			info->hne_event = NE_UP;
15749 			info->hne_data = NULL;
15750 			info->hne_datalen = 0;
15751 			info->hne_family = ill->ill_isv6 ?
15752 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15753 		} else
15754 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15755 			    "event information for %s (ENOMEM)\n",
15756 			    ill->ill_name));
15757 
15758 		ill->ill_nic_event_info = info;
15759 
15760 		mutex_exit(&ill->ill_lock);
15761 
15762 		/*
15763 		 * Now bring up the resolver; when that is complete, we'll
15764 		 * create IREs.  Note that we intentionally mirror what
15765 		 * ipif_up() would have done, because we got here by way of
15766 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15767 		 */
15768 		if (ill->ill_isv6) {
15769 			/*
15770 			 * v6 interfaces.
15771 			 * Unlike ARP which has to do another bind
15772 			 * and attach, once we get here we are
15773 			 * done with NDP. Except in the case of
15774 			 * ILLF_XRESOLV, in which case we send an
15775 			 * AR_INTERFACE_UP to the external resolver.
15776 			 * If all goes well, the ioctl will complete
15777 			 * in ip_rput(). If there's an error, we
15778 			 * complete it here.
15779 			 */
15780 			if ((err = ipif_ndp_up(ipif)) == 0) {
15781 				if (ill->ill_flags & ILLF_XRESOLV) {
15782 					mutex_enter(&connp->conn_lock);
15783 					mutex_enter(&ill->ill_lock);
15784 					success = ipsq_pending_mp_add(
15785 					    connp, ipif, q, mp1, 0);
15786 					mutex_exit(&ill->ill_lock);
15787 					mutex_exit(&connp->conn_lock);
15788 					if (success) {
15789 						err = ipif_resolver_up(ipif,
15790 						    Res_act_initial);
15791 						if (err == EINPROGRESS) {
15792 							freemsg(mp);
15793 							return;
15794 						}
15795 						ASSERT(err != 0);
15796 						mp1 = ipsq_pending_mp_get(ipsq,
15797 						    &connp);
15798 						ASSERT(mp1 != NULL);
15799 					} else {
15800 						/* conn has started closing */
15801 						err = EINTR;
15802 					}
15803 				} else { /* Non XRESOLV interface */
15804 					(void) ipif_resolver_up(ipif,
15805 					    Res_act_initial);
15806 					err = ipif_up_done_v6(ipif);
15807 				}
15808 			}
15809 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15810 			/*
15811 			 * ARP and other v4 external resolvers.
15812 			 * Leave the pending mblk intact so that
15813 			 * the ioctl completes in ip_rput().
15814 			 */
15815 			mutex_enter(&connp->conn_lock);
15816 			mutex_enter(&ill->ill_lock);
15817 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15818 			mutex_exit(&ill->ill_lock);
15819 			mutex_exit(&connp->conn_lock);
15820 			if (success) {
15821 				err = ipif_resolver_up(ipif, Res_act_initial);
15822 				if (err == EINPROGRESS) {
15823 					freemsg(mp);
15824 					return;
15825 				}
15826 				ASSERT(err != 0);
15827 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15828 			} else {
15829 				/* The conn has started closing */
15830 				err = EINTR;
15831 			}
15832 		} else {
15833 			/*
15834 			 * This one is complete. Reply to pending ioctl.
15835 			 */
15836 			(void) ipif_resolver_up(ipif, Res_act_initial);
15837 			err = ipif_up_done(ipif);
15838 		}
15839 
15840 		if ((err == 0) && (ill->ill_up_ipifs)) {
15841 			err = ill_up_ipifs(ill, q, mp1);
15842 			if (err == EINPROGRESS) {
15843 				freemsg(mp);
15844 				return;
15845 			}
15846 		}
15847 
15848 		if (ill->ill_up_ipifs) {
15849 			ill_group_cleanup(ill);
15850 		}
15851 
15852 		break;
15853 	case DL_NOTIFY_IND: {
15854 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15855 		ire_t *ire;
15856 		boolean_t need_ire_walk_v4 = B_FALSE;
15857 		boolean_t need_ire_walk_v6 = B_FALSE;
15858 
15859 		switch (notify->dl_notification) {
15860 		case DL_NOTE_PHYS_ADDR:
15861 			err = ill_set_phys_addr(ill, mp);
15862 			break;
15863 
15864 		case DL_NOTE_FASTPATH_FLUSH:
15865 			ill_fastpath_flush(ill);
15866 			break;
15867 
15868 		case DL_NOTE_SDU_SIZE:
15869 			/*
15870 			 * Change the MTU size of the interface, of all
15871 			 * attached ipif's, and of all relevant ire's.  The
15872 			 * new value's a uint32_t at notify->dl_data.
15873 			 * Mtu change Vs. new ire creation - protocol below.
15874 			 *
15875 			 * a Mark the ipif as IPIF_CHANGING.
15876 			 * b Set the new mtu in the ipif.
15877 			 * c Change the ire_max_frag on all affected ires
15878 			 * d Unmark the IPIF_CHANGING
15879 			 *
15880 			 * To see how the protocol works, assume an interface
15881 			 * route is also being added simultaneously by
15882 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15883 			 * the ire. If the ire is created before step a,
15884 			 * it will be cleaned up by step c. If the ire is
15885 			 * created after step d, it will see the new value of
15886 			 * ipif_mtu. Any attempt to create the ire between
15887 			 * steps a to d will fail because of the IPIF_CHANGING
15888 			 * flag. Note that ire_create() is passed a pointer to
15889 			 * the ipif_mtu, and not the value. During ire_add
15890 			 * under the bucket lock, the ire_max_frag of the
15891 			 * new ire being created is set from the ipif/ire from
15892 			 * which it is being derived.
15893 			 */
15894 			mutex_enter(&ill->ill_lock);
15895 			ill->ill_max_frag = (uint_t)notify->dl_data;
15896 
15897 			/*
15898 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15899 			 * leave it alone
15900 			 */
15901 			if (ill->ill_mtu_userspecified) {
15902 				mutex_exit(&ill->ill_lock);
15903 				break;
15904 			}
15905 			ill->ill_max_mtu = ill->ill_max_frag;
15906 			if (ill->ill_isv6) {
15907 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15908 					ill->ill_max_mtu = IPV6_MIN_MTU;
15909 			} else {
15910 				if (ill->ill_max_mtu < IP_MIN_MTU)
15911 					ill->ill_max_mtu = IP_MIN_MTU;
15912 			}
15913 			for (ipif = ill->ill_ipif; ipif != NULL;
15914 			    ipif = ipif->ipif_next) {
15915 				/*
15916 				 * Don't override the mtu if the user
15917 				 * has explicitly set it.
15918 				 */
15919 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15920 					continue;
15921 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15922 				if (ipif->ipif_isv6)
15923 					ire = ipif_to_ire_v6(ipif);
15924 				else
15925 					ire = ipif_to_ire(ipif);
15926 				if (ire != NULL) {
15927 					ire->ire_max_frag = ipif->ipif_mtu;
15928 					ire_refrele(ire);
15929 				}
15930 				if (ipif->ipif_flags & IPIF_UP) {
15931 					if (ill->ill_isv6)
15932 						need_ire_walk_v6 = B_TRUE;
15933 					else
15934 						need_ire_walk_v4 = B_TRUE;
15935 				}
15936 			}
15937 			mutex_exit(&ill->ill_lock);
15938 			if (need_ire_walk_v4)
15939 				ire_walk_v4(ill_mtu_change, (char *)ill,
15940 				    ALL_ZONES, ipst);
15941 			if (need_ire_walk_v6)
15942 				ire_walk_v6(ill_mtu_change, (char *)ill,
15943 				    ALL_ZONES, ipst);
15944 			break;
15945 		case DL_NOTE_LINK_UP:
15946 		case DL_NOTE_LINK_DOWN: {
15947 			/*
15948 			 * We are writer. ill / phyint / ipsq assocs stable.
15949 			 * The RUNNING flag reflects the state of the link.
15950 			 */
15951 			phyint_t *phyint = ill->ill_phyint;
15952 			uint64_t new_phyint_flags;
15953 			boolean_t changed = B_FALSE;
15954 			boolean_t went_up;
15955 
15956 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15957 			mutex_enter(&phyint->phyint_lock);
15958 			new_phyint_flags = went_up ?
15959 			    phyint->phyint_flags | PHYI_RUNNING :
15960 			    phyint->phyint_flags & ~PHYI_RUNNING;
15961 			if (new_phyint_flags != phyint->phyint_flags) {
15962 				phyint->phyint_flags = new_phyint_flags;
15963 				changed = B_TRUE;
15964 			}
15965 			mutex_exit(&phyint->phyint_lock);
15966 			/*
15967 			 * ill_restart_dad handles the DAD restart and routing
15968 			 * socket notification logic.
15969 			 */
15970 			if (changed) {
15971 				ill_restart_dad(phyint->phyint_illv4, went_up);
15972 				ill_restart_dad(phyint->phyint_illv6, went_up);
15973 			}
15974 			break;
15975 		}
15976 		case DL_NOTE_PROMISC_ON_PHYS:
15977 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15978 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15979 			mutex_enter(&ill->ill_lock);
15980 			ill->ill_promisc_on_phys = B_TRUE;
15981 			mutex_exit(&ill->ill_lock);
15982 			break;
15983 		case DL_NOTE_PROMISC_OFF_PHYS:
15984 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15985 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15986 			mutex_enter(&ill->ill_lock);
15987 			ill->ill_promisc_on_phys = B_FALSE;
15988 			mutex_exit(&ill->ill_lock);
15989 			break;
15990 		case DL_NOTE_CAPAB_RENEG:
15991 			/*
15992 			 * Something changed on the driver side.
15993 			 * It wants us to renegotiate the capabilities
15994 			 * on this ill. One possible cause is the aggregation
15995 			 * interface under us where a port got added or
15996 			 * went away.
15997 			 *
15998 			 * If the capability negotiation is already done
15999 			 * or is in progress, reset the capabilities and
16000 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16001 			 * so that when the ack comes back, we can start
16002 			 * the renegotiation process.
16003 			 *
16004 			 * Note that if ill_capab_reneg is already B_TRUE
16005 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16006 			 * the capability resetting request has been sent
16007 			 * and the renegotiation has not been started yet;
16008 			 * nothing needs to be done in this case.
16009 			 */
16010 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16011 				ill_capability_reset(ill);
16012 				ill->ill_capab_reneg = B_TRUE;
16013 			}
16014 			break;
16015 		default:
16016 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16017 			    "type 0x%x for DL_NOTIFY_IND\n",
16018 			    notify->dl_notification));
16019 			break;
16020 		}
16021 
16022 		/*
16023 		 * As this is an asynchronous operation, we
16024 		 * should not call ill_dlpi_done
16025 		 */
16026 		break;
16027 	}
16028 	case DL_NOTIFY_ACK: {
16029 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16030 
16031 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16032 			ill->ill_note_link = 1;
16033 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16034 		break;
16035 	}
16036 	case DL_PHYS_ADDR_ACK: {
16037 		/*
16038 		 * As part of plumbing the interface via SIOCSLIFNAME,
16039 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16040 		 * whose answers we receive here.  As each answer is received,
16041 		 * we call ill_dlpi_done() to dispatch the next request as
16042 		 * we're processing the current one.  Once all answers have
16043 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16044 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16045 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16046 		 * available, but we know the ioctl is pending on ill_wq.)
16047 		 */
16048 		uint_t paddrlen, paddroff;
16049 
16050 		paddrreq = ill->ill_phys_addr_pend;
16051 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16052 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16053 
16054 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16055 		if (paddrreq == DL_IPV6_TOKEN) {
16056 			/*
16057 			 * bcopy to low-order bits of ill_token
16058 			 *
16059 			 * XXX Temporary hack - currently, all known tokens
16060 			 * are 64 bits, so I'll cheat for the moment.
16061 			 */
16062 			bcopy(mp->b_rptr + paddroff,
16063 			    &ill->ill_token.s6_addr32[2], paddrlen);
16064 			ill->ill_token_length = paddrlen;
16065 			break;
16066 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16067 			ASSERT(ill->ill_nd_lla_mp == NULL);
16068 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16069 			mp = NULL;
16070 			break;
16071 		}
16072 
16073 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16074 		ASSERT(ill->ill_phys_addr_mp == NULL);
16075 		if (!ill->ill_ifname_pending)
16076 			break;
16077 		ill->ill_ifname_pending = 0;
16078 		if (!ioctl_aborted)
16079 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16080 		if (mp1 != NULL) {
16081 			ASSERT(connp == NULL);
16082 			q = ill->ill_wq;
16083 		}
16084 		/*
16085 		 * If any error acks received during the plumbing sequence,
16086 		 * ill_ifname_pending_err will be set. Break out and send up
16087 		 * the error to the pending ioctl.
16088 		 */
16089 		if (ill->ill_ifname_pending_err != 0) {
16090 			err = ill->ill_ifname_pending_err;
16091 			ill->ill_ifname_pending_err = 0;
16092 			break;
16093 		}
16094 
16095 		ill->ill_phys_addr_mp = mp;
16096 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16097 		mp = NULL;
16098 
16099 		/*
16100 		 * If paddrlen is zero, the DLPI provider doesn't support
16101 		 * physical addresses.  The other two tests were historical
16102 		 * workarounds for bugs in our former PPP implementation, but
16103 		 * now other things have grown dependencies on them -- e.g.,
16104 		 * the tun module specifies a dl_addr_length of zero in its
16105 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16106 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16107 		 * but only after careful testing ensures that all dependent
16108 		 * broken DLPI providers have been fixed.
16109 		 */
16110 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16111 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16112 			ill->ill_phys_addr = NULL;
16113 		} else if (paddrlen != ill->ill_phys_addr_length) {
16114 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16115 			    paddrlen, ill->ill_phys_addr_length));
16116 			err = EINVAL;
16117 			break;
16118 		}
16119 
16120 		if (ill->ill_nd_lla_mp == NULL) {
16121 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16122 				err = ENOMEM;
16123 				break;
16124 			}
16125 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16126 		}
16127 
16128 		/*
16129 		 * Set the interface token.  If the zeroth interface address
16130 		 * is unspecified, then set it to the link local address.
16131 		 */
16132 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16133 			(void) ill_setdefaulttoken(ill);
16134 
16135 		ASSERT(ill->ill_ipif->ipif_id == 0);
16136 		if (ipif != NULL &&
16137 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16138 			(void) ipif_setlinklocal(ipif);
16139 		}
16140 		break;
16141 	}
16142 	case DL_OK_ACK:
16143 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16144 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16145 		    dloa->dl_correct_primitive));
16146 		switch (dloa->dl_correct_primitive) {
16147 		case DL_PROMISCON_REQ:
16148 		case DL_PROMISCOFF_REQ:
16149 		case DL_ENABMULTI_REQ:
16150 		case DL_DISABMULTI_REQ:
16151 		case DL_UNBIND_REQ:
16152 		case DL_ATTACH_REQ:
16153 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16154 			break;
16155 		}
16156 		break;
16157 	default:
16158 		break;
16159 	}
16160 
16161 	freemsg(mp);
16162 	if (mp1 != NULL) {
16163 		/*
16164 		 * The operation must complete without EINPROGRESS
16165 		 * since ipsq_pending_mp_get() has removed the mblk
16166 		 * from ipsq_pending_mp.  Otherwise, the operation
16167 		 * will be stuck forever in the ipsq.
16168 		 */
16169 		ASSERT(err != EINPROGRESS);
16170 
16171 		switch (ipsq->ipsq_current_ioctl) {
16172 		case 0:
16173 			ipsq_current_finish(ipsq);
16174 			break;
16175 
16176 		case SIOCLIFADDIF:
16177 		case SIOCSLIFNAME:
16178 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16179 			break;
16180 
16181 		default:
16182 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16183 			break;
16184 		}
16185 	}
16186 }
16187 
16188 /*
16189  * ip_rput_other is called by ip_rput to handle messages modifying the global
16190  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16191  */
16192 /* ARGSUSED */
16193 void
16194 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16195 {
16196 	ill_t		*ill;
16197 	struct iocblk	*iocp;
16198 	mblk_t		*mp1;
16199 	conn_t		*connp = NULL;
16200 
16201 	ip1dbg(("ip_rput_other "));
16202 	ill = (ill_t *)q->q_ptr;
16203 	/*
16204 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16205 	 * in which case ipsq is NULL.
16206 	 */
16207 	if (ipsq != NULL) {
16208 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16209 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16210 	}
16211 
16212 	switch (mp->b_datap->db_type) {
16213 	case M_ERROR:
16214 	case M_HANGUP:
16215 		/*
16216 		 * The device has a problem.  We force the ILL down.  It can
16217 		 * be brought up again manually using SIOCSIFFLAGS (via
16218 		 * ifconfig or equivalent).
16219 		 */
16220 		ASSERT(ipsq != NULL);
16221 		if (mp->b_rptr < mp->b_wptr)
16222 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16223 		if (ill->ill_error == 0)
16224 			ill->ill_error = ENXIO;
16225 		if (!ill_down_start(q, mp))
16226 			return;
16227 		ipif_all_down_tail(ipsq, q, mp, NULL);
16228 		break;
16229 	case M_IOCACK:
16230 		iocp = (struct iocblk *)mp->b_rptr;
16231 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16232 		switch (iocp->ioc_cmd) {
16233 		case SIOCSTUNPARAM:
16234 		case OSIOCSTUNPARAM:
16235 			ASSERT(ipsq != NULL);
16236 			/*
16237 			 * Finish socket ioctl passed through to tun.
16238 			 * We should have an IOCTL waiting on this.
16239 			 */
16240 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16241 			if (ill->ill_isv6) {
16242 				struct iftun_req *ta;
16243 
16244 				/*
16245 				 * if a source or destination is
16246 				 * being set, try and set the link
16247 				 * local address for the tunnel
16248 				 */
16249 				ta = (struct iftun_req *)mp->b_cont->
16250 				    b_cont->b_rptr;
16251 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16252 					ipif_set_tun_llink(ill, ta);
16253 				}
16254 
16255 			}
16256 			if (mp1 != NULL) {
16257 				/*
16258 				 * Now copy back the b_next/b_prev used by
16259 				 * mi code for the mi_copy* functions.
16260 				 * See ip_sioctl_tunparam() for the reason.
16261 				 * Also protect against missing b_cont.
16262 				 */
16263 				if (mp->b_cont != NULL) {
16264 					mp->b_cont->b_next =
16265 					    mp1->b_cont->b_next;
16266 					mp->b_cont->b_prev =
16267 					    mp1->b_cont->b_prev;
16268 				}
16269 				inet_freemsg(mp1);
16270 				ASSERT(connp != NULL);
16271 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16272 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16273 			} else {
16274 				ASSERT(connp == NULL);
16275 				putnext(q, mp);
16276 			}
16277 			break;
16278 		case SIOCGTUNPARAM:
16279 		case OSIOCGTUNPARAM:
16280 			/*
16281 			 * This is really M_IOCDATA from the tunnel driver.
16282 			 * convert back and complete the ioctl.
16283 			 * We should have an IOCTL waiting on this.
16284 			 */
16285 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16286 			if (mp1) {
16287 				/*
16288 				 * Now copy back the b_next/b_prev used by
16289 				 * mi code for the mi_copy* functions.
16290 				 * See ip_sioctl_tunparam() for the reason.
16291 				 * Also protect against missing b_cont.
16292 				 */
16293 				if (mp->b_cont != NULL) {
16294 					mp->b_cont->b_next =
16295 					    mp1->b_cont->b_next;
16296 					mp->b_cont->b_prev =
16297 					    mp1->b_cont->b_prev;
16298 				}
16299 				inet_freemsg(mp1);
16300 				if (iocp->ioc_error == 0)
16301 					mp->b_datap->db_type = M_IOCDATA;
16302 				ASSERT(connp != NULL);
16303 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16304 				    iocp->ioc_error, COPYOUT, NULL);
16305 			} else {
16306 				ASSERT(connp == NULL);
16307 				putnext(q, mp);
16308 			}
16309 			break;
16310 		default:
16311 			break;
16312 		}
16313 		break;
16314 	case M_IOCNAK:
16315 		iocp = (struct iocblk *)mp->b_rptr;
16316 
16317 		switch (iocp->ioc_cmd) {
16318 		int mode;
16319 
16320 		case DL_IOC_HDR_INFO:
16321 			/*
16322 			 * If this was the first attempt turn of the
16323 			 * fastpath probing.
16324 			 */
16325 			mutex_enter(&ill->ill_lock);
16326 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16327 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16328 				mutex_exit(&ill->ill_lock);
16329 				ill_fastpath_nack(ill);
16330 				ip1dbg(("ip_rput: DLPI fastpath off on "
16331 				    "interface %s\n",
16332 				    ill->ill_name));
16333 			} else {
16334 				mutex_exit(&ill->ill_lock);
16335 			}
16336 			freemsg(mp);
16337 			break;
16338 		case SIOCSTUNPARAM:
16339 		case OSIOCSTUNPARAM:
16340 			ASSERT(ipsq != NULL);
16341 			/*
16342 			 * Finish socket ioctl passed through to tun
16343 			 * We should have an IOCTL waiting on this.
16344 			 */
16345 			/* FALLTHRU */
16346 		case SIOCGTUNPARAM:
16347 		case OSIOCGTUNPARAM:
16348 			/*
16349 			 * This is really M_IOCDATA from the tunnel driver.
16350 			 * convert back and complete the ioctl.
16351 			 * We should have an IOCTL waiting on this.
16352 			 */
16353 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16354 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16355 				mp1 = ill_pending_mp_get(ill, &connp,
16356 				    iocp->ioc_id);
16357 				mode = COPYOUT;
16358 				ipsq = NULL;
16359 			} else {
16360 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16361 				mode = NO_COPYOUT;
16362 			}
16363 			if (mp1 != NULL) {
16364 				/*
16365 				 * Now copy back the b_next/b_prev used by
16366 				 * mi code for the mi_copy* functions.
16367 				 * See ip_sioctl_tunparam() for the reason.
16368 				 * Also protect against missing b_cont.
16369 				 */
16370 				if (mp->b_cont != NULL) {
16371 					mp->b_cont->b_next =
16372 					    mp1->b_cont->b_next;
16373 					mp->b_cont->b_prev =
16374 					    mp1->b_cont->b_prev;
16375 				}
16376 				inet_freemsg(mp1);
16377 				if (iocp->ioc_error == 0)
16378 					iocp->ioc_error = EINVAL;
16379 				ASSERT(connp != NULL);
16380 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16381 				    iocp->ioc_error, mode, ipsq);
16382 			} else {
16383 				ASSERT(connp == NULL);
16384 				putnext(q, mp);
16385 			}
16386 			break;
16387 		default:
16388 			break;
16389 		}
16390 	default:
16391 		break;
16392 	}
16393 }
16394 
16395 /*
16396  * NOTE : This function does not ire_refrele the ire argument passed in.
16397  *
16398  * IPQoS notes
16399  * IP policy is invoked twice for a forwarded packet, once on the read side
16400  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16401  * enabled. An additional parameter, in_ill, has been added for this purpose.
16402  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16403  * because ip_mroute drops this information.
16404  *
16405  */
16406 void
16407 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16408 {
16409 	uint32_t	old_pkt_len;
16410 	uint32_t	pkt_len;
16411 	queue_t	*q;
16412 	uint32_t	sum;
16413 #define	rptr	((uchar_t *)ipha)
16414 	uint32_t	max_frag;
16415 	uint32_t	ill_index;
16416 	ill_t		*out_ill;
16417 	mib2_ipIfStatsEntry_t *mibptr;
16418 	ip_stack_t	*ipst = in_ill->ill_ipst;
16419 
16420 	/* Get the ill_index of the incoming ILL */
16421 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16422 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16423 
16424 	/* Initiate Read side IPPF processing */
16425 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16426 		ip_process(IPP_FWD_IN, &mp, ill_index);
16427 		if (mp == NULL) {
16428 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16429 			    "during IPPF processing\n"));
16430 			return;
16431 		}
16432 	}
16433 
16434 	/* Adjust the checksum to reflect the ttl decrement. */
16435 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16436 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16437 
16438 	if (ipha->ipha_ttl-- <= 1) {
16439 		if (ip_csum_hdr(ipha)) {
16440 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16441 			goto drop_pkt;
16442 		}
16443 		/*
16444 		 * Note: ire_stq this will be NULL for multicast
16445 		 * datagrams using the long path through arp (the IRE
16446 		 * is not an IRE_CACHE). This should not cause
16447 		 * problems since we don't generate ICMP errors for
16448 		 * multicast packets.
16449 		 */
16450 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16451 		q = ire->ire_stq;
16452 		if (q != NULL) {
16453 			/* Sent by forwarding path, and router is global zone */
16454 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16455 			    GLOBAL_ZONEID, ipst);
16456 		} else
16457 			freemsg(mp);
16458 		return;
16459 	}
16460 
16461 	/*
16462 	 * Don't forward if the interface is down
16463 	 */
16464 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16465 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16466 		ip2dbg(("ip_rput_forward:interface is down\n"));
16467 		goto drop_pkt;
16468 	}
16469 
16470 	/* Get the ill_index of the outgoing ILL */
16471 	out_ill = ire_to_ill(ire);
16472 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16473 
16474 	DTRACE_PROBE4(ip4__forwarding__start,
16475 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16476 
16477 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16478 	    ipst->ips_ipv4firewall_forwarding,
16479 	    in_ill, out_ill, ipha, mp, mp, ipst);
16480 
16481 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16482 
16483 	if (mp == NULL)
16484 		return;
16485 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16486 
16487 	if (is_system_labeled()) {
16488 		mblk_t *mp1;
16489 
16490 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16491 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16492 			goto drop_pkt;
16493 		}
16494 		/* Size may have changed */
16495 		mp = mp1;
16496 		ipha = (ipha_t *)mp->b_rptr;
16497 		pkt_len = ntohs(ipha->ipha_length);
16498 	}
16499 
16500 	/* Check if there are options to update */
16501 	if (!IS_SIMPLE_IPH(ipha)) {
16502 		if (ip_csum_hdr(ipha)) {
16503 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16504 			goto drop_pkt;
16505 		}
16506 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16507 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16508 			return;
16509 		}
16510 
16511 		ipha->ipha_hdr_checksum = 0;
16512 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16513 	}
16514 	max_frag = ire->ire_max_frag;
16515 	if (pkt_len > max_frag) {
16516 		/*
16517 		 * It needs fragging on its way out.  We haven't
16518 		 * verified the header checksum yet.  Since we
16519 		 * are going to put a surely good checksum in the
16520 		 * outgoing header, we have to make sure that it
16521 		 * was good coming in.
16522 		 */
16523 		if (ip_csum_hdr(ipha)) {
16524 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16525 			goto drop_pkt;
16526 		}
16527 		/* Initiate Write side IPPF processing */
16528 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16529 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16530 			if (mp == NULL) {
16531 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16532 				    " during IPPF processing\n"));
16533 				return;
16534 			}
16535 		}
16536 		/*
16537 		 * Handle labeled packet resizing.
16538 		 *
16539 		 * If we have added a label, inform ip_wput_frag() of its
16540 		 * effect on the MTU for ICMP messages.
16541 		 */
16542 		if (pkt_len > old_pkt_len) {
16543 			uint32_t secopt_size;
16544 
16545 			secopt_size = pkt_len - old_pkt_len;
16546 			if (secopt_size < max_frag)
16547 				max_frag -= secopt_size;
16548 		}
16549 
16550 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16551 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16552 		return;
16553 	}
16554 
16555 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16556 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16557 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16558 	    ipst->ips_ipv4firewall_physical_out,
16559 	    NULL, out_ill, ipha, mp, mp, ipst);
16560 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16561 	if (mp == NULL)
16562 		return;
16563 
16564 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16565 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16566 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16567 	/* ip_xmit_v4 always consumes the packet */
16568 	return;
16569 
16570 drop_pkt:;
16571 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16572 	freemsg(mp);
16573 #undef	rptr
16574 }
16575 
16576 void
16577 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16578 {
16579 	ire_t	*ire;
16580 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16581 
16582 	ASSERT(!ipif->ipif_isv6);
16583 	/*
16584 	 * Find an IRE which matches the destination and the outgoing
16585 	 * queue in the cache table. All we need is an IRE_CACHE which
16586 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16587 	 * then it is enough to have some IRE_CACHE in the group.
16588 	 */
16589 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16590 		dst = ipif->ipif_pp_dst_addr;
16591 
16592 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16593 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16594 	if (ire == NULL) {
16595 		/*
16596 		 * Mark this packet to make it be delivered to
16597 		 * ip_rput_forward after the new ire has been
16598 		 * created.
16599 		 */
16600 		mp->b_prev = NULL;
16601 		mp->b_next = mp;
16602 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16603 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16604 	} else {
16605 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16606 		IRE_REFRELE(ire);
16607 	}
16608 }
16609 
16610 /* Update any source route, record route or timestamp options */
16611 static int
16612 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16613 {
16614 	ipoptp_t	opts;
16615 	uchar_t		*opt;
16616 	uint8_t		optval;
16617 	uint8_t		optlen;
16618 	ipaddr_t	dst;
16619 	uint32_t	ts;
16620 	ire_t		*dst_ire = NULL;
16621 	ire_t		*tmp_ire = NULL;
16622 	timestruc_t	now;
16623 
16624 	ip2dbg(("ip_rput_forward_options\n"));
16625 	dst = ipha->ipha_dst;
16626 	for (optval = ipoptp_first(&opts, ipha);
16627 	    optval != IPOPT_EOL;
16628 	    optval = ipoptp_next(&opts)) {
16629 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16630 		opt = opts.ipoptp_cur;
16631 		optlen = opts.ipoptp_len;
16632 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16633 		    optval, opts.ipoptp_len));
16634 		switch (optval) {
16635 			uint32_t off;
16636 		case IPOPT_SSRR:
16637 		case IPOPT_LSRR:
16638 			/* Check if adminstratively disabled */
16639 			if (!ipst->ips_ip_forward_src_routed) {
16640 				if (ire->ire_stq != NULL) {
16641 					/*
16642 					 * Sent by forwarding path, and router
16643 					 * is global zone
16644 					 */
16645 					icmp_unreachable(ire->ire_stq, mp,
16646 					    ICMP_SOURCE_ROUTE_FAILED,
16647 					    GLOBAL_ZONEID, ipst);
16648 				} else {
16649 					ip0dbg(("ip_rput_forward_options: "
16650 					    "unable to send unreach\n"));
16651 					freemsg(mp);
16652 				}
16653 				return (-1);
16654 			}
16655 
16656 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16657 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16658 			if (dst_ire == NULL) {
16659 				/*
16660 				 * Must be partial since ip_rput_options
16661 				 * checked for strict.
16662 				 */
16663 				break;
16664 			}
16665 			off = opt[IPOPT_OFFSET];
16666 			off--;
16667 		redo_srr:
16668 			if (optlen < IP_ADDR_LEN ||
16669 			    off > optlen - IP_ADDR_LEN) {
16670 				/* End of source route */
16671 				ip1dbg((
16672 				    "ip_rput_forward_options: end of SR\n"));
16673 				ire_refrele(dst_ire);
16674 				break;
16675 			}
16676 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16677 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16678 			    IP_ADDR_LEN);
16679 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16680 			    ntohl(dst)));
16681 
16682 			/*
16683 			 * Check if our address is present more than
16684 			 * once as consecutive hops in source route.
16685 			 */
16686 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16687 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16688 			if (tmp_ire != NULL) {
16689 				ire_refrele(tmp_ire);
16690 				off += IP_ADDR_LEN;
16691 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16692 				goto redo_srr;
16693 			}
16694 			ipha->ipha_dst = dst;
16695 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16696 			ire_refrele(dst_ire);
16697 			break;
16698 		case IPOPT_RR:
16699 			off = opt[IPOPT_OFFSET];
16700 			off--;
16701 			if (optlen < IP_ADDR_LEN ||
16702 			    off > optlen - IP_ADDR_LEN) {
16703 				/* No more room - ignore */
16704 				ip1dbg((
16705 				    "ip_rput_forward_options: end of RR\n"));
16706 				break;
16707 			}
16708 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16709 			    IP_ADDR_LEN);
16710 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16711 			break;
16712 		case IPOPT_TS:
16713 			/* Insert timestamp if there is room */
16714 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16715 			case IPOPT_TS_TSONLY:
16716 				off = IPOPT_TS_TIMELEN;
16717 				break;
16718 			case IPOPT_TS_PRESPEC:
16719 			case IPOPT_TS_PRESPEC_RFC791:
16720 				/* Verify that the address matched */
16721 				off = opt[IPOPT_OFFSET] - 1;
16722 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16723 				dst_ire = ire_ctable_lookup(dst, 0,
16724 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16725 				    MATCH_IRE_TYPE, ipst);
16726 				if (dst_ire == NULL) {
16727 					/* Not for us */
16728 					break;
16729 				}
16730 				ire_refrele(dst_ire);
16731 				/* FALLTHRU */
16732 			case IPOPT_TS_TSANDADDR:
16733 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16734 				break;
16735 			default:
16736 				/*
16737 				 * ip_*put_options should have already
16738 				 * dropped this packet.
16739 				 */
16740 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16741 				    "unknown IT - bug in ip_rput_options?\n");
16742 				return (0);	/* Keep "lint" happy */
16743 			}
16744 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16745 				/* Increase overflow counter */
16746 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16747 				opt[IPOPT_POS_OV_FLG] =
16748 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16749 				    (off << 4));
16750 				break;
16751 			}
16752 			off = opt[IPOPT_OFFSET] - 1;
16753 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16754 			case IPOPT_TS_PRESPEC:
16755 			case IPOPT_TS_PRESPEC_RFC791:
16756 			case IPOPT_TS_TSANDADDR:
16757 				bcopy(&ire->ire_src_addr,
16758 				    (char *)opt + off, IP_ADDR_LEN);
16759 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16760 				/* FALLTHRU */
16761 			case IPOPT_TS_TSONLY:
16762 				off = opt[IPOPT_OFFSET] - 1;
16763 				/* Compute # of milliseconds since midnight */
16764 				gethrestime(&now);
16765 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16766 				    now.tv_nsec / (NANOSEC / MILLISEC);
16767 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16768 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16769 				break;
16770 			}
16771 			break;
16772 		}
16773 	}
16774 	return (0);
16775 }
16776 
16777 /*
16778  * This is called after processing at least one of AH/ESP headers.
16779  *
16780  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16781  * the actual, physical interface on which the packet was received,
16782  * but, when ip_strict_dst_multihoming is set to 1, could be the
16783  * interface which had the ipha_dst configured when the packet went
16784  * through ip_rput. The ill_index corresponding to the recv_ill
16785  * is saved in ipsec_in_rill_index
16786  *
16787  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16788  * cannot assume "ire" points to valid data for any IPv6 cases.
16789  */
16790 void
16791 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16792 {
16793 	mblk_t *mp;
16794 	ipaddr_t dst;
16795 	in6_addr_t *v6dstp;
16796 	ipha_t *ipha;
16797 	ip6_t *ip6h;
16798 	ipsec_in_t *ii;
16799 	boolean_t ill_need_rele = B_FALSE;
16800 	boolean_t rill_need_rele = B_FALSE;
16801 	boolean_t ire_need_rele = B_FALSE;
16802 	netstack_t	*ns;
16803 	ip_stack_t	*ipst;
16804 
16805 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16806 	ASSERT(ii->ipsec_in_ill_index != 0);
16807 	ns = ii->ipsec_in_ns;
16808 	ASSERT(ii->ipsec_in_ns != NULL);
16809 	ipst = ns->netstack_ip;
16810 
16811 	mp = ipsec_mp->b_cont;
16812 	ASSERT(mp != NULL);
16813 
16814 
16815 	if (ill == NULL) {
16816 		ASSERT(recv_ill == NULL);
16817 		/*
16818 		 * We need to get the original queue on which ip_rput_local
16819 		 * or ip_rput_data_v6 was called.
16820 		 */
16821 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16822 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16823 		ill_need_rele = B_TRUE;
16824 
16825 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16826 			recv_ill = ill_lookup_on_ifindex(
16827 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16828 			    NULL, NULL, NULL, NULL, ipst);
16829 			rill_need_rele = B_TRUE;
16830 		} else {
16831 			recv_ill = ill;
16832 		}
16833 
16834 		if ((ill == NULL) || (recv_ill == NULL)) {
16835 			ip0dbg(("ip_fanout_proto_again: interface "
16836 			    "disappeared\n"));
16837 			if (ill != NULL)
16838 				ill_refrele(ill);
16839 			if (recv_ill != NULL)
16840 				ill_refrele(recv_ill);
16841 			freemsg(ipsec_mp);
16842 			return;
16843 		}
16844 	}
16845 
16846 	ASSERT(ill != NULL && recv_ill != NULL);
16847 
16848 	if (mp->b_datap->db_type == M_CTL) {
16849 		/*
16850 		 * AH/ESP is returning the ICMP message after
16851 		 * removing their headers. Fanout again till
16852 		 * it gets to the right protocol.
16853 		 */
16854 		if (ii->ipsec_in_v4) {
16855 			icmph_t *icmph;
16856 			int iph_hdr_length;
16857 			int hdr_length;
16858 
16859 			ipha = (ipha_t *)mp->b_rptr;
16860 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16861 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16862 			ipha = (ipha_t *)&icmph[1];
16863 			hdr_length = IPH_HDR_LENGTH(ipha);
16864 			/*
16865 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16866 			 * Reset the type to M_DATA.
16867 			 */
16868 			mp->b_datap->db_type = M_DATA;
16869 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16870 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16871 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16872 		} else {
16873 			icmp6_t *icmp6;
16874 			int hdr_length;
16875 
16876 			ip6h = (ip6_t *)mp->b_rptr;
16877 			/* Don't call hdr_length_v6() unless you have to. */
16878 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16879 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16880 			else
16881 				hdr_length = IPV6_HDR_LEN;
16882 
16883 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16884 			/*
16885 			 * icmp_inbound_error_fanout_v6 may need to do
16886 			 * pullupmsg.  Reset the type to M_DATA.
16887 			 */
16888 			mp->b_datap->db_type = M_DATA;
16889 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16890 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16891 		}
16892 		if (ill_need_rele)
16893 			ill_refrele(ill);
16894 		if (rill_need_rele)
16895 			ill_refrele(recv_ill);
16896 		return;
16897 	}
16898 
16899 	if (ii->ipsec_in_v4) {
16900 		ipha = (ipha_t *)mp->b_rptr;
16901 		dst = ipha->ipha_dst;
16902 		if (CLASSD(dst)) {
16903 			/*
16904 			 * Multicast has to be delivered to all streams.
16905 			 */
16906 			dst = INADDR_BROADCAST;
16907 		}
16908 
16909 		if (ire == NULL) {
16910 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16911 			    MBLK_GETLABEL(mp), ipst);
16912 			if (ire == NULL) {
16913 				if (ill_need_rele)
16914 					ill_refrele(ill);
16915 				if (rill_need_rele)
16916 					ill_refrele(recv_ill);
16917 				ip1dbg(("ip_fanout_proto_again: "
16918 				    "IRE not found"));
16919 				freemsg(ipsec_mp);
16920 				return;
16921 			}
16922 			ire_need_rele = B_TRUE;
16923 		}
16924 
16925 		switch (ipha->ipha_protocol) {
16926 			case IPPROTO_UDP:
16927 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16928 				    recv_ill);
16929 				if (ire_need_rele)
16930 					ire_refrele(ire);
16931 				break;
16932 			case IPPROTO_TCP:
16933 				if (!ire_need_rele)
16934 					IRE_REFHOLD(ire);
16935 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16936 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16937 				IRE_REFRELE(ire);
16938 				if (mp != NULL)
16939 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16940 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16941 				break;
16942 			case IPPROTO_SCTP:
16943 				if (!ire_need_rele)
16944 					IRE_REFHOLD(ire);
16945 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16946 				    ipsec_mp, 0, ill->ill_rq, dst);
16947 				break;
16948 			default:
16949 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16950 				    recv_ill, B_FALSE);
16951 				if (ire_need_rele)
16952 					ire_refrele(ire);
16953 				break;
16954 		}
16955 	} else {
16956 		uint32_t rput_flags = 0;
16957 
16958 		ip6h = (ip6_t *)mp->b_rptr;
16959 		v6dstp = &ip6h->ip6_dst;
16960 		/*
16961 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16962 		 * address.
16963 		 *
16964 		 * Currently, we don't store that state in the IPSEC_IN
16965 		 * message, and we may need to.
16966 		 */
16967 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16968 		    IP6_IN_LLMCAST : 0);
16969 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16970 		    NULL, NULL);
16971 	}
16972 	if (ill_need_rele)
16973 		ill_refrele(ill);
16974 	if (rill_need_rele)
16975 		ill_refrele(recv_ill);
16976 }
16977 
16978 /*
16979  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16980  * returns 'true' if there are still fragments left on the queue, in
16981  * which case we restart the timer.
16982  */
16983 void
16984 ill_frag_timer(void *arg)
16985 {
16986 	ill_t	*ill = (ill_t *)arg;
16987 	boolean_t frag_pending;
16988 	ip_stack_t	*ipst = ill->ill_ipst;
16989 
16990 	mutex_enter(&ill->ill_lock);
16991 	ASSERT(!ill->ill_fragtimer_executing);
16992 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16993 		ill->ill_frag_timer_id = 0;
16994 		mutex_exit(&ill->ill_lock);
16995 		return;
16996 	}
16997 	ill->ill_fragtimer_executing = 1;
16998 	mutex_exit(&ill->ill_lock);
16999 
17000 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17001 
17002 	/*
17003 	 * Restart the timer, if we have fragments pending or if someone
17004 	 * wanted us to be scheduled again.
17005 	 */
17006 	mutex_enter(&ill->ill_lock);
17007 	ill->ill_fragtimer_executing = 0;
17008 	ill->ill_frag_timer_id = 0;
17009 	if (frag_pending || ill->ill_fragtimer_needrestart)
17010 		ill_frag_timer_start(ill);
17011 	mutex_exit(&ill->ill_lock);
17012 }
17013 
17014 void
17015 ill_frag_timer_start(ill_t *ill)
17016 {
17017 	ip_stack_t	*ipst = ill->ill_ipst;
17018 
17019 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17020 
17021 	/* If the ill is closing or opening don't proceed */
17022 	if (ill->ill_state_flags & ILL_CONDEMNED)
17023 		return;
17024 
17025 	if (ill->ill_fragtimer_executing) {
17026 		/*
17027 		 * ill_frag_timer is currently executing. Just record the
17028 		 * the fact that we want the timer to be restarted.
17029 		 * ill_frag_timer will post a timeout before it returns,
17030 		 * ensuring it will be called again.
17031 		 */
17032 		ill->ill_fragtimer_needrestart = 1;
17033 		return;
17034 	}
17035 
17036 	if (ill->ill_frag_timer_id == 0) {
17037 		/*
17038 		 * The timer is neither running nor is the timeout handler
17039 		 * executing. Post a timeout so that ill_frag_timer will be
17040 		 * called
17041 		 */
17042 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17043 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17044 		ill->ill_fragtimer_needrestart = 0;
17045 	}
17046 }
17047 
17048 /*
17049  * This routine is needed for loopback when forwarding multicasts.
17050  *
17051  * IPQoS Notes:
17052  * IPPF processing is done in fanout routines.
17053  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17054  * processing for IPsec packets is done when it comes back in clear.
17055  * NOTE : The callers of this function need to do the ire_refrele for the
17056  *	  ire that is being passed in.
17057  */
17058 void
17059 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17060     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17061 {
17062 	ill_t	*ill = (ill_t *)q->q_ptr;
17063 	uint32_t	sum;
17064 	uint32_t	u1;
17065 	uint32_t	u2;
17066 	int		hdr_length;
17067 	boolean_t	mctl_present;
17068 	mblk_t		*first_mp = mp;
17069 	mblk_t		*hada_mp = NULL;
17070 	ipha_t		*inner_ipha;
17071 	ip_stack_t	*ipst;
17072 
17073 	ASSERT(recv_ill != NULL);
17074 	ipst = recv_ill->ill_ipst;
17075 
17076 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17077 	    "ip_rput_locl_start: q %p", q);
17078 
17079 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17080 	ASSERT(ill != NULL);
17081 
17082 
17083 #define	rptr	((uchar_t *)ipha)
17084 #define	iphs	((uint16_t *)ipha)
17085 
17086 	/*
17087 	 * no UDP or TCP packet should come here anymore.
17088 	 */
17089 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17090 	    ipha->ipha_protocol != IPPROTO_UDP);
17091 
17092 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17093 	if (mctl_present &&
17094 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17095 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17096 
17097 		/*
17098 		 * It's an IPsec accelerated packet.
17099 		 * Keep a pointer to the data attributes around until
17100 		 * we allocate the ipsec_info_t.
17101 		 */
17102 		IPSECHW_DEBUG(IPSECHW_PKT,
17103 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17104 		hada_mp = first_mp;
17105 		hada_mp->b_cont = NULL;
17106 		/*
17107 		 * Since it is accelerated, it comes directly from
17108 		 * the ill and the data attributes is followed by
17109 		 * the packet data.
17110 		 */
17111 		ASSERT(mp->b_datap->db_type != M_CTL);
17112 		first_mp = mp;
17113 		mctl_present = B_FALSE;
17114 	}
17115 
17116 	/*
17117 	 * IF M_CTL is not present, then ipsec_in_is_secure
17118 	 * should return B_TRUE. There is a case where loopback
17119 	 * packets has an M_CTL in the front with all the
17120 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17121 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17122 	 * packets never comes here, it is safe to ASSERT the
17123 	 * following.
17124 	 */
17125 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17126 
17127 	/*
17128 	 * Also, we should never have an mctl_present if this is an
17129 	 * ESP-in-UDP packet.
17130 	 */
17131 	ASSERT(!mctl_present || !esp_in_udp_packet);
17132 
17133 
17134 	/* u1 is # words of IP options */
17135 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17136 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17137 
17138 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17139 		if (u1) {
17140 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17141 				if (hada_mp != NULL)
17142 					freemsg(hada_mp);
17143 				return;
17144 			}
17145 		} else {
17146 			/* Check the IP header checksum.  */
17147 #define	uph	((uint16_t *)ipha)
17148 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17149 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17150 #undef  uph
17151 			/* finish doing IP checksum */
17152 			sum = (sum & 0xFFFF) + (sum >> 16);
17153 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17154 			if (sum && sum != 0xFFFF) {
17155 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17156 				goto drop_pkt;
17157 			}
17158 		}
17159 	}
17160 
17161 	/*
17162 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17163 	 * might be called more than once for secure packets, count only
17164 	 * the first time.
17165 	 */
17166 	if (!mctl_present) {
17167 		UPDATE_IB_PKT_COUNT(ire);
17168 		ire->ire_last_used_time = lbolt;
17169 	}
17170 
17171 	/* Check for fragmentation offset. */
17172 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17173 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17174 	if (u1) {
17175 		/*
17176 		 * We re-assemble fragments before we do the AH/ESP
17177 		 * processing. Thus, M_CTL should not be present
17178 		 * while we are re-assembling.
17179 		 */
17180 		ASSERT(!mctl_present);
17181 		ASSERT(first_mp == mp);
17182 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17183 			return;
17184 		}
17185 		/*
17186 		 * Make sure that first_mp points back to mp as
17187 		 * the mp we came in with could have changed in
17188 		 * ip_rput_fragment().
17189 		 */
17190 		ipha = (ipha_t *)mp->b_rptr;
17191 		first_mp = mp;
17192 	}
17193 
17194 	/*
17195 	 * Clear hardware checksumming flag as it is currently only
17196 	 * used by TCP and UDP.
17197 	 */
17198 	DB_CKSUMFLAGS(mp) = 0;
17199 
17200 	/* Now we have a complete datagram, destined for this machine. */
17201 	u1 = IPH_HDR_LENGTH(ipha);
17202 	switch (ipha->ipha_protocol) {
17203 	case IPPROTO_ICMP: {
17204 		ire_t		*ire_zone;
17205 		ilm_t		*ilm;
17206 		mblk_t		*mp1;
17207 		zoneid_t	last_zoneid;
17208 
17209 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17210 			ASSERT(ire->ire_type == IRE_BROADCAST);
17211 			/*
17212 			 * In the multicast case, applications may have joined
17213 			 * the group from different zones, so we need to deliver
17214 			 * the packet to each of them. Loop through the
17215 			 * multicast memberships structures (ilm) on the receive
17216 			 * ill and send a copy of the packet up each matching
17217 			 * one. However, we don't do this for multicasts sent on
17218 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17219 			 * they must stay in the sender's zone.
17220 			 *
17221 			 * ilm_add_v6() ensures that ilms in the same zone are
17222 			 * contiguous in the ill_ilm list. We use this property
17223 			 * to avoid sending duplicates needed when two
17224 			 * applications in the same zone join the same group on
17225 			 * different logical interfaces: we ignore the ilm if
17226 			 * its zoneid is the same as the last matching one.
17227 			 * In addition, the sending of the packet for
17228 			 * ire_zoneid is delayed until all of the other ilms
17229 			 * have been exhausted.
17230 			 */
17231 			last_zoneid = -1;
17232 			ILM_WALKER_HOLD(recv_ill);
17233 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17234 			    ilm = ilm->ilm_next) {
17235 				if ((ilm->ilm_flags & ILM_DELETED) ||
17236 				    ipha->ipha_dst != ilm->ilm_addr ||
17237 				    ilm->ilm_zoneid == last_zoneid ||
17238 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17239 				    ilm->ilm_zoneid == ALL_ZONES ||
17240 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17241 					continue;
17242 				mp1 = ip_copymsg(first_mp);
17243 				if (mp1 == NULL)
17244 					continue;
17245 				icmp_inbound(q, mp1, B_TRUE, ill,
17246 				    0, sum, mctl_present, B_TRUE,
17247 				    recv_ill, ilm->ilm_zoneid);
17248 				last_zoneid = ilm->ilm_zoneid;
17249 			}
17250 			ILM_WALKER_RELE(recv_ill);
17251 		} else if (ire->ire_type == IRE_BROADCAST) {
17252 			/*
17253 			 * In the broadcast case, there may be many zones
17254 			 * which need a copy of the packet delivered to them.
17255 			 * There is one IRE_BROADCAST per broadcast address
17256 			 * and per zone; we walk those using a helper function.
17257 			 * In addition, the sending of the packet for ire is
17258 			 * delayed until all of the other ires have been
17259 			 * processed.
17260 			 */
17261 			IRB_REFHOLD(ire->ire_bucket);
17262 			ire_zone = NULL;
17263 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17264 			    ire)) != NULL) {
17265 				mp1 = ip_copymsg(first_mp);
17266 				if (mp1 == NULL)
17267 					continue;
17268 
17269 				UPDATE_IB_PKT_COUNT(ire_zone);
17270 				ire_zone->ire_last_used_time = lbolt;
17271 				icmp_inbound(q, mp1, B_TRUE, ill,
17272 				    0, sum, mctl_present, B_TRUE,
17273 				    recv_ill, ire_zone->ire_zoneid);
17274 			}
17275 			IRB_REFRELE(ire->ire_bucket);
17276 		}
17277 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17278 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17279 		    ire->ire_zoneid);
17280 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17281 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17282 		return;
17283 	}
17284 	case IPPROTO_IGMP:
17285 		/*
17286 		 * If we are not willing to accept IGMP packets in clear,
17287 		 * then check with global policy.
17288 		 */
17289 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17290 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17291 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17292 			if (first_mp == NULL)
17293 				return;
17294 		}
17295 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17296 			freemsg(first_mp);
17297 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17298 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17299 			return;
17300 		}
17301 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17302 			/* Bad packet - discarded by igmp_input */
17303 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17304 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17305 			if (mctl_present)
17306 				freeb(first_mp);
17307 			return;
17308 		}
17309 		/*
17310 		 * igmp_input() may have returned the pulled up message.
17311 		 * So first_mp and ipha need to be reinitialized.
17312 		 */
17313 		ipha = (ipha_t *)mp->b_rptr;
17314 		if (mctl_present)
17315 			first_mp->b_cont = mp;
17316 		else
17317 			first_mp = mp;
17318 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17319 		    connf_head != NULL) {
17320 			/* No user-level listener for IGMP packets */
17321 			goto drop_pkt;
17322 		}
17323 		/* deliver to local raw users */
17324 		break;
17325 	case IPPROTO_PIM:
17326 		/*
17327 		 * If we are not willing to accept PIM packets in clear,
17328 		 * then check with global policy.
17329 		 */
17330 		if (ipst->ips_pim_accept_clear_messages == 0) {
17331 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17332 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17333 			if (first_mp == NULL)
17334 				return;
17335 		}
17336 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17337 			freemsg(first_mp);
17338 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17339 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17340 			return;
17341 		}
17342 		if (pim_input(q, mp, ill) != 0) {
17343 			/* Bad packet - discarded by pim_input */
17344 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17345 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17346 			if (mctl_present)
17347 				freeb(first_mp);
17348 			return;
17349 		}
17350 
17351 		/*
17352 		 * pim_input() may have pulled up the message so ipha needs to
17353 		 * be reinitialized.
17354 		 */
17355 		ipha = (ipha_t *)mp->b_rptr;
17356 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17357 		    connf_head != NULL) {
17358 			/* No user-level listener for PIM packets */
17359 			goto drop_pkt;
17360 		}
17361 		/* deliver to local raw users */
17362 		break;
17363 	case IPPROTO_ENCAP:
17364 		/*
17365 		 * Handle self-encapsulated packets (IP-in-IP where
17366 		 * the inner addresses == the outer addresses).
17367 		 */
17368 		hdr_length = IPH_HDR_LENGTH(ipha);
17369 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17370 		    mp->b_wptr) {
17371 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17372 			    sizeof (ipha_t) - mp->b_rptr)) {
17373 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17374 				freemsg(first_mp);
17375 				return;
17376 			}
17377 			ipha = (ipha_t *)mp->b_rptr;
17378 		}
17379 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17380 		/*
17381 		 * Check the sanity of the inner IP header.
17382 		 */
17383 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17384 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17385 			freemsg(first_mp);
17386 			return;
17387 		}
17388 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17389 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17390 			freemsg(first_mp);
17391 			return;
17392 		}
17393 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17394 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17395 			ipsec_in_t *ii;
17396 
17397 			/*
17398 			 * Self-encapsulated tunnel packet. Remove
17399 			 * the outer IP header and fanout again.
17400 			 * We also need to make sure that the inner
17401 			 * header is pulled up until options.
17402 			 */
17403 			mp->b_rptr = (uchar_t *)inner_ipha;
17404 			ipha = inner_ipha;
17405 			hdr_length = IPH_HDR_LENGTH(ipha);
17406 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17407 				if (!pullupmsg(mp, (uchar_t *)ipha +
17408 				    + hdr_length - mp->b_rptr)) {
17409 					freemsg(first_mp);
17410 					return;
17411 				}
17412 				ipha = (ipha_t *)mp->b_rptr;
17413 			}
17414 			if (!mctl_present) {
17415 				ASSERT(first_mp == mp);
17416 				/*
17417 				 * This means that somebody is sending
17418 				 * Self-encapsualted packets without AH/ESP.
17419 				 * If AH/ESP was present, we would have already
17420 				 * allocated the first_mp.
17421 				 */
17422 				first_mp = ipsec_in_alloc(B_TRUE,
17423 				    ipst->ips_netstack);
17424 				if (first_mp == NULL) {
17425 					ip1dbg(("ip_proto_input: IPSEC_IN "
17426 					    "allocation failure.\n"));
17427 					BUMP_MIB(ill->ill_ip_mib,
17428 					    ipIfStatsInDiscards);
17429 					freemsg(mp);
17430 					return;
17431 				}
17432 				first_mp->b_cont = mp;
17433 			}
17434 			/*
17435 			 * We generally store the ill_index if we need to
17436 			 * do IPsec processing as we lose the ill queue when
17437 			 * we come back. But in this case, we never should
17438 			 * have to store the ill_index here as it should have
17439 			 * been stored previously when we processed the
17440 			 * AH/ESP header in this routine or for non-ipsec
17441 			 * cases, we still have the queue. But for some bad
17442 			 * packets from the wire, we can get to IPsec after
17443 			 * this and we better store the index for that case.
17444 			 */
17445 			ill = (ill_t *)q->q_ptr;
17446 			ii = (ipsec_in_t *)first_mp->b_rptr;
17447 			ii->ipsec_in_ill_index =
17448 			    ill->ill_phyint->phyint_ifindex;
17449 			ii->ipsec_in_rill_index =
17450 			    recv_ill->ill_phyint->phyint_ifindex;
17451 			if (ii->ipsec_in_decaps) {
17452 				/*
17453 				 * This packet is self-encapsulated multiple
17454 				 * times. We don't want to recurse infinitely.
17455 				 * To keep it simple, drop the packet.
17456 				 */
17457 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17458 				freemsg(first_mp);
17459 				return;
17460 			}
17461 			ii->ipsec_in_decaps = B_TRUE;
17462 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17463 			    ire);
17464 			return;
17465 		}
17466 		break;
17467 	case IPPROTO_AH:
17468 	case IPPROTO_ESP: {
17469 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17470 
17471 		/*
17472 		 * Fast path for AH/ESP. If this is the first time
17473 		 * we are sending a datagram to AH/ESP, allocate
17474 		 * a IPSEC_IN message and prepend it. Otherwise,
17475 		 * just fanout.
17476 		 */
17477 
17478 		int ipsec_rc;
17479 		ipsec_in_t *ii;
17480 		netstack_t *ns = ipst->ips_netstack;
17481 
17482 		IP_STAT(ipst, ipsec_proto_ahesp);
17483 		if (!mctl_present) {
17484 			ASSERT(first_mp == mp);
17485 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17486 			if (first_mp == NULL) {
17487 				ip1dbg(("ip_proto_input: IPSEC_IN "
17488 				    "allocation failure.\n"));
17489 				freemsg(hada_mp); /* okay ifnull */
17490 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17491 				freemsg(mp);
17492 				return;
17493 			}
17494 			/*
17495 			 * Store the ill_index so that when we come back
17496 			 * from IPsec we ride on the same queue.
17497 			 */
17498 			ill = (ill_t *)q->q_ptr;
17499 			ii = (ipsec_in_t *)first_mp->b_rptr;
17500 			ii->ipsec_in_ill_index =
17501 			    ill->ill_phyint->phyint_ifindex;
17502 			ii->ipsec_in_rill_index =
17503 			    recv_ill->ill_phyint->phyint_ifindex;
17504 			first_mp->b_cont = mp;
17505 			/*
17506 			 * Cache hardware acceleration info.
17507 			 */
17508 			if (hada_mp != NULL) {
17509 				IPSECHW_DEBUG(IPSECHW_PKT,
17510 				    ("ip_rput_local: caching data attr.\n"));
17511 				ii->ipsec_in_accelerated = B_TRUE;
17512 				ii->ipsec_in_da = hada_mp;
17513 				hada_mp = NULL;
17514 			}
17515 		} else {
17516 			ii = (ipsec_in_t *)first_mp->b_rptr;
17517 		}
17518 
17519 		if (!ipsec_loaded(ipss)) {
17520 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17521 			    ire->ire_zoneid, ipst);
17522 			return;
17523 		}
17524 
17525 		ns = ipst->ips_netstack;
17526 		/* select inbound SA and have IPsec process the pkt */
17527 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17528 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17529 			boolean_t esp_in_udp_sa;
17530 			if (esph == NULL)
17531 				return;
17532 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17533 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17534 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17535 			    IPSA_F_NATT) != 0);
17536 			/*
17537 			 * The following is a fancy, but quick, way of saying:
17538 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17539 			 *    OR
17540 			 * ESP SA and ESP-in-UDP packet --> drop
17541 			 */
17542 			if (esp_in_udp_sa != esp_in_udp_packet) {
17543 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17544 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17545 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17546 				    &ns->netstack_ipsec->ipsec_dropper);
17547 				return;
17548 			}
17549 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17550 			    first_mp, esph);
17551 		} else {
17552 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17553 			if (ah == NULL)
17554 				return;
17555 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17556 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17557 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17558 			    first_mp, ah);
17559 		}
17560 
17561 		switch (ipsec_rc) {
17562 		case IPSEC_STATUS_SUCCESS:
17563 			break;
17564 		case IPSEC_STATUS_FAILED:
17565 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17566 			/* FALLTHRU */
17567 		case IPSEC_STATUS_PENDING:
17568 			return;
17569 		}
17570 		/* we're done with IPsec processing, send it up */
17571 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17572 		return;
17573 	}
17574 	default:
17575 		break;
17576 	}
17577 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17578 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17579 		    ire->ire_zoneid));
17580 		goto drop_pkt;
17581 	}
17582 	/*
17583 	 * Handle protocols with which IP is less intimate.  There
17584 	 * can be more than one stream bound to a particular
17585 	 * protocol.  When this is the case, each one gets a copy
17586 	 * of any incoming packets.
17587 	 */
17588 	ip_fanout_proto(q, first_mp, ill, ipha,
17589 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17590 	    B_TRUE, recv_ill, ire->ire_zoneid);
17591 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17592 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17593 	return;
17594 
17595 drop_pkt:
17596 	freemsg(first_mp);
17597 	if (hada_mp != NULL)
17598 		freeb(hada_mp);
17599 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17600 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17601 #undef	rptr
17602 #undef  iphs
17603 
17604 }
17605 
17606 /*
17607  * Update any source route, record route or timestamp options.
17608  * Check that we are at end of strict source route.
17609  * The options have already been checked for sanity in ip_rput_options().
17610  */
17611 static boolean_t
17612 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17613     ip_stack_t *ipst)
17614 {
17615 	ipoptp_t	opts;
17616 	uchar_t		*opt;
17617 	uint8_t		optval;
17618 	uint8_t		optlen;
17619 	ipaddr_t	dst;
17620 	uint32_t	ts;
17621 	ire_t		*dst_ire;
17622 	timestruc_t	now;
17623 	zoneid_t	zoneid;
17624 	ill_t		*ill;
17625 
17626 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17627 
17628 	ip2dbg(("ip_rput_local_options\n"));
17629 
17630 	for (optval = ipoptp_first(&opts, ipha);
17631 	    optval != IPOPT_EOL;
17632 	    optval = ipoptp_next(&opts)) {
17633 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17634 		opt = opts.ipoptp_cur;
17635 		optlen = opts.ipoptp_len;
17636 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17637 		    optval, optlen));
17638 		switch (optval) {
17639 			uint32_t off;
17640 		case IPOPT_SSRR:
17641 		case IPOPT_LSRR:
17642 			off = opt[IPOPT_OFFSET];
17643 			off--;
17644 			if (optlen < IP_ADDR_LEN ||
17645 			    off > optlen - IP_ADDR_LEN) {
17646 				/* End of source route */
17647 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17648 				break;
17649 			}
17650 			/*
17651 			 * This will only happen if two consecutive entries
17652 			 * in the source route contains our address or if
17653 			 * it is a packet with a loose source route which
17654 			 * reaches us before consuming the whole source route
17655 			 */
17656 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17657 			if (optval == IPOPT_SSRR) {
17658 				goto bad_src_route;
17659 			}
17660 			/*
17661 			 * Hack: instead of dropping the packet truncate the
17662 			 * source route to what has been used by filling the
17663 			 * rest with IPOPT_NOP.
17664 			 */
17665 			opt[IPOPT_OLEN] = (uint8_t)off;
17666 			while (off < optlen) {
17667 				opt[off++] = IPOPT_NOP;
17668 			}
17669 			break;
17670 		case IPOPT_RR:
17671 			off = opt[IPOPT_OFFSET];
17672 			off--;
17673 			if (optlen < IP_ADDR_LEN ||
17674 			    off > optlen - IP_ADDR_LEN) {
17675 				/* No more room - ignore */
17676 				ip1dbg((
17677 				    "ip_rput_local_options: end of RR\n"));
17678 				break;
17679 			}
17680 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17681 			    IP_ADDR_LEN);
17682 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17683 			break;
17684 		case IPOPT_TS:
17685 			/* Insert timestamp if there is romm */
17686 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17687 			case IPOPT_TS_TSONLY:
17688 				off = IPOPT_TS_TIMELEN;
17689 				break;
17690 			case IPOPT_TS_PRESPEC:
17691 			case IPOPT_TS_PRESPEC_RFC791:
17692 				/* Verify that the address matched */
17693 				off = opt[IPOPT_OFFSET] - 1;
17694 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17695 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17696 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17697 				    ipst);
17698 				if (dst_ire == NULL) {
17699 					/* Not for us */
17700 					break;
17701 				}
17702 				ire_refrele(dst_ire);
17703 				/* FALLTHRU */
17704 			case IPOPT_TS_TSANDADDR:
17705 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17706 				break;
17707 			default:
17708 				/*
17709 				 * ip_*put_options should have already
17710 				 * dropped this packet.
17711 				 */
17712 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17713 				    "unknown IT - bug in ip_rput_options?\n");
17714 				return (B_TRUE);	/* Keep "lint" happy */
17715 			}
17716 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17717 				/* Increase overflow counter */
17718 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17719 				opt[IPOPT_POS_OV_FLG] =
17720 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17721 				    (off << 4));
17722 				break;
17723 			}
17724 			off = opt[IPOPT_OFFSET] - 1;
17725 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17726 			case IPOPT_TS_PRESPEC:
17727 			case IPOPT_TS_PRESPEC_RFC791:
17728 			case IPOPT_TS_TSANDADDR:
17729 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17730 				    IP_ADDR_LEN);
17731 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17732 				/* FALLTHRU */
17733 			case IPOPT_TS_TSONLY:
17734 				off = opt[IPOPT_OFFSET] - 1;
17735 				/* Compute # of milliseconds since midnight */
17736 				gethrestime(&now);
17737 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17738 				    now.tv_nsec / (NANOSEC / MILLISEC);
17739 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17740 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17741 				break;
17742 			}
17743 			break;
17744 		}
17745 	}
17746 	return (B_TRUE);
17747 
17748 bad_src_route:
17749 	q = WR(q);
17750 	if (q->q_next != NULL)
17751 		ill = q->q_ptr;
17752 	else
17753 		ill = NULL;
17754 
17755 	/* make sure we clear any indication of a hardware checksum */
17756 	DB_CKSUMFLAGS(mp) = 0;
17757 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17758 	if (zoneid == ALL_ZONES)
17759 		freemsg(mp);
17760 	else
17761 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17762 	return (B_FALSE);
17763 
17764 }
17765 
17766 /*
17767  * Process IP options in an inbound packet.  If an option affects the
17768  * effective destination address, return the next hop address via dstp.
17769  * Returns -1 if something fails in which case an ICMP error has been sent
17770  * and mp freed.
17771  */
17772 static int
17773 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17774     ip_stack_t *ipst)
17775 {
17776 	ipoptp_t	opts;
17777 	uchar_t		*opt;
17778 	uint8_t		optval;
17779 	uint8_t		optlen;
17780 	ipaddr_t	dst;
17781 	intptr_t	code = 0;
17782 	ire_t		*ire = NULL;
17783 	zoneid_t	zoneid;
17784 	ill_t		*ill;
17785 
17786 	ip2dbg(("ip_rput_options\n"));
17787 	dst = ipha->ipha_dst;
17788 	for (optval = ipoptp_first(&opts, ipha);
17789 	    optval != IPOPT_EOL;
17790 	    optval = ipoptp_next(&opts)) {
17791 		opt = opts.ipoptp_cur;
17792 		optlen = opts.ipoptp_len;
17793 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17794 		    optval, optlen));
17795 		/*
17796 		 * Note: we need to verify the checksum before we
17797 		 * modify anything thus this routine only extracts the next
17798 		 * hop dst from any source route.
17799 		 */
17800 		switch (optval) {
17801 			uint32_t off;
17802 		case IPOPT_SSRR:
17803 		case IPOPT_LSRR:
17804 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17805 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17806 			if (ire == NULL) {
17807 				if (optval == IPOPT_SSRR) {
17808 					ip1dbg(("ip_rput_options: not next"
17809 					    " strict source route 0x%x\n",
17810 					    ntohl(dst)));
17811 					code = (char *)&ipha->ipha_dst -
17812 					    (char *)ipha;
17813 					goto param_prob; /* RouterReq's */
17814 				}
17815 				ip2dbg(("ip_rput_options: "
17816 				    "not next source route 0x%x\n",
17817 				    ntohl(dst)));
17818 				break;
17819 			}
17820 			ire_refrele(ire);
17821 
17822 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17823 				ip1dbg((
17824 				    "ip_rput_options: bad option offset\n"));
17825 				code = (char *)&opt[IPOPT_OLEN] -
17826 				    (char *)ipha;
17827 				goto param_prob;
17828 			}
17829 			off = opt[IPOPT_OFFSET];
17830 			off--;
17831 		redo_srr:
17832 			if (optlen < IP_ADDR_LEN ||
17833 			    off > optlen - IP_ADDR_LEN) {
17834 				/* End of source route */
17835 				ip1dbg(("ip_rput_options: end of SR\n"));
17836 				break;
17837 			}
17838 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17839 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17840 			    ntohl(dst)));
17841 
17842 			/*
17843 			 * Check if our address is present more than
17844 			 * once as consecutive hops in source route.
17845 			 * XXX verify per-interface ip_forwarding
17846 			 * for source route?
17847 			 */
17848 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17849 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17850 
17851 			if (ire != NULL) {
17852 				ire_refrele(ire);
17853 				off += IP_ADDR_LEN;
17854 				goto redo_srr;
17855 			}
17856 
17857 			if (dst == htonl(INADDR_LOOPBACK)) {
17858 				ip1dbg(("ip_rput_options: loopback addr in "
17859 				    "source route!\n"));
17860 				goto bad_src_route;
17861 			}
17862 			/*
17863 			 * For strict: verify that dst is directly
17864 			 * reachable.
17865 			 */
17866 			if (optval == IPOPT_SSRR) {
17867 				ire = ire_ftable_lookup(dst, 0, 0,
17868 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17869 				    MBLK_GETLABEL(mp),
17870 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17871 				if (ire == NULL) {
17872 					ip1dbg(("ip_rput_options: SSRR not "
17873 					    "directly reachable: 0x%x\n",
17874 					    ntohl(dst)));
17875 					goto bad_src_route;
17876 				}
17877 				ire_refrele(ire);
17878 			}
17879 			/*
17880 			 * Defer update of the offset and the record route
17881 			 * until the packet is forwarded.
17882 			 */
17883 			break;
17884 		case IPOPT_RR:
17885 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17886 				ip1dbg((
17887 				    "ip_rput_options: bad option offset\n"));
17888 				code = (char *)&opt[IPOPT_OLEN] -
17889 				    (char *)ipha;
17890 				goto param_prob;
17891 			}
17892 			break;
17893 		case IPOPT_TS:
17894 			/*
17895 			 * Verify that length >= 5 and that there is either
17896 			 * room for another timestamp or that the overflow
17897 			 * counter is not maxed out.
17898 			 */
17899 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17900 			if (optlen < IPOPT_MINLEN_IT) {
17901 				goto param_prob;
17902 			}
17903 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17904 				ip1dbg((
17905 				    "ip_rput_options: bad option offset\n"));
17906 				code = (char *)&opt[IPOPT_OFFSET] -
17907 				    (char *)ipha;
17908 				goto param_prob;
17909 			}
17910 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17911 			case IPOPT_TS_TSONLY:
17912 				off = IPOPT_TS_TIMELEN;
17913 				break;
17914 			case IPOPT_TS_TSANDADDR:
17915 			case IPOPT_TS_PRESPEC:
17916 			case IPOPT_TS_PRESPEC_RFC791:
17917 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17918 				break;
17919 			default:
17920 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17921 				    (char *)ipha;
17922 				goto param_prob;
17923 			}
17924 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17925 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17926 				/*
17927 				 * No room and the overflow counter is 15
17928 				 * already.
17929 				 */
17930 				goto param_prob;
17931 			}
17932 			break;
17933 		}
17934 	}
17935 
17936 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17937 		*dstp = dst;
17938 		return (0);
17939 	}
17940 
17941 	ip1dbg(("ip_rput_options: error processing IP options."));
17942 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17943 
17944 param_prob:
17945 	q = WR(q);
17946 	if (q->q_next != NULL)
17947 		ill = q->q_ptr;
17948 	else
17949 		ill = NULL;
17950 
17951 	/* make sure we clear any indication of a hardware checksum */
17952 	DB_CKSUMFLAGS(mp) = 0;
17953 	/* Don't know whether this is for non-global or global/forwarding */
17954 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17955 	if (zoneid == ALL_ZONES)
17956 		freemsg(mp);
17957 	else
17958 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17959 	return (-1);
17960 
17961 bad_src_route:
17962 	q = WR(q);
17963 	if (q->q_next != NULL)
17964 		ill = q->q_ptr;
17965 	else
17966 		ill = NULL;
17967 
17968 	/* make sure we clear any indication of a hardware checksum */
17969 	DB_CKSUMFLAGS(mp) = 0;
17970 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17971 	if (zoneid == ALL_ZONES)
17972 		freemsg(mp);
17973 	else
17974 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17975 	return (-1);
17976 }
17977 
17978 /*
17979  * IP & ICMP info in >=14 msg's ...
17980  *  - ip fixed part (mib2_ip_t)
17981  *  - icmp fixed part (mib2_icmp_t)
17982  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17983  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17984  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17985  *  - ipRouteAttributeTable (ip 102)	labeled routes
17986  *  - ip multicast membership (ip_member_t)
17987  *  - ip multicast source filtering (ip_grpsrc_t)
17988  *  - igmp fixed part (struct igmpstat)
17989  *  - multicast routing stats (struct mrtstat)
17990  *  - multicast routing vifs (array of struct vifctl)
17991  *  - multicast routing routes (array of struct mfcctl)
17992  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17993  *					One per ill plus one generic
17994  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17995  *					One per ill plus one generic
17996  *  - ipv6RouteEntry			all IPv6 IREs
17997  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17998  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17999  *  - ipv6AddrEntry			all IPv6 ipifs
18000  *  - ipv6 multicast membership (ipv6_member_t)
18001  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18002  *
18003  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18004  *
18005  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18006  * already filled in by the caller.
18007  * Return value of 0 indicates that no messages were sent and caller
18008  * should free mpctl.
18009  */
18010 int
18011 ip_snmp_get(queue_t *q, mblk_t *mpctl)
18012 {
18013 	ip_stack_t *ipst;
18014 	sctp_stack_t *sctps;
18015 
18016 
18017 	if (q->q_next != NULL) {
18018 		ipst = ILLQ_TO_IPST(q);
18019 	} else {
18020 		ipst = CONNQ_TO_IPST(q);
18021 	}
18022 	ASSERT(ipst != NULL);
18023 	sctps = ipst->ips_netstack->netstack_sctp;
18024 
18025 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18026 		return (0);
18027 	}
18028 
18029 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18030 	    ipst)) == NULL) {
18031 		return (1);
18032 	}
18033 
18034 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18035 		return (1);
18036 	}
18037 
18038 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18039 		return (1);
18040 	}
18041 
18042 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18043 		return (1);
18044 	}
18045 
18046 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18047 		return (1);
18048 	}
18049 
18050 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18051 		return (1);
18052 	}
18053 
18054 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18055 		return (1);
18056 	}
18057 
18058 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18059 		return (1);
18060 	}
18061 
18062 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18063 		return (1);
18064 	}
18065 
18066 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18067 		return (1);
18068 	}
18069 
18070 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18071 		return (1);
18072 	}
18073 
18074 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18075 		return (1);
18076 	}
18077 
18078 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18079 		return (1);
18080 	}
18081 
18082 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18083 		return (1);
18084 	}
18085 
18086 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18087 		return (1);
18088 	}
18089 
18090 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18091 	if (mpctl == NULL) {
18092 		return (1);
18093 	}
18094 
18095 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18096 		return (1);
18097 	}
18098 	freemsg(mpctl);
18099 	return (1);
18100 }
18101 
18102 
18103 /* Get global (legacy) IPv4 statistics */
18104 static mblk_t *
18105 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18106     ip_stack_t *ipst)
18107 {
18108 	mib2_ip_t		old_ip_mib;
18109 	struct opthdr		*optp;
18110 	mblk_t			*mp2ctl;
18111 
18112 	/*
18113 	 * make a copy of the original message
18114 	 */
18115 	mp2ctl = copymsg(mpctl);
18116 
18117 	/* fixed length IP structure... */
18118 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18119 	optp->level = MIB2_IP;
18120 	optp->name = 0;
18121 	SET_MIB(old_ip_mib.ipForwarding,
18122 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18123 	SET_MIB(old_ip_mib.ipDefaultTTL,
18124 	    (uint32_t)ipst->ips_ip_def_ttl);
18125 	SET_MIB(old_ip_mib.ipReasmTimeout,
18126 	    ipst->ips_ip_g_frag_timeout);
18127 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18128 	    sizeof (mib2_ipAddrEntry_t));
18129 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18130 	    sizeof (mib2_ipRouteEntry_t));
18131 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18132 	    sizeof (mib2_ipNetToMediaEntry_t));
18133 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18134 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18135 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18136 	    sizeof (mib2_ipAttributeEntry_t));
18137 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18138 
18139 	/*
18140 	 * Grab the statistics from the new IP MIB
18141 	 */
18142 	SET_MIB(old_ip_mib.ipInReceives,
18143 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18144 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18145 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18146 	SET_MIB(old_ip_mib.ipForwDatagrams,
18147 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18148 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18149 	    ipmib->ipIfStatsInUnknownProtos);
18150 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18151 	SET_MIB(old_ip_mib.ipInDelivers,
18152 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18153 	SET_MIB(old_ip_mib.ipOutRequests,
18154 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18155 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18156 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18157 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18158 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18159 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18160 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18161 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18162 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18163 
18164 	/* ipRoutingDiscards is not being used */
18165 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18166 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18167 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18168 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18169 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18170 	    ipmib->ipIfStatsReasmDuplicates);
18171 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18172 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18173 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18174 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18175 	SET_MIB(old_ip_mib.rawipInOverflows,
18176 	    ipmib->rawipIfStatsInOverflows);
18177 
18178 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18179 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18180 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18181 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18182 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18183 	    ipmib->ipIfStatsOutSwitchIPVersion);
18184 
18185 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18186 	    (int)sizeof (old_ip_mib))) {
18187 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18188 		    (uint_t)sizeof (old_ip_mib)));
18189 	}
18190 
18191 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18192 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18193 	    (int)optp->level, (int)optp->name, (int)optp->len));
18194 	qreply(q, mpctl);
18195 	return (mp2ctl);
18196 }
18197 
18198 /* Per interface IPv4 statistics */
18199 static mblk_t *
18200 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18201 {
18202 	struct opthdr		*optp;
18203 	mblk_t			*mp2ctl;
18204 	ill_t			*ill;
18205 	ill_walk_context_t	ctx;
18206 	mblk_t			*mp_tail = NULL;
18207 	mib2_ipIfStatsEntry_t	global_ip_mib;
18208 
18209 	/*
18210 	 * Make a copy of the original message
18211 	 */
18212 	mp2ctl = copymsg(mpctl);
18213 
18214 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18215 	optp->level = MIB2_IP;
18216 	optp->name = MIB2_IP_TRAFFIC_STATS;
18217 	/* Include "unknown interface" ip_mib */
18218 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18219 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18220 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18221 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18222 	    (ipst->ips_ip_g_forward ? 1 : 2));
18223 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18224 	    (uint32_t)ipst->ips_ip_def_ttl);
18225 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18226 	    sizeof (mib2_ipIfStatsEntry_t));
18227 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18228 	    sizeof (mib2_ipAddrEntry_t));
18229 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18230 	    sizeof (mib2_ipRouteEntry_t));
18231 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18232 	    sizeof (mib2_ipNetToMediaEntry_t));
18233 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18234 	    sizeof (ip_member_t));
18235 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18236 	    sizeof (ip_grpsrc_t));
18237 
18238 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18239 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18240 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18241 		    "failed to allocate %u bytes\n",
18242 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18243 	}
18244 
18245 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18246 
18247 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18248 	ill = ILL_START_WALK_V4(&ctx, ipst);
18249 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18250 		ill->ill_ip_mib->ipIfStatsIfIndex =
18251 		    ill->ill_phyint->phyint_ifindex;
18252 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18253 		    (ipst->ips_ip_g_forward ? 1 : 2));
18254 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18255 		    (uint32_t)ipst->ips_ip_def_ttl);
18256 
18257 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18258 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18259 		    (char *)ill->ill_ip_mib,
18260 		    (int)sizeof (*ill->ill_ip_mib))) {
18261 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18262 			    "failed to allocate %u bytes\n",
18263 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18264 		}
18265 	}
18266 	rw_exit(&ipst->ips_ill_g_lock);
18267 
18268 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18269 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18270 	    "level %d, name %d, len %d\n",
18271 	    (int)optp->level, (int)optp->name, (int)optp->len));
18272 	qreply(q, mpctl);
18273 
18274 	if (mp2ctl == NULL)
18275 		return (NULL);
18276 
18277 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18278 }
18279 
18280 /* Global IPv4 ICMP statistics */
18281 static mblk_t *
18282 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18283 {
18284 	struct opthdr		*optp;
18285 	mblk_t			*mp2ctl;
18286 
18287 	/*
18288 	 * Make a copy of the original message
18289 	 */
18290 	mp2ctl = copymsg(mpctl);
18291 
18292 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18293 	optp->level = MIB2_ICMP;
18294 	optp->name = 0;
18295 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18296 	    (int)sizeof (ipst->ips_icmp_mib))) {
18297 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18298 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18299 	}
18300 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18301 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18302 	    (int)optp->level, (int)optp->name, (int)optp->len));
18303 	qreply(q, mpctl);
18304 	return (mp2ctl);
18305 }
18306 
18307 /* Global IPv4 IGMP statistics */
18308 static mblk_t *
18309 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18310 {
18311 	struct opthdr		*optp;
18312 	mblk_t			*mp2ctl;
18313 
18314 	/*
18315 	 * make a copy of the original message
18316 	 */
18317 	mp2ctl = copymsg(mpctl);
18318 
18319 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18320 	optp->level = EXPER_IGMP;
18321 	optp->name = 0;
18322 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18323 	    (int)sizeof (ipst->ips_igmpstat))) {
18324 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18325 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18326 	}
18327 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18328 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18329 	    (int)optp->level, (int)optp->name, (int)optp->len));
18330 	qreply(q, mpctl);
18331 	return (mp2ctl);
18332 }
18333 
18334 /* Global IPv4 Multicast Routing statistics */
18335 static mblk_t *
18336 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18337 {
18338 	struct opthdr		*optp;
18339 	mblk_t			*mp2ctl;
18340 
18341 	/*
18342 	 * make a copy of the original message
18343 	 */
18344 	mp2ctl = copymsg(mpctl);
18345 
18346 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18347 	optp->level = EXPER_DVMRP;
18348 	optp->name = 0;
18349 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18350 		ip0dbg(("ip_mroute_stats: failed\n"));
18351 	}
18352 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18353 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18354 	    (int)optp->level, (int)optp->name, (int)optp->len));
18355 	qreply(q, mpctl);
18356 	return (mp2ctl);
18357 }
18358 
18359 /* IPv4 address information */
18360 static mblk_t *
18361 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18362 {
18363 	struct opthdr		*optp;
18364 	mblk_t			*mp2ctl;
18365 	mblk_t			*mp_tail = NULL;
18366 	ill_t			*ill;
18367 	ipif_t			*ipif;
18368 	uint_t			bitval;
18369 	mib2_ipAddrEntry_t	mae;
18370 	zoneid_t		zoneid;
18371 	ill_walk_context_t ctx;
18372 
18373 	/*
18374 	 * make a copy of the original message
18375 	 */
18376 	mp2ctl = copymsg(mpctl);
18377 
18378 	/* ipAddrEntryTable */
18379 
18380 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18381 	optp->level = MIB2_IP;
18382 	optp->name = MIB2_IP_ADDR;
18383 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18384 
18385 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18386 	ill = ILL_START_WALK_V4(&ctx, ipst);
18387 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18388 		for (ipif = ill->ill_ipif; ipif != NULL;
18389 		    ipif = ipif->ipif_next) {
18390 			if (ipif->ipif_zoneid != zoneid &&
18391 			    ipif->ipif_zoneid != ALL_ZONES)
18392 				continue;
18393 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18394 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18395 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18396 
18397 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18398 			    OCTET_LENGTH);
18399 			mae.ipAdEntIfIndex.o_length =
18400 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18401 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18402 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18403 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18404 			mae.ipAdEntInfo.ae_subnet_len =
18405 			    ip_mask_to_plen(ipif->ipif_net_mask);
18406 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18407 			for (bitval = 1;
18408 			    bitval &&
18409 			    !(bitval & ipif->ipif_brd_addr);
18410 			    bitval <<= 1)
18411 				noop;
18412 			mae.ipAdEntBcastAddr = bitval;
18413 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18414 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18415 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18416 			mae.ipAdEntInfo.ae_broadcast_addr =
18417 			    ipif->ipif_brd_addr;
18418 			mae.ipAdEntInfo.ae_pp_dst_addr =
18419 			    ipif->ipif_pp_dst_addr;
18420 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18421 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18422 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18423 
18424 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18425 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18426 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18427 				    "allocate %u bytes\n",
18428 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18429 			}
18430 		}
18431 	}
18432 	rw_exit(&ipst->ips_ill_g_lock);
18433 
18434 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18435 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18436 	    (int)optp->level, (int)optp->name, (int)optp->len));
18437 	qreply(q, mpctl);
18438 	return (mp2ctl);
18439 }
18440 
18441 /* IPv6 address information */
18442 static mblk_t *
18443 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18444 {
18445 	struct opthdr		*optp;
18446 	mblk_t			*mp2ctl;
18447 	mblk_t			*mp_tail = NULL;
18448 	ill_t			*ill;
18449 	ipif_t			*ipif;
18450 	mib2_ipv6AddrEntry_t	mae6;
18451 	zoneid_t		zoneid;
18452 	ill_walk_context_t	ctx;
18453 
18454 	/*
18455 	 * make a copy of the original message
18456 	 */
18457 	mp2ctl = copymsg(mpctl);
18458 
18459 	/* ipv6AddrEntryTable */
18460 
18461 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18462 	optp->level = MIB2_IP6;
18463 	optp->name = MIB2_IP6_ADDR;
18464 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18465 
18466 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18467 	ill = ILL_START_WALK_V6(&ctx, ipst);
18468 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18469 		for (ipif = ill->ill_ipif; ipif != NULL;
18470 		    ipif = ipif->ipif_next) {
18471 			if (ipif->ipif_zoneid != zoneid &&
18472 			    ipif->ipif_zoneid != ALL_ZONES)
18473 				continue;
18474 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18475 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18476 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18477 
18478 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18479 			    OCTET_LENGTH);
18480 			mae6.ipv6AddrIfIndex.o_length =
18481 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18482 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18483 			mae6.ipv6AddrPfxLength =
18484 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18485 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18486 			mae6.ipv6AddrInfo.ae_subnet_len =
18487 			    mae6.ipv6AddrPfxLength;
18488 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18489 
18490 			/* Type: stateless(1), stateful(2), unknown(3) */
18491 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18492 				mae6.ipv6AddrType = 1;
18493 			else
18494 				mae6.ipv6AddrType = 2;
18495 			/* Anycast: true(1), false(2) */
18496 			if (ipif->ipif_flags & IPIF_ANYCAST)
18497 				mae6.ipv6AddrAnycastFlag = 1;
18498 			else
18499 				mae6.ipv6AddrAnycastFlag = 2;
18500 
18501 			/*
18502 			 * Address status: preferred(1), deprecated(2),
18503 			 * invalid(3), inaccessible(4), unknown(5)
18504 			 */
18505 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18506 				mae6.ipv6AddrStatus = 3;
18507 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18508 				mae6.ipv6AddrStatus = 2;
18509 			else
18510 				mae6.ipv6AddrStatus = 1;
18511 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18512 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18513 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18514 			    ipif->ipif_v6pp_dst_addr;
18515 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18516 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18517 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18518 			mae6.ipv6AddrIdentifier = ill->ill_token;
18519 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18520 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18521 			mae6.ipv6AddrRetransmitTime =
18522 			    ill->ill_reachable_retrans_time;
18523 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18524 			    (char *)&mae6,
18525 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18526 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18527 				    "allocate %u bytes\n",
18528 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18529 			}
18530 		}
18531 	}
18532 	rw_exit(&ipst->ips_ill_g_lock);
18533 
18534 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18535 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18536 	    (int)optp->level, (int)optp->name, (int)optp->len));
18537 	qreply(q, mpctl);
18538 	return (mp2ctl);
18539 }
18540 
18541 /* IPv4 multicast group membership. */
18542 static mblk_t *
18543 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18544 {
18545 	struct opthdr		*optp;
18546 	mblk_t			*mp2ctl;
18547 	ill_t			*ill;
18548 	ipif_t			*ipif;
18549 	ilm_t			*ilm;
18550 	ip_member_t		ipm;
18551 	mblk_t			*mp_tail = NULL;
18552 	ill_walk_context_t	ctx;
18553 	zoneid_t		zoneid;
18554 
18555 	/*
18556 	 * make a copy of the original message
18557 	 */
18558 	mp2ctl = copymsg(mpctl);
18559 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18560 
18561 	/* ipGroupMember table */
18562 	optp = (struct opthdr *)&mpctl->b_rptr[
18563 	    sizeof (struct T_optmgmt_ack)];
18564 	optp->level = MIB2_IP;
18565 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18566 
18567 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18568 	ill = ILL_START_WALK_V4(&ctx, ipst);
18569 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18570 		ILM_WALKER_HOLD(ill);
18571 		for (ipif = ill->ill_ipif; ipif != NULL;
18572 		    ipif = ipif->ipif_next) {
18573 			if (ipif->ipif_zoneid != zoneid &&
18574 			    ipif->ipif_zoneid != ALL_ZONES)
18575 				continue;	/* not this zone */
18576 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18577 			    OCTET_LENGTH);
18578 			ipm.ipGroupMemberIfIndex.o_length =
18579 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18580 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18581 				ASSERT(ilm->ilm_ipif != NULL);
18582 				ASSERT(ilm->ilm_ill == NULL);
18583 				if (ilm->ilm_ipif != ipif)
18584 					continue;
18585 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18586 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18587 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18588 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18589 				    (char *)&ipm, (int)sizeof (ipm))) {
18590 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18591 					    "failed to allocate %u bytes\n",
18592 					    (uint_t)sizeof (ipm)));
18593 				}
18594 			}
18595 		}
18596 		ILM_WALKER_RELE(ill);
18597 	}
18598 	rw_exit(&ipst->ips_ill_g_lock);
18599 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18600 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18601 	    (int)optp->level, (int)optp->name, (int)optp->len));
18602 	qreply(q, mpctl);
18603 	return (mp2ctl);
18604 }
18605 
18606 /* IPv6 multicast group membership. */
18607 static mblk_t *
18608 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18609 {
18610 	struct opthdr		*optp;
18611 	mblk_t			*mp2ctl;
18612 	ill_t			*ill;
18613 	ilm_t			*ilm;
18614 	ipv6_member_t		ipm6;
18615 	mblk_t			*mp_tail = NULL;
18616 	ill_walk_context_t	ctx;
18617 	zoneid_t		zoneid;
18618 
18619 	/*
18620 	 * make a copy of the original message
18621 	 */
18622 	mp2ctl = copymsg(mpctl);
18623 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18624 
18625 	/* ip6GroupMember table */
18626 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18627 	optp->level = MIB2_IP6;
18628 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18629 
18630 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18631 	ill = ILL_START_WALK_V6(&ctx, ipst);
18632 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18633 		ILM_WALKER_HOLD(ill);
18634 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18635 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18636 			ASSERT(ilm->ilm_ipif == NULL);
18637 			ASSERT(ilm->ilm_ill != NULL);
18638 			if (ilm->ilm_zoneid != zoneid)
18639 				continue;	/* not this zone */
18640 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18641 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18642 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18643 			if (!snmp_append_data2(mpctl->b_cont,
18644 			    &mp_tail,
18645 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18646 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18647 				    "failed to allocate %u bytes\n",
18648 				    (uint_t)sizeof (ipm6)));
18649 			}
18650 		}
18651 		ILM_WALKER_RELE(ill);
18652 	}
18653 	rw_exit(&ipst->ips_ill_g_lock);
18654 
18655 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18656 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18657 	    (int)optp->level, (int)optp->name, (int)optp->len));
18658 	qreply(q, mpctl);
18659 	return (mp2ctl);
18660 }
18661 
18662 /* IP multicast filtered sources */
18663 static mblk_t *
18664 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18665 {
18666 	struct opthdr		*optp;
18667 	mblk_t			*mp2ctl;
18668 	ill_t			*ill;
18669 	ipif_t			*ipif;
18670 	ilm_t			*ilm;
18671 	ip_grpsrc_t		ips;
18672 	mblk_t			*mp_tail = NULL;
18673 	ill_walk_context_t	ctx;
18674 	zoneid_t		zoneid;
18675 	int			i;
18676 	slist_t			*sl;
18677 
18678 	/*
18679 	 * make a copy of the original message
18680 	 */
18681 	mp2ctl = copymsg(mpctl);
18682 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18683 
18684 	/* ipGroupSource table */
18685 	optp = (struct opthdr *)&mpctl->b_rptr[
18686 	    sizeof (struct T_optmgmt_ack)];
18687 	optp->level = MIB2_IP;
18688 	optp->name = EXPER_IP_GROUP_SOURCES;
18689 
18690 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18691 	ill = ILL_START_WALK_V4(&ctx, ipst);
18692 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18693 		ILM_WALKER_HOLD(ill);
18694 		for (ipif = ill->ill_ipif; ipif != NULL;
18695 		    ipif = ipif->ipif_next) {
18696 			if (ipif->ipif_zoneid != zoneid)
18697 				continue;	/* not this zone */
18698 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18699 			    OCTET_LENGTH);
18700 			ips.ipGroupSourceIfIndex.o_length =
18701 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18702 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18703 				ASSERT(ilm->ilm_ipif != NULL);
18704 				ASSERT(ilm->ilm_ill == NULL);
18705 				sl = ilm->ilm_filter;
18706 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18707 					continue;
18708 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18709 				for (i = 0; i < sl->sl_numsrc; i++) {
18710 					if (!IN6_IS_ADDR_V4MAPPED(
18711 					    &sl->sl_addr[i]))
18712 						continue;
18713 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18714 					    ips.ipGroupSourceAddress);
18715 					if (snmp_append_data2(mpctl->b_cont,
18716 					    &mp_tail, (char *)&ips,
18717 					    (int)sizeof (ips)) == 0) {
18718 						ip1dbg(("ip_snmp_get_mib2_"
18719 						    "ip_group_src: failed to "
18720 						    "allocate %u bytes\n",
18721 						    (uint_t)sizeof (ips)));
18722 					}
18723 				}
18724 			}
18725 		}
18726 		ILM_WALKER_RELE(ill);
18727 	}
18728 	rw_exit(&ipst->ips_ill_g_lock);
18729 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18730 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18731 	    (int)optp->level, (int)optp->name, (int)optp->len));
18732 	qreply(q, mpctl);
18733 	return (mp2ctl);
18734 }
18735 
18736 /* IPv6 multicast filtered sources. */
18737 static mblk_t *
18738 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18739 {
18740 	struct opthdr		*optp;
18741 	mblk_t			*mp2ctl;
18742 	ill_t			*ill;
18743 	ilm_t			*ilm;
18744 	ipv6_grpsrc_t		ips6;
18745 	mblk_t			*mp_tail = NULL;
18746 	ill_walk_context_t	ctx;
18747 	zoneid_t		zoneid;
18748 	int			i;
18749 	slist_t			*sl;
18750 
18751 	/*
18752 	 * make a copy of the original message
18753 	 */
18754 	mp2ctl = copymsg(mpctl);
18755 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18756 
18757 	/* ip6GroupMember table */
18758 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18759 	optp->level = MIB2_IP6;
18760 	optp->name = EXPER_IP6_GROUP_SOURCES;
18761 
18762 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18763 	ill = ILL_START_WALK_V6(&ctx, ipst);
18764 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18765 		ILM_WALKER_HOLD(ill);
18766 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18767 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18768 			ASSERT(ilm->ilm_ipif == NULL);
18769 			ASSERT(ilm->ilm_ill != NULL);
18770 			sl = ilm->ilm_filter;
18771 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18772 				continue;
18773 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18774 			for (i = 0; i < sl->sl_numsrc; i++) {
18775 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18776 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18777 				    (char *)&ips6, (int)sizeof (ips6))) {
18778 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18779 					    "group_src: failed to allocate "
18780 					    "%u bytes\n",
18781 					    (uint_t)sizeof (ips6)));
18782 				}
18783 			}
18784 		}
18785 		ILM_WALKER_RELE(ill);
18786 	}
18787 	rw_exit(&ipst->ips_ill_g_lock);
18788 
18789 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18790 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18791 	    (int)optp->level, (int)optp->name, (int)optp->len));
18792 	qreply(q, mpctl);
18793 	return (mp2ctl);
18794 }
18795 
18796 /* Multicast routing virtual interface table. */
18797 static mblk_t *
18798 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18799 {
18800 	struct opthdr		*optp;
18801 	mblk_t			*mp2ctl;
18802 
18803 	/*
18804 	 * make a copy of the original message
18805 	 */
18806 	mp2ctl = copymsg(mpctl);
18807 
18808 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18809 	optp->level = EXPER_DVMRP;
18810 	optp->name = EXPER_DVMRP_VIF;
18811 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18812 		ip0dbg(("ip_mroute_vif: failed\n"));
18813 	}
18814 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18815 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18816 	    (int)optp->level, (int)optp->name, (int)optp->len));
18817 	qreply(q, mpctl);
18818 	return (mp2ctl);
18819 }
18820 
18821 /* Multicast routing table. */
18822 static mblk_t *
18823 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18824 {
18825 	struct opthdr		*optp;
18826 	mblk_t			*mp2ctl;
18827 
18828 	/*
18829 	 * make a copy of the original message
18830 	 */
18831 	mp2ctl = copymsg(mpctl);
18832 
18833 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18834 	optp->level = EXPER_DVMRP;
18835 	optp->name = EXPER_DVMRP_MRT;
18836 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18837 		ip0dbg(("ip_mroute_mrt: failed\n"));
18838 	}
18839 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18840 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18841 	    (int)optp->level, (int)optp->name, (int)optp->len));
18842 	qreply(q, mpctl);
18843 	return (mp2ctl);
18844 }
18845 
18846 /*
18847  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18848  * in one IRE walk.
18849  */
18850 static mblk_t *
18851 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18852 {
18853 	struct opthdr	*optp;
18854 	mblk_t		*mp2ctl;	/* Returned */
18855 	mblk_t		*mp3ctl;	/* nettomedia */
18856 	mblk_t		*mp4ctl;	/* routeattrs */
18857 	iproutedata_t	ird;
18858 	zoneid_t	zoneid;
18859 
18860 	/*
18861 	 * make copies of the original message
18862 	 *	- mp2ctl is returned unchanged to the caller for his use
18863 	 *	- mpctl is sent upstream as ipRouteEntryTable
18864 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18865 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18866 	 */
18867 	mp2ctl = copymsg(mpctl);
18868 	mp3ctl = copymsg(mpctl);
18869 	mp4ctl = copymsg(mpctl);
18870 	if (mp3ctl == NULL || mp4ctl == NULL) {
18871 		freemsg(mp4ctl);
18872 		freemsg(mp3ctl);
18873 		freemsg(mp2ctl);
18874 		freemsg(mpctl);
18875 		return (NULL);
18876 	}
18877 
18878 	bzero(&ird, sizeof (ird));
18879 
18880 	ird.ird_route.lp_head = mpctl->b_cont;
18881 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18882 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18883 
18884 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18885 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18886 
18887 	/* ipRouteEntryTable in mpctl */
18888 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18889 	optp->level = MIB2_IP;
18890 	optp->name = MIB2_IP_ROUTE;
18891 	optp->len = msgdsize(ird.ird_route.lp_head);
18892 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18893 	    (int)optp->level, (int)optp->name, (int)optp->len));
18894 	qreply(q, mpctl);
18895 
18896 	/* ipNetToMediaEntryTable in mp3ctl */
18897 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18898 	optp->level = MIB2_IP;
18899 	optp->name = MIB2_IP_MEDIA;
18900 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18901 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18902 	    (int)optp->level, (int)optp->name, (int)optp->len));
18903 	qreply(q, mp3ctl);
18904 
18905 	/* ipRouteAttributeTable in mp4ctl */
18906 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18907 	optp->level = MIB2_IP;
18908 	optp->name = EXPER_IP_RTATTR;
18909 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18910 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18911 	    (int)optp->level, (int)optp->name, (int)optp->len));
18912 	if (optp->len == 0)
18913 		freemsg(mp4ctl);
18914 	else
18915 		qreply(q, mp4ctl);
18916 
18917 	return (mp2ctl);
18918 }
18919 
18920 /*
18921  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18922  * ipv6NetToMediaEntryTable in an NDP walk.
18923  */
18924 static mblk_t *
18925 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18926 {
18927 	struct opthdr	*optp;
18928 	mblk_t		*mp2ctl;	/* Returned */
18929 	mblk_t		*mp3ctl;	/* nettomedia */
18930 	mblk_t		*mp4ctl;	/* routeattrs */
18931 	iproutedata_t	ird;
18932 	zoneid_t	zoneid;
18933 
18934 	/*
18935 	 * make copies of the original message
18936 	 *	- mp2ctl is returned unchanged to the caller for his use
18937 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18938 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18939 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18940 	 */
18941 	mp2ctl = copymsg(mpctl);
18942 	mp3ctl = copymsg(mpctl);
18943 	mp4ctl = copymsg(mpctl);
18944 	if (mp3ctl == NULL || mp4ctl == NULL) {
18945 		freemsg(mp4ctl);
18946 		freemsg(mp3ctl);
18947 		freemsg(mp2ctl);
18948 		freemsg(mpctl);
18949 		return (NULL);
18950 	}
18951 
18952 	bzero(&ird, sizeof (ird));
18953 
18954 	ird.ird_route.lp_head = mpctl->b_cont;
18955 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18956 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18957 
18958 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18959 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18960 
18961 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18962 	optp->level = MIB2_IP6;
18963 	optp->name = MIB2_IP6_ROUTE;
18964 	optp->len = msgdsize(ird.ird_route.lp_head);
18965 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18966 	    (int)optp->level, (int)optp->name, (int)optp->len));
18967 	qreply(q, mpctl);
18968 
18969 	/* ipv6NetToMediaEntryTable in mp3ctl */
18970 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18971 
18972 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18973 	optp->level = MIB2_IP6;
18974 	optp->name = MIB2_IP6_MEDIA;
18975 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18976 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18977 	    (int)optp->level, (int)optp->name, (int)optp->len));
18978 	qreply(q, mp3ctl);
18979 
18980 	/* ipv6RouteAttributeTable in mp4ctl */
18981 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18982 	optp->level = MIB2_IP6;
18983 	optp->name = EXPER_IP_RTATTR;
18984 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18985 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18986 	    (int)optp->level, (int)optp->name, (int)optp->len));
18987 	if (optp->len == 0)
18988 		freemsg(mp4ctl);
18989 	else
18990 		qreply(q, mp4ctl);
18991 
18992 	return (mp2ctl);
18993 }
18994 
18995 /*
18996  * IPv6 mib: One per ill
18997  */
18998 static mblk_t *
18999 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19000 {
19001 	struct opthdr		*optp;
19002 	mblk_t			*mp2ctl;
19003 	ill_t			*ill;
19004 	ill_walk_context_t	ctx;
19005 	mblk_t			*mp_tail = NULL;
19006 
19007 	/*
19008 	 * Make a copy of the original message
19009 	 */
19010 	mp2ctl = copymsg(mpctl);
19011 
19012 	/* fixed length IPv6 structure ... */
19013 
19014 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19015 	optp->level = MIB2_IP6;
19016 	optp->name = 0;
19017 	/* Include "unknown interface" ip6_mib */
19018 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19019 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19020 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19021 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19022 	    ipst->ips_ipv6_forward ? 1 : 2);
19023 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19024 	    ipst->ips_ipv6_def_hops);
19025 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19026 	    sizeof (mib2_ipIfStatsEntry_t));
19027 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19028 	    sizeof (mib2_ipv6AddrEntry_t));
19029 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19030 	    sizeof (mib2_ipv6RouteEntry_t));
19031 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19032 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19033 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19034 	    sizeof (ipv6_member_t));
19035 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19036 	    sizeof (ipv6_grpsrc_t));
19037 
19038 	/*
19039 	 * Synchronize 64- and 32-bit counters
19040 	 */
19041 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19042 	    ipIfStatsHCInReceives);
19043 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19044 	    ipIfStatsHCInDelivers);
19045 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19046 	    ipIfStatsHCOutRequests);
19047 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19048 	    ipIfStatsHCOutForwDatagrams);
19049 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19050 	    ipIfStatsHCOutMcastPkts);
19051 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19052 	    ipIfStatsHCInMcastPkts);
19053 
19054 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19055 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19056 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19057 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19058 	}
19059 
19060 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19061 	ill = ILL_START_WALK_V6(&ctx, ipst);
19062 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19063 		ill->ill_ip_mib->ipIfStatsIfIndex =
19064 		    ill->ill_phyint->phyint_ifindex;
19065 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19066 		    ipst->ips_ipv6_forward ? 1 : 2);
19067 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19068 		    ill->ill_max_hops);
19069 
19070 		/*
19071 		 * Synchronize 64- and 32-bit counters
19072 		 */
19073 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19074 		    ipIfStatsHCInReceives);
19075 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19076 		    ipIfStatsHCInDelivers);
19077 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19078 		    ipIfStatsHCOutRequests);
19079 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19080 		    ipIfStatsHCOutForwDatagrams);
19081 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19082 		    ipIfStatsHCOutMcastPkts);
19083 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19084 		    ipIfStatsHCInMcastPkts);
19085 
19086 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19087 		    (char *)ill->ill_ip_mib,
19088 		    (int)sizeof (*ill->ill_ip_mib))) {
19089 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19090 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19091 		}
19092 	}
19093 	rw_exit(&ipst->ips_ill_g_lock);
19094 
19095 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19096 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19097 	    (int)optp->level, (int)optp->name, (int)optp->len));
19098 	qreply(q, mpctl);
19099 	return (mp2ctl);
19100 }
19101 
19102 /*
19103  * ICMPv6 mib: One per ill
19104  */
19105 static mblk_t *
19106 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19107 {
19108 	struct opthdr		*optp;
19109 	mblk_t			*mp2ctl;
19110 	ill_t			*ill;
19111 	ill_walk_context_t	ctx;
19112 	mblk_t			*mp_tail = NULL;
19113 	/*
19114 	 * Make a copy of the original message
19115 	 */
19116 	mp2ctl = copymsg(mpctl);
19117 
19118 	/* fixed length ICMPv6 structure ... */
19119 
19120 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19121 	optp->level = MIB2_ICMP6;
19122 	optp->name = 0;
19123 	/* Include "unknown interface" icmp6_mib */
19124 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19125 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19126 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19127 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19128 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19129 	    (char *)&ipst->ips_icmp6_mib,
19130 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19131 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19132 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19133 	}
19134 
19135 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19136 	ill = ILL_START_WALK_V6(&ctx, ipst);
19137 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19138 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19139 		    ill->ill_phyint->phyint_ifindex;
19140 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19141 		    (char *)ill->ill_icmp6_mib,
19142 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19143 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19144 			    "%u bytes\n",
19145 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19146 		}
19147 	}
19148 	rw_exit(&ipst->ips_ill_g_lock);
19149 
19150 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19151 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19152 	    (int)optp->level, (int)optp->name, (int)optp->len));
19153 	qreply(q, mpctl);
19154 	return (mp2ctl);
19155 }
19156 
19157 /*
19158  * ire_walk routine to create both ipRouteEntryTable and
19159  * ipRouteAttributeTable in one IRE walk
19160  */
19161 static void
19162 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19163 {
19164 	ill_t				*ill;
19165 	ipif_t				*ipif;
19166 	mib2_ipRouteEntry_t		*re;
19167 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19168 	ipaddr_t			gw_addr;
19169 	tsol_ire_gw_secattr_t		*attrp;
19170 	tsol_gc_t			*gc = NULL;
19171 	tsol_gcgrp_t			*gcgrp = NULL;
19172 	uint_t				sacnt = 0;
19173 	int				i;
19174 
19175 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19176 
19177 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19178 		return;
19179 
19180 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19181 		mutex_enter(&attrp->igsa_lock);
19182 		if ((gc = attrp->igsa_gc) != NULL) {
19183 			gcgrp = gc->gc_grp;
19184 			ASSERT(gcgrp != NULL);
19185 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19186 			sacnt = 1;
19187 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19188 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19189 			gc = gcgrp->gcgrp_head;
19190 			sacnt = gcgrp->gcgrp_count;
19191 		}
19192 		mutex_exit(&attrp->igsa_lock);
19193 
19194 		/* do nothing if there's no gc to report */
19195 		if (gc == NULL) {
19196 			ASSERT(sacnt == 0);
19197 			if (gcgrp != NULL) {
19198 				/* we might as well drop the lock now */
19199 				rw_exit(&gcgrp->gcgrp_rwlock);
19200 				gcgrp = NULL;
19201 			}
19202 			attrp = NULL;
19203 		}
19204 
19205 		ASSERT(gc == NULL || (gcgrp != NULL &&
19206 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19207 	}
19208 	ASSERT(sacnt == 0 || gc != NULL);
19209 
19210 	if (sacnt != 0 &&
19211 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19212 		kmem_free(re, sizeof (*re));
19213 		rw_exit(&gcgrp->gcgrp_rwlock);
19214 		return;
19215 	}
19216 
19217 	/*
19218 	 * Return all IRE types for route table... let caller pick and choose
19219 	 */
19220 	re->ipRouteDest = ire->ire_addr;
19221 	ipif = ire->ire_ipif;
19222 	re->ipRouteIfIndex.o_length = 0;
19223 	if (ire->ire_type == IRE_CACHE) {
19224 		ill = (ill_t *)ire->ire_stq->q_ptr;
19225 		re->ipRouteIfIndex.o_length =
19226 		    ill->ill_name_length == 0 ? 0 :
19227 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19228 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19229 		    re->ipRouteIfIndex.o_length);
19230 	} else if (ipif != NULL) {
19231 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19232 		re->ipRouteIfIndex.o_length =
19233 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19234 	}
19235 	re->ipRouteMetric1 = -1;
19236 	re->ipRouteMetric2 = -1;
19237 	re->ipRouteMetric3 = -1;
19238 	re->ipRouteMetric4 = -1;
19239 
19240 	gw_addr = ire->ire_gateway_addr;
19241 
19242 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19243 		re->ipRouteNextHop = ire->ire_src_addr;
19244 	else
19245 		re->ipRouteNextHop = gw_addr;
19246 	/* indirect(4), direct(3), or invalid(2) */
19247 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19248 		re->ipRouteType = 2;
19249 	else
19250 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19251 	re->ipRouteProto = -1;
19252 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19253 	re->ipRouteMask = ire->ire_mask;
19254 	re->ipRouteMetric5 = -1;
19255 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19256 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19257 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19258 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19259 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19260 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19261 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19262 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19263 
19264 	if (ire->ire_flags & RTF_DYNAMIC) {
19265 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19266 	} else {
19267 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19268 	}
19269 
19270 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19271 	    (char *)re, (int)sizeof (*re))) {
19272 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19273 		    (uint_t)sizeof (*re)));
19274 	}
19275 
19276 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19277 		iaeptr->iae_routeidx = ird->ird_idx;
19278 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19279 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19280 	}
19281 
19282 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19283 	    (char *)iae, sacnt * sizeof (*iae))) {
19284 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19285 		    (unsigned)(sacnt * sizeof (*iae))));
19286 	}
19287 
19288 	/* bump route index for next pass */
19289 	ird->ird_idx++;
19290 
19291 	kmem_free(re, sizeof (*re));
19292 	if (sacnt != 0)
19293 		kmem_free(iae, sacnt * sizeof (*iae));
19294 
19295 	if (gcgrp != NULL)
19296 		rw_exit(&gcgrp->gcgrp_rwlock);
19297 }
19298 
19299 /*
19300  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19301  */
19302 static void
19303 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19304 {
19305 	ill_t				*ill;
19306 	ipif_t				*ipif;
19307 	mib2_ipv6RouteEntry_t		*re;
19308 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19309 	in6_addr_t			gw_addr_v6;
19310 	tsol_ire_gw_secattr_t		*attrp;
19311 	tsol_gc_t			*gc = NULL;
19312 	tsol_gcgrp_t			*gcgrp = NULL;
19313 	uint_t				sacnt = 0;
19314 	int				i;
19315 
19316 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19317 
19318 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19319 		return;
19320 
19321 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19322 		mutex_enter(&attrp->igsa_lock);
19323 		if ((gc = attrp->igsa_gc) != NULL) {
19324 			gcgrp = gc->gc_grp;
19325 			ASSERT(gcgrp != NULL);
19326 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19327 			sacnt = 1;
19328 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19329 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19330 			gc = gcgrp->gcgrp_head;
19331 			sacnt = gcgrp->gcgrp_count;
19332 		}
19333 		mutex_exit(&attrp->igsa_lock);
19334 
19335 		/* do nothing if there's no gc to report */
19336 		if (gc == NULL) {
19337 			ASSERT(sacnt == 0);
19338 			if (gcgrp != NULL) {
19339 				/* we might as well drop the lock now */
19340 				rw_exit(&gcgrp->gcgrp_rwlock);
19341 				gcgrp = NULL;
19342 			}
19343 			attrp = NULL;
19344 		}
19345 
19346 		ASSERT(gc == NULL || (gcgrp != NULL &&
19347 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19348 	}
19349 	ASSERT(sacnt == 0 || gc != NULL);
19350 
19351 	if (sacnt != 0 &&
19352 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19353 		kmem_free(re, sizeof (*re));
19354 		rw_exit(&gcgrp->gcgrp_rwlock);
19355 		return;
19356 	}
19357 
19358 	/*
19359 	 * Return all IRE types for route table... let caller pick and choose
19360 	 */
19361 	re->ipv6RouteDest = ire->ire_addr_v6;
19362 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19363 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19364 	re->ipv6RouteIfIndex.o_length = 0;
19365 	ipif = ire->ire_ipif;
19366 	if (ire->ire_type == IRE_CACHE) {
19367 		ill = (ill_t *)ire->ire_stq->q_ptr;
19368 		re->ipv6RouteIfIndex.o_length =
19369 		    ill->ill_name_length == 0 ? 0 :
19370 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19371 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19372 		    re->ipv6RouteIfIndex.o_length);
19373 	} else if (ipif != NULL) {
19374 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19375 		re->ipv6RouteIfIndex.o_length =
19376 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19377 	}
19378 
19379 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19380 
19381 	mutex_enter(&ire->ire_lock);
19382 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19383 	mutex_exit(&ire->ire_lock);
19384 
19385 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19386 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19387 	else
19388 		re->ipv6RouteNextHop = gw_addr_v6;
19389 
19390 	/* remote(4), local(3), or discard(2) */
19391 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19392 		re->ipv6RouteType = 2;
19393 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19394 		re->ipv6RouteType = 3;
19395 	else
19396 		re->ipv6RouteType = 4;
19397 
19398 	re->ipv6RouteProtocol	= -1;
19399 	re->ipv6RoutePolicy	= 0;
19400 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19401 	re->ipv6RouteNextHopRDI	= 0;
19402 	re->ipv6RouteWeight	= 0;
19403 	re->ipv6RouteMetric	= 0;
19404 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19405 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19406 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19407 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19408 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19409 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19410 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19411 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19412 
19413 	if (ire->ire_flags & RTF_DYNAMIC) {
19414 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19415 	} else {
19416 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19417 	}
19418 
19419 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19420 	    (char *)re, (int)sizeof (*re))) {
19421 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19422 		    (uint_t)sizeof (*re)));
19423 	}
19424 
19425 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19426 		iaeptr->iae_routeidx = ird->ird_idx;
19427 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19428 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19429 	}
19430 
19431 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19432 	    (char *)iae, sacnt * sizeof (*iae))) {
19433 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19434 		    (unsigned)(sacnt * sizeof (*iae))));
19435 	}
19436 
19437 	/* bump route index for next pass */
19438 	ird->ird_idx++;
19439 
19440 	kmem_free(re, sizeof (*re));
19441 	if (sacnt != 0)
19442 		kmem_free(iae, sacnt * sizeof (*iae));
19443 
19444 	if (gcgrp != NULL)
19445 		rw_exit(&gcgrp->gcgrp_rwlock);
19446 }
19447 
19448 /*
19449  * ndp_walk routine to create ipv6NetToMediaEntryTable
19450  */
19451 static int
19452 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19453 {
19454 	ill_t				*ill;
19455 	mib2_ipv6NetToMediaEntry_t	ntme;
19456 	dl_unitdata_req_t		*dl;
19457 
19458 	ill = nce->nce_ill;
19459 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19460 		return (0);
19461 
19462 	/*
19463 	 * Neighbor cache entry attached to IRE with on-link
19464 	 * destination.
19465 	 */
19466 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19467 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19468 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19469 	    (nce->nce_res_mp != NULL)) {
19470 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19471 		ntme.ipv6NetToMediaPhysAddress.o_length =
19472 		    dl->dl_dest_addr_length;
19473 	} else {
19474 		ntme.ipv6NetToMediaPhysAddress.o_length =
19475 		    ill->ill_phys_addr_length;
19476 	}
19477 	if (nce->nce_res_mp != NULL) {
19478 		bcopy((char *)nce->nce_res_mp->b_rptr +
19479 		    NCE_LL_ADDR_OFFSET(ill),
19480 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19481 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19482 	} else {
19483 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19484 		    ill->ill_phys_addr_length);
19485 	}
19486 	/*
19487 	 * Note: Returns ND_* states. Should be:
19488 	 * reachable(1), stale(2), delay(3), probe(4),
19489 	 * invalid(5), unknown(6)
19490 	 */
19491 	ntme.ipv6NetToMediaState = nce->nce_state;
19492 	ntme.ipv6NetToMediaLastUpdated = 0;
19493 
19494 	/* other(1), dynamic(2), static(3), local(4) */
19495 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19496 		ntme.ipv6NetToMediaType = 4;
19497 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19498 		ntme.ipv6NetToMediaType = 1;
19499 	} else {
19500 		ntme.ipv6NetToMediaType = 2;
19501 	}
19502 
19503 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19504 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19505 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19506 		    (uint_t)sizeof (ntme)));
19507 	}
19508 	return (0);
19509 }
19510 
19511 /*
19512  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19513  */
19514 /* ARGSUSED */
19515 int
19516 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19517 {
19518 	switch (level) {
19519 	case MIB2_IP:
19520 	case MIB2_ICMP:
19521 		switch (name) {
19522 		default:
19523 			break;
19524 		}
19525 		return (1);
19526 	default:
19527 		return (1);
19528 	}
19529 }
19530 
19531 /*
19532  * When there exists both a 64- and 32-bit counter of a particular type
19533  * (i.e., InReceives), only the 64-bit counters are added.
19534  */
19535 void
19536 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19537 {
19538 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19539 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19540 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19541 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19542 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19543 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19544 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19545 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19546 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19547 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19548 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19549 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19550 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19551 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19552 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19553 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19554 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19555 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19556 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19557 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19558 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19559 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19560 	    o2->ipIfStatsInWrongIPVersion);
19561 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19562 	    o2->ipIfStatsInWrongIPVersion);
19563 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19564 	    o2->ipIfStatsOutSwitchIPVersion);
19565 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19566 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19567 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19568 	    o2->ipIfStatsHCInForwDatagrams);
19569 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19570 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19571 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19572 	    o2->ipIfStatsHCOutForwDatagrams);
19573 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19574 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19575 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19576 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19577 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19578 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19579 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19580 	    o2->ipIfStatsHCOutMcastOctets);
19581 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19582 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19583 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19584 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19585 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19586 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19587 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19588 }
19589 
19590 void
19591 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19592 {
19593 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19594 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19595 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19596 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19597 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19598 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19599 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19600 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19601 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19602 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19603 	    o2->ipv6IfIcmpInRouterSolicits);
19604 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19605 	    o2->ipv6IfIcmpInRouterAdvertisements);
19606 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19607 	    o2->ipv6IfIcmpInNeighborSolicits);
19608 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19609 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19610 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19611 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19612 	    o2->ipv6IfIcmpInGroupMembQueries);
19613 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19614 	    o2->ipv6IfIcmpInGroupMembResponses);
19615 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19616 	    o2->ipv6IfIcmpInGroupMembReductions);
19617 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19618 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19619 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19620 	    o2->ipv6IfIcmpOutDestUnreachs);
19621 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19622 	    o2->ipv6IfIcmpOutAdminProhibs);
19623 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19624 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19625 	    o2->ipv6IfIcmpOutParmProblems);
19626 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19627 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19628 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19629 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19630 	    o2->ipv6IfIcmpOutRouterSolicits);
19631 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19632 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19633 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19634 	    o2->ipv6IfIcmpOutNeighborSolicits);
19635 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19636 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19637 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19638 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19639 	    o2->ipv6IfIcmpOutGroupMembQueries);
19640 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19641 	    o2->ipv6IfIcmpOutGroupMembResponses);
19642 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19643 	    o2->ipv6IfIcmpOutGroupMembReductions);
19644 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19645 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19646 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19647 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19648 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19649 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19650 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19651 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19652 	    o2->ipv6IfIcmpInGroupMembTotal);
19653 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19654 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19655 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19656 	    o2->ipv6IfIcmpInGroupMembBadReports);
19657 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19658 	    o2->ipv6IfIcmpInGroupMembOurReports);
19659 }
19660 
19661 /*
19662  * Called before the options are updated to check if this packet will
19663  * be source routed from here.
19664  * This routine assumes that the options are well formed i.e. that they
19665  * have already been checked.
19666  */
19667 static boolean_t
19668 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19669 {
19670 	ipoptp_t	opts;
19671 	uchar_t		*opt;
19672 	uint8_t		optval;
19673 	uint8_t		optlen;
19674 	ipaddr_t	dst;
19675 	ire_t		*ire;
19676 
19677 	if (IS_SIMPLE_IPH(ipha)) {
19678 		ip2dbg(("not source routed\n"));
19679 		return (B_FALSE);
19680 	}
19681 	dst = ipha->ipha_dst;
19682 	for (optval = ipoptp_first(&opts, ipha);
19683 	    optval != IPOPT_EOL;
19684 	    optval = ipoptp_next(&opts)) {
19685 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19686 		opt = opts.ipoptp_cur;
19687 		optlen = opts.ipoptp_len;
19688 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19689 		    optval, optlen));
19690 		switch (optval) {
19691 			uint32_t off;
19692 		case IPOPT_SSRR:
19693 		case IPOPT_LSRR:
19694 			/*
19695 			 * If dst is one of our addresses and there are some
19696 			 * entries left in the source route return (true).
19697 			 */
19698 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19699 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19700 			if (ire == NULL) {
19701 				ip2dbg(("ip_source_routed: not next"
19702 				    " source route 0x%x\n",
19703 				    ntohl(dst)));
19704 				return (B_FALSE);
19705 			}
19706 			ire_refrele(ire);
19707 			off = opt[IPOPT_OFFSET];
19708 			off--;
19709 			if (optlen < IP_ADDR_LEN ||
19710 			    off > optlen - IP_ADDR_LEN) {
19711 				/* End of source route */
19712 				ip1dbg(("ip_source_routed: end of SR\n"));
19713 				return (B_FALSE);
19714 			}
19715 			return (B_TRUE);
19716 		}
19717 	}
19718 	ip2dbg(("not source routed\n"));
19719 	return (B_FALSE);
19720 }
19721 
19722 /*
19723  * Check if the packet contains any source route.
19724  */
19725 static boolean_t
19726 ip_source_route_included(ipha_t *ipha)
19727 {
19728 	ipoptp_t	opts;
19729 	uint8_t		optval;
19730 
19731 	if (IS_SIMPLE_IPH(ipha))
19732 		return (B_FALSE);
19733 	for (optval = ipoptp_first(&opts, ipha);
19734 	    optval != IPOPT_EOL;
19735 	    optval = ipoptp_next(&opts)) {
19736 		switch (optval) {
19737 		case IPOPT_SSRR:
19738 		case IPOPT_LSRR:
19739 			return (B_TRUE);
19740 		}
19741 	}
19742 	return (B_FALSE);
19743 }
19744 
19745 /*
19746  * Called when the IRE expiration timer fires.
19747  */
19748 void
19749 ip_trash_timer_expire(void *args)
19750 {
19751 	int			flush_flag = 0;
19752 	ire_expire_arg_t	iea;
19753 	ip_stack_t		*ipst = (ip_stack_t *)args;
19754 
19755 	iea.iea_ipst = ipst;	/* No netstack_hold */
19756 
19757 	/*
19758 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19759 	 * This lock makes sure that a new invocation of this function
19760 	 * that occurs due to an almost immediate timer firing will not
19761 	 * progress beyond this point until the current invocation is done
19762 	 */
19763 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19764 	ipst->ips_ip_ire_expire_id = 0;
19765 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19766 
19767 	/* Periodic timer */
19768 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19769 	    ipst->ips_ip_ire_arp_interval) {
19770 		/*
19771 		 * Remove all IRE_CACHE entries since they might
19772 		 * contain arp information.
19773 		 */
19774 		flush_flag |= FLUSH_ARP_TIME;
19775 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19776 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19777 	}
19778 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19779 	    ipst->ips_ip_ire_redir_interval) {
19780 		/* Remove all redirects */
19781 		flush_flag |= FLUSH_REDIRECT_TIME;
19782 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19783 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19784 	}
19785 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19786 	    ipst->ips_ip_ire_pathmtu_interval) {
19787 		/* Increase path mtu */
19788 		flush_flag |= FLUSH_MTU_TIME;
19789 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19790 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19791 	}
19792 
19793 	/*
19794 	 * Optimize for the case when there are no redirects in the
19795 	 * ftable, that is, no need to walk the ftable in that case.
19796 	 */
19797 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19798 		iea.iea_flush_flag = flush_flag;
19799 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19800 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19801 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19802 		    NULL, ALL_ZONES, ipst);
19803 	}
19804 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19805 	    ipst->ips_ip_redirect_cnt > 0) {
19806 		iea.iea_flush_flag = flush_flag;
19807 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19808 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19809 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19810 	}
19811 	if (flush_flag & FLUSH_MTU_TIME) {
19812 		/*
19813 		 * Walk all IPv6 IRE's and update them
19814 		 * Note that ARP and redirect timers are not
19815 		 * needed since NUD handles stale entries.
19816 		 */
19817 		flush_flag = FLUSH_MTU_TIME;
19818 		iea.iea_flush_flag = flush_flag;
19819 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19820 		    ALL_ZONES, ipst);
19821 	}
19822 
19823 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19824 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19825 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19826 
19827 	/*
19828 	 * Hold the lock to serialize timeout calls and prevent
19829 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19830 	 * for the timer to fire and a new invocation of this function
19831 	 * to start before the return value of timeout has been stored
19832 	 * in ip_ire_expire_id by the current invocation.
19833 	 */
19834 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19835 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19836 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19837 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19838 }
19839 
19840 /*
19841  * Called by the memory allocator subsystem directly, when the system
19842  * is running low on memory.
19843  */
19844 /* ARGSUSED */
19845 void
19846 ip_trash_ire_reclaim(void *args)
19847 {
19848 	netstack_handle_t nh;
19849 	netstack_t *ns;
19850 
19851 	netstack_next_init(&nh);
19852 	while ((ns = netstack_next(&nh)) != NULL) {
19853 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19854 		netstack_rele(ns);
19855 	}
19856 	netstack_next_fini(&nh);
19857 }
19858 
19859 static void
19860 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19861 {
19862 	ire_cache_count_t icc;
19863 	ire_cache_reclaim_t icr;
19864 	ncc_cache_count_t ncc;
19865 	nce_cache_reclaim_t ncr;
19866 	uint_t delete_cnt;
19867 	/*
19868 	 * Memory reclaim call back.
19869 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19870 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19871 	 * entries, determine what fraction to free for
19872 	 * each category of IRE_CACHE entries giving absolute priority
19873 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19874 	 * entry will be freed unless all offlink entries are freed).
19875 	 */
19876 	icc.icc_total = 0;
19877 	icc.icc_unused = 0;
19878 	icc.icc_offlink = 0;
19879 	icc.icc_pmtu = 0;
19880 	icc.icc_onlink = 0;
19881 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19882 
19883 	/*
19884 	 * Free NCEs for IPv6 like the onlink ires.
19885 	 */
19886 	ncc.ncc_total = 0;
19887 	ncc.ncc_host = 0;
19888 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19889 
19890 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19891 	    icc.icc_pmtu + icc.icc_onlink);
19892 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19893 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19894 	if (delete_cnt == 0)
19895 		return;
19896 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19897 	/* Always delete all unused offlink entries */
19898 	icr.icr_ipst = ipst;
19899 	icr.icr_unused = 1;
19900 	if (delete_cnt <= icc.icc_unused) {
19901 		/*
19902 		 * Only need to free unused entries.  In other words,
19903 		 * there are enough unused entries to free to meet our
19904 		 * target number of freed ire cache entries.
19905 		 */
19906 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19907 		ncr.ncr_host = 0;
19908 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19909 		/*
19910 		 * Only need to free unused entries, plus a fraction of offlink
19911 		 * entries.  It follows from the first if statement that
19912 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19913 		 */
19914 		delete_cnt -= icc.icc_unused;
19915 		/* Round up # deleted by truncating fraction */
19916 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19917 		icr.icr_pmtu = icr.icr_onlink = 0;
19918 		ncr.ncr_host = 0;
19919 	} else if (delete_cnt <=
19920 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19921 		/*
19922 		 * Free all unused and offlink entries, plus a fraction of
19923 		 * pmtu entries.  It follows from the previous if statement
19924 		 * that icc_pmtu is non-zero, and that
19925 		 * delete_cnt != icc_unused + icc_offlink.
19926 		 */
19927 		icr.icr_offlink = 1;
19928 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19929 		/* Round up # deleted by truncating fraction */
19930 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19931 		icr.icr_onlink = 0;
19932 		ncr.ncr_host = 0;
19933 	} else {
19934 		/*
19935 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19936 		 * of onlink entries.  If we're here, then we know that
19937 		 * icc_onlink is non-zero, and that
19938 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19939 		 */
19940 		icr.icr_offlink = icr.icr_pmtu = 1;
19941 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19942 		    icc.icc_pmtu;
19943 		/* Round up # deleted by truncating fraction */
19944 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19945 		/* Using the same delete fraction as for onlink IREs */
19946 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19947 	}
19948 #ifdef DEBUG
19949 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19950 	    "fractions %d/%d/%d/%d\n",
19951 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19952 	    icc.icc_unused, icc.icc_offlink,
19953 	    icc.icc_pmtu, icc.icc_onlink,
19954 	    icr.icr_unused, icr.icr_offlink,
19955 	    icr.icr_pmtu, icr.icr_onlink));
19956 #endif
19957 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19958 	if (ncr.ncr_host != 0)
19959 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19960 		    (uchar_t *)&ncr, ipst);
19961 #ifdef DEBUG
19962 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19963 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19964 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19965 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19966 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19967 	    icc.icc_pmtu, icc.icc_onlink));
19968 #endif
19969 }
19970 
19971 /*
19972  * ip_unbind is called when a copy of an unbind request is received from the
19973  * upper level protocol.  We remove this conn from any fanout hash list it is
19974  * on, and zero out the bind information.  No reply is expected up above.
19975  */
19976 mblk_t *
19977 ip_unbind(queue_t *q, mblk_t *mp)
19978 {
19979 	conn_t	*connp = Q_TO_CONN(q);
19980 
19981 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19982 
19983 	if (is_system_labeled() && connp->conn_anon_port) {
19984 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19985 		    connp->conn_mlp_type, connp->conn_ulp,
19986 		    ntohs(connp->conn_lport), B_FALSE);
19987 		connp->conn_anon_port = 0;
19988 	}
19989 	connp->conn_mlp_type = mlptSingle;
19990 
19991 	ipcl_hash_remove(connp);
19992 
19993 	ASSERT(mp->b_cont == NULL);
19994 	/*
19995 	 * Convert mp into a T_OK_ACK
19996 	 */
19997 	mp = mi_tpi_ok_ack_alloc(mp);
19998 
19999 	/*
20000 	 * should not happen in practice... T_OK_ACK is smaller than the
20001 	 * original message.
20002 	 */
20003 	if (mp == NULL)
20004 		return (NULL);
20005 
20006 	/*
20007 	 * Don't bzero the ports if its TCP since TCP still needs the
20008 	 * lport to remove it from its own bind hash. TCP will do the
20009 	 * cleanup.
20010 	 */
20011 	if (!IPCL_IS_TCP(connp))
20012 		bzero(&connp->u_port, sizeof (connp->u_port));
20013 
20014 	return (mp);
20015 }
20016 
20017 /*
20018  * Write side put procedure.  Outbound data, IOCTLs, responses from
20019  * resolvers, etc, come down through here.
20020  *
20021  * arg2 is always a queue_t *.
20022  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20023  * the zoneid.
20024  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20025  */
20026 void
20027 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20028 {
20029 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20030 }
20031 
20032 void
20033 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20034     ip_opt_info_t *infop)
20035 {
20036 	conn_t		*connp = NULL;
20037 	queue_t		*q = (queue_t *)arg2;
20038 	ipha_t		*ipha;
20039 #define	rptr	((uchar_t *)ipha)
20040 	ire_t		*ire = NULL;
20041 	ire_t		*sctp_ire = NULL;
20042 	uint32_t	v_hlen_tos_len;
20043 	ipaddr_t	dst;
20044 	mblk_t		*first_mp = NULL;
20045 	boolean_t	mctl_present;
20046 	ipsec_out_t	*io;
20047 	int		match_flags;
20048 	ill_t		*attach_ill = NULL;
20049 					/* Bind to IPIF_NOFAILOVER ill etc. */
20050 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
20051 	ipif_t		*dst_ipif;
20052 	boolean_t	multirt_need_resolve = B_FALSE;
20053 	mblk_t		*copy_mp = NULL;
20054 	int		err;
20055 	zoneid_t	zoneid;
20056 	int	adjust;
20057 	uint16_t iplen;
20058 	boolean_t	need_decref = B_FALSE;
20059 	boolean_t	ignore_dontroute = B_FALSE;
20060 	boolean_t	ignore_nexthop = B_FALSE;
20061 	boolean_t	ip_nexthop = B_FALSE;
20062 	ipaddr_t	nexthop_addr;
20063 	ip_stack_t	*ipst;
20064 
20065 #ifdef	_BIG_ENDIAN
20066 #define	V_HLEN	(v_hlen_tos_len >> 24)
20067 #else
20068 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20069 #endif
20070 
20071 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20072 	    "ip_wput_start: q %p", q);
20073 
20074 	/*
20075 	 * ip_wput fast path
20076 	 */
20077 
20078 	/* is packet from ARP ? */
20079 	if (q->q_next != NULL) {
20080 		zoneid = (zoneid_t)(uintptr_t)arg;
20081 		goto qnext;
20082 	}
20083 
20084 	connp = (conn_t *)arg;
20085 	ASSERT(connp != NULL);
20086 	zoneid = connp->conn_zoneid;
20087 	ipst = connp->conn_netstack->netstack_ip;
20088 
20089 	/* is queue flow controlled? */
20090 	if ((q->q_first != NULL || connp->conn_draining) &&
20091 	    (caller == IP_WPUT)) {
20092 		ASSERT(!need_decref);
20093 		(void) putq(q, mp);
20094 		return;
20095 	}
20096 
20097 	/* Multidata transmit? */
20098 	if (DB_TYPE(mp) == M_MULTIDATA) {
20099 		/*
20100 		 * We should never get here, since all Multidata messages
20101 		 * originating from tcp should have been directed over to
20102 		 * tcp_multisend() in the first place.
20103 		 */
20104 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20105 		freemsg(mp);
20106 		return;
20107 	} else if (DB_TYPE(mp) != M_DATA)
20108 		goto notdata;
20109 
20110 	if (mp->b_flag & MSGHASREF) {
20111 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20112 		mp->b_flag &= ~MSGHASREF;
20113 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20114 		need_decref = B_TRUE;
20115 	}
20116 	ipha = (ipha_t *)mp->b_rptr;
20117 
20118 	/* is IP header non-aligned or mblk smaller than basic IP header */
20119 #ifndef SAFETY_BEFORE_SPEED
20120 	if (!OK_32PTR(rptr) ||
20121 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20122 		goto hdrtoosmall;
20123 #endif
20124 
20125 	ASSERT(OK_32PTR(ipha));
20126 
20127 	/*
20128 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20129 	 * wrong version, we'll catch it again in ip_output_v6.
20130 	 *
20131 	 * Note that this is *only* locally-generated output here, and never
20132 	 * forwarded data, and that we need to deal only with transports that
20133 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20134 	 * label.)
20135 	 */
20136 	if (is_system_labeled() &&
20137 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20138 	    !connp->conn_ulp_labeled) {
20139 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20140 		    connp->conn_mac_exempt, ipst);
20141 		ipha = (ipha_t *)mp->b_rptr;
20142 		if (err != 0) {
20143 			first_mp = mp;
20144 			if (err == EINVAL)
20145 				goto icmp_parameter_problem;
20146 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20147 			goto discard_pkt;
20148 		}
20149 		iplen = ntohs(ipha->ipha_length) + adjust;
20150 		ipha->ipha_length = htons(iplen);
20151 	}
20152 
20153 	ASSERT(infop != NULL);
20154 
20155 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20156 		/*
20157 		 * IP_PKTINFO ancillary option is present.
20158 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20159 		 * allows using address of any zone as the source address.
20160 		 */
20161 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20162 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20163 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20164 		if (ire == NULL)
20165 			goto drop_pkt;
20166 		ire_refrele(ire);
20167 		ire = NULL;
20168 	}
20169 
20170 	/*
20171 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
20172 	 * ill index passed in IP_PKTINFO.
20173 	 */
20174 	if (infop->ip_opt_ill_index != 0 &&
20175 	    connp->conn_xmit_if_ill == NULL &&
20176 	    connp->conn_nofailover_ill == NULL) {
20177 
20178 		xmit_ill = ill_lookup_on_ifindex(
20179 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20180 		    ipst);
20181 
20182 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20183 			goto drop_pkt;
20184 		/*
20185 		 * check that there is an ipif belonging
20186 		 * to our zone. IPCL_ZONEID is not used because
20187 		 * IP_ALLZONES option is valid only when the ill is
20188 		 * accessible from all zones i.e has a valid ipif in
20189 		 * all zones.
20190 		 */
20191 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20192 			goto drop_pkt;
20193 		}
20194 	}
20195 
20196 	/*
20197 	 * If there is a policy, try to attach an ipsec_out in
20198 	 * the front. At the end, first_mp either points to a
20199 	 * M_DATA message or IPSEC_OUT message linked to a
20200 	 * M_DATA message. We have to do it now as we might
20201 	 * lose the "conn" if we go through ip_newroute.
20202 	 */
20203 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20204 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20205 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20206 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20207 			if (need_decref)
20208 				CONN_DEC_REF(connp);
20209 			return;
20210 		} else {
20211 			ASSERT(mp->b_datap->db_type == M_CTL);
20212 			first_mp = mp;
20213 			mp = mp->b_cont;
20214 			mctl_present = B_TRUE;
20215 		}
20216 	} else {
20217 		first_mp = mp;
20218 		mctl_present = B_FALSE;
20219 	}
20220 
20221 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20222 
20223 	/* is wrong version or IP options present */
20224 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20225 		goto version_hdrlen_check;
20226 	dst = ipha->ipha_dst;
20227 
20228 	if (connp->conn_nofailover_ill != NULL) {
20229 		attach_ill = conn_get_held_ill(connp,
20230 		    &connp->conn_nofailover_ill, &err);
20231 		if (err == ILL_LOOKUP_FAILED) {
20232 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20233 			if (need_decref)
20234 				CONN_DEC_REF(connp);
20235 			freemsg(first_mp);
20236 			return;
20237 		}
20238 	}
20239 
20240 
20241 	/* is packet multicast? */
20242 	if (CLASSD(dst))
20243 		goto multicast;
20244 
20245 	/*
20246 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20247 	 * takes precedence over conn_dontroute and conn_nexthop_set
20248 	 */
20249 	if (xmit_ill != NULL) {
20250 		goto send_from_ill;
20251 	}
20252 
20253 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
20254 	    (connp->conn_nexthop_set)) {
20255 		/*
20256 		 * If the destination is a broadcast or a loopback
20257 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20258 		 * through the standard path. But in the case of local
20259 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20260 		 * the standard path not IP_XMIT_IF.
20261 		 */
20262 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20263 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20264 		    (ire->ire_type != IRE_LOOPBACK))) {
20265 			if ((connp->conn_dontroute ||
20266 			    connp->conn_nexthop_set) && (ire != NULL) &&
20267 			    (ire->ire_type == IRE_LOCAL))
20268 				goto standard_path;
20269 
20270 			if (ire != NULL) {
20271 				ire_refrele(ire);
20272 				/* No more access to ire */
20273 				ire = NULL;
20274 			}
20275 			/*
20276 			 * bypass routing checks and go directly to
20277 			 * interface.
20278 			 */
20279 			if (connp->conn_dontroute) {
20280 				goto dontroute;
20281 			} else if (connp->conn_nexthop_set) {
20282 				ip_nexthop = B_TRUE;
20283 				nexthop_addr = connp->conn_nexthop_v4;
20284 				goto send_from_ill;
20285 			}
20286 
20287 			/*
20288 			 * If IP_XMIT_IF socket option is set,
20289 			 * then we allow unicast and multicast
20290 			 * packets to go through the ill. It is
20291 			 * quite possible that the destination
20292 			 * is not in the ire cache table and we
20293 			 * do not want to go to ip_newroute()
20294 			 * instead we call ip_newroute_ipif.
20295 			 */
20296 			xmit_ill = conn_get_held_ill(connp,
20297 			    &connp->conn_xmit_if_ill, &err);
20298 			if (err == ILL_LOOKUP_FAILED) {
20299 				BUMP_MIB(&ipst->ips_ip_mib,
20300 				    ipIfStatsOutDiscards);
20301 				if (attach_ill != NULL)
20302 					ill_refrele(attach_ill);
20303 				if (need_decref)
20304 					CONN_DEC_REF(connp);
20305 				freemsg(first_mp);
20306 				return;
20307 			}
20308 			goto send_from_ill;
20309 		}
20310 standard_path:
20311 		/* Must be a broadcast, a loopback or a local ire */
20312 		if (ire != NULL) {
20313 			ire_refrele(ire);
20314 			/* No more access to ire */
20315 			ire = NULL;
20316 		}
20317 	}
20318 
20319 	if (attach_ill != NULL)
20320 		goto send_from_ill;
20321 
20322 	/*
20323 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20324 	 * this for the tcp global queue and listen end point
20325 	 * as it does not really have a real destination to
20326 	 * talk to.  This is also true for SCTP.
20327 	 */
20328 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20329 	    !connp->conn_fully_bound) {
20330 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20331 		if (ire == NULL)
20332 			goto noirefound;
20333 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20334 		    "ip_wput_end: q %p (%S)", q, "end");
20335 
20336 		/*
20337 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20338 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20339 		 */
20340 		if (ire->ire_flags & RTF_MULTIRT) {
20341 
20342 			/*
20343 			 * Force the TTL of multirouted packets if required.
20344 			 * The TTL of such packets is bounded by the
20345 			 * ip_multirt_ttl ndd variable.
20346 			 */
20347 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20348 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20349 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20350 				    "(was %d), dst 0x%08x\n",
20351 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20352 				    ntohl(ire->ire_addr)));
20353 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20354 			}
20355 			/*
20356 			 * We look at this point if there are pending
20357 			 * unresolved routes. ire_multirt_resolvable()
20358 			 * checks in O(n) that all IRE_OFFSUBNET ire
20359 			 * entries for the packet's destination and
20360 			 * flagged RTF_MULTIRT are currently resolved.
20361 			 * If some remain unresolved, we make a copy
20362 			 * of the current message. It will be used
20363 			 * to initiate additional route resolutions.
20364 			 */
20365 			multirt_need_resolve =
20366 			    ire_multirt_need_resolve(ire->ire_addr,
20367 			    MBLK_GETLABEL(first_mp), ipst);
20368 			ip2dbg(("ip_wput[TCP]: ire %p, "
20369 			    "multirt_need_resolve %d, first_mp %p\n",
20370 			    (void *)ire, multirt_need_resolve,
20371 			    (void *)first_mp));
20372 			if (multirt_need_resolve) {
20373 				copy_mp = copymsg(first_mp);
20374 				if (copy_mp != NULL) {
20375 					MULTIRT_DEBUG_TAG(copy_mp);
20376 				}
20377 			}
20378 		}
20379 
20380 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20381 
20382 		/*
20383 		 * Try to resolve another multiroute if
20384 		 * ire_multirt_need_resolve() deemed it necessary.
20385 		 */
20386 		if (copy_mp != NULL)
20387 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20388 		if (need_decref)
20389 			CONN_DEC_REF(connp);
20390 		return;
20391 	}
20392 
20393 	/*
20394 	 * Access to conn_ire_cache. (protected by conn_lock)
20395 	 *
20396 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20397 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20398 	 * send a packet or two with the IRE_CACHE that is going away.
20399 	 * Access to the ire requires an ire refhold on the ire prior to
20400 	 * its use since an interface unplumb thread may delete the cached
20401 	 * ire and release the refhold at any time.
20402 	 *
20403 	 * Caching an ire in the conn_ire_cache
20404 	 *
20405 	 * o Caching an ire pointer in the conn requires a strict check for
20406 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20407 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20408 	 * in the conn is done after making sure under the bucket lock that the
20409 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20410 	 * caching an ire after the unplumb thread has cleaned up the conn.
20411 	 * If the conn does not send a packet subsequently the unplumb thread
20412 	 * will be hanging waiting for the ire count to drop to zero.
20413 	 *
20414 	 * o We also need to atomically test for a null conn_ire_cache and
20415 	 * set the conn_ire_cache under the the protection of the conn_lock
20416 	 * to avoid races among concurrent threads trying to simultaneously
20417 	 * cache an ire in the conn_ire_cache.
20418 	 */
20419 	mutex_enter(&connp->conn_lock);
20420 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20421 
20422 	if (ire != NULL && ire->ire_addr == dst &&
20423 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20424 
20425 		IRE_REFHOLD(ire);
20426 		mutex_exit(&connp->conn_lock);
20427 
20428 	} else {
20429 		boolean_t cached = B_FALSE;
20430 		connp->conn_ire_cache = NULL;
20431 		mutex_exit(&connp->conn_lock);
20432 		/* Release the old ire */
20433 		if (ire != NULL && sctp_ire == NULL)
20434 			IRE_REFRELE_NOTR(ire);
20435 
20436 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20437 		if (ire == NULL)
20438 			goto noirefound;
20439 		IRE_REFHOLD_NOTR(ire);
20440 
20441 		mutex_enter(&connp->conn_lock);
20442 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20443 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20444 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20445 				if (connp->conn_ulp == IPPROTO_TCP)
20446 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20447 				connp->conn_ire_cache = ire;
20448 				cached = B_TRUE;
20449 			}
20450 			rw_exit(&ire->ire_bucket->irb_lock);
20451 		}
20452 		mutex_exit(&connp->conn_lock);
20453 
20454 		/*
20455 		 * We can continue to use the ire but since it was
20456 		 * not cached, we should drop the extra reference.
20457 		 */
20458 		if (!cached)
20459 			IRE_REFRELE_NOTR(ire);
20460 	}
20461 
20462 
20463 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20464 	    "ip_wput_end: q %p (%S)", q, "end");
20465 
20466 	/*
20467 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20468 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20469 	 */
20470 	if (ire->ire_flags & RTF_MULTIRT) {
20471 
20472 		/*
20473 		 * Force the TTL of multirouted packets if required.
20474 		 * The TTL of such packets is bounded by the
20475 		 * ip_multirt_ttl ndd variable.
20476 		 */
20477 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20478 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20479 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20480 			    "(was %d), dst 0x%08x\n",
20481 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20482 			    ntohl(ire->ire_addr)));
20483 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20484 		}
20485 
20486 		/*
20487 		 * At this point, we check to see if there are any pending
20488 		 * unresolved routes. ire_multirt_resolvable()
20489 		 * checks in O(n) that all IRE_OFFSUBNET ire
20490 		 * entries for the packet's destination and
20491 		 * flagged RTF_MULTIRT are currently resolved.
20492 		 * If some remain unresolved, we make a copy
20493 		 * of the current message. It will be used
20494 		 * to initiate additional route resolutions.
20495 		 */
20496 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20497 		    MBLK_GETLABEL(first_mp), ipst);
20498 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20499 		    "multirt_need_resolve %d, first_mp %p\n",
20500 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20501 		if (multirt_need_resolve) {
20502 			copy_mp = copymsg(first_mp);
20503 			if (copy_mp != NULL) {
20504 				MULTIRT_DEBUG_TAG(copy_mp);
20505 			}
20506 		}
20507 	}
20508 
20509 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20510 
20511 	/*
20512 	 * Try to resolve another multiroute if
20513 	 * ire_multirt_resolvable() deemed it necessary
20514 	 */
20515 	if (copy_mp != NULL)
20516 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20517 	if (need_decref)
20518 		CONN_DEC_REF(connp);
20519 	return;
20520 
20521 qnext:
20522 	/*
20523 	 * Upper Level Protocols pass down complete IP datagrams
20524 	 * as M_DATA messages.	Everything else is a sideshow.
20525 	 *
20526 	 * 1) We could be re-entering ip_wput because of ip_neworute
20527 	 *    in which case we could have a IPSEC_OUT message. We
20528 	 *    need to pass through ip_wput like other datagrams and
20529 	 *    hence cannot branch to ip_wput_nondata.
20530 	 *
20531 	 * 2) ARP, AH, ESP, and other clients who are on the module
20532 	 *    instance of IP stream, give us something to deal with.
20533 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20534 	 *
20535 	 * 3) ICMP replies also could come here.
20536 	 */
20537 	ipst = ILLQ_TO_IPST(q);
20538 
20539 	if (DB_TYPE(mp) != M_DATA) {
20540 notdata:
20541 		if (DB_TYPE(mp) == M_CTL) {
20542 			/*
20543 			 * M_CTL messages are used by ARP, AH and ESP to
20544 			 * communicate with IP. We deal with IPSEC_IN and
20545 			 * IPSEC_OUT here. ip_wput_nondata handles other
20546 			 * cases.
20547 			 */
20548 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20549 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20550 				first_mp = mp->b_cont;
20551 				first_mp->b_flag &= ~MSGHASREF;
20552 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20553 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20554 				CONN_DEC_REF(connp);
20555 				connp = NULL;
20556 			}
20557 			if (ii->ipsec_info_type == IPSEC_IN) {
20558 				/*
20559 				 * Either this message goes back to
20560 				 * IPsec for further processing or to
20561 				 * ULP after policy checks.
20562 				 */
20563 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20564 				return;
20565 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20566 				io = (ipsec_out_t *)ii;
20567 				if (io->ipsec_out_proc_begin) {
20568 					/*
20569 					 * IPsec processing has already started.
20570 					 * Complete it.
20571 					 * IPQoS notes: We don't care what is
20572 					 * in ipsec_out_ill_index since this
20573 					 * won't be processed for IPQoS policies
20574 					 * in ipsec_out_process.
20575 					 */
20576 					ipsec_out_process(q, mp, NULL,
20577 					    io->ipsec_out_ill_index);
20578 					return;
20579 				} else {
20580 					connp = (q->q_next != NULL) ?
20581 					    NULL : Q_TO_CONN(q);
20582 					first_mp = mp;
20583 					mp = mp->b_cont;
20584 					mctl_present = B_TRUE;
20585 				}
20586 				zoneid = io->ipsec_out_zoneid;
20587 				ASSERT(zoneid != ALL_ZONES);
20588 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20589 				/*
20590 				 * It's an IPsec control message requesting
20591 				 * an SADB update to be sent to the IPsec
20592 				 * hardware acceleration capable ills.
20593 				 */
20594 				ipsec_ctl_t *ipsec_ctl =
20595 				    (ipsec_ctl_t *)mp->b_rptr;
20596 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20597 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20598 				mblk_t *cmp = mp->b_cont;
20599 
20600 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20601 				ASSERT(cmp != NULL);
20602 
20603 				freeb(mp);
20604 				ill_ipsec_capab_send_all(satype, cmp, sa,
20605 				    ipst->ips_netstack);
20606 				return;
20607 			} else {
20608 				/*
20609 				 * This must be ARP or special TSOL signaling.
20610 				 */
20611 				ip_wput_nondata(NULL, q, mp, NULL);
20612 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20613 				    "ip_wput_end: q %p (%S)", q, "nondata");
20614 				return;
20615 			}
20616 		} else {
20617 			/*
20618 			 * This must be non-(ARP/AH/ESP) messages.
20619 			 */
20620 			ASSERT(!need_decref);
20621 			ip_wput_nondata(NULL, q, mp, NULL);
20622 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20623 			    "ip_wput_end: q %p (%S)", q, "nondata");
20624 			return;
20625 		}
20626 	} else {
20627 		first_mp = mp;
20628 		mctl_present = B_FALSE;
20629 	}
20630 
20631 	ASSERT(first_mp != NULL);
20632 	/*
20633 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20634 	 * to make sure that this packet goes out on the same interface it
20635 	 * came in. We handle that here.
20636 	 */
20637 	if (mctl_present) {
20638 		uint_t ifindex;
20639 
20640 		io = (ipsec_out_t *)first_mp->b_rptr;
20641 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20642 			/*
20643 			 * We may have lost the conn context if we are
20644 			 * coming here from ip_newroute(). Copy the
20645 			 * nexthop information.
20646 			 */
20647 			if (io->ipsec_out_ip_nexthop) {
20648 				ip_nexthop = B_TRUE;
20649 				nexthop_addr = io->ipsec_out_nexthop_addr;
20650 
20651 				ipha = (ipha_t *)mp->b_rptr;
20652 				dst = ipha->ipha_dst;
20653 				goto send_from_ill;
20654 			} else {
20655 				ASSERT(io->ipsec_out_ill_index != 0);
20656 				ifindex = io->ipsec_out_ill_index;
20657 				attach_ill = ill_lookup_on_ifindex(ifindex,
20658 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20659 				if (attach_ill == NULL) {
20660 					ASSERT(xmit_ill == NULL);
20661 					ip1dbg(("ip_output: bad ifindex for "
20662 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20663 					    ifindex));
20664 					freemsg(first_mp);
20665 					BUMP_MIB(&ipst->ips_ip_mib,
20666 					    ipIfStatsOutDiscards);
20667 					ASSERT(!need_decref);
20668 					return;
20669 				}
20670 			}
20671 		}
20672 	}
20673 
20674 	ASSERT(xmit_ill == NULL);
20675 
20676 	/* We have a complete IP datagram heading outbound. */
20677 	ipha = (ipha_t *)mp->b_rptr;
20678 
20679 #ifndef SPEED_BEFORE_SAFETY
20680 	/*
20681 	 * Make sure we have a full-word aligned message and that at least
20682 	 * a simple IP header is accessible in the first message.  If not,
20683 	 * try a pullup.
20684 	 */
20685 	if (!OK_32PTR(rptr) ||
20686 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20687 hdrtoosmall:
20688 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20689 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20690 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20691 			if (first_mp == NULL)
20692 				first_mp = mp;
20693 			goto discard_pkt;
20694 		}
20695 
20696 		/* This function assumes that mp points to an IPv4 packet. */
20697 		if (is_system_labeled() && q->q_next == NULL &&
20698 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20699 		    !connp->conn_ulp_labeled) {
20700 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20701 			    &adjust, connp->conn_mac_exempt, ipst);
20702 			ipha = (ipha_t *)mp->b_rptr;
20703 			if (first_mp != NULL)
20704 				first_mp->b_cont = mp;
20705 			if (err != 0) {
20706 				if (first_mp == NULL)
20707 					first_mp = mp;
20708 				if (err == EINVAL)
20709 					goto icmp_parameter_problem;
20710 				ip2dbg(("ip_wput: label check failed (%d)\n",
20711 				    err));
20712 				goto discard_pkt;
20713 			}
20714 			iplen = ntohs(ipha->ipha_length) + adjust;
20715 			ipha->ipha_length = htons(iplen);
20716 		}
20717 
20718 		ipha = (ipha_t *)mp->b_rptr;
20719 		if (first_mp == NULL) {
20720 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20721 			/*
20722 			 * If we got here because of "goto hdrtoosmall"
20723 			 * We need to attach a IPSEC_OUT.
20724 			 */
20725 			if (connp->conn_out_enforce_policy) {
20726 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20727 				    NULL, ipha->ipha_protocol,
20728 				    ipst->ips_netstack)) == NULL)) {
20729 					BUMP_MIB(&ipst->ips_ip_mib,
20730 					    ipIfStatsOutDiscards);
20731 					if (need_decref)
20732 						CONN_DEC_REF(connp);
20733 					return;
20734 				} else {
20735 					ASSERT(mp->b_datap->db_type == M_CTL);
20736 					first_mp = mp;
20737 					mp = mp->b_cont;
20738 					mctl_present = B_TRUE;
20739 				}
20740 			} else {
20741 				first_mp = mp;
20742 				mctl_present = B_FALSE;
20743 			}
20744 		}
20745 	}
20746 #endif
20747 
20748 	/* Most of the code below is written for speed, not readability */
20749 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20750 
20751 	/*
20752 	 * If ip_newroute() fails, we're going to need a full
20753 	 * header for the icmp wraparound.
20754 	 */
20755 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20756 		uint_t	v_hlen;
20757 version_hdrlen_check:
20758 		ASSERT(first_mp != NULL);
20759 		v_hlen = V_HLEN;
20760 		/*
20761 		 * siphon off IPv6 packets coming down from transport
20762 		 * layer modules here.
20763 		 * Note: high-order bit carries NUD reachability confirmation
20764 		 */
20765 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20766 			/*
20767 			 * XXX implement a IPv4 and IPv6 packet counter per
20768 			 * conn and switch when ratio exceeds e.g. 10:1
20769 			 */
20770 #ifdef notyet
20771 			if (q->q_next == NULL) /* Avoid ill queue */
20772 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
20773 #endif
20774 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20775 			ASSERT(xmit_ill == NULL);
20776 			if (attach_ill != NULL)
20777 				ill_refrele(attach_ill);
20778 			if (need_decref)
20779 				mp->b_flag |= MSGHASREF;
20780 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20781 			return;
20782 		}
20783 
20784 		if ((v_hlen >> 4) != IP_VERSION) {
20785 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20786 			    "ip_wput_end: q %p (%S)", q, "badvers");
20787 			goto discard_pkt;
20788 		}
20789 		/*
20790 		 * Is the header length at least 20 bytes?
20791 		 *
20792 		 * Are there enough bytes accessible in the header?  If
20793 		 * not, try a pullup.
20794 		 */
20795 		v_hlen &= 0xF;
20796 		v_hlen <<= 2;
20797 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20798 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20799 			    "ip_wput_end: q %p (%S)", q, "badlen");
20800 			goto discard_pkt;
20801 		}
20802 		if (v_hlen > (mp->b_wptr - rptr)) {
20803 			if (!pullupmsg(mp, v_hlen)) {
20804 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20805 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20806 				goto discard_pkt;
20807 			}
20808 			ipha = (ipha_t *)mp->b_rptr;
20809 		}
20810 		/*
20811 		 * Move first entry from any source route into ipha_dst and
20812 		 * verify the options
20813 		 */
20814 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20815 		    zoneid, ipst)) {
20816 			ASSERT(xmit_ill == NULL);
20817 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20818 			if (attach_ill != NULL)
20819 				ill_refrele(attach_ill);
20820 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20821 			    "ip_wput_end: q %p (%S)", q, "badopts");
20822 			if (need_decref)
20823 				CONN_DEC_REF(connp);
20824 			return;
20825 		}
20826 	}
20827 	dst = ipha->ipha_dst;
20828 
20829 	/*
20830 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20831 	 * we have to run the packet through ip_newroute which will take
20832 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20833 	 * a resolver, or assigning a default gateway, etc.
20834 	 */
20835 	if (CLASSD(dst)) {
20836 		ipif_t	*ipif;
20837 		uint32_t setsrc = 0;
20838 
20839 multicast:
20840 		ASSERT(first_mp != NULL);
20841 		ip2dbg(("ip_wput: CLASSD\n"));
20842 		if (connp == NULL) {
20843 			/*
20844 			 * Use the first good ipif on the ill.
20845 			 * XXX Should this ever happen? (Appears
20846 			 * to show up with just ppp and no ethernet due
20847 			 * to in.rdisc.)
20848 			 * However, ire_send should be able to
20849 			 * call ip_wput_ire directly.
20850 			 *
20851 			 * XXX Also, this can happen for ICMP and other packets
20852 			 * with multicast source addresses.  Perhaps we should
20853 			 * fix things so that we drop the packet in question,
20854 			 * but for now, just run with it.
20855 			 */
20856 			ill_t *ill = (ill_t *)q->q_ptr;
20857 
20858 			/*
20859 			 * Don't honor attach_if for this case. If ill
20860 			 * is part of the group, ipif could belong to
20861 			 * any ill and we cannot maintain attach_ill
20862 			 * and ipif_ill same anymore and the assert
20863 			 * below would fail.
20864 			 */
20865 			if (mctl_present && io->ipsec_out_attach_if) {
20866 				io->ipsec_out_ill_index = 0;
20867 				io->ipsec_out_attach_if = B_FALSE;
20868 				ASSERT(attach_ill != NULL);
20869 				ill_refrele(attach_ill);
20870 				attach_ill = NULL;
20871 			}
20872 
20873 			ASSERT(attach_ill == NULL);
20874 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20875 			if (ipif == NULL) {
20876 				if (need_decref)
20877 					CONN_DEC_REF(connp);
20878 				freemsg(first_mp);
20879 				return;
20880 			}
20881 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20882 			    ntohl(dst), ill->ill_name));
20883 		} else {
20884 			/*
20885 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20886 			 * and IP_MULTICAST_IF.
20887 			 * Block comment above this function explains the
20888 			 * locking mechanism used here
20889 			 */
20890 			if (xmit_ill == NULL) {
20891 				xmit_ill = conn_get_held_ill(connp,
20892 				    &connp->conn_xmit_if_ill, &err);
20893 				if (err == ILL_LOOKUP_FAILED) {
20894 					ip1dbg(("ip_wput: No ill for "
20895 					    "IP_XMIT_IF\n"));
20896 					BUMP_MIB(&ipst->ips_ip_mib,
20897 					    ipIfStatsOutNoRoutes);
20898 					goto drop_pkt;
20899 				}
20900 			}
20901 
20902 			if (xmit_ill == NULL) {
20903 				ipif = conn_get_held_ipif(connp,
20904 				    &connp->conn_multicast_ipif, &err);
20905 				if (err == IPIF_LOOKUP_FAILED) {
20906 					ip1dbg(("ip_wput: No ipif for "
20907 					    "multicast\n"));
20908 					BUMP_MIB(&ipst->ips_ip_mib,
20909 					    ipIfStatsOutNoRoutes);
20910 					goto drop_pkt;
20911 				}
20912 			}
20913 			if (xmit_ill != NULL) {
20914 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20915 				if (ipif == NULL) {
20916 					ip1dbg(("ip_wput: No ipif for "
20917 					    "IP_XMIT_IF\n"));
20918 					BUMP_MIB(&ipst->ips_ip_mib,
20919 					    ipIfStatsOutNoRoutes);
20920 					goto drop_pkt;
20921 				}
20922 			} else if (ipif == NULL || ipif->ipif_isv6) {
20923 				/*
20924 				 * We must do this ipif determination here
20925 				 * else we could pass through ip_newroute
20926 				 * and come back here without the conn context.
20927 				 *
20928 				 * Note: we do late binding i.e. we bind to
20929 				 * the interface when the first packet is sent.
20930 				 * For performance reasons we do not rebind on
20931 				 * each packet but keep the binding until the
20932 				 * next IP_MULTICAST_IF option.
20933 				 *
20934 				 * conn_multicast_{ipif,ill} are shared between
20935 				 * IPv4 and IPv6 and AF_INET6 sockets can
20936 				 * send both IPv4 and IPv6 packets. Hence
20937 				 * we have to check that "isv6" matches above.
20938 				 */
20939 				if (ipif != NULL)
20940 					ipif_refrele(ipif);
20941 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20942 				if (ipif == NULL) {
20943 					ip1dbg(("ip_wput: No ipif for "
20944 					    "multicast\n"));
20945 					BUMP_MIB(&ipst->ips_ip_mib,
20946 					    ipIfStatsOutNoRoutes);
20947 					goto drop_pkt;
20948 				}
20949 				err = conn_set_held_ipif(connp,
20950 				    &connp->conn_multicast_ipif, ipif);
20951 				if (err == IPIF_LOOKUP_FAILED) {
20952 					ipif_refrele(ipif);
20953 					ip1dbg(("ip_wput: No ipif for "
20954 					    "multicast\n"));
20955 					BUMP_MIB(&ipst->ips_ip_mib,
20956 					    ipIfStatsOutNoRoutes);
20957 					goto drop_pkt;
20958 				}
20959 			}
20960 		}
20961 		ASSERT(!ipif->ipif_isv6);
20962 		/*
20963 		 * As we may lose the conn by the time we reach ip_wput_ire,
20964 		 * we copy conn_multicast_loop and conn_dontroute on to an
20965 		 * ipsec_out. In case if this datagram goes out secure,
20966 		 * we need the ill_index also. Copy that also into the
20967 		 * ipsec_out.
20968 		 */
20969 		if (mctl_present) {
20970 			io = (ipsec_out_t *)first_mp->b_rptr;
20971 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20972 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20973 		} else {
20974 			ASSERT(mp == first_mp);
20975 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20976 			    BPRI_HI)) == NULL) {
20977 				ipif_refrele(ipif);
20978 				first_mp = mp;
20979 				goto discard_pkt;
20980 			}
20981 			first_mp->b_datap->db_type = M_CTL;
20982 			first_mp->b_wptr += sizeof (ipsec_info_t);
20983 			/* ipsec_out_secure is B_FALSE now */
20984 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20985 			io = (ipsec_out_t *)first_mp->b_rptr;
20986 			io->ipsec_out_type = IPSEC_OUT;
20987 			io->ipsec_out_len = sizeof (ipsec_out_t);
20988 			io->ipsec_out_use_global_policy = B_TRUE;
20989 			io->ipsec_out_ns = ipst->ips_netstack;
20990 			first_mp->b_cont = mp;
20991 			mctl_present = B_TRUE;
20992 		}
20993 		if (attach_ill != NULL) {
20994 			ASSERT(attach_ill == ipif->ipif_ill);
20995 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20996 
20997 			/*
20998 			 * Check if we need an ire that will not be
20999 			 * looked up by anybody else i.e. HIDDEN.
21000 			 */
21001 			if (ill_is_probeonly(attach_ill)) {
21002 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21003 			}
21004 			io->ipsec_out_ill_index =
21005 			    attach_ill->ill_phyint->phyint_ifindex;
21006 			io->ipsec_out_attach_if = B_TRUE;
21007 		} else {
21008 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21009 			io->ipsec_out_ill_index =
21010 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21011 		}
21012 		if (connp != NULL) {
21013 			io->ipsec_out_multicast_loop =
21014 			    connp->conn_multicast_loop;
21015 			io->ipsec_out_dontroute = connp->conn_dontroute;
21016 			io->ipsec_out_zoneid = connp->conn_zoneid;
21017 		}
21018 		/*
21019 		 * If the application uses IP_MULTICAST_IF with
21020 		 * different logical addresses of the same ILL, we
21021 		 * need to make sure that the soruce address of
21022 		 * the packet matches the logical IP address used
21023 		 * in the option. We do it by initializing ipha_src
21024 		 * here. This should keep IPsec also happy as
21025 		 * when we return from IPsec processing, we don't
21026 		 * have to worry about getting the right address on
21027 		 * the packet. Thus it is sufficient to look for
21028 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21029 		 * MATCH_IRE_IPIF.
21030 		 *
21031 		 * NOTE : We need to do it for non-secure case also as
21032 		 * this might go out secure if there is a global policy
21033 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21034 		 * address, the source should be initialized already and
21035 		 * hence we won't be initializing here.
21036 		 *
21037 		 * As we do not have the ire yet, it is possible that
21038 		 * we set the source address here and then later discover
21039 		 * that the ire implies the source address to be assigned
21040 		 * through the RTF_SETSRC flag.
21041 		 * In that case, the setsrc variable will remind us
21042 		 * that overwritting the source address by the one
21043 		 * of the RTF_SETSRC-flagged ire is allowed.
21044 		 */
21045 		if (ipha->ipha_src == INADDR_ANY &&
21046 		    (connp == NULL || !connp->conn_unspec_src)) {
21047 			ipha->ipha_src = ipif->ipif_src_addr;
21048 			setsrc = RTF_SETSRC;
21049 		}
21050 		/*
21051 		 * Find an IRE which matches the destination and the outgoing
21052 		 * queue (i.e. the outgoing interface.)
21053 		 * For loopback use a unicast IP address for
21054 		 * the ire lookup.
21055 		 */
21056 		if (IS_LOOPBACK(ipif->ipif_ill))
21057 			dst = ipif->ipif_lcl_addr;
21058 
21059 		/*
21060 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
21061 		 * We don't need to lookup ire in ctable as the packet
21062 		 * needs to be sent to the destination through the specified
21063 		 * ill irrespective of ires in the cache table.
21064 		 */
21065 		ire = NULL;
21066 		if (xmit_ill == NULL) {
21067 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21068 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21069 		}
21070 
21071 		/*
21072 		 * refrele attach_ill as its not needed anymore.
21073 		 */
21074 		if (attach_ill != NULL) {
21075 			ill_refrele(attach_ill);
21076 			attach_ill = NULL;
21077 		}
21078 
21079 		if (ire == NULL) {
21080 			/*
21081 			 * Multicast loopback and multicast forwarding is
21082 			 * done in ip_wput_ire.
21083 			 *
21084 			 * Mark this packet to make it be delivered to
21085 			 * ip_wput_ire after the new ire has been
21086 			 * created.
21087 			 *
21088 			 * The call to ip_newroute_ipif takes into account
21089 			 * the setsrc reminder. In any case, we take care
21090 			 * of the RTF_MULTIRT flag.
21091 			 */
21092 			mp->b_prev = mp->b_next = NULL;
21093 			if (xmit_ill == NULL ||
21094 			    xmit_ill->ill_ipif_up_count > 0) {
21095 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21096 				    setsrc | RTF_MULTIRT, zoneid, infop);
21097 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21098 				    "ip_wput_end: q %p (%S)", q, "noire");
21099 			} else {
21100 				freemsg(first_mp);
21101 			}
21102 			ipif_refrele(ipif);
21103 			if (xmit_ill != NULL)
21104 				ill_refrele(xmit_ill);
21105 			if (need_decref)
21106 				CONN_DEC_REF(connp);
21107 			return;
21108 		}
21109 
21110 		ipif_refrele(ipif);
21111 		ipif = NULL;
21112 		ASSERT(xmit_ill == NULL);
21113 
21114 		/*
21115 		 * Honor the RTF_SETSRC flag for multicast packets,
21116 		 * if allowed by the setsrc reminder.
21117 		 */
21118 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21119 			ipha->ipha_src = ire->ire_src_addr;
21120 		}
21121 
21122 		/*
21123 		 * Unconditionally force the TTL to 1 for
21124 		 * multirouted multicast packets:
21125 		 * multirouted multicast should not cross
21126 		 * multicast routers.
21127 		 */
21128 		if (ire->ire_flags & RTF_MULTIRT) {
21129 			if (ipha->ipha_ttl > 1) {
21130 				ip2dbg(("ip_wput: forcing multicast "
21131 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21132 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21133 				ipha->ipha_ttl = 1;
21134 			}
21135 		}
21136 	} else {
21137 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21138 		if ((ire != NULL) && (ire->ire_type &
21139 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21140 			ignore_dontroute = B_TRUE;
21141 			ignore_nexthop = B_TRUE;
21142 		}
21143 		if (ire != NULL) {
21144 			ire_refrele(ire);
21145 			ire = NULL;
21146 		}
21147 		/*
21148 		 * Guard against coming in from arp in which case conn is NULL.
21149 		 * Also guard against non M_DATA with dontroute set but
21150 		 * destined to local, loopback or broadcast addresses.
21151 		 */
21152 		if (connp != NULL && connp->conn_dontroute &&
21153 		    !ignore_dontroute) {
21154 dontroute:
21155 			/*
21156 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21157 			 * routing protocols from seeing false direct
21158 			 * connectivity.
21159 			 */
21160 			ipha->ipha_ttl = 1;
21161 			/*
21162 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
21163 			 * along with SO_DONTROUTE, higher precedence is
21164 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
21165 			 */
21166 			if (connp->conn_xmit_if_ill == NULL) {
21167 				/* If suitable ipif not found, drop packet */
21168 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
21169 				    ipst);
21170 				if (dst_ipif == NULL) {
21171 					ip1dbg(("ip_wput: no route for "
21172 					    "dst using SO_DONTROUTE\n"));
21173 					BUMP_MIB(&ipst->ips_ip_mib,
21174 					    ipIfStatsOutNoRoutes);
21175 					mp->b_prev = mp->b_next = NULL;
21176 					if (first_mp == NULL)
21177 						first_mp = mp;
21178 					goto drop_pkt;
21179 				} else {
21180 					/*
21181 					 * If suitable ipif has been found, set
21182 					 * xmit_ill to the corresponding
21183 					 * ipif_ill because we'll be following
21184 					 * the IP_XMIT_IF logic.
21185 					 */
21186 					ASSERT(xmit_ill == NULL);
21187 					xmit_ill = dst_ipif->ipif_ill;
21188 					mutex_enter(&xmit_ill->ill_lock);
21189 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
21190 						mutex_exit(&xmit_ill->ill_lock);
21191 						xmit_ill = NULL;
21192 						ipif_refrele(dst_ipif);
21193 						ip1dbg(("ip_wput: no route for"
21194 						    " dst using"
21195 						    " SO_DONTROUTE\n"));
21196 						BUMP_MIB(&ipst->ips_ip_mib,
21197 						    ipIfStatsOutNoRoutes);
21198 						mp->b_prev = mp->b_next = NULL;
21199 						if (first_mp == NULL)
21200 							first_mp = mp;
21201 						goto drop_pkt;
21202 					}
21203 					ill_refhold_locked(xmit_ill);
21204 					mutex_exit(&xmit_ill->ill_lock);
21205 					ipif_refrele(dst_ipif);
21206 				}
21207 			}
21208 
21209 		}
21210 		/*
21211 		 * If we are bound to IPIF_NOFAILOVER address, look for
21212 		 * an IRE_CACHE matching the ill.
21213 		 */
21214 send_from_ill:
21215 		if (attach_ill != NULL) {
21216 			ipif_t	*attach_ipif;
21217 
21218 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21219 
21220 			/*
21221 			 * Check if we need an ire that will not be
21222 			 * looked up by anybody else i.e. HIDDEN.
21223 			 */
21224 			if (ill_is_probeonly(attach_ill)) {
21225 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21226 			}
21227 
21228 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21229 			if (attach_ipif == NULL) {
21230 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21231 				goto discard_pkt;
21232 			}
21233 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21234 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21235 			ipif_refrele(attach_ipif);
21236 		} else if (xmit_ill != NULL || (connp != NULL &&
21237 		    connp->conn_xmit_if_ill != NULL)) {
21238 			/*
21239 			 * Mark this packet as originated locally
21240 			 */
21241 			mp->b_prev = mp->b_next = NULL;
21242 			/*
21243 			 * xmit_ill could be NULL if SO_DONTROUTE
21244 			 * is also set.
21245 			 */
21246 			if (xmit_ill == NULL) {
21247 				xmit_ill = conn_get_held_ill(connp,
21248 				    &connp->conn_xmit_if_ill, &err);
21249 				if (err == ILL_LOOKUP_FAILED) {
21250 					BUMP_MIB(&ipst->ips_ip_mib,
21251 					    ipIfStatsOutDiscards);
21252 					if (need_decref)
21253 						CONN_DEC_REF(connp);
21254 					freemsg(first_mp);
21255 					return;
21256 				}
21257 				if (xmit_ill == NULL) {
21258 					if (connp->conn_dontroute)
21259 						goto dontroute;
21260 					goto send_from_ill;
21261 				}
21262 			}
21263 			/*
21264 			 * Could be SO_DONTROUTE case also.
21265 			 * check at least one interface is UP as
21266 			 * specified by this ILL
21267 			 */
21268 			if (xmit_ill->ill_ipif_up_count > 0) {
21269 				ipif_t *ipif;
21270 
21271 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21272 				if (ipif == NULL) {
21273 					ip1dbg(("ip_output: "
21274 					    "xmit_ill NULL ipif\n"));
21275 					goto drop_pkt;
21276 				}
21277 				/*
21278 				 * Look for a ire that is part of the group,
21279 				 * if found use it else call ip_newroute_ipif.
21280 				 * IPCL_ZONEID is not used for matching because
21281 				 * IP_ALLZONES option is valid only when the
21282 				 * ill is accessible from all zones i.e has a
21283 				 * valid ipif in all zones.
21284 				 */
21285 				match_flags = MATCH_IRE_ILL_GROUP |
21286 				    MATCH_IRE_SECATTR;
21287 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21288 				    MBLK_GETLABEL(mp), match_flags, ipst);
21289 				/*
21290 				 * If an ire exists use it or else create
21291 				 * an ire but don't add it to the cache.
21292 				 * Adding an ire may cause issues with
21293 				 * asymmetric routing.
21294 				 * In case of multiroute always act as if
21295 				 * ire does not exist.
21296 				 */
21297 				if (ire == NULL ||
21298 				    ire->ire_flags & RTF_MULTIRT) {
21299 					if (ire != NULL)
21300 						ire_refrele(ire);
21301 					ip_newroute_ipif(q, first_mp, ipif,
21302 					    dst, connp, 0, zoneid, infop);
21303 					ipif_refrele(ipif);
21304 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21305 					ill_refrele(xmit_ill);
21306 					if (need_decref)
21307 						CONN_DEC_REF(connp);
21308 					return;
21309 				}
21310 				ipif_refrele(ipif);
21311 			} else {
21312 				goto drop_pkt;
21313 			}
21314 		} else if (ip_nexthop || (connp != NULL &&
21315 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21316 			if (!ip_nexthop) {
21317 				ip_nexthop = B_TRUE;
21318 				nexthop_addr = connp->conn_nexthop_v4;
21319 			}
21320 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21321 			    MATCH_IRE_GW;
21322 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21323 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21324 		} else {
21325 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21326 			    ipst);
21327 		}
21328 		if (!ire) {
21329 			/*
21330 			 * Make sure we don't load spread if this
21331 			 * is IPIF_NOFAILOVER case.
21332 			 */
21333 			if ((attach_ill != NULL) ||
21334 			    (ip_nexthop && !ignore_nexthop)) {
21335 				if (mctl_present) {
21336 					io = (ipsec_out_t *)first_mp->b_rptr;
21337 					ASSERT(first_mp->b_datap->db_type ==
21338 					    M_CTL);
21339 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21340 				} else {
21341 					ASSERT(mp == first_mp);
21342 					first_mp = allocb(
21343 					    sizeof (ipsec_info_t), BPRI_HI);
21344 					if (first_mp == NULL) {
21345 						first_mp = mp;
21346 						goto discard_pkt;
21347 					}
21348 					first_mp->b_datap->db_type = M_CTL;
21349 					first_mp->b_wptr +=
21350 					    sizeof (ipsec_info_t);
21351 					/* ipsec_out_secure is B_FALSE now */
21352 					bzero(first_mp->b_rptr,
21353 					    sizeof (ipsec_info_t));
21354 					io = (ipsec_out_t *)first_mp->b_rptr;
21355 					io->ipsec_out_type = IPSEC_OUT;
21356 					io->ipsec_out_len =
21357 					    sizeof (ipsec_out_t);
21358 					io->ipsec_out_use_global_policy =
21359 					    B_TRUE;
21360 					io->ipsec_out_ns = ipst->ips_netstack;
21361 					first_mp->b_cont = mp;
21362 					mctl_present = B_TRUE;
21363 				}
21364 				if (attach_ill != NULL) {
21365 					io->ipsec_out_ill_index = attach_ill->
21366 					    ill_phyint->phyint_ifindex;
21367 					io->ipsec_out_attach_if = B_TRUE;
21368 				} else {
21369 					io->ipsec_out_ip_nexthop = ip_nexthop;
21370 					io->ipsec_out_nexthop_addr =
21371 					    nexthop_addr;
21372 				}
21373 			}
21374 noirefound:
21375 			/*
21376 			 * Mark this packet as having originated on
21377 			 * this machine.  This will be noted in
21378 			 * ire_add_then_send, which needs to know
21379 			 * whether to run it back through ip_wput or
21380 			 * ip_rput following successful resolution.
21381 			 */
21382 			mp->b_prev = NULL;
21383 			mp->b_next = NULL;
21384 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21385 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21386 			    "ip_wput_end: q %p (%S)", q, "newroute");
21387 			if (attach_ill != NULL)
21388 				ill_refrele(attach_ill);
21389 			if (xmit_ill != NULL)
21390 				ill_refrele(xmit_ill);
21391 			if (need_decref)
21392 				CONN_DEC_REF(connp);
21393 			return;
21394 		}
21395 	}
21396 
21397 	/* We now know where we are going with it. */
21398 
21399 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21400 	    "ip_wput_end: q %p (%S)", q, "end");
21401 
21402 	/*
21403 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21404 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21405 	 */
21406 	if (ire->ire_flags & RTF_MULTIRT) {
21407 		/*
21408 		 * Force the TTL of multirouted packets if required.
21409 		 * The TTL of such packets is bounded by the
21410 		 * ip_multirt_ttl ndd variable.
21411 		 */
21412 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21413 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21414 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21415 			    "(was %d), dst 0x%08x\n",
21416 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21417 			    ntohl(ire->ire_addr)));
21418 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21419 		}
21420 		/*
21421 		 * At this point, we check to see if there are any pending
21422 		 * unresolved routes. ire_multirt_resolvable()
21423 		 * checks in O(n) that all IRE_OFFSUBNET ire
21424 		 * entries for the packet's destination and
21425 		 * flagged RTF_MULTIRT are currently resolved.
21426 		 * If some remain unresolved, we make a copy
21427 		 * of the current message. It will be used
21428 		 * to initiate additional route resolutions.
21429 		 */
21430 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21431 		    MBLK_GETLABEL(first_mp), ipst);
21432 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21433 		    "multirt_need_resolve %d, first_mp %p\n",
21434 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21435 		if (multirt_need_resolve) {
21436 			copy_mp = copymsg(first_mp);
21437 			if (copy_mp != NULL) {
21438 				MULTIRT_DEBUG_TAG(copy_mp);
21439 			}
21440 		}
21441 	}
21442 
21443 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21444 	/*
21445 	 * Try to resolve another multiroute if
21446 	 * ire_multirt_resolvable() deemed it necessary.
21447 	 * At this point, we need to distinguish
21448 	 * multicasts from other packets. For multicasts,
21449 	 * we call ip_newroute_ipif() and request that both
21450 	 * multirouting and setsrc flags are checked.
21451 	 */
21452 	if (copy_mp != NULL) {
21453 		if (CLASSD(dst)) {
21454 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21455 			if (ipif) {
21456 				ASSERT(infop->ip_opt_ill_index == 0);
21457 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21458 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21459 				ipif_refrele(ipif);
21460 			} else {
21461 				MULTIRT_DEBUG_UNTAG(copy_mp);
21462 				freemsg(copy_mp);
21463 				copy_mp = NULL;
21464 			}
21465 		} else {
21466 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21467 		}
21468 	}
21469 	if (attach_ill != NULL)
21470 		ill_refrele(attach_ill);
21471 	if (xmit_ill != NULL)
21472 		ill_refrele(xmit_ill);
21473 	if (need_decref)
21474 		CONN_DEC_REF(connp);
21475 	return;
21476 
21477 icmp_parameter_problem:
21478 	/* could not have originated externally */
21479 	ASSERT(mp->b_prev == NULL);
21480 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21481 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21482 		/* it's the IP header length that's in trouble */
21483 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21484 		first_mp = NULL;
21485 	}
21486 
21487 discard_pkt:
21488 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21489 drop_pkt:
21490 	ip1dbg(("ip_wput: dropped packet\n"));
21491 	if (ire != NULL)
21492 		ire_refrele(ire);
21493 	if (need_decref)
21494 		CONN_DEC_REF(connp);
21495 	freemsg(first_mp);
21496 	if (attach_ill != NULL)
21497 		ill_refrele(attach_ill);
21498 	if (xmit_ill != NULL)
21499 		ill_refrele(xmit_ill);
21500 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21501 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21502 }
21503 
21504 /*
21505  * If this is a conn_t queue, then we pass in the conn. This includes the
21506  * zoneid.
21507  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21508  * in which case we use the global zoneid since those are all part of
21509  * the global zone.
21510  */
21511 void
21512 ip_wput(queue_t *q, mblk_t *mp)
21513 {
21514 	if (CONN_Q(q))
21515 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21516 	else
21517 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21518 }
21519 
21520 /*
21521  *
21522  * The following rules must be observed when accessing any ipif or ill
21523  * that has been cached in the conn. Typically conn_nofailover_ill,
21524  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21525  *
21526  * Access: The ipif or ill pointed to from the conn can be accessed under
21527  * the protection of the conn_lock or after it has been refheld under the
21528  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21529  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21530  * The reason for this is that a concurrent unplumb could actually be
21531  * cleaning up these cached pointers by walking the conns and might have
21532  * finished cleaning up the conn in question. The macros check that an
21533  * unplumb has not yet started on the ipif or ill.
21534  *
21535  * Caching: An ipif or ill pointer may be cached in the conn only after
21536  * making sure that an unplumb has not started. So the caching is done
21537  * while holding both the conn_lock and the ill_lock and after using the
21538  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21539  * flag before starting the cleanup of conns.
21540  *
21541  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21542  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21543  * or a reference to the ipif or a reference to an ire that references the
21544  * ipif. An ipif does not change its ill except for failover/failback. Since
21545  * failover/failback happens only after bringing down the ipif and making sure
21546  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21547  * the above holds.
21548  */
21549 ipif_t *
21550 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21551 {
21552 	ipif_t	*ipif;
21553 	ill_t	*ill;
21554 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21555 
21556 	*err = 0;
21557 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21558 	mutex_enter(&connp->conn_lock);
21559 	ipif = *ipifp;
21560 	if (ipif != NULL) {
21561 		ill = ipif->ipif_ill;
21562 		mutex_enter(&ill->ill_lock);
21563 		if (IPIF_CAN_LOOKUP(ipif)) {
21564 			ipif_refhold_locked(ipif);
21565 			mutex_exit(&ill->ill_lock);
21566 			mutex_exit(&connp->conn_lock);
21567 			rw_exit(&ipst->ips_ill_g_lock);
21568 			return (ipif);
21569 		} else {
21570 			*err = IPIF_LOOKUP_FAILED;
21571 		}
21572 		mutex_exit(&ill->ill_lock);
21573 	}
21574 	mutex_exit(&connp->conn_lock);
21575 	rw_exit(&ipst->ips_ill_g_lock);
21576 	return (NULL);
21577 }
21578 
21579 ill_t *
21580 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21581 {
21582 	ill_t	*ill;
21583 
21584 	*err = 0;
21585 	mutex_enter(&connp->conn_lock);
21586 	ill = *illp;
21587 	if (ill != NULL) {
21588 		mutex_enter(&ill->ill_lock);
21589 		if (ILL_CAN_LOOKUP(ill)) {
21590 			ill_refhold_locked(ill);
21591 			mutex_exit(&ill->ill_lock);
21592 			mutex_exit(&connp->conn_lock);
21593 			return (ill);
21594 		} else {
21595 			*err = ILL_LOOKUP_FAILED;
21596 		}
21597 		mutex_exit(&ill->ill_lock);
21598 	}
21599 	mutex_exit(&connp->conn_lock);
21600 	return (NULL);
21601 }
21602 
21603 static int
21604 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21605 {
21606 	ill_t	*ill;
21607 
21608 	ill = ipif->ipif_ill;
21609 	mutex_enter(&connp->conn_lock);
21610 	mutex_enter(&ill->ill_lock);
21611 	if (IPIF_CAN_LOOKUP(ipif)) {
21612 		*ipifp = ipif;
21613 		mutex_exit(&ill->ill_lock);
21614 		mutex_exit(&connp->conn_lock);
21615 		return (0);
21616 	}
21617 	mutex_exit(&ill->ill_lock);
21618 	mutex_exit(&connp->conn_lock);
21619 	return (IPIF_LOOKUP_FAILED);
21620 }
21621 
21622 /*
21623  * This is called if the outbound datagram needs fragmentation.
21624  *
21625  * NOTE : This function does not ire_refrele the ire argument passed in.
21626  */
21627 static void
21628 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21629     ip_stack_t *ipst)
21630 {
21631 	ipha_t		*ipha;
21632 	mblk_t		*mp;
21633 	uint32_t	v_hlen_tos_len;
21634 	uint32_t	max_frag;
21635 	uint32_t	frag_flag;
21636 	boolean_t	dont_use;
21637 
21638 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21639 		mp = ipsec_mp->b_cont;
21640 	} else {
21641 		mp = ipsec_mp;
21642 	}
21643 
21644 	ipha = (ipha_t *)mp->b_rptr;
21645 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21646 
21647 #ifdef	_BIG_ENDIAN
21648 #define	V_HLEN	(v_hlen_tos_len >> 24)
21649 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21650 #else
21651 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21652 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21653 #endif
21654 
21655 #ifndef SPEED_BEFORE_SAFETY
21656 	/*
21657 	 * Check that ipha_length is consistent with
21658 	 * the mblk length
21659 	 */
21660 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21661 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21662 		    LENGTH, msgdsize(mp)));
21663 		freemsg(ipsec_mp);
21664 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21665 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21666 		    "packet length mismatch");
21667 		return;
21668 	}
21669 #endif
21670 	/*
21671 	 * Don't use frag_flag if pre-built packet or source
21672 	 * routed or if multicast (since multicast packets do not solicit
21673 	 * ICMP "packet too big" messages). Get the values of
21674 	 * max_frag and frag_flag atomically by acquiring the
21675 	 * ire_lock.
21676 	 */
21677 	mutex_enter(&ire->ire_lock);
21678 	max_frag = ire->ire_max_frag;
21679 	frag_flag = ire->ire_frag_flag;
21680 	mutex_exit(&ire->ire_lock);
21681 
21682 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21683 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21684 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21685 
21686 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21687 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21688 }
21689 
21690 /*
21691  * Used for deciding the MSS size for the upper layer. Thus
21692  * we need to check the outbound policy values in the conn.
21693  */
21694 int
21695 conn_ipsec_length(conn_t *connp)
21696 {
21697 	ipsec_latch_t *ipl;
21698 
21699 	ipl = connp->conn_latch;
21700 	if (ipl == NULL)
21701 		return (0);
21702 
21703 	if (ipl->ipl_out_policy == NULL)
21704 		return (0);
21705 
21706 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21707 }
21708 
21709 /*
21710  * Returns an estimate of the IPsec headers size. This is used if
21711  * we don't want to call into IPsec to get the exact size.
21712  */
21713 int
21714 ipsec_out_extra_length(mblk_t *ipsec_mp)
21715 {
21716 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21717 	ipsec_action_t *a;
21718 
21719 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21720 	if (!io->ipsec_out_secure)
21721 		return (0);
21722 
21723 	a = io->ipsec_out_act;
21724 
21725 	if (a == NULL) {
21726 		ASSERT(io->ipsec_out_policy != NULL);
21727 		a = io->ipsec_out_policy->ipsp_act;
21728 	}
21729 	ASSERT(a != NULL);
21730 
21731 	return (a->ipa_ovhd);
21732 }
21733 
21734 /*
21735  * Returns an estimate of the IPsec headers size. This is used if
21736  * we don't want to call into IPsec to get the exact size.
21737  */
21738 int
21739 ipsec_in_extra_length(mblk_t *ipsec_mp)
21740 {
21741 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21742 	ipsec_action_t *a;
21743 
21744 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21745 
21746 	a = ii->ipsec_in_action;
21747 	return (a == NULL ? 0 : a->ipa_ovhd);
21748 }
21749 
21750 /*
21751  * If there are any source route options, return the true final
21752  * destination. Otherwise, return the destination.
21753  */
21754 ipaddr_t
21755 ip_get_dst(ipha_t *ipha)
21756 {
21757 	ipoptp_t	opts;
21758 	uchar_t		*opt;
21759 	uint8_t		optval;
21760 	uint8_t		optlen;
21761 	ipaddr_t	dst;
21762 	uint32_t off;
21763 
21764 	dst = ipha->ipha_dst;
21765 
21766 	if (IS_SIMPLE_IPH(ipha))
21767 		return (dst);
21768 
21769 	for (optval = ipoptp_first(&opts, ipha);
21770 	    optval != IPOPT_EOL;
21771 	    optval = ipoptp_next(&opts)) {
21772 		opt = opts.ipoptp_cur;
21773 		optlen = opts.ipoptp_len;
21774 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21775 		switch (optval) {
21776 		case IPOPT_SSRR:
21777 		case IPOPT_LSRR:
21778 			off = opt[IPOPT_OFFSET];
21779 			/*
21780 			 * If one of the conditions is true, it means
21781 			 * end of options and dst already has the right
21782 			 * value.
21783 			 */
21784 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21785 				off = optlen - IP_ADDR_LEN;
21786 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21787 			}
21788 			return (dst);
21789 		default:
21790 			break;
21791 		}
21792 	}
21793 
21794 	return (dst);
21795 }
21796 
21797 mblk_t *
21798 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21799     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21800 {
21801 	ipsec_out_t	*io;
21802 	mblk_t		*first_mp;
21803 	boolean_t policy_present;
21804 	ip_stack_t	*ipst;
21805 	ipsec_stack_t	*ipss;
21806 
21807 	ASSERT(ire != NULL);
21808 	ipst = ire->ire_ipst;
21809 	ipss = ipst->ips_netstack->netstack_ipsec;
21810 
21811 	first_mp = mp;
21812 	if (mp->b_datap->db_type == M_CTL) {
21813 		io = (ipsec_out_t *)first_mp->b_rptr;
21814 		/*
21815 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21816 		 *
21817 		 * 1) There is per-socket policy (including cached global
21818 		 *    policy) or a policy on the IP-in-IP tunnel.
21819 		 * 2) There is no per-socket policy, but it is
21820 		 *    a multicast packet that needs to go out
21821 		 *    on a specific interface. This is the case
21822 		 *    where (ip_wput and ip_wput_multicast) attaches
21823 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21824 		 *
21825 		 * In case (2) we check with global policy to
21826 		 * see if there is a match and set the ill_index
21827 		 * appropriately so that we can lookup the ire
21828 		 * properly in ip_wput_ipsec_out.
21829 		 */
21830 
21831 		/*
21832 		 * ipsec_out_use_global_policy is set to B_FALSE
21833 		 * in ipsec_in_to_out(). Refer to that function for
21834 		 * details.
21835 		 */
21836 		if ((io->ipsec_out_latch == NULL) &&
21837 		    (io->ipsec_out_use_global_policy)) {
21838 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21839 			    ire, connp, unspec_src, zoneid));
21840 		}
21841 		if (!io->ipsec_out_secure) {
21842 			/*
21843 			 * If this is not a secure packet, drop
21844 			 * the IPSEC_OUT mp and treat it as a clear
21845 			 * packet. This happens when we are sending
21846 			 * a ICMP reply back to a clear packet. See
21847 			 * ipsec_in_to_out() for details.
21848 			 */
21849 			mp = first_mp->b_cont;
21850 			freeb(first_mp);
21851 		}
21852 		return (mp);
21853 	}
21854 	/*
21855 	 * See whether we need to attach a global policy here. We
21856 	 * don't depend on the conn (as it could be null) for deciding
21857 	 * what policy this datagram should go through because it
21858 	 * should have happened in ip_wput if there was some
21859 	 * policy. This normally happens for connections which are not
21860 	 * fully bound preventing us from caching policies in
21861 	 * ip_bind. Packets coming from the TCP listener/global queue
21862 	 * - which are non-hard_bound - could also be affected by
21863 	 * applying policy here.
21864 	 *
21865 	 * If this packet is coming from tcp global queue or listener,
21866 	 * we will be applying policy here.  This may not be *right*
21867 	 * if these packets are coming from the detached connection as
21868 	 * it could have gone in clear before. This happens only if a
21869 	 * TCP connection started when there is no policy and somebody
21870 	 * added policy before it became detached. Thus packets of the
21871 	 * detached connection could go out secure and the other end
21872 	 * would drop it because it will be expecting in clear. The
21873 	 * converse is not true i.e if somebody starts a TCP
21874 	 * connection and deletes the policy, all the packets will
21875 	 * still go out with the policy that existed before deleting
21876 	 * because ip_unbind sends up policy information which is used
21877 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21878 	 * TCP to attach a dummy IPSEC_OUT and set
21879 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21880 	 * affect performance for normal cases, we are not doing it.
21881 	 * Thus, set policy before starting any TCP connections.
21882 	 *
21883 	 * NOTE - We might apply policy even for a hard bound connection
21884 	 * - for which we cached policy in ip_bind - if somebody added
21885 	 * global policy after we inherited the policy in ip_bind.
21886 	 * This means that the packets that were going out in clear
21887 	 * previously would start going secure and hence get dropped
21888 	 * on the other side. To fix this, TCP attaches a dummy
21889 	 * ipsec_out and make sure that we don't apply global policy.
21890 	 */
21891 	if (ipha != NULL)
21892 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21893 	else
21894 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21895 	if (!policy_present)
21896 		return (mp);
21897 
21898 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21899 	    zoneid));
21900 }
21901 
21902 ire_t *
21903 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21904 {
21905 	ipaddr_t addr;
21906 	ire_t *save_ire;
21907 	irb_t *irb;
21908 	ill_group_t *illgrp;
21909 	int	err;
21910 
21911 	save_ire = ire;
21912 	addr = ire->ire_addr;
21913 
21914 	ASSERT(ire->ire_type == IRE_BROADCAST);
21915 
21916 	illgrp = connp->conn_outgoing_ill->ill_group;
21917 	if (illgrp == NULL) {
21918 		*conn_outgoing_ill = conn_get_held_ill(connp,
21919 		    &connp->conn_outgoing_ill, &err);
21920 		if (err == ILL_LOOKUP_FAILED) {
21921 			ire_refrele(save_ire);
21922 			return (NULL);
21923 		}
21924 		return (save_ire);
21925 	}
21926 	/*
21927 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21928 	 * If it is part of the group, we need to send on the ire
21929 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21930 	 * to this group. This is okay as IP_BOUND_IF really means
21931 	 * any ill in the group. We depend on the fact that the
21932 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21933 	 * if such an ire exists. This is possible only if you have
21934 	 * at least one ill in the group that has not failed.
21935 	 *
21936 	 * First get to the ire that matches the address and group.
21937 	 *
21938 	 * We don't look for an ire with a matching zoneid because a given zone
21939 	 * won't always have broadcast ires on all ills in the group.
21940 	 */
21941 	irb = ire->ire_bucket;
21942 	rw_enter(&irb->irb_lock, RW_READER);
21943 	if (ire->ire_marks & IRE_MARK_NORECV) {
21944 		/*
21945 		 * If the current zone only has an ire broadcast for this
21946 		 * address marked NORECV, the ire we want is ahead in the
21947 		 * bucket, so we look it up deliberately ignoring the zoneid.
21948 		 */
21949 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21950 			if (ire->ire_addr != addr)
21951 				continue;
21952 			/* skip over deleted ires */
21953 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21954 				continue;
21955 		}
21956 	}
21957 	while (ire != NULL) {
21958 		/*
21959 		 * If a new interface is coming up, we could end up
21960 		 * seeing the loopback ire and the non-loopback ire
21961 		 * may not have been added yet. So check for ire_stq
21962 		 */
21963 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21964 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21965 			break;
21966 		}
21967 		ire = ire->ire_next;
21968 	}
21969 	if (ire != NULL && ire->ire_addr == addr &&
21970 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21971 		IRE_REFHOLD(ire);
21972 		rw_exit(&irb->irb_lock);
21973 		ire_refrele(save_ire);
21974 		*conn_outgoing_ill = ire_to_ill(ire);
21975 		/*
21976 		 * Refhold the ill to make the conn_outgoing_ill
21977 		 * independent of the ire. ip_wput_ire goes in a loop
21978 		 * and may refrele the ire. Since we have an ire at this
21979 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21980 		 */
21981 		ill_refhold(*conn_outgoing_ill);
21982 		return (ire);
21983 	}
21984 	rw_exit(&irb->irb_lock);
21985 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21986 	/*
21987 	 * If we can't find a suitable ire, return the original ire.
21988 	 */
21989 	return (save_ire);
21990 }
21991 
21992 /*
21993  * This function does the ire_refrele of the ire passed in as the
21994  * argument. As this function looks up more ires i.e broadcast ires,
21995  * it needs to REFRELE them. Currently, for simplicity we don't
21996  * differentiate the one passed in and looked up here. We always
21997  * REFRELE.
21998  * IPQoS Notes:
21999  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22000  * IPsec packets are done in ipsec_out_process.
22001  *
22002  */
22003 void
22004 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22005     zoneid_t zoneid)
22006 {
22007 	ipha_t		*ipha;
22008 #define	rptr	((uchar_t *)ipha)
22009 	queue_t		*stq;
22010 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22011 	uint32_t	v_hlen_tos_len;
22012 	uint32_t	ttl_protocol;
22013 	ipaddr_t	src;
22014 	ipaddr_t	dst;
22015 	uint32_t	cksum;
22016 	ipaddr_t	orig_src;
22017 	ire_t		*ire1;
22018 	mblk_t		*next_mp;
22019 	uint_t		hlen;
22020 	uint16_t	*up;
22021 	uint32_t	max_frag = ire->ire_max_frag;
22022 	ill_t		*ill = ire_to_ill(ire);
22023 	int		clusterwide;
22024 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22025 	int		ipsec_len;
22026 	mblk_t		*first_mp;
22027 	ipsec_out_t	*io;
22028 	boolean_t	conn_dontroute;		/* conn value for multicast */
22029 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22030 	boolean_t	multicast_forward;	/* Should we forward ? */
22031 	boolean_t	unspec_src;
22032 	ill_t		*conn_outgoing_ill = NULL;
22033 	ill_t		*ire_ill;
22034 	ill_t		*ire1_ill;
22035 	ill_t		*out_ill;
22036 	uint32_t 	ill_index = 0;
22037 	boolean_t	multirt_send = B_FALSE;
22038 	int		err;
22039 	ipxmit_state_t	pktxmit_state;
22040 	ip_stack_t	*ipst = ire->ire_ipst;
22041 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22042 
22043 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22044 	    "ip_wput_ire_start: q %p", q);
22045 
22046 	multicast_forward = B_FALSE;
22047 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22048 
22049 	if (ire->ire_flags & RTF_MULTIRT) {
22050 		/*
22051 		 * Multirouting case. The bucket where ire is stored
22052 		 * probably holds other RTF_MULTIRT flagged ire
22053 		 * to the destination. In this call to ip_wput_ire,
22054 		 * we attempt to send the packet through all
22055 		 * those ires. Thus, we first ensure that ire is the
22056 		 * first RTF_MULTIRT ire in the bucket,
22057 		 * before walking the ire list.
22058 		 */
22059 		ire_t *first_ire;
22060 		irb_t *irb = ire->ire_bucket;
22061 		ASSERT(irb != NULL);
22062 
22063 		/* Make sure we do not omit any multiroute ire. */
22064 		IRB_REFHOLD(irb);
22065 		for (first_ire = irb->irb_ire;
22066 		    first_ire != NULL;
22067 		    first_ire = first_ire->ire_next) {
22068 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22069 			    (first_ire->ire_addr == ire->ire_addr) &&
22070 			    !(first_ire->ire_marks &
22071 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22072 				break;
22073 			}
22074 		}
22075 
22076 		if ((first_ire != NULL) && (first_ire != ire)) {
22077 			IRE_REFHOLD(first_ire);
22078 			ire_refrele(ire);
22079 			ire = first_ire;
22080 			ill = ire_to_ill(ire);
22081 		}
22082 		IRB_REFRELE(irb);
22083 	}
22084 
22085 	/*
22086 	 * conn_outgoing_ill is used only in the broadcast loop.
22087 	 * for performance we don't grab the mutexs in the fastpath
22088 	 */
22089 	if ((connp != NULL) &&
22090 	    (connp->conn_xmit_if_ill == NULL) &&
22091 	    (ire->ire_type == IRE_BROADCAST) &&
22092 	    ((connp->conn_nofailover_ill != NULL) ||
22093 	    (connp->conn_outgoing_ill != NULL))) {
22094 		/*
22095 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22096 		 * option. So, see if this endpoint is bound to a
22097 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22098 		 * that if the interface is failed, we will still send
22099 		 * the packet on the same ill which is what we want.
22100 		 */
22101 		conn_outgoing_ill = conn_get_held_ill(connp,
22102 		    &connp->conn_nofailover_ill, &err);
22103 		if (err == ILL_LOOKUP_FAILED) {
22104 			ire_refrele(ire);
22105 			freemsg(mp);
22106 			return;
22107 		}
22108 		if (conn_outgoing_ill == NULL) {
22109 			/*
22110 			 * Choose a good ill in the group to send the
22111 			 * packets on.
22112 			 */
22113 			ire = conn_set_outgoing_ill(connp, ire,
22114 			    &conn_outgoing_ill);
22115 			if (ire == NULL) {
22116 				freemsg(mp);
22117 				return;
22118 			}
22119 		}
22120 	}
22121 
22122 	if (mp->b_datap->db_type != M_CTL) {
22123 		ipha = (ipha_t *)mp->b_rptr;
22124 	} else {
22125 		io = (ipsec_out_t *)mp->b_rptr;
22126 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22127 		ASSERT(zoneid == io->ipsec_out_zoneid);
22128 		ASSERT(zoneid != ALL_ZONES);
22129 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22130 		dst = ipha->ipha_dst;
22131 		/*
22132 		 * For the multicast case, ipsec_out carries conn_dontroute and
22133 		 * conn_multicast_loop as conn may not be available here. We
22134 		 * need this for multicast loopback and forwarding which is done
22135 		 * later in the code.
22136 		 */
22137 		if (CLASSD(dst)) {
22138 			conn_dontroute = io->ipsec_out_dontroute;
22139 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22140 			/*
22141 			 * If conn_dontroute is not set or conn_multicast_loop
22142 			 * is set, we need to do forwarding/loopback. For
22143 			 * datagrams from ip_wput_multicast, conn_dontroute is
22144 			 * set to B_TRUE and conn_multicast_loop is set to
22145 			 * B_FALSE so that we neither do forwarding nor
22146 			 * loopback.
22147 			 */
22148 			if (!conn_dontroute || conn_multicast_loop)
22149 				multicast_forward = B_TRUE;
22150 		}
22151 	}
22152 
22153 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22154 	    ire->ire_zoneid != ALL_ZONES) {
22155 		/*
22156 		 * When a zone sends a packet to another zone, we try to deliver
22157 		 * the packet under the same conditions as if the destination
22158 		 * was a real node on the network. To do so, we look for a
22159 		 * matching route in the forwarding table.
22160 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22161 		 * ip_newroute() does.
22162 		 * Note that IRE_LOCAL are special, since they are used
22163 		 * when the zoneid doesn't match in some cases. This means that
22164 		 * we need to handle ipha_src differently since ire_src_addr
22165 		 * belongs to the receiving zone instead of the sending zone.
22166 		 * When ip_restrict_interzone_loopback is set, then
22167 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22168 		 * for loopback between zones when the logical "Ethernet" would
22169 		 * have looped them back.
22170 		 */
22171 		ire_t *src_ire;
22172 
22173 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22174 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22175 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22176 		if (src_ire != NULL &&
22177 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22178 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22179 		    ire_local_same_ill_group(ire, src_ire))) {
22180 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22181 				ipha->ipha_src = src_ire->ire_src_addr;
22182 			ire_refrele(src_ire);
22183 		} else {
22184 			ire_refrele(ire);
22185 			if (conn_outgoing_ill != NULL)
22186 				ill_refrele(conn_outgoing_ill);
22187 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22188 			if (src_ire != NULL) {
22189 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22190 					ire_refrele(src_ire);
22191 					freemsg(mp);
22192 					return;
22193 				}
22194 				ire_refrele(src_ire);
22195 			}
22196 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22197 				/* Failed */
22198 				freemsg(mp);
22199 				return;
22200 			}
22201 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22202 			    ipst);
22203 			return;
22204 		}
22205 	}
22206 
22207 	if (mp->b_datap->db_type == M_CTL ||
22208 	    ipss->ipsec_outbound_v4_policy_present) {
22209 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22210 		    unspec_src, zoneid);
22211 		if (mp == NULL) {
22212 			ire_refrele(ire);
22213 			if (conn_outgoing_ill != NULL)
22214 				ill_refrele(conn_outgoing_ill);
22215 			return;
22216 		}
22217 	}
22218 
22219 	first_mp = mp;
22220 	ipsec_len = 0;
22221 
22222 	if (first_mp->b_datap->db_type == M_CTL) {
22223 		io = (ipsec_out_t *)first_mp->b_rptr;
22224 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22225 		mp = first_mp->b_cont;
22226 		ipsec_len = ipsec_out_extra_length(first_mp);
22227 		ASSERT(ipsec_len >= 0);
22228 		/* We already picked up the zoneid from the M_CTL above */
22229 		ASSERT(zoneid == io->ipsec_out_zoneid);
22230 		ASSERT(zoneid != ALL_ZONES);
22231 
22232 		/*
22233 		 * Drop M_CTL here if IPsec processing is not needed.
22234 		 * (Non-IPsec use of M_CTL extracted any information it
22235 		 * needed above).
22236 		 */
22237 		if (ipsec_len == 0) {
22238 			freeb(first_mp);
22239 			first_mp = mp;
22240 		}
22241 	}
22242 
22243 	/*
22244 	 * Fast path for ip_wput_ire
22245 	 */
22246 
22247 	ipha = (ipha_t *)mp->b_rptr;
22248 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22249 	dst = ipha->ipha_dst;
22250 
22251 	/*
22252 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22253 	 * if the socket is a SOCK_RAW type. The transport checksum should
22254 	 * be provided in the pre-built packet, so we don't need to compute it.
22255 	 * Also, other application set flags, like DF, should not be altered.
22256 	 * Other transport MUST pass down zero.
22257 	 */
22258 	ip_hdr_included = ipha->ipha_ident;
22259 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22260 
22261 	if (CLASSD(dst)) {
22262 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22263 		    ntohl(dst),
22264 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22265 		    ntohl(ire->ire_addr)));
22266 	}
22267 
22268 /* Macros to extract header fields from data already in registers */
22269 #ifdef	_BIG_ENDIAN
22270 #define	V_HLEN	(v_hlen_tos_len >> 24)
22271 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22272 #define	PROTO	(ttl_protocol & 0xFF)
22273 #else
22274 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22275 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22276 #define	PROTO	(ttl_protocol >> 8)
22277 #endif
22278 
22279 
22280 	orig_src = src = ipha->ipha_src;
22281 	/* (The loop back to "another" is explained down below.) */
22282 another:;
22283 	/*
22284 	 * Assign an ident value for this packet.  We assign idents on
22285 	 * a per destination basis out of the IRE.  There could be
22286 	 * other threads targeting the same destination, so we have to
22287 	 * arrange for a atomic increment.  Note that we use a 32-bit
22288 	 * atomic add because it has better performance than its
22289 	 * 16-bit sibling.
22290 	 *
22291 	 * If running in cluster mode and if the source address
22292 	 * belongs to a replicated service then vector through
22293 	 * cl_inet_ipident vector to allocate ip identifier
22294 	 * NOTE: This is a contract private interface with the
22295 	 * clustering group.
22296 	 */
22297 	clusterwide = 0;
22298 	if (cl_inet_ipident) {
22299 		ASSERT(cl_inet_isclusterwide);
22300 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22301 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22302 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22303 			    AF_INET, (uint8_t *)(uintptr_t)src,
22304 			    (uint8_t *)(uintptr_t)dst);
22305 			clusterwide = 1;
22306 		}
22307 	}
22308 	if (!clusterwide) {
22309 		ipha->ipha_ident =
22310 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22311 	}
22312 
22313 #ifndef _BIG_ENDIAN
22314 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22315 #endif
22316 
22317 	/*
22318 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22319 	 * This is needed to obey conn_unspec_src when packets go through
22320 	 * ip_newroute + arp.
22321 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22322 	 */
22323 	if (src == INADDR_ANY && !unspec_src) {
22324 		/*
22325 		 * Assign the appropriate source address from the IRE if none
22326 		 * was specified.
22327 		 */
22328 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22329 
22330 		/*
22331 		 * With IP multipathing, broadcast packets are sent on the ire
22332 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22333 		 * the group. However, this ire might not be in the same zone so
22334 		 * we can't always use its source address. We look for a
22335 		 * broadcast ire in the same group and in the right zone.
22336 		 */
22337 		if (ire->ire_type == IRE_BROADCAST &&
22338 		    ire->ire_zoneid != zoneid) {
22339 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22340 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22341 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22342 			if (src_ire != NULL) {
22343 				src = src_ire->ire_src_addr;
22344 				ire_refrele(src_ire);
22345 			} else {
22346 				ire_refrele(ire);
22347 				if (conn_outgoing_ill != NULL)
22348 					ill_refrele(conn_outgoing_ill);
22349 				freemsg(first_mp);
22350 				if (ill != NULL) {
22351 					BUMP_MIB(ill->ill_ip_mib,
22352 					    ipIfStatsOutDiscards);
22353 				} else {
22354 					BUMP_MIB(&ipst->ips_ip_mib,
22355 					    ipIfStatsOutDiscards);
22356 				}
22357 				return;
22358 			}
22359 		} else {
22360 			src = ire->ire_src_addr;
22361 		}
22362 
22363 		if (connp == NULL) {
22364 			ip1dbg(("ip_wput_ire: no connp and no src "
22365 			    "address for dst 0x%x, using src 0x%x\n",
22366 			    ntohl(dst),
22367 			    ntohl(src)));
22368 		}
22369 		ipha->ipha_src = src;
22370 	}
22371 	stq = ire->ire_stq;
22372 
22373 	/*
22374 	 * We only allow ire chains for broadcasts since there will
22375 	 * be multiple IRE_CACHE entries for the same multicast
22376 	 * address (one per ipif).
22377 	 */
22378 	next_mp = NULL;
22379 
22380 	/* broadcast packet */
22381 	if (ire->ire_type == IRE_BROADCAST)
22382 		goto broadcast;
22383 
22384 	/* loopback ? */
22385 	if (stq == NULL)
22386 		goto nullstq;
22387 
22388 	/* The ill_index for outbound ILL */
22389 	ill_index = Q_TO_INDEX(stq);
22390 
22391 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22392 	ttl_protocol = ((uint16_t *)ipha)[4];
22393 
22394 	/* pseudo checksum (do it in parts for IP header checksum) */
22395 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22396 
22397 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22398 		queue_t *dev_q = stq->q_next;
22399 
22400 		/* flow controlled */
22401 		if ((dev_q->q_next || dev_q->q_first) &&
22402 		    !canput(dev_q))
22403 			goto blocked;
22404 		if ((PROTO == IPPROTO_UDP) &&
22405 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22406 			hlen = (V_HLEN & 0xF) << 2;
22407 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22408 			if (*up != 0) {
22409 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22410 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22411 				/* Software checksum? */
22412 				if (DB_CKSUMFLAGS(mp) == 0) {
22413 					IP_STAT(ipst, ip_out_sw_cksum);
22414 					IP_STAT_UPDATE(ipst,
22415 					    ip_udp_out_sw_cksum_bytes,
22416 					    LENGTH - hlen);
22417 				}
22418 			}
22419 		}
22420 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22421 		hlen = (V_HLEN & 0xF) << 2;
22422 		if (PROTO == IPPROTO_TCP) {
22423 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22424 			/*
22425 			 * The packet header is processed once and for all, even
22426 			 * in the multirouting case. We disable hardware
22427 			 * checksum if the packet is multirouted, as it will be
22428 			 * replicated via several interfaces, and not all of
22429 			 * them may have this capability.
22430 			 */
22431 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22432 			    LENGTH, max_frag, ipsec_len, cksum);
22433 			/* Software checksum? */
22434 			if (DB_CKSUMFLAGS(mp) == 0) {
22435 				IP_STAT(ipst, ip_out_sw_cksum);
22436 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22437 				    LENGTH - hlen);
22438 			}
22439 		} else {
22440 			sctp_hdr_t	*sctph;
22441 
22442 			ASSERT(PROTO == IPPROTO_SCTP);
22443 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22444 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22445 			/*
22446 			 * Zero out the checksum field to ensure proper
22447 			 * checksum calculation.
22448 			 */
22449 			sctph->sh_chksum = 0;
22450 #ifdef	DEBUG
22451 			if (!skip_sctp_cksum)
22452 #endif
22453 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22454 		}
22455 	}
22456 
22457 	/*
22458 	 * If this is a multicast packet and originated from ip_wput
22459 	 * we need to do loopback and forwarding checks. If it comes
22460 	 * from ip_wput_multicast, we SHOULD not do this.
22461 	 */
22462 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22463 
22464 	/* checksum */
22465 	cksum += ttl_protocol;
22466 
22467 	/* fragment the packet */
22468 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22469 		goto fragmentit;
22470 	/*
22471 	 * Don't use frag_flag if packet is pre-built or source
22472 	 * routed or if multicast (since multicast packets do
22473 	 * not solicit ICMP "packet too big" messages).
22474 	 */
22475 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22476 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22477 	    !ip_source_route_included(ipha)) &&
22478 	    !CLASSD(ipha->ipha_dst))
22479 		ipha->ipha_fragment_offset_and_flags |=
22480 		    htons(ire->ire_frag_flag);
22481 
22482 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22483 		/* calculate IP header checksum */
22484 		cksum += ipha->ipha_ident;
22485 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22486 		cksum += ipha->ipha_fragment_offset_and_flags;
22487 
22488 		/* IP options present */
22489 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22490 		if (hlen)
22491 			goto checksumoptions;
22492 
22493 		/* calculate hdr checksum */
22494 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22495 		cksum = ~(cksum + (cksum >> 16));
22496 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22497 	}
22498 	if (ipsec_len != 0) {
22499 		/*
22500 		 * We will do the rest of the processing after
22501 		 * we come back from IPsec in ip_wput_ipsec_out().
22502 		 */
22503 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22504 
22505 		io = (ipsec_out_t *)first_mp->b_rptr;
22506 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22507 		    ill_phyint->phyint_ifindex;
22508 
22509 		ipsec_out_process(q, first_mp, ire, ill_index);
22510 		ire_refrele(ire);
22511 		if (conn_outgoing_ill != NULL)
22512 			ill_refrele(conn_outgoing_ill);
22513 		return;
22514 	}
22515 
22516 	/*
22517 	 * In most cases, the emission loop below is entered only
22518 	 * once. Only in the case where the ire holds the
22519 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22520 	 * flagged ires in the bucket, and send the packet
22521 	 * through all crossed RTF_MULTIRT routes.
22522 	 */
22523 	if (ire->ire_flags & RTF_MULTIRT) {
22524 		multirt_send = B_TRUE;
22525 	}
22526 	do {
22527 		if (multirt_send) {
22528 			irb_t *irb;
22529 			/*
22530 			 * We are in a multiple send case, need to get
22531 			 * the next ire and make a duplicate of the packet.
22532 			 * ire1 holds here the next ire to process in the
22533 			 * bucket. If multirouting is expected,
22534 			 * any non-RTF_MULTIRT ire that has the
22535 			 * right destination address is ignored.
22536 			 */
22537 			irb = ire->ire_bucket;
22538 			ASSERT(irb != NULL);
22539 
22540 			IRB_REFHOLD(irb);
22541 			for (ire1 = ire->ire_next;
22542 			    ire1 != NULL;
22543 			    ire1 = ire1->ire_next) {
22544 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22545 					continue;
22546 				if (ire1->ire_addr != ire->ire_addr)
22547 					continue;
22548 				if (ire1->ire_marks &
22549 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22550 					continue;
22551 
22552 				/* Got one */
22553 				IRE_REFHOLD(ire1);
22554 				break;
22555 			}
22556 			IRB_REFRELE(irb);
22557 
22558 			if (ire1 != NULL) {
22559 				next_mp = copyb(mp);
22560 				if ((next_mp == NULL) ||
22561 				    ((mp->b_cont != NULL) &&
22562 				    ((next_mp->b_cont =
22563 				    dupmsg(mp->b_cont)) == NULL))) {
22564 					freemsg(next_mp);
22565 					next_mp = NULL;
22566 					ire_refrele(ire1);
22567 					ire1 = NULL;
22568 				}
22569 			}
22570 
22571 			/* Last multiroute ire; don't loop anymore. */
22572 			if (ire1 == NULL) {
22573 				multirt_send = B_FALSE;
22574 			}
22575 		}
22576 
22577 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22578 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22579 		    mblk_t *, mp);
22580 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22581 		    ipst->ips_ipv4firewall_physical_out,
22582 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22583 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22584 		if (mp == NULL)
22585 			goto release_ire_and_ill;
22586 
22587 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22588 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22589 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22590 		if ((pktxmit_state == SEND_FAILED) ||
22591 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22592 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22593 			    "- packet dropped\n"));
22594 release_ire_and_ill:
22595 			ire_refrele(ire);
22596 			if (next_mp != NULL) {
22597 				freemsg(next_mp);
22598 				ire_refrele(ire1);
22599 			}
22600 			if (conn_outgoing_ill != NULL)
22601 				ill_refrele(conn_outgoing_ill);
22602 			return;
22603 		}
22604 
22605 		if (CLASSD(dst)) {
22606 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22607 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22608 			    LENGTH);
22609 		}
22610 
22611 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22612 		    "ip_wput_ire_end: q %p (%S)",
22613 		    q, "last copy out");
22614 		IRE_REFRELE(ire);
22615 
22616 		if (multirt_send) {
22617 			ASSERT(ire1);
22618 			/*
22619 			 * Proceed with the next RTF_MULTIRT ire,
22620 			 * Also set up the send-to queue accordingly.
22621 			 */
22622 			ire = ire1;
22623 			ire1 = NULL;
22624 			stq = ire->ire_stq;
22625 			mp = next_mp;
22626 			next_mp = NULL;
22627 			ipha = (ipha_t *)mp->b_rptr;
22628 			ill_index = Q_TO_INDEX(stq);
22629 			ill = (ill_t *)stq->q_ptr;
22630 		}
22631 	} while (multirt_send);
22632 	if (conn_outgoing_ill != NULL)
22633 		ill_refrele(conn_outgoing_ill);
22634 	return;
22635 
22636 	/*
22637 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22638 	 */
22639 broadcast:
22640 	{
22641 		/*
22642 		 * Avoid broadcast storms by setting the ttl to 1
22643 		 * for broadcasts. This parameter can be set
22644 		 * via ndd, so make sure that for the SO_DONTROUTE
22645 		 * case that ipha_ttl is always set to 1.
22646 		 * In the event that we are replying to incoming
22647 		 * ICMP packets, conn could be NULL.
22648 		 */
22649 		if ((connp != NULL) && connp->conn_dontroute)
22650 			ipha->ipha_ttl = 1;
22651 		else
22652 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22653 
22654 		/*
22655 		 * Note that we are not doing a IRB_REFHOLD here.
22656 		 * Actually we don't care if the list changes i.e
22657 		 * if somebody deletes an IRE from the list while
22658 		 * we drop the lock, the next time we come around
22659 		 * ire_next will be NULL and hence we won't send
22660 		 * out multiple copies which is fine.
22661 		 */
22662 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22663 		ire1 = ire->ire_next;
22664 		if (conn_outgoing_ill != NULL) {
22665 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22666 				ASSERT(ire1 == ire->ire_next);
22667 				if (ire1 != NULL && ire1->ire_addr == dst) {
22668 					ire_refrele(ire);
22669 					ire = ire1;
22670 					IRE_REFHOLD(ire);
22671 					ire1 = ire->ire_next;
22672 					continue;
22673 				}
22674 				rw_exit(&ire->ire_bucket->irb_lock);
22675 				/* Did not find a matching ill */
22676 				ip1dbg(("ip_wput_ire: broadcast with no "
22677 				    "matching IP_BOUND_IF ill %s\n",
22678 				    conn_outgoing_ill->ill_name));
22679 				freemsg(first_mp);
22680 				if (ire != NULL)
22681 					ire_refrele(ire);
22682 				ill_refrele(conn_outgoing_ill);
22683 				return;
22684 			}
22685 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22686 			/*
22687 			 * If the next IRE has the same address and is not one
22688 			 * of the two copies that we need to send, try to see
22689 			 * whether this copy should be sent at all. This
22690 			 * assumes that we insert loopbacks first and then
22691 			 * non-loopbacks. This is acheived by inserting the
22692 			 * loopback always before non-loopback.
22693 			 * This is used to send a single copy of a broadcast
22694 			 * packet out all physical interfaces that have an
22695 			 * matching IRE_BROADCAST while also looping
22696 			 * back one copy (to ip_wput_local) for each
22697 			 * matching physical interface. However, we avoid
22698 			 * sending packets out different logical that match by
22699 			 * having ipif_up/ipif_down supress duplicate
22700 			 * IRE_BROADCASTS.
22701 			 *
22702 			 * This feature is currently used to get broadcasts
22703 			 * sent to multiple interfaces, when the broadcast
22704 			 * address being used applies to multiple interfaces.
22705 			 * For example, a whole net broadcast will be
22706 			 * replicated on every connected subnet of
22707 			 * the target net.
22708 			 *
22709 			 * Each zone has its own set of IRE_BROADCASTs, so that
22710 			 * we're able to distribute inbound packets to multiple
22711 			 * zones who share a broadcast address. We avoid looping
22712 			 * back outbound packets in different zones but on the
22713 			 * same ill, as the application would see duplicates.
22714 			 *
22715 			 * If the interfaces are part of the same group,
22716 			 * we would want to send only one copy out for
22717 			 * whole group.
22718 			 *
22719 			 * This logic assumes that ire_add_v4() groups the
22720 			 * IRE_BROADCAST entries so that those with the same
22721 			 * ire_addr and ill_group are kept together.
22722 			 */
22723 			ire_ill = ire->ire_ipif->ipif_ill;
22724 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22725 				if (ire_ill->ill_group != NULL &&
22726 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22727 					/*
22728 					 * If the current zone only has an ire
22729 					 * broadcast for this address marked
22730 					 * NORECV, the ire we want is ahead in
22731 					 * the bucket, so we look it up
22732 					 * deliberately ignoring the zoneid.
22733 					 */
22734 					for (ire1 = ire->ire_bucket->irb_ire;
22735 					    ire1 != NULL;
22736 					    ire1 = ire1->ire_next) {
22737 						ire1_ill =
22738 						    ire1->ire_ipif->ipif_ill;
22739 						if (ire1->ire_addr != dst)
22740 							continue;
22741 						/* skip over the current ire */
22742 						if (ire1 == ire)
22743 							continue;
22744 						/* skip over deleted ires */
22745 						if (ire1->ire_marks &
22746 						    IRE_MARK_CONDEMNED)
22747 							continue;
22748 						/*
22749 						 * non-loopback ire in our
22750 						 * group: use it for the next
22751 						 * pass in the loop
22752 						 */
22753 						if (ire1->ire_stq != NULL &&
22754 						    ire1_ill->ill_group ==
22755 						    ire_ill->ill_group)
22756 							break;
22757 					}
22758 				}
22759 			} else {
22760 				while (ire1 != NULL && ire1->ire_addr == dst) {
22761 					ire1_ill = ire1->ire_ipif->ipif_ill;
22762 					/*
22763 					 * We can have two broadcast ires on the
22764 					 * same ill in different zones; here
22765 					 * we'll send a copy of the packet on
22766 					 * each ill and the fanout code will
22767 					 * call conn_wantpacket() to check that
22768 					 * the zone has the broadcast address
22769 					 * configured on the ill. If the two
22770 					 * ires are in the same group we only
22771 					 * send one copy up.
22772 					 */
22773 					if (ire1_ill != ire_ill &&
22774 					    (ire1_ill->ill_group == NULL ||
22775 					    ire_ill->ill_group == NULL ||
22776 					    ire1_ill->ill_group !=
22777 					    ire_ill->ill_group)) {
22778 						break;
22779 					}
22780 					ire1 = ire1->ire_next;
22781 				}
22782 			}
22783 		}
22784 		ASSERT(multirt_send == B_FALSE);
22785 		if (ire1 != NULL && ire1->ire_addr == dst) {
22786 			if ((ire->ire_flags & RTF_MULTIRT) &&
22787 			    (ire1->ire_flags & RTF_MULTIRT)) {
22788 				/*
22789 				 * We are in the multirouting case.
22790 				 * The message must be sent at least
22791 				 * on both ires. These ires have been
22792 				 * inserted AFTER the standard ones
22793 				 * in ip_rt_add(). There are thus no
22794 				 * other ire entries for the destination
22795 				 * address in the rest of the bucket
22796 				 * that do not have the RTF_MULTIRT
22797 				 * flag. We don't process a copy
22798 				 * of the message here. This will be
22799 				 * done in the final sending loop.
22800 				 */
22801 				multirt_send = B_TRUE;
22802 			} else {
22803 				next_mp = ip_copymsg(first_mp);
22804 				if (next_mp != NULL)
22805 					IRE_REFHOLD(ire1);
22806 			}
22807 		}
22808 		rw_exit(&ire->ire_bucket->irb_lock);
22809 	}
22810 
22811 	if (stq) {
22812 		/*
22813 		 * A non-NULL send-to queue means this packet is going
22814 		 * out of this machine.
22815 		 */
22816 		out_ill = (ill_t *)stq->q_ptr;
22817 
22818 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22819 		ttl_protocol = ((uint16_t *)ipha)[4];
22820 		/*
22821 		 * We accumulate the pseudo header checksum in cksum.
22822 		 * This is pretty hairy code, so watch close.  One
22823 		 * thing to keep in mind is that UDP and TCP have
22824 		 * stored their respective datagram lengths in their
22825 		 * checksum fields.  This lines things up real nice.
22826 		 */
22827 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22828 		    (src >> 16) + (src & 0xFFFF);
22829 		/*
22830 		 * We assume the udp checksum field contains the
22831 		 * length, so to compute the pseudo header checksum,
22832 		 * all we need is the protocol number and src/dst.
22833 		 */
22834 		/* Provide the checksums for UDP and TCP. */
22835 		if ((PROTO == IPPROTO_TCP) &&
22836 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22837 			/* hlen gets the number of uchar_ts in the IP header */
22838 			hlen = (V_HLEN & 0xF) << 2;
22839 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22840 			IP_STAT(ipst, ip_out_sw_cksum);
22841 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22842 			    LENGTH - hlen);
22843 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22844 		} else if (PROTO == IPPROTO_SCTP &&
22845 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22846 			sctp_hdr_t	*sctph;
22847 
22848 			hlen = (V_HLEN & 0xF) << 2;
22849 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22850 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22851 			sctph->sh_chksum = 0;
22852 #ifdef	DEBUG
22853 			if (!skip_sctp_cksum)
22854 #endif
22855 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22856 		} else {
22857 			queue_t *dev_q = stq->q_next;
22858 
22859 			if ((dev_q->q_next || dev_q->q_first) &&
22860 			    !canput(dev_q)) {
22861 blocked:
22862 				ipha->ipha_ident = ip_hdr_included;
22863 				/*
22864 				 * If we don't have a conn to apply
22865 				 * backpressure, free the message.
22866 				 * In the ire_send path, we don't know
22867 				 * the position to requeue the packet. Rather
22868 				 * than reorder packets, we just drop this
22869 				 * packet.
22870 				 */
22871 				if (ipst->ips_ip_output_queue &&
22872 				    connp != NULL &&
22873 				    caller != IRE_SEND) {
22874 					if (caller == IP_WSRV) {
22875 						connp->conn_did_putbq = 1;
22876 						(void) putbq(connp->conn_wq,
22877 						    first_mp);
22878 						conn_drain_insert(connp);
22879 						/*
22880 						 * This is the service thread,
22881 						 * and the queue is already
22882 						 * noenabled. The check for
22883 						 * canput and the putbq is not
22884 						 * atomic. So we need to check
22885 						 * again.
22886 						 */
22887 						if (canput(stq->q_next))
22888 							connp->conn_did_putbq
22889 							    = 0;
22890 						IP_STAT(ipst, ip_conn_flputbq);
22891 					} else {
22892 						/*
22893 						 * We are not the service proc.
22894 						 * ip_wsrv will be scheduled or
22895 						 * is already running.
22896 						 */
22897 						(void) putq(connp->conn_wq,
22898 						    first_mp);
22899 					}
22900 				} else {
22901 					out_ill = (ill_t *)stq->q_ptr;
22902 					BUMP_MIB(out_ill->ill_ip_mib,
22903 					    ipIfStatsOutDiscards);
22904 					freemsg(first_mp);
22905 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22906 					    "ip_wput_ire_end: q %p (%S)",
22907 					    q, "discard");
22908 				}
22909 				ire_refrele(ire);
22910 				if (next_mp) {
22911 					ire_refrele(ire1);
22912 					freemsg(next_mp);
22913 				}
22914 				if (conn_outgoing_ill != NULL)
22915 					ill_refrele(conn_outgoing_ill);
22916 				return;
22917 			}
22918 			if ((PROTO == IPPROTO_UDP) &&
22919 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22920 				/*
22921 				 * hlen gets the number of uchar_ts in the
22922 				 * IP header
22923 				 */
22924 				hlen = (V_HLEN & 0xF) << 2;
22925 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22926 				max_frag = ire->ire_max_frag;
22927 				if (*up != 0) {
22928 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22929 					    up, PROTO, hlen, LENGTH, max_frag,
22930 					    ipsec_len, cksum);
22931 					/* Software checksum? */
22932 					if (DB_CKSUMFLAGS(mp) == 0) {
22933 						IP_STAT(ipst, ip_out_sw_cksum);
22934 						IP_STAT_UPDATE(ipst,
22935 						    ip_udp_out_sw_cksum_bytes,
22936 						    LENGTH - hlen);
22937 					}
22938 				}
22939 			}
22940 		}
22941 		/*
22942 		 * Need to do this even when fragmenting. The local
22943 		 * loopback can be done without computing checksums
22944 		 * but forwarding out other interface must be done
22945 		 * after the IP checksum (and ULP checksums) have been
22946 		 * computed.
22947 		 *
22948 		 * NOTE : multicast_forward is set only if this packet
22949 		 * originated from ip_wput. For packets originating from
22950 		 * ip_wput_multicast, it is not set.
22951 		 */
22952 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22953 multi_loopback:
22954 			ip2dbg(("ip_wput: multicast, loop %d\n",
22955 			    conn_multicast_loop));
22956 
22957 			/*  Forget header checksum offload */
22958 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22959 
22960 			/*
22961 			 * Local loopback of multicasts?  Check the
22962 			 * ill.
22963 			 *
22964 			 * Note that the loopback function will not come
22965 			 * in through ip_rput - it will only do the
22966 			 * client fanout thus we need to do an mforward
22967 			 * as well.  The is different from the BSD
22968 			 * logic.
22969 			 */
22970 			if (ill != NULL) {
22971 				ilm_t	*ilm;
22972 
22973 				ILM_WALKER_HOLD(ill);
22974 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22975 				    ALL_ZONES);
22976 				ILM_WALKER_RELE(ill);
22977 				if (ilm != NULL) {
22978 					/*
22979 					 * Pass along the virtual output q.
22980 					 * ip_wput_local() will distribute the
22981 					 * packet to all the matching zones,
22982 					 * except the sending zone when
22983 					 * IP_MULTICAST_LOOP is false.
22984 					 */
22985 					ip_multicast_loopback(q, ill, first_mp,
22986 					    conn_multicast_loop ? 0 :
22987 					    IP_FF_NO_MCAST_LOOP, zoneid);
22988 				}
22989 			}
22990 			if (ipha->ipha_ttl == 0) {
22991 				/*
22992 				 * 0 => only to this host i.e. we are
22993 				 * done. We are also done if this was the
22994 				 * loopback interface since it is sufficient
22995 				 * to loopback one copy of a multicast packet.
22996 				 */
22997 				freemsg(first_mp);
22998 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22999 				    "ip_wput_ire_end: q %p (%S)",
23000 				    q, "loopback");
23001 				ire_refrele(ire);
23002 				if (conn_outgoing_ill != NULL)
23003 					ill_refrele(conn_outgoing_ill);
23004 				return;
23005 			}
23006 			/*
23007 			 * ILLF_MULTICAST is checked in ip_newroute
23008 			 * i.e. we don't need to check it here since
23009 			 * all IRE_CACHEs come from ip_newroute.
23010 			 * For multicast traffic, SO_DONTROUTE is interpreted
23011 			 * to mean only send the packet out the interface
23012 			 * (optionally specified with IP_MULTICAST_IF)
23013 			 * and do not forward it out additional interfaces.
23014 			 * RSVP and the rsvp daemon is an example of a
23015 			 * protocol and user level process that
23016 			 * handles it's own routing. Hence, it uses the
23017 			 * SO_DONTROUTE option to accomplish this.
23018 			 */
23019 
23020 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23021 			    ill != NULL) {
23022 				/* Unconditionally redo the checksum */
23023 				ipha->ipha_hdr_checksum = 0;
23024 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23025 
23026 				/*
23027 				 * If this needs to go out secure, we need
23028 				 * to wait till we finish the IPsec
23029 				 * processing.
23030 				 */
23031 				if (ipsec_len == 0 &&
23032 				    ip_mforward(ill, ipha, mp)) {
23033 					freemsg(first_mp);
23034 					ip1dbg(("ip_wput: mforward failed\n"));
23035 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23036 					    "ip_wput_ire_end: q %p (%S)",
23037 					    q, "mforward failed");
23038 					ire_refrele(ire);
23039 					if (conn_outgoing_ill != NULL)
23040 						ill_refrele(conn_outgoing_ill);
23041 					return;
23042 				}
23043 			}
23044 		}
23045 		max_frag = ire->ire_max_frag;
23046 		cksum += ttl_protocol;
23047 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23048 			/* No fragmentation required for this one. */
23049 			/*
23050 			 * Don't use frag_flag if packet is pre-built or source
23051 			 * routed or if multicast (since multicast packets do
23052 			 * not solicit ICMP "packet too big" messages).
23053 			 */
23054 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23055 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23056 			    !ip_source_route_included(ipha)) &&
23057 			    !CLASSD(ipha->ipha_dst))
23058 				ipha->ipha_fragment_offset_and_flags |=
23059 				    htons(ire->ire_frag_flag);
23060 
23061 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23062 				/* Complete the IP header checksum. */
23063 				cksum += ipha->ipha_ident;
23064 				cksum += (v_hlen_tos_len >> 16)+
23065 				    (v_hlen_tos_len & 0xFFFF);
23066 				cksum += ipha->ipha_fragment_offset_and_flags;
23067 				hlen = (V_HLEN & 0xF) -
23068 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23069 				if (hlen) {
23070 checksumoptions:
23071 					/*
23072 					 * Account for the IP Options in the IP
23073 					 * header checksum.
23074 					 */
23075 					up = (uint16_t *)(rptr+
23076 					    IP_SIMPLE_HDR_LENGTH);
23077 					do {
23078 						cksum += up[0];
23079 						cksum += up[1];
23080 						up += 2;
23081 					} while (--hlen);
23082 				}
23083 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23084 				cksum = ~(cksum + (cksum >> 16));
23085 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23086 			}
23087 			if (ipsec_len != 0) {
23088 				ipsec_out_process(q, first_mp, ire, ill_index);
23089 				if (!next_mp) {
23090 					ire_refrele(ire);
23091 					if (conn_outgoing_ill != NULL)
23092 						ill_refrele(conn_outgoing_ill);
23093 					return;
23094 				}
23095 				goto next;
23096 			}
23097 
23098 			/*
23099 			 * multirt_send has already been handled
23100 			 * for broadcast, but not yet for multicast
23101 			 * or IP options.
23102 			 */
23103 			if (next_mp == NULL) {
23104 				if (ire->ire_flags & RTF_MULTIRT) {
23105 					multirt_send = B_TRUE;
23106 				}
23107 			}
23108 
23109 			/*
23110 			 * In most cases, the emission loop below is
23111 			 * entered only once. Only in the case where
23112 			 * the ire holds the RTF_MULTIRT flag, do we loop
23113 			 * to process all RTF_MULTIRT ires in the bucket,
23114 			 * and send the packet through all crossed
23115 			 * RTF_MULTIRT routes.
23116 			 */
23117 			do {
23118 				if (multirt_send) {
23119 					irb_t *irb;
23120 
23121 					irb = ire->ire_bucket;
23122 					ASSERT(irb != NULL);
23123 					/*
23124 					 * We are in a multiple send case,
23125 					 * need to get the next IRE and make
23126 					 * a duplicate of the packet.
23127 					 */
23128 					IRB_REFHOLD(irb);
23129 					for (ire1 = ire->ire_next;
23130 					    ire1 != NULL;
23131 					    ire1 = ire1->ire_next) {
23132 						if (!(ire1->ire_flags &
23133 						    RTF_MULTIRT)) {
23134 							continue;
23135 						}
23136 						if (ire1->ire_addr !=
23137 						    ire->ire_addr) {
23138 							continue;
23139 						}
23140 						if (ire1->ire_marks &
23141 						    (IRE_MARK_CONDEMNED|
23142 						    IRE_MARK_HIDDEN)) {
23143 							continue;
23144 						}
23145 
23146 						/* Got one */
23147 						IRE_REFHOLD(ire1);
23148 						break;
23149 					}
23150 					IRB_REFRELE(irb);
23151 
23152 					if (ire1 != NULL) {
23153 						next_mp = copyb(mp);
23154 						if ((next_mp == NULL) ||
23155 						    ((mp->b_cont != NULL) &&
23156 						    ((next_mp->b_cont =
23157 						    dupmsg(mp->b_cont))
23158 						    == NULL))) {
23159 							freemsg(next_mp);
23160 							next_mp = NULL;
23161 							ire_refrele(ire1);
23162 							ire1 = NULL;
23163 						}
23164 					}
23165 
23166 					/*
23167 					 * Last multiroute ire; don't loop
23168 					 * anymore. The emission is over
23169 					 * and next_mp is NULL.
23170 					 */
23171 					if (ire1 == NULL) {
23172 						multirt_send = B_FALSE;
23173 					}
23174 				}
23175 
23176 				out_ill = ire_to_ill(ire);
23177 				DTRACE_PROBE4(ip4__physical__out__start,
23178 				    ill_t *, NULL,
23179 				    ill_t *, out_ill,
23180 				    ipha_t *, ipha, mblk_t *, mp);
23181 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23182 				    ipst->ips_ipv4firewall_physical_out,
23183 				    NULL, out_ill, ipha, mp, mp, ipst);
23184 				DTRACE_PROBE1(ip4__physical__out__end,
23185 				    mblk_t *, mp);
23186 				if (mp == NULL)
23187 					goto release_ire_and_ill_2;
23188 
23189 				ASSERT(ipsec_len == 0);
23190 				mp->b_prev =
23191 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23192 				DTRACE_PROBE2(ip__xmit__2,
23193 				    mblk_t *, mp, ire_t *, ire);
23194 				pktxmit_state = ip_xmit_v4(mp, ire,
23195 				    NULL, B_TRUE);
23196 				if ((pktxmit_state == SEND_FAILED) ||
23197 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23198 release_ire_and_ill_2:
23199 					if (next_mp) {
23200 						freemsg(next_mp);
23201 						ire_refrele(ire1);
23202 					}
23203 					ire_refrele(ire);
23204 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23205 					    "ip_wput_ire_end: q %p (%S)",
23206 					    q, "discard MDATA");
23207 					if (conn_outgoing_ill != NULL)
23208 						ill_refrele(conn_outgoing_ill);
23209 					return;
23210 				}
23211 
23212 				if (CLASSD(dst)) {
23213 					BUMP_MIB(out_ill->ill_ip_mib,
23214 					    ipIfStatsHCOutMcastPkts);
23215 					UPDATE_MIB(out_ill->ill_ip_mib,
23216 					    ipIfStatsHCOutMcastOctets,
23217 					    LENGTH);
23218 				} else if (ire->ire_type == IRE_BROADCAST) {
23219 					BUMP_MIB(out_ill->ill_ip_mib,
23220 					    ipIfStatsHCOutBcastPkts);
23221 				}
23222 
23223 				if (multirt_send) {
23224 					/*
23225 					 * We are in a multiple send case,
23226 					 * need to re-enter the sending loop
23227 					 * using the next ire.
23228 					 */
23229 					ire_refrele(ire);
23230 					ire = ire1;
23231 					stq = ire->ire_stq;
23232 					mp = next_mp;
23233 					next_mp = NULL;
23234 					ipha = (ipha_t *)mp->b_rptr;
23235 					ill_index = Q_TO_INDEX(stq);
23236 				}
23237 			} while (multirt_send);
23238 
23239 			if (!next_mp) {
23240 				/*
23241 				 * Last copy going out (the ultra-common
23242 				 * case).  Note that we intentionally replicate
23243 				 * the putnext rather than calling it before
23244 				 * the next_mp check in hopes of a little
23245 				 * tail-call action out of the compiler.
23246 				 */
23247 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23248 				    "ip_wput_ire_end: q %p (%S)",
23249 				    q, "last copy out(1)");
23250 				ire_refrele(ire);
23251 				if (conn_outgoing_ill != NULL)
23252 					ill_refrele(conn_outgoing_ill);
23253 				return;
23254 			}
23255 			/* More copies going out below. */
23256 		} else {
23257 			int offset;
23258 fragmentit:
23259 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23260 			/*
23261 			 * If this would generate a icmp_frag_needed message,
23262 			 * we need to handle it before we do the IPsec
23263 			 * processing. Otherwise, we need to strip the IPsec
23264 			 * headers before we send up the message to the ULPs
23265 			 * which becomes messy and difficult.
23266 			 */
23267 			if (ipsec_len != 0) {
23268 				if ((max_frag < (unsigned int)(LENGTH +
23269 				    ipsec_len)) && (offset & IPH_DF)) {
23270 					out_ill = (ill_t *)stq->q_ptr;
23271 					BUMP_MIB(out_ill->ill_ip_mib,
23272 					    ipIfStatsOutFragFails);
23273 					BUMP_MIB(out_ill->ill_ip_mib,
23274 					    ipIfStatsOutFragReqds);
23275 					ipha->ipha_hdr_checksum = 0;
23276 					ipha->ipha_hdr_checksum =
23277 					    (uint16_t)ip_csum_hdr(ipha);
23278 					icmp_frag_needed(ire->ire_stq, first_mp,
23279 					    max_frag, zoneid, ipst);
23280 					if (!next_mp) {
23281 						ire_refrele(ire);
23282 						if (conn_outgoing_ill != NULL) {
23283 							ill_refrele(
23284 							    conn_outgoing_ill);
23285 						}
23286 						return;
23287 					}
23288 				} else {
23289 					/*
23290 					 * This won't cause a icmp_frag_needed
23291 					 * message. to be generated. Send it on
23292 					 * the wire. Note that this could still
23293 					 * cause fragmentation and all we
23294 					 * do is the generation of the message
23295 					 * to the ULP if needed before IPsec.
23296 					 */
23297 					if (!next_mp) {
23298 						ipsec_out_process(q, first_mp,
23299 						    ire, ill_index);
23300 						TRACE_2(TR_FAC_IP,
23301 						    TR_IP_WPUT_IRE_END,
23302 						    "ip_wput_ire_end: q %p "
23303 						    "(%S)", q,
23304 						    "last ipsec_out_process");
23305 						ire_refrele(ire);
23306 						if (conn_outgoing_ill != NULL) {
23307 							ill_refrele(
23308 							    conn_outgoing_ill);
23309 						}
23310 						return;
23311 					}
23312 					ipsec_out_process(q, first_mp,
23313 					    ire, ill_index);
23314 				}
23315 			} else {
23316 				/*
23317 				 * Initiate IPPF processing. For
23318 				 * fragmentable packets we finish
23319 				 * all QOS packet processing before
23320 				 * calling:
23321 				 * ip_wput_ire_fragmentit->ip_wput_frag
23322 				 */
23323 
23324 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23325 					ip_process(IPP_LOCAL_OUT, &mp,
23326 					    ill_index);
23327 					if (mp == NULL) {
23328 						out_ill = (ill_t *)stq->q_ptr;
23329 						BUMP_MIB(out_ill->ill_ip_mib,
23330 						    ipIfStatsOutDiscards);
23331 						if (next_mp != NULL) {
23332 							freemsg(next_mp);
23333 							ire_refrele(ire1);
23334 						}
23335 						ire_refrele(ire);
23336 						TRACE_2(TR_FAC_IP,
23337 						    TR_IP_WPUT_IRE_END,
23338 						    "ip_wput_ire: q %p (%S)",
23339 						    q, "discard MDATA");
23340 						if (conn_outgoing_ill != NULL) {
23341 							ill_refrele(
23342 							    conn_outgoing_ill);
23343 						}
23344 						return;
23345 					}
23346 				}
23347 				if (!next_mp) {
23348 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23349 					    "ip_wput_ire_end: q %p (%S)",
23350 					    q, "last fragmentation");
23351 					ip_wput_ire_fragmentit(mp, ire,
23352 					    zoneid, ipst);
23353 					ire_refrele(ire);
23354 					if (conn_outgoing_ill != NULL)
23355 						ill_refrele(conn_outgoing_ill);
23356 					return;
23357 				}
23358 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23359 			}
23360 		}
23361 	} else {
23362 nullstq:
23363 		/* A NULL stq means the destination address is local. */
23364 		UPDATE_OB_PKT_COUNT(ire);
23365 		ire->ire_last_used_time = lbolt;
23366 		ASSERT(ire->ire_ipif != NULL);
23367 		if (!next_mp) {
23368 			/*
23369 			 * Is there an "in" and "out" for traffic local
23370 			 * to a host (loopback)?  The code in Solaris doesn't
23371 			 * explicitly draw a line in its code for in vs out,
23372 			 * so we've had to draw a line in the sand: ip_wput_ire
23373 			 * is considered to be the "output" side and
23374 			 * ip_wput_local to be the "input" side.
23375 			 */
23376 			out_ill = ire_to_ill(ire);
23377 
23378 			DTRACE_PROBE4(ip4__loopback__out__start,
23379 			    ill_t *, NULL, ill_t *, out_ill,
23380 			    ipha_t *, ipha, mblk_t *, first_mp);
23381 
23382 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23383 			    ipst->ips_ipv4firewall_loopback_out,
23384 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23385 
23386 			DTRACE_PROBE1(ip4__loopback__out_end,
23387 			    mblk_t *, first_mp);
23388 
23389 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23390 			    "ip_wput_ire_end: q %p (%S)",
23391 			    q, "local address");
23392 
23393 			if (first_mp != NULL)
23394 				ip_wput_local(q, out_ill, ipha,
23395 				    first_mp, ire, 0, ire->ire_zoneid);
23396 			ire_refrele(ire);
23397 			if (conn_outgoing_ill != NULL)
23398 				ill_refrele(conn_outgoing_ill);
23399 			return;
23400 		}
23401 
23402 		out_ill = ire_to_ill(ire);
23403 
23404 		DTRACE_PROBE4(ip4__loopback__out__start,
23405 		    ill_t *, NULL, ill_t *, out_ill,
23406 		    ipha_t *, ipha, mblk_t *, first_mp);
23407 
23408 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23409 		    ipst->ips_ipv4firewall_loopback_out,
23410 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23411 
23412 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23413 
23414 		if (first_mp != NULL)
23415 			ip_wput_local(q, out_ill, ipha,
23416 			    first_mp, ire, 0, ire->ire_zoneid);
23417 	}
23418 next:
23419 	/*
23420 	 * More copies going out to additional interfaces.
23421 	 * ire1 has already been held. We don't need the
23422 	 * "ire" anymore.
23423 	 */
23424 	ire_refrele(ire);
23425 	ire = ire1;
23426 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23427 	mp = next_mp;
23428 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23429 	ill = ire_to_ill(ire);
23430 	first_mp = mp;
23431 	if (ipsec_len != 0) {
23432 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23433 		mp = mp->b_cont;
23434 	}
23435 	dst = ire->ire_addr;
23436 	ipha = (ipha_t *)mp->b_rptr;
23437 	/*
23438 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23439 	 * Restore ipha_ident "no checksum" flag.
23440 	 */
23441 	src = orig_src;
23442 	ipha->ipha_ident = ip_hdr_included;
23443 	goto another;
23444 
23445 #undef	rptr
23446 #undef	Q_TO_INDEX
23447 }
23448 
23449 /*
23450  * Routine to allocate a message that is used to notify the ULP about MDT.
23451  * The caller may provide a pointer to the link-layer MDT capabilities,
23452  * or NULL if MDT is to be disabled on the stream.
23453  */
23454 mblk_t *
23455 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23456 {
23457 	mblk_t *mp;
23458 	ip_mdt_info_t *mdti;
23459 	ill_mdt_capab_t *idst;
23460 
23461 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23462 		DB_TYPE(mp) = M_CTL;
23463 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23464 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23465 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23466 		idst = &(mdti->mdt_capab);
23467 
23468 		/*
23469 		 * If the caller provides us with the capability, copy
23470 		 * it over into our notification message; otherwise
23471 		 * we zero out the capability portion.
23472 		 */
23473 		if (isrc != NULL)
23474 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23475 		else
23476 			bzero((caddr_t)idst, sizeof (*idst));
23477 	}
23478 	return (mp);
23479 }
23480 
23481 /*
23482  * Routine which determines whether MDT can be enabled on the destination
23483  * IRE and IPC combination, and if so, allocates and returns the MDT
23484  * notification mblk that may be used by ULP.  We also check if we need to
23485  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23486  * MDT usage in the past have been lifted.  This gets called during IP
23487  * and ULP binding.
23488  */
23489 mblk_t *
23490 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23491     ill_mdt_capab_t *mdt_cap)
23492 {
23493 	mblk_t *mp;
23494 	boolean_t rc = B_FALSE;
23495 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23496 
23497 	ASSERT(dst_ire != NULL);
23498 	ASSERT(connp != NULL);
23499 	ASSERT(mdt_cap != NULL);
23500 
23501 	/*
23502 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23503 	 * Multidata, which is handled in tcp_multisend().  This
23504 	 * is the reason why we do all these checks here, to ensure
23505 	 * that we don't enable Multidata for the cases which we
23506 	 * can't handle at the moment.
23507 	 */
23508 	do {
23509 		/* Only do TCP at the moment */
23510 		if (connp->conn_ulp != IPPROTO_TCP)
23511 			break;
23512 
23513 		/*
23514 		 * IPsec outbound policy present?  Note that we get here
23515 		 * after calling ipsec_conn_cache_policy() where the global
23516 		 * policy checking is performed.  conn_latch will be
23517 		 * non-NULL as long as there's a policy defined,
23518 		 * i.e. conn_out_enforce_policy may be NULL in such case
23519 		 * when the connection is non-secure, and hence we check
23520 		 * further if the latch refers to an outbound policy.
23521 		 */
23522 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23523 			break;
23524 
23525 		/* CGTP (multiroute) is enabled? */
23526 		if (dst_ire->ire_flags & RTF_MULTIRT)
23527 			break;
23528 
23529 		/* Outbound IPQoS enabled? */
23530 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23531 			/*
23532 			 * In this case, we disable MDT for this and all
23533 			 * future connections going over the interface.
23534 			 */
23535 			mdt_cap->ill_mdt_on = 0;
23536 			break;
23537 		}
23538 
23539 		/* socket option(s) present? */
23540 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23541 			break;
23542 
23543 		rc = B_TRUE;
23544 	/* CONSTCOND */
23545 	} while (0);
23546 
23547 	/* Remember the result */
23548 	connp->conn_mdt_ok = rc;
23549 
23550 	if (!rc)
23551 		return (NULL);
23552 	else if (!mdt_cap->ill_mdt_on) {
23553 		/*
23554 		 * If MDT has been previously turned off in the past, and we
23555 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23556 		 * then enable it for this interface.
23557 		 */
23558 		mdt_cap->ill_mdt_on = 1;
23559 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23560 		    "interface %s\n", ill_name));
23561 	}
23562 
23563 	/* Allocate the MDT info mblk */
23564 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23565 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23566 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23567 		return (NULL);
23568 	}
23569 	return (mp);
23570 }
23571 
23572 /*
23573  * Routine to allocate a message that is used to notify the ULP about LSO.
23574  * The caller may provide a pointer to the link-layer LSO capabilities,
23575  * or NULL if LSO is to be disabled on the stream.
23576  */
23577 mblk_t *
23578 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23579 {
23580 	mblk_t *mp;
23581 	ip_lso_info_t *lsoi;
23582 	ill_lso_capab_t *idst;
23583 
23584 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23585 		DB_TYPE(mp) = M_CTL;
23586 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23587 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23588 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23589 		idst = &(lsoi->lso_capab);
23590 
23591 		/*
23592 		 * If the caller provides us with the capability, copy
23593 		 * it over into our notification message; otherwise
23594 		 * we zero out the capability portion.
23595 		 */
23596 		if (isrc != NULL)
23597 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23598 		else
23599 			bzero((caddr_t)idst, sizeof (*idst));
23600 	}
23601 	return (mp);
23602 }
23603 
23604 /*
23605  * Routine which determines whether LSO can be enabled on the destination
23606  * IRE and IPC combination, and if so, allocates and returns the LSO
23607  * notification mblk that may be used by ULP.  We also check if we need to
23608  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23609  * LSO usage in the past have been lifted.  This gets called during IP
23610  * and ULP binding.
23611  */
23612 mblk_t *
23613 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23614     ill_lso_capab_t *lso_cap)
23615 {
23616 	mblk_t *mp;
23617 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23618 
23619 	ASSERT(dst_ire != NULL);
23620 	ASSERT(connp != NULL);
23621 	ASSERT(lso_cap != NULL);
23622 
23623 	connp->conn_lso_ok = B_TRUE;
23624 
23625 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23626 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23627 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23628 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23629 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23630 		connp->conn_lso_ok = B_FALSE;
23631 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23632 			/*
23633 			 * Disable LSO for this and all future connections going
23634 			 * over the interface.
23635 			 */
23636 			lso_cap->ill_lso_on = 0;
23637 		}
23638 	}
23639 
23640 	if (!connp->conn_lso_ok)
23641 		return (NULL);
23642 	else if (!lso_cap->ill_lso_on) {
23643 		/*
23644 		 * If LSO has been previously turned off in the past, and we
23645 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23646 		 * then enable it for this interface.
23647 		 */
23648 		lso_cap->ill_lso_on = 1;
23649 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23650 		    ill_name));
23651 	}
23652 
23653 	/* Allocate the LSO info mblk */
23654 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23655 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23656 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23657 
23658 	return (mp);
23659 }
23660 
23661 /*
23662  * Create destination address attribute, and fill it with the physical
23663  * destination address and SAP taken from the template DL_UNITDATA_REQ
23664  * message block.
23665  */
23666 boolean_t
23667 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23668 {
23669 	dl_unitdata_req_t *dlurp;
23670 	pattr_t *pa;
23671 	pattrinfo_t pa_info;
23672 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23673 	uint_t das_len, das_off;
23674 
23675 	ASSERT(dlmp != NULL);
23676 
23677 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23678 	das_len = dlurp->dl_dest_addr_length;
23679 	das_off = dlurp->dl_dest_addr_offset;
23680 
23681 	pa_info.type = PATTR_DSTADDRSAP;
23682 	pa_info.len = sizeof (**das) + das_len - 1;
23683 
23684 	/* create and associate the attribute */
23685 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23686 	if (pa != NULL) {
23687 		ASSERT(*das != NULL);
23688 		(*das)->addr_is_group = 0;
23689 		(*das)->addr_len = (uint8_t)das_len;
23690 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23691 	}
23692 
23693 	return (pa != NULL);
23694 }
23695 
23696 /*
23697  * Create hardware checksum attribute and fill it with the values passed.
23698  */
23699 boolean_t
23700 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23701     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23702 {
23703 	pattr_t *pa;
23704 	pattrinfo_t pa_info;
23705 
23706 	ASSERT(mmd != NULL);
23707 
23708 	pa_info.type = PATTR_HCKSUM;
23709 	pa_info.len = sizeof (pattr_hcksum_t);
23710 
23711 	/* create and associate the attribute */
23712 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23713 	if (pa != NULL) {
23714 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23715 
23716 		hck->hcksum_start_offset = start_offset;
23717 		hck->hcksum_stuff_offset = stuff_offset;
23718 		hck->hcksum_end_offset = end_offset;
23719 		hck->hcksum_flags = flags;
23720 	}
23721 	return (pa != NULL);
23722 }
23723 
23724 /*
23725  * Create zerocopy attribute and fill it with the specified flags
23726  */
23727 boolean_t
23728 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23729 {
23730 	pattr_t *pa;
23731 	pattrinfo_t pa_info;
23732 
23733 	ASSERT(mmd != NULL);
23734 	pa_info.type = PATTR_ZCOPY;
23735 	pa_info.len = sizeof (pattr_zcopy_t);
23736 
23737 	/* create and associate the attribute */
23738 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23739 	if (pa != NULL) {
23740 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23741 
23742 		zcopy->zcopy_flags = flags;
23743 	}
23744 	return (pa != NULL);
23745 }
23746 
23747 /*
23748  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23749  * block chain. We could rewrite to handle arbitrary message block chains but
23750  * that would make the code complicated and slow. Right now there three
23751  * restrictions:
23752  *
23753  *   1. The first message block must contain the complete IP header and
23754  *	at least 1 byte of payload data.
23755  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23756  *	so that we can use a single Multidata message.
23757  *   3. No frag must be distributed over two or more message blocks so
23758  *	that we don't need more than two packet descriptors per frag.
23759  *
23760  * The above restrictions allow us to support userland applications (which
23761  * will send down a single message block) and NFS over UDP (which will
23762  * send down a chain of at most three message blocks).
23763  *
23764  * We also don't use MDT for payloads with less than or equal to
23765  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23766  */
23767 boolean_t
23768 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23769 {
23770 	int	blocks;
23771 	ssize_t	total, missing, size;
23772 
23773 	ASSERT(mp != NULL);
23774 	ASSERT(hdr_len > 0);
23775 
23776 	size = MBLKL(mp) - hdr_len;
23777 	if (size <= 0)
23778 		return (B_FALSE);
23779 
23780 	/* The first mblk contains the header and some payload. */
23781 	blocks = 1;
23782 	total = size;
23783 	size %= len;
23784 	missing = (size == 0) ? 0 : (len - size);
23785 	mp = mp->b_cont;
23786 
23787 	while (mp != NULL) {
23788 		/*
23789 		 * Give up if we encounter a zero length message block.
23790 		 * In practice, this should rarely happen and therefore
23791 		 * not worth the trouble of freeing and re-linking the
23792 		 * mblk from the chain to handle such case.
23793 		 */
23794 		if ((size = MBLKL(mp)) == 0)
23795 			return (B_FALSE);
23796 
23797 		/* Too many payload buffers for a single Multidata message? */
23798 		if (++blocks > MULTIDATA_MAX_PBUFS)
23799 			return (B_FALSE);
23800 
23801 		total += size;
23802 		/* Is a frag distributed over two or more message blocks? */
23803 		if (missing > size)
23804 			return (B_FALSE);
23805 		size -= missing;
23806 
23807 		size %= len;
23808 		missing = (size == 0) ? 0 : (len - size);
23809 
23810 		mp = mp->b_cont;
23811 	}
23812 
23813 	return (total > ip_wput_frag_mdt_min);
23814 }
23815 
23816 /*
23817  * Outbound IPv4 fragmentation routine using MDT.
23818  */
23819 static void
23820 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23821     uint32_t frag_flag, int offset)
23822 {
23823 	ipha_t		*ipha_orig;
23824 	int		i1, ip_data_end;
23825 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23826 	mblk_t		*hdr_mp, *md_mp = NULL;
23827 	unsigned char	*hdr_ptr, *pld_ptr;
23828 	multidata_t	*mmd;
23829 	ip_pdescinfo_t	pdi;
23830 	ill_t		*ill;
23831 	ip_stack_t	*ipst = ire->ire_ipst;
23832 
23833 	ASSERT(DB_TYPE(mp) == M_DATA);
23834 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23835 
23836 	ill = ire_to_ill(ire);
23837 	ASSERT(ill != NULL);
23838 
23839 	ipha_orig = (ipha_t *)mp->b_rptr;
23840 	mp->b_rptr += sizeof (ipha_t);
23841 
23842 	/* Calculate how many packets we will send out */
23843 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23844 	pkts = (i1 + len - 1) / len;
23845 	ASSERT(pkts > 1);
23846 
23847 	/* Allocate a message block which will hold all the IP Headers. */
23848 	wroff = ipst->ips_ip_wroff_extra;
23849 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23850 
23851 	i1 = pkts * hdr_chunk_len;
23852 	/*
23853 	 * Create the header buffer, Multidata and destination address
23854 	 * and SAP attribute that should be associated with it.
23855 	 */
23856 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23857 	    ((hdr_mp->b_wptr += i1),
23858 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23859 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23860 		freemsg(mp);
23861 		if (md_mp == NULL) {
23862 			freemsg(hdr_mp);
23863 		} else {
23864 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23865 			freemsg(md_mp);
23866 		}
23867 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23868 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23869 		return;
23870 	}
23871 	IP_STAT(ipst, ip_frag_mdt_allocd);
23872 
23873 	/*
23874 	 * Add a payload buffer to the Multidata; this operation must not
23875 	 * fail, or otherwise our logic in this routine is broken.  There
23876 	 * is no memory allocation done by the routine, so any returned
23877 	 * failure simply tells us that we've done something wrong.
23878 	 *
23879 	 * A failure tells us that either we're adding the same payload
23880 	 * buffer more than once, or we're trying to add more buffers than
23881 	 * allowed.  None of the above cases should happen, and we panic
23882 	 * because either there's horrible heap corruption, and/or
23883 	 * programming mistake.
23884 	 */
23885 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23886 		goto pbuf_panic;
23887 
23888 	hdr_ptr = hdr_mp->b_rptr;
23889 	pld_ptr = mp->b_rptr;
23890 
23891 	/* Establish the ending byte offset, based on the starting offset. */
23892 	offset <<= 3;
23893 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23894 	    IP_SIMPLE_HDR_LENGTH;
23895 
23896 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23897 
23898 	while (pld_ptr < mp->b_wptr) {
23899 		ipha_t		*ipha;
23900 		uint16_t	offset_and_flags;
23901 		uint16_t	ip_len;
23902 		int		error;
23903 
23904 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23905 		ipha = (ipha_t *)(hdr_ptr + wroff);
23906 		ASSERT(OK_32PTR(ipha));
23907 		*ipha = *ipha_orig;
23908 
23909 		if (ip_data_end - offset > len) {
23910 			offset_and_flags = IPH_MF;
23911 		} else {
23912 			/*
23913 			 * Last frag. Set len to the length of this last piece.
23914 			 */
23915 			len = ip_data_end - offset;
23916 			/* A frag of a frag might have IPH_MF non-zero */
23917 			offset_and_flags =
23918 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23919 			    IPH_MF;
23920 		}
23921 		offset_and_flags |= (uint16_t)(offset >> 3);
23922 		offset_and_flags |= (uint16_t)frag_flag;
23923 		/* Store the offset and flags in the IP header. */
23924 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23925 
23926 		/* Store the length in the IP header. */
23927 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23928 		ipha->ipha_length = htons(ip_len);
23929 
23930 		/*
23931 		 * Set the IP header checksum.  Note that mp is just
23932 		 * the header, so this is easy to pass to ip_csum.
23933 		 */
23934 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23935 
23936 		/*
23937 		 * Record offset and size of header and data of the next packet
23938 		 * in the multidata message.
23939 		 */
23940 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23941 		PDESC_PLD_INIT(&pdi);
23942 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23943 		ASSERT(i1 > 0);
23944 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23945 		if (i1 == len) {
23946 			pld_ptr += len;
23947 		} else {
23948 			i1 = len - i1;
23949 			mp = mp->b_cont;
23950 			ASSERT(mp != NULL);
23951 			ASSERT(MBLKL(mp) >= i1);
23952 			/*
23953 			 * Attach the next payload message block to the
23954 			 * multidata message.
23955 			 */
23956 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23957 				goto pbuf_panic;
23958 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23959 			pld_ptr = mp->b_rptr + i1;
23960 		}
23961 
23962 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23963 		    KM_NOSLEEP)) == NULL) {
23964 			/*
23965 			 * Any failure other than ENOMEM indicates that we
23966 			 * have passed in invalid pdesc info or parameters
23967 			 * to mmd_addpdesc, which must not happen.
23968 			 *
23969 			 * EINVAL is a result of failure on boundary checks
23970 			 * against the pdesc info contents.  It should not
23971 			 * happen, and we panic because either there's
23972 			 * horrible heap corruption, and/or programming
23973 			 * mistake.
23974 			 */
23975 			if (error != ENOMEM) {
23976 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23977 				    "pdesc logic error detected for "
23978 				    "mmd %p pinfo %p (%d)\n",
23979 				    (void *)mmd, (void *)&pdi, error);
23980 				/* NOTREACHED */
23981 			}
23982 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23983 			/* Free unattached payload message blocks as well */
23984 			md_mp->b_cont = mp->b_cont;
23985 			goto free_mmd;
23986 		}
23987 
23988 		/* Advance fragment offset. */
23989 		offset += len;
23990 
23991 		/* Advance to location for next header in the buffer. */
23992 		hdr_ptr += hdr_chunk_len;
23993 
23994 		/* Did we reach the next payload message block? */
23995 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23996 			mp = mp->b_cont;
23997 			/*
23998 			 * Attach the next message block with payload
23999 			 * data to the multidata message.
24000 			 */
24001 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24002 				goto pbuf_panic;
24003 			pld_ptr = mp->b_rptr;
24004 		}
24005 	}
24006 
24007 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24008 	ASSERT(mp->b_wptr == pld_ptr);
24009 
24010 	/* Update IP statistics */
24011 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24012 
24013 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24014 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24015 
24016 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24017 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24018 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24019 
24020 	if (pkt_type == OB_PKT) {
24021 		ire->ire_ob_pkt_count += pkts;
24022 		if (ire->ire_ipif != NULL)
24023 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24024 	} else {
24025 		/* The type is IB_PKT in the forwarding path. */
24026 		ire->ire_ib_pkt_count += pkts;
24027 		ASSERT(!IRE_IS_LOCAL(ire));
24028 		if (ire->ire_type & IRE_BROADCAST) {
24029 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24030 		} else {
24031 			UPDATE_MIB(ill->ill_ip_mib,
24032 			    ipIfStatsHCOutForwDatagrams, pkts);
24033 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24034 		}
24035 	}
24036 	ire->ire_last_used_time = lbolt;
24037 	/* Send it down */
24038 	putnext(ire->ire_stq, md_mp);
24039 	return;
24040 
24041 pbuf_panic:
24042 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24043 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24044 	    pbuf_idx);
24045 	/* NOTREACHED */
24046 }
24047 
24048 /*
24049  * Outbound IP fragmentation routine.
24050  *
24051  * NOTE : This routine does not ire_refrele the ire that is passed in
24052  * as the argument.
24053  */
24054 static void
24055 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24056     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24057 {
24058 	int		i1;
24059 	mblk_t		*ll_hdr_mp;
24060 	int 		ll_hdr_len;
24061 	int		hdr_len;
24062 	mblk_t		*hdr_mp;
24063 	ipha_t		*ipha;
24064 	int		ip_data_end;
24065 	int		len;
24066 	mblk_t		*mp = mp_orig, *mp1;
24067 	int		offset;
24068 	queue_t		*q;
24069 	uint32_t	v_hlen_tos_len;
24070 	mblk_t		*first_mp;
24071 	boolean_t	mctl_present;
24072 	ill_t		*ill;
24073 	ill_t		*out_ill;
24074 	mblk_t		*xmit_mp;
24075 	mblk_t		*carve_mp;
24076 	ire_t		*ire1 = NULL;
24077 	ire_t		*save_ire = NULL;
24078 	mblk_t  	*next_mp = NULL;
24079 	boolean_t	last_frag = B_FALSE;
24080 	boolean_t	multirt_send = B_FALSE;
24081 	ire_t		*first_ire = NULL;
24082 	irb_t		*irb = NULL;
24083 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24084 
24085 	ill = ire_to_ill(ire);
24086 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24087 
24088 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24089 
24090 	if (max_frag == 0) {
24091 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24092 		    " -  dropping packet\n"));
24093 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24094 		freemsg(mp);
24095 		return;
24096 	}
24097 
24098 	/*
24099 	 * IPsec does not allow hw accelerated packets to be fragmented
24100 	 * This check is made in ip_wput_ipsec_out prior to coming here
24101 	 * via ip_wput_ire_fragmentit.
24102 	 *
24103 	 * If at this point we have an ire whose ARP request has not
24104 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24105 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24106 	 * This packet and all fragmentable packets for this ire will
24107 	 * continue to get dropped while ire_nce->nce_state remains in
24108 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24109 	 * ND_REACHABLE, all subsquent large packets for this ire will
24110 	 * get fragemented and sent out by this function.
24111 	 */
24112 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24113 		/* If nce_state is ND_INITIAL, trigger ARP query */
24114 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24115 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24116 		    " -  dropping packet\n"));
24117 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24118 		freemsg(mp);
24119 		return;
24120 	}
24121 
24122 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24123 	    "ip_wput_frag_start:");
24124 
24125 	if (mp->b_datap->db_type == M_CTL) {
24126 		first_mp = mp;
24127 		mp_orig = mp = mp->b_cont;
24128 		mctl_present = B_TRUE;
24129 	} else {
24130 		first_mp = mp;
24131 		mctl_present = B_FALSE;
24132 	}
24133 
24134 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24135 	ipha = (ipha_t *)mp->b_rptr;
24136 
24137 	/*
24138 	 * If the Don't Fragment flag is on, generate an ICMP destination
24139 	 * unreachable, fragmentation needed.
24140 	 */
24141 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24142 	if (offset & IPH_DF) {
24143 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24144 		if (is_system_labeled()) {
24145 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24146 			    ire->ire_max_frag - max_frag, AF_INET);
24147 		}
24148 		/*
24149 		 * Need to compute hdr checksum if called from ip_wput_ire.
24150 		 * Note that ip_rput_forward verifies the checksum before
24151 		 * calling this routine so in that case this is a noop.
24152 		 */
24153 		ipha->ipha_hdr_checksum = 0;
24154 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24155 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24156 		    ipst);
24157 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24158 		    "ip_wput_frag_end:(%S)",
24159 		    "don't fragment");
24160 		return;
24161 	}
24162 	/*
24163 	 * Labeled systems adjust max_frag if they add a label
24164 	 * to send the correct path mtu.  We need the real mtu since we
24165 	 * are fragmenting the packet after label adjustment.
24166 	 */
24167 	if (is_system_labeled())
24168 		max_frag = ire->ire_max_frag;
24169 	if (mctl_present)
24170 		freeb(first_mp);
24171 	/*
24172 	 * Establish the starting offset.  May not be zero if we are fragging
24173 	 * a fragment that is being forwarded.
24174 	 */
24175 	offset = offset & IPH_OFFSET;
24176 
24177 	/* TODO why is this test needed? */
24178 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24179 	if (((max_frag - LENGTH) & ~7) < 8) {
24180 		/* TODO: notify ulp somehow */
24181 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24182 		freemsg(mp);
24183 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24184 		    "ip_wput_frag_end:(%S)",
24185 		    "len < 8");
24186 		return;
24187 	}
24188 
24189 	hdr_len = (V_HLEN & 0xF) << 2;
24190 
24191 	ipha->ipha_hdr_checksum = 0;
24192 
24193 	/*
24194 	 * Establish the number of bytes maximum per frag, after putting
24195 	 * in the header.
24196 	 */
24197 	len = (max_frag - hdr_len) & ~7;
24198 
24199 	/* Check if we can use MDT to send out the frags. */
24200 	ASSERT(!IRE_IS_LOCAL(ire));
24201 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24202 	    ipst->ips_ip_multidata_outbound &&
24203 	    !(ire->ire_flags & RTF_MULTIRT) &&
24204 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24205 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24206 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24207 		ASSERT(ill->ill_mdt_capab != NULL);
24208 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24209 			/*
24210 			 * If MDT has been previously turned off in the past,
24211 			 * and we currently can do MDT (due to IPQoS policy
24212 			 * removal, etc.) then enable it for this interface.
24213 			 */
24214 			ill->ill_mdt_capab->ill_mdt_on = 1;
24215 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24216 			    ill->ill_name));
24217 		}
24218 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24219 		    offset);
24220 		return;
24221 	}
24222 
24223 	/* Get a copy of the header for the trailing frags */
24224 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24225 	if (!hdr_mp) {
24226 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24227 		freemsg(mp);
24228 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24229 		    "ip_wput_frag_end:(%S)",
24230 		    "couldn't copy hdr");
24231 		return;
24232 	}
24233 	if (DB_CRED(mp) != NULL)
24234 		mblk_setcred(hdr_mp, DB_CRED(mp));
24235 
24236 	/* Store the starting offset, with the MoreFrags flag. */
24237 	i1 = offset | IPH_MF | frag_flag;
24238 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24239 
24240 	/* Establish the ending byte offset, based on the starting offset. */
24241 	offset <<= 3;
24242 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24243 
24244 	/* Store the length of the first fragment in the IP header. */
24245 	i1 = len + hdr_len;
24246 	ASSERT(i1 <= IP_MAXPACKET);
24247 	ipha->ipha_length = htons((uint16_t)i1);
24248 
24249 	/*
24250 	 * Compute the IP header checksum for the first frag.  We have to
24251 	 * watch out that we stop at the end of the header.
24252 	 */
24253 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24254 
24255 	/*
24256 	 * Now carve off the first frag.  Note that this will include the
24257 	 * original IP header.
24258 	 */
24259 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24260 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24261 		freeb(hdr_mp);
24262 		freemsg(mp_orig);
24263 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24264 		    "ip_wput_frag_end:(%S)",
24265 		    "couldn't carve first");
24266 		return;
24267 	}
24268 
24269 	/*
24270 	 * Multirouting case. Each fragment is replicated
24271 	 * via all non-condemned RTF_MULTIRT routes
24272 	 * currently resolved.
24273 	 * We ensure that first_ire is the first RTF_MULTIRT
24274 	 * ire in the bucket.
24275 	 */
24276 	if (ire->ire_flags & RTF_MULTIRT) {
24277 		irb = ire->ire_bucket;
24278 		ASSERT(irb != NULL);
24279 
24280 		multirt_send = B_TRUE;
24281 
24282 		/* Make sure we do not omit any multiroute ire. */
24283 		IRB_REFHOLD(irb);
24284 		for (first_ire = irb->irb_ire;
24285 		    first_ire != NULL;
24286 		    first_ire = first_ire->ire_next) {
24287 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24288 			    (first_ire->ire_addr == ire->ire_addr) &&
24289 			    !(first_ire->ire_marks &
24290 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24291 				break;
24292 			}
24293 		}
24294 
24295 		if (first_ire != NULL) {
24296 			if (first_ire != ire) {
24297 				IRE_REFHOLD(first_ire);
24298 				/*
24299 				 * Do not release the ire passed in
24300 				 * as the argument.
24301 				 */
24302 				ire = first_ire;
24303 			} else {
24304 				first_ire = NULL;
24305 			}
24306 		}
24307 		IRB_REFRELE(irb);
24308 
24309 		/*
24310 		 * Save the first ire; we will need to restore it
24311 		 * for the trailing frags.
24312 		 * We REFHOLD save_ire, as each iterated ire will be
24313 		 * REFRELEd.
24314 		 */
24315 		save_ire = ire;
24316 		IRE_REFHOLD(save_ire);
24317 	}
24318 
24319 	/*
24320 	 * First fragment emission loop.
24321 	 * In most cases, the emission loop below is entered only
24322 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24323 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24324 	 * bucket, and send the fragment through all crossed
24325 	 * RTF_MULTIRT routes.
24326 	 */
24327 	do {
24328 		if (ire->ire_flags & RTF_MULTIRT) {
24329 			/*
24330 			 * We are in a multiple send case, need to get
24331 			 * the next ire and make a copy of the packet.
24332 			 * ire1 holds here the next ire to process in the
24333 			 * bucket. If multirouting is expected,
24334 			 * any non-RTF_MULTIRT ire that has the
24335 			 * right destination address is ignored.
24336 			 *
24337 			 * We have to take into account the MTU of
24338 			 * each walked ire. max_frag is set by the
24339 			 * the caller and generally refers to
24340 			 * the primary ire entry. Here we ensure that
24341 			 * no route with a lower MTU will be used, as
24342 			 * fragments are carved once for all ires,
24343 			 * then replicated.
24344 			 */
24345 			ASSERT(irb != NULL);
24346 			IRB_REFHOLD(irb);
24347 			for (ire1 = ire->ire_next;
24348 			    ire1 != NULL;
24349 			    ire1 = ire1->ire_next) {
24350 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24351 					continue;
24352 				if (ire1->ire_addr != ire->ire_addr)
24353 					continue;
24354 				if (ire1->ire_marks &
24355 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24356 					continue;
24357 				/*
24358 				 * Ensure we do not exceed the MTU
24359 				 * of the next route.
24360 				 */
24361 				if (ire1->ire_max_frag < max_frag) {
24362 					ip_multirt_bad_mtu(ire1, max_frag);
24363 					continue;
24364 				}
24365 
24366 				/* Got one. */
24367 				IRE_REFHOLD(ire1);
24368 				break;
24369 			}
24370 			IRB_REFRELE(irb);
24371 
24372 			if (ire1 != NULL) {
24373 				next_mp = copyb(mp);
24374 				if ((next_mp == NULL) ||
24375 				    ((mp->b_cont != NULL) &&
24376 				    ((next_mp->b_cont =
24377 				    dupmsg(mp->b_cont)) == NULL))) {
24378 					freemsg(next_mp);
24379 					next_mp = NULL;
24380 					ire_refrele(ire1);
24381 					ire1 = NULL;
24382 				}
24383 			}
24384 
24385 			/* Last multiroute ire; don't loop anymore. */
24386 			if (ire1 == NULL) {
24387 				multirt_send = B_FALSE;
24388 			}
24389 		}
24390 
24391 		ll_hdr_len = 0;
24392 		LOCK_IRE_FP_MP(ire);
24393 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24394 		if (ll_hdr_mp != NULL) {
24395 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24396 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24397 		} else {
24398 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24399 		}
24400 
24401 		/* If there is a transmit header, get a copy for this frag. */
24402 		/*
24403 		 * TODO: should check db_ref before calling ip_carve_mp since
24404 		 * it might give us a dup.
24405 		 */
24406 		if (!ll_hdr_mp) {
24407 			/* No xmit header. */
24408 			xmit_mp = mp;
24409 
24410 		/* We have a link-layer header that can fit in our mblk. */
24411 		} else if (mp->b_datap->db_ref == 1 &&
24412 		    ll_hdr_len != 0 &&
24413 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24414 			/* M_DATA fastpath */
24415 			mp->b_rptr -= ll_hdr_len;
24416 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24417 			xmit_mp = mp;
24418 
24419 		/* Corner case if copyb has failed */
24420 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24421 			UNLOCK_IRE_FP_MP(ire);
24422 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24423 			freeb(hdr_mp);
24424 			freemsg(mp);
24425 			freemsg(mp_orig);
24426 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24427 			    "ip_wput_frag_end:(%S)",
24428 			    "discard");
24429 
24430 			if (multirt_send) {
24431 				ASSERT(ire1);
24432 				ASSERT(next_mp);
24433 
24434 				freemsg(next_mp);
24435 				ire_refrele(ire1);
24436 			}
24437 			if (save_ire != NULL)
24438 				IRE_REFRELE(save_ire);
24439 
24440 			if (first_ire != NULL)
24441 				ire_refrele(first_ire);
24442 			return;
24443 
24444 		/*
24445 		 * Case of res_mp OR the fastpath mp can't fit
24446 		 * in the mblk
24447 		 */
24448 		} else {
24449 			xmit_mp->b_cont = mp;
24450 			if (DB_CRED(mp) != NULL)
24451 				mblk_setcred(xmit_mp, DB_CRED(mp));
24452 			/*
24453 			 * Get priority marking, if any.
24454 			 * We propagate the CoS marking from the
24455 			 * original packet that went to QoS processing
24456 			 * in ip_wput_ire to the newly carved mp.
24457 			 */
24458 			if (DB_TYPE(xmit_mp) == M_DATA)
24459 				xmit_mp->b_band = mp->b_band;
24460 		}
24461 		UNLOCK_IRE_FP_MP(ire);
24462 
24463 		q = ire->ire_stq;
24464 		out_ill = (ill_t *)q->q_ptr;
24465 
24466 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24467 
24468 		DTRACE_PROBE4(ip4__physical__out__start,
24469 		    ill_t *, NULL, ill_t *, out_ill,
24470 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24471 
24472 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24473 		    ipst->ips_ipv4firewall_physical_out,
24474 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24475 
24476 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24477 
24478 		if (xmit_mp != NULL) {
24479 			putnext(q, xmit_mp);
24480 
24481 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24482 			UPDATE_MIB(out_ill->ill_ip_mib,
24483 			    ipIfStatsHCOutOctets, i1);
24484 
24485 			if (pkt_type != OB_PKT) {
24486 				/*
24487 				 * Update the packet count and MIB stats
24488 				 * of trailing RTF_MULTIRT ires.
24489 				 */
24490 				UPDATE_OB_PKT_COUNT(ire);
24491 				BUMP_MIB(out_ill->ill_ip_mib,
24492 				    ipIfStatsOutFragReqds);
24493 			}
24494 		}
24495 
24496 		if (multirt_send) {
24497 			/*
24498 			 * We are in a multiple send case; look for
24499 			 * the next ire and re-enter the loop.
24500 			 */
24501 			ASSERT(ire1);
24502 			ASSERT(next_mp);
24503 			/* REFRELE the current ire before looping */
24504 			ire_refrele(ire);
24505 			ire = ire1;
24506 			ire1 = NULL;
24507 			mp = next_mp;
24508 			next_mp = NULL;
24509 		}
24510 	} while (multirt_send);
24511 
24512 	ASSERT(ire1 == NULL);
24513 
24514 	/* Restore the original ire; we need it for the trailing frags */
24515 	if (save_ire != NULL) {
24516 		/* REFRELE the last iterated ire */
24517 		ire_refrele(ire);
24518 		/* save_ire has been REFHOLDed */
24519 		ire = save_ire;
24520 		save_ire = NULL;
24521 		q = ire->ire_stq;
24522 	}
24523 
24524 	if (pkt_type == OB_PKT) {
24525 		UPDATE_OB_PKT_COUNT(ire);
24526 	} else {
24527 		out_ill = (ill_t *)q->q_ptr;
24528 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24529 		UPDATE_IB_PKT_COUNT(ire);
24530 	}
24531 
24532 	/* Advance the offset to the second frag starting point. */
24533 	offset += len;
24534 	/*
24535 	 * Update hdr_len from the copied header - there might be less options
24536 	 * in the later fragments.
24537 	 */
24538 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24539 	/* Loop until done. */
24540 	for (;;) {
24541 		uint16_t	offset_and_flags;
24542 		uint16_t	ip_len;
24543 
24544 		if (ip_data_end - offset > len) {
24545 			/*
24546 			 * Carve off the appropriate amount from the original
24547 			 * datagram.
24548 			 */
24549 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24550 				mp = NULL;
24551 				break;
24552 			}
24553 			/*
24554 			 * More frags after this one.  Get another copy
24555 			 * of the header.
24556 			 */
24557 			if (carve_mp->b_datap->db_ref == 1 &&
24558 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24559 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24560 				/* Inline IP header */
24561 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24562 				    hdr_mp->b_rptr;
24563 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24564 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24565 				mp = carve_mp;
24566 			} else {
24567 				if (!(mp = copyb(hdr_mp))) {
24568 					freemsg(carve_mp);
24569 					break;
24570 				}
24571 				/* Get priority marking, if any. */
24572 				mp->b_band = carve_mp->b_band;
24573 				mp->b_cont = carve_mp;
24574 			}
24575 			ipha = (ipha_t *)mp->b_rptr;
24576 			offset_and_flags = IPH_MF;
24577 		} else {
24578 			/*
24579 			 * Last frag.  Consume the header. Set len to
24580 			 * the length of this last piece.
24581 			 */
24582 			len = ip_data_end - offset;
24583 
24584 			/*
24585 			 * Carve off the appropriate amount from the original
24586 			 * datagram.
24587 			 */
24588 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24589 				mp = NULL;
24590 				break;
24591 			}
24592 			if (carve_mp->b_datap->db_ref == 1 &&
24593 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24594 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24595 				/* Inline IP header */
24596 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24597 				    hdr_mp->b_rptr;
24598 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24599 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24600 				mp = carve_mp;
24601 				freeb(hdr_mp);
24602 				hdr_mp = mp;
24603 			} else {
24604 				mp = hdr_mp;
24605 				/* Get priority marking, if any. */
24606 				mp->b_band = carve_mp->b_band;
24607 				mp->b_cont = carve_mp;
24608 			}
24609 			ipha = (ipha_t *)mp->b_rptr;
24610 			/* A frag of a frag might have IPH_MF non-zero */
24611 			offset_and_flags =
24612 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24613 			    IPH_MF;
24614 		}
24615 		offset_and_flags |= (uint16_t)(offset >> 3);
24616 		offset_and_flags |= (uint16_t)frag_flag;
24617 		/* Store the offset and flags in the IP header. */
24618 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24619 
24620 		/* Store the length in the IP header. */
24621 		ip_len = (uint16_t)(len + hdr_len);
24622 		ipha->ipha_length = htons(ip_len);
24623 
24624 		/*
24625 		 * Set the IP header checksum.	Note that mp is just
24626 		 * the header, so this is easy to pass to ip_csum.
24627 		 */
24628 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24629 
24630 		/* Attach a transmit header, if any, and ship it. */
24631 		if (pkt_type == OB_PKT) {
24632 			UPDATE_OB_PKT_COUNT(ire);
24633 		} else {
24634 			out_ill = (ill_t *)q->q_ptr;
24635 			BUMP_MIB(out_ill->ill_ip_mib,
24636 			    ipIfStatsHCOutForwDatagrams);
24637 			UPDATE_IB_PKT_COUNT(ire);
24638 		}
24639 
24640 		if (ire->ire_flags & RTF_MULTIRT) {
24641 			irb = ire->ire_bucket;
24642 			ASSERT(irb != NULL);
24643 
24644 			multirt_send = B_TRUE;
24645 
24646 			/*
24647 			 * Save the original ire; we will need to restore it
24648 			 * for the tailing frags.
24649 			 */
24650 			save_ire = ire;
24651 			IRE_REFHOLD(save_ire);
24652 		}
24653 		/*
24654 		 * Emission loop for this fragment, similar
24655 		 * to what is done for the first fragment.
24656 		 */
24657 		do {
24658 			if (multirt_send) {
24659 				/*
24660 				 * We are in a multiple send case, need to get
24661 				 * the next ire and make a copy of the packet.
24662 				 */
24663 				ASSERT(irb != NULL);
24664 				IRB_REFHOLD(irb);
24665 				for (ire1 = ire->ire_next;
24666 				    ire1 != NULL;
24667 				    ire1 = ire1->ire_next) {
24668 					if (!(ire1->ire_flags & RTF_MULTIRT))
24669 						continue;
24670 					if (ire1->ire_addr != ire->ire_addr)
24671 						continue;
24672 					if (ire1->ire_marks &
24673 					    (IRE_MARK_CONDEMNED|
24674 					    IRE_MARK_HIDDEN)) {
24675 						continue;
24676 					}
24677 					/*
24678 					 * Ensure we do not exceed the MTU
24679 					 * of the next route.
24680 					 */
24681 					if (ire1->ire_max_frag < max_frag) {
24682 						ip_multirt_bad_mtu(ire1,
24683 						    max_frag);
24684 						continue;
24685 					}
24686 
24687 					/* Got one. */
24688 					IRE_REFHOLD(ire1);
24689 					break;
24690 				}
24691 				IRB_REFRELE(irb);
24692 
24693 				if (ire1 != NULL) {
24694 					next_mp = copyb(mp);
24695 					if ((next_mp == NULL) ||
24696 					    ((mp->b_cont != NULL) &&
24697 					    ((next_mp->b_cont =
24698 					    dupmsg(mp->b_cont)) == NULL))) {
24699 						freemsg(next_mp);
24700 						next_mp = NULL;
24701 						ire_refrele(ire1);
24702 						ire1 = NULL;
24703 					}
24704 				}
24705 
24706 				/* Last multiroute ire; don't loop anymore. */
24707 				if (ire1 == NULL) {
24708 					multirt_send = B_FALSE;
24709 				}
24710 			}
24711 
24712 			/* Update transmit header */
24713 			ll_hdr_len = 0;
24714 			LOCK_IRE_FP_MP(ire);
24715 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24716 			if (ll_hdr_mp != NULL) {
24717 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24718 				ll_hdr_len = MBLKL(ll_hdr_mp);
24719 			} else {
24720 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24721 			}
24722 
24723 			if (!ll_hdr_mp) {
24724 				xmit_mp = mp;
24725 
24726 			/*
24727 			 * We have link-layer header that can fit in
24728 			 * our mblk.
24729 			 */
24730 			} else if (mp->b_datap->db_ref == 1 &&
24731 			    ll_hdr_len != 0 &&
24732 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24733 				/* M_DATA fastpath */
24734 				mp->b_rptr -= ll_hdr_len;
24735 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24736 				    ll_hdr_len);
24737 				xmit_mp = mp;
24738 
24739 			/*
24740 			 * Case of res_mp OR the fastpath mp can't fit
24741 			 * in the mblk
24742 			 */
24743 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24744 				xmit_mp->b_cont = mp;
24745 				if (DB_CRED(mp) != NULL)
24746 					mblk_setcred(xmit_mp, DB_CRED(mp));
24747 				/* Get priority marking, if any. */
24748 				if (DB_TYPE(xmit_mp) == M_DATA)
24749 					xmit_mp->b_band = mp->b_band;
24750 
24751 			/* Corner case if copyb failed */
24752 			} else {
24753 				/*
24754 				 * Exit both the replication and
24755 				 * fragmentation loops.
24756 				 */
24757 				UNLOCK_IRE_FP_MP(ire);
24758 				goto drop_pkt;
24759 			}
24760 			UNLOCK_IRE_FP_MP(ire);
24761 
24762 			mp1 = mp;
24763 			out_ill = (ill_t *)q->q_ptr;
24764 
24765 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24766 
24767 			DTRACE_PROBE4(ip4__physical__out__start,
24768 			    ill_t *, NULL, ill_t *, out_ill,
24769 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24770 
24771 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24772 			    ipst->ips_ipv4firewall_physical_out,
24773 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24774 
24775 			DTRACE_PROBE1(ip4__physical__out__end,
24776 			    mblk_t *, xmit_mp);
24777 
24778 			if (mp != mp1 && hdr_mp == mp1)
24779 				hdr_mp = mp;
24780 			if (mp != mp1 && mp_orig == mp1)
24781 				mp_orig = mp;
24782 
24783 			if (xmit_mp != NULL) {
24784 				putnext(q, xmit_mp);
24785 
24786 				BUMP_MIB(out_ill->ill_ip_mib,
24787 				    ipIfStatsHCOutTransmits);
24788 				UPDATE_MIB(out_ill->ill_ip_mib,
24789 				    ipIfStatsHCOutOctets, ip_len);
24790 
24791 				if (pkt_type != OB_PKT) {
24792 					/*
24793 					 * Update the packet count of trailing
24794 					 * RTF_MULTIRT ires.
24795 					 */
24796 					UPDATE_OB_PKT_COUNT(ire);
24797 				}
24798 			}
24799 
24800 			/* All done if we just consumed the hdr_mp. */
24801 			if (mp == hdr_mp) {
24802 				last_frag = B_TRUE;
24803 				BUMP_MIB(out_ill->ill_ip_mib,
24804 				    ipIfStatsOutFragOKs);
24805 			}
24806 
24807 			if (multirt_send) {
24808 				/*
24809 				 * We are in a multiple send case; look for
24810 				 * the next ire and re-enter the loop.
24811 				 */
24812 				ASSERT(ire1);
24813 				ASSERT(next_mp);
24814 				/* REFRELE the current ire before looping */
24815 				ire_refrele(ire);
24816 				ire = ire1;
24817 				ire1 = NULL;
24818 				q = ire->ire_stq;
24819 				mp = next_mp;
24820 				next_mp = NULL;
24821 			}
24822 		} while (multirt_send);
24823 		/*
24824 		 * Restore the original ire; we need it for the
24825 		 * trailing frags
24826 		 */
24827 		if (save_ire != NULL) {
24828 			ASSERT(ire1 == NULL);
24829 			/* REFRELE the last iterated ire */
24830 			ire_refrele(ire);
24831 			/* save_ire has been REFHOLDed */
24832 			ire = save_ire;
24833 			q = ire->ire_stq;
24834 			save_ire = NULL;
24835 		}
24836 
24837 		if (last_frag) {
24838 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24839 			    "ip_wput_frag_end:(%S)",
24840 			    "consumed hdr_mp");
24841 
24842 			if (first_ire != NULL)
24843 				ire_refrele(first_ire);
24844 			return;
24845 		}
24846 		/* Otherwise, advance and loop. */
24847 		offset += len;
24848 	}
24849 
24850 drop_pkt:
24851 	/* Clean up following allocation failure. */
24852 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24853 	freemsg(mp);
24854 	if (mp != hdr_mp)
24855 		freeb(hdr_mp);
24856 	if (mp != mp_orig)
24857 		freemsg(mp_orig);
24858 
24859 	if (save_ire != NULL)
24860 		IRE_REFRELE(save_ire);
24861 	if (first_ire != NULL)
24862 		ire_refrele(first_ire);
24863 
24864 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24865 	    "ip_wput_frag_end:(%S)",
24866 	    "end--alloc failure");
24867 }
24868 
24869 /*
24870  * Copy the header plus those options which have the copy bit set
24871  */
24872 static mblk_t *
24873 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24874 {
24875 	mblk_t	*mp;
24876 	uchar_t	*up;
24877 
24878 	/*
24879 	 * Quick check if we need to look for options without the copy bit
24880 	 * set
24881 	 */
24882 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24883 	if (!mp)
24884 		return (mp);
24885 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24886 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24887 		bcopy(rptr, mp->b_rptr, hdr_len);
24888 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24889 		return (mp);
24890 	}
24891 	up  = mp->b_rptr;
24892 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24893 	up += IP_SIMPLE_HDR_LENGTH;
24894 	rptr += IP_SIMPLE_HDR_LENGTH;
24895 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24896 	while (hdr_len > 0) {
24897 		uint32_t optval;
24898 		uint32_t optlen;
24899 
24900 		optval = *rptr;
24901 		if (optval == IPOPT_EOL)
24902 			break;
24903 		if (optval == IPOPT_NOP)
24904 			optlen = 1;
24905 		else
24906 			optlen = rptr[1];
24907 		if (optval & IPOPT_COPY) {
24908 			bcopy(rptr, up, optlen);
24909 			up += optlen;
24910 		}
24911 		rptr += optlen;
24912 		hdr_len -= optlen;
24913 	}
24914 	/*
24915 	 * Make sure that we drop an even number of words by filling
24916 	 * with EOL to the next word boundary.
24917 	 */
24918 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24919 	    hdr_len & 0x3; hdr_len++)
24920 		*up++ = IPOPT_EOL;
24921 	mp->b_wptr = up;
24922 	/* Update header length */
24923 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24924 	return (mp);
24925 }
24926 
24927 /*
24928  * Delivery to local recipients including fanout to multiple recipients.
24929  * Does not do checksumming of UDP/TCP.
24930  * Note: q should be the read side queue for either the ill or conn.
24931  * Note: rq should be the read side q for the lower (ill) stream.
24932  * We don't send packets to IPPF processing, thus the last argument
24933  * to all the fanout calls are B_FALSE.
24934  */
24935 void
24936 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24937     int fanout_flags, zoneid_t zoneid)
24938 {
24939 	uint32_t	protocol;
24940 	mblk_t		*first_mp;
24941 	boolean_t	mctl_present;
24942 	int		ire_type;
24943 #define	rptr	((uchar_t *)ipha)
24944 	ip_stack_t	*ipst = ill->ill_ipst;
24945 
24946 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24947 	    "ip_wput_local_start: q %p", q);
24948 
24949 	if (ire != NULL) {
24950 		ire_type = ire->ire_type;
24951 	} else {
24952 		/*
24953 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24954 		 * packet is not multicast, we can't tell the ire type.
24955 		 */
24956 		ASSERT(CLASSD(ipha->ipha_dst));
24957 		ire_type = IRE_BROADCAST;
24958 	}
24959 
24960 	first_mp = mp;
24961 	if (first_mp->b_datap->db_type == M_CTL) {
24962 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24963 		if (!io->ipsec_out_secure) {
24964 			/*
24965 			 * This ipsec_out_t was allocated in ip_wput
24966 			 * for multicast packets to store the ill_index.
24967 			 * As this is being delivered locally, we don't
24968 			 * need this anymore.
24969 			 */
24970 			mp = first_mp->b_cont;
24971 			freeb(first_mp);
24972 			first_mp = mp;
24973 			mctl_present = B_FALSE;
24974 		} else {
24975 			/*
24976 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24977 			 * security properties for the looped-back packet.
24978 			 */
24979 			mctl_present = B_TRUE;
24980 			mp = first_mp->b_cont;
24981 			ASSERT(mp != NULL);
24982 			ipsec_out_to_in(first_mp);
24983 		}
24984 	} else {
24985 		mctl_present = B_FALSE;
24986 	}
24987 
24988 	DTRACE_PROBE4(ip4__loopback__in__start,
24989 	    ill_t *, ill, ill_t *, NULL,
24990 	    ipha_t *, ipha, mblk_t *, first_mp);
24991 
24992 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24993 	    ipst->ips_ipv4firewall_loopback_in,
24994 	    ill, NULL, ipha, first_mp, mp, ipst);
24995 
24996 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24997 
24998 	if (first_mp == NULL)
24999 		return;
25000 
25001 	ipst->ips_loopback_packets++;
25002 
25003 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25004 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25005 	if (!IS_SIMPLE_IPH(ipha)) {
25006 		ip_wput_local_options(ipha, ipst);
25007 	}
25008 
25009 	protocol = ipha->ipha_protocol;
25010 	switch (protocol) {
25011 	case IPPROTO_ICMP: {
25012 		ire_t		*ire_zone;
25013 		ilm_t		*ilm;
25014 		mblk_t		*mp1;
25015 		zoneid_t	last_zoneid;
25016 
25017 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25018 			ASSERT(ire_type == IRE_BROADCAST);
25019 			/*
25020 			 * In the multicast case, applications may have joined
25021 			 * the group from different zones, so we need to deliver
25022 			 * the packet to each of them. Loop through the
25023 			 * multicast memberships structures (ilm) on the receive
25024 			 * ill and send a copy of the packet up each matching
25025 			 * one. However, we don't do this for multicasts sent on
25026 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25027 			 * they must stay in the sender's zone.
25028 			 *
25029 			 * ilm_add_v6() ensures that ilms in the same zone are
25030 			 * contiguous in the ill_ilm list. We use this property
25031 			 * to avoid sending duplicates needed when two
25032 			 * applications in the same zone join the same group on
25033 			 * different logical interfaces: we ignore the ilm if
25034 			 * it's zoneid is the same as the last matching one.
25035 			 * In addition, the sending of the packet for
25036 			 * ire_zoneid is delayed until all of the other ilms
25037 			 * have been exhausted.
25038 			 */
25039 			last_zoneid = -1;
25040 			ILM_WALKER_HOLD(ill);
25041 			for (ilm = ill->ill_ilm; ilm != NULL;
25042 			    ilm = ilm->ilm_next) {
25043 				if ((ilm->ilm_flags & ILM_DELETED) ||
25044 				    ipha->ipha_dst != ilm->ilm_addr ||
25045 				    ilm->ilm_zoneid == last_zoneid ||
25046 				    ilm->ilm_zoneid == zoneid ||
25047 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25048 					continue;
25049 				mp1 = ip_copymsg(first_mp);
25050 				if (mp1 == NULL)
25051 					continue;
25052 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25053 				    mctl_present, B_FALSE, ill,
25054 				    ilm->ilm_zoneid);
25055 				last_zoneid = ilm->ilm_zoneid;
25056 			}
25057 			ILM_WALKER_RELE(ill);
25058 			/*
25059 			 * Loopback case: the sending endpoint has
25060 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25061 			 * dispatch the multicast packet to the sending zone.
25062 			 */
25063 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25064 				freemsg(first_mp);
25065 				return;
25066 			}
25067 		} else if (ire_type == IRE_BROADCAST) {
25068 			/*
25069 			 * In the broadcast case, there may be many zones
25070 			 * which need a copy of the packet delivered to them.
25071 			 * There is one IRE_BROADCAST per broadcast address
25072 			 * and per zone; we walk those using a helper function.
25073 			 * In addition, the sending of the packet for zoneid is
25074 			 * delayed until all of the other ires have been
25075 			 * processed.
25076 			 */
25077 			IRB_REFHOLD(ire->ire_bucket);
25078 			ire_zone = NULL;
25079 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25080 			    ire)) != NULL) {
25081 				mp1 = ip_copymsg(first_mp);
25082 				if (mp1 == NULL)
25083 					continue;
25084 
25085 				UPDATE_IB_PKT_COUNT(ire_zone);
25086 				ire_zone->ire_last_used_time = lbolt;
25087 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25088 				    mctl_present, B_FALSE, ill,
25089 				    ire_zone->ire_zoneid);
25090 			}
25091 			IRB_REFRELE(ire->ire_bucket);
25092 		}
25093 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25094 		    0, mctl_present, B_FALSE, ill, zoneid);
25095 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25096 		    "ip_wput_local_end: q %p (%S)",
25097 		    q, "icmp");
25098 		return;
25099 	}
25100 	case IPPROTO_IGMP:
25101 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25102 			/* Bad packet - discarded by igmp_input */
25103 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25104 			    "ip_wput_local_end: q %p (%S)",
25105 			    q, "igmp_input--bad packet");
25106 			if (mctl_present)
25107 				freeb(first_mp);
25108 			return;
25109 		}
25110 		/*
25111 		 * igmp_input() may have returned the pulled up message.
25112 		 * So first_mp and ipha need to be reinitialized.
25113 		 */
25114 		ipha = (ipha_t *)mp->b_rptr;
25115 		if (mctl_present)
25116 			first_mp->b_cont = mp;
25117 		else
25118 			first_mp = mp;
25119 		/* deliver to local raw users */
25120 		break;
25121 	case IPPROTO_ENCAP:
25122 		/*
25123 		 * This case is covered by either ip_fanout_proto, or by
25124 		 * the above security processing for self-tunneled packets.
25125 		 */
25126 		break;
25127 	case IPPROTO_UDP: {
25128 		uint16_t	*up;
25129 		uint32_t	ports;
25130 
25131 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25132 		    UDP_PORTS_OFFSET);
25133 		/* Force a 'valid' checksum. */
25134 		up[3] = 0;
25135 
25136 		ports = *(uint32_t *)up;
25137 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25138 		    (ire_type == IRE_BROADCAST),
25139 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25140 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25141 		    ill, zoneid);
25142 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25143 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25144 		return;
25145 	}
25146 	case IPPROTO_TCP: {
25147 
25148 		/*
25149 		 * For TCP, discard broadcast packets.
25150 		 */
25151 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25152 			freemsg(first_mp);
25153 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25154 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25155 			return;
25156 		}
25157 
25158 		if (mp->b_datap->db_type == M_DATA) {
25159 			/*
25160 			 * M_DATA mblk, so init mblk (chain) for no struio().
25161 			 */
25162 			mblk_t	*mp1 = mp;
25163 
25164 			do {
25165 				mp1->b_datap->db_struioflag = 0;
25166 			} while ((mp1 = mp1->b_cont) != NULL);
25167 		}
25168 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25169 		    <= mp->b_wptr);
25170 		ip_fanout_tcp(q, first_mp, ill, ipha,
25171 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25172 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25173 		    mctl_present, B_FALSE, zoneid);
25174 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25175 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25176 		return;
25177 	}
25178 	case IPPROTO_SCTP:
25179 	{
25180 		uint32_t	ports;
25181 
25182 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25183 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25184 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25185 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25186 		return;
25187 	}
25188 
25189 	default:
25190 		break;
25191 	}
25192 	/*
25193 	 * Find a client for some other protocol.  We give
25194 	 * copies to multiple clients, if more than one is
25195 	 * bound.
25196 	 */
25197 	ip_fanout_proto(q, first_mp, ill, ipha,
25198 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25199 	    mctl_present, B_FALSE, ill, zoneid);
25200 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25201 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25202 #undef	rptr
25203 }
25204 
25205 /*
25206  * Update any source route, record route, or timestamp options.
25207  * Check that we are at end of strict source route.
25208  * The options have been sanity checked by ip_wput_options().
25209  */
25210 static void
25211 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25212 {
25213 	ipoptp_t	opts;
25214 	uchar_t		*opt;
25215 	uint8_t		optval;
25216 	uint8_t		optlen;
25217 	ipaddr_t	dst;
25218 	uint32_t	ts;
25219 	ire_t		*ire;
25220 	timestruc_t	now;
25221 
25222 	ip2dbg(("ip_wput_local_options\n"));
25223 	for (optval = ipoptp_first(&opts, ipha);
25224 	    optval != IPOPT_EOL;
25225 	    optval = ipoptp_next(&opts)) {
25226 		opt = opts.ipoptp_cur;
25227 		optlen = opts.ipoptp_len;
25228 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25229 		switch (optval) {
25230 			uint32_t off;
25231 		case IPOPT_SSRR:
25232 		case IPOPT_LSRR:
25233 			off = opt[IPOPT_OFFSET];
25234 			off--;
25235 			if (optlen < IP_ADDR_LEN ||
25236 			    off > optlen - IP_ADDR_LEN) {
25237 				/* End of source route */
25238 				break;
25239 			}
25240 			/*
25241 			 * This will only happen if two consecutive entries
25242 			 * in the source route contains our address or if
25243 			 * it is a packet with a loose source route which
25244 			 * reaches us before consuming the whole source route
25245 			 */
25246 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25247 			if (optval == IPOPT_SSRR) {
25248 				return;
25249 			}
25250 			/*
25251 			 * Hack: instead of dropping the packet truncate the
25252 			 * source route to what has been used by filling the
25253 			 * rest with IPOPT_NOP.
25254 			 */
25255 			opt[IPOPT_OLEN] = (uint8_t)off;
25256 			while (off < optlen) {
25257 				opt[off++] = IPOPT_NOP;
25258 			}
25259 			break;
25260 		case IPOPT_RR:
25261 			off = opt[IPOPT_OFFSET];
25262 			off--;
25263 			if (optlen < IP_ADDR_LEN ||
25264 			    off > optlen - IP_ADDR_LEN) {
25265 				/* No more room - ignore */
25266 				ip1dbg((
25267 				    "ip_wput_forward_options: end of RR\n"));
25268 				break;
25269 			}
25270 			dst = htonl(INADDR_LOOPBACK);
25271 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25272 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25273 			break;
25274 		case IPOPT_TS:
25275 			/* Insert timestamp if there is romm */
25276 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25277 			case IPOPT_TS_TSONLY:
25278 				off = IPOPT_TS_TIMELEN;
25279 				break;
25280 			case IPOPT_TS_PRESPEC:
25281 			case IPOPT_TS_PRESPEC_RFC791:
25282 				/* Verify that the address matched */
25283 				off = opt[IPOPT_OFFSET] - 1;
25284 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25285 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25286 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25287 				    ipst);
25288 				if (ire == NULL) {
25289 					/* Not for us */
25290 					break;
25291 				}
25292 				ire_refrele(ire);
25293 				/* FALLTHRU */
25294 			case IPOPT_TS_TSANDADDR:
25295 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25296 				break;
25297 			default:
25298 				/*
25299 				 * ip_*put_options should have already
25300 				 * dropped this packet.
25301 				 */
25302 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25303 				    "unknown IT - bug in ip_wput_options?\n");
25304 				return;	/* Keep "lint" happy */
25305 			}
25306 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25307 				/* Increase overflow counter */
25308 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25309 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25310 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25311 				    (off << 4);
25312 				break;
25313 			}
25314 			off = opt[IPOPT_OFFSET] - 1;
25315 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25316 			case IPOPT_TS_PRESPEC:
25317 			case IPOPT_TS_PRESPEC_RFC791:
25318 			case IPOPT_TS_TSANDADDR:
25319 				dst = htonl(INADDR_LOOPBACK);
25320 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25321 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25322 				/* FALLTHRU */
25323 			case IPOPT_TS_TSONLY:
25324 				off = opt[IPOPT_OFFSET] - 1;
25325 				/* Compute # of milliseconds since midnight */
25326 				gethrestime(&now);
25327 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25328 				    now.tv_nsec / (NANOSEC / MILLISEC);
25329 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25330 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25331 				break;
25332 			}
25333 			break;
25334 		}
25335 	}
25336 }
25337 
25338 /*
25339  * Send out a multicast packet on interface ipif.
25340  * The sender does not have an conn.
25341  * Caller verifies that this isn't a PHYI_LOOPBACK.
25342  */
25343 void
25344 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25345 {
25346 	ipha_t	*ipha;
25347 	ire_t	*ire;
25348 	ipaddr_t	dst;
25349 	mblk_t		*first_mp;
25350 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25351 
25352 	/* igmp_sendpkt always allocates a ipsec_out_t */
25353 	ASSERT(mp->b_datap->db_type == M_CTL);
25354 	ASSERT(!ipif->ipif_isv6);
25355 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25356 
25357 	first_mp = mp;
25358 	mp = first_mp->b_cont;
25359 	ASSERT(mp->b_datap->db_type == M_DATA);
25360 	ipha = (ipha_t *)mp->b_rptr;
25361 
25362 	/*
25363 	 * Find an IRE which matches the destination and the outgoing
25364 	 * queue (i.e. the outgoing interface.)
25365 	 */
25366 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25367 		dst = ipif->ipif_pp_dst_addr;
25368 	else
25369 		dst = ipha->ipha_dst;
25370 	/*
25371 	 * The source address has already been initialized by the
25372 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25373 	 * be sufficient rather than MATCH_IRE_IPIF.
25374 	 *
25375 	 * This function is used for sending IGMP packets. We need
25376 	 * to make sure that we send the packet out of the interface
25377 	 * (ipif->ipif_ill) where we joined the group. This is to
25378 	 * prevent from switches doing IGMP snooping to send us multicast
25379 	 * packets for a given group on the interface we have joined.
25380 	 * If we can't find an ire, igmp_sendpkt has already initialized
25381 	 * ipsec_out_attach_if so that this will not be load spread in
25382 	 * ip_newroute_ipif.
25383 	 */
25384 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25385 	    MATCH_IRE_ILL, ipst);
25386 	if (!ire) {
25387 		/*
25388 		 * Mark this packet to make it be delivered to
25389 		 * ip_wput_ire after the new ire has been
25390 		 * created.
25391 		 */
25392 		mp->b_prev = NULL;
25393 		mp->b_next = NULL;
25394 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25395 		    zoneid, &zero_info);
25396 		return;
25397 	}
25398 
25399 	/*
25400 	 * Honor the RTF_SETSRC flag; this is the only case
25401 	 * where we force this addr whatever the current src addr is,
25402 	 * because this address is set by igmp_sendpkt(), and
25403 	 * cannot be specified by any user.
25404 	 */
25405 	if (ire->ire_flags & RTF_SETSRC) {
25406 		ipha->ipha_src = ire->ire_src_addr;
25407 	}
25408 
25409 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25410 }
25411 
25412 /*
25413  * NOTE : This function does not ire_refrele the ire argument passed in.
25414  *
25415  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25416  * failure. The nce_fp_mp can vanish any time in the case of
25417  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25418  * the ire_lock to access the nce_fp_mp in this case.
25419  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25420  * prepending a fastpath message IPQoS processing must precede it, we also set
25421  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25422  * (IPQoS might have set the b_band for CoS marking).
25423  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25424  * must follow it so that IPQoS can mark the dl_priority field for CoS
25425  * marking, if needed.
25426  */
25427 static mblk_t *
25428 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25429 {
25430 	uint_t	hlen;
25431 	ipha_t *ipha;
25432 	mblk_t *mp1;
25433 	boolean_t qos_done = B_FALSE;
25434 	uchar_t	*ll_hdr;
25435 	ip_stack_t	*ipst = ire->ire_ipst;
25436 
25437 #define	rptr	((uchar_t *)ipha)
25438 
25439 	ipha = (ipha_t *)mp->b_rptr;
25440 	hlen = 0;
25441 	LOCK_IRE_FP_MP(ire);
25442 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25443 		ASSERT(DB_TYPE(mp1) == M_DATA);
25444 		/* Initiate IPPF processing */
25445 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25446 			UNLOCK_IRE_FP_MP(ire);
25447 			ip_process(proc, &mp, ill_index);
25448 			if (mp == NULL)
25449 				return (NULL);
25450 
25451 			ipha = (ipha_t *)mp->b_rptr;
25452 			LOCK_IRE_FP_MP(ire);
25453 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25454 				qos_done = B_TRUE;
25455 				goto no_fp_mp;
25456 			}
25457 			ASSERT(DB_TYPE(mp1) == M_DATA);
25458 		}
25459 		hlen = MBLKL(mp1);
25460 		/*
25461 		 * Check if we have enough room to prepend fastpath
25462 		 * header
25463 		 */
25464 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25465 			ll_hdr = rptr - hlen;
25466 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25467 			/*
25468 			 * Set the b_rptr to the start of the link layer
25469 			 * header
25470 			 */
25471 			mp->b_rptr = ll_hdr;
25472 			mp1 = mp;
25473 		} else {
25474 			mp1 = copyb(mp1);
25475 			if (mp1 == NULL)
25476 				goto unlock_err;
25477 			mp1->b_band = mp->b_band;
25478 			mp1->b_cont = mp;
25479 			/*
25480 			 * certain system generated traffic may not
25481 			 * have cred/label in ip header block. This
25482 			 * is true even for a labeled system. But for
25483 			 * labeled traffic, inherit the label in the
25484 			 * new header.
25485 			 */
25486 			if (DB_CRED(mp) != NULL)
25487 				mblk_setcred(mp1, DB_CRED(mp));
25488 			/*
25489 			 * XXX disable ICK_VALID and compute checksum
25490 			 * here; can happen if nce_fp_mp changes and
25491 			 * it can't be copied now due to insufficient
25492 			 * space. (unlikely, fp mp can change, but it
25493 			 * does not increase in length)
25494 			 */
25495 		}
25496 		UNLOCK_IRE_FP_MP(ire);
25497 	} else {
25498 no_fp_mp:
25499 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25500 		if (mp1 == NULL) {
25501 unlock_err:
25502 			UNLOCK_IRE_FP_MP(ire);
25503 			freemsg(mp);
25504 			return (NULL);
25505 		}
25506 		UNLOCK_IRE_FP_MP(ire);
25507 		mp1->b_cont = mp;
25508 		/*
25509 		 * certain system generated traffic may not
25510 		 * have cred/label in ip header block. This
25511 		 * is true even for a labeled system. But for
25512 		 * labeled traffic, inherit the label in the
25513 		 * new header.
25514 		 */
25515 		if (DB_CRED(mp) != NULL)
25516 			mblk_setcred(mp1, DB_CRED(mp));
25517 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25518 			ip_process(proc, &mp1, ill_index);
25519 			if (mp1 == NULL)
25520 				return (NULL);
25521 		}
25522 	}
25523 	return (mp1);
25524 #undef rptr
25525 }
25526 
25527 /*
25528  * Finish the outbound IPsec processing for an IPv6 packet. This function
25529  * is called from ipsec_out_process() if the IPsec packet was processed
25530  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25531  * asynchronously.
25532  */
25533 void
25534 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25535     ire_t *ire_arg)
25536 {
25537 	in6_addr_t *v6dstp;
25538 	ire_t *ire;
25539 	mblk_t *mp;
25540 	ip6_t *ip6h1;
25541 	uint_t	ill_index;
25542 	ipsec_out_t *io;
25543 	boolean_t attach_if, hwaccel;
25544 	uint32_t flags = IP6_NO_IPPOLICY;
25545 	int match_flags;
25546 	zoneid_t zoneid;
25547 	boolean_t ill_need_rele = B_FALSE;
25548 	boolean_t ire_need_rele = B_FALSE;
25549 	ip_stack_t	*ipst;
25550 
25551 	mp = ipsec_mp->b_cont;
25552 	ip6h1 = (ip6_t *)mp->b_rptr;
25553 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25554 	ASSERT(io->ipsec_out_ns != NULL);
25555 	ipst = io->ipsec_out_ns->netstack_ip;
25556 	ill_index = io->ipsec_out_ill_index;
25557 	if (io->ipsec_out_reachable) {
25558 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25559 	}
25560 	attach_if = io->ipsec_out_attach_if;
25561 	hwaccel = io->ipsec_out_accelerated;
25562 	zoneid = io->ipsec_out_zoneid;
25563 	ASSERT(zoneid != ALL_ZONES);
25564 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25565 	/* Multicast addresses should have non-zero ill_index. */
25566 	v6dstp = &ip6h->ip6_dst;
25567 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25568 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25569 	ASSERT(!attach_if || ill_index != 0);
25570 	if (ill_index != 0) {
25571 		if (ill == NULL) {
25572 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25573 			    B_TRUE, ipst);
25574 
25575 			/* Failure case frees things for us. */
25576 			if (ill == NULL)
25577 				return;
25578 
25579 			ill_need_rele = B_TRUE;
25580 		}
25581 		/*
25582 		 * If this packet needs to go out on a particular interface
25583 		 * honor it.
25584 		 */
25585 		if (attach_if) {
25586 			match_flags = MATCH_IRE_ILL;
25587 
25588 			/*
25589 			 * Check if we need an ire that will not be
25590 			 * looked up by anybody else i.e. HIDDEN.
25591 			 */
25592 			if (ill_is_probeonly(ill)) {
25593 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25594 			}
25595 		}
25596 	}
25597 	ASSERT(mp != NULL);
25598 
25599 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25600 		boolean_t unspec_src;
25601 		ipif_t	*ipif;
25602 
25603 		/*
25604 		 * Use the ill_index to get the right ill.
25605 		 */
25606 		unspec_src = io->ipsec_out_unspec_src;
25607 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25608 		if (ipif == NULL) {
25609 			if (ill_need_rele)
25610 				ill_refrele(ill);
25611 			freemsg(ipsec_mp);
25612 			return;
25613 		}
25614 
25615 		if (ire_arg != NULL) {
25616 			ire = ire_arg;
25617 		} else {
25618 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25619 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25620 			ire_need_rele = B_TRUE;
25621 		}
25622 		if (ire != NULL) {
25623 			ipif_refrele(ipif);
25624 			/*
25625 			 * XXX Do the multicast forwarding now, as the IPsec
25626 			 * processing has been done.
25627 			 */
25628 			goto send;
25629 		}
25630 
25631 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25632 		mp->b_prev = NULL;
25633 		mp->b_next = NULL;
25634 
25635 		/*
25636 		 * If the IPsec packet was processed asynchronously,
25637 		 * drop it now.
25638 		 */
25639 		if (q == NULL) {
25640 			if (ill_need_rele)
25641 				ill_refrele(ill);
25642 			freemsg(ipsec_mp);
25643 			return;
25644 		}
25645 
25646 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25647 		    unspec_src, zoneid);
25648 		ipif_refrele(ipif);
25649 	} else {
25650 		if (attach_if) {
25651 			ipif_t	*ipif;
25652 
25653 			ipif = ipif_get_next_ipif(NULL, ill);
25654 			if (ipif == NULL) {
25655 				if (ill_need_rele)
25656 					ill_refrele(ill);
25657 				freemsg(ipsec_mp);
25658 				return;
25659 			}
25660 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25661 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25662 			ire_need_rele = B_TRUE;
25663 			ipif_refrele(ipif);
25664 		} else {
25665 			if (ire_arg != NULL) {
25666 				ire = ire_arg;
25667 			} else {
25668 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25669 				    ipst);
25670 				ire_need_rele = B_TRUE;
25671 			}
25672 		}
25673 		if (ire != NULL)
25674 			goto send;
25675 		/*
25676 		 * ire disappeared underneath.
25677 		 *
25678 		 * What we need to do here is the ip_newroute
25679 		 * logic to get the ire without doing the IPsec
25680 		 * processing. Follow the same old path. But this
25681 		 * time, ip_wput or ire_add_then_send will call us
25682 		 * directly as all the IPsec operations are done.
25683 		 */
25684 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25685 		mp->b_prev = NULL;
25686 		mp->b_next = NULL;
25687 
25688 		/*
25689 		 * If the IPsec packet was processed asynchronously,
25690 		 * drop it now.
25691 		 */
25692 		if (q == NULL) {
25693 			if (ill_need_rele)
25694 				ill_refrele(ill);
25695 			freemsg(ipsec_mp);
25696 			return;
25697 		}
25698 
25699 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25700 		    zoneid, ipst);
25701 	}
25702 	if (ill != NULL && ill_need_rele)
25703 		ill_refrele(ill);
25704 	return;
25705 send:
25706 	if (ill != NULL && ill_need_rele)
25707 		ill_refrele(ill);
25708 
25709 	/* Local delivery */
25710 	if (ire->ire_stq == NULL) {
25711 		ill_t	*out_ill;
25712 		ASSERT(q != NULL);
25713 
25714 		/* PFHooks: LOOPBACK_OUT */
25715 		out_ill = ire_to_ill(ire);
25716 
25717 		DTRACE_PROBE4(ip6__loopback__out__start,
25718 		    ill_t *, NULL, ill_t *, out_ill,
25719 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25720 
25721 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25722 		    ipst->ips_ipv6firewall_loopback_out,
25723 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25724 
25725 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25726 
25727 		if (ipsec_mp != NULL)
25728 			ip_wput_local_v6(RD(q), out_ill,
25729 			    ip6h, ipsec_mp, ire, 0);
25730 		if (ire_need_rele)
25731 			ire_refrele(ire);
25732 		return;
25733 	}
25734 	/*
25735 	 * Everything is done. Send it out on the wire.
25736 	 * We force the insertion of a fragment header using the
25737 	 * IPH_FRAG_HDR flag in two cases:
25738 	 * - after reception of an ICMPv6 "packet too big" message
25739 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25740 	 * - for multirouted IPv6 packets, so that the receiver can
25741 	 *   discard duplicates according to their fragment identifier
25742 	 */
25743 	/* XXX fix flow control problems. */
25744 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25745 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25746 		if (hwaccel) {
25747 			/*
25748 			 * hardware acceleration does not handle these
25749 			 * "slow path" cases.
25750 			 */
25751 			/* IPsec KSTATS: should bump bean counter here. */
25752 			if (ire_need_rele)
25753 				ire_refrele(ire);
25754 			freemsg(ipsec_mp);
25755 			return;
25756 		}
25757 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25758 		    (mp->b_cont ? msgdsize(mp) :
25759 		    mp->b_wptr - (uchar_t *)ip6h)) {
25760 			/* IPsec KSTATS: should bump bean counter here. */
25761 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25762 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25763 			    msgdsize(mp)));
25764 			if (ire_need_rele)
25765 				ire_refrele(ire);
25766 			freemsg(ipsec_mp);
25767 			return;
25768 		}
25769 		ASSERT(mp->b_prev == NULL);
25770 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25771 		    ntohs(ip6h->ip6_plen) +
25772 		    IPV6_HDR_LEN, ire->ire_max_frag));
25773 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25774 		    ire->ire_max_frag);
25775 	} else {
25776 		UPDATE_OB_PKT_COUNT(ire);
25777 		ire->ire_last_used_time = lbolt;
25778 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25779 	}
25780 	if (ire_need_rele)
25781 		ire_refrele(ire);
25782 	freeb(ipsec_mp);
25783 }
25784 
25785 void
25786 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25787 {
25788 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25789 	da_ipsec_t *hada;	/* data attributes */
25790 	ill_t *ill = (ill_t *)q->q_ptr;
25791 
25792 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25793 
25794 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25795 		/* IPsec KSTATS: Bump lose counter here! */
25796 		freemsg(mp);
25797 		return;
25798 	}
25799 
25800 	/*
25801 	 * It's an IPsec packet that must be
25802 	 * accelerated by the Provider, and the
25803 	 * outbound ill is IPsec acceleration capable.
25804 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25805 	 * to the ill.
25806 	 * IPsec KSTATS: should bump packet counter here.
25807 	 */
25808 
25809 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25810 	if (hada_mp == NULL) {
25811 		/* IPsec KSTATS: should bump packet counter here. */
25812 		freemsg(mp);
25813 		return;
25814 	}
25815 
25816 	hada_mp->b_datap->db_type = M_CTL;
25817 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25818 	hada_mp->b_cont = mp;
25819 
25820 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25821 	bzero(hada, sizeof (da_ipsec_t));
25822 	hada->da_type = IPHADA_M_CTL;
25823 
25824 	putnext(q, hada_mp);
25825 }
25826 
25827 /*
25828  * Finish the outbound IPsec processing. This function is called from
25829  * ipsec_out_process() if the IPsec packet was processed
25830  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25831  * asynchronously.
25832  */
25833 void
25834 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25835     ire_t *ire_arg)
25836 {
25837 	uint32_t v_hlen_tos_len;
25838 	ipaddr_t	dst;
25839 	ipif_t	*ipif = NULL;
25840 	ire_t *ire;
25841 	ire_t *ire1 = NULL;
25842 	mblk_t *next_mp = NULL;
25843 	uint32_t max_frag;
25844 	boolean_t multirt_send = B_FALSE;
25845 	mblk_t *mp;
25846 	ipha_t *ipha1;
25847 	uint_t	ill_index;
25848 	ipsec_out_t *io;
25849 	boolean_t attach_if;
25850 	int match_flags;
25851 	irb_t *irb = NULL;
25852 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25853 	zoneid_t zoneid;
25854 	ipxmit_state_t	pktxmit_state;
25855 	ip_stack_t	*ipst;
25856 
25857 #ifdef	_BIG_ENDIAN
25858 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25859 #else
25860 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25861 #endif
25862 
25863 	mp = ipsec_mp->b_cont;
25864 	ipha1 = (ipha_t *)mp->b_rptr;
25865 	ASSERT(mp != NULL);
25866 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25867 	dst = ipha->ipha_dst;
25868 
25869 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25870 	ill_index = io->ipsec_out_ill_index;
25871 	attach_if = io->ipsec_out_attach_if;
25872 	zoneid = io->ipsec_out_zoneid;
25873 	ASSERT(zoneid != ALL_ZONES);
25874 	ipst = io->ipsec_out_ns->netstack_ip;
25875 	ASSERT(io->ipsec_out_ns != NULL);
25876 
25877 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25878 	if (ill_index != 0) {
25879 		if (ill == NULL) {
25880 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25881 			    ill_index, B_FALSE, ipst);
25882 
25883 			/* Failure case frees things for us. */
25884 			if (ill == NULL)
25885 				return;
25886 
25887 			ill_need_rele = B_TRUE;
25888 		}
25889 		/*
25890 		 * If this packet needs to go out on a particular interface
25891 		 * honor it.
25892 		 */
25893 		if (attach_if) {
25894 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25895 
25896 			/*
25897 			 * Check if we need an ire that will not be
25898 			 * looked up by anybody else i.e. HIDDEN.
25899 			 */
25900 			if (ill_is_probeonly(ill)) {
25901 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25902 			}
25903 		}
25904 	}
25905 
25906 	if (CLASSD(dst)) {
25907 		boolean_t conn_dontroute;
25908 		/*
25909 		 * Use the ill_index to get the right ipif.
25910 		 */
25911 		conn_dontroute = io->ipsec_out_dontroute;
25912 		if (ill_index == 0)
25913 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25914 		else
25915 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25916 		if (ipif == NULL) {
25917 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25918 			    " multicast\n"));
25919 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25920 			freemsg(ipsec_mp);
25921 			goto done;
25922 		}
25923 		/*
25924 		 * ipha_src has already been intialized with the
25925 		 * value of the ipif in ip_wput. All we need now is
25926 		 * an ire to send this downstream.
25927 		 */
25928 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25929 		    MBLK_GETLABEL(mp), match_flags, ipst);
25930 		if (ire != NULL) {
25931 			ill_t *ill1;
25932 			/*
25933 			 * Do the multicast forwarding now, as the IPsec
25934 			 * processing has been done.
25935 			 */
25936 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25937 			    (ill1 = ire_to_ill(ire))) {
25938 				if (ip_mforward(ill1, ipha, mp)) {
25939 					freemsg(ipsec_mp);
25940 					ip1dbg(("ip_wput_ipsec_out: mforward "
25941 					    "failed\n"));
25942 					ire_refrele(ire);
25943 					goto done;
25944 				}
25945 			}
25946 			goto send;
25947 		}
25948 
25949 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25950 		mp->b_prev = NULL;
25951 		mp->b_next = NULL;
25952 
25953 		/*
25954 		 * If the IPsec packet was processed asynchronously,
25955 		 * drop it now.
25956 		 */
25957 		if (q == NULL) {
25958 			freemsg(ipsec_mp);
25959 			goto done;
25960 		}
25961 
25962 		/*
25963 		 * We may be using a wrong ipif to create the ire.
25964 		 * But it is okay as the source address is assigned
25965 		 * for the packet already. Next outbound packet would
25966 		 * create the IRE with the right IPIF in ip_wput.
25967 		 *
25968 		 * Also handle RTF_MULTIRT routes.
25969 		 */
25970 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25971 		    zoneid, &zero_info);
25972 	} else {
25973 		if (attach_if) {
25974 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25975 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25976 		} else {
25977 			if (ire_arg != NULL) {
25978 				ire = ire_arg;
25979 				ire_need_rele = B_FALSE;
25980 			} else {
25981 				ire = ire_cache_lookup(dst, zoneid,
25982 				    MBLK_GETLABEL(mp), ipst);
25983 			}
25984 		}
25985 		if (ire != NULL) {
25986 			goto send;
25987 		}
25988 
25989 		/*
25990 		 * ire disappeared underneath.
25991 		 *
25992 		 * What we need to do here is the ip_newroute
25993 		 * logic to get the ire without doing the IPsec
25994 		 * processing. Follow the same old path. But this
25995 		 * time, ip_wput or ire_add_then_put will call us
25996 		 * directly as all the IPsec operations are done.
25997 		 */
25998 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25999 		mp->b_prev = NULL;
26000 		mp->b_next = NULL;
26001 
26002 		/*
26003 		 * If the IPsec packet was processed asynchronously,
26004 		 * drop it now.
26005 		 */
26006 		if (q == NULL) {
26007 			freemsg(ipsec_mp);
26008 			goto done;
26009 		}
26010 
26011 		/*
26012 		 * Since we're going through ip_newroute() again, we
26013 		 * need to make sure we don't:
26014 		 *
26015 		 *	1.) Trigger the ASSERT() with the ipha_ident
26016 		 *	    overloading.
26017 		 *	2.) Redo transport-layer checksumming, since we've
26018 		 *	    already done all that to get this far.
26019 		 *
26020 		 * The easiest way not do either of the above is to set
26021 		 * the ipha_ident field to IP_HDR_INCLUDED.
26022 		 */
26023 		ipha->ipha_ident = IP_HDR_INCLUDED;
26024 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26025 		    zoneid, ipst);
26026 	}
26027 	goto done;
26028 send:
26029 	if (ire->ire_stq == NULL) {
26030 		ill_t	*out_ill;
26031 		/*
26032 		 * Loopbacks go through ip_wput_local except for one case.
26033 		 * We come here if we generate a icmp_frag_needed message
26034 		 * after IPsec processing is over. When this function calls
26035 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26036 		 * icmp_frag_needed. The message generated comes back here
26037 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26038 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26039 		 * source address as it is usually set in ip_wput_ire. As
26040 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26041 		 * and we end up here. We can't enter ip_wput_ire once the
26042 		 * IPsec processing is over and hence we need to do it here.
26043 		 */
26044 		ASSERT(q != NULL);
26045 		UPDATE_OB_PKT_COUNT(ire);
26046 		ire->ire_last_used_time = lbolt;
26047 		if (ipha->ipha_src == 0)
26048 			ipha->ipha_src = ire->ire_src_addr;
26049 
26050 		/* PFHooks: LOOPBACK_OUT */
26051 		out_ill = ire_to_ill(ire);
26052 
26053 		DTRACE_PROBE4(ip4__loopback__out__start,
26054 		    ill_t *, NULL, ill_t *, out_ill,
26055 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26056 
26057 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26058 		    ipst->ips_ipv4firewall_loopback_out,
26059 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26060 
26061 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26062 
26063 		if (ipsec_mp != NULL)
26064 			ip_wput_local(RD(q), out_ill,
26065 			    ipha, ipsec_mp, ire, 0, zoneid);
26066 		if (ire_need_rele)
26067 			ire_refrele(ire);
26068 		goto done;
26069 	}
26070 
26071 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26072 		/*
26073 		 * We are through with IPsec processing.
26074 		 * Fragment this and send it on the wire.
26075 		 */
26076 		if (io->ipsec_out_accelerated) {
26077 			/*
26078 			 * The packet has been accelerated but must
26079 			 * be fragmented. This should not happen
26080 			 * since AH and ESP must not accelerate
26081 			 * packets that need fragmentation, however
26082 			 * the configuration could have changed
26083 			 * since the AH or ESP processing.
26084 			 * Drop packet.
26085 			 * IPsec KSTATS: bump bean counter here.
26086 			 */
26087 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26088 			    "fragmented accelerated packet!\n"));
26089 			freemsg(ipsec_mp);
26090 		} else {
26091 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26092 		}
26093 		if (ire_need_rele)
26094 			ire_refrele(ire);
26095 		goto done;
26096 	}
26097 
26098 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26099 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26100 	    (void *)ire->ire_ipif, (void *)ipif));
26101 
26102 	/*
26103 	 * Multiroute the secured packet, unless IPsec really
26104 	 * requires the packet to go out only through a particular
26105 	 * interface.
26106 	 */
26107 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26108 		ire_t *first_ire;
26109 		irb = ire->ire_bucket;
26110 		ASSERT(irb != NULL);
26111 		/*
26112 		 * This ire has been looked up as the one that
26113 		 * goes through the given ipif;
26114 		 * make sure we do not omit any other multiroute ire
26115 		 * that may be present in the bucket before this one.
26116 		 */
26117 		IRB_REFHOLD(irb);
26118 		for (first_ire = irb->irb_ire;
26119 		    first_ire != NULL;
26120 		    first_ire = first_ire->ire_next) {
26121 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26122 			    (first_ire->ire_addr == ire->ire_addr) &&
26123 			    !(first_ire->ire_marks &
26124 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26125 				break;
26126 			}
26127 		}
26128 
26129 		if ((first_ire != NULL) && (first_ire != ire)) {
26130 			/*
26131 			 * Don't change the ire if the packet must
26132 			 * be fragmented if sent via this new one.
26133 			 */
26134 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26135 				IRE_REFHOLD(first_ire);
26136 				if (ire_need_rele)
26137 					ire_refrele(ire);
26138 				else
26139 					ire_need_rele = B_TRUE;
26140 				ire = first_ire;
26141 			}
26142 		}
26143 		IRB_REFRELE(irb);
26144 
26145 		multirt_send = B_TRUE;
26146 		max_frag = ire->ire_max_frag;
26147 	} else {
26148 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26149 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26150 			    "flag, attach_if %d\n", attach_if));
26151 		}
26152 	}
26153 
26154 	/*
26155 	 * In most cases, the emission loop below is entered only once.
26156 	 * Only in the case where the ire holds the RTF_MULTIRT
26157 	 * flag, we loop to process all RTF_MULTIRT ires in the
26158 	 * bucket, and send the packet through all crossed
26159 	 * RTF_MULTIRT routes.
26160 	 */
26161 	do {
26162 		if (multirt_send) {
26163 			/*
26164 			 * ire1 holds here the next ire to process in the
26165 			 * bucket. If multirouting is expected,
26166 			 * any non-RTF_MULTIRT ire that has the
26167 			 * right destination address is ignored.
26168 			 */
26169 			ASSERT(irb != NULL);
26170 			IRB_REFHOLD(irb);
26171 			for (ire1 = ire->ire_next;
26172 			    ire1 != NULL;
26173 			    ire1 = ire1->ire_next) {
26174 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26175 					continue;
26176 				if (ire1->ire_addr != ire->ire_addr)
26177 					continue;
26178 				if (ire1->ire_marks &
26179 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26180 					continue;
26181 				/* No loopback here */
26182 				if (ire1->ire_stq == NULL)
26183 					continue;
26184 				/*
26185 				 * Ensure we do not exceed the MTU
26186 				 * of the next route.
26187 				 */
26188 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26189 					ip_multirt_bad_mtu(ire1, max_frag);
26190 					continue;
26191 				}
26192 
26193 				IRE_REFHOLD(ire1);
26194 				break;
26195 			}
26196 			IRB_REFRELE(irb);
26197 			if (ire1 != NULL) {
26198 				/*
26199 				 * We are in a multiple send case, need to
26200 				 * make a copy of the packet.
26201 				 */
26202 				next_mp = copymsg(ipsec_mp);
26203 				if (next_mp == NULL) {
26204 					ire_refrele(ire1);
26205 					ire1 = NULL;
26206 				}
26207 			}
26208 		}
26209 		/*
26210 		 * Everything is done. Send it out on the wire
26211 		 *
26212 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26213 		 * either send it on the wire or, in the case of
26214 		 * HW acceleration, call ipsec_hw_putnext.
26215 		 */
26216 		if (ire->ire_nce &&
26217 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26218 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26219 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26220 			/*
26221 			 * If ire's link-layer is unresolved (this
26222 			 * would only happen if the incomplete ire
26223 			 * was added to cachetable via forwarding path)
26224 			 * don't bother going to ip_xmit_v4. Just drop the
26225 			 * packet.
26226 			 * There is a slight risk here, in that, if we
26227 			 * have the forwarding path create an incomplete
26228 			 * IRE, then until the IRE is completed, any
26229 			 * transmitted IPsec packets will be dropped
26230 			 * instead of being queued waiting for resolution.
26231 			 *
26232 			 * But the likelihood of a forwarding packet and a wput
26233 			 * packet sending to the same dst at the same time
26234 			 * and there not yet be an ARP entry for it is small.
26235 			 * Furthermore, if this actually happens, it might
26236 			 * be likely that wput would generate multiple
26237 			 * packets (and forwarding would also have a train
26238 			 * of packets) for that destination. If this is
26239 			 * the case, some of them would have been dropped
26240 			 * anyway, since ARP only queues a few packets while
26241 			 * waiting for resolution
26242 			 *
26243 			 * NOTE: We should really call ip_xmit_v4,
26244 			 * and let it queue the packet and send the
26245 			 * ARP query and have ARP come back thus:
26246 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26247 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26248 			 * hw accel work. But it's too complex to get
26249 			 * the IPsec hw  acceleration approach to fit
26250 			 * well with ip_xmit_v4 doing ARP without
26251 			 * doing IPsec simplification. For now, we just
26252 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26253 			 * that we can continue with the send on the next
26254 			 * attempt.
26255 			 *
26256 			 * XXX THis should be revisited, when
26257 			 * the IPsec/IP interaction is cleaned up
26258 			 */
26259 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26260 			    " - dropping packet\n"));
26261 			freemsg(ipsec_mp);
26262 			/*
26263 			 * Call ip_xmit_v4() to trigger ARP query
26264 			 * in case the nce_state is ND_INITIAL
26265 			 */
26266 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26267 			goto drop_pkt;
26268 		}
26269 
26270 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26271 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26272 		    mblk_t *, ipsec_mp);
26273 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26274 		    ipst->ips_ipv4firewall_physical_out,
26275 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26276 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26277 		if (ipsec_mp == NULL)
26278 			goto drop_pkt;
26279 
26280 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26281 		pktxmit_state = ip_xmit_v4(mp, ire,
26282 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26283 
26284 		if ((pktxmit_state ==  SEND_FAILED) ||
26285 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26286 
26287 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26288 drop_pkt:
26289 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26290 			    ipIfStatsOutDiscards);
26291 			if (ire_need_rele)
26292 				ire_refrele(ire);
26293 			if (ire1 != NULL) {
26294 				ire_refrele(ire1);
26295 				freemsg(next_mp);
26296 			}
26297 			goto done;
26298 		}
26299 
26300 		freeb(ipsec_mp);
26301 		if (ire_need_rele)
26302 			ire_refrele(ire);
26303 
26304 		if (ire1 != NULL) {
26305 			ire = ire1;
26306 			ire_need_rele = B_TRUE;
26307 			ASSERT(next_mp);
26308 			ipsec_mp = next_mp;
26309 			mp = ipsec_mp->b_cont;
26310 			ire1 = NULL;
26311 			next_mp = NULL;
26312 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26313 		} else {
26314 			multirt_send = B_FALSE;
26315 		}
26316 	} while (multirt_send);
26317 done:
26318 	if (ill != NULL && ill_need_rele)
26319 		ill_refrele(ill);
26320 	if (ipif != NULL)
26321 		ipif_refrele(ipif);
26322 }
26323 
26324 /*
26325  * Get the ill corresponding to the specified ire, and compare its
26326  * capabilities with the protocol and algorithms specified by the
26327  * the SA obtained from ipsec_out. If they match, annotate the
26328  * ipsec_out structure to indicate that the packet needs acceleration.
26329  *
26330  *
26331  * A packet is eligible for outbound hardware acceleration if the
26332  * following conditions are satisfied:
26333  *
26334  * 1. the packet will not be fragmented
26335  * 2. the provider supports the algorithm
26336  * 3. there is no pending control message being exchanged
26337  * 4. snoop is not attached
26338  * 5. the destination address is not a broadcast or multicast address.
26339  *
26340  * Rationale:
26341  *	- Hardware drivers do not support fragmentation with
26342  *	  the current interface.
26343  *	- snoop, multicast, and broadcast may result in exposure of
26344  *	  a cleartext datagram.
26345  * We check all five of these conditions here.
26346  *
26347  * XXX would like to nuke "ire_t *" parameter here; problem is that
26348  * IRE is only way to figure out if a v4 address is a broadcast and
26349  * thus ineligible for acceleration...
26350  */
26351 static void
26352 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26353 {
26354 	ipsec_out_t *io;
26355 	mblk_t *data_mp;
26356 	uint_t plen, overhead;
26357 	ip_stack_t	*ipst;
26358 
26359 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26360 		return;
26361 
26362 	if (ill == NULL)
26363 		return;
26364 	ipst = ill->ill_ipst;
26365 	/*
26366 	 * Destination address is a broadcast or multicast.  Punt.
26367 	 */
26368 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26369 	    IRE_LOCAL)))
26370 		return;
26371 
26372 	data_mp = ipsec_mp->b_cont;
26373 
26374 	if (ill->ill_isv6) {
26375 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26376 
26377 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26378 			return;
26379 
26380 		plen = ip6h->ip6_plen;
26381 	} else {
26382 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26383 
26384 		if (CLASSD(ipha->ipha_dst))
26385 			return;
26386 
26387 		plen = ipha->ipha_length;
26388 	}
26389 	/*
26390 	 * Is there a pending DLPI control message being exchanged
26391 	 * between IP/IPsec and the DLS Provider? If there is, it
26392 	 * could be a SADB update, and the state of the DLS Provider
26393 	 * SADB might not be in sync with the SADB maintained by
26394 	 * IPsec. To avoid dropping packets or using the wrong keying
26395 	 * material, we do not accelerate this packet.
26396 	 */
26397 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26398 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26399 		    "ill_dlpi_pending! don't accelerate packet\n"));
26400 		return;
26401 	}
26402 
26403 	/*
26404 	 * Is the Provider in promiscous mode? If it does, we don't
26405 	 * accelerate the packet since it will bounce back up to the
26406 	 * listeners in the clear.
26407 	 */
26408 	if (ill->ill_promisc_on_phys) {
26409 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26410 		    "ill in promiscous mode, don't accelerate packet\n"));
26411 		return;
26412 	}
26413 
26414 	/*
26415 	 * Will the packet require fragmentation?
26416 	 */
26417 
26418 	/*
26419 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26420 	 * as is used elsewhere.
26421 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26422 	 *	+ 2-byte trailer
26423 	 */
26424 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26425 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26426 
26427 	if ((plen + overhead) > ill->ill_max_mtu)
26428 		return;
26429 
26430 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26431 
26432 	/*
26433 	 * Can the ill accelerate this IPsec protocol and algorithm
26434 	 * specified by the SA?
26435 	 */
26436 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26437 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26438 		return;
26439 	}
26440 
26441 	/*
26442 	 * Tell AH or ESP that the outbound ill is capable of
26443 	 * accelerating this packet.
26444 	 */
26445 	io->ipsec_out_is_capab_ill = B_TRUE;
26446 }
26447 
26448 /*
26449  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26450  *
26451  * If this function returns B_TRUE, the requested SA's have been filled
26452  * into the ipsec_out_*_sa pointers.
26453  *
26454  * If the function returns B_FALSE, the packet has been "consumed", most
26455  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26456  *
26457  * The SA references created by the protocol-specific "select"
26458  * function will be released when the ipsec_mp is freed, thanks to the
26459  * ipsec_out_free destructor -- see spd.c.
26460  */
26461 static boolean_t
26462 ipsec_out_select_sa(mblk_t *ipsec_mp)
26463 {
26464 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26465 	ipsec_out_t *io;
26466 	ipsec_policy_t *pp;
26467 	ipsec_action_t *ap;
26468 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26469 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26470 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26471 
26472 	if (!io->ipsec_out_secure) {
26473 		/*
26474 		 * We came here by mistake.
26475 		 * Don't bother with ipsec processing
26476 		 * We should "discourage" this path in the future.
26477 		 */
26478 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26479 		return (B_FALSE);
26480 	}
26481 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26482 	ASSERT((io->ipsec_out_policy != NULL) ||
26483 	    (io->ipsec_out_act != NULL));
26484 
26485 	ASSERT(io->ipsec_out_failed == B_FALSE);
26486 
26487 	/*
26488 	 * IPsec processing has started.
26489 	 */
26490 	io->ipsec_out_proc_begin = B_TRUE;
26491 	ap = io->ipsec_out_act;
26492 	if (ap == NULL) {
26493 		pp = io->ipsec_out_policy;
26494 		ASSERT(pp != NULL);
26495 		ap = pp->ipsp_act;
26496 		ASSERT(ap != NULL);
26497 	}
26498 
26499 	/*
26500 	 * We have an action.  now, let's select SA's.
26501 	 * (In the future, we can cache this in the conn_t..)
26502 	 */
26503 	if (ap->ipa_want_esp) {
26504 		if (io->ipsec_out_esp_sa == NULL) {
26505 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26506 			    IPPROTO_ESP);
26507 		}
26508 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26509 	}
26510 
26511 	if (ap->ipa_want_ah) {
26512 		if (io->ipsec_out_ah_sa == NULL) {
26513 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26514 			    IPPROTO_AH);
26515 		}
26516 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26517 		/*
26518 		 * The ESP and AH processing order needs to be preserved
26519 		 * when both protocols are required (ESP should be applied
26520 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26521 		 * when both ESP and AH are required, and an AH ACQUIRE
26522 		 * is needed.
26523 		 */
26524 		if (ap->ipa_want_esp && need_ah_acquire)
26525 			need_esp_acquire = B_TRUE;
26526 	}
26527 
26528 	/*
26529 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26530 	 * Release SAs that got referenced, but will not be used until we
26531 	 * acquire _all_ of the SAs we need.
26532 	 */
26533 	if (need_ah_acquire || need_esp_acquire) {
26534 		if (io->ipsec_out_ah_sa != NULL) {
26535 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26536 			io->ipsec_out_ah_sa = NULL;
26537 		}
26538 		if (io->ipsec_out_esp_sa != NULL) {
26539 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26540 			io->ipsec_out_esp_sa = NULL;
26541 		}
26542 
26543 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26544 		return (B_FALSE);
26545 	}
26546 
26547 	return (B_TRUE);
26548 }
26549 
26550 /*
26551  * Process an IPSEC_OUT message and see what you can
26552  * do with it.
26553  * IPQoS Notes:
26554  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26555  * IPsec.
26556  * XXX would like to nuke ire_t.
26557  * XXX ill_index better be "real"
26558  */
26559 void
26560 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26561 {
26562 	ipsec_out_t *io;
26563 	ipsec_policy_t *pp;
26564 	ipsec_action_t *ap;
26565 	ipha_t *ipha;
26566 	ip6_t *ip6h;
26567 	mblk_t *mp;
26568 	ill_t *ill;
26569 	zoneid_t zoneid;
26570 	ipsec_status_t ipsec_rc;
26571 	boolean_t ill_need_rele = B_FALSE;
26572 	ip_stack_t	*ipst;
26573 	ipsec_stack_t	*ipss;
26574 
26575 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26576 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26577 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26578 	ipst = io->ipsec_out_ns->netstack_ip;
26579 	mp = ipsec_mp->b_cont;
26580 
26581 	/*
26582 	 * Initiate IPPF processing. We do it here to account for packets
26583 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26584 	 * We can check for ipsec_out_proc_begin even for such packets, as
26585 	 * they will always be false (asserted below).
26586 	 */
26587 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26588 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26589 		    io->ipsec_out_ill_index : ill_index);
26590 		if (mp == NULL) {
26591 			ip2dbg(("ipsec_out_process: packet dropped "\
26592 			    "during IPPF processing\n"));
26593 			freeb(ipsec_mp);
26594 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26595 			return;
26596 		}
26597 	}
26598 
26599 	if (!io->ipsec_out_secure) {
26600 		/*
26601 		 * We came here by mistake.
26602 		 * Don't bother with ipsec processing
26603 		 * Should "discourage" this path in the future.
26604 		 */
26605 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26606 		goto done;
26607 	}
26608 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26609 	ASSERT((io->ipsec_out_policy != NULL) ||
26610 	    (io->ipsec_out_act != NULL));
26611 	ASSERT(io->ipsec_out_failed == B_FALSE);
26612 
26613 	ipss = ipst->ips_netstack->netstack_ipsec;
26614 	if (!ipsec_loaded(ipss)) {
26615 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26616 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26617 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26618 		} else {
26619 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26620 		}
26621 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26622 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26623 		    &ipss->ipsec_dropper);
26624 		return;
26625 	}
26626 
26627 	/*
26628 	 * IPsec processing has started.
26629 	 */
26630 	io->ipsec_out_proc_begin = B_TRUE;
26631 	ap = io->ipsec_out_act;
26632 	if (ap == NULL) {
26633 		pp = io->ipsec_out_policy;
26634 		ASSERT(pp != NULL);
26635 		ap = pp->ipsp_act;
26636 		ASSERT(ap != NULL);
26637 	}
26638 
26639 	/*
26640 	 * Save the outbound ill index. When the packet comes back
26641 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26642 	 * before sending it the accelerated packet.
26643 	 */
26644 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26645 		int ifindex;
26646 		ill = ire_to_ill(ire);
26647 		ifindex = ill->ill_phyint->phyint_ifindex;
26648 		io->ipsec_out_capab_ill_index = ifindex;
26649 	}
26650 
26651 	/*
26652 	 * The order of processing is first insert a IP header if needed.
26653 	 * Then insert the ESP header and then the AH header.
26654 	 */
26655 	if ((io->ipsec_out_se_done == B_FALSE) &&
26656 	    (ap->ipa_want_se)) {
26657 		/*
26658 		 * First get the outer IP header before sending
26659 		 * it to ESP.
26660 		 */
26661 		ipha_t *oipha, *iipha;
26662 		mblk_t *outer_mp, *inner_mp;
26663 
26664 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26665 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26666 			    "ipsec_out_process: "
26667 			    "Self-Encapsulation failed: Out of memory\n");
26668 			freemsg(ipsec_mp);
26669 			if (ill != NULL) {
26670 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26671 			} else {
26672 				BUMP_MIB(&ipst->ips_ip_mib,
26673 				    ipIfStatsOutDiscards);
26674 			}
26675 			return;
26676 		}
26677 		inner_mp = ipsec_mp->b_cont;
26678 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26679 		oipha = (ipha_t *)outer_mp->b_rptr;
26680 		iipha = (ipha_t *)inner_mp->b_rptr;
26681 		*oipha = *iipha;
26682 		outer_mp->b_wptr += sizeof (ipha_t);
26683 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26684 		    sizeof (ipha_t));
26685 		oipha->ipha_protocol = IPPROTO_ENCAP;
26686 		oipha->ipha_version_and_hdr_length =
26687 		    IP_SIMPLE_HDR_VERSION;
26688 		oipha->ipha_hdr_checksum = 0;
26689 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26690 		outer_mp->b_cont = inner_mp;
26691 		ipsec_mp->b_cont = outer_mp;
26692 
26693 		io->ipsec_out_se_done = B_TRUE;
26694 		io->ipsec_out_tunnel = B_TRUE;
26695 	}
26696 
26697 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26698 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26699 	    !ipsec_out_select_sa(ipsec_mp))
26700 		return;
26701 
26702 	/*
26703 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26704 	 * to do the heavy lifting.
26705 	 */
26706 	zoneid = io->ipsec_out_zoneid;
26707 	ASSERT(zoneid != ALL_ZONES);
26708 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26709 		ASSERT(io->ipsec_out_esp_sa != NULL);
26710 		io->ipsec_out_esp_done = B_TRUE;
26711 		/*
26712 		 * Note that since hw accel can only apply one transform,
26713 		 * not two, we skip hw accel for ESP if we also have AH
26714 		 * This is an design limitation of the interface
26715 		 * which should be revisited.
26716 		 */
26717 		ASSERT(ire != NULL);
26718 		if (io->ipsec_out_ah_sa == NULL) {
26719 			ill = (ill_t *)ire->ire_stq->q_ptr;
26720 			ipsec_out_is_accelerated(ipsec_mp,
26721 			    io->ipsec_out_esp_sa, ill, ire);
26722 		}
26723 
26724 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26725 		switch (ipsec_rc) {
26726 		case IPSEC_STATUS_SUCCESS:
26727 			break;
26728 		case IPSEC_STATUS_FAILED:
26729 			if (ill != NULL) {
26730 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26731 			} else {
26732 				BUMP_MIB(&ipst->ips_ip_mib,
26733 				    ipIfStatsOutDiscards);
26734 			}
26735 			/* FALLTHRU */
26736 		case IPSEC_STATUS_PENDING:
26737 			return;
26738 		}
26739 	}
26740 
26741 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26742 		ASSERT(io->ipsec_out_ah_sa != NULL);
26743 		io->ipsec_out_ah_done = B_TRUE;
26744 		if (ire == NULL) {
26745 			int idx = io->ipsec_out_capab_ill_index;
26746 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26747 			    NULL, NULL, NULL, NULL, ipst);
26748 			ill_need_rele = B_TRUE;
26749 		} else {
26750 			ill = (ill_t *)ire->ire_stq->q_ptr;
26751 		}
26752 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26753 		    ire);
26754 
26755 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26756 		switch (ipsec_rc) {
26757 		case IPSEC_STATUS_SUCCESS:
26758 			break;
26759 		case IPSEC_STATUS_FAILED:
26760 			if (ill != NULL) {
26761 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26762 			} else {
26763 				BUMP_MIB(&ipst->ips_ip_mib,
26764 				    ipIfStatsOutDiscards);
26765 			}
26766 			/* FALLTHRU */
26767 		case IPSEC_STATUS_PENDING:
26768 			if (ill != NULL && ill_need_rele)
26769 				ill_refrele(ill);
26770 			return;
26771 		}
26772 	}
26773 	/*
26774 	 * We are done with IPsec processing. Send it over
26775 	 * the wire.
26776 	 */
26777 done:
26778 	mp = ipsec_mp->b_cont;
26779 	ipha = (ipha_t *)mp->b_rptr;
26780 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26781 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26782 	} else {
26783 		ip6h = (ip6_t *)ipha;
26784 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26785 	}
26786 	if (ill != NULL && ill_need_rele)
26787 		ill_refrele(ill);
26788 }
26789 
26790 /* ARGSUSED */
26791 void
26792 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26793 {
26794 	opt_restart_t	*or;
26795 	int	err;
26796 	conn_t	*connp;
26797 
26798 	ASSERT(CONN_Q(q));
26799 	connp = Q_TO_CONN(q);
26800 
26801 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26802 	or = (opt_restart_t *)first_mp->b_rptr;
26803 	/*
26804 	 * We don't need to pass any credentials here since this is just
26805 	 * a restart. The credentials are passed in when svr4_optcom_req
26806 	 * is called the first time (from ip_wput_nondata).
26807 	 */
26808 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26809 		err = svr4_optcom_req(q, first_mp, NULL,
26810 		    &ip_opt_obj);
26811 	} else {
26812 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26813 		err = tpi_optcom_req(q, first_mp, NULL,
26814 		    &ip_opt_obj);
26815 	}
26816 	if (err != EINPROGRESS) {
26817 		/* operation is done */
26818 		CONN_OPER_PENDING_DONE(connp);
26819 	}
26820 }
26821 
26822 /*
26823  * ioctls that go through a down/up sequence may need to wait for the down
26824  * to complete. This involves waiting for the ire and ipif refcnts to go down
26825  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26826  */
26827 /* ARGSUSED */
26828 void
26829 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26830 {
26831 	struct iocblk *iocp;
26832 	mblk_t *mp1;
26833 	ip_ioctl_cmd_t *ipip;
26834 	int err;
26835 	sin_t	*sin;
26836 	struct lifreq *lifr;
26837 	struct ifreq *ifr;
26838 
26839 	iocp = (struct iocblk *)mp->b_rptr;
26840 	ASSERT(ipsq != NULL);
26841 	/* Existence of mp1 verified in ip_wput_nondata */
26842 	mp1 = mp->b_cont->b_cont;
26843 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26844 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26845 		/*
26846 		 * Special case where ipsq_current_ipif is not set:
26847 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26848 		 * ill could also have become part of a ipmp group in the
26849 		 * process, we are here as were not able to complete the
26850 		 * operation in ipif_set_values because we could not become
26851 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26852 		 * will not be set so we need to set it.
26853 		 */
26854 		ill_t *ill = q->q_ptr;
26855 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26856 	}
26857 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26858 
26859 	if (ipip->ipi_cmd_type == IF_CMD) {
26860 		/* This a old style SIOC[GS]IF* command */
26861 		ifr = (struct ifreq *)mp1->b_rptr;
26862 		sin = (sin_t *)&ifr->ifr_addr;
26863 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26864 		/* This a new style SIOC[GS]LIF* command */
26865 		lifr = (struct lifreq *)mp1->b_rptr;
26866 		sin = (sin_t *)&lifr->lifr_addr;
26867 	} else {
26868 		sin = NULL;
26869 	}
26870 
26871 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26872 	    ipip, mp1->b_rptr);
26873 
26874 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26875 }
26876 
26877 /*
26878  * ioctl processing
26879  *
26880  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26881  * the ioctl command in the ioctl tables, determines the copyin data size
26882  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26883  *
26884  * ioctl processing then continues when the M_IOCDATA makes its way down to
26885  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26886  * associated 'conn' is refheld till the end of the ioctl and the general
26887  * ioctl processing function ip_process_ioctl() is called to extract the
26888  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26889  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26890  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26891  * is used to extract the ioctl's arguments.
26892  *
26893  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26894  * so goes thru the serialization primitive ipsq_try_enter. Then the
26895  * appropriate function to handle the ioctl is called based on the entry in
26896  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26897  * which also refreleases the 'conn' that was refheld at the start of the
26898  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26899  *
26900  * Many exclusive ioctls go thru an internal down up sequence as part of
26901  * the operation. For example an attempt to change the IP address of an
26902  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26903  * does all the cleanup such as deleting all ires that use this address.
26904  * Then we need to wait till all references to the interface go away.
26905  */
26906 void
26907 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26908 {
26909 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26910 	ip_ioctl_cmd_t *ipip = arg;
26911 	ip_extract_func_t *extract_funcp;
26912 	cmd_info_t ci;
26913 	int err;
26914 	boolean_t entered_ipsq = B_FALSE;
26915 
26916 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26917 
26918 	if (ipip == NULL)
26919 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26920 
26921 	/*
26922 	 * SIOCLIFADDIF needs to go thru a special path since the
26923 	 * ill may not exist yet. This happens in the case of lo0
26924 	 * which is created using this ioctl.
26925 	 */
26926 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26927 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26928 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26929 		return;
26930 	}
26931 
26932 	ci.ci_ipif = NULL;
26933 	if (ipip->ipi_cmd_type == MISC_CMD) {
26934 		/*
26935 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26936 		 */
26937 		if (ipip->ipi_cmd == IF_UNITSEL) {
26938 			/* ioctl comes down the ill */
26939 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26940 			ipif_refhold(ci.ci_ipif);
26941 		}
26942 		err = 0;
26943 		ci.ci_sin = NULL;
26944 		ci.ci_sin6 = NULL;
26945 		ci.ci_lifr = NULL;
26946 	} else {
26947 		switch (ipip->ipi_cmd_type) {
26948 		case IF_CMD:
26949 		case LIF_CMD:
26950 			extract_funcp = ip_extract_lifreq;
26951 			break;
26952 
26953 		case ARP_CMD:
26954 		case XARP_CMD:
26955 			extract_funcp = ip_extract_arpreq;
26956 			break;
26957 
26958 		case TUN_CMD:
26959 			extract_funcp = ip_extract_tunreq;
26960 			break;
26961 
26962 		case MSFILT_CMD:
26963 			extract_funcp = ip_extract_msfilter;
26964 			break;
26965 
26966 		default:
26967 			ASSERT(0);
26968 		}
26969 
26970 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26971 		if (err != 0) {
26972 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26973 			return;
26974 		}
26975 
26976 		/*
26977 		 * All of the extraction functions return a refheld ipif.
26978 		 */
26979 		ASSERT(ci.ci_ipif != NULL);
26980 	}
26981 
26982 	/*
26983 	 * If ipsq is non-null, we are already being called exclusively
26984 	 */
26985 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26986 	if (!(ipip->ipi_flags & IPI_WR)) {
26987 		/*
26988 		 * A return value of EINPROGRESS means the ioctl is
26989 		 * either queued and waiting for some reason or has
26990 		 * already completed.
26991 		 */
26992 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26993 		    ci.ci_lifr);
26994 		if (ci.ci_ipif != NULL)
26995 			ipif_refrele(ci.ci_ipif);
26996 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26997 		return;
26998 	}
26999 
27000 	ASSERT(ci.ci_ipif != NULL);
27001 
27002 	if (ipsq == NULL) {
27003 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27004 		    ip_process_ioctl, NEW_OP, B_TRUE);
27005 		entered_ipsq = B_TRUE;
27006 	}
27007 	/*
27008 	 * Release the ipif so that ipif_down and friends that wait for
27009 	 * references to go away are not misled about the current ipif_refcnt
27010 	 * values. We are writer so we can access the ipif even after releasing
27011 	 * the ipif.
27012 	 */
27013 	ipif_refrele(ci.ci_ipif);
27014 	if (ipsq == NULL)
27015 		return;
27016 
27017 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27018 
27019 	/*
27020 	 * For most set ioctls that come here, this serves as a single point
27021 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27022 	 * be any new references to the ipif. This helps functions that go
27023 	 * through this path and end up trying to wait for the refcnts
27024 	 * associated with the ipif to go down to zero. Some exceptions are
27025 	 * Failover, Failback, and Groupname commands that operate on more than
27026 	 * just the ci.ci_ipif. These commands internally determine the
27027 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27028 	 * flags on that set. Another exception is the Removeif command that
27029 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27030 	 * ipif to operate on.
27031 	 */
27032 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27033 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27034 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27035 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27036 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27037 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27038 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27039 
27040 	/*
27041 	 * A return value of EINPROGRESS means the ioctl is
27042 	 * either queued and waiting for some reason or has
27043 	 * already completed.
27044 	 */
27045 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27046 
27047 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27048 
27049 	if (entered_ipsq)
27050 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27051 }
27052 
27053 /*
27054  * Complete the ioctl. Typically ioctls use the mi package and need to
27055  * do mi_copyout/mi_copy_done.
27056  */
27057 void
27058 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27059 {
27060 	conn_t	*connp = NULL;
27061 
27062 	if (err == EINPROGRESS)
27063 		return;
27064 
27065 	if (CONN_Q(q)) {
27066 		connp = Q_TO_CONN(q);
27067 		ASSERT(connp->conn_ref >= 2);
27068 	}
27069 
27070 	switch (mode) {
27071 	case COPYOUT:
27072 		if (err == 0)
27073 			mi_copyout(q, mp);
27074 		else
27075 			mi_copy_done(q, mp, err);
27076 		break;
27077 
27078 	case NO_COPYOUT:
27079 		mi_copy_done(q, mp, err);
27080 		break;
27081 
27082 	default:
27083 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27084 		break;
27085 	}
27086 
27087 	/*
27088 	 * The refhold placed at the start of the ioctl is released here.
27089 	 */
27090 	if (connp != NULL)
27091 		CONN_OPER_PENDING_DONE(connp);
27092 
27093 	if (ipsq != NULL)
27094 		ipsq_current_finish(ipsq);
27095 }
27096 
27097 /*
27098  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27099  */
27100 /* ARGSUSED */
27101 void
27102 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27103 {
27104 	conn_t *connp = arg;
27105 	tcp_t	*tcp;
27106 
27107 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27108 	tcp = connp->conn_tcp;
27109 
27110 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27111 		freemsg(mp);
27112 	else
27113 		tcp_rput_other(tcp, mp);
27114 	CONN_OPER_PENDING_DONE(connp);
27115 }
27116 
27117 /* Called from ip_wput for all non data messages */
27118 /* ARGSUSED */
27119 void
27120 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27121 {
27122 	mblk_t		*mp1;
27123 	ire_t		*ire, *fake_ire;
27124 	ill_t		*ill;
27125 	struct iocblk	*iocp;
27126 	ip_ioctl_cmd_t	*ipip;
27127 	cred_t		*cr;
27128 	conn_t		*connp;
27129 	int		err;
27130 	nce_t		*nce;
27131 	ipif_t		*ipif;
27132 	ip_stack_t	*ipst;
27133 	char		*proto_str;
27134 
27135 	if (CONN_Q(q)) {
27136 		connp = Q_TO_CONN(q);
27137 		ipst = connp->conn_netstack->netstack_ip;
27138 	} else {
27139 		connp = NULL;
27140 		ipst = ILLQ_TO_IPST(q);
27141 	}
27142 
27143 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27144 
27145 	/* Check if it is a queue to /dev/sctp. */
27146 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
27147 	    connp->conn_rq == NULL) {
27148 		sctp_wput(q, mp);
27149 		return;
27150 	}
27151 
27152 	switch (DB_TYPE(mp)) {
27153 	case M_IOCTL:
27154 		/*
27155 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27156 		 * will arrange to copy in associated control structures.
27157 		 */
27158 		ip_sioctl_copyin_setup(q, mp);
27159 		return;
27160 	case M_IOCDATA:
27161 		/*
27162 		 * Ensure that this is associated with one of our trans-
27163 		 * parent ioctls.  If it's not ours, discard it if we're
27164 		 * running as a driver, or pass it on if we're a module.
27165 		 */
27166 		iocp = (struct iocblk *)mp->b_rptr;
27167 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27168 		if (ipip == NULL) {
27169 			if (q->q_next == NULL) {
27170 				goto nak;
27171 			} else {
27172 				putnext(q, mp);
27173 			}
27174 			return;
27175 		}
27176 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27177 			/*
27178 			 * the ioctl is one we recognise, but is not
27179 			 * consumed by IP as a module, pass M_IOCDATA
27180 			 * for processing downstream, but only for
27181 			 * common Streams ioctls.
27182 			 */
27183 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27184 				putnext(q, mp);
27185 				return;
27186 			} else {
27187 				goto nak;
27188 			}
27189 		}
27190 
27191 		/* IOCTL continuation following copyin or copyout. */
27192 		if (mi_copy_state(q, mp, NULL) == -1) {
27193 			/*
27194 			 * The copy operation failed.  mi_copy_state already
27195 			 * cleaned up, so we're out of here.
27196 			 */
27197 			return;
27198 		}
27199 		/*
27200 		 * If we just completed a copy in, we become writer and
27201 		 * continue processing in ip_sioctl_copyin_done.  If it
27202 		 * was a copy out, we call mi_copyout again.  If there is
27203 		 * nothing more to copy out, it will complete the IOCTL.
27204 		 */
27205 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27206 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27207 				mi_copy_done(q, mp, EPROTO);
27208 				return;
27209 			}
27210 			/*
27211 			 * Check for cases that need more copying.  A return
27212 			 * value of 0 means a second copyin has been started,
27213 			 * so we return; a return value of 1 means no more
27214 			 * copying is needed, so we continue.
27215 			 */
27216 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27217 			    MI_COPY_COUNT(mp) == 1) {
27218 				if (ip_copyin_msfilter(q, mp) == 0)
27219 					return;
27220 			}
27221 			/*
27222 			 * Refhold the conn, till the ioctl completes. This is
27223 			 * needed in case the ioctl ends up in the pending mp
27224 			 * list. Every mp in the ill_pending_mp list and
27225 			 * the ipsq_pending_mp must have a refhold on the conn
27226 			 * to resume processing. The refhold is released when
27227 			 * the ioctl completes. (normally or abnormally)
27228 			 * In all cases ip_ioctl_finish is called to finish
27229 			 * the ioctl.
27230 			 */
27231 			if (connp != NULL) {
27232 				/* This is not a reentry */
27233 				ASSERT(ipsq == NULL);
27234 				CONN_INC_REF(connp);
27235 			} else {
27236 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27237 					mi_copy_done(q, mp, EINVAL);
27238 					return;
27239 				}
27240 			}
27241 
27242 			ip_process_ioctl(ipsq, q, mp, ipip);
27243 
27244 		} else {
27245 			mi_copyout(q, mp);
27246 		}
27247 		return;
27248 nak:
27249 		iocp->ioc_error = EINVAL;
27250 		mp->b_datap->db_type = M_IOCNAK;
27251 		iocp->ioc_count = 0;
27252 		qreply(q, mp);
27253 		return;
27254 
27255 	case M_IOCNAK:
27256 		/*
27257 		 * The only way we could get here is if a resolver didn't like
27258 		 * an IOCTL we sent it.	 This shouldn't happen.
27259 		 */
27260 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27261 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27262 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27263 		freemsg(mp);
27264 		return;
27265 	case M_IOCACK:
27266 		/* /dev/ip shouldn't see this */
27267 		if (CONN_Q(q))
27268 			goto nak;
27269 
27270 		/* Finish socket ioctls passed through to ARP. */
27271 		ip_sioctl_iocack(q, mp);
27272 		return;
27273 	case M_FLUSH:
27274 		if (*mp->b_rptr & FLUSHW)
27275 			flushq(q, FLUSHALL);
27276 		if (q->q_next) {
27277 			putnext(q, mp);
27278 			return;
27279 		}
27280 		if (*mp->b_rptr & FLUSHR) {
27281 			*mp->b_rptr &= ~FLUSHW;
27282 			qreply(q, mp);
27283 			return;
27284 		}
27285 		freemsg(mp);
27286 		return;
27287 	case IRE_DB_REQ_TYPE:
27288 		if (connp == NULL) {
27289 			proto_str = "IRE_DB_REQ_TYPE";
27290 			goto protonak;
27291 		}
27292 		/* An Upper Level Protocol wants a copy of an IRE. */
27293 		ip_ire_req(q, mp);
27294 		return;
27295 	case M_CTL:
27296 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27297 			break;
27298 
27299 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27300 		    TUN_HELLO) {
27301 			ASSERT(connp != NULL);
27302 			connp->conn_flags |= IPCL_IPTUN;
27303 			freeb(mp);
27304 			return;
27305 		}
27306 
27307 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27308 		    IP_ULP_OUT_LABELED) {
27309 			out_labeled_t *olp;
27310 
27311 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27312 				break;
27313 			olp = (out_labeled_t *)mp->b_rptr;
27314 			connp->conn_ulp_labeled = olp->out_qnext == q;
27315 			freemsg(mp);
27316 			return;
27317 		}
27318 
27319 		/* M_CTL messages are used by ARP to tell us things. */
27320 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27321 			break;
27322 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27323 		case AR_ENTRY_SQUERY:
27324 			ip_wput_ctl(q, mp);
27325 			return;
27326 		case AR_CLIENT_NOTIFY:
27327 			ip_arp_news(q, mp);
27328 			return;
27329 		case AR_DLPIOP_DONE:
27330 			ASSERT(q->q_next != NULL);
27331 			ill = (ill_t *)q->q_ptr;
27332 			/* qwriter_ip releases the refhold */
27333 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27334 			ill_refhold(ill);
27335 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27336 			return;
27337 		case AR_ARP_CLOSING:
27338 			/*
27339 			 * ARP (above us) is closing. If no ARP bringup is
27340 			 * currently pending, ack the message so that ARP
27341 			 * can complete its close. Also mark ill_arp_closing
27342 			 * so that new ARP bringups will fail. If any
27343 			 * ARP bringup is currently in progress, we will
27344 			 * ack this when the current ARP bringup completes.
27345 			 */
27346 			ASSERT(q->q_next != NULL);
27347 			ill = (ill_t *)q->q_ptr;
27348 			mutex_enter(&ill->ill_lock);
27349 			ill->ill_arp_closing = 1;
27350 			if (!ill->ill_arp_bringup_pending) {
27351 				mutex_exit(&ill->ill_lock);
27352 				qreply(q, mp);
27353 			} else {
27354 				mutex_exit(&ill->ill_lock);
27355 				freemsg(mp);
27356 			}
27357 			return;
27358 		case AR_ARP_EXTEND:
27359 			/*
27360 			 * The ARP module above us is capable of duplicate
27361 			 * address detection.  Old ATM drivers will not send
27362 			 * this message.
27363 			 */
27364 			ASSERT(q->q_next != NULL);
27365 			ill = (ill_t *)q->q_ptr;
27366 			ill->ill_arp_extend = B_TRUE;
27367 			freemsg(mp);
27368 			return;
27369 		default:
27370 			break;
27371 		}
27372 		break;
27373 	case M_PROTO:
27374 	case M_PCPROTO:
27375 		/*
27376 		 * The only PROTO messages we expect are ULP binds and
27377 		 * copies of option negotiation acknowledgements.
27378 		 */
27379 		switch (((union T_primitives *)mp->b_rptr)->type) {
27380 		case O_T_BIND_REQ:
27381 		case T_BIND_REQ: {
27382 			/* Request can get queued in bind */
27383 			if (connp == NULL) {
27384 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27385 				goto protonak;
27386 			}
27387 			/*
27388 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27389 			 * instead of going through this path.  We only get
27390 			 * here in the following cases:
27391 			 *
27392 			 * a. Bind retries, where ipsq is non-NULL.
27393 			 * b. T_BIND_REQ is issued from non TCP/UDP
27394 			 *    transport, e.g. icmp for raw socket,
27395 			 *    in which case ipsq will be NULL.
27396 			 */
27397 			ASSERT(ipsq != NULL ||
27398 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27399 
27400 			/* Don't increment refcnt if this is a re-entry */
27401 			if (ipsq == NULL)
27402 				CONN_INC_REF(connp);
27403 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27404 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27405 			if (mp == NULL)
27406 				return;
27407 			if (IPCL_IS_TCP(connp)) {
27408 				/*
27409 				 * In the case of TCP endpoint we
27410 				 * come here only for bind retries
27411 				 */
27412 				ASSERT(ipsq != NULL);
27413 				CONN_INC_REF(connp);
27414 				squeue_fill(connp->conn_sqp, mp,
27415 				    ip_resume_tcp_bind, connp,
27416 				    SQTAG_BIND_RETRY);
27417 				return;
27418 			} else if (IPCL_IS_UDP(connp)) {
27419 				/*
27420 				 * In the case of UDP endpoint we
27421 				 * come here only for bind retries
27422 				 */
27423 				ASSERT(ipsq != NULL);
27424 				udp_resume_bind(connp, mp);
27425 				return;
27426 			}
27427 			qreply(q, mp);
27428 			CONN_OPER_PENDING_DONE(connp);
27429 			return;
27430 		}
27431 		case T_SVR4_OPTMGMT_REQ:
27432 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27433 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27434 
27435 			if (connp == NULL) {
27436 				proto_str = "T_SVR4_OPTMGMT_REQ";
27437 				goto protonak;
27438 			}
27439 
27440 			if (!snmpcom_req(q, mp, ip_snmp_set,
27441 			    ip_snmp_get, cr)) {
27442 				/*
27443 				 * Call svr4_optcom_req so that it can
27444 				 * generate the ack. We don't come here
27445 				 * if this operation is being restarted.
27446 				 * ip_restart_optmgmt will drop the conn ref.
27447 				 * In the case of ipsec option after the ipsec
27448 				 * load is complete conn_restart_ipsec_waiter
27449 				 * drops the conn ref.
27450 				 */
27451 				ASSERT(ipsq == NULL);
27452 				CONN_INC_REF(connp);
27453 				if (ip_check_for_ipsec_opt(q, mp))
27454 					return;
27455 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27456 				if (err != EINPROGRESS) {
27457 					/* Operation is done */
27458 					CONN_OPER_PENDING_DONE(connp);
27459 				}
27460 			}
27461 			return;
27462 		case T_OPTMGMT_REQ:
27463 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27464 			/*
27465 			 * Note: No snmpcom_req support through new
27466 			 * T_OPTMGMT_REQ.
27467 			 * Call tpi_optcom_req so that it can
27468 			 * generate the ack.
27469 			 */
27470 			if (connp == NULL) {
27471 				proto_str = "T_OPTMGMT_REQ";
27472 				goto protonak;
27473 			}
27474 
27475 			ASSERT(ipsq == NULL);
27476 			/*
27477 			 * We don't come here for restart. ip_restart_optmgmt
27478 			 * will drop the conn ref. In the case of ipsec option
27479 			 * after the ipsec load is complete
27480 			 * conn_restart_ipsec_waiter drops the conn ref.
27481 			 */
27482 			CONN_INC_REF(connp);
27483 			if (ip_check_for_ipsec_opt(q, mp))
27484 				return;
27485 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27486 			if (err != EINPROGRESS) {
27487 				/* Operation is done */
27488 				CONN_OPER_PENDING_DONE(connp);
27489 			}
27490 			return;
27491 		case T_UNBIND_REQ:
27492 			if (connp == NULL) {
27493 				proto_str = "T_UNBIND_REQ";
27494 				goto protonak;
27495 			}
27496 			mp = ip_unbind(q, mp);
27497 			qreply(q, mp);
27498 			return;
27499 		default:
27500 			/*
27501 			 * Have to drop any DLPI messages coming down from
27502 			 * arp (such as an info_req which would cause ip
27503 			 * to receive an extra info_ack if it was passed
27504 			 * through.
27505 			 */
27506 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27507 			    (int)*(uint_t *)mp->b_rptr));
27508 			freemsg(mp);
27509 			return;
27510 		}
27511 		/* NOTREACHED */
27512 	case IRE_DB_TYPE: {
27513 		nce_t		*nce;
27514 		ill_t		*ill;
27515 		in6_addr_t	gw_addr_v6;
27516 
27517 
27518 		/*
27519 		 * This is a response back from a resolver.  It
27520 		 * consists of a message chain containing:
27521 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27522 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27523 		 * The LL_HDR_MBLK is the DLPI header to use to get
27524 		 * the attached packet, and subsequent ones for the
27525 		 * same destination, transmitted.
27526 		 */
27527 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27528 			break;
27529 		/*
27530 		 * First, check to make sure the resolution succeeded.
27531 		 * If it failed, the second mblk will be empty.
27532 		 * If it is, free the chain, dropping the packet.
27533 		 * (We must ire_delete the ire; that frees the ire mblk)
27534 		 * We're doing this now to support PVCs for ATM; it's
27535 		 * a partial xresolv implementation. When we fully implement
27536 		 * xresolv interfaces, instead of freeing everything here
27537 		 * we'll initiate neighbor discovery.
27538 		 *
27539 		 * For v4 (ARP and other external resolvers) the resolver
27540 		 * frees the message, so no check is needed. This check
27541 		 * is required, though, for a full xresolve implementation.
27542 		 * Including this code here now both shows how external
27543 		 * resolvers can NACK a resolution request using an
27544 		 * existing design that has no specific provisions for NACKs,
27545 		 * and also takes into account that the current non-ARP
27546 		 * external resolver has been coded to use this method of
27547 		 * NACKing for all IPv6 (xresolv) cases,
27548 		 * whether our xresolv implementation is complete or not.
27549 		 *
27550 		 */
27551 		ire = (ire_t *)mp->b_rptr;
27552 		ill = ire_to_ill(ire);
27553 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27554 		if (mp1->b_rptr == mp1->b_wptr) {
27555 			if (ire->ire_ipversion == IPV6_VERSION) {
27556 				/*
27557 				 * XRESOLV interface.
27558 				 */
27559 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27560 				mutex_enter(&ire->ire_lock);
27561 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27562 				mutex_exit(&ire->ire_lock);
27563 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27564 					nce = ndp_lookup_v6(ill,
27565 					    &ire->ire_addr_v6, B_FALSE);
27566 				} else {
27567 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27568 					    B_FALSE);
27569 				}
27570 				if (nce != NULL) {
27571 					nce_resolv_failed(nce);
27572 					ndp_delete(nce);
27573 					NCE_REFRELE(nce);
27574 				}
27575 			}
27576 			mp->b_cont = NULL;
27577 			freemsg(mp1);		/* frees the pkt as well */
27578 			ASSERT(ire->ire_nce == NULL);
27579 			ire_delete((ire_t *)mp->b_rptr);
27580 			return;
27581 		}
27582 
27583 		/*
27584 		 * Split them into IRE_MBLK and pkt and feed it into
27585 		 * ire_add_then_send. Then in ire_add_then_send
27586 		 * the IRE will be added, and then the packet will be
27587 		 * run back through ip_wput. This time it will make
27588 		 * it to the wire.
27589 		 */
27590 		mp->b_cont = NULL;
27591 		mp = mp1->b_cont;		/* now, mp points to pkt */
27592 		mp1->b_cont = NULL;
27593 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27594 		if (ire->ire_ipversion == IPV6_VERSION) {
27595 			/*
27596 			 * XRESOLV interface. Find the nce and put a copy
27597 			 * of the dl_unitdata_req in nce_res_mp
27598 			 */
27599 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27600 			mutex_enter(&ire->ire_lock);
27601 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27602 			mutex_exit(&ire->ire_lock);
27603 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27604 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27605 				    B_FALSE);
27606 			} else {
27607 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27608 			}
27609 			if (nce != NULL) {
27610 				/*
27611 				 * We have to protect nce_res_mp here
27612 				 * from being accessed by other threads
27613 				 * while we change the mblk pointer.
27614 				 * Other functions will also lock the nce when
27615 				 * accessing nce_res_mp.
27616 				 *
27617 				 * The reason we change the mblk pointer
27618 				 * here rather than copying the resolved address
27619 				 * into the template is that, unlike with
27620 				 * ethernet, we have no guarantee that the
27621 				 * resolved address length will be
27622 				 * smaller than or equal to the lla length
27623 				 * with which the template was allocated,
27624 				 * (for ethernet, they're equal)
27625 				 * so we have to use the actual resolved
27626 				 * address mblk - which holds the real
27627 				 * dl_unitdata_req with the resolved address.
27628 				 *
27629 				 * Doing this is the same behavior as was
27630 				 * previously used in the v4 ARP case.
27631 				 */
27632 				mutex_enter(&nce->nce_lock);
27633 				if (nce->nce_res_mp != NULL)
27634 					freemsg(nce->nce_res_mp);
27635 				nce->nce_res_mp = mp1;
27636 				mutex_exit(&nce->nce_lock);
27637 				/*
27638 				 * We do a fastpath probe here because
27639 				 * we have resolved the address without
27640 				 * using Neighbor Discovery.
27641 				 * In the non-XRESOLV v6 case, the fastpath
27642 				 * probe is done right after neighbor
27643 				 * discovery completes.
27644 				 */
27645 				if (nce->nce_res_mp != NULL) {
27646 					int res;
27647 					nce_fastpath_list_add(nce);
27648 					res = ill_fastpath_probe(ill,
27649 					    nce->nce_res_mp);
27650 					if (res != 0 && res != EAGAIN)
27651 						nce_fastpath_list_delete(nce);
27652 				}
27653 
27654 				ire_add_then_send(q, ire, mp);
27655 				/*
27656 				 * Now we have to clean out any packets
27657 				 * that may have been queued on the nce
27658 				 * while it was waiting for address resolution
27659 				 * to complete.
27660 				 */
27661 				mutex_enter(&nce->nce_lock);
27662 				mp1 = nce->nce_qd_mp;
27663 				nce->nce_qd_mp = NULL;
27664 				mutex_exit(&nce->nce_lock);
27665 				while (mp1 != NULL) {
27666 					mblk_t *nxt_mp;
27667 					queue_t *fwdq = NULL;
27668 					ill_t   *inbound_ill;
27669 					uint_t ifindex;
27670 
27671 					nxt_mp = mp1->b_next;
27672 					mp1->b_next = NULL;
27673 					/*
27674 					 * Retrieve ifindex stored in
27675 					 * ip_rput_data_v6()
27676 					 */
27677 					ifindex =
27678 					    (uint_t)(uintptr_t)mp1->b_prev;
27679 					inbound_ill =
27680 					    ill_lookup_on_ifindex(ifindex,
27681 					    B_TRUE, NULL, NULL, NULL,
27682 					    NULL, ipst);
27683 					mp1->b_prev = NULL;
27684 					if (inbound_ill != NULL)
27685 						fwdq = inbound_ill->ill_rq;
27686 
27687 					if (fwdq != NULL) {
27688 						put(fwdq, mp1);
27689 						ill_refrele(inbound_ill);
27690 					} else
27691 						put(WR(ill->ill_rq), mp1);
27692 					mp1 = nxt_mp;
27693 				}
27694 				NCE_REFRELE(nce);
27695 			} else {	/* nce is NULL; clean up */
27696 				ire_delete(ire);
27697 				freemsg(mp);
27698 				freemsg(mp1);
27699 				return;
27700 			}
27701 		} else {
27702 			nce_t *arpce;
27703 			/*
27704 			 * Link layer resolution succeeded. Recompute the
27705 			 * ire_nce.
27706 			 */
27707 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27708 			if ((arpce = ndp_lookup_v4(ill,
27709 			    (ire->ire_gateway_addr != INADDR_ANY ?
27710 			    &ire->ire_gateway_addr : &ire->ire_addr),
27711 			    B_FALSE)) == NULL) {
27712 				freeb(ire->ire_mp);
27713 				freeb(mp1);
27714 				freemsg(mp);
27715 				return;
27716 			}
27717 			mutex_enter(&arpce->nce_lock);
27718 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27719 			if (arpce->nce_state == ND_REACHABLE) {
27720 				/*
27721 				 * Someone resolved this before us;
27722 				 * cleanup the res_mp. Since ire has
27723 				 * not been added yet, the call to ire_add_v4
27724 				 * from ire_add_then_send (when a dup is
27725 				 * detected) will clean up the ire.
27726 				 */
27727 				freeb(mp1);
27728 			} else {
27729 				ASSERT(arpce->nce_res_mp == NULL);
27730 				arpce->nce_res_mp = mp1;
27731 				arpce->nce_state = ND_REACHABLE;
27732 			}
27733 			mutex_exit(&arpce->nce_lock);
27734 			if (ire->ire_marks & IRE_MARK_NOADD) {
27735 				/*
27736 				 * this ire will not be added to the ire
27737 				 * cache table, so we can set the ire_nce
27738 				 * here, as there are no atomicity constraints.
27739 				 */
27740 				ire->ire_nce = arpce;
27741 				/*
27742 				 * We are associating this nce with the ire
27743 				 * so change the nce ref taken in
27744 				 * ndp_lookup_v4() from
27745 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27746 				 */
27747 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27748 			} else {
27749 				NCE_REFRELE(arpce);
27750 			}
27751 			ire_add_then_send(q, ire, mp);
27752 		}
27753 		return;	/* All is well, the packet has been sent. */
27754 	}
27755 	case IRE_ARPRESOLVE_TYPE: {
27756 
27757 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27758 			break;
27759 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27760 		mp->b_cont = NULL;
27761 		/*
27762 		 * First, check to make sure the resolution succeeded.
27763 		 * If it failed, the second mblk will be empty.
27764 		 */
27765 		if (mp1->b_rptr == mp1->b_wptr) {
27766 			/* cleanup  the incomplete ire, free queued packets */
27767 			freemsg(mp); /* fake ire */
27768 			freeb(mp1);  /* dl_unitdata response */
27769 			return;
27770 		}
27771 
27772 		/*
27773 		 * update any incomplete nce_t found. we lookup the ctable
27774 		 * and find the nce from the ire->ire_nce because we need
27775 		 * to pass the ire to ip_xmit_v4 later, and can find both
27776 		 * ire and nce in one lookup from the ctable.
27777 		 */
27778 		fake_ire = (ire_t *)mp->b_rptr;
27779 		/*
27780 		 * By the time we come back here from ARP
27781 		 * the logical outgoing interface  of the incomplete ire
27782 		 * we added in ire_forward could have disappeared,
27783 		 * causing the incomplete ire to also have
27784 		 * dissapeared. So we need to retreive the
27785 		 * proper ipif for the ire  before looking
27786 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27787 		 */
27788 		ill = q->q_ptr;
27789 
27790 		/* Get the outgoing ipif */
27791 		mutex_enter(&ill->ill_lock);
27792 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27793 			mutex_exit(&ill->ill_lock);
27794 			freemsg(mp); /* fake ire */
27795 			freeb(mp1);  /* dl_unitdata response */
27796 			return;
27797 		}
27798 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27799 
27800 		if (ipif == NULL) {
27801 			mutex_exit(&ill->ill_lock);
27802 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27803 			freemsg(mp);
27804 			freeb(mp1);
27805 			return;
27806 		}
27807 		ipif_refhold_locked(ipif);
27808 		mutex_exit(&ill->ill_lock);
27809 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27810 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27811 		    ipif, fake_ire->ire_zoneid, NULL,
27812 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27813 		ipif_refrele(ipif);
27814 		if (ire == NULL) {
27815 			/*
27816 			 * no ire was found; check if there is an nce
27817 			 * for this lookup; if it has no ire's pointing at it
27818 			 * cleanup.
27819 			 */
27820 			if ((nce = ndp_lookup_v4(ill,
27821 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27822 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27823 			    B_FALSE)) != NULL) {
27824 				/*
27825 				 * cleanup:
27826 				 * We check for refcnt 2 (one for the nce
27827 				 * hash list + 1 for the ref taken by
27828 				 * ndp_lookup_v4) to check that there are
27829 				 * no ire's pointing at the nce.
27830 				 */
27831 				if (nce->nce_refcnt == 2)
27832 					ndp_delete(nce);
27833 				NCE_REFRELE(nce);
27834 			}
27835 			freeb(mp1);  /* dl_unitdata response */
27836 			freemsg(mp); /* fake ire */
27837 			return;
27838 		}
27839 		nce = ire->ire_nce;
27840 		DTRACE_PROBE2(ire__arpresolve__type,
27841 		    ire_t *, ire, nce_t *, nce);
27842 		ASSERT(nce->nce_state != ND_INITIAL);
27843 		mutex_enter(&nce->nce_lock);
27844 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27845 		if (nce->nce_state == ND_REACHABLE) {
27846 			/*
27847 			 * Someone resolved this before us;
27848 			 * our response is not needed any more.
27849 			 */
27850 			mutex_exit(&nce->nce_lock);
27851 			freeb(mp1);  /* dl_unitdata response */
27852 		} else {
27853 			ASSERT(nce->nce_res_mp == NULL);
27854 			nce->nce_res_mp = mp1;
27855 			nce->nce_state = ND_REACHABLE;
27856 			mutex_exit(&nce->nce_lock);
27857 			nce_fastpath(nce);
27858 		}
27859 		/*
27860 		 * The cached nce_t has been updated to be reachable;
27861 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27862 		 */
27863 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27864 		freemsg(mp);
27865 		/*
27866 		 * send out queued packets.
27867 		 */
27868 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27869 
27870 		IRE_REFRELE(ire);
27871 		return;
27872 	}
27873 	default:
27874 		break;
27875 	}
27876 	if (q->q_next) {
27877 		putnext(q, mp);
27878 	} else
27879 		freemsg(mp);
27880 	return;
27881 
27882 protonak:
27883 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27884 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27885 		qreply(q, mp);
27886 }
27887 
27888 /*
27889  * Process IP options in an outbound packet.  Modify the destination if there
27890  * is a source route option.
27891  * Returns non-zero if something fails in which case an ICMP error has been
27892  * sent and mp freed.
27893  */
27894 static int
27895 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27896     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27897 {
27898 	ipoptp_t	opts;
27899 	uchar_t		*opt;
27900 	uint8_t		optval;
27901 	uint8_t		optlen;
27902 	ipaddr_t	dst;
27903 	intptr_t	code = 0;
27904 	mblk_t		*mp;
27905 	ire_t		*ire = NULL;
27906 
27907 	ip2dbg(("ip_wput_options\n"));
27908 	mp = ipsec_mp;
27909 	if (mctl_present) {
27910 		mp = ipsec_mp->b_cont;
27911 	}
27912 
27913 	dst = ipha->ipha_dst;
27914 	for (optval = ipoptp_first(&opts, ipha);
27915 	    optval != IPOPT_EOL;
27916 	    optval = ipoptp_next(&opts)) {
27917 		opt = opts.ipoptp_cur;
27918 		optlen = opts.ipoptp_len;
27919 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27920 		    optval, optlen));
27921 		switch (optval) {
27922 			uint32_t off;
27923 		case IPOPT_SSRR:
27924 		case IPOPT_LSRR:
27925 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27926 				ip1dbg((
27927 				    "ip_wput_options: bad option offset\n"));
27928 				code = (char *)&opt[IPOPT_OLEN] -
27929 				    (char *)ipha;
27930 				goto param_prob;
27931 			}
27932 			off = opt[IPOPT_OFFSET];
27933 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27934 			    ntohl(dst)));
27935 			/*
27936 			 * For strict: verify that dst is directly
27937 			 * reachable.
27938 			 */
27939 			if (optval == IPOPT_SSRR) {
27940 				ire = ire_ftable_lookup(dst, 0, 0,
27941 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27942 				    MBLK_GETLABEL(mp),
27943 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27944 				if (ire == NULL) {
27945 					ip1dbg(("ip_wput_options: SSRR not"
27946 					    " directly reachable: 0x%x\n",
27947 					    ntohl(dst)));
27948 					goto bad_src_route;
27949 				}
27950 				ire_refrele(ire);
27951 			}
27952 			break;
27953 		case IPOPT_RR:
27954 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27955 				ip1dbg((
27956 				    "ip_wput_options: bad option offset\n"));
27957 				code = (char *)&opt[IPOPT_OLEN] -
27958 				    (char *)ipha;
27959 				goto param_prob;
27960 			}
27961 			break;
27962 		case IPOPT_TS:
27963 			/*
27964 			 * Verify that length >=5 and that there is either
27965 			 * room for another timestamp or that the overflow
27966 			 * counter is not maxed out.
27967 			 */
27968 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27969 			if (optlen < IPOPT_MINLEN_IT) {
27970 				goto param_prob;
27971 			}
27972 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27973 				ip1dbg((
27974 				    "ip_wput_options: bad option offset\n"));
27975 				code = (char *)&opt[IPOPT_OFFSET] -
27976 				    (char *)ipha;
27977 				goto param_prob;
27978 			}
27979 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27980 			case IPOPT_TS_TSONLY:
27981 				off = IPOPT_TS_TIMELEN;
27982 				break;
27983 			case IPOPT_TS_TSANDADDR:
27984 			case IPOPT_TS_PRESPEC:
27985 			case IPOPT_TS_PRESPEC_RFC791:
27986 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27987 				break;
27988 			default:
27989 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27990 				    (char *)ipha;
27991 				goto param_prob;
27992 			}
27993 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27994 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27995 				/*
27996 				 * No room and the overflow counter is 15
27997 				 * already.
27998 				 */
27999 				goto param_prob;
28000 			}
28001 			break;
28002 		}
28003 	}
28004 
28005 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28006 		return (0);
28007 
28008 	ip1dbg(("ip_wput_options: error processing IP options."));
28009 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28010 
28011 param_prob:
28012 	/*
28013 	 * Since ip_wput() isn't close to finished, we fill
28014 	 * in enough of the header for credible error reporting.
28015 	 */
28016 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28017 		/* Failed */
28018 		freemsg(ipsec_mp);
28019 		return (-1);
28020 	}
28021 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28022 	return (-1);
28023 
28024 bad_src_route:
28025 	/*
28026 	 * Since ip_wput() isn't close to finished, we fill
28027 	 * in enough of the header for credible error reporting.
28028 	 */
28029 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28030 		/* Failed */
28031 		freemsg(ipsec_mp);
28032 		return (-1);
28033 	}
28034 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28035 	return (-1);
28036 }
28037 
28038 /*
28039  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28040  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28041  * thru /etc/system.
28042  */
28043 #define	CONN_MAXDRAINCNT	64
28044 
28045 static void
28046 conn_drain_init(ip_stack_t *ipst)
28047 {
28048 	int i;
28049 
28050 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28051 
28052 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28053 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28054 		/*
28055 		 * Default value of the number of drainers is the
28056 		 * number of cpus, subject to maximum of 8 drainers.
28057 		 */
28058 		if (boot_max_ncpus != -1)
28059 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28060 		else
28061 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28062 	}
28063 
28064 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28065 	    sizeof (idl_t), KM_SLEEP);
28066 
28067 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28068 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28069 		    MUTEX_DEFAULT, NULL);
28070 	}
28071 }
28072 
28073 static void
28074 conn_drain_fini(ip_stack_t *ipst)
28075 {
28076 	int i;
28077 
28078 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28079 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28080 	kmem_free(ipst->ips_conn_drain_list,
28081 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28082 	ipst->ips_conn_drain_list = NULL;
28083 }
28084 
28085 /*
28086  * Note: For an overview of how flowcontrol is handled in IP please see the
28087  * IP Flowcontrol notes at the top of this file.
28088  *
28089  * Flow control has blocked us from proceeding. Insert the given conn in one
28090  * of the conn drain lists. These conn wq's will be qenabled later on when
28091  * STREAMS flow control does a backenable. conn_walk_drain will enable
28092  * the first conn in each of these drain lists. Each of these qenabled conns
28093  * in turn enables the next in the list, after it runs, or when it closes,
28094  * thus sustaining the drain process.
28095  *
28096  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28097  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28098  * running at any time, on a given conn, since there can be only 1 service proc
28099  * running on a queue at any time.
28100  */
28101 void
28102 conn_drain_insert(conn_t *connp)
28103 {
28104 	idl_t	*idl;
28105 	uint_t	index;
28106 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28107 
28108 	mutex_enter(&connp->conn_lock);
28109 	if (connp->conn_state_flags & CONN_CLOSING) {
28110 		/*
28111 		 * The conn is closing as a result of which CONN_CLOSING
28112 		 * is set. Return.
28113 		 */
28114 		mutex_exit(&connp->conn_lock);
28115 		return;
28116 	} else if (connp->conn_idl == NULL) {
28117 		/*
28118 		 * Assign the next drain list round robin. We dont' use
28119 		 * a lock, and thus it may not be strictly round robin.
28120 		 * Atomicity of load/stores is enough to make sure that
28121 		 * conn_drain_list_index is always within bounds.
28122 		 */
28123 		index = ipst->ips_conn_drain_list_index;
28124 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28125 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28126 		index++;
28127 		if (index == ipst->ips_conn_drain_list_cnt)
28128 			index = 0;
28129 		ipst->ips_conn_drain_list_index = index;
28130 	}
28131 	mutex_exit(&connp->conn_lock);
28132 
28133 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28134 	if ((connp->conn_drain_prev != NULL) ||
28135 	    (connp->conn_state_flags & CONN_CLOSING)) {
28136 		/*
28137 		 * The conn is already in the drain list, OR
28138 		 * the conn is closing. We need to check again for
28139 		 * the closing case again since close can happen
28140 		 * after we drop the conn_lock, and before we
28141 		 * acquire the CONN_DRAIN_LIST_LOCK.
28142 		 */
28143 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28144 		return;
28145 	} else {
28146 		idl = connp->conn_idl;
28147 	}
28148 
28149 	/*
28150 	 * The conn is not in the drain list. Insert it at the
28151 	 * tail of the drain list. The drain list is circular
28152 	 * and doubly linked. idl_conn points to the 1st element
28153 	 * in the list.
28154 	 */
28155 	if (idl->idl_conn == NULL) {
28156 		idl->idl_conn = connp;
28157 		connp->conn_drain_next = connp;
28158 		connp->conn_drain_prev = connp;
28159 	} else {
28160 		conn_t *head = idl->idl_conn;
28161 
28162 		connp->conn_drain_next = head;
28163 		connp->conn_drain_prev = head->conn_drain_prev;
28164 		head->conn_drain_prev->conn_drain_next = connp;
28165 		head->conn_drain_prev = connp;
28166 	}
28167 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28168 }
28169 
28170 /*
28171  * This conn is closing, and we are called from ip_close. OR
28172  * This conn has been serviced by ip_wsrv, and we need to do the tail
28173  * processing.
28174  * If this conn is part of the drain list, we may need to sustain the drain
28175  * process by qenabling the next conn in the drain list. We may also need to
28176  * remove this conn from the list, if it is done.
28177  */
28178 static void
28179 conn_drain_tail(conn_t *connp, boolean_t closing)
28180 {
28181 	idl_t *idl;
28182 
28183 	/*
28184 	 * connp->conn_idl is stable at this point, and no lock is needed
28185 	 * to check it. If we are called from ip_close, close has already
28186 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28187 	 * called us only because conn_idl is non-null. If we are called thru
28188 	 * service, conn_idl could be null, but it cannot change because
28189 	 * service is single-threaded per queue, and there cannot be another
28190 	 * instance of service trying to call conn_drain_insert on this conn
28191 	 * now.
28192 	 */
28193 	ASSERT(!closing || (connp->conn_idl != NULL));
28194 
28195 	/*
28196 	 * If connp->conn_idl is null, the conn has not been inserted into any
28197 	 * drain list even once since creation of the conn. Just return.
28198 	 */
28199 	if (connp->conn_idl == NULL)
28200 		return;
28201 
28202 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28203 
28204 	if (connp->conn_drain_prev == NULL) {
28205 		/* This conn is currently not in the drain list.  */
28206 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28207 		return;
28208 	}
28209 	idl = connp->conn_idl;
28210 	if (idl->idl_conn_draining == connp) {
28211 		/*
28212 		 * This conn is the current drainer. If this is the last conn
28213 		 * in the drain list, we need to do more checks, in the 'if'
28214 		 * below. Otherwwise we need to just qenable the next conn,
28215 		 * to sustain the draining, and is handled in the 'else'
28216 		 * below.
28217 		 */
28218 		if (connp->conn_drain_next == idl->idl_conn) {
28219 			/*
28220 			 * This conn is the last in this list. This round
28221 			 * of draining is complete. If idl_repeat is set,
28222 			 * it means another flow enabling has happened from
28223 			 * the driver/streams and we need to another round
28224 			 * of draining.
28225 			 * If there are more than 2 conns in the drain list,
28226 			 * do a left rotate by 1, so that all conns except the
28227 			 * conn at the head move towards the head by 1, and the
28228 			 * the conn at the head goes to the tail. This attempts
28229 			 * a more even share for all queues that are being
28230 			 * drained.
28231 			 */
28232 			if ((connp->conn_drain_next != connp) &&
28233 			    (idl->idl_conn->conn_drain_next != connp)) {
28234 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28235 			}
28236 			if (idl->idl_repeat) {
28237 				qenable(idl->idl_conn->conn_wq);
28238 				idl->idl_conn_draining = idl->idl_conn;
28239 				idl->idl_repeat = 0;
28240 			} else {
28241 				idl->idl_conn_draining = NULL;
28242 			}
28243 		} else {
28244 			/*
28245 			 * If the next queue that we are now qenable'ing,
28246 			 * is closing, it will remove itself from this list
28247 			 * and qenable the subsequent queue in ip_close().
28248 			 * Serialization is acheived thru idl_lock.
28249 			 */
28250 			qenable(connp->conn_drain_next->conn_wq);
28251 			idl->idl_conn_draining = connp->conn_drain_next;
28252 		}
28253 	}
28254 	if (!connp->conn_did_putbq || closing) {
28255 		/*
28256 		 * Remove ourself from the drain list, if we did not do
28257 		 * a putbq, or if the conn is closing.
28258 		 * Note: It is possible that q->q_first is non-null. It means
28259 		 * that these messages landed after we did a enableok() in
28260 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28261 		 * service them.
28262 		 */
28263 		if (connp->conn_drain_next == connp) {
28264 			/* Singleton in the list */
28265 			ASSERT(connp->conn_drain_prev == connp);
28266 			idl->idl_conn = NULL;
28267 			idl->idl_conn_draining = NULL;
28268 		} else {
28269 			connp->conn_drain_prev->conn_drain_next =
28270 			    connp->conn_drain_next;
28271 			connp->conn_drain_next->conn_drain_prev =
28272 			    connp->conn_drain_prev;
28273 			if (idl->idl_conn == connp)
28274 				idl->idl_conn = connp->conn_drain_next;
28275 			ASSERT(idl->idl_conn_draining != connp);
28276 
28277 		}
28278 		connp->conn_drain_next = NULL;
28279 		connp->conn_drain_prev = NULL;
28280 	}
28281 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28282 }
28283 
28284 /*
28285  * Write service routine. Shared perimeter entry point.
28286  * ip_wsrv can be called in any of the following ways.
28287  * 1. The device queue's messages has fallen below the low water mark
28288  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28289  *    the drain lists and backenable the first conn in each list.
28290  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28291  *    qenabled non-tcp upper layers. We start dequeing messages and call
28292  *    ip_wput for each message.
28293  */
28294 
28295 void
28296 ip_wsrv(queue_t *q)
28297 {
28298 	conn_t	*connp;
28299 	ill_t	*ill;
28300 	mblk_t	*mp;
28301 
28302 	if (q->q_next) {
28303 		ill = (ill_t *)q->q_ptr;
28304 		if (ill->ill_state_flags == 0) {
28305 			/*
28306 			 * The device flow control has opened up.
28307 			 * Walk through conn drain lists and qenable the
28308 			 * first conn in each list. This makes sense only
28309 			 * if the stream is fully plumbed and setup.
28310 			 * Hence the if check above.
28311 			 */
28312 			ip1dbg(("ip_wsrv: walking\n"));
28313 			conn_walk_drain(ill->ill_ipst);
28314 		}
28315 		return;
28316 	}
28317 
28318 	connp = Q_TO_CONN(q);
28319 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28320 
28321 	/*
28322 	 * 1. Set conn_draining flag to signal that service is active.
28323 	 *
28324 	 * 2. ip_output determines whether it has been called from service,
28325 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28326 	 *    has been called from service.
28327 	 *
28328 	 * 3. Message ordering is preserved by the following logic.
28329 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28330 	 *    the message at the tail, if conn_draining is set (i.e. service
28331 	 *    is running) or if q->q_first is non-null.
28332 	 *
28333 	 *    ii. If ip_output is called from service, and if ip_output cannot
28334 	 *    putnext due to flow control, it does a putbq.
28335 	 *
28336 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28337 	 *    (causing an infinite loop).
28338 	 */
28339 	ASSERT(!connp->conn_did_putbq);
28340 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28341 		connp->conn_draining = 1;
28342 		noenable(q);
28343 		while ((mp = getq(q)) != NULL) {
28344 			ASSERT(CONN_Q(q));
28345 
28346 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28347 			if (connp->conn_did_putbq) {
28348 				/* ip_wput did a putbq */
28349 				break;
28350 			}
28351 		}
28352 		/*
28353 		 * At this point, a thread coming down from top, calling
28354 		 * ip_wput, may end up queueing the message. We have not yet
28355 		 * enabled the queue, so ip_wsrv won't be called again.
28356 		 * To avoid this race, check q->q_first again (in the loop)
28357 		 * If the other thread queued the message before we call
28358 		 * enableok(), we will catch it in the q->q_first check.
28359 		 * If the other thread queues the message after we call
28360 		 * enableok(), ip_wsrv will be called again by STREAMS.
28361 		 */
28362 		connp->conn_draining = 0;
28363 		enableok(q);
28364 	}
28365 
28366 	/* Enable the next conn for draining */
28367 	conn_drain_tail(connp, B_FALSE);
28368 
28369 	connp->conn_did_putbq = 0;
28370 }
28371 
28372 /*
28373  * Walk the list of all conn's calling the function provided with the
28374  * specified argument for each.	 Note that this only walks conn's that
28375  * have been bound.
28376  * Applies to both IPv4 and IPv6.
28377  */
28378 static void
28379 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28380 {
28381 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28382 	    ipst->ips_ipcl_udp_fanout_size,
28383 	    func, arg, zoneid);
28384 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28385 	    ipst->ips_ipcl_conn_fanout_size,
28386 	    func, arg, zoneid);
28387 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28388 	    ipst->ips_ipcl_bind_fanout_size,
28389 	    func, arg, zoneid);
28390 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28391 	    IPPROTO_MAX, func, arg, zoneid);
28392 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28393 	    IPPROTO_MAX, func, arg, zoneid);
28394 }
28395 
28396 /*
28397  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28398  * of conns that need to be drained, check if drain is already in progress.
28399  * If so set the idl_repeat bit, indicating that the last conn in the list
28400  * needs to reinitiate the drain once again, for the list. If drain is not
28401  * in progress for the list, initiate the draining, by qenabling the 1st
28402  * conn in the list. The drain is self-sustaining, each qenabled conn will
28403  * in turn qenable the next conn, when it is done/blocked/closing.
28404  */
28405 static void
28406 conn_walk_drain(ip_stack_t *ipst)
28407 {
28408 	int i;
28409 	idl_t *idl;
28410 
28411 	IP_STAT(ipst, ip_conn_walk_drain);
28412 
28413 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28414 		idl = &ipst->ips_conn_drain_list[i];
28415 		mutex_enter(&idl->idl_lock);
28416 		if (idl->idl_conn == NULL) {
28417 			mutex_exit(&idl->idl_lock);
28418 			continue;
28419 		}
28420 		/*
28421 		 * If this list is not being drained currently by
28422 		 * an ip_wsrv thread, start the process.
28423 		 */
28424 		if (idl->idl_conn_draining == NULL) {
28425 			ASSERT(idl->idl_repeat == 0);
28426 			qenable(idl->idl_conn->conn_wq);
28427 			idl->idl_conn_draining = idl->idl_conn;
28428 		} else {
28429 			idl->idl_repeat = 1;
28430 		}
28431 		mutex_exit(&idl->idl_lock);
28432 	}
28433 }
28434 
28435 /*
28436  * Walk an conn hash table of `count' buckets, calling func for each entry.
28437  */
28438 static void
28439 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28440     zoneid_t zoneid)
28441 {
28442 	conn_t	*connp;
28443 
28444 	while (count-- > 0) {
28445 		mutex_enter(&connfp->connf_lock);
28446 		for (connp = connfp->connf_head; connp != NULL;
28447 		    connp = connp->conn_next) {
28448 			if (zoneid == GLOBAL_ZONEID ||
28449 			    zoneid == connp->conn_zoneid) {
28450 				CONN_INC_REF(connp);
28451 				mutex_exit(&connfp->connf_lock);
28452 				(*func)(connp, arg);
28453 				mutex_enter(&connfp->connf_lock);
28454 				CONN_DEC_REF(connp);
28455 			}
28456 		}
28457 		mutex_exit(&connfp->connf_lock);
28458 		connfp++;
28459 	}
28460 }
28461 
28462 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28463 static void
28464 conn_report1(conn_t *connp, void *mp)
28465 {
28466 	char	buf1[INET6_ADDRSTRLEN];
28467 	char	buf2[INET6_ADDRSTRLEN];
28468 	uint_t	print_len, buf_len;
28469 
28470 	ASSERT(connp != NULL);
28471 
28472 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28473 	if (buf_len <= 0)
28474 		return;
28475 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28476 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28477 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28478 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28479 	    "%5d %s/%05d %s/%05d\n",
28480 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28481 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28482 	    buf1, connp->conn_lport,
28483 	    buf2, connp->conn_fport);
28484 	if (print_len < buf_len) {
28485 		((mblk_t *)mp)->b_wptr += print_len;
28486 	} else {
28487 		((mblk_t *)mp)->b_wptr += buf_len;
28488 	}
28489 }
28490 
28491 /*
28492  * Named Dispatch routine to produce a formatted report on all conns
28493  * that are listed in one of the fanout tables.
28494  * This report is accessed by using the ndd utility to "get" ND variable
28495  * "ip_conn_status".
28496  */
28497 /* ARGSUSED */
28498 static int
28499 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28500 {
28501 	conn_t *connp = Q_TO_CONN(q);
28502 
28503 	(void) mi_mpprintf(mp,
28504 	    "CONN      " MI_COL_HDRPAD_STR
28505 	    "rfq      " MI_COL_HDRPAD_STR
28506 	    "stq      " MI_COL_HDRPAD_STR
28507 	    " zone local                 remote");
28508 
28509 	/*
28510 	 * Because of the ndd constraint, at most we can have 64K buffer
28511 	 * to put in all conn info.  So to be more efficient, just
28512 	 * allocate a 64K buffer here, assuming we need that large buffer.
28513 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28514 	 */
28515 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28516 		/* The following may work even if we cannot get a large buf. */
28517 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28518 		return (0);
28519 	}
28520 
28521 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28522 	    connp->conn_netstack->netstack_ip);
28523 	return (0);
28524 }
28525 
28526 /*
28527  * Determine if the ill and multicast aspects of that packets
28528  * "matches" the conn.
28529  */
28530 boolean_t
28531 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28532     zoneid_t zoneid)
28533 {
28534 	ill_t *in_ill;
28535 	boolean_t found;
28536 	ipif_t *ipif;
28537 	ire_t *ire;
28538 	ipaddr_t dst, src;
28539 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28540 
28541 	dst = ipha->ipha_dst;
28542 	src = ipha->ipha_src;
28543 
28544 	/*
28545 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28546 	 * unicast, broadcast and multicast reception to
28547 	 * conn_incoming_ill. conn_wantpacket itself is called
28548 	 * only for BROADCAST and multicast.
28549 	 *
28550 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28551 	 *    is part of a group. Hence, we should be receiving
28552 	 *    just one copy of broadcast for the whole group.
28553 	 *    Thus, if it is part of the group the packet could
28554 	 *    come on any ill of the group and hence we need a
28555 	 *    match on the group. Otherwise, match on ill should
28556 	 *    be sufficient.
28557 	 *
28558 	 * 2) ip_rput does not suppress duplicate multicast packets.
28559 	 *    If there are two interfaces in a ill group and we have
28560 	 *    2 applications (conns) joined a multicast group G on
28561 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28562 	 *    will give us two packets because we join G on both the
28563 	 *    interfaces rather than nominating just one interface
28564 	 *    for receiving multicast like broadcast above. So,
28565 	 *    we have to call ilg_lookup_ill to filter out duplicate
28566 	 *    copies, if ill is part of a group.
28567 	 */
28568 	in_ill = connp->conn_incoming_ill;
28569 	if (in_ill != NULL) {
28570 		if (in_ill->ill_group == NULL) {
28571 			if (in_ill != ill)
28572 				return (B_FALSE);
28573 		} else if (in_ill->ill_group != ill->ill_group) {
28574 			return (B_FALSE);
28575 		}
28576 	}
28577 
28578 	if (!CLASSD(dst)) {
28579 		if (IPCL_ZONE_MATCH(connp, zoneid))
28580 			return (B_TRUE);
28581 		/*
28582 		 * The conn is in a different zone; we need to check that this
28583 		 * broadcast address is configured in the application's zone and
28584 		 * on one ill in the group.
28585 		 */
28586 		ipif = ipif_get_next_ipif(NULL, ill);
28587 		if (ipif == NULL)
28588 			return (B_FALSE);
28589 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28590 		    connp->conn_zoneid, NULL,
28591 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28592 		ipif_refrele(ipif);
28593 		if (ire != NULL) {
28594 			ire_refrele(ire);
28595 			return (B_TRUE);
28596 		} else {
28597 			return (B_FALSE);
28598 		}
28599 	}
28600 
28601 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28602 	    connp->conn_zoneid == zoneid) {
28603 		/*
28604 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28605 		 * disabled, therefore we don't dispatch the multicast packet to
28606 		 * the sending zone.
28607 		 */
28608 		return (B_FALSE);
28609 	}
28610 
28611 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28612 		/*
28613 		 * Multicast packet on the loopback interface: we only match
28614 		 * conns who joined the group in the specified zone.
28615 		 */
28616 		return (B_FALSE);
28617 	}
28618 
28619 	if (connp->conn_multi_router) {
28620 		/* multicast packet and multicast router socket: send up */
28621 		return (B_TRUE);
28622 	}
28623 
28624 	mutex_enter(&connp->conn_lock);
28625 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28626 	mutex_exit(&connp->conn_lock);
28627 	return (found);
28628 }
28629 
28630 /*
28631  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28632  */
28633 /* ARGSUSED */
28634 static void
28635 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28636 {
28637 	ill_t *ill = (ill_t *)q->q_ptr;
28638 	mblk_t	*mp1, *mp2;
28639 	ipif_t  *ipif;
28640 	int err = 0;
28641 	conn_t *connp = NULL;
28642 	ipsq_t	*ipsq;
28643 	arc_t	*arc;
28644 
28645 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28646 
28647 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28648 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28649 
28650 	ASSERT(IAM_WRITER_ILL(ill));
28651 	mp2 = mp->b_cont;
28652 	mp->b_cont = NULL;
28653 
28654 	/*
28655 	 * We have now received the arp bringup completion message
28656 	 * from ARP. Mark the arp bringup as done. Also if the arp
28657 	 * stream has already started closing, send up the AR_ARP_CLOSING
28658 	 * ack now since ARP is waiting in close for this ack.
28659 	 */
28660 	mutex_enter(&ill->ill_lock);
28661 	ill->ill_arp_bringup_pending = 0;
28662 	if (ill->ill_arp_closing) {
28663 		mutex_exit(&ill->ill_lock);
28664 		/* Let's reuse the mp for sending the ack */
28665 		arc = (arc_t *)mp->b_rptr;
28666 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28667 		arc->arc_cmd = AR_ARP_CLOSING;
28668 		qreply(q, mp);
28669 	} else {
28670 		mutex_exit(&ill->ill_lock);
28671 		freeb(mp);
28672 	}
28673 
28674 	ipsq = ill->ill_phyint->phyint_ipsq;
28675 	ipif = ipsq->ipsq_pending_ipif;
28676 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28677 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28678 	if (mp1 == NULL) {
28679 		/* bringup was aborted by the user */
28680 		freemsg(mp2);
28681 		return;
28682 	}
28683 
28684 	/*
28685 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28686 	 * must have an associated conn_t.  Otherwise, we're bringing this
28687 	 * interface back up as part of handling an asynchronous event (e.g.,
28688 	 * physical address change).
28689 	 */
28690 	if (ipsq->ipsq_current_ioctl != 0) {
28691 		ASSERT(connp != NULL);
28692 		q = CONNP_TO_WQ(connp);
28693 	} else {
28694 		ASSERT(connp == NULL);
28695 		q = ill->ill_rq;
28696 	}
28697 
28698 	/*
28699 	 * If the DL_BIND_REQ fails, it is noted
28700 	 * in arc_name_offset.
28701 	 */
28702 	err = *((int *)mp2->b_rptr);
28703 	if (err == 0) {
28704 		if (ipif->ipif_isv6) {
28705 			if ((err = ipif_up_done_v6(ipif)) != 0)
28706 				ip0dbg(("ip_arp_done: init failed\n"));
28707 		} else {
28708 			if ((err = ipif_up_done(ipif)) != 0)
28709 				ip0dbg(("ip_arp_done: init failed\n"));
28710 		}
28711 	} else {
28712 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28713 	}
28714 
28715 	freemsg(mp2);
28716 
28717 	if ((err == 0) && (ill->ill_up_ipifs)) {
28718 		err = ill_up_ipifs(ill, q, mp1);
28719 		if (err == EINPROGRESS)
28720 			return;
28721 	}
28722 
28723 	if (ill->ill_up_ipifs)
28724 		ill_group_cleanup(ill);
28725 
28726 	/*
28727 	 * The operation must complete without EINPROGRESS since
28728 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28729 	 * Otherwise, the operation will be stuck forever in the ipsq.
28730 	 */
28731 	ASSERT(err != EINPROGRESS);
28732 	if (ipsq->ipsq_current_ioctl != 0)
28733 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28734 	else
28735 		ipsq_current_finish(ipsq);
28736 }
28737 
28738 /* Allocate the private structure */
28739 static int
28740 ip_priv_alloc(void **bufp)
28741 {
28742 	void	*buf;
28743 
28744 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28745 		return (ENOMEM);
28746 
28747 	*bufp = buf;
28748 	return (0);
28749 }
28750 
28751 /* Function to delete the private structure */
28752 void
28753 ip_priv_free(void *buf)
28754 {
28755 	ASSERT(buf != NULL);
28756 	kmem_free(buf, sizeof (ip_priv_t));
28757 }
28758 
28759 /*
28760  * The entry point for IPPF processing.
28761  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28762  * routine just returns.
28763  *
28764  * When called, ip_process generates an ipp_packet_t structure
28765  * which holds the state information for this packet and invokes the
28766  * the classifier (via ipp_packet_process). The classification, depending on
28767  * configured filters, results in a list of actions for this packet. Invoking
28768  * an action may cause the packet to be dropped, in which case the resulting
28769  * mblk (*mpp) is NULL. proc indicates the callout position for
28770  * this packet and ill_index is the interface this packet on or will leave
28771  * on (inbound and outbound resp.).
28772  */
28773 void
28774 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28775 {
28776 	mblk_t		*mp;
28777 	ip_priv_t	*priv;
28778 	ipp_action_id_t	aid;
28779 	int		rc = 0;
28780 	ipp_packet_t	*pp;
28781 #define	IP_CLASS	"ip"
28782 
28783 	/* If the classifier is not loaded, return  */
28784 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28785 		return;
28786 	}
28787 
28788 	mp = *mpp;
28789 	ASSERT(mp != NULL);
28790 
28791 	/* Allocate the packet structure */
28792 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28793 	if (rc != 0) {
28794 		*mpp = NULL;
28795 		freemsg(mp);
28796 		return;
28797 	}
28798 
28799 	/* Allocate the private structure */
28800 	rc = ip_priv_alloc((void **)&priv);
28801 	if (rc != 0) {
28802 		*mpp = NULL;
28803 		freemsg(mp);
28804 		ipp_packet_free(pp);
28805 		return;
28806 	}
28807 	priv->proc = proc;
28808 	priv->ill_index = ill_index;
28809 	ipp_packet_set_private(pp, priv, ip_priv_free);
28810 	ipp_packet_set_data(pp, mp);
28811 
28812 	/* Invoke the classifier */
28813 	rc = ipp_packet_process(&pp);
28814 	if (pp != NULL) {
28815 		mp = ipp_packet_get_data(pp);
28816 		ipp_packet_free(pp);
28817 		if (rc != 0) {
28818 			freemsg(mp);
28819 			*mpp = NULL;
28820 		}
28821 	} else {
28822 		*mpp = NULL;
28823 	}
28824 #undef	IP_CLASS
28825 }
28826 
28827 /*
28828  * Propagate a multicast group membership operation (add/drop) on
28829  * all the interfaces crossed by the related multirt routes.
28830  * The call is considered successful if the operation succeeds
28831  * on at least one interface.
28832  */
28833 static int
28834 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28835     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28836     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28837     mblk_t *first_mp)
28838 {
28839 	ire_t		*ire_gw;
28840 	irb_t		*irb;
28841 	int		error = 0;
28842 	opt_restart_t	*or;
28843 	ip_stack_t	*ipst = ire->ire_ipst;
28844 
28845 	irb = ire->ire_bucket;
28846 	ASSERT(irb != NULL);
28847 
28848 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28849 
28850 	or = (opt_restart_t *)first_mp->b_rptr;
28851 	IRB_REFHOLD(irb);
28852 	for (; ire != NULL; ire = ire->ire_next) {
28853 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28854 			continue;
28855 		if (ire->ire_addr != group)
28856 			continue;
28857 
28858 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28859 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28860 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28861 		/* No resolver exists for the gateway; skip this ire. */
28862 		if (ire_gw == NULL)
28863 			continue;
28864 
28865 		/*
28866 		 * This function can return EINPROGRESS. If so the operation
28867 		 * will be restarted from ip_restart_optmgmt which will
28868 		 * call ip_opt_set and option processing will restart for
28869 		 * this option. So we may end up calling 'fn' more than once.
28870 		 * This requires that 'fn' is idempotent except for the
28871 		 * return value. The operation is considered a success if
28872 		 * it succeeds at least once on any one interface.
28873 		 */
28874 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28875 		    NULL, fmode, src, first_mp);
28876 		if (error == 0)
28877 			or->or_private = CGTP_MCAST_SUCCESS;
28878 
28879 		if (ip_debug > 0) {
28880 			ulong_t	off;
28881 			char	*ksym;
28882 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28883 			ip2dbg(("ip_multirt_apply_membership: "
28884 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28885 			    "error %d [success %u]\n",
28886 			    ksym ? ksym : "?",
28887 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28888 			    error, or->or_private));
28889 		}
28890 
28891 		ire_refrele(ire_gw);
28892 		if (error == EINPROGRESS) {
28893 			IRB_REFRELE(irb);
28894 			return (error);
28895 		}
28896 	}
28897 	IRB_REFRELE(irb);
28898 	/*
28899 	 * Consider the call as successful if we succeeded on at least
28900 	 * one interface. Otherwise, return the last encountered error.
28901 	 */
28902 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28903 }
28904 
28905 
28906 /*
28907  * Issue a warning regarding a route crossing an interface with an
28908  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28909  * amount of time is logged.
28910  */
28911 static void
28912 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28913 {
28914 	hrtime_t	current = gethrtime();
28915 	char		buf[INET_ADDRSTRLEN];
28916 	ip_stack_t	*ipst = ire->ire_ipst;
28917 
28918 	/* Convert interval in ms to hrtime in ns */
28919 	if (ipst->ips_multirt_bad_mtu_last_time +
28920 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28921 	    current) {
28922 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28923 		    "to %s, incorrect MTU %u (expected %u)\n",
28924 		    ip_dot_addr(ire->ire_addr, buf),
28925 		    ire->ire_max_frag, max_frag);
28926 
28927 		ipst->ips_multirt_bad_mtu_last_time = current;
28928 	}
28929 }
28930 
28931 
28932 /*
28933  * Get the CGTP (multirouting) filtering status.
28934  * If 0, the CGTP hooks are transparent.
28935  */
28936 /* ARGSUSED */
28937 static int
28938 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28939 {
28940 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28941 
28942 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28943 	return (0);
28944 }
28945 
28946 
28947 /*
28948  * Set the CGTP (multirouting) filtering status.
28949  * If the status is changed from active to transparent
28950  * or from transparent to active, forward the new status
28951  * to the filtering module (if loaded).
28952  */
28953 /* ARGSUSED */
28954 static int
28955 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28956     cred_t *ioc_cr)
28957 {
28958 	long		new_value;
28959 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28960 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28961 
28962 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28963 		return (EPERM);
28964 
28965 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28966 	    new_value < 0 || new_value > 1) {
28967 		return (EINVAL);
28968 	}
28969 
28970 	if ((!*ip_cgtp_filter_value) && new_value) {
28971 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28972 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28973 		    " (module not loaded)" : "");
28974 	}
28975 	if (*ip_cgtp_filter_value && (!new_value)) {
28976 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28977 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28978 		    " (module not loaded)" : "");
28979 	}
28980 
28981 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28982 		int	res;
28983 		netstackid_t stackid;
28984 
28985 		stackid = ipst->ips_netstack->netstack_stackid;
28986 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28987 		    new_value);
28988 		if (res)
28989 			return (res);
28990 	}
28991 
28992 	*ip_cgtp_filter_value = (boolean_t)new_value;
28993 
28994 	return (0);
28995 }
28996 
28997 
28998 /*
28999  * Return the expected CGTP hooks version number.
29000  */
29001 int
29002 ip_cgtp_filter_supported(void)
29003 {
29004 	return (ip_cgtp_filter_rev);
29005 }
29006 
29007 
29008 /*
29009  * CGTP hooks can be registered by invoking this function.
29010  * Checks that the version number matches.
29011  */
29012 int
29013 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29014 {
29015 	netstack_t *ns;
29016 	ip_stack_t *ipst;
29017 
29018 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29019 		return (ENOTSUP);
29020 
29021 	ns = netstack_find_by_stackid(stackid);
29022 	if (ns == NULL)
29023 		return (EINVAL);
29024 	ipst = ns->netstack_ip;
29025 	ASSERT(ipst != NULL);
29026 
29027 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29028 		netstack_rele(ns);
29029 		return (EALREADY);
29030 	}
29031 
29032 	ipst->ips_ip_cgtp_filter_ops = ops;
29033 	netstack_rele(ns);
29034 	return (0);
29035 }
29036 
29037 /*
29038  * CGTP hooks can be unregistered by invoking this function.
29039  * Returns ENXIO if there was no registration.
29040  * Returns EBUSY if the ndd variable has not been turned off.
29041  */
29042 int
29043 ip_cgtp_filter_unregister(netstackid_t stackid)
29044 {
29045 	netstack_t *ns;
29046 	ip_stack_t *ipst;
29047 
29048 	ns = netstack_find_by_stackid(stackid);
29049 	if (ns == NULL)
29050 		return (EINVAL);
29051 	ipst = ns->netstack_ip;
29052 	ASSERT(ipst != NULL);
29053 
29054 	if (ipst->ips_ip_cgtp_filter) {
29055 		netstack_rele(ns);
29056 		return (EBUSY);
29057 	}
29058 
29059 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29060 		netstack_rele(ns);
29061 		return (ENXIO);
29062 	}
29063 	ipst->ips_ip_cgtp_filter_ops = NULL;
29064 	netstack_rele(ns);
29065 	return (0);
29066 }
29067 
29068 /*
29069  * Check whether there is a CGTP filter registration.
29070  * Returns non-zero if there is a registration, otherwise returns zero.
29071  * Note: returns zero if bad stackid.
29072  */
29073 int
29074 ip_cgtp_filter_is_registered(netstackid_t stackid)
29075 {
29076 	netstack_t *ns;
29077 	ip_stack_t *ipst;
29078 	int ret;
29079 
29080 	ns = netstack_find_by_stackid(stackid);
29081 	if (ns == NULL)
29082 		return (0);
29083 	ipst = ns->netstack_ip;
29084 	ASSERT(ipst != NULL);
29085 
29086 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29087 		ret = 1;
29088 	else
29089 		ret = 0;
29090 
29091 	netstack_rele(ns);
29092 	return (ret);
29093 }
29094 
29095 static squeue_func_t
29096 ip_squeue_switch(int val)
29097 {
29098 	squeue_func_t rval = squeue_fill;
29099 
29100 	switch (val) {
29101 	case IP_SQUEUE_ENTER_NODRAIN:
29102 		rval = squeue_enter_nodrain;
29103 		break;
29104 	case IP_SQUEUE_ENTER:
29105 		rval = squeue_enter;
29106 		break;
29107 	default:
29108 		break;
29109 	}
29110 	return (rval);
29111 }
29112 
29113 /* ARGSUSED */
29114 static int
29115 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29116     caddr_t addr, cred_t *cr)
29117 {
29118 	int *v = (int *)addr;
29119 	long new_value;
29120 
29121 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29122 		return (EPERM);
29123 
29124 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29125 		return (EINVAL);
29126 
29127 	ip_input_proc = ip_squeue_switch(new_value);
29128 	*v = new_value;
29129 	return (0);
29130 }
29131 
29132 /* ARGSUSED */
29133 static int
29134 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29135     caddr_t addr, cred_t *cr)
29136 {
29137 	int *v = (int *)addr;
29138 	long new_value;
29139 
29140 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29141 		return (EPERM);
29142 
29143 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29144 		return (EINVAL);
29145 
29146 	*v = new_value;
29147 	return (0);
29148 }
29149 
29150 /*
29151  * Handle changes to ipmp_hook_emulation ndd variable.
29152  * Need to update phyint_hook_ifindex.
29153  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29154  */
29155 static void
29156 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29157 {
29158 	phyint_t *phyi;
29159 	phyint_t *phyi_tmp;
29160 	char *groupname;
29161 	int namelen;
29162 	ill_t	*ill;
29163 	boolean_t new_group;
29164 
29165 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29166 	/*
29167 	 * Group indicies are stored in the phyint - a common structure
29168 	 * to both IPv4 and IPv6.
29169 	 */
29170 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29171 	for (; phyi != NULL;
29172 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29173 	    phyi, AVL_AFTER)) {
29174 		/* Ignore the ones that do not have a group */
29175 		if (phyi->phyint_groupname_len == 0)
29176 			continue;
29177 
29178 		/*
29179 		 * Look for other phyint in group.
29180 		 * Clear name/namelen so the lookup doesn't find ourselves.
29181 		 */
29182 		namelen = phyi->phyint_groupname_len;
29183 		groupname = phyi->phyint_groupname;
29184 		phyi->phyint_groupname_len = 0;
29185 		phyi->phyint_groupname = NULL;
29186 
29187 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29188 		/* Restore */
29189 		phyi->phyint_groupname_len = namelen;
29190 		phyi->phyint_groupname = groupname;
29191 
29192 		new_group = B_FALSE;
29193 		if (ipst->ips_ipmp_hook_emulation) {
29194 			/*
29195 			 * If the group already exists and has already
29196 			 * been assigned a group ifindex, we use the existing
29197 			 * group_ifindex, otherwise we pick a new group_ifindex
29198 			 * here.
29199 			 */
29200 			if (phyi_tmp != NULL &&
29201 			    phyi_tmp->phyint_group_ifindex != 0) {
29202 				phyi->phyint_group_ifindex =
29203 				    phyi_tmp->phyint_group_ifindex;
29204 			} else {
29205 				/* XXX We need a recovery strategy here. */
29206 				if (!ip_assign_ifindex(
29207 				    &phyi->phyint_group_ifindex, ipst))
29208 					cmn_err(CE_PANIC,
29209 					    "ip_assign_ifindex() failed");
29210 				new_group = B_TRUE;
29211 			}
29212 		} else {
29213 			phyi->phyint_group_ifindex = 0;
29214 		}
29215 		if (ipst->ips_ipmp_hook_emulation)
29216 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29217 		else
29218 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29219 
29220 		/*
29221 		 * For IP Filter to find out the relationship between
29222 		 * names and interface indicies, we need to generate
29223 		 * a NE_PLUMB event when a new group can appear.
29224 		 * We always generate events when a new interface appears
29225 		 * (even when ipmp_hook_emulation is set) so there
29226 		 * is no need to generate NE_PLUMB events when
29227 		 * ipmp_hook_emulation is turned off.
29228 		 * And since it isn't critical for IP Filter to get
29229 		 * the NE_UNPLUMB events we skip those here.
29230 		 */
29231 		if (new_group) {
29232 			/*
29233 			 * First phyint in group - generate group PLUMB event.
29234 			 * Since we are not running inside the ipsq we do
29235 			 * the dispatch immediately.
29236 			 */
29237 			if (phyi->phyint_illv4 != NULL)
29238 				ill = phyi->phyint_illv4;
29239 			else
29240 				ill = phyi->phyint_illv6;
29241 
29242 			if (ill != NULL) {
29243 				mutex_enter(&ill->ill_lock);
29244 				ill_nic_info_plumb(ill, B_TRUE);
29245 				ill_nic_info_dispatch(ill);
29246 				mutex_exit(&ill->ill_lock);
29247 			}
29248 		}
29249 	}
29250 	rw_exit(&ipst->ips_ill_g_lock);
29251 }
29252 
29253 /* ARGSUSED */
29254 static int
29255 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29256     caddr_t addr, cred_t *cr)
29257 {
29258 	int *v = (int *)addr;
29259 	long new_value;
29260 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29261 
29262 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29263 		return (EINVAL);
29264 
29265 	if (*v != new_value) {
29266 		*v = new_value;
29267 		ipmp_hook_emulation_changed(ipst);
29268 	}
29269 	return (0);
29270 }
29271 
29272 static void *
29273 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29274 {
29275 	kstat_t *ksp;
29276 
29277 	ip_stat_t template = {
29278 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29279 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29280 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29281 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29282 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29283 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29284 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29285 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29286 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29287 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29288 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29289 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29290 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29291 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29292 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29293 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29294 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29295 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29296 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29297 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29298 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29299 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29300 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29301 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29302 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29303 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29304 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29305 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29306 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29307 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29308 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29309 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29310 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29311 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29312 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29313 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29314 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29315 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29316 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29317 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29318 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29319 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29320 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29321 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29322 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29323 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29324 	};
29325 
29326 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29327 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29328 	    KSTAT_FLAG_VIRTUAL, stackid);
29329 
29330 	if (ksp == NULL)
29331 		return (NULL);
29332 
29333 	bcopy(&template, ip_statisticsp, sizeof (template));
29334 	ksp->ks_data = (void *)ip_statisticsp;
29335 	ksp->ks_private = (void *)(uintptr_t)stackid;
29336 
29337 	kstat_install(ksp);
29338 	return (ksp);
29339 }
29340 
29341 static void
29342 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29343 {
29344 	if (ksp != NULL) {
29345 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29346 		kstat_delete_netstack(ksp, stackid);
29347 	}
29348 }
29349 
29350 static void *
29351 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29352 {
29353 	kstat_t	*ksp;
29354 
29355 	ip_named_kstat_t template = {
29356 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29357 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29358 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29359 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29360 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29361 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29362 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29363 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29364 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29365 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29366 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29367 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29368 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29369 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29370 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29371 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29372 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29373 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29374 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29375 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29376 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29377 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29378 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29379 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29380 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29381 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29382 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29383 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29384 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29385 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29386 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29387 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29388 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29389 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29390 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29391 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29392 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29393 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29394 	};
29395 
29396 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29397 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29398 	if (ksp == NULL || ksp->ks_data == NULL)
29399 		return (NULL);
29400 
29401 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29402 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29403 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29404 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29405 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29406 
29407 	template.netToMediaEntrySize.value.i32 =
29408 	    sizeof (mib2_ipNetToMediaEntry_t);
29409 
29410 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29411 
29412 	bcopy(&template, ksp->ks_data, sizeof (template));
29413 	ksp->ks_update = ip_kstat_update;
29414 	ksp->ks_private = (void *)(uintptr_t)stackid;
29415 
29416 	kstat_install(ksp);
29417 	return (ksp);
29418 }
29419 
29420 static void
29421 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29422 {
29423 	if (ksp != NULL) {
29424 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29425 		kstat_delete_netstack(ksp, stackid);
29426 	}
29427 }
29428 
29429 static int
29430 ip_kstat_update(kstat_t *kp, int rw)
29431 {
29432 	ip_named_kstat_t *ipkp;
29433 	mib2_ipIfStatsEntry_t ipmib;
29434 	ill_walk_context_t ctx;
29435 	ill_t *ill;
29436 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29437 	netstack_t	*ns;
29438 	ip_stack_t	*ipst;
29439 
29440 	if (kp == NULL || kp->ks_data == NULL)
29441 		return (EIO);
29442 
29443 	if (rw == KSTAT_WRITE)
29444 		return (EACCES);
29445 
29446 	ns = netstack_find_by_stackid(stackid);
29447 	if (ns == NULL)
29448 		return (-1);
29449 	ipst = ns->netstack_ip;
29450 	if (ipst == NULL) {
29451 		netstack_rele(ns);
29452 		return (-1);
29453 	}
29454 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29455 
29456 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29457 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29458 	ill = ILL_START_WALK_V4(&ctx, ipst);
29459 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29460 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29461 	rw_exit(&ipst->ips_ill_g_lock);
29462 
29463 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29464 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29465 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29466 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29467 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29468 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29469 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29470 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29471 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29472 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29473 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29474 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29475 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29476 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29477 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29478 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29479 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29480 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29481 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29482 
29483 	ipkp->routingDiscards.value.ui32 =	0;
29484 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29485 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29486 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29487 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29488 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29489 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29490 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29491 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29492 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29493 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29494 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29495 
29496 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29497 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29498 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29499 
29500 	netstack_rele(ns);
29501 
29502 	return (0);
29503 }
29504 
29505 static void *
29506 icmp_kstat_init(netstackid_t stackid)
29507 {
29508 	kstat_t	*ksp;
29509 
29510 	icmp_named_kstat_t template = {
29511 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29512 		{ "inErrors",		KSTAT_DATA_UINT32 },
29513 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29514 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29515 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29516 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29517 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29518 		{ "inEchos",		KSTAT_DATA_UINT32 },
29519 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29520 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29521 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29522 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29523 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29524 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29525 		{ "outErrors",		KSTAT_DATA_UINT32 },
29526 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29527 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29528 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29529 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29530 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29531 		{ "outEchos",		KSTAT_DATA_UINT32 },
29532 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29533 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29534 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29535 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29536 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29537 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29538 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29539 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29540 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29541 		{ "outDrops",		KSTAT_DATA_UINT32 },
29542 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29543 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29544 	};
29545 
29546 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29547 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29548 	if (ksp == NULL || ksp->ks_data == NULL)
29549 		return (NULL);
29550 
29551 	bcopy(&template, ksp->ks_data, sizeof (template));
29552 
29553 	ksp->ks_update = icmp_kstat_update;
29554 	ksp->ks_private = (void *)(uintptr_t)stackid;
29555 
29556 	kstat_install(ksp);
29557 	return (ksp);
29558 }
29559 
29560 static void
29561 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29562 {
29563 	if (ksp != NULL) {
29564 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29565 		kstat_delete_netstack(ksp, stackid);
29566 	}
29567 }
29568 
29569 static int
29570 icmp_kstat_update(kstat_t *kp, int rw)
29571 {
29572 	icmp_named_kstat_t *icmpkp;
29573 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29574 	netstack_t	*ns;
29575 	ip_stack_t	*ipst;
29576 
29577 	if ((kp == NULL) || (kp->ks_data == NULL))
29578 		return (EIO);
29579 
29580 	if (rw == KSTAT_WRITE)
29581 		return (EACCES);
29582 
29583 	ns = netstack_find_by_stackid(stackid);
29584 	if (ns == NULL)
29585 		return (-1);
29586 	ipst = ns->netstack_ip;
29587 	if (ipst == NULL) {
29588 		netstack_rele(ns);
29589 		return (-1);
29590 	}
29591 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29592 
29593 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29594 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29595 	icmpkp->inDestUnreachs.value.ui32 =
29596 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29597 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29598 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29599 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29600 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29601 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29602 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29603 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29604 	icmpkp->inTimestampReps.value.ui32 =
29605 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29606 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29607 	icmpkp->inAddrMaskReps.value.ui32 =
29608 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29609 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29610 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29611 	icmpkp->outDestUnreachs.value.ui32 =
29612 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29613 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29614 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29615 	icmpkp->outSrcQuenchs.value.ui32 =
29616 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29617 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29618 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29619 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29620 	icmpkp->outTimestamps.value.ui32 =
29621 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29622 	icmpkp->outTimestampReps.value.ui32 =
29623 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29624 	icmpkp->outAddrMasks.value.ui32 =
29625 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29626 	icmpkp->outAddrMaskReps.value.ui32 =
29627 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29628 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29629 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29630 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29631 	icmpkp->outFragNeeded.value.ui32 =
29632 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29633 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29634 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29635 	icmpkp->inBadRedirects.value.ui32 =
29636 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29637 
29638 	netstack_rele(ns);
29639 	return (0);
29640 }
29641 
29642 /*
29643  * This is the fanout function for raw socket opened for SCTP.  Note
29644  * that it is called after SCTP checks that there is no socket which
29645  * wants a packet.  Then before SCTP handles this out of the blue packet,
29646  * this function is called to see if there is any raw socket for SCTP.
29647  * If there is and it is bound to the correct address, the packet will
29648  * be sent to that socket.  Note that only one raw socket can be bound to
29649  * a port.  This is assured in ipcl_sctp_hash_insert();
29650  */
29651 void
29652 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29653     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29654     zoneid_t zoneid)
29655 {
29656 	conn_t		*connp;
29657 	queue_t		*rq;
29658 	mblk_t		*first_mp;
29659 	boolean_t	secure;
29660 	ip6_t		*ip6h;
29661 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29662 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29663 
29664 	first_mp = mp;
29665 	if (mctl_present) {
29666 		mp = first_mp->b_cont;
29667 		secure = ipsec_in_is_secure(first_mp);
29668 		ASSERT(mp != NULL);
29669 	} else {
29670 		secure = B_FALSE;
29671 	}
29672 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29673 
29674 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29675 	if (connp == NULL) {
29676 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29677 		return;
29678 	}
29679 	rq = connp->conn_rq;
29680 	if (!canputnext(rq)) {
29681 		CONN_DEC_REF(connp);
29682 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29683 		freemsg(first_mp);
29684 		return;
29685 	}
29686 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29687 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29688 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29689 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29690 		if (first_mp == NULL) {
29691 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29692 			CONN_DEC_REF(connp);
29693 			return;
29694 		}
29695 	}
29696 	/*
29697 	 * We probably should not send M_CTL message up to
29698 	 * raw socket.
29699 	 */
29700 	if (mctl_present)
29701 		freeb(first_mp);
29702 
29703 	/* Initiate IPPF processing here if needed. */
29704 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29705 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29706 		ip_process(IPP_LOCAL_IN, &mp,
29707 		    recv_ill->ill_phyint->phyint_ifindex);
29708 		if (mp == NULL) {
29709 			CONN_DEC_REF(connp);
29710 			return;
29711 		}
29712 	}
29713 
29714 	if (connp->conn_recvif || connp->conn_recvslla ||
29715 	    ((connp->conn_ip_recvpktinfo ||
29716 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29717 	    (flags & IP_FF_IPINFO))) {
29718 		int in_flags = 0;
29719 
29720 		/*
29721 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29722 		 * IPF_RECVIF.
29723 		 */
29724 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29725 			in_flags = IPF_RECVIF;
29726 		}
29727 		if (connp->conn_recvslla) {
29728 			in_flags |= IPF_RECVSLLA;
29729 		}
29730 		if (isv4) {
29731 			mp = ip_add_info(mp, recv_ill, in_flags,
29732 			    IPCL_ZONEID(connp), ipst);
29733 		} else {
29734 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29735 			if (mp == NULL) {
29736 				BUMP_MIB(recv_ill->ill_ip_mib,
29737 				    ipIfStatsInDiscards);
29738 				CONN_DEC_REF(connp);
29739 				return;
29740 			}
29741 		}
29742 	}
29743 
29744 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29745 	/*
29746 	 * We are sending the IPSEC_IN message also up. Refer
29747 	 * to comments above this function.
29748 	 */
29749 	putnext(rq, mp);
29750 	CONN_DEC_REF(connp);
29751 }
29752 
29753 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29754 {									\
29755 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29756 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29757 }
29758 /*
29759  * This function should be called only if all packet processing
29760  * including fragmentation is complete. Callers of this function
29761  * must set mp->b_prev to one of these values:
29762  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29763  * prior to handing over the mp as first argument to this function.
29764  *
29765  * If the ire passed by caller is incomplete, this function
29766  * queues the packet and if necessary, sends ARP request and bails.
29767  * If the ire passed is fully resolved, we simply prepend
29768  * the link-layer header to the packet, do ipsec hw acceleration
29769  * work if necessary, and send the packet out on the wire.
29770  *
29771  * NOTE: IPsec will only call this function with fully resolved
29772  * ires if hw acceleration is involved.
29773  * TODO list :
29774  * 	a Handle M_MULTIDATA so that
29775  *	  tcp_multisend->tcp_multisend_data can
29776  *	  call ip_xmit_v4 directly
29777  *	b Handle post-ARP work for fragments so that
29778  *	  ip_wput_frag can call this function.
29779  */
29780 ipxmit_state_t
29781 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29782 {
29783 	nce_t		*arpce;
29784 	queue_t		*q;
29785 	int		ill_index;
29786 	mblk_t		*nxt_mp, *first_mp;
29787 	boolean_t	xmit_drop = B_FALSE;
29788 	ip_proc_t	proc;
29789 	ill_t		*out_ill;
29790 	int		pkt_len;
29791 
29792 	arpce = ire->ire_nce;
29793 	ASSERT(arpce != NULL);
29794 
29795 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29796 
29797 	mutex_enter(&arpce->nce_lock);
29798 	switch (arpce->nce_state) {
29799 	case ND_REACHABLE:
29800 		/* If there are other queued packets, queue this packet */
29801 		if (arpce->nce_qd_mp != NULL) {
29802 			if (mp != NULL)
29803 				nce_queue_mp_common(arpce, mp, B_FALSE);
29804 			mp = arpce->nce_qd_mp;
29805 		}
29806 		arpce->nce_qd_mp = NULL;
29807 		mutex_exit(&arpce->nce_lock);
29808 
29809 		/*
29810 		 * Flush the queue.  In the common case, where the
29811 		 * ARP is already resolved,  it will go through the
29812 		 * while loop only once.
29813 		 */
29814 		while (mp != NULL) {
29815 
29816 			nxt_mp = mp->b_next;
29817 			mp->b_next = NULL;
29818 			ASSERT(mp->b_datap->db_type != M_CTL);
29819 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29820 			/*
29821 			 * This info is needed for IPQOS to do COS marking
29822 			 * in ip_wput_attach_llhdr->ip_process.
29823 			 */
29824 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29825 			mp->b_prev = NULL;
29826 
29827 			/* set up ill index for outbound qos processing */
29828 			out_ill = ire_to_ill(ire);
29829 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29830 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29831 			    ill_index);
29832 			if (first_mp == NULL) {
29833 				xmit_drop = B_TRUE;
29834 				BUMP_MIB(out_ill->ill_ip_mib,
29835 				    ipIfStatsOutDiscards);
29836 				goto next_mp;
29837 			}
29838 			/* non-ipsec hw accel case */
29839 			if (io == NULL || !io->ipsec_out_accelerated) {
29840 				/* send it */
29841 				q = ire->ire_stq;
29842 				if (proc == IPP_FWD_OUT) {
29843 					UPDATE_IB_PKT_COUNT(ire);
29844 				} else {
29845 					UPDATE_OB_PKT_COUNT(ire);
29846 				}
29847 				ire->ire_last_used_time = lbolt;
29848 
29849 				if (flow_ctl_enabled || canputnext(q)) {
29850 					if (proc == IPP_FWD_OUT) {
29851 
29852 					BUMP_MIB(out_ill->ill_ip_mib,
29853 					    ipIfStatsHCOutForwDatagrams);
29854 
29855 					}
29856 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29857 					    pkt_len);
29858 
29859 					putnext(q, first_mp);
29860 				} else {
29861 					BUMP_MIB(out_ill->ill_ip_mib,
29862 					    ipIfStatsOutDiscards);
29863 					xmit_drop = B_TRUE;
29864 					freemsg(first_mp);
29865 				}
29866 			} else {
29867 				/*
29868 				 * Safety Pup says: make sure this
29869 				 *  is going to the right interface!
29870 				 */
29871 				ill_t *ill1 =
29872 				    (ill_t *)ire->ire_stq->q_ptr;
29873 				int ifindex =
29874 				    ill1->ill_phyint->phyint_ifindex;
29875 				if (ifindex !=
29876 				    io->ipsec_out_capab_ill_index) {
29877 					xmit_drop = B_TRUE;
29878 					freemsg(mp);
29879 				} else {
29880 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29881 					    pkt_len);
29882 					ipsec_hw_putnext(ire->ire_stq, mp);
29883 				}
29884 			}
29885 next_mp:
29886 			mp = nxt_mp;
29887 		} /* while (mp != NULL) */
29888 		if (xmit_drop)
29889 			return (SEND_FAILED);
29890 		else
29891 			return (SEND_PASSED);
29892 
29893 	case ND_INITIAL:
29894 	case ND_INCOMPLETE:
29895 
29896 		/*
29897 		 * While we do send off packets to dests that
29898 		 * use fully-resolved CGTP routes, we do not
29899 		 * handle unresolved CGTP routes.
29900 		 */
29901 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29902 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29903 
29904 		if (mp != NULL) {
29905 			/* queue the packet */
29906 			nce_queue_mp_common(arpce, mp, B_FALSE);
29907 		}
29908 
29909 		if (arpce->nce_state == ND_INCOMPLETE) {
29910 			mutex_exit(&arpce->nce_lock);
29911 			DTRACE_PROBE3(ip__xmit__incomplete,
29912 			    (ire_t *), ire, (mblk_t *), mp,
29913 			    (ipsec_out_t *), io);
29914 			return (LOOKUP_IN_PROGRESS);
29915 		}
29916 
29917 		arpce->nce_state = ND_INCOMPLETE;
29918 		mutex_exit(&arpce->nce_lock);
29919 		/*
29920 		 * Note that ire_add() (called from ire_forward())
29921 		 * holds a ref on the ire until ARP is completed.
29922 		 */
29923 
29924 		ire_arpresolve(ire, ire_to_ill(ire));
29925 		return (LOOKUP_IN_PROGRESS);
29926 	default:
29927 		ASSERT(0);
29928 		mutex_exit(&arpce->nce_lock);
29929 		return (LLHDR_RESLV_FAILED);
29930 	}
29931 }
29932 
29933 #undef	UPDATE_IP_MIB_OB_COUNTERS
29934 
29935 /*
29936  * Return B_TRUE if the buffers differ in length or content.
29937  * This is used for comparing extension header buffers.
29938  * Note that an extension header would be declared different
29939  * even if all that changed was the next header value in that header i.e.
29940  * what really changed is the next extension header.
29941  */
29942 boolean_t
29943 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29944     uint_t blen)
29945 {
29946 	if (!b_valid)
29947 		blen = 0;
29948 
29949 	if (alen != blen)
29950 		return (B_TRUE);
29951 	if (alen == 0)
29952 		return (B_FALSE);	/* Both zero length */
29953 	return (bcmp(abuf, bbuf, alen));
29954 }
29955 
29956 /*
29957  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29958  * Return B_FALSE if memory allocation fails - don't change any state!
29959  */
29960 boolean_t
29961 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29962     const void *src, uint_t srclen)
29963 {
29964 	void *dst;
29965 
29966 	if (!src_valid)
29967 		srclen = 0;
29968 
29969 	ASSERT(*dstlenp == 0);
29970 	if (src != NULL && srclen != 0) {
29971 		dst = mi_alloc(srclen, BPRI_MED);
29972 		if (dst == NULL)
29973 			return (B_FALSE);
29974 	} else {
29975 		dst = NULL;
29976 	}
29977 	if (*dstp != NULL)
29978 		mi_free(*dstp);
29979 	*dstp = dst;
29980 	*dstlenp = dst == NULL ? 0 : srclen;
29981 	return (B_TRUE);
29982 }
29983 
29984 /*
29985  * Replace what is in *dst, *dstlen with the source.
29986  * Assumes ip_allocbuf has already been called.
29987  */
29988 void
29989 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29990     const void *src, uint_t srclen)
29991 {
29992 	if (!src_valid)
29993 		srclen = 0;
29994 
29995 	ASSERT(*dstlenp == srclen);
29996 	if (src != NULL && srclen != 0)
29997 		bcopy(src, *dstp, srclen);
29998 }
29999 
30000 /*
30001  * Free the storage pointed to by the members of an ip6_pkt_t.
30002  */
30003 void
30004 ip6_pkt_free(ip6_pkt_t *ipp)
30005 {
30006 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30007 
30008 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30009 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30010 		ipp->ipp_hopopts = NULL;
30011 		ipp->ipp_hopoptslen = 0;
30012 	}
30013 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30014 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30015 		ipp->ipp_rtdstopts = NULL;
30016 		ipp->ipp_rtdstoptslen = 0;
30017 	}
30018 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30019 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30020 		ipp->ipp_dstopts = NULL;
30021 		ipp->ipp_dstoptslen = 0;
30022 	}
30023 	if (ipp->ipp_fields & IPPF_RTHDR) {
30024 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30025 		ipp->ipp_rthdr = NULL;
30026 		ipp->ipp_rthdrlen = 0;
30027 	}
30028 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30029 	    IPPF_RTHDR);
30030 }
30031