xref: /titanic_50/usr/src/uts/common/inet/ip/ip.c (revision 9e2cd38c103ae52a41b09823a11c9b5c059555f0)
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 2008 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/optcom.h>
73 #include <inet/kstatcom.h>
74 
75 #include <netinet/igmp_var.h>
76 #include <netinet/ip6.h>
77 #include <netinet/icmp6.h>
78 #include <netinet/sctp.h>
79 
80 #include <inet/ip.h>
81 #include <inet/ip_impl.h>
82 #include <inet/ip6.h>
83 #include <inet/ip6_asp.h>
84 #include <inet/tcp.h>
85 #include <inet/tcp_impl.h>
86 #include <inet/ip_multi.h>
87 #include <inet/ip_if.h>
88 #include <inet/ip_ire.h>
89 #include <inet/ip_ftable.h>
90 #include <inet/ip_rts.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 <inet/rawip_impl.h>
122 #include <inet/rts_impl.h>
123 #include <sys/sunddi.h>
124 
125 #include <sys/tsol/label.h>
126 #include <sys/tsol/tnet.h>
127 
128 #include <rpc/pmap_prot.h>
129 
130 /*
131  * Values for squeue switch:
132  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
133  * IP_SQUEUE_ENTER: squeue_enter
134  * IP_SQUEUE_FILL: squeue_fill
135  */
136 int ip_squeue_enter = 2;	/* Setable in /etc/system */
137 
138 squeue_func_t ip_input_proc;
139 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
140 
141 /*
142  * Setable in /etc/system
143  */
144 int ip_poll_normal_ms = 100;
145 int ip_poll_normal_ticks = 0;
146 int ip_modclose_ackwait_ms = 3000;
147 
148 /*
149  * It would be nice to have these present only in DEBUG systems, but the
150  * current design of the global symbol checking logic requires them to be
151  * unconditionally present.
152  */
153 uint_t ip_thread_data;			/* TSD key for debug support */
154 krwlock_t ip_thread_rwlock;
155 list_t	ip_thread_list;
156 
157 /*
158  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
159  */
160 
161 struct listptr_s {
162 	mblk_t	*lp_head;	/* pointer to the head of the list */
163 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
164 };
165 
166 typedef struct listptr_s listptr_t;
167 
168 /*
169  * This is used by ip_snmp_get_mib2_ip_route_media and
170  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
171  */
172 typedef struct iproutedata_s {
173 	uint_t		ird_idx;
174 	listptr_t	ird_route;	/* ipRouteEntryTable */
175 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
176 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
177 } iproutedata_t;
178 
179 /*
180  * Cluster specific hooks. These should be NULL when booted as a non-cluster
181  */
182 
183 /*
184  * Hook functions to enable cluster networking
185  * On non-clustered systems these vectors must always be NULL.
186  *
187  * Hook function to Check ip specified ip address is a shared ip address
188  * in the cluster
189  *
190  */
191 int (*cl_inet_isclusterwide)(uint8_t protocol,
192     sa_family_t addr_family, uint8_t *laddrp) = NULL;
193 
194 /*
195  * Hook function to generate cluster wide ip fragment identifier
196  */
197 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
198     uint8_t *laddrp, uint8_t *faddrp) = NULL;
199 
200 /*
201  * Synchronization notes:
202  *
203  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
204  * MT level protection given by STREAMS. IP uses a combination of its own
205  * internal serialization mechanism and standard Solaris locking techniques.
206  * The internal serialization is per phyint (no IPMP) or per IPMP group.
207  * This is used to serialize plumbing operations, IPMP operations, certain
208  * multicast operations, most set ioctls, igmp/mld timers etc.
209  *
210  * Plumbing is a long sequence of operations involving message
211  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
212  * involved in plumbing operations. A natural model is to serialize these
213  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
214  * parallel without any interference. But various set ioctls on hme0 are best
215  * serialized. However if the system uses IPMP, the operations are easier if
216  * they are serialized on a per IPMP group basis since IPMP operations
217  * happen across ill's of a group. Thus the lowest common denominator is to
218  * serialize most set ioctls, multicast join/leave operations, IPMP operations
219  * igmp/mld timer operations, and processing of DLPI control messages received
220  * from drivers on a per IPMP group basis. If the system does not employ
221  * IPMP the serialization is on a per phyint basis. This serialization is
222  * provided by the ipsq_t and primitives operating on this. Details can
223  * be found in ip_if.c above the core primitives operating on ipsq_t.
224  *
225  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
226  * Simiarly lookup of an ire by a thread also returns a refheld ire.
227  * In addition ipif's and ill's referenced by the ire are also indirectly
228  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
229  * the ipif's address or netmask change as long as an ipif is refheld
230  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
231  * address of an ipif has to go through the ipsq_t. This ensures that only
232  * 1 such exclusive operation proceeds at any time on the ipif. It then
233  * deletes all ires associated with this ipif, and waits for all refcnts
234  * associated with this ipif to come down to zero. The address is changed
235  * only after the ipif has been quiesced. Then the ipif is brought up again.
236  * More details are described above the comment in ip_sioctl_flags.
237  *
238  * Packet processing is based mostly on IREs and are fully multi-threaded
239  * using standard Solaris MT techniques.
240  *
241  * There are explicit locks in IP to handle:
242  * - The ip_g_head list maintained by mi_open_link() and friends.
243  *
244  * - The reassembly data structures (one lock per hash bucket)
245  *
246  * - conn_lock is meant to protect conn_t fields. The fields actually
247  *   protected by conn_lock are documented in the conn_t definition.
248  *
249  * - ire_lock to protect some of the fields of the ire, IRE tables
250  *   (one lock per hash bucket). Refer to ip_ire.c for details.
251  *
252  * - ndp_g_lock and nce_lock for protecting NCEs.
253  *
254  * - ill_lock protects fields of the ill and ipif. Details in ip.h
255  *
256  * - ill_g_lock: This is a global reader/writer lock. Protects the following
257  *	* The AVL tree based global multi list of all ills.
258  *	* The linked list of all ipifs of an ill
259  *	* The <ill-ipsq> mapping
260  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
261  *	* The illgroup list threaded by ill_group_next.
262  *	* <ill-phyint> association
263  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
264  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
265  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
266  *   will all have to hold the ill_g_lock as writer for the actual duration
267  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
268  *   may be found in the IPMP section.
269  *
270  * - ill_lock:  This is a per ill mutex.
271  *   It protects some members of the ill and is documented below.
272  *   It also protects the <ill-ipsq> mapping
273  *   It also protects the illgroup list threaded by ill_group_next.
274  *   It also protects the <ill-phyint> assoc.
275  *   It also protects the list of ipifs hanging off the ill.
276  *
277  * - ipsq_lock: This is a per ipsq_t mutex lock.
278  *   This protects all the other members of the ipsq struct except
279  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
280  *
281  * - illgrp_lock: This is a per ill_group mutex lock.
282  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
283  *   which dictates which is the next ill in an ill_group that is to be chosen
284  *   for sending outgoing packets, through creation of an IRE_CACHE that
285  *   references this ill.
286  *
287  * - phyint_lock: This is a per phyint mutex lock. Protects just the
288  *   phyint_flags
289  *
290  * - ip_g_nd_lock: This is a global reader/writer lock.
291  *   Any call to nd_load to load a new parameter to the ND table must hold the
292  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
293  *   as reader.
294  *
295  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
296  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
297  *   uniqueness check also done atomically.
298  *
299  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
300  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
301  *   as a writer when adding or deleting elements from these lists, and
302  *   as a reader when walking these lists to send a SADB update to the
303  *   IPsec capable ills.
304  *
305  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
306  *   group list linked by ill_usesrc_grp_next. It also protects the
307  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
308  *   group is being added or deleted.  This lock is taken as a reader when
309  *   walking the list/group(eg: to get the number of members in a usesrc group).
310  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
311  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
312  *   example, it is not necessary to take this lock in the initial portion
313  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
314  *   ip_sioctl_flags since the these operations are executed exclusively and
315  *   that ensures that the "usesrc group state" cannot change. The "usesrc
316  *   group state" change can happen only in the latter part of
317  *   ip_sioctl_slifusesrc and in ill_delete.
318  *
319  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
320  *
321  * To change the <ill-phyint> association, the ill_g_lock must be held
322  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
323  * must be held.
324  *
325  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
326  * and the ill_lock of the ill in question must be held.
327  *
328  * To change the <ill-illgroup> association the ill_g_lock must be held as
329  * writer and the ill_lock of the ill in question must be held.
330  *
331  * To add or delete an ipif from the list of ipifs hanging off the ill,
332  * ill_g_lock (writer) and ill_lock must be held and the thread must be
333  * a writer on the associated ipsq,.
334  *
335  * To add or delete an ill to the system, the ill_g_lock must be held as
336  * writer and the thread must be a writer on the associated ipsq.
337  *
338  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
339  * must be a writer on the associated ipsq.
340  *
341  * Lock hierarchy
342  *
343  * Some lock hierarchy scenarios are listed below.
344  *
345  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
346  * ill_g_lock -> illgrp_lock -> ill_lock
347  * ill_g_lock -> ill_lock(s) -> phyint_lock
348  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
349  * ill_g_lock -> ip_addr_avail_lock
350  * conn_lock -> irb_lock -> ill_lock -> ire_lock
351  * ill_g_lock -> ip_g_nd_lock
352  *
353  * When more than 1 ill lock is needed to be held, all ill lock addresses
354  * are sorted on address and locked starting from highest addressed lock
355  * downward.
356  *
357  * IPsec scenarios
358  *
359  * ipsa_lock -> ill_g_lock -> ill_lock
360  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ipsa_lock
362  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
363  *
364  * Trusted Solaris scenarios
365  *
366  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
367  * igsa_lock -> gcdb_lock
368  * gcgrp_rwlock -> ire_lock
369  * gcgrp_rwlock -> gcdb_lock
370  *
371  *
372  * Routing/forwarding table locking notes:
373  *
374  * Lock acquisition order: Radix tree lock, irb_lock.
375  * Requirements:
376  * i.  Walker must not hold any locks during the walker callback.
377  * ii  Walker must not see a truncated tree during the walk because of any node
378  *     deletion.
379  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
380  *     in many places in the code to walk the irb list. Thus even if all the
381  *     ires in a bucket have been deleted, we still can't free the radix node
382  *     until the ires have actually been inactive'd (freed).
383  *
384  * Tree traversal - Need to hold the global tree lock in read mode.
385  * Before dropping the global tree lock, need to either increment the ire_refcnt
386  * to ensure that the radix node can't be deleted.
387  *
388  * Tree add - Need to hold the global tree lock in write mode to add a
389  * radix node. To prevent the node from being deleted, increment the
390  * irb_refcnt, after the node is added to the tree. The ire itself is
391  * added later while holding the irb_lock, but not the tree lock.
392  *
393  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
394  * All associated ires must be inactive (i.e. freed), and irb_refcnt
395  * must be zero.
396  *
397  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
398  * global tree lock (read mode) for traversal.
399  *
400  * IPsec notes :
401  *
402  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
403  * in front of the actual packet. For outbound datagrams, the M_CTL
404  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
405  * information used by the IPsec code for applying the right level of
406  * protection. The information initialized by IP in the ipsec_out_t
407  * is determined by the per-socket policy or global policy in the system.
408  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
409  * ipsec_info.h) which starts out with nothing in it. It gets filled
410  * with the right information if it goes through the AH/ESP code, which
411  * happens if the incoming packet is secure. The information initialized
412  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
413  * the policy requirements needed by per-socket policy or global policy
414  * is met or not.
415  *
416  * If there is both per-socket policy (set using setsockopt) and there
417  * is also global policy match for the 5 tuples of the socket,
418  * ipsec_override_policy() makes the decision of which one to use.
419  *
420  * For fully connected sockets i.e dst, src [addr, port] is known,
421  * conn_policy_cached is set indicating that policy has been cached.
422  * conn_in_enforce_policy may or may not be set depending on whether
423  * there is a global policy match or per-socket policy match.
424  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
425  * Once the right policy is set on the conn_t, policy cannot change for
426  * this socket. This makes life simpler for TCP (UDP ?) where
427  * re-transmissions go out with the same policy. For symmetry, policy
428  * is cached for fully connected UDP sockets also. Thus if policy is cached,
429  * it also implies that policy is latched i.e policy cannot change
430  * on these sockets. As we have the right policy on the conn, we don't
431  * have to lookup global policy for every outbound and inbound datagram
432  * and thus serving as an optimization. Note that a global policy change
433  * does not affect fully connected sockets if they have policy. If fully
434  * connected sockets did not have any policy associated with it, global
435  * policy change may affect them.
436  *
437  * IP Flow control notes:
438  *
439  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
440  * cannot be sent down to the driver by IP, because of a canput failure, IP
441  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
442  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
443  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
444  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
445  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
446  * the queued messages, and removes the conn from the drain list, if all
447  * messages were drained. It also qenables the next conn in the drain list to
448  * continue the drain process.
449  *
450  * In reality the drain list is not a single list, but a configurable number
451  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
452  * list. If the ip_wsrv of the next qenabled conn does not run, because the
453  * stream closes, ip_close takes responsibility to qenable the next conn in
454  * the drain list. The directly called ip_wput path always does a putq, if
455  * it cannot putnext. Thus synchronization problems are handled between
456  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
457  * functions that manipulate this drain list. Furthermore conn_drain_insert
458  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
459  * running on a queue at any time. conn_drain_tail can be simultaneously called
460  * from both ip_wsrv and ip_close.
461  *
462  * IPQOS notes:
463  *
464  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
465  * and IPQoS modules. IPPF includes hooks in IP at different control points
466  * (callout positions) which direct packets to IPQoS modules for policy
467  * processing. Policies, if present, are global.
468  *
469  * The callout positions are located in the following paths:
470  *		o local_in (packets destined for this host)
471  *		o local_out (packets orginating from this host )
472  *		o fwd_in  (packets forwarded by this m/c - inbound)
473  *		o fwd_out (packets forwarded by this m/c - outbound)
474  * Hooks at these callout points can be enabled/disabled using the ndd variable
475  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
476  * By default all the callout positions are enabled.
477  *
478  * Outbound (local_out)
479  * Hooks are placed in ip_wput_ire and ipsec_out_process.
480  *
481  * Inbound (local_in)
482  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
483  * TCP and UDP fanout routines.
484  *
485  * Forwarding (in and out)
486  * Hooks are placed in ip_rput_forward.
487  *
488  * IP Policy Framework processing (IPPF processing)
489  * Policy processing for a packet is initiated by ip_process, which ascertains
490  * that the classifier (ipgpc) is loaded and configured, failing which the
491  * packet resumes normal processing in IP. If the clasifier is present, the
492  * packet is acted upon by one or more IPQoS modules (action instances), per
493  * filters configured in ipgpc and resumes normal IP processing thereafter.
494  * An action instance can drop a packet in course of its processing.
495  *
496  * A boolean variable, ip_policy, is used in all the fanout routines that can
497  * invoke ip_process for a packet. This variable indicates if the packet should
498  * to be sent for policy processing. The variable is set to B_TRUE by default,
499  * i.e. when the routines are invoked in the normal ip procesing path for a
500  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
501  * ip_policy is set to B_FALSE for all the routines called in these two
502  * functions because, in the former case,  we don't process loopback traffic
503  * currently while in the latter, the packets have already been processed in
504  * icmp_inbound.
505  *
506  * Zones notes:
507  *
508  * The partitioning rules for networking are as follows:
509  * 1) Packets coming from a zone must have a source address belonging to that
510  * zone.
511  * 2) Packets coming from a zone can only be sent on a physical interface on
512  * which the zone has an IP address.
513  * 3) Between two zones on the same machine, packet delivery is only allowed if
514  * there's a matching route for the destination and zone in the forwarding
515  * table.
516  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
517  * different zones can bind to the same port with the wildcard address
518  * (INADDR_ANY).
519  *
520  * The granularity of interface partitioning is at the logical interface level.
521  * Therefore, every zone has its own IP addresses, and incoming packets can be
522  * attributed to a zone unambiguously. A logical interface is placed into a zone
523  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
524  * structure. Rule (1) is implemented by modifying the source address selection
525  * algorithm so that the list of eligible addresses is filtered based on the
526  * sending process zone.
527  *
528  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
529  * across all zones, depending on their type. Here is the break-up:
530  *
531  * IRE type				Shared/exclusive
532  * --------				----------------
533  * IRE_BROADCAST			Exclusive
534  * IRE_DEFAULT (default routes)		Shared (*)
535  * IRE_LOCAL				Exclusive (x)
536  * IRE_LOOPBACK				Exclusive
537  * IRE_PREFIX (net routes)		Shared (*)
538  * IRE_CACHE				Exclusive
539  * IRE_IF_NORESOLVER (interface routes)	Exclusive
540  * IRE_IF_RESOLVER (interface routes)	Exclusive
541  * IRE_HOST (host routes)		Shared (*)
542  *
543  * (*) A zone can only use a default or off-subnet route if the gateway is
544  * directly reachable from the zone, that is, if the gateway's address matches
545  * one of the zone's logical interfaces.
546  *
547  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
548  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
549  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
550  * address of the zone itself (the destination). Since IRE_LOCAL is used
551  * for communication between zones, ip_wput_ire has special logic to set
552  * the right source address when sending using an IRE_LOCAL.
553  *
554  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
555  * ire_cache_lookup restricts loopback using an IRE_LOCAL
556  * between zone to the case when L2 would have conceptually looped the packet
557  * back, i.e. the loopback which is required since neither Ethernet drivers
558  * nor Ethernet hardware loops them back. This is the case when the normal
559  * routes (ignoring IREs with different zoneids) would send out the packet on
560  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
561  * associated.
562  *
563  * Multiple zones can share a common broadcast address; typically all zones
564  * share the 255.255.255.255 address. Incoming as well as locally originated
565  * broadcast packets must be dispatched to all the zones on the broadcast
566  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
567  * since some zones may not be on the 10.16.72/24 network. To handle this, each
568  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
569  * sent to every zone that has an IRE_BROADCAST entry for the destination
570  * address on the input ill, see conn_wantpacket().
571  *
572  * Applications in different zones can join the same multicast group address.
573  * For IPv4, group memberships are per-logical interface, so they're already
574  * inherently part of a zone. For IPv6, group memberships are per-physical
575  * interface, so we distinguish IPv6 group memberships based on group address,
576  * interface and zoneid. In both cases, received multicast packets are sent to
577  * every zone for which a group membership entry exists. On IPv6 we need to
578  * check that the target zone still has an address on the receiving physical
579  * interface; it could have been removed since the application issued the
580  * IPV6_JOIN_GROUP.
581  */
582 
583 /*
584  * Squeue Fanout flags:
585  *	0: No fanout.
586  *	1: Fanout across all squeues
587  */
588 boolean_t	ip_squeue_fanout = 0;
589 
590 /*
591  * Maximum dups allowed per packet.
592  */
593 uint_t ip_max_frag_dups = 10;
594 
595 #define	IS_SIMPLE_IPH(ipha)						\
596 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
597 
598 /* RFC1122 Conformance */
599 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
600 
601 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
602 
603 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
604 
605 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
606 		    cred_t *credp, boolean_t isv6);
607 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
608 
609 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
610 		    ip_stack_t *);
611 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
612 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
613 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
614 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
615 		    mblk_t *, int, ip_stack_t *);
616 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
617 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
618 		    ill_t *, zoneid_t);
619 static void	icmp_options_update(ipha_t *);
620 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
621 		    ip_stack_t *);
622 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
623 		    zoneid_t zoneid, ip_stack_t *);
624 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
625 static void	icmp_redirect(ill_t *, mblk_t *);
626 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
627 		    ip_stack_t *);
628 
629 static void	ip_arp_news(queue_t *, mblk_t *);
630 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
631 		    ip_stack_t *);
632 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
633 char		*ip_dot_addr(ipaddr_t, char *);
634 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
635 int		ip_close(queue_t *, int);
636 static char	*ip_dot_saddr(uchar_t *, char *);
637 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
638 		    boolean_t, boolean_t, ill_t *, zoneid_t);
639 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
640 		    boolean_t, boolean_t, zoneid_t);
641 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
642 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
643 static void	ip_lrput(queue_t *, mblk_t *);
644 ipaddr_t	ip_net_mask(ipaddr_t);
645 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
646 		    ip_stack_t *);
647 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
648 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
649 char		*ip_nv_lookup(nv_t *, int);
650 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
651 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
652 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
654     ipndp_t *, size_t);
655 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
656 void	ip_rput(queue_t *, mblk_t *);
657 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
658 		    void *dummy_arg);
659 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
660 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
661     ip_stack_t *);
662 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
663 			    ire_t *, ip_stack_t *);
664 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
665 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
666 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
667     ip_stack_t *);
668 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
669 		    uint16_t *);
670 int		ip_snmp_get(queue_t *, mblk_t *, int);
671 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
672 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
673 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
674 		    ip_stack_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
677 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
681 		    ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
683 		    ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
701 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
702 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
703 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
704 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
705 static boolean_t	ip_source_route_included(ipha_t *);
706 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
707 
708 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
709 		    zoneid_t, ip_stack_t *);
710 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
711 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
712 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
713 		    zoneid_t, ip_stack_t *);
714 
715 static void	conn_drain_init(ip_stack_t *);
716 static void	conn_drain_fini(ip_stack_t *);
717 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
718 
719 static void	conn_walk_drain(ip_stack_t *);
720 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
721     zoneid_t);
722 
723 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
724 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
725 static void	ip_stack_fini(netstackid_t stackid, void *arg);
726 
727 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
728     zoneid_t);
729 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
730     void *dummy_arg);
731 
732 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
733 
734 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
735     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
736     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
737 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
738 
739 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
740 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
741     caddr_t, cred_t *);
742 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
743     caddr_t cp, cred_t *cr);
744 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
745     cred_t *);
746 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
747     caddr_t cp, cred_t *cr);
748 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
749     cred_t *);
750 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static squeue_func_t ip_squeue_switch(int);
753 
754 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
755 static void	ip_kstat_fini(netstackid_t, kstat_t *);
756 static int	ip_kstat_update(kstat_t *kp, int rw);
757 static void	*icmp_kstat_init(netstackid_t);
758 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
759 static int	icmp_kstat_update(kstat_t *kp, int rw);
760 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
761 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
762 
763 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
764 
765 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
766     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
767 
768 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
769     ipha_t *, ill_t *, boolean_t);
770 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
771 
772 /* How long, in seconds, we allow frags to hang around. */
773 #define	IP_FRAG_TIMEOUT	60
774 
775 /*
776  * Threshold which determines whether MDT should be used when
777  * generating IP fragments; payload size must be greater than
778  * this threshold for MDT to take place.
779  */
780 #define	IP_WPUT_FRAG_MDT_MIN	32768
781 
782 /* Setable in /etc/system only */
783 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
784 
785 static long ip_rput_pullups;
786 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
787 
788 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
789 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
790 
791 int	ip_debug;
792 
793 #ifdef DEBUG
794 uint32_t ipsechw_debug = 0;
795 #endif
796 
797 /*
798  * Multirouting/CGTP stuff
799  */
800 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
801 
802 /*
803  * XXX following really should only be in a header. Would need more
804  * header and .c clean up first.
805  */
806 extern optdb_obj_t	ip_opt_obj;
807 
808 ulong_t ip_squeue_enter_unbound = 0;
809 
810 /*
811  * Named Dispatch Parameter Table.
812  * All of these are alterable, within the min/max values given, at run time.
813  */
814 static ipparam_t	lcl_param_arr[] = {
815 	/* min	max	value	name */
816 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
817 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
818 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
819 	{  0,	1,	0,	"ip_respond_to_timestamp"},
820 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
821 	{  0,	1,	1,	"ip_send_redirects"},
822 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
823 	{  0,	10,	0,	"ip_mrtdebug"},
824 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
825 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
826 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
827 	{  1,	255,	255,	"ip_def_ttl" },
828 	{  0,	1,	0,	"ip_forward_src_routed"},
829 	{  0,	256,	32,	"ip_wroff_extra" },
830 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
831 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
832 	{  0,	1,	1,	"ip_path_mtu_discovery" },
833 	{  0,	240,	30,	"ip_ignore_delete_time" },
834 	{  0,	1,	0,	"ip_ignore_redirect" },
835 	{  0,	1,	1,	"ip_output_queue" },
836 	{  1,	254,	1,	"ip_broadcast_ttl" },
837 	{  0,	99999,	100,	"ip_icmp_err_interval" },
838 	{  1,	99999,	10,	"ip_icmp_err_burst" },
839 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
840 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
841 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
842 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
843 	{  0,	1,	1,	"icmp_accept_clear_messages" },
844 	{  0,	1,	1,	"igmp_accept_clear_messages" },
845 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
846 				"ip_ndp_delay_first_probe_time"},
847 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
848 				"ip_ndp_max_unicast_solicit"},
849 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
850 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
851 	{  0,	1,	0,	"ip6_forward_src_routed"},
852 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
853 	{  0,	1,	1,	"ip6_send_redirects"},
854 	{  0,	1,	0,	"ip6_ignore_redirect" },
855 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
856 
857 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
858 
859 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
860 
861 	{  0,	1,	1,	"pim_accept_clear_messages" },
862 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
863 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
864 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
865 	{  0,	15,	0,	"ip_policy_mask" },
866 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
867 	{  0,	255,	1,	"ip_multirt_ttl" },
868 	{  0,	1,	1,	"ip_multidata_outbound" },
869 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
870 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
871 	{  0,	1000,	1,	"ip_max_temp_defend" },
872 	{  0,	1000,	3,	"ip_max_defend" },
873 	{  0,	999999,	30,	"ip_defend_interval" },
874 	{  0,	3600000, 300000, "ip_dup_recovery" },
875 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
876 	{  0,	1,	1,	"ip_lso_outbound" },
877 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
878 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
879 #ifdef DEBUG
880 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
881 #else
882 	{  0,	0,	0,	"" },
883 #endif
884 };
885 
886 /*
887  * Extended NDP table
888  * The addresses for the first two are filled in to be ips_ip_g_forward
889  * and ips_ipv6_forward at init time.
890  */
891 static ipndp_t	lcl_ndp_arr[] = {
892 	/* getf			setf		data			name */
893 #define	IPNDP_IP_FORWARDING_OFFSET	0
894 	{  ip_param_generic_get,	ip_forward_set,	NULL,
895 	    "ip_forwarding" },
896 #define	IPNDP_IP6_FORWARDING_OFFSET	1
897 	{  ip_param_generic_get,	ip_forward_set,	NULL,
898 	    "ip6_forwarding" },
899 	{  ip_ill_report,	NULL,		NULL,
900 	    "ip_ill_status" },
901 	{  ip_ipif_report,	NULL,		NULL,
902 	    "ip_ipif_status" },
903 	{  ip_ire_report,	NULL,		NULL,
904 	    "ipv4_ire_status" },
905 	{  ip_ire_report_v6,	NULL,		NULL,
906 	    "ipv6_ire_status" },
907 	{  ip_conn_report,	NULL,		NULL,
908 	    "ip_conn_status" },
909 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
910 	    "ip_rput_pullups" },
911 	{  ndp_report,		NULL,		NULL,
912 	    "ip_ndp_cache_report" },
913 	{  ip_srcid_report,	NULL,		NULL,
914 	    "ip_srcid_status" },
915 	{ ip_param_generic_get, ip_squeue_profile_set,
916 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
917 	{ ip_param_generic_get, ip_squeue_bind_set,
918 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
919 	{ ip_param_generic_get, ip_input_proc_set,
920 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
921 	{ ip_param_generic_get, ip_int_set,
922 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
923 #define	IPNDP_CGTP_FILTER_OFFSET	14
924 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
925 	    "ip_cgtp_filter" },
926 	{ ip_param_generic_get, ip_int_set,
927 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
928 #define	IPNDP_IPMP_HOOK_OFFSET	16
929 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
930 	    "ipmp_hook_emulation" },
931 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
932 	    "ip_debug" },
933 };
934 
935 /*
936  * Table of IP ioctls encoding the various properties of the ioctl and
937  * indexed based on the last byte of the ioctl command. Occasionally there
938  * is a clash, and there is more than 1 ioctl with the same last byte.
939  * In such a case 1 ioctl is encoded in the ndx table and the remaining
940  * ioctls are encoded in the misc table. An entry in the ndx table is
941  * retrieved by indexing on the last byte of the ioctl command and comparing
942  * the ioctl command with the value in the ndx table. In the event of a
943  * mismatch the misc table is then searched sequentially for the desired
944  * ioctl command.
945  *
946  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
947  */
948 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
949 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 
960 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
961 			MISC_CMD, ip_siocaddrt, NULL },
962 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
963 			MISC_CMD, ip_siocdelrt, NULL },
964 
965 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
966 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
967 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
968 			IF_CMD, ip_sioctl_get_addr, NULL },
969 
970 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
971 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
972 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
973 			IPI_GET_CMD | IPI_REPL,
974 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
975 
976 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
977 			IPI_PRIV | IPI_WR | IPI_REPL,
978 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
979 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
980 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
981 			IF_CMD, ip_sioctl_get_flags, NULL },
982 
983 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
984 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
985 
986 	/* copyin size cannot be coded for SIOCGIFCONF */
987 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
988 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
989 
990 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
991 			IF_CMD, ip_sioctl_mtu, NULL },
992 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
993 			IF_CMD, ip_sioctl_get_mtu, NULL },
994 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
995 			IPI_GET_CMD | IPI_REPL,
996 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
997 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
998 			IF_CMD, ip_sioctl_brdaddr, NULL },
999 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1000 			IPI_GET_CMD | IPI_REPL,
1001 			IF_CMD, ip_sioctl_get_netmask, NULL },
1002 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1003 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1004 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1005 			IPI_GET_CMD | IPI_REPL,
1006 			IF_CMD, ip_sioctl_get_metric, NULL },
1007 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1008 			IF_CMD, ip_sioctl_metric, NULL },
1009 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1010 
1011 	/* See 166-168 below for extended SIOC*XARP ioctls */
1012 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1013 			ARP_CMD, ip_sioctl_arp, NULL },
1014 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1015 			ARP_CMD, ip_sioctl_arp, NULL },
1016 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1017 			ARP_CMD, ip_sioctl_arp, NULL },
1018 
1019 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 
1041 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1042 			MISC_CMD, if_unitsel, if_unitsel_restart },
1043 
1044 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 
1063 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1064 			IPI_PRIV | IPI_WR | IPI_MODOK,
1065 			IF_CMD, ip_sioctl_sifname, NULL },
1066 
1067 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 
1081 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1082 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1083 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1084 			IF_CMD, ip_sioctl_get_muxid, NULL },
1085 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1086 			IPI_PRIV | IPI_WR | IPI_REPL,
1087 			IF_CMD, ip_sioctl_muxid, NULL },
1088 
1089 	/* Both if and lif variants share same func */
1090 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1091 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1092 	/* Both if and lif variants share same func */
1093 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1094 			IPI_PRIV | IPI_WR | IPI_REPL,
1095 			IF_CMD, ip_sioctl_slifindex, NULL },
1096 
1097 	/* copyin size cannot be coded for SIOCGIFCONF */
1098 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1099 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1100 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 
1118 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1119 			IPI_PRIV | IPI_WR | IPI_REPL,
1120 			LIF_CMD, ip_sioctl_removeif,
1121 			ip_sioctl_removeif_restart },
1122 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1123 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1124 			LIF_CMD, ip_sioctl_addif, NULL },
1125 #define	SIOCLIFADDR_NDX 112
1126 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1127 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1128 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1129 			IPI_GET_CMD | IPI_REPL,
1130 			LIF_CMD, ip_sioctl_get_addr, NULL },
1131 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1132 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1133 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1134 			IPI_GET_CMD | IPI_REPL,
1135 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1136 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1137 			IPI_PRIV | IPI_WR | IPI_REPL,
1138 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1139 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1140 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1141 			LIF_CMD, ip_sioctl_get_flags, NULL },
1142 
1143 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1144 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 
1146 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1147 			ip_sioctl_get_lifconf, NULL },
1148 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1149 			LIF_CMD, ip_sioctl_mtu, NULL },
1150 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1151 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1152 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1153 			IPI_GET_CMD | IPI_REPL,
1154 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1155 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1156 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1157 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1158 			IPI_GET_CMD | IPI_REPL,
1159 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1160 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1161 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1162 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1163 			IPI_GET_CMD | IPI_REPL,
1164 			LIF_CMD, ip_sioctl_get_metric, NULL },
1165 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1166 			LIF_CMD, ip_sioctl_metric, NULL },
1167 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1168 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1169 			LIF_CMD, ip_sioctl_slifname,
1170 			ip_sioctl_slifname_restart },
1171 
1172 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1173 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1174 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1175 			IPI_GET_CMD | IPI_REPL,
1176 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1177 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1178 			IPI_PRIV | IPI_WR | IPI_REPL,
1179 			LIF_CMD, ip_sioctl_muxid, NULL },
1180 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1181 			IPI_GET_CMD | IPI_REPL,
1182 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1183 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1184 			IPI_PRIV | IPI_WR | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_slifindex, 0 },
1186 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1187 			LIF_CMD, ip_sioctl_token, NULL },
1188 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1189 			IPI_GET_CMD | IPI_REPL,
1190 			LIF_CMD, ip_sioctl_get_token, NULL },
1191 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1192 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1193 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1194 			IPI_GET_CMD | IPI_REPL,
1195 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1196 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1197 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1198 
1199 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1200 			IPI_GET_CMD | IPI_REPL,
1201 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1202 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1203 			LIF_CMD, ip_siocdelndp_v6, NULL },
1204 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1205 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1206 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1207 			LIF_CMD, ip_siocsetndp_v6, NULL },
1208 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1209 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1210 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1211 			MISC_CMD, ip_sioctl_tonlink, NULL },
1212 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1213 			MISC_CMD, ip_sioctl_tmysite, NULL },
1214 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1215 			TUN_CMD, ip_sioctl_tunparam, NULL },
1216 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1217 			IPI_PRIV | IPI_WR,
1218 			TUN_CMD, ip_sioctl_tunparam, NULL },
1219 
1220 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1221 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1222 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1223 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1224 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1225 
1226 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1227 			IPI_PRIV | IPI_WR | IPI_REPL,
1228 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1229 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1230 			IPI_PRIV | IPI_WR | IPI_REPL,
1231 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1232 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1233 			IPI_PRIV | IPI_WR,
1234 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1235 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1236 			IPI_GET_CMD | IPI_REPL,
1237 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1238 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1239 			IPI_GET_CMD | IPI_REPL,
1240 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1241 
1242 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1243 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1244 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1245 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1246 
1247 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1248 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1249 
1250 	/* These are handled in ip_sioctl_copyin_setup itself */
1251 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1252 			MISC_CMD, NULL, NULL },
1253 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1254 			MISC_CMD, NULL, NULL },
1255 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1256 
1257 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1258 			ip_sioctl_get_lifconf, NULL },
1259 
1260 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1261 			XARP_CMD, ip_sioctl_arp, NULL },
1262 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1263 			XARP_CMD, ip_sioctl_arp, NULL },
1264 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1265 			XARP_CMD, ip_sioctl_arp, NULL },
1266 
1267 	/* SIOCPOPSOCKFS is not handled by IP */
1268 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1269 
1270 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1271 			IPI_GET_CMD | IPI_REPL,
1272 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1273 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1274 			IPI_PRIV | IPI_WR | IPI_REPL,
1275 			LIF_CMD, ip_sioctl_slifzone,
1276 			ip_sioctl_slifzone_restart },
1277 	/* 172-174 are SCTP ioctls and not handled by IP */
1278 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1279 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1280 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1281 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1282 			IPI_GET_CMD, LIF_CMD,
1283 			ip_sioctl_get_lifusesrc, 0 },
1284 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1285 			IPI_PRIV | IPI_WR,
1286 			LIF_CMD, ip_sioctl_slifusesrc,
1287 			NULL },
1288 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1289 			ip_sioctl_get_lifsrcof, NULL },
1290 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1291 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1292 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1293 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1294 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1295 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1296 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1297 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1298 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1299 			ip_sioctl_set_ipmpfailback, NULL },
1300 	/* SIOCSENABLESDP is handled by SDP */
1301 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1302 };
1303 
1304 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1305 
1306 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1307 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1308 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1309 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1310 		TUN_CMD, ip_sioctl_tunparam, NULL },
1311 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1318 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1319 		MISC_CMD, mrt_ioctl},
1320 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1321 		MISC_CMD, mrt_ioctl},
1322 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1323 		MISC_CMD, mrt_ioctl}
1324 };
1325 
1326 int ip_misc_ioctl_count =
1327     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1328 
1329 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1330 					/* Settable in /etc/system */
1331 /* Defined in ip_ire.c */
1332 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1333 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1334 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1335 
1336 static nv_t	ire_nv_arr[] = {
1337 	{ IRE_BROADCAST, "BROADCAST" },
1338 	{ IRE_LOCAL, "LOCAL" },
1339 	{ IRE_LOOPBACK, "LOOPBACK" },
1340 	{ IRE_CACHE, "CACHE" },
1341 	{ IRE_DEFAULT, "DEFAULT" },
1342 	{ IRE_PREFIX, "PREFIX" },
1343 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1344 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1345 	{ IRE_HOST, "HOST" },
1346 	{ 0 }
1347 };
1348 
1349 nv_t	*ire_nv_tbl = ire_nv_arr;
1350 
1351 /* Defined in ip_netinfo.c */
1352 extern ddi_taskq_t	*eventq_queue_nic;
1353 
1354 /* Simple ICMP IP Header Template */
1355 static ipha_t icmp_ipha = {
1356 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1357 };
1358 
1359 struct module_info ip_mod_info = {
1360 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1361 };
1362 
1363 /*
1364  * Duplicate static symbols within a module confuses mdb; so we avoid the
1365  * problem by making the symbols here distinct from those in udp.c.
1366  */
1367 
1368 /*
1369  * Entry points for IP as a device and as a module.
1370  * FIXME: down the road we might want a separate module and driver qinit.
1371  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1372  */
1373 static struct qinit iprinitv4 = {
1374 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1375 	&ip_mod_info
1376 };
1377 
1378 struct qinit iprinitv6 = {
1379 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1380 	&ip_mod_info
1381 };
1382 
1383 static struct qinit ipwinitv4 = {
1384 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1385 	&ip_mod_info
1386 };
1387 
1388 struct qinit ipwinitv6 = {
1389 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1390 	&ip_mod_info
1391 };
1392 
1393 static struct qinit iplrinit = {
1394 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1395 	&ip_mod_info
1396 };
1397 
1398 static struct qinit iplwinit = {
1399 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1400 	&ip_mod_info
1401 };
1402 
1403 /* For AF_INET aka /dev/ip */
1404 struct streamtab ipinfov4 = {
1405 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1406 };
1407 
1408 /* For AF_INET6 aka /dev/ip6 */
1409 struct streamtab ipinfov6 = {
1410 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1411 };
1412 
1413 #ifdef	DEBUG
1414 static boolean_t skip_sctp_cksum = B_FALSE;
1415 #endif
1416 
1417 /*
1418  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1419  * ip_rput_v6(), ip_output(), etc.  If the message
1420  * block already has a M_CTL at the front of it, then simply set the zoneid
1421  * appropriately.
1422  */
1423 mblk_t *
1424 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1425 {
1426 	mblk_t		*first_mp;
1427 	ipsec_out_t	*io;
1428 
1429 	ASSERT(zoneid != ALL_ZONES);
1430 	if (mp->b_datap->db_type == M_CTL) {
1431 		io = (ipsec_out_t *)mp->b_rptr;
1432 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1433 		io->ipsec_out_zoneid = zoneid;
1434 		return (mp);
1435 	}
1436 
1437 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1438 	if (first_mp == NULL)
1439 		return (NULL);
1440 	io = (ipsec_out_t *)first_mp->b_rptr;
1441 	/* This is not a secure packet */
1442 	io->ipsec_out_secure = B_FALSE;
1443 	io->ipsec_out_zoneid = zoneid;
1444 	first_mp->b_cont = mp;
1445 	return (first_mp);
1446 }
1447 
1448 /*
1449  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1450  */
1451 mblk_t *
1452 ip_copymsg(mblk_t *mp)
1453 {
1454 	mblk_t *nmp;
1455 	ipsec_info_t *in;
1456 
1457 	if (mp->b_datap->db_type != M_CTL)
1458 		return (copymsg(mp));
1459 
1460 	in = (ipsec_info_t *)mp->b_rptr;
1461 
1462 	/*
1463 	 * Note that M_CTL is also used for delivering ICMP error messages
1464 	 * upstream to transport layers.
1465 	 */
1466 	if (in->ipsec_info_type != IPSEC_OUT &&
1467 	    in->ipsec_info_type != IPSEC_IN)
1468 		return (copymsg(mp));
1469 
1470 	nmp = copymsg(mp->b_cont);
1471 
1472 	if (in->ipsec_info_type == IPSEC_OUT) {
1473 		return (ipsec_out_tag(mp, nmp,
1474 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1475 	} else {
1476 		return (ipsec_in_tag(mp, nmp,
1477 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1478 	}
1479 }
1480 
1481 /* Generate an ICMP fragmentation needed message. */
1482 static void
1483 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1484     ip_stack_t *ipst)
1485 {
1486 	icmph_t	icmph;
1487 	mblk_t *first_mp;
1488 	boolean_t mctl_present;
1489 
1490 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1491 
1492 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1493 		if (mctl_present)
1494 			freeb(first_mp);
1495 		return;
1496 	}
1497 
1498 	bzero(&icmph, sizeof (icmph_t));
1499 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1500 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1501 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1502 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1503 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1504 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1505 	    ipst);
1506 }
1507 
1508 /*
1509  * icmp_inbound deals with ICMP messages in the following ways.
1510  *
1511  * 1) It needs to send a reply back and possibly delivering it
1512  *    to the "interested" upper clients.
1513  * 2) It needs to send it to the upper clients only.
1514  * 3) It needs to change some values in IP only.
1515  * 4) It needs to change some values in IP and upper layers e.g TCP.
1516  *
1517  * We need to accomodate icmp messages coming in clear until we get
1518  * everything secure from the wire. If icmp_accept_clear_messages
1519  * is zero we check with the global policy and act accordingly. If
1520  * it is non-zero, we accept the message without any checks. But
1521  * *this does not mean* that this will be delivered to the upper
1522  * clients. By accepting we might send replies back, change our MTU
1523  * value etc. but delivery to the ULP/clients depends on their policy
1524  * dispositions.
1525  *
1526  * We handle the above 4 cases in the context of IPsec in the
1527  * following way :
1528  *
1529  * 1) Send the reply back in the same way as the request came in.
1530  *    If it came in encrypted, it goes out encrypted. If it came in
1531  *    clear, it goes out in clear. Thus, this will prevent chosen
1532  *    plain text attack.
1533  * 2) The client may or may not expect things to come in secure.
1534  *    If it comes in secure, the policy constraints are checked
1535  *    before delivering it to the upper layers. If it comes in
1536  *    clear, ipsec_inbound_accept_clear will decide whether to
1537  *    accept this in clear or not. In both the cases, if the returned
1538  *    message (IP header + 8 bytes) that caused the icmp message has
1539  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1540  *    sending up. If there are only 8 bytes of returned message, then
1541  *    upper client will not be notified.
1542  * 3) Check with global policy to see whether it matches the constaints.
1543  *    But this will be done only if icmp_accept_messages_in_clear is
1544  *    zero.
1545  * 4) If we need to change both in IP and ULP, then the decision taken
1546  *    while affecting the values in IP and while delivering up to TCP
1547  *    should be the same.
1548  *
1549  * 	There are two cases.
1550  *
1551  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1552  *	   failed), we will not deliver it to the ULP, even though they
1553  *	   are *willing* to accept in *clear*. This is fine as our global
1554  *	   disposition to icmp messages asks us reject the datagram.
1555  *
1556  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1557  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1558  *	   to deliver it to ULP (policy failed), it can lead to
1559  *	   consistency problems. The cases known at this time are
1560  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1561  *	   values :
1562  *
1563  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1564  *	     and Upper layer rejects. Then the communication will
1565  *	     come to a stop. This is solved by making similar decisions
1566  *	     at both levels. Currently, when we are unable to deliver
1567  *	     to the Upper Layer (due to policy failures) while IP has
1568  *	     adjusted ire_max_frag, the next outbound datagram would
1569  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1570  *	     will be with the right level of protection. Thus the right
1571  *	     value will be communicated even if we are not able to
1572  *	     communicate when we get from the wire initially. But this
1573  *	     assumes there would be at least one outbound datagram after
1574  *	     IP has adjusted its ire_max_frag value. To make things
1575  *	     simpler, we accept in clear after the validation of
1576  *	     AH/ESP headers.
1577  *
1578  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1579  *	     upper layer depending on the level of protection the upper
1580  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1581  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1582  *	     should be accepted in clear when the Upper layer expects secure.
1583  *	     Thus the communication may get aborted by some bad ICMP
1584  *	     packets.
1585  *
1586  * IPQoS Notes:
1587  * The only instance when a packet is sent for processing is when there
1588  * isn't an ICMP client and if we are interested in it.
1589  * If there is a client, IPPF processing will take place in the
1590  * ip_fanout_proto routine.
1591  *
1592  * Zones notes:
1593  * The packet is only processed in the context of the specified zone: typically
1594  * only this zone will reply to an echo request, and only interested clients in
1595  * this zone will receive a copy of the packet. This means that the caller must
1596  * call icmp_inbound() for each relevant zone.
1597  */
1598 static void
1599 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1600     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1601     ill_t *recv_ill, zoneid_t zoneid)
1602 {
1603 	icmph_t	*icmph;
1604 	ipha_t	*ipha;
1605 	int	iph_hdr_length;
1606 	int	hdr_length;
1607 	boolean_t	interested;
1608 	uint32_t	ts;
1609 	uchar_t	*wptr;
1610 	ipif_t	*ipif;
1611 	mblk_t *first_mp;
1612 	ipsec_in_t *ii;
1613 	ire_t *src_ire;
1614 	boolean_t onlink;
1615 	timestruc_t now;
1616 	uint32_t ill_index;
1617 	ip_stack_t *ipst;
1618 
1619 	ASSERT(ill != NULL);
1620 	ipst = ill->ill_ipst;
1621 
1622 	first_mp = mp;
1623 	if (mctl_present) {
1624 		mp = first_mp->b_cont;
1625 		ASSERT(mp != NULL);
1626 	}
1627 
1628 	ipha = (ipha_t *)mp->b_rptr;
1629 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1630 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1631 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1632 		if (first_mp == NULL)
1633 			return;
1634 	}
1635 
1636 	/*
1637 	 * On a labeled system, we have to check whether the zone itself is
1638 	 * permitted to receive raw traffic.
1639 	 */
1640 	if (is_system_labeled()) {
1641 		if (zoneid == ALL_ZONES)
1642 			zoneid = tsol_packet_to_zoneid(mp);
1643 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1644 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1645 			    zoneid));
1646 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1647 			freemsg(first_mp);
1648 			return;
1649 		}
1650 	}
1651 
1652 	/*
1653 	 * We have accepted the ICMP message. It means that we will
1654 	 * respond to the packet if needed. It may not be delivered
1655 	 * to the upper client depending on the policy constraints
1656 	 * and the disposition in ipsec_inbound_accept_clear.
1657 	 */
1658 
1659 	ASSERT(ill != NULL);
1660 
1661 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1662 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1663 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1664 		/* Last chance to get real. */
1665 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1666 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1667 			freemsg(first_mp);
1668 			return;
1669 		}
1670 		/* Refresh iph following the pullup. */
1671 		ipha = (ipha_t *)mp->b_rptr;
1672 	}
1673 	/* ICMP header checksum, including checksum field, should be zero. */
1674 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1675 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1676 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1677 		freemsg(first_mp);
1678 		return;
1679 	}
1680 	/* The IP header will always be a multiple of four bytes */
1681 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1682 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1683 	    icmph->icmph_code));
1684 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1685 	/* We will set "interested" to "true" if we want a copy */
1686 	interested = B_FALSE;
1687 	switch (icmph->icmph_type) {
1688 	case ICMP_ECHO_REPLY:
1689 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1690 		break;
1691 	case ICMP_DEST_UNREACHABLE:
1692 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1693 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1694 		interested = B_TRUE;	/* Pass up to transport */
1695 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1696 		break;
1697 	case ICMP_SOURCE_QUENCH:
1698 		interested = B_TRUE;	/* Pass up to transport */
1699 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1700 		break;
1701 	case ICMP_REDIRECT:
1702 		if (!ipst->ips_ip_ignore_redirect)
1703 			interested = B_TRUE;
1704 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1705 		break;
1706 	case ICMP_ECHO_REQUEST:
1707 		/*
1708 		 * Whether to respond to echo requests that come in as IP
1709 		 * broadcasts or as IP multicast is subject to debate
1710 		 * (what isn't?).  We aim to please, you pick it.
1711 		 * Default is do it.
1712 		 */
1713 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1714 			/* unicast: always respond */
1715 			interested = B_TRUE;
1716 		} else if (CLASSD(ipha->ipha_dst)) {
1717 			/* multicast: respond based on tunable */
1718 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1719 		} else if (broadcast) {
1720 			/* broadcast: respond based on tunable */
1721 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1722 		}
1723 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1724 		break;
1725 	case ICMP_ROUTER_ADVERTISEMENT:
1726 	case ICMP_ROUTER_SOLICITATION:
1727 		break;
1728 	case ICMP_TIME_EXCEEDED:
1729 		interested = B_TRUE;	/* Pass up to transport */
1730 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1731 		break;
1732 	case ICMP_PARAM_PROBLEM:
1733 		interested = B_TRUE;	/* Pass up to transport */
1734 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1735 		break;
1736 	case ICMP_TIME_STAMP_REQUEST:
1737 		/* Response to Time Stamp Requests is local policy. */
1738 		if (ipst->ips_ip_g_resp_to_timestamp &&
1739 		    /* So is whether to respond if it was an IP broadcast. */
1740 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1741 			int tstamp_len = 3 * sizeof (uint32_t);
1742 
1743 			if (wptr +  tstamp_len > mp->b_wptr) {
1744 				if (!pullupmsg(mp, wptr + tstamp_len -
1745 				    mp->b_rptr)) {
1746 					BUMP_MIB(ill->ill_ip_mib,
1747 					    ipIfStatsInDiscards);
1748 					freemsg(first_mp);
1749 					return;
1750 				}
1751 				/* Refresh ipha following the pullup. */
1752 				ipha = (ipha_t *)mp->b_rptr;
1753 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1754 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1755 			}
1756 			interested = B_TRUE;
1757 		}
1758 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1759 		break;
1760 	case ICMP_TIME_STAMP_REPLY:
1761 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1762 		break;
1763 	case ICMP_INFO_REQUEST:
1764 		/* Per RFC 1122 3.2.2.7, ignore this. */
1765 	case ICMP_INFO_REPLY:
1766 		break;
1767 	case ICMP_ADDRESS_MASK_REQUEST:
1768 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1769 		    !broadcast) &&
1770 		    /* TODO m_pullup of complete header? */
1771 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1772 			interested = B_TRUE;
1773 		}
1774 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1775 		break;
1776 	case ICMP_ADDRESS_MASK_REPLY:
1777 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1778 		break;
1779 	default:
1780 		interested = B_TRUE;	/* Pass up to transport */
1781 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1782 		break;
1783 	}
1784 	/* See if there is an ICMP client. */
1785 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1786 		/* If there is an ICMP client and we want one too, copy it. */
1787 		mblk_t *first_mp1;
1788 
1789 		if (!interested) {
1790 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1791 			    ip_policy, recv_ill, zoneid);
1792 			return;
1793 		}
1794 		first_mp1 = ip_copymsg(first_mp);
1795 		if (first_mp1 != NULL) {
1796 			ip_fanout_proto(q, first_mp1, ill, ipha,
1797 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1798 		}
1799 	} else if (!interested) {
1800 		freemsg(first_mp);
1801 		return;
1802 	} else {
1803 		/*
1804 		 * Initiate policy processing for this packet if ip_policy
1805 		 * is true.
1806 		 */
1807 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1808 			ill_index = ill->ill_phyint->phyint_ifindex;
1809 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1810 			if (mp == NULL) {
1811 				if (mctl_present) {
1812 					freeb(first_mp);
1813 				}
1814 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1815 				return;
1816 			}
1817 		}
1818 	}
1819 	/* We want to do something with it. */
1820 	/* Check db_ref to make sure we can modify the packet. */
1821 	if (mp->b_datap->db_ref > 1) {
1822 		mblk_t	*first_mp1;
1823 
1824 		first_mp1 = ip_copymsg(first_mp);
1825 		freemsg(first_mp);
1826 		if (!first_mp1) {
1827 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1828 			return;
1829 		}
1830 		first_mp = first_mp1;
1831 		if (mctl_present) {
1832 			mp = first_mp->b_cont;
1833 			ASSERT(mp != NULL);
1834 		} else {
1835 			mp = first_mp;
1836 		}
1837 		ipha = (ipha_t *)mp->b_rptr;
1838 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1839 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1840 	}
1841 	switch (icmph->icmph_type) {
1842 	case ICMP_ADDRESS_MASK_REQUEST:
1843 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1844 		if (ipif == NULL) {
1845 			freemsg(first_mp);
1846 			return;
1847 		}
1848 		/*
1849 		 * outging interface must be IPv4
1850 		 */
1851 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1852 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1853 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1854 		ipif_refrele(ipif);
1855 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1856 		break;
1857 	case ICMP_ECHO_REQUEST:
1858 		icmph->icmph_type = ICMP_ECHO_REPLY;
1859 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1860 		break;
1861 	case ICMP_TIME_STAMP_REQUEST: {
1862 		uint32_t *tsp;
1863 
1864 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1865 		tsp = (uint32_t *)wptr;
1866 		tsp++;		/* Skip past 'originate time' */
1867 		/* Compute # of milliseconds since midnight */
1868 		gethrestime(&now);
1869 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1870 		    now.tv_nsec / (NANOSEC / MILLISEC);
1871 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1872 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1873 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1874 		break;
1875 	}
1876 	default:
1877 		ipha = (ipha_t *)&icmph[1];
1878 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1879 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1880 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1881 				freemsg(first_mp);
1882 				return;
1883 			}
1884 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1885 			ipha = (ipha_t *)&icmph[1];
1886 		}
1887 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1888 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1889 			freemsg(first_mp);
1890 			return;
1891 		}
1892 		hdr_length = IPH_HDR_LENGTH(ipha);
1893 		if (hdr_length < sizeof (ipha_t)) {
1894 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1895 			freemsg(first_mp);
1896 			return;
1897 		}
1898 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1899 			if (!pullupmsg(mp,
1900 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1901 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1902 				freemsg(first_mp);
1903 				return;
1904 			}
1905 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1906 			ipha = (ipha_t *)&icmph[1];
1907 		}
1908 		switch (icmph->icmph_type) {
1909 		case ICMP_REDIRECT:
1910 			/*
1911 			 * As there is no upper client to deliver, we don't
1912 			 * need the first_mp any more.
1913 			 */
1914 			if (mctl_present) {
1915 				freeb(first_mp);
1916 			}
1917 			icmp_redirect(ill, mp);
1918 			return;
1919 		case ICMP_DEST_UNREACHABLE:
1920 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1921 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1922 				    zoneid, mp, iph_hdr_length, ipst)) {
1923 					freemsg(first_mp);
1924 					return;
1925 				}
1926 				/*
1927 				 * icmp_inbound_too_big() may alter mp.
1928 				 * Resynch ipha and icmph accordingly.
1929 				 */
1930 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1931 				ipha = (ipha_t *)&icmph[1];
1932 			}
1933 			/* FALLTHRU */
1934 		default :
1935 			/*
1936 			 * IPQoS notes: Since we have already done IPQoS
1937 			 * processing we don't want to do it again in
1938 			 * the fanout routines called by
1939 			 * icmp_inbound_error_fanout, hence the last
1940 			 * argument, ip_policy, is B_FALSE.
1941 			 */
1942 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1943 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1944 			    B_FALSE, recv_ill, zoneid);
1945 		}
1946 		return;
1947 	}
1948 	/* Send out an ICMP packet */
1949 	icmph->icmph_checksum = 0;
1950 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1951 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1952 		ipif_t	*ipif_chosen;
1953 		/*
1954 		 * Make it look like it was directed to us, so we don't look
1955 		 * like a fool with a broadcast or multicast source address.
1956 		 */
1957 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1958 		/*
1959 		 * Make sure that we haven't grabbed an interface that's DOWN.
1960 		 */
1961 		if (ipif != NULL) {
1962 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1963 			    ipha->ipha_src, zoneid);
1964 			if (ipif_chosen != NULL) {
1965 				ipif_refrele(ipif);
1966 				ipif = ipif_chosen;
1967 			}
1968 		}
1969 		if (ipif == NULL) {
1970 			ip0dbg(("icmp_inbound: "
1971 			    "No source for broadcast/multicast:\n"
1972 			    "\tsrc 0x%x dst 0x%x ill %p "
1973 			    "ipif_lcl_addr 0x%x\n",
1974 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1975 			    (void *)ill,
1976 			    ill->ill_ipif->ipif_lcl_addr));
1977 			freemsg(first_mp);
1978 			return;
1979 		}
1980 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1981 		ipha->ipha_dst = ipif->ipif_src_addr;
1982 		ipif_refrele(ipif);
1983 	}
1984 	/* Reset time to live. */
1985 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1986 	{
1987 		/* Swap source and destination addresses */
1988 		ipaddr_t tmp;
1989 
1990 		tmp = ipha->ipha_src;
1991 		ipha->ipha_src = ipha->ipha_dst;
1992 		ipha->ipha_dst = tmp;
1993 	}
1994 	ipha->ipha_ident = 0;
1995 	if (!IS_SIMPLE_IPH(ipha))
1996 		icmp_options_update(ipha);
1997 
1998 	/*
1999 	 * ICMP echo replies should go out on the same interface
2000 	 * the request came on as probes used by in.mpathd for detecting
2001 	 * NIC failures are ECHO packets. We turn-off load spreading
2002 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2003 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2004 	 * function. This is in turn handled by ip_wput and ip_newroute
2005 	 * to make sure that the packet goes out on the interface it came
2006 	 * in on. If we don't turnoff load spreading, the packets might get
2007 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2008 	 * to go out and in.mpathd would wrongly detect a failure or
2009 	 * mis-detect a NIC failure for link failure. As load spreading
2010 	 * can happen only if ill_group is not NULL, we do only for
2011 	 * that case and this does not affect the normal case.
2012 	 *
2013 	 * We turn off load spreading only on echo packets that came from
2014 	 * on-link hosts. If the interface route has been deleted, this will
2015 	 * not be enforced as we can't do much. For off-link hosts, as the
2016 	 * default routes in IPv4 does not typically have an ire_ipif
2017 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2018 	 * Moreover, expecting a default route through this interface may
2019 	 * not be correct. We use ipha_dst because of the swap above.
2020 	 */
2021 	onlink = B_FALSE;
2022 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2023 		/*
2024 		 * First, we need to make sure that it is not one of our
2025 		 * local addresses. If we set onlink when it is one of
2026 		 * our local addresses, we will end up creating IRE_CACHES
2027 		 * for one of our local addresses. Then, we will never
2028 		 * accept packets for them afterwards.
2029 		 */
2030 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2031 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2032 		if (src_ire == NULL) {
2033 			ipif = ipif_get_next_ipif(NULL, ill);
2034 			if (ipif == NULL) {
2035 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2036 				freemsg(mp);
2037 				return;
2038 			}
2039 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2040 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2041 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2042 			ipif_refrele(ipif);
2043 			if (src_ire != NULL) {
2044 				onlink = B_TRUE;
2045 				ire_refrele(src_ire);
2046 			}
2047 		} else {
2048 			ire_refrele(src_ire);
2049 		}
2050 	}
2051 	if (!mctl_present) {
2052 		/*
2053 		 * This packet should go out the same way as it
2054 		 * came in i.e in clear. To make sure that global
2055 		 * policy will not be applied to this in ip_wput_ire,
2056 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2057 		 */
2058 		ASSERT(first_mp == mp);
2059 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2060 		if (first_mp == NULL) {
2061 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2062 			freemsg(mp);
2063 			return;
2064 		}
2065 		ii = (ipsec_in_t *)first_mp->b_rptr;
2066 
2067 		/* This is not a secure packet */
2068 		ii->ipsec_in_secure = B_FALSE;
2069 		if (onlink) {
2070 			ii->ipsec_in_attach_if = B_TRUE;
2071 			ii->ipsec_in_ill_index =
2072 			    ill->ill_phyint->phyint_ifindex;
2073 			ii->ipsec_in_rill_index =
2074 			    recv_ill->ill_phyint->phyint_ifindex;
2075 		}
2076 		first_mp->b_cont = mp;
2077 	} else if (onlink) {
2078 		ii = (ipsec_in_t *)first_mp->b_rptr;
2079 		ii->ipsec_in_attach_if = B_TRUE;
2080 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2081 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2082 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2083 	} else {
2084 		ii = (ipsec_in_t *)first_mp->b_rptr;
2085 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2086 	}
2087 	ii->ipsec_in_zoneid = zoneid;
2088 	ASSERT(zoneid != ALL_ZONES);
2089 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2090 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2091 		return;
2092 	}
2093 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2094 	put(WR(q), first_mp);
2095 }
2096 
2097 static ipaddr_t
2098 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2099 {
2100 	conn_t *connp;
2101 	connf_t *connfp;
2102 	ipaddr_t nexthop_addr = INADDR_ANY;
2103 	int hdr_length = IPH_HDR_LENGTH(ipha);
2104 	uint16_t *up;
2105 	uint32_t ports;
2106 	ip_stack_t *ipst = ill->ill_ipst;
2107 
2108 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2109 	switch (ipha->ipha_protocol) {
2110 		case IPPROTO_TCP:
2111 		{
2112 			tcph_t *tcph;
2113 
2114 			/* do a reverse lookup */
2115 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2116 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2117 			    TCPS_LISTEN, ipst);
2118 			break;
2119 		}
2120 		case IPPROTO_UDP:
2121 		{
2122 			uint32_t dstport, srcport;
2123 
2124 			((uint16_t *)&ports)[0] = up[1];
2125 			((uint16_t *)&ports)[1] = up[0];
2126 
2127 			/* Extract ports in net byte order */
2128 			dstport = htons(ntohl(ports) & 0xFFFF);
2129 			srcport = htons(ntohl(ports) >> 16);
2130 
2131 			connfp = &ipst->ips_ipcl_udp_fanout[
2132 			    IPCL_UDP_HASH(dstport, ipst)];
2133 			mutex_enter(&connfp->connf_lock);
2134 			connp = connfp->connf_head;
2135 
2136 			/* do a reverse lookup */
2137 			while ((connp != NULL) &&
2138 			    (!IPCL_UDP_MATCH(connp, dstport,
2139 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2140 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2141 				connp = connp->conn_next;
2142 			}
2143 			if (connp != NULL)
2144 				CONN_INC_REF(connp);
2145 			mutex_exit(&connfp->connf_lock);
2146 			break;
2147 		}
2148 		case IPPROTO_SCTP:
2149 		{
2150 			in6_addr_t map_src, map_dst;
2151 
2152 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2153 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2154 			((uint16_t *)&ports)[0] = up[1];
2155 			((uint16_t *)&ports)[1] = up[0];
2156 
2157 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2158 			    zoneid, ipst->ips_netstack->netstack_sctp);
2159 			if (connp == NULL) {
2160 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2161 				    zoneid, ports, ipha, ipst);
2162 			} else {
2163 				CONN_INC_REF(connp);
2164 				SCTP_REFRELE(CONN2SCTP(connp));
2165 			}
2166 			break;
2167 		}
2168 		default:
2169 		{
2170 			ipha_t ripha;
2171 
2172 			ripha.ipha_src = ipha->ipha_dst;
2173 			ripha.ipha_dst = ipha->ipha_src;
2174 			ripha.ipha_protocol = ipha->ipha_protocol;
2175 
2176 			connfp = &ipst->ips_ipcl_proto_fanout[
2177 			    ipha->ipha_protocol];
2178 			mutex_enter(&connfp->connf_lock);
2179 			connp = connfp->connf_head;
2180 			for (connp = connfp->connf_head; connp != NULL;
2181 			    connp = connp->conn_next) {
2182 				if (IPCL_PROTO_MATCH(connp,
2183 				    ipha->ipha_protocol, &ripha, ill,
2184 				    0, zoneid)) {
2185 					CONN_INC_REF(connp);
2186 					break;
2187 				}
2188 			}
2189 			mutex_exit(&connfp->connf_lock);
2190 		}
2191 	}
2192 	if (connp != NULL) {
2193 		if (connp->conn_nexthop_set)
2194 			nexthop_addr = connp->conn_nexthop_v4;
2195 		CONN_DEC_REF(connp);
2196 	}
2197 	return (nexthop_addr);
2198 }
2199 
2200 /* Table from RFC 1191 */
2201 static int icmp_frag_size_table[] =
2202 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2203 
2204 /*
2205  * Process received ICMP Packet too big.
2206  * After updating any IRE it does the fanout to any matching transport streams.
2207  * Assumes the message has been pulled up till the IP header that caused
2208  * the error.
2209  *
2210  * Returns B_FALSE on failure and B_TRUE on success.
2211  */
2212 static boolean_t
2213 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2214     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2215     ip_stack_t *ipst)
2216 {
2217 	ire_t	*ire, *first_ire;
2218 	int	mtu;
2219 	int	hdr_length;
2220 	ipaddr_t nexthop_addr;
2221 
2222 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2223 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2224 	ASSERT(ill != NULL);
2225 
2226 	hdr_length = IPH_HDR_LENGTH(ipha);
2227 
2228 	/* Drop if the original packet contained a source route */
2229 	if (ip_source_route_included(ipha)) {
2230 		return (B_FALSE);
2231 	}
2232 	/*
2233 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2234 	 * header.
2235 	 */
2236 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2237 	    mp->b_wptr) {
2238 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2239 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2240 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2241 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2242 			return (B_FALSE);
2243 		}
2244 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2245 		ipha = (ipha_t *)&icmph[1];
2246 	}
2247 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2248 	if (nexthop_addr != INADDR_ANY) {
2249 		/* nexthop set */
2250 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2251 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2252 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2253 	} else {
2254 		/* nexthop not set */
2255 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2256 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2257 	}
2258 
2259 	if (!first_ire) {
2260 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2261 		    ntohl(ipha->ipha_dst)));
2262 		return (B_FALSE);
2263 	}
2264 	/* Check for MTU discovery advice as described in RFC 1191 */
2265 	mtu = ntohs(icmph->icmph_du_mtu);
2266 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2267 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2268 	    ire = ire->ire_next) {
2269 		/*
2270 		 * Look for the connection to which this ICMP message is
2271 		 * directed. If it has the IP_NEXTHOP option set, then the
2272 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2273 		 * option. Else the search is limited to regular IREs.
2274 		 */
2275 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2276 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2277 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2278 		    (nexthop_addr != INADDR_ANY)))
2279 			continue;
2280 
2281 		mutex_enter(&ire->ire_lock);
2282 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2283 			/* Reduce the IRE max frag value as advised. */
2284 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2285 			    mtu, ire->ire_max_frag));
2286 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2287 		} else {
2288 			uint32_t length;
2289 			int	i;
2290 
2291 			/*
2292 			 * Use the table from RFC 1191 to figure out
2293 			 * the next "plateau" based on the length in
2294 			 * the original IP packet.
2295 			 */
2296 			length = ntohs(ipha->ipha_length);
2297 			if (ire->ire_max_frag <= length &&
2298 			    ire->ire_max_frag >= length - hdr_length) {
2299 				/*
2300 				 * Handle broken BSD 4.2 systems that
2301 				 * return the wrong iph_length in ICMP
2302 				 * errors.
2303 				 */
2304 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2305 				    length, ire->ire_max_frag));
2306 				length -= hdr_length;
2307 			}
2308 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2309 				if (length > icmp_frag_size_table[i])
2310 					break;
2311 			}
2312 			if (i == A_CNT(icmp_frag_size_table)) {
2313 				/* Smaller than 68! */
2314 				ip1dbg(("Too big for packet size %d\n",
2315 				    length));
2316 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2317 				ire->ire_frag_flag = 0;
2318 			} else {
2319 				mtu = icmp_frag_size_table[i];
2320 				ip1dbg(("Calculated mtu %d, packet size %d, "
2321 				    "before %d", mtu, length,
2322 				    ire->ire_max_frag));
2323 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2324 				ip1dbg((", after %d\n", ire->ire_max_frag));
2325 			}
2326 			/* Record the new max frag size for the ULP. */
2327 			icmph->icmph_du_zero = 0;
2328 			icmph->icmph_du_mtu =
2329 			    htons((uint16_t)ire->ire_max_frag);
2330 		}
2331 		mutex_exit(&ire->ire_lock);
2332 	}
2333 	rw_exit(&first_ire->ire_bucket->irb_lock);
2334 	ire_refrele(first_ire);
2335 	return (B_TRUE);
2336 }
2337 
2338 /*
2339  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2340  * calls this function.
2341  */
2342 static mblk_t *
2343 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2344 {
2345 	ipha_t *ipha;
2346 	icmph_t *icmph;
2347 	ipha_t *in_ipha;
2348 	int length;
2349 
2350 	ASSERT(mp->b_datap->db_type == M_DATA);
2351 
2352 	/*
2353 	 * For Self-encapsulated packets, we added an extra IP header
2354 	 * without the options. Inner IP header is the one from which
2355 	 * the outer IP header was formed. Thus, we need to remove the
2356 	 * outer IP header. To do this, we pullup the whole message
2357 	 * and overlay whatever follows the outer IP header over the
2358 	 * outer IP header.
2359 	 */
2360 
2361 	if (!pullupmsg(mp, -1))
2362 		return (NULL);
2363 
2364 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2365 	ipha = (ipha_t *)&icmph[1];
2366 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2367 
2368 	/*
2369 	 * The length that we want to overlay is following the inner
2370 	 * IP header. Subtracting the IP header + icmp header + outer
2371 	 * IP header's length should give us the length that we want to
2372 	 * overlay.
2373 	 */
2374 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2375 	    hdr_length;
2376 	/*
2377 	 * Overlay whatever follows the inner header over the
2378 	 * outer header.
2379 	 */
2380 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2381 
2382 	/* Set the wptr to account for the outer header */
2383 	mp->b_wptr -= hdr_length;
2384 	return (mp);
2385 }
2386 
2387 /*
2388  * Try to pass the ICMP message upstream in case the ULP cares.
2389  *
2390  * If the packet that caused the ICMP error is secure, we send
2391  * it to AH/ESP to make sure that the attached packet has a
2392  * valid association. ipha in the code below points to the
2393  * IP header of the packet that caused the error.
2394  *
2395  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2396  * in the context of IPsec. Normally we tell the upper layer
2397  * whenever we send the ire (including ip_bind), the IPsec header
2398  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2399  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2400  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2401  * same thing. As TCP has the IPsec options size that needs to be
2402  * adjusted, we just pass the MTU unchanged.
2403  *
2404  * IFN could have been generated locally or by some router.
2405  *
2406  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2407  *	    This happens because IP adjusted its value of MTU on an
2408  *	    earlier IFN message and could not tell the upper layer,
2409  *	    the new adjusted value of MTU e.g. Packet was encrypted
2410  *	    or there was not enough information to fanout to upper
2411  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2412  *	    generates the IFN, where IPsec processing has *not* been
2413  *	    done.
2414  *
2415  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2416  *	    could have generated this. This happens because ire_max_frag
2417  *	    value in IP was set to a new value, while the IPsec processing
2418  *	    was being done and after we made the fragmentation check in
2419  *	    ip_wput_ire. Thus on return from IPsec processing,
2420  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2421  *	    and generates the IFN. As IPsec processing is over, we fanout
2422  *	    to AH/ESP to remove the header.
2423  *
2424  *	    In both these cases, ipsec_in_loopback will be set indicating
2425  *	    that IFN was generated locally.
2426  *
2427  * ROUTER : IFN could be secure or non-secure.
2428  *
2429  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2430  *	      packet in error has AH/ESP headers to validate the AH/ESP
2431  *	      headers. AH/ESP will verify whether there is a valid SA or
2432  *	      not and send it back. We will fanout again if we have more
2433  *	      data in the packet.
2434  *
2435  *	      If the packet in error does not have AH/ESP, we handle it
2436  *	      like any other case.
2437  *
2438  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2439  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2440  *	      for validation. AH/ESP will verify whether there is a
2441  *	      valid SA or not and send it back. We will fanout again if
2442  *	      we have more data in the packet.
2443  *
2444  *	      If the packet in error does not have AH/ESP, we handle it
2445  *	      like any other case.
2446  */
2447 static void
2448 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2449     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2450     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2451     zoneid_t zoneid)
2452 {
2453 	uint16_t *up;	/* Pointer to ports in ULP header */
2454 	uint32_t ports;	/* reversed ports for fanout */
2455 	ipha_t ripha;	/* With reversed addresses */
2456 	mblk_t *first_mp;
2457 	ipsec_in_t *ii;
2458 	tcph_t	*tcph;
2459 	conn_t	*connp;
2460 	ip_stack_t *ipst;
2461 
2462 	ASSERT(ill != NULL);
2463 
2464 	ASSERT(recv_ill != NULL);
2465 	ipst = recv_ill->ill_ipst;
2466 
2467 	first_mp = mp;
2468 	if (mctl_present) {
2469 		mp = first_mp->b_cont;
2470 		ASSERT(mp != NULL);
2471 
2472 		ii = (ipsec_in_t *)first_mp->b_rptr;
2473 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2474 	} else {
2475 		ii = NULL;
2476 	}
2477 
2478 	switch (ipha->ipha_protocol) {
2479 	case IPPROTO_UDP:
2480 		/*
2481 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2482 		 * transport header.
2483 		 */
2484 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2485 		    mp->b_wptr) {
2486 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2487 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2488 				goto discard_pkt;
2489 			}
2490 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2491 			ipha = (ipha_t *)&icmph[1];
2492 		}
2493 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2494 
2495 		/*
2496 		 * Attempt to find a client stream based on port.
2497 		 * Note that we do a reverse lookup since the header is
2498 		 * in the form we sent it out.
2499 		 * The ripha header is only used for the IP_UDP_MATCH and we
2500 		 * only set the src and dst addresses and protocol.
2501 		 */
2502 		ripha.ipha_src = ipha->ipha_dst;
2503 		ripha.ipha_dst = ipha->ipha_src;
2504 		ripha.ipha_protocol = ipha->ipha_protocol;
2505 		((uint16_t *)&ports)[0] = up[1];
2506 		((uint16_t *)&ports)[1] = up[0];
2507 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2508 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2509 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2510 		    icmph->icmph_type, icmph->icmph_code));
2511 
2512 		/* Have to change db_type after any pullupmsg */
2513 		DB_TYPE(mp) = M_CTL;
2514 
2515 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2516 		    mctl_present, ip_policy, recv_ill, zoneid);
2517 		return;
2518 
2519 	case IPPROTO_TCP:
2520 		/*
2521 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2522 		 * transport header.
2523 		 */
2524 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2525 		    mp->b_wptr) {
2526 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2527 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2528 				goto discard_pkt;
2529 			}
2530 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2531 			ipha = (ipha_t *)&icmph[1];
2532 		}
2533 		/*
2534 		 * Find a TCP client stream for this packet.
2535 		 * Note that we do a reverse lookup since the header is
2536 		 * in the form we sent it out.
2537 		 */
2538 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2539 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2540 		    ipst);
2541 		if (connp == NULL)
2542 			goto discard_pkt;
2543 
2544 		/* Have to change db_type after any pullupmsg */
2545 		DB_TYPE(mp) = M_CTL;
2546 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2547 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2548 		return;
2549 
2550 	case IPPROTO_SCTP:
2551 		/*
2552 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2553 		 * transport header.
2554 		 */
2555 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2556 		    mp->b_wptr) {
2557 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2558 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2559 				goto discard_pkt;
2560 			}
2561 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2562 			ipha = (ipha_t *)&icmph[1];
2563 		}
2564 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2565 		/*
2566 		 * Find a SCTP client stream for this packet.
2567 		 * Note that we do a reverse lookup since the header is
2568 		 * in the form we sent it out.
2569 		 * The ripha header is only used for the matching and we
2570 		 * only set the src and dst addresses, protocol, and version.
2571 		 */
2572 		ripha.ipha_src = ipha->ipha_dst;
2573 		ripha.ipha_dst = ipha->ipha_src;
2574 		ripha.ipha_protocol = ipha->ipha_protocol;
2575 		ripha.ipha_version_and_hdr_length =
2576 		    ipha->ipha_version_and_hdr_length;
2577 		((uint16_t *)&ports)[0] = up[1];
2578 		((uint16_t *)&ports)[1] = up[0];
2579 
2580 		/* Have to change db_type after any pullupmsg */
2581 		DB_TYPE(mp) = M_CTL;
2582 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2583 		    mctl_present, ip_policy, zoneid);
2584 		return;
2585 
2586 	case IPPROTO_ESP:
2587 	case IPPROTO_AH: {
2588 		int ipsec_rc;
2589 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2590 
2591 		/*
2592 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2593 		 * We will re-use the IPSEC_IN if it is already present as
2594 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2595 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2596 		 * one and attach it in the front.
2597 		 */
2598 		if (ii != NULL) {
2599 			/*
2600 			 * ip_fanout_proto_again converts the ICMP errors
2601 			 * that come back from AH/ESP to M_DATA so that
2602 			 * if it is non-AH/ESP and we do a pullupmsg in
2603 			 * this function, it would work. Convert it back
2604 			 * to M_CTL before we send up as this is a ICMP
2605 			 * error. This could have been generated locally or
2606 			 * by some router. Validate the inner IPsec
2607 			 * headers.
2608 			 *
2609 			 * NOTE : ill_index is used by ip_fanout_proto_again
2610 			 * to locate the ill.
2611 			 */
2612 			ASSERT(ill != NULL);
2613 			ii->ipsec_in_ill_index =
2614 			    ill->ill_phyint->phyint_ifindex;
2615 			ii->ipsec_in_rill_index =
2616 			    recv_ill->ill_phyint->phyint_ifindex;
2617 			DB_TYPE(first_mp->b_cont) = M_CTL;
2618 		} else {
2619 			/*
2620 			 * IPSEC_IN is not present. We attach a ipsec_in
2621 			 * message and send up to IPsec for validating
2622 			 * and removing the IPsec headers. Clear
2623 			 * ipsec_in_secure so that when we return
2624 			 * from IPsec, we don't mistakenly think that this
2625 			 * is a secure packet came from the network.
2626 			 *
2627 			 * NOTE : ill_index is used by ip_fanout_proto_again
2628 			 * to locate the ill.
2629 			 */
2630 			ASSERT(first_mp == mp);
2631 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2632 			if (first_mp == NULL) {
2633 				freemsg(mp);
2634 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2635 				return;
2636 			}
2637 			ii = (ipsec_in_t *)first_mp->b_rptr;
2638 
2639 			/* This is not a secure packet */
2640 			ii->ipsec_in_secure = B_FALSE;
2641 			first_mp->b_cont = mp;
2642 			DB_TYPE(mp) = M_CTL;
2643 			ASSERT(ill != NULL);
2644 			ii->ipsec_in_ill_index =
2645 			    ill->ill_phyint->phyint_ifindex;
2646 			ii->ipsec_in_rill_index =
2647 			    recv_ill->ill_phyint->phyint_ifindex;
2648 		}
2649 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2650 
2651 		if (!ipsec_loaded(ipss)) {
2652 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2653 			return;
2654 		}
2655 
2656 		if (ipha->ipha_protocol == IPPROTO_ESP)
2657 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2658 		else
2659 			ipsec_rc = ipsecah_icmp_error(first_mp);
2660 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2661 			return;
2662 
2663 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2664 		return;
2665 	}
2666 	default:
2667 		/*
2668 		 * The ripha header is only used for the lookup and we
2669 		 * only set the src and dst addresses and protocol.
2670 		 */
2671 		ripha.ipha_src = ipha->ipha_dst;
2672 		ripha.ipha_dst = ipha->ipha_src;
2673 		ripha.ipha_protocol = ipha->ipha_protocol;
2674 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2675 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2676 		    ntohl(ipha->ipha_dst),
2677 		    icmph->icmph_type, icmph->icmph_code));
2678 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2679 			ipha_t *in_ipha;
2680 
2681 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2682 			    mp->b_wptr) {
2683 				if (!pullupmsg(mp, (uchar_t *)ipha +
2684 				    hdr_length + sizeof (ipha_t) -
2685 				    mp->b_rptr)) {
2686 					goto discard_pkt;
2687 				}
2688 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2689 				ipha = (ipha_t *)&icmph[1];
2690 			}
2691 			/*
2692 			 * Caller has verified that length has to be
2693 			 * at least the size of IP header.
2694 			 */
2695 			ASSERT(hdr_length >= sizeof (ipha_t));
2696 			/*
2697 			 * Check the sanity of the inner IP header like
2698 			 * we did for the outer header.
2699 			 */
2700 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2701 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2702 				goto discard_pkt;
2703 			}
2704 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2705 				goto discard_pkt;
2706 			}
2707 			/* Check for Self-encapsulated tunnels */
2708 			if (in_ipha->ipha_src == ipha->ipha_src &&
2709 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2710 
2711 				mp = icmp_inbound_self_encap_error(mp,
2712 				    iph_hdr_length, hdr_length);
2713 				if (mp == NULL)
2714 					goto discard_pkt;
2715 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2716 				ipha = (ipha_t *)&icmph[1];
2717 				hdr_length = IPH_HDR_LENGTH(ipha);
2718 				/*
2719 				 * The packet in error is self-encapsualted.
2720 				 * And we are finding it further encapsulated
2721 				 * which we could not have possibly generated.
2722 				 */
2723 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2724 					goto discard_pkt;
2725 				}
2726 				icmp_inbound_error_fanout(q, ill, first_mp,
2727 				    icmph, ipha, iph_hdr_length, hdr_length,
2728 				    mctl_present, ip_policy, recv_ill, zoneid);
2729 				return;
2730 			}
2731 		}
2732 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2733 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2734 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2735 		    ii != NULL &&
2736 		    ii->ipsec_in_loopback &&
2737 		    ii->ipsec_in_secure) {
2738 			/*
2739 			 * For IP tunnels that get a looped-back
2740 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2741 			 * reported new MTU to take into account the IPsec
2742 			 * headers protecting this configured tunnel.
2743 			 *
2744 			 * This allows the tunnel module (tun.c) to blindly
2745 			 * accept the MTU reported in an ICMP "too big"
2746 			 * message.
2747 			 *
2748 			 * Non-looped back ICMP messages will just be
2749 			 * handled by the security protocols (if needed),
2750 			 * and the first subsequent packet will hit this
2751 			 * path.
2752 			 */
2753 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2754 			    ipsec_in_extra_length(first_mp));
2755 		}
2756 		/* Have to change db_type after any pullupmsg */
2757 		DB_TYPE(mp) = M_CTL;
2758 
2759 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2760 		    ip_policy, recv_ill, zoneid);
2761 		return;
2762 	}
2763 	/* NOTREACHED */
2764 discard_pkt:
2765 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2766 drop_pkt:;
2767 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2768 	freemsg(first_mp);
2769 }
2770 
2771 /*
2772  * Common IP options parser.
2773  *
2774  * Setup routine: fill in *optp with options-parsing state, then
2775  * tail-call ipoptp_next to return the first option.
2776  */
2777 uint8_t
2778 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2779 {
2780 	uint32_t totallen; /* total length of all options */
2781 
2782 	totallen = ipha->ipha_version_and_hdr_length -
2783 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2784 	totallen <<= 2;
2785 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2786 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2787 	optp->ipoptp_flags = 0;
2788 	return (ipoptp_next(optp));
2789 }
2790 
2791 /*
2792  * Common IP options parser: extract next option.
2793  */
2794 uint8_t
2795 ipoptp_next(ipoptp_t *optp)
2796 {
2797 	uint8_t *end = optp->ipoptp_end;
2798 	uint8_t *cur = optp->ipoptp_next;
2799 	uint8_t opt, len, pointer;
2800 
2801 	/*
2802 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2803 	 * has been corrupted.
2804 	 */
2805 	ASSERT(cur <= end);
2806 
2807 	if (cur == end)
2808 		return (IPOPT_EOL);
2809 
2810 	opt = cur[IPOPT_OPTVAL];
2811 
2812 	/*
2813 	 * Skip any NOP options.
2814 	 */
2815 	while (opt == IPOPT_NOP) {
2816 		cur++;
2817 		if (cur == end)
2818 			return (IPOPT_EOL);
2819 		opt = cur[IPOPT_OPTVAL];
2820 	}
2821 
2822 	if (opt == IPOPT_EOL)
2823 		return (IPOPT_EOL);
2824 
2825 	/*
2826 	 * Option requiring a length.
2827 	 */
2828 	if ((cur + 1) >= end) {
2829 		optp->ipoptp_flags |= IPOPTP_ERROR;
2830 		return (IPOPT_EOL);
2831 	}
2832 	len = cur[IPOPT_OLEN];
2833 	if (len < 2) {
2834 		optp->ipoptp_flags |= IPOPTP_ERROR;
2835 		return (IPOPT_EOL);
2836 	}
2837 	optp->ipoptp_cur = cur;
2838 	optp->ipoptp_len = len;
2839 	optp->ipoptp_next = cur + len;
2840 	if (cur + len > end) {
2841 		optp->ipoptp_flags |= IPOPTP_ERROR;
2842 		return (IPOPT_EOL);
2843 	}
2844 
2845 	/*
2846 	 * For the options which require a pointer field, make sure
2847 	 * its there, and make sure it points to either something
2848 	 * inside this option, or the end of the option.
2849 	 */
2850 	switch (opt) {
2851 	case IPOPT_RR:
2852 	case IPOPT_TS:
2853 	case IPOPT_LSRR:
2854 	case IPOPT_SSRR:
2855 		if (len <= IPOPT_OFFSET) {
2856 			optp->ipoptp_flags |= IPOPTP_ERROR;
2857 			return (opt);
2858 		}
2859 		pointer = cur[IPOPT_OFFSET];
2860 		if (pointer - 1 > len) {
2861 			optp->ipoptp_flags |= IPOPTP_ERROR;
2862 			return (opt);
2863 		}
2864 		break;
2865 	}
2866 
2867 	/*
2868 	 * Sanity check the pointer field based on the type of the
2869 	 * option.
2870 	 */
2871 	switch (opt) {
2872 	case IPOPT_RR:
2873 	case IPOPT_SSRR:
2874 	case IPOPT_LSRR:
2875 		if (pointer < IPOPT_MINOFF_SR)
2876 			optp->ipoptp_flags |= IPOPTP_ERROR;
2877 		break;
2878 	case IPOPT_TS:
2879 		if (pointer < IPOPT_MINOFF_IT)
2880 			optp->ipoptp_flags |= IPOPTP_ERROR;
2881 		/*
2882 		 * Note that the Internet Timestamp option also
2883 		 * contains two four bit fields (the Overflow field,
2884 		 * and the Flag field), which follow the pointer
2885 		 * field.  We don't need to check that these fields
2886 		 * fall within the length of the option because this
2887 		 * was implicitely done above.  We've checked that the
2888 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2889 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2890 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2891 		 */
2892 		ASSERT(len > IPOPT_POS_OV_FLG);
2893 		break;
2894 	}
2895 
2896 	return (opt);
2897 }
2898 
2899 /*
2900  * Use the outgoing IP header to create an IP_OPTIONS option the way
2901  * it was passed down from the application.
2902  */
2903 int
2904 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2905 {
2906 	ipoptp_t	opts;
2907 	const uchar_t	*opt;
2908 	uint8_t		optval;
2909 	uint8_t		optlen;
2910 	uint32_t	len = 0;
2911 	uchar_t	*buf1 = buf;
2912 
2913 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2914 	len += IP_ADDR_LEN;
2915 	bzero(buf1, IP_ADDR_LEN);
2916 
2917 	/*
2918 	 * OK to cast away const here, as we don't store through the returned
2919 	 * opts.ipoptp_cur pointer.
2920 	 */
2921 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2922 	    optval != IPOPT_EOL;
2923 	    optval = ipoptp_next(&opts)) {
2924 		int	off;
2925 
2926 		opt = opts.ipoptp_cur;
2927 		optlen = opts.ipoptp_len;
2928 		switch (optval) {
2929 		case IPOPT_SSRR:
2930 		case IPOPT_LSRR:
2931 
2932 			/*
2933 			 * Insert ipha_dst as the first entry in the source
2934 			 * route and move down the entries on step.
2935 			 * The last entry gets placed at buf1.
2936 			 */
2937 			buf[IPOPT_OPTVAL] = optval;
2938 			buf[IPOPT_OLEN] = optlen;
2939 			buf[IPOPT_OFFSET] = optlen;
2940 
2941 			off = optlen - IP_ADDR_LEN;
2942 			if (off < 0) {
2943 				/* No entries in source route */
2944 				break;
2945 			}
2946 			/* Last entry in source route */
2947 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2948 			off -= IP_ADDR_LEN;
2949 
2950 			while (off > 0) {
2951 				bcopy(opt + off,
2952 				    buf + off + IP_ADDR_LEN,
2953 				    IP_ADDR_LEN);
2954 				off -= IP_ADDR_LEN;
2955 			}
2956 			/* ipha_dst into first slot */
2957 			bcopy(&ipha->ipha_dst,
2958 			    buf + off + IP_ADDR_LEN,
2959 			    IP_ADDR_LEN);
2960 			buf += optlen;
2961 			len += optlen;
2962 			break;
2963 
2964 		case IPOPT_COMSEC:
2965 		case IPOPT_SECURITY:
2966 			/* if passing up a label is not ok, then remove */
2967 			if (is_system_labeled())
2968 				break;
2969 			/* FALLTHROUGH */
2970 		default:
2971 			bcopy(opt, buf, optlen);
2972 			buf += optlen;
2973 			len += optlen;
2974 			break;
2975 		}
2976 	}
2977 done:
2978 	/* Pad the resulting options */
2979 	while (len & 0x3) {
2980 		*buf++ = IPOPT_EOL;
2981 		len++;
2982 	}
2983 	return (len);
2984 }
2985 
2986 /*
2987  * Update any record route or timestamp options to include this host.
2988  * Reverse any source route option.
2989  * This routine assumes that the options are well formed i.e. that they
2990  * have already been checked.
2991  */
2992 static void
2993 icmp_options_update(ipha_t *ipha)
2994 {
2995 	ipoptp_t	opts;
2996 	uchar_t		*opt;
2997 	uint8_t		optval;
2998 	ipaddr_t	src;		/* Our local address */
2999 	ipaddr_t	dst;
3000 
3001 	ip2dbg(("icmp_options_update\n"));
3002 	src = ipha->ipha_src;
3003 	dst = ipha->ipha_dst;
3004 
3005 	for (optval = ipoptp_first(&opts, ipha);
3006 	    optval != IPOPT_EOL;
3007 	    optval = ipoptp_next(&opts)) {
3008 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3009 		opt = opts.ipoptp_cur;
3010 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3011 		    optval, opts.ipoptp_len));
3012 		switch (optval) {
3013 			int off1, off2;
3014 		case IPOPT_SSRR:
3015 		case IPOPT_LSRR:
3016 			/*
3017 			 * Reverse the source route.  The first entry
3018 			 * should be the next to last one in the current
3019 			 * source route (the last entry is our address).
3020 			 * The last entry should be the final destination.
3021 			 */
3022 			off1 = IPOPT_MINOFF_SR - 1;
3023 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3024 			if (off2 < 0) {
3025 				/* No entries in source route */
3026 				ip1dbg((
3027 				    "icmp_options_update: bad src route\n"));
3028 				break;
3029 			}
3030 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3031 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3032 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3033 			off2 -= IP_ADDR_LEN;
3034 
3035 			while (off1 < off2) {
3036 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3037 				bcopy((char *)opt + off2, (char *)opt + off1,
3038 				    IP_ADDR_LEN);
3039 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3040 				off1 += IP_ADDR_LEN;
3041 				off2 -= IP_ADDR_LEN;
3042 			}
3043 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3044 			break;
3045 		}
3046 	}
3047 }
3048 
3049 /*
3050  * Process received ICMP Redirect messages.
3051  */
3052 static void
3053 icmp_redirect(ill_t *ill, mblk_t *mp)
3054 {
3055 	ipha_t	*ipha;
3056 	int	iph_hdr_length;
3057 	icmph_t	*icmph;
3058 	ipha_t	*ipha_err;
3059 	ire_t	*ire;
3060 	ire_t	*prev_ire;
3061 	ire_t	*save_ire;
3062 	ipaddr_t  src, dst, gateway;
3063 	iulp_t	ulp_info = { 0 };
3064 	int	error;
3065 	ip_stack_t *ipst;
3066 
3067 	ASSERT(ill != NULL);
3068 	ipst = ill->ill_ipst;
3069 
3070 	ipha = (ipha_t *)mp->b_rptr;
3071 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3072 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3073 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3074 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3075 		freemsg(mp);
3076 		return;
3077 	}
3078 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3079 	ipha_err = (ipha_t *)&icmph[1];
3080 	src = ipha->ipha_src;
3081 	dst = ipha_err->ipha_dst;
3082 	gateway = icmph->icmph_rd_gateway;
3083 	/* Make sure the new gateway is reachable somehow. */
3084 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3085 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3086 	/*
3087 	 * Make sure we had a route for the dest in question and that
3088 	 * that route was pointing to the old gateway (the source of the
3089 	 * redirect packet.)
3090 	 */
3091 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3092 	    NULL, MATCH_IRE_GW, ipst);
3093 	/*
3094 	 * Check that
3095 	 *	the redirect was not from ourselves
3096 	 *	the new gateway and the old gateway are directly reachable
3097 	 */
3098 	if (!prev_ire ||
3099 	    !ire ||
3100 	    ire->ire_type == IRE_LOCAL) {
3101 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3102 		freemsg(mp);
3103 		if (ire != NULL)
3104 			ire_refrele(ire);
3105 		if (prev_ire != NULL)
3106 			ire_refrele(prev_ire);
3107 		return;
3108 	}
3109 
3110 	/*
3111 	 * Should we use the old ULP info to create the new gateway?  From
3112 	 * a user's perspective, we should inherit the info so that it
3113 	 * is a "smooth" transition.  If we do not do that, then new
3114 	 * connections going thru the new gateway will have no route metrics,
3115 	 * which is counter-intuitive to user.  From a network point of
3116 	 * view, this may or may not make sense even though the new gateway
3117 	 * is still directly connected to us so the route metrics should not
3118 	 * change much.
3119 	 *
3120 	 * But if the old ire_uinfo is not initialized, we do another
3121 	 * recursive lookup on the dest using the new gateway.  There may
3122 	 * be a route to that.  If so, use it to initialize the redirect
3123 	 * route.
3124 	 */
3125 	if (prev_ire->ire_uinfo.iulp_set) {
3126 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3127 	} else {
3128 		ire_t *tmp_ire;
3129 		ire_t *sire;
3130 
3131 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3132 		    ALL_ZONES, 0, NULL,
3133 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3134 		    ipst);
3135 		if (sire != NULL) {
3136 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3137 			/*
3138 			 * If sire != NULL, ire_ftable_lookup() should not
3139 			 * return a NULL value.
3140 			 */
3141 			ASSERT(tmp_ire != NULL);
3142 			ire_refrele(tmp_ire);
3143 			ire_refrele(sire);
3144 		} else if (tmp_ire != NULL) {
3145 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3146 			    sizeof (iulp_t));
3147 			ire_refrele(tmp_ire);
3148 		}
3149 	}
3150 	if (prev_ire->ire_type == IRE_CACHE)
3151 		ire_delete(prev_ire);
3152 	ire_refrele(prev_ire);
3153 	/*
3154 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3155 	 * require TOS routing
3156 	 */
3157 	switch (icmph->icmph_code) {
3158 	case 0:
3159 	case 1:
3160 		/* TODO: TOS specificity for cases 2 and 3 */
3161 	case 2:
3162 	case 3:
3163 		break;
3164 	default:
3165 		freemsg(mp);
3166 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3167 		ire_refrele(ire);
3168 		return;
3169 	}
3170 	/*
3171 	 * Create a Route Association.  This will allow us to remember that
3172 	 * someone we believe told us to use the particular gateway.
3173 	 */
3174 	save_ire = ire;
3175 	ire = ire_create(
3176 	    (uchar_t *)&dst,			/* dest addr */
3177 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3178 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3179 	    (uchar_t *)&gateway,		/* gateway addr */
3180 	    &save_ire->ire_max_frag,		/* max frag */
3181 	    NULL,				/* no src nce */
3182 	    NULL,				/* no rfq */
3183 	    NULL,				/* no stq */
3184 	    IRE_HOST,
3185 	    NULL,				/* ipif */
3186 	    0,					/* cmask */
3187 	    0,					/* phandle */
3188 	    0,					/* ihandle */
3189 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3190 	    &ulp_info,
3191 	    NULL,				/* tsol_gc_t */
3192 	    NULL,				/* gcgrp */
3193 	    ipst);
3194 
3195 	if (ire == NULL) {
3196 		freemsg(mp);
3197 		ire_refrele(save_ire);
3198 		return;
3199 	}
3200 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3201 	ire_refrele(save_ire);
3202 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3203 
3204 	if (error == 0) {
3205 		ire_refrele(ire);		/* Held in ire_add_v4 */
3206 		/* tell routing sockets that we received a redirect */
3207 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3208 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3209 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3210 	}
3211 
3212 	/*
3213 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3214 	 * This together with the added IRE has the effect of
3215 	 * modifying an existing redirect.
3216 	 */
3217 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3218 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3219 	if (prev_ire != NULL) {
3220 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3221 			ire_delete(prev_ire);
3222 		ire_refrele(prev_ire);
3223 	}
3224 
3225 	freemsg(mp);
3226 }
3227 
3228 /*
3229  * Generate an ICMP parameter problem message.
3230  */
3231 static void
3232 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3233 	ip_stack_t *ipst)
3234 {
3235 	icmph_t	icmph;
3236 	boolean_t mctl_present;
3237 	mblk_t *first_mp;
3238 
3239 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3240 
3241 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3242 		if (mctl_present)
3243 			freeb(first_mp);
3244 		return;
3245 	}
3246 
3247 	bzero(&icmph, sizeof (icmph_t));
3248 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3249 	icmph.icmph_pp_ptr = ptr;
3250 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3251 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3252 	    ipst);
3253 }
3254 
3255 /*
3256  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3257  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3258  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3259  * an icmp error packet can be sent.
3260  * Assigns an appropriate source address to the packet. If ipha_dst is
3261  * one of our addresses use it for source. Otherwise pick a source based
3262  * on a route lookup back to ipha_src.
3263  * Note that ipha_src must be set here since the
3264  * packet is likely to arrive on an ill queue in ip_wput() which will
3265  * not set a source address.
3266  */
3267 static void
3268 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3269     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3270 {
3271 	ipaddr_t dst;
3272 	icmph_t	*icmph;
3273 	ipha_t	*ipha;
3274 	uint_t	len_needed;
3275 	size_t	msg_len;
3276 	mblk_t	*mp1;
3277 	ipaddr_t src;
3278 	ire_t	*ire;
3279 	mblk_t *ipsec_mp;
3280 	ipsec_out_t	*io = NULL;
3281 
3282 	if (mctl_present) {
3283 		/*
3284 		 * If it is :
3285 		 *
3286 		 * 1) a IPSEC_OUT, then this is caused by outbound
3287 		 *    datagram originating on this host. IPsec processing
3288 		 *    may or may not have been done. Refer to comments above
3289 		 *    icmp_inbound_error_fanout for details.
3290 		 *
3291 		 * 2) a IPSEC_IN if we are generating a icmp_message
3292 		 *    for an incoming datagram destined for us i.e called
3293 		 *    from ip_fanout_send_icmp.
3294 		 */
3295 		ipsec_info_t *in;
3296 		ipsec_mp = mp;
3297 		mp = ipsec_mp->b_cont;
3298 
3299 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3300 		ipha = (ipha_t *)mp->b_rptr;
3301 
3302 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3303 		    in->ipsec_info_type == IPSEC_IN);
3304 
3305 		if (in->ipsec_info_type == IPSEC_IN) {
3306 			/*
3307 			 * Convert the IPSEC_IN to IPSEC_OUT.
3308 			 */
3309 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3310 				BUMP_MIB(&ipst->ips_ip_mib,
3311 				    ipIfStatsOutDiscards);
3312 				return;
3313 			}
3314 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3315 		} else {
3316 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3317 			io = (ipsec_out_t *)in;
3318 			/*
3319 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3320 			 * ire lookup.
3321 			 */
3322 			io->ipsec_out_proc_begin = B_FALSE;
3323 		}
3324 		ASSERT(zoneid == io->ipsec_out_zoneid);
3325 		ASSERT(zoneid != ALL_ZONES);
3326 	} else {
3327 		/*
3328 		 * This is in clear. The icmp message we are building
3329 		 * here should go out in clear.
3330 		 *
3331 		 * Pardon the convolution of it all, but it's easier to
3332 		 * allocate a "use cleartext" IPSEC_IN message and convert
3333 		 * it than it is to allocate a new one.
3334 		 */
3335 		ipsec_in_t *ii;
3336 		ASSERT(DB_TYPE(mp) == M_DATA);
3337 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3338 		if (ipsec_mp == NULL) {
3339 			freemsg(mp);
3340 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3341 			return;
3342 		}
3343 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3344 
3345 		/* This is not a secure packet */
3346 		ii->ipsec_in_secure = B_FALSE;
3347 		/*
3348 		 * For trusted extensions using a shared IP address we can
3349 		 * send using any zoneid.
3350 		 */
3351 		if (zoneid == ALL_ZONES)
3352 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3353 		else
3354 			ii->ipsec_in_zoneid = zoneid;
3355 		ipsec_mp->b_cont = mp;
3356 		ipha = (ipha_t *)mp->b_rptr;
3357 		/*
3358 		 * Convert the IPSEC_IN to IPSEC_OUT.
3359 		 */
3360 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3361 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3362 			return;
3363 		}
3364 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3365 	}
3366 
3367 	/* Remember our eventual destination */
3368 	dst = ipha->ipha_src;
3369 
3370 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3371 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3372 	if (ire != NULL &&
3373 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3374 		src = ipha->ipha_dst;
3375 	} else {
3376 		if (ire != NULL)
3377 			ire_refrele(ire);
3378 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3379 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3380 		    ipst);
3381 		if (ire == NULL) {
3382 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3383 			freemsg(ipsec_mp);
3384 			return;
3385 		}
3386 		src = ire->ire_src_addr;
3387 	}
3388 
3389 	if (ire != NULL)
3390 		ire_refrele(ire);
3391 
3392 	/*
3393 	 * Check if we can send back more then 8 bytes in addition to
3394 	 * the IP header.  We try to send 64 bytes of data and the internal
3395 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3396 	 */
3397 	len_needed = IPH_HDR_LENGTH(ipha);
3398 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3399 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3400 
3401 		if (!pullupmsg(mp, -1)) {
3402 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3403 			freemsg(ipsec_mp);
3404 			return;
3405 		}
3406 		ipha = (ipha_t *)mp->b_rptr;
3407 
3408 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3409 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3410 			    len_needed));
3411 		} else {
3412 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3413 
3414 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3415 			len_needed += ip_hdr_length_v6(mp, ip6h);
3416 		}
3417 	}
3418 	len_needed += ipst->ips_ip_icmp_return;
3419 	msg_len = msgdsize(mp);
3420 	if (msg_len > len_needed) {
3421 		(void) adjmsg(mp, len_needed - msg_len);
3422 		msg_len = len_needed;
3423 	}
3424 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3425 	if (mp1 == NULL) {
3426 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3427 		freemsg(ipsec_mp);
3428 		return;
3429 	}
3430 	mp1->b_cont = mp;
3431 	mp = mp1;
3432 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3433 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3434 	    io->ipsec_out_type == IPSEC_OUT);
3435 	ipsec_mp->b_cont = mp;
3436 
3437 	/*
3438 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3439 	 * node generates be accepted in peace by all on-host destinations.
3440 	 * If we do NOT assume that all on-host destinations trust
3441 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3442 	 * (Look for ipsec_out_icmp_loopback).
3443 	 */
3444 	io->ipsec_out_icmp_loopback = B_TRUE;
3445 
3446 	ipha = (ipha_t *)mp->b_rptr;
3447 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3448 	*ipha = icmp_ipha;
3449 	ipha->ipha_src = src;
3450 	ipha->ipha_dst = dst;
3451 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3452 	msg_len += sizeof (icmp_ipha) + len;
3453 	if (msg_len > IP_MAXPACKET) {
3454 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3455 		msg_len = IP_MAXPACKET;
3456 	}
3457 	ipha->ipha_length = htons((uint16_t)msg_len);
3458 	icmph = (icmph_t *)&ipha[1];
3459 	bcopy(stuff, icmph, len);
3460 	icmph->icmph_checksum = 0;
3461 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3462 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3463 	put(q, ipsec_mp);
3464 }
3465 
3466 /*
3467  * Determine if an ICMP error packet can be sent given the rate limit.
3468  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3469  * in milliseconds) and a burst size. Burst size number of packets can
3470  * be sent arbitrarely closely spaced.
3471  * The state is tracked using two variables to implement an approximate
3472  * token bucket filter:
3473  *	icmp_pkt_err_last - lbolt value when the last burst started
3474  *	icmp_pkt_err_sent - number of packets sent in current burst
3475  */
3476 boolean_t
3477 icmp_err_rate_limit(ip_stack_t *ipst)
3478 {
3479 	clock_t now = TICK_TO_MSEC(lbolt);
3480 	uint_t refilled; /* Number of packets refilled in tbf since last */
3481 	/* Guard against changes by loading into local variable */
3482 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3483 
3484 	if (err_interval == 0)
3485 		return (B_FALSE);
3486 
3487 	if (ipst->ips_icmp_pkt_err_last > now) {
3488 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3489 		ipst->ips_icmp_pkt_err_last = 0;
3490 		ipst->ips_icmp_pkt_err_sent = 0;
3491 	}
3492 	/*
3493 	 * If we are in a burst update the token bucket filter.
3494 	 * Update the "last" time to be close to "now" but make sure
3495 	 * we don't loose precision.
3496 	 */
3497 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3498 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3499 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3500 			ipst->ips_icmp_pkt_err_sent = 0;
3501 		} else {
3502 			ipst->ips_icmp_pkt_err_sent -= refilled;
3503 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3504 		}
3505 	}
3506 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3507 		/* Start of new burst */
3508 		ipst->ips_icmp_pkt_err_last = now;
3509 	}
3510 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3511 		ipst->ips_icmp_pkt_err_sent++;
3512 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3513 		    ipst->ips_icmp_pkt_err_sent));
3514 		return (B_FALSE);
3515 	}
3516 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3517 	return (B_TRUE);
3518 }
3519 
3520 /*
3521  * Check if it is ok to send an IPv4 ICMP error packet in
3522  * response to the IPv4 packet in mp.
3523  * Free the message and return null if no
3524  * ICMP error packet should be sent.
3525  */
3526 static mblk_t *
3527 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3528 {
3529 	icmph_t	*icmph;
3530 	ipha_t	*ipha;
3531 	uint_t	len_needed;
3532 	ire_t	*src_ire;
3533 	ire_t	*dst_ire;
3534 
3535 	if (!mp)
3536 		return (NULL);
3537 	ipha = (ipha_t *)mp->b_rptr;
3538 	if (ip_csum_hdr(ipha)) {
3539 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3540 		freemsg(mp);
3541 		return (NULL);
3542 	}
3543 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3544 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3545 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3546 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3547 	if (src_ire != NULL || dst_ire != NULL ||
3548 	    CLASSD(ipha->ipha_dst) ||
3549 	    CLASSD(ipha->ipha_src) ||
3550 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3551 		/* Note: only errors to the fragment with offset 0 */
3552 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3553 		freemsg(mp);
3554 		if (src_ire != NULL)
3555 			ire_refrele(src_ire);
3556 		if (dst_ire != NULL)
3557 			ire_refrele(dst_ire);
3558 		return (NULL);
3559 	}
3560 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3561 		/*
3562 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3563 		 * errors in response to any ICMP errors.
3564 		 */
3565 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3566 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3567 			if (!pullupmsg(mp, len_needed)) {
3568 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3569 				freemsg(mp);
3570 				return (NULL);
3571 			}
3572 			ipha = (ipha_t *)mp->b_rptr;
3573 		}
3574 		icmph = (icmph_t *)
3575 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3576 		switch (icmph->icmph_type) {
3577 		case ICMP_DEST_UNREACHABLE:
3578 		case ICMP_SOURCE_QUENCH:
3579 		case ICMP_TIME_EXCEEDED:
3580 		case ICMP_PARAM_PROBLEM:
3581 		case ICMP_REDIRECT:
3582 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3583 			freemsg(mp);
3584 			return (NULL);
3585 		default:
3586 			break;
3587 		}
3588 	}
3589 	/*
3590 	 * If this is a labeled system, then check to see if we're allowed to
3591 	 * send a response to this particular sender.  If not, then just drop.
3592 	 */
3593 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3594 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3595 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3596 		freemsg(mp);
3597 		return (NULL);
3598 	}
3599 	if (icmp_err_rate_limit(ipst)) {
3600 		/*
3601 		 * Only send ICMP error packets every so often.
3602 		 * This should be done on a per port/source basis,
3603 		 * but for now this will suffice.
3604 		 */
3605 		freemsg(mp);
3606 		return (NULL);
3607 	}
3608 	return (mp);
3609 }
3610 
3611 /*
3612  * Generate an ICMP redirect message.
3613  */
3614 static void
3615 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3616 {
3617 	icmph_t	icmph;
3618 
3619 	/*
3620 	 * We are called from ip_rput where we could
3621 	 * not have attached an IPSEC_IN.
3622 	 */
3623 	ASSERT(mp->b_datap->db_type == M_DATA);
3624 
3625 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3626 		return;
3627 	}
3628 
3629 	bzero(&icmph, sizeof (icmph_t));
3630 	icmph.icmph_type = ICMP_REDIRECT;
3631 	icmph.icmph_code = 1;
3632 	icmph.icmph_rd_gateway = gateway;
3633 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3634 	/* Redirects sent by router, and router is global zone */
3635 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3636 }
3637 
3638 /*
3639  * Generate an ICMP time exceeded message.
3640  */
3641 void
3642 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3643     ip_stack_t *ipst)
3644 {
3645 	icmph_t	icmph;
3646 	boolean_t mctl_present;
3647 	mblk_t *first_mp;
3648 
3649 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3650 
3651 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3652 		if (mctl_present)
3653 			freeb(first_mp);
3654 		return;
3655 	}
3656 
3657 	bzero(&icmph, sizeof (icmph_t));
3658 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3659 	icmph.icmph_code = code;
3660 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3661 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3662 	    ipst);
3663 }
3664 
3665 /*
3666  * Generate an ICMP unreachable message.
3667  */
3668 void
3669 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3670     ip_stack_t *ipst)
3671 {
3672 	icmph_t	icmph;
3673 	mblk_t *first_mp;
3674 	boolean_t mctl_present;
3675 
3676 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3677 
3678 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3679 		if (mctl_present)
3680 			freeb(first_mp);
3681 		return;
3682 	}
3683 
3684 	bzero(&icmph, sizeof (icmph_t));
3685 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3686 	icmph.icmph_code = code;
3687 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3688 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3689 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3690 	    zoneid, ipst);
3691 }
3692 
3693 /*
3694  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3695  * duplicate.  As long as someone else holds the address, the interface will
3696  * stay down.  When that conflict goes away, the interface is brought back up.
3697  * This is done so that accidental shutdowns of addresses aren't made
3698  * permanent.  Your server will recover from a failure.
3699  *
3700  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3701  * user space process (dhcpagent).
3702  *
3703  * Recovery completes if ARP reports that the address is now ours (via
3704  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3705  *
3706  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3707  */
3708 static void
3709 ipif_dup_recovery(void *arg)
3710 {
3711 	ipif_t *ipif = arg;
3712 	ill_t *ill = ipif->ipif_ill;
3713 	mblk_t *arp_add_mp;
3714 	mblk_t *arp_del_mp;
3715 	area_t *area;
3716 	ip_stack_t *ipst = ill->ill_ipst;
3717 
3718 	ipif->ipif_recovery_id = 0;
3719 
3720 	/*
3721 	 * No lock needed for moving or condemned check, as this is just an
3722 	 * optimization.
3723 	 */
3724 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3725 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3726 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3727 		/* No reason to try to bring this address back. */
3728 		return;
3729 	}
3730 
3731 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3732 		goto alloc_fail;
3733 
3734 	if (ipif->ipif_arp_del_mp == NULL) {
3735 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3736 			goto alloc_fail;
3737 		ipif->ipif_arp_del_mp = arp_del_mp;
3738 	}
3739 
3740 	/* Setting the 'unverified' flag restarts DAD */
3741 	area = (area_t *)arp_add_mp->b_rptr;
3742 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3743 	    ACE_F_UNVERIFIED;
3744 	putnext(ill->ill_rq, arp_add_mp);
3745 	return;
3746 
3747 alloc_fail:
3748 	/*
3749 	 * On allocation failure, just restart the timer.  Note that the ipif
3750 	 * is down here, so no other thread could be trying to start a recovery
3751 	 * timer.  The ill_lock protects the condemned flag and the recovery
3752 	 * timer ID.
3753 	 */
3754 	freemsg(arp_add_mp);
3755 	mutex_enter(&ill->ill_lock);
3756 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3757 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3758 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3759 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3760 	}
3761 	mutex_exit(&ill->ill_lock);
3762 }
3763 
3764 /*
3765  * This is for exclusive changes due to ARP.  Either tear down an interface due
3766  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3767  */
3768 /* ARGSUSED */
3769 static void
3770 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3771 {
3772 	ill_t	*ill = rq->q_ptr;
3773 	arh_t *arh;
3774 	ipaddr_t src;
3775 	ipif_t	*ipif;
3776 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3777 	char hbuf[MAC_STR_LEN];
3778 	char sbuf[INET_ADDRSTRLEN];
3779 	const char *failtype;
3780 	boolean_t bring_up;
3781 	ip_stack_t *ipst = ill->ill_ipst;
3782 
3783 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3784 	case AR_CN_READY:
3785 		failtype = NULL;
3786 		bring_up = B_TRUE;
3787 		break;
3788 	case AR_CN_FAILED:
3789 		failtype = "in use";
3790 		bring_up = B_FALSE;
3791 		break;
3792 	default:
3793 		failtype = "claimed";
3794 		bring_up = B_FALSE;
3795 		break;
3796 	}
3797 
3798 	arh = (arh_t *)mp->b_cont->b_rptr;
3799 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3800 
3801 	/* Handle failures due to probes */
3802 	if (src == 0) {
3803 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3804 		    IP_ADDR_LEN);
3805 	}
3806 
3807 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3808 	    sizeof (hbuf));
3809 	(void) ip_dot_addr(src, sbuf);
3810 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3811 
3812 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3813 		    ipif->ipif_lcl_addr != src) {
3814 			continue;
3815 		}
3816 
3817 		/*
3818 		 * If we failed on a recovery probe, then restart the timer to
3819 		 * try again later.
3820 		 */
3821 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3822 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3823 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3824 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3825 		    ipst->ips_ip_dup_recovery > 0 &&
3826 		    ipif->ipif_recovery_id == 0) {
3827 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3828 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3829 			continue;
3830 		}
3831 
3832 		/*
3833 		 * If what we're trying to do has already been done, then do
3834 		 * nothing.
3835 		 */
3836 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3837 			continue;
3838 
3839 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3840 
3841 		if (failtype == NULL) {
3842 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3843 			    ibuf);
3844 		} else {
3845 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3846 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3847 		}
3848 
3849 		if (bring_up) {
3850 			ASSERT(ill->ill_dl_up);
3851 			/*
3852 			 * Free up the ARP delete message so we can allocate
3853 			 * a fresh one through the normal path.
3854 			 */
3855 			freemsg(ipif->ipif_arp_del_mp);
3856 			ipif->ipif_arp_del_mp = NULL;
3857 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3858 			    EINPROGRESS) {
3859 				ipif->ipif_addr_ready = 1;
3860 				(void) ipif_up_done(ipif);
3861 			}
3862 			continue;
3863 		}
3864 
3865 		mutex_enter(&ill->ill_lock);
3866 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3867 		ipif->ipif_flags |= IPIF_DUPLICATE;
3868 		ill->ill_ipif_dup_count++;
3869 		mutex_exit(&ill->ill_lock);
3870 		/*
3871 		 * Already exclusive on the ill; no need to handle deferred
3872 		 * processing here.
3873 		 */
3874 		(void) ipif_down(ipif, NULL, NULL);
3875 		ipif_down_tail(ipif);
3876 		mutex_enter(&ill->ill_lock);
3877 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3878 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3879 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3880 		    ipst->ips_ip_dup_recovery > 0) {
3881 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3882 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3883 		}
3884 		mutex_exit(&ill->ill_lock);
3885 	}
3886 	freemsg(mp);
3887 }
3888 
3889 /* ARGSUSED */
3890 static void
3891 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3892 {
3893 	ill_t	*ill = rq->q_ptr;
3894 	arh_t *arh;
3895 	ipaddr_t src;
3896 	ipif_t	*ipif;
3897 
3898 	arh = (arh_t *)mp->b_cont->b_rptr;
3899 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3900 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3901 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3902 			(void) ipif_resolver_up(ipif, Res_act_defend);
3903 	}
3904 	freemsg(mp);
3905 }
3906 
3907 /*
3908  * News from ARP.  ARP sends notification of interesting events down
3909  * to its clients using M_CTL messages with the interesting ARP packet
3910  * attached via b_cont.
3911  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3912  * queue as opposed to ARP sending the message to all the clients, i.e. all
3913  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3914  * table if a cache IRE is found to delete all the entries for the address in
3915  * the packet.
3916  */
3917 static void
3918 ip_arp_news(queue_t *q, mblk_t *mp)
3919 {
3920 	arcn_t		*arcn;
3921 	arh_t		*arh;
3922 	ire_t		*ire = NULL;
3923 	char		hbuf[MAC_STR_LEN];
3924 	char		sbuf[INET_ADDRSTRLEN];
3925 	ipaddr_t	src;
3926 	in6_addr_t	v6src;
3927 	boolean_t	isv6 = B_FALSE;
3928 	ipif_t		*ipif;
3929 	ill_t		*ill;
3930 	ip_stack_t	*ipst;
3931 
3932 	if (CONN_Q(q)) {
3933 		conn_t *connp = Q_TO_CONN(q);
3934 
3935 		ipst = connp->conn_netstack->netstack_ip;
3936 	} else {
3937 		ill_t *ill = (ill_t *)q->q_ptr;
3938 
3939 		ipst = ill->ill_ipst;
3940 	}
3941 
3942 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3943 		if (q->q_next) {
3944 			putnext(q, mp);
3945 		} else
3946 			freemsg(mp);
3947 		return;
3948 	}
3949 	arh = (arh_t *)mp->b_cont->b_rptr;
3950 	/* Is it one we are interested in? */
3951 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3952 		isv6 = B_TRUE;
3953 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3954 		    IPV6_ADDR_LEN);
3955 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3956 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3957 		    IP_ADDR_LEN);
3958 	} else {
3959 		freemsg(mp);
3960 		return;
3961 	}
3962 
3963 	ill = q->q_ptr;
3964 
3965 	arcn = (arcn_t *)mp->b_rptr;
3966 	switch (arcn->arcn_code) {
3967 	case AR_CN_BOGON:
3968 		/*
3969 		 * Someone is sending ARP packets with a source protocol
3970 		 * address that we have published and for which we believe our
3971 		 * entry is authoritative and (when ill_arp_extend is set)
3972 		 * verified to be unique on the network.
3973 		 *
3974 		 * The ARP module internally handles the cases where the sender
3975 		 * is just probing (for DAD) and where the hardware address of
3976 		 * a non-authoritative entry has changed.  Thus, these are the
3977 		 * real conflicts, and we have to do resolution.
3978 		 *
3979 		 * We back away quickly from the address if it's from DHCP or
3980 		 * otherwise temporary and hasn't been used recently (or at
3981 		 * all).  We'd like to include "deprecated" addresses here as
3982 		 * well (as there's no real reason to defend something we're
3983 		 * discarding), but IPMP "reuses" this flag to mean something
3984 		 * other than the standard meaning.
3985 		 *
3986 		 * If the ARP module above is not extended (meaning that it
3987 		 * doesn't know how to defend the address), then we just log
3988 		 * the problem as we always did and continue on.  It's not
3989 		 * right, but there's little else we can do, and those old ATM
3990 		 * users are going away anyway.
3991 		 */
3992 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3993 		    hbuf, sizeof (hbuf));
3994 		(void) ip_dot_addr(src, sbuf);
3995 		if (isv6) {
3996 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3997 			    ipst);
3998 		} else {
3999 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4000 		}
4001 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4002 			uint32_t now;
4003 			uint32_t maxage;
4004 			clock_t lused;
4005 			uint_t maxdefense;
4006 			uint_t defs;
4007 
4008 			/*
4009 			 * First, figure out if this address hasn't been used
4010 			 * in a while.  If it hasn't, then it's a better
4011 			 * candidate for abandoning.
4012 			 */
4013 			ipif = ire->ire_ipif;
4014 			ASSERT(ipif != NULL);
4015 			now = gethrestime_sec();
4016 			maxage = now - ire->ire_create_time;
4017 			if (maxage > ipst->ips_ip_max_temp_idle)
4018 				maxage = ipst->ips_ip_max_temp_idle;
4019 			lused = drv_hztousec(ddi_get_lbolt() -
4020 			    ire->ire_last_used_time) / MICROSEC + 1;
4021 			if (lused >= maxage && (ipif->ipif_flags &
4022 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4023 				maxdefense = ipst->ips_ip_max_temp_defend;
4024 			else
4025 				maxdefense = ipst->ips_ip_max_defend;
4026 
4027 			/*
4028 			 * Now figure out how many times we've defended
4029 			 * ourselves.  Ignore defenses that happened long in
4030 			 * the past.
4031 			 */
4032 			mutex_enter(&ire->ire_lock);
4033 			if ((defs = ire->ire_defense_count) > 0 &&
4034 			    now - ire->ire_defense_time >
4035 			    ipst->ips_ip_defend_interval) {
4036 				ire->ire_defense_count = defs = 0;
4037 			}
4038 			ire->ire_defense_count++;
4039 			ire->ire_defense_time = now;
4040 			mutex_exit(&ire->ire_lock);
4041 			ill_refhold(ill);
4042 			ire_refrele(ire);
4043 
4044 			/*
4045 			 * If we've defended ourselves too many times already,
4046 			 * then give up and tear down the interface(s) using
4047 			 * this address.  Otherwise, defend by sending out a
4048 			 * gratuitous ARP.
4049 			 */
4050 			if (defs >= maxdefense && ill->ill_arp_extend) {
4051 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4052 				    B_FALSE);
4053 			} else {
4054 				cmn_err(CE_WARN,
4055 				    "node %s is using our IP address %s on %s",
4056 				    hbuf, sbuf, ill->ill_name);
4057 				/*
4058 				 * If this is an old (ATM) ARP module, then
4059 				 * don't try to defend the address.  Remain
4060 				 * compatible with the old behavior.  Defend
4061 				 * only with new ARP.
4062 				 */
4063 				if (ill->ill_arp_extend) {
4064 					qwriter_ip(ill, q, mp, ip_arp_defend,
4065 					    NEW_OP, B_FALSE);
4066 				} else {
4067 					ill_refrele(ill);
4068 				}
4069 			}
4070 			return;
4071 		}
4072 		cmn_err(CE_WARN,
4073 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4074 		    hbuf, sbuf, ill->ill_name);
4075 		if (ire != NULL)
4076 			ire_refrele(ire);
4077 		break;
4078 	case AR_CN_ANNOUNCE:
4079 		if (isv6) {
4080 			/*
4081 			 * For XRESOLV interfaces.
4082 			 * Delete the IRE cache entry and NCE for this
4083 			 * v6 address
4084 			 */
4085 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4086 			/*
4087 			 * If v6src is a non-zero, it's a router address
4088 			 * as below. Do the same sort of thing to clean
4089 			 * out off-net IRE_CACHE entries that go through
4090 			 * the router.
4091 			 */
4092 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4093 				ire_walk_v6(ire_delete_cache_gw_v6,
4094 				    (char *)&v6src, ALL_ZONES, ipst);
4095 			}
4096 		} else {
4097 			nce_hw_map_t hwm;
4098 
4099 			/*
4100 			 * ARP gives us a copy of any packet where it thinks
4101 			 * the address has changed, so that we can update our
4102 			 * caches.  We're responsible for caching known answers
4103 			 * in the current design.  We check whether the
4104 			 * hardware address really has changed in all of our
4105 			 * entries that have cached this mapping, and if so, we
4106 			 * blow them away.  This way we will immediately pick
4107 			 * up the rare case of a host changing hardware
4108 			 * address.
4109 			 */
4110 			if (src == 0)
4111 				break;
4112 			hwm.hwm_addr = src;
4113 			hwm.hwm_hwlen = arh->arh_hlen;
4114 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4115 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4116 			ndp_walk_common(ipst->ips_ndp4, NULL,
4117 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4118 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4119 		}
4120 		break;
4121 	case AR_CN_READY:
4122 		/* No external v6 resolver has a contract to use this */
4123 		if (isv6)
4124 			break;
4125 		/* If the link is down, we'll retry this later */
4126 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4127 			break;
4128 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4129 		    NULL, NULL, ipst);
4130 		if (ipif != NULL) {
4131 			/*
4132 			 * If this is a duplicate recovery, then we now need to
4133 			 * go exclusive to bring this thing back up.
4134 			 */
4135 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4136 			    IPIF_DUPLICATE) {
4137 				ipif_refrele(ipif);
4138 				ill_refhold(ill);
4139 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4140 				    B_FALSE);
4141 				return;
4142 			}
4143 			/*
4144 			 * If this is the first notice that this address is
4145 			 * ready, then let the user know now.
4146 			 */
4147 			if ((ipif->ipif_flags & IPIF_UP) &&
4148 			    !ipif->ipif_addr_ready) {
4149 				ipif_mask_reply(ipif);
4150 				ip_rts_ifmsg(ipif);
4151 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4152 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4153 			}
4154 			ipif->ipif_addr_ready = 1;
4155 			ipif_refrele(ipif);
4156 		}
4157 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4158 		if (ire != NULL) {
4159 			ire->ire_defense_count = 0;
4160 			ire_refrele(ire);
4161 		}
4162 		break;
4163 	case AR_CN_FAILED:
4164 		/* No external v6 resolver has a contract to use this */
4165 		if (isv6)
4166 			break;
4167 		ill_refhold(ill);
4168 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4169 		return;
4170 	}
4171 	freemsg(mp);
4172 }
4173 
4174 /*
4175  * Create a mblk suitable for carrying the interface index and/or source link
4176  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4177  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4178  * application.
4179  */
4180 mblk_t *
4181 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4182     ip_stack_t *ipst)
4183 {
4184 	mblk_t		*mp;
4185 	ip_pktinfo_t	*pinfo;
4186 	ipha_t *ipha;
4187 	struct ether_header *pether;
4188 
4189 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4190 	if (mp == NULL) {
4191 		ip1dbg(("ip_add_info: allocation failure.\n"));
4192 		return (data_mp);
4193 	}
4194 
4195 	ipha	= (ipha_t *)data_mp->b_rptr;
4196 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4197 	bzero(pinfo, sizeof (ip_pktinfo_t));
4198 	pinfo->ip_pkt_flags = (uchar_t)flags;
4199 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4200 
4201 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4202 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4203 	if (flags & IPF_RECVADDR) {
4204 		ipif_t	*ipif;
4205 		ire_t	*ire;
4206 
4207 		/*
4208 		 * Only valid for V4
4209 		 */
4210 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4211 		    (IPV4_VERSION << 4));
4212 
4213 		ipif = ipif_get_next_ipif(NULL, ill);
4214 		if (ipif != NULL) {
4215 			/*
4216 			 * Since a decision has already been made to deliver the
4217 			 * packet, there is no need to test for SECATTR and
4218 			 * ZONEONLY.
4219 			 * When a multicast packet is transmitted
4220 			 * a cache entry is created for the multicast address.
4221 			 * When delivering a copy of the packet or when new
4222 			 * packets are received we do not want to match on the
4223 			 * cached entry so explicitly match on
4224 			 * IRE_LOCAL and IRE_LOOPBACK
4225 			 */
4226 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4227 			    IRE_LOCAL | IRE_LOOPBACK,
4228 			    ipif, zoneid, NULL,
4229 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4230 			if (ire == NULL) {
4231 				/*
4232 				 * packet must have come on a different
4233 				 * interface.
4234 				 * Since a decision has already been made to
4235 				 * deliver the packet, there is no need to test
4236 				 * for SECATTR and ZONEONLY.
4237 				 * Only match on local and broadcast ire's.
4238 				 * See detailed comment above.
4239 				 */
4240 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4241 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4242 				    NULL, MATCH_IRE_TYPE, ipst);
4243 			}
4244 
4245 			if (ire == NULL) {
4246 				/*
4247 				 * This is either a multicast packet or
4248 				 * the address has been removed since
4249 				 * the packet was received.
4250 				 * Return INADDR_ANY so that normal source
4251 				 * selection occurs for the response.
4252 				 */
4253 
4254 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4255 			} else {
4256 				pinfo->ip_pkt_match_addr.s_addr =
4257 				    ire->ire_src_addr;
4258 				ire_refrele(ire);
4259 			}
4260 			ipif_refrele(ipif);
4261 		} else {
4262 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4263 		}
4264 	}
4265 
4266 	pether = (struct ether_header *)((char *)ipha
4267 	    - sizeof (struct ether_header));
4268 	/*
4269 	 * Make sure the interface is an ethernet type, since this option
4270 	 * is currently supported only on this type of interface. Also make
4271 	 * sure we are pointing correctly above db_base.
4272 	 */
4273 
4274 	if ((flags & IPF_RECVSLLA) &&
4275 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4276 	    (ill->ill_type == IFT_ETHER) &&
4277 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4278 
4279 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4280 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4281 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4282 	} else {
4283 		/*
4284 		 * Clear the bit. Indicate to upper layer that IP is not
4285 		 * sending this ancillary info.
4286 		 */
4287 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4288 	}
4289 
4290 	mp->b_datap->db_type = M_CTL;
4291 	mp->b_wptr += sizeof (ip_pktinfo_t);
4292 	mp->b_cont = data_mp;
4293 
4294 	return (mp);
4295 }
4296 
4297 /*
4298  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4299  * part of the bind request.
4300  */
4301 
4302 boolean_t
4303 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4304 {
4305 	ipsec_in_t *ii;
4306 
4307 	ASSERT(policy_mp != NULL);
4308 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4309 
4310 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4311 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4312 
4313 	connp->conn_policy = ii->ipsec_in_policy;
4314 	ii->ipsec_in_policy = NULL;
4315 
4316 	if (ii->ipsec_in_action != NULL) {
4317 		if (connp->conn_latch == NULL) {
4318 			connp->conn_latch = iplatch_create();
4319 			if (connp->conn_latch == NULL)
4320 				return (B_FALSE);
4321 		}
4322 		ipsec_latch_inbound(connp->conn_latch, ii);
4323 	}
4324 	return (B_TRUE);
4325 }
4326 
4327 /*
4328  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4329  * and to arrange for power-fanout assist.  The ULP is identified by
4330  * adding a single byte at the end of the original bind message.
4331  * A ULP other than UDP or TCP that wishes to be recognized passes
4332  * down a bind with a zero length address.
4333  *
4334  * The binding works as follows:
4335  * - A zero byte address means just bind to the protocol.
4336  * - A four byte address is treated as a request to validate
4337  *   that the address is a valid local address, appropriate for
4338  *   an application to bind to. This does not affect any fanout
4339  *   information in IP.
4340  * - A sizeof sin_t byte address is used to bind to only the local address
4341  *   and port.
4342  * - A sizeof ipa_conn_t byte address contains complete fanout information
4343  *   consisting of local and remote addresses and ports.  In
4344  *   this case, the addresses are both validated as appropriate
4345  *   for this operation, and, if so, the information is retained
4346  *   for use in the inbound fanout.
4347  *
4348  * The ULP (except in the zero-length bind) can append an
4349  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4350  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4351  * a copy of the source or destination IRE (source for local bind;
4352  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4353  * policy information contained should be copied on to the conn.
4354  *
4355  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4356  */
4357 mblk_t *
4358 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4359 {
4360 	ssize_t		len;
4361 	struct T_bind_req	*tbr;
4362 	sin_t		*sin;
4363 	ipa_conn_t	*ac;
4364 	uchar_t		*ucp;
4365 	mblk_t		*mp1;
4366 	boolean_t	ire_requested;
4367 	boolean_t	ipsec_policy_set = B_FALSE;
4368 	int		error = 0;
4369 	int		protocol;
4370 	ipa_conn_x_t	*acx;
4371 
4372 	ASSERT(!connp->conn_af_isv6);
4373 	connp->conn_pkt_isv6 = B_FALSE;
4374 
4375 	len = MBLKL(mp);
4376 	if (len < (sizeof (*tbr) + 1)) {
4377 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4378 		    "ip_bind: bogus msg, len %ld", len);
4379 		/* XXX: Need to return something better */
4380 		goto bad_addr;
4381 	}
4382 	/* Back up and extract the protocol identifier. */
4383 	mp->b_wptr--;
4384 	protocol = *mp->b_wptr & 0xFF;
4385 	tbr = (struct T_bind_req *)mp->b_rptr;
4386 	/* Reset the message type in preparation for shipping it back. */
4387 	DB_TYPE(mp) = M_PCPROTO;
4388 
4389 	connp->conn_ulp = (uint8_t)protocol;
4390 
4391 	/*
4392 	 * Check for a zero length address.  This is from a protocol that
4393 	 * wants to register to receive all packets of its type.
4394 	 */
4395 	if (tbr->ADDR_length == 0) {
4396 		/*
4397 		 * These protocols are now intercepted in ip_bind_v6().
4398 		 * Reject protocol-level binds here for now.
4399 		 *
4400 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4401 		 * so that the protocol type cannot be SCTP.
4402 		 */
4403 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4404 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4405 			goto bad_addr;
4406 		}
4407 
4408 		/*
4409 		 *
4410 		 * The udp module never sends down a zero-length address,
4411 		 * and allowing this on a labeled system will break MLP
4412 		 * functionality.
4413 		 */
4414 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4415 			goto bad_addr;
4416 
4417 		if (connp->conn_mac_exempt)
4418 			goto bad_addr;
4419 
4420 		/* No hash here really.  The table is big enough. */
4421 		connp->conn_srcv6 = ipv6_all_zeros;
4422 
4423 		ipcl_proto_insert(connp, protocol);
4424 
4425 		tbr->PRIM_type = T_BIND_ACK;
4426 		return (mp);
4427 	}
4428 
4429 	/* Extract the address pointer from the message. */
4430 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4431 	    tbr->ADDR_length);
4432 	if (ucp == NULL) {
4433 		ip1dbg(("ip_bind: no address\n"));
4434 		goto bad_addr;
4435 	}
4436 	if (!OK_32PTR(ucp)) {
4437 		ip1dbg(("ip_bind: unaligned address\n"));
4438 		goto bad_addr;
4439 	}
4440 	/*
4441 	 * Check for trailing mps.
4442 	 */
4443 
4444 	mp1 = mp->b_cont;
4445 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4446 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4447 
4448 	switch (tbr->ADDR_length) {
4449 	default:
4450 		ip1dbg(("ip_bind: bad address length %d\n",
4451 		    (int)tbr->ADDR_length));
4452 		goto bad_addr;
4453 
4454 	case IP_ADDR_LEN:
4455 		/* Verification of local address only */
4456 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4457 		    ire_requested, ipsec_policy_set, B_FALSE);
4458 		break;
4459 
4460 	case sizeof (sin_t):
4461 		sin = (sin_t *)ucp;
4462 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4463 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4464 		break;
4465 
4466 	case sizeof (ipa_conn_t):
4467 		ac = (ipa_conn_t *)ucp;
4468 		/* For raw socket, the local port is not set. */
4469 		if (ac->ac_lport == 0)
4470 			ac->ac_lport = connp->conn_lport;
4471 		/* Always verify destination reachability. */
4472 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4473 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4474 		    ipsec_policy_set, B_TRUE, B_TRUE);
4475 		break;
4476 
4477 	case sizeof (ipa_conn_x_t):
4478 		acx = (ipa_conn_x_t *)ucp;
4479 		/*
4480 		 * Whether or not to verify destination reachability depends
4481 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4482 		 */
4483 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4484 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4485 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4486 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4487 		break;
4488 	}
4489 	if (error == EINPROGRESS)
4490 		return (NULL);
4491 	else if (error != 0)
4492 		goto bad_addr;
4493 	/*
4494 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4495 	 * We can't do this in ip_bind_insert_ire because the policy
4496 	 * may not have been inherited at that point in time and hence
4497 	 * conn_out_enforce_policy may not be set.
4498 	 */
4499 	mp1 = mp->b_cont;
4500 	if (ire_requested && connp->conn_out_enforce_policy &&
4501 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4502 		ire_t *ire = (ire_t *)mp1->b_rptr;
4503 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4504 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4505 	}
4506 
4507 	/* Send it home. */
4508 	mp->b_datap->db_type = M_PCPROTO;
4509 	tbr->PRIM_type = T_BIND_ACK;
4510 	return (mp);
4511 
4512 bad_addr:
4513 	/*
4514 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4515 	 * a unix errno.
4516 	 */
4517 	if (error > 0)
4518 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4519 	else
4520 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4521 	return (mp);
4522 }
4523 
4524 /*
4525  * Here address is verified to be a valid local address.
4526  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4527  * address is also considered a valid local address.
4528  * In the case of a broadcast/multicast address, however, the
4529  * upper protocol is expected to reset the src address
4530  * to 0 if it sees a IRE_BROADCAST type returned so that
4531  * no packets are emitted with broadcast/multicast address as
4532  * source address (that violates hosts requirements RFC1122)
4533  * The addresses valid for bind are:
4534  *	(1) - INADDR_ANY (0)
4535  *	(2) - IP address of an UP interface
4536  *	(3) - IP address of a DOWN interface
4537  *	(4) - valid local IP broadcast addresses. In this case
4538  *	the conn will only receive packets destined to
4539  *	the specified broadcast address.
4540  *	(5) - a multicast address. In this case
4541  *	the conn will only receive packets destined to
4542  *	the specified multicast address. Note: the
4543  *	application still has to issue an
4544  *	IP_ADD_MEMBERSHIP socket option.
4545  *
4546  * On error, return -1 for TBADADDR otherwise pass the
4547  * errno with TSYSERR reply.
4548  *
4549  * In all the above cases, the bound address must be valid in the current zone.
4550  * When the address is loopback, multicast or broadcast, there might be many
4551  * matching IREs so bind has to look up based on the zone.
4552  *
4553  * Note: lport is in network byte order.
4554  */
4555 int
4556 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4557     boolean_t ire_requested, boolean_t ipsec_policy_set,
4558     boolean_t fanout_insert)
4559 {
4560 	int		error = 0;
4561 	ire_t		*src_ire;
4562 	mblk_t		*policy_mp;
4563 	ipif_t		*ipif;
4564 	zoneid_t	zoneid;
4565 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4566 
4567 	if (ipsec_policy_set) {
4568 		policy_mp = mp->b_cont;
4569 	}
4570 
4571 	/*
4572 	 * If it was previously connected, conn_fully_bound would have
4573 	 * been set.
4574 	 */
4575 	connp->conn_fully_bound = B_FALSE;
4576 
4577 	src_ire = NULL;
4578 	ipif = NULL;
4579 
4580 	zoneid = IPCL_ZONEID(connp);
4581 
4582 	if (src_addr) {
4583 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4584 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4585 		/*
4586 		 * If an address other than 0.0.0.0 is requested,
4587 		 * we verify that it is a valid address for bind
4588 		 * Note: Following code is in if-else-if form for
4589 		 * readability compared to a condition check.
4590 		 */
4591 		/* LINTED - statement has no consequent */
4592 		if (IRE_IS_LOCAL(src_ire)) {
4593 			/*
4594 			 * (2) Bind to address of local UP interface
4595 			 */
4596 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4597 			/*
4598 			 * (4) Bind to broadcast address
4599 			 * Note: permitted only from transports that
4600 			 * request IRE
4601 			 */
4602 			if (!ire_requested)
4603 				error = EADDRNOTAVAIL;
4604 		} else {
4605 			/*
4606 			 * (3) Bind to address of local DOWN interface
4607 			 * (ipif_lookup_addr() looks up all interfaces
4608 			 * but we do not get here for UP interfaces
4609 			 * - case (2) above)
4610 			 * We put the protocol byte back into the mblk
4611 			 * since we may come back via ip_wput_nondata()
4612 			 * later with this mblk if ipif_lookup_addr chooses
4613 			 * to defer processing.
4614 			 */
4615 			*mp->b_wptr++ = (char)connp->conn_ulp;
4616 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4617 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4618 			    &error, ipst)) != NULL) {
4619 				ipif_refrele(ipif);
4620 			} else if (error == EINPROGRESS) {
4621 				if (src_ire != NULL)
4622 					ire_refrele(src_ire);
4623 				return (EINPROGRESS);
4624 			} else if (CLASSD(src_addr)) {
4625 				error = 0;
4626 				if (src_ire != NULL)
4627 					ire_refrele(src_ire);
4628 				/*
4629 				 * (5) bind to multicast address.
4630 				 * Fake out the IRE returned to upper
4631 				 * layer to be a broadcast IRE.
4632 				 */
4633 				src_ire = ire_ctable_lookup(
4634 				    INADDR_BROADCAST, INADDR_ANY,
4635 				    IRE_BROADCAST, NULL, zoneid, NULL,
4636 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4637 				    ipst);
4638 				if (src_ire == NULL || !ire_requested)
4639 					error = EADDRNOTAVAIL;
4640 			} else {
4641 				/*
4642 				 * Not a valid address for bind
4643 				 */
4644 				error = EADDRNOTAVAIL;
4645 			}
4646 			/*
4647 			 * Just to keep it consistent with the processing in
4648 			 * ip_bind_v4()
4649 			 */
4650 			mp->b_wptr--;
4651 		}
4652 		if (error) {
4653 			/* Red Alert!  Attempting to be a bogon! */
4654 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4655 			    ntohl(src_addr)));
4656 			goto bad_addr;
4657 		}
4658 	}
4659 
4660 	/*
4661 	 * Allow setting new policies. For example, disconnects come
4662 	 * down as ipa_t bind. As we would have set conn_policy_cached
4663 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4664 	 * can change after the disconnect.
4665 	 */
4666 	connp->conn_policy_cached = B_FALSE;
4667 
4668 	/*
4669 	 * If not fanout_insert this was just an address verification
4670 	 */
4671 	if (fanout_insert) {
4672 		/*
4673 		 * The addresses have been verified. Time to insert in
4674 		 * the correct fanout list.
4675 		 */
4676 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4677 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4678 		connp->conn_lport = lport;
4679 		connp->conn_fport = 0;
4680 		/*
4681 		 * Do we need to add a check to reject Multicast packets
4682 		 */
4683 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4684 	}
4685 
4686 	if (error == 0) {
4687 		if (ire_requested) {
4688 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4689 				error = -1;
4690 				/* Falls through to bad_addr */
4691 			}
4692 		} else if (ipsec_policy_set) {
4693 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4694 				error = -1;
4695 				/* Falls through to bad_addr */
4696 			}
4697 		}
4698 	}
4699 bad_addr:
4700 	if (error != 0) {
4701 		if (connp->conn_anon_port) {
4702 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4703 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4704 			    B_FALSE);
4705 		}
4706 		connp->conn_mlp_type = mlptSingle;
4707 	}
4708 	if (src_ire != NULL)
4709 		IRE_REFRELE(src_ire);
4710 	if (ipsec_policy_set) {
4711 		ASSERT(policy_mp == mp->b_cont);
4712 		ASSERT(policy_mp != NULL);
4713 		freeb(policy_mp);
4714 		/*
4715 		 * As of now assume that nothing else accompanies
4716 		 * IPSEC_POLICY_SET.
4717 		 */
4718 		mp->b_cont = NULL;
4719 	}
4720 	return (error);
4721 }
4722 
4723 /*
4724  * Verify that both the source and destination addresses
4725  * are valid.  If verify_dst is false, then the destination address may be
4726  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4727  * destination reachability, while tunnels do not.
4728  * Note that we allow connect to broadcast and multicast
4729  * addresses when ire_requested is set. Thus the ULP
4730  * has to check for IRE_BROADCAST and multicast.
4731  *
4732  * Returns zero if ok.
4733  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4734  * (for use with TSYSERR reply).
4735  *
4736  * Note: lport and fport are in network byte order.
4737  */
4738 int
4739 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4740     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4741     boolean_t ire_requested, boolean_t ipsec_policy_set,
4742     boolean_t fanout_insert, boolean_t verify_dst)
4743 {
4744 	ire_t		*src_ire;
4745 	ire_t		*dst_ire;
4746 	int		error = 0;
4747 	int 		protocol;
4748 	mblk_t		*policy_mp;
4749 	ire_t		*sire = NULL;
4750 	ire_t		*md_dst_ire = NULL;
4751 	ire_t		*lso_dst_ire = NULL;
4752 	ill_t		*ill = NULL;
4753 	zoneid_t	zoneid;
4754 	ipaddr_t	src_addr = *src_addrp;
4755 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4756 
4757 	src_ire = dst_ire = NULL;
4758 	protocol = *mp->b_wptr & 0xFF;
4759 
4760 	/*
4761 	 * If we never got a disconnect before, clear it now.
4762 	 */
4763 	connp->conn_fully_bound = B_FALSE;
4764 
4765 	if (ipsec_policy_set) {
4766 		policy_mp = mp->b_cont;
4767 	}
4768 
4769 	zoneid = IPCL_ZONEID(connp);
4770 
4771 	if (CLASSD(dst_addr)) {
4772 		/* Pick up an IRE_BROADCAST */
4773 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4774 		    NULL, zoneid, MBLK_GETLABEL(mp),
4775 		    (MATCH_IRE_RECURSIVE |
4776 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4777 		    MATCH_IRE_SECATTR), ipst);
4778 	} else {
4779 		/*
4780 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4781 		 * and onlink ipif is not found set ENETUNREACH error.
4782 		 */
4783 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4784 			ipif_t *ipif;
4785 
4786 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4787 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4788 			if (ipif == NULL) {
4789 				error = ENETUNREACH;
4790 				goto bad_addr;
4791 			}
4792 			ipif_refrele(ipif);
4793 		}
4794 
4795 		if (connp->conn_nexthop_set) {
4796 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4797 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4798 			    MATCH_IRE_SECATTR, ipst);
4799 		} else {
4800 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4801 			    &sire, zoneid, MBLK_GETLABEL(mp),
4802 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4803 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4804 			    MATCH_IRE_SECATTR), ipst);
4805 		}
4806 	}
4807 	/*
4808 	 * dst_ire can't be a broadcast when not ire_requested.
4809 	 * We also prevent ire's with src address INADDR_ANY to
4810 	 * be used, which are created temporarily for
4811 	 * sending out packets from endpoints that have
4812 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4813 	 * reachable.  If verify_dst is false, the destination needn't be
4814 	 * reachable.
4815 	 *
4816 	 * If we match on a reject or black hole, then we've got a
4817 	 * local failure.  May as well fail out the connect() attempt,
4818 	 * since it's never going to succeed.
4819 	 */
4820 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4821 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4822 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4823 		/*
4824 		 * If we're verifying destination reachability, we always want
4825 		 * to complain here.
4826 		 *
4827 		 * If we're not verifying destination reachability but the
4828 		 * destination has a route, we still want to fail on the
4829 		 * temporary address and broadcast address tests.
4830 		 */
4831 		if (verify_dst || (dst_ire != NULL)) {
4832 			if (ip_debug > 2) {
4833 				pr_addr_dbg("ip_bind_connected: bad connected "
4834 				    "dst %s\n", AF_INET, &dst_addr);
4835 			}
4836 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4837 				error = ENETUNREACH;
4838 			else
4839 				error = EHOSTUNREACH;
4840 			goto bad_addr;
4841 		}
4842 	}
4843 
4844 	/*
4845 	 * We now know that routing will allow us to reach the destination.
4846 	 * Check whether Trusted Solaris policy allows communication with this
4847 	 * host, and pretend that the destination is unreachable if not.
4848 	 *
4849 	 * This is never a problem for TCP, since that transport is known to
4850 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4851 	 * handling.  If the remote is unreachable, it will be detected at that
4852 	 * point, so there's no reason to check it here.
4853 	 *
4854 	 * Note that for sendto (and other datagram-oriented friends), this
4855 	 * check is done as part of the data path label computation instead.
4856 	 * The check here is just to make non-TCP connect() report the right
4857 	 * error.
4858 	 */
4859 	if (dst_ire != NULL && is_system_labeled() &&
4860 	    !IPCL_IS_TCP(connp) &&
4861 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4862 	    connp->conn_mac_exempt, ipst) != 0) {
4863 		error = EHOSTUNREACH;
4864 		if (ip_debug > 2) {
4865 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4866 			    AF_INET, &dst_addr);
4867 		}
4868 		goto bad_addr;
4869 	}
4870 
4871 	/*
4872 	 * If the app does a connect(), it means that it will most likely
4873 	 * send more than 1 packet to the destination.  It makes sense
4874 	 * to clear the temporary flag.
4875 	 */
4876 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4877 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4878 		irb_t *irb = dst_ire->ire_bucket;
4879 
4880 		rw_enter(&irb->irb_lock, RW_WRITER);
4881 		/*
4882 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4883 		 * the lock to guarantee irb_tmp_ire_cnt.
4884 		 */
4885 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4886 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4887 			irb->irb_tmp_ire_cnt--;
4888 		}
4889 		rw_exit(&irb->irb_lock);
4890 	}
4891 
4892 	/*
4893 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4894 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4895 	 * eligibility tests for passive connects are handled separately
4896 	 * through tcp_adapt_ire().  We do this before the source address
4897 	 * selection, because dst_ire may change after a call to
4898 	 * ipif_select_source().  This is a best-effort check, as the
4899 	 * packet for this connection may not actually go through
4900 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4901 	 * calling ip_newroute().  This is why we further check on the
4902 	 * IRE during LSO/Multidata packet transmission in
4903 	 * tcp_lsosend()/tcp_multisend().
4904 	 */
4905 	if (!ipsec_policy_set && dst_ire != NULL &&
4906 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4907 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4908 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4909 			lso_dst_ire = dst_ire;
4910 			IRE_REFHOLD(lso_dst_ire);
4911 		} else if (ipst->ips_ip_multidata_outbound &&
4912 		    ILL_MDT_CAPABLE(ill)) {
4913 			md_dst_ire = dst_ire;
4914 			IRE_REFHOLD(md_dst_ire);
4915 		}
4916 	}
4917 
4918 	if (dst_ire != NULL &&
4919 	    dst_ire->ire_type == IRE_LOCAL &&
4920 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4921 		/*
4922 		 * If the IRE belongs to a different zone, look for a matching
4923 		 * route in the forwarding table and use the source address from
4924 		 * that route.
4925 		 */
4926 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4927 		    zoneid, 0, NULL,
4928 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4929 		    MATCH_IRE_RJ_BHOLE, ipst);
4930 		if (src_ire == NULL) {
4931 			error = EHOSTUNREACH;
4932 			goto bad_addr;
4933 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4934 			if (!(src_ire->ire_type & IRE_HOST))
4935 				error = ENETUNREACH;
4936 			else
4937 				error = EHOSTUNREACH;
4938 			goto bad_addr;
4939 		}
4940 		if (src_addr == INADDR_ANY)
4941 			src_addr = src_ire->ire_src_addr;
4942 		ire_refrele(src_ire);
4943 		src_ire = NULL;
4944 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4945 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4946 			src_addr = sire->ire_src_addr;
4947 			ire_refrele(dst_ire);
4948 			dst_ire = sire;
4949 			sire = NULL;
4950 		} else {
4951 			/*
4952 			 * Pick a source address so that a proper inbound
4953 			 * load spreading would happen.
4954 			 */
4955 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4956 			ipif_t *src_ipif = NULL;
4957 			ire_t *ipif_ire;
4958 
4959 			/*
4960 			 * Supply a local source address such that inbound
4961 			 * load spreading happens.
4962 			 *
4963 			 * Determine the best source address on this ill for
4964 			 * the destination.
4965 			 *
4966 			 * 1) For broadcast, we should return a broadcast ire
4967 			 *    found above so that upper layers know that the
4968 			 *    destination address is a broadcast address.
4969 			 *
4970 			 * 2) If this is part of a group, select a better
4971 			 *    source address so that better inbound load
4972 			 *    balancing happens. Do the same if the ipif
4973 			 *    is DEPRECATED.
4974 			 *
4975 			 * 3) If the outgoing interface is part of a usesrc
4976 			 *    group, then try selecting a source address from
4977 			 *    the usesrc ILL.
4978 			 */
4979 			if ((dst_ire->ire_zoneid != zoneid &&
4980 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4981 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4982 			    ((dst_ill->ill_group != NULL) ||
4983 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4984 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4985 				/*
4986 				 * If the destination is reachable via a
4987 				 * given gateway, the selected source address
4988 				 * should be in the same subnet as the gateway.
4989 				 * Otherwise, the destination is not reachable.
4990 				 *
4991 				 * If there are no interfaces on the same subnet
4992 				 * as the destination, ipif_select_source gives
4993 				 * first non-deprecated interface which might be
4994 				 * on a different subnet than the gateway.
4995 				 * This is not desirable. Hence pass the dst_ire
4996 				 * source address to ipif_select_source.
4997 				 * It is sure that the destination is reachable
4998 				 * with the dst_ire source address subnet.
4999 				 * So passing dst_ire source address to
5000 				 * ipif_select_source will make sure that the
5001 				 * selected source will be on the same subnet
5002 				 * as dst_ire source address.
5003 				 */
5004 				ipaddr_t saddr =
5005 				    dst_ire->ire_ipif->ipif_src_addr;
5006 				src_ipif = ipif_select_source(dst_ill,
5007 				    saddr, zoneid);
5008 				if (src_ipif != NULL) {
5009 					if (IS_VNI(src_ipif->ipif_ill)) {
5010 						/*
5011 						 * For VNI there is no
5012 						 * interface route
5013 						 */
5014 						src_addr =
5015 						    src_ipif->ipif_src_addr;
5016 					} else {
5017 						ipif_ire =
5018 						    ipif_to_ire(src_ipif);
5019 						if (ipif_ire != NULL) {
5020 							IRE_REFRELE(dst_ire);
5021 							dst_ire = ipif_ire;
5022 						}
5023 						src_addr =
5024 						    dst_ire->ire_src_addr;
5025 					}
5026 					ipif_refrele(src_ipif);
5027 				} else {
5028 					src_addr = dst_ire->ire_src_addr;
5029 				}
5030 			} else {
5031 				src_addr = dst_ire->ire_src_addr;
5032 			}
5033 		}
5034 	}
5035 
5036 	/*
5037 	 * We do ire_route_lookup() here (and not
5038 	 * interface lookup as we assert that
5039 	 * src_addr should only come from an
5040 	 * UP interface for hard binding.
5041 	 */
5042 	ASSERT(src_ire == NULL);
5043 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5044 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5045 	/* src_ire must be a local|loopback */
5046 	if (!IRE_IS_LOCAL(src_ire)) {
5047 		if (ip_debug > 2) {
5048 			pr_addr_dbg("ip_bind_connected: bad connected "
5049 			    "src %s\n", AF_INET, &src_addr);
5050 		}
5051 		error = EADDRNOTAVAIL;
5052 		goto bad_addr;
5053 	}
5054 
5055 	/*
5056 	 * If the source address is a loopback address, the
5057 	 * destination had best be local or multicast.
5058 	 * The transports that can't handle multicast will reject
5059 	 * those addresses.
5060 	 */
5061 	if (src_ire->ire_type == IRE_LOOPBACK &&
5062 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5063 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5064 		error = -1;
5065 		goto bad_addr;
5066 	}
5067 
5068 	/*
5069 	 * Allow setting new policies. For example, disconnects come
5070 	 * down as ipa_t bind. As we would have set conn_policy_cached
5071 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5072 	 * can change after the disconnect.
5073 	 */
5074 	connp->conn_policy_cached = B_FALSE;
5075 
5076 	/*
5077 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5078 	 * can handle their passed-in conn's.
5079 	 */
5080 
5081 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5082 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5083 	connp->conn_lport = lport;
5084 	connp->conn_fport = fport;
5085 	*src_addrp = src_addr;
5086 
5087 	ASSERT(!(ipsec_policy_set && ire_requested));
5088 	if (ire_requested) {
5089 		iulp_t *ulp_info = NULL;
5090 
5091 		/*
5092 		 * Note that sire will not be NULL if this is an off-link
5093 		 * connection and there is not cache for that dest yet.
5094 		 *
5095 		 * XXX Because of an existing bug, if there are multiple
5096 		 * default routes, the IRE returned now may not be the actual
5097 		 * default route used (default routes are chosen in a
5098 		 * round robin fashion).  So if the metrics for different
5099 		 * default routes are different, we may return the wrong
5100 		 * metrics.  This will not be a problem if the existing
5101 		 * bug is fixed.
5102 		 */
5103 		if (sire != NULL) {
5104 			ulp_info = &(sire->ire_uinfo);
5105 		}
5106 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5107 			error = -1;
5108 			goto bad_addr;
5109 		}
5110 	} else if (ipsec_policy_set) {
5111 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5112 			error = -1;
5113 			goto bad_addr;
5114 		}
5115 	}
5116 
5117 	/*
5118 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5119 	 * we'll cache that.  If we don't, we'll inherit global policy.
5120 	 *
5121 	 * We can't insert until the conn reflects the policy. Note that
5122 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5123 	 * connections where we don't have a policy. This is to prevent
5124 	 * global policy lookups in the inbound path.
5125 	 *
5126 	 * If we insert before we set conn_policy_cached,
5127 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5128 	 * because global policy cound be non-empty. We normally call
5129 	 * ipsec_check_policy() for conn_policy_cached connections only if
5130 	 * ipc_in_enforce_policy is set. But in this case,
5131 	 * conn_policy_cached can get set anytime since we made the
5132 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5133 	 * called, which will make the above assumption false.  Thus, we
5134 	 * need to insert after we set conn_policy_cached.
5135 	 */
5136 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5137 		goto bad_addr;
5138 
5139 	if (fanout_insert) {
5140 		/*
5141 		 * The addresses have been verified. Time to insert in
5142 		 * the correct fanout list.
5143 		 */
5144 		error = ipcl_conn_insert(connp, protocol, src_addr,
5145 		    dst_addr, connp->conn_ports);
5146 	}
5147 
5148 	if (error == 0) {
5149 		connp->conn_fully_bound = B_TRUE;
5150 		/*
5151 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5152 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5153 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5154 		 * ip_xxinfo_return(), which performs further checks
5155 		 * against them and upon success, returns the LSO/MDT info
5156 		 * mblk which we will attach to the bind acknowledgment.
5157 		 */
5158 		if (lso_dst_ire != NULL) {
5159 			mblk_t *lsoinfo_mp;
5160 
5161 			ASSERT(ill->ill_lso_capab != NULL);
5162 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5163 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5164 				linkb(mp, lsoinfo_mp);
5165 		} else if (md_dst_ire != NULL) {
5166 			mblk_t *mdinfo_mp;
5167 
5168 			ASSERT(ill->ill_mdt_capab != NULL);
5169 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5170 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5171 				linkb(mp, mdinfo_mp);
5172 		}
5173 	}
5174 bad_addr:
5175 	if (ipsec_policy_set) {
5176 		ASSERT(policy_mp == mp->b_cont);
5177 		ASSERT(policy_mp != NULL);
5178 		freeb(policy_mp);
5179 		/*
5180 		 * As of now assume that nothing else accompanies
5181 		 * IPSEC_POLICY_SET.
5182 		 */
5183 		mp->b_cont = NULL;
5184 	}
5185 	if (src_ire != NULL)
5186 		IRE_REFRELE(src_ire);
5187 	if (dst_ire != NULL)
5188 		IRE_REFRELE(dst_ire);
5189 	if (sire != NULL)
5190 		IRE_REFRELE(sire);
5191 	if (md_dst_ire != NULL)
5192 		IRE_REFRELE(md_dst_ire);
5193 	if (lso_dst_ire != NULL)
5194 		IRE_REFRELE(lso_dst_ire);
5195 	return (error);
5196 }
5197 
5198 /*
5199  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5200  * Prefers dst_ire over src_ire.
5201  */
5202 static boolean_t
5203 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5204 {
5205 	mblk_t	*mp1;
5206 	ire_t *ret_ire = NULL;
5207 
5208 	mp1 = mp->b_cont;
5209 	ASSERT(mp1 != NULL);
5210 
5211 	if (ire != NULL) {
5212 		/*
5213 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5214 		 * appended mblk. Its <upper protocol>'s
5215 		 * job to make sure there is room.
5216 		 */
5217 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5218 			return (0);
5219 
5220 		mp1->b_datap->db_type = IRE_DB_TYPE;
5221 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5222 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5223 		ret_ire = (ire_t *)mp1->b_rptr;
5224 		/*
5225 		 * Pass the latest setting of the ip_path_mtu_discovery and
5226 		 * copy the ulp info if any.
5227 		 */
5228 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5229 		    IPH_DF : 0;
5230 		if (ulp_info != NULL) {
5231 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5232 			    sizeof (iulp_t));
5233 		}
5234 		ret_ire->ire_mp = mp1;
5235 	} else {
5236 		/*
5237 		 * No IRE was found. Remove IRE mblk.
5238 		 */
5239 		mp->b_cont = mp1->b_cont;
5240 		freeb(mp1);
5241 	}
5242 
5243 	return (1);
5244 }
5245 
5246 /*
5247  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5248  * the final piece where we don't.  Return a pointer to the first mblk in the
5249  * result, and update the pointer to the next mblk to chew on.  If anything
5250  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5251  * NULL pointer.
5252  */
5253 mblk_t *
5254 ip_carve_mp(mblk_t **mpp, ssize_t len)
5255 {
5256 	mblk_t	*mp0;
5257 	mblk_t	*mp1;
5258 	mblk_t	*mp2;
5259 
5260 	if (!len || !mpp || !(mp0 = *mpp))
5261 		return (NULL);
5262 	/* If we aren't going to consume the first mblk, we need a dup. */
5263 	if (mp0->b_wptr - mp0->b_rptr > len) {
5264 		mp1 = dupb(mp0);
5265 		if (mp1) {
5266 			/* Partition the data between the two mblks. */
5267 			mp1->b_wptr = mp1->b_rptr + len;
5268 			mp0->b_rptr = mp1->b_wptr;
5269 			/*
5270 			 * after adjustments if mblk not consumed is now
5271 			 * unaligned, try to align it. If this fails free
5272 			 * all messages and let upper layer recover.
5273 			 */
5274 			if (!OK_32PTR(mp0->b_rptr)) {
5275 				if (!pullupmsg(mp0, -1)) {
5276 					freemsg(mp0);
5277 					freemsg(mp1);
5278 					*mpp = NULL;
5279 					return (NULL);
5280 				}
5281 			}
5282 		}
5283 		return (mp1);
5284 	}
5285 	/* Eat through as many mblks as we need to get len bytes. */
5286 	len -= mp0->b_wptr - mp0->b_rptr;
5287 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5288 		if (mp2->b_wptr - mp2->b_rptr > len) {
5289 			/*
5290 			 * We won't consume the entire last mblk.  Like
5291 			 * above, dup and partition it.
5292 			 */
5293 			mp1->b_cont = dupb(mp2);
5294 			mp1 = mp1->b_cont;
5295 			if (!mp1) {
5296 				/*
5297 				 * Trouble.  Rather than go to a lot of
5298 				 * trouble to clean up, we free the messages.
5299 				 * This won't be any worse than losing it on
5300 				 * the wire.
5301 				 */
5302 				freemsg(mp0);
5303 				freemsg(mp2);
5304 				*mpp = NULL;
5305 				return (NULL);
5306 			}
5307 			mp1->b_wptr = mp1->b_rptr + len;
5308 			mp2->b_rptr = mp1->b_wptr;
5309 			/*
5310 			 * after adjustments if mblk not consumed is now
5311 			 * unaligned, try to align it. If this fails free
5312 			 * all messages and let upper layer recover.
5313 			 */
5314 			if (!OK_32PTR(mp2->b_rptr)) {
5315 				if (!pullupmsg(mp2, -1)) {
5316 					freemsg(mp0);
5317 					freemsg(mp2);
5318 					*mpp = NULL;
5319 					return (NULL);
5320 				}
5321 			}
5322 			*mpp = mp2;
5323 			return (mp0);
5324 		}
5325 		/* Decrement len by the amount we just got. */
5326 		len -= mp2->b_wptr - mp2->b_rptr;
5327 	}
5328 	/*
5329 	 * len should be reduced to zero now.  If not our caller has
5330 	 * screwed up.
5331 	 */
5332 	if (len) {
5333 		/* Shouldn't happen! */
5334 		freemsg(mp0);
5335 		*mpp = NULL;
5336 		return (NULL);
5337 	}
5338 	/*
5339 	 * We consumed up to exactly the end of an mblk.  Detach the part
5340 	 * we are returning from the rest of the chain.
5341 	 */
5342 	mp1->b_cont = NULL;
5343 	*mpp = mp2;
5344 	return (mp0);
5345 }
5346 
5347 /* The ill stream is being unplumbed. Called from ip_close */
5348 int
5349 ip_modclose(ill_t *ill)
5350 {
5351 	boolean_t success;
5352 	ipsq_t	*ipsq;
5353 	ipif_t	*ipif;
5354 	queue_t	*q = ill->ill_rq;
5355 	ip_stack_t	*ipst = ill->ill_ipst;
5356 	clock_t timeout;
5357 
5358 	/*
5359 	 * Wait for the ACKs of all deferred control messages to be processed.
5360 	 * In particular, we wait for a potential capability reset initiated
5361 	 * in ip_sioctl_plink() to complete before proceeding.
5362 	 *
5363 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5364 	 * in case the driver never replies.
5365 	 */
5366 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5367 	mutex_enter(&ill->ill_lock);
5368 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5369 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5370 			/* Timeout */
5371 			break;
5372 		}
5373 	}
5374 	mutex_exit(&ill->ill_lock);
5375 
5376 	/*
5377 	 * Forcibly enter the ipsq after some delay. This is to take
5378 	 * care of the case when some ioctl does not complete because
5379 	 * we sent a control message to the driver and it did not
5380 	 * send us a reply. We want to be able to at least unplumb
5381 	 * and replumb rather than force the user to reboot the system.
5382 	 */
5383 	success = ipsq_enter(ill, B_FALSE);
5384 
5385 	/*
5386 	 * Open/close/push/pop is guaranteed to be single threaded
5387 	 * per stream by STREAMS. FS guarantees that all references
5388 	 * from top are gone before close is called. So there can't
5389 	 * be another close thread that has set CONDEMNED on this ill.
5390 	 * and cause ipsq_enter to return failure.
5391 	 */
5392 	ASSERT(success);
5393 	ipsq = ill->ill_phyint->phyint_ipsq;
5394 
5395 	/*
5396 	 * Mark it condemned. No new reference will be made to this ill.
5397 	 * Lookup functions will return an error. Threads that try to
5398 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5399 	 * that the refcnt will drop down to zero.
5400 	 */
5401 	mutex_enter(&ill->ill_lock);
5402 	ill->ill_state_flags |= ILL_CONDEMNED;
5403 	for (ipif = ill->ill_ipif; ipif != NULL;
5404 	    ipif = ipif->ipif_next) {
5405 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5406 	}
5407 	/*
5408 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5409 	 * returns  error if ILL_CONDEMNED is set
5410 	 */
5411 	cv_broadcast(&ill->ill_cv);
5412 	mutex_exit(&ill->ill_lock);
5413 
5414 	/*
5415 	 * Send all the deferred DLPI messages downstream which came in
5416 	 * during the small window right before ipsq_enter(). We do this
5417 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5418 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5419 	 */
5420 	ill_dlpi_send_deferred(ill);
5421 
5422 	/*
5423 	 * Shut down fragmentation reassembly.
5424 	 * ill_frag_timer won't start a timer again.
5425 	 * Now cancel any existing timer
5426 	 */
5427 	(void) untimeout(ill->ill_frag_timer_id);
5428 	(void) ill_frag_timeout(ill, 0);
5429 
5430 	/*
5431 	 * If MOVE was in progress, clear the
5432 	 * move_in_progress fields also.
5433 	 */
5434 	if (ill->ill_move_in_progress) {
5435 		ILL_CLEAR_MOVE(ill);
5436 	}
5437 
5438 	/*
5439 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5440 	 * this ill. Then wait for the refcnts to drop to zero.
5441 	 * ill_is_quiescent checks whether the ill is really quiescent.
5442 	 * Then make sure that threads that are waiting to enter the
5443 	 * ipsq have seen the error returned by ipsq_enter and have
5444 	 * gone away. Then we call ill_delete_tail which does the
5445 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5446 	 */
5447 	ill_delete(ill);
5448 	mutex_enter(&ill->ill_lock);
5449 	while (!ill_is_quiescent(ill))
5450 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5451 	while (ill->ill_waiters)
5452 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5453 
5454 	mutex_exit(&ill->ill_lock);
5455 
5456 	/*
5457 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5458 	 * it held until the end of the function since the cleanup
5459 	 * below needs to be able to use the ip_stack_t.
5460 	 */
5461 	netstack_hold(ipst->ips_netstack);
5462 
5463 	/* qprocsoff is called in ill_delete_tail */
5464 	ill_delete_tail(ill);
5465 	ASSERT(ill->ill_ipst == NULL);
5466 
5467 	/*
5468 	 * Walk through all upper (conn) streams and qenable
5469 	 * those that have queued data.
5470 	 * close synchronization needs this to
5471 	 * be done to ensure that all upper layers blocked
5472 	 * due to flow control to the closing device
5473 	 * get unblocked.
5474 	 */
5475 	ip1dbg(("ip_wsrv: walking\n"));
5476 	conn_walk_drain(ipst);
5477 
5478 	mutex_enter(&ipst->ips_ip_mi_lock);
5479 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5480 	mutex_exit(&ipst->ips_ip_mi_lock);
5481 
5482 	/*
5483 	 * credp could be null if the open didn't succeed and ip_modopen
5484 	 * itself calls ip_close.
5485 	 */
5486 	if (ill->ill_credp != NULL)
5487 		crfree(ill->ill_credp);
5488 
5489 	mutex_enter(&ill->ill_lock);
5490 	ill_nic_info_dispatch(ill);
5491 	mutex_exit(&ill->ill_lock);
5492 
5493 	/*
5494 	 * Now we are done with the module close pieces that
5495 	 * need the netstack_t.
5496 	 */
5497 	netstack_rele(ipst->ips_netstack);
5498 
5499 	mi_close_free((IDP)ill);
5500 	q->q_ptr = WR(q)->q_ptr = NULL;
5501 
5502 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5503 
5504 	return (0);
5505 }
5506 
5507 /*
5508  * This is called as part of close() for IP, UDP, ICMP, and RTS
5509  * in order to quiesce the conn.
5510  */
5511 void
5512 ip_quiesce_conn(conn_t *connp)
5513 {
5514 	boolean_t	drain_cleanup_reqd = B_FALSE;
5515 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5516 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5517 	ip_stack_t	*ipst;
5518 
5519 	ASSERT(!IPCL_IS_TCP(connp));
5520 	ipst = connp->conn_netstack->netstack_ip;
5521 
5522 	/*
5523 	 * Mark the conn as closing, and this conn must not be
5524 	 * inserted in future into any list. Eg. conn_drain_insert(),
5525 	 * won't insert this conn into the conn_drain_list.
5526 	 * Similarly ill_pending_mp_add() will not add any mp to
5527 	 * the pending mp list, after this conn has started closing.
5528 	 *
5529 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5530 	 * cannot get set henceforth.
5531 	 */
5532 	mutex_enter(&connp->conn_lock);
5533 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5534 	connp->conn_state_flags |= CONN_CLOSING;
5535 	if (connp->conn_idl != NULL)
5536 		drain_cleanup_reqd = B_TRUE;
5537 	if (connp->conn_oper_pending_ill != NULL)
5538 		conn_ioctl_cleanup_reqd = B_TRUE;
5539 	if (connp->conn_dhcpinit_ill != NULL) {
5540 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5541 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5542 		connp->conn_dhcpinit_ill = NULL;
5543 	}
5544 	if (connp->conn_ilg_inuse != 0)
5545 		ilg_cleanup_reqd = B_TRUE;
5546 	mutex_exit(&connp->conn_lock);
5547 
5548 	if (conn_ioctl_cleanup_reqd)
5549 		conn_ioctl_cleanup(connp);
5550 
5551 	if (is_system_labeled() && connp->conn_anon_port) {
5552 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5553 		    connp->conn_mlp_type, connp->conn_ulp,
5554 		    ntohs(connp->conn_lport), B_FALSE);
5555 		connp->conn_anon_port = 0;
5556 	}
5557 	connp->conn_mlp_type = mlptSingle;
5558 
5559 	/*
5560 	 * Remove this conn from any fanout list it is on.
5561 	 * and then wait for any threads currently operating
5562 	 * on this endpoint to finish
5563 	 */
5564 	ipcl_hash_remove(connp);
5565 
5566 	/*
5567 	 * Remove this conn from the drain list, and do
5568 	 * any other cleanup that may be required.
5569 	 * (Only non-tcp streams may have a non-null conn_idl.
5570 	 * TCP streams are never flow controlled, and
5571 	 * conn_idl will be null)
5572 	 */
5573 	if (drain_cleanup_reqd)
5574 		conn_drain_tail(connp, B_TRUE);
5575 
5576 	if (connp == ipst->ips_ip_g_mrouter)
5577 		(void) ip_mrouter_done(NULL, ipst);
5578 
5579 	if (ilg_cleanup_reqd)
5580 		ilg_delete_all(connp);
5581 
5582 	conn_delete_ire(connp, NULL);
5583 
5584 	/*
5585 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5586 	 * callers from write side can't be there now because close
5587 	 * is in progress. The only other caller is ipcl_walk
5588 	 * which checks for the condemned flag.
5589 	 */
5590 	mutex_enter(&connp->conn_lock);
5591 	connp->conn_state_flags |= CONN_CONDEMNED;
5592 	while (connp->conn_ref != 1)
5593 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5594 	connp->conn_state_flags |= CONN_QUIESCED;
5595 	mutex_exit(&connp->conn_lock);
5596 }
5597 
5598 /* ARGSUSED */
5599 int
5600 ip_close(queue_t *q, int flags)
5601 {
5602 	conn_t		*connp;
5603 
5604 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5605 
5606 	/*
5607 	 * Call the appropriate delete routine depending on whether this is
5608 	 * a module or device.
5609 	 */
5610 	if (WR(q)->q_next != NULL) {
5611 		/* This is a module close */
5612 		return (ip_modclose((ill_t *)q->q_ptr));
5613 	}
5614 
5615 	connp = q->q_ptr;
5616 	ip_quiesce_conn(connp);
5617 
5618 	qprocsoff(q);
5619 
5620 	/*
5621 	 * Now we are truly single threaded on this stream, and can
5622 	 * delete the things hanging off the connp, and finally the connp.
5623 	 * We removed this connp from the fanout list, it cannot be
5624 	 * accessed thru the fanouts, and we already waited for the
5625 	 * conn_ref to drop to 0. We are already in close, so
5626 	 * there cannot be any other thread from the top. qprocsoff
5627 	 * has completed, and service has completed or won't run in
5628 	 * future.
5629 	 */
5630 	ASSERT(connp->conn_ref == 1);
5631 
5632 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5633 
5634 	connp->conn_ref--;
5635 	ipcl_conn_destroy(connp);
5636 
5637 	q->q_ptr = WR(q)->q_ptr = NULL;
5638 	return (0);
5639 }
5640 
5641 /*
5642  * Wapper around putnext() so that ip_rts_request can merely use
5643  * conn_recv.
5644  */
5645 /*ARGSUSED2*/
5646 static void
5647 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5648 {
5649 	conn_t *connp = (conn_t *)arg1;
5650 
5651 	putnext(connp->conn_rq, mp);
5652 }
5653 
5654 /* Return the IP checksum for the IP header at "iph". */
5655 uint16_t
5656 ip_csum_hdr(ipha_t *ipha)
5657 {
5658 	uint16_t	*uph;
5659 	uint32_t	sum;
5660 	int		opt_len;
5661 
5662 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5663 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5664 	uph = (uint16_t *)ipha;
5665 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5666 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5667 	if (opt_len > 0) {
5668 		do {
5669 			sum += uph[10];
5670 			sum += uph[11];
5671 			uph += 2;
5672 		} while (--opt_len);
5673 	}
5674 	sum = (sum & 0xFFFF) + (sum >> 16);
5675 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5676 	if (sum == 0xffff)
5677 		sum = 0;
5678 	return ((uint16_t)sum);
5679 }
5680 
5681 /*
5682  * Called when the module is about to be unloaded
5683  */
5684 void
5685 ip_ddi_destroy(void)
5686 {
5687 	tnet_fini();
5688 
5689 	icmp_ddi_destroy();
5690 	rts_ddi_destroy();
5691 	udp_ddi_destroy();
5692 	sctp_ddi_g_destroy();
5693 	tcp_ddi_g_destroy();
5694 	ipsec_policy_g_destroy();
5695 	ipcl_g_destroy();
5696 	ip_net_g_destroy();
5697 	ip_ire_g_fini();
5698 	inet_minor_destroy(ip_minor_arena_sa);
5699 #if defined(_LP64)
5700 	inet_minor_destroy(ip_minor_arena_la);
5701 #endif
5702 
5703 #ifdef DEBUG
5704 	list_destroy(&ip_thread_list);
5705 	rw_destroy(&ip_thread_rwlock);
5706 	tsd_destroy(&ip_thread_data);
5707 #endif
5708 
5709 	netstack_unregister(NS_IP);
5710 }
5711 
5712 /*
5713  * First step in cleanup.
5714  */
5715 /* ARGSUSED */
5716 static void
5717 ip_stack_shutdown(netstackid_t stackid, void *arg)
5718 {
5719 	ip_stack_t *ipst = (ip_stack_t *)arg;
5720 
5721 #ifdef NS_DEBUG
5722 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5723 #endif
5724 
5725 	/* Get rid of loopback interfaces and their IREs */
5726 	ip_loopback_cleanup(ipst);
5727 }
5728 
5729 /*
5730  * Free the IP stack instance.
5731  */
5732 static void
5733 ip_stack_fini(netstackid_t stackid, void *arg)
5734 {
5735 	ip_stack_t *ipst = (ip_stack_t *)arg;
5736 	int ret;
5737 
5738 #ifdef NS_DEBUG
5739 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5740 #endif
5741 	ipv4_hook_destroy(ipst);
5742 	ipv6_hook_destroy(ipst);
5743 	ip_net_destroy(ipst);
5744 
5745 	rw_destroy(&ipst->ips_srcid_lock);
5746 
5747 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5748 	ipst->ips_ip_mibkp = NULL;
5749 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5750 	ipst->ips_icmp_mibkp = NULL;
5751 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5752 	ipst->ips_ip_kstat = NULL;
5753 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5754 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5755 	ipst->ips_ip6_kstat = NULL;
5756 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5757 
5758 	nd_free(&ipst->ips_ip_g_nd);
5759 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5760 	ipst->ips_param_arr = NULL;
5761 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5762 	ipst->ips_ndp_arr = NULL;
5763 
5764 	ip_mrouter_stack_destroy(ipst);
5765 
5766 	mutex_destroy(&ipst->ips_ip_mi_lock);
5767 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5768 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5769 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5770 
5771 	ret = untimeout(ipst->ips_igmp_timeout_id);
5772 	if (ret == -1) {
5773 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5774 	} else {
5775 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5776 		ipst->ips_igmp_timeout_id = 0;
5777 	}
5778 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5779 	if (ret == -1) {
5780 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5781 	} else {
5782 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5783 		ipst->ips_igmp_slowtimeout_id = 0;
5784 	}
5785 	ret = untimeout(ipst->ips_mld_timeout_id);
5786 	if (ret == -1) {
5787 		ASSERT(ipst->ips_mld_timeout_id == 0);
5788 	} else {
5789 		ASSERT(ipst->ips_mld_timeout_id != 0);
5790 		ipst->ips_mld_timeout_id = 0;
5791 	}
5792 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5793 	if (ret == -1) {
5794 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5795 	} else {
5796 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5797 		ipst->ips_mld_slowtimeout_id = 0;
5798 	}
5799 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5800 	if (ret == -1) {
5801 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5802 	} else {
5803 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5804 		ipst->ips_ip_ire_expire_id = 0;
5805 	}
5806 
5807 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5808 	mutex_destroy(&ipst->ips_mld_timer_lock);
5809 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5810 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5811 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5812 	rw_destroy(&ipst->ips_ill_g_lock);
5813 
5814 	ip_ire_fini(ipst);
5815 	ip6_asp_free(ipst);
5816 	conn_drain_fini(ipst);
5817 	ipcl_destroy(ipst);
5818 
5819 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5820 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5821 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5822 	ipst->ips_ndp4 = NULL;
5823 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5824 	ipst->ips_ndp6 = NULL;
5825 
5826 	if (ipst->ips_loopback_ksp != NULL) {
5827 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5828 		ipst->ips_loopback_ksp = NULL;
5829 	}
5830 
5831 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5832 	ipst->ips_phyint_g_list = NULL;
5833 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5834 	ipst->ips_ill_g_heads = NULL;
5835 
5836 	kmem_free(ipst, sizeof (*ipst));
5837 }
5838 
5839 /*
5840  * This function is called from the TSD destructor, and is used to debug
5841  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5842  * details.
5843  */
5844 static void
5845 ip_thread_exit(void *phash)
5846 {
5847 	th_hash_t *thh = phash;
5848 
5849 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5850 	list_remove(&ip_thread_list, thh);
5851 	rw_exit(&ip_thread_rwlock);
5852 	mod_hash_destroy_hash(thh->thh_hash);
5853 	kmem_free(thh, sizeof (*thh));
5854 }
5855 
5856 /*
5857  * Called when the IP kernel module is loaded into the kernel
5858  */
5859 void
5860 ip_ddi_init(void)
5861 {
5862 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5863 
5864 	/*
5865 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5866 	 * initial devices: ip, ip6, tcp, tcp6.
5867 	 */
5868 	/*
5869 	 * If this is a 64-bit kernel, then create two separate arenas -
5870 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5871 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5872 	 */
5873 	ip_minor_arena_la = NULL;
5874 	ip_minor_arena_sa = NULL;
5875 #if defined(_LP64)
5876 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5877 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5878 		cmn_err(CE_PANIC,
5879 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5880 	}
5881 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5882 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5883 		cmn_err(CE_PANIC,
5884 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5885 	}
5886 #else
5887 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5888 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5889 		cmn_err(CE_PANIC,
5890 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5891 	}
5892 #endif
5893 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5894 
5895 	ipcl_g_init();
5896 	ip_ire_g_init();
5897 	ip_net_g_init();
5898 
5899 #ifdef DEBUG
5900 	tsd_create(&ip_thread_data, ip_thread_exit);
5901 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5902 	list_create(&ip_thread_list, sizeof (th_hash_t),
5903 	    offsetof(th_hash_t, thh_link));
5904 #endif
5905 
5906 	/*
5907 	 * We want to be informed each time a stack is created or
5908 	 * destroyed in the kernel, so we can maintain the
5909 	 * set of udp_stack_t's.
5910 	 */
5911 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5912 	    ip_stack_fini);
5913 
5914 	ipsec_policy_g_init();
5915 	tcp_ddi_g_init();
5916 	sctp_ddi_g_init();
5917 
5918 	tnet_init();
5919 
5920 	udp_ddi_init();
5921 	rts_ddi_init();
5922 	icmp_ddi_init();
5923 }
5924 
5925 /*
5926  * Initialize the IP stack instance.
5927  */
5928 static void *
5929 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5930 {
5931 	ip_stack_t	*ipst;
5932 	ipparam_t	*pa;
5933 	ipndp_t		*na;
5934 
5935 #ifdef NS_DEBUG
5936 	printf("ip_stack_init(stack %d)\n", stackid);
5937 #endif
5938 
5939 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5940 	ipst->ips_netstack = ns;
5941 
5942 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5943 	    KM_SLEEP);
5944 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5945 	    KM_SLEEP);
5946 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5947 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5948 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5949 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5950 
5951 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5952 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5953 	ipst->ips_igmp_deferred_next = INFINITY;
5954 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5955 	ipst->ips_mld_deferred_next = INFINITY;
5956 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5957 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5958 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5959 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5960 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5961 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5962 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5963 
5964 	ipcl_init(ipst);
5965 	ip_ire_init(ipst);
5966 	ip6_asp_init(ipst);
5967 	ipif_init(ipst);
5968 	conn_drain_init(ipst);
5969 	ip_mrouter_stack_init(ipst);
5970 
5971 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5972 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5973 
5974 	ipst->ips_ip_multirt_log_interval = 1000;
5975 
5976 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5977 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5978 	ipst->ips_ill_index = 1;
5979 
5980 	ipst->ips_saved_ip_g_forward = -1;
5981 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5982 
5983 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5984 	ipst->ips_param_arr = pa;
5985 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5986 
5987 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5988 	ipst->ips_ndp_arr = na;
5989 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5990 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5991 	    (caddr_t)&ipst->ips_ip_g_forward;
5992 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5993 	    (caddr_t)&ipst->ips_ipv6_forward;
5994 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5995 	    "ip_cgtp_filter") == 0);
5996 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5997 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5998 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5999 	    "ipmp_hook_emulation") == 0);
6000 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6001 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6002 
6003 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6004 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6005 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6006 
6007 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6008 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6009 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6010 	ipst->ips_ip6_kstat =
6011 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6012 
6013 	ipst->ips_ipmp_enable_failback = B_TRUE;
6014 
6015 	ipst->ips_ip_src_id = 1;
6016 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6017 
6018 	ip_net_init(ipst, ns);
6019 	ipv4_hook_init(ipst);
6020 	ipv6_hook_init(ipst);
6021 
6022 	return (ipst);
6023 }
6024 
6025 /*
6026  * Allocate and initialize a DLPI template of the specified length.  (May be
6027  * called as writer.)
6028  */
6029 mblk_t *
6030 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6031 {
6032 	mblk_t	*mp;
6033 
6034 	mp = allocb(len, BPRI_MED);
6035 	if (!mp)
6036 		return (NULL);
6037 
6038 	/*
6039 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6040 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6041 	 * that other DLPI are M_PROTO.
6042 	 */
6043 	if (prim == DL_INFO_REQ) {
6044 		mp->b_datap->db_type = M_PCPROTO;
6045 	} else {
6046 		mp->b_datap->db_type = M_PROTO;
6047 	}
6048 
6049 	mp->b_wptr = mp->b_rptr + len;
6050 	bzero(mp->b_rptr, len);
6051 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6052 	return (mp);
6053 }
6054 
6055 const char *
6056 dlpi_prim_str(int prim)
6057 {
6058 	switch (prim) {
6059 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6060 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6061 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6062 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6063 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6064 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6065 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6066 	case DL_OK_ACK:		return ("DL_OK_ACK");
6067 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6068 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6069 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6070 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6071 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6072 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6073 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6074 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6075 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6076 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6077 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6078 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6079 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6080 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6081 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6082 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6083 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6084 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6085 	default:		return ("<unknown primitive>");
6086 	}
6087 }
6088 
6089 const char *
6090 dlpi_err_str(int err)
6091 {
6092 	switch (err) {
6093 	case DL_ACCESS:		return ("DL_ACCESS");
6094 	case DL_BADADDR:	return ("DL_BADADDR");
6095 	case DL_BADCORR:	return ("DL_BADCORR");
6096 	case DL_BADDATA:	return ("DL_BADDATA");
6097 	case DL_BADPPA:		return ("DL_BADPPA");
6098 	case DL_BADPRIM:	return ("DL_BADPRIM");
6099 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6100 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6101 	case DL_BADSAP:		return ("DL_BADSAP");
6102 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6103 	case DL_BOUND:		return ("DL_BOUND");
6104 	case DL_INITFAILED:	return ("DL_INITFAILED");
6105 	case DL_NOADDR:		return ("DL_NOADDR");
6106 	case DL_NOTINIT:	return ("DL_NOTINIT");
6107 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6108 	case DL_SYSERR:		return ("DL_SYSERR");
6109 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6110 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6111 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6112 	case DL_TOOMANY:	return ("DL_TOOMANY");
6113 	case DL_NOTENAB:	return ("DL_NOTENAB");
6114 	case DL_BUSY:		return ("DL_BUSY");
6115 	case DL_NOAUTO:		return ("DL_NOAUTO");
6116 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6117 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6118 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6119 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6120 	case DL_PENDING:	return ("DL_PENDING");
6121 	default:		return ("<unknown error>");
6122 	}
6123 }
6124 
6125 /*
6126  * Debug formatting routine.  Returns a character string representation of the
6127  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6128  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6129  *
6130  * Once the ndd table-printing interfaces are removed, this can be changed to
6131  * standard dotted-decimal form.
6132  */
6133 char *
6134 ip_dot_addr(ipaddr_t addr, char *buf)
6135 {
6136 	uint8_t *ap = (uint8_t *)&addr;
6137 
6138 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6139 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6140 	return (buf);
6141 }
6142 
6143 /*
6144  * Write the given MAC address as a printable string in the usual colon-
6145  * separated format.
6146  */
6147 const char *
6148 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6149 {
6150 	char *bp;
6151 
6152 	if (alen == 0 || buflen < 4)
6153 		return ("?");
6154 	bp = buf;
6155 	for (;;) {
6156 		/*
6157 		 * If there are more MAC address bytes available, but we won't
6158 		 * have any room to print them, then add "..." to the string
6159 		 * instead.  See below for the 'magic number' explanation.
6160 		 */
6161 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6162 			(void) strcpy(bp, "...");
6163 			break;
6164 		}
6165 		(void) sprintf(bp, "%02x", *addr++);
6166 		bp += 2;
6167 		if (--alen == 0)
6168 			break;
6169 		*bp++ = ':';
6170 		buflen -= 3;
6171 		/*
6172 		 * At this point, based on the first 'if' statement above,
6173 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6174 		 * buflen >= 4.  The first case leaves room for the final "xx"
6175 		 * number and trailing NUL byte.  The second leaves room for at
6176 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6177 		 * that statement.
6178 		 */
6179 	}
6180 	return (buf);
6181 }
6182 
6183 /*
6184  * Send an ICMP error after patching up the packet appropriately.  Returns
6185  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6186  */
6187 static boolean_t
6188 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6189     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6190     zoneid_t zoneid, ip_stack_t *ipst)
6191 {
6192 	ipha_t *ipha;
6193 	mblk_t *first_mp;
6194 	boolean_t secure;
6195 	unsigned char db_type;
6196 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6197 
6198 	first_mp = mp;
6199 	if (mctl_present) {
6200 		mp = mp->b_cont;
6201 		secure = ipsec_in_is_secure(first_mp);
6202 		ASSERT(mp != NULL);
6203 	} else {
6204 		/*
6205 		 * If this is an ICMP error being reported - which goes
6206 		 * up as M_CTLs, we need to convert them to M_DATA till
6207 		 * we finish checking with global policy because
6208 		 * ipsec_check_global_policy() assumes M_DATA as clear
6209 		 * and M_CTL as secure.
6210 		 */
6211 		db_type = DB_TYPE(mp);
6212 		DB_TYPE(mp) = M_DATA;
6213 		secure = B_FALSE;
6214 	}
6215 	/*
6216 	 * We are generating an icmp error for some inbound packet.
6217 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6218 	 * Before we generate an error, check with global policy
6219 	 * to see whether this is allowed to enter the system. As
6220 	 * there is no "conn", we are checking with global policy.
6221 	 */
6222 	ipha = (ipha_t *)mp->b_rptr;
6223 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6224 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6225 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6226 		if (first_mp == NULL)
6227 			return (B_FALSE);
6228 	}
6229 
6230 	if (!mctl_present)
6231 		DB_TYPE(mp) = db_type;
6232 
6233 	if (flags & IP_FF_SEND_ICMP) {
6234 		if (flags & IP_FF_HDR_COMPLETE) {
6235 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6236 				freemsg(first_mp);
6237 				return (B_TRUE);
6238 			}
6239 		}
6240 		if (flags & IP_FF_CKSUM) {
6241 			/*
6242 			 * Have to correct checksum since
6243 			 * the packet might have been
6244 			 * fragmented and the reassembly code in ip_rput
6245 			 * does not restore the IP checksum.
6246 			 */
6247 			ipha->ipha_hdr_checksum = 0;
6248 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6249 		}
6250 		switch (icmp_type) {
6251 		case ICMP_DEST_UNREACHABLE:
6252 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6253 			    ipst);
6254 			break;
6255 		default:
6256 			freemsg(first_mp);
6257 			break;
6258 		}
6259 	} else {
6260 		freemsg(first_mp);
6261 		return (B_FALSE);
6262 	}
6263 
6264 	return (B_TRUE);
6265 }
6266 
6267 /*
6268  * Used to send an ICMP error message when a packet is received for
6269  * a protocol that is not supported. The mblk passed as argument
6270  * is consumed by this function.
6271  */
6272 void
6273 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6274     ip_stack_t *ipst)
6275 {
6276 	mblk_t *mp;
6277 	ipha_t *ipha;
6278 	ill_t *ill;
6279 	ipsec_in_t *ii;
6280 
6281 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6282 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6283 
6284 	mp = ipsec_mp->b_cont;
6285 	ipsec_mp->b_cont = NULL;
6286 	ipha = (ipha_t *)mp->b_rptr;
6287 	/* Get ill from index in ipsec_in_t. */
6288 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6289 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6290 	    ipst);
6291 	if (ill != NULL) {
6292 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6293 			if (ip_fanout_send_icmp(q, mp, flags,
6294 			    ICMP_DEST_UNREACHABLE,
6295 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6296 				BUMP_MIB(ill->ill_ip_mib,
6297 				    ipIfStatsInUnknownProtos);
6298 			}
6299 		} else {
6300 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6301 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6302 			    0, B_FALSE, zoneid, ipst)) {
6303 				BUMP_MIB(ill->ill_ip_mib,
6304 				    ipIfStatsInUnknownProtos);
6305 			}
6306 		}
6307 		ill_refrele(ill);
6308 	} else { /* re-link for the freemsg() below. */
6309 		ipsec_mp->b_cont = mp;
6310 	}
6311 
6312 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6313 	freemsg(ipsec_mp);
6314 }
6315 
6316 /*
6317  * See if the inbound datagram has had IPsec processing applied to it.
6318  */
6319 boolean_t
6320 ipsec_in_is_secure(mblk_t *ipsec_mp)
6321 {
6322 	ipsec_in_t *ii;
6323 
6324 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6325 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6326 
6327 	if (ii->ipsec_in_loopback) {
6328 		return (ii->ipsec_in_secure);
6329 	} else {
6330 		return (ii->ipsec_in_ah_sa != NULL ||
6331 		    ii->ipsec_in_esp_sa != NULL ||
6332 		    ii->ipsec_in_decaps);
6333 	}
6334 }
6335 
6336 /*
6337  * Handle protocols with which IP is less intimate.  There
6338  * can be more than one stream bound to a particular
6339  * protocol.  When this is the case, normally each one gets a copy
6340  * of any incoming packets.
6341  *
6342  * IPsec NOTE :
6343  *
6344  * Don't allow a secure packet going up a non-secure connection.
6345  * We don't allow this because
6346  *
6347  * 1) Reply might go out in clear which will be dropped at
6348  *    the sending side.
6349  * 2) If the reply goes out in clear it will give the
6350  *    adversary enough information for getting the key in
6351  *    most of the cases.
6352  *
6353  * Moreover getting a secure packet when we expect clear
6354  * implies that SA's were added without checking for
6355  * policy on both ends. This should not happen once ISAKMP
6356  * is used to negotiate SAs as SAs will be added only after
6357  * verifying the policy.
6358  *
6359  * NOTE : If the packet was tunneled and not multicast we only send
6360  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6361  * back to delivering packets to AF_INET6 raw sockets.
6362  *
6363  * IPQoS Notes:
6364  * Once we have determined the client, invoke IPPF processing.
6365  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6366  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6367  * ip_policy will be false.
6368  *
6369  * Zones notes:
6370  * Currently only applications in the global zone can create raw sockets for
6371  * protocols other than ICMP. So unlike the broadcast / multicast case of
6372  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6373  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6374  */
6375 static void
6376 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6377     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6378     zoneid_t zoneid)
6379 {
6380 	queue_t	*rq;
6381 	mblk_t	*mp1, *first_mp1;
6382 	uint_t	protocol = ipha->ipha_protocol;
6383 	ipaddr_t dst;
6384 	boolean_t one_only;
6385 	mblk_t *first_mp = mp;
6386 	boolean_t secure;
6387 	uint32_t ill_index;
6388 	conn_t	*connp, *first_connp, *next_connp;
6389 	connf_t	*connfp;
6390 	boolean_t shared_addr;
6391 	mib2_ipIfStatsEntry_t *mibptr;
6392 	ip_stack_t *ipst = recv_ill->ill_ipst;
6393 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6394 
6395 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6396 	if (mctl_present) {
6397 		mp = first_mp->b_cont;
6398 		secure = ipsec_in_is_secure(first_mp);
6399 		ASSERT(mp != NULL);
6400 	} else {
6401 		secure = B_FALSE;
6402 	}
6403 	dst = ipha->ipha_dst;
6404 	/*
6405 	 * If the packet was tunneled and not multicast we only send to it
6406 	 * the first match.
6407 	 */
6408 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6409 	    !CLASSD(dst));
6410 
6411 	shared_addr = (zoneid == ALL_ZONES);
6412 	if (shared_addr) {
6413 		/*
6414 		 * We don't allow multilevel ports for raw IP, so no need to
6415 		 * check for that here.
6416 		 */
6417 		zoneid = tsol_packet_to_zoneid(mp);
6418 	}
6419 
6420 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6421 	mutex_enter(&connfp->connf_lock);
6422 	connp = connfp->connf_head;
6423 	for (connp = connfp->connf_head; connp != NULL;
6424 	    connp = connp->conn_next) {
6425 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6426 		    zoneid) &&
6427 		    (!is_system_labeled() ||
6428 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6429 		    connp))) {
6430 			break;
6431 		}
6432 	}
6433 
6434 	if (connp == NULL || connp->conn_upq == NULL) {
6435 		/*
6436 		 * No one bound to these addresses.  Is
6437 		 * there a client that wants all
6438 		 * unclaimed datagrams?
6439 		 */
6440 		mutex_exit(&connfp->connf_lock);
6441 		/*
6442 		 * Check for IPPROTO_ENCAP...
6443 		 */
6444 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6445 			/*
6446 			 * If an IPsec mblk is here on a multicast
6447 			 * tunnel (using ip_mroute stuff), check policy here,
6448 			 * THEN ship off to ip_mroute_decap().
6449 			 *
6450 			 * BTW,  If I match a configured IP-in-IP
6451 			 * tunnel, this path will not be reached, and
6452 			 * ip_mroute_decap will never be called.
6453 			 */
6454 			first_mp = ipsec_check_global_policy(first_mp, connp,
6455 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6456 			if (first_mp != NULL) {
6457 				if (mctl_present)
6458 					freeb(first_mp);
6459 				ip_mroute_decap(q, mp, ill);
6460 			} /* Else we already freed everything! */
6461 		} else {
6462 			/*
6463 			 * Otherwise send an ICMP protocol unreachable.
6464 			 */
6465 			if (ip_fanout_send_icmp(q, first_mp, flags,
6466 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6467 			    mctl_present, zoneid, ipst)) {
6468 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6469 			}
6470 		}
6471 		return;
6472 	}
6473 	CONN_INC_REF(connp);
6474 	first_connp = connp;
6475 
6476 	/*
6477 	 * Only send message to one tunnel driver by immediately
6478 	 * terminating the loop.
6479 	 */
6480 	connp = one_only ? NULL : connp->conn_next;
6481 
6482 	for (;;) {
6483 		while (connp != NULL) {
6484 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6485 			    flags, zoneid) &&
6486 			    (!is_system_labeled() ||
6487 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6488 			    shared_addr, connp)))
6489 				break;
6490 			connp = connp->conn_next;
6491 		}
6492 
6493 		/*
6494 		 * Copy the packet.
6495 		 */
6496 		if (connp == NULL || connp->conn_upq == NULL ||
6497 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6498 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6499 			/*
6500 			 * No more interested clients or memory
6501 			 * allocation failed
6502 			 */
6503 			connp = first_connp;
6504 			break;
6505 		}
6506 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6507 		CONN_INC_REF(connp);
6508 		mutex_exit(&connfp->connf_lock);
6509 		rq = connp->conn_rq;
6510 		if (!canputnext(rq)) {
6511 			if (flags & IP_FF_RAWIP) {
6512 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6513 			} else {
6514 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6515 			}
6516 
6517 			freemsg(first_mp1);
6518 		} else {
6519 			/*
6520 			 * Don't enforce here if we're an actual tunnel -
6521 			 * let "tun" do it instead.
6522 			 */
6523 			if (!IPCL_IS_IPTUN(connp) &&
6524 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6525 			    secure)) {
6526 				first_mp1 = ipsec_check_inbound_policy
6527 				    (first_mp1, connp, ipha, NULL,
6528 				    mctl_present);
6529 			}
6530 			if (first_mp1 != NULL) {
6531 				int in_flags = 0;
6532 				/*
6533 				 * ip_fanout_proto also gets called from
6534 				 * icmp_inbound_error_fanout, in which case
6535 				 * the msg type is M_CTL.  Don't add info
6536 				 * in this case for the time being. In future
6537 				 * when there is a need for knowing the
6538 				 * inbound iface index for ICMP error msgs,
6539 				 * then this can be changed.
6540 				 */
6541 				if (connp->conn_recvif)
6542 					in_flags = IPF_RECVIF;
6543 				/*
6544 				 * The ULP may support IP_RECVPKTINFO for both
6545 				 * IP v4 and v6 so pass the appropriate argument
6546 				 * based on conn IP version.
6547 				 */
6548 				if (connp->conn_ip_recvpktinfo) {
6549 					if (connp->conn_af_isv6) {
6550 						/*
6551 						 * V6 only needs index
6552 						 */
6553 						in_flags |= IPF_RECVIF;
6554 					} else {
6555 						/*
6556 						 * V4 needs index +
6557 						 * matching address.
6558 						 */
6559 						in_flags |= IPF_RECVADDR;
6560 					}
6561 				}
6562 				if ((in_flags != 0) &&
6563 				    (mp->b_datap->db_type != M_CTL)) {
6564 					/*
6565 					 * the actual data will be
6566 					 * contained in b_cont upon
6567 					 * successful return of the
6568 					 * following call else
6569 					 * original mblk is returned
6570 					 */
6571 					ASSERT(recv_ill != NULL);
6572 					mp1 = ip_add_info(mp1, recv_ill,
6573 					    in_flags, IPCL_ZONEID(connp), ipst);
6574 				}
6575 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6576 				if (mctl_present)
6577 					freeb(first_mp1);
6578 				(connp->conn_recv)(connp, mp1, NULL);
6579 			}
6580 		}
6581 		mutex_enter(&connfp->connf_lock);
6582 		/* Follow the next pointer before releasing the conn. */
6583 		next_connp = connp->conn_next;
6584 		CONN_DEC_REF(connp);
6585 		connp = next_connp;
6586 	}
6587 
6588 	/* Last one.  Send it upstream. */
6589 	mutex_exit(&connfp->connf_lock);
6590 
6591 	/*
6592 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6593 	 * will be set to false.
6594 	 */
6595 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6596 		ill_index = ill->ill_phyint->phyint_ifindex;
6597 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6598 		if (mp == NULL) {
6599 			CONN_DEC_REF(connp);
6600 			if (mctl_present) {
6601 				freeb(first_mp);
6602 			}
6603 			return;
6604 		}
6605 	}
6606 
6607 	rq = connp->conn_rq;
6608 	if (!canputnext(rq)) {
6609 		if (flags & IP_FF_RAWIP) {
6610 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6611 		} else {
6612 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6613 		}
6614 
6615 		freemsg(first_mp);
6616 	} else {
6617 		if (IPCL_IS_IPTUN(connp)) {
6618 			/*
6619 			 * Tunneled packet.  We enforce policy in the tunnel
6620 			 * module itself.
6621 			 *
6622 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6623 			 * a policy check.
6624 			 * FIXME to use conn_recv for tun later.
6625 			 */
6626 			putnext(rq, first_mp);
6627 			CONN_DEC_REF(connp);
6628 			return;
6629 		}
6630 
6631 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6632 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6633 			    ipha, NULL, mctl_present);
6634 		}
6635 
6636 		if (first_mp != NULL) {
6637 			int in_flags = 0;
6638 
6639 			/*
6640 			 * ip_fanout_proto also gets called
6641 			 * from icmp_inbound_error_fanout, in
6642 			 * which case the msg type is M_CTL.
6643 			 * Don't add info in this case for time
6644 			 * being. In future when there is a
6645 			 * need for knowing the inbound iface
6646 			 * index for ICMP error msgs, then this
6647 			 * can be changed
6648 			 */
6649 			if (connp->conn_recvif)
6650 				in_flags = IPF_RECVIF;
6651 			if (connp->conn_ip_recvpktinfo) {
6652 				if (connp->conn_af_isv6) {
6653 					/*
6654 					 * V6 only needs index
6655 					 */
6656 					in_flags |= IPF_RECVIF;
6657 				} else {
6658 					/*
6659 					 * V4 needs index +
6660 					 * matching address.
6661 					 */
6662 					in_flags |= IPF_RECVADDR;
6663 				}
6664 			}
6665 			if ((in_flags != 0) &&
6666 			    (mp->b_datap->db_type != M_CTL)) {
6667 
6668 				/*
6669 				 * the actual data will be contained in
6670 				 * b_cont upon successful return
6671 				 * of the following call else original
6672 				 * mblk is returned
6673 				 */
6674 				ASSERT(recv_ill != NULL);
6675 				mp = ip_add_info(mp, recv_ill,
6676 				    in_flags, IPCL_ZONEID(connp), ipst);
6677 			}
6678 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6679 			(connp->conn_recv)(connp, mp, NULL);
6680 			if (mctl_present)
6681 				freeb(first_mp);
6682 		}
6683 	}
6684 	CONN_DEC_REF(connp);
6685 }
6686 
6687 /*
6688  * Fanout for TCP packets
6689  * The caller puts <fport, lport> in the ports parameter.
6690  *
6691  * IPQoS Notes
6692  * Before sending it to the client, invoke IPPF processing.
6693  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6694  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6695  * ip_policy is false.
6696  */
6697 static void
6698 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6699     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6700 {
6701 	mblk_t  *first_mp;
6702 	boolean_t secure;
6703 	uint32_t ill_index;
6704 	int	ip_hdr_len;
6705 	tcph_t	*tcph;
6706 	boolean_t syn_present = B_FALSE;
6707 	conn_t	*connp;
6708 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6709 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6710 
6711 	ASSERT(recv_ill != NULL);
6712 
6713 	first_mp = mp;
6714 	if (mctl_present) {
6715 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6716 		mp = first_mp->b_cont;
6717 		secure = ipsec_in_is_secure(first_mp);
6718 		ASSERT(mp != NULL);
6719 	} else {
6720 		secure = B_FALSE;
6721 	}
6722 
6723 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6724 
6725 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6726 	    zoneid, ipst)) == NULL) {
6727 		/*
6728 		 * No connected connection or listener. Send a
6729 		 * TH_RST via tcp_xmit_listeners_reset.
6730 		 */
6731 
6732 		/* Initiate IPPf processing, if needed. */
6733 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6734 			uint32_t ill_index;
6735 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6736 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6737 			if (first_mp == NULL)
6738 				return;
6739 		}
6740 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6741 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6742 		    zoneid));
6743 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6744 		    ipst->ips_netstack->netstack_tcp, NULL);
6745 		return;
6746 	}
6747 
6748 	/*
6749 	 * Allocate the SYN for the TCP connection here itself
6750 	 */
6751 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6752 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6753 		if (IPCL_IS_TCP(connp)) {
6754 			squeue_t *sqp;
6755 
6756 			/*
6757 			 * For fused tcp loopback, assign the eager's
6758 			 * squeue to be that of the active connect's.
6759 			 * Note that we don't check for IP_FF_LOOPBACK
6760 			 * here since this routine gets called only
6761 			 * for loopback (unlike the IPv6 counterpart).
6762 			 */
6763 			ASSERT(Q_TO_CONN(q) != NULL);
6764 			if (do_tcp_fusion &&
6765 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6766 			    !secure &&
6767 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6768 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6769 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6770 				sqp = Q_TO_CONN(q)->conn_sqp;
6771 			} else {
6772 				sqp = IP_SQUEUE_GET(lbolt);
6773 			}
6774 
6775 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6776 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6777 			syn_present = B_TRUE;
6778 		}
6779 	}
6780 
6781 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6782 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6783 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6784 		if ((flags & TH_RST) || (flags & TH_URG)) {
6785 			CONN_DEC_REF(connp);
6786 			freemsg(first_mp);
6787 			return;
6788 		}
6789 		if (flags & TH_ACK) {
6790 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6791 			    ipst->ips_netstack->netstack_tcp, connp);
6792 			CONN_DEC_REF(connp);
6793 			return;
6794 		}
6795 
6796 		CONN_DEC_REF(connp);
6797 		freemsg(first_mp);
6798 		return;
6799 	}
6800 
6801 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6802 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6803 		    NULL, mctl_present);
6804 		if (first_mp == NULL) {
6805 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6806 			CONN_DEC_REF(connp);
6807 			return;
6808 		}
6809 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6810 			ASSERT(syn_present);
6811 			if (mctl_present) {
6812 				ASSERT(first_mp != mp);
6813 				first_mp->b_datap->db_struioflag |=
6814 				    STRUIO_POLICY;
6815 			} else {
6816 				ASSERT(first_mp == mp);
6817 				mp->b_datap->db_struioflag &=
6818 				    ~STRUIO_EAGER;
6819 				mp->b_datap->db_struioflag |=
6820 				    STRUIO_POLICY;
6821 			}
6822 		} else {
6823 			/*
6824 			 * Discard first_mp early since we're dealing with a
6825 			 * fully-connected conn_t and tcp doesn't do policy in
6826 			 * this case.
6827 			 */
6828 			if (mctl_present) {
6829 				freeb(first_mp);
6830 				mctl_present = B_FALSE;
6831 			}
6832 			first_mp = mp;
6833 		}
6834 	}
6835 
6836 	/*
6837 	 * Initiate policy processing here if needed. If we get here from
6838 	 * icmp_inbound_error_fanout, ip_policy is false.
6839 	 */
6840 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6841 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6842 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6843 		if (mp == NULL) {
6844 			CONN_DEC_REF(connp);
6845 			if (mctl_present)
6846 				freeb(first_mp);
6847 			return;
6848 		} else if (mctl_present) {
6849 			ASSERT(first_mp != mp);
6850 			first_mp->b_cont = mp;
6851 		} else {
6852 			first_mp = mp;
6853 		}
6854 	}
6855 
6856 
6857 
6858 	/* Handle socket options. */
6859 	if (!syn_present &&
6860 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6861 		/* Add header */
6862 		ASSERT(recv_ill != NULL);
6863 		/*
6864 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6865 		 * IPF_RECVIF.
6866 		 */
6867 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6868 		    ipst);
6869 		if (mp == NULL) {
6870 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6871 			CONN_DEC_REF(connp);
6872 			if (mctl_present)
6873 				freeb(first_mp);
6874 			return;
6875 		} else if (mctl_present) {
6876 			/*
6877 			 * ip_add_info might return a new mp.
6878 			 */
6879 			ASSERT(first_mp != mp);
6880 			first_mp->b_cont = mp;
6881 		} else {
6882 			first_mp = mp;
6883 		}
6884 	}
6885 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6886 	if (IPCL_IS_TCP(connp)) {
6887 		/* do not drain, certain use cases can blow the stack */
6888 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6889 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6890 	} else {
6891 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6892 		(connp->conn_recv)(connp, first_mp, NULL);
6893 		CONN_DEC_REF(connp);
6894 	}
6895 }
6896 
6897 /*
6898  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6899  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6900  * is not consumed.
6901  *
6902  * One of four things can happen, all of which affect the passed-in mblk:
6903  *
6904  * 1.) ICMP messages that go through here just get returned TRUE.
6905  *
6906  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6907  *
6908  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6909  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6910  *
6911  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6912  */
6913 static boolean_t
6914 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6915     ipsec_stack_t *ipss)
6916 {
6917 	int shift, plen, iph_len;
6918 	ipha_t *ipha;
6919 	udpha_t *udpha;
6920 	uint32_t *spi;
6921 	uint8_t *orptr;
6922 	boolean_t udp_pkt, free_ire;
6923 
6924 	if (DB_TYPE(mp) == M_CTL) {
6925 		/*
6926 		 * ICMP message with UDP inside.  Don't bother stripping, just
6927 		 * send it up.
6928 		 *
6929 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6930 		 * to ignore errors set by ICMP anyway ('cause they might be
6931 		 * forged), but that's the app's decision, not ours.
6932 		 */
6933 
6934 		/* Bunch of reality checks for DEBUG kernels... */
6935 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6936 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6937 
6938 		return (B_TRUE);
6939 	}
6940 
6941 	ipha = (ipha_t *)mp->b_rptr;
6942 	iph_len = IPH_HDR_LENGTH(ipha);
6943 	plen = ntohs(ipha->ipha_length);
6944 
6945 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6946 		/*
6947 		 * Most likely a keepalive for the benefit of an intervening
6948 		 * NAT.  These aren't for us, per se, so drop it.
6949 		 *
6950 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6951 		 * byte packets (keepalives are 1-byte), but we'll drop them
6952 		 * also.
6953 		 */
6954 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6955 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6956 		return (B_FALSE);
6957 	}
6958 
6959 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6960 		/* might as well pull it all up - it might be ESP. */
6961 		if (!pullupmsg(mp, -1)) {
6962 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6963 			    DROPPER(ipss, ipds_esp_nomem),
6964 			    &ipss->ipsec_dropper);
6965 			return (B_FALSE);
6966 		}
6967 
6968 		ipha = (ipha_t *)mp->b_rptr;
6969 	}
6970 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6971 	if (*spi == 0) {
6972 		/* UDP packet - remove 0-spi. */
6973 		shift = sizeof (uint32_t);
6974 	} else {
6975 		/* ESP-in-UDP packet - reduce to ESP. */
6976 		ipha->ipha_protocol = IPPROTO_ESP;
6977 		shift = sizeof (udpha_t);
6978 	}
6979 
6980 	/* Fix IP header */
6981 	ipha->ipha_length = htons(plen - shift);
6982 	ipha->ipha_hdr_checksum = 0;
6983 
6984 	orptr = mp->b_rptr;
6985 	mp->b_rptr += shift;
6986 
6987 	if (*spi == 0) {
6988 		ASSERT((uint8_t *)ipha == orptr);
6989 		udpha = (udpha_t *)(orptr + iph_len);
6990 		udpha->uha_length = htons(plen - shift - iph_len);
6991 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6992 		udp_pkt = B_TRUE;
6993 	} else {
6994 		udp_pkt = B_FALSE;
6995 	}
6996 	ovbcopy(orptr, orptr + shift, iph_len);
6997 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6998 		ipha = (ipha_t *)(orptr + shift);
6999 
7000 		free_ire = (ire == NULL);
7001 		if (free_ire) {
7002 			/* Re-acquire ire. */
7003 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7004 			    ipss->ipsec_netstack->netstack_ip);
7005 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7006 				if (ire != NULL)
7007 					ire_refrele(ire);
7008 				/*
7009 				 * Do a regular freemsg(), as this is an IP
7010 				 * error (no local route) not an IPsec one.
7011 				 */
7012 				freemsg(mp);
7013 			}
7014 		}
7015 
7016 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
7017 		if (free_ire)
7018 			ire_refrele(ire);
7019 	}
7020 
7021 	return (udp_pkt);
7022 }
7023 
7024 /*
7025  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7026  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7027  * Caller is responsible for dropping references to the conn, and freeing
7028  * first_mp.
7029  *
7030  * IPQoS Notes
7031  * Before sending it to the client, invoke IPPF processing. Policy processing
7032  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7033  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7034  * ip_wput_local, ip_policy is false.
7035  */
7036 static void
7037 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7038     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7039     boolean_t ip_policy)
7040 {
7041 	boolean_t	mctl_present = (first_mp != NULL);
7042 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7043 	uint32_t	ill_index;
7044 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7045 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7046 
7047 	ASSERT(ill != NULL);
7048 
7049 	if (mctl_present)
7050 		first_mp->b_cont = mp;
7051 	else
7052 		first_mp = mp;
7053 
7054 	if (CONN_UDP_FLOWCTLD(connp)) {
7055 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7056 		freemsg(first_mp);
7057 		return;
7058 	}
7059 
7060 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7061 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7062 		    NULL, mctl_present);
7063 		if (first_mp == NULL) {
7064 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7065 			return;	/* Freed by ipsec_check_inbound_policy(). */
7066 		}
7067 	}
7068 	if (mctl_present)
7069 		freeb(first_mp);
7070 
7071 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7072 	if (connp->conn_udp->udp_nat_t_endpoint) {
7073 		if (mctl_present) {
7074 			/* mctl_present *shouldn't* happen. */
7075 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7076 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7077 			    &ipss->ipsec_dropper);
7078 			return;
7079 		}
7080 
7081 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7082 			return;
7083 	}
7084 
7085 	/* Handle options. */
7086 	if (connp->conn_recvif)
7087 		in_flags = IPF_RECVIF;
7088 	/*
7089 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7090 	 * passed to ip_add_info is based on IP version of connp.
7091 	 */
7092 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7093 		if (connp->conn_af_isv6) {
7094 			/*
7095 			 * V6 only needs index
7096 			 */
7097 			in_flags |= IPF_RECVIF;
7098 		} else {
7099 			/*
7100 			 * V4 needs index + matching address.
7101 			 */
7102 			in_flags |= IPF_RECVADDR;
7103 		}
7104 	}
7105 
7106 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7107 		in_flags |= IPF_RECVSLLA;
7108 
7109 	/*
7110 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7111 	 * freed if the packet is dropped. The caller will do so.
7112 	 */
7113 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7114 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7115 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7116 		if (mp == NULL) {
7117 			return;
7118 		}
7119 	}
7120 	if ((in_flags != 0) &&
7121 	    (mp->b_datap->db_type != M_CTL)) {
7122 		/*
7123 		 * The actual data will be contained in b_cont
7124 		 * upon successful return of the following call
7125 		 * else original mblk is returned
7126 		 */
7127 		ASSERT(recv_ill != NULL);
7128 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7129 		    ipst);
7130 	}
7131 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7132 	/* Send it upstream */
7133 	(connp->conn_recv)(connp, mp, NULL);
7134 }
7135 
7136 /*
7137  * Fanout for UDP packets.
7138  * The caller puts <fport, lport> in the ports parameter.
7139  *
7140  * If SO_REUSEADDR is set all multicast and broadcast packets
7141  * will be delivered to all streams bound to the same port.
7142  *
7143  * Zones notes:
7144  * Multicast and broadcast packets will be distributed to streams in all zones.
7145  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7146  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7147  * packets. To maintain this behavior with multiple zones, the conns are grouped
7148  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7149  * each zone. If unset, all the following conns in the same zone are skipped.
7150  */
7151 static void
7152 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7153     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7154     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7155 {
7156 	uint32_t	dstport, srcport;
7157 	ipaddr_t	dst;
7158 	mblk_t		*first_mp;
7159 	boolean_t	secure;
7160 	in6_addr_t	v6src;
7161 	conn_t		*connp;
7162 	connf_t		*connfp;
7163 	conn_t		*first_connp;
7164 	conn_t		*next_connp;
7165 	mblk_t		*mp1, *first_mp1;
7166 	ipaddr_t	src;
7167 	zoneid_t	last_zoneid;
7168 	boolean_t	reuseaddr;
7169 	boolean_t	shared_addr;
7170 	ip_stack_t	*ipst;
7171 
7172 	ASSERT(recv_ill != NULL);
7173 	ipst = recv_ill->ill_ipst;
7174 
7175 	first_mp = mp;
7176 	if (mctl_present) {
7177 		mp = first_mp->b_cont;
7178 		first_mp->b_cont = NULL;
7179 		secure = ipsec_in_is_secure(first_mp);
7180 		ASSERT(mp != NULL);
7181 	} else {
7182 		first_mp = NULL;
7183 		secure = B_FALSE;
7184 	}
7185 
7186 	/* Extract ports in net byte order */
7187 	dstport = htons(ntohl(ports) & 0xFFFF);
7188 	srcport = htons(ntohl(ports) >> 16);
7189 	dst = ipha->ipha_dst;
7190 	src = ipha->ipha_src;
7191 
7192 	shared_addr = (zoneid == ALL_ZONES);
7193 	if (shared_addr) {
7194 		/*
7195 		 * No need to handle exclusive-stack zones since ALL_ZONES
7196 		 * only applies to the shared stack.
7197 		 */
7198 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7199 		if (zoneid == ALL_ZONES)
7200 			zoneid = tsol_packet_to_zoneid(mp);
7201 	}
7202 
7203 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7204 	mutex_enter(&connfp->connf_lock);
7205 	connp = connfp->connf_head;
7206 	if (!broadcast && !CLASSD(dst)) {
7207 		/*
7208 		 * Not broadcast or multicast. Send to the one (first)
7209 		 * client we find. No need to check conn_wantpacket()
7210 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7211 		 * IPv4 unicast packets.
7212 		 */
7213 		while ((connp != NULL) &&
7214 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7215 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7216 			connp = connp->conn_next;
7217 		}
7218 
7219 		if (connp == NULL || connp->conn_upq == NULL)
7220 			goto notfound;
7221 
7222 		if (is_system_labeled() &&
7223 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7224 		    connp))
7225 			goto notfound;
7226 
7227 		CONN_INC_REF(connp);
7228 		mutex_exit(&connfp->connf_lock);
7229 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7230 		    flags, recv_ill, ip_policy);
7231 		IP_STAT(ipst, ip_udp_fannorm);
7232 		CONN_DEC_REF(connp);
7233 		return;
7234 	}
7235 
7236 	/*
7237 	 * Broadcast and multicast case
7238 	 *
7239 	 * Need to check conn_wantpacket().
7240 	 * If SO_REUSEADDR has been set on the first we send the
7241 	 * packet to all clients that have joined the group and
7242 	 * match the port.
7243 	 */
7244 
7245 	while (connp != NULL) {
7246 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7247 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7248 		    (!is_system_labeled() ||
7249 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7250 		    connp)))
7251 			break;
7252 		connp = connp->conn_next;
7253 	}
7254 
7255 	if (connp == NULL || connp->conn_upq == NULL)
7256 		goto notfound;
7257 
7258 	first_connp = connp;
7259 	/*
7260 	 * When SO_REUSEADDR is not set, send the packet only to the first
7261 	 * matching connection in its zone by keeping track of the zoneid.
7262 	 */
7263 	reuseaddr = first_connp->conn_reuseaddr;
7264 	last_zoneid = first_connp->conn_zoneid;
7265 
7266 	CONN_INC_REF(connp);
7267 	connp = connp->conn_next;
7268 	for (;;) {
7269 		while (connp != NULL) {
7270 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7271 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7272 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7273 			    (!is_system_labeled() ||
7274 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7275 			    shared_addr, connp)))
7276 				break;
7277 			connp = connp->conn_next;
7278 		}
7279 		/*
7280 		 * Just copy the data part alone. The mctl part is
7281 		 * needed just for verifying policy and it is never
7282 		 * sent up.
7283 		 */
7284 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7285 		    ((mp1 = copymsg(mp)) == NULL))) {
7286 			/*
7287 			 * No more interested clients or memory
7288 			 * allocation failed
7289 			 */
7290 			connp = first_connp;
7291 			break;
7292 		}
7293 		if (connp->conn_zoneid != last_zoneid) {
7294 			/*
7295 			 * Update the zoneid so that the packet isn't sent to
7296 			 * any more conns in the same zone unless SO_REUSEADDR
7297 			 * is set.
7298 			 */
7299 			reuseaddr = connp->conn_reuseaddr;
7300 			last_zoneid = connp->conn_zoneid;
7301 		}
7302 		if (first_mp != NULL) {
7303 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7304 			    ipsec_info_type == IPSEC_IN);
7305 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7306 			    ipst->ips_netstack);
7307 			if (first_mp1 == NULL) {
7308 				freemsg(mp1);
7309 				connp = first_connp;
7310 				break;
7311 			}
7312 		} else {
7313 			first_mp1 = NULL;
7314 		}
7315 		CONN_INC_REF(connp);
7316 		mutex_exit(&connfp->connf_lock);
7317 		/*
7318 		 * IPQoS notes: We don't send the packet for policy
7319 		 * processing here, will do it for the last one (below).
7320 		 * i.e. we do it per-packet now, but if we do policy
7321 		 * processing per-conn, then we would need to do it
7322 		 * here too.
7323 		 */
7324 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7325 		    ipha, flags, recv_ill, B_FALSE);
7326 		mutex_enter(&connfp->connf_lock);
7327 		/* Follow the next pointer before releasing the conn. */
7328 		next_connp = connp->conn_next;
7329 		IP_STAT(ipst, ip_udp_fanmb);
7330 		CONN_DEC_REF(connp);
7331 		connp = next_connp;
7332 	}
7333 
7334 	/* Last one.  Send it upstream. */
7335 	mutex_exit(&connfp->connf_lock);
7336 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7337 	    recv_ill, ip_policy);
7338 	IP_STAT(ipst, ip_udp_fanmb);
7339 	CONN_DEC_REF(connp);
7340 	return;
7341 
7342 notfound:
7343 
7344 	mutex_exit(&connfp->connf_lock);
7345 	IP_STAT(ipst, ip_udp_fanothers);
7346 	/*
7347 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7348 	 * have already been matched above, since they live in the IPv4
7349 	 * fanout tables. This implies we only need to
7350 	 * check for IPv6 in6addr_any endpoints here.
7351 	 * Thus we compare using ipv6_all_zeros instead of the destination
7352 	 * address, except for the multicast group membership lookup which
7353 	 * uses the IPv4 destination.
7354 	 */
7355 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7356 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7357 	mutex_enter(&connfp->connf_lock);
7358 	connp = connfp->connf_head;
7359 	if (!broadcast && !CLASSD(dst)) {
7360 		while (connp != NULL) {
7361 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7362 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7363 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7364 			    !connp->conn_ipv6_v6only)
7365 				break;
7366 			connp = connp->conn_next;
7367 		}
7368 
7369 		if (connp != NULL && is_system_labeled() &&
7370 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7371 		    connp))
7372 			connp = NULL;
7373 
7374 		if (connp == NULL || connp->conn_upq == NULL) {
7375 			/*
7376 			 * No one bound to this port.  Is
7377 			 * there a client that wants all
7378 			 * unclaimed datagrams?
7379 			 */
7380 			mutex_exit(&connfp->connf_lock);
7381 
7382 			if (mctl_present)
7383 				first_mp->b_cont = mp;
7384 			else
7385 				first_mp = mp;
7386 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7387 			    connf_head != NULL) {
7388 				ip_fanout_proto(q, first_mp, ill, ipha,
7389 				    flags | IP_FF_RAWIP, mctl_present,
7390 				    ip_policy, recv_ill, zoneid);
7391 			} else {
7392 				if (ip_fanout_send_icmp(q, first_mp, flags,
7393 				    ICMP_DEST_UNREACHABLE,
7394 				    ICMP_PORT_UNREACHABLE,
7395 				    mctl_present, zoneid, ipst)) {
7396 					BUMP_MIB(ill->ill_ip_mib,
7397 					    udpIfStatsNoPorts);
7398 				}
7399 			}
7400 			return;
7401 		}
7402 
7403 		CONN_INC_REF(connp);
7404 		mutex_exit(&connfp->connf_lock);
7405 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7406 		    flags, recv_ill, ip_policy);
7407 		CONN_DEC_REF(connp);
7408 		return;
7409 	}
7410 	/*
7411 	 * IPv4 multicast packet being delivered to an AF_INET6
7412 	 * in6addr_any endpoint.
7413 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7414 	 * and not conn_wantpacket_v6() since any multicast membership is
7415 	 * for an IPv4-mapped multicast address.
7416 	 * The packet is sent to all clients in all zones that have joined the
7417 	 * group and match the port.
7418 	 */
7419 	while (connp != NULL) {
7420 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7421 		    srcport, v6src) &&
7422 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7423 		    (!is_system_labeled() ||
7424 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7425 		    connp)))
7426 			break;
7427 		connp = connp->conn_next;
7428 	}
7429 
7430 	if (connp == NULL || connp->conn_upq == NULL) {
7431 		/*
7432 		 * No one bound to this port.  Is
7433 		 * there a client that wants all
7434 		 * unclaimed datagrams?
7435 		 */
7436 		mutex_exit(&connfp->connf_lock);
7437 
7438 		if (mctl_present)
7439 			first_mp->b_cont = mp;
7440 		else
7441 			first_mp = mp;
7442 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7443 		    NULL) {
7444 			ip_fanout_proto(q, first_mp, ill, ipha,
7445 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7446 			    recv_ill, zoneid);
7447 		} else {
7448 			/*
7449 			 * We used to attempt to send an icmp error here, but
7450 			 * since this is known to be a multicast packet
7451 			 * and we don't send icmp errors in response to
7452 			 * multicast, just drop the packet and give up sooner.
7453 			 */
7454 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7455 			freemsg(first_mp);
7456 		}
7457 		return;
7458 	}
7459 
7460 	first_connp = connp;
7461 
7462 	CONN_INC_REF(connp);
7463 	connp = connp->conn_next;
7464 	for (;;) {
7465 		while (connp != NULL) {
7466 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7467 			    ipv6_all_zeros, srcport, v6src) &&
7468 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7469 			    (!is_system_labeled() ||
7470 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7471 			    shared_addr, connp)))
7472 				break;
7473 			connp = connp->conn_next;
7474 		}
7475 		/*
7476 		 * Just copy the data part alone. The mctl part is
7477 		 * needed just for verifying policy and it is never
7478 		 * sent up.
7479 		 */
7480 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7481 		    ((mp1 = copymsg(mp)) == NULL))) {
7482 			/*
7483 			 * No more intested clients or memory
7484 			 * allocation failed
7485 			 */
7486 			connp = first_connp;
7487 			break;
7488 		}
7489 		if (first_mp != NULL) {
7490 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7491 			    ipsec_info_type == IPSEC_IN);
7492 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7493 			    ipst->ips_netstack);
7494 			if (first_mp1 == NULL) {
7495 				freemsg(mp1);
7496 				connp = first_connp;
7497 				break;
7498 			}
7499 		} else {
7500 			first_mp1 = NULL;
7501 		}
7502 		CONN_INC_REF(connp);
7503 		mutex_exit(&connfp->connf_lock);
7504 		/*
7505 		 * IPQoS notes: We don't send the packet for policy
7506 		 * processing here, will do it for the last one (below).
7507 		 * i.e. we do it per-packet now, but if we do policy
7508 		 * processing per-conn, then we would need to do it
7509 		 * here too.
7510 		 */
7511 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7512 		    ipha, flags, recv_ill, B_FALSE);
7513 		mutex_enter(&connfp->connf_lock);
7514 		/* Follow the next pointer before releasing the conn. */
7515 		next_connp = connp->conn_next;
7516 		CONN_DEC_REF(connp);
7517 		connp = next_connp;
7518 	}
7519 
7520 	/* Last one.  Send it upstream. */
7521 	mutex_exit(&connfp->connf_lock);
7522 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7523 	    recv_ill, ip_policy);
7524 	CONN_DEC_REF(connp);
7525 }
7526 
7527 /*
7528  * Complete the ip_wput header so that it
7529  * is possible to generate ICMP
7530  * errors.
7531  */
7532 int
7533 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7534 {
7535 	ire_t *ire;
7536 
7537 	if (ipha->ipha_src == INADDR_ANY) {
7538 		ire = ire_lookup_local(zoneid, ipst);
7539 		if (ire == NULL) {
7540 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7541 			return (1);
7542 		}
7543 		ipha->ipha_src = ire->ire_addr;
7544 		ire_refrele(ire);
7545 	}
7546 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7547 	ipha->ipha_hdr_checksum = 0;
7548 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7549 	return (0);
7550 }
7551 
7552 /*
7553  * Nobody should be sending
7554  * packets up this stream
7555  */
7556 static void
7557 ip_lrput(queue_t *q, mblk_t *mp)
7558 {
7559 	mblk_t *mp1;
7560 
7561 	switch (mp->b_datap->db_type) {
7562 	case M_FLUSH:
7563 		/* Turn around */
7564 		if (*mp->b_rptr & FLUSHW) {
7565 			*mp->b_rptr &= ~FLUSHR;
7566 			qreply(q, mp);
7567 			return;
7568 		}
7569 		break;
7570 	}
7571 	/* Could receive messages that passed through ar_rput */
7572 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7573 		mp1->b_prev = mp1->b_next = NULL;
7574 	freemsg(mp);
7575 }
7576 
7577 /* Nobody should be sending packets down this stream */
7578 /* ARGSUSED */
7579 void
7580 ip_lwput(queue_t *q, mblk_t *mp)
7581 {
7582 	freemsg(mp);
7583 }
7584 
7585 /*
7586  * Move the first hop in any source route to ipha_dst and remove that part of
7587  * the source route.  Called by other protocols.  Errors in option formatting
7588  * are ignored - will be handled by ip_wput_options Return the final
7589  * destination (either ipha_dst or the last entry in a source route.)
7590  */
7591 ipaddr_t
7592 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7593 {
7594 	ipoptp_t	opts;
7595 	uchar_t		*opt;
7596 	uint8_t		optval;
7597 	uint8_t		optlen;
7598 	ipaddr_t	dst;
7599 	int		i;
7600 	ire_t		*ire;
7601 	ip_stack_t	*ipst = ns->netstack_ip;
7602 
7603 	ip2dbg(("ip_massage_options\n"));
7604 	dst = ipha->ipha_dst;
7605 	for (optval = ipoptp_first(&opts, ipha);
7606 	    optval != IPOPT_EOL;
7607 	    optval = ipoptp_next(&opts)) {
7608 		opt = opts.ipoptp_cur;
7609 		switch (optval) {
7610 			uint8_t off;
7611 		case IPOPT_SSRR:
7612 		case IPOPT_LSRR:
7613 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7614 				ip1dbg(("ip_massage_options: bad src route\n"));
7615 				break;
7616 			}
7617 			optlen = opts.ipoptp_len;
7618 			off = opt[IPOPT_OFFSET];
7619 			off--;
7620 		redo_srr:
7621 			if (optlen < IP_ADDR_LEN ||
7622 			    off > optlen - IP_ADDR_LEN) {
7623 				/* End of source route */
7624 				ip1dbg(("ip_massage_options: end of SR\n"));
7625 				break;
7626 			}
7627 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7628 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7629 			    ntohl(dst)));
7630 			/*
7631 			 * Check if our address is present more than
7632 			 * once as consecutive hops in source route.
7633 			 * XXX verify per-interface ip_forwarding
7634 			 * for source route?
7635 			 */
7636 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7637 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7638 			if (ire != NULL) {
7639 				ire_refrele(ire);
7640 				off += IP_ADDR_LEN;
7641 				goto redo_srr;
7642 			}
7643 			if (dst == htonl(INADDR_LOOPBACK)) {
7644 				ip1dbg(("ip_massage_options: loopback addr in "
7645 				    "source route!\n"));
7646 				break;
7647 			}
7648 			/*
7649 			 * Update ipha_dst to be the first hop and remove the
7650 			 * first hop from the source route (by overwriting
7651 			 * part of the option with NOP options).
7652 			 */
7653 			ipha->ipha_dst = dst;
7654 			/* Put the last entry in dst */
7655 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7656 			    3;
7657 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7658 
7659 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7660 			    ntohl(dst)));
7661 			/* Move down and overwrite */
7662 			opt[IP_ADDR_LEN] = opt[0];
7663 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7664 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7665 			for (i = 0; i < IP_ADDR_LEN; i++)
7666 				opt[i] = IPOPT_NOP;
7667 			break;
7668 		}
7669 	}
7670 	return (dst);
7671 }
7672 
7673 /*
7674  * Return the network mask
7675  * associated with the specified address.
7676  */
7677 ipaddr_t
7678 ip_net_mask(ipaddr_t addr)
7679 {
7680 	uchar_t	*up = (uchar_t *)&addr;
7681 	ipaddr_t mask = 0;
7682 	uchar_t	*maskp = (uchar_t *)&mask;
7683 
7684 #if defined(__i386) || defined(__amd64)
7685 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7686 #endif
7687 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7688 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7689 #endif
7690 	if (CLASSD(addr)) {
7691 		maskp[0] = 0xF0;
7692 		return (mask);
7693 	}
7694 
7695 	/* We assume Class E default netmask to be 32 */
7696 	if (CLASSE(addr))
7697 		return (0xffffffffU);
7698 
7699 	if (addr == 0)
7700 		return (0);
7701 	maskp[0] = 0xFF;
7702 	if ((up[0] & 0x80) == 0)
7703 		return (mask);
7704 
7705 	maskp[1] = 0xFF;
7706 	if ((up[0] & 0xC0) == 0x80)
7707 		return (mask);
7708 
7709 	maskp[2] = 0xFF;
7710 	if ((up[0] & 0xE0) == 0xC0)
7711 		return (mask);
7712 
7713 	/* Otherwise return no mask */
7714 	return ((ipaddr_t)0);
7715 }
7716 
7717 /*
7718  * Select an ill for the packet by considering load spreading across
7719  * a different ill in the group if dst_ill is part of some group.
7720  */
7721 ill_t *
7722 ip_newroute_get_dst_ill(ill_t *dst_ill)
7723 {
7724 	ill_t *ill;
7725 
7726 	/*
7727 	 * We schedule irrespective of whether the source address is
7728 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7729 	 */
7730 	ill = illgrp_scheduler(dst_ill);
7731 	if (ill == NULL)
7732 		return (NULL);
7733 
7734 	/*
7735 	 * For groups with names ip_sioctl_groupname ensures that all
7736 	 * ills are of same type. For groups without names, ifgrp_insert
7737 	 * ensures this.
7738 	 */
7739 	ASSERT(dst_ill->ill_type == ill->ill_type);
7740 
7741 	return (ill);
7742 }
7743 
7744 /*
7745  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7746  */
7747 ill_t *
7748 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7749     ip_stack_t *ipst)
7750 {
7751 	ill_t *ret_ill;
7752 
7753 	ASSERT(ifindex != 0);
7754 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7755 	    ipst);
7756 	if (ret_ill == NULL ||
7757 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7758 		if (isv6) {
7759 			if (ill != NULL) {
7760 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7761 			} else {
7762 				BUMP_MIB(&ipst->ips_ip6_mib,
7763 				    ipIfStatsOutDiscards);
7764 			}
7765 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7766 			    "bad ifindex %d.\n", ifindex));
7767 		} else {
7768 			if (ill != NULL) {
7769 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7770 			} else {
7771 				BUMP_MIB(&ipst->ips_ip_mib,
7772 				    ipIfStatsOutDiscards);
7773 			}
7774 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7775 			    "bad ifindex %d.\n", ifindex));
7776 		}
7777 		if (ret_ill != NULL)
7778 			ill_refrele(ret_ill);
7779 		freemsg(first_mp);
7780 		return (NULL);
7781 	}
7782 
7783 	return (ret_ill);
7784 }
7785 
7786 /*
7787  * IPv4 -
7788  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7789  * out a packet to a destination address for which we do not have specific
7790  * (or sufficient) routing information.
7791  *
7792  * NOTE : These are the scopes of some of the variables that point at IRE,
7793  *	  which needs to be followed while making any future modifications
7794  *	  to avoid memory leaks.
7795  *
7796  *	- ire and sire are the entries looked up initially by
7797  *	  ire_ftable_lookup.
7798  *	- ipif_ire is used to hold the interface ire associated with
7799  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7800  *	  it before branching out to error paths.
7801  *	- save_ire is initialized before ire_create, so that ire returned
7802  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7803  *	  before breaking out of the switch.
7804  *
7805  *	Thus on failures, we have to REFRELE only ire and sire, if they
7806  *	are not NULL.
7807  */
7808 void
7809 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7810     zoneid_t zoneid, ip_stack_t *ipst)
7811 {
7812 	areq_t	*areq;
7813 	ipaddr_t gw = 0;
7814 	ire_t	*ire = NULL;
7815 	mblk_t	*res_mp;
7816 	ipaddr_t *addrp;
7817 	ipaddr_t nexthop_addr;
7818 	ipif_t  *src_ipif = NULL;
7819 	ill_t	*dst_ill = NULL;
7820 	ipha_t  *ipha;
7821 	ire_t	*sire = NULL;
7822 	mblk_t	*first_mp;
7823 	ire_t	*save_ire;
7824 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7825 	ushort_t ire_marks = 0;
7826 	boolean_t mctl_present;
7827 	ipsec_out_t *io;
7828 	mblk_t	*saved_mp;
7829 	ire_t	*first_sire = NULL;
7830 	mblk_t	*copy_mp = NULL;
7831 	mblk_t	*xmit_mp = NULL;
7832 	ipaddr_t save_dst;
7833 	uint32_t multirt_flags =
7834 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7835 	boolean_t multirt_is_resolvable;
7836 	boolean_t multirt_resolve_next;
7837 	boolean_t unspec_src;
7838 	boolean_t do_attach_ill = B_FALSE;
7839 	boolean_t ip_nexthop = B_FALSE;
7840 	tsol_ire_gw_secattr_t *attrp = NULL;
7841 	tsol_gcgrp_t *gcgrp = NULL;
7842 	tsol_gcgrp_addr_t ga;
7843 
7844 	if (ip_debug > 2) {
7845 		/* ip1dbg */
7846 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7847 	}
7848 
7849 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7850 	if (mctl_present) {
7851 		io = (ipsec_out_t *)first_mp->b_rptr;
7852 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7853 		ASSERT(zoneid == io->ipsec_out_zoneid);
7854 		ASSERT(zoneid != ALL_ZONES);
7855 	}
7856 
7857 	ipha = (ipha_t *)mp->b_rptr;
7858 
7859 	/* All multicast lookups come through ip_newroute_ipif() */
7860 	if (CLASSD(dst)) {
7861 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7862 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7863 		freemsg(first_mp);
7864 		return;
7865 	}
7866 
7867 	if (mctl_present && io->ipsec_out_attach_if) {
7868 		/* ip_grab_attach_ill returns a held ill */
7869 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7870 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7871 
7872 		/* Failure case frees things for us. */
7873 		if (attach_ill == NULL)
7874 			return;
7875 
7876 		/*
7877 		 * Check if we need an ire that will not be
7878 		 * looked up by anybody else i.e. HIDDEN.
7879 		 */
7880 		if (ill_is_probeonly(attach_ill))
7881 			ire_marks = IRE_MARK_HIDDEN;
7882 	}
7883 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7884 		ip_nexthop = B_TRUE;
7885 		nexthop_addr = io->ipsec_out_nexthop_addr;
7886 	}
7887 	/*
7888 	 * If this IRE is created for forwarding or it is not for
7889 	 * traffic for congestion controlled protocols, mark it as temporary.
7890 	 */
7891 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7892 		ire_marks |= IRE_MARK_TEMPORARY;
7893 
7894 	/*
7895 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7896 	 * chain until it gets the most specific information available.
7897 	 * For example, we know that there is no IRE_CACHE for this dest,
7898 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7899 	 * ire_ftable_lookup will look up the gateway, etc.
7900 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7901 	 * to the destination, of equal netmask length in the forward table,
7902 	 * will be recursively explored. If no information is available
7903 	 * for the final gateway of that route, we force the returned ire
7904 	 * to be equal to sire using MATCH_IRE_PARENT.
7905 	 * At least, in this case we have a starting point (in the buckets)
7906 	 * to look for other routes to the destination in the forward table.
7907 	 * This is actually used only for multirouting, where a list
7908 	 * of routes has to be processed in sequence.
7909 	 *
7910 	 * In the process of coming up with the most specific information,
7911 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7912 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7913 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7914 	 * Two caveats when handling incomplete ire's in ip_newroute:
7915 	 * - we should be careful when accessing its ire_nce (specifically
7916 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7917 	 * - not all legacy code path callers are prepared to handle
7918 	 *   incomplete ire's, so we should not create/add incomplete
7919 	 *   ire_cache entries here. (See discussion about temporary solution
7920 	 *   further below).
7921 	 *
7922 	 * In order to minimize packet dropping, and to preserve existing
7923 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7924 	 * gateway, and instead use the IF_RESOLVER ire to send out
7925 	 * another request to ARP (this is achieved by passing the
7926 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7927 	 * arp response comes back in ip_wput_nondata, we will create
7928 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7929 	 *
7930 	 * Note that this is a temporary solution; the correct solution is
7931 	 * to create an incomplete  per-dst ire_cache entry, and send the
7932 	 * packet out when the gw's nce is resolved. In order to achieve this,
7933 	 * all packet processing must have been completed prior to calling
7934 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7935 	 * to be modified to accomodate this solution.
7936 	 */
7937 	if (ip_nexthop) {
7938 		/*
7939 		 * The first time we come here, we look for an IRE_INTERFACE
7940 		 * entry for the specified nexthop, set the dst to be the
7941 		 * nexthop address and create an IRE_CACHE entry for the
7942 		 * nexthop. The next time around, we are able to find an
7943 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7944 		 * nexthop address and create an IRE_CACHE entry for the
7945 		 * destination address via the specified nexthop.
7946 		 */
7947 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7948 		    MBLK_GETLABEL(mp), ipst);
7949 		if (ire != NULL) {
7950 			gw = nexthop_addr;
7951 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7952 		} else {
7953 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7954 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7955 			    MBLK_GETLABEL(mp),
7956 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7957 			    ipst);
7958 			if (ire != NULL) {
7959 				dst = nexthop_addr;
7960 			}
7961 		}
7962 	} else if (attach_ill == NULL) {
7963 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7964 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7965 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7966 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7967 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7968 		    ipst);
7969 	} else {
7970 		/*
7971 		 * attach_ill is set only for communicating with
7972 		 * on-link hosts. So, don't look for DEFAULT.
7973 		 */
7974 		ipif_t	*attach_ipif;
7975 
7976 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7977 		if (attach_ipif == NULL) {
7978 			ill_refrele(attach_ill);
7979 			goto icmp_err_ret;
7980 		}
7981 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7982 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7983 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7984 		    MATCH_IRE_SECATTR, ipst);
7985 		ipif_refrele(attach_ipif);
7986 	}
7987 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7988 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7989 
7990 	/*
7991 	 * This loop is run only once in most cases.
7992 	 * We loop to resolve further routes only when the destination
7993 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7994 	 */
7995 	do {
7996 		/* Clear the previous iteration's values */
7997 		if (src_ipif != NULL) {
7998 			ipif_refrele(src_ipif);
7999 			src_ipif = NULL;
8000 		}
8001 		if (dst_ill != NULL) {
8002 			ill_refrele(dst_ill);
8003 			dst_ill = NULL;
8004 		}
8005 
8006 		multirt_resolve_next = B_FALSE;
8007 		/*
8008 		 * We check if packets have to be multirouted.
8009 		 * In this case, given the current <ire, sire> couple,
8010 		 * we look for the next suitable <ire, sire>.
8011 		 * This check is done in ire_multirt_lookup(),
8012 		 * which applies various criteria to find the next route
8013 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8014 		 * unchanged if it detects it has not been tried yet.
8015 		 */
8016 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8017 			ip3dbg(("ip_newroute: starting next_resolution "
8018 			    "with first_mp %p, tag %d\n",
8019 			    (void *)first_mp,
8020 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8021 
8022 			ASSERT(sire != NULL);
8023 			multirt_is_resolvable =
8024 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8025 			    MBLK_GETLABEL(mp), ipst);
8026 
8027 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8028 			    "ire %p, sire %p\n",
8029 			    multirt_is_resolvable,
8030 			    (void *)ire, (void *)sire));
8031 
8032 			if (!multirt_is_resolvable) {
8033 				/*
8034 				 * No more multirt route to resolve; give up
8035 				 * (all routes resolved or no more
8036 				 * resolvable routes).
8037 				 */
8038 				if (ire != NULL) {
8039 					ire_refrele(ire);
8040 					ire = NULL;
8041 				}
8042 			} else {
8043 				ASSERT(sire != NULL);
8044 				ASSERT(ire != NULL);
8045 				/*
8046 				 * We simply use first_sire as a flag that
8047 				 * indicates if a resolvable multirt route
8048 				 * has already been found.
8049 				 * If it is not the case, we may have to send
8050 				 * an ICMP error to report that the
8051 				 * destination is unreachable.
8052 				 * We do not IRE_REFHOLD first_sire.
8053 				 */
8054 				if (first_sire == NULL) {
8055 					first_sire = sire;
8056 				}
8057 			}
8058 		}
8059 		if (ire == NULL) {
8060 			if (ip_debug > 3) {
8061 				/* ip2dbg */
8062 				pr_addr_dbg("ip_newroute: "
8063 				    "can't resolve %s\n", AF_INET, &dst);
8064 			}
8065 			ip3dbg(("ip_newroute: "
8066 			    "ire %p, sire %p, first_sire %p\n",
8067 			    (void *)ire, (void *)sire, (void *)first_sire));
8068 
8069 			if (sire != NULL) {
8070 				ire_refrele(sire);
8071 				sire = NULL;
8072 			}
8073 
8074 			if (first_sire != NULL) {
8075 				/*
8076 				 * At least one multirt route has been found
8077 				 * in the same call to ip_newroute();
8078 				 * there is no need to report an ICMP error.
8079 				 * first_sire was not IRE_REFHOLDed.
8080 				 */
8081 				MULTIRT_DEBUG_UNTAG(first_mp);
8082 				freemsg(first_mp);
8083 				return;
8084 			}
8085 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8086 			    RTA_DST, ipst);
8087 			if (attach_ill != NULL)
8088 				ill_refrele(attach_ill);
8089 			goto icmp_err_ret;
8090 		}
8091 
8092 		/*
8093 		 * Verify that the returned IRE does not have either
8094 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8095 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8096 		 */
8097 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8098 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8099 			if (attach_ill != NULL)
8100 				ill_refrele(attach_ill);
8101 			goto icmp_err_ret;
8102 		}
8103 		/*
8104 		 * Increment the ire_ob_pkt_count field for ire if it is an
8105 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8106 		 * increment the same for the parent IRE, sire, if it is some
8107 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8108 		 */
8109 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8110 			UPDATE_OB_PKT_COUNT(ire);
8111 			ire->ire_last_used_time = lbolt;
8112 		}
8113 
8114 		if (sire != NULL) {
8115 			gw = sire->ire_gateway_addr;
8116 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8117 			    IRE_INTERFACE)) == 0);
8118 			UPDATE_OB_PKT_COUNT(sire);
8119 			sire->ire_last_used_time = lbolt;
8120 		}
8121 		/*
8122 		 * We have a route to reach the destination.
8123 		 *
8124 		 * 1) If the interface is part of ill group, try to get a new
8125 		 *    ill taking load spreading into account.
8126 		 *
8127 		 * 2) After selecting the ill, get a source address that
8128 		 *    might create good inbound load spreading.
8129 		 *    ipif_select_source does this for us.
8130 		 *
8131 		 * If the application specified the ill (ifindex), we still
8132 		 * load spread. Only if the packets needs to go out
8133 		 * specifically on a given ill e.g. binding to
8134 		 * IPIF_NOFAILOVER address, then we don't try to use a
8135 		 * different ill for load spreading.
8136 		 */
8137 		if (attach_ill == NULL) {
8138 			/*
8139 			 * Don't perform outbound load spreading in the
8140 			 * case of an RTF_MULTIRT route, as we actually
8141 			 * typically want to replicate outgoing packets
8142 			 * through particular interfaces.
8143 			 */
8144 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8145 				dst_ill = ire->ire_ipif->ipif_ill;
8146 				/* for uniformity */
8147 				ill_refhold(dst_ill);
8148 			} else {
8149 				/*
8150 				 * If we are here trying to create an IRE_CACHE
8151 				 * for an offlink destination and have the
8152 				 * IRE_CACHE for the next hop and the latter is
8153 				 * using virtual IP source address selection i.e
8154 				 * it's ire->ire_ipif is pointing to a virtual
8155 				 * network interface (vni) then
8156 				 * ip_newroute_get_dst_ll() will return the vni
8157 				 * interface as the dst_ill. Since the vni is
8158 				 * virtual i.e not associated with any physical
8159 				 * interface, it cannot be the dst_ill, hence
8160 				 * in such a case call ip_newroute_get_dst_ll()
8161 				 * with the stq_ill instead of the ire_ipif ILL.
8162 				 * The function returns a refheld ill.
8163 				 */
8164 				if ((ire->ire_type == IRE_CACHE) &&
8165 				    IS_VNI(ire->ire_ipif->ipif_ill))
8166 					dst_ill = ip_newroute_get_dst_ill(
8167 					    ire->ire_stq->q_ptr);
8168 				else
8169 					dst_ill = ip_newroute_get_dst_ill(
8170 					    ire->ire_ipif->ipif_ill);
8171 			}
8172 			if (dst_ill == NULL) {
8173 				if (ip_debug > 2) {
8174 					pr_addr_dbg("ip_newroute: "
8175 					    "no dst ill for dst"
8176 					    " %s\n", AF_INET, &dst);
8177 				}
8178 				goto icmp_err_ret;
8179 			}
8180 		} else {
8181 			dst_ill = ire->ire_ipif->ipif_ill;
8182 			/* for uniformity */
8183 			ill_refhold(dst_ill);
8184 			/*
8185 			 * We should have found a route matching ill as we
8186 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8187 			 * Rather than asserting, when there is a mismatch,
8188 			 * we just drop the packet.
8189 			 */
8190 			if (dst_ill != attach_ill) {
8191 				ip0dbg(("ip_newroute: Packet dropped as "
8192 				    "IPIF_NOFAILOVER ill is %s, "
8193 				    "ire->ire_ipif->ipif_ill is %s\n",
8194 				    attach_ill->ill_name,
8195 				    dst_ill->ill_name));
8196 				ill_refrele(attach_ill);
8197 				goto icmp_err_ret;
8198 			}
8199 		}
8200 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8201 		if (attach_ill != NULL) {
8202 			ill_refrele(attach_ill);
8203 			attach_ill = NULL;
8204 			do_attach_ill = B_TRUE;
8205 		}
8206 		ASSERT(dst_ill != NULL);
8207 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8208 
8209 		/*
8210 		 * Pick the best source address from dst_ill.
8211 		 *
8212 		 * 1) If it is part of a multipathing group, we would
8213 		 *    like to spread the inbound packets across different
8214 		 *    interfaces. ipif_select_source picks a random source
8215 		 *    across the different ills in the group.
8216 		 *
8217 		 * 2) If it is not part of a multipathing group, we try
8218 		 *    to pick the source address from the destination
8219 		 *    route. Clustering assumes that when we have multiple
8220 		 *    prefixes hosted on an interface, the prefix of the
8221 		 *    source address matches the prefix of the destination
8222 		 *    route. We do this only if the address is not
8223 		 *    DEPRECATED.
8224 		 *
8225 		 * 3) If the conn is in a different zone than the ire, we
8226 		 *    need to pick a source address from the right zone.
8227 		 *
8228 		 * NOTE : If we hit case (1) above, the prefix of the source
8229 		 *	  address picked may not match the prefix of the
8230 		 *	  destination routes prefix as ipif_select_source
8231 		 *	  does not look at "dst" while picking a source
8232 		 *	  address.
8233 		 *	  If we want the same behavior as (2), we will need
8234 		 *	  to change the behavior of ipif_select_source.
8235 		 */
8236 		ASSERT(src_ipif == NULL);
8237 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8238 			/*
8239 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8240 			 * Check that the ipif matching the requested source
8241 			 * address still exists.
8242 			 */
8243 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8244 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8245 		}
8246 
8247 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8248 
8249 		if (src_ipif == NULL &&
8250 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8251 			ire_marks |= IRE_MARK_USESRC_CHECK;
8252 			if ((dst_ill->ill_group != NULL) ||
8253 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8254 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8255 			    ire->ire_zoneid != ALL_ZONES) ||
8256 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8257 				/*
8258 				 * If the destination is reachable via a
8259 				 * given gateway, the selected source address
8260 				 * should be in the same subnet as the gateway.
8261 				 * Otherwise, the destination is not reachable.
8262 				 *
8263 				 * If there are no interfaces on the same subnet
8264 				 * as the destination, ipif_select_source gives
8265 				 * first non-deprecated interface which might be
8266 				 * on a different subnet than the gateway.
8267 				 * This is not desirable. Hence pass the dst_ire
8268 				 * source address to ipif_select_source.
8269 				 * It is sure that the destination is reachable
8270 				 * with the dst_ire source address subnet.
8271 				 * So passing dst_ire source address to
8272 				 * ipif_select_source will make sure that the
8273 				 * selected source will be on the same subnet
8274 				 * as dst_ire source address.
8275 				 */
8276 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8277 				src_ipif = ipif_select_source(dst_ill, saddr,
8278 				    zoneid);
8279 				if (src_ipif == NULL) {
8280 					if (ip_debug > 2) {
8281 						pr_addr_dbg("ip_newroute: "
8282 						    "no src for dst %s ",
8283 						    AF_INET, &dst);
8284 						printf("through interface %s\n",
8285 						    dst_ill->ill_name);
8286 					}
8287 					goto icmp_err_ret;
8288 				}
8289 			} else {
8290 				src_ipif = ire->ire_ipif;
8291 				ASSERT(src_ipif != NULL);
8292 				/* hold src_ipif for uniformity */
8293 				ipif_refhold(src_ipif);
8294 			}
8295 		}
8296 
8297 		/*
8298 		 * Assign a source address while we have the conn.
8299 		 * We can't have ip_wput_ire pick a source address when the
8300 		 * packet returns from arp since we need to look at
8301 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8302 		 * going through arp.
8303 		 *
8304 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8305 		 *	  it uses ip6i to store this information.
8306 		 */
8307 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8308 			ipha->ipha_src = src_ipif->ipif_src_addr;
8309 
8310 		if (ip_debug > 3) {
8311 			/* ip2dbg */
8312 			pr_addr_dbg("ip_newroute: first hop %s\n",
8313 			    AF_INET, &gw);
8314 		}
8315 		ip2dbg(("\tire type %s (%d)\n",
8316 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8317 
8318 		/*
8319 		 * The TTL of multirouted packets is bounded by the
8320 		 * ip_multirt_ttl ndd variable.
8321 		 */
8322 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8323 			/* Force TTL of multirouted packets */
8324 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8325 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8326 				ip2dbg(("ip_newroute: forcing multirt TTL "
8327 				    "to %d (was %d), dst 0x%08x\n",
8328 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8329 				    ntohl(sire->ire_addr)));
8330 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8331 			}
8332 		}
8333 		/*
8334 		 * At this point in ip_newroute(), ire is either the
8335 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8336 		 * destination or an IRE_INTERFACE type that should be used
8337 		 * to resolve an on-subnet destination or an on-subnet
8338 		 * next-hop gateway.
8339 		 *
8340 		 * In the IRE_CACHE case, we have the following :
8341 		 *
8342 		 * 1) src_ipif - used for getting a source address.
8343 		 *
8344 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8345 		 *    means packets using this IRE_CACHE will go out on
8346 		 *    dst_ill.
8347 		 *
8348 		 * 3) The IRE sire will point to the prefix that is the
8349 		 *    longest  matching route for the destination. These
8350 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8351 		 *
8352 		 *    The newly created IRE_CACHE entry for the off-subnet
8353 		 *    destination is tied to both the prefix route and the
8354 		 *    interface route used to resolve the next-hop gateway
8355 		 *    via the ire_phandle and ire_ihandle fields,
8356 		 *    respectively.
8357 		 *
8358 		 * In the IRE_INTERFACE case, we have the following :
8359 		 *
8360 		 * 1) src_ipif - used for getting a source address.
8361 		 *
8362 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8363 		 *    means packets using the IRE_CACHE that we will build
8364 		 *    here will go out on dst_ill.
8365 		 *
8366 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8367 		 *    to be created will only be tied to the IRE_INTERFACE
8368 		 *    that was derived from the ire_ihandle field.
8369 		 *
8370 		 *    If sire is non-NULL, it means the destination is
8371 		 *    off-link and we will first create the IRE_CACHE for the
8372 		 *    gateway. Next time through ip_newroute, we will create
8373 		 *    the IRE_CACHE for the final destination as described
8374 		 *    above.
8375 		 *
8376 		 * In both cases, after the current resolution has been
8377 		 * completed (or possibly initialised, in the IRE_INTERFACE
8378 		 * case), the loop may be re-entered to attempt the resolution
8379 		 * of another RTF_MULTIRT route.
8380 		 *
8381 		 * When an IRE_CACHE entry for the off-subnet destination is
8382 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8383 		 * for further processing in emission loops.
8384 		 */
8385 		save_ire = ire;
8386 		switch (ire->ire_type) {
8387 		case IRE_CACHE: {
8388 			ire_t	*ipif_ire;
8389 
8390 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8391 			if (gw == 0)
8392 				gw = ire->ire_gateway_addr;
8393 			/*
8394 			 * We need 3 ire's to create a new cache ire for an
8395 			 * off-link destination from the cache ire of the
8396 			 * gateway.
8397 			 *
8398 			 *	1. The prefix ire 'sire' (Note that this does
8399 			 *	   not apply to the conn_nexthop_set case)
8400 			 *	2. The cache ire of the gateway 'ire'
8401 			 *	3. The interface ire 'ipif_ire'
8402 			 *
8403 			 * We have (1) and (2). We lookup (3) below.
8404 			 *
8405 			 * If there is no interface route to the gateway,
8406 			 * it is a race condition, where we found the cache
8407 			 * but the interface route has been deleted.
8408 			 */
8409 			if (ip_nexthop) {
8410 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8411 			} else {
8412 				ipif_ire =
8413 				    ire_ihandle_lookup_offlink(ire, sire);
8414 			}
8415 			if (ipif_ire == NULL) {
8416 				ip1dbg(("ip_newroute: "
8417 				    "ire_ihandle_lookup_offlink failed\n"));
8418 				goto icmp_err_ret;
8419 			}
8420 
8421 			/*
8422 			 * Check cached gateway IRE for any security
8423 			 * attributes; if found, associate the gateway
8424 			 * credentials group to the destination IRE.
8425 			 */
8426 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8427 				mutex_enter(&attrp->igsa_lock);
8428 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8429 					GCGRP_REFHOLD(gcgrp);
8430 				mutex_exit(&attrp->igsa_lock);
8431 			}
8432 
8433 			/*
8434 			 * XXX For the source of the resolver mp,
8435 			 * we are using the same DL_UNITDATA_REQ
8436 			 * (from save_ire->ire_nce->nce_res_mp)
8437 			 * though the save_ire is not pointing at the same ill.
8438 			 * This is incorrect. We need to send it up to the
8439 			 * resolver to get the right res_mp. For ethernets
8440 			 * this may be okay (ill_type == DL_ETHER).
8441 			 */
8442 
8443 			ire = ire_create(
8444 			    (uchar_t *)&dst,		/* dest address */
8445 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8446 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8447 			    (uchar_t *)&gw,		/* gateway address */
8448 			    &save_ire->ire_max_frag,
8449 			    save_ire->ire_nce,		/* src nce */
8450 			    dst_ill->ill_rq,		/* recv-from queue */
8451 			    dst_ill->ill_wq,		/* send-to queue */
8452 			    IRE_CACHE,			/* IRE type */
8453 			    src_ipif,
8454 			    (sire != NULL) ?
8455 			    sire->ire_mask : 0, 	/* Parent mask */
8456 			    (sire != NULL) ?
8457 			    sire->ire_phandle : 0,	/* Parent handle */
8458 			    ipif_ire->ire_ihandle,	/* Interface handle */
8459 			    (sire != NULL) ? (sire->ire_flags &
8460 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8461 			    (sire != NULL) ?
8462 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8463 			    NULL,
8464 			    gcgrp,
8465 			    ipst);
8466 
8467 			if (ire == NULL) {
8468 				if (gcgrp != NULL) {
8469 					GCGRP_REFRELE(gcgrp);
8470 					gcgrp = NULL;
8471 				}
8472 				ire_refrele(ipif_ire);
8473 				ire_refrele(save_ire);
8474 				break;
8475 			}
8476 
8477 			/* reference now held by IRE */
8478 			gcgrp = NULL;
8479 
8480 			ire->ire_marks |= ire_marks;
8481 
8482 			/*
8483 			 * Prevent sire and ipif_ire from getting deleted.
8484 			 * The newly created ire is tied to both of them via
8485 			 * the phandle and ihandle respectively.
8486 			 */
8487 			if (sire != NULL) {
8488 				IRB_REFHOLD(sire->ire_bucket);
8489 				/* Has it been removed already ? */
8490 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8491 					IRB_REFRELE(sire->ire_bucket);
8492 					ire_refrele(ipif_ire);
8493 					ire_refrele(save_ire);
8494 					break;
8495 				}
8496 			}
8497 
8498 			IRB_REFHOLD(ipif_ire->ire_bucket);
8499 			/* Has it been removed already ? */
8500 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8501 				IRB_REFRELE(ipif_ire->ire_bucket);
8502 				if (sire != NULL)
8503 					IRB_REFRELE(sire->ire_bucket);
8504 				ire_refrele(ipif_ire);
8505 				ire_refrele(save_ire);
8506 				break;
8507 			}
8508 
8509 			xmit_mp = first_mp;
8510 			/*
8511 			 * In the case of multirouting, a copy
8512 			 * of the packet is done before its sending.
8513 			 * The copy is used to attempt another
8514 			 * route resolution, in a next loop.
8515 			 */
8516 			if (ire->ire_flags & RTF_MULTIRT) {
8517 				copy_mp = copymsg(first_mp);
8518 				if (copy_mp != NULL) {
8519 					xmit_mp = copy_mp;
8520 					MULTIRT_DEBUG_TAG(first_mp);
8521 				}
8522 			}
8523 			ire_add_then_send(q, ire, xmit_mp);
8524 			ire_refrele(save_ire);
8525 
8526 			/* Assert that sire is not deleted yet. */
8527 			if (sire != NULL) {
8528 				ASSERT(sire->ire_ptpn != NULL);
8529 				IRB_REFRELE(sire->ire_bucket);
8530 			}
8531 
8532 			/* Assert that ipif_ire is not deleted yet. */
8533 			ASSERT(ipif_ire->ire_ptpn != NULL);
8534 			IRB_REFRELE(ipif_ire->ire_bucket);
8535 			ire_refrele(ipif_ire);
8536 
8537 			/*
8538 			 * If copy_mp is not NULL, multirouting was
8539 			 * requested. We loop to initiate a next
8540 			 * route resolution attempt, starting from sire.
8541 			 */
8542 			if (copy_mp != NULL) {
8543 				/*
8544 				 * Search for the next unresolved
8545 				 * multirt route.
8546 				 */
8547 				copy_mp = NULL;
8548 				ipif_ire = NULL;
8549 				ire = NULL;
8550 				multirt_resolve_next = B_TRUE;
8551 				continue;
8552 			}
8553 			if (sire != NULL)
8554 				ire_refrele(sire);
8555 			ipif_refrele(src_ipif);
8556 			ill_refrele(dst_ill);
8557 			return;
8558 		}
8559 		case IRE_IF_NORESOLVER: {
8560 
8561 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8562 			    dst_ill->ill_resolver_mp == NULL) {
8563 				ip1dbg(("ip_newroute: dst_ill %p "
8564 				    "for IRE_IF_NORESOLVER ire %p has "
8565 				    "no ill_resolver_mp\n",
8566 				    (void *)dst_ill, (void *)ire));
8567 				break;
8568 			}
8569 
8570 			/*
8571 			 * TSol note: We are creating the ire cache for the
8572 			 * destination 'dst'. If 'dst' is offlink, going
8573 			 * through the first hop 'gw', the security attributes
8574 			 * of 'dst' must be set to point to the gateway
8575 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8576 			 * is possible that 'dst' is a potential gateway that is
8577 			 * referenced by some route that has some security
8578 			 * attributes. Thus in the former case, we need to do a
8579 			 * gcgrp_lookup of 'gw' while in the latter case we
8580 			 * need to do gcgrp_lookup of 'dst' itself.
8581 			 */
8582 			ga.ga_af = AF_INET;
8583 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8584 			    &ga.ga_addr);
8585 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8586 
8587 			ire = ire_create(
8588 			    (uchar_t *)&dst,		/* dest address */
8589 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8590 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8591 			    (uchar_t *)&gw,		/* gateway address */
8592 			    &save_ire->ire_max_frag,
8593 			    NULL,			/* no src nce */
8594 			    dst_ill->ill_rq,		/* recv-from queue */
8595 			    dst_ill->ill_wq,		/* send-to queue */
8596 			    IRE_CACHE,
8597 			    src_ipif,
8598 			    save_ire->ire_mask,		/* Parent mask */
8599 			    (sire != NULL) ?		/* Parent handle */
8600 			    sire->ire_phandle : 0,
8601 			    save_ire->ire_ihandle,	/* Interface handle */
8602 			    (sire != NULL) ? sire->ire_flags &
8603 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8604 			    &(save_ire->ire_uinfo),
8605 			    NULL,
8606 			    gcgrp,
8607 			    ipst);
8608 
8609 			if (ire == NULL) {
8610 				if (gcgrp != NULL) {
8611 					GCGRP_REFRELE(gcgrp);
8612 					gcgrp = NULL;
8613 				}
8614 				ire_refrele(save_ire);
8615 				break;
8616 			}
8617 
8618 			/* reference now held by IRE */
8619 			gcgrp = NULL;
8620 
8621 			ire->ire_marks |= ire_marks;
8622 
8623 			/* Prevent save_ire from getting deleted */
8624 			IRB_REFHOLD(save_ire->ire_bucket);
8625 			/* Has it been removed already ? */
8626 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8627 				IRB_REFRELE(save_ire->ire_bucket);
8628 				ire_refrele(save_ire);
8629 				break;
8630 			}
8631 
8632 			/*
8633 			 * In the case of multirouting, a copy
8634 			 * of the packet is made before it is sent.
8635 			 * The copy is used in the next
8636 			 * loop to attempt another resolution.
8637 			 */
8638 			xmit_mp = first_mp;
8639 			if ((sire != NULL) &&
8640 			    (sire->ire_flags & RTF_MULTIRT)) {
8641 				copy_mp = copymsg(first_mp);
8642 				if (copy_mp != NULL) {
8643 					xmit_mp = copy_mp;
8644 					MULTIRT_DEBUG_TAG(first_mp);
8645 				}
8646 			}
8647 			ire_add_then_send(q, ire, xmit_mp);
8648 
8649 			/* Assert that it is not deleted yet. */
8650 			ASSERT(save_ire->ire_ptpn != NULL);
8651 			IRB_REFRELE(save_ire->ire_bucket);
8652 			ire_refrele(save_ire);
8653 
8654 			if (copy_mp != NULL) {
8655 				/*
8656 				 * If we found a (no)resolver, we ignore any
8657 				 * trailing top priority IRE_CACHE in further
8658 				 * loops. This ensures that we do not omit any
8659 				 * (no)resolver.
8660 				 * This IRE_CACHE, if any, will be processed
8661 				 * by another thread entering ip_newroute().
8662 				 * IRE_CACHE entries, if any, will be processed
8663 				 * by another thread entering ip_newroute(),
8664 				 * (upon resolver response, for instance).
8665 				 * This aims to force parallel multirt
8666 				 * resolutions as soon as a packet must be sent.
8667 				 * In the best case, after the tx of only one
8668 				 * packet, all reachable routes are resolved.
8669 				 * Otherwise, the resolution of all RTF_MULTIRT
8670 				 * routes would require several emissions.
8671 				 */
8672 				multirt_flags &= ~MULTIRT_CACHEGW;
8673 
8674 				/*
8675 				 * Search for the next unresolved multirt
8676 				 * route.
8677 				 */
8678 				copy_mp = NULL;
8679 				save_ire = NULL;
8680 				ire = NULL;
8681 				multirt_resolve_next = B_TRUE;
8682 				continue;
8683 			}
8684 
8685 			/*
8686 			 * Don't need sire anymore
8687 			 */
8688 			if (sire != NULL)
8689 				ire_refrele(sire);
8690 
8691 			ipif_refrele(src_ipif);
8692 			ill_refrele(dst_ill);
8693 			return;
8694 		}
8695 		case IRE_IF_RESOLVER:
8696 			/*
8697 			 * We can't build an IRE_CACHE yet, but at least we
8698 			 * found a resolver that can help.
8699 			 */
8700 			res_mp = dst_ill->ill_resolver_mp;
8701 			if (!OK_RESOLVER_MP(res_mp))
8702 				break;
8703 
8704 			/*
8705 			 * To be at this point in the code with a non-zero gw
8706 			 * means that dst is reachable through a gateway that
8707 			 * we have never resolved.  By changing dst to the gw
8708 			 * addr we resolve the gateway first.
8709 			 * When ire_add_then_send() tries to put the IP dg
8710 			 * to dst, it will reenter ip_newroute() at which
8711 			 * time we will find the IRE_CACHE for the gw and
8712 			 * create another IRE_CACHE in case IRE_CACHE above.
8713 			 */
8714 			if (gw != INADDR_ANY) {
8715 				/*
8716 				 * The source ipif that was determined above was
8717 				 * relative to the destination address, not the
8718 				 * gateway's. If src_ipif was not taken out of
8719 				 * the IRE_IF_RESOLVER entry, we'll need to call
8720 				 * ipif_select_source() again.
8721 				 */
8722 				if (src_ipif != ire->ire_ipif) {
8723 					ipif_refrele(src_ipif);
8724 					src_ipif = ipif_select_source(dst_ill,
8725 					    gw, zoneid);
8726 					if (src_ipif == NULL) {
8727 						if (ip_debug > 2) {
8728 							pr_addr_dbg(
8729 							    "ip_newroute: no "
8730 							    "src for gw %s ",
8731 							    AF_INET, &gw);
8732 							printf("through "
8733 							    "interface %s\n",
8734 							    dst_ill->ill_name);
8735 						}
8736 						goto icmp_err_ret;
8737 					}
8738 				}
8739 				save_dst = dst;
8740 				dst = gw;
8741 				gw = INADDR_ANY;
8742 			}
8743 
8744 			/*
8745 			 * We obtain a partial IRE_CACHE which we will pass
8746 			 * along with the resolver query.  When the response
8747 			 * comes back it will be there ready for us to add.
8748 			 * The ire_max_frag is atomically set under the
8749 			 * irebucket lock in ire_add_v[46].
8750 			 */
8751 
8752 			ire = ire_create_mp(
8753 			    (uchar_t *)&dst,		/* dest address */
8754 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8755 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8756 			    (uchar_t *)&gw,		/* gateway address */
8757 			    NULL,			/* ire_max_frag */
8758 			    NULL,			/* no src nce */
8759 			    dst_ill->ill_rq,		/* recv-from queue */
8760 			    dst_ill->ill_wq,		/* send-to queue */
8761 			    IRE_CACHE,
8762 			    src_ipif,			/* Interface ipif */
8763 			    save_ire->ire_mask,		/* Parent mask */
8764 			    0,
8765 			    save_ire->ire_ihandle,	/* Interface handle */
8766 			    0,				/* flags if any */
8767 			    &(save_ire->ire_uinfo),
8768 			    NULL,
8769 			    NULL,
8770 			    ipst);
8771 
8772 			if (ire == NULL) {
8773 				ire_refrele(save_ire);
8774 				break;
8775 			}
8776 
8777 			if ((sire != NULL) &&
8778 			    (sire->ire_flags & RTF_MULTIRT)) {
8779 				copy_mp = copymsg(first_mp);
8780 				if (copy_mp != NULL)
8781 					MULTIRT_DEBUG_TAG(copy_mp);
8782 			}
8783 
8784 			ire->ire_marks |= ire_marks;
8785 
8786 			/*
8787 			 * Construct message chain for the resolver
8788 			 * of the form:
8789 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8790 			 * Packet could contain a IPSEC_OUT mp.
8791 			 *
8792 			 * NOTE : ire will be added later when the response
8793 			 * comes back from ARP. If the response does not
8794 			 * come back, ARP frees the packet. For this reason,
8795 			 * we can't REFHOLD the bucket of save_ire to prevent
8796 			 * deletions. We may not be able to REFRELE the bucket
8797 			 * if the response never comes back. Thus, before
8798 			 * adding the ire, ire_add_v4 will make sure that the
8799 			 * interface route does not get deleted. This is the
8800 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8801 			 * where we can always prevent deletions because of
8802 			 * the synchronous nature of adding IRES i.e
8803 			 * ire_add_then_send is called after creating the IRE.
8804 			 */
8805 			ASSERT(ire->ire_mp != NULL);
8806 			ire->ire_mp->b_cont = first_mp;
8807 			/* Have saved_mp handy, for cleanup if canput fails */
8808 			saved_mp = mp;
8809 			mp = copyb(res_mp);
8810 			if (mp == NULL) {
8811 				/* Prepare for cleanup */
8812 				mp = saved_mp; /* pkt */
8813 				ire_delete(ire); /* ire_mp */
8814 				ire = NULL;
8815 				ire_refrele(save_ire);
8816 				if (copy_mp != NULL) {
8817 					MULTIRT_DEBUG_UNTAG(copy_mp);
8818 					freemsg(copy_mp);
8819 					copy_mp = NULL;
8820 				}
8821 				break;
8822 			}
8823 			linkb(mp, ire->ire_mp);
8824 
8825 			/*
8826 			 * Fill in the source and dest addrs for the resolver.
8827 			 * NOTE: this depends on memory layouts imposed by
8828 			 * ill_init().
8829 			 */
8830 			areq = (areq_t *)mp->b_rptr;
8831 			addrp = (ipaddr_t *)((char *)areq +
8832 			    areq->areq_sender_addr_offset);
8833 			if (do_attach_ill) {
8834 				/*
8835 				 * This is bind to no failover case.
8836 				 * arp packet also must go out on attach_ill.
8837 				 */
8838 				ASSERT(ipha->ipha_src != NULL);
8839 				*addrp = ipha->ipha_src;
8840 			} else {
8841 				*addrp = save_ire->ire_src_addr;
8842 			}
8843 
8844 			ire_refrele(save_ire);
8845 			addrp = (ipaddr_t *)((char *)areq +
8846 			    areq->areq_target_addr_offset);
8847 			*addrp = dst;
8848 			/* Up to the resolver. */
8849 			if (canputnext(dst_ill->ill_rq) &&
8850 			    !(dst_ill->ill_arp_closing)) {
8851 				putnext(dst_ill->ill_rq, mp);
8852 				ire = NULL;
8853 				if (copy_mp != NULL) {
8854 					/*
8855 					 * If we found a resolver, we ignore
8856 					 * any trailing top priority IRE_CACHE
8857 					 * in the further loops. This ensures
8858 					 * that we do not omit any resolver.
8859 					 * IRE_CACHE entries, if any, will be
8860 					 * processed next time we enter
8861 					 * ip_newroute().
8862 					 */
8863 					multirt_flags &= ~MULTIRT_CACHEGW;
8864 					/*
8865 					 * Search for the next unresolved
8866 					 * multirt route.
8867 					 */
8868 					first_mp = copy_mp;
8869 					copy_mp = NULL;
8870 					/* Prepare the next resolution loop. */
8871 					mp = first_mp;
8872 					EXTRACT_PKT_MP(mp, first_mp,
8873 					    mctl_present);
8874 					if (mctl_present)
8875 						io = (ipsec_out_t *)
8876 						    first_mp->b_rptr;
8877 					ipha = (ipha_t *)mp->b_rptr;
8878 
8879 					ASSERT(sire != NULL);
8880 
8881 					dst = save_dst;
8882 					multirt_resolve_next = B_TRUE;
8883 					continue;
8884 				}
8885 
8886 				if (sire != NULL)
8887 					ire_refrele(sire);
8888 
8889 				/*
8890 				 * The response will come back in ip_wput
8891 				 * with db_type IRE_DB_TYPE.
8892 				 */
8893 				ipif_refrele(src_ipif);
8894 				ill_refrele(dst_ill);
8895 				return;
8896 			} else {
8897 				/* Prepare for cleanup */
8898 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8899 				    mp);
8900 				mp->b_cont = NULL;
8901 				freeb(mp); /* areq */
8902 				/*
8903 				 * this is an ire that is not added to the
8904 				 * cache. ire_freemblk will handle the release
8905 				 * of any resources associated with the ire.
8906 				 */
8907 				ire_delete(ire); /* ire_mp */
8908 				mp = saved_mp; /* pkt */
8909 				ire = NULL;
8910 				if (copy_mp != NULL) {
8911 					MULTIRT_DEBUG_UNTAG(copy_mp);
8912 					freemsg(copy_mp);
8913 					copy_mp = NULL;
8914 				}
8915 				break;
8916 			}
8917 		default:
8918 			break;
8919 		}
8920 	} while (multirt_resolve_next);
8921 
8922 	ip1dbg(("ip_newroute: dropped\n"));
8923 	/* Did this packet originate externally? */
8924 	if (mp->b_prev) {
8925 		mp->b_next = NULL;
8926 		mp->b_prev = NULL;
8927 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8928 	} else {
8929 		if (dst_ill != NULL) {
8930 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8931 		} else {
8932 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8933 		}
8934 	}
8935 	ASSERT(copy_mp == NULL);
8936 	MULTIRT_DEBUG_UNTAG(first_mp);
8937 	freemsg(first_mp);
8938 	if (ire != NULL)
8939 		ire_refrele(ire);
8940 	if (sire != NULL)
8941 		ire_refrele(sire);
8942 	if (src_ipif != NULL)
8943 		ipif_refrele(src_ipif);
8944 	if (dst_ill != NULL)
8945 		ill_refrele(dst_ill);
8946 	return;
8947 
8948 icmp_err_ret:
8949 	ip1dbg(("ip_newroute: no route\n"));
8950 	if (src_ipif != NULL)
8951 		ipif_refrele(src_ipif);
8952 	if (dst_ill != NULL)
8953 		ill_refrele(dst_ill);
8954 	if (sire != NULL)
8955 		ire_refrele(sire);
8956 	/* Did this packet originate externally? */
8957 	if (mp->b_prev) {
8958 		mp->b_next = NULL;
8959 		mp->b_prev = NULL;
8960 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8961 		q = WR(q);
8962 	} else {
8963 		/*
8964 		 * There is no outgoing ill, so just increment the
8965 		 * system MIB.
8966 		 */
8967 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8968 		/*
8969 		 * Since ip_wput() isn't close to finished, we fill
8970 		 * in enough of the header for credible error reporting.
8971 		 */
8972 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8973 			/* Failed */
8974 			MULTIRT_DEBUG_UNTAG(first_mp);
8975 			freemsg(first_mp);
8976 			if (ire != NULL)
8977 				ire_refrele(ire);
8978 			return;
8979 		}
8980 	}
8981 
8982 	/*
8983 	 * At this point we will have ire only if RTF_BLACKHOLE
8984 	 * or RTF_REJECT flags are set on the IRE. It will not
8985 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8986 	 */
8987 	if (ire != NULL) {
8988 		if (ire->ire_flags & RTF_BLACKHOLE) {
8989 			ire_refrele(ire);
8990 			MULTIRT_DEBUG_UNTAG(first_mp);
8991 			freemsg(first_mp);
8992 			return;
8993 		}
8994 		ire_refrele(ire);
8995 	}
8996 	if (ip_source_routed(ipha, ipst)) {
8997 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8998 		    zoneid, ipst);
8999 		return;
9000 	}
9001 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9002 }
9003 
9004 ip_opt_info_t zero_info;
9005 
9006 /*
9007  * IPv4 -
9008  * ip_newroute_ipif is called by ip_wput_multicast and
9009  * ip_rput_forward_multicast whenever we need to send
9010  * out a packet to a destination address for which we do not have specific
9011  * routing information. It is used when the packet will be sent out
9012  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9013  * socket option is set or icmp error message wants to go out on a particular
9014  * interface for a unicast packet.
9015  *
9016  * In most cases, the destination address is resolved thanks to the ipif
9017  * intrinsic resolver. However, there are some cases where the call to
9018  * ip_newroute_ipif must take into account the potential presence of
9019  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9020  * that uses the interface. This is specified through flags,
9021  * which can be a combination of:
9022  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9023  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9024  *   and flags. Additionally, the packet source address has to be set to
9025  *   the specified address. The caller is thus expected to set this flag
9026  *   if the packet has no specific source address yet.
9027  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9028  *   flag, the resulting ire will inherit the flag. All unresolved routes
9029  *   to the destination must be explored in the same call to
9030  *   ip_newroute_ipif().
9031  */
9032 static void
9033 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9034     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9035 {
9036 	areq_t	*areq;
9037 	ire_t	*ire = NULL;
9038 	mblk_t	*res_mp;
9039 	ipaddr_t *addrp;
9040 	mblk_t *first_mp;
9041 	ire_t	*save_ire = NULL;
9042 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9043 	ipif_t	*src_ipif = NULL;
9044 	ushort_t ire_marks = 0;
9045 	ill_t	*dst_ill = NULL;
9046 	boolean_t mctl_present;
9047 	ipsec_out_t *io;
9048 	ipha_t *ipha;
9049 	int	ihandle = 0;
9050 	mblk_t	*saved_mp;
9051 	ire_t   *fire = NULL;
9052 	mblk_t  *copy_mp = NULL;
9053 	boolean_t multirt_resolve_next;
9054 	boolean_t unspec_src;
9055 	ipaddr_t ipha_dst;
9056 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9057 
9058 	/*
9059 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9060 	 * here for uniformity
9061 	 */
9062 	ipif_refhold(ipif);
9063 
9064 	/*
9065 	 * This loop is run only once in most cases.
9066 	 * We loop to resolve further routes only when the destination
9067 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9068 	 */
9069 	do {
9070 		if (dst_ill != NULL) {
9071 			ill_refrele(dst_ill);
9072 			dst_ill = NULL;
9073 		}
9074 		if (src_ipif != NULL) {
9075 			ipif_refrele(src_ipif);
9076 			src_ipif = NULL;
9077 		}
9078 		multirt_resolve_next = B_FALSE;
9079 
9080 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9081 		    ipif->ipif_ill->ill_name));
9082 
9083 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9084 		if (mctl_present)
9085 			io = (ipsec_out_t *)first_mp->b_rptr;
9086 
9087 		ipha = (ipha_t *)mp->b_rptr;
9088 
9089 		/*
9090 		 * Save the packet destination address, we may need it after
9091 		 * the packet has been consumed.
9092 		 */
9093 		ipha_dst = ipha->ipha_dst;
9094 
9095 		/*
9096 		 * If the interface is a pt-pt interface we look for an
9097 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9098 		 * local_address and the pt-pt destination address. Otherwise
9099 		 * we just match the local address.
9100 		 * NOTE: dst could be different than ipha->ipha_dst in case
9101 		 * of sending igmp multicast packets over a point-to-point
9102 		 * connection.
9103 		 * Thus we must be careful enough to check ipha_dst to be a
9104 		 * multicast address, otherwise it will take xmit_if path for
9105 		 * multicast packets resulting into kernel stack overflow by
9106 		 * repeated calls to ip_newroute_ipif from ire_send().
9107 		 */
9108 		if (CLASSD(ipha_dst) &&
9109 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9110 			goto err_ret;
9111 		}
9112 
9113 		/*
9114 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9115 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9116 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9117 		 * propagate its flags to the new ire.
9118 		 */
9119 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9120 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9121 			ip2dbg(("ip_newroute_ipif: "
9122 			    "ipif_lookup_multi_ire("
9123 			    "ipif %p, dst %08x) = fire %p\n",
9124 			    (void *)ipif, ntohl(dst), (void *)fire));
9125 		}
9126 
9127 		if (mctl_present && io->ipsec_out_attach_if) {
9128 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9129 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9130 
9131 			/* Failure case frees things for us. */
9132 			if (attach_ill == NULL) {
9133 				ipif_refrele(ipif);
9134 				if (fire != NULL)
9135 					ire_refrele(fire);
9136 				return;
9137 			}
9138 
9139 			/*
9140 			 * Check if we need an ire that will not be
9141 			 * looked up by anybody else i.e. HIDDEN.
9142 			 */
9143 			if (ill_is_probeonly(attach_ill)) {
9144 				ire_marks = IRE_MARK_HIDDEN;
9145 			}
9146 			/*
9147 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9148 			 * case.
9149 			 */
9150 			dst_ill = ipif->ipif_ill;
9151 			/* attach_ill has been refheld by ip_grab_attach_ill */
9152 			ASSERT(dst_ill == attach_ill);
9153 		} else {
9154 			/*
9155 			 * If the interface belongs to an interface group,
9156 			 * make sure the next possible interface in the group
9157 			 * is used.  This encourages load spreading among
9158 			 * peers in an interface group.
9159 			 * Note: load spreading is disabled for RTF_MULTIRT
9160 			 * routes.
9161 			 */
9162 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9163 			    (fire->ire_flags & RTF_MULTIRT)) {
9164 				/*
9165 				 * Don't perform outbound load spreading
9166 				 * in the case of an RTF_MULTIRT issued route,
9167 				 * we actually typically want to replicate
9168 				 * outgoing packets through particular
9169 				 * interfaces.
9170 				 */
9171 				dst_ill = ipif->ipif_ill;
9172 				ill_refhold(dst_ill);
9173 			} else {
9174 				dst_ill = ip_newroute_get_dst_ill(
9175 				    ipif->ipif_ill);
9176 			}
9177 			if (dst_ill == NULL) {
9178 				if (ip_debug > 2) {
9179 					pr_addr_dbg("ip_newroute_ipif: "
9180 					    "no dst ill for dst %s\n",
9181 					    AF_INET, &dst);
9182 				}
9183 				goto err_ret;
9184 			}
9185 		}
9186 
9187 		/*
9188 		 * Pick a source address preferring non-deprecated ones.
9189 		 * Unlike ip_newroute, we don't do any source address
9190 		 * selection here since for multicast it really does not help
9191 		 * in inbound load spreading as in the unicast case.
9192 		 */
9193 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9194 		    (fire->ire_flags & RTF_SETSRC)) {
9195 			/*
9196 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9197 			 * on that interface. This ire has RTF_SETSRC flag, so
9198 			 * the source address of the packet must be changed.
9199 			 * Check that the ipif matching the requested source
9200 			 * address still exists.
9201 			 */
9202 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9203 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9204 		}
9205 
9206 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9207 
9208 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9209 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9210 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9211 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9212 		    (src_ipif == NULL) &&
9213 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9214 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9215 			if (src_ipif == NULL) {
9216 				if (ip_debug > 2) {
9217 					/* ip1dbg */
9218 					pr_addr_dbg("ip_newroute_ipif: "
9219 					    "no src for dst %s",
9220 					    AF_INET, &dst);
9221 				}
9222 				ip1dbg((" through interface %s\n",
9223 				    dst_ill->ill_name));
9224 				goto err_ret;
9225 			}
9226 			ipif_refrele(ipif);
9227 			ipif = src_ipif;
9228 			ipif_refhold(ipif);
9229 		}
9230 		if (src_ipif == NULL) {
9231 			src_ipif = ipif;
9232 			ipif_refhold(src_ipif);
9233 		}
9234 
9235 		/*
9236 		 * Assign a source address while we have the conn.
9237 		 * We can't have ip_wput_ire pick a source address when the
9238 		 * packet returns from arp since conn_unspec_src might be set
9239 		 * and we lose the conn when going through arp.
9240 		 */
9241 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9242 			ipha->ipha_src = src_ipif->ipif_src_addr;
9243 
9244 		/*
9245 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9246 		 * that the outgoing interface does not have an interface ire.
9247 		 */
9248 		if (CLASSD(ipha_dst) && (connp == NULL ||
9249 		    connp->conn_outgoing_ill == NULL) &&
9250 		    infop->ip_opt_ill_index == 0) {
9251 			/* ipif_to_ire returns an held ire */
9252 			ire = ipif_to_ire(ipif);
9253 			if (ire == NULL)
9254 				goto err_ret;
9255 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9256 				goto err_ret;
9257 			/*
9258 			 * ihandle is needed when the ire is added to
9259 			 * cache table.
9260 			 */
9261 			save_ire = ire;
9262 			ihandle = save_ire->ire_ihandle;
9263 
9264 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9265 			    "flags %04x\n",
9266 			    (void *)ire, (void *)ipif, flags));
9267 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9268 			    (fire->ire_flags & RTF_MULTIRT)) {
9269 				/*
9270 				 * As requested by flags, an IRE_OFFSUBNET was
9271 				 * looked up on that interface. This ire has
9272 				 * RTF_MULTIRT flag, so the resolution loop will
9273 				 * be re-entered to resolve additional routes on
9274 				 * other interfaces. For that purpose, a copy of
9275 				 * the packet is performed at this point.
9276 				 */
9277 				fire->ire_last_used_time = lbolt;
9278 				copy_mp = copymsg(first_mp);
9279 				if (copy_mp) {
9280 					MULTIRT_DEBUG_TAG(copy_mp);
9281 				}
9282 			}
9283 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9284 			    (fire->ire_flags & RTF_SETSRC)) {
9285 				/*
9286 				 * As requested by flags, an IRE_OFFSUBET was
9287 				 * looked up on that interface. This ire has
9288 				 * RTF_SETSRC flag, so the source address of the
9289 				 * packet must be changed.
9290 				 */
9291 				ipha->ipha_src = fire->ire_src_addr;
9292 			}
9293 		} else {
9294 			ASSERT((connp == NULL) ||
9295 			    (connp->conn_outgoing_ill != NULL) ||
9296 			    (connp->conn_dontroute) ||
9297 			    infop->ip_opt_ill_index != 0);
9298 			/*
9299 			 * The only ways we can come here are:
9300 			 * 1) IP_BOUND_IF socket option is set
9301 			 * 2) SO_DONTROUTE socket option is set
9302 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9303 			 * In all cases, the new ire will not be added
9304 			 * into cache table.
9305 			 */
9306 			ire_marks |= IRE_MARK_NOADD;
9307 		}
9308 
9309 		switch (ipif->ipif_net_type) {
9310 		case IRE_IF_NORESOLVER: {
9311 			/* We have what we need to build an IRE_CACHE. */
9312 
9313 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9314 			    (dst_ill->ill_resolver_mp == NULL)) {
9315 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9316 				    "for IRE_IF_NORESOLVER ire %p has "
9317 				    "no ill_resolver_mp\n",
9318 				    (void *)dst_ill, (void *)ire));
9319 				break;
9320 			}
9321 
9322 			/*
9323 			 * The new ire inherits the IRE_OFFSUBNET flags
9324 			 * and source address, if this was requested.
9325 			 */
9326 			ire = ire_create(
9327 			    (uchar_t *)&dst,		/* dest address */
9328 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9329 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9330 			    NULL,			/* gateway address */
9331 			    &ipif->ipif_mtu,
9332 			    NULL,			/* no src nce */
9333 			    dst_ill->ill_rq,		/* recv-from queue */
9334 			    dst_ill->ill_wq,		/* send-to queue */
9335 			    IRE_CACHE,
9336 			    src_ipif,
9337 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9338 			    (fire != NULL) ?		/* Parent handle */
9339 			    fire->ire_phandle : 0,
9340 			    ihandle,			/* Interface handle */
9341 			    (fire != NULL) ?
9342 			    (fire->ire_flags &
9343 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9344 			    (save_ire == NULL ? &ire_uinfo_null :
9345 			    &save_ire->ire_uinfo),
9346 			    NULL,
9347 			    NULL,
9348 			    ipst);
9349 
9350 			if (ire == NULL) {
9351 				if (save_ire != NULL)
9352 					ire_refrele(save_ire);
9353 				break;
9354 			}
9355 
9356 			ire->ire_marks |= ire_marks;
9357 
9358 			/*
9359 			 * If IRE_MARK_NOADD is set then we need to convert
9360 			 * the max_fragp to a useable value now. This is
9361 			 * normally done in ire_add_v[46]. We also need to
9362 			 * associate the ire with an nce (normally would be
9363 			 * done in ip_wput_nondata()).
9364 			 *
9365 			 * Note that IRE_MARK_NOADD packets created here
9366 			 * do not have a non-null ire_mp pointer. The null
9367 			 * value of ire_bucket indicates that they were
9368 			 * never added.
9369 			 */
9370 			if (ire->ire_marks & IRE_MARK_NOADD) {
9371 				uint_t  max_frag;
9372 
9373 				max_frag = *ire->ire_max_fragp;
9374 				ire->ire_max_fragp = NULL;
9375 				ire->ire_max_frag = max_frag;
9376 
9377 				if ((ire->ire_nce = ndp_lookup_v4(
9378 				    ire_to_ill(ire),
9379 				    (ire->ire_gateway_addr != INADDR_ANY ?
9380 				    &ire->ire_gateway_addr : &ire->ire_addr),
9381 				    B_FALSE)) == NULL) {
9382 					if (save_ire != NULL)
9383 						ire_refrele(save_ire);
9384 					break;
9385 				}
9386 				ASSERT(ire->ire_nce->nce_state ==
9387 				    ND_REACHABLE);
9388 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9389 			}
9390 
9391 			/* Prevent save_ire from getting deleted */
9392 			if (save_ire != NULL) {
9393 				IRB_REFHOLD(save_ire->ire_bucket);
9394 				/* Has it been removed already ? */
9395 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9396 					IRB_REFRELE(save_ire->ire_bucket);
9397 					ire_refrele(save_ire);
9398 					break;
9399 				}
9400 			}
9401 
9402 			ire_add_then_send(q, ire, first_mp);
9403 
9404 			/* Assert that save_ire is not deleted yet. */
9405 			if (save_ire != NULL) {
9406 				ASSERT(save_ire->ire_ptpn != NULL);
9407 				IRB_REFRELE(save_ire->ire_bucket);
9408 				ire_refrele(save_ire);
9409 				save_ire = NULL;
9410 			}
9411 			if (fire != NULL) {
9412 				ire_refrele(fire);
9413 				fire = NULL;
9414 			}
9415 
9416 			/*
9417 			 * the resolution loop is re-entered if this
9418 			 * was requested through flags and if we
9419 			 * actually are in a multirouting case.
9420 			 */
9421 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9422 				boolean_t need_resolve =
9423 				    ire_multirt_need_resolve(ipha_dst,
9424 				    MBLK_GETLABEL(copy_mp), ipst);
9425 				if (!need_resolve) {
9426 					MULTIRT_DEBUG_UNTAG(copy_mp);
9427 					freemsg(copy_mp);
9428 					copy_mp = NULL;
9429 				} else {
9430 					/*
9431 					 * ipif_lookup_group() calls
9432 					 * ire_lookup_multi() that uses
9433 					 * ire_ftable_lookup() to find
9434 					 * an IRE_INTERFACE for the group.
9435 					 * In the multirt case,
9436 					 * ire_lookup_multi() then invokes
9437 					 * ire_multirt_lookup() to find
9438 					 * the next resolvable ire.
9439 					 * As a result, we obtain an new
9440 					 * interface, derived from the
9441 					 * next ire.
9442 					 */
9443 					ipif_refrele(ipif);
9444 					ipif = ipif_lookup_group(ipha_dst,
9445 					    zoneid, ipst);
9446 					ip2dbg(("ip_newroute_ipif: "
9447 					    "multirt dst %08x, ipif %p\n",
9448 					    htonl(dst), (void *)ipif));
9449 					if (ipif != NULL) {
9450 						mp = copy_mp;
9451 						copy_mp = NULL;
9452 						multirt_resolve_next = B_TRUE;
9453 						continue;
9454 					} else {
9455 						freemsg(copy_mp);
9456 					}
9457 				}
9458 			}
9459 			if (ipif != NULL)
9460 				ipif_refrele(ipif);
9461 			ill_refrele(dst_ill);
9462 			ipif_refrele(src_ipif);
9463 			return;
9464 		}
9465 		case IRE_IF_RESOLVER:
9466 			/*
9467 			 * We can't build an IRE_CACHE yet, but at least
9468 			 * we found a resolver that can help.
9469 			 */
9470 			res_mp = dst_ill->ill_resolver_mp;
9471 			if (!OK_RESOLVER_MP(res_mp))
9472 				break;
9473 
9474 			/*
9475 			 * We obtain a partial IRE_CACHE which we will pass
9476 			 * along with the resolver query.  When the response
9477 			 * comes back it will be there ready for us to add.
9478 			 * The new ire inherits the IRE_OFFSUBNET flags
9479 			 * and source address, if this was requested.
9480 			 * The ire_max_frag is atomically set under the
9481 			 * irebucket lock in ire_add_v[46]. Only in the
9482 			 * case of IRE_MARK_NOADD, we set it here itself.
9483 			 */
9484 			ire = ire_create_mp(
9485 			    (uchar_t *)&dst,		/* dest address */
9486 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9487 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9488 			    NULL,			/* gateway address */
9489 			    (ire_marks & IRE_MARK_NOADD) ?
9490 			    ipif->ipif_mtu : 0,		/* max_frag */
9491 			    NULL,			/* no src nce */
9492 			    dst_ill->ill_rq,		/* recv-from queue */
9493 			    dst_ill->ill_wq,		/* send-to queue */
9494 			    IRE_CACHE,
9495 			    src_ipif,
9496 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9497 			    (fire != NULL) ?		/* Parent handle */
9498 			    fire->ire_phandle : 0,
9499 			    ihandle,			/* Interface handle */
9500 			    (fire != NULL) ?		/* flags if any */
9501 			    (fire->ire_flags &
9502 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9503 			    (save_ire == NULL ? &ire_uinfo_null :
9504 			    &save_ire->ire_uinfo),
9505 			    NULL,
9506 			    NULL,
9507 			    ipst);
9508 
9509 			if (save_ire != NULL) {
9510 				ire_refrele(save_ire);
9511 				save_ire = NULL;
9512 			}
9513 			if (ire == NULL)
9514 				break;
9515 
9516 			ire->ire_marks |= ire_marks;
9517 			/*
9518 			 * Construct message chain for the resolver of the
9519 			 * form:
9520 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9521 			 *
9522 			 * NOTE : ire will be added later when the response
9523 			 * comes back from ARP. If the response does not
9524 			 * come back, ARP frees the packet. For this reason,
9525 			 * we can't REFHOLD the bucket of save_ire to prevent
9526 			 * deletions. We may not be able to REFRELE the
9527 			 * bucket if the response never comes back.
9528 			 * Thus, before adding the ire, ire_add_v4 will make
9529 			 * sure that the interface route does not get deleted.
9530 			 * This is the only case unlike ip_newroute_v6,
9531 			 * ip_newroute_ipif_v6 where we can always prevent
9532 			 * deletions because ire_add_then_send is called after
9533 			 * creating the IRE.
9534 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9535 			 * does not add this IRE into the IRE CACHE.
9536 			 */
9537 			ASSERT(ire->ire_mp != NULL);
9538 			ire->ire_mp->b_cont = first_mp;
9539 			/* Have saved_mp handy, for cleanup if canput fails */
9540 			saved_mp = mp;
9541 			mp = copyb(res_mp);
9542 			if (mp == NULL) {
9543 				/* Prepare for cleanup */
9544 				mp = saved_mp; /* pkt */
9545 				ire_delete(ire); /* ire_mp */
9546 				ire = NULL;
9547 				if (copy_mp != NULL) {
9548 					MULTIRT_DEBUG_UNTAG(copy_mp);
9549 					freemsg(copy_mp);
9550 					copy_mp = NULL;
9551 				}
9552 				break;
9553 			}
9554 			linkb(mp, ire->ire_mp);
9555 
9556 			/*
9557 			 * Fill in the source and dest addrs for the resolver.
9558 			 * NOTE: this depends on memory layouts imposed by
9559 			 * ill_init().
9560 			 */
9561 			areq = (areq_t *)mp->b_rptr;
9562 			addrp = (ipaddr_t *)((char *)areq +
9563 			    areq->areq_sender_addr_offset);
9564 			*addrp = ire->ire_src_addr;
9565 			addrp = (ipaddr_t *)((char *)areq +
9566 			    areq->areq_target_addr_offset);
9567 			*addrp = dst;
9568 			/* Up to the resolver. */
9569 			if (canputnext(dst_ill->ill_rq) &&
9570 			    !(dst_ill->ill_arp_closing)) {
9571 				putnext(dst_ill->ill_rq, mp);
9572 				/*
9573 				 * The response will come back in ip_wput
9574 				 * with db_type IRE_DB_TYPE.
9575 				 */
9576 			} else {
9577 				mp->b_cont = NULL;
9578 				freeb(mp); /* areq */
9579 				ire_delete(ire); /* ire_mp */
9580 				saved_mp->b_next = NULL;
9581 				saved_mp->b_prev = NULL;
9582 				freemsg(first_mp); /* pkt */
9583 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9584 			}
9585 
9586 			if (fire != NULL) {
9587 				ire_refrele(fire);
9588 				fire = NULL;
9589 			}
9590 
9591 
9592 			/*
9593 			 * The resolution loop is re-entered if this was
9594 			 * requested through flags and we actually are
9595 			 * in a multirouting case.
9596 			 */
9597 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9598 				boolean_t need_resolve =
9599 				    ire_multirt_need_resolve(ipha_dst,
9600 				    MBLK_GETLABEL(copy_mp), ipst);
9601 				if (!need_resolve) {
9602 					MULTIRT_DEBUG_UNTAG(copy_mp);
9603 					freemsg(copy_mp);
9604 					copy_mp = NULL;
9605 				} else {
9606 					/*
9607 					 * ipif_lookup_group() calls
9608 					 * ire_lookup_multi() that uses
9609 					 * ire_ftable_lookup() to find
9610 					 * an IRE_INTERFACE for the group.
9611 					 * In the multirt case,
9612 					 * ire_lookup_multi() then invokes
9613 					 * ire_multirt_lookup() to find
9614 					 * the next resolvable ire.
9615 					 * As a result, we obtain an new
9616 					 * interface, derived from the
9617 					 * next ire.
9618 					 */
9619 					ipif_refrele(ipif);
9620 					ipif = ipif_lookup_group(ipha_dst,
9621 					    zoneid, ipst);
9622 					if (ipif != NULL) {
9623 						mp = copy_mp;
9624 						copy_mp = NULL;
9625 						multirt_resolve_next = B_TRUE;
9626 						continue;
9627 					} else {
9628 						freemsg(copy_mp);
9629 					}
9630 				}
9631 			}
9632 			if (ipif != NULL)
9633 				ipif_refrele(ipif);
9634 			ill_refrele(dst_ill);
9635 			ipif_refrele(src_ipif);
9636 			return;
9637 		default:
9638 			break;
9639 		}
9640 	} while (multirt_resolve_next);
9641 
9642 err_ret:
9643 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9644 	if (fire != NULL)
9645 		ire_refrele(fire);
9646 	ipif_refrele(ipif);
9647 	/* Did this packet originate externally? */
9648 	if (dst_ill != NULL)
9649 		ill_refrele(dst_ill);
9650 	if (src_ipif != NULL)
9651 		ipif_refrele(src_ipif);
9652 	if (mp->b_prev || mp->b_next) {
9653 		mp->b_next = NULL;
9654 		mp->b_prev = NULL;
9655 	} else {
9656 		/*
9657 		 * Since ip_wput() isn't close to finished, we fill
9658 		 * in enough of the header for credible error reporting.
9659 		 */
9660 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9661 			/* Failed */
9662 			freemsg(first_mp);
9663 			if (ire != NULL)
9664 				ire_refrele(ire);
9665 			return;
9666 		}
9667 	}
9668 	/*
9669 	 * At this point we will have ire only if RTF_BLACKHOLE
9670 	 * or RTF_REJECT flags are set on the IRE. It will not
9671 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9672 	 */
9673 	if (ire != NULL) {
9674 		if (ire->ire_flags & RTF_BLACKHOLE) {
9675 			ire_refrele(ire);
9676 			freemsg(first_mp);
9677 			return;
9678 		}
9679 		ire_refrele(ire);
9680 	}
9681 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9682 }
9683 
9684 /* Name/Value Table Lookup Routine */
9685 char *
9686 ip_nv_lookup(nv_t *nv, int value)
9687 {
9688 	if (!nv)
9689 		return (NULL);
9690 	for (; nv->nv_name; nv++) {
9691 		if (nv->nv_value == value)
9692 			return (nv->nv_name);
9693 	}
9694 	return ("unknown");
9695 }
9696 
9697 /*
9698  * This is a module open, i.e. this is a control stream for access
9699  * to a DLPI device.  We allocate an ill_t as the instance data in
9700  * this case.
9701  */
9702 int
9703 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9704 {
9705 	ill_t	*ill;
9706 	int	err;
9707 	zoneid_t zoneid;
9708 	netstack_t *ns;
9709 	ip_stack_t *ipst;
9710 
9711 	/*
9712 	 * Prevent unprivileged processes from pushing IP so that
9713 	 * they can't send raw IP.
9714 	 */
9715 	if (secpolicy_net_rawaccess(credp) != 0)
9716 		return (EPERM);
9717 
9718 	ns = netstack_find_by_cred(credp);
9719 	ASSERT(ns != NULL);
9720 	ipst = ns->netstack_ip;
9721 	ASSERT(ipst != NULL);
9722 
9723 	/*
9724 	 * For exclusive stacks we set the zoneid to zero
9725 	 * to make IP operate as if in the global zone.
9726 	 */
9727 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9728 		zoneid = GLOBAL_ZONEID;
9729 	else
9730 		zoneid = crgetzoneid(credp);
9731 
9732 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9733 	q->q_ptr = WR(q)->q_ptr = ill;
9734 	ill->ill_ipst = ipst;
9735 	ill->ill_zoneid = zoneid;
9736 
9737 	/*
9738 	 * ill_init initializes the ill fields and then sends down
9739 	 * down a DL_INFO_REQ after calling qprocson.
9740 	 */
9741 	err = ill_init(q, ill);
9742 	if (err != 0) {
9743 		mi_free(ill);
9744 		netstack_rele(ipst->ips_netstack);
9745 		q->q_ptr = NULL;
9746 		WR(q)->q_ptr = NULL;
9747 		return (err);
9748 	}
9749 
9750 	/* ill_init initializes the ipsq marking this thread as writer */
9751 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9752 	/* Wait for the DL_INFO_ACK */
9753 	mutex_enter(&ill->ill_lock);
9754 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9755 		/*
9756 		 * Return value of 0 indicates a pending signal.
9757 		 */
9758 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9759 		if (err == 0) {
9760 			mutex_exit(&ill->ill_lock);
9761 			(void) ip_close(q, 0);
9762 			return (EINTR);
9763 		}
9764 	}
9765 	mutex_exit(&ill->ill_lock);
9766 
9767 	/*
9768 	 * ip_rput_other could have set an error  in ill_error on
9769 	 * receipt of M_ERROR.
9770 	 */
9771 
9772 	err = ill->ill_error;
9773 	if (err != 0) {
9774 		(void) ip_close(q, 0);
9775 		return (err);
9776 	}
9777 
9778 	ill->ill_credp = credp;
9779 	crhold(credp);
9780 
9781 	mutex_enter(&ipst->ips_ip_mi_lock);
9782 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9783 	    credp);
9784 	mutex_exit(&ipst->ips_ip_mi_lock);
9785 	if (err) {
9786 		(void) ip_close(q, 0);
9787 		return (err);
9788 	}
9789 	return (0);
9790 }
9791 
9792 /* For /dev/ip aka AF_INET open */
9793 int
9794 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9795 {
9796 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9797 }
9798 
9799 /* For /dev/ip6 aka AF_INET6 open */
9800 int
9801 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9802 {
9803 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9804 }
9805 
9806 /* IP open routine. */
9807 int
9808 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9809     boolean_t isv6)
9810 {
9811 	conn_t 		*connp;
9812 	major_t		maj;
9813 	zoneid_t	zoneid;
9814 	netstack_t	*ns;
9815 	ip_stack_t	*ipst;
9816 
9817 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9818 
9819 	/* Allow reopen. */
9820 	if (q->q_ptr != NULL)
9821 		return (0);
9822 
9823 	if (sflag & MODOPEN) {
9824 		/* This is a module open */
9825 		return (ip_modopen(q, devp, flag, sflag, credp));
9826 	}
9827 
9828 	ns = netstack_find_by_cred(credp);
9829 	ASSERT(ns != NULL);
9830 	ipst = ns->netstack_ip;
9831 	ASSERT(ipst != NULL);
9832 
9833 	/*
9834 	 * For exclusive stacks we set the zoneid to zero
9835 	 * to make IP operate as if in the global zone.
9836 	 */
9837 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9838 		zoneid = GLOBAL_ZONEID;
9839 	else
9840 		zoneid = crgetzoneid(credp);
9841 
9842 	/*
9843 	 * We are opening as a device. This is an IP client stream, and we
9844 	 * allocate an conn_t as the instance data.
9845 	 */
9846 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9847 
9848 	/*
9849 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9850 	 * done by netstack_find_by_cred()
9851 	 */
9852 	netstack_rele(ipst->ips_netstack);
9853 
9854 	connp->conn_zoneid = zoneid;
9855 
9856 	connp->conn_upq = q;
9857 	q->q_ptr = WR(q)->q_ptr = connp;
9858 
9859 	if (flag & SO_SOCKSTR)
9860 		connp->conn_flags |= IPCL_SOCKET;
9861 
9862 	/* Minor tells us which /dev entry was opened */
9863 	if (isv6) {
9864 		connp->conn_flags |= IPCL_ISV6;
9865 		connp->conn_af_isv6 = B_TRUE;
9866 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9867 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9868 	} else {
9869 		connp->conn_af_isv6 = B_FALSE;
9870 		connp->conn_pkt_isv6 = B_FALSE;
9871 	}
9872 
9873 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9874 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9875 		connp->conn_minor_arena = ip_minor_arena_la;
9876 	} else {
9877 		/*
9878 		 * Either minor numbers in the large arena were exhausted
9879 		 * or a non socket application is doing the open.
9880 		 * Try to allocate from the small arena.
9881 		 */
9882 		if ((connp->conn_dev =
9883 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9884 			/* CONN_DEC_REF takes care of netstack_rele() */
9885 			q->q_ptr = WR(q)->q_ptr = NULL;
9886 			CONN_DEC_REF(connp);
9887 			return (EBUSY);
9888 		}
9889 		connp->conn_minor_arena = ip_minor_arena_sa;
9890 	}
9891 
9892 	maj = getemajor(*devp);
9893 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9894 
9895 	/*
9896 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9897 	 */
9898 	connp->conn_cred = credp;
9899 
9900 	/*
9901 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9902 	 */
9903 	connp->conn_recv = ip_conn_input;
9904 
9905 	crhold(connp->conn_cred);
9906 
9907 	/*
9908 	 * If the caller has the process-wide flag set, then default to MAC
9909 	 * exempt mode.  This allows read-down to unlabeled hosts.
9910 	 */
9911 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9912 		connp->conn_mac_exempt = B_TRUE;
9913 
9914 	connp->conn_rq = q;
9915 	connp->conn_wq = WR(q);
9916 
9917 	/* Non-zero default values */
9918 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9919 
9920 	/*
9921 	 * Make the conn globally visible to walkers
9922 	 */
9923 	ASSERT(connp->conn_ref == 1);
9924 	mutex_enter(&connp->conn_lock);
9925 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9926 	mutex_exit(&connp->conn_lock);
9927 
9928 	qprocson(q);
9929 
9930 	return (0);
9931 }
9932 
9933 /*
9934  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9935  * Note that there is no race since either ip_output function works - it
9936  * is just an optimization to enter the best ip_output routine directly.
9937  */
9938 void
9939 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9940     ip_stack_t *ipst)
9941 {
9942 	if (isv6)  {
9943 		if (bump_mib) {
9944 			BUMP_MIB(&ipst->ips_ip6_mib,
9945 			    ipIfStatsOutSwitchIPVersion);
9946 		}
9947 		connp->conn_send = ip_output_v6;
9948 		connp->conn_pkt_isv6 = B_TRUE;
9949 	} else {
9950 		if (bump_mib) {
9951 			BUMP_MIB(&ipst->ips_ip_mib,
9952 			    ipIfStatsOutSwitchIPVersion);
9953 		}
9954 		connp->conn_send = ip_output;
9955 		connp->conn_pkt_isv6 = B_FALSE;
9956 	}
9957 
9958 }
9959 
9960 /*
9961  * See if IPsec needs loading because of the options in mp.
9962  */
9963 static boolean_t
9964 ipsec_opt_present(mblk_t *mp)
9965 {
9966 	uint8_t *optcp, *next_optcp, *opt_endcp;
9967 	struct opthdr *opt;
9968 	struct T_opthdr *topt;
9969 	int opthdr_len;
9970 	t_uscalar_t optname, optlevel;
9971 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9972 	ipsec_req_t *ipsr;
9973 
9974 	/*
9975 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9976 	 * return TRUE.
9977 	 */
9978 
9979 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9980 	opt_endcp = optcp + tor->OPT_length;
9981 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9982 		opthdr_len = sizeof (struct T_opthdr);
9983 	} else {		/* O_OPTMGMT_REQ */
9984 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9985 		opthdr_len = sizeof (struct opthdr);
9986 	}
9987 	for (; optcp < opt_endcp; optcp = next_optcp) {
9988 		if (optcp + opthdr_len > opt_endcp)
9989 			return (B_FALSE);	/* Not enough option header. */
9990 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9991 			topt = (struct T_opthdr *)optcp;
9992 			optlevel = topt->level;
9993 			optname = topt->name;
9994 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9995 		} else {
9996 			opt = (struct opthdr *)optcp;
9997 			optlevel = opt->level;
9998 			optname = opt->name;
9999 			next_optcp = optcp + opthdr_len +
10000 			    _TPI_ALIGN_OPT(opt->len);
10001 		}
10002 		if ((next_optcp < optcp) || /* wraparound pointer space */
10003 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10004 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10005 			return (B_FALSE); /* bad option buffer */
10006 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10007 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10008 			/*
10009 			 * Check to see if it's an all-bypass or all-zeroes
10010 			 * IPsec request.  Don't bother loading IPsec if
10011 			 * the socket doesn't want to use it.  (A good example
10012 			 * is a bypass request.)
10013 			 *
10014 			 * Basically, if any of the non-NEVER bits are set,
10015 			 * load IPsec.
10016 			 */
10017 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10018 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10019 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10020 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10021 			    != 0)
10022 				return (B_TRUE);
10023 		}
10024 	}
10025 	return (B_FALSE);
10026 }
10027 
10028 /*
10029  * If conn is is waiting for ipsec to finish loading, kick it.
10030  */
10031 /* ARGSUSED */
10032 static void
10033 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10034 {
10035 	t_scalar_t	optreq_prim;
10036 	mblk_t		*mp;
10037 	cred_t		*cr;
10038 	int		err = 0;
10039 
10040 	/*
10041 	 * This function is called, after ipsec loading is complete.
10042 	 * Since IP checks exclusively and atomically (i.e it prevents
10043 	 * ipsec load from completing until ip_optcom_req completes)
10044 	 * whether ipsec load is complete, there cannot be a race with IP
10045 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10046 	 */
10047 	mutex_enter(&connp->conn_lock);
10048 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10049 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10050 		mp = connp->conn_ipsec_opt_mp;
10051 		connp->conn_ipsec_opt_mp = NULL;
10052 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10053 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10054 		mutex_exit(&connp->conn_lock);
10055 
10056 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10057 
10058 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10059 		if (optreq_prim == T_OPTMGMT_REQ) {
10060 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10061 			    &ip_opt_obj, B_FALSE);
10062 		} else {
10063 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10064 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10065 			    &ip_opt_obj, B_FALSE);
10066 		}
10067 		if (err != EINPROGRESS)
10068 			CONN_OPER_PENDING_DONE(connp);
10069 		return;
10070 	}
10071 	mutex_exit(&connp->conn_lock);
10072 }
10073 
10074 /*
10075  * Called from the ipsec_loader thread, outside any perimeter, to tell
10076  * ip qenable any of the queues waiting for the ipsec loader to
10077  * complete.
10078  */
10079 void
10080 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10081 {
10082 	netstack_t *ns = ipss->ipsec_netstack;
10083 
10084 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10085 }
10086 
10087 /*
10088  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10089  * determines the grp on which it has to become exclusive, queues the mp
10090  * and sq draining restarts the optmgmt
10091  */
10092 static boolean_t
10093 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10094 {
10095 	conn_t *connp = Q_TO_CONN(q);
10096 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10097 
10098 	/*
10099 	 * Take IPsec requests and treat them special.
10100 	 */
10101 	if (ipsec_opt_present(mp)) {
10102 		/* First check if IPsec is loaded. */
10103 		mutex_enter(&ipss->ipsec_loader_lock);
10104 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10105 			mutex_exit(&ipss->ipsec_loader_lock);
10106 			return (B_FALSE);
10107 		}
10108 		mutex_enter(&connp->conn_lock);
10109 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10110 
10111 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10112 		connp->conn_ipsec_opt_mp = mp;
10113 		mutex_exit(&connp->conn_lock);
10114 		mutex_exit(&ipss->ipsec_loader_lock);
10115 
10116 		ipsec_loader_loadnow(ipss);
10117 		return (B_TRUE);
10118 	}
10119 	return (B_FALSE);
10120 }
10121 
10122 /*
10123  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10124  * all of them are copied to the conn_t. If the req is "zero", the policy is
10125  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10126  * fields.
10127  * We keep only the latest setting of the policy and thus policy setting
10128  * is not incremental/cumulative.
10129  *
10130  * Requests to set policies with multiple alternative actions will
10131  * go through a different API.
10132  */
10133 int
10134 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10135 {
10136 	uint_t ah_req = 0;
10137 	uint_t esp_req = 0;
10138 	uint_t se_req = 0;
10139 	ipsec_selkey_t sel;
10140 	ipsec_act_t *actp = NULL;
10141 	uint_t nact;
10142 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10143 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10144 	ipsec_policy_root_t *pr;
10145 	ipsec_policy_head_t *ph;
10146 	int fam;
10147 	boolean_t is_pol_reset;
10148 	int error = 0;
10149 	netstack_t	*ns = connp->conn_netstack;
10150 	ip_stack_t	*ipst = ns->netstack_ip;
10151 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10152 
10153 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10154 
10155 	/*
10156 	 * The IP_SEC_OPT option does not allow variable length parameters,
10157 	 * hence a request cannot be NULL.
10158 	 */
10159 	if (req == NULL)
10160 		return (EINVAL);
10161 
10162 	ah_req = req->ipsr_ah_req;
10163 	esp_req = req->ipsr_esp_req;
10164 	se_req = req->ipsr_self_encap_req;
10165 
10166 	/*
10167 	 * Are we dealing with a request to reset the policy (i.e.
10168 	 * zero requests).
10169 	 */
10170 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10171 	    (esp_req & REQ_MASK) == 0 &&
10172 	    (se_req & REQ_MASK) == 0);
10173 
10174 	if (!is_pol_reset) {
10175 		/*
10176 		 * If we couldn't load IPsec, fail with "protocol
10177 		 * not supported".
10178 		 * IPsec may not have been loaded for a request with zero
10179 		 * policies, so we don't fail in this case.
10180 		 */
10181 		mutex_enter(&ipss->ipsec_loader_lock);
10182 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10183 			mutex_exit(&ipss->ipsec_loader_lock);
10184 			return (EPROTONOSUPPORT);
10185 		}
10186 		mutex_exit(&ipss->ipsec_loader_lock);
10187 
10188 		/*
10189 		 * Test for valid requests. Invalid algorithms
10190 		 * need to be tested by IPsec code because new
10191 		 * algorithms can be added dynamically.
10192 		 */
10193 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10194 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10195 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10196 			return (EINVAL);
10197 		}
10198 
10199 		/*
10200 		 * Only privileged users can issue these
10201 		 * requests.
10202 		 */
10203 		if (((ah_req & IPSEC_PREF_NEVER) ||
10204 		    (esp_req & IPSEC_PREF_NEVER) ||
10205 		    (se_req & IPSEC_PREF_NEVER)) &&
10206 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10207 			return (EPERM);
10208 		}
10209 
10210 		/*
10211 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10212 		 * are mutually exclusive.
10213 		 */
10214 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10215 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10216 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10217 			/* Both of them are set */
10218 			return (EINVAL);
10219 		}
10220 	}
10221 
10222 	mutex_enter(&connp->conn_lock);
10223 
10224 	/*
10225 	 * If we have already cached policies in ip_bind_connected*(), don't
10226 	 * let them change now. We cache policies for connections
10227 	 * whose src,dst [addr, port] is known.
10228 	 */
10229 	if (connp->conn_policy_cached) {
10230 		mutex_exit(&connp->conn_lock);
10231 		return (EINVAL);
10232 	}
10233 
10234 	/*
10235 	 * We have a zero policies, reset the connection policy if already
10236 	 * set. This will cause the connection to inherit the
10237 	 * global policy, if any.
10238 	 */
10239 	if (is_pol_reset) {
10240 		if (connp->conn_policy != NULL) {
10241 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10242 			connp->conn_policy = NULL;
10243 		}
10244 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10245 		connp->conn_in_enforce_policy = B_FALSE;
10246 		connp->conn_out_enforce_policy = B_FALSE;
10247 		mutex_exit(&connp->conn_lock);
10248 		return (0);
10249 	}
10250 
10251 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10252 	    ipst->ips_netstack);
10253 	if (ph == NULL)
10254 		goto enomem;
10255 
10256 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10257 	if (actp == NULL)
10258 		goto enomem;
10259 
10260 	/*
10261 	 * Always allocate IPv4 policy entries, since they can also
10262 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10263 	 */
10264 	bzero(&sel, sizeof (sel));
10265 	sel.ipsl_valid = IPSL_IPV4;
10266 
10267 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10268 	    ipst->ips_netstack);
10269 	if (pin4 == NULL)
10270 		goto enomem;
10271 
10272 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10273 	    ipst->ips_netstack);
10274 	if (pout4 == NULL)
10275 		goto enomem;
10276 
10277 	if (connp->conn_af_isv6) {
10278 		/*
10279 		 * We're looking at a v6 socket, also allocate the
10280 		 * v6-specific entries...
10281 		 */
10282 		sel.ipsl_valid = IPSL_IPV6;
10283 		pin6 = ipsec_policy_create(&sel, actp, nact,
10284 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10285 		if (pin6 == NULL)
10286 			goto enomem;
10287 
10288 		pout6 = ipsec_policy_create(&sel, actp, nact,
10289 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10290 		if (pout6 == NULL)
10291 			goto enomem;
10292 
10293 		/*
10294 		 * .. and file them away in the right place.
10295 		 */
10296 		fam = IPSEC_AF_V6;
10297 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10298 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10299 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10300 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10301 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10302 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10303 	}
10304 
10305 	ipsec_actvec_free(actp, nact);
10306 
10307 	/*
10308 	 * File the v4 policies.
10309 	 */
10310 	fam = IPSEC_AF_V4;
10311 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10312 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10313 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10314 
10315 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10316 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10317 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10318 
10319 	/*
10320 	 * If the requests need security, set enforce_policy.
10321 	 * If the requests are IPSEC_PREF_NEVER, one should
10322 	 * still set conn_out_enforce_policy so that an ipsec_out
10323 	 * gets attached in ip_wput. This is needed so that
10324 	 * for connections that we don't cache policy in ip_bind,
10325 	 * if global policy matches in ip_wput_attach_policy, we
10326 	 * don't wrongly inherit global policy. Similarly, we need
10327 	 * to set conn_in_enforce_policy also so that we don't verify
10328 	 * policy wrongly.
10329 	 */
10330 	if ((ah_req & REQ_MASK) != 0 ||
10331 	    (esp_req & REQ_MASK) != 0 ||
10332 	    (se_req & REQ_MASK) != 0) {
10333 		connp->conn_in_enforce_policy = B_TRUE;
10334 		connp->conn_out_enforce_policy = B_TRUE;
10335 		connp->conn_flags |= IPCL_CHECK_POLICY;
10336 	}
10337 
10338 	mutex_exit(&connp->conn_lock);
10339 	return (error);
10340 #undef REQ_MASK
10341 
10342 	/*
10343 	 * Common memory-allocation-failure exit path.
10344 	 */
10345 enomem:
10346 	mutex_exit(&connp->conn_lock);
10347 	if (actp != NULL)
10348 		ipsec_actvec_free(actp, nact);
10349 	if (pin4 != NULL)
10350 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10351 	if (pout4 != NULL)
10352 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10353 	if (pin6 != NULL)
10354 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10355 	if (pout6 != NULL)
10356 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10357 	return (ENOMEM);
10358 }
10359 
10360 /*
10361  * Only for options that pass in an IP addr. Currently only V4 options
10362  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10363  * So this function assumes level is IPPROTO_IP
10364  */
10365 int
10366 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10367     mblk_t *first_mp)
10368 {
10369 	ipif_t *ipif = NULL;
10370 	int error;
10371 	ill_t *ill;
10372 	int zoneid;
10373 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10374 
10375 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10376 
10377 	if (addr != INADDR_ANY || checkonly) {
10378 		ASSERT(connp != NULL);
10379 		zoneid = IPCL_ZONEID(connp);
10380 		if (option == IP_NEXTHOP) {
10381 			ipif = ipif_lookup_onlink_addr(addr,
10382 			    connp->conn_zoneid, ipst);
10383 		} else {
10384 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10385 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10386 			    &error, ipst);
10387 		}
10388 		if (ipif == NULL) {
10389 			if (error == EINPROGRESS)
10390 				return (error);
10391 			else if ((option == IP_MULTICAST_IF) ||
10392 			    (option == IP_NEXTHOP))
10393 				return (EHOSTUNREACH);
10394 			else
10395 				return (EINVAL);
10396 		} else if (checkonly) {
10397 			if (option == IP_MULTICAST_IF) {
10398 				ill = ipif->ipif_ill;
10399 				/* not supported by the virtual network iface */
10400 				if (IS_VNI(ill)) {
10401 					ipif_refrele(ipif);
10402 					return (EINVAL);
10403 				}
10404 			}
10405 			ipif_refrele(ipif);
10406 			return (0);
10407 		}
10408 		ill = ipif->ipif_ill;
10409 		mutex_enter(&connp->conn_lock);
10410 		mutex_enter(&ill->ill_lock);
10411 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10412 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10413 			mutex_exit(&ill->ill_lock);
10414 			mutex_exit(&connp->conn_lock);
10415 			ipif_refrele(ipif);
10416 			return (option == IP_MULTICAST_IF ?
10417 			    EHOSTUNREACH : EINVAL);
10418 		}
10419 	} else {
10420 		mutex_enter(&connp->conn_lock);
10421 	}
10422 
10423 	/* None of the options below are supported on the VNI */
10424 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10425 		mutex_exit(&ill->ill_lock);
10426 		mutex_exit(&connp->conn_lock);
10427 		ipif_refrele(ipif);
10428 		return (EINVAL);
10429 	}
10430 
10431 	switch (option) {
10432 	case IP_DONTFAILOVER_IF:
10433 		/*
10434 		 * This option is used by in.mpathd to ensure
10435 		 * that IPMP probe packets only go out on the
10436 		 * test interfaces. in.mpathd sets this option
10437 		 * on the non-failover interfaces.
10438 		 * For backward compatibility, this option
10439 		 * implicitly sets IP_MULTICAST_IF, as used
10440 		 * be done in bind(), so that ip_wput gets
10441 		 * this ipif to send mcast packets.
10442 		 */
10443 		if (ipif != NULL) {
10444 			ASSERT(addr != INADDR_ANY);
10445 			connp->conn_nofailover_ill = ipif->ipif_ill;
10446 			connp->conn_multicast_ipif = ipif;
10447 		} else {
10448 			ASSERT(addr == INADDR_ANY);
10449 			connp->conn_nofailover_ill = NULL;
10450 			connp->conn_multicast_ipif = NULL;
10451 		}
10452 		break;
10453 
10454 	case IP_MULTICAST_IF:
10455 		connp->conn_multicast_ipif = ipif;
10456 		break;
10457 	case IP_NEXTHOP:
10458 		connp->conn_nexthop_v4 = addr;
10459 		connp->conn_nexthop_set = B_TRUE;
10460 		break;
10461 	}
10462 
10463 	if (ipif != NULL) {
10464 		mutex_exit(&ill->ill_lock);
10465 		mutex_exit(&connp->conn_lock);
10466 		ipif_refrele(ipif);
10467 		return (0);
10468 	}
10469 	mutex_exit(&connp->conn_lock);
10470 	/* We succeded in cleared the option */
10471 	return (0);
10472 }
10473 
10474 /*
10475  * For options that pass in an ifindex specifying the ill. V6 options always
10476  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10477  */
10478 int
10479 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10480     int level, int option, mblk_t *first_mp)
10481 {
10482 	ill_t *ill = NULL;
10483 	int error = 0;
10484 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10485 
10486 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10487 	if (ifindex != 0) {
10488 		ASSERT(connp != NULL);
10489 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10490 		    first_mp, ip_restart_optmgmt, &error, ipst);
10491 		if (ill != NULL) {
10492 			if (checkonly) {
10493 				/* not supported by the virtual network iface */
10494 				if (IS_VNI(ill)) {
10495 					ill_refrele(ill);
10496 					return (EINVAL);
10497 				}
10498 				ill_refrele(ill);
10499 				return (0);
10500 			}
10501 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10502 			    0, NULL)) {
10503 				ill_refrele(ill);
10504 				ill = NULL;
10505 				mutex_enter(&connp->conn_lock);
10506 				goto setit;
10507 			}
10508 			mutex_enter(&connp->conn_lock);
10509 			mutex_enter(&ill->ill_lock);
10510 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10511 				mutex_exit(&ill->ill_lock);
10512 				mutex_exit(&connp->conn_lock);
10513 				ill_refrele(ill);
10514 				ill = NULL;
10515 				mutex_enter(&connp->conn_lock);
10516 			}
10517 			goto setit;
10518 		} else if (error == EINPROGRESS) {
10519 			return (error);
10520 		} else {
10521 			error = 0;
10522 		}
10523 	}
10524 	mutex_enter(&connp->conn_lock);
10525 setit:
10526 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10527 
10528 	/*
10529 	 * The options below assume that the ILL (if any) transmits and/or
10530 	 * receives traffic. Neither of which is true for the virtual network
10531 	 * interface, so fail setting these on a VNI.
10532 	 */
10533 	if (IS_VNI(ill)) {
10534 		ASSERT(ill != NULL);
10535 		mutex_exit(&ill->ill_lock);
10536 		mutex_exit(&connp->conn_lock);
10537 		ill_refrele(ill);
10538 		return (EINVAL);
10539 	}
10540 
10541 	if (level == IPPROTO_IP) {
10542 		switch (option) {
10543 		case IP_BOUND_IF:
10544 			connp->conn_incoming_ill = ill;
10545 			connp->conn_outgoing_ill = ill;
10546 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10547 			    0 : ifindex;
10548 			break;
10549 
10550 		case IP_MULTICAST_IF:
10551 			/*
10552 			 * This option is an internal special. The socket
10553 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10554 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10555 			 * specifies an ifindex and we try first on V6 ill's.
10556 			 * If we don't find one, we they try using on v4 ill's
10557 			 * intenally and we come here.
10558 			 */
10559 			if (!checkonly && ill != NULL) {
10560 				ipif_t	*ipif;
10561 				ipif = ill->ill_ipif;
10562 
10563 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10564 					mutex_exit(&ill->ill_lock);
10565 					mutex_exit(&connp->conn_lock);
10566 					ill_refrele(ill);
10567 					ill = NULL;
10568 					mutex_enter(&connp->conn_lock);
10569 				} else {
10570 					connp->conn_multicast_ipif = ipif;
10571 				}
10572 			}
10573 			break;
10574 
10575 		case IP_DHCPINIT_IF:
10576 			if (connp->conn_dhcpinit_ill != NULL) {
10577 				/*
10578 				 * We've locked the conn so conn_cleanup_ill()
10579 				 * cannot clear conn_dhcpinit_ill -- so it's
10580 				 * safe to access the ill.
10581 				 */
10582 				ill_t *oill = connp->conn_dhcpinit_ill;
10583 
10584 				ASSERT(oill->ill_dhcpinit != 0);
10585 				atomic_dec_32(&oill->ill_dhcpinit);
10586 				connp->conn_dhcpinit_ill = NULL;
10587 			}
10588 
10589 			if (ill != NULL) {
10590 				connp->conn_dhcpinit_ill = ill;
10591 				atomic_inc_32(&ill->ill_dhcpinit);
10592 			}
10593 			break;
10594 		}
10595 	} else {
10596 		switch (option) {
10597 		case IPV6_BOUND_IF:
10598 			connp->conn_incoming_ill = ill;
10599 			connp->conn_outgoing_ill = ill;
10600 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10601 			    0 : ifindex;
10602 			break;
10603 
10604 		case IPV6_BOUND_PIF:
10605 			/*
10606 			 * Limit all transmit to this ill.
10607 			 * Unlike IPV6_BOUND_IF, using this option
10608 			 * prevents load spreading and failover from
10609 			 * happening when the interface is part of the
10610 			 * group. That's why we don't need to remember
10611 			 * the ifindex in orig_bound_ifindex as in
10612 			 * IPV6_BOUND_IF.
10613 			 */
10614 			connp->conn_outgoing_pill = ill;
10615 			break;
10616 
10617 		case IPV6_DONTFAILOVER_IF:
10618 			/*
10619 			 * This option is used by in.mpathd to ensure
10620 			 * that IPMP probe packets only go out on the
10621 			 * test interfaces. in.mpathd sets this option
10622 			 * on the non-failover interfaces.
10623 			 */
10624 			connp->conn_nofailover_ill = ill;
10625 			/*
10626 			 * For backward compatibility, this option
10627 			 * implicitly sets ip_multicast_ill as used in
10628 			 * IPV6_MULTICAST_IF so that ip_wput gets
10629 			 * this ill to send mcast packets.
10630 			 */
10631 			connp->conn_multicast_ill = ill;
10632 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10633 			    0 : ifindex;
10634 			break;
10635 
10636 		case IPV6_MULTICAST_IF:
10637 			/*
10638 			 * Set conn_multicast_ill to be the IPv6 ill.
10639 			 * Set conn_multicast_ipif to be an IPv4 ipif
10640 			 * for ifindex to make IPv4 mapped addresses
10641 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10642 			 * Even if no IPv6 ill exists for the ifindex
10643 			 * we need to check for an IPv4 ifindex in order
10644 			 * for this to work with mapped addresses. In that
10645 			 * case only set conn_multicast_ipif.
10646 			 */
10647 			if (!checkonly) {
10648 				if (ifindex == 0) {
10649 					connp->conn_multicast_ill = NULL;
10650 					connp->conn_orig_multicast_ifindex = 0;
10651 					connp->conn_multicast_ipif = NULL;
10652 				} else if (ill != NULL) {
10653 					connp->conn_multicast_ill = ill;
10654 					connp->conn_orig_multicast_ifindex =
10655 					    ifindex;
10656 				}
10657 			}
10658 			break;
10659 		}
10660 	}
10661 
10662 	if (ill != NULL) {
10663 		mutex_exit(&ill->ill_lock);
10664 		mutex_exit(&connp->conn_lock);
10665 		ill_refrele(ill);
10666 		return (0);
10667 	}
10668 	mutex_exit(&connp->conn_lock);
10669 	/*
10670 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10671 	 * locate the ill and could not set the option (ifindex != 0)
10672 	 */
10673 	return (ifindex == 0 ? 0 : EINVAL);
10674 }
10675 
10676 /* This routine sets socket options. */
10677 /* ARGSUSED */
10678 int
10679 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10680     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10681     void *dummy, cred_t *cr, mblk_t *first_mp)
10682 {
10683 	int		*i1 = (int *)invalp;
10684 	conn_t		*connp = Q_TO_CONN(q);
10685 	int		error = 0;
10686 	boolean_t	checkonly;
10687 	ire_t		*ire;
10688 	boolean_t	found;
10689 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10690 
10691 	switch (optset_context) {
10692 
10693 	case SETFN_OPTCOM_CHECKONLY:
10694 		checkonly = B_TRUE;
10695 		/*
10696 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10697 		 * inlen != 0 implies value supplied and
10698 		 * 	we have to "pretend" to set it.
10699 		 * inlen == 0 implies that there is no
10700 		 * 	value part in T_CHECK request and just validation
10701 		 * done elsewhere should be enough, we just return here.
10702 		 */
10703 		if (inlen == 0) {
10704 			*outlenp = 0;
10705 			return (0);
10706 		}
10707 		break;
10708 	case SETFN_OPTCOM_NEGOTIATE:
10709 	case SETFN_UD_NEGOTIATE:
10710 	case SETFN_CONN_NEGOTIATE:
10711 		checkonly = B_FALSE;
10712 		break;
10713 	default:
10714 		/*
10715 		 * We should never get here
10716 		 */
10717 		*outlenp = 0;
10718 		return (EINVAL);
10719 	}
10720 
10721 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10722 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10723 
10724 	/*
10725 	 * For fixed length options, no sanity check
10726 	 * of passed in length is done. It is assumed *_optcom_req()
10727 	 * routines do the right thing.
10728 	 */
10729 
10730 	switch (level) {
10731 	case SOL_SOCKET:
10732 		/*
10733 		 * conn_lock protects the bitfields, and is used to
10734 		 * set the fields atomically.
10735 		 */
10736 		switch (name) {
10737 		case SO_BROADCAST:
10738 			if (!checkonly) {
10739 				/* TODO: use value someplace? */
10740 				mutex_enter(&connp->conn_lock);
10741 				connp->conn_broadcast = *i1 ? 1 : 0;
10742 				mutex_exit(&connp->conn_lock);
10743 			}
10744 			break;	/* goto sizeof (int) option return */
10745 		case SO_USELOOPBACK:
10746 			if (!checkonly) {
10747 				/* TODO: use value someplace? */
10748 				mutex_enter(&connp->conn_lock);
10749 				connp->conn_loopback = *i1 ? 1 : 0;
10750 				mutex_exit(&connp->conn_lock);
10751 			}
10752 			break;	/* goto sizeof (int) option return */
10753 		case SO_DONTROUTE:
10754 			if (!checkonly) {
10755 				mutex_enter(&connp->conn_lock);
10756 				connp->conn_dontroute = *i1 ? 1 : 0;
10757 				mutex_exit(&connp->conn_lock);
10758 			}
10759 			break;	/* goto sizeof (int) option return */
10760 		case SO_REUSEADDR:
10761 			if (!checkonly) {
10762 				mutex_enter(&connp->conn_lock);
10763 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10764 				mutex_exit(&connp->conn_lock);
10765 			}
10766 			break;	/* goto sizeof (int) option return */
10767 		case SO_PROTOTYPE:
10768 			if (!checkonly) {
10769 				mutex_enter(&connp->conn_lock);
10770 				connp->conn_proto = *i1;
10771 				mutex_exit(&connp->conn_lock);
10772 			}
10773 			break;	/* goto sizeof (int) option return */
10774 		case SO_ALLZONES:
10775 			if (!checkonly) {
10776 				mutex_enter(&connp->conn_lock);
10777 				if (IPCL_IS_BOUND(connp)) {
10778 					mutex_exit(&connp->conn_lock);
10779 					return (EINVAL);
10780 				}
10781 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10782 				mutex_exit(&connp->conn_lock);
10783 			}
10784 			break;	/* goto sizeof (int) option return */
10785 		case SO_ANON_MLP:
10786 			if (!checkonly) {
10787 				mutex_enter(&connp->conn_lock);
10788 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10789 				mutex_exit(&connp->conn_lock);
10790 			}
10791 			break;	/* goto sizeof (int) option return */
10792 		case SO_MAC_EXEMPT:
10793 			if (secpolicy_net_mac_aware(cr) != 0 ||
10794 			    IPCL_IS_BOUND(connp))
10795 				return (EACCES);
10796 			if (!checkonly) {
10797 				mutex_enter(&connp->conn_lock);
10798 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10799 				mutex_exit(&connp->conn_lock);
10800 			}
10801 			break;	/* goto sizeof (int) option return */
10802 		default:
10803 			/*
10804 			 * "soft" error (negative)
10805 			 * option not handled at this level
10806 			 * Note: Do not modify *outlenp
10807 			 */
10808 			return (-EINVAL);
10809 		}
10810 		break;
10811 	case IPPROTO_IP:
10812 		switch (name) {
10813 		case IP_NEXTHOP:
10814 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10815 				return (EPERM);
10816 			/* FALLTHRU */
10817 		case IP_MULTICAST_IF:
10818 		case IP_DONTFAILOVER_IF: {
10819 			ipaddr_t addr = *i1;
10820 
10821 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10822 			    first_mp);
10823 			if (error != 0)
10824 				return (error);
10825 			break;	/* goto sizeof (int) option return */
10826 		}
10827 
10828 		case IP_MULTICAST_TTL:
10829 			/* Recorded in transport above IP */
10830 			*outvalp = *invalp;
10831 			*outlenp = sizeof (uchar_t);
10832 			return (0);
10833 		case IP_MULTICAST_LOOP:
10834 			if (!checkonly) {
10835 				mutex_enter(&connp->conn_lock);
10836 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10837 				mutex_exit(&connp->conn_lock);
10838 			}
10839 			*outvalp = *invalp;
10840 			*outlenp = sizeof (uchar_t);
10841 			return (0);
10842 		case IP_ADD_MEMBERSHIP:
10843 		case MCAST_JOIN_GROUP:
10844 		case IP_DROP_MEMBERSHIP:
10845 		case MCAST_LEAVE_GROUP: {
10846 			struct ip_mreq *mreqp;
10847 			struct group_req *greqp;
10848 			ire_t *ire;
10849 			boolean_t done = B_FALSE;
10850 			ipaddr_t group, ifaddr;
10851 			struct sockaddr_in *sin;
10852 			uint32_t *ifindexp;
10853 			boolean_t mcast_opt = B_TRUE;
10854 			mcast_record_t fmode;
10855 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10856 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10857 
10858 			switch (name) {
10859 			case IP_ADD_MEMBERSHIP:
10860 				mcast_opt = B_FALSE;
10861 				/* FALLTHRU */
10862 			case MCAST_JOIN_GROUP:
10863 				fmode = MODE_IS_EXCLUDE;
10864 				optfn = ip_opt_add_group;
10865 				break;
10866 
10867 			case IP_DROP_MEMBERSHIP:
10868 				mcast_opt = B_FALSE;
10869 				/* FALLTHRU */
10870 			case MCAST_LEAVE_GROUP:
10871 				fmode = MODE_IS_INCLUDE;
10872 				optfn = ip_opt_delete_group;
10873 				break;
10874 			}
10875 
10876 			if (mcast_opt) {
10877 				greqp = (struct group_req *)i1;
10878 				sin = (struct sockaddr_in *)&greqp->gr_group;
10879 				if (sin->sin_family != AF_INET) {
10880 					*outlenp = 0;
10881 					return (ENOPROTOOPT);
10882 				}
10883 				group = (ipaddr_t)sin->sin_addr.s_addr;
10884 				ifaddr = INADDR_ANY;
10885 				ifindexp = &greqp->gr_interface;
10886 			} else {
10887 				mreqp = (struct ip_mreq *)i1;
10888 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10889 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10890 				ifindexp = NULL;
10891 			}
10892 
10893 			/*
10894 			 * In the multirouting case, we need to replicate
10895 			 * the request on all interfaces that will take part
10896 			 * in replication.  We do so because multirouting is
10897 			 * reflective, thus we will probably receive multi-
10898 			 * casts on those interfaces.
10899 			 * The ip_multirt_apply_membership() succeeds if the
10900 			 * operation succeeds on at least one interface.
10901 			 */
10902 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10903 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10904 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10905 			if (ire != NULL) {
10906 				if (ire->ire_flags & RTF_MULTIRT) {
10907 					error = ip_multirt_apply_membership(
10908 					    optfn, ire, connp, checkonly, group,
10909 					    fmode, INADDR_ANY, first_mp);
10910 					done = B_TRUE;
10911 				}
10912 				ire_refrele(ire);
10913 			}
10914 			if (!done) {
10915 				error = optfn(connp, checkonly, group, ifaddr,
10916 				    ifindexp, fmode, INADDR_ANY, first_mp);
10917 			}
10918 			if (error) {
10919 				/*
10920 				 * EINPROGRESS is a soft error, needs retry
10921 				 * so don't make *outlenp zero.
10922 				 */
10923 				if (error != EINPROGRESS)
10924 					*outlenp = 0;
10925 				return (error);
10926 			}
10927 			/* OK return - copy input buffer into output buffer */
10928 			if (invalp != outvalp) {
10929 				/* don't trust bcopy for identical src/dst */
10930 				bcopy(invalp, outvalp, inlen);
10931 			}
10932 			*outlenp = inlen;
10933 			return (0);
10934 		}
10935 		case IP_BLOCK_SOURCE:
10936 		case IP_UNBLOCK_SOURCE:
10937 		case IP_ADD_SOURCE_MEMBERSHIP:
10938 		case IP_DROP_SOURCE_MEMBERSHIP:
10939 		case MCAST_BLOCK_SOURCE:
10940 		case MCAST_UNBLOCK_SOURCE:
10941 		case MCAST_JOIN_SOURCE_GROUP:
10942 		case MCAST_LEAVE_SOURCE_GROUP: {
10943 			struct ip_mreq_source *imreqp;
10944 			struct group_source_req *gsreqp;
10945 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10946 			uint32_t ifindex = 0;
10947 			mcast_record_t fmode;
10948 			struct sockaddr_in *sin;
10949 			ire_t *ire;
10950 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10951 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10952 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10953 
10954 			switch (name) {
10955 			case IP_BLOCK_SOURCE:
10956 				mcast_opt = B_FALSE;
10957 				/* FALLTHRU */
10958 			case MCAST_BLOCK_SOURCE:
10959 				fmode = MODE_IS_EXCLUDE;
10960 				optfn = ip_opt_add_group;
10961 				break;
10962 
10963 			case IP_UNBLOCK_SOURCE:
10964 				mcast_opt = B_FALSE;
10965 				/* FALLTHRU */
10966 			case MCAST_UNBLOCK_SOURCE:
10967 				fmode = MODE_IS_EXCLUDE;
10968 				optfn = ip_opt_delete_group;
10969 				break;
10970 
10971 			case IP_ADD_SOURCE_MEMBERSHIP:
10972 				mcast_opt = B_FALSE;
10973 				/* FALLTHRU */
10974 			case MCAST_JOIN_SOURCE_GROUP:
10975 				fmode = MODE_IS_INCLUDE;
10976 				optfn = ip_opt_add_group;
10977 				break;
10978 
10979 			case IP_DROP_SOURCE_MEMBERSHIP:
10980 				mcast_opt = B_FALSE;
10981 				/* FALLTHRU */
10982 			case MCAST_LEAVE_SOURCE_GROUP:
10983 				fmode = MODE_IS_INCLUDE;
10984 				optfn = ip_opt_delete_group;
10985 				break;
10986 			}
10987 
10988 			if (mcast_opt) {
10989 				gsreqp = (struct group_source_req *)i1;
10990 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10991 					*outlenp = 0;
10992 					return (ENOPROTOOPT);
10993 				}
10994 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10995 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10996 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10997 				src = (ipaddr_t)sin->sin_addr.s_addr;
10998 				ifindex = gsreqp->gsr_interface;
10999 			} else {
11000 				imreqp = (struct ip_mreq_source *)i1;
11001 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11002 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11003 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11004 			}
11005 
11006 			/*
11007 			 * In the multirouting case, we need to replicate
11008 			 * the request as noted in the mcast cases above.
11009 			 */
11010 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11011 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11012 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11013 			if (ire != NULL) {
11014 				if (ire->ire_flags & RTF_MULTIRT) {
11015 					error = ip_multirt_apply_membership(
11016 					    optfn, ire, connp, checkonly, grp,
11017 					    fmode, src, first_mp);
11018 					done = B_TRUE;
11019 				}
11020 				ire_refrele(ire);
11021 			}
11022 			if (!done) {
11023 				error = optfn(connp, checkonly, grp, ifaddr,
11024 				    &ifindex, fmode, src, first_mp);
11025 			}
11026 			if (error != 0) {
11027 				/*
11028 				 * EINPROGRESS is a soft error, needs retry
11029 				 * so don't make *outlenp zero.
11030 				 */
11031 				if (error != EINPROGRESS)
11032 					*outlenp = 0;
11033 				return (error);
11034 			}
11035 			/* OK return - copy input buffer into output buffer */
11036 			if (invalp != outvalp) {
11037 				bcopy(invalp, outvalp, inlen);
11038 			}
11039 			*outlenp = inlen;
11040 			return (0);
11041 		}
11042 		case IP_SEC_OPT:
11043 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11044 			if (error != 0) {
11045 				*outlenp = 0;
11046 				return (error);
11047 			}
11048 			break;
11049 		case IP_HDRINCL:
11050 		case IP_OPTIONS:
11051 		case T_IP_OPTIONS:
11052 		case IP_TOS:
11053 		case T_IP_TOS:
11054 		case IP_TTL:
11055 		case IP_RECVDSTADDR:
11056 		case IP_RECVOPTS:
11057 			/* OK return - copy input buffer into output buffer */
11058 			if (invalp != outvalp) {
11059 				/* don't trust bcopy for identical src/dst */
11060 				bcopy(invalp, outvalp, inlen);
11061 			}
11062 			*outlenp = inlen;
11063 			return (0);
11064 		case IP_RECVIF:
11065 			/* Retrieve the inbound interface index */
11066 			if (!checkonly) {
11067 				mutex_enter(&connp->conn_lock);
11068 				connp->conn_recvif = *i1 ? 1 : 0;
11069 				mutex_exit(&connp->conn_lock);
11070 			}
11071 			break;	/* goto sizeof (int) option return */
11072 		case IP_RECVPKTINFO:
11073 			if (!checkonly) {
11074 				mutex_enter(&connp->conn_lock);
11075 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11076 				mutex_exit(&connp->conn_lock);
11077 			}
11078 			break;	/* goto sizeof (int) option return */
11079 		case IP_RECVSLLA:
11080 			/* Retrieve the source link layer address */
11081 			if (!checkonly) {
11082 				mutex_enter(&connp->conn_lock);
11083 				connp->conn_recvslla = *i1 ? 1 : 0;
11084 				mutex_exit(&connp->conn_lock);
11085 			}
11086 			break;	/* goto sizeof (int) option return */
11087 		case MRT_INIT:
11088 		case MRT_DONE:
11089 		case MRT_ADD_VIF:
11090 		case MRT_DEL_VIF:
11091 		case MRT_ADD_MFC:
11092 		case MRT_DEL_MFC:
11093 		case MRT_ASSERT:
11094 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11095 				*outlenp = 0;
11096 				return (error);
11097 			}
11098 			error = ip_mrouter_set((int)name, q, checkonly,
11099 			    (uchar_t *)invalp, inlen, first_mp);
11100 			if (error) {
11101 				*outlenp = 0;
11102 				return (error);
11103 			}
11104 			/* OK return - copy input buffer into output buffer */
11105 			if (invalp != outvalp) {
11106 				/* don't trust bcopy for identical src/dst */
11107 				bcopy(invalp, outvalp, inlen);
11108 			}
11109 			*outlenp = inlen;
11110 			return (0);
11111 		case IP_BOUND_IF:
11112 		case IP_DHCPINIT_IF:
11113 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11114 			    level, name, first_mp);
11115 			if (error != 0)
11116 				return (error);
11117 			break; 		/* goto sizeof (int) option return */
11118 
11119 		case IP_UNSPEC_SRC:
11120 			/* Allow sending with a zero source address */
11121 			if (!checkonly) {
11122 				mutex_enter(&connp->conn_lock);
11123 				connp->conn_unspec_src = *i1 ? 1 : 0;
11124 				mutex_exit(&connp->conn_lock);
11125 			}
11126 			break;	/* goto sizeof (int) option return */
11127 		default:
11128 			/*
11129 			 * "soft" error (negative)
11130 			 * option not handled at this level
11131 			 * Note: Do not modify *outlenp
11132 			 */
11133 			return (-EINVAL);
11134 		}
11135 		break;
11136 	case IPPROTO_IPV6:
11137 		switch (name) {
11138 		case IPV6_BOUND_IF:
11139 		case IPV6_BOUND_PIF:
11140 		case IPV6_DONTFAILOVER_IF:
11141 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11142 			    level, name, first_mp);
11143 			if (error != 0)
11144 				return (error);
11145 			break; 		/* goto sizeof (int) option return */
11146 
11147 		case IPV6_MULTICAST_IF:
11148 			/*
11149 			 * The only possible errors are EINPROGRESS and
11150 			 * EINVAL. EINPROGRESS will be restarted and is not
11151 			 * a hard error. We call this option on both V4 and V6
11152 			 * If both return EINVAL, then this call returns
11153 			 * EINVAL. If at least one of them succeeds we
11154 			 * return success.
11155 			 */
11156 			found = B_FALSE;
11157 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11158 			    level, name, first_mp);
11159 			if (error == EINPROGRESS)
11160 				return (error);
11161 			if (error == 0)
11162 				found = B_TRUE;
11163 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11164 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11165 			if (error == 0)
11166 				found = B_TRUE;
11167 			if (!found)
11168 				return (error);
11169 			break; 		/* goto sizeof (int) option return */
11170 
11171 		case IPV6_MULTICAST_HOPS:
11172 			/* Recorded in transport above IP */
11173 			break;	/* goto sizeof (int) option return */
11174 		case IPV6_MULTICAST_LOOP:
11175 			if (!checkonly) {
11176 				mutex_enter(&connp->conn_lock);
11177 				connp->conn_multicast_loop = *i1;
11178 				mutex_exit(&connp->conn_lock);
11179 			}
11180 			break;	/* goto sizeof (int) option return */
11181 		case IPV6_JOIN_GROUP:
11182 		case MCAST_JOIN_GROUP:
11183 		case IPV6_LEAVE_GROUP:
11184 		case MCAST_LEAVE_GROUP: {
11185 			struct ipv6_mreq *ip_mreqp;
11186 			struct group_req *greqp;
11187 			ire_t *ire;
11188 			boolean_t done = B_FALSE;
11189 			in6_addr_t groupv6;
11190 			uint32_t ifindex;
11191 			boolean_t mcast_opt = B_TRUE;
11192 			mcast_record_t fmode;
11193 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11194 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11195 
11196 			switch (name) {
11197 			case IPV6_JOIN_GROUP:
11198 				mcast_opt = B_FALSE;
11199 				/* FALLTHRU */
11200 			case MCAST_JOIN_GROUP:
11201 				fmode = MODE_IS_EXCLUDE;
11202 				optfn = ip_opt_add_group_v6;
11203 				break;
11204 
11205 			case IPV6_LEAVE_GROUP:
11206 				mcast_opt = B_FALSE;
11207 				/* FALLTHRU */
11208 			case MCAST_LEAVE_GROUP:
11209 				fmode = MODE_IS_INCLUDE;
11210 				optfn = ip_opt_delete_group_v6;
11211 				break;
11212 			}
11213 
11214 			if (mcast_opt) {
11215 				struct sockaddr_in *sin;
11216 				struct sockaddr_in6 *sin6;
11217 				greqp = (struct group_req *)i1;
11218 				if (greqp->gr_group.ss_family == AF_INET) {
11219 					sin = (struct sockaddr_in *)
11220 					    &(greqp->gr_group);
11221 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11222 					    &groupv6);
11223 				} else {
11224 					sin6 = (struct sockaddr_in6 *)
11225 					    &(greqp->gr_group);
11226 					groupv6 = sin6->sin6_addr;
11227 				}
11228 				ifindex = greqp->gr_interface;
11229 			} else {
11230 				ip_mreqp = (struct ipv6_mreq *)i1;
11231 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11232 				ifindex = ip_mreqp->ipv6mr_interface;
11233 			}
11234 			/*
11235 			 * In the multirouting case, we need to replicate
11236 			 * the request on all interfaces that will take part
11237 			 * in replication.  We do so because multirouting is
11238 			 * reflective, thus we will probably receive multi-
11239 			 * casts on those interfaces.
11240 			 * The ip_multirt_apply_membership_v6() succeeds if
11241 			 * the operation succeeds on at least one interface.
11242 			 */
11243 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11244 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11245 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11246 			if (ire != NULL) {
11247 				if (ire->ire_flags & RTF_MULTIRT) {
11248 					error = ip_multirt_apply_membership_v6(
11249 					    optfn, ire, connp, checkonly,
11250 					    &groupv6, fmode, &ipv6_all_zeros,
11251 					    first_mp);
11252 					done = B_TRUE;
11253 				}
11254 				ire_refrele(ire);
11255 			}
11256 			if (!done) {
11257 				error = optfn(connp, checkonly, &groupv6,
11258 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11259 			}
11260 			if (error) {
11261 				/*
11262 				 * EINPROGRESS is a soft error, needs retry
11263 				 * so don't make *outlenp zero.
11264 				 */
11265 				if (error != EINPROGRESS)
11266 					*outlenp = 0;
11267 				return (error);
11268 			}
11269 			/* OK return - copy input buffer into output buffer */
11270 			if (invalp != outvalp) {
11271 				/* don't trust bcopy for identical src/dst */
11272 				bcopy(invalp, outvalp, inlen);
11273 			}
11274 			*outlenp = inlen;
11275 			return (0);
11276 		}
11277 		case MCAST_BLOCK_SOURCE:
11278 		case MCAST_UNBLOCK_SOURCE:
11279 		case MCAST_JOIN_SOURCE_GROUP:
11280 		case MCAST_LEAVE_SOURCE_GROUP: {
11281 			struct group_source_req *gsreqp;
11282 			in6_addr_t v6grp, v6src;
11283 			uint32_t ifindex;
11284 			mcast_record_t fmode;
11285 			ire_t *ire;
11286 			boolean_t done = B_FALSE;
11287 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11288 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11289 
11290 			switch (name) {
11291 			case MCAST_BLOCK_SOURCE:
11292 				fmode = MODE_IS_EXCLUDE;
11293 				optfn = ip_opt_add_group_v6;
11294 				break;
11295 			case MCAST_UNBLOCK_SOURCE:
11296 				fmode = MODE_IS_EXCLUDE;
11297 				optfn = ip_opt_delete_group_v6;
11298 				break;
11299 			case MCAST_JOIN_SOURCE_GROUP:
11300 				fmode = MODE_IS_INCLUDE;
11301 				optfn = ip_opt_add_group_v6;
11302 				break;
11303 			case MCAST_LEAVE_SOURCE_GROUP:
11304 				fmode = MODE_IS_INCLUDE;
11305 				optfn = ip_opt_delete_group_v6;
11306 				break;
11307 			}
11308 
11309 			gsreqp = (struct group_source_req *)i1;
11310 			ifindex = gsreqp->gsr_interface;
11311 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11312 				struct sockaddr_in *s;
11313 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11314 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11315 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11316 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11317 			} else {
11318 				struct sockaddr_in6 *s6;
11319 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11320 				v6grp = s6->sin6_addr;
11321 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11322 				v6src = s6->sin6_addr;
11323 			}
11324 
11325 			/*
11326 			 * In the multirouting case, we need to replicate
11327 			 * the request as noted in the mcast cases above.
11328 			 */
11329 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11330 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11331 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11332 			if (ire != NULL) {
11333 				if (ire->ire_flags & RTF_MULTIRT) {
11334 					error = ip_multirt_apply_membership_v6(
11335 					    optfn, ire, connp, checkonly,
11336 					    &v6grp, fmode, &v6src, first_mp);
11337 					done = B_TRUE;
11338 				}
11339 				ire_refrele(ire);
11340 			}
11341 			if (!done) {
11342 				error = optfn(connp, checkonly, &v6grp,
11343 				    ifindex, fmode, &v6src, first_mp);
11344 			}
11345 			if (error != 0) {
11346 				/*
11347 				 * EINPROGRESS is a soft error, needs retry
11348 				 * so don't make *outlenp zero.
11349 				 */
11350 				if (error != EINPROGRESS)
11351 					*outlenp = 0;
11352 				return (error);
11353 			}
11354 			/* OK return - copy input buffer into output buffer */
11355 			if (invalp != outvalp) {
11356 				bcopy(invalp, outvalp, inlen);
11357 			}
11358 			*outlenp = inlen;
11359 			return (0);
11360 		}
11361 		case IPV6_UNICAST_HOPS:
11362 			/* Recorded in transport above IP */
11363 			break;	/* goto sizeof (int) option return */
11364 		case IPV6_UNSPEC_SRC:
11365 			/* Allow sending with a zero source address */
11366 			if (!checkonly) {
11367 				mutex_enter(&connp->conn_lock);
11368 				connp->conn_unspec_src = *i1 ? 1 : 0;
11369 				mutex_exit(&connp->conn_lock);
11370 			}
11371 			break;	/* goto sizeof (int) option return */
11372 		case IPV6_RECVPKTINFO:
11373 			if (!checkonly) {
11374 				mutex_enter(&connp->conn_lock);
11375 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11376 				mutex_exit(&connp->conn_lock);
11377 			}
11378 			break;	/* goto sizeof (int) option return */
11379 		case IPV6_RECVTCLASS:
11380 			if (!checkonly) {
11381 				if (*i1 < 0 || *i1 > 1) {
11382 					return (EINVAL);
11383 				}
11384 				mutex_enter(&connp->conn_lock);
11385 				connp->conn_ipv6_recvtclass = *i1;
11386 				mutex_exit(&connp->conn_lock);
11387 			}
11388 			break;
11389 		case IPV6_RECVPATHMTU:
11390 			if (!checkonly) {
11391 				if (*i1 < 0 || *i1 > 1) {
11392 					return (EINVAL);
11393 				}
11394 				mutex_enter(&connp->conn_lock);
11395 				connp->conn_ipv6_recvpathmtu = *i1;
11396 				mutex_exit(&connp->conn_lock);
11397 			}
11398 			break;
11399 		case IPV6_RECVHOPLIMIT:
11400 			if (!checkonly) {
11401 				mutex_enter(&connp->conn_lock);
11402 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11403 				mutex_exit(&connp->conn_lock);
11404 			}
11405 			break;	/* goto sizeof (int) option return */
11406 		case IPV6_RECVHOPOPTS:
11407 			if (!checkonly) {
11408 				mutex_enter(&connp->conn_lock);
11409 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11410 				mutex_exit(&connp->conn_lock);
11411 			}
11412 			break;	/* goto sizeof (int) option return */
11413 		case IPV6_RECVDSTOPTS:
11414 			if (!checkonly) {
11415 				mutex_enter(&connp->conn_lock);
11416 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11417 				mutex_exit(&connp->conn_lock);
11418 			}
11419 			break;	/* goto sizeof (int) option return */
11420 		case IPV6_RECVRTHDR:
11421 			if (!checkonly) {
11422 				mutex_enter(&connp->conn_lock);
11423 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11424 				mutex_exit(&connp->conn_lock);
11425 			}
11426 			break;	/* goto sizeof (int) option return */
11427 		case IPV6_RECVRTHDRDSTOPTS:
11428 			if (!checkonly) {
11429 				mutex_enter(&connp->conn_lock);
11430 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11431 				mutex_exit(&connp->conn_lock);
11432 			}
11433 			break;	/* goto sizeof (int) option return */
11434 		case IPV6_PKTINFO:
11435 			if (inlen == 0)
11436 				return (-EINVAL);	/* clearing option */
11437 			error = ip6_set_pktinfo(cr, connp,
11438 			    (struct in6_pktinfo *)invalp, first_mp);
11439 			if (error != 0)
11440 				*outlenp = 0;
11441 			else
11442 				*outlenp = inlen;
11443 			return (error);
11444 		case IPV6_NEXTHOP: {
11445 			struct sockaddr_in6 *sin6;
11446 
11447 			/* Verify that the nexthop is reachable */
11448 			if (inlen == 0)
11449 				return (-EINVAL);	/* clearing option */
11450 
11451 			sin6 = (struct sockaddr_in6 *)invalp;
11452 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11453 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11454 			    NULL, MATCH_IRE_DEFAULT, ipst);
11455 
11456 			if (ire == NULL) {
11457 				*outlenp = 0;
11458 				return (EHOSTUNREACH);
11459 			}
11460 			ire_refrele(ire);
11461 			return (-EINVAL);
11462 		}
11463 		case IPV6_SEC_OPT:
11464 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11465 			if (error != 0) {
11466 				*outlenp = 0;
11467 				return (error);
11468 			}
11469 			break;
11470 		case IPV6_SRC_PREFERENCES: {
11471 			/*
11472 			 * This is implemented strictly in the ip module
11473 			 * (here and in tcp_opt_*() to accomodate tcp
11474 			 * sockets).  Modules above ip pass this option
11475 			 * down here since ip is the only one that needs to
11476 			 * be aware of source address preferences.
11477 			 *
11478 			 * This socket option only affects connected
11479 			 * sockets that haven't already bound to a specific
11480 			 * IPv6 address.  In other words, sockets that
11481 			 * don't call bind() with an address other than the
11482 			 * unspecified address and that call connect().
11483 			 * ip_bind_connected_v6() passes these preferences
11484 			 * to the ipif_select_source_v6() function.
11485 			 */
11486 			if (inlen != sizeof (uint32_t))
11487 				return (EINVAL);
11488 			error = ip6_set_src_preferences(connp,
11489 			    *(uint32_t *)invalp);
11490 			if (error != 0) {
11491 				*outlenp = 0;
11492 				return (error);
11493 			} else {
11494 				*outlenp = sizeof (uint32_t);
11495 			}
11496 			break;
11497 		}
11498 		case IPV6_V6ONLY:
11499 			if (*i1 < 0 || *i1 > 1) {
11500 				return (EINVAL);
11501 			}
11502 			mutex_enter(&connp->conn_lock);
11503 			connp->conn_ipv6_v6only = *i1;
11504 			mutex_exit(&connp->conn_lock);
11505 			break;
11506 		default:
11507 			return (-EINVAL);
11508 		}
11509 		break;
11510 	default:
11511 		/*
11512 		 * "soft" error (negative)
11513 		 * option not handled at this level
11514 		 * Note: Do not modify *outlenp
11515 		 */
11516 		return (-EINVAL);
11517 	}
11518 	/*
11519 	 * Common case of return from an option that is sizeof (int)
11520 	 */
11521 	*(int *)outvalp = *i1;
11522 	*outlenp = sizeof (int);
11523 	return (0);
11524 }
11525 
11526 /*
11527  * This routine gets default values of certain options whose default
11528  * values are maintained by protocol specific code
11529  */
11530 /* ARGSUSED */
11531 int
11532 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11533 {
11534 	int *i1 = (int *)ptr;
11535 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11536 
11537 	switch (level) {
11538 	case IPPROTO_IP:
11539 		switch (name) {
11540 		case IP_MULTICAST_TTL:
11541 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11542 			return (sizeof (uchar_t));
11543 		case IP_MULTICAST_LOOP:
11544 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11545 			return (sizeof (uchar_t));
11546 		default:
11547 			return (-1);
11548 		}
11549 	case IPPROTO_IPV6:
11550 		switch (name) {
11551 		case IPV6_UNICAST_HOPS:
11552 			*i1 = ipst->ips_ipv6_def_hops;
11553 			return (sizeof (int));
11554 		case IPV6_MULTICAST_HOPS:
11555 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11556 			return (sizeof (int));
11557 		case IPV6_MULTICAST_LOOP:
11558 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11559 			return (sizeof (int));
11560 		case IPV6_V6ONLY:
11561 			*i1 = 1;
11562 			return (sizeof (int));
11563 		default:
11564 			return (-1);
11565 		}
11566 	default:
11567 		return (-1);
11568 	}
11569 	/* NOTREACHED */
11570 }
11571 
11572 /*
11573  * Given a destination address and a pointer to where to put the information
11574  * this routine fills in the mtuinfo.
11575  */
11576 int
11577 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11578     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11579 {
11580 	ire_t *ire;
11581 	ip_stack_t	*ipst = ns->netstack_ip;
11582 
11583 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11584 		return (-1);
11585 
11586 	bzero(mtuinfo, sizeof (*mtuinfo));
11587 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11588 	mtuinfo->ip6m_addr.sin6_port = port;
11589 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11590 
11591 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11592 	if (ire != NULL) {
11593 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11594 		ire_refrele(ire);
11595 	} else {
11596 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11597 	}
11598 	return (sizeof (struct ip6_mtuinfo));
11599 }
11600 
11601 /*
11602  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11603  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11604  * isn't.  This doesn't matter as the error checking is done properly for the
11605  * other MRT options coming in through ip_opt_set.
11606  */
11607 int
11608 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11609 {
11610 	conn_t		*connp = Q_TO_CONN(q);
11611 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11612 
11613 	switch (level) {
11614 	case IPPROTO_IP:
11615 		switch (name) {
11616 		case MRT_VERSION:
11617 		case MRT_ASSERT:
11618 			(void) ip_mrouter_get(name, q, ptr);
11619 			return (sizeof (int));
11620 		case IP_SEC_OPT:
11621 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11622 		case IP_NEXTHOP:
11623 			if (connp->conn_nexthop_set) {
11624 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11625 				return (sizeof (ipaddr_t));
11626 			} else
11627 				return (0);
11628 		case IP_RECVPKTINFO:
11629 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11630 			return (sizeof (int));
11631 		default:
11632 			break;
11633 		}
11634 		break;
11635 	case IPPROTO_IPV6:
11636 		switch (name) {
11637 		case IPV6_SEC_OPT:
11638 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11639 		case IPV6_SRC_PREFERENCES: {
11640 			return (ip6_get_src_preferences(connp,
11641 			    (uint32_t *)ptr));
11642 		}
11643 		case IPV6_V6ONLY:
11644 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11645 			return (sizeof (int));
11646 		case IPV6_PATHMTU:
11647 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11648 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11649 		default:
11650 			break;
11651 		}
11652 		break;
11653 	default:
11654 		break;
11655 	}
11656 	return (-1);
11657 }
11658 
11659 /* Named Dispatch routine to get a current value out of our parameter table. */
11660 /* ARGSUSED */
11661 static int
11662 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11663 {
11664 	ipparam_t *ippa = (ipparam_t *)cp;
11665 
11666 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11667 	return (0);
11668 }
11669 
11670 /* ARGSUSED */
11671 static int
11672 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11673 {
11674 
11675 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11676 	return (0);
11677 }
11678 
11679 /*
11680  * Set ip{,6}_forwarding values.  This means walking through all of the
11681  * ill's and toggling their forwarding values.
11682  */
11683 /* ARGSUSED */
11684 static int
11685 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11686 {
11687 	long new_value;
11688 	int *forwarding_value = (int *)cp;
11689 	ill_t *ill;
11690 	boolean_t isv6;
11691 	ill_walk_context_t ctx;
11692 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11693 
11694 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11695 
11696 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11697 	    new_value < 0 || new_value > 1) {
11698 		return (EINVAL);
11699 	}
11700 
11701 	*forwarding_value = new_value;
11702 
11703 	/*
11704 	 * Regardless of the current value of ip_forwarding, set all per-ill
11705 	 * values of ip_forwarding to the value being set.
11706 	 *
11707 	 * Bring all the ill's up to date with the new global value.
11708 	 */
11709 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11710 
11711 	if (isv6)
11712 		ill = ILL_START_WALK_V6(&ctx, ipst);
11713 	else
11714 		ill = ILL_START_WALK_V4(&ctx, ipst);
11715 
11716 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11717 		(void) ill_forward_set(ill, new_value != 0);
11718 
11719 	rw_exit(&ipst->ips_ill_g_lock);
11720 	return (0);
11721 }
11722 
11723 /*
11724  * Walk through the param array specified registering each element with the
11725  * Named Dispatch handler. This is called only during init. So it is ok
11726  * not to acquire any locks
11727  */
11728 static boolean_t
11729 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11730     ipndp_t *ipnd, size_t ipnd_cnt)
11731 {
11732 	for (; ippa_cnt-- > 0; ippa++) {
11733 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11734 			if (!nd_load(ndp, ippa->ip_param_name,
11735 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11736 				nd_free(ndp);
11737 				return (B_FALSE);
11738 			}
11739 		}
11740 	}
11741 
11742 	for (; ipnd_cnt-- > 0; ipnd++) {
11743 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11744 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11745 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11746 			    ipnd->ip_ndp_data)) {
11747 				nd_free(ndp);
11748 				return (B_FALSE);
11749 			}
11750 		}
11751 	}
11752 
11753 	return (B_TRUE);
11754 }
11755 
11756 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11757 /* ARGSUSED */
11758 static int
11759 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11760 {
11761 	long		new_value;
11762 	ipparam_t	*ippa = (ipparam_t *)cp;
11763 
11764 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11765 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11766 		return (EINVAL);
11767 	}
11768 	ippa->ip_param_value = new_value;
11769 	return (0);
11770 }
11771 
11772 /*
11773  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11774  * When an ipf is passed here for the first time, if
11775  * we already have in-order fragments on the queue, we convert from the fast-
11776  * path reassembly scheme to the hard-case scheme.  From then on, additional
11777  * fragments are reassembled here.  We keep track of the start and end offsets
11778  * of each piece, and the number of holes in the chain.  When the hole count
11779  * goes to zero, we are done!
11780  *
11781  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11782  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11783  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11784  * after the call to ip_reassemble().
11785  */
11786 int
11787 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11788     size_t msg_len)
11789 {
11790 	uint_t	end;
11791 	mblk_t	*next_mp;
11792 	mblk_t	*mp1;
11793 	uint_t	offset;
11794 	boolean_t incr_dups = B_TRUE;
11795 	boolean_t offset_zero_seen = B_FALSE;
11796 	boolean_t pkt_boundary_checked = B_FALSE;
11797 
11798 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11799 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11800 
11801 	/* Add in byte count */
11802 	ipf->ipf_count += msg_len;
11803 	if (ipf->ipf_end) {
11804 		/*
11805 		 * We were part way through in-order reassembly, but now there
11806 		 * is a hole.  We walk through messages already queued, and
11807 		 * mark them for hard case reassembly.  We know that up till
11808 		 * now they were in order starting from offset zero.
11809 		 */
11810 		offset = 0;
11811 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11812 			IP_REASS_SET_START(mp1, offset);
11813 			if (offset == 0) {
11814 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11815 				offset = -ipf->ipf_nf_hdr_len;
11816 			}
11817 			offset += mp1->b_wptr - mp1->b_rptr;
11818 			IP_REASS_SET_END(mp1, offset);
11819 		}
11820 		/* One hole at the end. */
11821 		ipf->ipf_hole_cnt = 1;
11822 		/* Brand it as a hard case, forever. */
11823 		ipf->ipf_end = 0;
11824 	}
11825 	/* Walk through all the new pieces. */
11826 	do {
11827 		end = start + (mp->b_wptr - mp->b_rptr);
11828 		/*
11829 		 * If start is 0, decrease 'end' only for the first mblk of
11830 		 * the fragment. Otherwise 'end' can get wrong value in the
11831 		 * second pass of the loop if first mblk is exactly the
11832 		 * size of ipf_nf_hdr_len.
11833 		 */
11834 		if (start == 0 && !offset_zero_seen) {
11835 			/* First segment */
11836 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11837 			end -= ipf->ipf_nf_hdr_len;
11838 			offset_zero_seen = B_TRUE;
11839 		}
11840 		next_mp = mp->b_cont;
11841 		/*
11842 		 * We are checking to see if there is any interesing data
11843 		 * to process.  If there isn't and the mblk isn't the
11844 		 * one which carries the unfragmentable header then we
11845 		 * drop it.  It's possible to have just the unfragmentable
11846 		 * header come through without any data.  That needs to be
11847 		 * saved.
11848 		 *
11849 		 * If the assert at the top of this function holds then the
11850 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11851 		 * is infrequently traveled enough that the test is left in
11852 		 * to protect against future code changes which break that
11853 		 * invariant.
11854 		 */
11855 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11856 			/* Empty.  Blast it. */
11857 			IP_REASS_SET_START(mp, 0);
11858 			IP_REASS_SET_END(mp, 0);
11859 			/*
11860 			 * If the ipf points to the mblk we are about to free,
11861 			 * update ipf to point to the next mblk (or NULL
11862 			 * if none).
11863 			 */
11864 			if (ipf->ipf_mp->b_cont == mp)
11865 				ipf->ipf_mp->b_cont = next_mp;
11866 			freeb(mp);
11867 			continue;
11868 		}
11869 		mp->b_cont = NULL;
11870 		IP_REASS_SET_START(mp, start);
11871 		IP_REASS_SET_END(mp, end);
11872 		if (!ipf->ipf_tail_mp) {
11873 			ipf->ipf_tail_mp = mp;
11874 			ipf->ipf_mp->b_cont = mp;
11875 			if (start == 0 || !more) {
11876 				ipf->ipf_hole_cnt = 1;
11877 				/*
11878 				 * if the first fragment comes in more than one
11879 				 * mblk, this loop will be executed for each
11880 				 * mblk. Need to adjust hole count so exiting
11881 				 * this routine will leave hole count at 1.
11882 				 */
11883 				if (next_mp)
11884 					ipf->ipf_hole_cnt++;
11885 			} else
11886 				ipf->ipf_hole_cnt = 2;
11887 			continue;
11888 		} else if (ipf->ipf_last_frag_seen && !more &&
11889 		    !pkt_boundary_checked) {
11890 			/*
11891 			 * We check datagram boundary only if this fragment
11892 			 * claims to be the last fragment and we have seen a
11893 			 * last fragment in the past too. We do this only
11894 			 * once for a given fragment.
11895 			 *
11896 			 * start cannot be 0 here as fragments with start=0
11897 			 * and MF=0 gets handled as a complete packet. These
11898 			 * fragments should not reach here.
11899 			 */
11900 
11901 			if (start + msgdsize(mp) !=
11902 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11903 				/*
11904 				 * We have two fragments both of which claim
11905 				 * to be the last fragment but gives conflicting
11906 				 * information about the whole datagram size.
11907 				 * Something fishy is going on. Drop the
11908 				 * fragment and free up the reassembly list.
11909 				 */
11910 				return (IP_REASS_FAILED);
11911 			}
11912 
11913 			/*
11914 			 * We shouldn't come to this code block again for this
11915 			 * particular fragment.
11916 			 */
11917 			pkt_boundary_checked = B_TRUE;
11918 		}
11919 
11920 		/* New stuff at or beyond tail? */
11921 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11922 		if (start >= offset) {
11923 			if (ipf->ipf_last_frag_seen) {
11924 				/* current fragment is beyond last fragment */
11925 				return (IP_REASS_FAILED);
11926 			}
11927 			/* Link it on end. */
11928 			ipf->ipf_tail_mp->b_cont = mp;
11929 			ipf->ipf_tail_mp = mp;
11930 			if (more) {
11931 				if (start != offset)
11932 					ipf->ipf_hole_cnt++;
11933 			} else if (start == offset && next_mp == NULL)
11934 					ipf->ipf_hole_cnt--;
11935 			continue;
11936 		}
11937 		mp1 = ipf->ipf_mp->b_cont;
11938 		offset = IP_REASS_START(mp1);
11939 		/* New stuff at the front? */
11940 		if (start < offset) {
11941 			if (start == 0) {
11942 				if (end >= offset) {
11943 					/* Nailed the hole at the begining. */
11944 					ipf->ipf_hole_cnt--;
11945 				}
11946 			} else if (end < offset) {
11947 				/*
11948 				 * A hole, stuff, and a hole where there used
11949 				 * to be just a hole.
11950 				 */
11951 				ipf->ipf_hole_cnt++;
11952 			}
11953 			mp->b_cont = mp1;
11954 			/* Check for overlap. */
11955 			while (end > offset) {
11956 				if (end < IP_REASS_END(mp1)) {
11957 					mp->b_wptr -= end - offset;
11958 					IP_REASS_SET_END(mp, offset);
11959 					BUMP_MIB(ill->ill_ip_mib,
11960 					    ipIfStatsReasmPartDups);
11961 					break;
11962 				}
11963 				/* Did we cover another hole? */
11964 				if ((mp1->b_cont &&
11965 				    IP_REASS_END(mp1) !=
11966 				    IP_REASS_START(mp1->b_cont) &&
11967 				    end >= IP_REASS_START(mp1->b_cont)) ||
11968 				    (!ipf->ipf_last_frag_seen && !more)) {
11969 					ipf->ipf_hole_cnt--;
11970 				}
11971 				/* Clip out mp1. */
11972 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11973 					/*
11974 					 * After clipping out mp1, this guy
11975 					 * is now hanging off the end.
11976 					 */
11977 					ipf->ipf_tail_mp = mp;
11978 				}
11979 				IP_REASS_SET_START(mp1, 0);
11980 				IP_REASS_SET_END(mp1, 0);
11981 				/* Subtract byte count */
11982 				ipf->ipf_count -= mp1->b_datap->db_lim -
11983 				    mp1->b_datap->db_base;
11984 				freeb(mp1);
11985 				BUMP_MIB(ill->ill_ip_mib,
11986 				    ipIfStatsReasmPartDups);
11987 				mp1 = mp->b_cont;
11988 				if (!mp1)
11989 					break;
11990 				offset = IP_REASS_START(mp1);
11991 			}
11992 			ipf->ipf_mp->b_cont = mp;
11993 			continue;
11994 		}
11995 		/*
11996 		 * The new piece starts somewhere between the start of the head
11997 		 * and before the end of the tail.
11998 		 */
11999 		for (; mp1; mp1 = mp1->b_cont) {
12000 			offset = IP_REASS_END(mp1);
12001 			if (start < offset) {
12002 				if (end <= offset) {
12003 					/* Nothing new. */
12004 					IP_REASS_SET_START(mp, 0);
12005 					IP_REASS_SET_END(mp, 0);
12006 					/* Subtract byte count */
12007 					ipf->ipf_count -= mp->b_datap->db_lim -
12008 					    mp->b_datap->db_base;
12009 					if (incr_dups) {
12010 						ipf->ipf_num_dups++;
12011 						incr_dups = B_FALSE;
12012 					}
12013 					freeb(mp);
12014 					BUMP_MIB(ill->ill_ip_mib,
12015 					    ipIfStatsReasmDuplicates);
12016 					break;
12017 				}
12018 				/*
12019 				 * Trim redundant stuff off beginning of new
12020 				 * piece.
12021 				 */
12022 				IP_REASS_SET_START(mp, offset);
12023 				mp->b_rptr += offset - start;
12024 				BUMP_MIB(ill->ill_ip_mib,
12025 				    ipIfStatsReasmPartDups);
12026 				start = offset;
12027 				if (!mp1->b_cont) {
12028 					/*
12029 					 * After trimming, this guy is now
12030 					 * hanging off the end.
12031 					 */
12032 					mp1->b_cont = mp;
12033 					ipf->ipf_tail_mp = mp;
12034 					if (!more) {
12035 						ipf->ipf_hole_cnt--;
12036 					}
12037 					break;
12038 				}
12039 			}
12040 			if (start >= IP_REASS_START(mp1->b_cont))
12041 				continue;
12042 			/* Fill a hole */
12043 			if (start > offset)
12044 				ipf->ipf_hole_cnt++;
12045 			mp->b_cont = mp1->b_cont;
12046 			mp1->b_cont = mp;
12047 			mp1 = mp->b_cont;
12048 			offset = IP_REASS_START(mp1);
12049 			if (end >= offset) {
12050 				ipf->ipf_hole_cnt--;
12051 				/* Check for overlap. */
12052 				while (end > offset) {
12053 					if (end < IP_REASS_END(mp1)) {
12054 						mp->b_wptr -= end - offset;
12055 						IP_REASS_SET_END(mp, offset);
12056 						/*
12057 						 * TODO we might bump
12058 						 * this up twice if there is
12059 						 * overlap at both ends.
12060 						 */
12061 						BUMP_MIB(ill->ill_ip_mib,
12062 						    ipIfStatsReasmPartDups);
12063 						break;
12064 					}
12065 					/* Did we cover another hole? */
12066 					if ((mp1->b_cont &&
12067 					    IP_REASS_END(mp1)
12068 					    != IP_REASS_START(mp1->b_cont) &&
12069 					    end >=
12070 					    IP_REASS_START(mp1->b_cont)) ||
12071 					    (!ipf->ipf_last_frag_seen &&
12072 					    !more)) {
12073 						ipf->ipf_hole_cnt--;
12074 					}
12075 					/* Clip out mp1. */
12076 					if ((mp->b_cont = mp1->b_cont) ==
12077 					    NULL) {
12078 						/*
12079 						 * After clipping out mp1,
12080 						 * this guy is now hanging
12081 						 * off the end.
12082 						 */
12083 						ipf->ipf_tail_mp = mp;
12084 					}
12085 					IP_REASS_SET_START(mp1, 0);
12086 					IP_REASS_SET_END(mp1, 0);
12087 					/* Subtract byte count */
12088 					ipf->ipf_count -=
12089 					    mp1->b_datap->db_lim -
12090 					    mp1->b_datap->db_base;
12091 					freeb(mp1);
12092 					BUMP_MIB(ill->ill_ip_mib,
12093 					    ipIfStatsReasmPartDups);
12094 					mp1 = mp->b_cont;
12095 					if (!mp1)
12096 						break;
12097 					offset = IP_REASS_START(mp1);
12098 				}
12099 			}
12100 			break;
12101 		}
12102 	} while (start = end, mp = next_mp);
12103 
12104 	/* Fragment just processed could be the last one. Remember this fact */
12105 	if (!more)
12106 		ipf->ipf_last_frag_seen = B_TRUE;
12107 
12108 	/* Still got holes? */
12109 	if (ipf->ipf_hole_cnt)
12110 		return (IP_REASS_PARTIAL);
12111 	/* Clean up overloaded fields to avoid upstream disasters. */
12112 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12113 		IP_REASS_SET_START(mp1, 0);
12114 		IP_REASS_SET_END(mp1, 0);
12115 	}
12116 	return (IP_REASS_COMPLETE);
12117 }
12118 
12119 /*
12120  * ipsec processing for the fast path, used for input UDP Packets
12121  * Returns true if ready for passup to UDP.
12122  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12123  * was an ESP-in-UDP packet, etc.).
12124  */
12125 static boolean_t
12126 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12127     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12128 {
12129 	uint32_t	ill_index;
12130 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12131 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12132 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12133 	udp_t		*udp = connp->conn_udp;
12134 
12135 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12136 	/* The ill_index of the incoming ILL */
12137 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12138 
12139 	/* pass packet up to the transport */
12140 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12141 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12142 		    NULL, mctl_present);
12143 		if (*first_mpp == NULL) {
12144 			return (B_FALSE);
12145 		}
12146 	}
12147 
12148 	/* Initiate IPPF processing for fastpath UDP */
12149 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12150 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12151 		if (*mpp == NULL) {
12152 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12153 			    "deferred/dropped during IPPF processing\n"));
12154 			return (B_FALSE);
12155 		}
12156 	}
12157 	/*
12158 	 * Remove 0-spi if it's 0, or move everything behind
12159 	 * the UDP header over it and forward to ESP via
12160 	 * ip_proto_input().
12161 	 */
12162 	if (udp->udp_nat_t_endpoint) {
12163 		if (mctl_present) {
12164 			/* mctl_present *shouldn't* happen. */
12165 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12166 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12167 			    &ipss->ipsec_dropper);
12168 			*first_mpp = NULL;
12169 			return (B_FALSE);
12170 		}
12171 
12172 		/* "ill" is "recv_ill" in actuality. */
12173 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12174 			return (B_FALSE);
12175 
12176 		/* Else continue like a normal UDP packet. */
12177 	}
12178 
12179 	/*
12180 	 * We make the checks as below since we are in the fast path
12181 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12182 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12183 	 */
12184 	if (connp->conn_recvif || connp->conn_recvslla ||
12185 	    connp->conn_ip_recvpktinfo) {
12186 		if (connp->conn_recvif) {
12187 			in_flags = IPF_RECVIF;
12188 		}
12189 		/*
12190 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12191 		 * so the flag passed to ip_add_info is based on IP version
12192 		 * of connp.
12193 		 */
12194 		if (connp->conn_ip_recvpktinfo) {
12195 			if (connp->conn_af_isv6) {
12196 				/*
12197 				 * V6 only needs index
12198 				 */
12199 				in_flags |= IPF_RECVIF;
12200 			} else {
12201 				/*
12202 				 * V4 needs index + matching address.
12203 				 */
12204 				in_flags |= IPF_RECVADDR;
12205 			}
12206 		}
12207 		if (connp->conn_recvslla) {
12208 			in_flags |= IPF_RECVSLLA;
12209 		}
12210 		/*
12211 		 * since in_flags are being set ill will be
12212 		 * referenced in ip_add_info, so it better not
12213 		 * be NULL.
12214 		 */
12215 		/*
12216 		 * the actual data will be contained in b_cont
12217 		 * upon successful return of the following call.
12218 		 * If the call fails then the original mblk is
12219 		 * returned.
12220 		 */
12221 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12222 		    ipst);
12223 	}
12224 
12225 	return (B_TRUE);
12226 }
12227 
12228 /*
12229  * Fragmentation reassembly.  Each ILL has a hash table for
12230  * queuing packets undergoing reassembly for all IPIFs
12231  * associated with the ILL.  The hash is based on the packet
12232  * IP ident field.  The ILL frag hash table was allocated
12233  * as a timer block at the time the ILL was created.  Whenever
12234  * there is anything on the reassembly queue, the timer will
12235  * be running.  Returns B_TRUE if successful else B_FALSE;
12236  * frees mp on failure.
12237  */
12238 static boolean_t
12239 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12240     uint32_t *cksum_val, uint16_t *cksum_flags)
12241 {
12242 	uint32_t	frag_offset_flags;
12243 	ill_t		*ill = (ill_t *)q->q_ptr;
12244 	mblk_t		*mp = *mpp;
12245 	mblk_t		*t_mp;
12246 	ipaddr_t	dst;
12247 	uint8_t		proto = ipha->ipha_protocol;
12248 	uint32_t	sum_val;
12249 	uint16_t	sum_flags;
12250 	ipf_t		*ipf;
12251 	ipf_t		**ipfp;
12252 	ipfb_t		*ipfb;
12253 	uint16_t	ident;
12254 	uint32_t	offset;
12255 	ipaddr_t	src;
12256 	uint_t		hdr_length;
12257 	uint32_t	end;
12258 	mblk_t		*mp1;
12259 	mblk_t		*tail_mp;
12260 	size_t		count;
12261 	size_t		msg_len;
12262 	uint8_t		ecn_info = 0;
12263 	uint32_t	packet_size;
12264 	boolean_t	pruned = B_FALSE;
12265 	ip_stack_t *ipst = ill->ill_ipst;
12266 
12267 	if (cksum_val != NULL)
12268 		*cksum_val = 0;
12269 	if (cksum_flags != NULL)
12270 		*cksum_flags = 0;
12271 
12272 	/*
12273 	 * Drop the fragmented as early as possible, if
12274 	 * we don't have resource(s) to re-assemble.
12275 	 */
12276 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12277 		freemsg(mp);
12278 		return (B_FALSE);
12279 	}
12280 
12281 	/* Check for fragmentation offset; return if there's none */
12282 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12283 	    (IPH_MF | IPH_OFFSET)) == 0)
12284 		return (B_TRUE);
12285 
12286 	/*
12287 	 * We utilize hardware computed checksum info only for UDP since
12288 	 * IP fragmentation is a normal occurence for the protocol.  In
12289 	 * addition, checksum offload support for IP fragments carrying
12290 	 * UDP payload is commonly implemented across network adapters.
12291 	 */
12292 	ASSERT(ill != NULL);
12293 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12294 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12295 		mblk_t *mp1 = mp->b_cont;
12296 		int32_t len;
12297 
12298 		/* Record checksum information from the packet */
12299 		sum_val = (uint32_t)DB_CKSUM16(mp);
12300 		sum_flags = DB_CKSUMFLAGS(mp);
12301 
12302 		/* IP payload offset from beginning of mblk */
12303 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12304 
12305 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12306 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12307 		    offset >= DB_CKSUMSTART(mp) &&
12308 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12309 			uint32_t adj;
12310 			/*
12311 			 * Partial checksum has been calculated by hardware
12312 			 * and attached to the packet; in addition, any
12313 			 * prepended extraneous data is even byte aligned.
12314 			 * If any such data exists, we adjust the checksum;
12315 			 * this would also handle any postpended data.
12316 			 */
12317 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12318 			    mp, mp1, len, adj);
12319 
12320 			/* One's complement subtract extraneous checksum */
12321 			if (adj >= sum_val)
12322 				sum_val = ~(adj - sum_val) & 0xFFFF;
12323 			else
12324 				sum_val -= adj;
12325 		}
12326 	} else {
12327 		sum_val = 0;
12328 		sum_flags = 0;
12329 	}
12330 
12331 	/* Clear hardware checksumming flag */
12332 	DB_CKSUMFLAGS(mp) = 0;
12333 
12334 	ident = ipha->ipha_ident;
12335 	offset = (frag_offset_flags << 3) & 0xFFFF;
12336 	src = ipha->ipha_src;
12337 	dst = ipha->ipha_dst;
12338 	hdr_length = IPH_HDR_LENGTH(ipha);
12339 	end = ntohs(ipha->ipha_length) - hdr_length;
12340 
12341 	/* If end == 0 then we have a packet with no data, so just free it */
12342 	if (end == 0) {
12343 		freemsg(mp);
12344 		return (B_FALSE);
12345 	}
12346 
12347 	/* Record the ECN field info. */
12348 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12349 	if (offset != 0) {
12350 		/*
12351 		 * If this isn't the first piece, strip the header, and
12352 		 * add the offset to the end value.
12353 		 */
12354 		mp->b_rptr += hdr_length;
12355 		end += offset;
12356 	}
12357 
12358 	msg_len = MBLKSIZE(mp);
12359 	tail_mp = mp;
12360 	while (tail_mp->b_cont != NULL) {
12361 		tail_mp = tail_mp->b_cont;
12362 		msg_len += MBLKSIZE(tail_mp);
12363 	}
12364 
12365 	/* If the reassembly list for this ILL will get too big, prune it */
12366 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12367 	    ipst->ips_ip_reass_queue_bytes) {
12368 		ill_frag_prune(ill,
12369 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12370 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12371 		pruned = B_TRUE;
12372 	}
12373 
12374 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12375 	mutex_enter(&ipfb->ipfb_lock);
12376 
12377 	ipfp = &ipfb->ipfb_ipf;
12378 	/* Try to find an existing fragment queue for this packet. */
12379 	for (;;) {
12380 		ipf = ipfp[0];
12381 		if (ipf != NULL) {
12382 			/*
12383 			 * It has to match on ident and src/dst address.
12384 			 */
12385 			if (ipf->ipf_ident == ident &&
12386 			    ipf->ipf_src == src &&
12387 			    ipf->ipf_dst == dst &&
12388 			    ipf->ipf_protocol == proto) {
12389 				/*
12390 				 * If we have received too many
12391 				 * duplicate fragments for this packet
12392 				 * free it.
12393 				 */
12394 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12395 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12396 					freemsg(mp);
12397 					mutex_exit(&ipfb->ipfb_lock);
12398 					return (B_FALSE);
12399 				}
12400 				/* Found it. */
12401 				break;
12402 			}
12403 			ipfp = &ipf->ipf_hash_next;
12404 			continue;
12405 		}
12406 
12407 		/*
12408 		 * If we pruned the list, do we want to store this new
12409 		 * fragment?. We apply an optimization here based on the
12410 		 * fact that most fragments will be received in order.
12411 		 * So if the offset of this incoming fragment is zero,
12412 		 * it is the first fragment of a new packet. We will
12413 		 * keep it.  Otherwise drop the fragment, as we have
12414 		 * probably pruned the packet already (since the
12415 		 * packet cannot be found).
12416 		 */
12417 		if (pruned && offset != 0) {
12418 			mutex_exit(&ipfb->ipfb_lock);
12419 			freemsg(mp);
12420 			return (B_FALSE);
12421 		}
12422 
12423 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12424 			/*
12425 			 * Too many fragmented packets in this hash
12426 			 * bucket. Free the oldest.
12427 			 */
12428 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12429 		}
12430 
12431 		/* New guy.  Allocate a frag message. */
12432 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12433 		if (mp1 == NULL) {
12434 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12435 			freemsg(mp);
12436 reass_done:
12437 			mutex_exit(&ipfb->ipfb_lock);
12438 			return (B_FALSE);
12439 		}
12440 
12441 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12442 		mp1->b_cont = mp;
12443 
12444 		/* Initialize the fragment header. */
12445 		ipf = (ipf_t *)mp1->b_rptr;
12446 		ipf->ipf_mp = mp1;
12447 		ipf->ipf_ptphn = ipfp;
12448 		ipfp[0] = ipf;
12449 		ipf->ipf_hash_next = NULL;
12450 		ipf->ipf_ident = ident;
12451 		ipf->ipf_protocol = proto;
12452 		ipf->ipf_src = src;
12453 		ipf->ipf_dst = dst;
12454 		ipf->ipf_nf_hdr_len = 0;
12455 		/* Record reassembly start time. */
12456 		ipf->ipf_timestamp = gethrestime_sec();
12457 		/* Record ipf generation and account for frag header */
12458 		ipf->ipf_gen = ill->ill_ipf_gen++;
12459 		ipf->ipf_count = MBLKSIZE(mp1);
12460 		ipf->ipf_last_frag_seen = B_FALSE;
12461 		ipf->ipf_ecn = ecn_info;
12462 		ipf->ipf_num_dups = 0;
12463 		ipfb->ipfb_frag_pkts++;
12464 		ipf->ipf_checksum = 0;
12465 		ipf->ipf_checksum_flags = 0;
12466 
12467 		/* Store checksum value in fragment header */
12468 		if (sum_flags != 0) {
12469 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12470 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12471 			ipf->ipf_checksum = sum_val;
12472 			ipf->ipf_checksum_flags = sum_flags;
12473 		}
12474 
12475 		/*
12476 		 * We handle reassembly two ways.  In the easy case,
12477 		 * where all the fragments show up in order, we do
12478 		 * minimal bookkeeping, and just clip new pieces on
12479 		 * the end.  If we ever see a hole, then we go off
12480 		 * to ip_reassemble which has to mark the pieces and
12481 		 * keep track of the number of holes, etc.  Obviously,
12482 		 * the point of having both mechanisms is so we can
12483 		 * handle the easy case as efficiently as possible.
12484 		 */
12485 		if (offset == 0) {
12486 			/* Easy case, in-order reassembly so far. */
12487 			ipf->ipf_count += msg_len;
12488 			ipf->ipf_tail_mp = tail_mp;
12489 			/*
12490 			 * Keep track of next expected offset in
12491 			 * ipf_end.
12492 			 */
12493 			ipf->ipf_end = end;
12494 			ipf->ipf_nf_hdr_len = hdr_length;
12495 		} else {
12496 			/* Hard case, hole at the beginning. */
12497 			ipf->ipf_tail_mp = NULL;
12498 			/*
12499 			 * ipf_end == 0 means that we have given up
12500 			 * on easy reassembly.
12501 			 */
12502 			ipf->ipf_end = 0;
12503 
12504 			/* Forget checksum offload from now on */
12505 			ipf->ipf_checksum_flags = 0;
12506 
12507 			/*
12508 			 * ipf_hole_cnt is set by ip_reassemble.
12509 			 * ipf_count is updated by ip_reassemble.
12510 			 * No need to check for return value here
12511 			 * as we don't expect reassembly to complete
12512 			 * or fail for the first fragment itself.
12513 			 */
12514 			(void) ip_reassemble(mp, ipf,
12515 			    (frag_offset_flags & IPH_OFFSET) << 3,
12516 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12517 		}
12518 		/* Update per ipfb and ill byte counts */
12519 		ipfb->ipfb_count += ipf->ipf_count;
12520 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12521 		ill->ill_frag_count += ipf->ipf_count;
12522 		/* If the frag timer wasn't already going, start it. */
12523 		mutex_enter(&ill->ill_lock);
12524 		ill_frag_timer_start(ill);
12525 		mutex_exit(&ill->ill_lock);
12526 		goto reass_done;
12527 	}
12528 
12529 	/*
12530 	 * If the packet's flag has changed (it could be coming up
12531 	 * from an interface different than the previous, therefore
12532 	 * possibly different checksum capability), then forget about
12533 	 * any stored checksum states.  Otherwise add the value to
12534 	 * the existing one stored in the fragment header.
12535 	 */
12536 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12537 		sum_val += ipf->ipf_checksum;
12538 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12539 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12540 		ipf->ipf_checksum = sum_val;
12541 	} else if (ipf->ipf_checksum_flags != 0) {
12542 		/* Forget checksum offload from now on */
12543 		ipf->ipf_checksum_flags = 0;
12544 	}
12545 
12546 	/*
12547 	 * We have a new piece of a datagram which is already being
12548 	 * reassembled.  Update the ECN info if all IP fragments
12549 	 * are ECN capable.  If there is one which is not, clear
12550 	 * all the info.  If there is at least one which has CE
12551 	 * code point, IP needs to report that up to transport.
12552 	 */
12553 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12554 		if (ecn_info == IPH_ECN_CE)
12555 			ipf->ipf_ecn = IPH_ECN_CE;
12556 	} else {
12557 		ipf->ipf_ecn = IPH_ECN_NECT;
12558 	}
12559 	if (offset && ipf->ipf_end == offset) {
12560 		/* The new fragment fits at the end */
12561 		ipf->ipf_tail_mp->b_cont = mp;
12562 		/* Update the byte count */
12563 		ipf->ipf_count += msg_len;
12564 		/* Update per ipfb and ill byte counts */
12565 		ipfb->ipfb_count += msg_len;
12566 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12567 		ill->ill_frag_count += msg_len;
12568 		if (frag_offset_flags & IPH_MF) {
12569 			/* More to come. */
12570 			ipf->ipf_end = end;
12571 			ipf->ipf_tail_mp = tail_mp;
12572 			goto reass_done;
12573 		}
12574 	} else {
12575 		/* Go do the hard cases. */
12576 		int ret;
12577 
12578 		if (offset == 0)
12579 			ipf->ipf_nf_hdr_len = hdr_length;
12580 
12581 		/* Save current byte count */
12582 		count = ipf->ipf_count;
12583 		ret = ip_reassemble(mp, ipf,
12584 		    (frag_offset_flags & IPH_OFFSET) << 3,
12585 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12586 		/* Count of bytes added and subtracted (freeb()ed) */
12587 		count = ipf->ipf_count - count;
12588 		if (count) {
12589 			/* Update per ipfb and ill byte counts */
12590 			ipfb->ipfb_count += count;
12591 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12592 			ill->ill_frag_count += count;
12593 		}
12594 		if (ret == IP_REASS_PARTIAL) {
12595 			goto reass_done;
12596 		} else if (ret == IP_REASS_FAILED) {
12597 			/* Reassembly failed. Free up all resources */
12598 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12599 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12600 				IP_REASS_SET_START(t_mp, 0);
12601 				IP_REASS_SET_END(t_mp, 0);
12602 			}
12603 			freemsg(mp);
12604 			goto reass_done;
12605 		}
12606 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12607 	}
12608 	/*
12609 	 * We have completed reassembly.  Unhook the frag header from
12610 	 * the reassembly list.
12611 	 *
12612 	 * Before we free the frag header, record the ECN info
12613 	 * to report back to the transport.
12614 	 */
12615 	ecn_info = ipf->ipf_ecn;
12616 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12617 	ipfp = ipf->ipf_ptphn;
12618 
12619 	/* We need to supply these to caller */
12620 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12621 		sum_val = ipf->ipf_checksum;
12622 	else
12623 		sum_val = 0;
12624 
12625 	mp1 = ipf->ipf_mp;
12626 	count = ipf->ipf_count;
12627 	ipf = ipf->ipf_hash_next;
12628 	if (ipf != NULL)
12629 		ipf->ipf_ptphn = ipfp;
12630 	ipfp[0] = ipf;
12631 	ill->ill_frag_count -= count;
12632 	ASSERT(ipfb->ipfb_count >= count);
12633 	ipfb->ipfb_count -= count;
12634 	ipfb->ipfb_frag_pkts--;
12635 	mutex_exit(&ipfb->ipfb_lock);
12636 	/* Ditch the frag header. */
12637 	mp = mp1->b_cont;
12638 
12639 	freeb(mp1);
12640 
12641 	/* Restore original IP length in header. */
12642 	packet_size = (uint32_t)msgdsize(mp);
12643 	if (packet_size > IP_MAXPACKET) {
12644 		freemsg(mp);
12645 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12646 		return (B_FALSE);
12647 	}
12648 
12649 	if (DB_REF(mp) > 1) {
12650 		mblk_t *mp2 = copymsg(mp);
12651 
12652 		freemsg(mp);
12653 		if (mp2 == NULL) {
12654 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12655 			return (B_FALSE);
12656 		}
12657 		mp = mp2;
12658 	}
12659 	ipha = (ipha_t *)mp->b_rptr;
12660 
12661 	ipha->ipha_length = htons((uint16_t)packet_size);
12662 	/* We're now complete, zip the frag state */
12663 	ipha->ipha_fragment_offset_and_flags = 0;
12664 	/* Record the ECN info. */
12665 	ipha->ipha_type_of_service &= 0xFC;
12666 	ipha->ipha_type_of_service |= ecn_info;
12667 	*mpp = mp;
12668 
12669 	/* Reassembly is successful; return checksum information if needed */
12670 	if (cksum_val != NULL)
12671 		*cksum_val = sum_val;
12672 	if (cksum_flags != NULL)
12673 		*cksum_flags = sum_flags;
12674 
12675 	return (B_TRUE);
12676 }
12677 
12678 /*
12679  * Perform ip header check sum update local options.
12680  * return B_TRUE if all is well, else return B_FALSE and release
12681  * the mp. caller is responsible for decrementing ire ref cnt.
12682  */
12683 static boolean_t
12684 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12685     ip_stack_t *ipst)
12686 {
12687 	mblk_t		*first_mp;
12688 	boolean_t	mctl_present;
12689 	uint16_t	sum;
12690 
12691 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12692 	/*
12693 	 * Don't do the checksum if it has gone through AH/ESP
12694 	 * processing.
12695 	 */
12696 	if (!mctl_present) {
12697 		sum = ip_csum_hdr(ipha);
12698 		if (sum != 0) {
12699 			if (ill != NULL) {
12700 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12701 			} else {
12702 				BUMP_MIB(&ipst->ips_ip_mib,
12703 				    ipIfStatsInCksumErrs);
12704 			}
12705 			freemsg(first_mp);
12706 			return (B_FALSE);
12707 		}
12708 	}
12709 
12710 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12711 		if (mctl_present)
12712 			freeb(first_mp);
12713 		return (B_FALSE);
12714 	}
12715 
12716 	return (B_TRUE);
12717 }
12718 
12719 /*
12720  * All udp packet are delivered to the local host via this routine.
12721  */
12722 void
12723 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12724     ill_t *recv_ill)
12725 {
12726 	uint32_t	sum;
12727 	uint32_t	u1;
12728 	boolean_t	mctl_present;
12729 	conn_t		*connp;
12730 	mblk_t		*first_mp;
12731 	uint16_t	*up;
12732 	ill_t		*ill = (ill_t *)q->q_ptr;
12733 	uint16_t	reass_hck_flags = 0;
12734 	ip_stack_t	*ipst;
12735 
12736 	ASSERT(recv_ill != NULL);
12737 	ipst = recv_ill->ill_ipst;
12738 
12739 #define	rptr    ((uchar_t *)ipha)
12740 
12741 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12742 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12743 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12744 	ASSERT(ill != NULL);
12745 
12746 	/*
12747 	 * FAST PATH for udp packets
12748 	 */
12749 
12750 	/* u1 is # words of IP options */
12751 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12752 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12753 
12754 	/* IP options present */
12755 	if (u1 != 0)
12756 		goto ipoptions;
12757 
12758 	/* Check the IP header checksum.  */
12759 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12760 		/* Clear the IP header h/w cksum flag */
12761 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12762 	} else if (!mctl_present) {
12763 		/*
12764 		 * Don't verify header checksum if this packet is coming
12765 		 * back from AH/ESP as we already did it.
12766 		 */
12767 #define	uph	((uint16_t *)ipha)
12768 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12769 		    uph[6] + uph[7] + uph[8] + uph[9];
12770 #undef	uph
12771 		/* finish doing IP checksum */
12772 		sum = (sum & 0xFFFF) + (sum >> 16);
12773 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12774 		if (sum != 0 && sum != 0xFFFF) {
12775 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12776 			freemsg(first_mp);
12777 			return;
12778 		}
12779 	}
12780 
12781 	/*
12782 	 * Count for SNMP of inbound packets for ire.
12783 	 * if mctl is present this might be a secure packet and
12784 	 * has already been counted for in ip_proto_input().
12785 	 */
12786 	if (!mctl_present) {
12787 		UPDATE_IB_PKT_COUNT(ire);
12788 		ire->ire_last_used_time = lbolt;
12789 	}
12790 
12791 	/* packet part of fragmented IP packet? */
12792 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12793 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12794 		goto fragmented;
12795 	}
12796 
12797 	/* u1 = IP header length (20 bytes) */
12798 	u1 = IP_SIMPLE_HDR_LENGTH;
12799 
12800 	/* packet does not contain complete IP & UDP headers */
12801 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12802 		goto udppullup;
12803 
12804 	/* up points to UDP header */
12805 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12806 #define	iphs    ((uint16_t *)ipha)
12807 
12808 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12809 	if (up[3] != 0) {
12810 		mblk_t *mp1 = mp->b_cont;
12811 		boolean_t cksum_err;
12812 		uint16_t hck_flags = 0;
12813 
12814 		/* Pseudo-header checksum */
12815 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12816 		    iphs[9] + up[2];
12817 
12818 		/*
12819 		 * Revert to software checksum calculation if the interface
12820 		 * isn't capable of checksum offload or if IPsec is present.
12821 		 */
12822 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12823 			hck_flags = DB_CKSUMFLAGS(mp);
12824 
12825 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12826 			IP_STAT(ipst, ip_in_sw_cksum);
12827 
12828 		IP_CKSUM_RECV(hck_flags, u1,
12829 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12830 		    (int32_t)((uchar_t *)up - rptr),
12831 		    mp, mp1, cksum_err);
12832 
12833 		if (cksum_err) {
12834 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12835 			if (hck_flags & HCK_FULLCKSUM)
12836 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12837 			else if (hck_flags & HCK_PARTIALCKSUM)
12838 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12839 			else
12840 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12841 
12842 			freemsg(first_mp);
12843 			return;
12844 		}
12845 	}
12846 
12847 	/* Non-fragmented broadcast or multicast packet? */
12848 	if (ire->ire_type == IRE_BROADCAST)
12849 		goto udpslowpath;
12850 
12851 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12852 	    ire->ire_zoneid, ipst)) != NULL) {
12853 		ASSERT(connp->conn_upq != NULL);
12854 		IP_STAT(ipst, ip_udp_fast_path);
12855 
12856 		if (CONN_UDP_FLOWCTLD(connp)) {
12857 			freemsg(mp);
12858 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12859 		} else {
12860 			if (!mctl_present) {
12861 				BUMP_MIB(ill->ill_ip_mib,
12862 				    ipIfStatsHCInDelivers);
12863 			}
12864 			/*
12865 			 * mp and first_mp can change.
12866 			 */
12867 			if (ip_udp_check(q, connp, recv_ill,
12868 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12869 				/* Send it upstream */
12870 				(connp->conn_recv)(connp, mp, NULL);
12871 			}
12872 		}
12873 		/*
12874 		 * freeb() cannot deal with null mblk being passed
12875 		 * in and first_mp can be set to null in the call
12876 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12877 		 */
12878 		if (mctl_present && first_mp != NULL) {
12879 			freeb(first_mp);
12880 		}
12881 		CONN_DEC_REF(connp);
12882 		return;
12883 	}
12884 
12885 	/*
12886 	 * if we got here we know the packet is not fragmented and
12887 	 * has no options. The classifier could not find a conn_t and
12888 	 * most likely its an icmp packet so send it through slow path.
12889 	 */
12890 
12891 	goto udpslowpath;
12892 
12893 ipoptions:
12894 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12895 		goto slow_done;
12896 	}
12897 
12898 	UPDATE_IB_PKT_COUNT(ire);
12899 	ire->ire_last_used_time = lbolt;
12900 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12901 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12902 fragmented:
12903 		/*
12904 		 * "sum" and "reass_hck_flags" are non-zero if the
12905 		 * reassembled packet has a valid hardware computed
12906 		 * checksum information associated with it.
12907 		 */
12908 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12909 			goto slow_done;
12910 		/*
12911 		 * Make sure that first_mp points back to mp as
12912 		 * the mp we came in with could have changed in
12913 		 * ip_rput_fragment().
12914 		 */
12915 		ASSERT(!mctl_present);
12916 		ipha = (ipha_t *)mp->b_rptr;
12917 		first_mp = mp;
12918 	}
12919 
12920 	/* Now we have a complete datagram, destined for this machine. */
12921 	u1 = IPH_HDR_LENGTH(ipha);
12922 	/* Pull up the UDP header, if necessary. */
12923 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12924 udppullup:
12925 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12926 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12927 			freemsg(first_mp);
12928 			goto slow_done;
12929 		}
12930 		ipha = (ipha_t *)mp->b_rptr;
12931 	}
12932 
12933 	/*
12934 	 * Validate the checksum for the reassembled packet; for the
12935 	 * pullup case we calculate the payload checksum in software.
12936 	 */
12937 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12938 	if (up[3] != 0) {
12939 		boolean_t cksum_err;
12940 
12941 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12942 			IP_STAT(ipst, ip_in_sw_cksum);
12943 
12944 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12945 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12946 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12947 		    iphs[9] + up[2], sum, cksum_err);
12948 
12949 		if (cksum_err) {
12950 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12951 
12952 			if (reass_hck_flags & HCK_FULLCKSUM)
12953 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12954 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12955 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12956 			else
12957 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12958 
12959 			freemsg(first_mp);
12960 			goto slow_done;
12961 		}
12962 	}
12963 udpslowpath:
12964 
12965 	/* Clear hardware checksum flag to be safe */
12966 	DB_CKSUMFLAGS(mp) = 0;
12967 
12968 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12969 	    (ire->ire_type == IRE_BROADCAST),
12970 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12971 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12972 
12973 slow_done:
12974 	IP_STAT(ipst, ip_udp_slow_path);
12975 	return;
12976 
12977 #undef  iphs
12978 #undef  rptr
12979 }
12980 
12981 /* ARGSUSED */
12982 static mblk_t *
12983 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12984     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12985     ill_rx_ring_t *ill_ring)
12986 {
12987 	conn_t		*connp;
12988 	uint32_t	sum;
12989 	uint32_t	u1;
12990 	uint16_t	*up;
12991 	int		offset;
12992 	ssize_t		len;
12993 	mblk_t		*mp1;
12994 	boolean_t	syn_present = B_FALSE;
12995 	tcph_t		*tcph;
12996 	uint_t		ip_hdr_len;
12997 	ill_t		*ill = (ill_t *)q->q_ptr;
12998 	zoneid_t	zoneid = ire->ire_zoneid;
12999 	boolean_t	cksum_err;
13000 	uint16_t	hck_flags = 0;
13001 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13002 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13003 
13004 #define	rptr	((uchar_t *)ipha)
13005 
13006 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13007 	ASSERT(ill != NULL);
13008 
13009 	/*
13010 	 * FAST PATH for tcp packets
13011 	 */
13012 
13013 	/* u1 is # words of IP options */
13014 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13015 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13016 
13017 	/* IP options present */
13018 	if (u1) {
13019 		goto ipoptions;
13020 	} else if (!mctl_present) {
13021 		/* Check the IP header checksum.  */
13022 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13023 			/* Clear the IP header h/w cksum flag */
13024 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13025 		} else if (!mctl_present) {
13026 			/*
13027 			 * Don't verify header checksum if this packet
13028 			 * is coming back from AH/ESP as we already did it.
13029 			 */
13030 #define	uph	((uint16_t *)ipha)
13031 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13032 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13033 #undef	uph
13034 			/* finish doing IP checksum */
13035 			sum = (sum & 0xFFFF) + (sum >> 16);
13036 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13037 			if (sum != 0 && sum != 0xFFFF) {
13038 				BUMP_MIB(ill->ill_ip_mib,
13039 				    ipIfStatsInCksumErrs);
13040 				goto error;
13041 			}
13042 		}
13043 	}
13044 
13045 	if (!mctl_present) {
13046 		UPDATE_IB_PKT_COUNT(ire);
13047 		ire->ire_last_used_time = lbolt;
13048 	}
13049 
13050 	/* packet part of fragmented IP packet? */
13051 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13052 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13053 		goto fragmented;
13054 	}
13055 
13056 	/* u1 = IP header length (20 bytes) */
13057 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13058 
13059 	/* does packet contain IP+TCP headers? */
13060 	len = mp->b_wptr - rptr;
13061 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13062 		IP_STAT(ipst, ip_tcppullup);
13063 		goto tcppullup;
13064 	}
13065 
13066 	/* TCP options present? */
13067 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13068 
13069 	/*
13070 	 * If options need to be pulled up, then goto tcpoptions.
13071 	 * otherwise we are still in the fast path
13072 	 */
13073 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13074 		IP_STAT(ipst, ip_tcpoptions);
13075 		goto tcpoptions;
13076 	}
13077 
13078 	/* multiple mblks of tcp data? */
13079 	if ((mp1 = mp->b_cont) != NULL) {
13080 		/* more then two? */
13081 		if (mp1->b_cont != NULL) {
13082 			IP_STAT(ipst, ip_multipkttcp);
13083 			goto multipkttcp;
13084 		}
13085 		len += mp1->b_wptr - mp1->b_rptr;
13086 	}
13087 
13088 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13089 
13090 	/* part of pseudo checksum */
13091 
13092 	/* TCP datagram length */
13093 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13094 
13095 #define	iphs    ((uint16_t *)ipha)
13096 
13097 #ifdef	_BIG_ENDIAN
13098 	u1 += IPPROTO_TCP;
13099 #else
13100 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13101 #endif
13102 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13103 
13104 	/*
13105 	 * Revert to software checksum calculation if the interface
13106 	 * isn't capable of checksum offload or if IPsec is present.
13107 	 */
13108 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13109 		hck_flags = DB_CKSUMFLAGS(mp);
13110 
13111 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13112 		IP_STAT(ipst, ip_in_sw_cksum);
13113 
13114 	IP_CKSUM_RECV(hck_flags, u1,
13115 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13116 	    (int32_t)((uchar_t *)up - rptr),
13117 	    mp, mp1, cksum_err);
13118 
13119 	if (cksum_err) {
13120 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13121 
13122 		if (hck_flags & HCK_FULLCKSUM)
13123 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13124 		else if (hck_flags & HCK_PARTIALCKSUM)
13125 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13126 		else
13127 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13128 
13129 		goto error;
13130 	}
13131 
13132 try_again:
13133 
13134 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13135 	    zoneid, ipst)) == NULL) {
13136 		/* Send the TH_RST */
13137 		goto no_conn;
13138 	}
13139 
13140 	/*
13141 	 * TCP FAST PATH for AF_INET socket.
13142 	 *
13143 	 * TCP fast path to avoid extra work. An AF_INET socket type
13144 	 * does not have facility to receive extra information via
13145 	 * ip_process or ip_add_info. Also, when the connection was
13146 	 * established, we made a check if this connection is impacted
13147 	 * by any global IPsec policy or per connection policy (a
13148 	 * policy that comes in effect later will not apply to this
13149 	 * connection). Since all this can be determined at the
13150 	 * connection establishment time, a quick check of flags
13151 	 * can avoid extra work.
13152 	 */
13153 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13154 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13155 		ASSERT(first_mp == mp);
13156 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13157 		SET_SQUEUE(mp, tcp_rput_data, connp);
13158 		return (mp);
13159 	}
13160 
13161 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13162 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13163 		if (IPCL_IS_TCP(connp)) {
13164 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13165 			DB_CKSUMSTART(mp) =
13166 			    (intptr_t)ip_squeue_get(ill_ring);
13167 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13168 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13169 				BUMP_MIB(ill->ill_ip_mib,
13170 				    ipIfStatsHCInDelivers);
13171 				SET_SQUEUE(mp, connp->conn_recv, connp);
13172 				return (mp);
13173 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13174 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13175 				BUMP_MIB(ill->ill_ip_mib,
13176 				    ipIfStatsHCInDelivers);
13177 				ip_squeue_enter_unbound++;
13178 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13179 				    connp);
13180 				return (mp);
13181 			}
13182 			syn_present = B_TRUE;
13183 		}
13184 
13185 	}
13186 
13187 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13188 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13189 
13190 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13191 		/* No need to send this packet to TCP */
13192 		if ((flags & TH_RST) || (flags & TH_URG)) {
13193 			CONN_DEC_REF(connp);
13194 			freemsg(first_mp);
13195 			return (NULL);
13196 		}
13197 		if (flags & TH_ACK) {
13198 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13199 			    ipst->ips_netstack->netstack_tcp, connp);
13200 			CONN_DEC_REF(connp);
13201 			return (NULL);
13202 		}
13203 
13204 		CONN_DEC_REF(connp);
13205 		freemsg(first_mp);
13206 		return (NULL);
13207 	}
13208 
13209 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13210 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13211 		    ipha, NULL, mctl_present);
13212 		if (first_mp == NULL) {
13213 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13214 			CONN_DEC_REF(connp);
13215 			return (NULL);
13216 		}
13217 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13218 			ASSERT(syn_present);
13219 			if (mctl_present) {
13220 				ASSERT(first_mp != mp);
13221 				first_mp->b_datap->db_struioflag |=
13222 				    STRUIO_POLICY;
13223 			} else {
13224 				ASSERT(first_mp == mp);
13225 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13226 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13227 			}
13228 		} else {
13229 			/*
13230 			 * Discard first_mp early since we're dealing with a
13231 			 * fully-connected conn_t and tcp doesn't do policy in
13232 			 * this case.
13233 			 */
13234 			if (mctl_present) {
13235 				freeb(first_mp);
13236 				mctl_present = B_FALSE;
13237 			}
13238 			first_mp = mp;
13239 		}
13240 	}
13241 
13242 	/* Initiate IPPF processing for fastpath */
13243 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13244 		uint32_t	ill_index;
13245 
13246 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13247 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13248 		if (mp == NULL) {
13249 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13250 			    "deferred/dropped during IPPF processing\n"));
13251 			CONN_DEC_REF(connp);
13252 			if (mctl_present)
13253 				freeb(first_mp);
13254 			return (NULL);
13255 		} else if (mctl_present) {
13256 			/*
13257 			 * ip_process might return a new mp.
13258 			 */
13259 			ASSERT(first_mp != mp);
13260 			first_mp->b_cont = mp;
13261 		} else {
13262 			first_mp = mp;
13263 		}
13264 
13265 	}
13266 
13267 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13268 		/*
13269 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13270 		 * make sure IPF_RECVIF is passed to ip_add_info.
13271 		 */
13272 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13273 		    IPCL_ZONEID(connp), ipst);
13274 		if (mp == NULL) {
13275 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13276 			CONN_DEC_REF(connp);
13277 			if (mctl_present)
13278 				freeb(first_mp);
13279 			return (NULL);
13280 		} else if (mctl_present) {
13281 			/*
13282 			 * ip_add_info might return a new mp.
13283 			 */
13284 			ASSERT(first_mp != mp);
13285 			first_mp->b_cont = mp;
13286 		} else {
13287 			first_mp = mp;
13288 		}
13289 	}
13290 
13291 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13292 	if (IPCL_IS_TCP(connp)) {
13293 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13294 		return (first_mp);
13295 	} else {
13296 		/* SOCK_RAW, IPPROTO_TCP case */
13297 		(connp->conn_recv)(connp, first_mp, NULL);
13298 		CONN_DEC_REF(connp);
13299 		return (NULL);
13300 	}
13301 
13302 no_conn:
13303 	/* Initiate IPPf processing, if needed. */
13304 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13305 		uint32_t ill_index;
13306 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13307 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13308 		if (first_mp == NULL) {
13309 			return (NULL);
13310 		}
13311 	}
13312 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13313 
13314 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13315 	    ipst->ips_netstack->netstack_tcp, NULL);
13316 	return (NULL);
13317 ipoptions:
13318 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13319 		goto slow_done;
13320 	}
13321 
13322 	UPDATE_IB_PKT_COUNT(ire);
13323 	ire->ire_last_used_time = lbolt;
13324 
13325 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13326 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13327 fragmented:
13328 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13329 			if (mctl_present)
13330 				freeb(first_mp);
13331 			goto slow_done;
13332 		}
13333 		/*
13334 		 * Make sure that first_mp points back to mp as
13335 		 * the mp we came in with could have changed in
13336 		 * ip_rput_fragment().
13337 		 */
13338 		ASSERT(!mctl_present);
13339 		ipha = (ipha_t *)mp->b_rptr;
13340 		first_mp = mp;
13341 	}
13342 
13343 	/* Now we have a complete datagram, destined for this machine. */
13344 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13345 
13346 	len = mp->b_wptr - mp->b_rptr;
13347 	/* Pull up a minimal TCP header, if necessary. */
13348 	if (len < (u1 + 20)) {
13349 tcppullup:
13350 		if (!pullupmsg(mp, u1 + 20)) {
13351 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13352 			goto error;
13353 		}
13354 		ipha = (ipha_t *)mp->b_rptr;
13355 		len = mp->b_wptr - mp->b_rptr;
13356 	}
13357 
13358 	/*
13359 	 * Extract the offset field from the TCP header.  As usual, we
13360 	 * try to help the compiler more than the reader.
13361 	 */
13362 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13363 	if (offset != 5) {
13364 tcpoptions:
13365 		if (offset < 5) {
13366 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13367 			goto error;
13368 		}
13369 		/*
13370 		 * There must be TCP options.
13371 		 * Make sure we can grab them.
13372 		 */
13373 		offset <<= 2;
13374 		offset += u1;
13375 		if (len < offset) {
13376 			if (!pullupmsg(mp, offset)) {
13377 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13378 				goto error;
13379 			}
13380 			ipha = (ipha_t *)mp->b_rptr;
13381 			len = mp->b_wptr - rptr;
13382 		}
13383 	}
13384 
13385 	/* Get the total packet length in len, including headers. */
13386 	if (mp->b_cont) {
13387 multipkttcp:
13388 		len = msgdsize(mp);
13389 	}
13390 
13391 	/*
13392 	 * Check the TCP checksum by pulling together the pseudo-
13393 	 * header checksum, and passing it to ip_csum to be added in
13394 	 * with the TCP datagram.
13395 	 *
13396 	 * Since we are not using the hwcksum if available we must
13397 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13398 	 * If either of these fails along the way the mblk is freed.
13399 	 * If this logic ever changes and mblk is reused to say send
13400 	 * ICMP's back, then this flag may need to be cleared in
13401 	 * other places as well.
13402 	 */
13403 	DB_CKSUMFLAGS(mp) = 0;
13404 
13405 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13406 
13407 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13408 #ifdef	_BIG_ENDIAN
13409 	u1 += IPPROTO_TCP;
13410 #else
13411 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13412 #endif
13413 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13414 	/*
13415 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13416 	 */
13417 	IP_STAT(ipst, ip_in_sw_cksum);
13418 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13419 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13420 		goto error;
13421 	}
13422 
13423 	IP_STAT(ipst, ip_tcp_slow_path);
13424 	goto try_again;
13425 #undef  iphs
13426 #undef  rptr
13427 
13428 error:
13429 	freemsg(first_mp);
13430 slow_done:
13431 	return (NULL);
13432 }
13433 
13434 /* ARGSUSED */
13435 static void
13436 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13437     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13438 {
13439 	conn_t		*connp;
13440 	uint32_t	sum;
13441 	uint32_t	u1;
13442 	ssize_t		len;
13443 	sctp_hdr_t	*sctph;
13444 	zoneid_t	zoneid = ire->ire_zoneid;
13445 	uint32_t	pktsum;
13446 	uint32_t	calcsum;
13447 	uint32_t	ports;
13448 	in6_addr_t	map_src, map_dst;
13449 	ill_t		*ill = (ill_t *)q->q_ptr;
13450 	ip_stack_t	*ipst;
13451 	sctp_stack_t	*sctps;
13452 	boolean_t	sctp_csum_err = B_FALSE;
13453 
13454 	ASSERT(recv_ill != NULL);
13455 	ipst = recv_ill->ill_ipst;
13456 	sctps = ipst->ips_netstack->netstack_sctp;
13457 
13458 #define	rptr	((uchar_t *)ipha)
13459 
13460 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13461 	ASSERT(ill != NULL);
13462 
13463 	/* u1 is # words of IP options */
13464 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13465 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13466 
13467 	/* IP options present */
13468 	if (u1 > 0) {
13469 		goto ipoptions;
13470 	} else {
13471 		/* Check the IP header checksum.  */
13472 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13473 		    !mctl_present) {
13474 #define	uph	((uint16_t *)ipha)
13475 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13476 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13477 #undef	uph
13478 			/* finish doing IP checksum */
13479 			sum = (sum & 0xFFFF) + (sum >> 16);
13480 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13481 			/*
13482 			 * Don't verify header checksum if this packet
13483 			 * is coming back from AH/ESP as we already did it.
13484 			 */
13485 			if (sum != 0 && sum != 0xFFFF) {
13486 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13487 				goto error;
13488 			}
13489 		}
13490 		/*
13491 		 * Since there is no SCTP h/w cksum support yet, just
13492 		 * clear the flag.
13493 		 */
13494 		DB_CKSUMFLAGS(mp) = 0;
13495 	}
13496 
13497 	/*
13498 	 * Don't verify header checksum if this packet is coming
13499 	 * back from AH/ESP as we already did it.
13500 	 */
13501 	if (!mctl_present) {
13502 		UPDATE_IB_PKT_COUNT(ire);
13503 		ire->ire_last_used_time = lbolt;
13504 	}
13505 
13506 	/* packet part of fragmented IP packet? */
13507 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13508 	if (u1 & (IPH_MF | IPH_OFFSET))
13509 		goto fragmented;
13510 
13511 	/* u1 = IP header length (20 bytes) */
13512 	u1 = IP_SIMPLE_HDR_LENGTH;
13513 
13514 find_sctp_client:
13515 	/* Pullup if we don't have the sctp common header. */
13516 	len = MBLKL(mp);
13517 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13518 		if (mp->b_cont == NULL ||
13519 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13520 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13521 			goto error;
13522 		}
13523 		ipha = (ipha_t *)mp->b_rptr;
13524 		len = MBLKL(mp);
13525 	}
13526 
13527 	sctph = (sctp_hdr_t *)(rptr + u1);
13528 #ifdef	DEBUG
13529 	if (!skip_sctp_cksum) {
13530 #endif
13531 		pktsum = sctph->sh_chksum;
13532 		sctph->sh_chksum = 0;
13533 		calcsum = sctp_cksum(mp, u1);
13534 		sctph->sh_chksum = pktsum;
13535 		if (calcsum != pktsum)
13536 			sctp_csum_err = B_TRUE;
13537 #ifdef	DEBUG	/* skip_sctp_cksum */
13538 	}
13539 #endif
13540 	/* get the ports */
13541 	ports = *(uint32_t *)&sctph->sh_sport;
13542 
13543 	IRE_REFRELE(ire);
13544 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13545 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13546 	if (sctp_csum_err) {
13547 		/*
13548 		 * No potential sctp checksum errors go to the Sun
13549 		 * sctp stack however they might be Adler-32 summed
13550 		 * packets a userland stack bound to a raw IP socket
13551 		 * could reasonably use. Note though that Adler-32 is
13552 		 * a long deprecated algorithm and customer sctp
13553 		 * networks should eventually migrate to CRC-32 at
13554 		 * which time this facility should be removed.
13555 		 */
13556 		flags |= IP_FF_SCTP_CSUM_ERR;
13557 		goto no_conn;
13558 	}
13559 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13560 	    sctps)) == NULL) {
13561 		/* Check for raw socket or OOTB handling */
13562 		goto no_conn;
13563 	}
13564 
13565 	/* Found a client; up it goes */
13566 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13567 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13568 	return;
13569 
13570 no_conn:
13571 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13572 	    ports, mctl_present, flags, B_TRUE, zoneid);
13573 	return;
13574 
13575 ipoptions:
13576 	DB_CKSUMFLAGS(mp) = 0;
13577 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13578 		goto slow_done;
13579 
13580 	UPDATE_IB_PKT_COUNT(ire);
13581 	ire->ire_last_used_time = lbolt;
13582 
13583 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13584 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13585 fragmented:
13586 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13587 			goto slow_done;
13588 		/*
13589 		 * Make sure that first_mp points back to mp as
13590 		 * the mp we came in with could have changed in
13591 		 * ip_rput_fragment().
13592 		 */
13593 		ASSERT(!mctl_present);
13594 		ipha = (ipha_t *)mp->b_rptr;
13595 		first_mp = mp;
13596 	}
13597 
13598 	/* Now we have a complete datagram, destined for this machine. */
13599 	u1 = IPH_HDR_LENGTH(ipha);
13600 	goto find_sctp_client;
13601 #undef  iphs
13602 #undef  rptr
13603 
13604 error:
13605 	freemsg(first_mp);
13606 slow_done:
13607 	IRE_REFRELE(ire);
13608 }
13609 
13610 #define	VER_BITS	0xF0
13611 #define	VERSION_6	0x60
13612 
13613 static boolean_t
13614 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13615     ipaddr_t *dstp, ip_stack_t *ipst)
13616 {
13617 	uint_t	opt_len;
13618 	ipha_t *ipha;
13619 	ssize_t len;
13620 	uint_t	pkt_len;
13621 
13622 	ASSERT(ill != NULL);
13623 	IP_STAT(ipst, ip_ipoptions);
13624 	ipha = *iphapp;
13625 
13626 #define	rptr    ((uchar_t *)ipha)
13627 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13628 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13629 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13630 		freemsg(mp);
13631 		return (B_FALSE);
13632 	}
13633 
13634 	/* multiple mblk or too short */
13635 	pkt_len = ntohs(ipha->ipha_length);
13636 
13637 	/* Get the number of words of IP options in the IP header. */
13638 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13639 	if (opt_len) {
13640 		/* IP Options present!  Validate and process. */
13641 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13642 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13643 			goto done;
13644 		}
13645 		/*
13646 		 * Recompute complete header length and make sure we
13647 		 * have access to all of it.
13648 		 */
13649 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13650 		if (len > (mp->b_wptr - rptr)) {
13651 			if (len > pkt_len) {
13652 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13653 				goto done;
13654 			}
13655 			if (!pullupmsg(mp, len)) {
13656 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13657 				goto done;
13658 			}
13659 			ipha = (ipha_t *)mp->b_rptr;
13660 		}
13661 		/*
13662 		 * Go off to ip_rput_options which returns the next hop
13663 		 * destination address, which may have been affected
13664 		 * by source routing.
13665 		 */
13666 		IP_STAT(ipst, ip_opt);
13667 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13668 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13669 			return (B_FALSE);
13670 		}
13671 	}
13672 	*iphapp = ipha;
13673 	return (B_TRUE);
13674 done:
13675 	/* clear b_prev - used by ip_mroute_decap */
13676 	mp->b_prev = NULL;
13677 	freemsg(mp);
13678 	return (B_FALSE);
13679 #undef  rptr
13680 }
13681 
13682 /*
13683  * Deal with the fact that there is no ire for the destination.
13684  */
13685 static ire_t *
13686 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13687 {
13688 	ipha_t	*ipha;
13689 	ill_t	*ill;
13690 	ire_t	*ire;
13691 	boolean_t	check_multirt = B_FALSE;
13692 	ip_stack_t *ipst;
13693 
13694 	ipha = (ipha_t *)mp->b_rptr;
13695 	ill = (ill_t *)q->q_ptr;
13696 
13697 	ASSERT(ill != NULL);
13698 	ipst = ill->ill_ipst;
13699 
13700 	/*
13701 	 * No IRE for this destination, so it can't be for us.
13702 	 * Unless we are forwarding, drop the packet.
13703 	 * We have to let source routed packets through
13704 	 * since we don't yet know if they are 'ping -l'
13705 	 * packets i.e. if they will go out over the
13706 	 * same interface as they came in on.
13707 	 */
13708 	if (ll_multicast) {
13709 		freemsg(mp);
13710 		return (NULL);
13711 	}
13712 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13713 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13714 		freemsg(mp);
13715 		return (NULL);
13716 	}
13717 
13718 	/*
13719 	 * Mark this packet as having originated externally.
13720 	 *
13721 	 * For non-forwarding code path, ire_send later double
13722 	 * checks this interface to see if it is still exists
13723 	 * post-ARP resolution.
13724 	 *
13725 	 * Also, IPQOS uses this to differentiate between
13726 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13727 	 * QOS packet processing in ip_wput_attach_llhdr().
13728 	 * The QoS module can mark the b_band for a fastpath message
13729 	 * or the dl_priority field in a unitdata_req header for
13730 	 * CoS marking. This info can only be found in
13731 	 * ip_wput_attach_llhdr().
13732 	 */
13733 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13734 	/*
13735 	 * Clear the indication that this may have a hardware checksum
13736 	 * as we are not using it
13737 	 */
13738 	DB_CKSUMFLAGS(mp) = 0;
13739 
13740 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13741 	    MBLK_GETLABEL(mp), ipst);
13742 
13743 	if (ire == NULL && check_multirt) {
13744 		/* Let ip_newroute handle CGTP  */
13745 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13746 		return (NULL);
13747 	}
13748 
13749 	if (ire != NULL)
13750 		return (ire);
13751 
13752 	mp->b_prev = mp->b_next = 0;
13753 	/* send icmp unreachable */
13754 	q = WR(q);
13755 	/* Sent by forwarding path, and router is global zone */
13756 	if (ip_source_routed(ipha, ipst)) {
13757 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13758 		    GLOBAL_ZONEID, ipst);
13759 	} else {
13760 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13761 		    ipst);
13762 	}
13763 
13764 	return (NULL);
13765 
13766 }
13767 
13768 /*
13769  * check ip header length and align it.
13770  */
13771 static boolean_t
13772 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13773 {
13774 	ssize_t len;
13775 	ill_t *ill;
13776 	ipha_t	*ipha;
13777 
13778 	len = MBLKL(mp);
13779 
13780 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13781 		ill = (ill_t *)q->q_ptr;
13782 
13783 		if (!OK_32PTR(mp->b_rptr))
13784 			IP_STAT(ipst, ip_notaligned1);
13785 		else
13786 			IP_STAT(ipst, ip_notaligned2);
13787 		/* Guard against bogus device drivers */
13788 		if (len < 0) {
13789 			/* clear b_prev - used by ip_mroute_decap */
13790 			mp->b_prev = NULL;
13791 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13792 			freemsg(mp);
13793 			return (B_FALSE);
13794 		}
13795 
13796 		if (ip_rput_pullups++ == 0) {
13797 			ipha = (ipha_t *)mp->b_rptr;
13798 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13799 			    "ip_check_and_align_header: %s forced us to "
13800 			    " pullup pkt, hdr len %ld, hdr addr %p",
13801 			    ill->ill_name, len, ipha);
13802 		}
13803 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13804 			/* clear b_prev - used by ip_mroute_decap */
13805 			mp->b_prev = NULL;
13806 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13807 			freemsg(mp);
13808 			return (B_FALSE);
13809 		}
13810 	}
13811 	return (B_TRUE);
13812 }
13813 
13814 ire_t *
13815 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13816 {
13817 	ire_t		*new_ire;
13818 	ill_t		*ire_ill;
13819 	uint_t		ifindex;
13820 	ip_stack_t	*ipst = ill->ill_ipst;
13821 	boolean_t	strict_check = B_FALSE;
13822 
13823 	/*
13824 	 * This packet came in on an interface other than the one associated
13825 	 * with the first ire we found for the destination address. We do
13826 	 * another ire lookup here, using the ingress ill, to see if the
13827 	 * interface is in an interface group.
13828 	 * As long as the ills belong to the same group, we don't consider
13829 	 * them to be arriving on the wrong interface. Thus, if the switch
13830 	 * is doing inbound load spreading, we won't drop packets when the
13831 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13832 	 * for 'usesrc groups' where the destination address may belong to
13833 	 * another interface to allow multipathing to happen.
13834 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13835 	 * where the local address may not be unique. In this case we were
13836 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13837 	 * actually returned. The new lookup, which is more specific, should
13838 	 * only find the IRE_LOCAL associated with the ingress ill if one
13839 	 * exists.
13840 	 */
13841 
13842 	if (ire->ire_ipversion == IPV4_VERSION) {
13843 		if (ipst->ips_ip_strict_dst_multihoming)
13844 			strict_check = B_TRUE;
13845 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13846 		    ill->ill_ipif, ALL_ZONES, NULL,
13847 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13848 	} else {
13849 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13850 		if (ipst->ips_ipv6_strict_dst_multihoming)
13851 			strict_check = B_TRUE;
13852 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13853 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13854 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13855 	}
13856 	/*
13857 	 * If the same ire that was returned in ip_input() is found then this
13858 	 * is an indication that interface groups are in use. The packet
13859 	 * arrived on a different ill in the group than the one associated with
13860 	 * the destination address.  If a different ire was found then the same
13861 	 * IP address must be hosted on multiple ills. This is possible with
13862 	 * unnumbered point2point interfaces. We switch to use this new ire in
13863 	 * order to have accurate interface statistics.
13864 	 */
13865 	if (new_ire != NULL) {
13866 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13867 			ire_refrele(ire);
13868 			ire = new_ire;
13869 		} else {
13870 			ire_refrele(new_ire);
13871 		}
13872 		return (ire);
13873 	} else if ((ire->ire_rfq == NULL) &&
13874 	    (ire->ire_ipversion == IPV4_VERSION)) {
13875 		/*
13876 		 * The best match could have been the original ire which
13877 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13878 		 * the strict multihoming checks are irrelevant as we consider
13879 		 * local addresses hosted on lo0 to be interface agnostic. We
13880 		 * only expect a null ire_rfq on IREs which are associated with
13881 		 * lo0 hence we can return now.
13882 		 */
13883 		return (ire);
13884 	}
13885 
13886 	/*
13887 	 * Chase pointers once and store locally.
13888 	 */
13889 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13890 	    (ill_t *)(ire->ire_rfq->q_ptr);
13891 	ifindex = ill->ill_usesrc_ifindex;
13892 
13893 	/*
13894 	 * Check if it's a legal address on the 'usesrc' interface.
13895 	 */
13896 	if ((ifindex != 0) && (ire_ill != NULL) &&
13897 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13898 		return (ire);
13899 	}
13900 
13901 	/*
13902 	 * If the ip*_strict_dst_multihoming switch is on then we can
13903 	 * only accept this packet if the interface is marked as routing.
13904 	 */
13905 	if (!(strict_check))
13906 		return (ire);
13907 
13908 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13909 	    ILLF_ROUTER) != 0) {
13910 		return (ire);
13911 	}
13912 
13913 	ire_refrele(ire);
13914 	return (NULL);
13915 }
13916 
13917 ire_t *
13918 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13919 {
13920 	ipha_t	*ipha;
13921 	ire_t	*src_ire;
13922 	ill_t	*stq_ill;
13923 	uint_t	hlen;
13924 	uint_t	pkt_len;
13925 	uint32_t sum;
13926 	queue_t	*dev_q;
13927 	ip_stack_t *ipst = ill->ill_ipst;
13928 	mblk_t *fpmp;
13929 
13930 	ipha = (ipha_t *)mp->b_rptr;
13931 
13932 	/*
13933 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13934 	 * The loopback address check for both src and dst has already
13935 	 * been checked in ip_input
13936 	 */
13937 
13938 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13939 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13940 		goto drop;
13941 	}
13942 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13943 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13944 
13945 	if (src_ire != NULL) {
13946 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13947 		ire_refrele(src_ire);
13948 		goto drop;
13949 	}
13950 
13951 
13952 	/* No ire cache of nexthop. So first create one  */
13953 	if (ire == NULL) {
13954 		boolean_t check_multirt;
13955 
13956 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13957 		/*
13958 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13959 		 * is not set. So upon return from ire_forward
13960 		 * check_multirt should remain as false.
13961 		 */
13962 		if (ire == NULL) {
13963 			/* An attempt was made to forward the packet */
13964 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13965 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13966 			mp->b_prev = mp->b_next = 0;
13967 			/* send icmp unreachable */
13968 			/* Sent by forwarding path, and router is global zone */
13969 			if (ip_source_routed(ipha, ipst)) {
13970 				icmp_unreachable(ill->ill_wq, mp,
13971 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13972 				    ipst);
13973 			} else {
13974 				icmp_unreachable(ill->ill_wq, mp,
13975 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13976 				    ipst);
13977 			}
13978 			return (ire);
13979 		}
13980 	}
13981 
13982 	/*
13983 	 * Forwarding fastpath exception case:
13984 	 * If either of the follwoing case is true, we take
13985 	 * the slowpath
13986 	 *	o forwarding is not enabled
13987 	 *	o incoming and outgoing interface are the same, or the same
13988 	 *	  IPMP group
13989 	 *	o corresponding ire is in incomplete state
13990 	 *	o packet needs fragmentation
13991 	 *	o ARP cache is not resolved
13992 	 *
13993 	 * The codeflow from here on is thus:
13994 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13995 	 */
13996 	pkt_len = ntohs(ipha->ipha_length);
13997 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13998 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13999 	    !(ill->ill_flags & ILLF_ROUTER) ||
14000 	    (ill == stq_ill) ||
14001 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14002 	    (ire->ire_nce == NULL) ||
14003 	    (pkt_len > ire->ire_max_frag) ||
14004 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14005 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14006 	    ipha->ipha_ttl <= 1) {
14007 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14008 		    ipha, ill, B_FALSE);
14009 		return (ire);
14010 	}
14011 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14012 
14013 	DTRACE_PROBE4(ip4__forwarding__start,
14014 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14015 
14016 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14017 	    ipst->ips_ipv4firewall_forwarding,
14018 	    ill, stq_ill, ipha, mp, mp, ipst);
14019 
14020 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14021 
14022 	if (mp == NULL)
14023 		goto drop;
14024 
14025 	mp->b_datap->db_struioun.cksum.flags = 0;
14026 	/* Adjust the checksum to reflect the ttl decrement. */
14027 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14028 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14029 	ipha->ipha_ttl--;
14030 
14031 	/*
14032 	 * Write the link layer header.  We can do this safely here,
14033 	 * because we have already tested to make sure that the IP
14034 	 * policy is not set, and that we have a fast path destination
14035 	 * header.
14036 	 */
14037 	mp->b_rptr -= hlen;
14038 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14039 
14040 	UPDATE_IB_PKT_COUNT(ire);
14041 	ire->ire_last_used_time = lbolt;
14042 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14043 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14044 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14045 
14046 	dev_q = ire->ire_stq->q_next;
14047 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14048 	    !canputnext(ire->ire_stq)) {
14049 		goto indiscard;
14050 	}
14051 	if (ILL_DLS_CAPABLE(stq_ill)) {
14052 		/*
14053 		 * Send the packet directly to DLD, where it
14054 		 * may be queued depending on the availability
14055 		 * of transmit resources at the media layer.
14056 		 */
14057 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14058 	} else {
14059 		DTRACE_PROBE4(ip4__physical__out__start,
14060 		    ill_t *, NULL, ill_t *, stq_ill,
14061 		    ipha_t *, ipha, mblk_t *, mp);
14062 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14063 		    ipst->ips_ipv4firewall_physical_out,
14064 		    NULL, stq_ill, ipha, mp, mp, ipst);
14065 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14066 		if (mp == NULL)
14067 			goto drop;
14068 		putnext(ire->ire_stq, mp);
14069 	}
14070 	return (ire);
14071 
14072 indiscard:
14073 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14074 drop:
14075 	if (mp != NULL)
14076 		freemsg(mp);
14077 	return (ire);
14078 
14079 }
14080 
14081 /*
14082  * This function is called in the forwarding slowpath, when
14083  * either the ire lacks the link-layer address, or the packet needs
14084  * further processing(eg. fragmentation), before transmission.
14085  */
14086 
14087 static void
14088 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14089     ill_t *ill, boolean_t ll_multicast)
14090 {
14091 	ill_group_t	*ill_group;
14092 	ill_group_t	*ire_group;
14093 	queue_t		*dev_q;
14094 	ire_t		*src_ire;
14095 	ip_stack_t	*ipst = ill->ill_ipst;
14096 
14097 	ASSERT(ire->ire_stq != NULL);
14098 
14099 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14100 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14101 
14102 	if (ll_multicast != 0) {
14103 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14104 		goto drop_pkt;
14105 	}
14106 
14107 	/*
14108 	 * check if ipha_src is a broadcast address. Note that this
14109 	 * check is redundant when we get here from ip_fast_forward()
14110 	 * which has already done this check. However, since we can
14111 	 * also get here from ip_rput_process_broadcast() or, for
14112 	 * for the slow path through ip_fast_forward(), we perform
14113 	 * the check again for code-reusability
14114 	 */
14115 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14116 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14117 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14118 		if (src_ire != NULL)
14119 			ire_refrele(src_ire);
14120 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14121 		ip2dbg(("ip_rput_process_forward: Received packet with"
14122 		    " bad src/dst address on %s\n", ill->ill_name));
14123 		goto drop_pkt;
14124 	}
14125 
14126 	ill_group = ill->ill_group;
14127 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14128 	/*
14129 	 * Check if we want to forward this one at this time.
14130 	 * We allow source routed packets on a host provided that
14131 	 * they go out the same interface or same interface group
14132 	 * as they came in on.
14133 	 *
14134 	 * XXX To be quicker, we may wish to not chase pointers to
14135 	 * get the ILLF_ROUTER flag and instead store the
14136 	 * forwarding policy in the ire.  An unfortunate
14137 	 * side-effect of that would be requiring an ire flush
14138 	 * whenever the ILLF_ROUTER flag changes.
14139 	 */
14140 	if (((ill->ill_flags &
14141 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14142 	    ILLF_ROUTER) == 0) &&
14143 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14144 	    (ill_group != NULL && ill_group == ire_group)))) {
14145 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14146 		if (ip_source_routed(ipha, ipst)) {
14147 			q = WR(q);
14148 			/*
14149 			 * Clear the indication that this may have
14150 			 * hardware checksum as we are not using it.
14151 			 */
14152 			DB_CKSUMFLAGS(mp) = 0;
14153 			/* Sent by forwarding path, and router is global zone */
14154 			icmp_unreachable(q, mp,
14155 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14156 			return;
14157 		}
14158 		goto drop_pkt;
14159 	}
14160 
14161 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14162 
14163 	/* Packet is being forwarded. Turning off hwcksum flag. */
14164 	DB_CKSUMFLAGS(mp) = 0;
14165 	if (ipst->ips_ip_g_send_redirects) {
14166 		/*
14167 		 * Check whether the incoming interface and outgoing
14168 		 * interface is part of the same group. If so,
14169 		 * send redirects.
14170 		 *
14171 		 * Check the source address to see if it originated
14172 		 * on the same logical subnet it is going back out on.
14173 		 * If so, we should be able to send it a redirect.
14174 		 * Avoid sending a redirect if the destination
14175 		 * is directly connected (i.e., ipha_dst is the same
14176 		 * as ire_gateway_addr or the ire_addr of the
14177 		 * nexthop IRE_CACHE ), or if the packet was source
14178 		 * routed out this interface.
14179 		 */
14180 		ipaddr_t src, nhop;
14181 		mblk_t	*mp1;
14182 		ire_t	*nhop_ire = NULL;
14183 
14184 		/*
14185 		 * Check whether ire_rfq and q are from the same ill
14186 		 * or if they are not same, they at least belong
14187 		 * to the same group. If so, send redirects.
14188 		 */
14189 		if ((ire->ire_rfq == q ||
14190 		    (ill_group != NULL && ill_group == ire_group)) &&
14191 		    !ip_source_routed(ipha, ipst)) {
14192 
14193 			nhop = (ire->ire_gateway_addr != 0 ?
14194 			    ire->ire_gateway_addr : ire->ire_addr);
14195 
14196 			if (ipha->ipha_dst == nhop) {
14197 				/*
14198 				 * We avoid sending a redirect if the
14199 				 * destination is directly connected
14200 				 * because it is possible that multiple
14201 				 * IP subnets may have been configured on
14202 				 * the link, and the source may not
14203 				 * be on the same subnet as ip destination,
14204 				 * even though they are on the same
14205 				 * physical link.
14206 				 */
14207 				goto sendit;
14208 			}
14209 
14210 			src = ipha->ipha_src;
14211 
14212 			/*
14213 			 * We look up the interface ire for the nexthop,
14214 			 * to see if ipha_src is in the same subnet
14215 			 * as the nexthop.
14216 			 *
14217 			 * Note that, if, in the future, IRE_CACHE entries
14218 			 * are obsoleted,  this lookup will not be needed,
14219 			 * as the ire passed to this function will be the
14220 			 * same as the nhop_ire computed below.
14221 			 */
14222 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14223 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14224 			    0, NULL, MATCH_IRE_TYPE, ipst);
14225 
14226 			if (nhop_ire != NULL) {
14227 				if ((src & nhop_ire->ire_mask) ==
14228 				    (nhop & nhop_ire->ire_mask)) {
14229 					/*
14230 					 * The source is directly connected.
14231 					 * Just copy the ip header (which is
14232 					 * in the first mblk)
14233 					 */
14234 					mp1 = copyb(mp);
14235 					if (mp1 != NULL) {
14236 						icmp_send_redirect(WR(q), mp1,
14237 						    nhop, ipst);
14238 					}
14239 				}
14240 				ire_refrele(nhop_ire);
14241 			}
14242 		}
14243 	}
14244 sendit:
14245 	dev_q = ire->ire_stq->q_next;
14246 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14247 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14248 		freemsg(mp);
14249 		return;
14250 	}
14251 
14252 	ip_rput_forward(ire, ipha, mp, ill);
14253 	return;
14254 
14255 drop_pkt:
14256 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14257 	freemsg(mp);
14258 }
14259 
14260 ire_t *
14261 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14262     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14263 {
14264 	queue_t		*q;
14265 	uint16_t	hcksumflags;
14266 	ip_stack_t	*ipst = ill->ill_ipst;
14267 
14268 	q = *qp;
14269 
14270 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14271 
14272 	/*
14273 	 * Clear the indication that this may have hardware
14274 	 * checksum as we are not using it for forwarding.
14275 	 */
14276 	hcksumflags = DB_CKSUMFLAGS(mp);
14277 	DB_CKSUMFLAGS(mp) = 0;
14278 
14279 	/*
14280 	 * Directed broadcast forwarding: if the packet came in over a
14281 	 * different interface then it is routed out over we can forward it.
14282 	 */
14283 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14284 		ire_refrele(ire);
14285 		freemsg(mp);
14286 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14287 		return (NULL);
14288 	}
14289 	/*
14290 	 * For multicast we have set dst to be INADDR_BROADCAST
14291 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14292 	 * only for broadcast packets.
14293 	 */
14294 	if (!CLASSD(ipha->ipha_dst)) {
14295 		ire_t *new_ire;
14296 		ipif_t *ipif;
14297 		/*
14298 		 * For ill groups, as the switch duplicates broadcasts
14299 		 * across all the ports, we need to filter out and
14300 		 * send up only one copy. There is one copy for every
14301 		 * broadcast address on each ill. Thus, we look for a
14302 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14303 		 * later to see whether this ill is eligible to receive
14304 		 * them or not. ill_nominate_bcast_rcv() nominates only
14305 		 * one set of IREs for receiving.
14306 		 */
14307 
14308 		ipif = ipif_get_next_ipif(NULL, ill);
14309 		if (ipif == NULL) {
14310 			ire_refrele(ire);
14311 			freemsg(mp);
14312 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14313 			return (NULL);
14314 		}
14315 		new_ire = ire_ctable_lookup(dst, 0, 0,
14316 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14317 		ipif_refrele(ipif);
14318 
14319 		if (new_ire != NULL) {
14320 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14321 				ire_refrele(ire);
14322 				ire_refrele(new_ire);
14323 				freemsg(mp);
14324 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14325 				return (NULL);
14326 			}
14327 			/*
14328 			 * In the special case of multirouted broadcast
14329 			 * packets, we unconditionally need to "gateway"
14330 			 * them to the appropriate interface here.
14331 			 * In the normal case, this cannot happen, because
14332 			 * there is no broadcast IRE tagged with the
14333 			 * RTF_MULTIRT flag.
14334 			 */
14335 			if (new_ire->ire_flags & RTF_MULTIRT) {
14336 				ire_refrele(new_ire);
14337 				if (ire->ire_rfq != NULL) {
14338 					q = ire->ire_rfq;
14339 					*qp = q;
14340 				}
14341 			} else {
14342 				ire_refrele(ire);
14343 				ire = new_ire;
14344 			}
14345 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14346 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14347 				/*
14348 				 * Free the message if
14349 				 * ip_g_forward_directed_bcast is turned
14350 				 * off for non-local broadcast.
14351 				 */
14352 				ire_refrele(ire);
14353 				freemsg(mp);
14354 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14355 				return (NULL);
14356 			}
14357 		} else {
14358 			/*
14359 			 * This CGTP packet successfully passed the
14360 			 * CGTP filter, but the related CGTP
14361 			 * broadcast IRE has not been found,
14362 			 * meaning that the redundant ipif is
14363 			 * probably down. However, if we discarded
14364 			 * this packet, its duplicate would be
14365 			 * filtered out by the CGTP filter so none
14366 			 * of them would get through. So we keep
14367 			 * going with this one.
14368 			 */
14369 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14370 			if (ire->ire_rfq != NULL) {
14371 				q = ire->ire_rfq;
14372 				*qp = q;
14373 			}
14374 		}
14375 	}
14376 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14377 		/*
14378 		 * Verify that there are not more then one
14379 		 * IRE_BROADCAST with this broadcast address which
14380 		 * has ire_stq set.
14381 		 * TODO: simplify, loop over all IRE's
14382 		 */
14383 		ire_t	*ire1;
14384 		int	num_stq = 0;
14385 		mblk_t	*mp1;
14386 
14387 		/* Find the first one with ire_stq set */
14388 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14389 		for (ire1 = ire; ire1 &&
14390 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14391 		    ire1 = ire1->ire_next)
14392 			;
14393 		if (ire1) {
14394 			ire_refrele(ire);
14395 			ire = ire1;
14396 			IRE_REFHOLD(ire);
14397 		}
14398 
14399 		/* Check if there are additional ones with stq set */
14400 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14401 			if (ire->ire_addr != ire1->ire_addr)
14402 				break;
14403 			if (ire1->ire_stq) {
14404 				num_stq++;
14405 				break;
14406 			}
14407 		}
14408 		rw_exit(&ire->ire_bucket->irb_lock);
14409 		if (num_stq == 1 && ire->ire_stq != NULL) {
14410 			ip1dbg(("ip_rput_process_broadcast: directed "
14411 			    "broadcast to 0x%x\n",
14412 			    ntohl(ire->ire_addr)));
14413 			mp1 = copymsg(mp);
14414 			if (mp1) {
14415 				switch (ipha->ipha_protocol) {
14416 				case IPPROTO_UDP:
14417 					ip_udp_input(q, mp1, ipha, ire, ill);
14418 					break;
14419 				default:
14420 					ip_proto_input(q, mp1, ipha, ire, ill,
14421 					    B_FALSE);
14422 					break;
14423 				}
14424 			}
14425 			/*
14426 			 * Adjust ttl to 2 (1+1 - the forward engine
14427 			 * will decrement it by one.
14428 			 */
14429 			if (ip_csum_hdr(ipha)) {
14430 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14431 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14432 				freemsg(mp);
14433 				ire_refrele(ire);
14434 				return (NULL);
14435 			}
14436 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14437 			ipha->ipha_hdr_checksum = 0;
14438 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14439 			ip_rput_process_forward(q, mp, ire, ipha,
14440 			    ill, ll_multicast);
14441 			ire_refrele(ire);
14442 			return (NULL);
14443 		}
14444 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14445 		    ntohl(ire->ire_addr)));
14446 	}
14447 
14448 
14449 	/* Restore any hardware checksum flags */
14450 	DB_CKSUMFLAGS(mp) = hcksumflags;
14451 	return (ire);
14452 }
14453 
14454 /* ARGSUSED */
14455 static boolean_t
14456 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14457     int *ll_multicast, ipaddr_t *dstp)
14458 {
14459 	ip_stack_t	*ipst = ill->ill_ipst;
14460 
14461 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14462 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14463 	    ntohs(ipha->ipha_length));
14464 
14465 	/*
14466 	 * Forward packets only if we have joined the allmulti
14467 	 * group on this interface.
14468 	 */
14469 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14470 		int retval;
14471 
14472 		/*
14473 		 * Clear the indication that this may have hardware
14474 		 * checksum as we are not using it.
14475 		 */
14476 		DB_CKSUMFLAGS(mp) = 0;
14477 		retval = ip_mforward(ill, ipha, mp);
14478 		/* ip_mforward updates mib variables if needed */
14479 		/* clear b_prev - used by ip_mroute_decap */
14480 		mp->b_prev = NULL;
14481 
14482 		switch (retval) {
14483 		case 0:
14484 			/*
14485 			 * pkt is okay and arrived on phyint.
14486 			 *
14487 			 * If we are running as a multicast router
14488 			 * we need to see all IGMP and/or PIM packets.
14489 			 */
14490 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14491 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14492 				goto done;
14493 			}
14494 			break;
14495 		case -1:
14496 			/* pkt is mal-formed, toss it */
14497 			goto drop_pkt;
14498 		case 1:
14499 			/* pkt is okay and arrived on a tunnel */
14500 			/*
14501 			 * If we are running a multicast router
14502 			 *  we need to see all igmp packets.
14503 			 */
14504 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14505 				*dstp = INADDR_BROADCAST;
14506 				*ll_multicast = 1;
14507 				return (B_FALSE);
14508 			}
14509 
14510 			goto drop_pkt;
14511 		}
14512 	}
14513 
14514 	ILM_WALKER_HOLD(ill);
14515 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14516 		/*
14517 		 * This might just be caused by the fact that
14518 		 * multiple IP Multicast addresses map to the same
14519 		 * link layer multicast - no need to increment counter!
14520 		 */
14521 		ILM_WALKER_RELE(ill);
14522 		freemsg(mp);
14523 		return (B_TRUE);
14524 	}
14525 	ILM_WALKER_RELE(ill);
14526 done:
14527 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14528 	/*
14529 	 * This assumes the we deliver to all streams for multicast
14530 	 * and broadcast packets.
14531 	 */
14532 	*dstp = INADDR_BROADCAST;
14533 	*ll_multicast = 1;
14534 	return (B_FALSE);
14535 drop_pkt:
14536 	ip2dbg(("ip_rput: drop pkt\n"));
14537 	freemsg(mp);
14538 	return (B_TRUE);
14539 }
14540 
14541 static boolean_t
14542 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14543     int *ll_multicast, mblk_t **mpp)
14544 {
14545 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14546 	boolean_t must_copy = B_FALSE;
14547 	struct iocblk   *iocp;
14548 	ipha_t		*ipha;
14549 	ip_stack_t	*ipst = ill->ill_ipst;
14550 
14551 #define	rptr    ((uchar_t *)ipha)
14552 
14553 	first_mp = *first_mpp;
14554 	mp = *mpp;
14555 
14556 	ASSERT(first_mp == mp);
14557 
14558 	/*
14559 	 * if db_ref > 1 then copymsg and free original. Packet may be
14560 	 * changed and do not want other entity who has a reference to this
14561 	 * message to trip over the changes. This is a blind change because
14562 	 * trying to catch all places that might change packet is too
14563 	 * difficult (since it may be a module above this one)
14564 	 *
14565 	 * This corresponds to the non-fast path case. We walk down the full
14566 	 * chain in this case, and check the db_ref count of all the dblks,
14567 	 * and do a copymsg if required. It is possible that the db_ref counts
14568 	 * of the data blocks in the mblk chain can be different.
14569 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14570 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14571 	 * 'snoop' is running.
14572 	 */
14573 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14574 		if (mp1->b_datap->db_ref > 1) {
14575 			must_copy = B_TRUE;
14576 			break;
14577 		}
14578 	}
14579 
14580 	if (must_copy) {
14581 		mp1 = copymsg(mp);
14582 		if (mp1 == NULL) {
14583 			for (mp1 = mp; mp1 != NULL;
14584 			    mp1 = mp1->b_cont) {
14585 				mp1->b_next = NULL;
14586 				mp1->b_prev = NULL;
14587 			}
14588 			freemsg(mp);
14589 			if (ill != NULL) {
14590 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14591 			} else {
14592 				BUMP_MIB(&ipst->ips_ip_mib,
14593 				    ipIfStatsInDiscards);
14594 			}
14595 			return (B_TRUE);
14596 		}
14597 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14598 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14599 			/* Copy b_prev - used by ip_mroute_decap */
14600 			to_mp->b_prev = from_mp->b_prev;
14601 			from_mp->b_prev = NULL;
14602 		}
14603 		*first_mpp = first_mp = mp1;
14604 		freemsg(mp);
14605 		mp = mp1;
14606 		*mpp = mp1;
14607 	}
14608 
14609 	ipha = (ipha_t *)mp->b_rptr;
14610 
14611 	/*
14612 	 * previous code has a case for M_DATA.
14613 	 * We want to check how that happens.
14614 	 */
14615 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14616 	switch (first_mp->b_datap->db_type) {
14617 	case M_PROTO:
14618 	case M_PCPROTO:
14619 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14620 		    DL_UNITDATA_IND) {
14621 			/* Go handle anything other than data elsewhere. */
14622 			ip_rput_dlpi(q, mp);
14623 			return (B_TRUE);
14624 		}
14625 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14626 		/* Ditch the DLPI header. */
14627 		mp1 = mp->b_cont;
14628 		ASSERT(first_mp == mp);
14629 		*first_mpp = mp1;
14630 		freeb(mp);
14631 		*mpp = mp1;
14632 		return (B_FALSE);
14633 	case M_IOCACK:
14634 		ip1dbg(("got iocack "));
14635 		iocp = (struct iocblk *)mp->b_rptr;
14636 		switch (iocp->ioc_cmd) {
14637 		case DL_IOC_HDR_INFO:
14638 			ill = (ill_t *)q->q_ptr;
14639 			ill_fastpath_ack(ill, mp);
14640 			return (B_TRUE);
14641 		case SIOCSTUNPARAM:
14642 		case OSIOCSTUNPARAM:
14643 			/* Go through qwriter_ip */
14644 			break;
14645 		case SIOCGTUNPARAM:
14646 		case OSIOCGTUNPARAM:
14647 			ip_rput_other(NULL, q, mp, NULL);
14648 			return (B_TRUE);
14649 		default:
14650 			putnext(q, mp);
14651 			return (B_TRUE);
14652 		}
14653 		/* FALLTHRU */
14654 	case M_ERROR:
14655 	case M_HANGUP:
14656 		/*
14657 		 * Since this is on the ill stream we unconditionally
14658 		 * bump up the refcount
14659 		 */
14660 		ill_refhold(ill);
14661 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14662 		return (B_TRUE);
14663 	case M_CTL:
14664 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14665 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14666 		    IPHADA_M_CTL)) {
14667 			/*
14668 			 * It's an IPsec accelerated packet.
14669 			 * Make sure that the ill from which we received the
14670 			 * packet has enabled IPsec hardware acceleration.
14671 			 */
14672 			if (!(ill->ill_capabilities &
14673 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14674 				/* IPsec kstats: bean counter */
14675 				freemsg(mp);
14676 				return (B_TRUE);
14677 			}
14678 
14679 			/*
14680 			 * Make mp point to the mblk following the M_CTL,
14681 			 * then process according to type of mp.
14682 			 * After this processing, first_mp will point to
14683 			 * the data-attributes and mp to the pkt following
14684 			 * the M_CTL.
14685 			 */
14686 			mp = first_mp->b_cont;
14687 			if (mp == NULL) {
14688 				freemsg(first_mp);
14689 				return (B_TRUE);
14690 			}
14691 			/*
14692 			 * A Hardware Accelerated packet can only be M_DATA
14693 			 * ESP or AH packet.
14694 			 */
14695 			if (mp->b_datap->db_type != M_DATA) {
14696 				/* non-M_DATA IPsec accelerated packet */
14697 				IPSECHW_DEBUG(IPSECHW_PKT,
14698 				    ("non-M_DATA IPsec accelerated pkt\n"));
14699 				freemsg(first_mp);
14700 				return (B_TRUE);
14701 			}
14702 			ipha = (ipha_t *)mp->b_rptr;
14703 			if (ipha->ipha_protocol != IPPROTO_AH &&
14704 			    ipha->ipha_protocol != IPPROTO_ESP) {
14705 				IPSECHW_DEBUG(IPSECHW_PKT,
14706 				    ("non-M_DATA IPsec accelerated pkt\n"));
14707 				freemsg(first_mp);
14708 				return (B_TRUE);
14709 			}
14710 			*mpp = mp;
14711 			return (B_FALSE);
14712 		}
14713 		putnext(q, mp);
14714 		return (B_TRUE);
14715 	case M_IOCNAK:
14716 		ip1dbg(("got iocnak "));
14717 		iocp = (struct iocblk *)mp->b_rptr;
14718 		switch (iocp->ioc_cmd) {
14719 		case SIOCSTUNPARAM:
14720 		case OSIOCSTUNPARAM:
14721 			/*
14722 			 * Since this is on the ill stream we unconditionally
14723 			 * bump up the refcount
14724 			 */
14725 			ill_refhold(ill);
14726 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14727 			return (B_TRUE);
14728 		case DL_IOC_HDR_INFO:
14729 		case SIOCGTUNPARAM:
14730 		case OSIOCGTUNPARAM:
14731 			ip_rput_other(NULL, q, mp, NULL);
14732 			return (B_TRUE);
14733 		default:
14734 			break;
14735 		}
14736 		/* FALLTHRU */
14737 	default:
14738 		putnext(q, mp);
14739 		return (B_TRUE);
14740 	}
14741 }
14742 
14743 /* Read side put procedure.  Packets coming from the wire arrive here. */
14744 void
14745 ip_rput(queue_t *q, mblk_t *mp)
14746 {
14747 	ill_t	*ill;
14748 	union DL_primitives *dl;
14749 
14750 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14751 
14752 	ill = (ill_t *)q->q_ptr;
14753 
14754 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14755 		/*
14756 		 * If things are opening or closing, only accept high-priority
14757 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14758 		 * created; on close, things hanging off the ill may have been
14759 		 * freed already.)
14760 		 */
14761 		dl = (union DL_primitives *)mp->b_rptr;
14762 		if (DB_TYPE(mp) != M_PCPROTO ||
14763 		    dl->dl_primitive == DL_UNITDATA_IND) {
14764 			/*
14765 			 * SIOC[GS]TUNPARAM ioctls can come here.
14766 			 */
14767 			inet_freemsg(mp);
14768 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14769 			    "ip_rput_end: q %p (%S)", q, "uninit");
14770 			return;
14771 		}
14772 	}
14773 
14774 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14775 	    "ip_rput_end: q %p (%S)", q, "end");
14776 
14777 	ip_input(ill, NULL, mp, NULL);
14778 }
14779 
14780 static mblk_t *
14781 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14782 {
14783 	mblk_t *mp1;
14784 	boolean_t adjusted = B_FALSE;
14785 	ip_stack_t *ipst = ill->ill_ipst;
14786 
14787 	IP_STAT(ipst, ip_db_ref);
14788 	/*
14789 	 * The IP_RECVSLLA option depends on having the
14790 	 * link layer header. First check that:
14791 	 * a> the underlying device is of type ether,
14792 	 * since this option is currently supported only
14793 	 * over ethernet.
14794 	 * b> there is enough room to copy over the link
14795 	 * layer header.
14796 	 *
14797 	 * Once the checks are done, adjust rptr so that
14798 	 * the link layer header will be copied via
14799 	 * copymsg. Note that, IFT_ETHER may be returned
14800 	 * by some non-ethernet drivers but in this case
14801 	 * the second check will fail.
14802 	 */
14803 	if (ill->ill_type == IFT_ETHER &&
14804 	    (mp->b_rptr - mp->b_datap->db_base) >=
14805 	    sizeof (struct ether_header)) {
14806 		mp->b_rptr -= sizeof (struct ether_header);
14807 		adjusted = B_TRUE;
14808 	}
14809 	mp1 = copymsg(mp);
14810 
14811 	if (mp1 == NULL) {
14812 		mp->b_next = NULL;
14813 		/* clear b_prev - used by ip_mroute_decap */
14814 		mp->b_prev = NULL;
14815 		freemsg(mp);
14816 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14817 		return (NULL);
14818 	}
14819 
14820 	if (adjusted) {
14821 		/*
14822 		 * Copy is done. Restore the pointer in
14823 		 * the _new_ mblk
14824 		 */
14825 		mp1->b_rptr += sizeof (struct ether_header);
14826 	}
14827 
14828 	/* Copy b_prev - used by ip_mroute_decap */
14829 	mp1->b_prev = mp->b_prev;
14830 	mp->b_prev = NULL;
14831 
14832 	/* preserve the hardware checksum flags and data, if present */
14833 	if (DB_CKSUMFLAGS(mp) != 0) {
14834 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14835 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14836 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14837 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14838 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14839 	}
14840 
14841 	freemsg(mp);
14842 	return (mp1);
14843 }
14844 
14845 /*
14846  * Direct read side procedure capable of dealing with chains. GLDv3 based
14847  * drivers call this function directly with mblk chains while STREAMS
14848  * read side procedure ip_rput() calls this for single packet with ip_ring
14849  * set to NULL to process one packet at a time.
14850  *
14851  * The ill will always be valid if this function is called directly from
14852  * the driver.
14853  *
14854  * If ip_input() is called from GLDv3:
14855  *
14856  *   - This must be a non-VLAN IP stream.
14857  *   - 'mp' is either an untagged or a special priority-tagged packet.
14858  *   - Any VLAN tag that was in the MAC header has been stripped.
14859  *
14860  * If the IP header in packet is not 32-bit aligned, every message in the
14861  * chain will be aligned before further operations. This is required on SPARC
14862  * platform.
14863  */
14864 /* ARGSUSED */
14865 void
14866 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14867     struct mac_header_info_s *mhip)
14868 {
14869 	ipaddr_t		dst = NULL;
14870 	ipaddr_t		prev_dst;
14871 	ire_t			*ire = NULL;
14872 	ipha_t			*ipha;
14873 	uint_t			pkt_len;
14874 	ssize_t			len;
14875 	uint_t			opt_len;
14876 	int			ll_multicast;
14877 	int			cgtp_flt_pkt;
14878 	queue_t			*q = ill->ill_rq;
14879 	squeue_t		*curr_sqp = NULL;
14880 	mblk_t 			*head = NULL;
14881 	mblk_t			*tail = NULL;
14882 	mblk_t			*first_mp;
14883 	mblk_t 			*mp;
14884 	mblk_t			*dmp;
14885 	int			cnt = 0;
14886 	ip_stack_t		*ipst = ill->ill_ipst;
14887 
14888 	ASSERT(mp_chain != NULL);
14889 	ASSERT(ill != NULL);
14890 
14891 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14892 
14893 #define	rptr	((uchar_t *)ipha)
14894 
14895 	while (mp_chain != NULL) {
14896 		first_mp = mp = mp_chain;
14897 		mp_chain = mp_chain->b_next;
14898 		mp->b_next = NULL;
14899 		ll_multicast = 0;
14900 
14901 		/*
14902 		 * We do ire caching from one iteration to
14903 		 * another. In the event the packet chain contains
14904 		 * all packets from the same dst, this caching saves
14905 		 * an ire_cache_lookup for each of the succeeding
14906 		 * packets in a packet chain.
14907 		 */
14908 		prev_dst = dst;
14909 
14910 		/*
14911 		 * if db_ref > 1 then copymsg and free original. Packet
14912 		 * may be changed and we do not want the other entity
14913 		 * who has a reference to this message to trip over the
14914 		 * changes. This is a blind change because trying to
14915 		 * catch all places that might change the packet is too
14916 		 * difficult.
14917 		 *
14918 		 * This corresponds to the fast path case, where we have
14919 		 * a chain of M_DATA mblks.  We check the db_ref count
14920 		 * of only the 1st data block in the mblk chain. There
14921 		 * doesn't seem to be a reason why a device driver would
14922 		 * send up data with varying db_ref counts in the mblk
14923 		 * chain. In any case the Fast path is a private
14924 		 * interface, and our drivers don't do such a thing.
14925 		 * Given the above assumption, there is no need to walk
14926 		 * down the entire mblk chain (which could have a
14927 		 * potential performance problem)
14928 		 */
14929 
14930 		if (DB_REF(mp) > 1) {
14931 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14932 				continue;
14933 		}
14934 
14935 		/*
14936 		 * Check and align the IP header.
14937 		 */
14938 		first_mp = mp;
14939 		if (DB_TYPE(mp) == M_DATA) {
14940 			dmp = mp;
14941 		} else if (DB_TYPE(mp) == M_PROTO &&
14942 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14943 			dmp = mp->b_cont;
14944 		} else {
14945 			dmp = NULL;
14946 		}
14947 		if (dmp != NULL) {
14948 			/*
14949 			 * IP header ptr not aligned?
14950 			 * OR IP header not complete in first mblk
14951 			 */
14952 			if (!OK_32PTR(dmp->b_rptr) ||
14953 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14954 				if (!ip_check_and_align_header(q, dmp, ipst))
14955 					continue;
14956 			}
14957 		}
14958 
14959 		/*
14960 		 * ip_input fast path
14961 		 */
14962 
14963 		/* mblk type is not M_DATA */
14964 		if (DB_TYPE(mp) != M_DATA) {
14965 			if (ip_rput_process_notdata(q, &first_mp, ill,
14966 			    &ll_multicast, &mp))
14967 				continue;
14968 
14969 			/*
14970 			 * The only way we can get here is if we had a
14971 			 * packet that was either a DL_UNITDATA_IND or
14972 			 * an M_CTL for an IPsec accelerated packet.
14973 			 *
14974 			 * In either case, the first_mp will point to
14975 			 * the leading M_PROTO or M_CTL.
14976 			 */
14977 			ASSERT(first_mp != NULL);
14978 		}
14979 
14980 		/* Make sure its an M_DATA and that its aligned */
14981 		ASSERT(DB_TYPE(mp) == M_DATA);
14982 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14983 
14984 		ipha = (ipha_t *)mp->b_rptr;
14985 		len = mp->b_wptr - rptr;
14986 		pkt_len = ntohs(ipha->ipha_length);
14987 
14988 		/*
14989 		 * We must count all incoming packets, even if they end
14990 		 * up being dropped later on.
14991 		 */
14992 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14993 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14994 
14995 		/* multiple mblk or too short */
14996 		len -= pkt_len;
14997 		if (len != 0) {
14998 			/*
14999 			 * Make sure we have data length consistent
15000 			 * with the IP header.
15001 			 */
15002 			if (mp->b_cont == NULL) {
15003 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15004 					BUMP_MIB(ill->ill_ip_mib,
15005 					    ipIfStatsInHdrErrors);
15006 					ip2dbg(("ip_input: drop pkt\n"));
15007 					freemsg(mp);
15008 					continue;
15009 				}
15010 				mp->b_wptr = rptr + pkt_len;
15011 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15012 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15013 					BUMP_MIB(ill->ill_ip_mib,
15014 					    ipIfStatsInHdrErrors);
15015 					ip2dbg(("ip_input: drop pkt\n"));
15016 					freemsg(mp);
15017 					continue;
15018 				}
15019 				(void) adjmsg(mp, -len);
15020 				IP_STAT(ipst, ip_multimblk3);
15021 			}
15022 		}
15023 
15024 		/* Obtain the dst of the current packet */
15025 		dst = ipha->ipha_dst;
15026 
15027 		/*
15028 		 * The following test for loopback is faster than
15029 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15030 		 * operations.
15031 		 * Note that these addresses are always in network byte order
15032 		 */
15033 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15034 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15035 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15036 			freemsg(mp);
15037 			continue;
15038 		}
15039 
15040 		/*
15041 		 * The event for packets being received from a 'physical'
15042 		 * interface is placed after validation of the source and/or
15043 		 * destination address as being local so that packets can be
15044 		 * redirected to loopback addresses using ipnat.
15045 		 */
15046 		DTRACE_PROBE4(ip4__physical__in__start,
15047 		    ill_t *, ill, ill_t *, NULL,
15048 		    ipha_t *, ipha, mblk_t *, first_mp);
15049 
15050 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15051 		    ipst->ips_ipv4firewall_physical_in,
15052 		    ill, NULL, ipha, first_mp, mp, ipst);
15053 
15054 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15055 
15056 		if (first_mp == NULL) {
15057 			continue;
15058 		}
15059 		dst = ipha->ipha_dst;
15060 
15061 		/*
15062 		 * Attach any necessary label information to
15063 		 * this packet
15064 		 */
15065 		if (is_system_labeled() &&
15066 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15067 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15068 			freemsg(mp);
15069 			continue;
15070 		}
15071 
15072 		/*
15073 		 * Reuse the cached ire only if the ipha_dst of the previous
15074 		 * packet is the same as the current packet AND it is not
15075 		 * INADDR_ANY.
15076 		 */
15077 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15078 		    (ire != NULL)) {
15079 			ire_refrele(ire);
15080 			ire = NULL;
15081 		}
15082 		opt_len = ipha->ipha_version_and_hdr_length -
15083 		    IP_SIMPLE_HDR_VERSION;
15084 
15085 		/*
15086 		 * Check to see if we can take the fastpath.
15087 		 * That is possible if the following conditions are met
15088 		 *	o Tsol disabled
15089 		 *	o CGTP disabled
15090 		 *	o ipp_action_count is 0
15091 		 *	o no options in the packet
15092 		 *	o not a RSVP packet
15093 		 * 	o not a multicast packet
15094 		 *	o ill not in IP_DHCPINIT_IF mode
15095 		 */
15096 		if (!is_system_labeled() &&
15097 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15098 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15099 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15100 			if (ire == NULL)
15101 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15102 				    ipst);
15103 
15104 			/* incoming packet is for forwarding */
15105 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15106 				ire = ip_fast_forward(ire, dst, ill, mp);
15107 				continue;
15108 			}
15109 			/* incoming packet is for local consumption */
15110 			if (ire->ire_type & IRE_LOCAL)
15111 				goto local;
15112 		}
15113 
15114 		/*
15115 		 * Disable ire caching for anything more complex
15116 		 * than the simple fast path case we checked for above.
15117 		 */
15118 		if (ire != NULL) {
15119 			ire_refrele(ire);
15120 			ire = NULL;
15121 		}
15122 
15123 		/*
15124 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15125 		 * server to unicast DHCP packets to a DHCP client using the
15126 		 * IP address it is offering to the client.  This can be
15127 		 * disabled through the "broadcast bit", but not all DHCP
15128 		 * servers honor that bit.  Therefore, to interoperate with as
15129 		 * many DHCP servers as possible, the DHCP client allows the
15130 		 * server to unicast, but we treat those packets as broadcast
15131 		 * here.  Note that we don't rewrite the packet itself since
15132 		 * (a) that would mess up the checksums and (b) the DHCP
15133 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15134 		 * hand it the packet regardless.
15135 		 */
15136 		if (ill->ill_dhcpinit != 0 &&
15137 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15138 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15139 			udpha_t *udpha;
15140 
15141 			/*
15142 			 * Reload ipha since pullupmsg() can change b_rptr.
15143 			 */
15144 			ipha = (ipha_t *)mp->b_rptr;
15145 			udpha = (udpha_t *)&ipha[1];
15146 
15147 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15148 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15149 				    mblk_t *, mp);
15150 				dst = INADDR_BROADCAST;
15151 			}
15152 		}
15153 
15154 		/* Full-blown slow path */
15155 		if (opt_len != 0) {
15156 			if (len != 0)
15157 				IP_STAT(ipst, ip_multimblk4);
15158 			else
15159 				IP_STAT(ipst, ip_ipoptions);
15160 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15161 			    &dst, ipst))
15162 				continue;
15163 		}
15164 
15165 		/*
15166 		 * Invoke the CGTP (multirouting) filtering module to process
15167 		 * the incoming packet. Packets identified as duplicates
15168 		 * must be discarded. Filtering is active only if the
15169 		 * the ip_cgtp_filter ndd variable is non-zero.
15170 		 */
15171 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15172 		if (ipst->ips_ip_cgtp_filter &&
15173 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15174 			netstackid_t stackid;
15175 
15176 			stackid = ipst->ips_netstack->netstack_stackid;
15177 			cgtp_flt_pkt =
15178 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15179 			    ill->ill_phyint->phyint_ifindex, mp);
15180 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15181 				freemsg(first_mp);
15182 				continue;
15183 			}
15184 		}
15185 
15186 		/*
15187 		 * If rsvpd is running, let RSVP daemon handle its processing
15188 		 * and forwarding of RSVP multicast/unicast packets.
15189 		 * If rsvpd is not running but mrouted is running, RSVP
15190 		 * multicast packets are forwarded as multicast traffic
15191 		 * and RSVP unicast packets are forwarded by unicast router.
15192 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15193 		 * packets are not forwarded, but the unicast packets are
15194 		 * forwarded like unicast traffic.
15195 		 */
15196 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15197 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15198 		    NULL) {
15199 			/* RSVP packet and rsvpd running. Treat as ours */
15200 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15201 			/*
15202 			 * This assumes that we deliver to all streams for
15203 			 * multicast and broadcast packets.
15204 			 * We have to force ll_multicast to 1 to handle the
15205 			 * M_DATA messages passed in from ip_mroute_decap.
15206 			 */
15207 			dst = INADDR_BROADCAST;
15208 			ll_multicast = 1;
15209 		} else if (CLASSD(dst)) {
15210 			/* packet is multicast */
15211 			mp->b_next = NULL;
15212 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15213 			    &ll_multicast, &dst))
15214 				continue;
15215 		}
15216 
15217 		if (ire == NULL) {
15218 			ire = ire_cache_lookup(dst, ALL_ZONES,
15219 			    MBLK_GETLABEL(mp), ipst);
15220 		}
15221 
15222 		if (ire == NULL) {
15223 			/*
15224 			 * No IRE for this destination, so it can't be for us.
15225 			 * Unless we are forwarding, drop the packet.
15226 			 * We have to let source routed packets through
15227 			 * since we don't yet know if they are 'ping -l'
15228 			 * packets i.e. if they will go out over the
15229 			 * same interface as they came in on.
15230 			 */
15231 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15232 			if (ire == NULL)
15233 				continue;
15234 		}
15235 
15236 		/*
15237 		 * Broadcast IRE may indicate either broadcast or
15238 		 * multicast packet
15239 		 */
15240 		if (ire->ire_type == IRE_BROADCAST) {
15241 			/*
15242 			 * Skip broadcast checks if packet is UDP multicast;
15243 			 * we'd rather not enter ip_rput_process_broadcast()
15244 			 * unless the packet is broadcast for real, since
15245 			 * that routine is a no-op for multicast.
15246 			 */
15247 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15248 			    !CLASSD(ipha->ipha_dst)) {
15249 				ire = ip_rput_process_broadcast(&q, mp,
15250 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15251 				    ll_multicast);
15252 				if (ire == NULL)
15253 					continue;
15254 			}
15255 		} else if (ire->ire_stq != NULL) {
15256 			/* fowarding? */
15257 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15258 			    ll_multicast);
15259 			/* ip_rput_process_forward consumed the packet */
15260 			continue;
15261 		}
15262 
15263 local:
15264 		/*
15265 		 * If the queue in the ire is different to the ingress queue
15266 		 * then we need to check to see if we can accept the packet.
15267 		 * Note that for multicast packets and broadcast packets sent
15268 		 * to a broadcast address which is shared between multiple
15269 		 * interfaces we should not do this since we just got a random
15270 		 * broadcast ire.
15271 		 */
15272 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15273 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15274 			    ill)) == NULL) {
15275 				/* Drop packet */
15276 				BUMP_MIB(ill->ill_ip_mib,
15277 				    ipIfStatsForwProhibits);
15278 				freemsg(mp);
15279 				continue;
15280 			}
15281 			if (ire->ire_rfq != NULL)
15282 				q = ire->ire_rfq;
15283 		}
15284 
15285 		switch (ipha->ipha_protocol) {
15286 		case IPPROTO_TCP:
15287 			ASSERT(first_mp == mp);
15288 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15289 			    mp, 0, q, ip_ring)) != NULL) {
15290 				if (curr_sqp == NULL) {
15291 					curr_sqp = GET_SQUEUE(mp);
15292 					ASSERT(cnt == 0);
15293 					cnt++;
15294 					head = tail = mp;
15295 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15296 					ASSERT(tail != NULL);
15297 					cnt++;
15298 					tail->b_next = mp;
15299 					tail = mp;
15300 				} else {
15301 					/*
15302 					 * A different squeue. Send the
15303 					 * chain for the previous squeue on
15304 					 * its way. This shouldn't happen
15305 					 * often unless interrupt binding
15306 					 * changes.
15307 					 */
15308 					IP_STAT(ipst, ip_input_multi_squeue);
15309 					squeue_enter_chain(curr_sqp, head,
15310 					    tail, cnt, SQTAG_IP_INPUT);
15311 					curr_sqp = GET_SQUEUE(mp);
15312 					head = mp;
15313 					tail = mp;
15314 					cnt = 1;
15315 				}
15316 			}
15317 			continue;
15318 		case IPPROTO_UDP:
15319 			ASSERT(first_mp == mp);
15320 			ip_udp_input(q, mp, ipha, ire, ill);
15321 			continue;
15322 		case IPPROTO_SCTP:
15323 			ASSERT(first_mp == mp);
15324 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15325 			    q, dst);
15326 			/* ire has been released by ip_sctp_input */
15327 			ire = NULL;
15328 			continue;
15329 		default:
15330 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15331 			continue;
15332 		}
15333 	}
15334 
15335 	if (ire != NULL)
15336 		ire_refrele(ire);
15337 
15338 	if (head != NULL)
15339 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15340 
15341 	/*
15342 	 * This code is there just to make netperf/ttcp look good.
15343 	 *
15344 	 * Its possible that after being in polling mode (and having cleared
15345 	 * the backlog), squeues have turned the interrupt frequency higher
15346 	 * to improve latency at the expense of more CPU utilization (less
15347 	 * packets per interrupts or more number of interrupts). Workloads
15348 	 * like ttcp/netperf do manage to tickle polling once in a while
15349 	 * but for the remaining time, stay in higher interrupt mode since
15350 	 * their packet arrival rate is pretty uniform and this shows up
15351 	 * as higher CPU utilization. Since people care about CPU utilization
15352 	 * while running netperf/ttcp, turn the interrupt frequency back to
15353 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15354 	 */
15355 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15356 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15357 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15358 			ip_ring->rr_blank(ip_ring->rr_handle,
15359 			    ip_ring->rr_normal_blank_time,
15360 			    ip_ring->rr_normal_pkt_cnt);
15361 		}
15362 		}
15363 
15364 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15365 	    "ip_input_end: q %p (%S)", q, "end");
15366 #undef  rptr
15367 }
15368 
15369 static void
15370 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15371     t_uscalar_t err)
15372 {
15373 	if (dl_err == DL_SYSERR) {
15374 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15375 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15376 		    ill->ill_name, dlpi_prim_str(prim), err);
15377 		return;
15378 	}
15379 
15380 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15381 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15382 	    dlpi_err_str(dl_err));
15383 }
15384 
15385 /*
15386  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15387  * than DL_UNITDATA_IND messages. If we need to process this message
15388  * exclusively, we call qwriter_ip, in which case we also need to call
15389  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15390  */
15391 void
15392 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15393 {
15394 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15395 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15396 	ill_t		*ill = (ill_t *)q->q_ptr;
15397 	boolean_t	pending;
15398 
15399 	ip1dbg(("ip_rput_dlpi"));
15400 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15401 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15402 		    "%s (0x%x), unix %u\n", ill->ill_name,
15403 		    dlpi_prim_str(dlea->dl_error_primitive),
15404 		    dlea->dl_error_primitive,
15405 		    dlpi_err_str(dlea->dl_errno),
15406 		    dlea->dl_errno,
15407 		    dlea->dl_unix_errno));
15408 	}
15409 
15410 	/*
15411 	 * If we received an ACK but didn't send a request for it, then it
15412 	 * can't be part of any pending operation; discard up-front.
15413 	 */
15414 	switch (dloa->dl_primitive) {
15415 	case DL_NOTIFY_IND:
15416 		pending = B_TRUE;
15417 		break;
15418 	case DL_ERROR_ACK:
15419 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15420 		break;
15421 	case DL_OK_ACK:
15422 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15423 		break;
15424 	case DL_INFO_ACK:
15425 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15426 		break;
15427 	case DL_BIND_ACK:
15428 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15429 		break;
15430 	case DL_PHYS_ADDR_ACK:
15431 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15432 		break;
15433 	case DL_NOTIFY_ACK:
15434 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15435 		break;
15436 	case DL_CONTROL_ACK:
15437 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15438 		break;
15439 	case DL_CAPABILITY_ACK:
15440 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15441 		break;
15442 	default:
15443 		/* Not a DLPI message we support or were expecting */
15444 		freemsg(mp);
15445 		return;
15446 	}
15447 
15448 	if (!pending) {
15449 		freemsg(mp);
15450 		return;
15451 	}
15452 
15453 	switch (dloa->dl_primitive) {
15454 	case DL_ERROR_ACK:
15455 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15456 			mutex_enter(&ill->ill_lock);
15457 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15458 			cv_signal(&ill->ill_cv);
15459 			mutex_exit(&ill->ill_lock);
15460 		}
15461 		break;
15462 
15463 	case DL_OK_ACK:
15464 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15465 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15466 		switch (dloa->dl_correct_primitive) {
15467 		case DL_UNBIND_REQ:
15468 			mutex_enter(&ill->ill_lock);
15469 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15470 			cv_signal(&ill->ill_cv);
15471 			mutex_exit(&ill->ill_lock);
15472 			break;
15473 
15474 		case DL_ENABMULTI_REQ:
15475 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15476 				ill->ill_dlpi_multicast_state = IDS_OK;
15477 			break;
15478 		}
15479 		break;
15480 	default:
15481 		break;
15482 	}
15483 
15484 	/*
15485 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15486 	 * and we need to become writer to continue to process it. If it's not
15487 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15488 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15489 	 * some work as part of the current exclusive operation that actually
15490 	 * is not part of it -- which is wrong, but better than the
15491 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15492 	 * should track which DLPI requests have ACKs that we wait on
15493 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15494 	 *
15495 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15496 	 * Since this is on the ill stream we unconditionally bump up the
15497 	 * refcount without doing ILL_CAN_LOOKUP().
15498 	 */
15499 	ill_refhold(ill);
15500 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15501 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15502 	else
15503 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15504 }
15505 
15506 /*
15507  * Handling of DLPI messages that require exclusive access to the ipsq.
15508  *
15509  * Need to do ill_pending_mp_release on ioctl completion, which could
15510  * happen here. (along with mi_copy_done)
15511  */
15512 /* ARGSUSED */
15513 static void
15514 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15515 {
15516 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15517 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15518 	int		err = 0;
15519 	ill_t		*ill;
15520 	ipif_t		*ipif = NULL;
15521 	mblk_t		*mp1 = NULL;
15522 	conn_t		*connp = NULL;
15523 	t_uscalar_t	paddrreq;
15524 	mblk_t		*mp_hw;
15525 	boolean_t	success;
15526 	boolean_t	ioctl_aborted = B_FALSE;
15527 	boolean_t	log = B_TRUE;
15528 	hook_nic_event_t	*info;
15529 	ip_stack_t		*ipst;
15530 
15531 	ip1dbg(("ip_rput_dlpi_writer .."));
15532 	ill = (ill_t *)q->q_ptr;
15533 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15534 
15535 	ASSERT(IAM_WRITER_ILL(ill));
15536 
15537 	ipst = ill->ill_ipst;
15538 
15539 	/*
15540 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15541 	 * both are null or non-null. However we can assert that only
15542 	 * after grabbing the ipsq_lock. So we don't make any assertion
15543 	 * here and in other places in the code.
15544 	 */
15545 	ipif = ipsq->ipsq_pending_ipif;
15546 	/*
15547 	 * The current ioctl could have been aborted by the user and a new
15548 	 * ioctl to bring up another ill could have started. We could still
15549 	 * get a response from the driver later.
15550 	 */
15551 	if (ipif != NULL && ipif->ipif_ill != ill)
15552 		ioctl_aborted = B_TRUE;
15553 
15554 	switch (dloa->dl_primitive) {
15555 	case DL_ERROR_ACK:
15556 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15557 		    dlpi_prim_str(dlea->dl_error_primitive)));
15558 
15559 		switch (dlea->dl_error_primitive) {
15560 		case DL_PROMISCON_REQ:
15561 		case DL_PROMISCOFF_REQ:
15562 		case DL_DISABMULTI_REQ:
15563 		case DL_UNBIND_REQ:
15564 		case DL_ATTACH_REQ:
15565 		case DL_INFO_REQ:
15566 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15567 			break;
15568 		case DL_NOTIFY_REQ:
15569 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15570 			log = B_FALSE;
15571 			break;
15572 		case DL_PHYS_ADDR_REQ:
15573 			/*
15574 			 * For IPv6 only, there are two additional
15575 			 * phys_addr_req's sent to the driver to get the
15576 			 * IPv6 token and lla. This allows IP to acquire
15577 			 * the hardware address format for a given interface
15578 			 * without having built in knowledge of the hardware
15579 			 * address. ill_phys_addr_pend keeps track of the last
15580 			 * DL_PAR sent so we know which response we are
15581 			 * dealing with. ill_dlpi_done will update
15582 			 * ill_phys_addr_pend when it sends the next req.
15583 			 * We don't complete the IOCTL until all three DL_PARs
15584 			 * have been attempted, so set *_len to 0 and break.
15585 			 */
15586 			paddrreq = ill->ill_phys_addr_pend;
15587 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15588 			if (paddrreq == DL_IPV6_TOKEN) {
15589 				ill->ill_token_length = 0;
15590 				log = B_FALSE;
15591 				break;
15592 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15593 				ill->ill_nd_lla_len = 0;
15594 				log = B_FALSE;
15595 				break;
15596 			}
15597 			/*
15598 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15599 			 * We presumably have an IOCTL hanging out waiting
15600 			 * for completion. Find it and complete the IOCTL
15601 			 * with the error noted.
15602 			 * However, ill_dl_phys was called on an ill queue
15603 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15604 			 * set. But the ioctl is known to be pending on ill_wq.
15605 			 */
15606 			if (!ill->ill_ifname_pending)
15607 				break;
15608 			ill->ill_ifname_pending = 0;
15609 			if (!ioctl_aborted)
15610 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15611 			if (mp1 != NULL) {
15612 				/*
15613 				 * This operation (SIOCSLIFNAME) must have
15614 				 * happened on the ill. Assert there is no conn
15615 				 */
15616 				ASSERT(connp == NULL);
15617 				q = ill->ill_wq;
15618 			}
15619 			break;
15620 		case DL_BIND_REQ:
15621 			ill_dlpi_done(ill, DL_BIND_REQ);
15622 			if (ill->ill_ifname_pending)
15623 				break;
15624 			/*
15625 			 * Something went wrong with the bind.  We presumably
15626 			 * have an IOCTL hanging out waiting for completion.
15627 			 * Find it, take down the interface that was coming
15628 			 * up, and complete the IOCTL with the error noted.
15629 			 */
15630 			if (!ioctl_aborted)
15631 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15632 			if (mp1 != NULL) {
15633 				/*
15634 				 * This operation (SIOCSLIFFLAGS) must have
15635 				 * happened from a conn.
15636 				 */
15637 				ASSERT(connp != NULL);
15638 				q = CONNP_TO_WQ(connp);
15639 				if (ill->ill_move_in_progress) {
15640 					ILL_CLEAR_MOVE(ill);
15641 				}
15642 				(void) ipif_down(ipif, NULL, NULL);
15643 				/* error is set below the switch */
15644 			}
15645 			break;
15646 		case DL_ENABMULTI_REQ:
15647 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15648 
15649 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15650 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15651 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15652 				ipif_t *ipif;
15653 
15654 				printf("ip: joining multicasts failed (%d)"
15655 				    " on %s - will use link layer "
15656 				    "broadcasts for multicast\n",
15657 				    dlea->dl_errno, ill->ill_name);
15658 
15659 				/*
15660 				 * Set up the multicast mapping alone.
15661 				 * writer, so ok to access ill->ill_ipif
15662 				 * without any lock.
15663 				 */
15664 				ipif = ill->ill_ipif;
15665 				mutex_enter(&ill->ill_phyint->phyint_lock);
15666 				ill->ill_phyint->phyint_flags |=
15667 				    PHYI_MULTI_BCAST;
15668 				mutex_exit(&ill->ill_phyint->phyint_lock);
15669 
15670 				if (!ill->ill_isv6) {
15671 					(void) ipif_arp_setup_multicast(ipif,
15672 					    NULL);
15673 				} else {
15674 					(void) ipif_ndp_setup_multicast(ipif,
15675 					    NULL);
15676 				}
15677 			}
15678 			freemsg(mp);	/* Don't want to pass this up */
15679 			return;
15680 
15681 		case DL_CAPABILITY_REQ:
15682 		case DL_CONTROL_REQ:
15683 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15684 			ill->ill_dlpi_capab_state = IDS_FAILED;
15685 			freemsg(mp);
15686 			return;
15687 		}
15688 		/*
15689 		 * Note the error for IOCTL completion (mp1 is set when
15690 		 * ready to complete ioctl). If ill_ifname_pending_err is
15691 		 * set, an error occured during plumbing (ill_ifname_pending),
15692 		 * so we want to report that error.
15693 		 *
15694 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15695 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15696 		 * expected to get errack'd if the driver doesn't support
15697 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15698 		 * if these error conditions are encountered.
15699 		 */
15700 		if (mp1 != NULL) {
15701 			if (ill->ill_ifname_pending_err != 0)  {
15702 				err = ill->ill_ifname_pending_err;
15703 				ill->ill_ifname_pending_err = 0;
15704 			} else {
15705 				err = dlea->dl_unix_errno ?
15706 				    dlea->dl_unix_errno : ENXIO;
15707 			}
15708 		/*
15709 		 * If we're plumbing an interface and an error hasn't already
15710 		 * been saved, set ill_ifname_pending_err to the error passed
15711 		 * up. Ignore the error if log is B_FALSE (see comment above).
15712 		 */
15713 		} else if (log && ill->ill_ifname_pending &&
15714 		    ill->ill_ifname_pending_err == 0) {
15715 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15716 			    dlea->dl_unix_errno : ENXIO;
15717 		}
15718 
15719 		if (log)
15720 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15721 			    dlea->dl_errno, dlea->dl_unix_errno);
15722 		break;
15723 	case DL_CAPABILITY_ACK:
15724 		/* Call a routine to handle this one. */
15725 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15726 		ill_capability_ack(ill, mp);
15727 
15728 		/*
15729 		 * If the ack is due to renegotiation, we will need to send
15730 		 * a new CAPABILITY_REQ to start the renegotiation.
15731 		 */
15732 		if (ill->ill_capab_reneg) {
15733 			ill->ill_capab_reneg = B_FALSE;
15734 			ill_capability_probe(ill);
15735 		}
15736 		break;
15737 	case DL_CONTROL_ACK:
15738 		/* We treat all of these as "fire and forget" */
15739 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15740 		break;
15741 	case DL_INFO_ACK:
15742 		/* Call a routine to handle this one. */
15743 		ill_dlpi_done(ill, DL_INFO_REQ);
15744 		ip_ll_subnet_defaults(ill, mp);
15745 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15746 		return;
15747 	case DL_BIND_ACK:
15748 		/*
15749 		 * We should have an IOCTL waiting on this unless
15750 		 * sent by ill_dl_phys, in which case just return
15751 		 */
15752 		ill_dlpi_done(ill, DL_BIND_REQ);
15753 		if (ill->ill_ifname_pending)
15754 			break;
15755 
15756 		if (!ioctl_aborted)
15757 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15758 		if (mp1 == NULL)
15759 			break;
15760 		/*
15761 		 * Because mp1 was added by ill_dl_up(), and it always
15762 		 * passes a valid connp, connp must be valid here.
15763 		 */
15764 		ASSERT(connp != NULL);
15765 		q = CONNP_TO_WQ(connp);
15766 
15767 		/*
15768 		 * We are exclusive. So nothing can change even after
15769 		 * we get the pending mp. If need be we can put it back
15770 		 * and restart, as in calling ipif_arp_up()  below.
15771 		 */
15772 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15773 
15774 		mutex_enter(&ill->ill_lock);
15775 
15776 		ill->ill_dl_up = 1;
15777 
15778 		if ((info = ill->ill_nic_event_info) != NULL) {
15779 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15780 			    "attached for %s\n", info->hne_event,
15781 			    ill->ill_name));
15782 			if (info->hne_data != NULL)
15783 				kmem_free(info->hne_data, info->hne_datalen);
15784 			kmem_free(info, sizeof (hook_nic_event_t));
15785 		}
15786 
15787 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15788 		if (info != NULL) {
15789 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15790 			info->hne_lif = 0;
15791 			info->hne_event = NE_UP;
15792 			info->hne_data = NULL;
15793 			info->hne_datalen = 0;
15794 			info->hne_family = ill->ill_isv6 ?
15795 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15796 		} else
15797 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15798 			    "event information for %s (ENOMEM)\n",
15799 			    ill->ill_name));
15800 
15801 		ill->ill_nic_event_info = info;
15802 
15803 		mutex_exit(&ill->ill_lock);
15804 
15805 		/*
15806 		 * Now bring up the resolver; when that is complete, we'll
15807 		 * create IREs.  Note that we intentionally mirror what
15808 		 * ipif_up() would have done, because we got here by way of
15809 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15810 		 */
15811 		if (ill->ill_isv6) {
15812 			/*
15813 			 * v6 interfaces.
15814 			 * Unlike ARP which has to do another bind
15815 			 * and attach, once we get here we are
15816 			 * done with NDP. Except in the case of
15817 			 * ILLF_XRESOLV, in which case we send an
15818 			 * AR_INTERFACE_UP to the external resolver.
15819 			 * If all goes well, the ioctl will complete
15820 			 * in ip_rput(). If there's an error, we
15821 			 * complete it here.
15822 			 */
15823 			if ((err = ipif_ndp_up(ipif)) == 0) {
15824 				if (ill->ill_flags & ILLF_XRESOLV) {
15825 					mutex_enter(&connp->conn_lock);
15826 					mutex_enter(&ill->ill_lock);
15827 					success = ipsq_pending_mp_add(
15828 					    connp, ipif, q, mp1, 0);
15829 					mutex_exit(&ill->ill_lock);
15830 					mutex_exit(&connp->conn_lock);
15831 					if (success) {
15832 						err = ipif_resolver_up(ipif,
15833 						    Res_act_initial);
15834 						if (err == EINPROGRESS) {
15835 							freemsg(mp);
15836 							return;
15837 						}
15838 						ASSERT(err != 0);
15839 						mp1 = ipsq_pending_mp_get(ipsq,
15840 						    &connp);
15841 						ASSERT(mp1 != NULL);
15842 					} else {
15843 						/* conn has started closing */
15844 						err = EINTR;
15845 					}
15846 				} else { /* Non XRESOLV interface */
15847 					(void) ipif_resolver_up(ipif,
15848 					    Res_act_initial);
15849 					err = ipif_up_done_v6(ipif);
15850 				}
15851 			}
15852 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15853 			/*
15854 			 * ARP and other v4 external resolvers.
15855 			 * Leave the pending mblk intact so that
15856 			 * the ioctl completes in ip_rput().
15857 			 */
15858 			mutex_enter(&connp->conn_lock);
15859 			mutex_enter(&ill->ill_lock);
15860 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15861 			mutex_exit(&ill->ill_lock);
15862 			mutex_exit(&connp->conn_lock);
15863 			if (success) {
15864 				err = ipif_resolver_up(ipif, Res_act_initial);
15865 				if (err == EINPROGRESS) {
15866 					freemsg(mp);
15867 					return;
15868 				}
15869 				ASSERT(err != 0);
15870 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15871 			} else {
15872 				/* The conn has started closing */
15873 				err = EINTR;
15874 			}
15875 		} else {
15876 			/*
15877 			 * This one is complete. Reply to pending ioctl.
15878 			 */
15879 			(void) ipif_resolver_up(ipif, Res_act_initial);
15880 			err = ipif_up_done(ipif);
15881 		}
15882 
15883 		if ((err == 0) && (ill->ill_up_ipifs)) {
15884 			err = ill_up_ipifs(ill, q, mp1);
15885 			if (err == EINPROGRESS) {
15886 				freemsg(mp);
15887 				return;
15888 			}
15889 		}
15890 
15891 		if (ill->ill_up_ipifs) {
15892 			ill_group_cleanup(ill);
15893 		}
15894 
15895 		break;
15896 	case DL_NOTIFY_IND: {
15897 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15898 		ire_t *ire;
15899 		boolean_t need_ire_walk_v4 = B_FALSE;
15900 		boolean_t need_ire_walk_v6 = B_FALSE;
15901 
15902 		switch (notify->dl_notification) {
15903 		case DL_NOTE_PHYS_ADDR:
15904 			err = ill_set_phys_addr(ill, mp);
15905 			break;
15906 
15907 		case DL_NOTE_FASTPATH_FLUSH:
15908 			ill_fastpath_flush(ill);
15909 			break;
15910 
15911 		case DL_NOTE_SDU_SIZE:
15912 			/*
15913 			 * Change the MTU size of the interface, of all
15914 			 * attached ipif's, and of all relevant ire's.  The
15915 			 * new value's a uint32_t at notify->dl_data.
15916 			 * Mtu change Vs. new ire creation - protocol below.
15917 			 *
15918 			 * a Mark the ipif as IPIF_CHANGING.
15919 			 * b Set the new mtu in the ipif.
15920 			 * c Change the ire_max_frag on all affected ires
15921 			 * d Unmark the IPIF_CHANGING
15922 			 *
15923 			 * To see how the protocol works, assume an interface
15924 			 * route is also being added simultaneously by
15925 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15926 			 * the ire. If the ire is created before step a,
15927 			 * it will be cleaned up by step c. If the ire is
15928 			 * created after step d, it will see the new value of
15929 			 * ipif_mtu. Any attempt to create the ire between
15930 			 * steps a to d will fail because of the IPIF_CHANGING
15931 			 * flag. Note that ire_create() is passed a pointer to
15932 			 * the ipif_mtu, and not the value. During ire_add
15933 			 * under the bucket lock, the ire_max_frag of the
15934 			 * new ire being created is set from the ipif/ire from
15935 			 * which it is being derived.
15936 			 */
15937 			mutex_enter(&ill->ill_lock);
15938 			ill->ill_max_frag = (uint_t)notify->dl_data;
15939 
15940 			/*
15941 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15942 			 * leave it alone
15943 			 */
15944 			if (ill->ill_mtu_userspecified) {
15945 				mutex_exit(&ill->ill_lock);
15946 				break;
15947 			}
15948 			ill->ill_max_mtu = ill->ill_max_frag;
15949 			if (ill->ill_isv6) {
15950 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15951 					ill->ill_max_mtu = IPV6_MIN_MTU;
15952 			} else {
15953 				if (ill->ill_max_mtu < IP_MIN_MTU)
15954 					ill->ill_max_mtu = IP_MIN_MTU;
15955 			}
15956 			for (ipif = ill->ill_ipif; ipif != NULL;
15957 			    ipif = ipif->ipif_next) {
15958 				/*
15959 				 * Don't override the mtu if the user
15960 				 * has explicitly set it.
15961 				 */
15962 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15963 					continue;
15964 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15965 				if (ipif->ipif_isv6)
15966 					ire = ipif_to_ire_v6(ipif);
15967 				else
15968 					ire = ipif_to_ire(ipif);
15969 				if (ire != NULL) {
15970 					ire->ire_max_frag = ipif->ipif_mtu;
15971 					ire_refrele(ire);
15972 				}
15973 				if (ipif->ipif_flags & IPIF_UP) {
15974 					if (ill->ill_isv6)
15975 						need_ire_walk_v6 = B_TRUE;
15976 					else
15977 						need_ire_walk_v4 = B_TRUE;
15978 				}
15979 			}
15980 			mutex_exit(&ill->ill_lock);
15981 			if (need_ire_walk_v4)
15982 				ire_walk_v4(ill_mtu_change, (char *)ill,
15983 				    ALL_ZONES, ipst);
15984 			if (need_ire_walk_v6)
15985 				ire_walk_v6(ill_mtu_change, (char *)ill,
15986 				    ALL_ZONES, ipst);
15987 			break;
15988 		case DL_NOTE_LINK_UP:
15989 		case DL_NOTE_LINK_DOWN: {
15990 			/*
15991 			 * We are writer. ill / phyint / ipsq assocs stable.
15992 			 * The RUNNING flag reflects the state of the link.
15993 			 */
15994 			phyint_t *phyint = ill->ill_phyint;
15995 			uint64_t new_phyint_flags;
15996 			boolean_t changed = B_FALSE;
15997 			boolean_t went_up;
15998 
15999 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16000 			mutex_enter(&phyint->phyint_lock);
16001 			new_phyint_flags = went_up ?
16002 			    phyint->phyint_flags | PHYI_RUNNING :
16003 			    phyint->phyint_flags & ~PHYI_RUNNING;
16004 			if (new_phyint_flags != phyint->phyint_flags) {
16005 				phyint->phyint_flags = new_phyint_flags;
16006 				changed = B_TRUE;
16007 			}
16008 			mutex_exit(&phyint->phyint_lock);
16009 			/*
16010 			 * ill_restart_dad handles the DAD restart and routing
16011 			 * socket notification logic.
16012 			 */
16013 			if (changed) {
16014 				ill_restart_dad(phyint->phyint_illv4, went_up);
16015 				ill_restart_dad(phyint->phyint_illv6, went_up);
16016 			}
16017 			break;
16018 		}
16019 		case DL_NOTE_PROMISC_ON_PHYS:
16020 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16021 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16022 			mutex_enter(&ill->ill_lock);
16023 			ill->ill_promisc_on_phys = B_TRUE;
16024 			mutex_exit(&ill->ill_lock);
16025 			break;
16026 		case DL_NOTE_PROMISC_OFF_PHYS:
16027 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16028 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16029 			mutex_enter(&ill->ill_lock);
16030 			ill->ill_promisc_on_phys = B_FALSE;
16031 			mutex_exit(&ill->ill_lock);
16032 			break;
16033 		case DL_NOTE_CAPAB_RENEG:
16034 			/*
16035 			 * Something changed on the driver side.
16036 			 * It wants us to renegotiate the capabilities
16037 			 * on this ill. One possible cause is the aggregation
16038 			 * interface under us where a port got added or
16039 			 * went away.
16040 			 *
16041 			 * If the capability negotiation is already done
16042 			 * or is in progress, reset the capabilities and
16043 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16044 			 * so that when the ack comes back, we can start
16045 			 * the renegotiation process.
16046 			 *
16047 			 * Note that if ill_capab_reneg is already B_TRUE
16048 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16049 			 * the capability resetting request has been sent
16050 			 * and the renegotiation has not been started yet;
16051 			 * nothing needs to be done in this case.
16052 			 */
16053 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16054 				ill_capability_reset(ill);
16055 				ill->ill_capab_reneg = B_TRUE;
16056 			}
16057 			break;
16058 		default:
16059 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16060 			    "type 0x%x for DL_NOTIFY_IND\n",
16061 			    notify->dl_notification));
16062 			break;
16063 		}
16064 
16065 		/*
16066 		 * As this is an asynchronous operation, we
16067 		 * should not call ill_dlpi_done
16068 		 */
16069 		break;
16070 	}
16071 	case DL_NOTIFY_ACK: {
16072 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16073 
16074 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16075 			ill->ill_note_link = 1;
16076 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16077 		break;
16078 	}
16079 	case DL_PHYS_ADDR_ACK: {
16080 		/*
16081 		 * As part of plumbing the interface via SIOCSLIFNAME,
16082 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16083 		 * whose answers we receive here.  As each answer is received,
16084 		 * we call ill_dlpi_done() to dispatch the next request as
16085 		 * we're processing the current one.  Once all answers have
16086 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16087 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16088 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16089 		 * available, but we know the ioctl is pending on ill_wq.)
16090 		 */
16091 		uint_t paddrlen, paddroff;
16092 
16093 		paddrreq = ill->ill_phys_addr_pend;
16094 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16095 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16096 
16097 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16098 		if (paddrreq == DL_IPV6_TOKEN) {
16099 			/*
16100 			 * bcopy to low-order bits of ill_token
16101 			 *
16102 			 * XXX Temporary hack - currently, all known tokens
16103 			 * are 64 bits, so I'll cheat for the moment.
16104 			 */
16105 			bcopy(mp->b_rptr + paddroff,
16106 			    &ill->ill_token.s6_addr32[2], paddrlen);
16107 			ill->ill_token_length = paddrlen;
16108 			break;
16109 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16110 			ASSERT(ill->ill_nd_lla_mp == NULL);
16111 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16112 			mp = NULL;
16113 			break;
16114 		}
16115 
16116 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16117 		ASSERT(ill->ill_phys_addr_mp == NULL);
16118 		if (!ill->ill_ifname_pending)
16119 			break;
16120 		ill->ill_ifname_pending = 0;
16121 		if (!ioctl_aborted)
16122 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16123 		if (mp1 != NULL) {
16124 			ASSERT(connp == NULL);
16125 			q = ill->ill_wq;
16126 		}
16127 		/*
16128 		 * If any error acks received during the plumbing sequence,
16129 		 * ill_ifname_pending_err will be set. Break out and send up
16130 		 * the error to the pending ioctl.
16131 		 */
16132 		if (ill->ill_ifname_pending_err != 0) {
16133 			err = ill->ill_ifname_pending_err;
16134 			ill->ill_ifname_pending_err = 0;
16135 			break;
16136 		}
16137 
16138 		ill->ill_phys_addr_mp = mp;
16139 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16140 		mp = NULL;
16141 
16142 		/*
16143 		 * If paddrlen is zero, the DLPI provider doesn't support
16144 		 * physical addresses.  The other two tests were historical
16145 		 * workarounds for bugs in our former PPP implementation, but
16146 		 * now other things have grown dependencies on them -- e.g.,
16147 		 * the tun module specifies a dl_addr_length of zero in its
16148 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16149 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16150 		 * but only after careful testing ensures that all dependent
16151 		 * broken DLPI providers have been fixed.
16152 		 */
16153 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16154 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16155 			ill->ill_phys_addr = NULL;
16156 		} else if (paddrlen != ill->ill_phys_addr_length) {
16157 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16158 			    paddrlen, ill->ill_phys_addr_length));
16159 			err = EINVAL;
16160 			break;
16161 		}
16162 
16163 		if (ill->ill_nd_lla_mp == NULL) {
16164 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16165 				err = ENOMEM;
16166 				break;
16167 			}
16168 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16169 		}
16170 
16171 		/*
16172 		 * Set the interface token.  If the zeroth interface address
16173 		 * is unspecified, then set it to the link local address.
16174 		 */
16175 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16176 			(void) ill_setdefaulttoken(ill);
16177 
16178 		ASSERT(ill->ill_ipif->ipif_id == 0);
16179 		if (ipif != NULL &&
16180 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16181 			(void) ipif_setlinklocal(ipif);
16182 		}
16183 		break;
16184 	}
16185 	case DL_OK_ACK:
16186 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16187 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16188 		    dloa->dl_correct_primitive));
16189 		switch (dloa->dl_correct_primitive) {
16190 		case DL_PROMISCON_REQ:
16191 		case DL_PROMISCOFF_REQ:
16192 		case DL_ENABMULTI_REQ:
16193 		case DL_DISABMULTI_REQ:
16194 		case DL_UNBIND_REQ:
16195 		case DL_ATTACH_REQ:
16196 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16197 			break;
16198 		}
16199 		break;
16200 	default:
16201 		break;
16202 	}
16203 
16204 	freemsg(mp);
16205 	if (mp1 != NULL) {
16206 		/*
16207 		 * The operation must complete without EINPROGRESS
16208 		 * since ipsq_pending_mp_get() has removed the mblk
16209 		 * from ipsq_pending_mp.  Otherwise, the operation
16210 		 * will be stuck forever in the ipsq.
16211 		 */
16212 		ASSERT(err != EINPROGRESS);
16213 
16214 		switch (ipsq->ipsq_current_ioctl) {
16215 		case 0:
16216 			ipsq_current_finish(ipsq);
16217 			break;
16218 
16219 		case SIOCLIFADDIF:
16220 		case SIOCSLIFNAME:
16221 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16222 			break;
16223 
16224 		default:
16225 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16226 			break;
16227 		}
16228 	}
16229 }
16230 
16231 /*
16232  * ip_rput_other is called by ip_rput to handle messages modifying the global
16233  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16234  */
16235 /* ARGSUSED */
16236 void
16237 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16238 {
16239 	ill_t		*ill;
16240 	struct iocblk	*iocp;
16241 	mblk_t		*mp1;
16242 	conn_t		*connp = NULL;
16243 
16244 	ip1dbg(("ip_rput_other "));
16245 	ill = (ill_t *)q->q_ptr;
16246 	/*
16247 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16248 	 * in which case ipsq is NULL.
16249 	 */
16250 	if (ipsq != NULL) {
16251 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16252 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16253 	}
16254 
16255 	switch (mp->b_datap->db_type) {
16256 	case M_ERROR:
16257 	case M_HANGUP:
16258 		/*
16259 		 * The device has a problem.  We force the ILL down.  It can
16260 		 * be brought up again manually using SIOCSIFFLAGS (via
16261 		 * ifconfig or equivalent).
16262 		 */
16263 		ASSERT(ipsq != NULL);
16264 		if (mp->b_rptr < mp->b_wptr)
16265 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16266 		if (ill->ill_error == 0)
16267 			ill->ill_error = ENXIO;
16268 		if (!ill_down_start(q, mp))
16269 			return;
16270 		ipif_all_down_tail(ipsq, q, mp, NULL);
16271 		break;
16272 	case M_IOCACK:
16273 		iocp = (struct iocblk *)mp->b_rptr;
16274 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16275 		switch (iocp->ioc_cmd) {
16276 		case SIOCSTUNPARAM:
16277 		case OSIOCSTUNPARAM:
16278 			ASSERT(ipsq != NULL);
16279 			/*
16280 			 * Finish socket ioctl passed through to tun.
16281 			 * We should have an IOCTL waiting on this.
16282 			 */
16283 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16284 			if (ill->ill_isv6) {
16285 				struct iftun_req *ta;
16286 
16287 				/*
16288 				 * if a source or destination is
16289 				 * being set, try and set the link
16290 				 * local address for the tunnel
16291 				 */
16292 				ta = (struct iftun_req *)mp->b_cont->
16293 				    b_cont->b_rptr;
16294 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16295 					ipif_set_tun_llink(ill, ta);
16296 				}
16297 
16298 			}
16299 			if (mp1 != NULL) {
16300 				/*
16301 				 * Now copy back the b_next/b_prev used by
16302 				 * mi code for the mi_copy* functions.
16303 				 * See ip_sioctl_tunparam() for the reason.
16304 				 * Also protect against missing b_cont.
16305 				 */
16306 				if (mp->b_cont != NULL) {
16307 					mp->b_cont->b_next =
16308 					    mp1->b_cont->b_next;
16309 					mp->b_cont->b_prev =
16310 					    mp1->b_cont->b_prev;
16311 				}
16312 				inet_freemsg(mp1);
16313 				ASSERT(connp != NULL);
16314 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16315 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16316 			} else {
16317 				ASSERT(connp == NULL);
16318 				putnext(q, mp);
16319 			}
16320 			break;
16321 		case SIOCGTUNPARAM:
16322 		case OSIOCGTUNPARAM:
16323 			/*
16324 			 * This is really M_IOCDATA from the tunnel driver.
16325 			 * convert back and complete the ioctl.
16326 			 * We should have an IOCTL waiting on this.
16327 			 */
16328 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16329 			if (mp1) {
16330 				/*
16331 				 * Now copy back the b_next/b_prev used by
16332 				 * mi code for the mi_copy* functions.
16333 				 * See ip_sioctl_tunparam() for the reason.
16334 				 * Also protect against missing b_cont.
16335 				 */
16336 				if (mp->b_cont != NULL) {
16337 					mp->b_cont->b_next =
16338 					    mp1->b_cont->b_next;
16339 					mp->b_cont->b_prev =
16340 					    mp1->b_cont->b_prev;
16341 				}
16342 				inet_freemsg(mp1);
16343 				if (iocp->ioc_error == 0)
16344 					mp->b_datap->db_type = M_IOCDATA;
16345 				ASSERT(connp != NULL);
16346 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16347 				    iocp->ioc_error, COPYOUT, NULL);
16348 			} else {
16349 				ASSERT(connp == NULL);
16350 				putnext(q, mp);
16351 			}
16352 			break;
16353 		default:
16354 			break;
16355 		}
16356 		break;
16357 	case M_IOCNAK:
16358 		iocp = (struct iocblk *)mp->b_rptr;
16359 
16360 		switch (iocp->ioc_cmd) {
16361 		int mode;
16362 
16363 		case DL_IOC_HDR_INFO:
16364 			/*
16365 			 * If this was the first attempt turn of the
16366 			 * fastpath probing.
16367 			 */
16368 			mutex_enter(&ill->ill_lock);
16369 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16370 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16371 				mutex_exit(&ill->ill_lock);
16372 				ill_fastpath_nack(ill);
16373 				ip1dbg(("ip_rput: DLPI fastpath off on "
16374 				    "interface %s\n",
16375 				    ill->ill_name));
16376 			} else {
16377 				mutex_exit(&ill->ill_lock);
16378 			}
16379 			freemsg(mp);
16380 			break;
16381 		case SIOCSTUNPARAM:
16382 		case OSIOCSTUNPARAM:
16383 			ASSERT(ipsq != NULL);
16384 			/*
16385 			 * Finish socket ioctl passed through to tun
16386 			 * We should have an IOCTL waiting on this.
16387 			 */
16388 			/* FALLTHRU */
16389 		case SIOCGTUNPARAM:
16390 		case OSIOCGTUNPARAM:
16391 			/*
16392 			 * This is really M_IOCDATA from the tunnel driver.
16393 			 * convert back and complete the ioctl.
16394 			 * We should have an IOCTL waiting on this.
16395 			 */
16396 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16397 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16398 				mp1 = ill_pending_mp_get(ill, &connp,
16399 				    iocp->ioc_id);
16400 				mode = COPYOUT;
16401 				ipsq = NULL;
16402 			} else {
16403 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16404 				mode = NO_COPYOUT;
16405 			}
16406 			if (mp1 != NULL) {
16407 				/*
16408 				 * Now copy back the b_next/b_prev used by
16409 				 * mi code for the mi_copy* functions.
16410 				 * See ip_sioctl_tunparam() for the reason.
16411 				 * Also protect against missing b_cont.
16412 				 */
16413 				if (mp->b_cont != NULL) {
16414 					mp->b_cont->b_next =
16415 					    mp1->b_cont->b_next;
16416 					mp->b_cont->b_prev =
16417 					    mp1->b_cont->b_prev;
16418 				}
16419 				inet_freemsg(mp1);
16420 				if (iocp->ioc_error == 0)
16421 					iocp->ioc_error = EINVAL;
16422 				ASSERT(connp != NULL);
16423 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16424 				    iocp->ioc_error, mode, ipsq);
16425 			} else {
16426 				ASSERT(connp == NULL);
16427 				putnext(q, mp);
16428 			}
16429 			break;
16430 		default:
16431 			break;
16432 		}
16433 	default:
16434 		break;
16435 	}
16436 }
16437 
16438 /*
16439  * NOTE : This function does not ire_refrele the ire argument passed in.
16440  *
16441  * IPQoS notes
16442  * IP policy is invoked twice for a forwarded packet, once on the read side
16443  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16444  * enabled. An additional parameter, in_ill, has been added for this purpose.
16445  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16446  * because ip_mroute drops this information.
16447  *
16448  */
16449 void
16450 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16451 {
16452 	uint32_t	old_pkt_len;
16453 	uint32_t	pkt_len;
16454 	queue_t	*q;
16455 	uint32_t	sum;
16456 #define	rptr	((uchar_t *)ipha)
16457 	uint32_t	max_frag;
16458 	uint32_t	ill_index;
16459 	ill_t		*out_ill;
16460 	mib2_ipIfStatsEntry_t *mibptr;
16461 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16462 
16463 	/* Get the ill_index of the incoming ILL */
16464 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16465 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16466 
16467 	/* Initiate Read side IPPF processing */
16468 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16469 		ip_process(IPP_FWD_IN, &mp, ill_index);
16470 		if (mp == NULL) {
16471 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16472 			    "during IPPF processing\n"));
16473 			return;
16474 		}
16475 	}
16476 
16477 	/* Adjust the checksum to reflect the ttl decrement. */
16478 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16479 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16480 
16481 	if (ipha->ipha_ttl-- <= 1) {
16482 		if (ip_csum_hdr(ipha)) {
16483 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16484 			goto drop_pkt;
16485 		}
16486 		/*
16487 		 * Note: ire_stq this will be NULL for multicast
16488 		 * datagrams using the long path through arp (the IRE
16489 		 * is not an IRE_CACHE). This should not cause
16490 		 * problems since we don't generate ICMP errors for
16491 		 * multicast packets.
16492 		 */
16493 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16494 		q = ire->ire_stq;
16495 		if (q != NULL) {
16496 			/* Sent by forwarding path, and router is global zone */
16497 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16498 			    GLOBAL_ZONEID, ipst);
16499 		} else
16500 			freemsg(mp);
16501 		return;
16502 	}
16503 
16504 	/*
16505 	 * Don't forward if the interface is down
16506 	 */
16507 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16508 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16509 		ip2dbg(("ip_rput_forward:interface is down\n"));
16510 		goto drop_pkt;
16511 	}
16512 
16513 	/* Get the ill_index of the outgoing ILL */
16514 	out_ill = ire_to_ill(ire);
16515 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16516 
16517 	DTRACE_PROBE4(ip4__forwarding__start,
16518 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16519 
16520 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16521 	    ipst->ips_ipv4firewall_forwarding,
16522 	    in_ill, out_ill, ipha, mp, mp, ipst);
16523 
16524 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16525 
16526 	if (mp == NULL)
16527 		return;
16528 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16529 
16530 	if (is_system_labeled()) {
16531 		mblk_t *mp1;
16532 
16533 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16534 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16535 			goto drop_pkt;
16536 		}
16537 		/* Size may have changed */
16538 		mp = mp1;
16539 		ipha = (ipha_t *)mp->b_rptr;
16540 		pkt_len = ntohs(ipha->ipha_length);
16541 	}
16542 
16543 	/* Check if there are options to update */
16544 	if (!IS_SIMPLE_IPH(ipha)) {
16545 		if (ip_csum_hdr(ipha)) {
16546 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16547 			goto drop_pkt;
16548 		}
16549 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16550 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16551 			return;
16552 		}
16553 
16554 		ipha->ipha_hdr_checksum = 0;
16555 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16556 	}
16557 	max_frag = ire->ire_max_frag;
16558 	if (pkt_len > max_frag) {
16559 		/*
16560 		 * It needs fragging on its way out.  We haven't
16561 		 * verified the header checksum yet.  Since we
16562 		 * are going to put a surely good checksum in the
16563 		 * outgoing header, we have to make sure that it
16564 		 * was good coming in.
16565 		 */
16566 		if (ip_csum_hdr(ipha)) {
16567 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16568 			goto drop_pkt;
16569 		}
16570 		/* Initiate Write side IPPF processing */
16571 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16572 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16573 			if (mp == NULL) {
16574 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16575 				    " during IPPF processing\n"));
16576 				return;
16577 			}
16578 		}
16579 		/*
16580 		 * Handle labeled packet resizing.
16581 		 *
16582 		 * If we have added a label, inform ip_wput_frag() of its
16583 		 * effect on the MTU for ICMP messages.
16584 		 */
16585 		if (pkt_len > old_pkt_len) {
16586 			uint32_t secopt_size;
16587 
16588 			secopt_size = pkt_len - old_pkt_len;
16589 			if (secopt_size < max_frag)
16590 				max_frag -= secopt_size;
16591 		}
16592 
16593 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16594 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16595 		return;
16596 	}
16597 
16598 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16599 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16600 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16601 	    ipst->ips_ipv4firewall_physical_out,
16602 	    NULL, out_ill, ipha, mp, mp, ipst);
16603 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16604 	if (mp == NULL)
16605 		return;
16606 
16607 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16608 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16609 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16610 	/* ip_xmit_v4 always consumes the packet */
16611 	return;
16612 
16613 drop_pkt:;
16614 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16615 	freemsg(mp);
16616 #undef	rptr
16617 }
16618 
16619 void
16620 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16621 {
16622 	ire_t	*ire;
16623 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16624 
16625 	ASSERT(!ipif->ipif_isv6);
16626 	/*
16627 	 * Find an IRE which matches the destination and the outgoing
16628 	 * queue in the cache table. All we need is an IRE_CACHE which
16629 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16630 	 * then it is enough to have some IRE_CACHE in the group.
16631 	 */
16632 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16633 		dst = ipif->ipif_pp_dst_addr;
16634 
16635 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16636 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16637 	if (ire == NULL) {
16638 		/*
16639 		 * Mark this packet to make it be delivered to
16640 		 * ip_rput_forward after the new ire has been
16641 		 * created.
16642 		 */
16643 		mp->b_prev = NULL;
16644 		mp->b_next = mp;
16645 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16646 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16647 	} else {
16648 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16649 		IRE_REFRELE(ire);
16650 	}
16651 }
16652 
16653 /* Update any source route, record route or timestamp options */
16654 static int
16655 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16656 {
16657 	ipoptp_t	opts;
16658 	uchar_t		*opt;
16659 	uint8_t		optval;
16660 	uint8_t		optlen;
16661 	ipaddr_t	dst;
16662 	uint32_t	ts;
16663 	ire_t		*dst_ire = NULL;
16664 	ire_t		*tmp_ire = NULL;
16665 	timestruc_t	now;
16666 
16667 	ip2dbg(("ip_rput_forward_options\n"));
16668 	dst = ipha->ipha_dst;
16669 	for (optval = ipoptp_first(&opts, ipha);
16670 	    optval != IPOPT_EOL;
16671 	    optval = ipoptp_next(&opts)) {
16672 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16673 		opt = opts.ipoptp_cur;
16674 		optlen = opts.ipoptp_len;
16675 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16676 		    optval, opts.ipoptp_len));
16677 		switch (optval) {
16678 			uint32_t off;
16679 		case IPOPT_SSRR:
16680 		case IPOPT_LSRR:
16681 			/* Check if adminstratively disabled */
16682 			if (!ipst->ips_ip_forward_src_routed) {
16683 				if (ire->ire_stq != NULL) {
16684 					/*
16685 					 * Sent by forwarding path, and router
16686 					 * is global zone
16687 					 */
16688 					icmp_unreachable(ire->ire_stq, mp,
16689 					    ICMP_SOURCE_ROUTE_FAILED,
16690 					    GLOBAL_ZONEID, ipst);
16691 				} else {
16692 					ip0dbg(("ip_rput_forward_options: "
16693 					    "unable to send unreach\n"));
16694 					freemsg(mp);
16695 				}
16696 				return (-1);
16697 			}
16698 
16699 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16700 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16701 			if (dst_ire == NULL) {
16702 				/*
16703 				 * Must be partial since ip_rput_options
16704 				 * checked for strict.
16705 				 */
16706 				break;
16707 			}
16708 			off = opt[IPOPT_OFFSET];
16709 			off--;
16710 		redo_srr:
16711 			if (optlen < IP_ADDR_LEN ||
16712 			    off > optlen - IP_ADDR_LEN) {
16713 				/* End of source route */
16714 				ip1dbg((
16715 				    "ip_rput_forward_options: end of SR\n"));
16716 				ire_refrele(dst_ire);
16717 				break;
16718 			}
16719 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16720 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16721 			    IP_ADDR_LEN);
16722 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16723 			    ntohl(dst)));
16724 
16725 			/*
16726 			 * Check if our address is present more than
16727 			 * once as consecutive hops in source route.
16728 			 */
16729 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16730 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16731 			if (tmp_ire != NULL) {
16732 				ire_refrele(tmp_ire);
16733 				off += IP_ADDR_LEN;
16734 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16735 				goto redo_srr;
16736 			}
16737 			ipha->ipha_dst = dst;
16738 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16739 			ire_refrele(dst_ire);
16740 			break;
16741 		case IPOPT_RR:
16742 			off = opt[IPOPT_OFFSET];
16743 			off--;
16744 			if (optlen < IP_ADDR_LEN ||
16745 			    off > optlen - IP_ADDR_LEN) {
16746 				/* No more room - ignore */
16747 				ip1dbg((
16748 				    "ip_rput_forward_options: end of RR\n"));
16749 				break;
16750 			}
16751 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16752 			    IP_ADDR_LEN);
16753 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16754 			break;
16755 		case IPOPT_TS:
16756 			/* Insert timestamp if there is room */
16757 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16758 			case IPOPT_TS_TSONLY:
16759 				off = IPOPT_TS_TIMELEN;
16760 				break;
16761 			case IPOPT_TS_PRESPEC:
16762 			case IPOPT_TS_PRESPEC_RFC791:
16763 				/* Verify that the address matched */
16764 				off = opt[IPOPT_OFFSET] - 1;
16765 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16766 				dst_ire = ire_ctable_lookup(dst, 0,
16767 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16768 				    MATCH_IRE_TYPE, ipst);
16769 				if (dst_ire == NULL) {
16770 					/* Not for us */
16771 					break;
16772 				}
16773 				ire_refrele(dst_ire);
16774 				/* FALLTHRU */
16775 			case IPOPT_TS_TSANDADDR:
16776 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16777 				break;
16778 			default:
16779 				/*
16780 				 * ip_*put_options should have already
16781 				 * dropped this packet.
16782 				 */
16783 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16784 				    "unknown IT - bug in ip_rput_options?\n");
16785 				return (0);	/* Keep "lint" happy */
16786 			}
16787 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16788 				/* Increase overflow counter */
16789 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16790 				opt[IPOPT_POS_OV_FLG] =
16791 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16792 				    (off << 4));
16793 				break;
16794 			}
16795 			off = opt[IPOPT_OFFSET] - 1;
16796 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16797 			case IPOPT_TS_PRESPEC:
16798 			case IPOPT_TS_PRESPEC_RFC791:
16799 			case IPOPT_TS_TSANDADDR:
16800 				bcopy(&ire->ire_src_addr,
16801 				    (char *)opt + off, IP_ADDR_LEN);
16802 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16803 				/* FALLTHRU */
16804 			case IPOPT_TS_TSONLY:
16805 				off = opt[IPOPT_OFFSET] - 1;
16806 				/* Compute # of milliseconds since midnight */
16807 				gethrestime(&now);
16808 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16809 				    now.tv_nsec / (NANOSEC / MILLISEC);
16810 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16811 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16812 				break;
16813 			}
16814 			break;
16815 		}
16816 	}
16817 	return (0);
16818 }
16819 
16820 /*
16821  * This is called after processing at least one of AH/ESP headers.
16822  *
16823  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16824  * the actual, physical interface on which the packet was received,
16825  * but, when ip_strict_dst_multihoming is set to 1, could be the
16826  * interface which had the ipha_dst configured when the packet went
16827  * through ip_rput. The ill_index corresponding to the recv_ill
16828  * is saved in ipsec_in_rill_index
16829  *
16830  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16831  * cannot assume "ire" points to valid data for any IPv6 cases.
16832  */
16833 void
16834 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16835 {
16836 	mblk_t *mp;
16837 	ipaddr_t dst;
16838 	in6_addr_t *v6dstp;
16839 	ipha_t *ipha;
16840 	ip6_t *ip6h;
16841 	ipsec_in_t *ii;
16842 	boolean_t ill_need_rele = B_FALSE;
16843 	boolean_t rill_need_rele = B_FALSE;
16844 	boolean_t ire_need_rele = B_FALSE;
16845 	netstack_t	*ns;
16846 	ip_stack_t	*ipst;
16847 
16848 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16849 	ASSERT(ii->ipsec_in_ill_index != 0);
16850 	ns = ii->ipsec_in_ns;
16851 	ASSERT(ii->ipsec_in_ns != NULL);
16852 	ipst = ns->netstack_ip;
16853 
16854 	mp = ipsec_mp->b_cont;
16855 	ASSERT(mp != NULL);
16856 
16857 
16858 	if (ill == NULL) {
16859 		ASSERT(recv_ill == NULL);
16860 		/*
16861 		 * We need to get the original queue on which ip_rput_local
16862 		 * or ip_rput_data_v6 was called.
16863 		 */
16864 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16865 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16866 		ill_need_rele = B_TRUE;
16867 
16868 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16869 			recv_ill = ill_lookup_on_ifindex(
16870 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16871 			    NULL, NULL, NULL, NULL, ipst);
16872 			rill_need_rele = B_TRUE;
16873 		} else {
16874 			recv_ill = ill;
16875 		}
16876 
16877 		if ((ill == NULL) || (recv_ill == NULL)) {
16878 			ip0dbg(("ip_fanout_proto_again: interface "
16879 			    "disappeared\n"));
16880 			if (ill != NULL)
16881 				ill_refrele(ill);
16882 			if (recv_ill != NULL)
16883 				ill_refrele(recv_ill);
16884 			freemsg(ipsec_mp);
16885 			return;
16886 		}
16887 	}
16888 
16889 	ASSERT(ill != NULL && recv_ill != NULL);
16890 
16891 	if (mp->b_datap->db_type == M_CTL) {
16892 		/*
16893 		 * AH/ESP is returning the ICMP message after
16894 		 * removing their headers. Fanout again till
16895 		 * it gets to the right protocol.
16896 		 */
16897 		if (ii->ipsec_in_v4) {
16898 			icmph_t *icmph;
16899 			int iph_hdr_length;
16900 			int hdr_length;
16901 
16902 			ipha = (ipha_t *)mp->b_rptr;
16903 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16904 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16905 			ipha = (ipha_t *)&icmph[1];
16906 			hdr_length = IPH_HDR_LENGTH(ipha);
16907 			/*
16908 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16909 			 * Reset the type to M_DATA.
16910 			 */
16911 			mp->b_datap->db_type = M_DATA;
16912 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16913 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16914 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16915 		} else {
16916 			icmp6_t *icmp6;
16917 			int hdr_length;
16918 
16919 			ip6h = (ip6_t *)mp->b_rptr;
16920 			/* Don't call hdr_length_v6() unless you have to. */
16921 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16922 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16923 			else
16924 				hdr_length = IPV6_HDR_LEN;
16925 
16926 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16927 			/*
16928 			 * icmp_inbound_error_fanout_v6 may need to do
16929 			 * pullupmsg.  Reset the type to M_DATA.
16930 			 */
16931 			mp->b_datap->db_type = M_DATA;
16932 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16933 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16934 		}
16935 		if (ill_need_rele)
16936 			ill_refrele(ill);
16937 		if (rill_need_rele)
16938 			ill_refrele(recv_ill);
16939 		return;
16940 	}
16941 
16942 	if (ii->ipsec_in_v4) {
16943 		ipha = (ipha_t *)mp->b_rptr;
16944 		dst = ipha->ipha_dst;
16945 		if (CLASSD(dst)) {
16946 			/*
16947 			 * Multicast has to be delivered to all streams.
16948 			 */
16949 			dst = INADDR_BROADCAST;
16950 		}
16951 
16952 		if (ire == NULL) {
16953 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16954 			    MBLK_GETLABEL(mp), ipst);
16955 			if (ire == NULL) {
16956 				if (ill_need_rele)
16957 					ill_refrele(ill);
16958 				if (rill_need_rele)
16959 					ill_refrele(recv_ill);
16960 				ip1dbg(("ip_fanout_proto_again: "
16961 				    "IRE not found"));
16962 				freemsg(ipsec_mp);
16963 				return;
16964 			}
16965 			ire_need_rele = B_TRUE;
16966 		}
16967 
16968 		switch (ipha->ipha_protocol) {
16969 			case IPPROTO_UDP:
16970 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16971 				    recv_ill);
16972 				if (ire_need_rele)
16973 					ire_refrele(ire);
16974 				break;
16975 			case IPPROTO_TCP:
16976 				if (!ire_need_rele)
16977 					IRE_REFHOLD(ire);
16978 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16979 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16980 				IRE_REFRELE(ire);
16981 				if (mp != NULL)
16982 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16983 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16984 				break;
16985 			case IPPROTO_SCTP:
16986 				if (!ire_need_rele)
16987 					IRE_REFHOLD(ire);
16988 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16989 				    ipsec_mp, 0, ill->ill_rq, dst);
16990 				break;
16991 			default:
16992 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16993 				    recv_ill, B_FALSE);
16994 				if (ire_need_rele)
16995 					ire_refrele(ire);
16996 				break;
16997 		}
16998 	} else {
16999 		uint32_t rput_flags = 0;
17000 
17001 		ip6h = (ip6_t *)mp->b_rptr;
17002 		v6dstp = &ip6h->ip6_dst;
17003 		/*
17004 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17005 		 * address.
17006 		 *
17007 		 * Currently, we don't store that state in the IPSEC_IN
17008 		 * message, and we may need to.
17009 		 */
17010 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17011 		    IP6_IN_LLMCAST : 0);
17012 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17013 		    NULL, NULL);
17014 	}
17015 	if (ill_need_rele)
17016 		ill_refrele(ill);
17017 	if (rill_need_rele)
17018 		ill_refrele(recv_ill);
17019 }
17020 
17021 /*
17022  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17023  * returns 'true' if there are still fragments left on the queue, in
17024  * which case we restart the timer.
17025  */
17026 void
17027 ill_frag_timer(void *arg)
17028 {
17029 	ill_t	*ill = (ill_t *)arg;
17030 	boolean_t frag_pending;
17031 	ip_stack_t	*ipst = ill->ill_ipst;
17032 
17033 	mutex_enter(&ill->ill_lock);
17034 	ASSERT(!ill->ill_fragtimer_executing);
17035 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17036 		ill->ill_frag_timer_id = 0;
17037 		mutex_exit(&ill->ill_lock);
17038 		return;
17039 	}
17040 	ill->ill_fragtimer_executing = 1;
17041 	mutex_exit(&ill->ill_lock);
17042 
17043 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17044 
17045 	/*
17046 	 * Restart the timer, if we have fragments pending or if someone
17047 	 * wanted us to be scheduled again.
17048 	 */
17049 	mutex_enter(&ill->ill_lock);
17050 	ill->ill_fragtimer_executing = 0;
17051 	ill->ill_frag_timer_id = 0;
17052 	if (frag_pending || ill->ill_fragtimer_needrestart)
17053 		ill_frag_timer_start(ill);
17054 	mutex_exit(&ill->ill_lock);
17055 }
17056 
17057 void
17058 ill_frag_timer_start(ill_t *ill)
17059 {
17060 	ip_stack_t	*ipst = ill->ill_ipst;
17061 
17062 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17063 
17064 	/* If the ill is closing or opening don't proceed */
17065 	if (ill->ill_state_flags & ILL_CONDEMNED)
17066 		return;
17067 
17068 	if (ill->ill_fragtimer_executing) {
17069 		/*
17070 		 * ill_frag_timer is currently executing. Just record the
17071 		 * the fact that we want the timer to be restarted.
17072 		 * ill_frag_timer will post a timeout before it returns,
17073 		 * ensuring it will be called again.
17074 		 */
17075 		ill->ill_fragtimer_needrestart = 1;
17076 		return;
17077 	}
17078 
17079 	if (ill->ill_frag_timer_id == 0) {
17080 		/*
17081 		 * The timer is neither running nor is the timeout handler
17082 		 * executing. Post a timeout so that ill_frag_timer will be
17083 		 * called
17084 		 */
17085 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17086 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17087 		ill->ill_fragtimer_needrestart = 0;
17088 	}
17089 }
17090 
17091 /*
17092  * This routine is needed for loopback when forwarding multicasts.
17093  *
17094  * IPQoS Notes:
17095  * IPPF processing is done in fanout routines.
17096  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17097  * processing for IPsec packets is done when it comes back in clear.
17098  * NOTE : The callers of this function need to do the ire_refrele for the
17099  *	  ire that is being passed in.
17100  */
17101 void
17102 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17103     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17104 {
17105 	ill_t	*ill = (ill_t *)q->q_ptr;
17106 	uint32_t	sum;
17107 	uint32_t	u1;
17108 	uint32_t	u2;
17109 	int		hdr_length;
17110 	boolean_t	mctl_present;
17111 	mblk_t		*first_mp = mp;
17112 	mblk_t		*hada_mp = NULL;
17113 	ipha_t		*inner_ipha;
17114 	ip_stack_t	*ipst;
17115 
17116 	ASSERT(recv_ill != NULL);
17117 	ipst = recv_ill->ill_ipst;
17118 
17119 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17120 	    "ip_rput_locl_start: q %p", q);
17121 
17122 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17123 	ASSERT(ill != NULL);
17124 
17125 
17126 #define	rptr	((uchar_t *)ipha)
17127 #define	iphs	((uint16_t *)ipha)
17128 
17129 	/*
17130 	 * no UDP or TCP packet should come here anymore.
17131 	 */
17132 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17133 	    ipha->ipha_protocol != IPPROTO_UDP);
17134 
17135 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17136 	if (mctl_present &&
17137 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17138 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17139 
17140 		/*
17141 		 * It's an IPsec accelerated packet.
17142 		 * Keep a pointer to the data attributes around until
17143 		 * we allocate the ipsec_info_t.
17144 		 */
17145 		IPSECHW_DEBUG(IPSECHW_PKT,
17146 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17147 		hada_mp = first_mp;
17148 		hada_mp->b_cont = NULL;
17149 		/*
17150 		 * Since it is accelerated, it comes directly from
17151 		 * the ill and the data attributes is followed by
17152 		 * the packet data.
17153 		 */
17154 		ASSERT(mp->b_datap->db_type != M_CTL);
17155 		first_mp = mp;
17156 		mctl_present = B_FALSE;
17157 	}
17158 
17159 	/*
17160 	 * IF M_CTL is not present, then ipsec_in_is_secure
17161 	 * should return B_TRUE. There is a case where loopback
17162 	 * packets has an M_CTL in the front with all the
17163 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17164 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17165 	 * packets never comes here, it is safe to ASSERT the
17166 	 * following.
17167 	 */
17168 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17169 
17170 	/*
17171 	 * Also, we should never have an mctl_present if this is an
17172 	 * ESP-in-UDP packet.
17173 	 */
17174 	ASSERT(!mctl_present || !esp_in_udp_packet);
17175 
17176 
17177 	/* u1 is # words of IP options */
17178 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17179 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17180 
17181 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17182 		if (u1) {
17183 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17184 				if (hada_mp != NULL)
17185 					freemsg(hada_mp);
17186 				return;
17187 			}
17188 		} else {
17189 			/* Check the IP header checksum.  */
17190 #define	uph	((uint16_t *)ipha)
17191 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17192 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17193 #undef  uph
17194 			/* finish doing IP checksum */
17195 			sum = (sum & 0xFFFF) + (sum >> 16);
17196 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17197 			if (sum && sum != 0xFFFF) {
17198 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17199 				goto drop_pkt;
17200 			}
17201 		}
17202 	}
17203 
17204 	/*
17205 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17206 	 * might be called more than once for secure packets, count only
17207 	 * the first time.
17208 	 */
17209 	if (!mctl_present) {
17210 		UPDATE_IB_PKT_COUNT(ire);
17211 		ire->ire_last_used_time = lbolt;
17212 	}
17213 
17214 	/* Check for fragmentation offset. */
17215 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17216 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17217 	if (u1) {
17218 		/*
17219 		 * We re-assemble fragments before we do the AH/ESP
17220 		 * processing. Thus, M_CTL should not be present
17221 		 * while we are re-assembling.
17222 		 */
17223 		ASSERT(!mctl_present);
17224 		ASSERT(first_mp == mp);
17225 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17226 			return;
17227 		}
17228 		/*
17229 		 * Make sure that first_mp points back to mp as
17230 		 * the mp we came in with could have changed in
17231 		 * ip_rput_fragment().
17232 		 */
17233 		ipha = (ipha_t *)mp->b_rptr;
17234 		first_mp = mp;
17235 	}
17236 
17237 	/*
17238 	 * Clear hardware checksumming flag as it is currently only
17239 	 * used by TCP and UDP.
17240 	 */
17241 	DB_CKSUMFLAGS(mp) = 0;
17242 
17243 	/* Now we have a complete datagram, destined for this machine. */
17244 	u1 = IPH_HDR_LENGTH(ipha);
17245 	switch (ipha->ipha_protocol) {
17246 	case IPPROTO_ICMP: {
17247 		ire_t		*ire_zone;
17248 		ilm_t		*ilm;
17249 		mblk_t		*mp1;
17250 		zoneid_t	last_zoneid;
17251 
17252 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17253 			ASSERT(ire->ire_type == IRE_BROADCAST);
17254 			/*
17255 			 * In the multicast case, applications may have joined
17256 			 * the group from different zones, so we need to deliver
17257 			 * the packet to each of them. Loop through the
17258 			 * multicast memberships structures (ilm) on the receive
17259 			 * ill and send a copy of the packet up each matching
17260 			 * one. However, we don't do this for multicasts sent on
17261 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17262 			 * they must stay in the sender's zone.
17263 			 *
17264 			 * ilm_add_v6() ensures that ilms in the same zone are
17265 			 * contiguous in the ill_ilm list. We use this property
17266 			 * to avoid sending duplicates needed when two
17267 			 * applications in the same zone join the same group on
17268 			 * different logical interfaces: we ignore the ilm if
17269 			 * its zoneid is the same as the last matching one.
17270 			 * In addition, the sending of the packet for
17271 			 * ire_zoneid is delayed until all of the other ilms
17272 			 * have been exhausted.
17273 			 */
17274 			last_zoneid = -1;
17275 			ILM_WALKER_HOLD(recv_ill);
17276 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17277 			    ilm = ilm->ilm_next) {
17278 				if ((ilm->ilm_flags & ILM_DELETED) ||
17279 				    ipha->ipha_dst != ilm->ilm_addr ||
17280 				    ilm->ilm_zoneid == last_zoneid ||
17281 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17282 				    ilm->ilm_zoneid == ALL_ZONES ||
17283 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17284 					continue;
17285 				mp1 = ip_copymsg(first_mp);
17286 				if (mp1 == NULL)
17287 					continue;
17288 				icmp_inbound(q, mp1, B_TRUE, ill,
17289 				    0, sum, mctl_present, B_TRUE,
17290 				    recv_ill, ilm->ilm_zoneid);
17291 				last_zoneid = ilm->ilm_zoneid;
17292 			}
17293 			ILM_WALKER_RELE(recv_ill);
17294 		} else if (ire->ire_type == IRE_BROADCAST) {
17295 			/*
17296 			 * In the broadcast case, there may be many zones
17297 			 * which need a copy of the packet delivered to them.
17298 			 * There is one IRE_BROADCAST per broadcast address
17299 			 * and per zone; we walk those using a helper function.
17300 			 * In addition, the sending of the packet for ire is
17301 			 * delayed until all of the other ires have been
17302 			 * processed.
17303 			 */
17304 			IRB_REFHOLD(ire->ire_bucket);
17305 			ire_zone = NULL;
17306 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17307 			    ire)) != NULL) {
17308 				mp1 = ip_copymsg(first_mp);
17309 				if (mp1 == NULL)
17310 					continue;
17311 
17312 				UPDATE_IB_PKT_COUNT(ire_zone);
17313 				ire_zone->ire_last_used_time = lbolt;
17314 				icmp_inbound(q, mp1, B_TRUE, ill,
17315 				    0, sum, mctl_present, B_TRUE,
17316 				    recv_ill, ire_zone->ire_zoneid);
17317 			}
17318 			IRB_REFRELE(ire->ire_bucket);
17319 		}
17320 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17321 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17322 		    ire->ire_zoneid);
17323 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17324 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17325 		return;
17326 	}
17327 	case IPPROTO_IGMP:
17328 		/*
17329 		 * If we are not willing to accept IGMP packets in clear,
17330 		 * then check with global policy.
17331 		 */
17332 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17333 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17334 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17335 			if (first_mp == NULL)
17336 				return;
17337 		}
17338 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17339 			freemsg(first_mp);
17340 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17341 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17342 			return;
17343 		}
17344 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17345 			/* Bad packet - discarded by igmp_input */
17346 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17347 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17348 			if (mctl_present)
17349 				freeb(first_mp);
17350 			return;
17351 		}
17352 		/*
17353 		 * igmp_input() may have returned the pulled up message.
17354 		 * So first_mp and ipha need to be reinitialized.
17355 		 */
17356 		ipha = (ipha_t *)mp->b_rptr;
17357 		if (mctl_present)
17358 			first_mp->b_cont = mp;
17359 		else
17360 			first_mp = mp;
17361 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17362 		    connf_head != NULL) {
17363 			/* No user-level listener for IGMP packets */
17364 			goto drop_pkt;
17365 		}
17366 		/* deliver to local raw users */
17367 		break;
17368 	case IPPROTO_PIM:
17369 		/*
17370 		 * If we are not willing to accept PIM packets in clear,
17371 		 * then check with global policy.
17372 		 */
17373 		if (ipst->ips_pim_accept_clear_messages == 0) {
17374 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17375 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17376 			if (first_mp == NULL)
17377 				return;
17378 		}
17379 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17380 			freemsg(first_mp);
17381 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17382 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17383 			return;
17384 		}
17385 		if (pim_input(q, mp, ill) != 0) {
17386 			/* Bad packet - discarded by pim_input */
17387 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17388 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17389 			if (mctl_present)
17390 				freeb(first_mp);
17391 			return;
17392 		}
17393 
17394 		/*
17395 		 * pim_input() may have pulled up the message so ipha needs to
17396 		 * be reinitialized.
17397 		 */
17398 		ipha = (ipha_t *)mp->b_rptr;
17399 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17400 		    connf_head != NULL) {
17401 			/* No user-level listener for PIM packets */
17402 			goto drop_pkt;
17403 		}
17404 		/* deliver to local raw users */
17405 		break;
17406 	case IPPROTO_ENCAP:
17407 		/*
17408 		 * Handle self-encapsulated packets (IP-in-IP where
17409 		 * the inner addresses == the outer addresses).
17410 		 */
17411 		hdr_length = IPH_HDR_LENGTH(ipha);
17412 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17413 		    mp->b_wptr) {
17414 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17415 			    sizeof (ipha_t) - mp->b_rptr)) {
17416 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17417 				freemsg(first_mp);
17418 				return;
17419 			}
17420 			ipha = (ipha_t *)mp->b_rptr;
17421 		}
17422 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17423 		/*
17424 		 * Check the sanity of the inner IP header.
17425 		 */
17426 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17427 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17428 			freemsg(first_mp);
17429 			return;
17430 		}
17431 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17432 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17433 			freemsg(first_mp);
17434 			return;
17435 		}
17436 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17437 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17438 			ipsec_in_t *ii;
17439 
17440 			/*
17441 			 * Self-encapsulated tunnel packet. Remove
17442 			 * the outer IP header and fanout again.
17443 			 * We also need to make sure that the inner
17444 			 * header is pulled up until options.
17445 			 */
17446 			mp->b_rptr = (uchar_t *)inner_ipha;
17447 			ipha = inner_ipha;
17448 			hdr_length = IPH_HDR_LENGTH(ipha);
17449 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17450 				if (!pullupmsg(mp, (uchar_t *)ipha +
17451 				    + hdr_length - mp->b_rptr)) {
17452 					freemsg(first_mp);
17453 					return;
17454 				}
17455 				ipha = (ipha_t *)mp->b_rptr;
17456 			}
17457 			if (!mctl_present) {
17458 				ASSERT(first_mp == mp);
17459 				/*
17460 				 * This means that somebody is sending
17461 				 * Self-encapsualted packets without AH/ESP.
17462 				 * If AH/ESP was present, we would have already
17463 				 * allocated the first_mp.
17464 				 */
17465 				first_mp = ipsec_in_alloc(B_TRUE,
17466 				    ipst->ips_netstack);
17467 				if (first_mp == NULL) {
17468 					ip1dbg(("ip_proto_input: IPSEC_IN "
17469 					    "allocation failure.\n"));
17470 					BUMP_MIB(ill->ill_ip_mib,
17471 					    ipIfStatsInDiscards);
17472 					freemsg(mp);
17473 					return;
17474 				}
17475 				first_mp->b_cont = mp;
17476 			}
17477 			/*
17478 			 * We generally store the ill_index if we need to
17479 			 * do IPsec processing as we lose the ill queue when
17480 			 * we come back. But in this case, we never should
17481 			 * have to store the ill_index here as it should have
17482 			 * been stored previously when we processed the
17483 			 * AH/ESP header in this routine or for non-ipsec
17484 			 * cases, we still have the queue. But for some bad
17485 			 * packets from the wire, we can get to IPsec after
17486 			 * this and we better store the index for that case.
17487 			 */
17488 			ill = (ill_t *)q->q_ptr;
17489 			ii = (ipsec_in_t *)first_mp->b_rptr;
17490 			ii->ipsec_in_ill_index =
17491 			    ill->ill_phyint->phyint_ifindex;
17492 			ii->ipsec_in_rill_index =
17493 			    recv_ill->ill_phyint->phyint_ifindex;
17494 			if (ii->ipsec_in_decaps) {
17495 				/*
17496 				 * This packet is self-encapsulated multiple
17497 				 * times. We don't want to recurse infinitely.
17498 				 * To keep it simple, drop the packet.
17499 				 */
17500 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17501 				freemsg(first_mp);
17502 				return;
17503 			}
17504 			ii->ipsec_in_decaps = B_TRUE;
17505 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17506 			    ire);
17507 			return;
17508 		}
17509 		break;
17510 	case IPPROTO_AH:
17511 	case IPPROTO_ESP: {
17512 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17513 
17514 		/*
17515 		 * Fast path for AH/ESP. If this is the first time
17516 		 * we are sending a datagram to AH/ESP, allocate
17517 		 * a IPSEC_IN message and prepend it. Otherwise,
17518 		 * just fanout.
17519 		 */
17520 
17521 		int ipsec_rc;
17522 		ipsec_in_t *ii;
17523 		netstack_t *ns = ipst->ips_netstack;
17524 
17525 		IP_STAT(ipst, ipsec_proto_ahesp);
17526 		if (!mctl_present) {
17527 			ASSERT(first_mp == mp);
17528 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17529 			if (first_mp == NULL) {
17530 				ip1dbg(("ip_proto_input: IPSEC_IN "
17531 				    "allocation failure.\n"));
17532 				freemsg(hada_mp); /* okay ifnull */
17533 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17534 				freemsg(mp);
17535 				return;
17536 			}
17537 			/*
17538 			 * Store the ill_index so that when we come back
17539 			 * from IPsec we ride on the same queue.
17540 			 */
17541 			ill = (ill_t *)q->q_ptr;
17542 			ii = (ipsec_in_t *)first_mp->b_rptr;
17543 			ii->ipsec_in_ill_index =
17544 			    ill->ill_phyint->phyint_ifindex;
17545 			ii->ipsec_in_rill_index =
17546 			    recv_ill->ill_phyint->phyint_ifindex;
17547 			first_mp->b_cont = mp;
17548 			/*
17549 			 * Cache hardware acceleration info.
17550 			 */
17551 			if (hada_mp != NULL) {
17552 				IPSECHW_DEBUG(IPSECHW_PKT,
17553 				    ("ip_rput_local: caching data attr.\n"));
17554 				ii->ipsec_in_accelerated = B_TRUE;
17555 				ii->ipsec_in_da = hada_mp;
17556 				hada_mp = NULL;
17557 			}
17558 		} else {
17559 			ii = (ipsec_in_t *)first_mp->b_rptr;
17560 		}
17561 
17562 		if (!ipsec_loaded(ipss)) {
17563 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17564 			    ire->ire_zoneid, ipst);
17565 			return;
17566 		}
17567 
17568 		ns = ipst->ips_netstack;
17569 		/* select inbound SA and have IPsec process the pkt */
17570 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17571 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17572 			boolean_t esp_in_udp_sa;
17573 			if (esph == NULL)
17574 				return;
17575 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17576 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17577 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17578 			    IPSA_F_NATT) != 0);
17579 			/*
17580 			 * The following is a fancy, but quick, way of saying:
17581 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17582 			 *    OR
17583 			 * ESP SA and ESP-in-UDP packet --> drop
17584 			 */
17585 			if (esp_in_udp_sa != esp_in_udp_packet) {
17586 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17587 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17588 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17589 				    &ns->netstack_ipsec->ipsec_dropper);
17590 				return;
17591 			}
17592 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17593 			    first_mp, esph);
17594 		} else {
17595 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17596 			if (ah == NULL)
17597 				return;
17598 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17599 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17600 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17601 			    first_mp, ah);
17602 		}
17603 
17604 		switch (ipsec_rc) {
17605 		case IPSEC_STATUS_SUCCESS:
17606 			break;
17607 		case IPSEC_STATUS_FAILED:
17608 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17609 			/* FALLTHRU */
17610 		case IPSEC_STATUS_PENDING:
17611 			return;
17612 		}
17613 		/* we're done with IPsec processing, send it up */
17614 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17615 		return;
17616 	}
17617 	default:
17618 		break;
17619 	}
17620 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17621 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17622 		    ire->ire_zoneid));
17623 		goto drop_pkt;
17624 	}
17625 	/*
17626 	 * Handle protocols with which IP is less intimate.  There
17627 	 * can be more than one stream bound to a particular
17628 	 * protocol.  When this is the case, each one gets a copy
17629 	 * of any incoming packets.
17630 	 */
17631 	ip_fanout_proto(q, first_mp, ill, ipha,
17632 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17633 	    B_TRUE, recv_ill, ire->ire_zoneid);
17634 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17635 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17636 	return;
17637 
17638 drop_pkt:
17639 	freemsg(first_mp);
17640 	if (hada_mp != NULL)
17641 		freeb(hada_mp);
17642 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17643 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17644 #undef	rptr
17645 #undef  iphs
17646 
17647 }
17648 
17649 /*
17650  * Update any source route, record route or timestamp options.
17651  * Check that we are at end of strict source route.
17652  * The options have already been checked for sanity in ip_rput_options().
17653  */
17654 static boolean_t
17655 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17656     ip_stack_t *ipst)
17657 {
17658 	ipoptp_t	opts;
17659 	uchar_t		*opt;
17660 	uint8_t		optval;
17661 	uint8_t		optlen;
17662 	ipaddr_t	dst;
17663 	uint32_t	ts;
17664 	ire_t		*dst_ire;
17665 	timestruc_t	now;
17666 	zoneid_t	zoneid;
17667 	ill_t		*ill;
17668 
17669 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17670 
17671 	ip2dbg(("ip_rput_local_options\n"));
17672 
17673 	for (optval = ipoptp_first(&opts, ipha);
17674 	    optval != IPOPT_EOL;
17675 	    optval = ipoptp_next(&opts)) {
17676 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17677 		opt = opts.ipoptp_cur;
17678 		optlen = opts.ipoptp_len;
17679 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17680 		    optval, optlen));
17681 		switch (optval) {
17682 			uint32_t off;
17683 		case IPOPT_SSRR:
17684 		case IPOPT_LSRR:
17685 			off = opt[IPOPT_OFFSET];
17686 			off--;
17687 			if (optlen < IP_ADDR_LEN ||
17688 			    off > optlen - IP_ADDR_LEN) {
17689 				/* End of source route */
17690 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17691 				break;
17692 			}
17693 			/*
17694 			 * This will only happen if two consecutive entries
17695 			 * in the source route contains our address or if
17696 			 * it is a packet with a loose source route which
17697 			 * reaches us before consuming the whole source route
17698 			 */
17699 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17700 			if (optval == IPOPT_SSRR) {
17701 				goto bad_src_route;
17702 			}
17703 			/*
17704 			 * Hack: instead of dropping the packet truncate the
17705 			 * source route to what has been used by filling the
17706 			 * rest with IPOPT_NOP.
17707 			 */
17708 			opt[IPOPT_OLEN] = (uint8_t)off;
17709 			while (off < optlen) {
17710 				opt[off++] = IPOPT_NOP;
17711 			}
17712 			break;
17713 		case IPOPT_RR:
17714 			off = opt[IPOPT_OFFSET];
17715 			off--;
17716 			if (optlen < IP_ADDR_LEN ||
17717 			    off > optlen - IP_ADDR_LEN) {
17718 				/* No more room - ignore */
17719 				ip1dbg((
17720 				    "ip_rput_local_options: end of RR\n"));
17721 				break;
17722 			}
17723 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17724 			    IP_ADDR_LEN);
17725 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17726 			break;
17727 		case IPOPT_TS:
17728 			/* Insert timestamp if there is romm */
17729 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17730 			case IPOPT_TS_TSONLY:
17731 				off = IPOPT_TS_TIMELEN;
17732 				break;
17733 			case IPOPT_TS_PRESPEC:
17734 			case IPOPT_TS_PRESPEC_RFC791:
17735 				/* Verify that the address matched */
17736 				off = opt[IPOPT_OFFSET] - 1;
17737 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17738 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17739 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17740 				    ipst);
17741 				if (dst_ire == NULL) {
17742 					/* Not for us */
17743 					break;
17744 				}
17745 				ire_refrele(dst_ire);
17746 				/* FALLTHRU */
17747 			case IPOPT_TS_TSANDADDR:
17748 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17749 				break;
17750 			default:
17751 				/*
17752 				 * ip_*put_options should have already
17753 				 * dropped this packet.
17754 				 */
17755 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17756 				    "unknown IT - bug in ip_rput_options?\n");
17757 				return (B_TRUE);	/* Keep "lint" happy */
17758 			}
17759 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17760 				/* Increase overflow counter */
17761 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17762 				opt[IPOPT_POS_OV_FLG] =
17763 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17764 				    (off << 4));
17765 				break;
17766 			}
17767 			off = opt[IPOPT_OFFSET] - 1;
17768 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17769 			case IPOPT_TS_PRESPEC:
17770 			case IPOPT_TS_PRESPEC_RFC791:
17771 			case IPOPT_TS_TSANDADDR:
17772 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17773 				    IP_ADDR_LEN);
17774 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17775 				/* FALLTHRU */
17776 			case IPOPT_TS_TSONLY:
17777 				off = opt[IPOPT_OFFSET] - 1;
17778 				/* Compute # of milliseconds since midnight */
17779 				gethrestime(&now);
17780 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17781 				    now.tv_nsec / (NANOSEC / MILLISEC);
17782 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17783 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17784 				break;
17785 			}
17786 			break;
17787 		}
17788 	}
17789 	return (B_TRUE);
17790 
17791 bad_src_route:
17792 	q = WR(q);
17793 	if (q->q_next != NULL)
17794 		ill = q->q_ptr;
17795 	else
17796 		ill = NULL;
17797 
17798 	/* make sure we clear any indication of a hardware checksum */
17799 	DB_CKSUMFLAGS(mp) = 0;
17800 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17801 	if (zoneid == ALL_ZONES)
17802 		freemsg(mp);
17803 	else
17804 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17805 	return (B_FALSE);
17806 
17807 }
17808 
17809 /*
17810  * Process IP options in an inbound packet.  If an option affects the
17811  * effective destination address, return the next hop address via dstp.
17812  * Returns -1 if something fails in which case an ICMP error has been sent
17813  * and mp freed.
17814  */
17815 static int
17816 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17817     ip_stack_t *ipst)
17818 {
17819 	ipoptp_t	opts;
17820 	uchar_t		*opt;
17821 	uint8_t		optval;
17822 	uint8_t		optlen;
17823 	ipaddr_t	dst;
17824 	intptr_t	code = 0;
17825 	ire_t		*ire = NULL;
17826 	zoneid_t	zoneid;
17827 	ill_t		*ill;
17828 
17829 	ip2dbg(("ip_rput_options\n"));
17830 	dst = ipha->ipha_dst;
17831 	for (optval = ipoptp_first(&opts, ipha);
17832 	    optval != IPOPT_EOL;
17833 	    optval = ipoptp_next(&opts)) {
17834 		opt = opts.ipoptp_cur;
17835 		optlen = opts.ipoptp_len;
17836 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17837 		    optval, optlen));
17838 		/*
17839 		 * Note: we need to verify the checksum before we
17840 		 * modify anything thus this routine only extracts the next
17841 		 * hop dst from any source route.
17842 		 */
17843 		switch (optval) {
17844 			uint32_t off;
17845 		case IPOPT_SSRR:
17846 		case IPOPT_LSRR:
17847 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17848 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17849 			if (ire == NULL) {
17850 				if (optval == IPOPT_SSRR) {
17851 					ip1dbg(("ip_rput_options: not next"
17852 					    " strict source route 0x%x\n",
17853 					    ntohl(dst)));
17854 					code = (char *)&ipha->ipha_dst -
17855 					    (char *)ipha;
17856 					goto param_prob; /* RouterReq's */
17857 				}
17858 				ip2dbg(("ip_rput_options: "
17859 				    "not next source route 0x%x\n",
17860 				    ntohl(dst)));
17861 				break;
17862 			}
17863 			ire_refrele(ire);
17864 
17865 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17866 				ip1dbg((
17867 				    "ip_rput_options: bad option offset\n"));
17868 				code = (char *)&opt[IPOPT_OLEN] -
17869 				    (char *)ipha;
17870 				goto param_prob;
17871 			}
17872 			off = opt[IPOPT_OFFSET];
17873 			off--;
17874 		redo_srr:
17875 			if (optlen < IP_ADDR_LEN ||
17876 			    off > optlen - IP_ADDR_LEN) {
17877 				/* End of source route */
17878 				ip1dbg(("ip_rput_options: end of SR\n"));
17879 				break;
17880 			}
17881 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17882 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17883 			    ntohl(dst)));
17884 
17885 			/*
17886 			 * Check if our address is present more than
17887 			 * once as consecutive hops in source route.
17888 			 * XXX verify per-interface ip_forwarding
17889 			 * for source route?
17890 			 */
17891 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17892 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17893 
17894 			if (ire != NULL) {
17895 				ire_refrele(ire);
17896 				off += IP_ADDR_LEN;
17897 				goto redo_srr;
17898 			}
17899 
17900 			if (dst == htonl(INADDR_LOOPBACK)) {
17901 				ip1dbg(("ip_rput_options: loopback addr in "
17902 				    "source route!\n"));
17903 				goto bad_src_route;
17904 			}
17905 			/*
17906 			 * For strict: verify that dst is directly
17907 			 * reachable.
17908 			 */
17909 			if (optval == IPOPT_SSRR) {
17910 				ire = ire_ftable_lookup(dst, 0, 0,
17911 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17912 				    MBLK_GETLABEL(mp),
17913 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17914 				if (ire == NULL) {
17915 					ip1dbg(("ip_rput_options: SSRR not "
17916 					    "directly reachable: 0x%x\n",
17917 					    ntohl(dst)));
17918 					goto bad_src_route;
17919 				}
17920 				ire_refrele(ire);
17921 			}
17922 			/*
17923 			 * Defer update of the offset and the record route
17924 			 * until the packet is forwarded.
17925 			 */
17926 			break;
17927 		case IPOPT_RR:
17928 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17929 				ip1dbg((
17930 				    "ip_rput_options: bad option offset\n"));
17931 				code = (char *)&opt[IPOPT_OLEN] -
17932 				    (char *)ipha;
17933 				goto param_prob;
17934 			}
17935 			break;
17936 		case IPOPT_TS:
17937 			/*
17938 			 * Verify that length >= 5 and that there is either
17939 			 * room for another timestamp or that the overflow
17940 			 * counter is not maxed out.
17941 			 */
17942 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17943 			if (optlen < IPOPT_MINLEN_IT) {
17944 				goto param_prob;
17945 			}
17946 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17947 				ip1dbg((
17948 				    "ip_rput_options: bad option offset\n"));
17949 				code = (char *)&opt[IPOPT_OFFSET] -
17950 				    (char *)ipha;
17951 				goto param_prob;
17952 			}
17953 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17954 			case IPOPT_TS_TSONLY:
17955 				off = IPOPT_TS_TIMELEN;
17956 				break;
17957 			case IPOPT_TS_TSANDADDR:
17958 			case IPOPT_TS_PRESPEC:
17959 			case IPOPT_TS_PRESPEC_RFC791:
17960 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17961 				break;
17962 			default:
17963 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17964 				    (char *)ipha;
17965 				goto param_prob;
17966 			}
17967 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17968 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17969 				/*
17970 				 * No room and the overflow counter is 15
17971 				 * already.
17972 				 */
17973 				goto param_prob;
17974 			}
17975 			break;
17976 		}
17977 	}
17978 
17979 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17980 		*dstp = dst;
17981 		return (0);
17982 	}
17983 
17984 	ip1dbg(("ip_rput_options: error processing IP options."));
17985 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17986 
17987 param_prob:
17988 	q = WR(q);
17989 	if (q->q_next != NULL)
17990 		ill = q->q_ptr;
17991 	else
17992 		ill = NULL;
17993 
17994 	/* make sure we clear any indication of a hardware checksum */
17995 	DB_CKSUMFLAGS(mp) = 0;
17996 	/* Don't know whether this is for non-global or global/forwarding */
17997 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17998 	if (zoneid == ALL_ZONES)
17999 		freemsg(mp);
18000 	else
18001 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18002 	return (-1);
18003 
18004 bad_src_route:
18005 	q = WR(q);
18006 	if (q->q_next != NULL)
18007 		ill = q->q_ptr;
18008 	else
18009 		ill = NULL;
18010 
18011 	/* make sure we clear any indication of a hardware checksum */
18012 	DB_CKSUMFLAGS(mp) = 0;
18013 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18014 	if (zoneid == ALL_ZONES)
18015 		freemsg(mp);
18016 	else
18017 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18018 	return (-1);
18019 }
18020 
18021 /*
18022  * IP & ICMP info in >=14 msg's ...
18023  *  - ip fixed part (mib2_ip_t)
18024  *  - icmp fixed part (mib2_icmp_t)
18025  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18026  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18027  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18028  *  - ipRouteAttributeTable (ip 102)	labeled routes
18029  *  - ip multicast membership (ip_member_t)
18030  *  - ip multicast source filtering (ip_grpsrc_t)
18031  *  - igmp fixed part (struct igmpstat)
18032  *  - multicast routing stats (struct mrtstat)
18033  *  - multicast routing vifs (array of struct vifctl)
18034  *  - multicast routing routes (array of struct mfcctl)
18035  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18036  *					One per ill plus one generic
18037  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18038  *					One per ill plus one generic
18039  *  - ipv6RouteEntry			all IPv6 IREs
18040  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18041  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18042  *  - ipv6AddrEntry			all IPv6 ipifs
18043  *  - ipv6 multicast membership (ipv6_member_t)
18044  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18045  *
18046  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18047  *
18048  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18049  * already filled in by the caller.
18050  * Return value of 0 indicates that no messages were sent and caller
18051  * should free mpctl.
18052  */
18053 int
18054 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18055 {
18056 	ip_stack_t *ipst;
18057 	sctp_stack_t *sctps;
18058 
18059 	if (q->q_next != NULL) {
18060 		ipst = ILLQ_TO_IPST(q);
18061 	} else {
18062 		ipst = CONNQ_TO_IPST(q);
18063 	}
18064 	ASSERT(ipst != NULL);
18065 	sctps = ipst->ips_netstack->netstack_sctp;
18066 
18067 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18068 		return (0);
18069 	}
18070 
18071 	/*
18072 	 * For the purposes of the (broken) packet shell use
18073 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18074 	 * to make TCP and UDP appear first in the list of mib items.
18075 	 * TBD: We could expand this and use it in netstat so that
18076 	 * the kernel doesn't have to produce large tables (connections,
18077 	 * routes, etc) when netstat only wants the statistics or a particular
18078 	 * table.
18079 	 */
18080 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18081 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18082 			return (1);
18083 		}
18084 	}
18085 
18086 	if (level != MIB2_TCP) {
18087 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18088 			return (1);
18089 		}
18090 	}
18091 
18092 	if (level != MIB2_UDP) {
18093 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18094 			return (1);
18095 		}
18096 	}
18097 
18098 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18099 	    ipst)) == NULL) {
18100 		return (1);
18101 	}
18102 
18103 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18104 		return (1);
18105 	}
18106 
18107 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18108 		return (1);
18109 	}
18110 
18111 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18112 		return (1);
18113 	}
18114 
18115 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18116 		return (1);
18117 	}
18118 
18119 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18120 		return (1);
18121 	}
18122 
18123 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18124 		return (1);
18125 	}
18126 
18127 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18128 		return (1);
18129 	}
18130 
18131 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18132 		return (1);
18133 	}
18134 
18135 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18136 		return (1);
18137 	}
18138 
18139 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18140 		return (1);
18141 	}
18142 
18143 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18144 		return (1);
18145 	}
18146 
18147 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18148 		return (1);
18149 	}
18150 
18151 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18152 		return (1);
18153 	}
18154 
18155 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18156 		return (1);
18157 	}
18158 
18159 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18160 	if (mpctl == NULL) {
18161 		return (1);
18162 	}
18163 
18164 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18165 		return (1);
18166 	}
18167 	freemsg(mpctl);
18168 	return (1);
18169 }
18170 
18171 
18172 /* Get global (legacy) IPv4 statistics */
18173 static mblk_t *
18174 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18175     ip_stack_t *ipst)
18176 {
18177 	mib2_ip_t		old_ip_mib;
18178 	struct opthdr		*optp;
18179 	mblk_t			*mp2ctl;
18180 
18181 	/*
18182 	 * make a copy of the original message
18183 	 */
18184 	mp2ctl = copymsg(mpctl);
18185 
18186 	/* fixed length IP structure... */
18187 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18188 	optp->level = MIB2_IP;
18189 	optp->name = 0;
18190 	SET_MIB(old_ip_mib.ipForwarding,
18191 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18192 	SET_MIB(old_ip_mib.ipDefaultTTL,
18193 	    (uint32_t)ipst->ips_ip_def_ttl);
18194 	SET_MIB(old_ip_mib.ipReasmTimeout,
18195 	    ipst->ips_ip_g_frag_timeout);
18196 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18197 	    sizeof (mib2_ipAddrEntry_t));
18198 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18199 	    sizeof (mib2_ipRouteEntry_t));
18200 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18201 	    sizeof (mib2_ipNetToMediaEntry_t));
18202 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18203 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18204 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18205 	    sizeof (mib2_ipAttributeEntry_t));
18206 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18207 
18208 	/*
18209 	 * Grab the statistics from the new IP MIB
18210 	 */
18211 	SET_MIB(old_ip_mib.ipInReceives,
18212 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18213 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18214 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18215 	SET_MIB(old_ip_mib.ipForwDatagrams,
18216 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18217 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18218 	    ipmib->ipIfStatsInUnknownProtos);
18219 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18220 	SET_MIB(old_ip_mib.ipInDelivers,
18221 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18222 	SET_MIB(old_ip_mib.ipOutRequests,
18223 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18224 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18225 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18226 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18227 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18228 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18229 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18230 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18231 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18232 
18233 	/* ipRoutingDiscards is not being used */
18234 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18235 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18236 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18237 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18238 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18239 	    ipmib->ipIfStatsReasmDuplicates);
18240 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18241 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18242 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18243 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18244 	SET_MIB(old_ip_mib.rawipInOverflows,
18245 	    ipmib->rawipIfStatsInOverflows);
18246 
18247 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18248 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18249 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18250 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18251 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18252 	    ipmib->ipIfStatsOutSwitchIPVersion);
18253 
18254 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18255 	    (int)sizeof (old_ip_mib))) {
18256 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18257 		    (uint_t)sizeof (old_ip_mib)));
18258 	}
18259 
18260 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18261 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18262 	    (int)optp->level, (int)optp->name, (int)optp->len));
18263 	qreply(q, mpctl);
18264 	return (mp2ctl);
18265 }
18266 
18267 /* Per interface IPv4 statistics */
18268 static mblk_t *
18269 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18270 {
18271 	struct opthdr		*optp;
18272 	mblk_t			*mp2ctl;
18273 	ill_t			*ill;
18274 	ill_walk_context_t	ctx;
18275 	mblk_t			*mp_tail = NULL;
18276 	mib2_ipIfStatsEntry_t	global_ip_mib;
18277 
18278 	/*
18279 	 * Make a copy of the original message
18280 	 */
18281 	mp2ctl = copymsg(mpctl);
18282 
18283 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18284 	optp->level = MIB2_IP;
18285 	optp->name = MIB2_IP_TRAFFIC_STATS;
18286 	/* Include "unknown interface" ip_mib */
18287 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18288 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18289 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18290 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18291 	    (ipst->ips_ip_g_forward ? 1 : 2));
18292 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18293 	    (uint32_t)ipst->ips_ip_def_ttl);
18294 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18295 	    sizeof (mib2_ipIfStatsEntry_t));
18296 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18297 	    sizeof (mib2_ipAddrEntry_t));
18298 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18299 	    sizeof (mib2_ipRouteEntry_t));
18300 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18301 	    sizeof (mib2_ipNetToMediaEntry_t));
18302 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18303 	    sizeof (ip_member_t));
18304 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18305 	    sizeof (ip_grpsrc_t));
18306 
18307 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18308 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18309 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18310 		    "failed to allocate %u bytes\n",
18311 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18312 	}
18313 
18314 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18315 
18316 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18317 	ill = ILL_START_WALK_V4(&ctx, ipst);
18318 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18319 		ill->ill_ip_mib->ipIfStatsIfIndex =
18320 		    ill->ill_phyint->phyint_ifindex;
18321 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18322 		    (ipst->ips_ip_g_forward ? 1 : 2));
18323 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18324 		    (uint32_t)ipst->ips_ip_def_ttl);
18325 
18326 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18327 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18328 		    (char *)ill->ill_ip_mib,
18329 		    (int)sizeof (*ill->ill_ip_mib))) {
18330 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18331 			    "failed to allocate %u bytes\n",
18332 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18333 		}
18334 	}
18335 	rw_exit(&ipst->ips_ill_g_lock);
18336 
18337 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18338 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18339 	    "level %d, name %d, len %d\n",
18340 	    (int)optp->level, (int)optp->name, (int)optp->len));
18341 	qreply(q, mpctl);
18342 
18343 	if (mp2ctl == NULL)
18344 		return (NULL);
18345 
18346 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18347 }
18348 
18349 /* Global IPv4 ICMP statistics */
18350 static mblk_t *
18351 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18352 {
18353 	struct opthdr		*optp;
18354 	mblk_t			*mp2ctl;
18355 
18356 	/*
18357 	 * Make a copy of the original message
18358 	 */
18359 	mp2ctl = copymsg(mpctl);
18360 
18361 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18362 	optp->level = MIB2_ICMP;
18363 	optp->name = 0;
18364 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18365 	    (int)sizeof (ipst->ips_icmp_mib))) {
18366 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18367 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18368 	}
18369 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18370 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18371 	    (int)optp->level, (int)optp->name, (int)optp->len));
18372 	qreply(q, mpctl);
18373 	return (mp2ctl);
18374 }
18375 
18376 /* Global IPv4 IGMP statistics */
18377 static mblk_t *
18378 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18379 {
18380 	struct opthdr		*optp;
18381 	mblk_t			*mp2ctl;
18382 
18383 	/*
18384 	 * make a copy of the original message
18385 	 */
18386 	mp2ctl = copymsg(mpctl);
18387 
18388 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18389 	optp->level = EXPER_IGMP;
18390 	optp->name = 0;
18391 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18392 	    (int)sizeof (ipst->ips_igmpstat))) {
18393 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18394 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18395 	}
18396 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18397 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18398 	    (int)optp->level, (int)optp->name, (int)optp->len));
18399 	qreply(q, mpctl);
18400 	return (mp2ctl);
18401 }
18402 
18403 /* Global IPv4 Multicast Routing statistics */
18404 static mblk_t *
18405 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18406 {
18407 	struct opthdr		*optp;
18408 	mblk_t			*mp2ctl;
18409 
18410 	/*
18411 	 * make a copy of the original message
18412 	 */
18413 	mp2ctl = copymsg(mpctl);
18414 
18415 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18416 	optp->level = EXPER_DVMRP;
18417 	optp->name = 0;
18418 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18419 		ip0dbg(("ip_mroute_stats: failed\n"));
18420 	}
18421 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18422 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18423 	    (int)optp->level, (int)optp->name, (int)optp->len));
18424 	qreply(q, mpctl);
18425 	return (mp2ctl);
18426 }
18427 
18428 /* IPv4 address information */
18429 static mblk_t *
18430 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18431 {
18432 	struct opthdr		*optp;
18433 	mblk_t			*mp2ctl;
18434 	mblk_t			*mp_tail = NULL;
18435 	ill_t			*ill;
18436 	ipif_t			*ipif;
18437 	uint_t			bitval;
18438 	mib2_ipAddrEntry_t	mae;
18439 	zoneid_t		zoneid;
18440 	ill_walk_context_t ctx;
18441 
18442 	/*
18443 	 * make a copy of the original message
18444 	 */
18445 	mp2ctl = copymsg(mpctl);
18446 
18447 	/* ipAddrEntryTable */
18448 
18449 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18450 	optp->level = MIB2_IP;
18451 	optp->name = MIB2_IP_ADDR;
18452 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18453 
18454 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18455 	ill = ILL_START_WALK_V4(&ctx, ipst);
18456 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18457 		for (ipif = ill->ill_ipif; ipif != NULL;
18458 		    ipif = ipif->ipif_next) {
18459 			if (ipif->ipif_zoneid != zoneid &&
18460 			    ipif->ipif_zoneid != ALL_ZONES)
18461 				continue;
18462 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18463 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18464 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18465 
18466 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18467 			    OCTET_LENGTH);
18468 			mae.ipAdEntIfIndex.o_length =
18469 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18470 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18471 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18472 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18473 			mae.ipAdEntInfo.ae_subnet_len =
18474 			    ip_mask_to_plen(ipif->ipif_net_mask);
18475 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18476 			for (bitval = 1;
18477 			    bitval &&
18478 			    !(bitval & ipif->ipif_brd_addr);
18479 			    bitval <<= 1)
18480 				noop;
18481 			mae.ipAdEntBcastAddr = bitval;
18482 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18483 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18484 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18485 			mae.ipAdEntInfo.ae_broadcast_addr =
18486 			    ipif->ipif_brd_addr;
18487 			mae.ipAdEntInfo.ae_pp_dst_addr =
18488 			    ipif->ipif_pp_dst_addr;
18489 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18490 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18491 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18492 
18493 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18494 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18495 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18496 				    "allocate %u bytes\n",
18497 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18498 			}
18499 		}
18500 	}
18501 	rw_exit(&ipst->ips_ill_g_lock);
18502 
18503 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18504 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18505 	    (int)optp->level, (int)optp->name, (int)optp->len));
18506 	qreply(q, mpctl);
18507 	return (mp2ctl);
18508 }
18509 
18510 /* IPv6 address information */
18511 static mblk_t *
18512 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18513 {
18514 	struct opthdr		*optp;
18515 	mblk_t			*mp2ctl;
18516 	mblk_t			*mp_tail = NULL;
18517 	ill_t			*ill;
18518 	ipif_t			*ipif;
18519 	mib2_ipv6AddrEntry_t	mae6;
18520 	zoneid_t		zoneid;
18521 	ill_walk_context_t	ctx;
18522 
18523 	/*
18524 	 * make a copy of the original message
18525 	 */
18526 	mp2ctl = copymsg(mpctl);
18527 
18528 	/* ipv6AddrEntryTable */
18529 
18530 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18531 	optp->level = MIB2_IP6;
18532 	optp->name = MIB2_IP6_ADDR;
18533 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18534 
18535 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18536 	ill = ILL_START_WALK_V6(&ctx, ipst);
18537 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18538 		for (ipif = ill->ill_ipif; ipif != NULL;
18539 		    ipif = ipif->ipif_next) {
18540 			if (ipif->ipif_zoneid != zoneid &&
18541 			    ipif->ipif_zoneid != ALL_ZONES)
18542 				continue;
18543 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18544 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18545 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18546 
18547 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18548 			    OCTET_LENGTH);
18549 			mae6.ipv6AddrIfIndex.o_length =
18550 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18551 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18552 			mae6.ipv6AddrPfxLength =
18553 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18554 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18555 			mae6.ipv6AddrInfo.ae_subnet_len =
18556 			    mae6.ipv6AddrPfxLength;
18557 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18558 
18559 			/* Type: stateless(1), stateful(2), unknown(3) */
18560 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18561 				mae6.ipv6AddrType = 1;
18562 			else
18563 				mae6.ipv6AddrType = 2;
18564 			/* Anycast: true(1), false(2) */
18565 			if (ipif->ipif_flags & IPIF_ANYCAST)
18566 				mae6.ipv6AddrAnycastFlag = 1;
18567 			else
18568 				mae6.ipv6AddrAnycastFlag = 2;
18569 
18570 			/*
18571 			 * Address status: preferred(1), deprecated(2),
18572 			 * invalid(3), inaccessible(4), unknown(5)
18573 			 */
18574 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18575 				mae6.ipv6AddrStatus = 3;
18576 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18577 				mae6.ipv6AddrStatus = 2;
18578 			else
18579 				mae6.ipv6AddrStatus = 1;
18580 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18581 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18582 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18583 			    ipif->ipif_v6pp_dst_addr;
18584 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18585 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18586 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18587 			mae6.ipv6AddrIdentifier = ill->ill_token;
18588 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18589 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18590 			mae6.ipv6AddrRetransmitTime =
18591 			    ill->ill_reachable_retrans_time;
18592 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18593 			    (char *)&mae6,
18594 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18595 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18596 				    "allocate %u bytes\n",
18597 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18598 			}
18599 		}
18600 	}
18601 	rw_exit(&ipst->ips_ill_g_lock);
18602 
18603 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18604 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18605 	    (int)optp->level, (int)optp->name, (int)optp->len));
18606 	qreply(q, mpctl);
18607 	return (mp2ctl);
18608 }
18609 
18610 /* IPv4 multicast group membership. */
18611 static mblk_t *
18612 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18613 {
18614 	struct opthdr		*optp;
18615 	mblk_t			*mp2ctl;
18616 	ill_t			*ill;
18617 	ipif_t			*ipif;
18618 	ilm_t			*ilm;
18619 	ip_member_t		ipm;
18620 	mblk_t			*mp_tail = NULL;
18621 	ill_walk_context_t	ctx;
18622 	zoneid_t		zoneid;
18623 
18624 	/*
18625 	 * make a copy of the original message
18626 	 */
18627 	mp2ctl = copymsg(mpctl);
18628 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18629 
18630 	/* ipGroupMember table */
18631 	optp = (struct opthdr *)&mpctl->b_rptr[
18632 	    sizeof (struct T_optmgmt_ack)];
18633 	optp->level = MIB2_IP;
18634 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18635 
18636 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18637 	ill = ILL_START_WALK_V4(&ctx, ipst);
18638 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18639 		ILM_WALKER_HOLD(ill);
18640 		for (ipif = ill->ill_ipif; ipif != NULL;
18641 		    ipif = ipif->ipif_next) {
18642 			if (ipif->ipif_zoneid != zoneid &&
18643 			    ipif->ipif_zoneid != ALL_ZONES)
18644 				continue;	/* not this zone */
18645 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18646 			    OCTET_LENGTH);
18647 			ipm.ipGroupMemberIfIndex.o_length =
18648 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18649 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18650 				ASSERT(ilm->ilm_ipif != NULL);
18651 				ASSERT(ilm->ilm_ill == NULL);
18652 				if (ilm->ilm_ipif != ipif)
18653 					continue;
18654 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18655 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18656 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18657 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18658 				    (char *)&ipm, (int)sizeof (ipm))) {
18659 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18660 					    "failed to allocate %u bytes\n",
18661 					    (uint_t)sizeof (ipm)));
18662 				}
18663 			}
18664 		}
18665 		ILM_WALKER_RELE(ill);
18666 	}
18667 	rw_exit(&ipst->ips_ill_g_lock);
18668 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18669 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18670 	    (int)optp->level, (int)optp->name, (int)optp->len));
18671 	qreply(q, mpctl);
18672 	return (mp2ctl);
18673 }
18674 
18675 /* IPv6 multicast group membership. */
18676 static mblk_t *
18677 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18678 {
18679 	struct opthdr		*optp;
18680 	mblk_t			*mp2ctl;
18681 	ill_t			*ill;
18682 	ilm_t			*ilm;
18683 	ipv6_member_t		ipm6;
18684 	mblk_t			*mp_tail = NULL;
18685 	ill_walk_context_t	ctx;
18686 	zoneid_t		zoneid;
18687 
18688 	/*
18689 	 * make a copy of the original message
18690 	 */
18691 	mp2ctl = copymsg(mpctl);
18692 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18693 
18694 	/* ip6GroupMember table */
18695 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18696 	optp->level = MIB2_IP6;
18697 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18698 
18699 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18700 	ill = ILL_START_WALK_V6(&ctx, ipst);
18701 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18702 		ILM_WALKER_HOLD(ill);
18703 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18704 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18705 			ASSERT(ilm->ilm_ipif == NULL);
18706 			ASSERT(ilm->ilm_ill != NULL);
18707 			if (ilm->ilm_zoneid != zoneid)
18708 				continue;	/* not this zone */
18709 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18710 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18711 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18712 			if (!snmp_append_data2(mpctl->b_cont,
18713 			    &mp_tail,
18714 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18715 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18716 				    "failed to allocate %u bytes\n",
18717 				    (uint_t)sizeof (ipm6)));
18718 			}
18719 		}
18720 		ILM_WALKER_RELE(ill);
18721 	}
18722 	rw_exit(&ipst->ips_ill_g_lock);
18723 
18724 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18725 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18726 	    (int)optp->level, (int)optp->name, (int)optp->len));
18727 	qreply(q, mpctl);
18728 	return (mp2ctl);
18729 }
18730 
18731 /* IP multicast filtered sources */
18732 static mblk_t *
18733 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18734 {
18735 	struct opthdr		*optp;
18736 	mblk_t			*mp2ctl;
18737 	ill_t			*ill;
18738 	ipif_t			*ipif;
18739 	ilm_t			*ilm;
18740 	ip_grpsrc_t		ips;
18741 	mblk_t			*mp_tail = NULL;
18742 	ill_walk_context_t	ctx;
18743 	zoneid_t		zoneid;
18744 	int			i;
18745 	slist_t			*sl;
18746 
18747 	/*
18748 	 * make a copy of the original message
18749 	 */
18750 	mp2ctl = copymsg(mpctl);
18751 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18752 
18753 	/* ipGroupSource table */
18754 	optp = (struct opthdr *)&mpctl->b_rptr[
18755 	    sizeof (struct T_optmgmt_ack)];
18756 	optp->level = MIB2_IP;
18757 	optp->name = EXPER_IP_GROUP_SOURCES;
18758 
18759 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18760 	ill = ILL_START_WALK_V4(&ctx, ipst);
18761 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18762 		ILM_WALKER_HOLD(ill);
18763 		for (ipif = ill->ill_ipif; ipif != NULL;
18764 		    ipif = ipif->ipif_next) {
18765 			if (ipif->ipif_zoneid != zoneid)
18766 				continue;	/* not this zone */
18767 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18768 			    OCTET_LENGTH);
18769 			ips.ipGroupSourceIfIndex.o_length =
18770 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18771 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18772 				ASSERT(ilm->ilm_ipif != NULL);
18773 				ASSERT(ilm->ilm_ill == NULL);
18774 				sl = ilm->ilm_filter;
18775 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18776 					continue;
18777 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18778 				for (i = 0; i < sl->sl_numsrc; i++) {
18779 					if (!IN6_IS_ADDR_V4MAPPED(
18780 					    &sl->sl_addr[i]))
18781 						continue;
18782 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18783 					    ips.ipGroupSourceAddress);
18784 					if (snmp_append_data2(mpctl->b_cont,
18785 					    &mp_tail, (char *)&ips,
18786 					    (int)sizeof (ips)) == 0) {
18787 						ip1dbg(("ip_snmp_get_mib2_"
18788 						    "ip_group_src: failed to "
18789 						    "allocate %u bytes\n",
18790 						    (uint_t)sizeof (ips)));
18791 					}
18792 				}
18793 			}
18794 		}
18795 		ILM_WALKER_RELE(ill);
18796 	}
18797 	rw_exit(&ipst->ips_ill_g_lock);
18798 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18799 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18800 	    (int)optp->level, (int)optp->name, (int)optp->len));
18801 	qreply(q, mpctl);
18802 	return (mp2ctl);
18803 }
18804 
18805 /* IPv6 multicast filtered sources. */
18806 static mblk_t *
18807 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18808 {
18809 	struct opthdr		*optp;
18810 	mblk_t			*mp2ctl;
18811 	ill_t			*ill;
18812 	ilm_t			*ilm;
18813 	ipv6_grpsrc_t		ips6;
18814 	mblk_t			*mp_tail = NULL;
18815 	ill_walk_context_t	ctx;
18816 	zoneid_t		zoneid;
18817 	int			i;
18818 	slist_t			*sl;
18819 
18820 	/*
18821 	 * make a copy of the original message
18822 	 */
18823 	mp2ctl = copymsg(mpctl);
18824 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18825 
18826 	/* ip6GroupMember table */
18827 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18828 	optp->level = MIB2_IP6;
18829 	optp->name = EXPER_IP6_GROUP_SOURCES;
18830 
18831 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18832 	ill = ILL_START_WALK_V6(&ctx, ipst);
18833 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18834 		ILM_WALKER_HOLD(ill);
18835 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18836 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18837 			ASSERT(ilm->ilm_ipif == NULL);
18838 			ASSERT(ilm->ilm_ill != NULL);
18839 			sl = ilm->ilm_filter;
18840 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18841 				continue;
18842 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18843 			for (i = 0; i < sl->sl_numsrc; i++) {
18844 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18845 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18846 				    (char *)&ips6, (int)sizeof (ips6))) {
18847 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18848 					    "group_src: failed to allocate "
18849 					    "%u bytes\n",
18850 					    (uint_t)sizeof (ips6)));
18851 				}
18852 			}
18853 		}
18854 		ILM_WALKER_RELE(ill);
18855 	}
18856 	rw_exit(&ipst->ips_ill_g_lock);
18857 
18858 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18859 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18860 	    (int)optp->level, (int)optp->name, (int)optp->len));
18861 	qreply(q, mpctl);
18862 	return (mp2ctl);
18863 }
18864 
18865 /* Multicast routing virtual interface table. */
18866 static mblk_t *
18867 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18868 {
18869 	struct opthdr		*optp;
18870 	mblk_t			*mp2ctl;
18871 
18872 	/*
18873 	 * make a copy of the original message
18874 	 */
18875 	mp2ctl = copymsg(mpctl);
18876 
18877 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18878 	optp->level = EXPER_DVMRP;
18879 	optp->name = EXPER_DVMRP_VIF;
18880 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18881 		ip0dbg(("ip_mroute_vif: failed\n"));
18882 	}
18883 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18884 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18885 	    (int)optp->level, (int)optp->name, (int)optp->len));
18886 	qreply(q, mpctl);
18887 	return (mp2ctl);
18888 }
18889 
18890 /* Multicast routing table. */
18891 static mblk_t *
18892 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18893 {
18894 	struct opthdr		*optp;
18895 	mblk_t			*mp2ctl;
18896 
18897 	/*
18898 	 * make a copy of the original message
18899 	 */
18900 	mp2ctl = copymsg(mpctl);
18901 
18902 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18903 	optp->level = EXPER_DVMRP;
18904 	optp->name = EXPER_DVMRP_MRT;
18905 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18906 		ip0dbg(("ip_mroute_mrt: failed\n"));
18907 	}
18908 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18909 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18910 	    (int)optp->level, (int)optp->name, (int)optp->len));
18911 	qreply(q, mpctl);
18912 	return (mp2ctl);
18913 }
18914 
18915 /*
18916  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18917  * in one IRE walk.
18918  */
18919 static mblk_t *
18920 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18921 {
18922 	struct opthdr	*optp;
18923 	mblk_t		*mp2ctl;	/* Returned */
18924 	mblk_t		*mp3ctl;	/* nettomedia */
18925 	mblk_t		*mp4ctl;	/* routeattrs */
18926 	iproutedata_t	ird;
18927 	zoneid_t	zoneid;
18928 
18929 	/*
18930 	 * make copies of the original message
18931 	 *	- mp2ctl is returned unchanged to the caller for his use
18932 	 *	- mpctl is sent upstream as ipRouteEntryTable
18933 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18934 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18935 	 */
18936 	mp2ctl = copymsg(mpctl);
18937 	mp3ctl = copymsg(mpctl);
18938 	mp4ctl = copymsg(mpctl);
18939 	if (mp3ctl == NULL || mp4ctl == NULL) {
18940 		freemsg(mp4ctl);
18941 		freemsg(mp3ctl);
18942 		freemsg(mp2ctl);
18943 		freemsg(mpctl);
18944 		return (NULL);
18945 	}
18946 
18947 	bzero(&ird, sizeof (ird));
18948 
18949 	ird.ird_route.lp_head = mpctl->b_cont;
18950 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18951 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18952 
18953 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18954 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18955 
18956 	/* ipRouteEntryTable in mpctl */
18957 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18958 	optp->level = MIB2_IP;
18959 	optp->name = MIB2_IP_ROUTE;
18960 	optp->len = msgdsize(ird.ird_route.lp_head);
18961 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18962 	    (int)optp->level, (int)optp->name, (int)optp->len));
18963 	qreply(q, mpctl);
18964 
18965 	/* ipNetToMediaEntryTable in mp3ctl */
18966 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18967 	optp->level = MIB2_IP;
18968 	optp->name = MIB2_IP_MEDIA;
18969 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18970 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18971 	    (int)optp->level, (int)optp->name, (int)optp->len));
18972 	qreply(q, mp3ctl);
18973 
18974 	/* ipRouteAttributeTable in mp4ctl */
18975 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18976 	optp->level = MIB2_IP;
18977 	optp->name = EXPER_IP_RTATTR;
18978 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18979 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18980 	    (int)optp->level, (int)optp->name, (int)optp->len));
18981 	if (optp->len == 0)
18982 		freemsg(mp4ctl);
18983 	else
18984 		qreply(q, mp4ctl);
18985 
18986 	return (mp2ctl);
18987 }
18988 
18989 /*
18990  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18991  * ipv6NetToMediaEntryTable in an NDP walk.
18992  */
18993 static mblk_t *
18994 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18995 {
18996 	struct opthdr	*optp;
18997 	mblk_t		*mp2ctl;	/* Returned */
18998 	mblk_t		*mp3ctl;	/* nettomedia */
18999 	mblk_t		*mp4ctl;	/* routeattrs */
19000 	iproutedata_t	ird;
19001 	zoneid_t	zoneid;
19002 
19003 	/*
19004 	 * make copies of the original message
19005 	 *	- mp2ctl is returned unchanged to the caller for his use
19006 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19007 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19008 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19009 	 */
19010 	mp2ctl = copymsg(mpctl);
19011 	mp3ctl = copymsg(mpctl);
19012 	mp4ctl = copymsg(mpctl);
19013 	if (mp3ctl == NULL || mp4ctl == NULL) {
19014 		freemsg(mp4ctl);
19015 		freemsg(mp3ctl);
19016 		freemsg(mp2ctl);
19017 		freemsg(mpctl);
19018 		return (NULL);
19019 	}
19020 
19021 	bzero(&ird, sizeof (ird));
19022 
19023 	ird.ird_route.lp_head = mpctl->b_cont;
19024 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19025 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19026 
19027 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19028 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19029 
19030 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19031 	optp->level = MIB2_IP6;
19032 	optp->name = MIB2_IP6_ROUTE;
19033 	optp->len = msgdsize(ird.ird_route.lp_head);
19034 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19035 	    (int)optp->level, (int)optp->name, (int)optp->len));
19036 	qreply(q, mpctl);
19037 
19038 	/* ipv6NetToMediaEntryTable in mp3ctl */
19039 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19040 
19041 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19042 	optp->level = MIB2_IP6;
19043 	optp->name = MIB2_IP6_MEDIA;
19044 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19045 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19046 	    (int)optp->level, (int)optp->name, (int)optp->len));
19047 	qreply(q, mp3ctl);
19048 
19049 	/* ipv6RouteAttributeTable in mp4ctl */
19050 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19051 	optp->level = MIB2_IP6;
19052 	optp->name = EXPER_IP_RTATTR;
19053 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19054 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19055 	    (int)optp->level, (int)optp->name, (int)optp->len));
19056 	if (optp->len == 0)
19057 		freemsg(mp4ctl);
19058 	else
19059 		qreply(q, mp4ctl);
19060 
19061 	return (mp2ctl);
19062 }
19063 
19064 /*
19065  * IPv6 mib: One per ill
19066  */
19067 static mblk_t *
19068 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19069 {
19070 	struct opthdr		*optp;
19071 	mblk_t			*mp2ctl;
19072 	ill_t			*ill;
19073 	ill_walk_context_t	ctx;
19074 	mblk_t			*mp_tail = NULL;
19075 
19076 	/*
19077 	 * Make a copy of the original message
19078 	 */
19079 	mp2ctl = copymsg(mpctl);
19080 
19081 	/* fixed length IPv6 structure ... */
19082 
19083 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19084 	optp->level = MIB2_IP6;
19085 	optp->name = 0;
19086 	/* Include "unknown interface" ip6_mib */
19087 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19088 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19089 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19090 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19091 	    ipst->ips_ipv6_forward ? 1 : 2);
19092 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19093 	    ipst->ips_ipv6_def_hops);
19094 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19095 	    sizeof (mib2_ipIfStatsEntry_t));
19096 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19097 	    sizeof (mib2_ipv6AddrEntry_t));
19098 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19099 	    sizeof (mib2_ipv6RouteEntry_t));
19100 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19101 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19102 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19103 	    sizeof (ipv6_member_t));
19104 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19105 	    sizeof (ipv6_grpsrc_t));
19106 
19107 	/*
19108 	 * Synchronize 64- and 32-bit counters
19109 	 */
19110 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19111 	    ipIfStatsHCInReceives);
19112 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19113 	    ipIfStatsHCInDelivers);
19114 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19115 	    ipIfStatsHCOutRequests);
19116 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19117 	    ipIfStatsHCOutForwDatagrams);
19118 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19119 	    ipIfStatsHCOutMcastPkts);
19120 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19121 	    ipIfStatsHCInMcastPkts);
19122 
19123 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19124 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19125 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19126 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19127 	}
19128 
19129 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19130 	ill = ILL_START_WALK_V6(&ctx, ipst);
19131 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19132 		ill->ill_ip_mib->ipIfStatsIfIndex =
19133 		    ill->ill_phyint->phyint_ifindex;
19134 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19135 		    ipst->ips_ipv6_forward ? 1 : 2);
19136 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19137 		    ill->ill_max_hops);
19138 
19139 		/*
19140 		 * Synchronize 64- and 32-bit counters
19141 		 */
19142 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19143 		    ipIfStatsHCInReceives);
19144 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19145 		    ipIfStatsHCInDelivers);
19146 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19147 		    ipIfStatsHCOutRequests);
19148 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19149 		    ipIfStatsHCOutForwDatagrams);
19150 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19151 		    ipIfStatsHCOutMcastPkts);
19152 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19153 		    ipIfStatsHCInMcastPkts);
19154 
19155 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19156 		    (char *)ill->ill_ip_mib,
19157 		    (int)sizeof (*ill->ill_ip_mib))) {
19158 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19159 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19160 		}
19161 	}
19162 	rw_exit(&ipst->ips_ill_g_lock);
19163 
19164 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19165 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19166 	    (int)optp->level, (int)optp->name, (int)optp->len));
19167 	qreply(q, mpctl);
19168 	return (mp2ctl);
19169 }
19170 
19171 /*
19172  * ICMPv6 mib: One per ill
19173  */
19174 static mblk_t *
19175 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19176 {
19177 	struct opthdr		*optp;
19178 	mblk_t			*mp2ctl;
19179 	ill_t			*ill;
19180 	ill_walk_context_t	ctx;
19181 	mblk_t			*mp_tail = NULL;
19182 	/*
19183 	 * Make a copy of the original message
19184 	 */
19185 	mp2ctl = copymsg(mpctl);
19186 
19187 	/* fixed length ICMPv6 structure ... */
19188 
19189 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19190 	optp->level = MIB2_ICMP6;
19191 	optp->name = 0;
19192 	/* Include "unknown interface" icmp6_mib */
19193 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19194 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19195 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19196 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19197 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19198 	    (char *)&ipst->ips_icmp6_mib,
19199 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19200 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19201 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19202 	}
19203 
19204 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19205 	ill = ILL_START_WALK_V6(&ctx, ipst);
19206 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19207 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19208 		    ill->ill_phyint->phyint_ifindex;
19209 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19210 		    (char *)ill->ill_icmp6_mib,
19211 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19212 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19213 			    "%u bytes\n",
19214 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19215 		}
19216 	}
19217 	rw_exit(&ipst->ips_ill_g_lock);
19218 
19219 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19220 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19221 	    (int)optp->level, (int)optp->name, (int)optp->len));
19222 	qreply(q, mpctl);
19223 	return (mp2ctl);
19224 }
19225 
19226 /*
19227  * ire_walk routine to create both ipRouteEntryTable and
19228  * ipRouteAttributeTable in one IRE walk
19229  */
19230 static void
19231 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19232 {
19233 	ill_t				*ill;
19234 	ipif_t				*ipif;
19235 	mib2_ipRouteEntry_t		*re;
19236 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19237 	ipaddr_t			gw_addr;
19238 	tsol_ire_gw_secattr_t		*attrp;
19239 	tsol_gc_t			*gc = NULL;
19240 	tsol_gcgrp_t			*gcgrp = NULL;
19241 	uint_t				sacnt = 0;
19242 	int				i;
19243 
19244 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19245 
19246 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19247 		return;
19248 
19249 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19250 		mutex_enter(&attrp->igsa_lock);
19251 		if ((gc = attrp->igsa_gc) != NULL) {
19252 			gcgrp = gc->gc_grp;
19253 			ASSERT(gcgrp != NULL);
19254 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19255 			sacnt = 1;
19256 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19257 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19258 			gc = gcgrp->gcgrp_head;
19259 			sacnt = gcgrp->gcgrp_count;
19260 		}
19261 		mutex_exit(&attrp->igsa_lock);
19262 
19263 		/* do nothing if there's no gc to report */
19264 		if (gc == NULL) {
19265 			ASSERT(sacnt == 0);
19266 			if (gcgrp != NULL) {
19267 				/* we might as well drop the lock now */
19268 				rw_exit(&gcgrp->gcgrp_rwlock);
19269 				gcgrp = NULL;
19270 			}
19271 			attrp = NULL;
19272 		}
19273 
19274 		ASSERT(gc == NULL || (gcgrp != NULL &&
19275 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19276 	}
19277 	ASSERT(sacnt == 0 || gc != NULL);
19278 
19279 	if (sacnt != 0 &&
19280 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19281 		kmem_free(re, sizeof (*re));
19282 		rw_exit(&gcgrp->gcgrp_rwlock);
19283 		return;
19284 	}
19285 
19286 	/*
19287 	 * Return all IRE types for route table... let caller pick and choose
19288 	 */
19289 	re->ipRouteDest = ire->ire_addr;
19290 	ipif = ire->ire_ipif;
19291 	re->ipRouteIfIndex.o_length = 0;
19292 	if (ire->ire_type == IRE_CACHE) {
19293 		ill = (ill_t *)ire->ire_stq->q_ptr;
19294 		re->ipRouteIfIndex.o_length =
19295 		    ill->ill_name_length == 0 ? 0 :
19296 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19297 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19298 		    re->ipRouteIfIndex.o_length);
19299 	} else if (ipif != NULL) {
19300 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19301 		re->ipRouteIfIndex.o_length =
19302 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19303 	}
19304 	re->ipRouteMetric1 = -1;
19305 	re->ipRouteMetric2 = -1;
19306 	re->ipRouteMetric3 = -1;
19307 	re->ipRouteMetric4 = -1;
19308 
19309 	gw_addr = ire->ire_gateway_addr;
19310 
19311 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19312 		re->ipRouteNextHop = ire->ire_src_addr;
19313 	else
19314 		re->ipRouteNextHop = gw_addr;
19315 	/* indirect(4), direct(3), or invalid(2) */
19316 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19317 		re->ipRouteType = 2;
19318 	else
19319 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19320 	re->ipRouteProto = -1;
19321 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19322 	re->ipRouteMask = ire->ire_mask;
19323 	re->ipRouteMetric5 = -1;
19324 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19325 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19326 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19327 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19328 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19329 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19330 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19331 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19332 
19333 	if (ire->ire_flags & RTF_DYNAMIC) {
19334 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19335 	} else {
19336 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19337 	}
19338 
19339 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19340 	    (char *)re, (int)sizeof (*re))) {
19341 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19342 		    (uint_t)sizeof (*re)));
19343 	}
19344 
19345 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19346 		iaeptr->iae_routeidx = ird->ird_idx;
19347 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19348 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19349 	}
19350 
19351 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19352 	    (char *)iae, sacnt * sizeof (*iae))) {
19353 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19354 		    (unsigned)(sacnt * sizeof (*iae))));
19355 	}
19356 
19357 	/* bump route index for next pass */
19358 	ird->ird_idx++;
19359 
19360 	kmem_free(re, sizeof (*re));
19361 	if (sacnt != 0)
19362 		kmem_free(iae, sacnt * sizeof (*iae));
19363 
19364 	if (gcgrp != NULL)
19365 		rw_exit(&gcgrp->gcgrp_rwlock);
19366 }
19367 
19368 /*
19369  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19370  */
19371 static void
19372 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19373 {
19374 	ill_t				*ill;
19375 	ipif_t				*ipif;
19376 	mib2_ipv6RouteEntry_t		*re;
19377 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19378 	in6_addr_t			gw_addr_v6;
19379 	tsol_ire_gw_secattr_t		*attrp;
19380 	tsol_gc_t			*gc = NULL;
19381 	tsol_gcgrp_t			*gcgrp = NULL;
19382 	uint_t				sacnt = 0;
19383 	int				i;
19384 
19385 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19386 
19387 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19388 		return;
19389 
19390 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19391 		mutex_enter(&attrp->igsa_lock);
19392 		if ((gc = attrp->igsa_gc) != NULL) {
19393 			gcgrp = gc->gc_grp;
19394 			ASSERT(gcgrp != NULL);
19395 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19396 			sacnt = 1;
19397 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19398 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19399 			gc = gcgrp->gcgrp_head;
19400 			sacnt = gcgrp->gcgrp_count;
19401 		}
19402 		mutex_exit(&attrp->igsa_lock);
19403 
19404 		/* do nothing if there's no gc to report */
19405 		if (gc == NULL) {
19406 			ASSERT(sacnt == 0);
19407 			if (gcgrp != NULL) {
19408 				/* we might as well drop the lock now */
19409 				rw_exit(&gcgrp->gcgrp_rwlock);
19410 				gcgrp = NULL;
19411 			}
19412 			attrp = NULL;
19413 		}
19414 
19415 		ASSERT(gc == NULL || (gcgrp != NULL &&
19416 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19417 	}
19418 	ASSERT(sacnt == 0 || gc != NULL);
19419 
19420 	if (sacnt != 0 &&
19421 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19422 		kmem_free(re, sizeof (*re));
19423 		rw_exit(&gcgrp->gcgrp_rwlock);
19424 		return;
19425 	}
19426 
19427 	/*
19428 	 * Return all IRE types for route table... let caller pick and choose
19429 	 */
19430 	re->ipv6RouteDest = ire->ire_addr_v6;
19431 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19432 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19433 	re->ipv6RouteIfIndex.o_length = 0;
19434 	ipif = ire->ire_ipif;
19435 	if (ire->ire_type == IRE_CACHE) {
19436 		ill = (ill_t *)ire->ire_stq->q_ptr;
19437 		re->ipv6RouteIfIndex.o_length =
19438 		    ill->ill_name_length == 0 ? 0 :
19439 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19440 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19441 		    re->ipv6RouteIfIndex.o_length);
19442 	} else if (ipif != NULL) {
19443 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19444 		re->ipv6RouteIfIndex.o_length =
19445 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19446 	}
19447 
19448 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19449 
19450 	mutex_enter(&ire->ire_lock);
19451 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19452 	mutex_exit(&ire->ire_lock);
19453 
19454 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19455 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19456 	else
19457 		re->ipv6RouteNextHop = gw_addr_v6;
19458 
19459 	/* remote(4), local(3), or discard(2) */
19460 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19461 		re->ipv6RouteType = 2;
19462 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19463 		re->ipv6RouteType = 3;
19464 	else
19465 		re->ipv6RouteType = 4;
19466 
19467 	re->ipv6RouteProtocol	= -1;
19468 	re->ipv6RoutePolicy	= 0;
19469 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19470 	re->ipv6RouteNextHopRDI	= 0;
19471 	re->ipv6RouteWeight	= 0;
19472 	re->ipv6RouteMetric	= 0;
19473 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19474 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19475 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19476 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19477 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19478 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19479 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19480 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19481 
19482 	if (ire->ire_flags & RTF_DYNAMIC) {
19483 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19484 	} else {
19485 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19486 	}
19487 
19488 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19489 	    (char *)re, (int)sizeof (*re))) {
19490 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19491 		    (uint_t)sizeof (*re)));
19492 	}
19493 
19494 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19495 		iaeptr->iae_routeidx = ird->ird_idx;
19496 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19497 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19498 	}
19499 
19500 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19501 	    (char *)iae, sacnt * sizeof (*iae))) {
19502 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19503 		    (unsigned)(sacnt * sizeof (*iae))));
19504 	}
19505 
19506 	/* bump route index for next pass */
19507 	ird->ird_idx++;
19508 
19509 	kmem_free(re, sizeof (*re));
19510 	if (sacnt != 0)
19511 		kmem_free(iae, sacnt * sizeof (*iae));
19512 
19513 	if (gcgrp != NULL)
19514 		rw_exit(&gcgrp->gcgrp_rwlock);
19515 }
19516 
19517 /*
19518  * ndp_walk routine to create ipv6NetToMediaEntryTable
19519  */
19520 static int
19521 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19522 {
19523 	ill_t				*ill;
19524 	mib2_ipv6NetToMediaEntry_t	ntme;
19525 	dl_unitdata_req_t		*dl;
19526 
19527 	ill = nce->nce_ill;
19528 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19529 		return (0);
19530 
19531 	/*
19532 	 * Neighbor cache entry attached to IRE with on-link
19533 	 * destination.
19534 	 */
19535 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19536 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19537 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19538 	    (nce->nce_res_mp != NULL)) {
19539 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19540 		ntme.ipv6NetToMediaPhysAddress.o_length =
19541 		    dl->dl_dest_addr_length;
19542 	} else {
19543 		ntme.ipv6NetToMediaPhysAddress.o_length =
19544 		    ill->ill_phys_addr_length;
19545 	}
19546 	if (nce->nce_res_mp != NULL) {
19547 		bcopy((char *)nce->nce_res_mp->b_rptr +
19548 		    NCE_LL_ADDR_OFFSET(ill),
19549 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19550 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19551 	} else {
19552 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19553 		    ill->ill_phys_addr_length);
19554 	}
19555 	/*
19556 	 * Note: Returns ND_* states. Should be:
19557 	 * reachable(1), stale(2), delay(3), probe(4),
19558 	 * invalid(5), unknown(6)
19559 	 */
19560 	ntme.ipv6NetToMediaState = nce->nce_state;
19561 	ntme.ipv6NetToMediaLastUpdated = 0;
19562 
19563 	/* other(1), dynamic(2), static(3), local(4) */
19564 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19565 		ntme.ipv6NetToMediaType = 4;
19566 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19567 		ntme.ipv6NetToMediaType = 1;
19568 	} else {
19569 		ntme.ipv6NetToMediaType = 2;
19570 	}
19571 
19572 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19573 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19574 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19575 		    (uint_t)sizeof (ntme)));
19576 	}
19577 	return (0);
19578 }
19579 
19580 /*
19581  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19582  */
19583 /* ARGSUSED */
19584 int
19585 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19586 {
19587 	switch (level) {
19588 	case MIB2_IP:
19589 	case MIB2_ICMP:
19590 		switch (name) {
19591 		default:
19592 			break;
19593 		}
19594 		return (1);
19595 	default:
19596 		return (1);
19597 	}
19598 }
19599 
19600 /*
19601  * When there exists both a 64- and 32-bit counter of a particular type
19602  * (i.e., InReceives), only the 64-bit counters are added.
19603  */
19604 void
19605 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19606 {
19607 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19608 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19609 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19610 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19611 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19612 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19613 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19614 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19615 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19616 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19617 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19618 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19619 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19620 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19621 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19622 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19623 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19624 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19625 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19626 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19627 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19628 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19629 	    o2->ipIfStatsInWrongIPVersion);
19630 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19631 	    o2->ipIfStatsInWrongIPVersion);
19632 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19633 	    o2->ipIfStatsOutSwitchIPVersion);
19634 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19635 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19636 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19637 	    o2->ipIfStatsHCInForwDatagrams);
19638 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19639 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19640 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19641 	    o2->ipIfStatsHCOutForwDatagrams);
19642 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19643 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19644 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19645 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19646 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19647 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19648 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19649 	    o2->ipIfStatsHCOutMcastOctets);
19650 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19651 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19652 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19653 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19654 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19655 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19656 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19657 }
19658 
19659 void
19660 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19661 {
19662 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19663 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19664 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19665 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19666 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19667 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19668 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19669 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19670 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19671 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19672 	    o2->ipv6IfIcmpInRouterSolicits);
19673 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19674 	    o2->ipv6IfIcmpInRouterAdvertisements);
19675 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19676 	    o2->ipv6IfIcmpInNeighborSolicits);
19677 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19678 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19679 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19680 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19681 	    o2->ipv6IfIcmpInGroupMembQueries);
19682 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19683 	    o2->ipv6IfIcmpInGroupMembResponses);
19684 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19685 	    o2->ipv6IfIcmpInGroupMembReductions);
19686 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19687 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19688 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19689 	    o2->ipv6IfIcmpOutDestUnreachs);
19690 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19691 	    o2->ipv6IfIcmpOutAdminProhibs);
19692 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19693 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19694 	    o2->ipv6IfIcmpOutParmProblems);
19695 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19696 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19697 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19698 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19699 	    o2->ipv6IfIcmpOutRouterSolicits);
19700 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19701 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19702 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19703 	    o2->ipv6IfIcmpOutNeighborSolicits);
19704 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19705 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19706 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19707 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19708 	    o2->ipv6IfIcmpOutGroupMembQueries);
19709 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19710 	    o2->ipv6IfIcmpOutGroupMembResponses);
19711 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19712 	    o2->ipv6IfIcmpOutGroupMembReductions);
19713 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19714 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19715 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19716 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19717 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19718 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19719 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19720 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19721 	    o2->ipv6IfIcmpInGroupMembTotal);
19722 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19723 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19724 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19725 	    o2->ipv6IfIcmpInGroupMembBadReports);
19726 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19727 	    o2->ipv6IfIcmpInGroupMembOurReports);
19728 }
19729 
19730 /*
19731  * Called before the options are updated to check if this packet will
19732  * be source routed from here.
19733  * This routine assumes that the options are well formed i.e. that they
19734  * have already been checked.
19735  */
19736 static boolean_t
19737 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19738 {
19739 	ipoptp_t	opts;
19740 	uchar_t		*opt;
19741 	uint8_t		optval;
19742 	uint8_t		optlen;
19743 	ipaddr_t	dst;
19744 	ire_t		*ire;
19745 
19746 	if (IS_SIMPLE_IPH(ipha)) {
19747 		ip2dbg(("not source routed\n"));
19748 		return (B_FALSE);
19749 	}
19750 	dst = ipha->ipha_dst;
19751 	for (optval = ipoptp_first(&opts, ipha);
19752 	    optval != IPOPT_EOL;
19753 	    optval = ipoptp_next(&opts)) {
19754 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19755 		opt = opts.ipoptp_cur;
19756 		optlen = opts.ipoptp_len;
19757 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19758 		    optval, optlen));
19759 		switch (optval) {
19760 			uint32_t off;
19761 		case IPOPT_SSRR:
19762 		case IPOPT_LSRR:
19763 			/*
19764 			 * If dst is one of our addresses and there are some
19765 			 * entries left in the source route return (true).
19766 			 */
19767 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19768 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19769 			if (ire == NULL) {
19770 				ip2dbg(("ip_source_routed: not next"
19771 				    " source route 0x%x\n",
19772 				    ntohl(dst)));
19773 				return (B_FALSE);
19774 			}
19775 			ire_refrele(ire);
19776 			off = opt[IPOPT_OFFSET];
19777 			off--;
19778 			if (optlen < IP_ADDR_LEN ||
19779 			    off > optlen - IP_ADDR_LEN) {
19780 				/* End of source route */
19781 				ip1dbg(("ip_source_routed: end of SR\n"));
19782 				return (B_FALSE);
19783 			}
19784 			return (B_TRUE);
19785 		}
19786 	}
19787 	ip2dbg(("not source routed\n"));
19788 	return (B_FALSE);
19789 }
19790 
19791 /*
19792  * Check if the packet contains any source route.
19793  */
19794 static boolean_t
19795 ip_source_route_included(ipha_t *ipha)
19796 {
19797 	ipoptp_t	opts;
19798 	uint8_t		optval;
19799 
19800 	if (IS_SIMPLE_IPH(ipha))
19801 		return (B_FALSE);
19802 	for (optval = ipoptp_first(&opts, ipha);
19803 	    optval != IPOPT_EOL;
19804 	    optval = ipoptp_next(&opts)) {
19805 		switch (optval) {
19806 		case IPOPT_SSRR:
19807 		case IPOPT_LSRR:
19808 			return (B_TRUE);
19809 		}
19810 	}
19811 	return (B_FALSE);
19812 }
19813 
19814 /*
19815  * Called when the IRE expiration timer fires.
19816  */
19817 void
19818 ip_trash_timer_expire(void *args)
19819 {
19820 	int			flush_flag = 0;
19821 	ire_expire_arg_t	iea;
19822 	ip_stack_t		*ipst = (ip_stack_t *)args;
19823 
19824 	iea.iea_ipst = ipst;	/* No netstack_hold */
19825 
19826 	/*
19827 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19828 	 * This lock makes sure that a new invocation of this function
19829 	 * that occurs due to an almost immediate timer firing will not
19830 	 * progress beyond this point until the current invocation is done
19831 	 */
19832 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19833 	ipst->ips_ip_ire_expire_id = 0;
19834 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19835 
19836 	/* Periodic timer */
19837 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19838 	    ipst->ips_ip_ire_arp_interval) {
19839 		/*
19840 		 * Remove all IRE_CACHE entries since they might
19841 		 * contain arp information.
19842 		 */
19843 		flush_flag |= FLUSH_ARP_TIME;
19844 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19845 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19846 	}
19847 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19848 	    ipst->ips_ip_ire_redir_interval) {
19849 		/* Remove all redirects */
19850 		flush_flag |= FLUSH_REDIRECT_TIME;
19851 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19852 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19853 	}
19854 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19855 	    ipst->ips_ip_ire_pathmtu_interval) {
19856 		/* Increase path mtu */
19857 		flush_flag |= FLUSH_MTU_TIME;
19858 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19859 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19860 	}
19861 
19862 	/*
19863 	 * Optimize for the case when there are no redirects in the
19864 	 * ftable, that is, no need to walk the ftable in that case.
19865 	 */
19866 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19867 		iea.iea_flush_flag = flush_flag;
19868 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19869 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19870 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19871 		    NULL, ALL_ZONES, ipst);
19872 	}
19873 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19874 	    ipst->ips_ip_redirect_cnt > 0) {
19875 		iea.iea_flush_flag = flush_flag;
19876 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19877 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19878 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19879 	}
19880 	if (flush_flag & FLUSH_MTU_TIME) {
19881 		/*
19882 		 * Walk all IPv6 IRE's and update them
19883 		 * Note that ARP and redirect timers are not
19884 		 * needed since NUD handles stale entries.
19885 		 */
19886 		flush_flag = FLUSH_MTU_TIME;
19887 		iea.iea_flush_flag = flush_flag;
19888 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19889 		    ALL_ZONES, ipst);
19890 	}
19891 
19892 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19893 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19894 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19895 
19896 	/*
19897 	 * Hold the lock to serialize timeout calls and prevent
19898 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19899 	 * for the timer to fire and a new invocation of this function
19900 	 * to start before the return value of timeout has been stored
19901 	 * in ip_ire_expire_id by the current invocation.
19902 	 */
19903 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19904 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19905 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19906 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19907 }
19908 
19909 /*
19910  * Called by the memory allocator subsystem directly, when the system
19911  * is running low on memory.
19912  */
19913 /* ARGSUSED */
19914 void
19915 ip_trash_ire_reclaim(void *args)
19916 {
19917 	netstack_handle_t nh;
19918 	netstack_t *ns;
19919 
19920 	netstack_next_init(&nh);
19921 	while ((ns = netstack_next(&nh)) != NULL) {
19922 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19923 		netstack_rele(ns);
19924 	}
19925 	netstack_next_fini(&nh);
19926 }
19927 
19928 static void
19929 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19930 {
19931 	ire_cache_count_t icc;
19932 	ire_cache_reclaim_t icr;
19933 	ncc_cache_count_t ncc;
19934 	nce_cache_reclaim_t ncr;
19935 	uint_t delete_cnt;
19936 	/*
19937 	 * Memory reclaim call back.
19938 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19939 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19940 	 * entries, determine what fraction to free for
19941 	 * each category of IRE_CACHE entries giving absolute priority
19942 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19943 	 * entry will be freed unless all offlink entries are freed).
19944 	 */
19945 	icc.icc_total = 0;
19946 	icc.icc_unused = 0;
19947 	icc.icc_offlink = 0;
19948 	icc.icc_pmtu = 0;
19949 	icc.icc_onlink = 0;
19950 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19951 
19952 	/*
19953 	 * Free NCEs for IPv6 like the onlink ires.
19954 	 */
19955 	ncc.ncc_total = 0;
19956 	ncc.ncc_host = 0;
19957 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19958 
19959 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19960 	    icc.icc_pmtu + icc.icc_onlink);
19961 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19962 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19963 	if (delete_cnt == 0)
19964 		return;
19965 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19966 	/* Always delete all unused offlink entries */
19967 	icr.icr_ipst = ipst;
19968 	icr.icr_unused = 1;
19969 	if (delete_cnt <= icc.icc_unused) {
19970 		/*
19971 		 * Only need to free unused entries.  In other words,
19972 		 * there are enough unused entries to free to meet our
19973 		 * target number of freed ire cache entries.
19974 		 */
19975 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19976 		ncr.ncr_host = 0;
19977 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19978 		/*
19979 		 * Only need to free unused entries, plus a fraction of offlink
19980 		 * entries.  It follows from the first if statement that
19981 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19982 		 */
19983 		delete_cnt -= icc.icc_unused;
19984 		/* Round up # deleted by truncating fraction */
19985 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19986 		icr.icr_pmtu = icr.icr_onlink = 0;
19987 		ncr.ncr_host = 0;
19988 	} else if (delete_cnt <=
19989 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19990 		/*
19991 		 * Free all unused and offlink entries, plus a fraction of
19992 		 * pmtu entries.  It follows from the previous if statement
19993 		 * that icc_pmtu is non-zero, and that
19994 		 * delete_cnt != icc_unused + icc_offlink.
19995 		 */
19996 		icr.icr_offlink = 1;
19997 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19998 		/* Round up # deleted by truncating fraction */
19999 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20000 		icr.icr_onlink = 0;
20001 		ncr.ncr_host = 0;
20002 	} else {
20003 		/*
20004 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20005 		 * of onlink entries.  If we're here, then we know that
20006 		 * icc_onlink is non-zero, and that
20007 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20008 		 */
20009 		icr.icr_offlink = icr.icr_pmtu = 1;
20010 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20011 		    icc.icc_pmtu;
20012 		/* Round up # deleted by truncating fraction */
20013 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20014 		/* Using the same delete fraction as for onlink IREs */
20015 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20016 	}
20017 #ifdef DEBUG
20018 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20019 	    "fractions %d/%d/%d/%d\n",
20020 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20021 	    icc.icc_unused, icc.icc_offlink,
20022 	    icc.icc_pmtu, icc.icc_onlink,
20023 	    icr.icr_unused, icr.icr_offlink,
20024 	    icr.icr_pmtu, icr.icr_onlink));
20025 #endif
20026 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20027 	if (ncr.ncr_host != 0)
20028 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20029 		    (uchar_t *)&ncr, ipst);
20030 #ifdef DEBUG
20031 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20032 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20033 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20034 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20035 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20036 	    icc.icc_pmtu, icc.icc_onlink));
20037 #endif
20038 }
20039 
20040 /*
20041  * ip_unbind is called when a copy of an unbind request is received from the
20042  * upper level protocol.  We remove this conn from any fanout hash list it is
20043  * on, and zero out the bind information.  No reply is expected up above.
20044  */
20045 mblk_t *
20046 ip_unbind(queue_t *q, mblk_t *mp)
20047 {
20048 	conn_t	*connp = Q_TO_CONN(q);
20049 
20050 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20051 
20052 	if (is_system_labeled() && connp->conn_anon_port) {
20053 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20054 		    connp->conn_mlp_type, connp->conn_ulp,
20055 		    ntohs(connp->conn_lport), B_FALSE);
20056 		connp->conn_anon_port = 0;
20057 	}
20058 	connp->conn_mlp_type = mlptSingle;
20059 
20060 	ipcl_hash_remove(connp);
20061 
20062 	ASSERT(mp->b_cont == NULL);
20063 	/*
20064 	 * Convert mp into a T_OK_ACK
20065 	 */
20066 	mp = mi_tpi_ok_ack_alloc(mp);
20067 
20068 	/*
20069 	 * should not happen in practice... T_OK_ACK is smaller than the
20070 	 * original message.
20071 	 */
20072 	if (mp == NULL)
20073 		return (NULL);
20074 
20075 	return (mp);
20076 }
20077 
20078 /*
20079  * Write side put procedure.  Outbound data, IOCTLs, responses from
20080  * resolvers, etc, come down through here.
20081  *
20082  * arg2 is always a queue_t *.
20083  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20084  * the zoneid.
20085  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20086  */
20087 void
20088 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20089 {
20090 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20091 }
20092 
20093 void
20094 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20095     ip_opt_info_t *infop)
20096 {
20097 	conn_t		*connp = NULL;
20098 	queue_t		*q = (queue_t *)arg2;
20099 	ipha_t		*ipha;
20100 #define	rptr	((uchar_t *)ipha)
20101 	ire_t		*ire = NULL;
20102 	ire_t		*sctp_ire = NULL;
20103 	uint32_t	v_hlen_tos_len;
20104 	ipaddr_t	dst;
20105 	mblk_t		*first_mp = NULL;
20106 	boolean_t	mctl_present;
20107 	ipsec_out_t	*io;
20108 	int		match_flags;
20109 	ill_t		*attach_ill = NULL;
20110 					/* Bind to IPIF_NOFAILOVER ill etc. */
20111 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20112 	ipif_t		*dst_ipif;
20113 	boolean_t	multirt_need_resolve = B_FALSE;
20114 	mblk_t		*copy_mp = NULL;
20115 	int		err;
20116 	zoneid_t	zoneid;
20117 	int	adjust;
20118 	uint16_t iplen;
20119 	boolean_t	need_decref = B_FALSE;
20120 	boolean_t	ignore_dontroute = B_FALSE;
20121 	boolean_t	ignore_nexthop = B_FALSE;
20122 	boolean_t	ip_nexthop = B_FALSE;
20123 	ipaddr_t	nexthop_addr;
20124 	ip_stack_t	*ipst;
20125 
20126 #ifdef	_BIG_ENDIAN
20127 #define	V_HLEN	(v_hlen_tos_len >> 24)
20128 #else
20129 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20130 #endif
20131 
20132 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20133 	    "ip_wput_start: q %p", q);
20134 
20135 	/*
20136 	 * ip_wput fast path
20137 	 */
20138 
20139 	/* is packet from ARP ? */
20140 	if (q->q_next != NULL) {
20141 		zoneid = (zoneid_t)(uintptr_t)arg;
20142 		goto qnext;
20143 	}
20144 
20145 	connp = (conn_t *)arg;
20146 	ASSERT(connp != NULL);
20147 	zoneid = connp->conn_zoneid;
20148 	ipst = connp->conn_netstack->netstack_ip;
20149 
20150 	/* is queue flow controlled? */
20151 	if ((q->q_first != NULL || connp->conn_draining) &&
20152 	    (caller == IP_WPUT)) {
20153 		ASSERT(!need_decref);
20154 		(void) putq(q, mp);
20155 		return;
20156 	}
20157 
20158 	/* Multidata transmit? */
20159 	if (DB_TYPE(mp) == M_MULTIDATA) {
20160 		/*
20161 		 * We should never get here, since all Multidata messages
20162 		 * originating from tcp should have been directed over to
20163 		 * tcp_multisend() in the first place.
20164 		 */
20165 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20166 		freemsg(mp);
20167 		return;
20168 	} else if (DB_TYPE(mp) != M_DATA)
20169 		goto notdata;
20170 
20171 	if (mp->b_flag & MSGHASREF) {
20172 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20173 		mp->b_flag &= ~MSGHASREF;
20174 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20175 		need_decref = B_TRUE;
20176 	}
20177 	ipha = (ipha_t *)mp->b_rptr;
20178 
20179 	/* is IP header non-aligned or mblk smaller than basic IP header */
20180 #ifndef SAFETY_BEFORE_SPEED
20181 	if (!OK_32PTR(rptr) ||
20182 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20183 		goto hdrtoosmall;
20184 #endif
20185 
20186 	ASSERT(OK_32PTR(ipha));
20187 
20188 	/*
20189 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20190 	 * wrong version, we'll catch it again in ip_output_v6.
20191 	 *
20192 	 * Note that this is *only* locally-generated output here, and never
20193 	 * forwarded data, and that we need to deal only with transports that
20194 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20195 	 * label.)
20196 	 */
20197 	if (is_system_labeled() &&
20198 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20199 	    !connp->conn_ulp_labeled) {
20200 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20201 		    connp->conn_mac_exempt, ipst);
20202 		ipha = (ipha_t *)mp->b_rptr;
20203 		if (err != 0) {
20204 			first_mp = mp;
20205 			if (err == EINVAL)
20206 				goto icmp_parameter_problem;
20207 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20208 			goto discard_pkt;
20209 		}
20210 		iplen = ntohs(ipha->ipha_length) + adjust;
20211 		ipha->ipha_length = htons(iplen);
20212 	}
20213 
20214 	ASSERT(infop != NULL);
20215 
20216 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20217 		/*
20218 		 * IP_PKTINFO ancillary option is present.
20219 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20220 		 * allows using address of any zone as the source address.
20221 		 */
20222 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20223 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20224 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20225 		if (ire == NULL)
20226 			goto drop_pkt;
20227 		ire_refrele(ire);
20228 		ire = NULL;
20229 	}
20230 
20231 	/*
20232 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20233 	 * passed in IP_PKTINFO.
20234 	 */
20235 	if (infop->ip_opt_ill_index != 0 &&
20236 	    connp->conn_outgoing_ill == NULL &&
20237 	    connp->conn_nofailover_ill == NULL) {
20238 
20239 		xmit_ill = ill_lookup_on_ifindex(
20240 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20241 		    ipst);
20242 
20243 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20244 			goto drop_pkt;
20245 		/*
20246 		 * check that there is an ipif belonging
20247 		 * to our zone. IPCL_ZONEID is not used because
20248 		 * IP_ALLZONES option is valid only when the ill is
20249 		 * accessible from all zones i.e has a valid ipif in
20250 		 * all zones.
20251 		 */
20252 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20253 			goto drop_pkt;
20254 		}
20255 	}
20256 
20257 	/*
20258 	 * If there is a policy, try to attach an ipsec_out in
20259 	 * the front. At the end, first_mp either points to a
20260 	 * M_DATA message or IPSEC_OUT message linked to a
20261 	 * M_DATA message. We have to do it now as we might
20262 	 * lose the "conn" if we go through ip_newroute.
20263 	 */
20264 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20265 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20266 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20267 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20268 			if (need_decref)
20269 				CONN_DEC_REF(connp);
20270 			return;
20271 		} else {
20272 			ASSERT(mp->b_datap->db_type == M_CTL);
20273 			first_mp = mp;
20274 			mp = mp->b_cont;
20275 			mctl_present = B_TRUE;
20276 		}
20277 	} else {
20278 		first_mp = mp;
20279 		mctl_present = B_FALSE;
20280 	}
20281 
20282 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20283 
20284 	/* is wrong version or IP options present */
20285 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20286 		goto version_hdrlen_check;
20287 	dst = ipha->ipha_dst;
20288 
20289 	if (connp->conn_nofailover_ill != NULL) {
20290 		attach_ill = conn_get_held_ill(connp,
20291 		    &connp->conn_nofailover_ill, &err);
20292 		if (err == ILL_LOOKUP_FAILED) {
20293 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20294 			if (need_decref)
20295 				CONN_DEC_REF(connp);
20296 			freemsg(first_mp);
20297 			return;
20298 		}
20299 	}
20300 
20301 	/* If IP_BOUND_IF has been set, use that ill. */
20302 	if (connp->conn_outgoing_ill != NULL) {
20303 		xmit_ill = conn_get_held_ill(connp,
20304 		    &connp->conn_outgoing_ill, &err);
20305 		if (err == ILL_LOOKUP_FAILED)
20306 			goto drop_pkt;
20307 
20308 		goto send_from_ill;
20309 	}
20310 
20311 	/* is packet multicast? */
20312 	if (CLASSD(dst))
20313 		goto multicast;
20314 
20315 	/*
20316 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20317 	 * takes precedence over conn_dontroute and conn_nexthop_set
20318 	 */
20319 	if (xmit_ill != NULL)
20320 		goto send_from_ill;
20321 
20322 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20323 		/*
20324 		 * If the destination is a broadcast, local, or loopback
20325 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20326 		 * standard path.
20327 		 */
20328 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20329 		if ((ire == NULL) || (ire->ire_type &
20330 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20331 			if (ire != NULL) {
20332 				ire_refrele(ire);
20333 				/* No more access to ire */
20334 				ire = NULL;
20335 			}
20336 			/*
20337 			 * bypass routing checks and go directly to interface.
20338 			 */
20339 			if (connp->conn_dontroute)
20340 				goto dontroute;
20341 
20342 			ASSERT(connp->conn_nexthop_set);
20343 			ip_nexthop = B_TRUE;
20344 			nexthop_addr = connp->conn_nexthop_v4;
20345 			goto send_from_ill;
20346 		}
20347 
20348 		/* Must be a broadcast, a loopback or a local ire */
20349 		ire_refrele(ire);
20350 		/* No more access to ire */
20351 		ire = NULL;
20352 	}
20353 
20354 	if (attach_ill != NULL)
20355 		goto send_from_ill;
20356 
20357 	/*
20358 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20359 	 * this for the tcp global queue and listen end point
20360 	 * as it does not really have a real destination to
20361 	 * talk to.  This is also true for SCTP.
20362 	 */
20363 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20364 	    !connp->conn_fully_bound) {
20365 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20366 		if (ire == NULL)
20367 			goto noirefound;
20368 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20369 		    "ip_wput_end: q %p (%S)", q, "end");
20370 
20371 		/*
20372 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20373 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20374 		 */
20375 		if (ire->ire_flags & RTF_MULTIRT) {
20376 
20377 			/*
20378 			 * Force the TTL of multirouted packets if required.
20379 			 * The TTL of such packets is bounded by the
20380 			 * ip_multirt_ttl ndd variable.
20381 			 */
20382 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20383 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20384 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20385 				    "(was %d), dst 0x%08x\n",
20386 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20387 				    ntohl(ire->ire_addr)));
20388 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20389 			}
20390 			/*
20391 			 * We look at this point if there are pending
20392 			 * unresolved routes. ire_multirt_resolvable()
20393 			 * checks in O(n) that all IRE_OFFSUBNET ire
20394 			 * entries for the packet's destination and
20395 			 * flagged RTF_MULTIRT are currently resolved.
20396 			 * If some remain unresolved, we make a copy
20397 			 * of the current message. It will be used
20398 			 * to initiate additional route resolutions.
20399 			 */
20400 			multirt_need_resolve =
20401 			    ire_multirt_need_resolve(ire->ire_addr,
20402 			    MBLK_GETLABEL(first_mp), ipst);
20403 			ip2dbg(("ip_wput[TCP]: ire %p, "
20404 			    "multirt_need_resolve %d, first_mp %p\n",
20405 			    (void *)ire, multirt_need_resolve,
20406 			    (void *)first_mp));
20407 			if (multirt_need_resolve) {
20408 				copy_mp = copymsg(first_mp);
20409 				if (copy_mp != NULL) {
20410 					MULTIRT_DEBUG_TAG(copy_mp);
20411 				}
20412 			}
20413 		}
20414 
20415 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20416 
20417 		/*
20418 		 * Try to resolve another multiroute if
20419 		 * ire_multirt_need_resolve() deemed it necessary.
20420 		 */
20421 		if (copy_mp != NULL)
20422 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20423 		if (need_decref)
20424 			CONN_DEC_REF(connp);
20425 		return;
20426 	}
20427 
20428 	/*
20429 	 * Access to conn_ire_cache. (protected by conn_lock)
20430 	 *
20431 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20432 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20433 	 * send a packet or two with the IRE_CACHE that is going away.
20434 	 * Access to the ire requires an ire refhold on the ire prior to
20435 	 * its use since an interface unplumb thread may delete the cached
20436 	 * ire and release the refhold at any time.
20437 	 *
20438 	 * Caching an ire in the conn_ire_cache
20439 	 *
20440 	 * o Caching an ire pointer in the conn requires a strict check for
20441 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20442 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20443 	 * in the conn is done after making sure under the bucket lock that the
20444 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20445 	 * caching an ire after the unplumb thread has cleaned up the conn.
20446 	 * If the conn does not send a packet subsequently the unplumb thread
20447 	 * will be hanging waiting for the ire count to drop to zero.
20448 	 *
20449 	 * o We also need to atomically test for a null conn_ire_cache and
20450 	 * set the conn_ire_cache under the the protection of the conn_lock
20451 	 * to avoid races among concurrent threads trying to simultaneously
20452 	 * cache an ire in the conn_ire_cache.
20453 	 */
20454 	mutex_enter(&connp->conn_lock);
20455 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20456 
20457 	if (ire != NULL && ire->ire_addr == dst &&
20458 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20459 
20460 		IRE_REFHOLD(ire);
20461 		mutex_exit(&connp->conn_lock);
20462 
20463 	} else {
20464 		boolean_t cached = B_FALSE;
20465 		connp->conn_ire_cache = NULL;
20466 		mutex_exit(&connp->conn_lock);
20467 		/* Release the old ire */
20468 		if (ire != NULL && sctp_ire == NULL)
20469 			IRE_REFRELE_NOTR(ire);
20470 
20471 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20472 		if (ire == NULL)
20473 			goto noirefound;
20474 		IRE_REFHOLD_NOTR(ire);
20475 
20476 		mutex_enter(&connp->conn_lock);
20477 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20478 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20479 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20480 				if (connp->conn_ulp == IPPROTO_TCP)
20481 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20482 				connp->conn_ire_cache = ire;
20483 				cached = B_TRUE;
20484 			}
20485 			rw_exit(&ire->ire_bucket->irb_lock);
20486 		}
20487 		mutex_exit(&connp->conn_lock);
20488 
20489 		/*
20490 		 * We can continue to use the ire but since it was
20491 		 * not cached, we should drop the extra reference.
20492 		 */
20493 		if (!cached)
20494 			IRE_REFRELE_NOTR(ire);
20495 	}
20496 
20497 
20498 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20499 	    "ip_wput_end: q %p (%S)", q, "end");
20500 
20501 	/*
20502 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20503 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20504 	 */
20505 	if (ire->ire_flags & RTF_MULTIRT) {
20506 
20507 		/*
20508 		 * Force the TTL of multirouted packets if required.
20509 		 * The TTL of such packets is bounded by the
20510 		 * ip_multirt_ttl ndd variable.
20511 		 */
20512 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20513 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20514 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20515 			    "(was %d), dst 0x%08x\n",
20516 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20517 			    ntohl(ire->ire_addr)));
20518 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20519 		}
20520 
20521 		/*
20522 		 * At this point, we check to see if there are any pending
20523 		 * unresolved routes. ire_multirt_resolvable()
20524 		 * checks in O(n) that all IRE_OFFSUBNET ire
20525 		 * entries for the packet's destination and
20526 		 * flagged RTF_MULTIRT are currently resolved.
20527 		 * If some remain unresolved, we make a copy
20528 		 * of the current message. It will be used
20529 		 * to initiate additional route resolutions.
20530 		 */
20531 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20532 		    MBLK_GETLABEL(first_mp), ipst);
20533 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20534 		    "multirt_need_resolve %d, first_mp %p\n",
20535 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20536 		if (multirt_need_resolve) {
20537 			copy_mp = copymsg(first_mp);
20538 			if (copy_mp != NULL) {
20539 				MULTIRT_DEBUG_TAG(copy_mp);
20540 			}
20541 		}
20542 	}
20543 
20544 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20545 
20546 	/*
20547 	 * Try to resolve another multiroute if
20548 	 * ire_multirt_resolvable() deemed it necessary
20549 	 */
20550 	if (copy_mp != NULL)
20551 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20552 	if (need_decref)
20553 		CONN_DEC_REF(connp);
20554 	return;
20555 
20556 qnext:
20557 	/*
20558 	 * Upper Level Protocols pass down complete IP datagrams
20559 	 * as M_DATA messages.	Everything else is a sideshow.
20560 	 *
20561 	 * 1) We could be re-entering ip_wput because of ip_neworute
20562 	 *    in which case we could have a IPSEC_OUT message. We
20563 	 *    need to pass through ip_wput like other datagrams and
20564 	 *    hence cannot branch to ip_wput_nondata.
20565 	 *
20566 	 * 2) ARP, AH, ESP, and other clients who are on the module
20567 	 *    instance of IP stream, give us something to deal with.
20568 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20569 	 *
20570 	 * 3) ICMP replies also could come here.
20571 	 */
20572 	ipst = ILLQ_TO_IPST(q);
20573 
20574 	if (DB_TYPE(mp) != M_DATA) {
20575 notdata:
20576 		if (DB_TYPE(mp) == M_CTL) {
20577 			/*
20578 			 * M_CTL messages are used by ARP, AH and ESP to
20579 			 * communicate with IP. We deal with IPSEC_IN and
20580 			 * IPSEC_OUT here. ip_wput_nondata handles other
20581 			 * cases.
20582 			 */
20583 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20584 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20585 				first_mp = mp->b_cont;
20586 				first_mp->b_flag &= ~MSGHASREF;
20587 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20588 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20589 				CONN_DEC_REF(connp);
20590 				connp = NULL;
20591 			}
20592 			if (ii->ipsec_info_type == IPSEC_IN) {
20593 				/*
20594 				 * Either this message goes back to
20595 				 * IPsec for further processing or to
20596 				 * ULP after policy checks.
20597 				 */
20598 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20599 				return;
20600 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20601 				io = (ipsec_out_t *)ii;
20602 				if (io->ipsec_out_proc_begin) {
20603 					/*
20604 					 * IPsec processing has already started.
20605 					 * Complete it.
20606 					 * IPQoS notes: We don't care what is
20607 					 * in ipsec_out_ill_index since this
20608 					 * won't be processed for IPQoS policies
20609 					 * in ipsec_out_process.
20610 					 */
20611 					ipsec_out_process(q, mp, NULL,
20612 					    io->ipsec_out_ill_index);
20613 					return;
20614 				} else {
20615 					connp = (q->q_next != NULL) ?
20616 					    NULL : Q_TO_CONN(q);
20617 					first_mp = mp;
20618 					mp = mp->b_cont;
20619 					mctl_present = B_TRUE;
20620 				}
20621 				zoneid = io->ipsec_out_zoneid;
20622 				ASSERT(zoneid != ALL_ZONES);
20623 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20624 				/*
20625 				 * It's an IPsec control message requesting
20626 				 * an SADB update to be sent to the IPsec
20627 				 * hardware acceleration capable ills.
20628 				 */
20629 				ipsec_ctl_t *ipsec_ctl =
20630 				    (ipsec_ctl_t *)mp->b_rptr;
20631 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20632 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20633 				mblk_t *cmp = mp->b_cont;
20634 
20635 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20636 				ASSERT(cmp != NULL);
20637 
20638 				freeb(mp);
20639 				ill_ipsec_capab_send_all(satype, cmp, sa,
20640 				    ipst->ips_netstack);
20641 				return;
20642 			} else {
20643 				/*
20644 				 * This must be ARP or special TSOL signaling.
20645 				 */
20646 				ip_wput_nondata(NULL, q, mp, NULL);
20647 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20648 				    "ip_wput_end: q %p (%S)", q, "nondata");
20649 				return;
20650 			}
20651 		} else {
20652 			/*
20653 			 * This must be non-(ARP/AH/ESP) messages.
20654 			 */
20655 			ASSERT(!need_decref);
20656 			ip_wput_nondata(NULL, q, mp, NULL);
20657 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20658 			    "ip_wput_end: q %p (%S)", q, "nondata");
20659 			return;
20660 		}
20661 	} else {
20662 		first_mp = mp;
20663 		mctl_present = B_FALSE;
20664 	}
20665 
20666 	ASSERT(first_mp != NULL);
20667 	/*
20668 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20669 	 * to make sure that this packet goes out on the same interface it
20670 	 * came in. We handle that here.
20671 	 */
20672 	if (mctl_present) {
20673 		uint_t ifindex;
20674 
20675 		io = (ipsec_out_t *)first_mp->b_rptr;
20676 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20677 			/*
20678 			 * We may have lost the conn context if we are
20679 			 * coming here from ip_newroute(). Copy the
20680 			 * nexthop information.
20681 			 */
20682 			if (io->ipsec_out_ip_nexthop) {
20683 				ip_nexthop = B_TRUE;
20684 				nexthop_addr = io->ipsec_out_nexthop_addr;
20685 
20686 				ipha = (ipha_t *)mp->b_rptr;
20687 				dst = ipha->ipha_dst;
20688 				goto send_from_ill;
20689 			} else {
20690 				ASSERT(io->ipsec_out_ill_index != 0);
20691 				ifindex = io->ipsec_out_ill_index;
20692 				attach_ill = ill_lookup_on_ifindex(ifindex,
20693 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20694 				if (attach_ill == NULL) {
20695 					ASSERT(xmit_ill == NULL);
20696 					ip1dbg(("ip_output: bad ifindex for "
20697 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20698 					    ifindex));
20699 					freemsg(first_mp);
20700 					BUMP_MIB(&ipst->ips_ip_mib,
20701 					    ipIfStatsOutDiscards);
20702 					ASSERT(!need_decref);
20703 					return;
20704 				}
20705 			}
20706 		}
20707 	}
20708 
20709 	ASSERT(xmit_ill == NULL);
20710 
20711 	/* We have a complete IP datagram heading outbound. */
20712 	ipha = (ipha_t *)mp->b_rptr;
20713 
20714 #ifndef SPEED_BEFORE_SAFETY
20715 	/*
20716 	 * Make sure we have a full-word aligned message and that at least
20717 	 * a simple IP header is accessible in the first message.  If not,
20718 	 * try a pullup.
20719 	 */
20720 	if (!OK_32PTR(rptr) ||
20721 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20722 hdrtoosmall:
20723 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20724 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20725 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20726 			if (first_mp == NULL)
20727 				first_mp = mp;
20728 			goto discard_pkt;
20729 		}
20730 
20731 		/* This function assumes that mp points to an IPv4 packet. */
20732 		if (is_system_labeled() && q->q_next == NULL &&
20733 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20734 		    !connp->conn_ulp_labeled) {
20735 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20736 			    &adjust, connp->conn_mac_exempt, ipst);
20737 			ipha = (ipha_t *)mp->b_rptr;
20738 			if (first_mp != NULL)
20739 				first_mp->b_cont = mp;
20740 			if (err != 0) {
20741 				if (first_mp == NULL)
20742 					first_mp = mp;
20743 				if (err == EINVAL)
20744 					goto icmp_parameter_problem;
20745 				ip2dbg(("ip_wput: label check failed (%d)\n",
20746 				    err));
20747 				goto discard_pkt;
20748 			}
20749 			iplen = ntohs(ipha->ipha_length) + adjust;
20750 			ipha->ipha_length = htons(iplen);
20751 		}
20752 
20753 		ipha = (ipha_t *)mp->b_rptr;
20754 		if (first_mp == NULL) {
20755 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20756 			/*
20757 			 * If we got here because of "goto hdrtoosmall"
20758 			 * We need to attach a IPSEC_OUT.
20759 			 */
20760 			if (connp->conn_out_enforce_policy) {
20761 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20762 				    NULL, ipha->ipha_protocol,
20763 				    ipst->ips_netstack)) == NULL)) {
20764 					BUMP_MIB(&ipst->ips_ip_mib,
20765 					    ipIfStatsOutDiscards);
20766 					if (need_decref)
20767 						CONN_DEC_REF(connp);
20768 					return;
20769 				} else {
20770 					ASSERT(mp->b_datap->db_type == M_CTL);
20771 					first_mp = mp;
20772 					mp = mp->b_cont;
20773 					mctl_present = B_TRUE;
20774 				}
20775 			} else {
20776 				first_mp = mp;
20777 				mctl_present = B_FALSE;
20778 			}
20779 		}
20780 	}
20781 #endif
20782 
20783 	/* Most of the code below is written for speed, not readability */
20784 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20785 
20786 	/*
20787 	 * If ip_newroute() fails, we're going to need a full
20788 	 * header for the icmp wraparound.
20789 	 */
20790 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20791 		uint_t	v_hlen;
20792 version_hdrlen_check:
20793 		ASSERT(first_mp != NULL);
20794 		v_hlen = V_HLEN;
20795 		/*
20796 		 * siphon off IPv6 packets coming down from transport
20797 		 * layer modules here.
20798 		 * Note: high-order bit carries NUD reachability confirmation
20799 		 */
20800 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20801 			/*
20802 			 * FIXME: assume that callers of ip_output* call
20803 			 * the right version?
20804 			 */
20805 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20806 			ASSERT(xmit_ill == NULL);
20807 			if (attach_ill != NULL)
20808 				ill_refrele(attach_ill);
20809 			if (need_decref)
20810 				mp->b_flag |= MSGHASREF;
20811 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20812 			return;
20813 		}
20814 
20815 		if ((v_hlen >> 4) != IP_VERSION) {
20816 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20817 			    "ip_wput_end: q %p (%S)", q, "badvers");
20818 			goto discard_pkt;
20819 		}
20820 		/*
20821 		 * Is the header length at least 20 bytes?
20822 		 *
20823 		 * Are there enough bytes accessible in the header?  If
20824 		 * not, try a pullup.
20825 		 */
20826 		v_hlen &= 0xF;
20827 		v_hlen <<= 2;
20828 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20829 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20830 			    "ip_wput_end: q %p (%S)", q, "badlen");
20831 			goto discard_pkt;
20832 		}
20833 		if (v_hlen > (mp->b_wptr - rptr)) {
20834 			if (!pullupmsg(mp, v_hlen)) {
20835 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20836 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20837 				goto discard_pkt;
20838 			}
20839 			ipha = (ipha_t *)mp->b_rptr;
20840 		}
20841 		/*
20842 		 * Move first entry from any source route into ipha_dst and
20843 		 * verify the options
20844 		 */
20845 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20846 		    zoneid, ipst)) {
20847 			ASSERT(xmit_ill == NULL);
20848 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20849 			if (attach_ill != NULL)
20850 				ill_refrele(attach_ill);
20851 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20852 			    "ip_wput_end: q %p (%S)", q, "badopts");
20853 			if (need_decref)
20854 				CONN_DEC_REF(connp);
20855 			return;
20856 		}
20857 	}
20858 	dst = ipha->ipha_dst;
20859 
20860 	/*
20861 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20862 	 * we have to run the packet through ip_newroute which will take
20863 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20864 	 * a resolver, or assigning a default gateway, etc.
20865 	 */
20866 	if (CLASSD(dst)) {
20867 		ipif_t	*ipif;
20868 		uint32_t setsrc = 0;
20869 
20870 multicast:
20871 		ASSERT(first_mp != NULL);
20872 		ip2dbg(("ip_wput: CLASSD\n"));
20873 		if (connp == NULL) {
20874 			/*
20875 			 * Use the first good ipif on the ill.
20876 			 * XXX Should this ever happen? (Appears
20877 			 * to show up with just ppp and no ethernet due
20878 			 * to in.rdisc.)
20879 			 * However, ire_send should be able to
20880 			 * call ip_wput_ire directly.
20881 			 *
20882 			 * XXX Also, this can happen for ICMP and other packets
20883 			 * with multicast source addresses.  Perhaps we should
20884 			 * fix things so that we drop the packet in question,
20885 			 * but for now, just run with it.
20886 			 */
20887 			ill_t *ill = (ill_t *)q->q_ptr;
20888 
20889 			/*
20890 			 * Don't honor attach_if for this case. If ill
20891 			 * is part of the group, ipif could belong to
20892 			 * any ill and we cannot maintain attach_ill
20893 			 * and ipif_ill same anymore and the assert
20894 			 * below would fail.
20895 			 */
20896 			if (mctl_present && io->ipsec_out_attach_if) {
20897 				io->ipsec_out_ill_index = 0;
20898 				io->ipsec_out_attach_if = B_FALSE;
20899 				ASSERT(attach_ill != NULL);
20900 				ill_refrele(attach_ill);
20901 				attach_ill = NULL;
20902 			}
20903 
20904 			ASSERT(attach_ill == NULL);
20905 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20906 			if (ipif == NULL) {
20907 				if (need_decref)
20908 					CONN_DEC_REF(connp);
20909 				freemsg(first_mp);
20910 				return;
20911 			}
20912 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20913 			    ntohl(dst), ill->ill_name));
20914 		} else {
20915 			/*
20916 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20917 			 * and IP_MULTICAST_IF.  The block comment above this
20918 			 * function explains the locking mechanism used here.
20919 			 */
20920 			if (xmit_ill == NULL) {
20921 				xmit_ill = conn_get_held_ill(connp,
20922 				    &connp->conn_outgoing_ill, &err);
20923 				if (err == ILL_LOOKUP_FAILED) {
20924 					ip1dbg(("ip_wput: No ill for "
20925 					    "IP_BOUND_IF\n"));
20926 					BUMP_MIB(&ipst->ips_ip_mib,
20927 					    ipIfStatsOutNoRoutes);
20928 					goto drop_pkt;
20929 				}
20930 			}
20931 
20932 			if (xmit_ill == NULL) {
20933 				ipif = conn_get_held_ipif(connp,
20934 				    &connp->conn_multicast_ipif, &err);
20935 				if (err == IPIF_LOOKUP_FAILED) {
20936 					ip1dbg(("ip_wput: No ipif for "
20937 					    "multicast\n"));
20938 					BUMP_MIB(&ipst->ips_ip_mib,
20939 					    ipIfStatsOutNoRoutes);
20940 					goto drop_pkt;
20941 				}
20942 			}
20943 			if (xmit_ill != NULL) {
20944 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20945 				if (ipif == NULL) {
20946 					ip1dbg(("ip_wput: No ipif for "
20947 					    "xmit_ill\n"));
20948 					BUMP_MIB(&ipst->ips_ip_mib,
20949 					    ipIfStatsOutNoRoutes);
20950 					goto drop_pkt;
20951 				}
20952 			} else if (ipif == NULL || ipif->ipif_isv6) {
20953 				/*
20954 				 * We must do this ipif determination here
20955 				 * else we could pass through ip_newroute
20956 				 * and come back here without the conn context.
20957 				 *
20958 				 * Note: we do late binding i.e. we bind to
20959 				 * the interface when the first packet is sent.
20960 				 * For performance reasons we do not rebind on
20961 				 * each packet but keep the binding until the
20962 				 * next IP_MULTICAST_IF option.
20963 				 *
20964 				 * conn_multicast_{ipif,ill} are shared between
20965 				 * IPv4 and IPv6 and AF_INET6 sockets can
20966 				 * send both IPv4 and IPv6 packets. Hence
20967 				 * we have to check that "isv6" matches above.
20968 				 */
20969 				if (ipif != NULL)
20970 					ipif_refrele(ipif);
20971 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20972 				if (ipif == NULL) {
20973 					ip1dbg(("ip_wput: No ipif for "
20974 					    "multicast\n"));
20975 					BUMP_MIB(&ipst->ips_ip_mib,
20976 					    ipIfStatsOutNoRoutes);
20977 					goto drop_pkt;
20978 				}
20979 				err = conn_set_held_ipif(connp,
20980 				    &connp->conn_multicast_ipif, ipif);
20981 				if (err == IPIF_LOOKUP_FAILED) {
20982 					ipif_refrele(ipif);
20983 					ip1dbg(("ip_wput: No ipif for "
20984 					    "multicast\n"));
20985 					BUMP_MIB(&ipst->ips_ip_mib,
20986 					    ipIfStatsOutNoRoutes);
20987 					goto drop_pkt;
20988 				}
20989 			}
20990 		}
20991 		ASSERT(!ipif->ipif_isv6);
20992 		/*
20993 		 * As we may lose the conn by the time we reach ip_wput_ire,
20994 		 * we copy conn_multicast_loop and conn_dontroute on to an
20995 		 * ipsec_out. In case if this datagram goes out secure,
20996 		 * we need the ill_index also. Copy that also into the
20997 		 * ipsec_out.
20998 		 */
20999 		if (mctl_present) {
21000 			io = (ipsec_out_t *)first_mp->b_rptr;
21001 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21002 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21003 		} else {
21004 			ASSERT(mp == first_mp);
21005 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21006 			    BPRI_HI)) == NULL) {
21007 				ipif_refrele(ipif);
21008 				first_mp = mp;
21009 				goto discard_pkt;
21010 			}
21011 			first_mp->b_datap->db_type = M_CTL;
21012 			first_mp->b_wptr += sizeof (ipsec_info_t);
21013 			/* ipsec_out_secure is B_FALSE now */
21014 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21015 			io = (ipsec_out_t *)first_mp->b_rptr;
21016 			io->ipsec_out_type = IPSEC_OUT;
21017 			io->ipsec_out_len = sizeof (ipsec_out_t);
21018 			io->ipsec_out_use_global_policy = B_TRUE;
21019 			io->ipsec_out_ns = ipst->ips_netstack;
21020 			first_mp->b_cont = mp;
21021 			mctl_present = B_TRUE;
21022 		}
21023 		if (attach_ill != NULL) {
21024 			ASSERT(attach_ill == ipif->ipif_ill);
21025 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21026 
21027 			/*
21028 			 * Check if we need an ire that will not be
21029 			 * looked up by anybody else i.e. HIDDEN.
21030 			 */
21031 			if (ill_is_probeonly(attach_ill)) {
21032 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21033 			}
21034 			io->ipsec_out_ill_index =
21035 			    attach_ill->ill_phyint->phyint_ifindex;
21036 			io->ipsec_out_attach_if = B_TRUE;
21037 		} else {
21038 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21039 			io->ipsec_out_ill_index =
21040 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21041 		}
21042 		if (connp != NULL) {
21043 			io->ipsec_out_multicast_loop =
21044 			    connp->conn_multicast_loop;
21045 			io->ipsec_out_dontroute = connp->conn_dontroute;
21046 			io->ipsec_out_zoneid = connp->conn_zoneid;
21047 		}
21048 		/*
21049 		 * If the application uses IP_MULTICAST_IF with
21050 		 * different logical addresses of the same ILL, we
21051 		 * need to make sure that the soruce address of
21052 		 * the packet matches the logical IP address used
21053 		 * in the option. We do it by initializing ipha_src
21054 		 * here. This should keep IPsec also happy as
21055 		 * when we return from IPsec processing, we don't
21056 		 * have to worry about getting the right address on
21057 		 * the packet. Thus it is sufficient to look for
21058 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21059 		 * MATCH_IRE_IPIF.
21060 		 *
21061 		 * NOTE : We need to do it for non-secure case also as
21062 		 * this might go out secure if there is a global policy
21063 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21064 		 * address, the source should be initialized already and
21065 		 * hence we won't be initializing here.
21066 		 *
21067 		 * As we do not have the ire yet, it is possible that
21068 		 * we set the source address here and then later discover
21069 		 * that the ire implies the source address to be assigned
21070 		 * through the RTF_SETSRC flag.
21071 		 * In that case, the setsrc variable will remind us
21072 		 * that overwritting the source address by the one
21073 		 * of the RTF_SETSRC-flagged ire is allowed.
21074 		 */
21075 		if (ipha->ipha_src == INADDR_ANY &&
21076 		    (connp == NULL || !connp->conn_unspec_src)) {
21077 			ipha->ipha_src = ipif->ipif_src_addr;
21078 			setsrc = RTF_SETSRC;
21079 		}
21080 		/*
21081 		 * Find an IRE which matches the destination and the outgoing
21082 		 * queue (i.e. the outgoing interface.)
21083 		 * For loopback use a unicast IP address for
21084 		 * the ire lookup.
21085 		 */
21086 		if (IS_LOOPBACK(ipif->ipif_ill))
21087 			dst = ipif->ipif_lcl_addr;
21088 
21089 		/*
21090 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21091 		 * We don't need to lookup ire in ctable as the packet
21092 		 * needs to be sent to the destination through the specified
21093 		 * ill irrespective of ires in the cache table.
21094 		 */
21095 		ire = NULL;
21096 		if (xmit_ill == NULL) {
21097 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21098 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21099 		}
21100 
21101 		/*
21102 		 * refrele attach_ill as its not needed anymore.
21103 		 */
21104 		if (attach_ill != NULL) {
21105 			ill_refrele(attach_ill);
21106 			attach_ill = NULL;
21107 		}
21108 
21109 		if (ire == NULL) {
21110 			/*
21111 			 * Multicast loopback and multicast forwarding is
21112 			 * done in ip_wput_ire.
21113 			 *
21114 			 * Mark this packet to make it be delivered to
21115 			 * ip_wput_ire after the new ire has been
21116 			 * created.
21117 			 *
21118 			 * The call to ip_newroute_ipif takes into account
21119 			 * the setsrc reminder. In any case, we take care
21120 			 * of the RTF_MULTIRT flag.
21121 			 */
21122 			mp->b_prev = mp->b_next = NULL;
21123 			if (xmit_ill == NULL ||
21124 			    xmit_ill->ill_ipif_up_count > 0) {
21125 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21126 				    setsrc | RTF_MULTIRT, zoneid, infop);
21127 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21128 				    "ip_wput_end: q %p (%S)", q, "noire");
21129 			} else {
21130 				freemsg(first_mp);
21131 			}
21132 			ipif_refrele(ipif);
21133 			if (xmit_ill != NULL)
21134 				ill_refrele(xmit_ill);
21135 			if (need_decref)
21136 				CONN_DEC_REF(connp);
21137 			return;
21138 		}
21139 
21140 		ipif_refrele(ipif);
21141 		ipif = NULL;
21142 		ASSERT(xmit_ill == NULL);
21143 
21144 		/*
21145 		 * Honor the RTF_SETSRC flag for multicast packets,
21146 		 * if allowed by the setsrc reminder.
21147 		 */
21148 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21149 			ipha->ipha_src = ire->ire_src_addr;
21150 		}
21151 
21152 		/*
21153 		 * Unconditionally force the TTL to 1 for
21154 		 * multirouted multicast packets:
21155 		 * multirouted multicast should not cross
21156 		 * multicast routers.
21157 		 */
21158 		if (ire->ire_flags & RTF_MULTIRT) {
21159 			if (ipha->ipha_ttl > 1) {
21160 				ip2dbg(("ip_wput: forcing multicast "
21161 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21162 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21163 				ipha->ipha_ttl = 1;
21164 			}
21165 		}
21166 	} else {
21167 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21168 		if ((ire != NULL) && (ire->ire_type &
21169 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21170 			ignore_dontroute = B_TRUE;
21171 			ignore_nexthop = B_TRUE;
21172 		}
21173 		if (ire != NULL) {
21174 			ire_refrele(ire);
21175 			ire = NULL;
21176 		}
21177 		/*
21178 		 * Guard against coming in from arp in which case conn is NULL.
21179 		 * Also guard against non M_DATA with dontroute set but
21180 		 * destined to local, loopback or broadcast addresses.
21181 		 */
21182 		if (connp != NULL && connp->conn_dontroute &&
21183 		    !ignore_dontroute) {
21184 dontroute:
21185 			/*
21186 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21187 			 * routing protocols from seeing false direct
21188 			 * connectivity.
21189 			 */
21190 			ipha->ipha_ttl = 1;
21191 
21192 			/* If suitable ipif not found, drop packet */
21193 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21194 			if (dst_ipif == NULL) {
21195 noroute:
21196 				ip1dbg(("ip_wput: no route for dst using"
21197 				    " SO_DONTROUTE\n"));
21198 				BUMP_MIB(&ipst->ips_ip_mib,
21199 				    ipIfStatsOutNoRoutes);
21200 				mp->b_prev = mp->b_next = NULL;
21201 				if (first_mp == NULL)
21202 					first_mp = mp;
21203 				goto drop_pkt;
21204 			} else {
21205 				/*
21206 				 * If suitable ipif has been found, set
21207 				 * xmit_ill to the corresponding
21208 				 * ipif_ill because we'll be using the
21209 				 * send_from_ill logic below.
21210 				 */
21211 				ASSERT(xmit_ill == NULL);
21212 				xmit_ill = dst_ipif->ipif_ill;
21213 				mutex_enter(&xmit_ill->ill_lock);
21214 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21215 					mutex_exit(&xmit_ill->ill_lock);
21216 					xmit_ill = NULL;
21217 					ipif_refrele(dst_ipif);
21218 					goto noroute;
21219 				}
21220 				ill_refhold_locked(xmit_ill);
21221 				mutex_exit(&xmit_ill->ill_lock);
21222 				ipif_refrele(dst_ipif);
21223 			}
21224 		}
21225 		/*
21226 		 * If we are bound to IPIF_NOFAILOVER address, look for
21227 		 * an IRE_CACHE matching the ill.
21228 		 */
21229 send_from_ill:
21230 		if (attach_ill != NULL) {
21231 			ipif_t	*attach_ipif;
21232 
21233 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21234 
21235 			/*
21236 			 * Check if we need an ire that will not be
21237 			 * looked up by anybody else i.e. HIDDEN.
21238 			 */
21239 			if (ill_is_probeonly(attach_ill)) {
21240 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21241 			}
21242 
21243 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21244 			if (attach_ipif == NULL) {
21245 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21246 				goto discard_pkt;
21247 			}
21248 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21249 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21250 			ipif_refrele(attach_ipif);
21251 		} else if (xmit_ill != NULL) {
21252 			ipif_t *ipif;
21253 
21254 			/*
21255 			 * Mark this packet as originated locally
21256 			 */
21257 			mp->b_prev = mp->b_next = NULL;
21258 
21259 			/*
21260 			 * Could be SO_DONTROUTE case also.
21261 			 * Verify that at least one ipif is up on the ill.
21262 			 */
21263 			if (xmit_ill->ill_ipif_up_count == 0) {
21264 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21265 				    xmit_ill->ill_name));
21266 				goto drop_pkt;
21267 			}
21268 
21269 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21270 			if (ipif == NULL) {
21271 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21272 				    xmit_ill->ill_name));
21273 				goto drop_pkt;
21274 			}
21275 
21276 			/*
21277 			 * Look for a ire that is part of the group,
21278 			 * if found use it else call ip_newroute_ipif.
21279 			 * IPCL_ZONEID is not used for matching because
21280 			 * IP_ALLZONES option is valid only when the
21281 			 * ill is accessible from all zones i.e has a
21282 			 * valid ipif in all zones.
21283 			 */
21284 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21285 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21286 			    MBLK_GETLABEL(mp), match_flags, ipst);
21287 			/*
21288 			 * If an ire exists use it or else create
21289 			 * an ire but don't add it to the cache.
21290 			 * Adding an ire may cause issues with
21291 			 * asymmetric routing.
21292 			 * In case of multiroute always act as if
21293 			 * ire does not exist.
21294 			 */
21295 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21296 				if (ire != NULL)
21297 					ire_refrele(ire);
21298 				ip_newroute_ipif(q, first_mp, ipif,
21299 				    dst, connp, 0, zoneid, infop);
21300 				ipif_refrele(ipif);
21301 				ip1dbg(("ip_output: xmit_ill via %s\n",
21302 				    xmit_ill->ill_name));
21303 				ill_refrele(xmit_ill);
21304 				if (need_decref)
21305 					CONN_DEC_REF(connp);
21306 				return;
21307 			}
21308 			ipif_refrele(ipif);
21309 		} else if (ip_nexthop || (connp != NULL &&
21310 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21311 			if (!ip_nexthop) {
21312 				ip_nexthop = B_TRUE;
21313 				nexthop_addr = connp->conn_nexthop_v4;
21314 			}
21315 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21316 			    MATCH_IRE_GW;
21317 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21318 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21319 		} else {
21320 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21321 			    ipst);
21322 		}
21323 		if (!ire) {
21324 			/*
21325 			 * Make sure we don't load spread if this
21326 			 * is IPIF_NOFAILOVER case.
21327 			 */
21328 			if ((attach_ill != NULL) ||
21329 			    (ip_nexthop && !ignore_nexthop)) {
21330 				if (mctl_present) {
21331 					io = (ipsec_out_t *)first_mp->b_rptr;
21332 					ASSERT(first_mp->b_datap->db_type ==
21333 					    M_CTL);
21334 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21335 				} else {
21336 					ASSERT(mp == first_mp);
21337 					first_mp = allocb(
21338 					    sizeof (ipsec_info_t), BPRI_HI);
21339 					if (first_mp == NULL) {
21340 						first_mp = mp;
21341 						goto discard_pkt;
21342 					}
21343 					first_mp->b_datap->db_type = M_CTL;
21344 					first_mp->b_wptr +=
21345 					    sizeof (ipsec_info_t);
21346 					/* ipsec_out_secure is B_FALSE now */
21347 					bzero(first_mp->b_rptr,
21348 					    sizeof (ipsec_info_t));
21349 					io = (ipsec_out_t *)first_mp->b_rptr;
21350 					io->ipsec_out_type = IPSEC_OUT;
21351 					io->ipsec_out_len =
21352 					    sizeof (ipsec_out_t);
21353 					io->ipsec_out_use_global_policy =
21354 					    B_TRUE;
21355 					io->ipsec_out_ns = ipst->ips_netstack;
21356 					first_mp->b_cont = mp;
21357 					mctl_present = B_TRUE;
21358 				}
21359 				if (attach_ill != NULL) {
21360 					io->ipsec_out_ill_index = attach_ill->
21361 					    ill_phyint->phyint_ifindex;
21362 					io->ipsec_out_attach_if = B_TRUE;
21363 				} else {
21364 					io->ipsec_out_ip_nexthop = ip_nexthop;
21365 					io->ipsec_out_nexthop_addr =
21366 					    nexthop_addr;
21367 				}
21368 			}
21369 noirefound:
21370 			/*
21371 			 * Mark this packet as having originated on
21372 			 * this machine.  This will be noted in
21373 			 * ire_add_then_send, which needs to know
21374 			 * whether to run it back through ip_wput or
21375 			 * ip_rput following successful resolution.
21376 			 */
21377 			mp->b_prev = NULL;
21378 			mp->b_next = NULL;
21379 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21380 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21381 			    "ip_wput_end: q %p (%S)", q, "newroute");
21382 			if (attach_ill != NULL)
21383 				ill_refrele(attach_ill);
21384 			if (xmit_ill != NULL)
21385 				ill_refrele(xmit_ill);
21386 			if (need_decref)
21387 				CONN_DEC_REF(connp);
21388 			return;
21389 		}
21390 	}
21391 
21392 	/* We now know where we are going with it. */
21393 
21394 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21395 	    "ip_wput_end: q %p (%S)", q, "end");
21396 
21397 	/*
21398 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21399 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21400 	 */
21401 	if (ire->ire_flags & RTF_MULTIRT) {
21402 		/*
21403 		 * Force the TTL of multirouted packets if required.
21404 		 * The TTL of such packets is bounded by the
21405 		 * ip_multirt_ttl ndd variable.
21406 		 */
21407 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21408 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21409 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21410 			    "(was %d), dst 0x%08x\n",
21411 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21412 			    ntohl(ire->ire_addr)));
21413 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21414 		}
21415 		/*
21416 		 * At this point, we check to see if there are any pending
21417 		 * unresolved routes. ire_multirt_resolvable()
21418 		 * checks in O(n) that all IRE_OFFSUBNET ire
21419 		 * entries for the packet's destination and
21420 		 * flagged RTF_MULTIRT are currently resolved.
21421 		 * If some remain unresolved, we make a copy
21422 		 * of the current message. It will be used
21423 		 * to initiate additional route resolutions.
21424 		 */
21425 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21426 		    MBLK_GETLABEL(first_mp), ipst);
21427 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21428 		    "multirt_need_resolve %d, first_mp %p\n",
21429 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21430 		if (multirt_need_resolve) {
21431 			copy_mp = copymsg(first_mp);
21432 			if (copy_mp != NULL) {
21433 				MULTIRT_DEBUG_TAG(copy_mp);
21434 			}
21435 		}
21436 	}
21437 
21438 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21439 	/*
21440 	 * Try to resolve another multiroute if
21441 	 * ire_multirt_resolvable() deemed it necessary.
21442 	 * At this point, we need to distinguish
21443 	 * multicasts from other packets. For multicasts,
21444 	 * we call ip_newroute_ipif() and request that both
21445 	 * multirouting and setsrc flags are checked.
21446 	 */
21447 	if (copy_mp != NULL) {
21448 		if (CLASSD(dst)) {
21449 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21450 			if (ipif) {
21451 				ASSERT(infop->ip_opt_ill_index == 0);
21452 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21453 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21454 				ipif_refrele(ipif);
21455 			} else {
21456 				MULTIRT_DEBUG_UNTAG(copy_mp);
21457 				freemsg(copy_mp);
21458 				copy_mp = NULL;
21459 			}
21460 		} else {
21461 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21462 		}
21463 	}
21464 	if (attach_ill != NULL)
21465 		ill_refrele(attach_ill);
21466 	if (xmit_ill != NULL)
21467 		ill_refrele(xmit_ill);
21468 	if (need_decref)
21469 		CONN_DEC_REF(connp);
21470 	return;
21471 
21472 icmp_parameter_problem:
21473 	/* could not have originated externally */
21474 	ASSERT(mp->b_prev == NULL);
21475 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21476 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21477 		/* it's the IP header length that's in trouble */
21478 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21479 		first_mp = NULL;
21480 	}
21481 
21482 discard_pkt:
21483 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21484 drop_pkt:
21485 	ip1dbg(("ip_wput: dropped packet\n"));
21486 	if (ire != NULL)
21487 		ire_refrele(ire);
21488 	if (need_decref)
21489 		CONN_DEC_REF(connp);
21490 	freemsg(first_mp);
21491 	if (attach_ill != NULL)
21492 		ill_refrele(attach_ill);
21493 	if (xmit_ill != NULL)
21494 		ill_refrele(xmit_ill);
21495 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21496 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21497 }
21498 
21499 /*
21500  * If this is a conn_t queue, then we pass in the conn. This includes the
21501  * zoneid.
21502  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21503  * in which case we use the global zoneid since those are all part of
21504  * the global zone.
21505  */
21506 void
21507 ip_wput(queue_t *q, mblk_t *mp)
21508 {
21509 	if (CONN_Q(q))
21510 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21511 	else
21512 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21513 }
21514 
21515 /*
21516  *
21517  * The following rules must be observed when accessing any ipif or ill
21518  * that has been cached in the conn. Typically conn_nofailover_ill,
21519  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21520  *
21521  * Access: The ipif or ill pointed to from the conn can be accessed under
21522  * the protection of the conn_lock or after it has been refheld under the
21523  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21524  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21525  * The reason for this is that a concurrent unplumb could actually be
21526  * cleaning up these cached pointers by walking the conns and might have
21527  * finished cleaning up the conn in question. The macros check that an
21528  * unplumb has not yet started on the ipif or ill.
21529  *
21530  * Caching: An ipif or ill pointer may be cached in the conn only after
21531  * making sure that an unplumb has not started. So the caching is done
21532  * while holding both the conn_lock and the ill_lock and after using the
21533  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21534  * flag before starting the cleanup of conns.
21535  *
21536  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21537  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21538  * or a reference to the ipif or a reference to an ire that references the
21539  * ipif. An ipif does not change its ill except for failover/failback. Since
21540  * failover/failback happens only after bringing down the ipif and making sure
21541  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21542  * the above holds.
21543  */
21544 ipif_t *
21545 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21546 {
21547 	ipif_t	*ipif;
21548 	ill_t	*ill;
21549 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21550 
21551 	*err = 0;
21552 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21553 	mutex_enter(&connp->conn_lock);
21554 	ipif = *ipifp;
21555 	if (ipif != NULL) {
21556 		ill = ipif->ipif_ill;
21557 		mutex_enter(&ill->ill_lock);
21558 		if (IPIF_CAN_LOOKUP(ipif)) {
21559 			ipif_refhold_locked(ipif);
21560 			mutex_exit(&ill->ill_lock);
21561 			mutex_exit(&connp->conn_lock);
21562 			rw_exit(&ipst->ips_ill_g_lock);
21563 			return (ipif);
21564 		} else {
21565 			*err = IPIF_LOOKUP_FAILED;
21566 		}
21567 		mutex_exit(&ill->ill_lock);
21568 	}
21569 	mutex_exit(&connp->conn_lock);
21570 	rw_exit(&ipst->ips_ill_g_lock);
21571 	return (NULL);
21572 }
21573 
21574 ill_t *
21575 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21576 {
21577 	ill_t	*ill;
21578 
21579 	*err = 0;
21580 	mutex_enter(&connp->conn_lock);
21581 	ill = *illp;
21582 	if (ill != NULL) {
21583 		mutex_enter(&ill->ill_lock);
21584 		if (ILL_CAN_LOOKUP(ill)) {
21585 			ill_refhold_locked(ill);
21586 			mutex_exit(&ill->ill_lock);
21587 			mutex_exit(&connp->conn_lock);
21588 			return (ill);
21589 		} else {
21590 			*err = ILL_LOOKUP_FAILED;
21591 		}
21592 		mutex_exit(&ill->ill_lock);
21593 	}
21594 	mutex_exit(&connp->conn_lock);
21595 	return (NULL);
21596 }
21597 
21598 static int
21599 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21600 {
21601 	ill_t	*ill;
21602 
21603 	ill = ipif->ipif_ill;
21604 	mutex_enter(&connp->conn_lock);
21605 	mutex_enter(&ill->ill_lock);
21606 	if (IPIF_CAN_LOOKUP(ipif)) {
21607 		*ipifp = ipif;
21608 		mutex_exit(&ill->ill_lock);
21609 		mutex_exit(&connp->conn_lock);
21610 		return (0);
21611 	}
21612 	mutex_exit(&ill->ill_lock);
21613 	mutex_exit(&connp->conn_lock);
21614 	return (IPIF_LOOKUP_FAILED);
21615 }
21616 
21617 /*
21618  * This is called if the outbound datagram needs fragmentation.
21619  *
21620  * NOTE : This function does not ire_refrele the ire argument passed in.
21621  */
21622 static void
21623 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21624     ip_stack_t *ipst)
21625 {
21626 	ipha_t		*ipha;
21627 	mblk_t		*mp;
21628 	uint32_t	v_hlen_tos_len;
21629 	uint32_t	max_frag;
21630 	uint32_t	frag_flag;
21631 	boolean_t	dont_use;
21632 
21633 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21634 		mp = ipsec_mp->b_cont;
21635 	} else {
21636 		mp = ipsec_mp;
21637 	}
21638 
21639 	ipha = (ipha_t *)mp->b_rptr;
21640 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21641 
21642 #ifdef	_BIG_ENDIAN
21643 #define	V_HLEN	(v_hlen_tos_len >> 24)
21644 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21645 #else
21646 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21647 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21648 #endif
21649 
21650 #ifndef SPEED_BEFORE_SAFETY
21651 	/*
21652 	 * Check that ipha_length is consistent with
21653 	 * the mblk length
21654 	 */
21655 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21656 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21657 		    LENGTH, msgdsize(mp)));
21658 		freemsg(ipsec_mp);
21659 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21660 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21661 		    "packet length mismatch");
21662 		return;
21663 	}
21664 #endif
21665 	/*
21666 	 * Don't use frag_flag if pre-built packet or source
21667 	 * routed or if multicast (since multicast packets do not solicit
21668 	 * ICMP "packet too big" messages). Get the values of
21669 	 * max_frag and frag_flag atomically by acquiring the
21670 	 * ire_lock.
21671 	 */
21672 	mutex_enter(&ire->ire_lock);
21673 	max_frag = ire->ire_max_frag;
21674 	frag_flag = ire->ire_frag_flag;
21675 	mutex_exit(&ire->ire_lock);
21676 
21677 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21678 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21679 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21680 
21681 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21682 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21683 }
21684 
21685 /*
21686  * Used for deciding the MSS size for the upper layer. Thus
21687  * we need to check the outbound policy values in the conn.
21688  */
21689 int
21690 conn_ipsec_length(conn_t *connp)
21691 {
21692 	ipsec_latch_t *ipl;
21693 
21694 	ipl = connp->conn_latch;
21695 	if (ipl == NULL)
21696 		return (0);
21697 
21698 	if (ipl->ipl_out_policy == NULL)
21699 		return (0);
21700 
21701 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21702 }
21703 
21704 /*
21705  * Returns an estimate of the IPsec headers size. This is used if
21706  * we don't want to call into IPsec to get the exact size.
21707  */
21708 int
21709 ipsec_out_extra_length(mblk_t *ipsec_mp)
21710 {
21711 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21712 	ipsec_action_t *a;
21713 
21714 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21715 	if (!io->ipsec_out_secure)
21716 		return (0);
21717 
21718 	a = io->ipsec_out_act;
21719 
21720 	if (a == NULL) {
21721 		ASSERT(io->ipsec_out_policy != NULL);
21722 		a = io->ipsec_out_policy->ipsp_act;
21723 	}
21724 	ASSERT(a != NULL);
21725 
21726 	return (a->ipa_ovhd);
21727 }
21728 
21729 /*
21730  * Returns an estimate of the IPsec headers size. This is used if
21731  * we don't want to call into IPsec to get the exact size.
21732  */
21733 int
21734 ipsec_in_extra_length(mblk_t *ipsec_mp)
21735 {
21736 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21737 	ipsec_action_t *a;
21738 
21739 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21740 
21741 	a = ii->ipsec_in_action;
21742 	return (a == NULL ? 0 : a->ipa_ovhd);
21743 }
21744 
21745 /*
21746  * If there are any source route options, return the true final
21747  * destination. Otherwise, return the destination.
21748  */
21749 ipaddr_t
21750 ip_get_dst(ipha_t *ipha)
21751 {
21752 	ipoptp_t	opts;
21753 	uchar_t		*opt;
21754 	uint8_t		optval;
21755 	uint8_t		optlen;
21756 	ipaddr_t	dst;
21757 	uint32_t off;
21758 
21759 	dst = ipha->ipha_dst;
21760 
21761 	if (IS_SIMPLE_IPH(ipha))
21762 		return (dst);
21763 
21764 	for (optval = ipoptp_first(&opts, ipha);
21765 	    optval != IPOPT_EOL;
21766 	    optval = ipoptp_next(&opts)) {
21767 		opt = opts.ipoptp_cur;
21768 		optlen = opts.ipoptp_len;
21769 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21770 		switch (optval) {
21771 		case IPOPT_SSRR:
21772 		case IPOPT_LSRR:
21773 			off = opt[IPOPT_OFFSET];
21774 			/*
21775 			 * If one of the conditions is true, it means
21776 			 * end of options and dst already has the right
21777 			 * value.
21778 			 */
21779 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21780 				off = optlen - IP_ADDR_LEN;
21781 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21782 			}
21783 			return (dst);
21784 		default:
21785 			break;
21786 		}
21787 	}
21788 
21789 	return (dst);
21790 }
21791 
21792 mblk_t *
21793 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21794     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21795 {
21796 	ipsec_out_t	*io;
21797 	mblk_t		*first_mp;
21798 	boolean_t policy_present;
21799 	ip_stack_t	*ipst;
21800 	ipsec_stack_t	*ipss;
21801 
21802 	ASSERT(ire != NULL);
21803 	ipst = ire->ire_ipst;
21804 	ipss = ipst->ips_netstack->netstack_ipsec;
21805 
21806 	first_mp = mp;
21807 	if (mp->b_datap->db_type == M_CTL) {
21808 		io = (ipsec_out_t *)first_mp->b_rptr;
21809 		/*
21810 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21811 		 *
21812 		 * 1) There is per-socket policy (including cached global
21813 		 *    policy) or a policy on the IP-in-IP tunnel.
21814 		 * 2) There is no per-socket policy, but it is
21815 		 *    a multicast packet that needs to go out
21816 		 *    on a specific interface. This is the case
21817 		 *    where (ip_wput and ip_wput_multicast) attaches
21818 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21819 		 *
21820 		 * In case (2) we check with global policy to
21821 		 * see if there is a match and set the ill_index
21822 		 * appropriately so that we can lookup the ire
21823 		 * properly in ip_wput_ipsec_out.
21824 		 */
21825 
21826 		/*
21827 		 * ipsec_out_use_global_policy is set to B_FALSE
21828 		 * in ipsec_in_to_out(). Refer to that function for
21829 		 * details.
21830 		 */
21831 		if ((io->ipsec_out_latch == NULL) &&
21832 		    (io->ipsec_out_use_global_policy)) {
21833 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21834 			    ire, connp, unspec_src, zoneid));
21835 		}
21836 		if (!io->ipsec_out_secure) {
21837 			/*
21838 			 * If this is not a secure packet, drop
21839 			 * the IPSEC_OUT mp and treat it as a clear
21840 			 * packet. This happens when we are sending
21841 			 * a ICMP reply back to a clear packet. See
21842 			 * ipsec_in_to_out() for details.
21843 			 */
21844 			mp = first_mp->b_cont;
21845 			freeb(first_mp);
21846 		}
21847 		return (mp);
21848 	}
21849 	/*
21850 	 * See whether we need to attach a global policy here. We
21851 	 * don't depend on the conn (as it could be null) for deciding
21852 	 * what policy this datagram should go through because it
21853 	 * should have happened in ip_wput if there was some
21854 	 * policy. This normally happens for connections which are not
21855 	 * fully bound preventing us from caching policies in
21856 	 * ip_bind. Packets coming from the TCP listener/global queue
21857 	 * - which are non-hard_bound - could also be affected by
21858 	 * applying policy here.
21859 	 *
21860 	 * If this packet is coming from tcp global queue or listener,
21861 	 * we will be applying policy here.  This may not be *right*
21862 	 * if these packets are coming from the detached connection as
21863 	 * it could have gone in clear before. This happens only if a
21864 	 * TCP connection started when there is no policy and somebody
21865 	 * added policy before it became detached. Thus packets of the
21866 	 * detached connection could go out secure and the other end
21867 	 * would drop it because it will be expecting in clear. The
21868 	 * converse is not true i.e if somebody starts a TCP
21869 	 * connection and deletes the policy, all the packets will
21870 	 * still go out with the policy that existed before deleting
21871 	 * because ip_unbind sends up policy information which is used
21872 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21873 	 * TCP to attach a dummy IPSEC_OUT and set
21874 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21875 	 * affect performance for normal cases, we are not doing it.
21876 	 * Thus, set policy before starting any TCP connections.
21877 	 *
21878 	 * NOTE - We might apply policy even for a hard bound connection
21879 	 * - for which we cached policy in ip_bind - if somebody added
21880 	 * global policy after we inherited the policy in ip_bind.
21881 	 * This means that the packets that were going out in clear
21882 	 * previously would start going secure and hence get dropped
21883 	 * on the other side. To fix this, TCP attaches a dummy
21884 	 * ipsec_out and make sure that we don't apply global policy.
21885 	 */
21886 	if (ipha != NULL)
21887 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21888 	else
21889 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21890 	if (!policy_present)
21891 		return (mp);
21892 
21893 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21894 	    zoneid));
21895 }
21896 
21897 ire_t *
21898 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21899 {
21900 	ipaddr_t addr;
21901 	ire_t *save_ire;
21902 	irb_t *irb;
21903 	ill_group_t *illgrp;
21904 	int	err;
21905 
21906 	save_ire = ire;
21907 	addr = ire->ire_addr;
21908 
21909 	ASSERT(ire->ire_type == IRE_BROADCAST);
21910 
21911 	illgrp = connp->conn_outgoing_ill->ill_group;
21912 	if (illgrp == NULL) {
21913 		*conn_outgoing_ill = conn_get_held_ill(connp,
21914 		    &connp->conn_outgoing_ill, &err);
21915 		if (err == ILL_LOOKUP_FAILED) {
21916 			ire_refrele(save_ire);
21917 			return (NULL);
21918 		}
21919 		return (save_ire);
21920 	}
21921 	/*
21922 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21923 	 * If it is part of the group, we need to send on the ire
21924 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21925 	 * to this group. This is okay as IP_BOUND_IF really means
21926 	 * any ill in the group. We depend on the fact that the
21927 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21928 	 * if such an ire exists. This is possible only if you have
21929 	 * at least one ill in the group that has not failed.
21930 	 *
21931 	 * First get to the ire that matches the address and group.
21932 	 *
21933 	 * We don't look for an ire with a matching zoneid because a given zone
21934 	 * won't always have broadcast ires on all ills in the group.
21935 	 */
21936 	irb = ire->ire_bucket;
21937 	rw_enter(&irb->irb_lock, RW_READER);
21938 	if (ire->ire_marks & IRE_MARK_NORECV) {
21939 		/*
21940 		 * If the current zone only has an ire broadcast for this
21941 		 * address marked NORECV, the ire we want is ahead in the
21942 		 * bucket, so we look it up deliberately ignoring the zoneid.
21943 		 */
21944 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21945 			if (ire->ire_addr != addr)
21946 				continue;
21947 			/* skip over deleted ires */
21948 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21949 				continue;
21950 		}
21951 	}
21952 	while (ire != NULL) {
21953 		/*
21954 		 * If a new interface is coming up, we could end up
21955 		 * seeing the loopback ire and the non-loopback ire
21956 		 * may not have been added yet. So check for ire_stq
21957 		 */
21958 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21959 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21960 			break;
21961 		}
21962 		ire = ire->ire_next;
21963 	}
21964 	if (ire != NULL && ire->ire_addr == addr &&
21965 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21966 		IRE_REFHOLD(ire);
21967 		rw_exit(&irb->irb_lock);
21968 		ire_refrele(save_ire);
21969 		*conn_outgoing_ill = ire_to_ill(ire);
21970 		/*
21971 		 * Refhold the ill to make the conn_outgoing_ill
21972 		 * independent of the ire. ip_wput_ire goes in a loop
21973 		 * and may refrele the ire. Since we have an ire at this
21974 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21975 		 */
21976 		ill_refhold(*conn_outgoing_ill);
21977 		return (ire);
21978 	}
21979 	rw_exit(&irb->irb_lock);
21980 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21981 	/*
21982 	 * If we can't find a suitable ire, return the original ire.
21983 	 */
21984 	return (save_ire);
21985 }
21986 
21987 /*
21988  * This function does the ire_refrele of the ire passed in as the
21989  * argument. As this function looks up more ires i.e broadcast ires,
21990  * it needs to REFRELE them. Currently, for simplicity we don't
21991  * differentiate the one passed in and looked up here. We always
21992  * REFRELE.
21993  * IPQoS Notes:
21994  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21995  * IPsec packets are done in ipsec_out_process.
21996  *
21997  */
21998 void
21999 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22000     zoneid_t zoneid)
22001 {
22002 	ipha_t		*ipha;
22003 #define	rptr	((uchar_t *)ipha)
22004 	queue_t		*stq;
22005 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22006 	uint32_t	v_hlen_tos_len;
22007 	uint32_t	ttl_protocol;
22008 	ipaddr_t	src;
22009 	ipaddr_t	dst;
22010 	uint32_t	cksum;
22011 	ipaddr_t	orig_src;
22012 	ire_t		*ire1;
22013 	mblk_t		*next_mp;
22014 	uint_t		hlen;
22015 	uint16_t	*up;
22016 	uint32_t	max_frag = ire->ire_max_frag;
22017 	ill_t		*ill = ire_to_ill(ire);
22018 	int		clusterwide;
22019 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22020 	int		ipsec_len;
22021 	mblk_t		*first_mp;
22022 	ipsec_out_t	*io;
22023 	boolean_t	conn_dontroute;		/* conn value for multicast */
22024 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22025 	boolean_t	multicast_forward;	/* Should we forward ? */
22026 	boolean_t	unspec_src;
22027 	ill_t		*conn_outgoing_ill = NULL;
22028 	ill_t		*ire_ill;
22029 	ill_t		*ire1_ill;
22030 	ill_t		*out_ill;
22031 	uint32_t 	ill_index = 0;
22032 	boolean_t	multirt_send = B_FALSE;
22033 	int		err;
22034 	ipxmit_state_t	pktxmit_state;
22035 	ip_stack_t	*ipst = ire->ire_ipst;
22036 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22037 
22038 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22039 	    "ip_wput_ire_start: q %p", q);
22040 
22041 	multicast_forward = B_FALSE;
22042 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22043 
22044 	if (ire->ire_flags & RTF_MULTIRT) {
22045 		/*
22046 		 * Multirouting case. The bucket where ire is stored
22047 		 * probably holds other RTF_MULTIRT flagged ire
22048 		 * to the destination. In this call to ip_wput_ire,
22049 		 * we attempt to send the packet through all
22050 		 * those ires. Thus, we first ensure that ire is the
22051 		 * first RTF_MULTIRT ire in the bucket,
22052 		 * before walking the ire list.
22053 		 */
22054 		ire_t *first_ire;
22055 		irb_t *irb = ire->ire_bucket;
22056 		ASSERT(irb != NULL);
22057 
22058 		/* Make sure we do not omit any multiroute ire. */
22059 		IRB_REFHOLD(irb);
22060 		for (first_ire = irb->irb_ire;
22061 		    first_ire != NULL;
22062 		    first_ire = first_ire->ire_next) {
22063 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22064 			    (first_ire->ire_addr == ire->ire_addr) &&
22065 			    !(first_ire->ire_marks &
22066 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22067 				break;
22068 			}
22069 		}
22070 
22071 		if ((first_ire != NULL) && (first_ire != ire)) {
22072 			IRE_REFHOLD(first_ire);
22073 			ire_refrele(ire);
22074 			ire = first_ire;
22075 			ill = ire_to_ill(ire);
22076 		}
22077 		IRB_REFRELE(irb);
22078 	}
22079 
22080 	/*
22081 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22082 	 * for performance we don't grab the mutexs in the fastpath
22083 	 */
22084 	if ((connp != NULL) &&
22085 	    (ire->ire_type == IRE_BROADCAST) &&
22086 	    ((connp->conn_nofailover_ill != NULL) ||
22087 	    (connp->conn_outgoing_ill != NULL))) {
22088 		/*
22089 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22090 		 * option. So, see if this endpoint is bound to a
22091 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22092 		 * that if the interface is failed, we will still send
22093 		 * the packet on the same ill which is what we want.
22094 		 */
22095 		conn_outgoing_ill = conn_get_held_ill(connp,
22096 		    &connp->conn_nofailover_ill, &err);
22097 		if (err == ILL_LOOKUP_FAILED) {
22098 			ire_refrele(ire);
22099 			freemsg(mp);
22100 			return;
22101 		}
22102 		if (conn_outgoing_ill == NULL) {
22103 			/*
22104 			 * Choose a good ill in the group to send the
22105 			 * packets on.
22106 			 */
22107 			ire = conn_set_outgoing_ill(connp, ire,
22108 			    &conn_outgoing_ill);
22109 			if (ire == NULL) {
22110 				freemsg(mp);
22111 				return;
22112 			}
22113 		}
22114 	}
22115 
22116 	if (mp->b_datap->db_type != M_CTL) {
22117 		ipha = (ipha_t *)mp->b_rptr;
22118 	} else {
22119 		io = (ipsec_out_t *)mp->b_rptr;
22120 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22121 		ASSERT(zoneid == io->ipsec_out_zoneid);
22122 		ASSERT(zoneid != ALL_ZONES);
22123 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22124 		dst = ipha->ipha_dst;
22125 		/*
22126 		 * For the multicast case, ipsec_out carries conn_dontroute and
22127 		 * conn_multicast_loop as conn may not be available here. We
22128 		 * need this for multicast loopback and forwarding which is done
22129 		 * later in the code.
22130 		 */
22131 		if (CLASSD(dst)) {
22132 			conn_dontroute = io->ipsec_out_dontroute;
22133 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22134 			/*
22135 			 * If conn_dontroute is not set or conn_multicast_loop
22136 			 * is set, we need to do forwarding/loopback. For
22137 			 * datagrams from ip_wput_multicast, conn_dontroute is
22138 			 * set to B_TRUE and conn_multicast_loop is set to
22139 			 * B_FALSE so that we neither do forwarding nor
22140 			 * loopback.
22141 			 */
22142 			if (!conn_dontroute || conn_multicast_loop)
22143 				multicast_forward = B_TRUE;
22144 		}
22145 	}
22146 
22147 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22148 	    ire->ire_zoneid != ALL_ZONES) {
22149 		/*
22150 		 * When a zone sends a packet to another zone, we try to deliver
22151 		 * the packet under the same conditions as if the destination
22152 		 * was a real node on the network. To do so, we look for a
22153 		 * matching route in the forwarding table.
22154 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22155 		 * ip_newroute() does.
22156 		 * Note that IRE_LOCAL are special, since they are used
22157 		 * when the zoneid doesn't match in some cases. This means that
22158 		 * we need to handle ipha_src differently since ire_src_addr
22159 		 * belongs to the receiving zone instead of the sending zone.
22160 		 * When ip_restrict_interzone_loopback is set, then
22161 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22162 		 * for loopback between zones when the logical "Ethernet" would
22163 		 * have looped them back.
22164 		 */
22165 		ire_t *src_ire;
22166 
22167 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22168 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22169 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22170 		if (src_ire != NULL &&
22171 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22172 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22173 		    ire_local_same_ill_group(ire, src_ire))) {
22174 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22175 				ipha->ipha_src = src_ire->ire_src_addr;
22176 			ire_refrele(src_ire);
22177 		} else {
22178 			ire_refrele(ire);
22179 			if (conn_outgoing_ill != NULL)
22180 				ill_refrele(conn_outgoing_ill);
22181 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22182 			if (src_ire != NULL) {
22183 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22184 					ire_refrele(src_ire);
22185 					freemsg(mp);
22186 					return;
22187 				}
22188 				ire_refrele(src_ire);
22189 			}
22190 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22191 				/* Failed */
22192 				freemsg(mp);
22193 				return;
22194 			}
22195 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22196 			    ipst);
22197 			return;
22198 		}
22199 	}
22200 
22201 	if (mp->b_datap->db_type == M_CTL ||
22202 	    ipss->ipsec_outbound_v4_policy_present) {
22203 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22204 		    unspec_src, zoneid);
22205 		if (mp == NULL) {
22206 			ire_refrele(ire);
22207 			if (conn_outgoing_ill != NULL)
22208 				ill_refrele(conn_outgoing_ill);
22209 			return;
22210 		}
22211 	}
22212 
22213 	first_mp = mp;
22214 	ipsec_len = 0;
22215 
22216 	if (first_mp->b_datap->db_type == M_CTL) {
22217 		io = (ipsec_out_t *)first_mp->b_rptr;
22218 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22219 		mp = first_mp->b_cont;
22220 		ipsec_len = ipsec_out_extra_length(first_mp);
22221 		ASSERT(ipsec_len >= 0);
22222 		/* We already picked up the zoneid from the M_CTL above */
22223 		ASSERT(zoneid == io->ipsec_out_zoneid);
22224 		ASSERT(zoneid != ALL_ZONES);
22225 
22226 		/*
22227 		 * Drop M_CTL here if IPsec processing is not needed.
22228 		 * (Non-IPsec use of M_CTL extracted any information it
22229 		 * needed above).
22230 		 */
22231 		if (ipsec_len == 0) {
22232 			freeb(first_mp);
22233 			first_mp = mp;
22234 		}
22235 	}
22236 
22237 	/*
22238 	 * Fast path for ip_wput_ire
22239 	 */
22240 
22241 	ipha = (ipha_t *)mp->b_rptr;
22242 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22243 	dst = ipha->ipha_dst;
22244 
22245 	/*
22246 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22247 	 * if the socket is a SOCK_RAW type. The transport checksum should
22248 	 * be provided in the pre-built packet, so we don't need to compute it.
22249 	 * Also, other application set flags, like DF, should not be altered.
22250 	 * Other transport MUST pass down zero.
22251 	 */
22252 	ip_hdr_included = ipha->ipha_ident;
22253 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22254 
22255 	if (CLASSD(dst)) {
22256 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22257 		    ntohl(dst),
22258 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22259 		    ntohl(ire->ire_addr)));
22260 	}
22261 
22262 /* Macros to extract header fields from data already in registers */
22263 #ifdef	_BIG_ENDIAN
22264 #define	V_HLEN	(v_hlen_tos_len >> 24)
22265 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22266 #define	PROTO	(ttl_protocol & 0xFF)
22267 #else
22268 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22269 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22270 #define	PROTO	(ttl_protocol >> 8)
22271 #endif
22272 
22273 
22274 	orig_src = src = ipha->ipha_src;
22275 	/* (The loop back to "another" is explained down below.) */
22276 another:;
22277 	/*
22278 	 * Assign an ident value for this packet.  We assign idents on
22279 	 * a per destination basis out of the IRE.  There could be
22280 	 * other threads targeting the same destination, so we have to
22281 	 * arrange for a atomic increment.  Note that we use a 32-bit
22282 	 * atomic add because it has better performance than its
22283 	 * 16-bit sibling.
22284 	 *
22285 	 * If running in cluster mode and if the source address
22286 	 * belongs to a replicated service then vector through
22287 	 * cl_inet_ipident vector to allocate ip identifier
22288 	 * NOTE: This is a contract private interface with the
22289 	 * clustering group.
22290 	 */
22291 	clusterwide = 0;
22292 	if (cl_inet_ipident) {
22293 		ASSERT(cl_inet_isclusterwide);
22294 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22295 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22296 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22297 			    AF_INET, (uint8_t *)(uintptr_t)src,
22298 			    (uint8_t *)(uintptr_t)dst);
22299 			clusterwide = 1;
22300 		}
22301 	}
22302 	if (!clusterwide) {
22303 		ipha->ipha_ident =
22304 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22305 	}
22306 
22307 #ifndef _BIG_ENDIAN
22308 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22309 #endif
22310 
22311 	/*
22312 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22313 	 * This is needed to obey conn_unspec_src when packets go through
22314 	 * ip_newroute + arp.
22315 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22316 	 */
22317 	if (src == INADDR_ANY && !unspec_src) {
22318 		/*
22319 		 * Assign the appropriate source address from the IRE if none
22320 		 * was specified.
22321 		 */
22322 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22323 
22324 		/*
22325 		 * With IP multipathing, broadcast packets are sent on the ire
22326 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22327 		 * the group. However, this ire might not be in the same zone so
22328 		 * we can't always use its source address. We look for a
22329 		 * broadcast ire in the same group and in the right zone.
22330 		 */
22331 		if (ire->ire_type == IRE_BROADCAST &&
22332 		    ire->ire_zoneid != zoneid) {
22333 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22334 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22335 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22336 			if (src_ire != NULL) {
22337 				src = src_ire->ire_src_addr;
22338 				ire_refrele(src_ire);
22339 			} else {
22340 				ire_refrele(ire);
22341 				if (conn_outgoing_ill != NULL)
22342 					ill_refrele(conn_outgoing_ill);
22343 				freemsg(first_mp);
22344 				if (ill != NULL) {
22345 					BUMP_MIB(ill->ill_ip_mib,
22346 					    ipIfStatsOutDiscards);
22347 				} else {
22348 					BUMP_MIB(&ipst->ips_ip_mib,
22349 					    ipIfStatsOutDiscards);
22350 				}
22351 				return;
22352 			}
22353 		} else {
22354 			src = ire->ire_src_addr;
22355 		}
22356 
22357 		if (connp == NULL) {
22358 			ip1dbg(("ip_wput_ire: no connp and no src "
22359 			    "address for dst 0x%x, using src 0x%x\n",
22360 			    ntohl(dst),
22361 			    ntohl(src)));
22362 		}
22363 		ipha->ipha_src = src;
22364 	}
22365 	stq = ire->ire_stq;
22366 
22367 	/*
22368 	 * We only allow ire chains for broadcasts since there will
22369 	 * be multiple IRE_CACHE entries for the same multicast
22370 	 * address (one per ipif).
22371 	 */
22372 	next_mp = NULL;
22373 
22374 	/* broadcast packet */
22375 	if (ire->ire_type == IRE_BROADCAST)
22376 		goto broadcast;
22377 
22378 	/* loopback ? */
22379 	if (stq == NULL)
22380 		goto nullstq;
22381 
22382 	/* The ill_index for outbound ILL */
22383 	ill_index = Q_TO_INDEX(stq);
22384 
22385 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22386 	ttl_protocol = ((uint16_t *)ipha)[4];
22387 
22388 	/* pseudo checksum (do it in parts for IP header checksum) */
22389 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22390 
22391 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22392 		queue_t *dev_q = stq->q_next;
22393 
22394 		/* flow controlled */
22395 		if ((dev_q->q_next || dev_q->q_first) &&
22396 		    !canput(dev_q))
22397 			goto blocked;
22398 		if ((PROTO == IPPROTO_UDP) &&
22399 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22400 			hlen = (V_HLEN & 0xF) << 2;
22401 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22402 			if (*up != 0) {
22403 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22404 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22405 				/* Software checksum? */
22406 				if (DB_CKSUMFLAGS(mp) == 0) {
22407 					IP_STAT(ipst, ip_out_sw_cksum);
22408 					IP_STAT_UPDATE(ipst,
22409 					    ip_udp_out_sw_cksum_bytes,
22410 					    LENGTH - hlen);
22411 				}
22412 			}
22413 		}
22414 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22415 		hlen = (V_HLEN & 0xF) << 2;
22416 		if (PROTO == IPPROTO_TCP) {
22417 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22418 			/*
22419 			 * The packet header is processed once and for all, even
22420 			 * in the multirouting case. We disable hardware
22421 			 * checksum if the packet is multirouted, as it will be
22422 			 * replicated via several interfaces, and not all of
22423 			 * them may have this capability.
22424 			 */
22425 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22426 			    LENGTH, max_frag, ipsec_len, cksum);
22427 			/* Software checksum? */
22428 			if (DB_CKSUMFLAGS(mp) == 0) {
22429 				IP_STAT(ipst, ip_out_sw_cksum);
22430 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22431 				    LENGTH - hlen);
22432 			}
22433 		} else {
22434 			sctp_hdr_t	*sctph;
22435 
22436 			ASSERT(PROTO == IPPROTO_SCTP);
22437 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22438 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22439 			/*
22440 			 * Zero out the checksum field to ensure proper
22441 			 * checksum calculation.
22442 			 */
22443 			sctph->sh_chksum = 0;
22444 #ifdef	DEBUG
22445 			if (!skip_sctp_cksum)
22446 #endif
22447 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22448 		}
22449 	}
22450 
22451 	/*
22452 	 * If this is a multicast packet and originated from ip_wput
22453 	 * we need to do loopback and forwarding checks. If it comes
22454 	 * from ip_wput_multicast, we SHOULD not do this.
22455 	 */
22456 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22457 
22458 	/* checksum */
22459 	cksum += ttl_protocol;
22460 
22461 	/* fragment the packet */
22462 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22463 		goto fragmentit;
22464 	/*
22465 	 * Don't use frag_flag if packet is pre-built or source
22466 	 * routed or if multicast (since multicast packets do
22467 	 * not solicit ICMP "packet too big" messages).
22468 	 */
22469 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22470 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22471 	    !ip_source_route_included(ipha)) &&
22472 	    !CLASSD(ipha->ipha_dst))
22473 		ipha->ipha_fragment_offset_and_flags |=
22474 		    htons(ire->ire_frag_flag);
22475 
22476 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22477 		/* calculate IP header checksum */
22478 		cksum += ipha->ipha_ident;
22479 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22480 		cksum += ipha->ipha_fragment_offset_and_flags;
22481 
22482 		/* IP options present */
22483 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22484 		if (hlen)
22485 			goto checksumoptions;
22486 
22487 		/* calculate hdr checksum */
22488 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22489 		cksum = ~(cksum + (cksum >> 16));
22490 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22491 	}
22492 	if (ipsec_len != 0) {
22493 		/*
22494 		 * We will do the rest of the processing after
22495 		 * we come back from IPsec in ip_wput_ipsec_out().
22496 		 */
22497 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22498 
22499 		io = (ipsec_out_t *)first_mp->b_rptr;
22500 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22501 		    ill_phyint->phyint_ifindex;
22502 
22503 		ipsec_out_process(q, first_mp, ire, ill_index);
22504 		ire_refrele(ire);
22505 		if (conn_outgoing_ill != NULL)
22506 			ill_refrele(conn_outgoing_ill);
22507 		return;
22508 	}
22509 
22510 	/*
22511 	 * In most cases, the emission loop below is entered only
22512 	 * once. Only in the case where the ire holds the
22513 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22514 	 * flagged ires in the bucket, and send the packet
22515 	 * through all crossed RTF_MULTIRT routes.
22516 	 */
22517 	if (ire->ire_flags & RTF_MULTIRT) {
22518 		multirt_send = B_TRUE;
22519 	}
22520 	do {
22521 		if (multirt_send) {
22522 			irb_t *irb;
22523 			/*
22524 			 * We are in a multiple send case, need to get
22525 			 * the next ire and make a duplicate of the packet.
22526 			 * ire1 holds here the next ire to process in the
22527 			 * bucket. If multirouting is expected,
22528 			 * any non-RTF_MULTIRT ire that has the
22529 			 * right destination address is ignored.
22530 			 */
22531 			irb = ire->ire_bucket;
22532 			ASSERT(irb != NULL);
22533 
22534 			IRB_REFHOLD(irb);
22535 			for (ire1 = ire->ire_next;
22536 			    ire1 != NULL;
22537 			    ire1 = ire1->ire_next) {
22538 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22539 					continue;
22540 				if (ire1->ire_addr != ire->ire_addr)
22541 					continue;
22542 				if (ire1->ire_marks &
22543 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22544 					continue;
22545 
22546 				/* Got one */
22547 				IRE_REFHOLD(ire1);
22548 				break;
22549 			}
22550 			IRB_REFRELE(irb);
22551 
22552 			if (ire1 != NULL) {
22553 				next_mp = copyb(mp);
22554 				if ((next_mp == NULL) ||
22555 				    ((mp->b_cont != NULL) &&
22556 				    ((next_mp->b_cont =
22557 				    dupmsg(mp->b_cont)) == NULL))) {
22558 					freemsg(next_mp);
22559 					next_mp = NULL;
22560 					ire_refrele(ire1);
22561 					ire1 = NULL;
22562 				}
22563 			}
22564 
22565 			/* Last multiroute ire; don't loop anymore. */
22566 			if (ire1 == NULL) {
22567 				multirt_send = B_FALSE;
22568 			}
22569 		}
22570 
22571 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22572 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22573 		    mblk_t *, mp);
22574 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22575 		    ipst->ips_ipv4firewall_physical_out,
22576 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22577 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22578 		if (mp == NULL)
22579 			goto release_ire_and_ill;
22580 
22581 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22582 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22583 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22584 		if ((pktxmit_state == SEND_FAILED) ||
22585 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22586 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22587 			    "- packet dropped\n"));
22588 release_ire_and_ill:
22589 			ire_refrele(ire);
22590 			if (next_mp != NULL) {
22591 				freemsg(next_mp);
22592 				ire_refrele(ire1);
22593 			}
22594 			if (conn_outgoing_ill != NULL)
22595 				ill_refrele(conn_outgoing_ill);
22596 			return;
22597 		}
22598 
22599 		if (CLASSD(dst)) {
22600 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22601 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22602 			    LENGTH);
22603 		}
22604 
22605 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22606 		    "ip_wput_ire_end: q %p (%S)",
22607 		    q, "last copy out");
22608 		IRE_REFRELE(ire);
22609 
22610 		if (multirt_send) {
22611 			ASSERT(ire1);
22612 			/*
22613 			 * Proceed with the next RTF_MULTIRT ire,
22614 			 * Also set up the send-to queue accordingly.
22615 			 */
22616 			ire = ire1;
22617 			ire1 = NULL;
22618 			stq = ire->ire_stq;
22619 			mp = next_mp;
22620 			next_mp = NULL;
22621 			ipha = (ipha_t *)mp->b_rptr;
22622 			ill_index = Q_TO_INDEX(stq);
22623 			ill = (ill_t *)stq->q_ptr;
22624 		}
22625 	} while (multirt_send);
22626 	if (conn_outgoing_ill != NULL)
22627 		ill_refrele(conn_outgoing_ill);
22628 	return;
22629 
22630 	/*
22631 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22632 	 */
22633 broadcast:
22634 	{
22635 		/*
22636 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22637 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22638 		 * can be overridden stack-wide through the ip_broadcast_ttl
22639 		 * ndd tunable, or on a per-connection basis through the
22640 		 * IP_BROADCAST_TTL socket option.
22641 		 *
22642 		 * In the event that we are replying to incoming ICMP packets,
22643 		 * connp could be NULL.
22644 		 */
22645 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22646 		if (connp != NULL) {
22647 			if (connp->conn_dontroute)
22648 				ipha->ipha_ttl = 1;
22649 			else if (connp->conn_broadcast_ttl != 0)
22650 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22651 		}
22652 
22653 		/*
22654 		 * Note that we are not doing a IRB_REFHOLD here.
22655 		 * Actually we don't care if the list changes i.e
22656 		 * if somebody deletes an IRE from the list while
22657 		 * we drop the lock, the next time we come around
22658 		 * ire_next will be NULL and hence we won't send
22659 		 * out multiple copies which is fine.
22660 		 */
22661 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22662 		ire1 = ire->ire_next;
22663 		if (conn_outgoing_ill != NULL) {
22664 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22665 				ASSERT(ire1 == ire->ire_next);
22666 				if (ire1 != NULL && ire1->ire_addr == dst) {
22667 					ire_refrele(ire);
22668 					ire = ire1;
22669 					IRE_REFHOLD(ire);
22670 					ire1 = ire->ire_next;
22671 					continue;
22672 				}
22673 				rw_exit(&ire->ire_bucket->irb_lock);
22674 				/* Did not find a matching ill */
22675 				ip1dbg(("ip_wput_ire: broadcast with no "
22676 				    "matching IP_BOUND_IF ill %s dst %x\n",
22677 				    conn_outgoing_ill->ill_name, dst));
22678 				freemsg(first_mp);
22679 				if (ire != NULL)
22680 					ire_refrele(ire);
22681 				ill_refrele(conn_outgoing_ill);
22682 				return;
22683 			}
22684 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22685 			/*
22686 			 * If the next IRE has the same address and is not one
22687 			 * of the two copies that we need to send, try to see
22688 			 * whether this copy should be sent at all. This
22689 			 * assumes that we insert loopbacks first and then
22690 			 * non-loopbacks. This is acheived by inserting the
22691 			 * loopback always before non-loopback.
22692 			 * This is used to send a single copy of a broadcast
22693 			 * packet out all physical interfaces that have an
22694 			 * matching IRE_BROADCAST while also looping
22695 			 * back one copy (to ip_wput_local) for each
22696 			 * matching physical interface. However, we avoid
22697 			 * sending packets out different logical that match by
22698 			 * having ipif_up/ipif_down supress duplicate
22699 			 * IRE_BROADCASTS.
22700 			 *
22701 			 * This feature is currently used to get broadcasts
22702 			 * sent to multiple interfaces, when the broadcast
22703 			 * address being used applies to multiple interfaces.
22704 			 * For example, a whole net broadcast will be
22705 			 * replicated on every connected subnet of
22706 			 * the target net.
22707 			 *
22708 			 * Each zone has its own set of IRE_BROADCASTs, so that
22709 			 * we're able to distribute inbound packets to multiple
22710 			 * zones who share a broadcast address. We avoid looping
22711 			 * back outbound packets in different zones but on the
22712 			 * same ill, as the application would see duplicates.
22713 			 *
22714 			 * If the interfaces are part of the same group,
22715 			 * we would want to send only one copy out for
22716 			 * whole group.
22717 			 *
22718 			 * This logic assumes that ire_add_v4() groups the
22719 			 * IRE_BROADCAST entries so that those with the same
22720 			 * ire_addr and ill_group are kept together.
22721 			 */
22722 			ire_ill = ire->ire_ipif->ipif_ill;
22723 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22724 				if (ire_ill->ill_group != NULL &&
22725 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22726 					/*
22727 					 * If the current zone only has an ire
22728 					 * broadcast for this address marked
22729 					 * NORECV, the ire we want is ahead in
22730 					 * the bucket, so we look it up
22731 					 * deliberately ignoring the zoneid.
22732 					 */
22733 					for (ire1 = ire->ire_bucket->irb_ire;
22734 					    ire1 != NULL;
22735 					    ire1 = ire1->ire_next) {
22736 						ire1_ill =
22737 						    ire1->ire_ipif->ipif_ill;
22738 						if (ire1->ire_addr != dst)
22739 							continue;
22740 						/* skip over the current ire */
22741 						if (ire1 == ire)
22742 							continue;
22743 						/* skip over deleted ires */
22744 						if (ire1->ire_marks &
22745 						    IRE_MARK_CONDEMNED)
22746 							continue;
22747 						/*
22748 						 * non-loopback ire in our
22749 						 * group: use it for the next
22750 						 * pass in the loop
22751 						 */
22752 						if (ire1->ire_stq != NULL &&
22753 						    ire1_ill->ill_group ==
22754 						    ire_ill->ill_group)
22755 							break;
22756 					}
22757 				}
22758 			} else {
22759 				while (ire1 != NULL && ire1->ire_addr == dst) {
22760 					ire1_ill = ire1->ire_ipif->ipif_ill;
22761 					/*
22762 					 * We can have two broadcast ires on the
22763 					 * same ill in different zones; here
22764 					 * we'll send a copy of the packet on
22765 					 * each ill and the fanout code will
22766 					 * call conn_wantpacket() to check that
22767 					 * the zone has the broadcast address
22768 					 * configured on the ill. If the two
22769 					 * ires are in the same group we only
22770 					 * send one copy up.
22771 					 */
22772 					if (ire1_ill != ire_ill &&
22773 					    (ire1_ill->ill_group == NULL ||
22774 					    ire_ill->ill_group == NULL ||
22775 					    ire1_ill->ill_group !=
22776 					    ire_ill->ill_group)) {
22777 						break;
22778 					}
22779 					ire1 = ire1->ire_next;
22780 				}
22781 			}
22782 		}
22783 		ASSERT(multirt_send == B_FALSE);
22784 		if (ire1 != NULL && ire1->ire_addr == dst) {
22785 			if ((ire->ire_flags & RTF_MULTIRT) &&
22786 			    (ire1->ire_flags & RTF_MULTIRT)) {
22787 				/*
22788 				 * We are in the multirouting case.
22789 				 * The message must be sent at least
22790 				 * on both ires. These ires have been
22791 				 * inserted AFTER the standard ones
22792 				 * in ip_rt_add(). There are thus no
22793 				 * other ire entries for the destination
22794 				 * address in the rest of the bucket
22795 				 * that do not have the RTF_MULTIRT
22796 				 * flag. We don't process a copy
22797 				 * of the message here. This will be
22798 				 * done in the final sending loop.
22799 				 */
22800 				multirt_send = B_TRUE;
22801 			} else {
22802 				next_mp = ip_copymsg(first_mp);
22803 				if (next_mp != NULL)
22804 					IRE_REFHOLD(ire1);
22805 			}
22806 		}
22807 		rw_exit(&ire->ire_bucket->irb_lock);
22808 	}
22809 
22810 	if (stq) {
22811 		/*
22812 		 * A non-NULL send-to queue means this packet is going
22813 		 * out of this machine.
22814 		 */
22815 		out_ill = (ill_t *)stq->q_ptr;
22816 
22817 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22818 		ttl_protocol = ((uint16_t *)ipha)[4];
22819 		/*
22820 		 * We accumulate the pseudo header checksum in cksum.
22821 		 * This is pretty hairy code, so watch close.  One
22822 		 * thing to keep in mind is that UDP and TCP have
22823 		 * stored their respective datagram lengths in their
22824 		 * checksum fields.  This lines things up real nice.
22825 		 */
22826 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22827 		    (src >> 16) + (src & 0xFFFF);
22828 		/*
22829 		 * We assume the udp checksum field contains the
22830 		 * length, so to compute the pseudo header checksum,
22831 		 * all we need is the protocol number and src/dst.
22832 		 */
22833 		/* Provide the checksums for UDP and TCP. */
22834 		if ((PROTO == IPPROTO_TCP) &&
22835 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22836 			/* hlen gets the number of uchar_ts in the IP header */
22837 			hlen = (V_HLEN & 0xF) << 2;
22838 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22839 			IP_STAT(ipst, ip_out_sw_cksum);
22840 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22841 			    LENGTH - hlen);
22842 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22843 		} else if (PROTO == IPPROTO_SCTP &&
22844 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22845 			sctp_hdr_t	*sctph;
22846 
22847 			hlen = (V_HLEN & 0xF) << 2;
22848 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22849 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22850 			sctph->sh_chksum = 0;
22851 #ifdef	DEBUG
22852 			if (!skip_sctp_cksum)
22853 #endif
22854 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22855 		} else {
22856 			queue_t *dev_q = stq->q_next;
22857 
22858 			if ((dev_q->q_next || dev_q->q_first) &&
22859 			    !canput(dev_q)) {
22860 blocked:
22861 				ipha->ipha_ident = ip_hdr_included;
22862 				/*
22863 				 * If we don't have a conn to apply
22864 				 * backpressure, free the message.
22865 				 * In the ire_send path, we don't know
22866 				 * the position to requeue the packet. Rather
22867 				 * than reorder packets, we just drop this
22868 				 * packet.
22869 				 */
22870 				if (ipst->ips_ip_output_queue &&
22871 				    connp != NULL &&
22872 				    caller != IRE_SEND) {
22873 					if (caller == IP_WSRV) {
22874 						connp->conn_did_putbq = 1;
22875 						(void) putbq(connp->conn_wq,
22876 						    first_mp);
22877 						conn_drain_insert(connp);
22878 						/*
22879 						 * This is the service thread,
22880 						 * and the queue is already
22881 						 * noenabled. The check for
22882 						 * canput and the putbq is not
22883 						 * atomic. So we need to check
22884 						 * again.
22885 						 */
22886 						if (canput(stq->q_next))
22887 							connp->conn_did_putbq
22888 							    = 0;
22889 						IP_STAT(ipst, ip_conn_flputbq);
22890 					} else {
22891 						/*
22892 						 * We are not the service proc.
22893 						 * ip_wsrv will be scheduled or
22894 						 * is already running.
22895 						 */
22896 						(void) putq(connp->conn_wq,
22897 						    first_mp);
22898 					}
22899 				} else {
22900 					out_ill = (ill_t *)stq->q_ptr;
22901 					BUMP_MIB(out_ill->ill_ip_mib,
22902 					    ipIfStatsOutDiscards);
22903 					freemsg(first_mp);
22904 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22905 					    "ip_wput_ire_end: q %p (%S)",
22906 					    q, "discard");
22907 				}
22908 				ire_refrele(ire);
22909 				if (next_mp) {
22910 					ire_refrele(ire1);
22911 					freemsg(next_mp);
22912 				}
22913 				if (conn_outgoing_ill != NULL)
22914 					ill_refrele(conn_outgoing_ill);
22915 				return;
22916 			}
22917 			if ((PROTO == IPPROTO_UDP) &&
22918 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22919 				/*
22920 				 * hlen gets the number of uchar_ts in the
22921 				 * IP header
22922 				 */
22923 				hlen = (V_HLEN & 0xF) << 2;
22924 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22925 				max_frag = ire->ire_max_frag;
22926 				if (*up != 0) {
22927 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22928 					    up, PROTO, hlen, LENGTH, max_frag,
22929 					    ipsec_len, cksum);
22930 					/* Software checksum? */
22931 					if (DB_CKSUMFLAGS(mp) == 0) {
22932 						IP_STAT(ipst, ip_out_sw_cksum);
22933 						IP_STAT_UPDATE(ipst,
22934 						    ip_udp_out_sw_cksum_bytes,
22935 						    LENGTH - hlen);
22936 					}
22937 				}
22938 			}
22939 		}
22940 		/*
22941 		 * Need to do this even when fragmenting. The local
22942 		 * loopback can be done without computing checksums
22943 		 * but forwarding out other interface must be done
22944 		 * after the IP checksum (and ULP checksums) have been
22945 		 * computed.
22946 		 *
22947 		 * NOTE : multicast_forward is set only if this packet
22948 		 * originated from ip_wput. For packets originating from
22949 		 * ip_wput_multicast, it is not set.
22950 		 */
22951 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22952 multi_loopback:
22953 			ip2dbg(("ip_wput: multicast, loop %d\n",
22954 			    conn_multicast_loop));
22955 
22956 			/*  Forget header checksum offload */
22957 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22958 
22959 			/*
22960 			 * Local loopback of multicasts?  Check the
22961 			 * ill.
22962 			 *
22963 			 * Note that the loopback function will not come
22964 			 * in through ip_rput - it will only do the
22965 			 * client fanout thus we need to do an mforward
22966 			 * as well.  The is different from the BSD
22967 			 * logic.
22968 			 */
22969 			if (ill != NULL) {
22970 				ilm_t	*ilm;
22971 
22972 				ILM_WALKER_HOLD(ill);
22973 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22974 				    ALL_ZONES);
22975 				ILM_WALKER_RELE(ill);
22976 				if (ilm != NULL) {
22977 					/*
22978 					 * Pass along the virtual output q.
22979 					 * ip_wput_local() will distribute the
22980 					 * packet to all the matching zones,
22981 					 * except the sending zone when
22982 					 * IP_MULTICAST_LOOP is false.
22983 					 */
22984 					ip_multicast_loopback(q, ill, first_mp,
22985 					    conn_multicast_loop ? 0 :
22986 					    IP_FF_NO_MCAST_LOOP, zoneid);
22987 				}
22988 			}
22989 			if (ipha->ipha_ttl == 0) {
22990 				/*
22991 				 * 0 => only to this host i.e. we are
22992 				 * done. We are also done if this was the
22993 				 * loopback interface since it is sufficient
22994 				 * to loopback one copy of a multicast packet.
22995 				 */
22996 				freemsg(first_mp);
22997 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22998 				    "ip_wput_ire_end: q %p (%S)",
22999 				    q, "loopback");
23000 				ire_refrele(ire);
23001 				if (conn_outgoing_ill != NULL)
23002 					ill_refrele(conn_outgoing_ill);
23003 				return;
23004 			}
23005 			/*
23006 			 * ILLF_MULTICAST is checked in ip_newroute
23007 			 * i.e. we don't need to check it here since
23008 			 * all IRE_CACHEs come from ip_newroute.
23009 			 * For multicast traffic, SO_DONTROUTE is interpreted
23010 			 * to mean only send the packet out the interface
23011 			 * (optionally specified with IP_MULTICAST_IF)
23012 			 * and do not forward it out additional interfaces.
23013 			 * RSVP and the rsvp daemon is an example of a
23014 			 * protocol and user level process that
23015 			 * handles it's own routing. Hence, it uses the
23016 			 * SO_DONTROUTE option to accomplish this.
23017 			 */
23018 
23019 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23020 			    ill != NULL) {
23021 				/* Unconditionally redo the checksum */
23022 				ipha->ipha_hdr_checksum = 0;
23023 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23024 
23025 				/*
23026 				 * If this needs to go out secure, we need
23027 				 * to wait till we finish the IPsec
23028 				 * processing.
23029 				 */
23030 				if (ipsec_len == 0 &&
23031 				    ip_mforward(ill, ipha, mp)) {
23032 					freemsg(first_mp);
23033 					ip1dbg(("ip_wput: mforward failed\n"));
23034 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23035 					    "ip_wput_ire_end: q %p (%S)",
23036 					    q, "mforward failed");
23037 					ire_refrele(ire);
23038 					if (conn_outgoing_ill != NULL)
23039 						ill_refrele(conn_outgoing_ill);
23040 					return;
23041 				}
23042 			}
23043 		}
23044 		max_frag = ire->ire_max_frag;
23045 		cksum += ttl_protocol;
23046 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23047 			/* No fragmentation required for this one. */
23048 			/*
23049 			 * Don't use frag_flag if packet is pre-built or source
23050 			 * routed or if multicast (since multicast packets do
23051 			 * not solicit ICMP "packet too big" messages).
23052 			 */
23053 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23054 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23055 			    !ip_source_route_included(ipha)) &&
23056 			    !CLASSD(ipha->ipha_dst))
23057 				ipha->ipha_fragment_offset_and_flags |=
23058 				    htons(ire->ire_frag_flag);
23059 
23060 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23061 				/* Complete the IP header checksum. */
23062 				cksum += ipha->ipha_ident;
23063 				cksum += (v_hlen_tos_len >> 16)+
23064 				    (v_hlen_tos_len & 0xFFFF);
23065 				cksum += ipha->ipha_fragment_offset_and_flags;
23066 				hlen = (V_HLEN & 0xF) -
23067 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23068 				if (hlen) {
23069 checksumoptions:
23070 					/*
23071 					 * Account for the IP Options in the IP
23072 					 * header checksum.
23073 					 */
23074 					up = (uint16_t *)(rptr+
23075 					    IP_SIMPLE_HDR_LENGTH);
23076 					do {
23077 						cksum += up[0];
23078 						cksum += up[1];
23079 						up += 2;
23080 					} while (--hlen);
23081 				}
23082 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23083 				cksum = ~(cksum + (cksum >> 16));
23084 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23085 			}
23086 			if (ipsec_len != 0) {
23087 				ipsec_out_process(q, first_mp, ire, ill_index);
23088 				if (!next_mp) {
23089 					ire_refrele(ire);
23090 					if (conn_outgoing_ill != NULL)
23091 						ill_refrele(conn_outgoing_ill);
23092 					return;
23093 				}
23094 				goto next;
23095 			}
23096 
23097 			/*
23098 			 * multirt_send has already been handled
23099 			 * for broadcast, but not yet for multicast
23100 			 * or IP options.
23101 			 */
23102 			if (next_mp == NULL) {
23103 				if (ire->ire_flags & RTF_MULTIRT) {
23104 					multirt_send = B_TRUE;
23105 				}
23106 			}
23107 
23108 			/*
23109 			 * In most cases, the emission loop below is
23110 			 * entered only once. Only in the case where
23111 			 * the ire holds the RTF_MULTIRT flag, do we loop
23112 			 * to process all RTF_MULTIRT ires in the bucket,
23113 			 * and send the packet through all crossed
23114 			 * RTF_MULTIRT routes.
23115 			 */
23116 			do {
23117 				if (multirt_send) {
23118 					irb_t *irb;
23119 
23120 					irb = ire->ire_bucket;
23121 					ASSERT(irb != NULL);
23122 					/*
23123 					 * We are in a multiple send case,
23124 					 * need to get the next IRE and make
23125 					 * a duplicate of the packet.
23126 					 */
23127 					IRB_REFHOLD(irb);
23128 					for (ire1 = ire->ire_next;
23129 					    ire1 != NULL;
23130 					    ire1 = ire1->ire_next) {
23131 						if (!(ire1->ire_flags &
23132 						    RTF_MULTIRT)) {
23133 							continue;
23134 						}
23135 						if (ire1->ire_addr !=
23136 						    ire->ire_addr) {
23137 							continue;
23138 						}
23139 						if (ire1->ire_marks &
23140 						    (IRE_MARK_CONDEMNED|
23141 						    IRE_MARK_HIDDEN)) {
23142 							continue;
23143 						}
23144 
23145 						/* Got one */
23146 						IRE_REFHOLD(ire1);
23147 						break;
23148 					}
23149 					IRB_REFRELE(irb);
23150 
23151 					if (ire1 != NULL) {
23152 						next_mp = copyb(mp);
23153 						if ((next_mp == NULL) ||
23154 						    ((mp->b_cont != NULL) &&
23155 						    ((next_mp->b_cont =
23156 						    dupmsg(mp->b_cont))
23157 						    == NULL))) {
23158 							freemsg(next_mp);
23159 							next_mp = NULL;
23160 							ire_refrele(ire1);
23161 							ire1 = NULL;
23162 						}
23163 					}
23164 
23165 					/*
23166 					 * Last multiroute ire; don't loop
23167 					 * anymore. The emission is over
23168 					 * and next_mp is NULL.
23169 					 */
23170 					if (ire1 == NULL) {
23171 						multirt_send = B_FALSE;
23172 					}
23173 				}
23174 
23175 				out_ill = ire_to_ill(ire);
23176 				DTRACE_PROBE4(ip4__physical__out__start,
23177 				    ill_t *, NULL,
23178 				    ill_t *, out_ill,
23179 				    ipha_t *, ipha, mblk_t *, mp);
23180 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23181 				    ipst->ips_ipv4firewall_physical_out,
23182 				    NULL, out_ill, ipha, mp, mp, ipst);
23183 				DTRACE_PROBE1(ip4__physical__out__end,
23184 				    mblk_t *, mp);
23185 				if (mp == NULL)
23186 					goto release_ire_and_ill_2;
23187 
23188 				ASSERT(ipsec_len == 0);
23189 				mp->b_prev =
23190 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23191 				DTRACE_PROBE2(ip__xmit__2,
23192 				    mblk_t *, mp, ire_t *, ire);
23193 				pktxmit_state = ip_xmit_v4(mp, ire,
23194 				    NULL, B_TRUE);
23195 				if ((pktxmit_state == SEND_FAILED) ||
23196 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23197 release_ire_and_ill_2:
23198 					if (next_mp) {
23199 						freemsg(next_mp);
23200 						ire_refrele(ire1);
23201 					}
23202 					ire_refrele(ire);
23203 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23204 					    "ip_wput_ire_end: q %p (%S)",
23205 					    q, "discard MDATA");
23206 					if (conn_outgoing_ill != NULL)
23207 						ill_refrele(conn_outgoing_ill);
23208 					return;
23209 				}
23210 
23211 				if (CLASSD(dst)) {
23212 					BUMP_MIB(out_ill->ill_ip_mib,
23213 					    ipIfStatsHCOutMcastPkts);
23214 					UPDATE_MIB(out_ill->ill_ip_mib,
23215 					    ipIfStatsHCOutMcastOctets,
23216 					    LENGTH);
23217 				} else if (ire->ire_type == IRE_BROADCAST) {
23218 					BUMP_MIB(out_ill->ill_ip_mib,
23219 					    ipIfStatsHCOutBcastPkts);
23220 				}
23221 
23222 				if (multirt_send) {
23223 					/*
23224 					 * We are in a multiple send case,
23225 					 * need to re-enter the sending loop
23226 					 * using the next ire.
23227 					 */
23228 					ire_refrele(ire);
23229 					ire = ire1;
23230 					stq = ire->ire_stq;
23231 					mp = next_mp;
23232 					next_mp = NULL;
23233 					ipha = (ipha_t *)mp->b_rptr;
23234 					ill_index = Q_TO_INDEX(stq);
23235 				}
23236 			} while (multirt_send);
23237 
23238 			if (!next_mp) {
23239 				/*
23240 				 * Last copy going out (the ultra-common
23241 				 * case).  Note that we intentionally replicate
23242 				 * the putnext rather than calling it before
23243 				 * the next_mp check in hopes of a little
23244 				 * tail-call action out of the compiler.
23245 				 */
23246 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23247 				    "ip_wput_ire_end: q %p (%S)",
23248 				    q, "last copy out(1)");
23249 				ire_refrele(ire);
23250 				if (conn_outgoing_ill != NULL)
23251 					ill_refrele(conn_outgoing_ill);
23252 				return;
23253 			}
23254 			/* More copies going out below. */
23255 		} else {
23256 			int offset;
23257 fragmentit:
23258 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23259 			/*
23260 			 * If this would generate a icmp_frag_needed message,
23261 			 * we need to handle it before we do the IPsec
23262 			 * processing. Otherwise, we need to strip the IPsec
23263 			 * headers before we send up the message to the ULPs
23264 			 * which becomes messy and difficult.
23265 			 */
23266 			if (ipsec_len != 0) {
23267 				if ((max_frag < (unsigned int)(LENGTH +
23268 				    ipsec_len)) && (offset & IPH_DF)) {
23269 					out_ill = (ill_t *)stq->q_ptr;
23270 					BUMP_MIB(out_ill->ill_ip_mib,
23271 					    ipIfStatsOutFragFails);
23272 					BUMP_MIB(out_ill->ill_ip_mib,
23273 					    ipIfStatsOutFragReqds);
23274 					ipha->ipha_hdr_checksum = 0;
23275 					ipha->ipha_hdr_checksum =
23276 					    (uint16_t)ip_csum_hdr(ipha);
23277 					icmp_frag_needed(ire->ire_stq, first_mp,
23278 					    max_frag, zoneid, ipst);
23279 					if (!next_mp) {
23280 						ire_refrele(ire);
23281 						if (conn_outgoing_ill != NULL) {
23282 							ill_refrele(
23283 							    conn_outgoing_ill);
23284 						}
23285 						return;
23286 					}
23287 				} else {
23288 					/*
23289 					 * This won't cause a icmp_frag_needed
23290 					 * message. to be generated. Send it on
23291 					 * the wire. Note that this could still
23292 					 * cause fragmentation and all we
23293 					 * do is the generation of the message
23294 					 * to the ULP if needed before IPsec.
23295 					 */
23296 					if (!next_mp) {
23297 						ipsec_out_process(q, first_mp,
23298 						    ire, ill_index);
23299 						TRACE_2(TR_FAC_IP,
23300 						    TR_IP_WPUT_IRE_END,
23301 						    "ip_wput_ire_end: q %p "
23302 						    "(%S)", q,
23303 						    "last ipsec_out_process");
23304 						ire_refrele(ire);
23305 						if (conn_outgoing_ill != NULL) {
23306 							ill_refrele(
23307 							    conn_outgoing_ill);
23308 						}
23309 						return;
23310 					}
23311 					ipsec_out_process(q, first_mp,
23312 					    ire, ill_index);
23313 				}
23314 			} else {
23315 				/*
23316 				 * Initiate IPPF processing. For
23317 				 * fragmentable packets we finish
23318 				 * all QOS packet processing before
23319 				 * calling:
23320 				 * ip_wput_ire_fragmentit->ip_wput_frag
23321 				 */
23322 
23323 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23324 					ip_process(IPP_LOCAL_OUT, &mp,
23325 					    ill_index);
23326 					if (mp == NULL) {
23327 						out_ill = (ill_t *)stq->q_ptr;
23328 						BUMP_MIB(out_ill->ill_ip_mib,
23329 						    ipIfStatsOutDiscards);
23330 						if (next_mp != NULL) {
23331 							freemsg(next_mp);
23332 							ire_refrele(ire1);
23333 						}
23334 						ire_refrele(ire);
23335 						TRACE_2(TR_FAC_IP,
23336 						    TR_IP_WPUT_IRE_END,
23337 						    "ip_wput_ire: q %p (%S)",
23338 						    q, "discard MDATA");
23339 						if (conn_outgoing_ill != NULL) {
23340 							ill_refrele(
23341 							    conn_outgoing_ill);
23342 						}
23343 						return;
23344 					}
23345 				}
23346 				if (!next_mp) {
23347 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23348 					    "ip_wput_ire_end: q %p (%S)",
23349 					    q, "last fragmentation");
23350 					ip_wput_ire_fragmentit(mp, ire,
23351 					    zoneid, ipst);
23352 					ire_refrele(ire);
23353 					if (conn_outgoing_ill != NULL)
23354 						ill_refrele(conn_outgoing_ill);
23355 					return;
23356 				}
23357 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23358 			}
23359 		}
23360 	} else {
23361 nullstq:
23362 		/* A NULL stq means the destination address is local. */
23363 		UPDATE_OB_PKT_COUNT(ire);
23364 		ire->ire_last_used_time = lbolt;
23365 		ASSERT(ire->ire_ipif != NULL);
23366 		if (!next_mp) {
23367 			/*
23368 			 * Is there an "in" and "out" for traffic local
23369 			 * to a host (loopback)?  The code in Solaris doesn't
23370 			 * explicitly draw a line in its code for in vs out,
23371 			 * so we've had to draw a line in the sand: ip_wput_ire
23372 			 * is considered to be the "output" side and
23373 			 * ip_wput_local to be the "input" side.
23374 			 */
23375 			out_ill = ire_to_ill(ire);
23376 
23377 			DTRACE_PROBE4(ip4__loopback__out__start,
23378 			    ill_t *, NULL, ill_t *, out_ill,
23379 			    ipha_t *, ipha, mblk_t *, first_mp);
23380 
23381 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23382 			    ipst->ips_ipv4firewall_loopback_out,
23383 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23384 
23385 			DTRACE_PROBE1(ip4__loopback__out_end,
23386 			    mblk_t *, first_mp);
23387 
23388 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23389 			    "ip_wput_ire_end: q %p (%S)",
23390 			    q, "local address");
23391 
23392 			if (first_mp != NULL)
23393 				ip_wput_local(q, out_ill, ipha,
23394 				    first_mp, ire, 0, ire->ire_zoneid);
23395 			ire_refrele(ire);
23396 			if (conn_outgoing_ill != NULL)
23397 				ill_refrele(conn_outgoing_ill);
23398 			return;
23399 		}
23400 
23401 		out_ill = ire_to_ill(ire);
23402 
23403 		DTRACE_PROBE4(ip4__loopback__out__start,
23404 		    ill_t *, NULL, ill_t *, out_ill,
23405 		    ipha_t *, ipha, mblk_t *, first_mp);
23406 
23407 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23408 		    ipst->ips_ipv4firewall_loopback_out,
23409 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23410 
23411 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23412 
23413 		if (first_mp != NULL)
23414 			ip_wput_local(q, out_ill, ipha,
23415 			    first_mp, ire, 0, ire->ire_zoneid);
23416 	}
23417 next:
23418 	/*
23419 	 * More copies going out to additional interfaces.
23420 	 * ire1 has already been held. We don't need the
23421 	 * "ire" anymore.
23422 	 */
23423 	ire_refrele(ire);
23424 	ire = ire1;
23425 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23426 	mp = next_mp;
23427 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23428 	ill = ire_to_ill(ire);
23429 	first_mp = mp;
23430 	if (ipsec_len != 0) {
23431 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23432 		mp = mp->b_cont;
23433 	}
23434 	dst = ire->ire_addr;
23435 	ipha = (ipha_t *)mp->b_rptr;
23436 	/*
23437 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23438 	 * Restore ipha_ident "no checksum" flag.
23439 	 */
23440 	src = orig_src;
23441 	ipha->ipha_ident = ip_hdr_included;
23442 	goto another;
23443 
23444 #undef	rptr
23445 #undef	Q_TO_INDEX
23446 }
23447 
23448 /*
23449  * Routine to allocate a message that is used to notify the ULP about MDT.
23450  * The caller may provide a pointer to the link-layer MDT capabilities,
23451  * or NULL if MDT is to be disabled on the stream.
23452  */
23453 mblk_t *
23454 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23455 {
23456 	mblk_t *mp;
23457 	ip_mdt_info_t *mdti;
23458 	ill_mdt_capab_t *idst;
23459 
23460 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23461 		DB_TYPE(mp) = M_CTL;
23462 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23463 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23464 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23465 		idst = &(mdti->mdt_capab);
23466 
23467 		/*
23468 		 * If the caller provides us with the capability, copy
23469 		 * it over into our notification message; otherwise
23470 		 * we zero out the capability portion.
23471 		 */
23472 		if (isrc != NULL)
23473 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23474 		else
23475 			bzero((caddr_t)idst, sizeof (*idst));
23476 	}
23477 	return (mp);
23478 }
23479 
23480 /*
23481  * Routine which determines whether MDT can be enabled on the destination
23482  * IRE and IPC combination, and if so, allocates and returns the MDT
23483  * notification mblk that may be used by ULP.  We also check if we need to
23484  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23485  * MDT usage in the past have been lifted.  This gets called during IP
23486  * and ULP binding.
23487  */
23488 mblk_t *
23489 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23490     ill_mdt_capab_t *mdt_cap)
23491 {
23492 	mblk_t *mp;
23493 	boolean_t rc = B_FALSE;
23494 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23495 
23496 	ASSERT(dst_ire != NULL);
23497 	ASSERT(connp != NULL);
23498 	ASSERT(mdt_cap != NULL);
23499 
23500 	/*
23501 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23502 	 * Multidata, which is handled in tcp_multisend().  This
23503 	 * is the reason why we do all these checks here, to ensure
23504 	 * that we don't enable Multidata for the cases which we
23505 	 * can't handle at the moment.
23506 	 */
23507 	do {
23508 		/* Only do TCP at the moment */
23509 		if (connp->conn_ulp != IPPROTO_TCP)
23510 			break;
23511 
23512 		/*
23513 		 * IPsec outbound policy present?  Note that we get here
23514 		 * after calling ipsec_conn_cache_policy() where the global
23515 		 * policy checking is performed.  conn_latch will be
23516 		 * non-NULL as long as there's a policy defined,
23517 		 * i.e. conn_out_enforce_policy may be NULL in such case
23518 		 * when the connection is non-secure, and hence we check
23519 		 * further if the latch refers to an outbound policy.
23520 		 */
23521 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23522 			break;
23523 
23524 		/* CGTP (multiroute) is enabled? */
23525 		if (dst_ire->ire_flags & RTF_MULTIRT)
23526 			break;
23527 
23528 		/* Outbound IPQoS enabled? */
23529 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23530 			/*
23531 			 * In this case, we disable MDT for this and all
23532 			 * future connections going over the interface.
23533 			 */
23534 			mdt_cap->ill_mdt_on = 0;
23535 			break;
23536 		}
23537 
23538 		/* socket option(s) present? */
23539 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23540 			break;
23541 
23542 		rc = B_TRUE;
23543 	/* CONSTCOND */
23544 	} while (0);
23545 
23546 	/* Remember the result */
23547 	connp->conn_mdt_ok = rc;
23548 
23549 	if (!rc)
23550 		return (NULL);
23551 	else if (!mdt_cap->ill_mdt_on) {
23552 		/*
23553 		 * If MDT has been previously turned off in the past, and we
23554 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23555 		 * then enable it for this interface.
23556 		 */
23557 		mdt_cap->ill_mdt_on = 1;
23558 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23559 		    "interface %s\n", ill_name));
23560 	}
23561 
23562 	/* Allocate the MDT info mblk */
23563 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23564 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23565 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23566 		return (NULL);
23567 	}
23568 	return (mp);
23569 }
23570 
23571 /*
23572  * Routine to allocate a message that is used to notify the ULP about LSO.
23573  * The caller may provide a pointer to the link-layer LSO capabilities,
23574  * or NULL if LSO is to be disabled on the stream.
23575  */
23576 mblk_t *
23577 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23578 {
23579 	mblk_t *mp;
23580 	ip_lso_info_t *lsoi;
23581 	ill_lso_capab_t *idst;
23582 
23583 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23584 		DB_TYPE(mp) = M_CTL;
23585 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23586 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23587 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23588 		idst = &(lsoi->lso_capab);
23589 
23590 		/*
23591 		 * If the caller provides us with the capability, copy
23592 		 * it over into our notification message; otherwise
23593 		 * we zero out the capability portion.
23594 		 */
23595 		if (isrc != NULL)
23596 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23597 		else
23598 			bzero((caddr_t)idst, sizeof (*idst));
23599 	}
23600 	return (mp);
23601 }
23602 
23603 /*
23604  * Routine which determines whether LSO can be enabled on the destination
23605  * IRE and IPC combination, and if so, allocates and returns the LSO
23606  * notification mblk that may be used by ULP.  We also check if we need to
23607  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23608  * LSO usage in the past have been lifted.  This gets called during IP
23609  * and ULP binding.
23610  */
23611 mblk_t *
23612 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23613     ill_lso_capab_t *lso_cap)
23614 {
23615 	mblk_t *mp;
23616 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23617 
23618 	ASSERT(dst_ire != NULL);
23619 	ASSERT(connp != NULL);
23620 	ASSERT(lso_cap != NULL);
23621 
23622 	connp->conn_lso_ok = B_TRUE;
23623 
23624 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23625 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23626 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23627 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23628 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23629 		connp->conn_lso_ok = B_FALSE;
23630 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23631 			/*
23632 			 * Disable LSO for this and all future connections going
23633 			 * over the interface.
23634 			 */
23635 			lso_cap->ill_lso_on = 0;
23636 		}
23637 	}
23638 
23639 	if (!connp->conn_lso_ok)
23640 		return (NULL);
23641 	else if (!lso_cap->ill_lso_on) {
23642 		/*
23643 		 * If LSO has been previously turned off in the past, and we
23644 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23645 		 * then enable it for this interface.
23646 		 */
23647 		lso_cap->ill_lso_on = 1;
23648 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23649 		    ill_name));
23650 	}
23651 
23652 	/* Allocate the LSO info mblk */
23653 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23654 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23655 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23656 
23657 	return (mp);
23658 }
23659 
23660 /*
23661  * Create destination address attribute, and fill it with the physical
23662  * destination address and SAP taken from the template DL_UNITDATA_REQ
23663  * message block.
23664  */
23665 boolean_t
23666 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23667 {
23668 	dl_unitdata_req_t *dlurp;
23669 	pattr_t *pa;
23670 	pattrinfo_t pa_info;
23671 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23672 	uint_t das_len, das_off;
23673 
23674 	ASSERT(dlmp != NULL);
23675 
23676 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23677 	das_len = dlurp->dl_dest_addr_length;
23678 	das_off = dlurp->dl_dest_addr_offset;
23679 
23680 	pa_info.type = PATTR_DSTADDRSAP;
23681 	pa_info.len = sizeof (**das) + das_len - 1;
23682 
23683 	/* create and associate the attribute */
23684 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23685 	if (pa != NULL) {
23686 		ASSERT(*das != NULL);
23687 		(*das)->addr_is_group = 0;
23688 		(*das)->addr_len = (uint8_t)das_len;
23689 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23690 	}
23691 
23692 	return (pa != NULL);
23693 }
23694 
23695 /*
23696  * Create hardware checksum attribute and fill it with the values passed.
23697  */
23698 boolean_t
23699 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23700     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23701 {
23702 	pattr_t *pa;
23703 	pattrinfo_t pa_info;
23704 
23705 	ASSERT(mmd != NULL);
23706 
23707 	pa_info.type = PATTR_HCKSUM;
23708 	pa_info.len = sizeof (pattr_hcksum_t);
23709 
23710 	/* create and associate the attribute */
23711 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23712 	if (pa != NULL) {
23713 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23714 
23715 		hck->hcksum_start_offset = start_offset;
23716 		hck->hcksum_stuff_offset = stuff_offset;
23717 		hck->hcksum_end_offset = end_offset;
23718 		hck->hcksum_flags = flags;
23719 	}
23720 	return (pa != NULL);
23721 }
23722 
23723 /*
23724  * Create zerocopy attribute and fill it with the specified flags
23725  */
23726 boolean_t
23727 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23728 {
23729 	pattr_t *pa;
23730 	pattrinfo_t pa_info;
23731 
23732 	ASSERT(mmd != NULL);
23733 	pa_info.type = PATTR_ZCOPY;
23734 	pa_info.len = sizeof (pattr_zcopy_t);
23735 
23736 	/* create and associate the attribute */
23737 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23738 	if (pa != NULL) {
23739 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23740 
23741 		zcopy->zcopy_flags = flags;
23742 	}
23743 	return (pa != NULL);
23744 }
23745 
23746 /*
23747  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23748  * block chain. We could rewrite to handle arbitrary message block chains but
23749  * that would make the code complicated and slow. Right now there three
23750  * restrictions:
23751  *
23752  *   1. The first message block must contain the complete IP header and
23753  *	at least 1 byte of payload data.
23754  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23755  *	so that we can use a single Multidata message.
23756  *   3. No frag must be distributed over two or more message blocks so
23757  *	that we don't need more than two packet descriptors per frag.
23758  *
23759  * The above restrictions allow us to support userland applications (which
23760  * will send down a single message block) and NFS over UDP (which will
23761  * send down a chain of at most three message blocks).
23762  *
23763  * We also don't use MDT for payloads with less than or equal to
23764  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23765  */
23766 boolean_t
23767 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23768 {
23769 	int	blocks;
23770 	ssize_t	total, missing, size;
23771 
23772 	ASSERT(mp != NULL);
23773 	ASSERT(hdr_len > 0);
23774 
23775 	size = MBLKL(mp) - hdr_len;
23776 	if (size <= 0)
23777 		return (B_FALSE);
23778 
23779 	/* The first mblk contains the header and some payload. */
23780 	blocks = 1;
23781 	total = size;
23782 	size %= len;
23783 	missing = (size == 0) ? 0 : (len - size);
23784 	mp = mp->b_cont;
23785 
23786 	while (mp != NULL) {
23787 		/*
23788 		 * Give up if we encounter a zero length message block.
23789 		 * In practice, this should rarely happen and therefore
23790 		 * not worth the trouble of freeing and re-linking the
23791 		 * mblk from the chain to handle such case.
23792 		 */
23793 		if ((size = MBLKL(mp)) == 0)
23794 			return (B_FALSE);
23795 
23796 		/* Too many payload buffers for a single Multidata message? */
23797 		if (++blocks > MULTIDATA_MAX_PBUFS)
23798 			return (B_FALSE);
23799 
23800 		total += size;
23801 		/* Is a frag distributed over two or more message blocks? */
23802 		if (missing > size)
23803 			return (B_FALSE);
23804 		size -= missing;
23805 
23806 		size %= len;
23807 		missing = (size == 0) ? 0 : (len - size);
23808 
23809 		mp = mp->b_cont;
23810 	}
23811 
23812 	return (total > ip_wput_frag_mdt_min);
23813 }
23814 
23815 /*
23816  * Outbound IPv4 fragmentation routine using MDT.
23817  */
23818 static void
23819 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23820     uint32_t frag_flag, int offset)
23821 {
23822 	ipha_t		*ipha_orig;
23823 	int		i1, ip_data_end;
23824 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23825 	mblk_t		*hdr_mp, *md_mp = NULL;
23826 	unsigned char	*hdr_ptr, *pld_ptr;
23827 	multidata_t	*mmd;
23828 	ip_pdescinfo_t	pdi;
23829 	ill_t		*ill;
23830 	ip_stack_t	*ipst = ire->ire_ipst;
23831 
23832 	ASSERT(DB_TYPE(mp) == M_DATA);
23833 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23834 
23835 	ill = ire_to_ill(ire);
23836 	ASSERT(ill != NULL);
23837 
23838 	ipha_orig = (ipha_t *)mp->b_rptr;
23839 	mp->b_rptr += sizeof (ipha_t);
23840 
23841 	/* Calculate how many packets we will send out */
23842 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23843 	pkts = (i1 + len - 1) / len;
23844 	ASSERT(pkts > 1);
23845 
23846 	/* Allocate a message block which will hold all the IP Headers. */
23847 	wroff = ipst->ips_ip_wroff_extra;
23848 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23849 
23850 	i1 = pkts * hdr_chunk_len;
23851 	/*
23852 	 * Create the header buffer, Multidata and destination address
23853 	 * and SAP attribute that should be associated with it.
23854 	 */
23855 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23856 	    ((hdr_mp->b_wptr += i1),
23857 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23858 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23859 		freemsg(mp);
23860 		if (md_mp == NULL) {
23861 			freemsg(hdr_mp);
23862 		} else {
23863 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23864 			freemsg(md_mp);
23865 		}
23866 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23867 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23868 		return;
23869 	}
23870 	IP_STAT(ipst, ip_frag_mdt_allocd);
23871 
23872 	/*
23873 	 * Add a payload buffer to the Multidata; this operation must not
23874 	 * fail, or otherwise our logic in this routine is broken.  There
23875 	 * is no memory allocation done by the routine, so any returned
23876 	 * failure simply tells us that we've done something wrong.
23877 	 *
23878 	 * A failure tells us that either we're adding the same payload
23879 	 * buffer more than once, or we're trying to add more buffers than
23880 	 * allowed.  None of the above cases should happen, and we panic
23881 	 * because either there's horrible heap corruption, and/or
23882 	 * programming mistake.
23883 	 */
23884 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23885 		goto pbuf_panic;
23886 
23887 	hdr_ptr = hdr_mp->b_rptr;
23888 	pld_ptr = mp->b_rptr;
23889 
23890 	/* Establish the ending byte offset, based on the starting offset. */
23891 	offset <<= 3;
23892 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23893 	    IP_SIMPLE_HDR_LENGTH;
23894 
23895 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23896 
23897 	while (pld_ptr < mp->b_wptr) {
23898 		ipha_t		*ipha;
23899 		uint16_t	offset_and_flags;
23900 		uint16_t	ip_len;
23901 		int		error;
23902 
23903 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23904 		ipha = (ipha_t *)(hdr_ptr + wroff);
23905 		ASSERT(OK_32PTR(ipha));
23906 		*ipha = *ipha_orig;
23907 
23908 		if (ip_data_end - offset > len) {
23909 			offset_and_flags = IPH_MF;
23910 		} else {
23911 			/*
23912 			 * Last frag. Set len to the length of this last piece.
23913 			 */
23914 			len = ip_data_end - offset;
23915 			/* A frag of a frag might have IPH_MF non-zero */
23916 			offset_and_flags =
23917 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23918 			    IPH_MF;
23919 		}
23920 		offset_and_flags |= (uint16_t)(offset >> 3);
23921 		offset_and_flags |= (uint16_t)frag_flag;
23922 		/* Store the offset and flags in the IP header. */
23923 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23924 
23925 		/* Store the length in the IP header. */
23926 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23927 		ipha->ipha_length = htons(ip_len);
23928 
23929 		/*
23930 		 * Set the IP header checksum.  Note that mp is just
23931 		 * the header, so this is easy to pass to ip_csum.
23932 		 */
23933 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23934 
23935 		/*
23936 		 * Record offset and size of header and data of the next packet
23937 		 * in the multidata message.
23938 		 */
23939 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23940 		PDESC_PLD_INIT(&pdi);
23941 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23942 		ASSERT(i1 > 0);
23943 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23944 		if (i1 == len) {
23945 			pld_ptr += len;
23946 		} else {
23947 			i1 = len - i1;
23948 			mp = mp->b_cont;
23949 			ASSERT(mp != NULL);
23950 			ASSERT(MBLKL(mp) >= i1);
23951 			/*
23952 			 * Attach the next payload message block to the
23953 			 * multidata message.
23954 			 */
23955 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23956 				goto pbuf_panic;
23957 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23958 			pld_ptr = mp->b_rptr + i1;
23959 		}
23960 
23961 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23962 		    KM_NOSLEEP)) == NULL) {
23963 			/*
23964 			 * Any failure other than ENOMEM indicates that we
23965 			 * have passed in invalid pdesc info or parameters
23966 			 * to mmd_addpdesc, which must not happen.
23967 			 *
23968 			 * EINVAL is a result of failure on boundary checks
23969 			 * against the pdesc info contents.  It should not
23970 			 * happen, and we panic because either there's
23971 			 * horrible heap corruption, and/or programming
23972 			 * mistake.
23973 			 */
23974 			if (error != ENOMEM) {
23975 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23976 				    "pdesc logic error detected for "
23977 				    "mmd %p pinfo %p (%d)\n",
23978 				    (void *)mmd, (void *)&pdi, error);
23979 				/* NOTREACHED */
23980 			}
23981 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23982 			/* Free unattached payload message blocks as well */
23983 			md_mp->b_cont = mp->b_cont;
23984 			goto free_mmd;
23985 		}
23986 
23987 		/* Advance fragment offset. */
23988 		offset += len;
23989 
23990 		/* Advance to location for next header in the buffer. */
23991 		hdr_ptr += hdr_chunk_len;
23992 
23993 		/* Did we reach the next payload message block? */
23994 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23995 			mp = mp->b_cont;
23996 			/*
23997 			 * Attach the next message block with payload
23998 			 * data to the multidata message.
23999 			 */
24000 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24001 				goto pbuf_panic;
24002 			pld_ptr = mp->b_rptr;
24003 		}
24004 	}
24005 
24006 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24007 	ASSERT(mp->b_wptr == pld_ptr);
24008 
24009 	/* Update IP statistics */
24010 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24011 
24012 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24013 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24014 
24015 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24016 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24017 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24018 
24019 	if (pkt_type == OB_PKT) {
24020 		ire->ire_ob_pkt_count += pkts;
24021 		if (ire->ire_ipif != NULL)
24022 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24023 	} else {
24024 		/* The type is IB_PKT in the forwarding path. */
24025 		ire->ire_ib_pkt_count += pkts;
24026 		ASSERT(!IRE_IS_LOCAL(ire));
24027 		if (ire->ire_type & IRE_BROADCAST) {
24028 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24029 		} else {
24030 			UPDATE_MIB(ill->ill_ip_mib,
24031 			    ipIfStatsHCOutForwDatagrams, pkts);
24032 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24033 		}
24034 	}
24035 	ire->ire_last_used_time = lbolt;
24036 	/* Send it down */
24037 	putnext(ire->ire_stq, md_mp);
24038 	return;
24039 
24040 pbuf_panic:
24041 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24042 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24043 	    pbuf_idx);
24044 	/* NOTREACHED */
24045 }
24046 
24047 /*
24048  * Outbound IP fragmentation routine.
24049  *
24050  * NOTE : This routine does not ire_refrele the ire that is passed in
24051  * as the argument.
24052  */
24053 static void
24054 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24055     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24056 {
24057 	int		i1;
24058 	mblk_t		*ll_hdr_mp;
24059 	int 		ll_hdr_len;
24060 	int		hdr_len;
24061 	mblk_t		*hdr_mp;
24062 	ipha_t		*ipha;
24063 	int		ip_data_end;
24064 	int		len;
24065 	mblk_t		*mp = mp_orig, *mp1;
24066 	int		offset;
24067 	queue_t		*q;
24068 	uint32_t	v_hlen_tos_len;
24069 	mblk_t		*first_mp;
24070 	boolean_t	mctl_present;
24071 	ill_t		*ill;
24072 	ill_t		*out_ill;
24073 	mblk_t		*xmit_mp;
24074 	mblk_t		*carve_mp;
24075 	ire_t		*ire1 = NULL;
24076 	ire_t		*save_ire = NULL;
24077 	mblk_t  	*next_mp = NULL;
24078 	boolean_t	last_frag = B_FALSE;
24079 	boolean_t	multirt_send = B_FALSE;
24080 	ire_t		*first_ire = NULL;
24081 	irb_t		*irb = NULL;
24082 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24083 
24084 	ill = ire_to_ill(ire);
24085 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24086 
24087 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24088 
24089 	if (max_frag == 0) {
24090 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24091 		    " -  dropping packet\n"));
24092 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24093 		freemsg(mp);
24094 		return;
24095 	}
24096 
24097 	/*
24098 	 * IPsec does not allow hw accelerated packets to be fragmented
24099 	 * This check is made in ip_wput_ipsec_out prior to coming here
24100 	 * via ip_wput_ire_fragmentit.
24101 	 *
24102 	 * If at this point we have an ire whose ARP request has not
24103 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24104 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24105 	 * This packet and all fragmentable packets for this ire will
24106 	 * continue to get dropped while ire_nce->nce_state remains in
24107 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24108 	 * ND_REACHABLE, all subsquent large packets for this ire will
24109 	 * get fragemented and sent out by this function.
24110 	 */
24111 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24112 		/* If nce_state is ND_INITIAL, trigger ARP query */
24113 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24114 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24115 		    " -  dropping packet\n"));
24116 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24117 		freemsg(mp);
24118 		return;
24119 	}
24120 
24121 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24122 	    "ip_wput_frag_start:");
24123 
24124 	if (mp->b_datap->db_type == M_CTL) {
24125 		first_mp = mp;
24126 		mp_orig = mp = mp->b_cont;
24127 		mctl_present = B_TRUE;
24128 	} else {
24129 		first_mp = mp;
24130 		mctl_present = B_FALSE;
24131 	}
24132 
24133 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24134 	ipha = (ipha_t *)mp->b_rptr;
24135 
24136 	/*
24137 	 * If the Don't Fragment flag is on, generate an ICMP destination
24138 	 * unreachable, fragmentation needed.
24139 	 */
24140 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24141 	if (offset & IPH_DF) {
24142 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24143 		if (is_system_labeled()) {
24144 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24145 			    ire->ire_max_frag - max_frag, AF_INET);
24146 		}
24147 		/*
24148 		 * Need to compute hdr checksum if called from ip_wput_ire.
24149 		 * Note that ip_rput_forward verifies the checksum before
24150 		 * calling this routine so in that case this is a noop.
24151 		 */
24152 		ipha->ipha_hdr_checksum = 0;
24153 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24154 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24155 		    ipst);
24156 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24157 		    "ip_wput_frag_end:(%S)",
24158 		    "don't fragment");
24159 		return;
24160 	}
24161 	/*
24162 	 * Labeled systems adjust max_frag if they add a label
24163 	 * to send the correct path mtu.  We need the real mtu since we
24164 	 * are fragmenting the packet after label adjustment.
24165 	 */
24166 	if (is_system_labeled())
24167 		max_frag = ire->ire_max_frag;
24168 	if (mctl_present)
24169 		freeb(first_mp);
24170 	/*
24171 	 * Establish the starting offset.  May not be zero if we are fragging
24172 	 * a fragment that is being forwarded.
24173 	 */
24174 	offset = offset & IPH_OFFSET;
24175 
24176 	/* TODO why is this test needed? */
24177 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24178 	if (((max_frag - LENGTH) & ~7) < 8) {
24179 		/* TODO: notify ulp somehow */
24180 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24181 		freemsg(mp);
24182 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24183 		    "ip_wput_frag_end:(%S)",
24184 		    "len < 8");
24185 		return;
24186 	}
24187 
24188 	hdr_len = (V_HLEN & 0xF) << 2;
24189 
24190 	ipha->ipha_hdr_checksum = 0;
24191 
24192 	/*
24193 	 * Establish the number of bytes maximum per frag, after putting
24194 	 * in the header.
24195 	 */
24196 	len = (max_frag - hdr_len) & ~7;
24197 
24198 	/* Check if we can use MDT to send out the frags. */
24199 	ASSERT(!IRE_IS_LOCAL(ire));
24200 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24201 	    ipst->ips_ip_multidata_outbound &&
24202 	    !(ire->ire_flags & RTF_MULTIRT) &&
24203 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24204 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24205 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24206 		ASSERT(ill->ill_mdt_capab != NULL);
24207 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24208 			/*
24209 			 * If MDT has been previously turned off in the past,
24210 			 * and we currently can do MDT (due to IPQoS policy
24211 			 * removal, etc.) then enable it for this interface.
24212 			 */
24213 			ill->ill_mdt_capab->ill_mdt_on = 1;
24214 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24215 			    ill->ill_name));
24216 		}
24217 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24218 		    offset);
24219 		return;
24220 	}
24221 
24222 	/* Get a copy of the header for the trailing frags */
24223 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24224 	if (!hdr_mp) {
24225 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24226 		freemsg(mp);
24227 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24228 		    "ip_wput_frag_end:(%S)",
24229 		    "couldn't copy hdr");
24230 		return;
24231 	}
24232 	if (DB_CRED(mp) != NULL)
24233 		mblk_setcred(hdr_mp, DB_CRED(mp));
24234 
24235 	/* Store the starting offset, with the MoreFrags flag. */
24236 	i1 = offset | IPH_MF | frag_flag;
24237 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24238 
24239 	/* Establish the ending byte offset, based on the starting offset. */
24240 	offset <<= 3;
24241 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24242 
24243 	/* Store the length of the first fragment in the IP header. */
24244 	i1 = len + hdr_len;
24245 	ASSERT(i1 <= IP_MAXPACKET);
24246 	ipha->ipha_length = htons((uint16_t)i1);
24247 
24248 	/*
24249 	 * Compute the IP header checksum for the first frag.  We have to
24250 	 * watch out that we stop at the end of the header.
24251 	 */
24252 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24253 
24254 	/*
24255 	 * Now carve off the first frag.  Note that this will include the
24256 	 * original IP header.
24257 	 */
24258 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24259 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24260 		freeb(hdr_mp);
24261 		freemsg(mp_orig);
24262 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24263 		    "ip_wput_frag_end:(%S)",
24264 		    "couldn't carve first");
24265 		return;
24266 	}
24267 
24268 	/*
24269 	 * Multirouting case. Each fragment is replicated
24270 	 * via all non-condemned RTF_MULTIRT routes
24271 	 * currently resolved.
24272 	 * We ensure that first_ire is the first RTF_MULTIRT
24273 	 * ire in the bucket.
24274 	 */
24275 	if (ire->ire_flags & RTF_MULTIRT) {
24276 		irb = ire->ire_bucket;
24277 		ASSERT(irb != NULL);
24278 
24279 		multirt_send = B_TRUE;
24280 
24281 		/* Make sure we do not omit any multiroute ire. */
24282 		IRB_REFHOLD(irb);
24283 		for (first_ire = irb->irb_ire;
24284 		    first_ire != NULL;
24285 		    first_ire = first_ire->ire_next) {
24286 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24287 			    (first_ire->ire_addr == ire->ire_addr) &&
24288 			    !(first_ire->ire_marks &
24289 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24290 				break;
24291 			}
24292 		}
24293 
24294 		if (first_ire != NULL) {
24295 			if (first_ire != ire) {
24296 				IRE_REFHOLD(first_ire);
24297 				/*
24298 				 * Do not release the ire passed in
24299 				 * as the argument.
24300 				 */
24301 				ire = first_ire;
24302 			} else {
24303 				first_ire = NULL;
24304 			}
24305 		}
24306 		IRB_REFRELE(irb);
24307 
24308 		/*
24309 		 * Save the first ire; we will need to restore it
24310 		 * for the trailing frags.
24311 		 * We REFHOLD save_ire, as each iterated ire will be
24312 		 * REFRELEd.
24313 		 */
24314 		save_ire = ire;
24315 		IRE_REFHOLD(save_ire);
24316 	}
24317 
24318 	/*
24319 	 * First fragment emission loop.
24320 	 * In most cases, the emission loop below is entered only
24321 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24322 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24323 	 * bucket, and send the fragment through all crossed
24324 	 * RTF_MULTIRT routes.
24325 	 */
24326 	do {
24327 		if (ire->ire_flags & RTF_MULTIRT) {
24328 			/*
24329 			 * We are in a multiple send case, need to get
24330 			 * the next ire and make a copy of the packet.
24331 			 * ire1 holds here the next ire to process in the
24332 			 * bucket. If multirouting is expected,
24333 			 * any non-RTF_MULTIRT ire that has the
24334 			 * right destination address is ignored.
24335 			 *
24336 			 * We have to take into account the MTU of
24337 			 * each walked ire. max_frag is set by the
24338 			 * the caller and generally refers to
24339 			 * the primary ire entry. Here we ensure that
24340 			 * no route with a lower MTU will be used, as
24341 			 * fragments are carved once for all ires,
24342 			 * then replicated.
24343 			 */
24344 			ASSERT(irb != NULL);
24345 			IRB_REFHOLD(irb);
24346 			for (ire1 = ire->ire_next;
24347 			    ire1 != NULL;
24348 			    ire1 = ire1->ire_next) {
24349 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24350 					continue;
24351 				if (ire1->ire_addr != ire->ire_addr)
24352 					continue;
24353 				if (ire1->ire_marks &
24354 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24355 					continue;
24356 				/*
24357 				 * Ensure we do not exceed the MTU
24358 				 * of the next route.
24359 				 */
24360 				if (ire1->ire_max_frag < max_frag) {
24361 					ip_multirt_bad_mtu(ire1, max_frag);
24362 					continue;
24363 				}
24364 
24365 				/* Got one. */
24366 				IRE_REFHOLD(ire1);
24367 				break;
24368 			}
24369 			IRB_REFRELE(irb);
24370 
24371 			if (ire1 != NULL) {
24372 				next_mp = copyb(mp);
24373 				if ((next_mp == NULL) ||
24374 				    ((mp->b_cont != NULL) &&
24375 				    ((next_mp->b_cont =
24376 				    dupmsg(mp->b_cont)) == NULL))) {
24377 					freemsg(next_mp);
24378 					next_mp = NULL;
24379 					ire_refrele(ire1);
24380 					ire1 = NULL;
24381 				}
24382 			}
24383 
24384 			/* Last multiroute ire; don't loop anymore. */
24385 			if (ire1 == NULL) {
24386 				multirt_send = B_FALSE;
24387 			}
24388 		}
24389 
24390 		ll_hdr_len = 0;
24391 		LOCK_IRE_FP_MP(ire);
24392 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24393 		if (ll_hdr_mp != NULL) {
24394 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24395 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24396 		} else {
24397 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24398 		}
24399 
24400 		/* If there is a transmit header, get a copy for this frag. */
24401 		/*
24402 		 * TODO: should check db_ref before calling ip_carve_mp since
24403 		 * it might give us a dup.
24404 		 */
24405 		if (!ll_hdr_mp) {
24406 			/* No xmit header. */
24407 			xmit_mp = mp;
24408 
24409 		/* We have a link-layer header that can fit in our mblk. */
24410 		} else if (mp->b_datap->db_ref == 1 &&
24411 		    ll_hdr_len != 0 &&
24412 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24413 			/* M_DATA fastpath */
24414 			mp->b_rptr -= ll_hdr_len;
24415 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24416 			xmit_mp = mp;
24417 
24418 		/* Corner case if copyb has failed */
24419 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24420 			UNLOCK_IRE_FP_MP(ire);
24421 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24422 			freeb(hdr_mp);
24423 			freemsg(mp);
24424 			freemsg(mp_orig);
24425 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24426 			    "ip_wput_frag_end:(%S)",
24427 			    "discard");
24428 
24429 			if (multirt_send) {
24430 				ASSERT(ire1);
24431 				ASSERT(next_mp);
24432 
24433 				freemsg(next_mp);
24434 				ire_refrele(ire1);
24435 			}
24436 			if (save_ire != NULL)
24437 				IRE_REFRELE(save_ire);
24438 
24439 			if (first_ire != NULL)
24440 				ire_refrele(first_ire);
24441 			return;
24442 
24443 		/*
24444 		 * Case of res_mp OR the fastpath mp can't fit
24445 		 * in the mblk
24446 		 */
24447 		} else {
24448 			xmit_mp->b_cont = mp;
24449 			if (DB_CRED(mp) != NULL)
24450 				mblk_setcred(xmit_mp, DB_CRED(mp));
24451 			/*
24452 			 * Get priority marking, if any.
24453 			 * We propagate the CoS marking from the
24454 			 * original packet that went to QoS processing
24455 			 * in ip_wput_ire to the newly carved mp.
24456 			 */
24457 			if (DB_TYPE(xmit_mp) == M_DATA)
24458 				xmit_mp->b_band = mp->b_band;
24459 		}
24460 		UNLOCK_IRE_FP_MP(ire);
24461 
24462 		q = ire->ire_stq;
24463 		out_ill = (ill_t *)q->q_ptr;
24464 
24465 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24466 
24467 		DTRACE_PROBE4(ip4__physical__out__start,
24468 		    ill_t *, NULL, ill_t *, out_ill,
24469 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24470 
24471 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24472 		    ipst->ips_ipv4firewall_physical_out,
24473 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24474 
24475 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24476 
24477 		if (xmit_mp != NULL) {
24478 			putnext(q, xmit_mp);
24479 
24480 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24481 			UPDATE_MIB(out_ill->ill_ip_mib,
24482 			    ipIfStatsHCOutOctets, i1);
24483 
24484 			if (pkt_type != OB_PKT) {
24485 				/*
24486 				 * Update the packet count and MIB stats
24487 				 * of trailing RTF_MULTIRT ires.
24488 				 */
24489 				UPDATE_OB_PKT_COUNT(ire);
24490 				BUMP_MIB(out_ill->ill_ip_mib,
24491 				    ipIfStatsOutFragReqds);
24492 			}
24493 		}
24494 
24495 		if (multirt_send) {
24496 			/*
24497 			 * We are in a multiple send case; look for
24498 			 * the next ire and re-enter the loop.
24499 			 */
24500 			ASSERT(ire1);
24501 			ASSERT(next_mp);
24502 			/* REFRELE the current ire before looping */
24503 			ire_refrele(ire);
24504 			ire = ire1;
24505 			ire1 = NULL;
24506 			mp = next_mp;
24507 			next_mp = NULL;
24508 		}
24509 	} while (multirt_send);
24510 
24511 	ASSERT(ire1 == NULL);
24512 
24513 	/* Restore the original ire; we need it for the trailing frags */
24514 	if (save_ire != NULL) {
24515 		/* REFRELE the last iterated ire */
24516 		ire_refrele(ire);
24517 		/* save_ire has been REFHOLDed */
24518 		ire = save_ire;
24519 		save_ire = NULL;
24520 		q = ire->ire_stq;
24521 	}
24522 
24523 	if (pkt_type == OB_PKT) {
24524 		UPDATE_OB_PKT_COUNT(ire);
24525 	} else {
24526 		out_ill = (ill_t *)q->q_ptr;
24527 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24528 		UPDATE_IB_PKT_COUNT(ire);
24529 	}
24530 
24531 	/* Advance the offset to the second frag starting point. */
24532 	offset += len;
24533 	/*
24534 	 * Update hdr_len from the copied header - there might be less options
24535 	 * in the later fragments.
24536 	 */
24537 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24538 	/* Loop until done. */
24539 	for (;;) {
24540 		uint16_t	offset_and_flags;
24541 		uint16_t	ip_len;
24542 
24543 		if (ip_data_end - offset > len) {
24544 			/*
24545 			 * Carve off the appropriate amount from the original
24546 			 * datagram.
24547 			 */
24548 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24549 				mp = NULL;
24550 				break;
24551 			}
24552 			/*
24553 			 * More frags after this one.  Get another copy
24554 			 * of the header.
24555 			 */
24556 			if (carve_mp->b_datap->db_ref == 1 &&
24557 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24558 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24559 				/* Inline IP header */
24560 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24561 				    hdr_mp->b_rptr;
24562 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24563 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24564 				mp = carve_mp;
24565 			} else {
24566 				if (!(mp = copyb(hdr_mp))) {
24567 					freemsg(carve_mp);
24568 					break;
24569 				}
24570 				/* Get priority marking, if any. */
24571 				mp->b_band = carve_mp->b_band;
24572 				mp->b_cont = carve_mp;
24573 			}
24574 			ipha = (ipha_t *)mp->b_rptr;
24575 			offset_and_flags = IPH_MF;
24576 		} else {
24577 			/*
24578 			 * Last frag.  Consume the header. Set len to
24579 			 * the length of this last piece.
24580 			 */
24581 			len = ip_data_end - offset;
24582 
24583 			/*
24584 			 * Carve off the appropriate amount from the original
24585 			 * datagram.
24586 			 */
24587 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24588 				mp = NULL;
24589 				break;
24590 			}
24591 			if (carve_mp->b_datap->db_ref == 1 &&
24592 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24593 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24594 				/* Inline IP header */
24595 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24596 				    hdr_mp->b_rptr;
24597 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24598 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24599 				mp = carve_mp;
24600 				freeb(hdr_mp);
24601 				hdr_mp = mp;
24602 			} else {
24603 				mp = hdr_mp;
24604 				/* Get priority marking, if any. */
24605 				mp->b_band = carve_mp->b_band;
24606 				mp->b_cont = carve_mp;
24607 			}
24608 			ipha = (ipha_t *)mp->b_rptr;
24609 			/* A frag of a frag might have IPH_MF non-zero */
24610 			offset_and_flags =
24611 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24612 			    IPH_MF;
24613 		}
24614 		offset_and_flags |= (uint16_t)(offset >> 3);
24615 		offset_and_flags |= (uint16_t)frag_flag;
24616 		/* Store the offset and flags in the IP header. */
24617 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24618 
24619 		/* Store the length in the IP header. */
24620 		ip_len = (uint16_t)(len + hdr_len);
24621 		ipha->ipha_length = htons(ip_len);
24622 
24623 		/*
24624 		 * Set the IP header checksum.	Note that mp is just
24625 		 * the header, so this is easy to pass to ip_csum.
24626 		 */
24627 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24628 
24629 		/* Attach a transmit header, if any, and ship it. */
24630 		if (pkt_type == OB_PKT) {
24631 			UPDATE_OB_PKT_COUNT(ire);
24632 		} else {
24633 			out_ill = (ill_t *)q->q_ptr;
24634 			BUMP_MIB(out_ill->ill_ip_mib,
24635 			    ipIfStatsHCOutForwDatagrams);
24636 			UPDATE_IB_PKT_COUNT(ire);
24637 		}
24638 
24639 		if (ire->ire_flags & RTF_MULTIRT) {
24640 			irb = ire->ire_bucket;
24641 			ASSERT(irb != NULL);
24642 
24643 			multirt_send = B_TRUE;
24644 
24645 			/*
24646 			 * Save the original ire; we will need to restore it
24647 			 * for the tailing frags.
24648 			 */
24649 			save_ire = ire;
24650 			IRE_REFHOLD(save_ire);
24651 		}
24652 		/*
24653 		 * Emission loop for this fragment, similar
24654 		 * to what is done for the first fragment.
24655 		 */
24656 		do {
24657 			if (multirt_send) {
24658 				/*
24659 				 * We are in a multiple send case, need to get
24660 				 * the next ire and make a copy of the packet.
24661 				 */
24662 				ASSERT(irb != NULL);
24663 				IRB_REFHOLD(irb);
24664 				for (ire1 = ire->ire_next;
24665 				    ire1 != NULL;
24666 				    ire1 = ire1->ire_next) {
24667 					if (!(ire1->ire_flags & RTF_MULTIRT))
24668 						continue;
24669 					if (ire1->ire_addr != ire->ire_addr)
24670 						continue;
24671 					if (ire1->ire_marks &
24672 					    (IRE_MARK_CONDEMNED|
24673 					    IRE_MARK_HIDDEN)) {
24674 						continue;
24675 					}
24676 					/*
24677 					 * Ensure we do not exceed the MTU
24678 					 * of the next route.
24679 					 */
24680 					if (ire1->ire_max_frag < max_frag) {
24681 						ip_multirt_bad_mtu(ire1,
24682 						    max_frag);
24683 						continue;
24684 					}
24685 
24686 					/* Got one. */
24687 					IRE_REFHOLD(ire1);
24688 					break;
24689 				}
24690 				IRB_REFRELE(irb);
24691 
24692 				if (ire1 != NULL) {
24693 					next_mp = copyb(mp);
24694 					if ((next_mp == NULL) ||
24695 					    ((mp->b_cont != NULL) &&
24696 					    ((next_mp->b_cont =
24697 					    dupmsg(mp->b_cont)) == NULL))) {
24698 						freemsg(next_mp);
24699 						next_mp = NULL;
24700 						ire_refrele(ire1);
24701 						ire1 = NULL;
24702 					}
24703 				}
24704 
24705 				/* Last multiroute ire; don't loop anymore. */
24706 				if (ire1 == NULL) {
24707 					multirt_send = B_FALSE;
24708 				}
24709 			}
24710 
24711 			/* Update transmit header */
24712 			ll_hdr_len = 0;
24713 			LOCK_IRE_FP_MP(ire);
24714 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24715 			if (ll_hdr_mp != NULL) {
24716 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24717 				ll_hdr_len = MBLKL(ll_hdr_mp);
24718 			} else {
24719 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24720 			}
24721 
24722 			if (!ll_hdr_mp) {
24723 				xmit_mp = mp;
24724 
24725 			/*
24726 			 * We have link-layer header that can fit in
24727 			 * our mblk.
24728 			 */
24729 			} else if (mp->b_datap->db_ref == 1 &&
24730 			    ll_hdr_len != 0 &&
24731 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24732 				/* M_DATA fastpath */
24733 				mp->b_rptr -= ll_hdr_len;
24734 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24735 				    ll_hdr_len);
24736 				xmit_mp = mp;
24737 
24738 			/*
24739 			 * Case of res_mp OR the fastpath mp can't fit
24740 			 * in the mblk
24741 			 */
24742 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24743 				xmit_mp->b_cont = mp;
24744 				if (DB_CRED(mp) != NULL)
24745 					mblk_setcred(xmit_mp, DB_CRED(mp));
24746 				/* Get priority marking, if any. */
24747 				if (DB_TYPE(xmit_mp) == M_DATA)
24748 					xmit_mp->b_band = mp->b_band;
24749 
24750 			/* Corner case if copyb failed */
24751 			} else {
24752 				/*
24753 				 * Exit both the replication and
24754 				 * fragmentation loops.
24755 				 */
24756 				UNLOCK_IRE_FP_MP(ire);
24757 				goto drop_pkt;
24758 			}
24759 			UNLOCK_IRE_FP_MP(ire);
24760 
24761 			mp1 = mp;
24762 			out_ill = (ill_t *)q->q_ptr;
24763 
24764 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24765 
24766 			DTRACE_PROBE4(ip4__physical__out__start,
24767 			    ill_t *, NULL, ill_t *, out_ill,
24768 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24769 
24770 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24771 			    ipst->ips_ipv4firewall_physical_out,
24772 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24773 
24774 			DTRACE_PROBE1(ip4__physical__out__end,
24775 			    mblk_t *, xmit_mp);
24776 
24777 			if (mp != mp1 && hdr_mp == mp1)
24778 				hdr_mp = mp;
24779 			if (mp != mp1 && mp_orig == mp1)
24780 				mp_orig = mp;
24781 
24782 			if (xmit_mp != NULL) {
24783 				putnext(q, xmit_mp);
24784 
24785 				BUMP_MIB(out_ill->ill_ip_mib,
24786 				    ipIfStatsHCOutTransmits);
24787 				UPDATE_MIB(out_ill->ill_ip_mib,
24788 				    ipIfStatsHCOutOctets, ip_len);
24789 
24790 				if (pkt_type != OB_PKT) {
24791 					/*
24792 					 * Update the packet count of trailing
24793 					 * RTF_MULTIRT ires.
24794 					 */
24795 					UPDATE_OB_PKT_COUNT(ire);
24796 				}
24797 			}
24798 
24799 			/* All done if we just consumed the hdr_mp. */
24800 			if (mp == hdr_mp) {
24801 				last_frag = B_TRUE;
24802 				BUMP_MIB(out_ill->ill_ip_mib,
24803 				    ipIfStatsOutFragOKs);
24804 			}
24805 
24806 			if (multirt_send) {
24807 				/*
24808 				 * We are in a multiple send case; look for
24809 				 * the next ire and re-enter the loop.
24810 				 */
24811 				ASSERT(ire1);
24812 				ASSERT(next_mp);
24813 				/* REFRELE the current ire before looping */
24814 				ire_refrele(ire);
24815 				ire = ire1;
24816 				ire1 = NULL;
24817 				q = ire->ire_stq;
24818 				mp = next_mp;
24819 				next_mp = NULL;
24820 			}
24821 		} while (multirt_send);
24822 		/*
24823 		 * Restore the original ire; we need it for the
24824 		 * trailing frags
24825 		 */
24826 		if (save_ire != NULL) {
24827 			ASSERT(ire1 == NULL);
24828 			/* REFRELE the last iterated ire */
24829 			ire_refrele(ire);
24830 			/* save_ire has been REFHOLDed */
24831 			ire = save_ire;
24832 			q = ire->ire_stq;
24833 			save_ire = NULL;
24834 		}
24835 
24836 		if (last_frag) {
24837 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24838 			    "ip_wput_frag_end:(%S)",
24839 			    "consumed hdr_mp");
24840 
24841 			if (first_ire != NULL)
24842 				ire_refrele(first_ire);
24843 			return;
24844 		}
24845 		/* Otherwise, advance and loop. */
24846 		offset += len;
24847 	}
24848 
24849 drop_pkt:
24850 	/* Clean up following allocation failure. */
24851 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24852 	freemsg(mp);
24853 	if (mp != hdr_mp)
24854 		freeb(hdr_mp);
24855 	if (mp != mp_orig)
24856 		freemsg(mp_orig);
24857 
24858 	if (save_ire != NULL)
24859 		IRE_REFRELE(save_ire);
24860 	if (first_ire != NULL)
24861 		ire_refrele(first_ire);
24862 
24863 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24864 	    "ip_wput_frag_end:(%S)",
24865 	    "end--alloc failure");
24866 }
24867 
24868 /*
24869  * Copy the header plus those options which have the copy bit set
24870  */
24871 static mblk_t *
24872 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24873 {
24874 	mblk_t	*mp;
24875 	uchar_t	*up;
24876 
24877 	/*
24878 	 * Quick check if we need to look for options without the copy bit
24879 	 * set
24880 	 */
24881 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24882 	if (!mp)
24883 		return (mp);
24884 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24885 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24886 		bcopy(rptr, mp->b_rptr, hdr_len);
24887 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24888 		return (mp);
24889 	}
24890 	up  = mp->b_rptr;
24891 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24892 	up += IP_SIMPLE_HDR_LENGTH;
24893 	rptr += IP_SIMPLE_HDR_LENGTH;
24894 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24895 	while (hdr_len > 0) {
24896 		uint32_t optval;
24897 		uint32_t optlen;
24898 
24899 		optval = *rptr;
24900 		if (optval == IPOPT_EOL)
24901 			break;
24902 		if (optval == IPOPT_NOP)
24903 			optlen = 1;
24904 		else
24905 			optlen = rptr[1];
24906 		if (optval & IPOPT_COPY) {
24907 			bcopy(rptr, up, optlen);
24908 			up += optlen;
24909 		}
24910 		rptr += optlen;
24911 		hdr_len -= optlen;
24912 	}
24913 	/*
24914 	 * Make sure that we drop an even number of words by filling
24915 	 * with EOL to the next word boundary.
24916 	 */
24917 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24918 	    hdr_len & 0x3; hdr_len++)
24919 		*up++ = IPOPT_EOL;
24920 	mp->b_wptr = up;
24921 	/* Update header length */
24922 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24923 	return (mp);
24924 }
24925 
24926 /*
24927  * Delivery to local recipients including fanout to multiple recipients.
24928  * Does not do checksumming of UDP/TCP.
24929  * Note: q should be the read side queue for either the ill or conn.
24930  * Note: rq should be the read side q for the lower (ill) stream.
24931  * We don't send packets to IPPF processing, thus the last argument
24932  * to all the fanout calls are B_FALSE.
24933  */
24934 void
24935 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24936     int fanout_flags, zoneid_t zoneid)
24937 {
24938 	uint32_t	protocol;
24939 	mblk_t		*first_mp;
24940 	boolean_t	mctl_present;
24941 	int		ire_type;
24942 #define	rptr	((uchar_t *)ipha)
24943 	ip_stack_t	*ipst = ill->ill_ipst;
24944 
24945 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24946 	    "ip_wput_local_start: q %p", q);
24947 
24948 	if (ire != NULL) {
24949 		ire_type = ire->ire_type;
24950 	} else {
24951 		/*
24952 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24953 		 * packet is not multicast, we can't tell the ire type.
24954 		 */
24955 		ASSERT(CLASSD(ipha->ipha_dst));
24956 		ire_type = IRE_BROADCAST;
24957 	}
24958 
24959 	first_mp = mp;
24960 	if (first_mp->b_datap->db_type == M_CTL) {
24961 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24962 		if (!io->ipsec_out_secure) {
24963 			/*
24964 			 * This ipsec_out_t was allocated in ip_wput
24965 			 * for multicast packets to store the ill_index.
24966 			 * As this is being delivered locally, we don't
24967 			 * need this anymore.
24968 			 */
24969 			mp = first_mp->b_cont;
24970 			freeb(first_mp);
24971 			first_mp = mp;
24972 			mctl_present = B_FALSE;
24973 		} else {
24974 			/*
24975 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24976 			 * security properties for the looped-back packet.
24977 			 */
24978 			mctl_present = B_TRUE;
24979 			mp = first_mp->b_cont;
24980 			ASSERT(mp != NULL);
24981 			ipsec_out_to_in(first_mp);
24982 		}
24983 	} else {
24984 		mctl_present = B_FALSE;
24985 	}
24986 
24987 	DTRACE_PROBE4(ip4__loopback__in__start,
24988 	    ill_t *, ill, ill_t *, NULL,
24989 	    ipha_t *, ipha, mblk_t *, first_mp);
24990 
24991 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24992 	    ipst->ips_ipv4firewall_loopback_in,
24993 	    ill, NULL, ipha, first_mp, mp, ipst);
24994 
24995 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24996 
24997 	if (first_mp == NULL)
24998 		return;
24999 
25000 	ipst->ips_loopback_packets++;
25001 
25002 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25003 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25004 	if (!IS_SIMPLE_IPH(ipha)) {
25005 		ip_wput_local_options(ipha, ipst);
25006 	}
25007 
25008 	protocol = ipha->ipha_protocol;
25009 	switch (protocol) {
25010 	case IPPROTO_ICMP: {
25011 		ire_t		*ire_zone;
25012 		ilm_t		*ilm;
25013 		mblk_t		*mp1;
25014 		zoneid_t	last_zoneid;
25015 
25016 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25017 			ASSERT(ire_type == IRE_BROADCAST);
25018 			/*
25019 			 * In the multicast case, applications may have joined
25020 			 * the group from different zones, so we need to deliver
25021 			 * the packet to each of them. Loop through the
25022 			 * multicast memberships structures (ilm) on the receive
25023 			 * ill and send a copy of the packet up each matching
25024 			 * one. However, we don't do this for multicasts sent on
25025 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25026 			 * they must stay in the sender's zone.
25027 			 *
25028 			 * ilm_add_v6() ensures that ilms in the same zone are
25029 			 * contiguous in the ill_ilm list. We use this property
25030 			 * to avoid sending duplicates needed when two
25031 			 * applications in the same zone join the same group on
25032 			 * different logical interfaces: we ignore the ilm if
25033 			 * it's zoneid is the same as the last matching one.
25034 			 * In addition, the sending of the packet for
25035 			 * ire_zoneid is delayed until all of the other ilms
25036 			 * have been exhausted.
25037 			 */
25038 			last_zoneid = -1;
25039 			ILM_WALKER_HOLD(ill);
25040 			for (ilm = ill->ill_ilm; ilm != NULL;
25041 			    ilm = ilm->ilm_next) {
25042 				if ((ilm->ilm_flags & ILM_DELETED) ||
25043 				    ipha->ipha_dst != ilm->ilm_addr ||
25044 				    ilm->ilm_zoneid == last_zoneid ||
25045 				    ilm->ilm_zoneid == zoneid ||
25046 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25047 					continue;
25048 				mp1 = ip_copymsg(first_mp);
25049 				if (mp1 == NULL)
25050 					continue;
25051 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25052 				    mctl_present, B_FALSE, ill,
25053 				    ilm->ilm_zoneid);
25054 				last_zoneid = ilm->ilm_zoneid;
25055 			}
25056 			ILM_WALKER_RELE(ill);
25057 			/*
25058 			 * Loopback case: the sending endpoint has
25059 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25060 			 * dispatch the multicast packet to the sending zone.
25061 			 */
25062 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25063 				freemsg(first_mp);
25064 				return;
25065 			}
25066 		} else if (ire_type == IRE_BROADCAST) {
25067 			/*
25068 			 * In the broadcast case, there may be many zones
25069 			 * which need a copy of the packet delivered to them.
25070 			 * There is one IRE_BROADCAST per broadcast address
25071 			 * and per zone; we walk those using a helper function.
25072 			 * In addition, the sending of the packet for zoneid is
25073 			 * delayed until all of the other ires have been
25074 			 * processed.
25075 			 */
25076 			IRB_REFHOLD(ire->ire_bucket);
25077 			ire_zone = NULL;
25078 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25079 			    ire)) != NULL) {
25080 				mp1 = ip_copymsg(first_mp);
25081 				if (mp1 == NULL)
25082 					continue;
25083 
25084 				UPDATE_IB_PKT_COUNT(ire_zone);
25085 				ire_zone->ire_last_used_time = lbolt;
25086 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25087 				    mctl_present, B_FALSE, ill,
25088 				    ire_zone->ire_zoneid);
25089 			}
25090 			IRB_REFRELE(ire->ire_bucket);
25091 		}
25092 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25093 		    0, mctl_present, B_FALSE, ill, zoneid);
25094 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25095 		    "ip_wput_local_end: q %p (%S)",
25096 		    q, "icmp");
25097 		return;
25098 	}
25099 	case IPPROTO_IGMP:
25100 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25101 			/* Bad packet - discarded by igmp_input */
25102 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25103 			    "ip_wput_local_end: q %p (%S)",
25104 			    q, "igmp_input--bad packet");
25105 			if (mctl_present)
25106 				freeb(first_mp);
25107 			return;
25108 		}
25109 		/*
25110 		 * igmp_input() may have returned the pulled up message.
25111 		 * So first_mp and ipha need to be reinitialized.
25112 		 */
25113 		ipha = (ipha_t *)mp->b_rptr;
25114 		if (mctl_present)
25115 			first_mp->b_cont = mp;
25116 		else
25117 			first_mp = mp;
25118 		/* deliver to local raw users */
25119 		break;
25120 	case IPPROTO_ENCAP:
25121 		/*
25122 		 * This case is covered by either ip_fanout_proto, or by
25123 		 * the above security processing for self-tunneled packets.
25124 		 */
25125 		break;
25126 	case IPPROTO_UDP: {
25127 		uint16_t	*up;
25128 		uint32_t	ports;
25129 
25130 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25131 		    UDP_PORTS_OFFSET);
25132 		/* Force a 'valid' checksum. */
25133 		up[3] = 0;
25134 
25135 		ports = *(uint32_t *)up;
25136 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25137 		    (ire_type == IRE_BROADCAST),
25138 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25139 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25140 		    ill, zoneid);
25141 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25142 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25143 		return;
25144 	}
25145 	case IPPROTO_TCP: {
25146 
25147 		/*
25148 		 * For TCP, discard broadcast packets.
25149 		 */
25150 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25151 			freemsg(first_mp);
25152 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25153 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25154 			return;
25155 		}
25156 
25157 		if (mp->b_datap->db_type == M_DATA) {
25158 			/*
25159 			 * M_DATA mblk, so init mblk (chain) for no struio().
25160 			 */
25161 			mblk_t	*mp1 = mp;
25162 
25163 			do {
25164 				mp1->b_datap->db_struioflag = 0;
25165 			} while ((mp1 = mp1->b_cont) != NULL);
25166 		}
25167 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25168 		    <= mp->b_wptr);
25169 		ip_fanout_tcp(q, first_mp, ill, ipha,
25170 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25171 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25172 		    mctl_present, B_FALSE, zoneid);
25173 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25174 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25175 		return;
25176 	}
25177 	case IPPROTO_SCTP:
25178 	{
25179 		uint32_t	ports;
25180 
25181 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25182 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25183 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25184 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25185 		return;
25186 	}
25187 
25188 	default:
25189 		break;
25190 	}
25191 	/*
25192 	 * Find a client for some other protocol.  We give
25193 	 * copies to multiple clients, if more than one is
25194 	 * bound.
25195 	 */
25196 	ip_fanout_proto(q, first_mp, ill, ipha,
25197 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25198 	    mctl_present, B_FALSE, ill, zoneid);
25199 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25200 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25201 #undef	rptr
25202 }
25203 
25204 /*
25205  * Update any source route, record route, or timestamp options.
25206  * Check that we are at end of strict source route.
25207  * The options have been sanity checked by ip_wput_options().
25208  */
25209 static void
25210 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25211 {
25212 	ipoptp_t	opts;
25213 	uchar_t		*opt;
25214 	uint8_t		optval;
25215 	uint8_t		optlen;
25216 	ipaddr_t	dst;
25217 	uint32_t	ts;
25218 	ire_t		*ire;
25219 	timestruc_t	now;
25220 
25221 	ip2dbg(("ip_wput_local_options\n"));
25222 	for (optval = ipoptp_first(&opts, ipha);
25223 	    optval != IPOPT_EOL;
25224 	    optval = ipoptp_next(&opts)) {
25225 		opt = opts.ipoptp_cur;
25226 		optlen = opts.ipoptp_len;
25227 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25228 		switch (optval) {
25229 			uint32_t off;
25230 		case IPOPT_SSRR:
25231 		case IPOPT_LSRR:
25232 			off = opt[IPOPT_OFFSET];
25233 			off--;
25234 			if (optlen < IP_ADDR_LEN ||
25235 			    off > optlen - IP_ADDR_LEN) {
25236 				/* End of source route */
25237 				break;
25238 			}
25239 			/*
25240 			 * This will only happen if two consecutive entries
25241 			 * in the source route contains our address or if
25242 			 * it is a packet with a loose source route which
25243 			 * reaches us before consuming the whole source route
25244 			 */
25245 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25246 			if (optval == IPOPT_SSRR) {
25247 				return;
25248 			}
25249 			/*
25250 			 * Hack: instead of dropping the packet truncate the
25251 			 * source route to what has been used by filling the
25252 			 * rest with IPOPT_NOP.
25253 			 */
25254 			opt[IPOPT_OLEN] = (uint8_t)off;
25255 			while (off < optlen) {
25256 				opt[off++] = IPOPT_NOP;
25257 			}
25258 			break;
25259 		case IPOPT_RR:
25260 			off = opt[IPOPT_OFFSET];
25261 			off--;
25262 			if (optlen < IP_ADDR_LEN ||
25263 			    off > optlen - IP_ADDR_LEN) {
25264 				/* No more room - ignore */
25265 				ip1dbg((
25266 				    "ip_wput_forward_options: end of RR\n"));
25267 				break;
25268 			}
25269 			dst = htonl(INADDR_LOOPBACK);
25270 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25271 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25272 			break;
25273 		case IPOPT_TS:
25274 			/* Insert timestamp if there is romm */
25275 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25276 			case IPOPT_TS_TSONLY:
25277 				off = IPOPT_TS_TIMELEN;
25278 				break;
25279 			case IPOPT_TS_PRESPEC:
25280 			case IPOPT_TS_PRESPEC_RFC791:
25281 				/* Verify that the address matched */
25282 				off = opt[IPOPT_OFFSET] - 1;
25283 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25284 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25285 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25286 				    ipst);
25287 				if (ire == NULL) {
25288 					/* Not for us */
25289 					break;
25290 				}
25291 				ire_refrele(ire);
25292 				/* FALLTHRU */
25293 			case IPOPT_TS_TSANDADDR:
25294 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25295 				break;
25296 			default:
25297 				/*
25298 				 * ip_*put_options should have already
25299 				 * dropped this packet.
25300 				 */
25301 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25302 				    "unknown IT - bug in ip_wput_options?\n");
25303 				return;	/* Keep "lint" happy */
25304 			}
25305 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25306 				/* Increase overflow counter */
25307 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25308 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25309 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25310 				    (off << 4);
25311 				break;
25312 			}
25313 			off = opt[IPOPT_OFFSET] - 1;
25314 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25315 			case IPOPT_TS_PRESPEC:
25316 			case IPOPT_TS_PRESPEC_RFC791:
25317 			case IPOPT_TS_TSANDADDR:
25318 				dst = htonl(INADDR_LOOPBACK);
25319 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25320 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25321 				/* FALLTHRU */
25322 			case IPOPT_TS_TSONLY:
25323 				off = opt[IPOPT_OFFSET] - 1;
25324 				/* Compute # of milliseconds since midnight */
25325 				gethrestime(&now);
25326 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25327 				    now.tv_nsec / (NANOSEC / MILLISEC);
25328 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25329 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25330 				break;
25331 			}
25332 			break;
25333 		}
25334 	}
25335 }
25336 
25337 /*
25338  * Send out a multicast packet on interface ipif.
25339  * The sender does not have an conn.
25340  * Caller verifies that this isn't a PHYI_LOOPBACK.
25341  */
25342 void
25343 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25344 {
25345 	ipha_t	*ipha;
25346 	ire_t	*ire;
25347 	ipaddr_t	dst;
25348 	mblk_t		*first_mp;
25349 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25350 
25351 	/* igmp_sendpkt always allocates a ipsec_out_t */
25352 	ASSERT(mp->b_datap->db_type == M_CTL);
25353 	ASSERT(!ipif->ipif_isv6);
25354 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25355 
25356 	first_mp = mp;
25357 	mp = first_mp->b_cont;
25358 	ASSERT(mp->b_datap->db_type == M_DATA);
25359 	ipha = (ipha_t *)mp->b_rptr;
25360 
25361 	/*
25362 	 * Find an IRE which matches the destination and the outgoing
25363 	 * queue (i.e. the outgoing interface.)
25364 	 */
25365 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25366 		dst = ipif->ipif_pp_dst_addr;
25367 	else
25368 		dst = ipha->ipha_dst;
25369 	/*
25370 	 * The source address has already been initialized by the
25371 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25372 	 * be sufficient rather than MATCH_IRE_IPIF.
25373 	 *
25374 	 * This function is used for sending IGMP packets. We need
25375 	 * to make sure that we send the packet out of the interface
25376 	 * (ipif->ipif_ill) where we joined the group. This is to
25377 	 * prevent from switches doing IGMP snooping to send us multicast
25378 	 * packets for a given group on the interface we have joined.
25379 	 * If we can't find an ire, igmp_sendpkt has already initialized
25380 	 * ipsec_out_attach_if so that this will not be load spread in
25381 	 * ip_newroute_ipif.
25382 	 */
25383 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25384 	    MATCH_IRE_ILL, ipst);
25385 	if (!ire) {
25386 		/*
25387 		 * Mark this packet to make it be delivered to
25388 		 * ip_wput_ire after the new ire has been
25389 		 * created.
25390 		 */
25391 		mp->b_prev = NULL;
25392 		mp->b_next = NULL;
25393 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25394 		    zoneid, &zero_info);
25395 		return;
25396 	}
25397 
25398 	/*
25399 	 * Honor the RTF_SETSRC flag; this is the only case
25400 	 * where we force this addr whatever the current src addr is,
25401 	 * because this address is set by igmp_sendpkt(), and
25402 	 * cannot be specified by any user.
25403 	 */
25404 	if (ire->ire_flags & RTF_SETSRC) {
25405 		ipha->ipha_src = ire->ire_src_addr;
25406 	}
25407 
25408 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25409 }
25410 
25411 /*
25412  * NOTE : This function does not ire_refrele the ire argument passed in.
25413  *
25414  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25415  * failure. The nce_fp_mp can vanish any time in the case of
25416  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25417  * the ire_lock to access the nce_fp_mp in this case.
25418  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25419  * prepending a fastpath message IPQoS processing must precede it, we also set
25420  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25421  * (IPQoS might have set the b_band for CoS marking).
25422  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25423  * must follow it so that IPQoS can mark the dl_priority field for CoS
25424  * marking, if needed.
25425  */
25426 static mblk_t *
25427 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25428 {
25429 	uint_t	hlen;
25430 	ipha_t *ipha;
25431 	mblk_t *mp1;
25432 	boolean_t qos_done = B_FALSE;
25433 	uchar_t	*ll_hdr;
25434 	ip_stack_t	*ipst = ire->ire_ipst;
25435 
25436 #define	rptr	((uchar_t *)ipha)
25437 
25438 	ipha = (ipha_t *)mp->b_rptr;
25439 	hlen = 0;
25440 	LOCK_IRE_FP_MP(ire);
25441 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25442 		ASSERT(DB_TYPE(mp1) == M_DATA);
25443 		/* Initiate IPPF processing */
25444 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25445 			UNLOCK_IRE_FP_MP(ire);
25446 			ip_process(proc, &mp, ill_index);
25447 			if (mp == NULL)
25448 				return (NULL);
25449 
25450 			ipha = (ipha_t *)mp->b_rptr;
25451 			LOCK_IRE_FP_MP(ire);
25452 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25453 				qos_done = B_TRUE;
25454 				goto no_fp_mp;
25455 			}
25456 			ASSERT(DB_TYPE(mp1) == M_DATA);
25457 		}
25458 		hlen = MBLKL(mp1);
25459 		/*
25460 		 * Check if we have enough room to prepend fastpath
25461 		 * header
25462 		 */
25463 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25464 			ll_hdr = rptr - hlen;
25465 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25466 			/*
25467 			 * Set the b_rptr to the start of the link layer
25468 			 * header
25469 			 */
25470 			mp->b_rptr = ll_hdr;
25471 			mp1 = mp;
25472 		} else {
25473 			mp1 = copyb(mp1);
25474 			if (mp1 == NULL)
25475 				goto unlock_err;
25476 			mp1->b_band = mp->b_band;
25477 			mp1->b_cont = mp;
25478 			/*
25479 			 * certain system generated traffic may not
25480 			 * have cred/label in ip header block. This
25481 			 * is true even for a labeled system. But for
25482 			 * labeled traffic, inherit the label in the
25483 			 * new header.
25484 			 */
25485 			if (DB_CRED(mp) != NULL)
25486 				mblk_setcred(mp1, DB_CRED(mp));
25487 			/*
25488 			 * XXX disable ICK_VALID and compute checksum
25489 			 * here; can happen if nce_fp_mp changes and
25490 			 * it can't be copied now due to insufficient
25491 			 * space. (unlikely, fp mp can change, but it
25492 			 * does not increase in length)
25493 			 */
25494 		}
25495 		UNLOCK_IRE_FP_MP(ire);
25496 	} else {
25497 no_fp_mp:
25498 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25499 		if (mp1 == NULL) {
25500 unlock_err:
25501 			UNLOCK_IRE_FP_MP(ire);
25502 			freemsg(mp);
25503 			return (NULL);
25504 		}
25505 		UNLOCK_IRE_FP_MP(ire);
25506 		mp1->b_cont = mp;
25507 		/*
25508 		 * certain system generated traffic may not
25509 		 * have cred/label in ip header block. This
25510 		 * is true even for a labeled system. But for
25511 		 * labeled traffic, inherit the label in the
25512 		 * new header.
25513 		 */
25514 		if (DB_CRED(mp) != NULL)
25515 			mblk_setcred(mp1, DB_CRED(mp));
25516 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25517 			ip_process(proc, &mp1, ill_index);
25518 			if (mp1 == NULL)
25519 				return (NULL);
25520 		}
25521 	}
25522 	return (mp1);
25523 #undef rptr
25524 }
25525 
25526 /*
25527  * Finish the outbound IPsec processing for an IPv6 packet. This function
25528  * is called from ipsec_out_process() if the IPsec packet was processed
25529  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25530  * asynchronously.
25531  */
25532 void
25533 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25534     ire_t *ire_arg)
25535 {
25536 	in6_addr_t *v6dstp;
25537 	ire_t *ire;
25538 	mblk_t *mp;
25539 	ip6_t *ip6h1;
25540 	uint_t	ill_index;
25541 	ipsec_out_t *io;
25542 	boolean_t attach_if, hwaccel;
25543 	uint32_t flags = IP6_NO_IPPOLICY;
25544 	int match_flags;
25545 	zoneid_t zoneid;
25546 	boolean_t ill_need_rele = B_FALSE;
25547 	boolean_t ire_need_rele = B_FALSE;
25548 	ip_stack_t	*ipst;
25549 
25550 	mp = ipsec_mp->b_cont;
25551 	ip6h1 = (ip6_t *)mp->b_rptr;
25552 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25553 	ASSERT(io->ipsec_out_ns != NULL);
25554 	ipst = io->ipsec_out_ns->netstack_ip;
25555 	ill_index = io->ipsec_out_ill_index;
25556 	if (io->ipsec_out_reachable) {
25557 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25558 	}
25559 	attach_if = io->ipsec_out_attach_if;
25560 	hwaccel = io->ipsec_out_accelerated;
25561 	zoneid = io->ipsec_out_zoneid;
25562 	ASSERT(zoneid != ALL_ZONES);
25563 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25564 	/* Multicast addresses should have non-zero ill_index. */
25565 	v6dstp = &ip6h->ip6_dst;
25566 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25567 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25568 	ASSERT(!attach_if || ill_index != 0);
25569 	if (ill_index != 0) {
25570 		if (ill == NULL) {
25571 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25572 			    B_TRUE, ipst);
25573 
25574 			/* Failure case frees things for us. */
25575 			if (ill == NULL)
25576 				return;
25577 
25578 			ill_need_rele = B_TRUE;
25579 		}
25580 		/*
25581 		 * If this packet needs to go out on a particular interface
25582 		 * honor it.
25583 		 */
25584 		if (attach_if) {
25585 			match_flags = MATCH_IRE_ILL;
25586 
25587 			/*
25588 			 * Check if we need an ire that will not be
25589 			 * looked up by anybody else i.e. HIDDEN.
25590 			 */
25591 			if (ill_is_probeonly(ill)) {
25592 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25593 			}
25594 		}
25595 	}
25596 	ASSERT(mp != NULL);
25597 
25598 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25599 		boolean_t unspec_src;
25600 		ipif_t	*ipif;
25601 
25602 		/*
25603 		 * Use the ill_index to get the right ill.
25604 		 */
25605 		unspec_src = io->ipsec_out_unspec_src;
25606 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25607 		if (ipif == NULL) {
25608 			if (ill_need_rele)
25609 				ill_refrele(ill);
25610 			freemsg(ipsec_mp);
25611 			return;
25612 		}
25613 
25614 		if (ire_arg != NULL) {
25615 			ire = ire_arg;
25616 		} else {
25617 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25618 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25619 			ire_need_rele = B_TRUE;
25620 		}
25621 		if (ire != NULL) {
25622 			ipif_refrele(ipif);
25623 			/*
25624 			 * XXX Do the multicast forwarding now, as the IPsec
25625 			 * processing has been done.
25626 			 */
25627 			goto send;
25628 		}
25629 
25630 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25631 		mp->b_prev = NULL;
25632 		mp->b_next = NULL;
25633 
25634 		/*
25635 		 * If the IPsec packet was processed asynchronously,
25636 		 * drop it now.
25637 		 */
25638 		if (q == NULL) {
25639 			if (ill_need_rele)
25640 				ill_refrele(ill);
25641 			freemsg(ipsec_mp);
25642 			return;
25643 		}
25644 
25645 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25646 		    unspec_src, zoneid);
25647 		ipif_refrele(ipif);
25648 	} else {
25649 		if (attach_if) {
25650 			ipif_t	*ipif;
25651 
25652 			ipif = ipif_get_next_ipif(NULL, ill);
25653 			if (ipif == NULL) {
25654 				if (ill_need_rele)
25655 					ill_refrele(ill);
25656 				freemsg(ipsec_mp);
25657 				return;
25658 			}
25659 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25660 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25661 			ire_need_rele = B_TRUE;
25662 			ipif_refrele(ipif);
25663 		} else {
25664 			if (ire_arg != NULL) {
25665 				ire = ire_arg;
25666 			} else {
25667 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25668 				    ipst);
25669 				ire_need_rele = B_TRUE;
25670 			}
25671 		}
25672 		if (ire != NULL)
25673 			goto send;
25674 		/*
25675 		 * ire disappeared underneath.
25676 		 *
25677 		 * What we need to do here is the ip_newroute
25678 		 * logic to get the ire without doing the IPsec
25679 		 * processing. Follow the same old path. But this
25680 		 * time, ip_wput or ire_add_then_send will call us
25681 		 * directly as all the IPsec operations are done.
25682 		 */
25683 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25684 		mp->b_prev = NULL;
25685 		mp->b_next = NULL;
25686 
25687 		/*
25688 		 * If the IPsec packet was processed asynchronously,
25689 		 * drop it now.
25690 		 */
25691 		if (q == NULL) {
25692 			if (ill_need_rele)
25693 				ill_refrele(ill);
25694 			freemsg(ipsec_mp);
25695 			return;
25696 		}
25697 
25698 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25699 		    zoneid, ipst);
25700 	}
25701 	if (ill != NULL && ill_need_rele)
25702 		ill_refrele(ill);
25703 	return;
25704 send:
25705 	if (ill != NULL && ill_need_rele)
25706 		ill_refrele(ill);
25707 
25708 	/* Local delivery */
25709 	if (ire->ire_stq == NULL) {
25710 		ill_t	*out_ill;
25711 		ASSERT(q != NULL);
25712 
25713 		/* PFHooks: LOOPBACK_OUT */
25714 		out_ill = ire_to_ill(ire);
25715 
25716 		DTRACE_PROBE4(ip6__loopback__out__start,
25717 		    ill_t *, NULL, ill_t *, out_ill,
25718 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25719 
25720 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25721 		    ipst->ips_ipv6firewall_loopback_out,
25722 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25723 
25724 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25725 
25726 		if (ipsec_mp != NULL)
25727 			ip_wput_local_v6(RD(q), out_ill,
25728 			    ip6h, ipsec_mp, ire, 0);
25729 		if (ire_need_rele)
25730 			ire_refrele(ire);
25731 		return;
25732 	}
25733 	/*
25734 	 * Everything is done. Send it out on the wire.
25735 	 * We force the insertion of a fragment header using the
25736 	 * IPH_FRAG_HDR flag in two cases:
25737 	 * - after reception of an ICMPv6 "packet too big" message
25738 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25739 	 * - for multirouted IPv6 packets, so that the receiver can
25740 	 *   discard duplicates according to their fragment identifier
25741 	 */
25742 	/* XXX fix flow control problems. */
25743 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25744 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25745 		if (hwaccel) {
25746 			/*
25747 			 * hardware acceleration does not handle these
25748 			 * "slow path" cases.
25749 			 */
25750 			/* IPsec KSTATS: should bump bean counter here. */
25751 			if (ire_need_rele)
25752 				ire_refrele(ire);
25753 			freemsg(ipsec_mp);
25754 			return;
25755 		}
25756 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25757 		    (mp->b_cont ? msgdsize(mp) :
25758 		    mp->b_wptr - (uchar_t *)ip6h)) {
25759 			/* IPsec KSTATS: should bump bean counter here. */
25760 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25761 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25762 			    msgdsize(mp)));
25763 			if (ire_need_rele)
25764 				ire_refrele(ire);
25765 			freemsg(ipsec_mp);
25766 			return;
25767 		}
25768 		ASSERT(mp->b_prev == NULL);
25769 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25770 		    ntohs(ip6h->ip6_plen) +
25771 		    IPV6_HDR_LEN, ire->ire_max_frag));
25772 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25773 		    ire->ire_max_frag);
25774 	} else {
25775 		UPDATE_OB_PKT_COUNT(ire);
25776 		ire->ire_last_used_time = lbolt;
25777 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25778 	}
25779 	if (ire_need_rele)
25780 		ire_refrele(ire);
25781 	freeb(ipsec_mp);
25782 }
25783 
25784 void
25785 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25786 {
25787 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25788 	da_ipsec_t *hada;	/* data attributes */
25789 	ill_t *ill = (ill_t *)q->q_ptr;
25790 
25791 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25792 
25793 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25794 		/* IPsec KSTATS: Bump lose counter here! */
25795 		freemsg(mp);
25796 		return;
25797 	}
25798 
25799 	/*
25800 	 * It's an IPsec packet that must be
25801 	 * accelerated by the Provider, and the
25802 	 * outbound ill is IPsec acceleration capable.
25803 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25804 	 * to the ill.
25805 	 * IPsec KSTATS: should bump packet counter here.
25806 	 */
25807 
25808 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25809 	if (hada_mp == NULL) {
25810 		/* IPsec KSTATS: should bump packet counter here. */
25811 		freemsg(mp);
25812 		return;
25813 	}
25814 
25815 	hada_mp->b_datap->db_type = M_CTL;
25816 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25817 	hada_mp->b_cont = mp;
25818 
25819 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25820 	bzero(hada, sizeof (da_ipsec_t));
25821 	hada->da_type = IPHADA_M_CTL;
25822 
25823 	putnext(q, hada_mp);
25824 }
25825 
25826 /*
25827  * Finish the outbound IPsec processing. This function is called from
25828  * ipsec_out_process() if the IPsec packet was processed
25829  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25830  * asynchronously.
25831  */
25832 void
25833 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25834     ire_t *ire_arg)
25835 {
25836 	uint32_t v_hlen_tos_len;
25837 	ipaddr_t	dst;
25838 	ipif_t	*ipif = NULL;
25839 	ire_t *ire;
25840 	ire_t *ire1 = NULL;
25841 	mblk_t *next_mp = NULL;
25842 	uint32_t max_frag;
25843 	boolean_t multirt_send = B_FALSE;
25844 	mblk_t *mp;
25845 	ipha_t *ipha1;
25846 	uint_t	ill_index;
25847 	ipsec_out_t *io;
25848 	boolean_t attach_if;
25849 	int match_flags;
25850 	irb_t *irb = NULL;
25851 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25852 	zoneid_t zoneid;
25853 	ipxmit_state_t	pktxmit_state;
25854 	ip_stack_t	*ipst;
25855 
25856 #ifdef	_BIG_ENDIAN
25857 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25858 #else
25859 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25860 #endif
25861 
25862 	mp = ipsec_mp->b_cont;
25863 	ipha1 = (ipha_t *)mp->b_rptr;
25864 	ASSERT(mp != NULL);
25865 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25866 	dst = ipha->ipha_dst;
25867 
25868 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25869 	ill_index = io->ipsec_out_ill_index;
25870 	attach_if = io->ipsec_out_attach_if;
25871 	zoneid = io->ipsec_out_zoneid;
25872 	ASSERT(zoneid != ALL_ZONES);
25873 	ipst = io->ipsec_out_ns->netstack_ip;
25874 	ASSERT(io->ipsec_out_ns != NULL);
25875 
25876 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25877 	if (ill_index != 0) {
25878 		if (ill == NULL) {
25879 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25880 			    ill_index, B_FALSE, ipst);
25881 
25882 			/* Failure case frees things for us. */
25883 			if (ill == NULL)
25884 				return;
25885 
25886 			ill_need_rele = B_TRUE;
25887 		}
25888 		/*
25889 		 * If this packet needs to go out on a particular interface
25890 		 * honor it.
25891 		 */
25892 		if (attach_if) {
25893 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25894 
25895 			/*
25896 			 * Check if we need an ire that will not be
25897 			 * looked up by anybody else i.e. HIDDEN.
25898 			 */
25899 			if (ill_is_probeonly(ill)) {
25900 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25901 			}
25902 		}
25903 	}
25904 
25905 	if (CLASSD(dst)) {
25906 		boolean_t conn_dontroute;
25907 		/*
25908 		 * Use the ill_index to get the right ipif.
25909 		 */
25910 		conn_dontroute = io->ipsec_out_dontroute;
25911 		if (ill_index == 0)
25912 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25913 		else
25914 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25915 		if (ipif == NULL) {
25916 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25917 			    " multicast\n"));
25918 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25919 			freemsg(ipsec_mp);
25920 			goto done;
25921 		}
25922 		/*
25923 		 * ipha_src has already been intialized with the
25924 		 * value of the ipif in ip_wput. All we need now is
25925 		 * an ire to send this downstream.
25926 		 */
25927 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25928 		    MBLK_GETLABEL(mp), match_flags, ipst);
25929 		if (ire != NULL) {
25930 			ill_t *ill1;
25931 			/*
25932 			 * Do the multicast forwarding now, as the IPsec
25933 			 * processing has been done.
25934 			 */
25935 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25936 			    (ill1 = ire_to_ill(ire))) {
25937 				if (ip_mforward(ill1, ipha, mp)) {
25938 					freemsg(ipsec_mp);
25939 					ip1dbg(("ip_wput_ipsec_out: mforward "
25940 					    "failed\n"));
25941 					ire_refrele(ire);
25942 					goto done;
25943 				}
25944 			}
25945 			goto send;
25946 		}
25947 
25948 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25949 		mp->b_prev = NULL;
25950 		mp->b_next = NULL;
25951 
25952 		/*
25953 		 * If the IPsec packet was processed asynchronously,
25954 		 * drop it now.
25955 		 */
25956 		if (q == NULL) {
25957 			freemsg(ipsec_mp);
25958 			goto done;
25959 		}
25960 
25961 		/*
25962 		 * We may be using a wrong ipif to create the ire.
25963 		 * But it is okay as the source address is assigned
25964 		 * for the packet already. Next outbound packet would
25965 		 * create the IRE with the right IPIF in ip_wput.
25966 		 *
25967 		 * Also handle RTF_MULTIRT routes.
25968 		 */
25969 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25970 		    zoneid, &zero_info);
25971 	} else {
25972 		if (attach_if) {
25973 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25974 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25975 		} else {
25976 			if (ire_arg != NULL) {
25977 				ire = ire_arg;
25978 				ire_need_rele = B_FALSE;
25979 			} else {
25980 				ire = ire_cache_lookup(dst, zoneid,
25981 				    MBLK_GETLABEL(mp), ipst);
25982 			}
25983 		}
25984 		if (ire != NULL) {
25985 			goto send;
25986 		}
25987 
25988 		/*
25989 		 * ire disappeared underneath.
25990 		 *
25991 		 * What we need to do here is the ip_newroute
25992 		 * logic to get the ire without doing the IPsec
25993 		 * processing. Follow the same old path. But this
25994 		 * time, ip_wput or ire_add_then_put will call us
25995 		 * directly as all the IPsec operations are done.
25996 		 */
25997 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25998 		mp->b_prev = NULL;
25999 		mp->b_next = NULL;
26000 
26001 		/*
26002 		 * If the IPsec packet was processed asynchronously,
26003 		 * drop it now.
26004 		 */
26005 		if (q == NULL) {
26006 			freemsg(ipsec_mp);
26007 			goto done;
26008 		}
26009 
26010 		/*
26011 		 * Since we're going through ip_newroute() again, we
26012 		 * need to make sure we don't:
26013 		 *
26014 		 *	1.) Trigger the ASSERT() with the ipha_ident
26015 		 *	    overloading.
26016 		 *	2.) Redo transport-layer checksumming, since we've
26017 		 *	    already done all that to get this far.
26018 		 *
26019 		 * The easiest way not do either of the above is to set
26020 		 * the ipha_ident field to IP_HDR_INCLUDED.
26021 		 */
26022 		ipha->ipha_ident = IP_HDR_INCLUDED;
26023 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26024 		    zoneid, ipst);
26025 	}
26026 	goto done;
26027 send:
26028 	if (ire->ire_stq == NULL) {
26029 		ill_t	*out_ill;
26030 		/*
26031 		 * Loopbacks go through ip_wput_local except for one case.
26032 		 * We come here if we generate a icmp_frag_needed message
26033 		 * after IPsec processing is over. When this function calls
26034 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26035 		 * icmp_frag_needed. The message generated comes back here
26036 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26037 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26038 		 * source address as it is usually set in ip_wput_ire. As
26039 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26040 		 * and we end up here. We can't enter ip_wput_ire once the
26041 		 * IPsec processing is over and hence we need to do it here.
26042 		 */
26043 		ASSERT(q != NULL);
26044 		UPDATE_OB_PKT_COUNT(ire);
26045 		ire->ire_last_used_time = lbolt;
26046 		if (ipha->ipha_src == 0)
26047 			ipha->ipha_src = ire->ire_src_addr;
26048 
26049 		/* PFHooks: LOOPBACK_OUT */
26050 		out_ill = ire_to_ill(ire);
26051 
26052 		DTRACE_PROBE4(ip4__loopback__out__start,
26053 		    ill_t *, NULL, ill_t *, out_ill,
26054 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26055 
26056 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26057 		    ipst->ips_ipv4firewall_loopback_out,
26058 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
26059 
26060 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26061 
26062 		if (ipsec_mp != NULL)
26063 			ip_wput_local(RD(q), out_ill,
26064 			    ipha, ipsec_mp, ire, 0, zoneid);
26065 		if (ire_need_rele)
26066 			ire_refrele(ire);
26067 		goto done;
26068 	}
26069 
26070 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26071 		/*
26072 		 * We are through with IPsec processing.
26073 		 * Fragment this and send it on the wire.
26074 		 */
26075 		if (io->ipsec_out_accelerated) {
26076 			/*
26077 			 * The packet has been accelerated but must
26078 			 * be fragmented. This should not happen
26079 			 * since AH and ESP must not accelerate
26080 			 * packets that need fragmentation, however
26081 			 * the configuration could have changed
26082 			 * since the AH or ESP processing.
26083 			 * Drop packet.
26084 			 * IPsec KSTATS: bump bean counter here.
26085 			 */
26086 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26087 			    "fragmented accelerated packet!\n"));
26088 			freemsg(ipsec_mp);
26089 		} else {
26090 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26091 		}
26092 		if (ire_need_rele)
26093 			ire_refrele(ire);
26094 		goto done;
26095 	}
26096 
26097 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26098 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26099 	    (void *)ire->ire_ipif, (void *)ipif));
26100 
26101 	/*
26102 	 * Multiroute the secured packet, unless IPsec really
26103 	 * requires the packet to go out only through a particular
26104 	 * interface.
26105 	 */
26106 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26107 		ire_t *first_ire;
26108 		irb = ire->ire_bucket;
26109 		ASSERT(irb != NULL);
26110 		/*
26111 		 * This ire has been looked up as the one that
26112 		 * goes through the given ipif;
26113 		 * make sure we do not omit any other multiroute ire
26114 		 * that may be present in the bucket before this one.
26115 		 */
26116 		IRB_REFHOLD(irb);
26117 		for (first_ire = irb->irb_ire;
26118 		    first_ire != NULL;
26119 		    first_ire = first_ire->ire_next) {
26120 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26121 			    (first_ire->ire_addr == ire->ire_addr) &&
26122 			    !(first_ire->ire_marks &
26123 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26124 				break;
26125 			}
26126 		}
26127 
26128 		if ((first_ire != NULL) && (first_ire != ire)) {
26129 			/*
26130 			 * Don't change the ire if the packet must
26131 			 * be fragmented if sent via this new one.
26132 			 */
26133 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26134 				IRE_REFHOLD(first_ire);
26135 				if (ire_need_rele)
26136 					ire_refrele(ire);
26137 				else
26138 					ire_need_rele = B_TRUE;
26139 				ire = first_ire;
26140 			}
26141 		}
26142 		IRB_REFRELE(irb);
26143 
26144 		multirt_send = B_TRUE;
26145 		max_frag = ire->ire_max_frag;
26146 	} else {
26147 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26148 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26149 			    "flag, attach_if %d\n", attach_if));
26150 		}
26151 	}
26152 
26153 	/*
26154 	 * In most cases, the emission loop below is entered only once.
26155 	 * Only in the case where the ire holds the RTF_MULTIRT
26156 	 * flag, we loop to process all RTF_MULTIRT ires in the
26157 	 * bucket, and send the packet through all crossed
26158 	 * RTF_MULTIRT routes.
26159 	 */
26160 	do {
26161 		if (multirt_send) {
26162 			/*
26163 			 * ire1 holds here the next ire to process in the
26164 			 * bucket. If multirouting is expected,
26165 			 * any non-RTF_MULTIRT ire that has the
26166 			 * right destination address is ignored.
26167 			 */
26168 			ASSERT(irb != NULL);
26169 			IRB_REFHOLD(irb);
26170 			for (ire1 = ire->ire_next;
26171 			    ire1 != NULL;
26172 			    ire1 = ire1->ire_next) {
26173 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26174 					continue;
26175 				if (ire1->ire_addr != ire->ire_addr)
26176 					continue;
26177 				if (ire1->ire_marks &
26178 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26179 					continue;
26180 				/* No loopback here */
26181 				if (ire1->ire_stq == NULL)
26182 					continue;
26183 				/*
26184 				 * Ensure we do not exceed the MTU
26185 				 * of the next route.
26186 				 */
26187 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26188 					ip_multirt_bad_mtu(ire1, max_frag);
26189 					continue;
26190 				}
26191 
26192 				IRE_REFHOLD(ire1);
26193 				break;
26194 			}
26195 			IRB_REFRELE(irb);
26196 			if (ire1 != NULL) {
26197 				/*
26198 				 * We are in a multiple send case, need to
26199 				 * make a copy of the packet.
26200 				 */
26201 				next_mp = copymsg(ipsec_mp);
26202 				if (next_mp == NULL) {
26203 					ire_refrele(ire1);
26204 					ire1 = NULL;
26205 				}
26206 			}
26207 		}
26208 		/*
26209 		 * Everything is done. Send it out on the wire
26210 		 *
26211 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26212 		 * either send it on the wire or, in the case of
26213 		 * HW acceleration, call ipsec_hw_putnext.
26214 		 */
26215 		if (ire->ire_nce &&
26216 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26217 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26218 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26219 			/*
26220 			 * If ire's link-layer is unresolved (this
26221 			 * would only happen if the incomplete ire
26222 			 * was added to cachetable via forwarding path)
26223 			 * don't bother going to ip_xmit_v4. Just drop the
26224 			 * packet.
26225 			 * There is a slight risk here, in that, if we
26226 			 * have the forwarding path create an incomplete
26227 			 * IRE, then until the IRE is completed, any
26228 			 * transmitted IPsec packets will be dropped
26229 			 * instead of being queued waiting for resolution.
26230 			 *
26231 			 * But the likelihood of a forwarding packet and a wput
26232 			 * packet sending to the same dst at the same time
26233 			 * and there not yet be an ARP entry for it is small.
26234 			 * Furthermore, if this actually happens, it might
26235 			 * be likely that wput would generate multiple
26236 			 * packets (and forwarding would also have a train
26237 			 * of packets) for that destination. If this is
26238 			 * the case, some of them would have been dropped
26239 			 * anyway, since ARP only queues a few packets while
26240 			 * waiting for resolution
26241 			 *
26242 			 * NOTE: We should really call ip_xmit_v4,
26243 			 * and let it queue the packet and send the
26244 			 * ARP query and have ARP come back thus:
26245 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26246 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26247 			 * hw accel work. But it's too complex to get
26248 			 * the IPsec hw  acceleration approach to fit
26249 			 * well with ip_xmit_v4 doing ARP without
26250 			 * doing IPsec simplification. For now, we just
26251 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26252 			 * that we can continue with the send on the next
26253 			 * attempt.
26254 			 *
26255 			 * XXX THis should be revisited, when
26256 			 * the IPsec/IP interaction is cleaned up
26257 			 */
26258 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26259 			    " - dropping packet\n"));
26260 			freemsg(ipsec_mp);
26261 			/*
26262 			 * Call ip_xmit_v4() to trigger ARP query
26263 			 * in case the nce_state is ND_INITIAL
26264 			 */
26265 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26266 			goto drop_pkt;
26267 		}
26268 
26269 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26270 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26271 		    mblk_t *, ipsec_mp);
26272 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26273 		    ipst->ips_ipv4firewall_physical_out,
26274 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26275 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26276 		if (ipsec_mp == NULL)
26277 			goto drop_pkt;
26278 
26279 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26280 		pktxmit_state = ip_xmit_v4(mp, ire,
26281 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26282 
26283 		if ((pktxmit_state ==  SEND_FAILED) ||
26284 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26285 
26286 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26287 drop_pkt:
26288 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26289 			    ipIfStatsOutDiscards);
26290 			if (ire_need_rele)
26291 				ire_refrele(ire);
26292 			if (ire1 != NULL) {
26293 				ire_refrele(ire1);
26294 				freemsg(next_mp);
26295 			}
26296 			goto done;
26297 		}
26298 
26299 		freeb(ipsec_mp);
26300 		if (ire_need_rele)
26301 			ire_refrele(ire);
26302 
26303 		if (ire1 != NULL) {
26304 			ire = ire1;
26305 			ire_need_rele = B_TRUE;
26306 			ASSERT(next_mp);
26307 			ipsec_mp = next_mp;
26308 			mp = ipsec_mp->b_cont;
26309 			ire1 = NULL;
26310 			next_mp = NULL;
26311 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26312 		} else {
26313 			multirt_send = B_FALSE;
26314 		}
26315 	} while (multirt_send);
26316 done:
26317 	if (ill != NULL && ill_need_rele)
26318 		ill_refrele(ill);
26319 	if (ipif != NULL)
26320 		ipif_refrele(ipif);
26321 }
26322 
26323 /*
26324  * Get the ill corresponding to the specified ire, and compare its
26325  * capabilities with the protocol and algorithms specified by the
26326  * the SA obtained from ipsec_out. If they match, annotate the
26327  * ipsec_out structure to indicate that the packet needs acceleration.
26328  *
26329  *
26330  * A packet is eligible for outbound hardware acceleration if the
26331  * following conditions are satisfied:
26332  *
26333  * 1. the packet will not be fragmented
26334  * 2. the provider supports the algorithm
26335  * 3. there is no pending control message being exchanged
26336  * 4. snoop is not attached
26337  * 5. the destination address is not a broadcast or multicast address.
26338  *
26339  * Rationale:
26340  *	- Hardware drivers do not support fragmentation with
26341  *	  the current interface.
26342  *	- snoop, multicast, and broadcast may result in exposure of
26343  *	  a cleartext datagram.
26344  * We check all five of these conditions here.
26345  *
26346  * XXX would like to nuke "ire_t *" parameter here; problem is that
26347  * IRE is only way to figure out if a v4 address is a broadcast and
26348  * thus ineligible for acceleration...
26349  */
26350 static void
26351 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26352 {
26353 	ipsec_out_t *io;
26354 	mblk_t *data_mp;
26355 	uint_t plen, overhead;
26356 	ip_stack_t	*ipst;
26357 
26358 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26359 		return;
26360 
26361 	if (ill == NULL)
26362 		return;
26363 	ipst = ill->ill_ipst;
26364 	/*
26365 	 * Destination address is a broadcast or multicast.  Punt.
26366 	 */
26367 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26368 	    IRE_LOCAL)))
26369 		return;
26370 
26371 	data_mp = ipsec_mp->b_cont;
26372 
26373 	if (ill->ill_isv6) {
26374 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26375 
26376 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26377 			return;
26378 
26379 		plen = ip6h->ip6_plen;
26380 	} else {
26381 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26382 
26383 		if (CLASSD(ipha->ipha_dst))
26384 			return;
26385 
26386 		plen = ipha->ipha_length;
26387 	}
26388 	/*
26389 	 * Is there a pending DLPI control message being exchanged
26390 	 * between IP/IPsec and the DLS Provider? If there is, it
26391 	 * could be a SADB update, and the state of the DLS Provider
26392 	 * SADB might not be in sync with the SADB maintained by
26393 	 * IPsec. To avoid dropping packets or using the wrong keying
26394 	 * material, we do not accelerate this packet.
26395 	 */
26396 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26397 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26398 		    "ill_dlpi_pending! don't accelerate packet\n"));
26399 		return;
26400 	}
26401 
26402 	/*
26403 	 * Is the Provider in promiscous mode? If it does, we don't
26404 	 * accelerate the packet since it will bounce back up to the
26405 	 * listeners in the clear.
26406 	 */
26407 	if (ill->ill_promisc_on_phys) {
26408 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26409 		    "ill in promiscous mode, don't accelerate packet\n"));
26410 		return;
26411 	}
26412 
26413 	/*
26414 	 * Will the packet require fragmentation?
26415 	 */
26416 
26417 	/*
26418 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26419 	 * as is used elsewhere.
26420 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26421 	 *	+ 2-byte trailer
26422 	 */
26423 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26424 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26425 
26426 	if ((plen + overhead) > ill->ill_max_mtu)
26427 		return;
26428 
26429 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26430 
26431 	/*
26432 	 * Can the ill accelerate this IPsec protocol and algorithm
26433 	 * specified by the SA?
26434 	 */
26435 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26436 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26437 		return;
26438 	}
26439 
26440 	/*
26441 	 * Tell AH or ESP that the outbound ill is capable of
26442 	 * accelerating this packet.
26443 	 */
26444 	io->ipsec_out_is_capab_ill = B_TRUE;
26445 }
26446 
26447 /*
26448  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26449  *
26450  * If this function returns B_TRUE, the requested SA's have been filled
26451  * into the ipsec_out_*_sa pointers.
26452  *
26453  * If the function returns B_FALSE, the packet has been "consumed", most
26454  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26455  *
26456  * The SA references created by the protocol-specific "select"
26457  * function will be released when the ipsec_mp is freed, thanks to the
26458  * ipsec_out_free destructor -- see spd.c.
26459  */
26460 static boolean_t
26461 ipsec_out_select_sa(mblk_t *ipsec_mp)
26462 {
26463 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26464 	ipsec_out_t *io;
26465 	ipsec_policy_t *pp;
26466 	ipsec_action_t *ap;
26467 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26468 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26469 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26470 
26471 	if (!io->ipsec_out_secure) {
26472 		/*
26473 		 * We came here by mistake.
26474 		 * Don't bother with ipsec processing
26475 		 * We should "discourage" this path in the future.
26476 		 */
26477 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26478 		return (B_FALSE);
26479 	}
26480 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26481 	ASSERT((io->ipsec_out_policy != NULL) ||
26482 	    (io->ipsec_out_act != NULL));
26483 
26484 	ASSERT(io->ipsec_out_failed == B_FALSE);
26485 
26486 	/*
26487 	 * IPsec processing has started.
26488 	 */
26489 	io->ipsec_out_proc_begin = B_TRUE;
26490 	ap = io->ipsec_out_act;
26491 	if (ap == NULL) {
26492 		pp = io->ipsec_out_policy;
26493 		ASSERT(pp != NULL);
26494 		ap = pp->ipsp_act;
26495 		ASSERT(ap != NULL);
26496 	}
26497 
26498 	/*
26499 	 * We have an action.  now, let's select SA's.
26500 	 * (In the future, we can cache this in the conn_t..)
26501 	 */
26502 	if (ap->ipa_want_esp) {
26503 		if (io->ipsec_out_esp_sa == NULL) {
26504 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26505 			    IPPROTO_ESP);
26506 		}
26507 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26508 	}
26509 
26510 	if (ap->ipa_want_ah) {
26511 		if (io->ipsec_out_ah_sa == NULL) {
26512 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26513 			    IPPROTO_AH);
26514 		}
26515 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26516 		/*
26517 		 * The ESP and AH processing order needs to be preserved
26518 		 * when both protocols are required (ESP should be applied
26519 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26520 		 * when both ESP and AH are required, and an AH ACQUIRE
26521 		 * is needed.
26522 		 */
26523 		if (ap->ipa_want_esp && need_ah_acquire)
26524 			need_esp_acquire = B_TRUE;
26525 	}
26526 
26527 	/*
26528 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26529 	 * Release SAs that got referenced, but will not be used until we
26530 	 * acquire _all_ of the SAs we need.
26531 	 */
26532 	if (need_ah_acquire || need_esp_acquire) {
26533 		if (io->ipsec_out_ah_sa != NULL) {
26534 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26535 			io->ipsec_out_ah_sa = NULL;
26536 		}
26537 		if (io->ipsec_out_esp_sa != NULL) {
26538 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26539 			io->ipsec_out_esp_sa = NULL;
26540 		}
26541 
26542 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26543 		return (B_FALSE);
26544 	}
26545 
26546 	return (B_TRUE);
26547 }
26548 
26549 /*
26550  * Process an IPSEC_OUT message and see what you can
26551  * do with it.
26552  * IPQoS Notes:
26553  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26554  * IPsec.
26555  * XXX would like to nuke ire_t.
26556  * XXX ill_index better be "real"
26557  */
26558 void
26559 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26560 {
26561 	ipsec_out_t *io;
26562 	ipsec_policy_t *pp;
26563 	ipsec_action_t *ap;
26564 	ipha_t *ipha;
26565 	ip6_t *ip6h;
26566 	mblk_t *mp;
26567 	ill_t *ill;
26568 	zoneid_t zoneid;
26569 	ipsec_status_t ipsec_rc;
26570 	boolean_t ill_need_rele = B_FALSE;
26571 	ip_stack_t	*ipst;
26572 	ipsec_stack_t	*ipss;
26573 
26574 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26575 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26576 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26577 	ipst = io->ipsec_out_ns->netstack_ip;
26578 	mp = ipsec_mp->b_cont;
26579 
26580 	/*
26581 	 * Initiate IPPF processing. We do it here to account for packets
26582 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26583 	 * We can check for ipsec_out_proc_begin even for such packets, as
26584 	 * they will always be false (asserted below).
26585 	 */
26586 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26587 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26588 		    io->ipsec_out_ill_index : ill_index);
26589 		if (mp == NULL) {
26590 			ip2dbg(("ipsec_out_process: packet dropped "\
26591 			    "during IPPF processing\n"));
26592 			freeb(ipsec_mp);
26593 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26594 			return;
26595 		}
26596 	}
26597 
26598 	if (!io->ipsec_out_secure) {
26599 		/*
26600 		 * We came here by mistake.
26601 		 * Don't bother with ipsec processing
26602 		 * Should "discourage" this path in the future.
26603 		 */
26604 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26605 		goto done;
26606 	}
26607 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26608 	ASSERT((io->ipsec_out_policy != NULL) ||
26609 	    (io->ipsec_out_act != NULL));
26610 	ASSERT(io->ipsec_out_failed == B_FALSE);
26611 
26612 	ipss = ipst->ips_netstack->netstack_ipsec;
26613 	if (!ipsec_loaded(ipss)) {
26614 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26615 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26616 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26617 		} else {
26618 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26619 		}
26620 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26621 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26622 		    &ipss->ipsec_dropper);
26623 		return;
26624 	}
26625 
26626 	/*
26627 	 * IPsec processing has started.
26628 	 */
26629 	io->ipsec_out_proc_begin = B_TRUE;
26630 	ap = io->ipsec_out_act;
26631 	if (ap == NULL) {
26632 		pp = io->ipsec_out_policy;
26633 		ASSERT(pp != NULL);
26634 		ap = pp->ipsp_act;
26635 		ASSERT(ap != NULL);
26636 	}
26637 
26638 	/*
26639 	 * Save the outbound ill index. When the packet comes back
26640 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26641 	 * before sending it the accelerated packet.
26642 	 */
26643 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26644 		int ifindex;
26645 		ill = ire_to_ill(ire);
26646 		ifindex = ill->ill_phyint->phyint_ifindex;
26647 		io->ipsec_out_capab_ill_index = ifindex;
26648 	}
26649 
26650 	/*
26651 	 * The order of processing is first insert a IP header if needed.
26652 	 * Then insert the ESP header and then the AH header.
26653 	 */
26654 	if ((io->ipsec_out_se_done == B_FALSE) &&
26655 	    (ap->ipa_want_se)) {
26656 		/*
26657 		 * First get the outer IP header before sending
26658 		 * it to ESP.
26659 		 */
26660 		ipha_t *oipha, *iipha;
26661 		mblk_t *outer_mp, *inner_mp;
26662 
26663 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26664 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26665 			    "ipsec_out_process: "
26666 			    "Self-Encapsulation failed: Out of memory\n");
26667 			freemsg(ipsec_mp);
26668 			if (ill != NULL) {
26669 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26670 			} else {
26671 				BUMP_MIB(&ipst->ips_ip_mib,
26672 				    ipIfStatsOutDiscards);
26673 			}
26674 			return;
26675 		}
26676 		inner_mp = ipsec_mp->b_cont;
26677 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26678 		oipha = (ipha_t *)outer_mp->b_rptr;
26679 		iipha = (ipha_t *)inner_mp->b_rptr;
26680 		*oipha = *iipha;
26681 		outer_mp->b_wptr += sizeof (ipha_t);
26682 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26683 		    sizeof (ipha_t));
26684 		oipha->ipha_protocol = IPPROTO_ENCAP;
26685 		oipha->ipha_version_and_hdr_length =
26686 		    IP_SIMPLE_HDR_VERSION;
26687 		oipha->ipha_hdr_checksum = 0;
26688 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26689 		outer_mp->b_cont = inner_mp;
26690 		ipsec_mp->b_cont = outer_mp;
26691 
26692 		io->ipsec_out_se_done = B_TRUE;
26693 		io->ipsec_out_tunnel = B_TRUE;
26694 	}
26695 
26696 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26697 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26698 	    !ipsec_out_select_sa(ipsec_mp))
26699 		return;
26700 
26701 	/*
26702 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26703 	 * to do the heavy lifting.
26704 	 */
26705 	zoneid = io->ipsec_out_zoneid;
26706 	ASSERT(zoneid != ALL_ZONES);
26707 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26708 		ASSERT(io->ipsec_out_esp_sa != NULL);
26709 		io->ipsec_out_esp_done = B_TRUE;
26710 		/*
26711 		 * Note that since hw accel can only apply one transform,
26712 		 * not two, we skip hw accel for ESP if we also have AH
26713 		 * This is an design limitation of the interface
26714 		 * which should be revisited.
26715 		 */
26716 		ASSERT(ire != NULL);
26717 		if (io->ipsec_out_ah_sa == NULL) {
26718 			ill = (ill_t *)ire->ire_stq->q_ptr;
26719 			ipsec_out_is_accelerated(ipsec_mp,
26720 			    io->ipsec_out_esp_sa, ill, ire);
26721 		}
26722 
26723 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26724 		switch (ipsec_rc) {
26725 		case IPSEC_STATUS_SUCCESS:
26726 			break;
26727 		case IPSEC_STATUS_FAILED:
26728 			if (ill != NULL) {
26729 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26730 			} else {
26731 				BUMP_MIB(&ipst->ips_ip_mib,
26732 				    ipIfStatsOutDiscards);
26733 			}
26734 			/* FALLTHRU */
26735 		case IPSEC_STATUS_PENDING:
26736 			return;
26737 		}
26738 	}
26739 
26740 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26741 		ASSERT(io->ipsec_out_ah_sa != NULL);
26742 		io->ipsec_out_ah_done = B_TRUE;
26743 		if (ire == NULL) {
26744 			int idx = io->ipsec_out_capab_ill_index;
26745 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26746 			    NULL, NULL, NULL, NULL, ipst);
26747 			ill_need_rele = B_TRUE;
26748 		} else {
26749 			ill = (ill_t *)ire->ire_stq->q_ptr;
26750 		}
26751 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26752 		    ire);
26753 
26754 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26755 		switch (ipsec_rc) {
26756 		case IPSEC_STATUS_SUCCESS:
26757 			break;
26758 		case IPSEC_STATUS_FAILED:
26759 			if (ill != NULL) {
26760 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26761 			} else {
26762 				BUMP_MIB(&ipst->ips_ip_mib,
26763 				    ipIfStatsOutDiscards);
26764 			}
26765 			/* FALLTHRU */
26766 		case IPSEC_STATUS_PENDING:
26767 			if (ill != NULL && ill_need_rele)
26768 				ill_refrele(ill);
26769 			return;
26770 		}
26771 	}
26772 	/*
26773 	 * We are done with IPsec processing. Send it over
26774 	 * the wire.
26775 	 */
26776 done:
26777 	mp = ipsec_mp->b_cont;
26778 	ipha = (ipha_t *)mp->b_rptr;
26779 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26780 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26781 	} else {
26782 		ip6h = (ip6_t *)ipha;
26783 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26784 	}
26785 	if (ill != NULL && ill_need_rele)
26786 		ill_refrele(ill);
26787 }
26788 
26789 /* ARGSUSED */
26790 void
26791 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26792 {
26793 	opt_restart_t	*or;
26794 	int	err;
26795 	conn_t	*connp;
26796 
26797 	ASSERT(CONN_Q(q));
26798 	connp = Q_TO_CONN(q);
26799 
26800 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26801 	or = (opt_restart_t *)first_mp->b_rptr;
26802 	/*
26803 	 * We don't need to pass any credentials here since this is just
26804 	 * a restart. The credentials are passed in when svr4_optcom_req
26805 	 * is called the first time (from ip_wput_nondata).
26806 	 */
26807 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26808 		err = svr4_optcom_req(q, first_mp, NULL,
26809 		    &ip_opt_obj, B_FALSE);
26810 	} else {
26811 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26812 		err = tpi_optcom_req(q, first_mp, NULL,
26813 		    &ip_opt_obj, B_FALSE);
26814 	}
26815 	if (err != EINPROGRESS) {
26816 		/* operation is done */
26817 		CONN_OPER_PENDING_DONE(connp);
26818 	}
26819 }
26820 
26821 /*
26822  * ioctls that go through a down/up sequence may need to wait for the down
26823  * to complete. This involves waiting for the ire and ipif refcnts to go down
26824  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26825  */
26826 /* ARGSUSED */
26827 void
26828 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26829 {
26830 	struct iocblk *iocp;
26831 	mblk_t *mp1;
26832 	ip_ioctl_cmd_t *ipip;
26833 	int err;
26834 	sin_t	*sin;
26835 	struct lifreq *lifr;
26836 	struct ifreq *ifr;
26837 
26838 	iocp = (struct iocblk *)mp->b_rptr;
26839 	ASSERT(ipsq != NULL);
26840 	/* Existence of mp1 verified in ip_wput_nondata */
26841 	mp1 = mp->b_cont->b_cont;
26842 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26843 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26844 		/*
26845 		 * Special case where ipsq_current_ipif is not set:
26846 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26847 		 * ill could also have become part of a ipmp group in the
26848 		 * process, we are here as were not able to complete the
26849 		 * operation in ipif_set_values because we could not become
26850 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26851 		 * will not be set so we need to set it.
26852 		 */
26853 		ill_t *ill = q->q_ptr;
26854 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26855 	}
26856 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26857 
26858 	if (ipip->ipi_cmd_type == IF_CMD) {
26859 		/* This a old style SIOC[GS]IF* command */
26860 		ifr = (struct ifreq *)mp1->b_rptr;
26861 		sin = (sin_t *)&ifr->ifr_addr;
26862 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26863 		/* This a new style SIOC[GS]LIF* command */
26864 		lifr = (struct lifreq *)mp1->b_rptr;
26865 		sin = (sin_t *)&lifr->lifr_addr;
26866 	} else {
26867 		sin = NULL;
26868 	}
26869 
26870 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26871 	    ipip, mp1->b_rptr);
26872 
26873 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26874 }
26875 
26876 /*
26877  * ioctl processing
26878  *
26879  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26880  * the ioctl command in the ioctl tables, determines the copyin data size
26881  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26882  *
26883  * ioctl processing then continues when the M_IOCDATA makes its way down to
26884  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26885  * associated 'conn' is refheld till the end of the ioctl and the general
26886  * ioctl processing function ip_process_ioctl() is called to extract the
26887  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26888  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26889  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26890  * is used to extract the ioctl's arguments.
26891  *
26892  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26893  * so goes thru the serialization primitive ipsq_try_enter. Then the
26894  * appropriate function to handle the ioctl is called based on the entry in
26895  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26896  * which also refreleases the 'conn' that was refheld at the start of the
26897  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26898  *
26899  * Many exclusive ioctls go thru an internal down up sequence as part of
26900  * the operation. For example an attempt to change the IP address of an
26901  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26902  * does all the cleanup such as deleting all ires that use this address.
26903  * Then we need to wait till all references to the interface go away.
26904  */
26905 void
26906 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26907 {
26908 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26909 	ip_ioctl_cmd_t *ipip = arg;
26910 	ip_extract_func_t *extract_funcp;
26911 	cmd_info_t ci;
26912 	int err;
26913 	boolean_t entered_ipsq = B_FALSE;
26914 
26915 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26916 
26917 	if (ipip == NULL)
26918 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26919 
26920 	/*
26921 	 * SIOCLIFADDIF needs to go thru a special path since the
26922 	 * ill may not exist yet. This happens in the case of lo0
26923 	 * which is created using this ioctl.
26924 	 */
26925 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26926 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26927 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26928 		return;
26929 	}
26930 
26931 	ci.ci_ipif = NULL;
26932 	if (ipip->ipi_cmd_type == MISC_CMD) {
26933 		/*
26934 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26935 		 */
26936 		if (ipip->ipi_cmd == IF_UNITSEL) {
26937 			/* ioctl comes down the ill */
26938 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26939 			ipif_refhold(ci.ci_ipif);
26940 		}
26941 		err = 0;
26942 		ci.ci_sin = NULL;
26943 		ci.ci_sin6 = NULL;
26944 		ci.ci_lifr = NULL;
26945 	} else {
26946 		switch (ipip->ipi_cmd_type) {
26947 		case IF_CMD:
26948 		case LIF_CMD:
26949 			extract_funcp = ip_extract_lifreq;
26950 			break;
26951 
26952 		case ARP_CMD:
26953 		case XARP_CMD:
26954 			extract_funcp = ip_extract_arpreq;
26955 			break;
26956 
26957 		case TUN_CMD:
26958 			extract_funcp = ip_extract_tunreq;
26959 			break;
26960 
26961 		case MSFILT_CMD:
26962 			extract_funcp = ip_extract_msfilter;
26963 			break;
26964 
26965 		default:
26966 			ASSERT(0);
26967 		}
26968 
26969 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26970 		if (err != 0) {
26971 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26972 			return;
26973 		}
26974 
26975 		/*
26976 		 * All of the extraction functions return a refheld ipif.
26977 		 */
26978 		ASSERT(ci.ci_ipif != NULL);
26979 	}
26980 
26981 	/*
26982 	 * If ipsq is non-null, we are already being called exclusively
26983 	 */
26984 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26985 	if (!(ipip->ipi_flags & IPI_WR)) {
26986 		/*
26987 		 * A return value of EINPROGRESS means the ioctl is
26988 		 * either queued and waiting for some reason or has
26989 		 * already completed.
26990 		 */
26991 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26992 		    ci.ci_lifr);
26993 		if (ci.ci_ipif != NULL)
26994 			ipif_refrele(ci.ci_ipif);
26995 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26996 		return;
26997 	}
26998 
26999 	ASSERT(ci.ci_ipif != NULL);
27000 
27001 	if (ipsq == NULL) {
27002 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27003 		    ip_process_ioctl, NEW_OP, B_TRUE);
27004 		entered_ipsq = B_TRUE;
27005 	}
27006 	/*
27007 	 * Release the ipif so that ipif_down and friends that wait for
27008 	 * references to go away are not misled about the current ipif_refcnt
27009 	 * values. We are writer so we can access the ipif even after releasing
27010 	 * the ipif.
27011 	 */
27012 	ipif_refrele(ci.ci_ipif);
27013 	if (ipsq == NULL)
27014 		return;
27015 
27016 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27017 
27018 	/*
27019 	 * For most set ioctls that come here, this serves as a single point
27020 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27021 	 * be any new references to the ipif. This helps functions that go
27022 	 * through this path and end up trying to wait for the refcnts
27023 	 * associated with the ipif to go down to zero. Some exceptions are
27024 	 * Failover, Failback, and Groupname commands that operate on more than
27025 	 * just the ci.ci_ipif. These commands internally determine the
27026 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27027 	 * flags on that set. Another exception is the Removeif command that
27028 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27029 	 * ipif to operate on.
27030 	 */
27031 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27032 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27033 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27034 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27035 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27036 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27037 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27038 
27039 	/*
27040 	 * A return value of EINPROGRESS means the ioctl is
27041 	 * either queued and waiting for some reason or has
27042 	 * already completed.
27043 	 */
27044 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27045 
27046 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27047 
27048 	if (entered_ipsq)
27049 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27050 }
27051 
27052 /*
27053  * Complete the ioctl. Typically ioctls use the mi package and need to
27054  * do mi_copyout/mi_copy_done.
27055  */
27056 void
27057 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27058 {
27059 	conn_t	*connp = NULL;
27060 
27061 	if (err == EINPROGRESS)
27062 		return;
27063 
27064 	if (CONN_Q(q)) {
27065 		connp = Q_TO_CONN(q);
27066 		ASSERT(connp->conn_ref >= 2);
27067 	}
27068 
27069 	switch (mode) {
27070 	case COPYOUT:
27071 		if (err == 0)
27072 			mi_copyout(q, mp);
27073 		else
27074 			mi_copy_done(q, mp, err);
27075 		break;
27076 
27077 	case NO_COPYOUT:
27078 		mi_copy_done(q, mp, err);
27079 		break;
27080 
27081 	default:
27082 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27083 		break;
27084 	}
27085 
27086 	/*
27087 	 * The refhold placed at the start of the ioctl is released here.
27088 	 */
27089 	if (connp != NULL)
27090 		CONN_OPER_PENDING_DONE(connp);
27091 
27092 	if (ipsq != NULL)
27093 		ipsq_current_finish(ipsq);
27094 }
27095 
27096 /*
27097  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27098  */
27099 /* ARGSUSED */
27100 void
27101 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27102 {
27103 	conn_t *connp = arg;
27104 	tcp_t	*tcp;
27105 
27106 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27107 	tcp = connp->conn_tcp;
27108 
27109 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27110 		freemsg(mp);
27111 	else
27112 		tcp_rput_other(tcp, mp);
27113 	CONN_OPER_PENDING_DONE(connp);
27114 }
27115 
27116 /* Called from ip_wput for all non data messages */
27117 /* ARGSUSED */
27118 void
27119 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27120 {
27121 	mblk_t		*mp1;
27122 	ire_t		*ire, *fake_ire;
27123 	ill_t		*ill;
27124 	struct iocblk	*iocp;
27125 	ip_ioctl_cmd_t	*ipip;
27126 	cred_t		*cr;
27127 	conn_t		*connp;
27128 	int		err;
27129 	nce_t		*nce;
27130 	ipif_t		*ipif;
27131 	ip_stack_t	*ipst;
27132 	char		*proto_str;
27133 
27134 	if (CONN_Q(q)) {
27135 		connp = Q_TO_CONN(q);
27136 		ipst = connp->conn_netstack->netstack_ip;
27137 	} else {
27138 		connp = NULL;
27139 		ipst = ILLQ_TO_IPST(q);
27140 	}
27141 
27142 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27143 
27144 	switch (DB_TYPE(mp)) {
27145 	case M_IOCTL:
27146 		/*
27147 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27148 		 * will arrange to copy in associated control structures.
27149 		 */
27150 		ip_sioctl_copyin_setup(q, mp);
27151 		return;
27152 	case M_IOCDATA:
27153 		/*
27154 		 * Ensure that this is associated with one of our trans-
27155 		 * parent ioctls.  If it's not ours, discard it if we're
27156 		 * running as a driver, or pass it on if we're a module.
27157 		 */
27158 		iocp = (struct iocblk *)mp->b_rptr;
27159 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27160 		if (ipip == NULL) {
27161 			if (q->q_next == NULL) {
27162 				goto nak;
27163 			} else {
27164 				putnext(q, mp);
27165 			}
27166 			return;
27167 		}
27168 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27169 			/*
27170 			 * the ioctl is one we recognise, but is not
27171 			 * consumed by IP as a module, pass M_IOCDATA
27172 			 * for processing downstream, but only for
27173 			 * common Streams ioctls.
27174 			 */
27175 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27176 				putnext(q, mp);
27177 				return;
27178 			} else {
27179 				goto nak;
27180 			}
27181 		}
27182 
27183 		/* IOCTL continuation following copyin or copyout. */
27184 		if (mi_copy_state(q, mp, NULL) == -1) {
27185 			/*
27186 			 * The copy operation failed.  mi_copy_state already
27187 			 * cleaned up, so we're out of here.
27188 			 */
27189 			return;
27190 		}
27191 		/*
27192 		 * If we just completed a copy in, we become writer and
27193 		 * continue processing in ip_sioctl_copyin_done.  If it
27194 		 * was a copy out, we call mi_copyout again.  If there is
27195 		 * nothing more to copy out, it will complete the IOCTL.
27196 		 */
27197 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27198 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27199 				mi_copy_done(q, mp, EPROTO);
27200 				return;
27201 			}
27202 			/*
27203 			 * Check for cases that need more copying.  A return
27204 			 * value of 0 means a second copyin has been started,
27205 			 * so we return; a return value of 1 means no more
27206 			 * copying is needed, so we continue.
27207 			 */
27208 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27209 			    MI_COPY_COUNT(mp) == 1) {
27210 				if (ip_copyin_msfilter(q, mp) == 0)
27211 					return;
27212 			}
27213 			/*
27214 			 * Refhold the conn, till the ioctl completes. This is
27215 			 * needed in case the ioctl ends up in the pending mp
27216 			 * list. Every mp in the ill_pending_mp list and
27217 			 * the ipsq_pending_mp must have a refhold on the conn
27218 			 * to resume processing. The refhold is released when
27219 			 * the ioctl completes. (normally or abnormally)
27220 			 * In all cases ip_ioctl_finish is called to finish
27221 			 * the ioctl.
27222 			 */
27223 			if (connp != NULL) {
27224 				/* This is not a reentry */
27225 				ASSERT(ipsq == NULL);
27226 				CONN_INC_REF(connp);
27227 			} else {
27228 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27229 					mi_copy_done(q, mp, EINVAL);
27230 					return;
27231 				}
27232 			}
27233 
27234 			ip_process_ioctl(ipsq, q, mp, ipip);
27235 
27236 		} else {
27237 			mi_copyout(q, mp);
27238 		}
27239 		return;
27240 nak:
27241 		iocp->ioc_error = EINVAL;
27242 		mp->b_datap->db_type = M_IOCNAK;
27243 		iocp->ioc_count = 0;
27244 		qreply(q, mp);
27245 		return;
27246 
27247 	case M_IOCNAK:
27248 		/*
27249 		 * The only way we could get here is if a resolver didn't like
27250 		 * an IOCTL we sent it.	 This shouldn't happen.
27251 		 */
27252 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27253 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27254 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27255 		freemsg(mp);
27256 		return;
27257 	case M_IOCACK:
27258 		/* /dev/ip shouldn't see this */
27259 		if (CONN_Q(q))
27260 			goto nak;
27261 
27262 		/* Finish socket ioctls passed through to ARP. */
27263 		ip_sioctl_iocack(q, mp);
27264 		return;
27265 	case M_FLUSH:
27266 		if (*mp->b_rptr & FLUSHW)
27267 			flushq(q, FLUSHALL);
27268 		if (q->q_next) {
27269 			putnext(q, mp);
27270 			return;
27271 		}
27272 		if (*mp->b_rptr & FLUSHR) {
27273 			*mp->b_rptr &= ~FLUSHW;
27274 			qreply(q, mp);
27275 			return;
27276 		}
27277 		freemsg(mp);
27278 		return;
27279 	case IRE_DB_REQ_TYPE:
27280 		if (connp == NULL) {
27281 			proto_str = "IRE_DB_REQ_TYPE";
27282 			goto protonak;
27283 		}
27284 		/* An Upper Level Protocol wants a copy of an IRE. */
27285 		ip_ire_req(q, mp);
27286 		return;
27287 	case M_CTL:
27288 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27289 			break;
27290 
27291 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27292 		    TUN_HELLO) {
27293 			ASSERT(connp != NULL);
27294 			connp->conn_flags |= IPCL_IPTUN;
27295 			freeb(mp);
27296 			return;
27297 		}
27298 
27299 		/* M_CTL messages are used by ARP to tell us things. */
27300 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27301 			break;
27302 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27303 		case AR_ENTRY_SQUERY:
27304 			ip_wput_ctl(q, mp);
27305 			return;
27306 		case AR_CLIENT_NOTIFY:
27307 			ip_arp_news(q, mp);
27308 			return;
27309 		case AR_DLPIOP_DONE:
27310 			ASSERT(q->q_next != NULL);
27311 			ill = (ill_t *)q->q_ptr;
27312 			/* qwriter_ip releases the refhold */
27313 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27314 			ill_refhold(ill);
27315 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27316 			return;
27317 		case AR_ARP_CLOSING:
27318 			/*
27319 			 * ARP (above us) is closing. If no ARP bringup is
27320 			 * currently pending, ack the message so that ARP
27321 			 * can complete its close. Also mark ill_arp_closing
27322 			 * so that new ARP bringups will fail. If any
27323 			 * ARP bringup is currently in progress, we will
27324 			 * ack this when the current ARP bringup completes.
27325 			 */
27326 			ASSERT(q->q_next != NULL);
27327 			ill = (ill_t *)q->q_ptr;
27328 			mutex_enter(&ill->ill_lock);
27329 			ill->ill_arp_closing = 1;
27330 			if (!ill->ill_arp_bringup_pending) {
27331 				mutex_exit(&ill->ill_lock);
27332 				qreply(q, mp);
27333 			} else {
27334 				mutex_exit(&ill->ill_lock);
27335 				freemsg(mp);
27336 			}
27337 			return;
27338 		case AR_ARP_EXTEND:
27339 			/*
27340 			 * The ARP module above us is capable of duplicate
27341 			 * address detection.  Old ATM drivers will not send
27342 			 * this message.
27343 			 */
27344 			ASSERT(q->q_next != NULL);
27345 			ill = (ill_t *)q->q_ptr;
27346 			ill->ill_arp_extend = B_TRUE;
27347 			freemsg(mp);
27348 			return;
27349 		default:
27350 			break;
27351 		}
27352 		break;
27353 	case M_PROTO:
27354 	case M_PCPROTO:
27355 		/*
27356 		 * The only PROTO messages we expect are ULP binds and
27357 		 * copies of option negotiation acknowledgements.
27358 		 */
27359 		switch (((union T_primitives *)mp->b_rptr)->type) {
27360 		case O_T_BIND_REQ:
27361 		case T_BIND_REQ: {
27362 			/* Request can get queued in bind */
27363 			if (connp == NULL) {
27364 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27365 				goto protonak;
27366 			}
27367 			/*
27368 			 * The transports except SCTP call ip_bind_{v4,v6}()
27369 			 * directly instead of a a putnext. SCTP doesn't
27370 			 * generate any T_BIND_REQ since it has its own
27371 			 * fanout data structures. However, ESP and AH
27372 			 * come in for regular binds; all other cases are
27373 			 * bind retries.
27374 			 */
27375 			ASSERT(!IPCL_IS_SCTP(connp));
27376 
27377 			/* Don't increment refcnt if this is a re-entry */
27378 			if (ipsq == NULL)
27379 				CONN_INC_REF(connp);
27380 
27381 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27382 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27383 			if (mp == NULL)
27384 				return;
27385 			if (IPCL_IS_TCP(connp)) {
27386 				/*
27387 				 * In the case of TCP endpoint we
27388 				 * come here only for bind retries
27389 				 */
27390 				ASSERT(ipsq != NULL);
27391 				CONN_INC_REF(connp);
27392 				squeue_fill(connp->conn_sqp, mp,
27393 				    ip_resume_tcp_bind, connp,
27394 				    SQTAG_BIND_RETRY);
27395 			} else if (IPCL_IS_UDP(connp)) {
27396 				/*
27397 				 * In the case of UDP endpoint we
27398 				 * come here only for bind retries
27399 				 */
27400 				ASSERT(ipsq != NULL);
27401 				udp_resume_bind(connp, mp);
27402 			} else if (IPCL_IS_RAWIP(connp)) {
27403 				/*
27404 				 * In the case of RAWIP endpoint we
27405 				 * come here only for bind retries
27406 				 */
27407 				ASSERT(ipsq != NULL);
27408 				rawip_resume_bind(connp, mp);
27409 			} else {
27410 				/* The case of AH and ESP */
27411 				qreply(q, mp);
27412 				CONN_OPER_PENDING_DONE(connp);
27413 			}
27414 			return;
27415 		}
27416 		case T_SVR4_OPTMGMT_REQ:
27417 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27418 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27419 
27420 			if (connp == NULL) {
27421 				proto_str = "T_SVR4_OPTMGMT_REQ";
27422 				goto protonak;
27423 			}
27424 
27425 			if (!snmpcom_req(q, mp, ip_snmp_set,
27426 			    ip_snmp_get, cr)) {
27427 				/*
27428 				 * Call svr4_optcom_req so that it can
27429 				 * generate the ack. We don't come here
27430 				 * if this operation is being restarted.
27431 				 * ip_restart_optmgmt will drop the conn ref.
27432 				 * In the case of ipsec option after the ipsec
27433 				 * load is complete conn_restart_ipsec_waiter
27434 				 * drops the conn ref.
27435 				 */
27436 				ASSERT(ipsq == NULL);
27437 				CONN_INC_REF(connp);
27438 				if (ip_check_for_ipsec_opt(q, mp))
27439 					return;
27440 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27441 				    B_FALSE);
27442 				if (err != EINPROGRESS) {
27443 					/* Operation is done */
27444 					CONN_OPER_PENDING_DONE(connp);
27445 				}
27446 			}
27447 			return;
27448 		case T_OPTMGMT_REQ:
27449 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27450 			/*
27451 			 * Note: No snmpcom_req support through new
27452 			 * T_OPTMGMT_REQ.
27453 			 * Call tpi_optcom_req so that it can
27454 			 * generate the ack.
27455 			 */
27456 			if (connp == NULL) {
27457 				proto_str = "T_OPTMGMT_REQ";
27458 				goto protonak;
27459 			}
27460 
27461 			ASSERT(ipsq == NULL);
27462 			/*
27463 			 * We don't come here for restart. ip_restart_optmgmt
27464 			 * will drop the conn ref. In the case of ipsec option
27465 			 * after the ipsec load is complete
27466 			 * conn_restart_ipsec_waiter drops the conn ref.
27467 			 */
27468 			CONN_INC_REF(connp);
27469 			if (ip_check_for_ipsec_opt(q, mp))
27470 				return;
27471 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27472 			if (err != EINPROGRESS) {
27473 				/* Operation is done */
27474 				CONN_OPER_PENDING_DONE(connp);
27475 			}
27476 			return;
27477 		case T_UNBIND_REQ:
27478 			if (connp == NULL) {
27479 				proto_str = "T_UNBIND_REQ";
27480 				goto protonak;
27481 			}
27482 			mp = ip_unbind(q, mp);
27483 			qreply(q, mp);
27484 			return;
27485 		default:
27486 			/*
27487 			 * Have to drop any DLPI messages coming down from
27488 			 * arp (such as an info_req which would cause ip
27489 			 * to receive an extra info_ack if it was passed
27490 			 * through.
27491 			 */
27492 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27493 			    (int)*(uint_t *)mp->b_rptr));
27494 			freemsg(mp);
27495 			return;
27496 		}
27497 		/* NOTREACHED */
27498 	case IRE_DB_TYPE: {
27499 		nce_t		*nce;
27500 		ill_t		*ill;
27501 		in6_addr_t	gw_addr_v6;
27502 
27503 
27504 		/*
27505 		 * This is a response back from a resolver.  It
27506 		 * consists of a message chain containing:
27507 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27508 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27509 		 * The LL_HDR_MBLK is the DLPI header to use to get
27510 		 * the attached packet, and subsequent ones for the
27511 		 * same destination, transmitted.
27512 		 */
27513 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27514 			break;
27515 		/*
27516 		 * First, check to make sure the resolution succeeded.
27517 		 * If it failed, the second mblk will be empty.
27518 		 * If it is, free the chain, dropping the packet.
27519 		 * (We must ire_delete the ire; that frees the ire mblk)
27520 		 * We're doing this now to support PVCs for ATM; it's
27521 		 * a partial xresolv implementation. When we fully implement
27522 		 * xresolv interfaces, instead of freeing everything here
27523 		 * we'll initiate neighbor discovery.
27524 		 *
27525 		 * For v4 (ARP and other external resolvers) the resolver
27526 		 * frees the message, so no check is needed. This check
27527 		 * is required, though, for a full xresolve implementation.
27528 		 * Including this code here now both shows how external
27529 		 * resolvers can NACK a resolution request using an
27530 		 * existing design that has no specific provisions for NACKs,
27531 		 * and also takes into account that the current non-ARP
27532 		 * external resolver has been coded to use this method of
27533 		 * NACKing for all IPv6 (xresolv) cases,
27534 		 * whether our xresolv implementation is complete or not.
27535 		 *
27536 		 */
27537 		ire = (ire_t *)mp->b_rptr;
27538 		ill = ire_to_ill(ire);
27539 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27540 		if (mp1->b_rptr == mp1->b_wptr) {
27541 			if (ire->ire_ipversion == IPV6_VERSION) {
27542 				/*
27543 				 * XRESOLV interface.
27544 				 */
27545 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27546 				mutex_enter(&ire->ire_lock);
27547 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27548 				mutex_exit(&ire->ire_lock);
27549 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27550 					nce = ndp_lookup_v6(ill,
27551 					    &ire->ire_addr_v6, B_FALSE);
27552 				} else {
27553 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27554 					    B_FALSE);
27555 				}
27556 				if (nce != NULL) {
27557 					nce_resolv_failed(nce);
27558 					ndp_delete(nce);
27559 					NCE_REFRELE(nce);
27560 				}
27561 			}
27562 			mp->b_cont = NULL;
27563 			freemsg(mp1);		/* frees the pkt as well */
27564 			ASSERT(ire->ire_nce == NULL);
27565 			ire_delete((ire_t *)mp->b_rptr);
27566 			return;
27567 		}
27568 
27569 		/*
27570 		 * Split them into IRE_MBLK and pkt and feed it into
27571 		 * ire_add_then_send. Then in ire_add_then_send
27572 		 * the IRE will be added, and then the packet will be
27573 		 * run back through ip_wput. This time it will make
27574 		 * it to the wire.
27575 		 */
27576 		mp->b_cont = NULL;
27577 		mp = mp1->b_cont;		/* now, mp points to pkt */
27578 		mp1->b_cont = NULL;
27579 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27580 		if (ire->ire_ipversion == IPV6_VERSION) {
27581 			/*
27582 			 * XRESOLV interface. Find the nce and put a copy
27583 			 * of the dl_unitdata_req in nce_res_mp
27584 			 */
27585 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27586 			mutex_enter(&ire->ire_lock);
27587 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27588 			mutex_exit(&ire->ire_lock);
27589 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27590 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27591 				    B_FALSE);
27592 			} else {
27593 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27594 			}
27595 			if (nce != NULL) {
27596 				/*
27597 				 * We have to protect nce_res_mp here
27598 				 * from being accessed by other threads
27599 				 * while we change the mblk pointer.
27600 				 * Other functions will also lock the nce when
27601 				 * accessing nce_res_mp.
27602 				 *
27603 				 * The reason we change the mblk pointer
27604 				 * here rather than copying the resolved address
27605 				 * into the template is that, unlike with
27606 				 * ethernet, we have no guarantee that the
27607 				 * resolved address length will be
27608 				 * smaller than or equal to the lla length
27609 				 * with which the template was allocated,
27610 				 * (for ethernet, they're equal)
27611 				 * so we have to use the actual resolved
27612 				 * address mblk - which holds the real
27613 				 * dl_unitdata_req with the resolved address.
27614 				 *
27615 				 * Doing this is the same behavior as was
27616 				 * previously used in the v4 ARP case.
27617 				 */
27618 				mutex_enter(&nce->nce_lock);
27619 				if (nce->nce_res_mp != NULL)
27620 					freemsg(nce->nce_res_mp);
27621 				nce->nce_res_mp = mp1;
27622 				mutex_exit(&nce->nce_lock);
27623 				/*
27624 				 * We do a fastpath probe here because
27625 				 * we have resolved the address without
27626 				 * using Neighbor Discovery.
27627 				 * In the non-XRESOLV v6 case, the fastpath
27628 				 * probe is done right after neighbor
27629 				 * discovery completes.
27630 				 */
27631 				if (nce->nce_res_mp != NULL) {
27632 					int res;
27633 					nce_fastpath_list_add(nce);
27634 					res = ill_fastpath_probe(ill,
27635 					    nce->nce_res_mp);
27636 					if (res != 0 && res != EAGAIN)
27637 						nce_fastpath_list_delete(nce);
27638 				}
27639 
27640 				ire_add_then_send(q, ire, mp);
27641 				/*
27642 				 * Now we have to clean out any packets
27643 				 * that may have been queued on the nce
27644 				 * while it was waiting for address resolution
27645 				 * to complete.
27646 				 */
27647 				mutex_enter(&nce->nce_lock);
27648 				mp1 = nce->nce_qd_mp;
27649 				nce->nce_qd_mp = NULL;
27650 				mutex_exit(&nce->nce_lock);
27651 				while (mp1 != NULL) {
27652 					mblk_t *nxt_mp;
27653 					queue_t *fwdq = NULL;
27654 					ill_t   *inbound_ill;
27655 					uint_t ifindex;
27656 
27657 					nxt_mp = mp1->b_next;
27658 					mp1->b_next = NULL;
27659 					/*
27660 					 * Retrieve ifindex stored in
27661 					 * ip_rput_data_v6()
27662 					 */
27663 					ifindex =
27664 					    (uint_t)(uintptr_t)mp1->b_prev;
27665 					inbound_ill =
27666 					    ill_lookup_on_ifindex(ifindex,
27667 					    B_TRUE, NULL, NULL, NULL,
27668 					    NULL, ipst);
27669 					mp1->b_prev = NULL;
27670 					if (inbound_ill != NULL)
27671 						fwdq = inbound_ill->ill_rq;
27672 
27673 					if (fwdq != NULL) {
27674 						put(fwdq, mp1);
27675 						ill_refrele(inbound_ill);
27676 					} else
27677 						put(WR(ill->ill_rq), mp1);
27678 					mp1 = nxt_mp;
27679 				}
27680 				NCE_REFRELE(nce);
27681 			} else {	/* nce is NULL; clean up */
27682 				ire_delete(ire);
27683 				freemsg(mp);
27684 				freemsg(mp1);
27685 				return;
27686 			}
27687 		} else {
27688 			nce_t *arpce;
27689 			/*
27690 			 * Link layer resolution succeeded. Recompute the
27691 			 * ire_nce.
27692 			 */
27693 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27694 			if ((arpce = ndp_lookup_v4(ill,
27695 			    (ire->ire_gateway_addr != INADDR_ANY ?
27696 			    &ire->ire_gateway_addr : &ire->ire_addr),
27697 			    B_FALSE)) == NULL) {
27698 				freeb(ire->ire_mp);
27699 				freeb(mp1);
27700 				freemsg(mp);
27701 				return;
27702 			}
27703 			mutex_enter(&arpce->nce_lock);
27704 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27705 			if (arpce->nce_state == ND_REACHABLE) {
27706 				/*
27707 				 * Someone resolved this before us;
27708 				 * cleanup the res_mp. Since ire has
27709 				 * not been added yet, the call to ire_add_v4
27710 				 * from ire_add_then_send (when a dup is
27711 				 * detected) will clean up the ire.
27712 				 */
27713 				freeb(mp1);
27714 			} else {
27715 				ASSERT(arpce->nce_res_mp == NULL);
27716 				arpce->nce_res_mp = mp1;
27717 				arpce->nce_state = ND_REACHABLE;
27718 			}
27719 			mutex_exit(&arpce->nce_lock);
27720 			if (ire->ire_marks & IRE_MARK_NOADD) {
27721 				/*
27722 				 * this ire will not be added to the ire
27723 				 * cache table, so we can set the ire_nce
27724 				 * here, as there are no atomicity constraints.
27725 				 */
27726 				ire->ire_nce = arpce;
27727 				/*
27728 				 * We are associating this nce with the ire
27729 				 * so change the nce ref taken in
27730 				 * ndp_lookup_v4() from
27731 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27732 				 */
27733 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27734 			} else {
27735 				NCE_REFRELE(arpce);
27736 			}
27737 			ire_add_then_send(q, ire, mp);
27738 		}
27739 		return;	/* All is well, the packet has been sent. */
27740 	}
27741 	case IRE_ARPRESOLVE_TYPE: {
27742 
27743 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27744 			break;
27745 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27746 		mp->b_cont = NULL;
27747 		/*
27748 		 * First, check to make sure the resolution succeeded.
27749 		 * If it failed, the second mblk will be empty.
27750 		 */
27751 		if (mp1->b_rptr == mp1->b_wptr) {
27752 			/* cleanup  the incomplete ire, free queued packets */
27753 			freemsg(mp); /* fake ire */
27754 			freeb(mp1);  /* dl_unitdata response */
27755 			return;
27756 		}
27757 
27758 		/*
27759 		 * update any incomplete nce_t found. we lookup the ctable
27760 		 * and find the nce from the ire->ire_nce because we need
27761 		 * to pass the ire to ip_xmit_v4 later, and can find both
27762 		 * ire and nce in one lookup from the ctable.
27763 		 */
27764 		fake_ire = (ire_t *)mp->b_rptr;
27765 		/*
27766 		 * By the time we come back here from ARP
27767 		 * the logical outgoing interface  of the incomplete ire
27768 		 * we added in ire_forward could have disappeared,
27769 		 * causing the incomplete ire to also have
27770 		 * dissapeared. So we need to retreive the
27771 		 * proper ipif for the ire  before looking
27772 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27773 		 */
27774 		ill = q->q_ptr;
27775 
27776 		/* Get the outgoing ipif */
27777 		mutex_enter(&ill->ill_lock);
27778 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27779 			mutex_exit(&ill->ill_lock);
27780 			freemsg(mp); /* fake ire */
27781 			freeb(mp1);  /* dl_unitdata response */
27782 			return;
27783 		}
27784 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27785 
27786 		if (ipif == NULL) {
27787 			mutex_exit(&ill->ill_lock);
27788 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27789 			freemsg(mp);
27790 			freeb(mp1);
27791 			return;
27792 		}
27793 		ipif_refhold_locked(ipif);
27794 		mutex_exit(&ill->ill_lock);
27795 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27796 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27797 		    ipif, fake_ire->ire_zoneid, NULL,
27798 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27799 		ipif_refrele(ipif);
27800 		if (ire == NULL) {
27801 			/*
27802 			 * no ire was found; check if there is an nce
27803 			 * for this lookup; if it has no ire's pointing at it
27804 			 * cleanup.
27805 			 */
27806 			if ((nce = ndp_lookup_v4(ill,
27807 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27808 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27809 			    B_FALSE)) != NULL) {
27810 				/*
27811 				 * cleanup:
27812 				 * We check for refcnt 2 (one for the nce
27813 				 * hash list + 1 for the ref taken by
27814 				 * ndp_lookup_v4) to check that there are
27815 				 * no ire's pointing at the nce.
27816 				 */
27817 				if (nce->nce_refcnt == 2)
27818 					ndp_delete(nce);
27819 				NCE_REFRELE(nce);
27820 			}
27821 			freeb(mp1);  /* dl_unitdata response */
27822 			freemsg(mp); /* fake ire */
27823 			return;
27824 		}
27825 		nce = ire->ire_nce;
27826 		DTRACE_PROBE2(ire__arpresolve__type,
27827 		    ire_t *, ire, nce_t *, nce);
27828 		ASSERT(nce->nce_state != ND_INITIAL);
27829 		mutex_enter(&nce->nce_lock);
27830 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27831 		if (nce->nce_state == ND_REACHABLE) {
27832 			/*
27833 			 * Someone resolved this before us;
27834 			 * our response is not needed any more.
27835 			 */
27836 			mutex_exit(&nce->nce_lock);
27837 			freeb(mp1);  /* dl_unitdata response */
27838 		} else {
27839 			ASSERT(nce->nce_res_mp == NULL);
27840 			nce->nce_res_mp = mp1;
27841 			nce->nce_state = ND_REACHABLE;
27842 			mutex_exit(&nce->nce_lock);
27843 			nce_fastpath(nce);
27844 		}
27845 		/*
27846 		 * The cached nce_t has been updated to be reachable;
27847 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27848 		 */
27849 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27850 		freemsg(mp);
27851 		/*
27852 		 * send out queued packets.
27853 		 */
27854 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27855 
27856 		IRE_REFRELE(ire);
27857 		return;
27858 	}
27859 	default:
27860 		break;
27861 	}
27862 	if (q->q_next) {
27863 		putnext(q, mp);
27864 	} else
27865 		freemsg(mp);
27866 	return;
27867 
27868 protonak:
27869 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27870 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27871 		qreply(q, mp);
27872 }
27873 
27874 /*
27875  * Process IP options in an outbound packet.  Modify the destination if there
27876  * is a source route option.
27877  * Returns non-zero if something fails in which case an ICMP error has been
27878  * sent and mp freed.
27879  */
27880 static int
27881 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27882     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27883 {
27884 	ipoptp_t	opts;
27885 	uchar_t		*opt;
27886 	uint8_t		optval;
27887 	uint8_t		optlen;
27888 	ipaddr_t	dst;
27889 	intptr_t	code = 0;
27890 	mblk_t		*mp;
27891 	ire_t		*ire = NULL;
27892 
27893 	ip2dbg(("ip_wput_options\n"));
27894 	mp = ipsec_mp;
27895 	if (mctl_present) {
27896 		mp = ipsec_mp->b_cont;
27897 	}
27898 
27899 	dst = ipha->ipha_dst;
27900 	for (optval = ipoptp_first(&opts, ipha);
27901 	    optval != IPOPT_EOL;
27902 	    optval = ipoptp_next(&opts)) {
27903 		opt = opts.ipoptp_cur;
27904 		optlen = opts.ipoptp_len;
27905 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27906 		    optval, optlen));
27907 		switch (optval) {
27908 			uint32_t off;
27909 		case IPOPT_SSRR:
27910 		case IPOPT_LSRR:
27911 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27912 				ip1dbg((
27913 				    "ip_wput_options: bad option offset\n"));
27914 				code = (char *)&opt[IPOPT_OLEN] -
27915 				    (char *)ipha;
27916 				goto param_prob;
27917 			}
27918 			off = opt[IPOPT_OFFSET];
27919 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27920 			    ntohl(dst)));
27921 			/*
27922 			 * For strict: verify that dst is directly
27923 			 * reachable.
27924 			 */
27925 			if (optval == IPOPT_SSRR) {
27926 				ire = ire_ftable_lookup(dst, 0, 0,
27927 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27928 				    MBLK_GETLABEL(mp),
27929 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27930 				if (ire == NULL) {
27931 					ip1dbg(("ip_wput_options: SSRR not"
27932 					    " directly reachable: 0x%x\n",
27933 					    ntohl(dst)));
27934 					goto bad_src_route;
27935 				}
27936 				ire_refrele(ire);
27937 			}
27938 			break;
27939 		case IPOPT_RR:
27940 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27941 				ip1dbg((
27942 				    "ip_wput_options: bad option offset\n"));
27943 				code = (char *)&opt[IPOPT_OLEN] -
27944 				    (char *)ipha;
27945 				goto param_prob;
27946 			}
27947 			break;
27948 		case IPOPT_TS:
27949 			/*
27950 			 * Verify that length >=5 and that there is either
27951 			 * room for another timestamp or that the overflow
27952 			 * counter is not maxed out.
27953 			 */
27954 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27955 			if (optlen < IPOPT_MINLEN_IT) {
27956 				goto param_prob;
27957 			}
27958 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27959 				ip1dbg((
27960 				    "ip_wput_options: bad option offset\n"));
27961 				code = (char *)&opt[IPOPT_OFFSET] -
27962 				    (char *)ipha;
27963 				goto param_prob;
27964 			}
27965 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27966 			case IPOPT_TS_TSONLY:
27967 				off = IPOPT_TS_TIMELEN;
27968 				break;
27969 			case IPOPT_TS_TSANDADDR:
27970 			case IPOPT_TS_PRESPEC:
27971 			case IPOPT_TS_PRESPEC_RFC791:
27972 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27973 				break;
27974 			default:
27975 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27976 				    (char *)ipha;
27977 				goto param_prob;
27978 			}
27979 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27980 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27981 				/*
27982 				 * No room and the overflow counter is 15
27983 				 * already.
27984 				 */
27985 				goto param_prob;
27986 			}
27987 			break;
27988 		}
27989 	}
27990 
27991 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27992 		return (0);
27993 
27994 	ip1dbg(("ip_wput_options: error processing IP options."));
27995 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27996 
27997 param_prob:
27998 	/*
27999 	 * Since ip_wput() isn't close to finished, we fill
28000 	 * in enough of the header for credible error reporting.
28001 	 */
28002 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28003 		/* Failed */
28004 		freemsg(ipsec_mp);
28005 		return (-1);
28006 	}
28007 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28008 	return (-1);
28009 
28010 bad_src_route:
28011 	/*
28012 	 * Since ip_wput() isn't close to finished, we fill
28013 	 * in enough of the header for credible error reporting.
28014 	 */
28015 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28016 		/* Failed */
28017 		freemsg(ipsec_mp);
28018 		return (-1);
28019 	}
28020 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28021 	return (-1);
28022 }
28023 
28024 /*
28025  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28026  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28027  * thru /etc/system.
28028  */
28029 #define	CONN_MAXDRAINCNT	64
28030 
28031 static void
28032 conn_drain_init(ip_stack_t *ipst)
28033 {
28034 	int i;
28035 
28036 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28037 
28038 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28039 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28040 		/*
28041 		 * Default value of the number of drainers is the
28042 		 * number of cpus, subject to maximum of 8 drainers.
28043 		 */
28044 		if (boot_max_ncpus != -1)
28045 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28046 		else
28047 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28048 	}
28049 
28050 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28051 	    sizeof (idl_t), KM_SLEEP);
28052 
28053 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28054 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28055 		    MUTEX_DEFAULT, NULL);
28056 	}
28057 }
28058 
28059 static void
28060 conn_drain_fini(ip_stack_t *ipst)
28061 {
28062 	int i;
28063 
28064 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28065 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28066 	kmem_free(ipst->ips_conn_drain_list,
28067 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28068 	ipst->ips_conn_drain_list = NULL;
28069 }
28070 
28071 /*
28072  * Note: For an overview of how flowcontrol is handled in IP please see the
28073  * IP Flowcontrol notes at the top of this file.
28074  *
28075  * Flow control has blocked us from proceeding. Insert the given conn in one
28076  * of the conn drain lists. These conn wq's will be qenabled later on when
28077  * STREAMS flow control does a backenable. conn_walk_drain will enable
28078  * the first conn in each of these drain lists. Each of these qenabled conns
28079  * in turn enables the next in the list, after it runs, or when it closes,
28080  * thus sustaining the drain process.
28081  *
28082  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28083  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28084  * running at any time, on a given conn, since there can be only 1 service proc
28085  * running on a queue at any time.
28086  */
28087 void
28088 conn_drain_insert(conn_t *connp)
28089 {
28090 	idl_t	*idl;
28091 	uint_t	index;
28092 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28093 
28094 	mutex_enter(&connp->conn_lock);
28095 	if (connp->conn_state_flags & CONN_CLOSING) {
28096 		/*
28097 		 * The conn is closing as a result of which CONN_CLOSING
28098 		 * is set. Return.
28099 		 */
28100 		mutex_exit(&connp->conn_lock);
28101 		return;
28102 	} else if (connp->conn_idl == NULL) {
28103 		/*
28104 		 * Assign the next drain list round robin. We dont' use
28105 		 * a lock, and thus it may not be strictly round robin.
28106 		 * Atomicity of load/stores is enough to make sure that
28107 		 * conn_drain_list_index is always within bounds.
28108 		 */
28109 		index = ipst->ips_conn_drain_list_index;
28110 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28111 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28112 		index++;
28113 		if (index == ipst->ips_conn_drain_list_cnt)
28114 			index = 0;
28115 		ipst->ips_conn_drain_list_index = index;
28116 	}
28117 	mutex_exit(&connp->conn_lock);
28118 
28119 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28120 	if ((connp->conn_drain_prev != NULL) ||
28121 	    (connp->conn_state_flags & CONN_CLOSING)) {
28122 		/*
28123 		 * The conn is already in the drain list, OR
28124 		 * the conn is closing. We need to check again for
28125 		 * the closing case again since close can happen
28126 		 * after we drop the conn_lock, and before we
28127 		 * acquire the CONN_DRAIN_LIST_LOCK.
28128 		 */
28129 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28130 		return;
28131 	} else {
28132 		idl = connp->conn_idl;
28133 	}
28134 
28135 	/*
28136 	 * The conn is not in the drain list. Insert it at the
28137 	 * tail of the drain list. The drain list is circular
28138 	 * and doubly linked. idl_conn points to the 1st element
28139 	 * in the list.
28140 	 */
28141 	if (idl->idl_conn == NULL) {
28142 		idl->idl_conn = connp;
28143 		connp->conn_drain_next = connp;
28144 		connp->conn_drain_prev = connp;
28145 	} else {
28146 		conn_t *head = idl->idl_conn;
28147 
28148 		connp->conn_drain_next = head;
28149 		connp->conn_drain_prev = head->conn_drain_prev;
28150 		head->conn_drain_prev->conn_drain_next = connp;
28151 		head->conn_drain_prev = connp;
28152 	}
28153 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28154 }
28155 
28156 /*
28157  * This conn is closing, and we are called from ip_close. OR
28158  * This conn has been serviced by ip_wsrv, and we need to do the tail
28159  * processing.
28160  * If this conn is part of the drain list, we may need to sustain the drain
28161  * process by qenabling the next conn in the drain list. We may also need to
28162  * remove this conn from the list, if it is done.
28163  */
28164 static void
28165 conn_drain_tail(conn_t *connp, boolean_t closing)
28166 {
28167 	idl_t *idl;
28168 
28169 	/*
28170 	 * connp->conn_idl is stable at this point, and no lock is needed
28171 	 * to check it. If we are called from ip_close, close has already
28172 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28173 	 * called us only because conn_idl is non-null. If we are called thru
28174 	 * service, conn_idl could be null, but it cannot change because
28175 	 * service is single-threaded per queue, and there cannot be another
28176 	 * instance of service trying to call conn_drain_insert on this conn
28177 	 * now.
28178 	 */
28179 	ASSERT(!closing || (connp->conn_idl != NULL));
28180 
28181 	/*
28182 	 * If connp->conn_idl is null, the conn has not been inserted into any
28183 	 * drain list even once since creation of the conn. Just return.
28184 	 */
28185 	if (connp->conn_idl == NULL)
28186 		return;
28187 
28188 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28189 
28190 	if (connp->conn_drain_prev == NULL) {
28191 		/* This conn is currently not in the drain list.  */
28192 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28193 		return;
28194 	}
28195 	idl = connp->conn_idl;
28196 	if (idl->idl_conn_draining == connp) {
28197 		/*
28198 		 * This conn is the current drainer. If this is the last conn
28199 		 * in the drain list, we need to do more checks, in the 'if'
28200 		 * below. Otherwwise we need to just qenable the next conn,
28201 		 * to sustain the draining, and is handled in the 'else'
28202 		 * below.
28203 		 */
28204 		if (connp->conn_drain_next == idl->idl_conn) {
28205 			/*
28206 			 * This conn is the last in this list. This round
28207 			 * of draining is complete. If idl_repeat is set,
28208 			 * it means another flow enabling has happened from
28209 			 * the driver/streams and we need to another round
28210 			 * of draining.
28211 			 * If there are more than 2 conns in the drain list,
28212 			 * do a left rotate by 1, so that all conns except the
28213 			 * conn at the head move towards the head by 1, and the
28214 			 * the conn at the head goes to the tail. This attempts
28215 			 * a more even share for all queues that are being
28216 			 * drained.
28217 			 */
28218 			if ((connp->conn_drain_next != connp) &&
28219 			    (idl->idl_conn->conn_drain_next != connp)) {
28220 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28221 			}
28222 			if (idl->idl_repeat) {
28223 				qenable(idl->idl_conn->conn_wq);
28224 				idl->idl_conn_draining = idl->idl_conn;
28225 				idl->idl_repeat = 0;
28226 			} else {
28227 				idl->idl_conn_draining = NULL;
28228 			}
28229 		} else {
28230 			/*
28231 			 * If the next queue that we are now qenable'ing,
28232 			 * is closing, it will remove itself from this list
28233 			 * and qenable the subsequent queue in ip_close().
28234 			 * Serialization is acheived thru idl_lock.
28235 			 */
28236 			qenable(connp->conn_drain_next->conn_wq);
28237 			idl->idl_conn_draining = connp->conn_drain_next;
28238 		}
28239 	}
28240 	if (!connp->conn_did_putbq || closing) {
28241 		/*
28242 		 * Remove ourself from the drain list, if we did not do
28243 		 * a putbq, or if the conn is closing.
28244 		 * Note: It is possible that q->q_first is non-null. It means
28245 		 * that these messages landed after we did a enableok() in
28246 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28247 		 * service them.
28248 		 */
28249 		if (connp->conn_drain_next == connp) {
28250 			/* Singleton in the list */
28251 			ASSERT(connp->conn_drain_prev == connp);
28252 			idl->idl_conn = NULL;
28253 			idl->idl_conn_draining = NULL;
28254 		} else {
28255 			connp->conn_drain_prev->conn_drain_next =
28256 			    connp->conn_drain_next;
28257 			connp->conn_drain_next->conn_drain_prev =
28258 			    connp->conn_drain_prev;
28259 			if (idl->idl_conn == connp)
28260 				idl->idl_conn = connp->conn_drain_next;
28261 			ASSERT(idl->idl_conn_draining != connp);
28262 
28263 		}
28264 		connp->conn_drain_next = NULL;
28265 		connp->conn_drain_prev = NULL;
28266 	}
28267 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28268 }
28269 
28270 /*
28271  * Write service routine. Shared perimeter entry point.
28272  * ip_wsrv can be called in any of the following ways.
28273  * 1. The device queue's messages has fallen below the low water mark
28274  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28275  *    the drain lists and backenable the first conn in each list.
28276  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28277  *    qenabled non-tcp upper layers. We start dequeing messages and call
28278  *    ip_wput for each message.
28279  */
28280 
28281 void
28282 ip_wsrv(queue_t *q)
28283 {
28284 	conn_t	*connp;
28285 	ill_t	*ill;
28286 	mblk_t	*mp;
28287 
28288 	if (q->q_next) {
28289 		ill = (ill_t *)q->q_ptr;
28290 		if (ill->ill_state_flags == 0) {
28291 			/*
28292 			 * The device flow control has opened up.
28293 			 * Walk through conn drain lists and qenable the
28294 			 * first conn in each list. This makes sense only
28295 			 * if the stream is fully plumbed and setup.
28296 			 * Hence the if check above.
28297 			 */
28298 			ip1dbg(("ip_wsrv: walking\n"));
28299 			conn_walk_drain(ill->ill_ipst);
28300 		}
28301 		return;
28302 	}
28303 
28304 	connp = Q_TO_CONN(q);
28305 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28306 
28307 	/*
28308 	 * 1. Set conn_draining flag to signal that service is active.
28309 	 *
28310 	 * 2. ip_output determines whether it has been called from service,
28311 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28312 	 *    has been called from service.
28313 	 *
28314 	 * 3. Message ordering is preserved by the following logic.
28315 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28316 	 *    the message at the tail, if conn_draining is set (i.e. service
28317 	 *    is running) or if q->q_first is non-null.
28318 	 *
28319 	 *    ii. If ip_output is called from service, and if ip_output cannot
28320 	 *    putnext due to flow control, it does a putbq.
28321 	 *
28322 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28323 	 *    (causing an infinite loop).
28324 	 */
28325 	ASSERT(!connp->conn_did_putbq);
28326 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28327 		connp->conn_draining = 1;
28328 		noenable(q);
28329 		while ((mp = getq(q)) != NULL) {
28330 			ASSERT(CONN_Q(q));
28331 
28332 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28333 			if (connp->conn_did_putbq) {
28334 				/* ip_wput did a putbq */
28335 				break;
28336 			}
28337 		}
28338 		/*
28339 		 * At this point, a thread coming down from top, calling
28340 		 * ip_wput, may end up queueing the message. We have not yet
28341 		 * enabled the queue, so ip_wsrv won't be called again.
28342 		 * To avoid this race, check q->q_first again (in the loop)
28343 		 * If the other thread queued the message before we call
28344 		 * enableok(), we will catch it in the q->q_first check.
28345 		 * If the other thread queues the message after we call
28346 		 * enableok(), ip_wsrv will be called again by STREAMS.
28347 		 */
28348 		connp->conn_draining = 0;
28349 		enableok(q);
28350 	}
28351 
28352 	/* Enable the next conn for draining */
28353 	conn_drain_tail(connp, B_FALSE);
28354 
28355 	connp->conn_did_putbq = 0;
28356 }
28357 
28358 /*
28359  * Walk the list of all conn's calling the function provided with the
28360  * specified argument for each.	 Note that this only walks conn's that
28361  * have been bound.
28362  * Applies to both IPv4 and IPv6.
28363  */
28364 static void
28365 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28366 {
28367 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28368 	    ipst->ips_ipcl_udp_fanout_size,
28369 	    func, arg, zoneid);
28370 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28371 	    ipst->ips_ipcl_conn_fanout_size,
28372 	    func, arg, zoneid);
28373 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28374 	    ipst->ips_ipcl_bind_fanout_size,
28375 	    func, arg, zoneid);
28376 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28377 	    IPPROTO_MAX, func, arg, zoneid);
28378 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28379 	    IPPROTO_MAX, func, arg, zoneid);
28380 }
28381 
28382 /*
28383  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28384  * of conns that need to be drained, check if drain is already in progress.
28385  * If so set the idl_repeat bit, indicating that the last conn in the list
28386  * needs to reinitiate the drain once again, for the list. If drain is not
28387  * in progress for the list, initiate the draining, by qenabling the 1st
28388  * conn in the list. The drain is self-sustaining, each qenabled conn will
28389  * in turn qenable the next conn, when it is done/blocked/closing.
28390  */
28391 static void
28392 conn_walk_drain(ip_stack_t *ipst)
28393 {
28394 	int i;
28395 	idl_t *idl;
28396 
28397 	IP_STAT(ipst, ip_conn_walk_drain);
28398 
28399 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28400 		idl = &ipst->ips_conn_drain_list[i];
28401 		mutex_enter(&idl->idl_lock);
28402 		if (idl->idl_conn == NULL) {
28403 			mutex_exit(&idl->idl_lock);
28404 			continue;
28405 		}
28406 		/*
28407 		 * If this list is not being drained currently by
28408 		 * an ip_wsrv thread, start the process.
28409 		 */
28410 		if (idl->idl_conn_draining == NULL) {
28411 			ASSERT(idl->idl_repeat == 0);
28412 			qenable(idl->idl_conn->conn_wq);
28413 			idl->idl_conn_draining = idl->idl_conn;
28414 		} else {
28415 			idl->idl_repeat = 1;
28416 		}
28417 		mutex_exit(&idl->idl_lock);
28418 	}
28419 }
28420 
28421 /*
28422  * Walk an conn hash table of `count' buckets, calling func for each entry.
28423  */
28424 static void
28425 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28426     zoneid_t zoneid)
28427 {
28428 	conn_t	*connp;
28429 
28430 	while (count-- > 0) {
28431 		mutex_enter(&connfp->connf_lock);
28432 		for (connp = connfp->connf_head; connp != NULL;
28433 		    connp = connp->conn_next) {
28434 			if (zoneid == GLOBAL_ZONEID ||
28435 			    zoneid == connp->conn_zoneid) {
28436 				CONN_INC_REF(connp);
28437 				mutex_exit(&connfp->connf_lock);
28438 				(*func)(connp, arg);
28439 				mutex_enter(&connfp->connf_lock);
28440 				CONN_DEC_REF(connp);
28441 			}
28442 		}
28443 		mutex_exit(&connfp->connf_lock);
28444 		connfp++;
28445 	}
28446 }
28447 
28448 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28449 static void
28450 conn_report1(conn_t *connp, void *mp)
28451 {
28452 	char	buf1[INET6_ADDRSTRLEN];
28453 	char	buf2[INET6_ADDRSTRLEN];
28454 	uint_t	print_len, buf_len;
28455 
28456 	ASSERT(connp != NULL);
28457 
28458 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28459 	if (buf_len <= 0)
28460 		return;
28461 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28462 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28463 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28464 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28465 	    "%5d %s/%05d %s/%05d\n",
28466 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28467 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28468 	    buf1, connp->conn_lport,
28469 	    buf2, connp->conn_fport);
28470 	if (print_len < buf_len) {
28471 		((mblk_t *)mp)->b_wptr += print_len;
28472 	} else {
28473 		((mblk_t *)mp)->b_wptr += buf_len;
28474 	}
28475 }
28476 
28477 /*
28478  * Named Dispatch routine to produce a formatted report on all conns
28479  * that are listed in one of the fanout tables.
28480  * This report is accessed by using the ndd utility to "get" ND variable
28481  * "ip_conn_status".
28482  */
28483 /* ARGSUSED */
28484 static int
28485 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28486 {
28487 	conn_t *connp = Q_TO_CONN(q);
28488 
28489 	(void) mi_mpprintf(mp,
28490 	    "CONN      " MI_COL_HDRPAD_STR
28491 	    "rfq      " MI_COL_HDRPAD_STR
28492 	    "stq      " MI_COL_HDRPAD_STR
28493 	    " zone local                 remote");
28494 
28495 	/*
28496 	 * Because of the ndd constraint, at most we can have 64K buffer
28497 	 * to put in all conn info.  So to be more efficient, just
28498 	 * allocate a 64K buffer here, assuming we need that large buffer.
28499 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28500 	 */
28501 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28502 		/* The following may work even if we cannot get a large buf. */
28503 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28504 		return (0);
28505 	}
28506 
28507 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28508 	    connp->conn_netstack->netstack_ip);
28509 	return (0);
28510 }
28511 
28512 /*
28513  * Determine if the ill and multicast aspects of that packets
28514  * "matches" the conn.
28515  */
28516 boolean_t
28517 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28518     zoneid_t zoneid)
28519 {
28520 	ill_t *in_ill;
28521 	boolean_t found;
28522 	ipif_t *ipif;
28523 	ire_t *ire;
28524 	ipaddr_t dst, src;
28525 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28526 
28527 	dst = ipha->ipha_dst;
28528 	src = ipha->ipha_src;
28529 
28530 	/*
28531 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28532 	 * unicast, broadcast and multicast reception to
28533 	 * conn_incoming_ill. conn_wantpacket itself is called
28534 	 * only for BROADCAST and multicast.
28535 	 *
28536 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28537 	 *    is part of a group. Hence, we should be receiving
28538 	 *    just one copy of broadcast for the whole group.
28539 	 *    Thus, if it is part of the group the packet could
28540 	 *    come on any ill of the group and hence we need a
28541 	 *    match on the group. Otherwise, match on ill should
28542 	 *    be sufficient.
28543 	 *
28544 	 * 2) ip_rput does not suppress duplicate multicast packets.
28545 	 *    If there are two interfaces in a ill group and we have
28546 	 *    2 applications (conns) joined a multicast group G on
28547 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28548 	 *    will give us two packets because we join G on both the
28549 	 *    interfaces rather than nominating just one interface
28550 	 *    for receiving multicast like broadcast above. So,
28551 	 *    we have to call ilg_lookup_ill to filter out duplicate
28552 	 *    copies, if ill is part of a group.
28553 	 */
28554 	in_ill = connp->conn_incoming_ill;
28555 	if (in_ill != NULL) {
28556 		if (in_ill->ill_group == NULL) {
28557 			if (in_ill != ill)
28558 				return (B_FALSE);
28559 		} else if (in_ill->ill_group != ill->ill_group) {
28560 			return (B_FALSE);
28561 		}
28562 	}
28563 
28564 	if (!CLASSD(dst)) {
28565 		if (IPCL_ZONE_MATCH(connp, zoneid))
28566 			return (B_TRUE);
28567 		/*
28568 		 * The conn is in a different zone; we need to check that this
28569 		 * broadcast address is configured in the application's zone and
28570 		 * on one ill in the group.
28571 		 */
28572 		ipif = ipif_get_next_ipif(NULL, ill);
28573 		if (ipif == NULL)
28574 			return (B_FALSE);
28575 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28576 		    connp->conn_zoneid, NULL,
28577 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28578 		ipif_refrele(ipif);
28579 		if (ire != NULL) {
28580 			ire_refrele(ire);
28581 			return (B_TRUE);
28582 		} else {
28583 			return (B_FALSE);
28584 		}
28585 	}
28586 
28587 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28588 	    connp->conn_zoneid == zoneid) {
28589 		/*
28590 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28591 		 * disabled, therefore we don't dispatch the multicast packet to
28592 		 * the sending zone.
28593 		 */
28594 		return (B_FALSE);
28595 	}
28596 
28597 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28598 		/*
28599 		 * Multicast packet on the loopback interface: we only match
28600 		 * conns who joined the group in the specified zone.
28601 		 */
28602 		return (B_FALSE);
28603 	}
28604 
28605 	if (connp->conn_multi_router) {
28606 		/* multicast packet and multicast router socket: send up */
28607 		return (B_TRUE);
28608 	}
28609 
28610 	mutex_enter(&connp->conn_lock);
28611 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28612 	mutex_exit(&connp->conn_lock);
28613 	return (found);
28614 }
28615 
28616 /*
28617  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28618  */
28619 /* ARGSUSED */
28620 static void
28621 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28622 {
28623 	ill_t *ill = (ill_t *)q->q_ptr;
28624 	mblk_t	*mp1, *mp2;
28625 	ipif_t  *ipif;
28626 	int err = 0;
28627 	conn_t *connp = NULL;
28628 	ipsq_t	*ipsq;
28629 	arc_t	*arc;
28630 
28631 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28632 
28633 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28634 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28635 
28636 	ASSERT(IAM_WRITER_ILL(ill));
28637 	mp2 = mp->b_cont;
28638 	mp->b_cont = NULL;
28639 
28640 	/*
28641 	 * We have now received the arp bringup completion message
28642 	 * from ARP. Mark the arp bringup as done. Also if the arp
28643 	 * stream has already started closing, send up the AR_ARP_CLOSING
28644 	 * ack now since ARP is waiting in close for this ack.
28645 	 */
28646 	mutex_enter(&ill->ill_lock);
28647 	ill->ill_arp_bringup_pending = 0;
28648 	if (ill->ill_arp_closing) {
28649 		mutex_exit(&ill->ill_lock);
28650 		/* Let's reuse the mp for sending the ack */
28651 		arc = (arc_t *)mp->b_rptr;
28652 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28653 		arc->arc_cmd = AR_ARP_CLOSING;
28654 		qreply(q, mp);
28655 	} else {
28656 		mutex_exit(&ill->ill_lock);
28657 		freeb(mp);
28658 	}
28659 
28660 	ipsq = ill->ill_phyint->phyint_ipsq;
28661 	ipif = ipsq->ipsq_pending_ipif;
28662 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28663 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28664 	if (mp1 == NULL) {
28665 		/* bringup was aborted by the user */
28666 		freemsg(mp2);
28667 		return;
28668 	}
28669 
28670 	/*
28671 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28672 	 * must have an associated conn_t.  Otherwise, we're bringing this
28673 	 * interface back up as part of handling an asynchronous event (e.g.,
28674 	 * physical address change).
28675 	 */
28676 	if (ipsq->ipsq_current_ioctl != 0) {
28677 		ASSERT(connp != NULL);
28678 		q = CONNP_TO_WQ(connp);
28679 	} else {
28680 		ASSERT(connp == NULL);
28681 		q = ill->ill_rq;
28682 	}
28683 
28684 	/*
28685 	 * If the DL_BIND_REQ fails, it is noted
28686 	 * in arc_name_offset.
28687 	 */
28688 	err = *((int *)mp2->b_rptr);
28689 	if (err == 0) {
28690 		if (ipif->ipif_isv6) {
28691 			if ((err = ipif_up_done_v6(ipif)) != 0)
28692 				ip0dbg(("ip_arp_done: init failed\n"));
28693 		} else {
28694 			if ((err = ipif_up_done(ipif)) != 0)
28695 				ip0dbg(("ip_arp_done: init failed\n"));
28696 		}
28697 	} else {
28698 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28699 	}
28700 
28701 	freemsg(mp2);
28702 
28703 	if ((err == 0) && (ill->ill_up_ipifs)) {
28704 		err = ill_up_ipifs(ill, q, mp1);
28705 		if (err == EINPROGRESS)
28706 			return;
28707 	}
28708 
28709 	if (ill->ill_up_ipifs)
28710 		ill_group_cleanup(ill);
28711 
28712 	/*
28713 	 * The operation must complete without EINPROGRESS since
28714 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28715 	 * Otherwise, the operation will be stuck forever in the ipsq.
28716 	 */
28717 	ASSERT(err != EINPROGRESS);
28718 	if (ipsq->ipsq_current_ioctl != 0)
28719 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28720 	else
28721 		ipsq_current_finish(ipsq);
28722 }
28723 
28724 /* Allocate the private structure */
28725 static int
28726 ip_priv_alloc(void **bufp)
28727 {
28728 	void	*buf;
28729 
28730 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28731 		return (ENOMEM);
28732 
28733 	*bufp = buf;
28734 	return (0);
28735 }
28736 
28737 /* Function to delete the private structure */
28738 void
28739 ip_priv_free(void *buf)
28740 {
28741 	ASSERT(buf != NULL);
28742 	kmem_free(buf, sizeof (ip_priv_t));
28743 }
28744 
28745 /*
28746  * The entry point for IPPF processing.
28747  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28748  * routine just returns.
28749  *
28750  * When called, ip_process generates an ipp_packet_t structure
28751  * which holds the state information for this packet and invokes the
28752  * the classifier (via ipp_packet_process). The classification, depending on
28753  * configured filters, results in a list of actions for this packet. Invoking
28754  * an action may cause the packet to be dropped, in which case the resulting
28755  * mblk (*mpp) is NULL. proc indicates the callout position for
28756  * this packet and ill_index is the interface this packet on or will leave
28757  * on (inbound and outbound resp.).
28758  */
28759 void
28760 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28761 {
28762 	mblk_t		*mp;
28763 	ip_priv_t	*priv;
28764 	ipp_action_id_t	aid;
28765 	int		rc = 0;
28766 	ipp_packet_t	*pp;
28767 #define	IP_CLASS	"ip"
28768 
28769 	/* If the classifier is not loaded, return  */
28770 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28771 		return;
28772 	}
28773 
28774 	mp = *mpp;
28775 	ASSERT(mp != NULL);
28776 
28777 	/* Allocate the packet structure */
28778 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28779 	if (rc != 0) {
28780 		*mpp = NULL;
28781 		freemsg(mp);
28782 		return;
28783 	}
28784 
28785 	/* Allocate the private structure */
28786 	rc = ip_priv_alloc((void **)&priv);
28787 	if (rc != 0) {
28788 		*mpp = NULL;
28789 		freemsg(mp);
28790 		ipp_packet_free(pp);
28791 		return;
28792 	}
28793 	priv->proc = proc;
28794 	priv->ill_index = ill_index;
28795 	ipp_packet_set_private(pp, priv, ip_priv_free);
28796 	ipp_packet_set_data(pp, mp);
28797 
28798 	/* Invoke the classifier */
28799 	rc = ipp_packet_process(&pp);
28800 	if (pp != NULL) {
28801 		mp = ipp_packet_get_data(pp);
28802 		ipp_packet_free(pp);
28803 		if (rc != 0) {
28804 			freemsg(mp);
28805 			*mpp = NULL;
28806 		}
28807 	} else {
28808 		*mpp = NULL;
28809 	}
28810 #undef	IP_CLASS
28811 }
28812 
28813 /*
28814  * Propagate a multicast group membership operation (add/drop) on
28815  * all the interfaces crossed by the related multirt routes.
28816  * The call is considered successful if the operation succeeds
28817  * on at least one interface.
28818  */
28819 static int
28820 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28821     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28822     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28823     mblk_t *first_mp)
28824 {
28825 	ire_t		*ire_gw;
28826 	irb_t		*irb;
28827 	int		error = 0;
28828 	opt_restart_t	*or;
28829 	ip_stack_t	*ipst = ire->ire_ipst;
28830 
28831 	irb = ire->ire_bucket;
28832 	ASSERT(irb != NULL);
28833 
28834 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28835 
28836 	or = (opt_restart_t *)first_mp->b_rptr;
28837 	IRB_REFHOLD(irb);
28838 	for (; ire != NULL; ire = ire->ire_next) {
28839 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28840 			continue;
28841 		if (ire->ire_addr != group)
28842 			continue;
28843 
28844 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28845 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28846 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28847 		/* No resolver exists for the gateway; skip this ire. */
28848 		if (ire_gw == NULL)
28849 			continue;
28850 
28851 		/*
28852 		 * This function can return EINPROGRESS. If so the operation
28853 		 * will be restarted from ip_restart_optmgmt which will
28854 		 * call ip_opt_set and option processing will restart for
28855 		 * this option. So we may end up calling 'fn' more than once.
28856 		 * This requires that 'fn' is idempotent except for the
28857 		 * return value. The operation is considered a success if
28858 		 * it succeeds at least once on any one interface.
28859 		 */
28860 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28861 		    NULL, fmode, src, first_mp);
28862 		if (error == 0)
28863 			or->or_private = CGTP_MCAST_SUCCESS;
28864 
28865 		if (ip_debug > 0) {
28866 			ulong_t	off;
28867 			char	*ksym;
28868 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28869 			ip2dbg(("ip_multirt_apply_membership: "
28870 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28871 			    "error %d [success %u]\n",
28872 			    ksym ? ksym : "?",
28873 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28874 			    error, or->or_private));
28875 		}
28876 
28877 		ire_refrele(ire_gw);
28878 		if (error == EINPROGRESS) {
28879 			IRB_REFRELE(irb);
28880 			return (error);
28881 		}
28882 	}
28883 	IRB_REFRELE(irb);
28884 	/*
28885 	 * Consider the call as successful if we succeeded on at least
28886 	 * one interface. Otherwise, return the last encountered error.
28887 	 */
28888 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28889 }
28890 
28891 
28892 /*
28893  * Issue a warning regarding a route crossing an interface with an
28894  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28895  * amount of time is logged.
28896  */
28897 static void
28898 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28899 {
28900 	hrtime_t	current = gethrtime();
28901 	char		buf[INET_ADDRSTRLEN];
28902 	ip_stack_t	*ipst = ire->ire_ipst;
28903 
28904 	/* Convert interval in ms to hrtime in ns */
28905 	if (ipst->ips_multirt_bad_mtu_last_time +
28906 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28907 	    current) {
28908 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28909 		    "to %s, incorrect MTU %u (expected %u)\n",
28910 		    ip_dot_addr(ire->ire_addr, buf),
28911 		    ire->ire_max_frag, max_frag);
28912 
28913 		ipst->ips_multirt_bad_mtu_last_time = current;
28914 	}
28915 }
28916 
28917 
28918 /*
28919  * Get the CGTP (multirouting) filtering status.
28920  * If 0, the CGTP hooks are transparent.
28921  */
28922 /* ARGSUSED */
28923 static int
28924 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28925 {
28926 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28927 
28928 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28929 	return (0);
28930 }
28931 
28932 
28933 /*
28934  * Set the CGTP (multirouting) filtering status.
28935  * If the status is changed from active to transparent
28936  * or from transparent to active, forward the new status
28937  * to the filtering module (if loaded).
28938  */
28939 /* ARGSUSED */
28940 static int
28941 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28942     cred_t *ioc_cr)
28943 {
28944 	long		new_value;
28945 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28946 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28947 
28948 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28949 		return (EPERM);
28950 
28951 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28952 	    new_value < 0 || new_value > 1) {
28953 		return (EINVAL);
28954 	}
28955 
28956 	if ((!*ip_cgtp_filter_value) && new_value) {
28957 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28958 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28959 		    " (module not loaded)" : "");
28960 	}
28961 	if (*ip_cgtp_filter_value && (!new_value)) {
28962 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28963 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28964 		    " (module not loaded)" : "");
28965 	}
28966 
28967 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28968 		int	res;
28969 		netstackid_t stackid;
28970 
28971 		stackid = ipst->ips_netstack->netstack_stackid;
28972 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28973 		    new_value);
28974 		if (res)
28975 			return (res);
28976 	}
28977 
28978 	*ip_cgtp_filter_value = (boolean_t)new_value;
28979 
28980 	return (0);
28981 }
28982 
28983 
28984 /*
28985  * Return the expected CGTP hooks version number.
28986  */
28987 int
28988 ip_cgtp_filter_supported(void)
28989 {
28990 	return (ip_cgtp_filter_rev);
28991 }
28992 
28993 
28994 /*
28995  * CGTP hooks can be registered by invoking this function.
28996  * Checks that the version number matches.
28997  */
28998 int
28999 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29000 {
29001 	netstack_t *ns;
29002 	ip_stack_t *ipst;
29003 
29004 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29005 		return (ENOTSUP);
29006 
29007 	ns = netstack_find_by_stackid(stackid);
29008 	if (ns == NULL)
29009 		return (EINVAL);
29010 	ipst = ns->netstack_ip;
29011 	ASSERT(ipst != NULL);
29012 
29013 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29014 		netstack_rele(ns);
29015 		return (EALREADY);
29016 	}
29017 
29018 	ipst->ips_ip_cgtp_filter_ops = ops;
29019 	netstack_rele(ns);
29020 	return (0);
29021 }
29022 
29023 /*
29024  * CGTP hooks can be unregistered by invoking this function.
29025  * Returns ENXIO if there was no registration.
29026  * Returns EBUSY if the ndd variable has not been turned off.
29027  */
29028 int
29029 ip_cgtp_filter_unregister(netstackid_t stackid)
29030 {
29031 	netstack_t *ns;
29032 	ip_stack_t *ipst;
29033 
29034 	ns = netstack_find_by_stackid(stackid);
29035 	if (ns == NULL)
29036 		return (EINVAL);
29037 	ipst = ns->netstack_ip;
29038 	ASSERT(ipst != NULL);
29039 
29040 	if (ipst->ips_ip_cgtp_filter) {
29041 		netstack_rele(ns);
29042 		return (EBUSY);
29043 	}
29044 
29045 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29046 		netstack_rele(ns);
29047 		return (ENXIO);
29048 	}
29049 	ipst->ips_ip_cgtp_filter_ops = NULL;
29050 	netstack_rele(ns);
29051 	return (0);
29052 }
29053 
29054 /*
29055  * Check whether there is a CGTP filter registration.
29056  * Returns non-zero if there is a registration, otherwise returns zero.
29057  * Note: returns zero if bad stackid.
29058  */
29059 int
29060 ip_cgtp_filter_is_registered(netstackid_t stackid)
29061 {
29062 	netstack_t *ns;
29063 	ip_stack_t *ipst;
29064 	int ret;
29065 
29066 	ns = netstack_find_by_stackid(stackid);
29067 	if (ns == NULL)
29068 		return (0);
29069 	ipst = ns->netstack_ip;
29070 	ASSERT(ipst != NULL);
29071 
29072 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29073 		ret = 1;
29074 	else
29075 		ret = 0;
29076 
29077 	netstack_rele(ns);
29078 	return (ret);
29079 }
29080 
29081 static squeue_func_t
29082 ip_squeue_switch(int val)
29083 {
29084 	squeue_func_t rval = squeue_fill;
29085 
29086 	switch (val) {
29087 	case IP_SQUEUE_ENTER_NODRAIN:
29088 		rval = squeue_enter_nodrain;
29089 		break;
29090 	case IP_SQUEUE_ENTER:
29091 		rval = squeue_enter;
29092 		break;
29093 	default:
29094 		break;
29095 	}
29096 	return (rval);
29097 }
29098 
29099 /* ARGSUSED */
29100 static int
29101 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29102     caddr_t addr, cred_t *cr)
29103 {
29104 	int *v = (int *)addr;
29105 	long new_value;
29106 
29107 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29108 		return (EPERM);
29109 
29110 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29111 		return (EINVAL);
29112 
29113 	ip_input_proc = ip_squeue_switch(new_value);
29114 	*v = new_value;
29115 	return (0);
29116 }
29117 
29118 /*
29119  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29120  * ip_debug.
29121  */
29122 /* ARGSUSED */
29123 static int
29124 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29125     caddr_t addr, cred_t *cr)
29126 {
29127 	int *v = (int *)addr;
29128 	long new_value;
29129 
29130 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29131 		return (EPERM);
29132 
29133 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29134 		return (EINVAL);
29135 
29136 	*v = new_value;
29137 	return (0);
29138 }
29139 
29140 /*
29141  * Handle changes to ipmp_hook_emulation ndd variable.
29142  * Need to update phyint_hook_ifindex.
29143  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29144  */
29145 static void
29146 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29147 {
29148 	phyint_t *phyi;
29149 	phyint_t *phyi_tmp;
29150 	char *groupname;
29151 	int namelen;
29152 	ill_t	*ill;
29153 	boolean_t new_group;
29154 
29155 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29156 	/*
29157 	 * Group indicies are stored in the phyint - a common structure
29158 	 * to both IPv4 and IPv6.
29159 	 */
29160 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29161 	for (; phyi != NULL;
29162 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29163 	    phyi, AVL_AFTER)) {
29164 		/* Ignore the ones that do not have a group */
29165 		if (phyi->phyint_groupname_len == 0)
29166 			continue;
29167 
29168 		/*
29169 		 * Look for other phyint in group.
29170 		 * Clear name/namelen so the lookup doesn't find ourselves.
29171 		 */
29172 		namelen = phyi->phyint_groupname_len;
29173 		groupname = phyi->phyint_groupname;
29174 		phyi->phyint_groupname_len = 0;
29175 		phyi->phyint_groupname = NULL;
29176 
29177 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29178 		/* Restore */
29179 		phyi->phyint_groupname_len = namelen;
29180 		phyi->phyint_groupname = groupname;
29181 
29182 		new_group = B_FALSE;
29183 		if (ipst->ips_ipmp_hook_emulation) {
29184 			/*
29185 			 * If the group already exists and has already
29186 			 * been assigned a group ifindex, we use the existing
29187 			 * group_ifindex, otherwise we pick a new group_ifindex
29188 			 * here.
29189 			 */
29190 			if (phyi_tmp != NULL &&
29191 			    phyi_tmp->phyint_group_ifindex != 0) {
29192 				phyi->phyint_group_ifindex =
29193 				    phyi_tmp->phyint_group_ifindex;
29194 			} else {
29195 				/* XXX We need a recovery strategy here. */
29196 				if (!ip_assign_ifindex(
29197 				    &phyi->phyint_group_ifindex, ipst))
29198 					cmn_err(CE_PANIC,
29199 					    "ip_assign_ifindex() failed");
29200 				new_group = B_TRUE;
29201 			}
29202 		} else {
29203 			phyi->phyint_group_ifindex = 0;
29204 		}
29205 		if (ipst->ips_ipmp_hook_emulation)
29206 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29207 		else
29208 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29209 
29210 		/*
29211 		 * For IP Filter to find out the relationship between
29212 		 * names and interface indicies, we need to generate
29213 		 * a NE_PLUMB event when a new group can appear.
29214 		 * We always generate events when a new interface appears
29215 		 * (even when ipmp_hook_emulation is set) so there
29216 		 * is no need to generate NE_PLUMB events when
29217 		 * ipmp_hook_emulation is turned off.
29218 		 * And since it isn't critical for IP Filter to get
29219 		 * the NE_UNPLUMB events we skip those here.
29220 		 */
29221 		if (new_group) {
29222 			/*
29223 			 * First phyint in group - generate group PLUMB event.
29224 			 * Since we are not running inside the ipsq we do
29225 			 * the dispatch immediately.
29226 			 */
29227 			if (phyi->phyint_illv4 != NULL)
29228 				ill = phyi->phyint_illv4;
29229 			else
29230 				ill = phyi->phyint_illv6;
29231 
29232 			if (ill != NULL) {
29233 				mutex_enter(&ill->ill_lock);
29234 				ill_nic_info_plumb(ill, B_TRUE);
29235 				ill_nic_info_dispatch(ill);
29236 				mutex_exit(&ill->ill_lock);
29237 			}
29238 		}
29239 	}
29240 	rw_exit(&ipst->ips_ill_g_lock);
29241 }
29242 
29243 /* ARGSUSED */
29244 static int
29245 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29246     caddr_t addr, cred_t *cr)
29247 {
29248 	int *v = (int *)addr;
29249 	long new_value;
29250 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29251 
29252 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29253 		return (EINVAL);
29254 
29255 	if (*v != new_value) {
29256 		*v = new_value;
29257 		ipmp_hook_emulation_changed(ipst);
29258 	}
29259 	return (0);
29260 }
29261 
29262 static void *
29263 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29264 {
29265 	kstat_t *ksp;
29266 
29267 	ip_stat_t template = {
29268 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29269 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29270 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29271 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29272 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29273 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29274 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29275 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29276 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29277 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29278 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29279 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29280 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29281 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29282 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29283 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29284 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29285 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29286 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29287 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29288 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29289 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29290 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29291 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29292 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29293 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29294 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29295 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29296 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29297 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29298 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29299 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29300 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29301 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29302 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29303 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29304 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29305 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29306 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29307 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29308 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29309 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29310 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29311 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29312 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29313 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29314 	};
29315 
29316 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29317 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29318 	    KSTAT_FLAG_VIRTUAL, stackid);
29319 
29320 	if (ksp == NULL)
29321 		return (NULL);
29322 
29323 	bcopy(&template, ip_statisticsp, sizeof (template));
29324 	ksp->ks_data = (void *)ip_statisticsp;
29325 	ksp->ks_private = (void *)(uintptr_t)stackid;
29326 
29327 	kstat_install(ksp);
29328 	return (ksp);
29329 }
29330 
29331 static void
29332 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29333 {
29334 	if (ksp != NULL) {
29335 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29336 		kstat_delete_netstack(ksp, stackid);
29337 	}
29338 }
29339 
29340 static void *
29341 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29342 {
29343 	kstat_t	*ksp;
29344 
29345 	ip_named_kstat_t template = {
29346 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29347 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29348 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29349 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29350 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29351 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29352 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29353 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29354 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29355 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29356 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29357 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29358 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29359 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29360 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29361 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29362 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29363 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29364 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29365 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29366 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29367 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29368 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29369 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29370 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29371 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29372 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29373 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29374 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29375 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29376 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29377 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29378 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29379 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29380 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29381 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29382 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29383 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29384 	};
29385 
29386 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29387 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29388 	if (ksp == NULL || ksp->ks_data == NULL)
29389 		return (NULL);
29390 
29391 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29392 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29393 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29394 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29395 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29396 
29397 	template.netToMediaEntrySize.value.i32 =
29398 	    sizeof (mib2_ipNetToMediaEntry_t);
29399 
29400 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29401 
29402 	bcopy(&template, ksp->ks_data, sizeof (template));
29403 	ksp->ks_update = ip_kstat_update;
29404 	ksp->ks_private = (void *)(uintptr_t)stackid;
29405 
29406 	kstat_install(ksp);
29407 	return (ksp);
29408 }
29409 
29410 static void
29411 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29412 {
29413 	if (ksp != NULL) {
29414 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29415 		kstat_delete_netstack(ksp, stackid);
29416 	}
29417 }
29418 
29419 static int
29420 ip_kstat_update(kstat_t *kp, int rw)
29421 {
29422 	ip_named_kstat_t *ipkp;
29423 	mib2_ipIfStatsEntry_t ipmib;
29424 	ill_walk_context_t ctx;
29425 	ill_t *ill;
29426 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29427 	netstack_t	*ns;
29428 	ip_stack_t	*ipst;
29429 
29430 	if (kp == NULL || kp->ks_data == NULL)
29431 		return (EIO);
29432 
29433 	if (rw == KSTAT_WRITE)
29434 		return (EACCES);
29435 
29436 	ns = netstack_find_by_stackid(stackid);
29437 	if (ns == NULL)
29438 		return (-1);
29439 	ipst = ns->netstack_ip;
29440 	if (ipst == NULL) {
29441 		netstack_rele(ns);
29442 		return (-1);
29443 	}
29444 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29445 
29446 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29447 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29448 	ill = ILL_START_WALK_V4(&ctx, ipst);
29449 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29450 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29451 	rw_exit(&ipst->ips_ill_g_lock);
29452 
29453 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29454 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29455 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29456 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29457 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29458 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29459 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29460 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29461 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29462 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29463 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29464 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29465 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29466 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29467 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29468 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29469 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29470 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29471 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29472 
29473 	ipkp->routingDiscards.value.ui32 =	0;
29474 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29475 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29476 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29477 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29478 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29479 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29480 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29481 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29482 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29483 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29484 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29485 
29486 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29487 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29488 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29489 
29490 	netstack_rele(ns);
29491 
29492 	return (0);
29493 }
29494 
29495 static void *
29496 icmp_kstat_init(netstackid_t stackid)
29497 {
29498 	kstat_t	*ksp;
29499 
29500 	icmp_named_kstat_t template = {
29501 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29502 		{ "inErrors",		KSTAT_DATA_UINT32 },
29503 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29504 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29505 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29506 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29507 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29508 		{ "inEchos",		KSTAT_DATA_UINT32 },
29509 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29510 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29511 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29512 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29513 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29514 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29515 		{ "outErrors",		KSTAT_DATA_UINT32 },
29516 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29517 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29518 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29519 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29520 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29521 		{ "outEchos",		KSTAT_DATA_UINT32 },
29522 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29523 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29524 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29525 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29526 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29527 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29528 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29529 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29530 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29531 		{ "outDrops",		KSTAT_DATA_UINT32 },
29532 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29533 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29534 	};
29535 
29536 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29537 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29538 	if (ksp == NULL || ksp->ks_data == NULL)
29539 		return (NULL);
29540 
29541 	bcopy(&template, ksp->ks_data, sizeof (template));
29542 
29543 	ksp->ks_update = icmp_kstat_update;
29544 	ksp->ks_private = (void *)(uintptr_t)stackid;
29545 
29546 	kstat_install(ksp);
29547 	return (ksp);
29548 }
29549 
29550 static void
29551 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29552 {
29553 	if (ksp != NULL) {
29554 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29555 		kstat_delete_netstack(ksp, stackid);
29556 	}
29557 }
29558 
29559 static int
29560 icmp_kstat_update(kstat_t *kp, int rw)
29561 {
29562 	icmp_named_kstat_t *icmpkp;
29563 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29564 	netstack_t	*ns;
29565 	ip_stack_t	*ipst;
29566 
29567 	if ((kp == NULL) || (kp->ks_data == NULL))
29568 		return (EIO);
29569 
29570 	if (rw == KSTAT_WRITE)
29571 		return (EACCES);
29572 
29573 	ns = netstack_find_by_stackid(stackid);
29574 	if (ns == NULL)
29575 		return (-1);
29576 	ipst = ns->netstack_ip;
29577 	if (ipst == NULL) {
29578 		netstack_rele(ns);
29579 		return (-1);
29580 	}
29581 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29582 
29583 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29584 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29585 	icmpkp->inDestUnreachs.value.ui32 =
29586 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29587 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29588 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29589 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29590 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29591 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29592 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29593 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29594 	icmpkp->inTimestampReps.value.ui32 =
29595 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29596 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29597 	icmpkp->inAddrMaskReps.value.ui32 =
29598 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29599 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29600 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29601 	icmpkp->outDestUnreachs.value.ui32 =
29602 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29603 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29604 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29605 	icmpkp->outSrcQuenchs.value.ui32 =
29606 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29607 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29608 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29609 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29610 	icmpkp->outTimestamps.value.ui32 =
29611 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29612 	icmpkp->outTimestampReps.value.ui32 =
29613 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29614 	icmpkp->outAddrMasks.value.ui32 =
29615 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29616 	icmpkp->outAddrMaskReps.value.ui32 =
29617 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29618 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29619 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29620 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29621 	icmpkp->outFragNeeded.value.ui32 =
29622 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29623 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29624 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29625 	icmpkp->inBadRedirects.value.ui32 =
29626 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29627 
29628 	netstack_rele(ns);
29629 	return (0);
29630 }
29631 
29632 /*
29633  * This is the fanout function for raw socket opened for SCTP.  Note
29634  * that it is called after SCTP checks that there is no socket which
29635  * wants a packet.  Then before SCTP handles this out of the blue packet,
29636  * this function is called to see if there is any raw socket for SCTP.
29637  * If there is and it is bound to the correct address, the packet will
29638  * be sent to that socket.  Note that only one raw socket can be bound to
29639  * a port.  This is assured in ipcl_sctp_hash_insert();
29640  */
29641 void
29642 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29643     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29644     zoneid_t zoneid)
29645 {
29646 	conn_t		*connp;
29647 	queue_t		*rq;
29648 	mblk_t		*first_mp;
29649 	boolean_t	secure;
29650 	ip6_t		*ip6h;
29651 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29652 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29653 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29654 	boolean_t	sctp_csum_err = B_FALSE;
29655 
29656 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29657 		sctp_csum_err = B_TRUE;
29658 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29659 	}
29660 
29661 	first_mp = mp;
29662 	if (mctl_present) {
29663 		mp = first_mp->b_cont;
29664 		secure = ipsec_in_is_secure(first_mp);
29665 		ASSERT(mp != NULL);
29666 	} else {
29667 		secure = B_FALSE;
29668 	}
29669 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29670 
29671 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29672 	if (connp == NULL) {
29673 		/*
29674 		 * Although raw sctp is not summed, OOB chunks must be.
29675 		 * Drop the packet here if the sctp checksum failed.
29676 		 */
29677 		if (sctp_csum_err) {
29678 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29679 			freemsg(first_mp);
29680 			return;
29681 		}
29682 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29683 		return;
29684 	}
29685 	rq = connp->conn_rq;
29686 	if (!canputnext(rq)) {
29687 		CONN_DEC_REF(connp);
29688 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29689 		freemsg(first_mp);
29690 		return;
29691 	}
29692 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29693 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29694 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29695 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29696 		if (first_mp == NULL) {
29697 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29698 			CONN_DEC_REF(connp);
29699 			return;
29700 		}
29701 	}
29702 	/*
29703 	 * We probably should not send M_CTL message up to
29704 	 * raw socket.
29705 	 */
29706 	if (mctl_present)
29707 		freeb(first_mp);
29708 
29709 	/* Initiate IPPF processing here if needed. */
29710 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29711 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29712 		ip_process(IPP_LOCAL_IN, &mp,
29713 		    recv_ill->ill_phyint->phyint_ifindex);
29714 		if (mp == NULL) {
29715 			CONN_DEC_REF(connp);
29716 			return;
29717 		}
29718 	}
29719 
29720 	if (connp->conn_recvif || connp->conn_recvslla ||
29721 	    ((connp->conn_ip_recvpktinfo ||
29722 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29723 	    (flags & IP_FF_IPINFO))) {
29724 		int in_flags = 0;
29725 
29726 		/*
29727 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29728 		 * IPF_RECVIF.
29729 		 */
29730 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29731 			in_flags = IPF_RECVIF;
29732 		}
29733 		if (connp->conn_recvslla) {
29734 			in_flags |= IPF_RECVSLLA;
29735 		}
29736 		if (isv4) {
29737 			mp = ip_add_info(mp, recv_ill, in_flags,
29738 			    IPCL_ZONEID(connp), ipst);
29739 		} else {
29740 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29741 			if (mp == NULL) {
29742 				BUMP_MIB(recv_ill->ill_ip_mib,
29743 				    ipIfStatsInDiscards);
29744 				CONN_DEC_REF(connp);
29745 				return;
29746 			}
29747 		}
29748 	}
29749 
29750 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29751 	/*
29752 	 * We are sending the IPSEC_IN message also up. Refer
29753 	 * to comments above this function.
29754 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29755 	 */
29756 	(connp->conn_recv)(connp, mp, NULL);
29757 	CONN_DEC_REF(connp);
29758 }
29759 
29760 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29761 {									\
29762 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29763 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29764 }
29765 /*
29766  * This function should be called only if all packet processing
29767  * including fragmentation is complete. Callers of this function
29768  * must set mp->b_prev to one of these values:
29769  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29770  * prior to handing over the mp as first argument to this function.
29771  *
29772  * If the ire passed by caller is incomplete, this function
29773  * queues the packet and if necessary, sends ARP request and bails.
29774  * If the ire passed is fully resolved, we simply prepend
29775  * the link-layer header to the packet, do ipsec hw acceleration
29776  * work if necessary, and send the packet out on the wire.
29777  *
29778  * NOTE: IPsec will only call this function with fully resolved
29779  * ires if hw acceleration is involved.
29780  * TODO list :
29781  * 	a Handle M_MULTIDATA so that
29782  *	  tcp_multisend->tcp_multisend_data can
29783  *	  call ip_xmit_v4 directly
29784  *	b Handle post-ARP work for fragments so that
29785  *	  ip_wput_frag can call this function.
29786  */
29787 ipxmit_state_t
29788 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29789 {
29790 	nce_t		*arpce;
29791 	queue_t		*q;
29792 	int		ill_index;
29793 	mblk_t		*nxt_mp, *first_mp;
29794 	boolean_t	xmit_drop = B_FALSE;
29795 	ip_proc_t	proc;
29796 	ill_t		*out_ill;
29797 	int		pkt_len;
29798 
29799 	arpce = ire->ire_nce;
29800 	ASSERT(arpce != NULL);
29801 
29802 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29803 
29804 	mutex_enter(&arpce->nce_lock);
29805 	switch (arpce->nce_state) {
29806 	case ND_REACHABLE:
29807 		/* If there are other queued packets, queue this packet */
29808 		if (arpce->nce_qd_mp != NULL) {
29809 			if (mp != NULL)
29810 				nce_queue_mp_common(arpce, mp, B_FALSE);
29811 			mp = arpce->nce_qd_mp;
29812 		}
29813 		arpce->nce_qd_mp = NULL;
29814 		mutex_exit(&arpce->nce_lock);
29815 
29816 		/*
29817 		 * Flush the queue.  In the common case, where the
29818 		 * ARP is already resolved,  it will go through the
29819 		 * while loop only once.
29820 		 */
29821 		while (mp != NULL) {
29822 
29823 			nxt_mp = mp->b_next;
29824 			mp->b_next = NULL;
29825 			ASSERT(mp->b_datap->db_type != M_CTL);
29826 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29827 			/*
29828 			 * This info is needed for IPQOS to do COS marking
29829 			 * in ip_wput_attach_llhdr->ip_process.
29830 			 */
29831 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29832 			mp->b_prev = NULL;
29833 
29834 			/* set up ill index for outbound qos processing */
29835 			out_ill = ire_to_ill(ire);
29836 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29837 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29838 			    ill_index);
29839 			if (first_mp == NULL) {
29840 				xmit_drop = B_TRUE;
29841 				BUMP_MIB(out_ill->ill_ip_mib,
29842 				    ipIfStatsOutDiscards);
29843 				goto next_mp;
29844 			}
29845 			/* non-ipsec hw accel case */
29846 			if (io == NULL || !io->ipsec_out_accelerated) {
29847 				/* send it */
29848 				q = ire->ire_stq;
29849 				if (proc == IPP_FWD_OUT) {
29850 					UPDATE_IB_PKT_COUNT(ire);
29851 				} else {
29852 					UPDATE_OB_PKT_COUNT(ire);
29853 				}
29854 				ire->ire_last_used_time = lbolt;
29855 
29856 				if (flow_ctl_enabled || canputnext(q)) {
29857 					if (proc == IPP_FWD_OUT) {
29858 
29859 					BUMP_MIB(out_ill->ill_ip_mib,
29860 					    ipIfStatsHCOutForwDatagrams);
29861 
29862 					}
29863 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29864 					    pkt_len);
29865 
29866 					putnext(q, first_mp);
29867 				} else {
29868 					BUMP_MIB(out_ill->ill_ip_mib,
29869 					    ipIfStatsOutDiscards);
29870 					xmit_drop = B_TRUE;
29871 					freemsg(first_mp);
29872 				}
29873 			} else {
29874 				/*
29875 				 * Safety Pup says: make sure this
29876 				 *  is going to the right interface!
29877 				 */
29878 				ill_t *ill1 =
29879 				    (ill_t *)ire->ire_stq->q_ptr;
29880 				int ifindex =
29881 				    ill1->ill_phyint->phyint_ifindex;
29882 				if (ifindex !=
29883 				    io->ipsec_out_capab_ill_index) {
29884 					xmit_drop = B_TRUE;
29885 					freemsg(mp);
29886 				} else {
29887 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29888 					    pkt_len);
29889 					ipsec_hw_putnext(ire->ire_stq, mp);
29890 				}
29891 			}
29892 next_mp:
29893 			mp = nxt_mp;
29894 		} /* while (mp != NULL) */
29895 		if (xmit_drop)
29896 			return (SEND_FAILED);
29897 		else
29898 			return (SEND_PASSED);
29899 
29900 	case ND_INITIAL:
29901 	case ND_INCOMPLETE:
29902 
29903 		/*
29904 		 * While we do send off packets to dests that
29905 		 * use fully-resolved CGTP routes, we do not
29906 		 * handle unresolved CGTP routes.
29907 		 */
29908 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29909 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29910 
29911 		if (mp != NULL) {
29912 			/* queue the packet */
29913 			nce_queue_mp_common(arpce, mp, B_FALSE);
29914 		}
29915 
29916 		if (arpce->nce_state == ND_INCOMPLETE) {
29917 			mutex_exit(&arpce->nce_lock);
29918 			DTRACE_PROBE3(ip__xmit__incomplete,
29919 			    (ire_t *), ire, (mblk_t *), mp,
29920 			    (ipsec_out_t *), io);
29921 			return (LOOKUP_IN_PROGRESS);
29922 		}
29923 
29924 		arpce->nce_state = ND_INCOMPLETE;
29925 		mutex_exit(&arpce->nce_lock);
29926 		/*
29927 		 * Note that ire_add() (called from ire_forward())
29928 		 * holds a ref on the ire until ARP is completed.
29929 		 */
29930 
29931 		ire_arpresolve(ire, ire_to_ill(ire));
29932 		return (LOOKUP_IN_PROGRESS);
29933 	default:
29934 		ASSERT(0);
29935 		mutex_exit(&arpce->nce_lock);
29936 		return (LLHDR_RESLV_FAILED);
29937 	}
29938 }
29939 
29940 #undef	UPDATE_IP_MIB_OB_COUNTERS
29941 
29942 /*
29943  * Return B_TRUE if the buffers differ in length or content.
29944  * This is used for comparing extension header buffers.
29945  * Note that an extension header would be declared different
29946  * even if all that changed was the next header value in that header i.e.
29947  * what really changed is the next extension header.
29948  */
29949 boolean_t
29950 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29951     uint_t blen)
29952 {
29953 	if (!b_valid)
29954 		blen = 0;
29955 
29956 	if (alen != blen)
29957 		return (B_TRUE);
29958 	if (alen == 0)
29959 		return (B_FALSE);	/* Both zero length */
29960 	return (bcmp(abuf, bbuf, alen));
29961 }
29962 
29963 /*
29964  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29965  * Return B_FALSE if memory allocation fails - don't change any state!
29966  */
29967 boolean_t
29968 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29969     const void *src, uint_t srclen)
29970 {
29971 	void *dst;
29972 
29973 	if (!src_valid)
29974 		srclen = 0;
29975 
29976 	ASSERT(*dstlenp == 0);
29977 	if (src != NULL && srclen != 0) {
29978 		dst = mi_alloc(srclen, BPRI_MED);
29979 		if (dst == NULL)
29980 			return (B_FALSE);
29981 	} else {
29982 		dst = NULL;
29983 	}
29984 	if (*dstp != NULL)
29985 		mi_free(*dstp);
29986 	*dstp = dst;
29987 	*dstlenp = dst == NULL ? 0 : srclen;
29988 	return (B_TRUE);
29989 }
29990 
29991 /*
29992  * Replace what is in *dst, *dstlen with the source.
29993  * Assumes ip_allocbuf has already been called.
29994  */
29995 void
29996 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29997     const void *src, uint_t srclen)
29998 {
29999 	if (!src_valid)
30000 		srclen = 0;
30001 
30002 	ASSERT(*dstlenp == srclen);
30003 	if (src != NULL && srclen != 0)
30004 		bcopy(src, *dstp, srclen);
30005 }
30006 
30007 /*
30008  * Free the storage pointed to by the members of an ip6_pkt_t.
30009  */
30010 void
30011 ip6_pkt_free(ip6_pkt_t *ipp)
30012 {
30013 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30014 
30015 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30016 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30017 		ipp->ipp_hopopts = NULL;
30018 		ipp->ipp_hopoptslen = 0;
30019 	}
30020 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30021 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30022 		ipp->ipp_rtdstopts = NULL;
30023 		ipp->ipp_rtdstoptslen = 0;
30024 	}
30025 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30026 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30027 		ipp->ipp_dstopts = NULL;
30028 		ipp->ipp_dstoptslen = 0;
30029 	}
30030 	if (ipp->ipp_fields & IPPF_RTHDR) {
30031 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30032 		ipp->ipp_rthdr = NULL;
30033 		ipp->ipp_rthdrlen = 0;
30034 	}
30035 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30036 	    IPPF_RTHDR);
30037 }
30038