xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision 2f79bea12c9814c8829dad82312f3c944423bcce)
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 <sys/mac.h>
60 #include <net/if.h>
61 #include <net/if_arp.h>
62 #include <net/route.h>
63 #include <sys/sockio.h>
64 #include <netinet/in.h>
65 #include <net/if_dl.h>
66 
67 #include <inet/common.h>
68 #include <inet/mi.h>
69 #include <inet/mib2.h>
70 #include <inet/nd.h>
71 #include <inet/arp.h>
72 #include <inet/snmpcom.h>
73 #include <inet/optcom.h>
74 #include <inet/kstatcom.h>
75 
76 #include <netinet/igmp_var.h>
77 #include <netinet/ip6.h>
78 #include <netinet/icmp6.h>
79 #include <netinet/sctp.h>
80 
81 #include <inet/ip.h>
82 #include <inet/ip_impl.h>
83 #include <inet/ip6.h>
84 #include <inet/ip6_asp.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <inet/ip_multi.h>
88 #include <inet/ip_if.h>
89 #include <inet/ip_ire.h>
90 #include <inet/ip_ftable.h>
91 #include <inet/ip_rts.h>
92 #include <inet/ip_ndp.h>
93 #include <inet/ip_listutils.h>
94 #include <netinet/igmp.h>
95 #include <netinet/ip_mroute.h>
96 #include <inet/ipp_common.h>
97 
98 #include <net/pfkeyv2.h>
99 #include <inet/ipsec_info.h>
100 #include <inet/sadb.h>
101 #include <inet/ipsec_impl.h>
102 #include <sys/iphada.h>
103 #include <inet/tun.h>
104 #include <inet/ipdrop.h>
105 #include <inet/ip_netinfo.h>
106 
107 #include <sys/ethernet.h>
108 #include <net/if_types.h>
109 #include <sys/cpuvar.h>
110 
111 #include <ipp/ipp.h>
112 #include <ipp/ipp_impl.h>
113 #include <ipp/ipgpc/ipgpc.h>
114 
115 #include <sys/multidata.h>
116 #include <sys/pattr.h>
117 
118 #include <inet/ipclassifier.h>
119 #include <inet/sctp_ip.h>
120 #include <inet/sctp/sctp_impl.h>
121 #include <inet/udp_impl.h>
122 #include <inet/rawip_impl.h>
123 #include <inet/rts_impl.h>
124 #include <sys/sunddi.h>
125 
126 #include <sys/tsol/label.h>
127 #include <sys/tsol/tnet.h>
128 
129 #include <rpc/pmap_prot.h>
130 
131 /*
132  * Values for squeue switch:
133  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
134  * IP_SQUEUE_ENTER: squeue_enter
135  * IP_SQUEUE_FILL: squeue_fill
136  */
137 int ip_squeue_enter = 2;	/* Setable in /etc/system */
138 
139 squeue_func_t ip_input_proc;
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 /*
143  * Setable in /etc/system
144  */
145 int ip_poll_normal_ms = 100;
146 int ip_poll_normal_ticks = 0;
147 int ip_modclose_ackwait_ms = 3000;
148 
149 /*
150  * It would be nice to have these present only in DEBUG systems, but the
151  * current design of the global symbol checking logic requires them to be
152  * unconditionally present.
153  */
154 uint_t ip_thread_data;			/* TSD key for debug support */
155 krwlock_t ip_thread_rwlock;
156 list_t	ip_thread_list;
157 
158 /*
159  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
160  */
161 
162 struct listptr_s {
163 	mblk_t	*lp_head;	/* pointer to the head of the list */
164 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
165 };
166 
167 typedef struct listptr_s listptr_t;
168 
169 /*
170  * This is used by ip_snmp_get_mib2_ip_route_media and
171  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
172  */
173 typedef struct iproutedata_s {
174 	uint_t		ird_idx;
175 	listptr_t	ird_route;	/* ipRouteEntryTable */
176 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
177 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
178 } iproutedata_t;
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
199     uint8_t *laddrp, uint8_t *faddrp) = NULL;
200 
201 /*
202  * Synchronization notes:
203  *
204  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
205  * MT level protection given by STREAMS. IP uses a combination of its own
206  * internal serialization mechanism and standard Solaris locking techniques.
207  * The internal serialization is per phyint (no IPMP) or per IPMP group.
208  * This is used to serialize plumbing operations, IPMP operations, certain
209  * multicast operations, most set ioctls, igmp/mld timers etc.
210  *
211  * Plumbing is a long sequence of operations involving message
212  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
213  * involved in plumbing operations. A natural model is to serialize these
214  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
215  * parallel without any interference. But various set ioctls on hme0 are best
216  * serialized. However if the system uses IPMP, the operations are easier if
217  * they are serialized on a per IPMP group basis since IPMP operations
218  * happen across ill's of a group. Thus the lowest common denominator is to
219  * serialize most set ioctls, multicast join/leave operations, IPMP operations
220  * igmp/mld timer operations, and processing of DLPI control messages received
221  * from drivers on a per IPMP group basis. If the system does not employ
222  * IPMP the serialization is on a per phyint basis. This serialization is
223  * provided by the ipsq_t and primitives operating on this. Details can
224  * be found in ip_if.c above the core primitives operating on ipsq_t.
225  *
226  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
227  * Simiarly lookup of an ire by a thread also returns a refheld ire.
228  * In addition ipif's and ill's referenced by the ire are also indirectly
229  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
230  * the ipif's address or netmask change as long as an ipif is refheld
231  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
232  * address of an ipif has to go through the ipsq_t. This ensures that only
233  * 1 such exclusive operation proceeds at any time on the ipif. It then
234  * deletes all ires associated with this ipif, and waits for all refcnts
235  * associated with this ipif to come down to zero. The address is changed
236  * only after the ipif has been quiesced. Then the ipif is brought up again.
237  * More details are described above the comment in ip_sioctl_flags.
238  *
239  * Packet processing is based mostly on IREs and are fully multi-threaded
240  * using standard Solaris MT techniques.
241  *
242  * There are explicit locks in IP to handle:
243  * - The ip_g_head list maintained by mi_open_link() and friends.
244  *
245  * - The reassembly data structures (one lock per hash bucket)
246  *
247  * - conn_lock is meant to protect conn_t fields. The fields actually
248  *   protected by conn_lock are documented in the conn_t definition.
249  *
250  * - ire_lock to protect some of the fields of the ire, IRE tables
251  *   (one lock per hash bucket). Refer to ip_ire.c for details.
252  *
253  * - ndp_g_lock and nce_lock for protecting NCEs.
254  *
255  * - ill_lock protects fields of the ill and ipif. Details in ip.h
256  *
257  * - ill_g_lock: This is a global reader/writer lock. Protects the following
258  *	* The AVL tree based global multi list of all ills.
259  *	* The linked list of all ipifs of an ill
260  *	* The <ill-ipsq> mapping
261  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
262  *	* The illgroup list threaded by ill_group_next.
263  *	* <ill-phyint> association
264  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
265  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
266  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
267  *   will all have to hold the ill_g_lock as writer for the actual duration
268  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
269  *   may be found in the IPMP section.
270  *
271  * - ill_lock:  This is a per ill mutex.
272  *   It protects some members of the ill and is documented below.
273  *   It also protects the <ill-ipsq> mapping
274  *   It also protects the illgroup list threaded by ill_group_next.
275  *   It also protects the <ill-phyint> assoc.
276  *   It also protects the list of ipifs hanging off the ill.
277  *
278  * - ipsq_lock: This is a per ipsq_t mutex lock.
279  *   This protects all the other members of the ipsq struct except
280  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
281  *
282  * - illgrp_lock: This is a per ill_group mutex lock.
283  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
284  *   which dictates which is the next ill in an ill_group that is to be chosen
285  *   for sending outgoing packets, through creation of an IRE_CACHE that
286  *   references this ill.
287  *
288  * - phyint_lock: This is a per phyint mutex lock. Protects just the
289  *   phyint_flags
290  *
291  * - ip_g_nd_lock: This is a global reader/writer lock.
292  *   Any call to nd_load to load a new parameter to the ND table must hold the
293  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
294  *   as reader.
295  *
296  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
297  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
298  *   uniqueness check also done atomically.
299  *
300  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
301  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
302  *   as a writer when adding or deleting elements from these lists, and
303  *   as a reader when walking these lists to send a SADB update to the
304  *   IPsec capable ills.
305  *
306  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
307  *   group list linked by ill_usesrc_grp_next. It also protects the
308  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
309  *   group is being added or deleted.  This lock is taken as a reader when
310  *   walking the list/group(eg: to get the number of members in a usesrc group).
311  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
312  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
313  *   example, it is not necessary to take this lock in the initial portion
314  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
315  *   ip_sioctl_flags since the these operations are executed exclusively and
316  *   that ensures that the "usesrc group state" cannot change. The "usesrc
317  *   group state" change can happen only in the latter part of
318  *   ip_sioctl_slifusesrc and in ill_delete.
319  *
320  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
321  *
322  * To change the <ill-phyint> association, the ill_g_lock must be held
323  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
324  * must be held.
325  *
326  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
327  * and the ill_lock of the ill in question must be held.
328  *
329  * To change the <ill-illgroup> association the ill_g_lock must be held as
330  * writer and the ill_lock of the ill in question must be held.
331  *
332  * To add or delete an ipif from the list of ipifs hanging off the ill,
333  * ill_g_lock (writer) and ill_lock must be held and the thread must be
334  * a writer on the associated ipsq,.
335  *
336  * To add or delete an ill to the system, the ill_g_lock must be held as
337  * writer and the thread must be a writer on the associated ipsq.
338  *
339  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
340  * must be a writer on the associated ipsq.
341  *
342  * Lock hierarchy
343  *
344  * Some lock hierarchy scenarios are listed below.
345  *
346  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
347  * ill_g_lock -> illgrp_lock -> ill_lock
348  * ill_g_lock -> ill_lock(s) -> phyint_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
350  * ill_g_lock -> ip_addr_avail_lock
351  * conn_lock -> irb_lock -> ill_lock -> ire_lock
352  * ill_g_lock -> ip_g_nd_lock
353  *
354  * When more than 1 ill lock is needed to be held, all ill lock addresses
355  * are sorted on address and locked starting from highest addressed lock
356  * downward.
357  *
358  * IPsec scenarios
359  *
360  * ipsa_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
362  * ipsec_capab_ills_lock -> ipsa_lock
363  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
364  *
365  * Trusted Solaris scenarios
366  *
367  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
368  * igsa_lock -> gcdb_lock
369  * gcgrp_rwlock -> ire_lock
370  * gcgrp_rwlock -> gcdb_lock
371  *
372  *
373  * Routing/forwarding table locking notes:
374  *
375  * Lock acquisition order: Radix tree lock, irb_lock.
376  * Requirements:
377  * i.  Walker must not hold any locks during the walker callback.
378  * ii  Walker must not see a truncated tree during the walk because of any node
379  *     deletion.
380  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
381  *     in many places in the code to walk the irb list. Thus even if all the
382  *     ires in a bucket have been deleted, we still can't free the radix node
383  *     until the ires have actually been inactive'd (freed).
384  *
385  * Tree traversal - Need to hold the global tree lock in read mode.
386  * Before dropping the global tree lock, need to either increment the ire_refcnt
387  * to ensure that the radix node can't be deleted.
388  *
389  * Tree add - Need to hold the global tree lock in write mode to add a
390  * radix node. To prevent the node from being deleted, increment the
391  * irb_refcnt, after the node is added to the tree. The ire itself is
392  * added later while holding the irb_lock, but not the tree lock.
393  *
394  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
395  * All associated ires must be inactive (i.e. freed), and irb_refcnt
396  * must be zero.
397  *
398  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
399  * global tree lock (read mode) for traversal.
400  *
401  * IPsec notes :
402  *
403  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
404  * in front of the actual packet. For outbound datagrams, the M_CTL
405  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
406  * information used by the IPsec code for applying the right level of
407  * protection. The information initialized by IP in the ipsec_out_t
408  * is determined by the per-socket policy or global policy in the system.
409  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
410  * ipsec_info.h) which starts out with nothing in it. It gets filled
411  * with the right information if it goes through the AH/ESP code, which
412  * happens if the incoming packet is secure. The information initialized
413  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
414  * the policy requirements needed by per-socket policy or global policy
415  * is met or not.
416  *
417  * If there is both per-socket policy (set using setsockopt) and there
418  * is also global policy match for the 5 tuples of the socket,
419  * ipsec_override_policy() makes the decision of which one to use.
420  *
421  * For fully connected sockets i.e dst, src [addr, port] is known,
422  * conn_policy_cached is set indicating that policy has been cached.
423  * conn_in_enforce_policy may or may not be set depending on whether
424  * there is a global policy match or per-socket policy match.
425  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
426  * Once the right policy is set on the conn_t, policy cannot change for
427  * this socket. This makes life simpler for TCP (UDP ?) where
428  * re-transmissions go out with the same policy. For symmetry, policy
429  * is cached for fully connected UDP sockets also. Thus if policy is cached,
430  * it also implies that policy is latched i.e policy cannot change
431  * on these sockets. As we have the right policy on the conn, we don't
432  * have to lookup global policy for every outbound and inbound datagram
433  * and thus serving as an optimization. Note that a global policy change
434  * does not affect fully connected sockets if they have policy. If fully
435  * connected sockets did not have any policy associated with it, global
436  * policy change may affect them.
437  *
438  * IP Flow control notes:
439  *
440  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
441  * cannot be sent down to the driver by IP, because of a canput failure, IP
442  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
443  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
444  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
445  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
446  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
447  * the queued messages, and removes the conn from the drain list, if all
448  * messages were drained. It also qenables the next conn in the drain list to
449  * continue the drain process.
450  *
451  * In reality the drain list is not a single list, but a configurable number
452  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
453  * list. If the ip_wsrv of the next qenabled conn does not run, because the
454  * stream closes, ip_close takes responsibility to qenable the next conn in
455  * the drain list. The directly called ip_wput path always does a putq, if
456  * it cannot putnext. Thus synchronization problems are handled between
457  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
458  * functions that manipulate this drain list. Furthermore conn_drain_insert
459  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
460  * running on a queue at any time. conn_drain_tail can be simultaneously called
461  * from both ip_wsrv and ip_close.
462  *
463  * IPQOS notes:
464  *
465  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
466  * and IPQoS modules. IPPF includes hooks in IP at different control points
467  * (callout positions) which direct packets to IPQoS modules for policy
468  * processing. Policies, if present, are global.
469  *
470  * The callout positions are located in the following paths:
471  *		o local_in (packets destined for this host)
472  *		o local_out (packets orginating from this host )
473  *		o fwd_in  (packets forwarded by this m/c - inbound)
474  *		o fwd_out (packets forwarded by this m/c - outbound)
475  * Hooks at these callout points can be enabled/disabled using the ndd variable
476  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
477  * By default all the callout positions are enabled.
478  *
479  * Outbound (local_out)
480  * Hooks are placed in ip_wput_ire and ipsec_out_process.
481  *
482  * Inbound (local_in)
483  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
484  * TCP and UDP fanout routines.
485  *
486  * Forwarding (in and out)
487  * Hooks are placed in ip_rput_forward.
488  *
489  * IP Policy Framework processing (IPPF processing)
490  * Policy processing for a packet is initiated by ip_process, which ascertains
491  * that the classifier (ipgpc) is loaded and configured, failing which the
492  * packet resumes normal processing in IP. If the clasifier is present, the
493  * packet is acted upon by one or more IPQoS modules (action instances), per
494  * filters configured in ipgpc and resumes normal IP processing thereafter.
495  * An action instance can drop a packet in course of its processing.
496  *
497  * A boolean variable, ip_policy, is used in all the fanout routines that can
498  * invoke ip_process for a packet. This variable indicates if the packet should
499  * to be sent for policy processing. The variable is set to B_TRUE by default,
500  * i.e. when the routines are invoked in the normal ip procesing path for a
501  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
502  * ip_policy is set to B_FALSE for all the routines called in these two
503  * functions because, in the former case,  we don't process loopback traffic
504  * currently while in the latter, the packets have already been processed in
505  * icmp_inbound.
506  *
507  * Zones notes:
508  *
509  * The partitioning rules for networking are as follows:
510  * 1) Packets coming from a zone must have a source address belonging to that
511  * zone.
512  * 2) Packets coming from a zone can only be sent on a physical interface on
513  * which the zone has an IP address.
514  * 3) Between two zones on the same machine, packet delivery is only allowed if
515  * there's a matching route for the destination and zone in the forwarding
516  * table.
517  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
518  * different zones can bind to the same port with the wildcard address
519  * (INADDR_ANY).
520  *
521  * The granularity of interface partitioning is at the logical interface level.
522  * Therefore, every zone has its own IP addresses, and incoming packets can be
523  * attributed to a zone unambiguously. A logical interface is placed into a zone
524  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
525  * structure. Rule (1) is implemented by modifying the source address selection
526  * algorithm so that the list of eligible addresses is filtered based on the
527  * sending process zone.
528  *
529  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
530  * across all zones, depending on their type. Here is the break-up:
531  *
532  * IRE type				Shared/exclusive
533  * --------				----------------
534  * IRE_BROADCAST			Exclusive
535  * IRE_DEFAULT (default routes)		Shared (*)
536  * IRE_LOCAL				Exclusive (x)
537  * IRE_LOOPBACK				Exclusive
538  * IRE_PREFIX (net routes)		Shared (*)
539  * IRE_CACHE				Exclusive
540  * IRE_IF_NORESOLVER (interface routes)	Exclusive
541  * IRE_IF_RESOLVER (interface routes)	Exclusive
542  * IRE_HOST (host routes)		Shared (*)
543  *
544  * (*) A zone can only use a default or off-subnet route if the gateway is
545  * directly reachable from the zone, that is, if the gateway's address matches
546  * one of the zone's logical interfaces.
547  *
548  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
549  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
550  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
551  * address of the zone itself (the destination). Since IRE_LOCAL is used
552  * for communication between zones, ip_wput_ire has special logic to set
553  * the right source address when sending using an IRE_LOCAL.
554  *
555  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
556  * ire_cache_lookup restricts loopback using an IRE_LOCAL
557  * between zone to the case when L2 would have conceptually looped the packet
558  * back, i.e. the loopback which is required since neither Ethernet drivers
559  * nor Ethernet hardware loops them back. This is the case when the normal
560  * routes (ignoring IREs with different zoneids) would send out the packet on
561  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
562  * associated.
563  *
564  * Multiple zones can share a common broadcast address; typically all zones
565  * share the 255.255.255.255 address. Incoming as well as locally originated
566  * broadcast packets must be dispatched to all the zones on the broadcast
567  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
568  * since some zones may not be on the 10.16.72/24 network. To handle this, each
569  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
570  * sent to every zone that has an IRE_BROADCAST entry for the destination
571  * address on the input ill, see conn_wantpacket().
572  *
573  * Applications in different zones can join the same multicast group address.
574  * For IPv4, group memberships are per-logical interface, so they're already
575  * inherently part of a zone. For IPv6, group memberships are per-physical
576  * interface, so we distinguish IPv6 group memberships based on group address,
577  * interface and zoneid. In both cases, received multicast packets are sent to
578  * every zone for which a group membership entry exists. On IPv6 we need to
579  * check that the target zone still has an address on the receiving physical
580  * interface; it could have been removed since the application issued the
581  * IPV6_JOIN_GROUP.
582  */
583 
584 /*
585  * Squeue Fanout flags:
586  *	0: No fanout.
587  *	1: Fanout across all squeues
588  */
589 boolean_t	ip_squeue_fanout = 0;
590 
591 /*
592  * Maximum dups allowed per packet.
593  */
594 uint_t ip_max_frag_dups = 10;
595 
596 #define	IS_SIMPLE_IPH(ipha)						\
597 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
598 
599 /* RFC1122 Conformance */
600 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
601 
602 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
603 
604 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
605 
606 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
607 		    cred_t *credp, boolean_t isv6);
608 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
609 
610 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
611 		    ip_stack_t *);
612 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
613 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
614 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
615 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
616 		    mblk_t *, int, ip_stack_t *);
617 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
618 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
619 		    ill_t *, zoneid_t);
620 static void	icmp_options_update(ipha_t *);
621 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
622 		    ip_stack_t *);
623 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
624 		    zoneid_t zoneid, ip_stack_t *);
625 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
626 static void	icmp_redirect(ill_t *, mblk_t *);
627 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
628 		    ip_stack_t *);
629 
630 static void	ip_arp_news(queue_t *, mblk_t *);
631 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
632 		    ip_stack_t *);
633 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
634 char		*ip_dot_addr(ipaddr_t, char *);
635 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
636 int		ip_close(queue_t *, int);
637 static char	*ip_dot_saddr(uchar_t *, char *);
638 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
639 		    boolean_t, boolean_t, ill_t *, zoneid_t);
640 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
641 		    boolean_t, boolean_t, zoneid_t);
642 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
643 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
644 static void	ip_lrput(queue_t *, mblk_t *);
645 ipaddr_t	ip_net_mask(ipaddr_t);
646 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
647 		    ip_stack_t *);
648 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
649 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
650 char		*ip_nv_lookup(nv_t *, int);
651 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
652 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
654 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
655     ipndp_t *, size_t);
656 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
657 void	ip_rput(queue_t *, mblk_t *);
658 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
659 		    void *dummy_arg);
660 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
661 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
662     ip_stack_t *);
663 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
664 			    ire_t *, ip_stack_t *);
665 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
666 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
667 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
668     ip_stack_t *);
669 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
670 		    uint16_t *);
671 int		ip_snmp_get(queue_t *, mblk_t *, int);
672 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
673 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
674 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
675 		    ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
682 		    ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
684 		    ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst);
689 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
702 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
703 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
704 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
705 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
706 static boolean_t	ip_source_route_included(ipha_t *);
707 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
708 
709 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
710 		    zoneid_t, ip_stack_t *);
711 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
712 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
713 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
714 		    zoneid_t, ip_stack_t *);
715 
716 static void	conn_drain_init(ip_stack_t *);
717 static void	conn_drain_fini(ip_stack_t *);
718 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
719 
720 static void	conn_walk_drain(ip_stack_t *);
721 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
722     zoneid_t);
723 
724 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
725 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
726 static void	ip_stack_fini(netstackid_t stackid, void *arg);
727 
728 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
729     zoneid_t);
730 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
731     void *dummy_arg);
732 
733 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
734 
735 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
736     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
737     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
738 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
739 
740 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
741 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
742     caddr_t, cred_t *);
743 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
744     caddr_t cp, cred_t *cr);
745 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
746     cred_t *);
747 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
748     caddr_t cp, cred_t *cr);
749 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
750     cred_t *);
751 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
752     cred_t *);
753 static squeue_func_t ip_squeue_switch(int);
754 
755 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
756 static void	ip_kstat_fini(netstackid_t, kstat_t *);
757 static int	ip_kstat_update(kstat_t *kp, int rw);
758 static void	*icmp_kstat_init(netstackid_t);
759 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
760 static int	icmp_kstat_update(kstat_t *kp, int rw);
761 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
762 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
763 
764 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
765 
766 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
767     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
768 
769 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
770     ipha_t *, ill_t *, boolean_t);
771 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
772 
773 /* How long, in seconds, we allow frags to hang around. */
774 #define	IP_FRAG_TIMEOUT	60
775 
776 /*
777  * Threshold which determines whether MDT should be used when
778  * generating IP fragments; payload size must be greater than
779  * this threshold for MDT to take place.
780  */
781 #define	IP_WPUT_FRAG_MDT_MIN	32768
782 
783 /* Setable in /etc/system only */
784 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
785 
786 static long ip_rput_pullups;
787 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
788 
789 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
790 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
791 
792 int	ip_debug;
793 
794 #ifdef DEBUG
795 uint32_t ipsechw_debug = 0;
796 #endif
797 
798 /*
799  * Multirouting/CGTP stuff
800  */
801 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
802 
803 /*
804  * XXX following really should only be in a header. Would need more
805  * header and .c clean up first.
806  */
807 extern optdb_obj_t	ip_opt_obj;
808 
809 ulong_t ip_squeue_enter_unbound = 0;
810 
811 /*
812  * Named Dispatch Parameter Table.
813  * All of these are alterable, within the min/max values given, at run time.
814  */
815 static ipparam_t	lcl_param_arr[] = {
816 	/* min	max	value	name */
817 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
818 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
819 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
820 	{  0,	1,	0,	"ip_respond_to_timestamp"},
821 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
822 	{  0,	1,	1,	"ip_send_redirects"},
823 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
824 	{  0,	10,	0,	"ip_mrtdebug"},
825 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
826 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
827 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
828 	{  1,	255,	255,	"ip_def_ttl" },
829 	{  0,	1,	0,	"ip_forward_src_routed"},
830 	{  0,	256,	32,	"ip_wroff_extra" },
831 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
832 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
833 	{  0,	1,	1,	"ip_path_mtu_discovery" },
834 	{  0,	240,	30,	"ip_ignore_delete_time" },
835 	{  0,	1,	0,	"ip_ignore_redirect" },
836 	{  0,	1,	1,	"ip_output_queue" },
837 	{  1,	254,	1,	"ip_broadcast_ttl" },
838 	{  0,	99999,	100,	"ip_icmp_err_interval" },
839 	{  1,	99999,	10,	"ip_icmp_err_burst" },
840 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
841 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
842 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
843 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
844 	{  0,	1,	1,	"icmp_accept_clear_messages" },
845 	{  0,	1,	1,	"igmp_accept_clear_messages" },
846 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
847 				"ip_ndp_delay_first_probe_time"},
848 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
849 				"ip_ndp_max_unicast_solicit"},
850 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
851 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
852 	{  0,	1,	0,	"ip6_forward_src_routed"},
853 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
854 	{  0,	1,	1,	"ip6_send_redirects"},
855 	{  0,	1,	0,	"ip6_ignore_redirect" },
856 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
857 
858 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
859 
860 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
861 
862 	{  0,	1,	1,	"pim_accept_clear_messages" },
863 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
864 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
865 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
866 	{  0,	15,	0,	"ip_policy_mask" },
867 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
868 	{  0,	255,	1,	"ip_multirt_ttl" },
869 	{  0,	1,	1,	"ip_multidata_outbound" },
870 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
871 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
872 	{  0,	1000,	1,	"ip_max_temp_defend" },
873 	{  0,	1000,	3,	"ip_max_defend" },
874 	{  0,	999999,	30,	"ip_defend_interval" },
875 	{  0,	3600000, 300000, "ip_dup_recovery" },
876 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
877 	{  0,	1,	1,	"ip_lso_outbound" },
878 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
879 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
880 #ifdef DEBUG
881 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
882 #else
883 	{  0,	0,	0,	"" },
884 #endif
885 };
886 
887 /*
888  * Extended NDP table
889  * The addresses for the first two are filled in to be ips_ip_g_forward
890  * and ips_ipv6_forward at init time.
891  */
892 static ipndp_t	lcl_ndp_arr[] = {
893 	/* getf			setf		data			name */
894 #define	IPNDP_IP_FORWARDING_OFFSET	0
895 	{  ip_param_generic_get,	ip_forward_set,	NULL,
896 	    "ip_forwarding" },
897 #define	IPNDP_IP6_FORWARDING_OFFSET	1
898 	{  ip_param_generic_get,	ip_forward_set,	NULL,
899 	    "ip6_forwarding" },
900 	{  ip_ill_report,	NULL,		NULL,
901 	    "ip_ill_status" },
902 	{  ip_ipif_report,	NULL,		NULL,
903 	    "ip_ipif_status" },
904 	{  ip_ire_report,	NULL,		NULL,
905 	    "ipv4_ire_status" },
906 	{  ip_ire_report_v6,	NULL,		NULL,
907 	    "ipv6_ire_status" },
908 	{  ip_conn_report,	NULL,		NULL,
909 	    "ip_conn_status" },
910 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
911 	    "ip_rput_pullups" },
912 	{  ndp_report,		NULL,		NULL,
913 	    "ip_ndp_cache_report" },
914 	{  ip_srcid_report,	NULL,		NULL,
915 	    "ip_srcid_status" },
916 	{ ip_param_generic_get, ip_squeue_profile_set,
917 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
918 	{ ip_param_generic_get, ip_squeue_bind_set,
919 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
920 	{ ip_param_generic_get, ip_input_proc_set,
921 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
922 	{ ip_param_generic_get, ip_int_set,
923 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
924 #define	IPNDP_CGTP_FILTER_OFFSET	14
925 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
926 	    "ip_cgtp_filter" },
927 	{ ip_param_generic_get, ip_int_set,
928 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
929 #define	IPNDP_IPMP_HOOK_OFFSET	16
930 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
931 	    "ipmp_hook_emulation" },
932 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
933 	    "ip_debug" },
934 };
935 
936 /*
937  * Table of IP ioctls encoding the various properties of the ioctl and
938  * indexed based on the last byte of the ioctl command. Occasionally there
939  * is a clash, and there is more than 1 ioctl with the same last byte.
940  * In such a case 1 ioctl is encoded in the ndx table and the remaining
941  * ioctls are encoded in the misc table. An entry in the ndx table is
942  * retrieved by indexing on the last byte of the ioctl command and comparing
943  * the ioctl command with the value in the ndx table. In the event of a
944  * mismatch the misc table is then searched sequentially for the desired
945  * ioctl command.
946  *
947  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
948  */
949 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
950 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 
961 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
962 			MISC_CMD, ip_siocaddrt, NULL },
963 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
964 			MISC_CMD, ip_siocdelrt, NULL },
965 
966 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
967 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
968 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
969 			IF_CMD, ip_sioctl_get_addr, NULL },
970 
971 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
972 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
973 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
974 			IPI_GET_CMD | IPI_REPL,
975 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
976 
977 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
978 			IPI_PRIV | IPI_WR | IPI_REPL,
979 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
980 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
981 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
982 			IF_CMD, ip_sioctl_get_flags, NULL },
983 
984 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
985 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
986 
987 	/* copyin size cannot be coded for SIOCGIFCONF */
988 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
989 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
990 
991 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
992 			IF_CMD, ip_sioctl_mtu, NULL },
993 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
994 			IF_CMD, ip_sioctl_get_mtu, NULL },
995 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
996 			IPI_GET_CMD | IPI_REPL,
997 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
998 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
999 			IF_CMD, ip_sioctl_brdaddr, NULL },
1000 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1001 			IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_netmask, NULL },
1003 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1004 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1005 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1006 			IPI_GET_CMD | IPI_REPL,
1007 			IF_CMD, ip_sioctl_get_metric, NULL },
1008 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1009 			IF_CMD, ip_sioctl_metric, NULL },
1010 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1011 
1012 	/* See 166-168 below for extended SIOC*XARP ioctls */
1013 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1014 			ARP_CMD, ip_sioctl_arp, NULL },
1015 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1016 			ARP_CMD, ip_sioctl_arp, NULL },
1017 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1018 			ARP_CMD, ip_sioctl_arp, NULL },
1019 
1020 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 
1042 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1043 			MISC_CMD, if_unitsel, if_unitsel_restart },
1044 
1045 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 
1064 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1065 			IPI_PRIV | IPI_WR | IPI_MODOK,
1066 			IF_CMD, ip_sioctl_sifname, NULL },
1067 
1068 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 
1082 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1083 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1084 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_muxid, NULL },
1086 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1087 			IPI_PRIV | IPI_WR | IPI_REPL,
1088 			IF_CMD, ip_sioctl_muxid, NULL },
1089 
1090 	/* Both if and lif variants share same func */
1091 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1092 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1093 	/* Both if and lif variants share same func */
1094 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1095 			IPI_PRIV | IPI_WR | IPI_REPL,
1096 			IF_CMD, ip_sioctl_slifindex, NULL },
1097 
1098 	/* copyin size cannot be coded for SIOCGIFCONF */
1099 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1100 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1101 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 
1119 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1120 			IPI_PRIV | IPI_WR | IPI_REPL,
1121 			LIF_CMD, ip_sioctl_removeif,
1122 			ip_sioctl_removeif_restart },
1123 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1124 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1125 			LIF_CMD, ip_sioctl_addif, NULL },
1126 #define	SIOCLIFADDR_NDX 112
1127 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1128 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1129 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1130 			IPI_GET_CMD | IPI_REPL,
1131 			LIF_CMD, ip_sioctl_get_addr, NULL },
1132 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1133 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1134 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1137 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1138 			IPI_PRIV | IPI_WR | IPI_REPL,
1139 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1140 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1141 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1142 			LIF_CMD, ip_sioctl_get_flags, NULL },
1143 
1144 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 
1147 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1148 			ip_sioctl_get_lifconf, NULL },
1149 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1150 			LIF_CMD, ip_sioctl_mtu, NULL },
1151 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1152 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1153 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1154 			IPI_GET_CMD | IPI_REPL,
1155 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1156 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1157 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1158 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1161 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1162 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1163 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1164 			IPI_GET_CMD | IPI_REPL,
1165 			LIF_CMD, ip_sioctl_get_metric, NULL },
1166 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1167 			LIF_CMD, ip_sioctl_metric, NULL },
1168 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1169 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1170 			LIF_CMD, ip_sioctl_slifname,
1171 			ip_sioctl_slifname_restart },
1172 
1173 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1174 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1175 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1176 			IPI_GET_CMD | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1178 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1179 			IPI_PRIV | IPI_WR | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_muxid, NULL },
1181 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1182 			IPI_GET_CMD | IPI_REPL,
1183 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1184 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1185 			IPI_PRIV | IPI_WR | IPI_REPL,
1186 			LIF_CMD, ip_sioctl_slifindex, 0 },
1187 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1188 			LIF_CMD, ip_sioctl_token, NULL },
1189 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1190 			IPI_GET_CMD | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_get_token, NULL },
1192 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1194 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1197 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1198 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1199 
1200 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1201 			IPI_GET_CMD | IPI_REPL,
1202 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1203 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1204 			LIF_CMD, ip_siocdelndp_v6, NULL },
1205 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1206 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1207 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1208 			LIF_CMD, ip_siocsetndp_v6, NULL },
1209 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1210 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1211 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1212 			MISC_CMD, ip_sioctl_tonlink, NULL },
1213 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1214 			MISC_CMD, ip_sioctl_tmysite, NULL },
1215 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1216 			TUN_CMD, ip_sioctl_tunparam, NULL },
1217 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1218 			IPI_PRIV | IPI_WR,
1219 			TUN_CMD, ip_sioctl_tunparam, NULL },
1220 
1221 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1222 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1223 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1224 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1225 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1226 
1227 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1228 			IPI_PRIV | IPI_WR | IPI_REPL,
1229 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1230 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1233 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1234 			IPI_PRIV | IPI_WR,
1235 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1236 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1237 			IPI_GET_CMD | IPI_REPL,
1238 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1239 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1240 			IPI_GET_CMD | IPI_REPL,
1241 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1242 
1243 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1244 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1245 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1246 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1247 
1248 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1249 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1250 
1251 	/* These are handled in ip_sioctl_copyin_setup itself */
1252 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1253 			MISC_CMD, NULL, NULL },
1254 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1255 			MISC_CMD, NULL, NULL },
1256 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1257 
1258 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1259 			ip_sioctl_get_lifconf, NULL },
1260 
1261 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1262 			XARP_CMD, ip_sioctl_arp, NULL },
1263 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1264 			XARP_CMD, ip_sioctl_arp, NULL },
1265 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1266 			XARP_CMD, ip_sioctl_arp, NULL },
1267 
1268 	/* SIOCPOPSOCKFS is not handled by IP */
1269 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1270 
1271 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1272 			IPI_GET_CMD | IPI_REPL,
1273 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1274 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1275 			IPI_PRIV | IPI_WR | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_slifzone,
1277 			ip_sioctl_slifzone_restart },
1278 	/* 172-174 are SCTP ioctls and not handled by IP */
1279 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1280 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1281 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1282 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1283 			IPI_GET_CMD, LIF_CMD,
1284 			ip_sioctl_get_lifusesrc, 0 },
1285 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1286 			IPI_PRIV | IPI_WR,
1287 			LIF_CMD, ip_sioctl_slifusesrc,
1288 			NULL },
1289 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1290 			ip_sioctl_get_lifsrcof, NULL },
1291 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1292 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1294 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1295 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1296 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1297 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1298 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1299 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1300 			ip_sioctl_set_ipmpfailback, NULL },
1301 	/* SIOCSENABLESDP is handled by SDP */
1302 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1303 };
1304 
1305 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1306 
1307 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1308 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1309 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1310 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1311 		TUN_CMD, ip_sioctl_tunparam, NULL },
1312 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1319 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1320 		MISC_CMD, mrt_ioctl},
1321 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1322 		MISC_CMD, mrt_ioctl},
1323 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1324 		MISC_CMD, mrt_ioctl}
1325 };
1326 
1327 int ip_misc_ioctl_count =
1328     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1329 
1330 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1331 					/* Settable in /etc/system */
1332 /* Defined in ip_ire.c */
1333 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1334 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1335 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1336 
1337 static nv_t	ire_nv_arr[] = {
1338 	{ IRE_BROADCAST, "BROADCAST" },
1339 	{ IRE_LOCAL, "LOCAL" },
1340 	{ IRE_LOOPBACK, "LOOPBACK" },
1341 	{ IRE_CACHE, "CACHE" },
1342 	{ IRE_DEFAULT, "DEFAULT" },
1343 	{ IRE_PREFIX, "PREFIX" },
1344 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1345 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1346 	{ IRE_HOST, "HOST" },
1347 	{ 0 }
1348 };
1349 
1350 nv_t	*ire_nv_tbl = ire_nv_arr;
1351 
1352 /* Defined in ip_netinfo.c */
1353 extern ddi_taskq_t	*eventq_queue_nic;
1354 
1355 /* Simple ICMP IP Header Template */
1356 static ipha_t icmp_ipha = {
1357 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1358 };
1359 
1360 struct module_info ip_mod_info = {
1361 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1362 };
1363 
1364 /*
1365  * Duplicate static symbols within a module confuses mdb; so we avoid the
1366  * problem by making the symbols here distinct from those in udp.c.
1367  */
1368 
1369 /*
1370  * Entry points for IP as a device and as a module.
1371  * FIXME: down the road we might want a separate module and driver qinit.
1372  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1373  */
1374 static struct qinit iprinitv4 = {
1375 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1376 	&ip_mod_info
1377 };
1378 
1379 struct qinit iprinitv6 = {
1380 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1381 	&ip_mod_info
1382 };
1383 
1384 static struct qinit ipwinitv4 = {
1385 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1386 	&ip_mod_info
1387 };
1388 
1389 struct qinit ipwinitv6 = {
1390 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1391 	&ip_mod_info
1392 };
1393 
1394 static struct qinit iplrinit = {
1395 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1396 	&ip_mod_info
1397 };
1398 
1399 static struct qinit iplwinit = {
1400 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1401 	&ip_mod_info
1402 };
1403 
1404 /* For AF_INET aka /dev/ip */
1405 struct streamtab ipinfov4 = {
1406 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1407 };
1408 
1409 /* For AF_INET6 aka /dev/ip6 */
1410 struct streamtab ipinfov6 = {
1411 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1412 };
1413 
1414 #ifdef	DEBUG
1415 static boolean_t skip_sctp_cksum = B_FALSE;
1416 #endif
1417 
1418 /*
1419  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1420  * ip_rput_v6(), ip_output(), etc.  If the message
1421  * block already has a M_CTL at the front of it, then simply set the zoneid
1422  * appropriately.
1423  */
1424 mblk_t *
1425 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1426 {
1427 	mblk_t		*first_mp;
1428 	ipsec_out_t	*io;
1429 
1430 	ASSERT(zoneid != ALL_ZONES);
1431 	if (mp->b_datap->db_type == M_CTL) {
1432 		io = (ipsec_out_t *)mp->b_rptr;
1433 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1434 		io->ipsec_out_zoneid = zoneid;
1435 		return (mp);
1436 	}
1437 
1438 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1439 	if (first_mp == NULL)
1440 		return (NULL);
1441 	io = (ipsec_out_t *)first_mp->b_rptr;
1442 	/* This is not a secure packet */
1443 	io->ipsec_out_secure = B_FALSE;
1444 	io->ipsec_out_zoneid = zoneid;
1445 	first_mp->b_cont = mp;
1446 	return (first_mp);
1447 }
1448 
1449 /*
1450  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1451  */
1452 mblk_t *
1453 ip_copymsg(mblk_t *mp)
1454 {
1455 	mblk_t *nmp;
1456 	ipsec_info_t *in;
1457 
1458 	if (mp->b_datap->db_type != M_CTL)
1459 		return (copymsg(mp));
1460 
1461 	in = (ipsec_info_t *)mp->b_rptr;
1462 
1463 	/*
1464 	 * Note that M_CTL is also used for delivering ICMP error messages
1465 	 * upstream to transport layers.
1466 	 */
1467 	if (in->ipsec_info_type != IPSEC_OUT &&
1468 	    in->ipsec_info_type != IPSEC_IN)
1469 		return (copymsg(mp));
1470 
1471 	nmp = copymsg(mp->b_cont);
1472 
1473 	if (in->ipsec_info_type == IPSEC_OUT) {
1474 		return (ipsec_out_tag(mp, nmp,
1475 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1476 	} else {
1477 		return (ipsec_in_tag(mp, nmp,
1478 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1479 	}
1480 }
1481 
1482 /* Generate an ICMP fragmentation needed message. */
1483 static void
1484 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1485     ip_stack_t *ipst)
1486 {
1487 	icmph_t	icmph;
1488 	mblk_t *first_mp;
1489 	boolean_t mctl_present;
1490 
1491 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1492 
1493 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1494 		if (mctl_present)
1495 			freeb(first_mp);
1496 		return;
1497 	}
1498 
1499 	bzero(&icmph, sizeof (icmph_t));
1500 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1501 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1502 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1503 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1504 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1505 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1506 	    ipst);
1507 }
1508 
1509 /*
1510  * icmp_inbound deals with ICMP messages in the following ways.
1511  *
1512  * 1) It needs to send a reply back and possibly delivering it
1513  *    to the "interested" upper clients.
1514  * 2) It needs to send it to the upper clients only.
1515  * 3) It needs to change some values in IP only.
1516  * 4) It needs to change some values in IP and upper layers e.g TCP.
1517  *
1518  * We need to accomodate icmp messages coming in clear until we get
1519  * everything secure from the wire. If icmp_accept_clear_messages
1520  * is zero we check with the global policy and act accordingly. If
1521  * it is non-zero, we accept the message without any checks. But
1522  * *this does not mean* that this will be delivered to the upper
1523  * clients. By accepting we might send replies back, change our MTU
1524  * value etc. but delivery to the ULP/clients depends on their policy
1525  * dispositions.
1526  *
1527  * We handle the above 4 cases in the context of IPsec in the
1528  * following way :
1529  *
1530  * 1) Send the reply back in the same way as the request came in.
1531  *    If it came in encrypted, it goes out encrypted. If it came in
1532  *    clear, it goes out in clear. Thus, this will prevent chosen
1533  *    plain text attack.
1534  * 2) The client may or may not expect things to come in secure.
1535  *    If it comes in secure, the policy constraints are checked
1536  *    before delivering it to the upper layers. If it comes in
1537  *    clear, ipsec_inbound_accept_clear will decide whether to
1538  *    accept this in clear or not. In both the cases, if the returned
1539  *    message (IP header + 8 bytes) that caused the icmp message has
1540  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1541  *    sending up. If there are only 8 bytes of returned message, then
1542  *    upper client will not be notified.
1543  * 3) Check with global policy to see whether it matches the constaints.
1544  *    But this will be done only if icmp_accept_messages_in_clear is
1545  *    zero.
1546  * 4) If we need to change both in IP and ULP, then the decision taken
1547  *    while affecting the values in IP and while delivering up to TCP
1548  *    should be the same.
1549  *
1550  * 	There are two cases.
1551  *
1552  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1553  *	   failed), we will not deliver it to the ULP, even though they
1554  *	   are *willing* to accept in *clear*. This is fine as our global
1555  *	   disposition to icmp messages asks us reject the datagram.
1556  *
1557  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1558  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1559  *	   to deliver it to ULP (policy failed), it can lead to
1560  *	   consistency problems. The cases known at this time are
1561  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1562  *	   values :
1563  *
1564  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1565  *	     and Upper layer rejects. Then the communication will
1566  *	     come to a stop. This is solved by making similar decisions
1567  *	     at both levels. Currently, when we are unable to deliver
1568  *	     to the Upper Layer (due to policy failures) while IP has
1569  *	     adjusted ire_max_frag, the next outbound datagram would
1570  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1571  *	     will be with the right level of protection. Thus the right
1572  *	     value will be communicated even if we are not able to
1573  *	     communicate when we get from the wire initially. But this
1574  *	     assumes there would be at least one outbound datagram after
1575  *	     IP has adjusted its ire_max_frag value. To make things
1576  *	     simpler, we accept in clear after the validation of
1577  *	     AH/ESP headers.
1578  *
1579  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1580  *	     upper layer depending on the level of protection the upper
1581  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1582  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1583  *	     should be accepted in clear when the Upper layer expects secure.
1584  *	     Thus the communication may get aborted by some bad ICMP
1585  *	     packets.
1586  *
1587  * IPQoS Notes:
1588  * The only instance when a packet is sent for processing is when there
1589  * isn't an ICMP client and if we are interested in it.
1590  * If there is a client, IPPF processing will take place in the
1591  * ip_fanout_proto routine.
1592  *
1593  * Zones notes:
1594  * The packet is only processed in the context of the specified zone: typically
1595  * only this zone will reply to an echo request, and only interested clients in
1596  * this zone will receive a copy of the packet. This means that the caller must
1597  * call icmp_inbound() for each relevant zone.
1598  */
1599 static void
1600 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1601     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1602     ill_t *recv_ill, zoneid_t zoneid)
1603 {
1604 	icmph_t	*icmph;
1605 	ipha_t	*ipha;
1606 	int	iph_hdr_length;
1607 	int	hdr_length;
1608 	boolean_t	interested;
1609 	uint32_t	ts;
1610 	uchar_t	*wptr;
1611 	ipif_t	*ipif;
1612 	mblk_t *first_mp;
1613 	ipsec_in_t *ii;
1614 	ire_t *src_ire;
1615 	boolean_t onlink;
1616 	timestruc_t now;
1617 	uint32_t ill_index;
1618 	ip_stack_t *ipst;
1619 
1620 	ASSERT(ill != NULL);
1621 	ipst = ill->ill_ipst;
1622 
1623 	first_mp = mp;
1624 	if (mctl_present) {
1625 		mp = first_mp->b_cont;
1626 		ASSERT(mp != NULL);
1627 	}
1628 
1629 	ipha = (ipha_t *)mp->b_rptr;
1630 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1631 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1632 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1633 		if (first_mp == NULL)
1634 			return;
1635 	}
1636 
1637 	/*
1638 	 * On a labeled system, we have to check whether the zone itself is
1639 	 * permitted to receive raw traffic.
1640 	 */
1641 	if (is_system_labeled()) {
1642 		if (zoneid == ALL_ZONES)
1643 			zoneid = tsol_packet_to_zoneid(mp);
1644 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1645 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1646 			    zoneid));
1647 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1648 			freemsg(first_mp);
1649 			return;
1650 		}
1651 	}
1652 
1653 	/*
1654 	 * We have accepted the ICMP message. It means that we will
1655 	 * respond to the packet if needed. It may not be delivered
1656 	 * to the upper client depending on the policy constraints
1657 	 * and the disposition in ipsec_inbound_accept_clear.
1658 	 */
1659 
1660 	ASSERT(ill != NULL);
1661 
1662 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1663 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1664 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1665 		/* Last chance to get real. */
1666 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1667 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1668 			freemsg(first_mp);
1669 			return;
1670 		}
1671 		/* Refresh iph following the pullup. */
1672 		ipha = (ipha_t *)mp->b_rptr;
1673 	}
1674 	/* ICMP header checksum, including checksum field, should be zero. */
1675 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1676 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1677 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1678 		freemsg(first_mp);
1679 		return;
1680 	}
1681 	/* The IP header will always be a multiple of four bytes */
1682 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1683 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1684 	    icmph->icmph_code));
1685 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1686 	/* We will set "interested" to "true" if we want a copy */
1687 	interested = B_FALSE;
1688 	switch (icmph->icmph_type) {
1689 	case ICMP_ECHO_REPLY:
1690 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1691 		break;
1692 	case ICMP_DEST_UNREACHABLE:
1693 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1694 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1695 		interested = B_TRUE;	/* Pass up to transport */
1696 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1697 		break;
1698 	case ICMP_SOURCE_QUENCH:
1699 		interested = B_TRUE;	/* Pass up to transport */
1700 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1701 		break;
1702 	case ICMP_REDIRECT:
1703 		if (!ipst->ips_ip_ignore_redirect)
1704 			interested = B_TRUE;
1705 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1706 		break;
1707 	case ICMP_ECHO_REQUEST:
1708 		/*
1709 		 * Whether to respond to echo requests that come in as IP
1710 		 * broadcasts or as IP multicast is subject to debate
1711 		 * (what isn't?).  We aim to please, you pick it.
1712 		 * Default is do it.
1713 		 */
1714 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1715 			/* unicast: always respond */
1716 			interested = B_TRUE;
1717 		} else if (CLASSD(ipha->ipha_dst)) {
1718 			/* multicast: respond based on tunable */
1719 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1720 		} else if (broadcast) {
1721 			/* broadcast: respond based on tunable */
1722 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1723 		}
1724 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1725 		break;
1726 	case ICMP_ROUTER_ADVERTISEMENT:
1727 	case ICMP_ROUTER_SOLICITATION:
1728 		break;
1729 	case ICMP_TIME_EXCEEDED:
1730 		interested = B_TRUE;	/* Pass up to transport */
1731 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1732 		break;
1733 	case ICMP_PARAM_PROBLEM:
1734 		interested = B_TRUE;	/* Pass up to transport */
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1736 		break;
1737 	case ICMP_TIME_STAMP_REQUEST:
1738 		/* Response to Time Stamp Requests is local policy. */
1739 		if (ipst->ips_ip_g_resp_to_timestamp &&
1740 		    /* So is whether to respond if it was an IP broadcast. */
1741 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1742 			int tstamp_len = 3 * sizeof (uint32_t);
1743 
1744 			if (wptr +  tstamp_len > mp->b_wptr) {
1745 				if (!pullupmsg(mp, wptr + tstamp_len -
1746 				    mp->b_rptr)) {
1747 					BUMP_MIB(ill->ill_ip_mib,
1748 					    ipIfStatsInDiscards);
1749 					freemsg(first_mp);
1750 					return;
1751 				}
1752 				/* Refresh ipha following the pullup. */
1753 				ipha = (ipha_t *)mp->b_rptr;
1754 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1755 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1756 			}
1757 			interested = B_TRUE;
1758 		}
1759 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1760 		break;
1761 	case ICMP_TIME_STAMP_REPLY:
1762 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1763 		break;
1764 	case ICMP_INFO_REQUEST:
1765 		/* Per RFC 1122 3.2.2.7, ignore this. */
1766 	case ICMP_INFO_REPLY:
1767 		break;
1768 	case ICMP_ADDRESS_MASK_REQUEST:
1769 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1770 		    !broadcast) &&
1771 		    /* TODO m_pullup of complete header? */
1772 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1773 			interested = B_TRUE;
1774 		}
1775 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1776 		break;
1777 	case ICMP_ADDRESS_MASK_REPLY:
1778 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1779 		break;
1780 	default:
1781 		interested = B_TRUE;	/* Pass up to transport */
1782 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1783 		break;
1784 	}
1785 	/* See if there is an ICMP client. */
1786 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1787 		/* If there is an ICMP client and we want one too, copy it. */
1788 		mblk_t *first_mp1;
1789 
1790 		if (!interested) {
1791 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1792 			    ip_policy, recv_ill, zoneid);
1793 			return;
1794 		}
1795 		first_mp1 = ip_copymsg(first_mp);
1796 		if (first_mp1 != NULL) {
1797 			ip_fanout_proto(q, first_mp1, ill, ipha,
1798 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1799 		}
1800 	} else if (!interested) {
1801 		freemsg(first_mp);
1802 		return;
1803 	} else {
1804 		/*
1805 		 * Initiate policy processing for this packet if ip_policy
1806 		 * is true.
1807 		 */
1808 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1809 			ill_index = ill->ill_phyint->phyint_ifindex;
1810 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1811 			if (mp == NULL) {
1812 				if (mctl_present) {
1813 					freeb(first_mp);
1814 				}
1815 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1816 				return;
1817 			}
1818 		}
1819 	}
1820 	/* We want to do something with it. */
1821 	/* Check db_ref to make sure we can modify the packet. */
1822 	if (mp->b_datap->db_ref > 1) {
1823 		mblk_t	*first_mp1;
1824 
1825 		first_mp1 = ip_copymsg(first_mp);
1826 		freemsg(first_mp);
1827 		if (!first_mp1) {
1828 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1829 			return;
1830 		}
1831 		first_mp = first_mp1;
1832 		if (mctl_present) {
1833 			mp = first_mp->b_cont;
1834 			ASSERT(mp != NULL);
1835 		} else {
1836 			mp = first_mp;
1837 		}
1838 		ipha = (ipha_t *)mp->b_rptr;
1839 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1840 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1841 	}
1842 	switch (icmph->icmph_type) {
1843 	case ICMP_ADDRESS_MASK_REQUEST:
1844 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1845 		if (ipif == NULL) {
1846 			freemsg(first_mp);
1847 			return;
1848 		}
1849 		/*
1850 		 * outging interface must be IPv4
1851 		 */
1852 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1853 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1854 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1855 		ipif_refrele(ipif);
1856 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1857 		break;
1858 	case ICMP_ECHO_REQUEST:
1859 		icmph->icmph_type = ICMP_ECHO_REPLY;
1860 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1861 		break;
1862 	case ICMP_TIME_STAMP_REQUEST: {
1863 		uint32_t *tsp;
1864 
1865 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1866 		tsp = (uint32_t *)wptr;
1867 		tsp++;		/* Skip past 'originate time' */
1868 		/* Compute # of milliseconds since midnight */
1869 		gethrestime(&now);
1870 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1871 		    now.tv_nsec / (NANOSEC / MILLISEC);
1872 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1873 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1874 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1875 		break;
1876 	}
1877 	default:
1878 		ipha = (ipha_t *)&icmph[1];
1879 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1880 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1881 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1882 				freemsg(first_mp);
1883 				return;
1884 			}
1885 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1886 			ipha = (ipha_t *)&icmph[1];
1887 		}
1888 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1889 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1890 			freemsg(first_mp);
1891 			return;
1892 		}
1893 		hdr_length = IPH_HDR_LENGTH(ipha);
1894 		if (hdr_length < sizeof (ipha_t)) {
1895 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1896 			freemsg(first_mp);
1897 			return;
1898 		}
1899 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1900 			if (!pullupmsg(mp,
1901 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1902 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1903 				freemsg(first_mp);
1904 				return;
1905 			}
1906 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1907 			ipha = (ipha_t *)&icmph[1];
1908 		}
1909 		switch (icmph->icmph_type) {
1910 		case ICMP_REDIRECT:
1911 			/*
1912 			 * As there is no upper client to deliver, we don't
1913 			 * need the first_mp any more.
1914 			 */
1915 			if (mctl_present) {
1916 				freeb(first_mp);
1917 			}
1918 			icmp_redirect(ill, mp);
1919 			return;
1920 		case ICMP_DEST_UNREACHABLE:
1921 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1922 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1923 				    zoneid, mp, iph_hdr_length, ipst)) {
1924 					freemsg(first_mp);
1925 					return;
1926 				}
1927 				/*
1928 				 * icmp_inbound_too_big() may alter mp.
1929 				 * Resynch ipha and icmph accordingly.
1930 				 */
1931 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1932 				ipha = (ipha_t *)&icmph[1];
1933 			}
1934 			/* FALLTHRU */
1935 		default :
1936 			/*
1937 			 * IPQoS notes: Since we have already done IPQoS
1938 			 * processing we don't want to do it again in
1939 			 * the fanout routines called by
1940 			 * icmp_inbound_error_fanout, hence the last
1941 			 * argument, ip_policy, is B_FALSE.
1942 			 */
1943 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1944 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1945 			    B_FALSE, recv_ill, zoneid);
1946 		}
1947 		return;
1948 	}
1949 	/* Send out an ICMP packet */
1950 	icmph->icmph_checksum = 0;
1951 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1952 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1953 		ipif_t	*ipif_chosen;
1954 		/*
1955 		 * Make it look like it was directed to us, so we don't look
1956 		 * like a fool with a broadcast or multicast source address.
1957 		 */
1958 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1959 		/*
1960 		 * Make sure that we haven't grabbed an interface that's DOWN.
1961 		 */
1962 		if (ipif != NULL) {
1963 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1964 			    ipha->ipha_src, zoneid);
1965 			if (ipif_chosen != NULL) {
1966 				ipif_refrele(ipif);
1967 				ipif = ipif_chosen;
1968 			}
1969 		}
1970 		if (ipif == NULL) {
1971 			ip0dbg(("icmp_inbound: "
1972 			    "No source for broadcast/multicast:\n"
1973 			    "\tsrc 0x%x dst 0x%x ill %p "
1974 			    "ipif_lcl_addr 0x%x\n",
1975 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1976 			    (void *)ill,
1977 			    ill->ill_ipif->ipif_lcl_addr));
1978 			freemsg(first_mp);
1979 			return;
1980 		}
1981 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1982 		ipha->ipha_dst = ipif->ipif_src_addr;
1983 		ipif_refrele(ipif);
1984 	}
1985 	/* Reset time to live. */
1986 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1987 	{
1988 		/* Swap source and destination addresses */
1989 		ipaddr_t tmp;
1990 
1991 		tmp = ipha->ipha_src;
1992 		ipha->ipha_src = ipha->ipha_dst;
1993 		ipha->ipha_dst = tmp;
1994 	}
1995 	ipha->ipha_ident = 0;
1996 	if (!IS_SIMPLE_IPH(ipha))
1997 		icmp_options_update(ipha);
1998 
1999 	/*
2000 	 * ICMP echo replies should go out on the same interface
2001 	 * the request came on as probes used by in.mpathd for detecting
2002 	 * NIC failures are ECHO packets. We turn-off load spreading
2003 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2004 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2005 	 * function. This is in turn handled by ip_wput and ip_newroute
2006 	 * to make sure that the packet goes out on the interface it came
2007 	 * in on. If we don't turnoff load spreading, the packets might get
2008 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2009 	 * to go out and in.mpathd would wrongly detect a failure or
2010 	 * mis-detect a NIC failure for link failure. As load spreading
2011 	 * can happen only if ill_group is not NULL, we do only for
2012 	 * that case and this does not affect the normal case.
2013 	 *
2014 	 * We turn off load spreading only on echo packets that came from
2015 	 * on-link hosts. If the interface route has been deleted, this will
2016 	 * not be enforced as we can't do much. For off-link hosts, as the
2017 	 * default routes in IPv4 does not typically have an ire_ipif
2018 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2019 	 * Moreover, expecting a default route through this interface may
2020 	 * not be correct. We use ipha_dst because of the swap above.
2021 	 */
2022 	onlink = B_FALSE;
2023 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2024 		/*
2025 		 * First, we need to make sure that it is not one of our
2026 		 * local addresses. If we set onlink when it is one of
2027 		 * our local addresses, we will end up creating IRE_CACHES
2028 		 * for one of our local addresses. Then, we will never
2029 		 * accept packets for them afterwards.
2030 		 */
2031 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2032 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2033 		if (src_ire == NULL) {
2034 			ipif = ipif_get_next_ipif(NULL, ill);
2035 			if (ipif == NULL) {
2036 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2037 				freemsg(mp);
2038 				return;
2039 			}
2040 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2041 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2042 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2043 			ipif_refrele(ipif);
2044 			if (src_ire != NULL) {
2045 				onlink = B_TRUE;
2046 				ire_refrele(src_ire);
2047 			}
2048 		} else {
2049 			ire_refrele(src_ire);
2050 		}
2051 	}
2052 	if (!mctl_present) {
2053 		/*
2054 		 * This packet should go out the same way as it
2055 		 * came in i.e in clear. To make sure that global
2056 		 * policy will not be applied to this in ip_wput_ire,
2057 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2058 		 */
2059 		ASSERT(first_mp == mp);
2060 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2061 		if (first_mp == NULL) {
2062 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2063 			freemsg(mp);
2064 			return;
2065 		}
2066 		ii = (ipsec_in_t *)first_mp->b_rptr;
2067 
2068 		/* This is not a secure packet */
2069 		ii->ipsec_in_secure = B_FALSE;
2070 		if (onlink) {
2071 			ii->ipsec_in_attach_if = B_TRUE;
2072 			ii->ipsec_in_ill_index =
2073 			    ill->ill_phyint->phyint_ifindex;
2074 			ii->ipsec_in_rill_index =
2075 			    recv_ill->ill_phyint->phyint_ifindex;
2076 		}
2077 		first_mp->b_cont = mp;
2078 	} else if (onlink) {
2079 		ii = (ipsec_in_t *)first_mp->b_rptr;
2080 		ii->ipsec_in_attach_if = B_TRUE;
2081 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2082 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2083 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2084 	} else {
2085 		ii = (ipsec_in_t *)first_mp->b_rptr;
2086 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2087 	}
2088 	ii->ipsec_in_zoneid = zoneid;
2089 	ASSERT(zoneid != ALL_ZONES);
2090 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2091 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2092 		return;
2093 	}
2094 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2095 	put(WR(q), first_mp);
2096 }
2097 
2098 static ipaddr_t
2099 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2100 {
2101 	conn_t *connp;
2102 	connf_t *connfp;
2103 	ipaddr_t nexthop_addr = INADDR_ANY;
2104 	int hdr_length = IPH_HDR_LENGTH(ipha);
2105 	uint16_t *up;
2106 	uint32_t ports;
2107 	ip_stack_t *ipst = ill->ill_ipst;
2108 
2109 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2110 	switch (ipha->ipha_protocol) {
2111 		case IPPROTO_TCP:
2112 		{
2113 			tcph_t *tcph;
2114 
2115 			/* do a reverse lookup */
2116 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2117 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2118 			    TCPS_LISTEN, ipst);
2119 			break;
2120 		}
2121 		case IPPROTO_UDP:
2122 		{
2123 			uint32_t dstport, srcport;
2124 
2125 			((uint16_t *)&ports)[0] = up[1];
2126 			((uint16_t *)&ports)[1] = up[0];
2127 
2128 			/* Extract ports in net byte order */
2129 			dstport = htons(ntohl(ports) & 0xFFFF);
2130 			srcport = htons(ntohl(ports) >> 16);
2131 
2132 			connfp = &ipst->ips_ipcl_udp_fanout[
2133 			    IPCL_UDP_HASH(dstport, ipst)];
2134 			mutex_enter(&connfp->connf_lock);
2135 			connp = connfp->connf_head;
2136 
2137 			/* do a reverse lookup */
2138 			while ((connp != NULL) &&
2139 			    (!IPCL_UDP_MATCH(connp, dstport,
2140 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2141 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2142 				connp = connp->conn_next;
2143 			}
2144 			if (connp != NULL)
2145 				CONN_INC_REF(connp);
2146 			mutex_exit(&connfp->connf_lock);
2147 			break;
2148 		}
2149 		case IPPROTO_SCTP:
2150 		{
2151 			in6_addr_t map_src, map_dst;
2152 
2153 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2154 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2155 			((uint16_t *)&ports)[0] = up[1];
2156 			((uint16_t *)&ports)[1] = up[0];
2157 
2158 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2159 			    zoneid, ipst->ips_netstack->netstack_sctp);
2160 			if (connp == NULL) {
2161 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2162 				    zoneid, ports, ipha, ipst);
2163 			} else {
2164 				CONN_INC_REF(connp);
2165 				SCTP_REFRELE(CONN2SCTP(connp));
2166 			}
2167 			break;
2168 		}
2169 		default:
2170 		{
2171 			ipha_t ripha;
2172 
2173 			ripha.ipha_src = ipha->ipha_dst;
2174 			ripha.ipha_dst = ipha->ipha_src;
2175 			ripha.ipha_protocol = ipha->ipha_protocol;
2176 
2177 			connfp = &ipst->ips_ipcl_proto_fanout[
2178 			    ipha->ipha_protocol];
2179 			mutex_enter(&connfp->connf_lock);
2180 			connp = connfp->connf_head;
2181 			for (connp = connfp->connf_head; connp != NULL;
2182 			    connp = connp->conn_next) {
2183 				if (IPCL_PROTO_MATCH(connp,
2184 				    ipha->ipha_protocol, &ripha, ill,
2185 				    0, zoneid)) {
2186 					CONN_INC_REF(connp);
2187 					break;
2188 				}
2189 			}
2190 			mutex_exit(&connfp->connf_lock);
2191 		}
2192 	}
2193 	if (connp != NULL) {
2194 		if (connp->conn_nexthop_set)
2195 			nexthop_addr = connp->conn_nexthop_v4;
2196 		CONN_DEC_REF(connp);
2197 	}
2198 	return (nexthop_addr);
2199 }
2200 
2201 /* Table from RFC 1191 */
2202 static int icmp_frag_size_table[] =
2203 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2204 
2205 /*
2206  * Process received ICMP Packet too big.
2207  * After updating any IRE it does the fanout to any matching transport streams.
2208  * Assumes the message has been pulled up till the IP header that caused
2209  * the error.
2210  *
2211  * Returns B_FALSE on failure and B_TRUE on success.
2212  */
2213 static boolean_t
2214 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2215     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2216     ip_stack_t *ipst)
2217 {
2218 	ire_t	*ire, *first_ire;
2219 	int	mtu;
2220 	int	hdr_length;
2221 	ipaddr_t nexthop_addr;
2222 
2223 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2224 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2225 	ASSERT(ill != NULL);
2226 
2227 	hdr_length = IPH_HDR_LENGTH(ipha);
2228 
2229 	/* Drop if the original packet contained a source route */
2230 	if (ip_source_route_included(ipha)) {
2231 		return (B_FALSE);
2232 	}
2233 	/*
2234 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2235 	 * header.
2236 	 */
2237 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2238 	    mp->b_wptr) {
2239 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2240 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2241 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2242 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2243 			return (B_FALSE);
2244 		}
2245 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2246 		ipha = (ipha_t *)&icmph[1];
2247 	}
2248 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2249 	if (nexthop_addr != INADDR_ANY) {
2250 		/* nexthop set */
2251 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2252 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2253 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2254 	} else {
2255 		/* nexthop not set */
2256 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2257 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2258 	}
2259 
2260 	if (!first_ire) {
2261 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2262 		    ntohl(ipha->ipha_dst)));
2263 		return (B_FALSE);
2264 	}
2265 	/* Check for MTU discovery advice as described in RFC 1191 */
2266 	mtu = ntohs(icmph->icmph_du_mtu);
2267 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2268 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2269 	    ire = ire->ire_next) {
2270 		/*
2271 		 * Look for the connection to which this ICMP message is
2272 		 * directed. If it has the IP_NEXTHOP option set, then the
2273 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2274 		 * option. Else the search is limited to regular IREs.
2275 		 */
2276 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2277 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2278 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2279 		    (nexthop_addr != INADDR_ANY)))
2280 			continue;
2281 
2282 		mutex_enter(&ire->ire_lock);
2283 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2284 			/* Reduce the IRE max frag value as advised. */
2285 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2286 			    mtu, ire->ire_max_frag));
2287 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2288 		} else {
2289 			uint32_t length;
2290 			int	i;
2291 
2292 			/*
2293 			 * Use the table from RFC 1191 to figure out
2294 			 * the next "plateau" based on the length in
2295 			 * the original IP packet.
2296 			 */
2297 			length = ntohs(ipha->ipha_length);
2298 			if (ire->ire_max_frag <= length &&
2299 			    ire->ire_max_frag >= length - hdr_length) {
2300 				/*
2301 				 * Handle broken BSD 4.2 systems that
2302 				 * return the wrong iph_length in ICMP
2303 				 * errors.
2304 				 */
2305 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2306 				    length, ire->ire_max_frag));
2307 				length -= hdr_length;
2308 			}
2309 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2310 				if (length > icmp_frag_size_table[i])
2311 					break;
2312 			}
2313 			if (i == A_CNT(icmp_frag_size_table)) {
2314 				/* Smaller than 68! */
2315 				ip1dbg(("Too big for packet size %d\n",
2316 				    length));
2317 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2318 				ire->ire_frag_flag = 0;
2319 			} else {
2320 				mtu = icmp_frag_size_table[i];
2321 				ip1dbg(("Calculated mtu %d, packet size %d, "
2322 				    "before %d", mtu, length,
2323 				    ire->ire_max_frag));
2324 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2325 				ip1dbg((", after %d\n", ire->ire_max_frag));
2326 			}
2327 			/* Record the new max frag size for the ULP. */
2328 			icmph->icmph_du_zero = 0;
2329 			icmph->icmph_du_mtu =
2330 			    htons((uint16_t)ire->ire_max_frag);
2331 		}
2332 		mutex_exit(&ire->ire_lock);
2333 	}
2334 	rw_exit(&first_ire->ire_bucket->irb_lock);
2335 	ire_refrele(first_ire);
2336 	return (B_TRUE);
2337 }
2338 
2339 /*
2340  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2341  * calls this function.
2342  */
2343 static mblk_t *
2344 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2345 {
2346 	ipha_t *ipha;
2347 	icmph_t *icmph;
2348 	ipha_t *in_ipha;
2349 	int length;
2350 
2351 	ASSERT(mp->b_datap->db_type == M_DATA);
2352 
2353 	/*
2354 	 * For Self-encapsulated packets, we added an extra IP header
2355 	 * without the options. Inner IP header is the one from which
2356 	 * the outer IP header was formed. Thus, we need to remove the
2357 	 * outer IP header. To do this, we pullup the whole message
2358 	 * and overlay whatever follows the outer IP header over the
2359 	 * outer IP header.
2360 	 */
2361 
2362 	if (!pullupmsg(mp, -1))
2363 		return (NULL);
2364 
2365 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2366 	ipha = (ipha_t *)&icmph[1];
2367 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2368 
2369 	/*
2370 	 * The length that we want to overlay is following the inner
2371 	 * IP header. Subtracting the IP header + icmp header + outer
2372 	 * IP header's length should give us the length that we want to
2373 	 * overlay.
2374 	 */
2375 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2376 	    hdr_length;
2377 	/*
2378 	 * Overlay whatever follows the inner header over the
2379 	 * outer header.
2380 	 */
2381 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2382 
2383 	/* Set the wptr to account for the outer header */
2384 	mp->b_wptr -= hdr_length;
2385 	return (mp);
2386 }
2387 
2388 /*
2389  * Try to pass the ICMP message upstream in case the ULP cares.
2390  *
2391  * If the packet that caused the ICMP error is secure, we send
2392  * it to AH/ESP to make sure that the attached packet has a
2393  * valid association. ipha in the code below points to the
2394  * IP header of the packet that caused the error.
2395  *
2396  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2397  * in the context of IPsec. Normally we tell the upper layer
2398  * whenever we send the ire (including ip_bind), the IPsec header
2399  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2400  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2401  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2402  * same thing. As TCP has the IPsec options size that needs to be
2403  * adjusted, we just pass the MTU unchanged.
2404  *
2405  * IFN could have been generated locally or by some router.
2406  *
2407  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2408  *	    This happens because IP adjusted its value of MTU on an
2409  *	    earlier IFN message and could not tell the upper layer,
2410  *	    the new adjusted value of MTU e.g. Packet was encrypted
2411  *	    or there was not enough information to fanout to upper
2412  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2413  *	    generates the IFN, where IPsec processing has *not* been
2414  *	    done.
2415  *
2416  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2417  *	    could have generated this. This happens because ire_max_frag
2418  *	    value in IP was set to a new value, while the IPsec processing
2419  *	    was being done and after we made the fragmentation check in
2420  *	    ip_wput_ire. Thus on return from IPsec processing,
2421  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2422  *	    and generates the IFN. As IPsec processing is over, we fanout
2423  *	    to AH/ESP to remove the header.
2424  *
2425  *	    In both these cases, ipsec_in_loopback will be set indicating
2426  *	    that IFN was generated locally.
2427  *
2428  * ROUTER : IFN could be secure or non-secure.
2429  *
2430  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2431  *	      packet in error has AH/ESP headers to validate the AH/ESP
2432  *	      headers. AH/ESP will verify whether there is a valid SA or
2433  *	      not and send it back. We will fanout again if we have more
2434  *	      data in the packet.
2435  *
2436  *	      If the packet in error does not have AH/ESP, we handle it
2437  *	      like any other case.
2438  *
2439  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2440  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2441  *	      for validation. AH/ESP will verify whether there is a
2442  *	      valid SA or not and send it back. We will fanout again if
2443  *	      we have more data in the packet.
2444  *
2445  *	      If the packet in error does not have AH/ESP, we handle it
2446  *	      like any other case.
2447  */
2448 static void
2449 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2450     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2451     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2452     zoneid_t zoneid)
2453 {
2454 	uint16_t *up;	/* Pointer to ports in ULP header */
2455 	uint32_t ports;	/* reversed ports for fanout */
2456 	ipha_t ripha;	/* With reversed addresses */
2457 	mblk_t *first_mp;
2458 	ipsec_in_t *ii;
2459 	tcph_t	*tcph;
2460 	conn_t	*connp;
2461 	ip_stack_t *ipst;
2462 
2463 	ASSERT(ill != NULL);
2464 
2465 	ASSERT(recv_ill != NULL);
2466 	ipst = recv_ill->ill_ipst;
2467 
2468 	first_mp = mp;
2469 	if (mctl_present) {
2470 		mp = first_mp->b_cont;
2471 		ASSERT(mp != NULL);
2472 
2473 		ii = (ipsec_in_t *)first_mp->b_rptr;
2474 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2475 	} else {
2476 		ii = NULL;
2477 	}
2478 
2479 	switch (ipha->ipha_protocol) {
2480 	case IPPROTO_UDP:
2481 		/*
2482 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2483 		 * transport header.
2484 		 */
2485 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2486 		    mp->b_wptr) {
2487 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2488 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2489 				goto discard_pkt;
2490 			}
2491 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2492 			ipha = (ipha_t *)&icmph[1];
2493 		}
2494 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2495 
2496 		/*
2497 		 * Attempt to find a client stream based on port.
2498 		 * Note that we do a reverse lookup since the header is
2499 		 * in the form we sent it out.
2500 		 * The ripha header is only used for the IP_UDP_MATCH and we
2501 		 * only set the src and dst addresses and protocol.
2502 		 */
2503 		ripha.ipha_src = ipha->ipha_dst;
2504 		ripha.ipha_dst = ipha->ipha_src;
2505 		ripha.ipha_protocol = ipha->ipha_protocol;
2506 		((uint16_t *)&ports)[0] = up[1];
2507 		((uint16_t *)&ports)[1] = up[0];
2508 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2509 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2510 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2511 		    icmph->icmph_type, icmph->icmph_code));
2512 
2513 		/* Have to change db_type after any pullupmsg */
2514 		DB_TYPE(mp) = M_CTL;
2515 
2516 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2517 		    mctl_present, ip_policy, recv_ill, zoneid);
2518 		return;
2519 
2520 	case IPPROTO_TCP:
2521 		/*
2522 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2523 		 * transport header.
2524 		 */
2525 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2526 		    mp->b_wptr) {
2527 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2528 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2529 				goto discard_pkt;
2530 			}
2531 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2532 			ipha = (ipha_t *)&icmph[1];
2533 		}
2534 		/*
2535 		 * Find a TCP client stream for this packet.
2536 		 * Note that we do a reverse lookup since the header is
2537 		 * in the form we sent it out.
2538 		 */
2539 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2540 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2541 		    ipst);
2542 		if (connp == NULL)
2543 			goto discard_pkt;
2544 
2545 		/* Have to change db_type after any pullupmsg */
2546 		DB_TYPE(mp) = M_CTL;
2547 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2548 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2549 		return;
2550 
2551 	case IPPROTO_SCTP:
2552 		/*
2553 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2554 		 * transport header.
2555 		 */
2556 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2557 		    mp->b_wptr) {
2558 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2559 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2560 				goto discard_pkt;
2561 			}
2562 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2563 			ipha = (ipha_t *)&icmph[1];
2564 		}
2565 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2566 		/*
2567 		 * Find a SCTP client stream for this packet.
2568 		 * Note that we do a reverse lookup since the header is
2569 		 * in the form we sent it out.
2570 		 * The ripha header is only used for the matching and we
2571 		 * only set the src and dst addresses, protocol, and version.
2572 		 */
2573 		ripha.ipha_src = ipha->ipha_dst;
2574 		ripha.ipha_dst = ipha->ipha_src;
2575 		ripha.ipha_protocol = ipha->ipha_protocol;
2576 		ripha.ipha_version_and_hdr_length =
2577 		    ipha->ipha_version_and_hdr_length;
2578 		((uint16_t *)&ports)[0] = up[1];
2579 		((uint16_t *)&ports)[1] = up[0];
2580 
2581 		/* Have to change db_type after any pullupmsg */
2582 		DB_TYPE(mp) = M_CTL;
2583 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2584 		    mctl_present, ip_policy, zoneid);
2585 		return;
2586 
2587 	case IPPROTO_ESP:
2588 	case IPPROTO_AH: {
2589 		int ipsec_rc;
2590 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2591 
2592 		/*
2593 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2594 		 * We will re-use the IPSEC_IN if it is already present as
2595 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2596 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2597 		 * one and attach it in the front.
2598 		 */
2599 		if (ii != NULL) {
2600 			/*
2601 			 * ip_fanout_proto_again converts the ICMP errors
2602 			 * that come back from AH/ESP to M_DATA so that
2603 			 * if it is non-AH/ESP and we do a pullupmsg in
2604 			 * this function, it would work. Convert it back
2605 			 * to M_CTL before we send up as this is a ICMP
2606 			 * error. This could have been generated locally or
2607 			 * by some router. Validate the inner IPsec
2608 			 * headers.
2609 			 *
2610 			 * NOTE : ill_index is used by ip_fanout_proto_again
2611 			 * to locate the ill.
2612 			 */
2613 			ASSERT(ill != NULL);
2614 			ii->ipsec_in_ill_index =
2615 			    ill->ill_phyint->phyint_ifindex;
2616 			ii->ipsec_in_rill_index =
2617 			    recv_ill->ill_phyint->phyint_ifindex;
2618 			DB_TYPE(first_mp->b_cont) = M_CTL;
2619 		} else {
2620 			/*
2621 			 * IPSEC_IN is not present. We attach a ipsec_in
2622 			 * message and send up to IPsec for validating
2623 			 * and removing the IPsec headers. Clear
2624 			 * ipsec_in_secure so that when we return
2625 			 * from IPsec, we don't mistakenly think that this
2626 			 * is a secure packet came from the network.
2627 			 *
2628 			 * NOTE : ill_index is used by ip_fanout_proto_again
2629 			 * to locate the ill.
2630 			 */
2631 			ASSERT(first_mp == mp);
2632 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2633 			if (first_mp == NULL) {
2634 				freemsg(mp);
2635 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2636 				return;
2637 			}
2638 			ii = (ipsec_in_t *)first_mp->b_rptr;
2639 
2640 			/* This is not a secure packet */
2641 			ii->ipsec_in_secure = B_FALSE;
2642 			first_mp->b_cont = mp;
2643 			DB_TYPE(mp) = M_CTL;
2644 			ASSERT(ill != NULL);
2645 			ii->ipsec_in_ill_index =
2646 			    ill->ill_phyint->phyint_ifindex;
2647 			ii->ipsec_in_rill_index =
2648 			    recv_ill->ill_phyint->phyint_ifindex;
2649 		}
2650 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2651 
2652 		if (!ipsec_loaded(ipss)) {
2653 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2654 			return;
2655 		}
2656 
2657 		if (ipha->ipha_protocol == IPPROTO_ESP)
2658 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2659 		else
2660 			ipsec_rc = ipsecah_icmp_error(first_mp);
2661 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2662 			return;
2663 
2664 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2665 		return;
2666 	}
2667 	default:
2668 		/*
2669 		 * The ripha header is only used for the lookup and we
2670 		 * only set the src and dst addresses and protocol.
2671 		 */
2672 		ripha.ipha_src = ipha->ipha_dst;
2673 		ripha.ipha_dst = ipha->ipha_src;
2674 		ripha.ipha_protocol = ipha->ipha_protocol;
2675 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2676 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2677 		    ntohl(ipha->ipha_dst),
2678 		    icmph->icmph_type, icmph->icmph_code));
2679 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2680 			ipha_t *in_ipha;
2681 
2682 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2683 			    mp->b_wptr) {
2684 				if (!pullupmsg(mp, (uchar_t *)ipha +
2685 				    hdr_length + sizeof (ipha_t) -
2686 				    mp->b_rptr)) {
2687 					goto discard_pkt;
2688 				}
2689 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2690 				ipha = (ipha_t *)&icmph[1];
2691 			}
2692 			/*
2693 			 * Caller has verified that length has to be
2694 			 * at least the size of IP header.
2695 			 */
2696 			ASSERT(hdr_length >= sizeof (ipha_t));
2697 			/*
2698 			 * Check the sanity of the inner IP header like
2699 			 * we did for the outer header.
2700 			 */
2701 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2702 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2703 				goto discard_pkt;
2704 			}
2705 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2706 				goto discard_pkt;
2707 			}
2708 			/* Check for Self-encapsulated tunnels */
2709 			if (in_ipha->ipha_src == ipha->ipha_src &&
2710 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2711 
2712 				mp = icmp_inbound_self_encap_error(mp,
2713 				    iph_hdr_length, hdr_length);
2714 				if (mp == NULL)
2715 					goto discard_pkt;
2716 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2717 				ipha = (ipha_t *)&icmph[1];
2718 				hdr_length = IPH_HDR_LENGTH(ipha);
2719 				/*
2720 				 * The packet in error is self-encapsualted.
2721 				 * And we are finding it further encapsulated
2722 				 * which we could not have possibly generated.
2723 				 */
2724 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2725 					goto discard_pkt;
2726 				}
2727 				icmp_inbound_error_fanout(q, ill, first_mp,
2728 				    icmph, ipha, iph_hdr_length, hdr_length,
2729 				    mctl_present, ip_policy, recv_ill, zoneid);
2730 				return;
2731 			}
2732 		}
2733 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2734 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2735 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2736 		    ii != NULL &&
2737 		    ii->ipsec_in_loopback &&
2738 		    ii->ipsec_in_secure) {
2739 			/*
2740 			 * For IP tunnels that get a looped-back
2741 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2742 			 * reported new MTU to take into account the IPsec
2743 			 * headers protecting this configured tunnel.
2744 			 *
2745 			 * This allows the tunnel module (tun.c) to blindly
2746 			 * accept the MTU reported in an ICMP "too big"
2747 			 * message.
2748 			 *
2749 			 * Non-looped back ICMP messages will just be
2750 			 * handled by the security protocols (if needed),
2751 			 * and the first subsequent packet will hit this
2752 			 * path.
2753 			 */
2754 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2755 			    ipsec_in_extra_length(first_mp));
2756 		}
2757 		/* Have to change db_type after any pullupmsg */
2758 		DB_TYPE(mp) = M_CTL;
2759 
2760 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2761 		    ip_policy, recv_ill, zoneid);
2762 		return;
2763 	}
2764 	/* NOTREACHED */
2765 discard_pkt:
2766 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2767 drop_pkt:;
2768 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2769 	freemsg(first_mp);
2770 }
2771 
2772 /*
2773  * Common IP options parser.
2774  *
2775  * Setup routine: fill in *optp with options-parsing state, then
2776  * tail-call ipoptp_next to return the first option.
2777  */
2778 uint8_t
2779 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2780 {
2781 	uint32_t totallen; /* total length of all options */
2782 
2783 	totallen = ipha->ipha_version_and_hdr_length -
2784 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2785 	totallen <<= 2;
2786 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2787 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2788 	optp->ipoptp_flags = 0;
2789 	return (ipoptp_next(optp));
2790 }
2791 
2792 /*
2793  * Common IP options parser: extract next option.
2794  */
2795 uint8_t
2796 ipoptp_next(ipoptp_t *optp)
2797 {
2798 	uint8_t *end = optp->ipoptp_end;
2799 	uint8_t *cur = optp->ipoptp_next;
2800 	uint8_t opt, len, pointer;
2801 
2802 	/*
2803 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2804 	 * has been corrupted.
2805 	 */
2806 	ASSERT(cur <= end);
2807 
2808 	if (cur == end)
2809 		return (IPOPT_EOL);
2810 
2811 	opt = cur[IPOPT_OPTVAL];
2812 
2813 	/*
2814 	 * Skip any NOP options.
2815 	 */
2816 	while (opt == IPOPT_NOP) {
2817 		cur++;
2818 		if (cur == end)
2819 			return (IPOPT_EOL);
2820 		opt = cur[IPOPT_OPTVAL];
2821 	}
2822 
2823 	if (opt == IPOPT_EOL)
2824 		return (IPOPT_EOL);
2825 
2826 	/*
2827 	 * Option requiring a length.
2828 	 */
2829 	if ((cur + 1) >= end) {
2830 		optp->ipoptp_flags |= IPOPTP_ERROR;
2831 		return (IPOPT_EOL);
2832 	}
2833 	len = cur[IPOPT_OLEN];
2834 	if (len < 2) {
2835 		optp->ipoptp_flags |= IPOPTP_ERROR;
2836 		return (IPOPT_EOL);
2837 	}
2838 	optp->ipoptp_cur = cur;
2839 	optp->ipoptp_len = len;
2840 	optp->ipoptp_next = cur + len;
2841 	if (cur + len > end) {
2842 		optp->ipoptp_flags |= IPOPTP_ERROR;
2843 		return (IPOPT_EOL);
2844 	}
2845 
2846 	/*
2847 	 * For the options which require a pointer field, make sure
2848 	 * its there, and make sure it points to either something
2849 	 * inside this option, or the end of the option.
2850 	 */
2851 	switch (opt) {
2852 	case IPOPT_RR:
2853 	case IPOPT_TS:
2854 	case IPOPT_LSRR:
2855 	case IPOPT_SSRR:
2856 		if (len <= IPOPT_OFFSET) {
2857 			optp->ipoptp_flags |= IPOPTP_ERROR;
2858 			return (opt);
2859 		}
2860 		pointer = cur[IPOPT_OFFSET];
2861 		if (pointer - 1 > len) {
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 			return (opt);
2864 		}
2865 		break;
2866 	}
2867 
2868 	/*
2869 	 * Sanity check the pointer field based on the type of the
2870 	 * option.
2871 	 */
2872 	switch (opt) {
2873 	case IPOPT_RR:
2874 	case IPOPT_SSRR:
2875 	case IPOPT_LSRR:
2876 		if (pointer < IPOPT_MINOFF_SR)
2877 			optp->ipoptp_flags |= IPOPTP_ERROR;
2878 		break;
2879 	case IPOPT_TS:
2880 		if (pointer < IPOPT_MINOFF_IT)
2881 			optp->ipoptp_flags |= IPOPTP_ERROR;
2882 		/*
2883 		 * Note that the Internet Timestamp option also
2884 		 * contains two four bit fields (the Overflow field,
2885 		 * and the Flag field), which follow the pointer
2886 		 * field.  We don't need to check that these fields
2887 		 * fall within the length of the option because this
2888 		 * was implicitely done above.  We've checked that the
2889 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2890 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2891 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2892 		 */
2893 		ASSERT(len > IPOPT_POS_OV_FLG);
2894 		break;
2895 	}
2896 
2897 	return (opt);
2898 }
2899 
2900 /*
2901  * Use the outgoing IP header to create an IP_OPTIONS option the way
2902  * it was passed down from the application.
2903  */
2904 int
2905 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2906 {
2907 	ipoptp_t	opts;
2908 	const uchar_t	*opt;
2909 	uint8_t		optval;
2910 	uint8_t		optlen;
2911 	uint32_t	len = 0;
2912 	uchar_t	*buf1 = buf;
2913 
2914 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2915 	len += IP_ADDR_LEN;
2916 	bzero(buf1, IP_ADDR_LEN);
2917 
2918 	/*
2919 	 * OK to cast away const here, as we don't store through the returned
2920 	 * opts.ipoptp_cur pointer.
2921 	 */
2922 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2923 	    optval != IPOPT_EOL;
2924 	    optval = ipoptp_next(&opts)) {
2925 		int	off;
2926 
2927 		opt = opts.ipoptp_cur;
2928 		optlen = opts.ipoptp_len;
2929 		switch (optval) {
2930 		case IPOPT_SSRR:
2931 		case IPOPT_LSRR:
2932 
2933 			/*
2934 			 * Insert ipha_dst as the first entry in the source
2935 			 * route and move down the entries on step.
2936 			 * The last entry gets placed at buf1.
2937 			 */
2938 			buf[IPOPT_OPTVAL] = optval;
2939 			buf[IPOPT_OLEN] = optlen;
2940 			buf[IPOPT_OFFSET] = optlen;
2941 
2942 			off = optlen - IP_ADDR_LEN;
2943 			if (off < 0) {
2944 				/* No entries in source route */
2945 				break;
2946 			}
2947 			/* Last entry in source route */
2948 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2949 			off -= IP_ADDR_LEN;
2950 
2951 			while (off > 0) {
2952 				bcopy(opt + off,
2953 				    buf + off + IP_ADDR_LEN,
2954 				    IP_ADDR_LEN);
2955 				off -= IP_ADDR_LEN;
2956 			}
2957 			/* ipha_dst into first slot */
2958 			bcopy(&ipha->ipha_dst,
2959 			    buf + off + IP_ADDR_LEN,
2960 			    IP_ADDR_LEN);
2961 			buf += optlen;
2962 			len += optlen;
2963 			break;
2964 
2965 		case IPOPT_COMSEC:
2966 		case IPOPT_SECURITY:
2967 			/* if passing up a label is not ok, then remove */
2968 			if (is_system_labeled())
2969 				break;
2970 			/* FALLTHROUGH */
2971 		default:
2972 			bcopy(opt, buf, optlen);
2973 			buf += optlen;
2974 			len += optlen;
2975 			break;
2976 		}
2977 	}
2978 done:
2979 	/* Pad the resulting options */
2980 	while (len & 0x3) {
2981 		*buf++ = IPOPT_EOL;
2982 		len++;
2983 	}
2984 	return (len);
2985 }
2986 
2987 /*
2988  * Update any record route or timestamp options to include this host.
2989  * Reverse any source route option.
2990  * This routine assumes that the options are well formed i.e. that they
2991  * have already been checked.
2992  */
2993 static void
2994 icmp_options_update(ipha_t *ipha)
2995 {
2996 	ipoptp_t	opts;
2997 	uchar_t		*opt;
2998 	uint8_t		optval;
2999 	ipaddr_t	src;		/* Our local address */
3000 	ipaddr_t	dst;
3001 
3002 	ip2dbg(("icmp_options_update\n"));
3003 	src = ipha->ipha_src;
3004 	dst = ipha->ipha_dst;
3005 
3006 	for (optval = ipoptp_first(&opts, ipha);
3007 	    optval != IPOPT_EOL;
3008 	    optval = ipoptp_next(&opts)) {
3009 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3010 		opt = opts.ipoptp_cur;
3011 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3012 		    optval, opts.ipoptp_len));
3013 		switch (optval) {
3014 			int off1, off2;
3015 		case IPOPT_SSRR:
3016 		case IPOPT_LSRR:
3017 			/*
3018 			 * Reverse the source route.  The first entry
3019 			 * should be the next to last one in the current
3020 			 * source route (the last entry is our address).
3021 			 * The last entry should be the final destination.
3022 			 */
3023 			off1 = IPOPT_MINOFF_SR - 1;
3024 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3025 			if (off2 < 0) {
3026 				/* No entries in source route */
3027 				ip1dbg((
3028 				    "icmp_options_update: bad src route\n"));
3029 				break;
3030 			}
3031 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3032 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3033 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3034 			off2 -= IP_ADDR_LEN;
3035 
3036 			while (off1 < off2) {
3037 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3038 				bcopy((char *)opt + off2, (char *)opt + off1,
3039 				    IP_ADDR_LEN);
3040 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3041 				off1 += IP_ADDR_LEN;
3042 				off2 -= IP_ADDR_LEN;
3043 			}
3044 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3045 			break;
3046 		}
3047 	}
3048 }
3049 
3050 /*
3051  * Process received ICMP Redirect messages.
3052  */
3053 static void
3054 icmp_redirect(ill_t *ill, mblk_t *mp)
3055 {
3056 	ipha_t	*ipha;
3057 	int	iph_hdr_length;
3058 	icmph_t	*icmph;
3059 	ipha_t	*ipha_err;
3060 	ire_t	*ire;
3061 	ire_t	*prev_ire;
3062 	ire_t	*save_ire;
3063 	ipaddr_t  src, dst, gateway;
3064 	iulp_t	ulp_info = { 0 };
3065 	int	error;
3066 	ip_stack_t *ipst;
3067 
3068 	ASSERT(ill != NULL);
3069 	ipst = ill->ill_ipst;
3070 
3071 	ipha = (ipha_t *)mp->b_rptr;
3072 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3073 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3074 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3075 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3076 		freemsg(mp);
3077 		return;
3078 	}
3079 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3080 	ipha_err = (ipha_t *)&icmph[1];
3081 	src = ipha->ipha_src;
3082 	dst = ipha_err->ipha_dst;
3083 	gateway = icmph->icmph_rd_gateway;
3084 	/* Make sure the new gateway is reachable somehow. */
3085 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3086 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3087 	/*
3088 	 * Make sure we had a route for the dest in question and that
3089 	 * that route was pointing to the old gateway (the source of the
3090 	 * redirect packet.)
3091 	 */
3092 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3093 	    NULL, MATCH_IRE_GW, ipst);
3094 	/*
3095 	 * Check that
3096 	 *	the redirect was not from ourselves
3097 	 *	the new gateway and the old gateway are directly reachable
3098 	 */
3099 	if (!prev_ire ||
3100 	    !ire ||
3101 	    ire->ire_type == IRE_LOCAL) {
3102 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3103 		freemsg(mp);
3104 		if (ire != NULL)
3105 			ire_refrele(ire);
3106 		if (prev_ire != NULL)
3107 			ire_refrele(prev_ire);
3108 		return;
3109 	}
3110 
3111 	/*
3112 	 * Should we use the old ULP info to create the new gateway?  From
3113 	 * a user's perspective, we should inherit the info so that it
3114 	 * is a "smooth" transition.  If we do not do that, then new
3115 	 * connections going thru the new gateway will have no route metrics,
3116 	 * which is counter-intuitive to user.  From a network point of
3117 	 * view, this may or may not make sense even though the new gateway
3118 	 * is still directly connected to us so the route metrics should not
3119 	 * change much.
3120 	 *
3121 	 * But if the old ire_uinfo is not initialized, we do another
3122 	 * recursive lookup on the dest using the new gateway.  There may
3123 	 * be a route to that.  If so, use it to initialize the redirect
3124 	 * route.
3125 	 */
3126 	if (prev_ire->ire_uinfo.iulp_set) {
3127 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3128 	} else {
3129 		ire_t *tmp_ire;
3130 		ire_t *sire;
3131 
3132 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3133 		    ALL_ZONES, 0, NULL,
3134 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3135 		    ipst);
3136 		if (sire != NULL) {
3137 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3138 			/*
3139 			 * If sire != NULL, ire_ftable_lookup() should not
3140 			 * return a NULL value.
3141 			 */
3142 			ASSERT(tmp_ire != NULL);
3143 			ire_refrele(tmp_ire);
3144 			ire_refrele(sire);
3145 		} else if (tmp_ire != NULL) {
3146 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3147 			    sizeof (iulp_t));
3148 			ire_refrele(tmp_ire);
3149 		}
3150 	}
3151 	if (prev_ire->ire_type == IRE_CACHE)
3152 		ire_delete(prev_ire);
3153 	ire_refrele(prev_ire);
3154 	/*
3155 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3156 	 * require TOS routing
3157 	 */
3158 	switch (icmph->icmph_code) {
3159 	case 0:
3160 	case 1:
3161 		/* TODO: TOS specificity for cases 2 and 3 */
3162 	case 2:
3163 	case 3:
3164 		break;
3165 	default:
3166 		freemsg(mp);
3167 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3168 		ire_refrele(ire);
3169 		return;
3170 	}
3171 	/*
3172 	 * Create a Route Association.  This will allow us to remember that
3173 	 * someone we believe told us to use the particular gateway.
3174 	 */
3175 	save_ire = ire;
3176 	ire = ire_create(
3177 	    (uchar_t *)&dst,			/* dest addr */
3178 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3179 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3180 	    (uchar_t *)&gateway,		/* gateway addr */
3181 	    &save_ire->ire_max_frag,		/* max frag */
3182 	    NULL,				/* no src nce */
3183 	    NULL,				/* no rfq */
3184 	    NULL,				/* no stq */
3185 	    IRE_HOST,
3186 	    NULL,				/* ipif */
3187 	    0,					/* cmask */
3188 	    0,					/* phandle */
3189 	    0,					/* ihandle */
3190 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3191 	    &ulp_info,
3192 	    NULL,				/* tsol_gc_t */
3193 	    NULL,				/* gcgrp */
3194 	    ipst);
3195 
3196 	if (ire == NULL) {
3197 		freemsg(mp);
3198 		ire_refrele(save_ire);
3199 		return;
3200 	}
3201 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3202 	ire_refrele(save_ire);
3203 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3204 
3205 	if (error == 0) {
3206 		ire_refrele(ire);		/* Held in ire_add_v4 */
3207 		/* tell routing sockets that we received a redirect */
3208 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3209 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3210 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3211 	}
3212 
3213 	/*
3214 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3215 	 * This together with the added IRE has the effect of
3216 	 * modifying an existing redirect.
3217 	 */
3218 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3219 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3220 	if (prev_ire != NULL) {
3221 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3222 			ire_delete(prev_ire);
3223 		ire_refrele(prev_ire);
3224 	}
3225 
3226 	freemsg(mp);
3227 }
3228 
3229 /*
3230  * Generate an ICMP parameter problem message.
3231  */
3232 static void
3233 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3234 	ip_stack_t *ipst)
3235 {
3236 	icmph_t	icmph;
3237 	boolean_t mctl_present;
3238 	mblk_t *first_mp;
3239 
3240 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3241 
3242 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3243 		if (mctl_present)
3244 			freeb(first_mp);
3245 		return;
3246 	}
3247 
3248 	bzero(&icmph, sizeof (icmph_t));
3249 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3250 	icmph.icmph_pp_ptr = ptr;
3251 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3252 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3253 	    ipst);
3254 }
3255 
3256 /*
3257  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3258  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3259  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3260  * an icmp error packet can be sent.
3261  * Assigns an appropriate source address to the packet. If ipha_dst is
3262  * one of our addresses use it for source. Otherwise pick a source based
3263  * on a route lookup back to ipha_src.
3264  * Note that ipha_src must be set here since the
3265  * packet is likely to arrive on an ill queue in ip_wput() which will
3266  * not set a source address.
3267  */
3268 static void
3269 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3270     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3271 {
3272 	ipaddr_t dst;
3273 	icmph_t	*icmph;
3274 	ipha_t	*ipha;
3275 	uint_t	len_needed;
3276 	size_t	msg_len;
3277 	mblk_t	*mp1;
3278 	ipaddr_t src;
3279 	ire_t	*ire;
3280 	mblk_t *ipsec_mp;
3281 	ipsec_out_t	*io = NULL;
3282 
3283 	if (mctl_present) {
3284 		/*
3285 		 * If it is :
3286 		 *
3287 		 * 1) a IPSEC_OUT, then this is caused by outbound
3288 		 *    datagram originating on this host. IPsec processing
3289 		 *    may or may not have been done. Refer to comments above
3290 		 *    icmp_inbound_error_fanout for details.
3291 		 *
3292 		 * 2) a IPSEC_IN if we are generating a icmp_message
3293 		 *    for an incoming datagram destined for us i.e called
3294 		 *    from ip_fanout_send_icmp.
3295 		 */
3296 		ipsec_info_t *in;
3297 		ipsec_mp = mp;
3298 		mp = ipsec_mp->b_cont;
3299 
3300 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3301 		ipha = (ipha_t *)mp->b_rptr;
3302 
3303 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3304 		    in->ipsec_info_type == IPSEC_IN);
3305 
3306 		if (in->ipsec_info_type == IPSEC_IN) {
3307 			/*
3308 			 * Convert the IPSEC_IN to IPSEC_OUT.
3309 			 */
3310 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3311 				BUMP_MIB(&ipst->ips_ip_mib,
3312 				    ipIfStatsOutDiscards);
3313 				return;
3314 			}
3315 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3316 		} else {
3317 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3318 			io = (ipsec_out_t *)in;
3319 			/*
3320 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3321 			 * ire lookup.
3322 			 */
3323 			io->ipsec_out_proc_begin = B_FALSE;
3324 		}
3325 		ASSERT(zoneid == io->ipsec_out_zoneid);
3326 		ASSERT(zoneid != ALL_ZONES);
3327 	} else {
3328 		/*
3329 		 * This is in clear. The icmp message we are building
3330 		 * here should go out in clear.
3331 		 *
3332 		 * Pardon the convolution of it all, but it's easier to
3333 		 * allocate a "use cleartext" IPSEC_IN message and convert
3334 		 * it than it is to allocate a new one.
3335 		 */
3336 		ipsec_in_t *ii;
3337 		ASSERT(DB_TYPE(mp) == M_DATA);
3338 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3339 		if (ipsec_mp == NULL) {
3340 			freemsg(mp);
3341 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3342 			return;
3343 		}
3344 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3345 
3346 		/* This is not a secure packet */
3347 		ii->ipsec_in_secure = B_FALSE;
3348 		/*
3349 		 * For trusted extensions using a shared IP address we can
3350 		 * send using any zoneid.
3351 		 */
3352 		if (zoneid == ALL_ZONES)
3353 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3354 		else
3355 			ii->ipsec_in_zoneid = zoneid;
3356 		ipsec_mp->b_cont = mp;
3357 		ipha = (ipha_t *)mp->b_rptr;
3358 		/*
3359 		 * Convert the IPSEC_IN to IPSEC_OUT.
3360 		 */
3361 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3362 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3363 			return;
3364 		}
3365 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3366 	}
3367 
3368 	/* Remember our eventual destination */
3369 	dst = ipha->ipha_src;
3370 
3371 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3372 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3373 	if (ire != NULL &&
3374 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3375 		src = ipha->ipha_dst;
3376 	} else {
3377 		if (ire != NULL)
3378 			ire_refrele(ire);
3379 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3380 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3381 		    ipst);
3382 		if (ire == NULL) {
3383 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3384 			freemsg(ipsec_mp);
3385 			return;
3386 		}
3387 		src = ire->ire_src_addr;
3388 	}
3389 
3390 	if (ire != NULL)
3391 		ire_refrele(ire);
3392 
3393 	/*
3394 	 * Check if we can send back more then 8 bytes in addition to
3395 	 * the IP header.  We try to send 64 bytes of data and the internal
3396 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3397 	 */
3398 	len_needed = IPH_HDR_LENGTH(ipha);
3399 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3400 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3401 
3402 		if (!pullupmsg(mp, -1)) {
3403 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3404 			freemsg(ipsec_mp);
3405 			return;
3406 		}
3407 		ipha = (ipha_t *)mp->b_rptr;
3408 
3409 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3410 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3411 			    len_needed));
3412 		} else {
3413 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3414 
3415 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3416 			len_needed += ip_hdr_length_v6(mp, ip6h);
3417 		}
3418 	}
3419 	len_needed += ipst->ips_ip_icmp_return;
3420 	msg_len = msgdsize(mp);
3421 	if (msg_len > len_needed) {
3422 		(void) adjmsg(mp, len_needed - msg_len);
3423 		msg_len = len_needed;
3424 	}
3425 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3426 	if (mp1 == NULL) {
3427 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3428 		freemsg(ipsec_mp);
3429 		return;
3430 	}
3431 	mp1->b_cont = mp;
3432 	mp = mp1;
3433 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3434 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3435 	    io->ipsec_out_type == IPSEC_OUT);
3436 	ipsec_mp->b_cont = mp;
3437 
3438 	/*
3439 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3440 	 * node generates be accepted in peace by all on-host destinations.
3441 	 * If we do NOT assume that all on-host destinations trust
3442 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3443 	 * (Look for ipsec_out_icmp_loopback).
3444 	 */
3445 	io->ipsec_out_icmp_loopback = B_TRUE;
3446 
3447 	ipha = (ipha_t *)mp->b_rptr;
3448 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3449 	*ipha = icmp_ipha;
3450 	ipha->ipha_src = src;
3451 	ipha->ipha_dst = dst;
3452 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3453 	msg_len += sizeof (icmp_ipha) + len;
3454 	if (msg_len > IP_MAXPACKET) {
3455 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3456 		msg_len = IP_MAXPACKET;
3457 	}
3458 	ipha->ipha_length = htons((uint16_t)msg_len);
3459 	icmph = (icmph_t *)&ipha[1];
3460 	bcopy(stuff, icmph, len);
3461 	icmph->icmph_checksum = 0;
3462 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3463 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3464 	put(q, ipsec_mp);
3465 }
3466 
3467 /*
3468  * Determine if an ICMP error packet can be sent given the rate limit.
3469  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3470  * in milliseconds) and a burst size. Burst size number of packets can
3471  * be sent arbitrarely closely spaced.
3472  * The state is tracked using two variables to implement an approximate
3473  * token bucket filter:
3474  *	icmp_pkt_err_last - lbolt value when the last burst started
3475  *	icmp_pkt_err_sent - number of packets sent in current burst
3476  */
3477 boolean_t
3478 icmp_err_rate_limit(ip_stack_t *ipst)
3479 {
3480 	clock_t now = TICK_TO_MSEC(lbolt);
3481 	uint_t refilled; /* Number of packets refilled in tbf since last */
3482 	/* Guard against changes by loading into local variable */
3483 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3484 
3485 	if (err_interval == 0)
3486 		return (B_FALSE);
3487 
3488 	if (ipst->ips_icmp_pkt_err_last > now) {
3489 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3490 		ipst->ips_icmp_pkt_err_last = 0;
3491 		ipst->ips_icmp_pkt_err_sent = 0;
3492 	}
3493 	/*
3494 	 * If we are in a burst update the token bucket filter.
3495 	 * Update the "last" time to be close to "now" but make sure
3496 	 * we don't loose precision.
3497 	 */
3498 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3499 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3500 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3501 			ipst->ips_icmp_pkt_err_sent = 0;
3502 		} else {
3503 			ipst->ips_icmp_pkt_err_sent -= refilled;
3504 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3505 		}
3506 	}
3507 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3508 		/* Start of new burst */
3509 		ipst->ips_icmp_pkt_err_last = now;
3510 	}
3511 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3512 		ipst->ips_icmp_pkt_err_sent++;
3513 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3514 		    ipst->ips_icmp_pkt_err_sent));
3515 		return (B_FALSE);
3516 	}
3517 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3518 	return (B_TRUE);
3519 }
3520 
3521 /*
3522  * Check if it is ok to send an IPv4 ICMP error packet in
3523  * response to the IPv4 packet in mp.
3524  * Free the message and return null if no
3525  * ICMP error packet should be sent.
3526  */
3527 static mblk_t *
3528 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3529 {
3530 	icmph_t	*icmph;
3531 	ipha_t	*ipha;
3532 	uint_t	len_needed;
3533 	ire_t	*src_ire;
3534 	ire_t	*dst_ire;
3535 
3536 	if (!mp)
3537 		return (NULL);
3538 	ipha = (ipha_t *)mp->b_rptr;
3539 	if (ip_csum_hdr(ipha)) {
3540 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3541 		freemsg(mp);
3542 		return (NULL);
3543 	}
3544 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3545 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3546 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3547 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3548 	if (src_ire != NULL || dst_ire != NULL ||
3549 	    CLASSD(ipha->ipha_dst) ||
3550 	    CLASSD(ipha->ipha_src) ||
3551 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3552 		/* Note: only errors to the fragment with offset 0 */
3553 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3554 		freemsg(mp);
3555 		if (src_ire != NULL)
3556 			ire_refrele(src_ire);
3557 		if (dst_ire != NULL)
3558 			ire_refrele(dst_ire);
3559 		return (NULL);
3560 	}
3561 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3562 		/*
3563 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3564 		 * errors in response to any ICMP errors.
3565 		 */
3566 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3567 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3568 			if (!pullupmsg(mp, len_needed)) {
3569 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3570 				freemsg(mp);
3571 				return (NULL);
3572 			}
3573 			ipha = (ipha_t *)mp->b_rptr;
3574 		}
3575 		icmph = (icmph_t *)
3576 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3577 		switch (icmph->icmph_type) {
3578 		case ICMP_DEST_UNREACHABLE:
3579 		case ICMP_SOURCE_QUENCH:
3580 		case ICMP_TIME_EXCEEDED:
3581 		case ICMP_PARAM_PROBLEM:
3582 		case ICMP_REDIRECT:
3583 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3584 			freemsg(mp);
3585 			return (NULL);
3586 		default:
3587 			break;
3588 		}
3589 	}
3590 	/*
3591 	 * If this is a labeled system, then check to see if we're allowed to
3592 	 * send a response to this particular sender.  If not, then just drop.
3593 	 */
3594 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3595 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3596 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3597 		freemsg(mp);
3598 		return (NULL);
3599 	}
3600 	if (icmp_err_rate_limit(ipst)) {
3601 		/*
3602 		 * Only send ICMP error packets every so often.
3603 		 * This should be done on a per port/source basis,
3604 		 * but for now this will suffice.
3605 		 */
3606 		freemsg(mp);
3607 		return (NULL);
3608 	}
3609 	return (mp);
3610 }
3611 
3612 /*
3613  * Generate an ICMP redirect message.
3614  */
3615 static void
3616 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3617 {
3618 	icmph_t	icmph;
3619 
3620 	/*
3621 	 * We are called from ip_rput where we could
3622 	 * not have attached an IPSEC_IN.
3623 	 */
3624 	ASSERT(mp->b_datap->db_type == M_DATA);
3625 
3626 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3627 		return;
3628 	}
3629 
3630 	bzero(&icmph, sizeof (icmph_t));
3631 	icmph.icmph_type = ICMP_REDIRECT;
3632 	icmph.icmph_code = 1;
3633 	icmph.icmph_rd_gateway = gateway;
3634 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3635 	/* Redirects sent by router, and router is global zone */
3636 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3637 }
3638 
3639 /*
3640  * Generate an ICMP time exceeded message.
3641  */
3642 void
3643 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3644     ip_stack_t *ipst)
3645 {
3646 	icmph_t	icmph;
3647 	boolean_t mctl_present;
3648 	mblk_t *first_mp;
3649 
3650 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3651 
3652 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3653 		if (mctl_present)
3654 			freeb(first_mp);
3655 		return;
3656 	}
3657 
3658 	bzero(&icmph, sizeof (icmph_t));
3659 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3660 	icmph.icmph_code = code;
3661 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3662 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3663 	    ipst);
3664 }
3665 
3666 /*
3667  * Generate an ICMP unreachable message.
3668  */
3669 void
3670 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3671     ip_stack_t *ipst)
3672 {
3673 	icmph_t	icmph;
3674 	mblk_t *first_mp;
3675 	boolean_t mctl_present;
3676 
3677 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3678 
3679 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3680 		if (mctl_present)
3681 			freeb(first_mp);
3682 		return;
3683 	}
3684 
3685 	bzero(&icmph, sizeof (icmph_t));
3686 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3687 	icmph.icmph_code = code;
3688 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3689 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3690 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3691 	    zoneid, ipst);
3692 }
3693 
3694 /*
3695  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3696  * duplicate.  As long as someone else holds the address, the interface will
3697  * stay down.  When that conflict goes away, the interface is brought back up.
3698  * This is done so that accidental shutdowns of addresses aren't made
3699  * permanent.  Your server will recover from a failure.
3700  *
3701  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3702  * user space process (dhcpagent).
3703  *
3704  * Recovery completes if ARP reports that the address is now ours (via
3705  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3706  *
3707  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3708  */
3709 static void
3710 ipif_dup_recovery(void *arg)
3711 {
3712 	ipif_t *ipif = arg;
3713 	ill_t *ill = ipif->ipif_ill;
3714 	mblk_t *arp_add_mp;
3715 	mblk_t *arp_del_mp;
3716 	area_t *area;
3717 	ip_stack_t *ipst = ill->ill_ipst;
3718 
3719 	ipif->ipif_recovery_id = 0;
3720 
3721 	/*
3722 	 * No lock needed for moving or condemned check, as this is just an
3723 	 * optimization.
3724 	 */
3725 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3726 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3727 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3728 		/* No reason to try to bring this address back. */
3729 		return;
3730 	}
3731 
3732 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3733 		goto alloc_fail;
3734 
3735 	if (ipif->ipif_arp_del_mp == NULL) {
3736 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3737 			goto alloc_fail;
3738 		ipif->ipif_arp_del_mp = arp_del_mp;
3739 	}
3740 
3741 	/* Setting the 'unverified' flag restarts DAD */
3742 	area = (area_t *)arp_add_mp->b_rptr;
3743 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3744 	    ACE_F_UNVERIFIED;
3745 	putnext(ill->ill_rq, arp_add_mp);
3746 	return;
3747 
3748 alloc_fail:
3749 	/*
3750 	 * On allocation failure, just restart the timer.  Note that the ipif
3751 	 * is down here, so no other thread could be trying to start a recovery
3752 	 * timer.  The ill_lock protects the condemned flag and the recovery
3753 	 * timer ID.
3754 	 */
3755 	freemsg(arp_add_mp);
3756 	mutex_enter(&ill->ill_lock);
3757 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3758 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3759 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3760 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3761 	}
3762 	mutex_exit(&ill->ill_lock);
3763 }
3764 
3765 /*
3766  * This is for exclusive changes due to ARP.  Either tear down an interface due
3767  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3768  */
3769 /* ARGSUSED */
3770 static void
3771 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3772 {
3773 	ill_t	*ill = rq->q_ptr;
3774 	arh_t *arh;
3775 	ipaddr_t src;
3776 	ipif_t	*ipif;
3777 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3778 	char hbuf[MAC_STR_LEN];
3779 	char sbuf[INET_ADDRSTRLEN];
3780 	const char *failtype;
3781 	boolean_t bring_up;
3782 	ip_stack_t *ipst = ill->ill_ipst;
3783 
3784 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3785 	case AR_CN_READY:
3786 		failtype = NULL;
3787 		bring_up = B_TRUE;
3788 		break;
3789 	case AR_CN_FAILED:
3790 		failtype = "in use";
3791 		bring_up = B_FALSE;
3792 		break;
3793 	default:
3794 		failtype = "claimed";
3795 		bring_up = B_FALSE;
3796 		break;
3797 	}
3798 
3799 	arh = (arh_t *)mp->b_cont->b_rptr;
3800 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3801 
3802 	/* Handle failures due to probes */
3803 	if (src == 0) {
3804 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3805 		    IP_ADDR_LEN);
3806 	}
3807 
3808 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3809 	    sizeof (hbuf));
3810 	(void) ip_dot_addr(src, sbuf);
3811 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3812 
3813 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3814 		    ipif->ipif_lcl_addr != src) {
3815 			continue;
3816 		}
3817 
3818 		/*
3819 		 * If we failed on a recovery probe, then restart the timer to
3820 		 * try again later.
3821 		 */
3822 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3823 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3824 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3825 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3826 		    ipst->ips_ip_dup_recovery > 0 &&
3827 		    ipif->ipif_recovery_id == 0) {
3828 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3829 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3830 			continue;
3831 		}
3832 
3833 		/*
3834 		 * If what we're trying to do has already been done, then do
3835 		 * nothing.
3836 		 */
3837 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3838 			continue;
3839 
3840 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3841 
3842 		if (failtype == NULL) {
3843 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3844 			    ibuf);
3845 		} else {
3846 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3847 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3848 		}
3849 
3850 		if (bring_up) {
3851 			ASSERT(ill->ill_dl_up);
3852 			/*
3853 			 * Free up the ARP delete message so we can allocate
3854 			 * a fresh one through the normal path.
3855 			 */
3856 			freemsg(ipif->ipif_arp_del_mp);
3857 			ipif->ipif_arp_del_mp = NULL;
3858 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3859 			    EINPROGRESS) {
3860 				ipif->ipif_addr_ready = 1;
3861 				(void) ipif_up_done(ipif);
3862 			}
3863 			continue;
3864 		}
3865 
3866 		mutex_enter(&ill->ill_lock);
3867 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3868 		ipif->ipif_flags |= IPIF_DUPLICATE;
3869 		ill->ill_ipif_dup_count++;
3870 		mutex_exit(&ill->ill_lock);
3871 		/*
3872 		 * Already exclusive on the ill; no need to handle deferred
3873 		 * processing here.
3874 		 */
3875 		(void) ipif_down(ipif, NULL, NULL);
3876 		ipif_down_tail(ipif);
3877 		mutex_enter(&ill->ill_lock);
3878 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3879 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3880 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3881 		    ipst->ips_ip_dup_recovery > 0) {
3882 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3883 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3884 		}
3885 		mutex_exit(&ill->ill_lock);
3886 	}
3887 	freemsg(mp);
3888 }
3889 
3890 /* ARGSUSED */
3891 static void
3892 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3893 {
3894 	ill_t	*ill = rq->q_ptr;
3895 	arh_t *arh;
3896 	ipaddr_t src;
3897 	ipif_t	*ipif;
3898 
3899 	arh = (arh_t *)mp->b_cont->b_rptr;
3900 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3901 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3902 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3903 			(void) ipif_resolver_up(ipif, Res_act_defend);
3904 	}
3905 	freemsg(mp);
3906 }
3907 
3908 /*
3909  * News from ARP.  ARP sends notification of interesting events down
3910  * to its clients using M_CTL messages with the interesting ARP packet
3911  * attached via b_cont.
3912  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3913  * queue as opposed to ARP sending the message to all the clients, i.e. all
3914  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3915  * table if a cache IRE is found to delete all the entries for the address in
3916  * the packet.
3917  */
3918 static void
3919 ip_arp_news(queue_t *q, mblk_t *mp)
3920 {
3921 	arcn_t		*arcn;
3922 	arh_t		*arh;
3923 	ire_t		*ire = NULL;
3924 	char		hbuf[MAC_STR_LEN];
3925 	char		sbuf[INET_ADDRSTRLEN];
3926 	ipaddr_t	src;
3927 	in6_addr_t	v6src;
3928 	boolean_t	isv6 = B_FALSE;
3929 	ipif_t		*ipif;
3930 	ill_t		*ill;
3931 	ip_stack_t	*ipst;
3932 
3933 	if (CONN_Q(q)) {
3934 		conn_t *connp = Q_TO_CONN(q);
3935 
3936 		ipst = connp->conn_netstack->netstack_ip;
3937 	} else {
3938 		ill_t *ill = (ill_t *)q->q_ptr;
3939 
3940 		ipst = ill->ill_ipst;
3941 	}
3942 
3943 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3944 		if (q->q_next) {
3945 			putnext(q, mp);
3946 		} else
3947 			freemsg(mp);
3948 		return;
3949 	}
3950 	arh = (arh_t *)mp->b_cont->b_rptr;
3951 	/* Is it one we are interested in? */
3952 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3953 		isv6 = B_TRUE;
3954 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3955 		    IPV6_ADDR_LEN);
3956 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3957 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3958 		    IP_ADDR_LEN);
3959 	} else {
3960 		freemsg(mp);
3961 		return;
3962 	}
3963 
3964 	ill = q->q_ptr;
3965 
3966 	arcn = (arcn_t *)mp->b_rptr;
3967 	switch (arcn->arcn_code) {
3968 	case AR_CN_BOGON:
3969 		/*
3970 		 * Someone is sending ARP packets with a source protocol
3971 		 * address that we have published and for which we believe our
3972 		 * entry is authoritative and (when ill_arp_extend is set)
3973 		 * verified to be unique on the network.
3974 		 *
3975 		 * The ARP module internally handles the cases where the sender
3976 		 * is just probing (for DAD) and where the hardware address of
3977 		 * a non-authoritative entry has changed.  Thus, these are the
3978 		 * real conflicts, and we have to do resolution.
3979 		 *
3980 		 * We back away quickly from the address if it's from DHCP or
3981 		 * otherwise temporary and hasn't been used recently (or at
3982 		 * all).  We'd like to include "deprecated" addresses here as
3983 		 * well (as there's no real reason to defend something we're
3984 		 * discarding), but IPMP "reuses" this flag to mean something
3985 		 * other than the standard meaning.
3986 		 *
3987 		 * If the ARP module above is not extended (meaning that it
3988 		 * doesn't know how to defend the address), then we just log
3989 		 * the problem as we always did and continue on.  It's not
3990 		 * right, but there's little else we can do, and those old ATM
3991 		 * users are going away anyway.
3992 		 */
3993 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3994 		    hbuf, sizeof (hbuf));
3995 		(void) ip_dot_addr(src, sbuf);
3996 		if (isv6) {
3997 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3998 			    ipst);
3999 		} else {
4000 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4001 		}
4002 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4003 			uint32_t now;
4004 			uint32_t maxage;
4005 			clock_t lused;
4006 			uint_t maxdefense;
4007 			uint_t defs;
4008 
4009 			/*
4010 			 * First, figure out if this address hasn't been used
4011 			 * in a while.  If it hasn't, then it's a better
4012 			 * candidate for abandoning.
4013 			 */
4014 			ipif = ire->ire_ipif;
4015 			ASSERT(ipif != NULL);
4016 			now = gethrestime_sec();
4017 			maxage = now - ire->ire_create_time;
4018 			if (maxage > ipst->ips_ip_max_temp_idle)
4019 				maxage = ipst->ips_ip_max_temp_idle;
4020 			lused = drv_hztousec(ddi_get_lbolt() -
4021 			    ire->ire_last_used_time) / MICROSEC + 1;
4022 			if (lused >= maxage && (ipif->ipif_flags &
4023 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4024 				maxdefense = ipst->ips_ip_max_temp_defend;
4025 			else
4026 				maxdefense = ipst->ips_ip_max_defend;
4027 
4028 			/*
4029 			 * Now figure out how many times we've defended
4030 			 * ourselves.  Ignore defenses that happened long in
4031 			 * the past.
4032 			 */
4033 			mutex_enter(&ire->ire_lock);
4034 			if ((defs = ire->ire_defense_count) > 0 &&
4035 			    now - ire->ire_defense_time >
4036 			    ipst->ips_ip_defend_interval) {
4037 				ire->ire_defense_count = defs = 0;
4038 			}
4039 			ire->ire_defense_count++;
4040 			ire->ire_defense_time = now;
4041 			mutex_exit(&ire->ire_lock);
4042 			ill_refhold(ill);
4043 			ire_refrele(ire);
4044 
4045 			/*
4046 			 * If we've defended ourselves too many times already,
4047 			 * then give up and tear down the interface(s) using
4048 			 * this address.  Otherwise, defend by sending out a
4049 			 * gratuitous ARP.
4050 			 */
4051 			if (defs >= maxdefense && ill->ill_arp_extend) {
4052 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4053 				    B_FALSE);
4054 			} else {
4055 				cmn_err(CE_WARN,
4056 				    "node %s is using our IP address %s on %s",
4057 				    hbuf, sbuf, ill->ill_name);
4058 				/*
4059 				 * If this is an old (ATM) ARP module, then
4060 				 * don't try to defend the address.  Remain
4061 				 * compatible with the old behavior.  Defend
4062 				 * only with new ARP.
4063 				 */
4064 				if (ill->ill_arp_extend) {
4065 					qwriter_ip(ill, q, mp, ip_arp_defend,
4066 					    NEW_OP, B_FALSE);
4067 				} else {
4068 					ill_refrele(ill);
4069 				}
4070 			}
4071 			return;
4072 		}
4073 		cmn_err(CE_WARN,
4074 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4075 		    hbuf, sbuf, ill->ill_name);
4076 		if (ire != NULL)
4077 			ire_refrele(ire);
4078 		break;
4079 	case AR_CN_ANNOUNCE:
4080 		if (isv6) {
4081 			/*
4082 			 * For XRESOLV interfaces.
4083 			 * Delete the IRE cache entry and NCE for this
4084 			 * v6 address
4085 			 */
4086 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4087 			/*
4088 			 * If v6src is a non-zero, it's a router address
4089 			 * as below. Do the same sort of thing to clean
4090 			 * out off-net IRE_CACHE entries that go through
4091 			 * the router.
4092 			 */
4093 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4094 				ire_walk_v6(ire_delete_cache_gw_v6,
4095 				    (char *)&v6src, ALL_ZONES, ipst);
4096 			}
4097 		} else {
4098 			nce_hw_map_t hwm;
4099 
4100 			/*
4101 			 * ARP gives us a copy of any packet where it thinks
4102 			 * the address has changed, so that we can update our
4103 			 * caches.  We're responsible for caching known answers
4104 			 * in the current design.  We check whether the
4105 			 * hardware address really has changed in all of our
4106 			 * entries that have cached this mapping, and if so, we
4107 			 * blow them away.  This way we will immediately pick
4108 			 * up the rare case of a host changing hardware
4109 			 * address.
4110 			 */
4111 			if (src == 0)
4112 				break;
4113 			hwm.hwm_addr = src;
4114 			hwm.hwm_hwlen = arh->arh_hlen;
4115 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4116 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4117 			ndp_walk_common(ipst->ips_ndp4, NULL,
4118 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4119 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4120 		}
4121 		break;
4122 	case AR_CN_READY:
4123 		/* No external v6 resolver has a contract to use this */
4124 		if (isv6)
4125 			break;
4126 		/* If the link is down, we'll retry this later */
4127 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4128 			break;
4129 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4130 		    NULL, NULL, ipst);
4131 		if (ipif != NULL) {
4132 			/*
4133 			 * If this is a duplicate recovery, then we now need to
4134 			 * go exclusive to bring this thing back up.
4135 			 */
4136 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4137 			    IPIF_DUPLICATE) {
4138 				ipif_refrele(ipif);
4139 				ill_refhold(ill);
4140 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4141 				    B_FALSE);
4142 				return;
4143 			}
4144 			/*
4145 			 * If this is the first notice that this address is
4146 			 * ready, then let the user know now.
4147 			 */
4148 			if ((ipif->ipif_flags & IPIF_UP) &&
4149 			    !ipif->ipif_addr_ready) {
4150 				ipif_mask_reply(ipif);
4151 				ip_rts_ifmsg(ipif);
4152 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4153 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4154 			}
4155 			ipif->ipif_addr_ready = 1;
4156 			ipif_refrele(ipif);
4157 		}
4158 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4159 		if (ire != NULL) {
4160 			ire->ire_defense_count = 0;
4161 			ire_refrele(ire);
4162 		}
4163 		break;
4164 	case AR_CN_FAILED:
4165 		/* No external v6 resolver has a contract to use this */
4166 		if (isv6)
4167 			break;
4168 		ill_refhold(ill);
4169 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4170 		return;
4171 	}
4172 	freemsg(mp);
4173 }
4174 
4175 /*
4176  * Create a mblk suitable for carrying the interface index and/or source link
4177  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4178  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4179  * application.
4180  */
4181 mblk_t *
4182 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4183     ip_stack_t *ipst)
4184 {
4185 	mblk_t		*mp;
4186 	ip_pktinfo_t	*pinfo;
4187 	ipha_t *ipha;
4188 	struct ether_header *pether;
4189 
4190 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4191 	if (mp == NULL) {
4192 		ip1dbg(("ip_add_info: allocation failure.\n"));
4193 		return (data_mp);
4194 	}
4195 
4196 	ipha	= (ipha_t *)data_mp->b_rptr;
4197 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4198 	bzero(pinfo, sizeof (ip_pktinfo_t));
4199 	pinfo->ip_pkt_flags = (uchar_t)flags;
4200 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4201 
4202 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4203 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4204 	if (flags & IPF_RECVADDR) {
4205 		ipif_t	*ipif;
4206 		ire_t	*ire;
4207 
4208 		/*
4209 		 * Only valid for V4
4210 		 */
4211 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4212 		    (IPV4_VERSION << 4));
4213 
4214 		ipif = ipif_get_next_ipif(NULL, ill);
4215 		if (ipif != NULL) {
4216 			/*
4217 			 * Since a decision has already been made to deliver the
4218 			 * packet, there is no need to test for SECATTR and
4219 			 * ZONEONLY.
4220 			 * When a multicast packet is transmitted
4221 			 * a cache entry is created for the multicast address.
4222 			 * When delivering a copy of the packet or when new
4223 			 * packets are received we do not want to match on the
4224 			 * cached entry so explicitly match on
4225 			 * IRE_LOCAL and IRE_LOOPBACK
4226 			 */
4227 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4228 			    IRE_LOCAL | IRE_LOOPBACK,
4229 			    ipif, zoneid, NULL,
4230 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4231 			if (ire == NULL) {
4232 				/*
4233 				 * packet must have come on a different
4234 				 * interface.
4235 				 * Since a decision has already been made to
4236 				 * deliver the packet, there is no need to test
4237 				 * for SECATTR and ZONEONLY.
4238 				 * Only match on local and broadcast ire's.
4239 				 * See detailed comment above.
4240 				 */
4241 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4242 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4243 				    NULL, MATCH_IRE_TYPE, ipst);
4244 			}
4245 
4246 			if (ire == NULL) {
4247 				/*
4248 				 * This is either a multicast packet or
4249 				 * the address has been removed since
4250 				 * the packet was received.
4251 				 * Return INADDR_ANY so that normal source
4252 				 * selection occurs for the response.
4253 				 */
4254 
4255 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4256 			} else {
4257 				pinfo->ip_pkt_match_addr.s_addr =
4258 				    ire->ire_src_addr;
4259 				ire_refrele(ire);
4260 			}
4261 			ipif_refrele(ipif);
4262 		} else {
4263 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4264 		}
4265 	}
4266 
4267 	pether = (struct ether_header *)((char *)ipha
4268 	    - sizeof (struct ether_header));
4269 	/*
4270 	 * Make sure the interface is an ethernet type, since this option
4271 	 * is currently supported only on this type of interface. Also make
4272 	 * sure we are pointing correctly above db_base.
4273 	 */
4274 
4275 	if ((flags & IPF_RECVSLLA) &&
4276 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4277 	    (ill->ill_type == IFT_ETHER) &&
4278 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4279 
4280 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4281 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4282 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4283 	} else {
4284 		/*
4285 		 * Clear the bit. Indicate to upper layer that IP is not
4286 		 * sending this ancillary info.
4287 		 */
4288 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4289 	}
4290 
4291 	mp->b_datap->db_type = M_CTL;
4292 	mp->b_wptr += sizeof (ip_pktinfo_t);
4293 	mp->b_cont = data_mp;
4294 
4295 	return (mp);
4296 }
4297 
4298 /*
4299  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4300  * part of the bind request.
4301  */
4302 
4303 boolean_t
4304 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4305 {
4306 	ipsec_in_t *ii;
4307 
4308 	ASSERT(policy_mp != NULL);
4309 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4310 
4311 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4312 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4313 
4314 	connp->conn_policy = ii->ipsec_in_policy;
4315 	ii->ipsec_in_policy = NULL;
4316 
4317 	if (ii->ipsec_in_action != NULL) {
4318 		if (connp->conn_latch == NULL) {
4319 			connp->conn_latch = iplatch_create();
4320 			if (connp->conn_latch == NULL)
4321 				return (B_FALSE);
4322 		}
4323 		ipsec_latch_inbound(connp->conn_latch, ii);
4324 	}
4325 	return (B_TRUE);
4326 }
4327 
4328 /*
4329  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4330  * and to arrange for power-fanout assist.  The ULP is identified by
4331  * adding a single byte at the end of the original bind message.
4332  * A ULP other than UDP or TCP that wishes to be recognized passes
4333  * down a bind with a zero length address.
4334  *
4335  * The binding works as follows:
4336  * - A zero byte address means just bind to the protocol.
4337  * - A four byte address is treated as a request to validate
4338  *   that the address is a valid local address, appropriate for
4339  *   an application to bind to. This does not affect any fanout
4340  *   information in IP.
4341  * - A sizeof sin_t byte address is used to bind to only the local address
4342  *   and port.
4343  * - A sizeof ipa_conn_t byte address contains complete fanout information
4344  *   consisting of local and remote addresses and ports.  In
4345  *   this case, the addresses are both validated as appropriate
4346  *   for this operation, and, if so, the information is retained
4347  *   for use in the inbound fanout.
4348  *
4349  * The ULP (except in the zero-length bind) can append an
4350  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4351  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4352  * a copy of the source or destination IRE (source for local bind;
4353  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4354  * policy information contained should be copied on to the conn.
4355  *
4356  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4357  */
4358 mblk_t *
4359 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4360 {
4361 	ssize_t		len;
4362 	struct T_bind_req	*tbr;
4363 	sin_t		*sin;
4364 	ipa_conn_t	*ac;
4365 	uchar_t		*ucp;
4366 	mblk_t		*mp1;
4367 	boolean_t	ire_requested;
4368 	boolean_t	ipsec_policy_set = B_FALSE;
4369 	int		error = 0;
4370 	int		protocol;
4371 	ipa_conn_x_t	*acx;
4372 
4373 	ASSERT(!connp->conn_af_isv6);
4374 	connp->conn_pkt_isv6 = B_FALSE;
4375 
4376 	len = MBLKL(mp);
4377 	if (len < (sizeof (*tbr) + 1)) {
4378 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4379 		    "ip_bind: bogus msg, len %ld", len);
4380 		/* XXX: Need to return something better */
4381 		goto bad_addr;
4382 	}
4383 	/* Back up and extract the protocol identifier. */
4384 	mp->b_wptr--;
4385 	protocol = *mp->b_wptr & 0xFF;
4386 	tbr = (struct T_bind_req *)mp->b_rptr;
4387 	/* Reset the message type in preparation for shipping it back. */
4388 	DB_TYPE(mp) = M_PCPROTO;
4389 
4390 	connp->conn_ulp = (uint8_t)protocol;
4391 
4392 	/*
4393 	 * Check for a zero length address.  This is from a protocol that
4394 	 * wants to register to receive all packets of its type.
4395 	 */
4396 	if (tbr->ADDR_length == 0) {
4397 		/*
4398 		 * These protocols are now intercepted in ip_bind_v6().
4399 		 * Reject protocol-level binds here for now.
4400 		 *
4401 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4402 		 * so that the protocol type cannot be SCTP.
4403 		 */
4404 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4405 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4406 			goto bad_addr;
4407 		}
4408 
4409 		/*
4410 		 *
4411 		 * The udp module never sends down a zero-length address,
4412 		 * and allowing this on a labeled system will break MLP
4413 		 * functionality.
4414 		 */
4415 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4416 			goto bad_addr;
4417 
4418 		if (connp->conn_mac_exempt)
4419 			goto bad_addr;
4420 
4421 		/* No hash here really.  The table is big enough. */
4422 		connp->conn_srcv6 = ipv6_all_zeros;
4423 
4424 		ipcl_proto_insert(connp, protocol);
4425 
4426 		tbr->PRIM_type = T_BIND_ACK;
4427 		return (mp);
4428 	}
4429 
4430 	/* Extract the address pointer from the message. */
4431 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4432 	    tbr->ADDR_length);
4433 	if (ucp == NULL) {
4434 		ip1dbg(("ip_bind: no address\n"));
4435 		goto bad_addr;
4436 	}
4437 	if (!OK_32PTR(ucp)) {
4438 		ip1dbg(("ip_bind: unaligned address\n"));
4439 		goto bad_addr;
4440 	}
4441 	/*
4442 	 * Check for trailing mps.
4443 	 */
4444 
4445 	mp1 = mp->b_cont;
4446 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4447 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4448 
4449 	switch (tbr->ADDR_length) {
4450 	default:
4451 		ip1dbg(("ip_bind: bad address length %d\n",
4452 		    (int)tbr->ADDR_length));
4453 		goto bad_addr;
4454 
4455 	case IP_ADDR_LEN:
4456 		/* Verification of local address only */
4457 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4458 		    ire_requested, ipsec_policy_set, B_FALSE);
4459 		break;
4460 
4461 	case sizeof (sin_t):
4462 		sin = (sin_t *)ucp;
4463 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4464 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4465 		break;
4466 
4467 	case sizeof (ipa_conn_t):
4468 		ac = (ipa_conn_t *)ucp;
4469 		/* For raw socket, the local port is not set. */
4470 		if (ac->ac_lport == 0)
4471 			ac->ac_lport = connp->conn_lport;
4472 		/* Always verify destination reachability. */
4473 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4474 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4475 		    ipsec_policy_set, B_TRUE, B_TRUE);
4476 		break;
4477 
4478 	case sizeof (ipa_conn_x_t):
4479 		acx = (ipa_conn_x_t *)ucp;
4480 		/*
4481 		 * Whether or not to verify destination reachability depends
4482 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4483 		 */
4484 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4485 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4486 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4487 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4488 		break;
4489 	}
4490 	if (error == EINPROGRESS)
4491 		return (NULL);
4492 	else if (error != 0)
4493 		goto bad_addr;
4494 	/*
4495 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4496 	 * We can't do this in ip_bind_insert_ire because the policy
4497 	 * may not have been inherited at that point in time and hence
4498 	 * conn_out_enforce_policy may not be set.
4499 	 */
4500 	mp1 = mp->b_cont;
4501 	if (ire_requested && connp->conn_out_enforce_policy &&
4502 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4503 		ire_t *ire = (ire_t *)mp1->b_rptr;
4504 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4505 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4506 	}
4507 
4508 	/* Send it home. */
4509 	mp->b_datap->db_type = M_PCPROTO;
4510 	tbr->PRIM_type = T_BIND_ACK;
4511 	return (mp);
4512 
4513 bad_addr:
4514 	/*
4515 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4516 	 * a unix errno.
4517 	 */
4518 	if (error > 0)
4519 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4520 	else
4521 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4522 	return (mp);
4523 }
4524 
4525 /*
4526  * Here address is verified to be a valid local address.
4527  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4528  * address is also considered a valid local address.
4529  * In the case of a broadcast/multicast address, however, the
4530  * upper protocol is expected to reset the src address
4531  * to 0 if it sees a IRE_BROADCAST type returned so that
4532  * no packets are emitted with broadcast/multicast address as
4533  * source address (that violates hosts requirements RFC1122)
4534  * The addresses valid for bind are:
4535  *	(1) - INADDR_ANY (0)
4536  *	(2) - IP address of an UP interface
4537  *	(3) - IP address of a DOWN interface
4538  *	(4) - valid local IP broadcast addresses. In this case
4539  *	the conn will only receive packets destined to
4540  *	the specified broadcast address.
4541  *	(5) - a multicast address. In this case
4542  *	the conn will only receive packets destined to
4543  *	the specified multicast address. Note: the
4544  *	application still has to issue an
4545  *	IP_ADD_MEMBERSHIP socket option.
4546  *
4547  * On error, return -1 for TBADADDR otherwise pass the
4548  * errno with TSYSERR reply.
4549  *
4550  * In all the above cases, the bound address must be valid in the current zone.
4551  * When the address is loopback, multicast or broadcast, there might be many
4552  * matching IREs so bind has to look up based on the zone.
4553  *
4554  * Note: lport is in network byte order.
4555  */
4556 int
4557 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4558     boolean_t ire_requested, boolean_t ipsec_policy_set,
4559     boolean_t fanout_insert)
4560 {
4561 	int		error = 0;
4562 	ire_t		*src_ire;
4563 	mblk_t		*policy_mp;
4564 	ipif_t		*ipif;
4565 	zoneid_t	zoneid;
4566 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4567 
4568 	if (ipsec_policy_set) {
4569 		policy_mp = mp->b_cont;
4570 	}
4571 
4572 	/*
4573 	 * If it was previously connected, conn_fully_bound would have
4574 	 * been set.
4575 	 */
4576 	connp->conn_fully_bound = B_FALSE;
4577 
4578 	src_ire = NULL;
4579 	ipif = NULL;
4580 
4581 	zoneid = IPCL_ZONEID(connp);
4582 
4583 	if (src_addr) {
4584 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4585 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4586 		/*
4587 		 * If an address other than 0.0.0.0 is requested,
4588 		 * we verify that it is a valid address for bind
4589 		 * Note: Following code is in if-else-if form for
4590 		 * readability compared to a condition check.
4591 		 */
4592 		/* LINTED - statement has no consequent */
4593 		if (IRE_IS_LOCAL(src_ire)) {
4594 			/*
4595 			 * (2) Bind to address of local UP interface
4596 			 */
4597 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4598 			/*
4599 			 * (4) Bind to broadcast address
4600 			 * Note: permitted only from transports that
4601 			 * request IRE
4602 			 */
4603 			if (!ire_requested)
4604 				error = EADDRNOTAVAIL;
4605 		} else {
4606 			/*
4607 			 * (3) Bind to address of local DOWN interface
4608 			 * (ipif_lookup_addr() looks up all interfaces
4609 			 * but we do not get here for UP interfaces
4610 			 * - case (2) above)
4611 			 * We put the protocol byte back into the mblk
4612 			 * since we may come back via ip_wput_nondata()
4613 			 * later with this mblk if ipif_lookup_addr chooses
4614 			 * to defer processing.
4615 			 */
4616 			*mp->b_wptr++ = (char)connp->conn_ulp;
4617 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4618 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4619 			    &error, ipst)) != NULL) {
4620 				ipif_refrele(ipif);
4621 			} else if (error == EINPROGRESS) {
4622 				if (src_ire != NULL)
4623 					ire_refrele(src_ire);
4624 				return (EINPROGRESS);
4625 			} else if (CLASSD(src_addr)) {
4626 				error = 0;
4627 				if (src_ire != NULL)
4628 					ire_refrele(src_ire);
4629 				/*
4630 				 * (5) bind to multicast address.
4631 				 * Fake out the IRE returned to upper
4632 				 * layer to be a broadcast IRE.
4633 				 */
4634 				src_ire = ire_ctable_lookup(
4635 				    INADDR_BROADCAST, INADDR_ANY,
4636 				    IRE_BROADCAST, NULL, zoneid, NULL,
4637 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4638 				    ipst);
4639 				if (src_ire == NULL || !ire_requested)
4640 					error = EADDRNOTAVAIL;
4641 			} else {
4642 				/*
4643 				 * Not a valid address for bind
4644 				 */
4645 				error = EADDRNOTAVAIL;
4646 			}
4647 			/*
4648 			 * Just to keep it consistent with the processing in
4649 			 * ip_bind_v4()
4650 			 */
4651 			mp->b_wptr--;
4652 		}
4653 		if (error) {
4654 			/* Red Alert!  Attempting to be a bogon! */
4655 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4656 			    ntohl(src_addr)));
4657 			goto bad_addr;
4658 		}
4659 	}
4660 
4661 	/*
4662 	 * Allow setting new policies. For example, disconnects come
4663 	 * down as ipa_t bind. As we would have set conn_policy_cached
4664 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4665 	 * can change after the disconnect.
4666 	 */
4667 	connp->conn_policy_cached = B_FALSE;
4668 
4669 	/*
4670 	 * If not fanout_insert this was just an address verification
4671 	 */
4672 	if (fanout_insert) {
4673 		/*
4674 		 * The addresses have been verified. Time to insert in
4675 		 * the correct fanout list.
4676 		 */
4677 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4678 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4679 		connp->conn_lport = lport;
4680 		connp->conn_fport = 0;
4681 		/*
4682 		 * Do we need to add a check to reject Multicast packets
4683 		 */
4684 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4685 	}
4686 
4687 	if (error == 0) {
4688 		if (ire_requested) {
4689 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4690 				error = -1;
4691 				/* Falls through to bad_addr */
4692 			}
4693 		} else if (ipsec_policy_set) {
4694 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4695 				error = -1;
4696 				/* Falls through to bad_addr */
4697 			}
4698 		}
4699 	}
4700 bad_addr:
4701 	if (error != 0) {
4702 		if (connp->conn_anon_port) {
4703 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4704 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4705 			    B_FALSE);
4706 		}
4707 		connp->conn_mlp_type = mlptSingle;
4708 	}
4709 	if (src_ire != NULL)
4710 		IRE_REFRELE(src_ire);
4711 	if (ipsec_policy_set) {
4712 		ASSERT(policy_mp == mp->b_cont);
4713 		ASSERT(policy_mp != NULL);
4714 		freeb(policy_mp);
4715 		/*
4716 		 * As of now assume that nothing else accompanies
4717 		 * IPSEC_POLICY_SET.
4718 		 */
4719 		mp->b_cont = NULL;
4720 	}
4721 	return (error);
4722 }
4723 
4724 /*
4725  * Verify that both the source and destination addresses
4726  * are valid.  If verify_dst is false, then the destination address may be
4727  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4728  * destination reachability, while tunnels do not.
4729  * Note that we allow connect to broadcast and multicast
4730  * addresses when ire_requested is set. Thus the ULP
4731  * has to check for IRE_BROADCAST and multicast.
4732  *
4733  * Returns zero if ok.
4734  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4735  * (for use with TSYSERR reply).
4736  *
4737  * Note: lport and fport are in network byte order.
4738  */
4739 int
4740 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4741     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4742     boolean_t ire_requested, boolean_t ipsec_policy_set,
4743     boolean_t fanout_insert, boolean_t verify_dst)
4744 {
4745 	ire_t		*src_ire;
4746 	ire_t		*dst_ire;
4747 	int		error = 0;
4748 	int 		protocol;
4749 	mblk_t		*policy_mp;
4750 	ire_t		*sire = NULL;
4751 	ire_t		*md_dst_ire = NULL;
4752 	ire_t		*lso_dst_ire = NULL;
4753 	ill_t		*ill = NULL;
4754 	zoneid_t	zoneid;
4755 	ipaddr_t	src_addr = *src_addrp;
4756 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4757 
4758 	src_ire = dst_ire = NULL;
4759 	protocol = *mp->b_wptr & 0xFF;
4760 
4761 	/*
4762 	 * If we never got a disconnect before, clear it now.
4763 	 */
4764 	connp->conn_fully_bound = B_FALSE;
4765 
4766 	if (ipsec_policy_set) {
4767 		policy_mp = mp->b_cont;
4768 	}
4769 
4770 	zoneid = IPCL_ZONEID(connp);
4771 
4772 	if (CLASSD(dst_addr)) {
4773 		/* Pick up an IRE_BROADCAST */
4774 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4775 		    NULL, zoneid, MBLK_GETLABEL(mp),
4776 		    (MATCH_IRE_RECURSIVE |
4777 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4778 		    MATCH_IRE_SECATTR), ipst);
4779 	} else {
4780 		/*
4781 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4782 		 * and onlink ipif is not found set ENETUNREACH error.
4783 		 */
4784 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4785 			ipif_t *ipif;
4786 
4787 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4788 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4789 			if (ipif == NULL) {
4790 				error = ENETUNREACH;
4791 				goto bad_addr;
4792 			}
4793 			ipif_refrele(ipif);
4794 		}
4795 
4796 		if (connp->conn_nexthop_set) {
4797 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4798 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4799 			    MATCH_IRE_SECATTR, ipst);
4800 		} else {
4801 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4802 			    &sire, zoneid, MBLK_GETLABEL(mp),
4803 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4804 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4805 			    MATCH_IRE_SECATTR), ipst);
4806 		}
4807 	}
4808 	/*
4809 	 * dst_ire can't be a broadcast when not ire_requested.
4810 	 * We also prevent ire's with src address INADDR_ANY to
4811 	 * be used, which are created temporarily for
4812 	 * sending out packets from endpoints that have
4813 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4814 	 * reachable.  If verify_dst is false, the destination needn't be
4815 	 * reachable.
4816 	 *
4817 	 * If we match on a reject or black hole, then we've got a
4818 	 * local failure.  May as well fail out the connect() attempt,
4819 	 * since it's never going to succeed.
4820 	 */
4821 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4822 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4823 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4824 		/*
4825 		 * If we're verifying destination reachability, we always want
4826 		 * to complain here.
4827 		 *
4828 		 * If we're not verifying destination reachability but the
4829 		 * destination has a route, we still want to fail on the
4830 		 * temporary address and broadcast address tests.
4831 		 */
4832 		if (verify_dst || (dst_ire != NULL)) {
4833 			if (ip_debug > 2) {
4834 				pr_addr_dbg("ip_bind_connected: bad connected "
4835 				    "dst %s\n", AF_INET, &dst_addr);
4836 			}
4837 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4838 				error = ENETUNREACH;
4839 			else
4840 				error = EHOSTUNREACH;
4841 			goto bad_addr;
4842 		}
4843 	}
4844 
4845 	/*
4846 	 * We now know that routing will allow us to reach the destination.
4847 	 * Check whether Trusted Solaris policy allows communication with this
4848 	 * host, and pretend that the destination is unreachable if not.
4849 	 *
4850 	 * This is never a problem for TCP, since that transport is known to
4851 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4852 	 * handling.  If the remote is unreachable, it will be detected at that
4853 	 * point, so there's no reason to check it here.
4854 	 *
4855 	 * Note that for sendto (and other datagram-oriented friends), this
4856 	 * check is done as part of the data path label computation instead.
4857 	 * The check here is just to make non-TCP connect() report the right
4858 	 * error.
4859 	 */
4860 	if (dst_ire != NULL && is_system_labeled() &&
4861 	    !IPCL_IS_TCP(connp) &&
4862 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4863 	    connp->conn_mac_exempt, ipst) != 0) {
4864 		error = EHOSTUNREACH;
4865 		if (ip_debug > 2) {
4866 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4867 			    AF_INET, &dst_addr);
4868 		}
4869 		goto bad_addr;
4870 	}
4871 
4872 	/*
4873 	 * If the app does a connect(), it means that it will most likely
4874 	 * send more than 1 packet to the destination.  It makes sense
4875 	 * to clear the temporary flag.
4876 	 */
4877 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4878 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4879 		irb_t *irb = dst_ire->ire_bucket;
4880 
4881 		rw_enter(&irb->irb_lock, RW_WRITER);
4882 		/*
4883 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4884 		 * the lock to guarantee irb_tmp_ire_cnt.
4885 		 */
4886 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4887 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4888 			irb->irb_tmp_ire_cnt--;
4889 		}
4890 		rw_exit(&irb->irb_lock);
4891 	}
4892 
4893 	/*
4894 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4895 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4896 	 * eligibility tests for passive connects are handled separately
4897 	 * through tcp_adapt_ire().  We do this before the source address
4898 	 * selection, because dst_ire may change after a call to
4899 	 * ipif_select_source().  This is a best-effort check, as the
4900 	 * packet for this connection may not actually go through
4901 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4902 	 * calling ip_newroute().  This is why we further check on the
4903 	 * IRE during LSO/Multidata packet transmission in
4904 	 * tcp_lsosend()/tcp_multisend().
4905 	 */
4906 	if (!ipsec_policy_set && dst_ire != NULL &&
4907 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4908 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4909 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4910 			lso_dst_ire = dst_ire;
4911 			IRE_REFHOLD(lso_dst_ire);
4912 		} else if (ipst->ips_ip_multidata_outbound &&
4913 		    ILL_MDT_CAPABLE(ill)) {
4914 			md_dst_ire = dst_ire;
4915 			IRE_REFHOLD(md_dst_ire);
4916 		}
4917 	}
4918 
4919 	if (dst_ire != NULL &&
4920 	    dst_ire->ire_type == IRE_LOCAL &&
4921 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4922 		/*
4923 		 * If the IRE belongs to a different zone, look for a matching
4924 		 * route in the forwarding table and use the source address from
4925 		 * that route.
4926 		 */
4927 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4928 		    zoneid, 0, NULL,
4929 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4930 		    MATCH_IRE_RJ_BHOLE, ipst);
4931 		if (src_ire == NULL) {
4932 			error = EHOSTUNREACH;
4933 			goto bad_addr;
4934 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4935 			if (!(src_ire->ire_type & IRE_HOST))
4936 				error = ENETUNREACH;
4937 			else
4938 				error = EHOSTUNREACH;
4939 			goto bad_addr;
4940 		}
4941 		if (src_addr == INADDR_ANY)
4942 			src_addr = src_ire->ire_src_addr;
4943 		ire_refrele(src_ire);
4944 		src_ire = NULL;
4945 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4946 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4947 			src_addr = sire->ire_src_addr;
4948 			ire_refrele(dst_ire);
4949 			dst_ire = sire;
4950 			sire = NULL;
4951 		} else {
4952 			/*
4953 			 * Pick a source address so that a proper inbound
4954 			 * load spreading would happen.
4955 			 */
4956 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4957 			ipif_t *src_ipif = NULL;
4958 			ire_t *ipif_ire;
4959 
4960 			/*
4961 			 * Supply a local source address such that inbound
4962 			 * load spreading happens.
4963 			 *
4964 			 * Determine the best source address on this ill for
4965 			 * the destination.
4966 			 *
4967 			 * 1) For broadcast, we should return a broadcast ire
4968 			 *    found above so that upper layers know that the
4969 			 *    destination address is a broadcast address.
4970 			 *
4971 			 * 2) If this is part of a group, select a better
4972 			 *    source address so that better inbound load
4973 			 *    balancing happens. Do the same if the ipif
4974 			 *    is DEPRECATED.
4975 			 *
4976 			 * 3) If the outgoing interface is part of a usesrc
4977 			 *    group, then try selecting a source address from
4978 			 *    the usesrc ILL.
4979 			 */
4980 			if ((dst_ire->ire_zoneid != zoneid &&
4981 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4982 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4983 			    ((dst_ill->ill_group != NULL) ||
4984 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4985 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4986 				/*
4987 				 * If the destination is reachable via a
4988 				 * given gateway, the selected source address
4989 				 * should be in the same subnet as the gateway.
4990 				 * Otherwise, the destination is not reachable.
4991 				 *
4992 				 * If there are no interfaces on the same subnet
4993 				 * as the destination, ipif_select_source gives
4994 				 * first non-deprecated interface which might be
4995 				 * on a different subnet than the gateway.
4996 				 * This is not desirable. Hence pass the dst_ire
4997 				 * source address to ipif_select_source.
4998 				 * It is sure that the destination is reachable
4999 				 * with the dst_ire source address subnet.
5000 				 * So passing dst_ire source address to
5001 				 * ipif_select_source will make sure that the
5002 				 * selected source will be on the same subnet
5003 				 * as dst_ire source address.
5004 				 */
5005 				ipaddr_t saddr =
5006 				    dst_ire->ire_ipif->ipif_src_addr;
5007 				src_ipif = ipif_select_source(dst_ill,
5008 				    saddr, zoneid);
5009 				if (src_ipif != NULL) {
5010 					if (IS_VNI(src_ipif->ipif_ill)) {
5011 						/*
5012 						 * For VNI there is no
5013 						 * interface route
5014 						 */
5015 						src_addr =
5016 						    src_ipif->ipif_src_addr;
5017 					} else {
5018 						ipif_ire =
5019 						    ipif_to_ire(src_ipif);
5020 						if (ipif_ire != NULL) {
5021 							IRE_REFRELE(dst_ire);
5022 							dst_ire = ipif_ire;
5023 						}
5024 						src_addr =
5025 						    dst_ire->ire_src_addr;
5026 					}
5027 					ipif_refrele(src_ipif);
5028 				} else {
5029 					src_addr = dst_ire->ire_src_addr;
5030 				}
5031 			} else {
5032 				src_addr = dst_ire->ire_src_addr;
5033 			}
5034 		}
5035 	}
5036 
5037 	/*
5038 	 * We do ire_route_lookup() here (and not
5039 	 * interface lookup as we assert that
5040 	 * src_addr should only come from an
5041 	 * UP interface for hard binding.
5042 	 */
5043 	ASSERT(src_ire == NULL);
5044 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5045 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5046 	/* src_ire must be a local|loopback */
5047 	if (!IRE_IS_LOCAL(src_ire)) {
5048 		if (ip_debug > 2) {
5049 			pr_addr_dbg("ip_bind_connected: bad connected "
5050 			    "src %s\n", AF_INET, &src_addr);
5051 		}
5052 		error = EADDRNOTAVAIL;
5053 		goto bad_addr;
5054 	}
5055 
5056 	/*
5057 	 * If the source address is a loopback address, the
5058 	 * destination had best be local or multicast.
5059 	 * The transports that can't handle multicast will reject
5060 	 * those addresses.
5061 	 */
5062 	if (src_ire->ire_type == IRE_LOOPBACK &&
5063 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5064 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5065 		error = -1;
5066 		goto bad_addr;
5067 	}
5068 
5069 	/*
5070 	 * Allow setting new policies. For example, disconnects come
5071 	 * down as ipa_t bind. As we would have set conn_policy_cached
5072 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5073 	 * can change after the disconnect.
5074 	 */
5075 	connp->conn_policy_cached = B_FALSE;
5076 
5077 	/*
5078 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5079 	 * can handle their passed-in conn's.
5080 	 */
5081 
5082 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5083 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5084 	connp->conn_lport = lport;
5085 	connp->conn_fport = fport;
5086 	*src_addrp = src_addr;
5087 
5088 	ASSERT(!(ipsec_policy_set && ire_requested));
5089 	if (ire_requested) {
5090 		iulp_t *ulp_info = NULL;
5091 
5092 		/*
5093 		 * Note that sire will not be NULL if this is an off-link
5094 		 * connection and there is not cache for that dest yet.
5095 		 *
5096 		 * XXX Because of an existing bug, if there are multiple
5097 		 * default routes, the IRE returned now may not be the actual
5098 		 * default route used (default routes are chosen in a
5099 		 * round robin fashion).  So if the metrics for different
5100 		 * default routes are different, we may return the wrong
5101 		 * metrics.  This will not be a problem if the existing
5102 		 * bug is fixed.
5103 		 */
5104 		if (sire != NULL) {
5105 			ulp_info = &(sire->ire_uinfo);
5106 		}
5107 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5108 			error = -1;
5109 			goto bad_addr;
5110 		}
5111 	} else if (ipsec_policy_set) {
5112 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5113 			error = -1;
5114 			goto bad_addr;
5115 		}
5116 	}
5117 
5118 	/*
5119 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5120 	 * we'll cache that.  If we don't, we'll inherit global policy.
5121 	 *
5122 	 * We can't insert until the conn reflects the policy. Note that
5123 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5124 	 * connections where we don't have a policy. This is to prevent
5125 	 * global policy lookups in the inbound path.
5126 	 *
5127 	 * If we insert before we set conn_policy_cached,
5128 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5129 	 * because global policy cound be non-empty. We normally call
5130 	 * ipsec_check_policy() for conn_policy_cached connections only if
5131 	 * ipc_in_enforce_policy is set. But in this case,
5132 	 * conn_policy_cached can get set anytime since we made the
5133 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5134 	 * called, which will make the above assumption false.  Thus, we
5135 	 * need to insert after we set conn_policy_cached.
5136 	 */
5137 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5138 		goto bad_addr;
5139 
5140 	if (fanout_insert) {
5141 		/*
5142 		 * The addresses have been verified. Time to insert in
5143 		 * the correct fanout list.
5144 		 */
5145 		error = ipcl_conn_insert(connp, protocol, src_addr,
5146 		    dst_addr, connp->conn_ports);
5147 	}
5148 
5149 	if (error == 0) {
5150 		connp->conn_fully_bound = B_TRUE;
5151 		/*
5152 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5153 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5154 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5155 		 * ip_xxinfo_return(), which performs further checks
5156 		 * against them and upon success, returns the LSO/MDT info
5157 		 * mblk which we will attach to the bind acknowledgment.
5158 		 */
5159 		if (lso_dst_ire != NULL) {
5160 			mblk_t *lsoinfo_mp;
5161 
5162 			ASSERT(ill->ill_lso_capab != NULL);
5163 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5164 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5165 				linkb(mp, lsoinfo_mp);
5166 		} else if (md_dst_ire != NULL) {
5167 			mblk_t *mdinfo_mp;
5168 
5169 			ASSERT(ill->ill_mdt_capab != NULL);
5170 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5171 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5172 				linkb(mp, mdinfo_mp);
5173 		}
5174 	}
5175 bad_addr:
5176 	if (ipsec_policy_set) {
5177 		ASSERT(policy_mp == mp->b_cont);
5178 		ASSERT(policy_mp != NULL);
5179 		freeb(policy_mp);
5180 		/*
5181 		 * As of now assume that nothing else accompanies
5182 		 * IPSEC_POLICY_SET.
5183 		 */
5184 		mp->b_cont = NULL;
5185 	}
5186 	if (src_ire != NULL)
5187 		IRE_REFRELE(src_ire);
5188 	if (dst_ire != NULL)
5189 		IRE_REFRELE(dst_ire);
5190 	if (sire != NULL)
5191 		IRE_REFRELE(sire);
5192 	if (md_dst_ire != NULL)
5193 		IRE_REFRELE(md_dst_ire);
5194 	if (lso_dst_ire != NULL)
5195 		IRE_REFRELE(lso_dst_ire);
5196 	return (error);
5197 }
5198 
5199 /*
5200  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5201  * Prefers dst_ire over src_ire.
5202  */
5203 static boolean_t
5204 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5205 {
5206 	mblk_t	*mp1;
5207 	ire_t *ret_ire = NULL;
5208 
5209 	mp1 = mp->b_cont;
5210 	ASSERT(mp1 != NULL);
5211 
5212 	if (ire != NULL) {
5213 		/*
5214 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5215 		 * appended mblk. Its <upper protocol>'s
5216 		 * job to make sure there is room.
5217 		 */
5218 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5219 			return (0);
5220 
5221 		mp1->b_datap->db_type = IRE_DB_TYPE;
5222 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5223 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5224 		ret_ire = (ire_t *)mp1->b_rptr;
5225 		/*
5226 		 * Pass the latest setting of the ip_path_mtu_discovery and
5227 		 * copy the ulp info if any.
5228 		 */
5229 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5230 		    IPH_DF : 0;
5231 		if (ulp_info != NULL) {
5232 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5233 			    sizeof (iulp_t));
5234 		}
5235 		ret_ire->ire_mp = mp1;
5236 	} else {
5237 		/*
5238 		 * No IRE was found. Remove IRE mblk.
5239 		 */
5240 		mp->b_cont = mp1->b_cont;
5241 		freeb(mp1);
5242 	}
5243 
5244 	return (1);
5245 }
5246 
5247 /*
5248  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5249  * the final piece where we don't.  Return a pointer to the first mblk in the
5250  * result, and update the pointer to the next mblk to chew on.  If anything
5251  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5252  * NULL pointer.
5253  */
5254 mblk_t *
5255 ip_carve_mp(mblk_t **mpp, ssize_t len)
5256 {
5257 	mblk_t	*mp0;
5258 	mblk_t	*mp1;
5259 	mblk_t	*mp2;
5260 
5261 	if (!len || !mpp || !(mp0 = *mpp))
5262 		return (NULL);
5263 	/* If we aren't going to consume the first mblk, we need a dup. */
5264 	if (mp0->b_wptr - mp0->b_rptr > len) {
5265 		mp1 = dupb(mp0);
5266 		if (mp1) {
5267 			/* Partition the data between the two mblks. */
5268 			mp1->b_wptr = mp1->b_rptr + len;
5269 			mp0->b_rptr = mp1->b_wptr;
5270 			/*
5271 			 * after adjustments if mblk not consumed is now
5272 			 * unaligned, try to align it. If this fails free
5273 			 * all messages and let upper layer recover.
5274 			 */
5275 			if (!OK_32PTR(mp0->b_rptr)) {
5276 				if (!pullupmsg(mp0, -1)) {
5277 					freemsg(mp0);
5278 					freemsg(mp1);
5279 					*mpp = NULL;
5280 					return (NULL);
5281 				}
5282 			}
5283 		}
5284 		return (mp1);
5285 	}
5286 	/* Eat through as many mblks as we need to get len bytes. */
5287 	len -= mp0->b_wptr - mp0->b_rptr;
5288 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5289 		if (mp2->b_wptr - mp2->b_rptr > len) {
5290 			/*
5291 			 * We won't consume the entire last mblk.  Like
5292 			 * above, dup and partition it.
5293 			 */
5294 			mp1->b_cont = dupb(mp2);
5295 			mp1 = mp1->b_cont;
5296 			if (!mp1) {
5297 				/*
5298 				 * Trouble.  Rather than go to a lot of
5299 				 * trouble to clean up, we free the messages.
5300 				 * This won't be any worse than losing it on
5301 				 * the wire.
5302 				 */
5303 				freemsg(mp0);
5304 				freemsg(mp2);
5305 				*mpp = NULL;
5306 				return (NULL);
5307 			}
5308 			mp1->b_wptr = mp1->b_rptr + len;
5309 			mp2->b_rptr = mp1->b_wptr;
5310 			/*
5311 			 * after adjustments if mblk not consumed is now
5312 			 * unaligned, try to align it. If this fails free
5313 			 * all messages and let upper layer recover.
5314 			 */
5315 			if (!OK_32PTR(mp2->b_rptr)) {
5316 				if (!pullupmsg(mp2, -1)) {
5317 					freemsg(mp0);
5318 					freemsg(mp2);
5319 					*mpp = NULL;
5320 					return (NULL);
5321 				}
5322 			}
5323 			*mpp = mp2;
5324 			return (mp0);
5325 		}
5326 		/* Decrement len by the amount we just got. */
5327 		len -= mp2->b_wptr - mp2->b_rptr;
5328 	}
5329 	/*
5330 	 * len should be reduced to zero now.  If not our caller has
5331 	 * screwed up.
5332 	 */
5333 	if (len) {
5334 		/* Shouldn't happen! */
5335 		freemsg(mp0);
5336 		*mpp = NULL;
5337 		return (NULL);
5338 	}
5339 	/*
5340 	 * We consumed up to exactly the end of an mblk.  Detach the part
5341 	 * we are returning from the rest of the chain.
5342 	 */
5343 	mp1->b_cont = NULL;
5344 	*mpp = mp2;
5345 	return (mp0);
5346 }
5347 
5348 /* The ill stream is being unplumbed. Called from ip_close */
5349 int
5350 ip_modclose(ill_t *ill)
5351 {
5352 	boolean_t success;
5353 	ipsq_t	*ipsq;
5354 	ipif_t	*ipif;
5355 	queue_t	*q = ill->ill_rq;
5356 	ip_stack_t	*ipst = ill->ill_ipst;
5357 	clock_t timeout;
5358 
5359 	/*
5360 	 * Wait for the ACKs of all deferred control messages to be processed.
5361 	 * In particular, we wait for a potential capability reset initiated
5362 	 * in ip_sioctl_plink() to complete before proceeding.
5363 	 *
5364 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5365 	 * in case the driver never replies.
5366 	 */
5367 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5368 	mutex_enter(&ill->ill_lock);
5369 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5370 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5371 			/* Timeout */
5372 			break;
5373 		}
5374 	}
5375 	mutex_exit(&ill->ill_lock);
5376 
5377 	/*
5378 	 * Forcibly enter the ipsq after some delay. This is to take
5379 	 * care of the case when some ioctl does not complete because
5380 	 * we sent a control message to the driver and it did not
5381 	 * send us a reply. We want to be able to at least unplumb
5382 	 * and replumb rather than force the user to reboot the system.
5383 	 */
5384 	success = ipsq_enter(ill, B_FALSE);
5385 
5386 	/*
5387 	 * Open/close/push/pop is guaranteed to be single threaded
5388 	 * per stream by STREAMS. FS guarantees that all references
5389 	 * from top are gone before close is called. So there can't
5390 	 * be another close thread that has set CONDEMNED on this ill.
5391 	 * and cause ipsq_enter to return failure.
5392 	 */
5393 	ASSERT(success);
5394 	ipsq = ill->ill_phyint->phyint_ipsq;
5395 
5396 	/*
5397 	 * Mark it condemned. No new reference will be made to this ill.
5398 	 * Lookup functions will return an error. Threads that try to
5399 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5400 	 * that the refcnt will drop down to zero.
5401 	 */
5402 	mutex_enter(&ill->ill_lock);
5403 	ill->ill_state_flags |= ILL_CONDEMNED;
5404 	for (ipif = ill->ill_ipif; ipif != NULL;
5405 	    ipif = ipif->ipif_next) {
5406 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5407 	}
5408 	/*
5409 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5410 	 * returns  error if ILL_CONDEMNED is set
5411 	 */
5412 	cv_broadcast(&ill->ill_cv);
5413 	mutex_exit(&ill->ill_lock);
5414 
5415 	/*
5416 	 * Send all the deferred DLPI messages downstream which came in
5417 	 * during the small window right before ipsq_enter(). We do this
5418 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5419 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5420 	 */
5421 	ill_dlpi_send_deferred(ill);
5422 
5423 	/*
5424 	 * Shut down fragmentation reassembly.
5425 	 * ill_frag_timer won't start a timer again.
5426 	 * Now cancel any existing timer
5427 	 */
5428 	(void) untimeout(ill->ill_frag_timer_id);
5429 	(void) ill_frag_timeout(ill, 0);
5430 
5431 	/*
5432 	 * If MOVE was in progress, clear the
5433 	 * move_in_progress fields also.
5434 	 */
5435 	if (ill->ill_move_in_progress) {
5436 		ILL_CLEAR_MOVE(ill);
5437 	}
5438 
5439 	/*
5440 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5441 	 * this ill. Then wait for the refcnts to drop to zero.
5442 	 * ill_is_quiescent checks whether the ill is really quiescent.
5443 	 * Then make sure that threads that are waiting to enter the
5444 	 * ipsq have seen the error returned by ipsq_enter and have
5445 	 * gone away. Then we call ill_delete_tail which does the
5446 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5447 	 */
5448 	ill_delete(ill);
5449 	mutex_enter(&ill->ill_lock);
5450 	while (!ill_is_quiescent(ill))
5451 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5452 	while (ill->ill_waiters)
5453 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5454 
5455 	mutex_exit(&ill->ill_lock);
5456 
5457 	/*
5458 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5459 	 * it held until the end of the function since the cleanup
5460 	 * below needs to be able to use the ip_stack_t.
5461 	 */
5462 	netstack_hold(ipst->ips_netstack);
5463 
5464 	/* qprocsoff is called in ill_delete_tail */
5465 	ill_delete_tail(ill);
5466 	ASSERT(ill->ill_ipst == NULL);
5467 
5468 	/*
5469 	 * Walk through all upper (conn) streams and qenable
5470 	 * those that have queued data.
5471 	 * close synchronization needs this to
5472 	 * be done to ensure that all upper layers blocked
5473 	 * due to flow control to the closing device
5474 	 * get unblocked.
5475 	 */
5476 	ip1dbg(("ip_wsrv: walking\n"));
5477 	conn_walk_drain(ipst);
5478 
5479 	mutex_enter(&ipst->ips_ip_mi_lock);
5480 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5481 	mutex_exit(&ipst->ips_ip_mi_lock);
5482 
5483 	/*
5484 	 * credp could be null if the open didn't succeed and ip_modopen
5485 	 * itself calls ip_close.
5486 	 */
5487 	if (ill->ill_credp != NULL)
5488 		crfree(ill->ill_credp);
5489 
5490 	mutex_enter(&ill->ill_lock);
5491 	ill_nic_info_dispatch(ill);
5492 	mutex_exit(&ill->ill_lock);
5493 
5494 	/*
5495 	 * Now we are done with the module close pieces that
5496 	 * need the netstack_t.
5497 	 */
5498 	netstack_rele(ipst->ips_netstack);
5499 
5500 	mi_close_free((IDP)ill);
5501 	q->q_ptr = WR(q)->q_ptr = NULL;
5502 
5503 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5504 
5505 	return (0);
5506 }
5507 
5508 /*
5509  * This is called as part of close() for IP, UDP, ICMP, and RTS
5510  * in order to quiesce the conn.
5511  */
5512 void
5513 ip_quiesce_conn(conn_t *connp)
5514 {
5515 	boolean_t	drain_cleanup_reqd = B_FALSE;
5516 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5517 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5518 	ip_stack_t	*ipst;
5519 
5520 	ASSERT(!IPCL_IS_TCP(connp));
5521 	ipst = connp->conn_netstack->netstack_ip;
5522 
5523 	/*
5524 	 * Mark the conn as closing, and this conn must not be
5525 	 * inserted in future into any list. Eg. conn_drain_insert(),
5526 	 * won't insert this conn into the conn_drain_list.
5527 	 * Similarly ill_pending_mp_add() will not add any mp to
5528 	 * the pending mp list, after this conn has started closing.
5529 	 *
5530 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5531 	 * cannot get set henceforth.
5532 	 */
5533 	mutex_enter(&connp->conn_lock);
5534 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5535 	connp->conn_state_flags |= CONN_CLOSING;
5536 	if (connp->conn_idl != NULL)
5537 		drain_cleanup_reqd = B_TRUE;
5538 	if (connp->conn_oper_pending_ill != NULL)
5539 		conn_ioctl_cleanup_reqd = B_TRUE;
5540 	if (connp->conn_dhcpinit_ill != NULL) {
5541 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5542 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5543 		connp->conn_dhcpinit_ill = NULL;
5544 	}
5545 	if (connp->conn_ilg_inuse != 0)
5546 		ilg_cleanup_reqd = B_TRUE;
5547 	mutex_exit(&connp->conn_lock);
5548 
5549 	if (conn_ioctl_cleanup_reqd)
5550 		conn_ioctl_cleanup(connp);
5551 
5552 	if (is_system_labeled() && connp->conn_anon_port) {
5553 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5554 		    connp->conn_mlp_type, connp->conn_ulp,
5555 		    ntohs(connp->conn_lport), B_FALSE);
5556 		connp->conn_anon_port = 0;
5557 	}
5558 	connp->conn_mlp_type = mlptSingle;
5559 
5560 	/*
5561 	 * Remove this conn from any fanout list it is on.
5562 	 * and then wait for any threads currently operating
5563 	 * on this endpoint to finish
5564 	 */
5565 	ipcl_hash_remove(connp);
5566 
5567 	/*
5568 	 * Remove this conn from the drain list, and do
5569 	 * any other cleanup that may be required.
5570 	 * (Only non-tcp streams may have a non-null conn_idl.
5571 	 * TCP streams are never flow controlled, and
5572 	 * conn_idl will be null)
5573 	 */
5574 	if (drain_cleanup_reqd)
5575 		conn_drain_tail(connp, B_TRUE);
5576 
5577 	if (connp == ipst->ips_ip_g_mrouter)
5578 		(void) ip_mrouter_done(NULL, ipst);
5579 
5580 	if (ilg_cleanup_reqd)
5581 		ilg_delete_all(connp);
5582 
5583 	conn_delete_ire(connp, NULL);
5584 
5585 	/*
5586 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5587 	 * callers from write side can't be there now because close
5588 	 * is in progress. The only other caller is ipcl_walk
5589 	 * which checks for the condemned flag.
5590 	 */
5591 	mutex_enter(&connp->conn_lock);
5592 	connp->conn_state_flags |= CONN_CONDEMNED;
5593 	while (connp->conn_ref != 1)
5594 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5595 	connp->conn_state_flags |= CONN_QUIESCED;
5596 	mutex_exit(&connp->conn_lock);
5597 }
5598 
5599 /* ARGSUSED */
5600 int
5601 ip_close(queue_t *q, int flags)
5602 {
5603 	conn_t		*connp;
5604 
5605 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5606 
5607 	/*
5608 	 * Call the appropriate delete routine depending on whether this is
5609 	 * a module or device.
5610 	 */
5611 	if (WR(q)->q_next != NULL) {
5612 		/* This is a module close */
5613 		return (ip_modclose((ill_t *)q->q_ptr));
5614 	}
5615 
5616 	connp = q->q_ptr;
5617 	ip_quiesce_conn(connp);
5618 
5619 	qprocsoff(q);
5620 
5621 	/*
5622 	 * Now we are truly single threaded on this stream, and can
5623 	 * delete the things hanging off the connp, and finally the connp.
5624 	 * We removed this connp from the fanout list, it cannot be
5625 	 * accessed thru the fanouts, and we already waited for the
5626 	 * conn_ref to drop to 0. We are already in close, so
5627 	 * there cannot be any other thread from the top. qprocsoff
5628 	 * has completed, and service has completed or won't run in
5629 	 * future.
5630 	 */
5631 	ASSERT(connp->conn_ref == 1);
5632 
5633 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5634 
5635 	connp->conn_ref--;
5636 	ipcl_conn_destroy(connp);
5637 
5638 	q->q_ptr = WR(q)->q_ptr = NULL;
5639 	return (0);
5640 }
5641 
5642 /*
5643  * Wapper around putnext() so that ip_rts_request can merely use
5644  * conn_recv.
5645  */
5646 /*ARGSUSED2*/
5647 static void
5648 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5649 {
5650 	conn_t *connp = (conn_t *)arg1;
5651 
5652 	putnext(connp->conn_rq, mp);
5653 }
5654 
5655 /* Return the IP checksum for the IP header at "iph". */
5656 uint16_t
5657 ip_csum_hdr(ipha_t *ipha)
5658 {
5659 	uint16_t	*uph;
5660 	uint32_t	sum;
5661 	int		opt_len;
5662 
5663 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5664 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5665 	uph = (uint16_t *)ipha;
5666 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5667 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5668 	if (opt_len > 0) {
5669 		do {
5670 			sum += uph[10];
5671 			sum += uph[11];
5672 			uph += 2;
5673 		} while (--opt_len);
5674 	}
5675 	sum = (sum & 0xFFFF) + (sum >> 16);
5676 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5677 	if (sum == 0xffff)
5678 		sum = 0;
5679 	return ((uint16_t)sum);
5680 }
5681 
5682 /*
5683  * Called when the module is about to be unloaded
5684  */
5685 void
5686 ip_ddi_destroy(void)
5687 {
5688 	tnet_fini();
5689 
5690 	icmp_ddi_destroy();
5691 	rts_ddi_destroy();
5692 	udp_ddi_destroy();
5693 	sctp_ddi_g_destroy();
5694 	tcp_ddi_g_destroy();
5695 	ipsec_policy_g_destroy();
5696 	ipcl_g_destroy();
5697 	ip_net_g_destroy();
5698 	ip_ire_g_fini();
5699 	inet_minor_destroy(ip_minor_arena_sa);
5700 #if defined(_LP64)
5701 	inet_minor_destroy(ip_minor_arena_la);
5702 #endif
5703 
5704 #ifdef DEBUG
5705 	list_destroy(&ip_thread_list);
5706 	rw_destroy(&ip_thread_rwlock);
5707 	tsd_destroy(&ip_thread_data);
5708 #endif
5709 
5710 	netstack_unregister(NS_IP);
5711 }
5712 
5713 /*
5714  * First step in cleanup.
5715  */
5716 /* ARGSUSED */
5717 static void
5718 ip_stack_shutdown(netstackid_t stackid, void *arg)
5719 {
5720 	ip_stack_t *ipst = (ip_stack_t *)arg;
5721 
5722 #ifdef NS_DEBUG
5723 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5724 #endif
5725 
5726 	/* Get rid of loopback interfaces and their IREs */
5727 	ip_loopback_cleanup(ipst);
5728 }
5729 
5730 /*
5731  * Free the IP stack instance.
5732  */
5733 static void
5734 ip_stack_fini(netstackid_t stackid, void *arg)
5735 {
5736 	ip_stack_t *ipst = (ip_stack_t *)arg;
5737 	int ret;
5738 
5739 #ifdef NS_DEBUG
5740 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5741 #endif
5742 	ipv4_hook_destroy(ipst);
5743 	ipv6_hook_destroy(ipst);
5744 	ip_net_destroy(ipst);
5745 
5746 	rw_destroy(&ipst->ips_srcid_lock);
5747 
5748 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5749 	ipst->ips_ip_mibkp = NULL;
5750 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5751 	ipst->ips_icmp_mibkp = NULL;
5752 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5753 	ipst->ips_ip_kstat = NULL;
5754 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5755 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5756 	ipst->ips_ip6_kstat = NULL;
5757 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5758 
5759 	nd_free(&ipst->ips_ip_g_nd);
5760 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5761 	ipst->ips_param_arr = NULL;
5762 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5763 	ipst->ips_ndp_arr = NULL;
5764 
5765 	ip_mrouter_stack_destroy(ipst);
5766 
5767 	mutex_destroy(&ipst->ips_ip_mi_lock);
5768 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5769 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5770 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5771 
5772 	ret = untimeout(ipst->ips_igmp_timeout_id);
5773 	if (ret == -1) {
5774 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5775 	} else {
5776 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5777 		ipst->ips_igmp_timeout_id = 0;
5778 	}
5779 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5780 	if (ret == -1) {
5781 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5782 	} else {
5783 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5784 		ipst->ips_igmp_slowtimeout_id = 0;
5785 	}
5786 	ret = untimeout(ipst->ips_mld_timeout_id);
5787 	if (ret == -1) {
5788 		ASSERT(ipst->ips_mld_timeout_id == 0);
5789 	} else {
5790 		ASSERT(ipst->ips_mld_timeout_id != 0);
5791 		ipst->ips_mld_timeout_id = 0;
5792 	}
5793 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5794 	if (ret == -1) {
5795 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5796 	} else {
5797 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5798 		ipst->ips_mld_slowtimeout_id = 0;
5799 	}
5800 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5801 	if (ret == -1) {
5802 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5803 	} else {
5804 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5805 		ipst->ips_ip_ire_expire_id = 0;
5806 	}
5807 
5808 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5809 	mutex_destroy(&ipst->ips_mld_timer_lock);
5810 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5811 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5812 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5813 	rw_destroy(&ipst->ips_ill_g_lock);
5814 
5815 	ip_ire_fini(ipst);
5816 	ip6_asp_free(ipst);
5817 	conn_drain_fini(ipst);
5818 	ipcl_destroy(ipst);
5819 
5820 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5821 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5822 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5823 	ipst->ips_ndp4 = NULL;
5824 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5825 	ipst->ips_ndp6 = NULL;
5826 
5827 	if (ipst->ips_loopback_ksp != NULL) {
5828 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5829 		ipst->ips_loopback_ksp = NULL;
5830 	}
5831 
5832 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5833 	ipst->ips_phyint_g_list = NULL;
5834 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5835 	ipst->ips_ill_g_heads = NULL;
5836 
5837 	kmem_free(ipst, sizeof (*ipst));
5838 }
5839 
5840 /*
5841  * This function is called from the TSD destructor, and is used to debug
5842  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5843  * details.
5844  */
5845 static void
5846 ip_thread_exit(void *phash)
5847 {
5848 	th_hash_t *thh = phash;
5849 
5850 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5851 	list_remove(&ip_thread_list, thh);
5852 	rw_exit(&ip_thread_rwlock);
5853 	mod_hash_destroy_hash(thh->thh_hash);
5854 	kmem_free(thh, sizeof (*thh));
5855 }
5856 
5857 /*
5858  * Called when the IP kernel module is loaded into the kernel
5859  */
5860 void
5861 ip_ddi_init(void)
5862 {
5863 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5864 
5865 	/*
5866 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5867 	 * initial devices: ip, ip6, tcp, tcp6.
5868 	 */
5869 	/*
5870 	 * If this is a 64-bit kernel, then create two separate arenas -
5871 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5872 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5873 	 */
5874 	ip_minor_arena_la = NULL;
5875 	ip_minor_arena_sa = NULL;
5876 #if defined(_LP64)
5877 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5878 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5879 		cmn_err(CE_PANIC,
5880 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5881 	}
5882 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5883 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5884 		cmn_err(CE_PANIC,
5885 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5886 	}
5887 #else
5888 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5889 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5890 		cmn_err(CE_PANIC,
5891 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5892 	}
5893 #endif
5894 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5895 
5896 	ipcl_g_init();
5897 	ip_ire_g_init();
5898 	ip_net_g_init();
5899 
5900 #ifdef DEBUG
5901 	tsd_create(&ip_thread_data, ip_thread_exit);
5902 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5903 	list_create(&ip_thread_list, sizeof (th_hash_t),
5904 	    offsetof(th_hash_t, thh_link));
5905 #endif
5906 
5907 	/*
5908 	 * We want to be informed each time a stack is created or
5909 	 * destroyed in the kernel, so we can maintain the
5910 	 * set of udp_stack_t's.
5911 	 */
5912 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5913 	    ip_stack_fini);
5914 
5915 	ipsec_policy_g_init();
5916 	tcp_ddi_g_init();
5917 	sctp_ddi_g_init();
5918 
5919 	tnet_init();
5920 
5921 	udp_ddi_init();
5922 	rts_ddi_init();
5923 	icmp_ddi_init();
5924 }
5925 
5926 /*
5927  * Initialize the IP stack instance.
5928  */
5929 static void *
5930 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5931 {
5932 	ip_stack_t	*ipst;
5933 	ipparam_t	*pa;
5934 	ipndp_t		*na;
5935 
5936 #ifdef NS_DEBUG
5937 	printf("ip_stack_init(stack %d)\n", stackid);
5938 #endif
5939 
5940 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5941 	ipst->ips_netstack = ns;
5942 
5943 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5944 	    KM_SLEEP);
5945 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5946 	    KM_SLEEP);
5947 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5948 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5949 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5950 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5951 
5952 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5953 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5954 	ipst->ips_igmp_deferred_next = INFINITY;
5955 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5956 	ipst->ips_mld_deferred_next = INFINITY;
5957 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5958 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5959 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5960 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5961 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5962 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5963 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5964 
5965 	ipcl_init(ipst);
5966 	ip_ire_init(ipst);
5967 	ip6_asp_init(ipst);
5968 	ipif_init(ipst);
5969 	conn_drain_init(ipst);
5970 	ip_mrouter_stack_init(ipst);
5971 
5972 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5973 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5974 
5975 	ipst->ips_ip_multirt_log_interval = 1000;
5976 
5977 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5978 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5979 	ipst->ips_ill_index = 1;
5980 
5981 	ipst->ips_saved_ip_g_forward = -1;
5982 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5983 
5984 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5985 	ipst->ips_param_arr = pa;
5986 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5987 
5988 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5989 	ipst->ips_ndp_arr = na;
5990 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5991 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5992 	    (caddr_t)&ipst->ips_ip_g_forward;
5993 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5994 	    (caddr_t)&ipst->ips_ipv6_forward;
5995 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5996 	    "ip_cgtp_filter") == 0);
5997 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5998 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5999 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6000 	    "ipmp_hook_emulation") == 0);
6001 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6002 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6003 
6004 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6005 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6006 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6007 
6008 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6009 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6010 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6011 	ipst->ips_ip6_kstat =
6012 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6013 
6014 	ipst->ips_ipmp_enable_failback = B_TRUE;
6015 
6016 	ipst->ips_ip_src_id = 1;
6017 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6018 
6019 	ip_net_init(ipst, ns);
6020 	ipv4_hook_init(ipst);
6021 	ipv6_hook_init(ipst);
6022 
6023 	return (ipst);
6024 }
6025 
6026 /*
6027  * Allocate and initialize a DLPI template of the specified length.  (May be
6028  * called as writer.)
6029  */
6030 mblk_t *
6031 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6032 {
6033 	mblk_t	*mp;
6034 
6035 	mp = allocb(len, BPRI_MED);
6036 	if (!mp)
6037 		return (NULL);
6038 
6039 	/*
6040 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6041 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6042 	 * that other DLPI are M_PROTO.
6043 	 */
6044 	if (prim == DL_INFO_REQ) {
6045 		mp->b_datap->db_type = M_PCPROTO;
6046 	} else {
6047 		mp->b_datap->db_type = M_PROTO;
6048 	}
6049 
6050 	mp->b_wptr = mp->b_rptr + len;
6051 	bzero(mp->b_rptr, len);
6052 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6053 	return (mp);
6054 }
6055 
6056 /*
6057  * Debug formatting routine.  Returns a character string representation of the
6058  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6059  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6060  *
6061  * Once the ndd table-printing interfaces are removed, this can be changed to
6062  * standard dotted-decimal form.
6063  */
6064 char *
6065 ip_dot_addr(ipaddr_t addr, char *buf)
6066 {
6067 	uint8_t *ap = (uint8_t *)&addr;
6068 
6069 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6070 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6071 	return (buf);
6072 }
6073 
6074 /*
6075  * Write the given MAC address as a printable string in the usual colon-
6076  * separated format.
6077  */
6078 const char *
6079 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6080 {
6081 	char *bp;
6082 
6083 	if (alen == 0 || buflen < 4)
6084 		return ("?");
6085 	bp = buf;
6086 	for (;;) {
6087 		/*
6088 		 * If there are more MAC address bytes available, but we won't
6089 		 * have any room to print them, then add "..." to the string
6090 		 * instead.  See below for the 'magic number' explanation.
6091 		 */
6092 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6093 			(void) strcpy(bp, "...");
6094 			break;
6095 		}
6096 		(void) sprintf(bp, "%02x", *addr++);
6097 		bp += 2;
6098 		if (--alen == 0)
6099 			break;
6100 		*bp++ = ':';
6101 		buflen -= 3;
6102 		/*
6103 		 * At this point, based on the first 'if' statement above,
6104 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6105 		 * buflen >= 4.  The first case leaves room for the final "xx"
6106 		 * number and trailing NUL byte.  The second leaves room for at
6107 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6108 		 * that statement.
6109 		 */
6110 	}
6111 	return (buf);
6112 }
6113 
6114 /*
6115  * Send an ICMP error after patching up the packet appropriately.  Returns
6116  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6117  */
6118 static boolean_t
6119 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6120     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6121     zoneid_t zoneid, ip_stack_t *ipst)
6122 {
6123 	ipha_t *ipha;
6124 	mblk_t *first_mp;
6125 	boolean_t secure;
6126 	unsigned char db_type;
6127 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6128 
6129 	first_mp = mp;
6130 	if (mctl_present) {
6131 		mp = mp->b_cont;
6132 		secure = ipsec_in_is_secure(first_mp);
6133 		ASSERT(mp != NULL);
6134 	} else {
6135 		/*
6136 		 * If this is an ICMP error being reported - which goes
6137 		 * up as M_CTLs, we need to convert them to M_DATA till
6138 		 * we finish checking with global policy because
6139 		 * ipsec_check_global_policy() assumes M_DATA as clear
6140 		 * and M_CTL as secure.
6141 		 */
6142 		db_type = DB_TYPE(mp);
6143 		DB_TYPE(mp) = M_DATA;
6144 		secure = B_FALSE;
6145 	}
6146 	/*
6147 	 * We are generating an icmp error for some inbound packet.
6148 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6149 	 * Before we generate an error, check with global policy
6150 	 * to see whether this is allowed to enter the system. As
6151 	 * there is no "conn", we are checking with global policy.
6152 	 */
6153 	ipha = (ipha_t *)mp->b_rptr;
6154 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6155 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6156 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6157 		if (first_mp == NULL)
6158 			return (B_FALSE);
6159 	}
6160 
6161 	if (!mctl_present)
6162 		DB_TYPE(mp) = db_type;
6163 
6164 	if (flags & IP_FF_SEND_ICMP) {
6165 		if (flags & IP_FF_HDR_COMPLETE) {
6166 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6167 				freemsg(first_mp);
6168 				return (B_TRUE);
6169 			}
6170 		}
6171 		if (flags & IP_FF_CKSUM) {
6172 			/*
6173 			 * Have to correct checksum since
6174 			 * the packet might have been
6175 			 * fragmented and the reassembly code in ip_rput
6176 			 * does not restore the IP checksum.
6177 			 */
6178 			ipha->ipha_hdr_checksum = 0;
6179 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6180 		}
6181 		switch (icmp_type) {
6182 		case ICMP_DEST_UNREACHABLE:
6183 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6184 			    ipst);
6185 			break;
6186 		default:
6187 			freemsg(first_mp);
6188 			break;
6189 		}
6190 	} else {
6191 		freemsg(first_mp);
6192 		return (B_FALSE);
6193 	}
6194 
6195 	return (B_TRUE);
6196 }
6197 
6198 /*
6199  * Used to send an ICMP error message when a packet is received for
6200  * a protocol that is not supported. The mblk passed as argument
6201  * is consumed by this function.
6202  */
6203 void
6204 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6205     ip_stack_t *ipst)
6206 {
6207 	mblk_t *mp;
6208 	ipha_t *ipha;
6209 	ill_t *ill;
6210 	ipsec_in_t *ii;
6211 
6212 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6213 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6214 
6215 	mp = ipsec_mp->b_cont;
6216 	ipsec_mp->b_cont = NULL;
6217 	ipha = (ipha_t *)mp->b_rptr;
6218 	/* Get ill from index in ipsec_in_t. */
6219 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6220 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6221 	    ipst);
6222 	if (ill != NULL) {
6223 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6224 			if (ip_fanout_send_icmp(q, mp, flags,
6225 			    ICMP_DEST_UNREACHABLE,
6226 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6227 				BUMP_MIB(ill->ill_ip_mib,
6228 				    ipIfStatsInUnknownProtos);
6229 			}
6230 		} else {
6231 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6232 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6233 			    0, B_FALSE, zoneid, ipst)) {
6234 				BUMP_MIB(ill->ill_ip_mib,
6235 				    ipIfStatsInUnknownProtos);
6236 			}
6237 		}
6238 		ill_refrele(ill);
6239 	} else { /* re-link for the freemsg() below. */
6240 		ipsec_mp->b_cont = mp;
6241 	}
6242 
6243 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6244 	freemsg(ipsec_mp);
6245 }
6246 
6247 /*
6248  * See if the inbound datagram has had IPsec processing applied to it.
6249  */
6250 boolean_t
6251 ipsec_in_is_secure(mblk_t *ipsec_mp)
6252 {
6253 	ipsec_in_t *ii;
6254 
6255 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6256 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6257 
6258 	if (ii->ipsec_in_loopback) {
6259 		return (ii->ipsec_in_secure);
6260 	} else {
6261 		return (ii->ipsec_in_ah_sa != NULL ||
6262 		    ii->ipsec_in_esp_sa != NULL ||
6263 		    ii->ipsec_in_decaps);
6264 	}
6265 }
6266 
6267 /*
6268  * Handle protocols with which IP is less intimate.  There
6269  * can be more than one stream bound to a particular
6270  * protocol.  When this is the case, normally each one gets a copy
6271  * of any incoming packets.
6272  *
6273  * IPsec NOTE :
6274  *
6275  * Don't allow a secure packet going up a non-secure connection.
6276  * We don't allow this because
6277  *
6278  * 1) Reply might go out in clear which will be dropped at
6279  *    the sending side.
6280  * 2) If the reply goes out in clear it will give the
6281  *    adversary enough information for getting the key in
6282  *    most of the cases.
6283  *
6284  * Moreover getting a secure packet when we expect clear
6285  * implies that SA's were added without checking for
6286  * policy on both ends. This should not happen once ISAKMP
6287  * is used to negotiate SAs as SAs will be added only after
6288  * verifying the policy.
6289  *
6290  * NOTE : If the packet was tunneled and not multicast we only send
6291  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6292  * back to delivering packets to AF_INET6 raw sockets.
6293  *
6294  * IPQoS Notes:
6295  * Once we have determined the client, invoke IPPF processing.
6296  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6297  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6298  * ip_policy will be false.
6299  *
6300  * Zones notes:
6301  * Currently only applications in the global zone can create raw sockets for
6302  * protocols other than ICMP. So unlike the broadcast / multicast case of
6303  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6304  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6305  */
6306 static void
6307 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6308     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6309     zoneid_t zoneid)
6310 {
6311 	queue_t	*rq;
6312 	mblk_t	*mp1, *first_mp1;
6313 	uint_t	protocol = ipha->ipha_protocol;
6314 	ipaddr_t dst;
6315 	boolean_t one_only;
6316 	mblk_t *first_mp = mp;
6317 	boolean_t secure;
6318 	uint32_t ill_index;
6319 	conn_t	*connp, *first_connp, *next_connp;
6320 	connf_t	*connfp;
6321 	boolean_t shared_addr;
6322 	mib2_ipIfStatsEntry_t *mibptr;
6323 	ip_stack_t *ipst = recv_ill->ill_ipst;
6324 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6325 
6326 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6327 	if (mctl_present) {
6328 		mp = first_mp->b_cont;
6329 		secure = ipsec_in_is_secure(first_mp);
6330 		ASSERT(mp != NULL);
6331 	} else {
6332 		secure = B_FALSE;
6333 	}
6334 	dst = ipha->ipha_dst;
6335 	/*
6336 	 * If the packet was tunneled and not multicast we only send to it
6337 	 * the first match.
6338 	 */
6339 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6340 	    !CLASSD(dst));
6341 
6342 	shared_addr = (zoneid == ALL_ZONES);
6343 	if (shared_addr) {
6344 		/*
6345 		 * We don't allow multilevel ports for raw IP, so no need to
6346 		 * check for that here.
6347 		 */
6348 		zoneid = tsol_packet_to_zoneid(mp);
6349 	}
6350 
6351 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6352 	mutex_enter(&connfp->connf_lock);
6353 	connp = connfp->connf_head;
6354 	for (connp = connfp->connf_head; connp != NULL;
6355 	    connp = connp->conn_next) {
6356 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6357 		    zoneid) &&
6358 		    (!is_system_labeled() ||
6359 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6360 		    connp))) {
6361 			break;
6362 		}
6363 	}
6364 
6365 	if (connp == NULL || connp->conn_upq == NULL) {
6366 		/*
6367 		 * No one bound to these addresses.  Is
6368 		 * there a client that wants all
6369 		 * unclaimed datagrams?
6370 		 */
6371 		mutex_exit(&connfp->connf_lock);
6372 		/*
6373 		 * Check for IPPROTO_ENCAP...
6374 		 */
6375 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6376 			/*
6377 			 * If an IPsec mblk is here on a multicast
6378 			 * tunnel (using ip_mroute stuff), check policy here,
6379 			 * THEN ship off to ip_mroute_decap().
6380 			 *
6381 			 * BTW,  If I match a configured IP-in-IP
6382 			 * tunnel, this path will not be reached, and
6383 			 * ip_mroute_decap will never be called.
6384 			 */
6385 			first_mp = ipsec_check_global_policy(first_mp, connp,
6386 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6387 			if (first_mp != NULL) {
6388 				if (mctl_present)
6389 					freeb(first_mp);
6390 				ip_mroute_decap(q, mp, ill);
6391 			} /* Else we already freed everything! */
6392 		} else {
6393 			/*
6394 			 * Otherwise send an ICMP protocol unreachable.
6395 			 */
6396 			if (ip_fanout_send_icmp(q, first_mp, flags,
6397 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6398 			    mctl_present, zoneid, ipst)) {
6399 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6400 			}
6401 		}
6402 		return;
6403 	}
6404 	CONN_INC_REF(connp);
6405 	first_connp = connp;
6406 
6407 	/*
6408 	 * Only send message to one tunnel driver by immediately
6409 	 * terminating the loop.
6410 	 */
6411 	connp = one_only ? NULL : connp->conn_next;
6412 
6413 	for (;;) {
6414 		while (connp != NULL) {
6415 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6416 			    flags, zoneid) &&
6417 			    (!is_system_labeled() ||
6418 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6419 			    shared_addr, connp)))
6420 				break;
6421 			connp = connp->conn_next;
6422 		}
6423 
6424 		/*
6425 		 * Copy the packet.
6426 		 */
6427 		if (connp == NULL || connp->conn_upq == NULL ||
6428 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6429 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6430 			/*
6431 			 * No more interested clients or memory
6432 			 * allocation failed
6433 			 */
6434 			connp = first_connp;
6435 			break;
6436 		}
6437 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6438 		CONN_INC_REF(connp);
6439 		mutex_exit(&connfp->connf_lock);
6440 		rq = connp->conn_rq;
6441 		if (!canputnext(rq)) {
6442 			if (flags & IP_FF_RAWIP) {
6443 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6444 			} else {
6445 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6446 			}
6447 
6448 			freemsg(first_mp1);
6449 		} else {
6450 			/*
6451 			 * Don't enforce here if we're an actual tunnel -
6452 			 * let "tun" do it instead.
6453 			 */
6454 			if (!IPCL_IS_IPTUN(connp) &&
6455 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6456 			    secure)) {
6457 				first_mp1 = ipsec_check_inbound_policy
6458 				    (first_mp1, connp, ipha, NULL,
6459 				    mctl_present);
6460 			}
6461 			if (first_mp1 != NULL) {
6462 				int in_flags = 0;
6463 				/*
6464 				 * ip_fanout_proto also gets called from
6465 				 * icmp_inbound_error_fanout, in which case
6466 				 * the msg type is M_CTL.  Don't add info
6467 				 * in this case for the time being. In future
6468 				 * when there is a need for knowing the
6469 				 * inbound iface index for ICMP error msgs,
6470 				 * then this can be changed.
6471 				 */
6472 				if (connp->conn_recvif)
6473 					in_flags = IPF_RECVIF;
6474 				/*
6475 				 * The ULP may support IP_RECVPKTINFO for both
6476 				 * IP v4 and v6 so pass the appropriate argument
6477 				 * based on conn IP version.
6478 				 */
6479 				if (connp->conn_ip_recvpktinfo) {
6480 					if (connp->conn_af_isv6) {
6481 						/*
6482 						 * V6 only needs index
6483 						 */
6484 						in_flags |= IPF_RECVIF;
6485 					} else {
6486 						/*
6487 						 * V4 needs index +
6488 						 * matching address.
6489 						 */
6490 						in_flags |= IPF_RECVADDR;
6491 					}
6492 				}
6493 				if ((in_flags != 0) &&
6494 				    (mp->b_datap->db_type != M_CTL)) {
6495 					/*
6496 					 * the actual data will be
6497 					 * contained in b_cont upon
6498 					 * successful return of the
6499 					 * following call else
6500 					 * original mblk is returned
6501 					 */
6502 					ASSERT(recv_ill != NULL);
6503 					mp1 = ip_add_info(mp1, recv_ill,
6504 					    in_flags, IPCL_ZONEID(connp), ipst);
6505 				}
6506 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6507 				if (mctl_present)
6508 					freeb(first_mp1);
6509 				(connp->conn_recv)(connp, mp1, NULL);
6510 			}
6511 		}
6512 		mutex_enter(&connfp->connf_lock);
6513 		/* Follow the next pointer before releasing the conn. */
6514 		next_connp = connp->conn_next;
6515 		CONN_DEC_REF(connp);
6516 		connp = next_connp;
6517 	}
6518 
6519 	/* Last one.  Send it upstream. */
6520 	mutex_exit(&connfp->connf_lock);
6521 
6522 	/*
6523 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6524 	 * will be set to false.
6525 	 */
6526 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6527 		ill_index = ill->ill_phyint->phyint_ifindex;
6528 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6529 		if (mp == NULL) {
6530 			CONN_DEC_REF(connp);
6531 			if (mctl_present) {
6532 				freeb(first_mp);
6533 			}
6534 			return;
6535 		}
6536 	}
6537 
6538 	rq = connp->conn_rq;
6539 	if (!canputnext(rq)) {
6540 		if (flags & IP_FF_RAWIP) {
6541 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6542 		} else {
6543 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6544 		}
6545 
6546 		freemsg(first_mp);
6547 	} else {
6548 		if (IPCL_IS_IPTUN(connp)) {
6549 			/*
6550 			 * Tunneled packet.  We enforce policy in the tunnel
6551 			 * module itself.
6552 			 *
6553 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6554 			 * a policy check.
6555 			 * FIXME to use conn_recv for tun later.
6556 			 */
6557 			putnext(rq, first_mp);
6558 			CONN_DEC_REF(connp);
6559 			return;
6560 		}
6561 
6562 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6563 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6564 			    ipha, NULL, mctl_present);
6565 		}
6566 
6567 		if (first_mp != NULL) {
6568 			int in_flags = 0;
6569 
6570 			/*
6571 			 * ip_fanout_proto also gets called
6572 			 * from icmp_inbound_error_fanout, in
6573 			 * which case the msg type is M_CTL.
6574 			 * Don't add info in this case for time
6575 			 * being. In future when there is a
6576 			 * need for knowing the inbound iface
6577 			 * index for ICMP error msgs, then this
6578 			 * can be changed
6579 			 */
6580 			if (connp->conn_recvif)
6581 				in_flags = IPF_RECVIF;
6582 			if (connp->conn_ip_recvpktinfo) {
6583 				if (connp->conn_af_isv6) {
6584 					/*
6585 					 * V6 only needs index
6586 					 */
6587 					in_flags |= IPF_RECVIF;
6588 				} else {
6589 					/*
6590 					 * V4 needs index +
6591 					 * matching address.
6592 					 */
6593 					in_flags |= IPF_RECVADDR;
6594 				}
6595 			}
6596 			if ((in_flags != 0) &&
6597 			    (mp->b_datap->db_type != M_CTL)) {
6598 
6599 				/*
6600 				 * the actual data will be contained in
6601 				 * b_cont upon successful return
6602 				 * of the following call else original
6603 				 * mblk is returned
6604 				 */
6605 				ASSERT(recv_ill != NULL);
6606 				mp = ip_add_info(mp, recv_ill,
6607 				    in_flags, IPCL_ZONEID(connp), ipst);
6608 			}
6609 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6610 			(connp->conn_recv)(connp, mp, NULL);
6611 			if (mctl_present)
6612 				freeb(first_mp);
6613 		}
6614 	}
6615 	CONN_DEC_REF(connp);
6616 }
6617 
6618 /*
6619  * Fanout for TCP packets
6620  * The caller puts <fport, lport> in the ports parameter.
6621  *
6622  * IPQoS Notes
6623  * Before sending it to the client, invoke IPPF processing.
6624  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6625  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6626  * ip_policy is false.
6627  */
6628 static void
6629 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6630     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6631 {
6632 	mblk_t  *first_mp;
6633 	boolean_t secure;
6634 	uint32_t ill_index;
6635 	int	ip_hdr_len;
6636 	tcph_t	*tcph;
6637 	boolean_t syn_present = B_FALSE;
6638 	conn_t	*connp;
6639 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6640 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6641 
6642 	ASSERT(recv_ill != NULL);
6643 
6644 	first_mp = mp;
6645 	if (mctl_present) {
6646 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6647 		mp = first_mp->b_cont;
6648 		secure = ipsec_in_is_secure(first_mp);
6649 		ASSERT(mp != NULL);
6650 	} else {
6651 		secure = B_FALSE;
6652 	}
6653 
6654 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6655 
6656 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6657 	    zoneid, ipst)) == NULL) {
6658 		/*
6659 		 * No connected connection or listener. Send a
6660 		 * TH_RST via tcp_xmit_listeners_reset.
6661 		 */
6662 
6663 		/* Initiate IPPf processing, if needed. */
6664 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6665 			uint32_t ill_index;
6666 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6667 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6668 			if (first_mp == NULL)
6669 				return;
6670 		}
6671 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6672 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6673 		    zoneid));
6674 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6675 		    ipst->ips_netstack->netstack_tcp, NULL);
6676 		return;
6677 	}
6678 
6679 	/*
6680 	 * Allocate the SYN for the TCP connection here itself
6681 	 */
6682 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6683 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6684 		if (IPCL_IS_TCP(connp)) {
6685 			squeue_t *sqp;
6686 
6687 			/*
6688 			 * For fused tcp loopback, assign the eager's
6689 			 * squeue to be that of the active connect's.
6690 			 * Note that we don't check for IP_FF_LOOPBACK
6691 			 * here since this routine gets called only
6692 			 * for loopback (unlike the IPv6 counterpart).
6693 			 */
6694 			ASSERT(Q_TO_CONN(q) != NULL);
6695 			if (do_tcp_fusion &&
6696 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6697 			    !secure &&
6698 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6699 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6700 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6701 				sqp = Q_TO_CONN(q)->conn_sqp;
6702 			} else {
6703 				sqp = IP_SQUEUE_GET(lbolt);
6704 			}
6705 
6706 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6707 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6708 			syn_present = B_TRUE;
6709 		}
6710 	}
6711 
6712 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6713 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6714 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6715 		if ((flags & TH_RST) || (flags & TH_URG)) {
6716 			CONN_DEC_REF(connp);
6717 			freemsg(first_mp);
6718 			return;
6719 		}
6720 		if (flags & TH_ACK) {
6721 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6722 			    ipst->ips_netstack->netstack_tcp, connp);
6723 			CONN_DEC_REF(connp);
6724 			return;
6725 		}
6726 
6727 		CONN_DEC_REF(connp);
6728 		freemsg(first_mp);
6729 		return;
6730 	}
6731 
6732 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6733 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6734 		    NULL, mctl_present);
6735 		if (first_mp == NULL) {
6736 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6737 			CONN_DEC_REF(connp);
6738 			return;
6739 		}
6740 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6741 			ASSERT(syn_present);
6742 			if (mctl_present) {
6743 				ASSERT(first_mp != mp);
6744 				first_mp->b_datap->db_struioflag |=
6745 				    STRUIO_POLICY;
6746 			} else {
6747 				ASSERT(first_mp == mp);
6748 				mp->b_datap->db_struioflag &=
6749 				    ~STRUIO_EAGER;
6750 				mp->b_datap->db_struioflag |=
6751 				    STRUIO_POLICY;
6752 			}
6753 		} else {
6754 			/*
6755 			 * Discard first_mp early since we're dealing with a
6756 			 * fully-connected conn_t and tcp doesn't do policy in
6757 			 * this case.
6758 			 */
6759 			if (mctl_present) {
6760 				freeb(first_mp);
6761 				mctl_present = B_FALSE;
6762 			}
6763 			first_mp = mp;
6764 		}
6765 	}
6766 
6767 	/*
6768 	 * Initiate policy processing here if needed. If we get here from
6769 	 * icmp_inbound_error_fanout, ip_policy is false.
6770 	 */
6771 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6772 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6773 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6774 		if (mp == NULL) {
6775 			CONN_DEC_REF(connp);
6776 			if (mctl_present)
6777 				freeb(first_mp);
6778 			return;
6779 		} else if (mctl_present) {
6780 			ASSERT(first_mp != mp);
6781 			first_mp->b_cont = mp;
6782 		} else {
6783 			first_mp = mp;
6784 		}
6785 	}
6786 
6787 
6788 
6789 	/* Handle socket options. */
6790 	if (!syn_present &&
6791 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6792 		/* Add header */
6793 		ASSERT(recv_ill != NULL);
6794 		/*
6795 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6796 		 * IPF_RECVIF.
6797 		 */
6798 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6799 		    ipst);
6800 		if (mp == NULL) {
6801 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6802 			CONN_DEC_REF(connp);
6803 			if (mctl_present)
6804 				freeb(first_mp);
6805 			return;
6806 		} else if (mctl_present) {
6807 			/*
6808 			 * ip_add_info might return a new mp.
6809 			 */
6810 			ASSERT(first_mp != mp);
6811 			first_mp->b_cont = mp;
6812 		} else {
6813 			first_mp = mp;
6814 		}
6815 	}
6816 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6817 	if (IPCL_IS_TCP(connp)) {
6818 		/* do not drain, certain use cases can blow the stack */
6819 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6820 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6821 	} else {
6822 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6823 		(connp->conn_recv)(connp, first_mp, NULL);
6824 		CONN_DEC_REF(connp);
6825 	}
6826 }
6827 
6828 /*
6829  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6830  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6831  * is not consumed.
6832  *
6833  * One of four things can happen, all of which affect the passed-in mblk:
6834  *
6835  * 1.) ICMP messages that go through here just get returned TRUE.
6836  *
6837  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6838  *
6839  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6840  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6841  *
6842  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6843  */
6844 static boolean_t
6845 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6846     ipsec_stack_t *ipss)
6847 {
6848 	int shift, plen, iph_len;
6849 	ipha_t *ipha;
6850 	udpha_t *udpha;
6851 	uint32_t *spi;
6852 	uint8_t *orptr;
6853 	boolean_t udp_pkt, free_ire;
6854 
6855 	if (DB_TYPE(mp) == M_CTL) {
6856 		/*
6857 		 * ICMP message with UDP inside.  Don't bother stripping, just
6858 		 * send it up.
6859 		 *
6860 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6861 		 * to ignore errors set by ICMP anyway ('cause they might be
6862 		 * forged), but that's the app's decision, not ours.
6863 		 */
6864 
6865 		/* Bunch of reality checks for DEBUG kernels... */
6866 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6867 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6868 
6869 		return (B_TRUE);
6870 	}
6871 
6872 	ipha = (ipha_t *)mp->b_rptr;
6873 	iph_len = IPH_HDR_LENGTH(ipha);
6874 	plen = ntohs(ipha->ipha_length);
6875 
6876 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6877 		/*
6878 		 * Most likely a keepalive for the benefit of an intervening
6879 		 * NAT.  These aren't for us, per se, so drop it.
6880 		 *
6881 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6882 		 * byte packets (keepalives are 1-byte), but we'll drop them
6883 		 * also.
6884 		 */
6885 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6886 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6887 		return (B_FALSE);
6888 	}
6889 
6890 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6891 		/* might as well pull it all up - it might be ESP. */
6892 		if (!pullupmsg(mp, -1)) {
6893 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6894 			    DROPPER(ipss, ipds_esp_nomem),
6895 			    &ipss->ipsec_dropper);
6896 			return (B_FALSE);
6897 		}
6898 
6899 		ipha = (ipha_t *)mp->b_rptr;
6900 	}
6901 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6902 	if (*spi == 0) {
6903 		/* UDP packet - remove 0-spi. */
6904 		shift = sizeof (uint32_t);
6905 	} else {
6906 		/* ESP-in-UDP packet - reduce to ESP. */
6907 		ipha->ipha_protocol = IPPROTO_ESP;
6908 		shift = sizeof (udpha_t);
6909 	}
6910 
6911 	/* Fix IP header */
6912 	ipha->ipha_length = htons(plen - shift);
6913 	ipha->ipha_hdr_checksum = 0;
6914 
6915 	orptr = mp->b_rptr;
6916 	mp->b_rptr += shift;
6917 
6918 	if (*spi == 0) {
6919 		ASSERT((uint8_t *)ipha == orptr);
6920 		udpha = (udpha_t *)(orptr + iph_len);
6921 		udpha->uha_length = htons(plen - shift - iph_len);
6922 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6923 		udp_pkt = B_TRUE;
6924 	} else {
6925 		udp_pkt = B_FALSE;
6926 	}
6927 	ovbcopy(orptr, orptr + shift, iph_len);
6928 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6929 		ipha = (ipha_t *)(orptr + shift);
6930 
6931 		free_ire = (ire == NULL);
6932 		if (free_ire) {
6933 			/* Re-acquire ire. */
6934 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6935 			    ipss->ipsec_netstack->netstack_ip);
6936 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6937 				if (ire != NULL)
6938 					ire_refrele(ire);
6939 				/*
6940 				 * Do a regular freemsg(), as this is an IP
6941 				 * error (no local route) not an IPsec one.
6942 				 */
6943 				freemsg(mp);
6944 			}
6945 		}
6946 
6947 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6948 		if (free_ire)
6949 			ire_refrele(ire);
6950 	}
6951 
6952 	return (udp_pkt);
6953 }
6954 
6955 /*
6956  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6957  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6958  * Caller is responsible for dropping references to the conn, and freeing
6959  * first_mp.
6960  *
6961  * IPQoS Notes
6962  * Before sending it to the client, invoke IPPF processing. Policy processing
6963  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6964  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6965  * ip_wput_local, ip_policy is false.
6966  */
6967 static void
6968 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6969     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6970     boolean_t ip_policy)
6971 {
6972 	boolean_t	mctl_present = (first_mp != NULL);
6973 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6974 	uint32_t	ill_index;
6975 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6976 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6977 
6978 	ASSERT(ill != NULL);
6979 
6980 	if (mctl_present)
6981 		first_mp->b_cont = mp;
6982 	else
6983 		first_mp = mp;
6984 
6985 	if (CONN_UDP_FLOWCTLD(connp)) {
6986 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6987 		freemsg(first_mp);
6988 		return;
6989 	}
6990 
6991 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6992 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6993 		    NULL, mctl_present);
6994 		if (first_mp == NULL) {
6995 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6996 			return;	/* Freed by ipsec_check_inbound_policy(). */
6997 		}
6998 	}
6999 	if (mctl_present)
7000 		freeb(first_mp);
7001 
7002 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7003 	if (connp->conn_udp->udp_nat_t_endpoint) {
7004 		if (mctl_present) {
7005 			/* mctl_present *shouldn't* happen. */
7006 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7007 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7008 			    &ipss->ipsec_dropper);
7009 			return;
7010 		}
7011 
7012 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7013 			return;
7014 	}
7015 
7016 	/* Handle options. */
7017 	if (connp->conn_recvif)
7018 		in_flags = IPF_RECVIF;
7019 	/*
7020 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7021 	 * passed to ip_add_info is based on IP version of connp.
7022 	 */
7023 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7024 		if (connp->conn_af_isv6) {
7025 			/*
7026 			 * V6 only needs index
7027 			 */
7028 			in_flags |= IPF_RECVIF;
7029 		} else {
7030 			/*
7031 			 * V4 needs index + matching address.
7032 			 */
7033 			in_flags |= IPF_RECVADDR;
7034 		}
7035 	}
7036 
7037 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7038 		in_flags |= IPF_RECVSLLA;
7039 
7040 	/*
7041 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7042 	 * freed if the packet is dropped. The caller will do so.
7043 	 */
7044 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7045 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7046 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7047 		if (mp == NULL) {
7048 			return;
7049 		}
7050 	}
7051 	if ((in_flags != 0) &&
7052 	    (mp->b_datap->db_type != M_CTL)) {
7053 		/*
7054 		 * The actual data will be contained in b_cont
7055 		 * upon successful return of the following call
7056 		 * else original mblk is returned
7057 		 */
7058 		ASSERT(recv_ill != NULL);
7059 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7060 		    ipst);
7061 	}
7062 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7063 	/* Send it upstream */
7064 	(connp->conn_recv)(connp, mp, NULL);
7065 }
7066 
7067 /*
7068  * Fanout for UDP packets.
7069  * The caller puts <fport, lport> in the ports parameter.
7070  *
7071  * If SO_REUSEADDR is set all multicast and broadcast packets
7072  * will be delivered to all streams bound to the same port.
7073  *
7074  * Zones notes:
7075  * Multicast and broadcast packets will be distributed to streams in all zones.
7076  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7077  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7078  * packets. To maintain this behavior with multiple zones, the conns are grouped
7079  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7080  * each zone. If unset, all the following conns in the same zone are skipped.
7081  */
7082 static void
7083 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7084     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7085     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7086 {
7087 	uint32_t	dstport, srcport;
7088 	ipaddr_t	dst;
7089 	mblk_t		*first_mp;
7090 	boolean_t	secure;
7091 	in6_addr_t	v6src;
7092 	conn_t		*connp;
7093 	connf_t		*connfp;
7094 	conn_t		*first_connp;
7095 	conn_t		*next_connp;
7096 	mblk_t		*mp1, *first_mp1;
7097 	ipaddr_t	src;
7098 	zoneid_t	last_zoneid;
7099 	boolean_t	reuseaddr;
7100 	boolean_t	shared_addr;
7101 	ip_stack_t	*ipst;
7102 
7103 	ASSERT(recv_ill != NULL);
7104 	ipst = recv_ill->ill_ipst;
7105 
7106 	first_mp = mp;
7107 	if (mctl_present) {
7108 		mp = first_mp->b_cont;
7109 		first_mp->b_cont = NULL;
7110 		secure = ipsec_in_is_secure(first_mp);
7111 		ASSERT(mp != NULL);
7112 	} else {
7113 		first_mp = NULL;
7114 		secure = B_FALSE;
7115 	}
7116 
7117 	/* Extract ports in net byte order */
7118 	dstport = htons(ntohl(ports) & 0xFFFF);
7119 	srcport = htons(ntohl(ports) >> 16);
7120 	dst = ipha->ipha_dst;
7121 	src = ipha->ipha_src;
7122 
7123 	shared_addr = (zoneid == ALL_ZONES);
7124 	if (shared_addr) {
7125 		/*
7126 		 * No need to handle exclusive-stack zones since ALL_ZONES
7127 		 * only applies to the shared stack.
7128 		 */
7129 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7130 		if (zoneid == ALL_ZONES)
7131 			zoneid = tsol_packet_to_zoneid(mp);
7132 	}
7133 
7134 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7135 	mutex_enter(&connfp->connf_lock);
7136 	connp = connfp->connf_head;
7137 	if (!broadcast && !CLASSD(dst)) {
7138 		/*
7139 		 * Not broadcast or multicast. Send to the one (first)
7140 		 * client we find. No need to check conn_wantpacket()
7141 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7142 		 * IPv4 unicast packets.
7143 		 */
7144 		while ((connp != NULL) &&
7145 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7146 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7147 			connp = connp->conn_next;
7148 		}
7149 
7150 		if (connp == NULL || connp->conn_upq == NULL)
7151 			goto notfound;
7152 
7153 		if (is_system_labeled() &&
7154 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7155 		    connp))
7156 			goto notfound;
7157 
7158 		CONN_INC_REF(connp);
7159 		mutex_exit(&connfp->connf_lock);
7160 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7161 		    flags, recv_ill, ip_policy);
7162 		IP_STAT(ipst, ip_udp_fannorm);
7163 		CONN_DEC_REF(connp);
7164 		return;
7165 	}
7166 
7167 	/*
7168 	 * Broadcast and multicast case
7169 	 *
7170 	 * Need to check conn_wantpacket().
7171 	 * If SO_REUSEADDR has been set on the first we send the
7172 	 * packet to all clients that have joined the group and
7173 	 * match the port.
7174 	 */
7175 
7176 	while (connp != NULL) {
7177 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7178 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7179 		    (!is_system_labeled() ||
7180 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7181 		    connp)))
7182 			break;
7183 		connp = connp->conn_next;
7184 	}
7185 
7186 	if (connp == NULL || connp->conn_upq == NULL)
7187 		goto notfound;
7188 
7189 	first_connp = connp;
7190 	/*
7191 	 * When SO_REUSEADDR is not set, send the packet only to the first
7192 	 * matching connection in its zone by keeping track of the zoneid.
7193 	 */
7194 	reuseaddr = first_connp->conn_reuseaddr;
7195 	last_zoneid = first_connp->conn_zoneid;
7196 
7197 	CONN_INC_REF(connp);
7198 	connp = connp->conn_next;
7199 	for (;;) {
7200 		while (connp != NULL) {
7201 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7202 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7203 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7204 			    (!is_system_labeled() ||
7205 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7206 			    shared_addr, connp)))
7207 				break;
7208 			connp = connp->conn_next;
7209 		}
7210 		/*
7211 		 * Just copy the data part alone. The mctl part is
7212 		 * needed just for verifying policy and it is never
7213 		 * sent up.
7214 		 */
7215 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7216 		    ((mp1 = copymsg(mp)) == NULL))) {
7217 			/*
7218 			 * No more interested clients or memory
7219 			 * allocation failed
7220 			 */
7221 			connp = first_connp;
7222 			break;
7223 		}
7224 		if (connp->conn_zoneid != last_zoneid) {
7225 			/*
7226 			 * Update the zoneid so that the packet isn't sent to
7227 			 * any more conns in the same zone unless SO_REUSEADDR
7228 			 * is set.
7229 			 */
7230 			reuseaddr = connp->conn_reuseaddr;
7231 			last_zoneid = connp->conn_zoneid;
7232 		}
7233 		if (first_mp != NULL) {
7234 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7235 			    ipsec_info_type == IPSEC_IN);
7236 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7237 			    ipst->ips_netstack);
7238 			if (first_mp1 == NULL) {
7239 				freemsg(mp1);
7240 				connp = first_connp;
7241 				break;
7242 			}
7243 		} else {
7244 			first_mp1 = NULL;
7245 		}
7246 		CONN_INC_REF(connp);
7247 		mutex_exit(&connfp->connf_lock);
7248 		/*
7249 		 * IPQoS notes: We don't send the packet for policy
7250 		 * processing here, will do it for the last one (below).
7251 		 * i.e. we do it per-packet now, but if we do policy
7252 		 * processing per-conn, then we would need to do it
7253 		 * here too.
7254 		 */
7255 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7256 		    ipha, flags, recv_ill, B_FALSE);
7257 		mutex_enter(&connfp->connf_lock);
7258 		/* Follow the next pointer before releasing the conn. */
7259 		next_connp = connp->conn_next;
7260 		IP_STAT(ipst, ip_udp_fanmb);
7261 		CONN_DEC_REF(connp);
7262 		connp = next_connp;
7263 	}
7264 
7265 	/* Last one.  Send it upstream. */
7266 	mutex_exit(&connfp->connf_lock);
7267 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7268 	    recv_ill, ip_policy);
7269 	IP_STAT(ipst, ip_udp_fanmb);
7270 	CONN_DEC_REF(connp);
7271 	return;
7272 
7273 notfound:
7274 
7275 	mutex_exit(&connfp->connf_lock);
7276 	IP_STAT(ipst, ip_udp_fanothers);
7277 	/*
7278 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7279 	 * have already been matched above, since they live in the IPv4
7280 	 * fanout tables. This implies we only need to
7281 	 * check for IPv6 in6addr_any endpoints here.
7282 	 * Thus we compare using ipv6_all_zeros instead of the destination
7283 	 * address, except for the multicast group membership lookup which
7284 	 * uses the IPv4 destination.
7285 	 */
7286 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7287 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7288 	mutex_enter(&connfp->connf_lock);
7289 	connp = connfp->connf_head;
7290 	if (!broadcast && !CLASSD(dst)) {
7291 		while (connp != NULL) {
7292 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7293 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7294 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7295 			    !connp->conn_ipv6_v6only)
7296 				break;
7297 			connp = connp->conn_next;
7298 		}
7299 
7300 		if (connp != NULL && is_system_labeled() &&
7301 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7302 		    connp))
7303 			connp = NULL;
7304 
7305 		if (connp == NULL || connp->conn_upq == NULL) {
7306 			/*
7307 			 * No one bound to this port.  Is
7308 			 * there a client that wants all
7309 			 * unclaimed datagrams?
7310 			 */
7311 			mutex_exit(&connfp->connf_lock);
7312 
7313 			if (mctl_present)
7314 				first_mp->b_cont = mp;
7315 			else
7316 				first_mp = mp;
7317 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7318 			    connf_head != NULL) {
7319 				ip_fanout_proto(q, first_mp, ill, ipha,
7320 				    flags | IP_FF_RAWIP, mctl_present,
7321 				    ip_policy, recv_ill, zoneid);
7322 			} else {
7323 				if (ip_fanout_send_icmp(q, first_mp, flags,
7324 				    ICMP_DEST_UNREACHABLE,
7325 				    ICMP_PORT_UNREACHABLE,
7326 				    mctl_present, zoneid, ipst)) {
7327 					BUMP_MIB(ill->ill_ip_mib,
7328 					    udpIfStatsNoPorts);
7329 				}
7330 			}
7331 			return;
7332 		}
7333 
7334 		CONN_INC_REF(connp);
7335 		mutex_exit(&connfp->connf_lock);
7336 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7337 		    flags, recv_ill, ip_policy);
7338 		CONN_DEC_REF(connp);
7339 		return;
7340 	}
7341 	/*
7342 	 * IPv4 multicast packet being delivered to an AF_INET6
7343 	 * in6addr_any endpoint.
7344 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7345 	 * and not conn_wantpacket_v6() since any multicast membership is
7346 	 * for an IPv4-mapped multicast address.
7347 	 * The packet is sent to all clients in all zones that have joined the
7348 	 * group and match the port.
7349 	 */
7350 	while (connp != NULL) {
7351 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7352 		    srcport, v6src) &&
7353 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7354 		    (!is_system_labeled() ||
7355 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7356 		    connp)))
7357 			break;
7358 		connp = connp->conn_next;
7359 	}
7360 
7361 	if (connp == NULL || connp->conn_upq == NULL) {
7362 		/*
7363 		 * No one bound to this port.  Is
7364 		 * there a client that wants all
7365 		 * unclaimed datagrams?
7366 		 */
7367 		mutex_exit(&connfp->connf_lock);
7368 
7369 		if (mctl_present)
7370 			first_mp->b_cont = mp;
7371 		else
7372 			first_mp = mp;
7373 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7374 		    NULL) {
7375 			ip_fanout_proto(q, first_mp, ill, ipha,
7376 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7377 			    recv_ill, zoneid);
7378 		} else {
7379 			/*
7380 			 * We used to attempt to send an icmp error here, but
7381 			 * since this is known to be a multicast packet
7382 			 * and we don't send icmp errors in response to
7383 			 * multicast, just drop the packet and give up sooner.
7384 			 */
7385 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7386 			freemsg(first_mp);
7387 		}
7388 		return;
7389 	}
7390 
7391 	first_connp = connp;
7392 
7393 	CONN_INC_REF(connp);
7394 	connp = connp->conn_next;
7395 	for (;;) {
7396 		while (connp != NULL) {
7397 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7398 			    ipv6_all_zeros, srcport, v6src) &&
7399 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7400 			    (!is_system_labeled() ||
7401 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7402 			    shared_addr, connp)))
7403 				break;
7404 			connp = connp->conn_next;
7405 		}
7406 		/*
7407 		 * Just copy the data part alone. The mctl part is
7408 		 * needed just for verifying policy and it is never
7409 		 * sent up.
7410 		 */
7411 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7412 		    ((mp1 = copymsg(mp)) == NULL))) {
7413 			/*
7414 			 * No more intested clients or memory
7415 			 * allocation failed
7416 			 */
7417 			connp = first_connp;
7418 			break;
7419 		}
7420 		if (first_mp != NULL) {
7421 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7422 			    ipsec_info_type == IPSEC_IN);
7423 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7424 			    ipst->ips_netstack);
7425 			if (first_mp1 == NULL) {
7426 				freemsg(mp1);
7427 				connp = first_connp;
7428 				break;
7429 			}
7430 		} else {
7431 			first_mp1 = NULL;
7432 		}
7433 		CONN_INC_REF(connp);
7434 		mutex_exit(&connfp->connf_lock);
7435 		/*
7436 		 * IPQoS notes: We don't send the packet for policy
7437 		 * processing here, will do it for the last one (below).
7438 		 * i.e. we do it per-packet now, but if we do policy
7439 		 * processing per-conn, then we would need to do it
7440 		 * here too.
7441 		 */
7442 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7443 		    ipha, flags, recv_ill, B_FALSE);
7444 		mutex_enter(&connfp->connf_lock);
7445 		/* Follow the next pointer before releasing the conn. */
7446 		next_connp = connp->conn_next;
7447 		CONN_DEC_REF(connp);
7448 		connp = next_connp;
7449 	}
7450 
7451 	/* Last one.  Send it upstream. */
7452 	mutex_exit(&connfp->connf_lock);
7453 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7454 	    recv_ill, ip_policy);
7455 	CONN_DEC_REF(connp);
7456 }
7457 
7458 /*
7459  * Complete the ip_wput header so that it
7460  * is possible to generate ICMP
7461  * errors.
7462  */
7463 int
7464 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7465 {
7466 	ire_t *ire;
7467 
7468 	if (ipha->ipha_src == INADDR_ANY) {
7469 		ire = ire_lookup_local(zoneid, ipst);
7470 		if (ire == NULL) {
7471 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7472 			return (1);
7473 		}
7474 		ipha->ipha_src = ire->ire_addr;
7475 		ire_refrele(ire);
7476 	}
7477 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7478 	ipha->ipha_hdr_checksum = 0;
7479 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7480 	return (0);
7481 }
7482 
7483 /*
7484  * Nobody should be sending
7485  * packets up this stream
7486  */
7487 static void
7488 ip_lrput(queue_t *q, mblk_t *mp)
7489 {
7490 	mblk_t *mp1;
7491 
7492 	switch (mp->b_datap->db_type) {
7493 	case M_FLUSH:
7494 		/* Turn around */
7495 		if (*mp->b_rptr & FLUSHW) {
7496 			*mp->b_rptr &= ~FLUSHR;
7497 			qreply(q, mp);
7498 			return;
7499 		}
7500 		break;
7501 	}
7502 	/* Could receive messages that passed through ar_rput */
7503 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7504 		mp1->b_prev = mp1->b_next = NULL;
7505 	freemsg(mp);
7506 }
7507 
7508 /* Nobody should be sending packets down this stream */
7509 /* ARGSUSED */
7510 void
7511 ip_lwput(queue_t *q, mblk_t *mp)
7512 {
7513 	freemsg(mp);
7514 }
7515 
7516 /*
7517  * Move the first hop in any source route to ipha_dst and remove that part of
7518  * the source route.  Called by other protocols.  Errors in option formatting
7519  * are ignored - will be handled by ip_wput_options Return the final
7520  * destination (either ipha_dst or the last entry in a source route.)
7521  */
7522 ipaddr_t
7523 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7524 {
7525 	ipoptp_t	opts;
7526 	uchar_t		*opt;
7527 	uint8_t		optval;
7528 	uint8_t		optlen;
7529 	ipaddr_t	dst;
7530 	int		i;
7531 	ire_t		*ire;
7532 	ip_stack_t	*ipst = ns->netstack_ip;
7533 
7534 	ip2dbg(("ip_massage_options\n"));
7535 	dst = ipha->ipha_dst;
7536 	for (optval = ipoptp_first(&opts, ipha);
7537 	    optval != IPOPT_EOL;
7538 	    optval = ipoptp_next(&opts)) {
7539 		opt = opts.ipoptp_cur;
7540 		switch (optval) {
7541 			uint8_t off;
7542 		case IPOPT_SSRR:
7543 		case IPOPT_LSRR:
7544 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7545 				ip1dbg(("ip_massage_options: bad src route\n"));
7546 				break;
7547 			}
7548 			optlen = opts.ipoptp_len;
7549 			off = opt[IPOPT_OFFSET];
7550 			off--;
7551 		redo_srr:
7552 			if (optlen < IP_ADDR_LEN ||
7553 			    off > optlen - IP_ADDR_LEN) {
7554 				/* End of source route */
7555 				ip1dbg(("ip_massage_options: end of SR\n"));
7556 				break;
7557 			}
7558 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7559 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7560 			    ntohl(dst)));
7561 			/*
7562 			 * Check if our address is present more than
7563 			 * once as consecutive hops in source route.
7564 			 * XXX verify per-interface ip_forwarding
7565 			 * for source route?
7566 			 */
7567 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7568 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7569 			if (ire != NULL) {
7570 				ire_refrele(ire);
7571 				off += IP_ADDR_LEN;
7572 				goto redo_srr;
7573 			}
7574 			if (dst == htonl(INADDR_LOOPBACK)) {
7575 				ip1dbg(("ip_massage_options: loopback addr in "
7576 				    "source route!\n"));
7577 				break;
7578 			}
7579 			/*
7580 			 * Update ipha_dst to be the first hop and remove the
7581 			 * first hop from the source route (by overwriting
7582 			 * part of the option with NOP options).
7583 			 */
7584 			ipha->ipha_dst = dst;
7585 			/* Put the last entry in dst */
7586 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7587 			    3;
7588 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7589 
7590 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7591 			    ntohl(dst)));
7592 			/* Move down and overwrite */
7593 			opt[IP_ADDR_LEN] = opt[0];
7594 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7595 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7596 			for (i = 0; i < IP_ADDR_LEN; i++)
7597 				opt[i] = IPOPT_NOP;
7598 			break;
7599 		}
7600 	}
7601 	return (dst);
7602 }
7603 
7604 /*
7605  * Return the network mask
7606  * associated with the specified address.
7607  */
7608 ipaddr_t
7609 ip_net_mask(ipaddr_t addr)
7610 {
7611 	uchar_t	*up = (uchar_t *)&addr;
7612 	ipaddr_t mask = 0;
7613 	uchar_t	*maskp = (uchar_t *)&mask;
7614 
7615 #if defined(__i386) || defined(__amd64)
7616 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7617 #endif
7618 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7619 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7620 #endif
7621 	if (CLASSD(addr)) {
7622 		maskp[0] = 0xF0;
7623 		return (mask);
7624 	}
7625 
7626 	/* We assume Class E default netmask to be 32 */
7627 	if (CLASSE(addr))
7628 		return (0xffffffffU);
7629 
7630 	if (addr == 0)
7631 		return (0);
7632 	maskp[0] = 0xFF;
7633 	if ((up[0] & 0x80) == 0)
7634 		return (mask);
7635 
7636 	maskp[1] = 0xFF;
7637 	if ((up[0] & 0xC0) == 0x80)
7638 		return (mask);
7639 
7640 	maskp[2] = 0xFF;
7641 	if ((up[0] & 0xE0) == 0xC0)
7642 		return (mask);
7643 
7644 	/* Otherwise return no mask */
7645 	return ((ipaddr_t)0);
7646 }
7647 
7648 /*
7649  * Select an ill for the packet by considering load spreading across
7650  * a different ill in the group if dst_ill is part of some group.
7651  */
7652 ill_t *
7653 ip_newroute_get_dst_ill(ill_t *dst_ill)
7654 {
7655 	ill_t *ill;
7656 
7657 	/*
7658 	 * We schedule irrespective of whether the source address is
7659 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7660 	 */
7661 	ill = illgrp_scheduler(dst_ill);
7662 	if (ill == NULL)
7663 		return (NULL);
7664 
7665 	/*
7666 	 * For groups with names ip_sioctl_groupname ensures that all
7667 	 * ills are of same type. For groups without names, ifgrp_insert
7668 	 * ensures this.
7669 	 */
7670 	ASSERT(dst_ill->ill_type == ill->ill_type);
7671 
7672 	return (ill);
7673 }
7674 
7675 /*
7676  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7677  */
7678 ill_t *
7679 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7680     ip_stack_t *ipst)
7681 {
7682 	ill_t *ret_ill;
7683 
7684 	ASSERT(ifindex != 0);
7685 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7686 	    ipst);
7687 	if (ret_ill == NULL ||
7688 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7689 		if (isv6) {
7690 			if (ill != NULL) {
7691 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7692 			} else {
7693 				BUMP_MIB(&ipst->ips_ip6_mib,
7694 				    ipIfStatsOutDiscards);
7695 			}
7696 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7697 			    "bad ifindex %d.\n", ifindex));
7698 		} else {
7699 			if (ill != NULL) {
7700 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7701 			} else {
7702 				BUMP_MIB(&ipst->ips_ip_mib,
7703 				    ipIfStatsOutDiscards);
7704 			}
7705 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7706 			    "bad ifindex %d.\n", ifindex));
7707 		}
7708 		if (ret_ill != NULL)
7709 			ill_refrele(ret_ill);
7710 		freemsg(first_mp);
7711 		return (NULL);
7712 	}
7713 
7714 	return (ret_ill);
7715 }
7716 
7717 /*
7718  * IPv4 -
7719  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7720  * out a packet to a destination address for which we do not have specific
7721  * (or sufficient) routing information.
7722  *
7723  * NOTE : These are the scopes of some of the variables that point at IRE,
7724  *	  which needs to be followed while making any future modifications
7725  *	  to avoid memory leaks.
7726  *
7727  *	- ire and sire are the entries looked up initially by
7728  *	  ire_ftable_lookup.
7729  *	- ipif_ire is used to hold the interface ire associated with
7730  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7731  *	  it before branching out to error paths.
7732  *	- save_ire is initialized before ire_create, so that ire returned
7733  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7734  *	  before breaking out of the switch.
7735  *
7736  *	Thus on failures, we have to REFRELE only ire and sire, if they
7737  *	are not NULL.
7738  */
7739 void
7740 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7741     zoneid_t zoneid, ip_stack_t *ipst)
7742 {
7743 	areq_t	*areq;
7744 	ipaddr_t gw = 0;
7745 	ire_t	*ire = NULL;
7746 	mblk_t	*res_mp;
7747 	ipaddr_t *addrp;
7748 	ipaddr_t nexthop_addr;
7749 	ipif_t  *src_ipif = NULL;
7750 	ill_t	*dst_ill = NULL;
7751 	ipha_t  *ipha;
7752 	ire_t	*sire = NULL;
7753 	mblk_t	*first_mp;
7754 	ire_t	*save_ire;
7755 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7756 	ushort_t ire_marks = 0;
7757 	boolean_t mctl_present;
7758 	ipsec_out_t *io;
7759 	mblk_t	*saved_mp;
7760 	ire_t	*first_sire = NULL;
7761 	mblk_t	*copy_mp = NULL;
7762 	mblk_t	*xmit_mp = NULL;
7763 	ipaddr_t save_dst;
7764 	uint32_t multirt_flags =
7765 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7766 	boolean_t multirt_is_resolvable;
7767 	boolean_t multirt_resolve_next;
7768 	boolean_t unspec_src;
7769 	boolean_t do_attach_ill = B_FALSE;
7770 	boolean_t ip_nexthop = B_FALSE;
7771 	tsol_ire_gw_secattr_t *attrp = NULL;
7772 	tsol_gcgrp_t *gcgrp = NULL;
7773 	tsol_gcgrp_addr_t ga;
7774 
7775 	if (ip_debug > 2) {
7776 		/* ip1dbg */
7777 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7778 	}
7779 
7780 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7781 	if (mctl_present) {
7782 		io = (ipsec_out_t *)first_mp->b_rptr;
7783 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7784 		ASSERT(zoneid == io->ipsec_out_zoneid);
7785 		ASSERT(zoneid != ALL_ZONES);
7786 	}
7787 
7788 	ipha = (ipha_t *)mp->b_rptr;
7789 
7790 	/* All multicast lookups come through ip_newroute_ipif() */
7791 	if (CLASSD(dst)) {
7792 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7793 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7794 		freemsg(first_mp);
7795 		return;
7796 	}
7797 
7798 	if (mctl_present && io->ipsec_out_attach_if) {
7799 		/* ip_grab_attach_ill returns a held ill */
7800 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7801 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7802 
7803 		/* Failure case frees things for us. */
7804 		if (attach_ill == NULL)
7805 			return;
7806 
7807 		/*
7808 		 * Check if we need an ire that will not be
7809 		 * looked up by anybody else i.e. HIDDEN.
7810 		 */
7811 		if (ill_is_probeonly(attach_ill))
7812 			ire_marks = IRE_MARK_HIDDEN;
7813 	}
7814 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7815 		ip_nexthop = B_TRUE;
7816 		nexthop_addr = io->ipsec_out_nexthop_addr;
7817 	}
7818 	/*
7819 	 * If this IRE is created for forwarding or it is not for
7820 	 * traffic for congestion controlled protocols, mark it as temporary.
7821 	 */
7822 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7823 		ire_marks |= IRE_MARK_TEMPORARY;
7824 
7825 	/*
7826 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7827 	 * chain until it gets the most specific information available.
7828 	 * For example, we know that there is no IRE_CACHE for this dest,
7829 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7830 	 * ire_ftable_lookup will look up the gateway, etc.
7831 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7832 	 * to the destination, of equal netmask length in the forward table,
7833 	 * will be recursively explored. If no information is available
7834 	 * for the final gateway of that route, we force the returned ire
7835 	 * to be equal to sire using MATCH_IRE_PARENT.
7836 	 * At least, in this case we have a starting point (in the buckets)
7837 	 * to look for other routes to the destination in the forward table.
7838 	 * This is actually used only for multirouting, where a list
7839 	 * of routes has to be processed in sequence.
7840 	 *
7841 	 * In the process of coming up with the most specific information,
7842 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7843 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7844 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7845 	 * Two caveats when handling incomplete ire's in ip_newroute:
7846 	 * - we should be careful when accessing its ire_nce (specifically
7847 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7848 	 * - not all legacy code path callers are prepared to handle
7849 	 *   incomplete ire's, so we should not create/add incomplete
7850 	 *   ire_cache entries here. (See discussion about temporary solution
7851 	 *   further below).
7852 	 *
7853 	 * In order to minimize packet dropping, and to preserve existing
7854 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7855 	 * gateway, and instead use the IF_RESOLVER ire to send out
7856 	 * another request to ARP (this is achieved by passing the
7857 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7858 	 * arp response comes back in ip_wput_nondata, we will create
7859 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7860 	 *
7861 	 * Note that this is a temporary solution; the correct solution is
7862 	 * to create an incomplete  per-dst ire_cache entry, and send the
7863 	 * packet out when the gw's nce is resolved. In order to achieve this,
7864 	 * all packet processing must have been completed prior to calling
7865 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7866 	 * to be modified to accomodate this solution.
7867 	 */
7868 	if (ip_nexthop) {
7869 		/*
7870 		 * The first time we come here, we look for an IRE_INTERFACE
7871 		 * entry for the specified nexthop, set the dst to be the
7872 		 * nexthop address and create an IRE_CACHE entry for the
7873 		 * nexthop. The next time around, we are able to find an
7874 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7875 		 * nexthop address and create an IRE_CACHE entry for the
7876 		 * destination address via the specified nexthop.
7877 		 */
7878 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7879 		    MBLK_GETLABEL(mp), ipst);
7880 		if (ire != NULL) {
7881 			gw = nexthop_addr;
7882 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7883 		} else {
7884 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7885 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7886 			    MBLK_GETLABEL(mp),
7887 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7888 			    ipst);
7889 			if (ire != NULL) {
7890 				dst = nexthop_addr;
7891 			}
7892 		}
7893 	} else if (attach_ill == NULL) {
7894 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7895 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7896 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7897 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7898 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7899 		    ipst);
7900 	} else {
7901 		/*
7902 		 * attach_ill is set only for communicating with
7903 		 * on-link hosts. So, don't look for DEFAULT.
7904 		 */
7905 		ipif_t	*attach_ipif;
7906 
7907 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7908 		if (attach_ipif == NULL) {
7909 			ill_refrele(attach_ill);
7910 			goto icmp_err_ret;
7911 		}
7912 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7913 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7914 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7915 		    MATCH_IRE_SECATTR, ipst);
7916 		ipif_refrele(attach_ipif);
7917 	}
7918 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7919 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7920 
7921 	/*
7922 	 * This loop is run only once in most cases.
7923 	 * We loop to resolve further routes only when the destination
7924 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7925 	 */
7926 	do {
7927 		/* Clear the previous iteration's values */
7928 		if (src_ipif != NULL) {
7929 			ipif_refrele(src_ipif);
7930 			src_ipif = NULL;
7931 		}
7932 		if (dst_ill != NULL) {
7933 			ill_refrele(dst_ill);
7934 			dst_ill = NULL;
7935 		}
7936 
7937 		multirt_resolve_next = B_FALSE;
7938 		/*
7939 		 * We check if packets have to be multirouted.
7940 		 * In this case, given the current <ire, sire> couple,
7941 		 * we look for the next suitable <ire, sire>.
7942 		 * This check is done in ire_multirt_lookup(),
7943 		 * which applies various criteria to find the next route
7944 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7945 		 * unchanged if it detects it has not been tried yet.
7946 		 */
7947 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7948 			ip3dbg(("ip_newroute: starting next_resolution "
7949 			    "with first_mp %p, tag %d\n",
7950 			    (void *)first_mp,
7951 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7952 
7953 			ASSERT(sire != NULL);
7954 			multirt_is_resolvable =
7955 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7956 			    MBLK_GETLABEL(mp), ipst);
7957 
7958 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7959 			    "ire %p, sire %p\n",
7960 			    multirt_is_resolvable,
7961 			    (void *)ire, (void *)sire));
7962 
7963 			if (!multirt_is_resolvable) {
7964 				/*
7965 				 * No more multirt route to resolve; give up
7966 				 * (all routes resolved or no more
7967 				 * resolvable routes).
7968 				 */
7969 				if (ire != NULL) {
7970 					ire_refrele(ire);
7971 					ire = NULL;
7972 				}
7973 			} else {
7974 				ASSERT(sire != NULL);
7975 				ASSERT(ire != NULL);
7976 				/*
7977 				 * We simply use first_sire as a flag that
7978 				 * indicates if a resolvable multirt route
7979 				 * has already been found.
7980 				 * If it is not the case, we may have to send
7981 				 * an ICMP error to report that the
7982 				 * destination is unreachable.
7983 				 * We do not IRE_REFHOLD first_sire.
7984 				 */
7985 				if (first_sire == NULL) {
7986 					first_sire = sire;
7987 				}
7988 			}
7989 		}
7990 		if (ire == NULL) {
7991 			if (ip_debug > 3) {
7992 				/* ip2dbg */
7993 				pr_addr_dbg("ip_newroute: "
7994 				    "can't resolve %s\n", AF_INET, &dst);
7995 			}
7996 			ip3dbg(("ip_newroute: "
7997 			    "ire %p, sire %p, first_sire %p\n",
7998 			    (void *)ire, (void *)sire, (void *)first_sire));
7999 
8000 			if (sire != NULL) {
8001 				ire_refrele(sire);
8002 				sire = NULL;
8003 			}
8004 
8005 			if (first_sire != NULL) {
8006 				/*
8007 				 * At least one multirt route has been found
8008 				 * in the same call to ip_newroute();
8009 				 * there is no need to report an ICMP error.
8010 				 * first_sire was not IRE_REFHOLDed.
8011 				 */
8012 				MULTIRT_DEBUG_UNTAG(first_mp);
8013 				freemsg(first_mp);
8014 				return;
8015 			}
8016 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8017 			    RTA_DST, ipst);
8018 			if (attach_ill != NULL)
8019 				ill_refrele(attach_ill);
8020 			goto icmp_err_ret;
8021 		}
8022 
8023 		/*
8024 		 * Verify that the returned IRE does not have either
8025 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8026 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8027 		 */
8028 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8029 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8030 			if (attach_ill != NULL)
8031 				ill_refrele(attach_ill);
8032 			goto icmp_err_ret;
8033 		}
8034 		/*
8035 		 * Increment the ire_ob_pkt_count field for ire if it is an
8036 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8037 		 * increment the same for the parent IRE, sire, if it is some
8038 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8039 		 */
8040 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8041 			UPDATE_OB_PKT_COUNT(ire);
8042 			ire->ire_last_used_time = lbolt;
8043 		}
8044 
8045 		if (sire != NULL) {
8046 			gw = sire->ire_gateway_addr;
8047 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8048 			    IRE_INTERFACE)) == 0);
8049 			UPDATE_OB_PKT_COUNT(sire);
8050 			sire->ire_last_used_time = lbolt;
8051 		}
8052 		/*
8053 		 * We have a route to reach the destination.
8054 		 *
8055 		 * 1) If the interface is part of ill group, try to get a new
8056 		 *    ill taking load spreading into account.
8057 		 *
8058 		 * 2) After selecting the ill, get a source address that
8059 		 *    might create good inbound load spreading.
8060 		 *    ipif_select_source does this for us.
8061 		 *
8062 		 * If the application specified the ill (ifindex), we still
8063 		 * load spread. Only if the packets needs to go out
8064 		 * specifically on a given ill e.g. binding to
8065 		 * IPIF_NOFAILOVER address, then we don't try to use a
8066 		 * different ill for load spreading.
8067 		 */
8068 		if (attach_ill == NULL) {
8069 			/*
8070 			 * Don't perform outbound load spreading in the
8071 			 * case of an RTF_MULTIRT route, as we actually
8072 			 * typically want to replicate outgoing packets
8073 			 * through particular interfaces.
8074 			 */
8075 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8076 				dst_ill = ire->ire_ipif->ipif_ill;
8077 				/* for uniformity */
8078 				ill_refhold(dst_ill);
8079 			} else {
8080 				/*
8081 				 * If we are here trying to create an IRE_CACHE
8082 				 * for an offlink destination and have the
8083 				 * IRE_CACHE for the next hop and the latter is
8084 				 * using virtual IP source address selection i.e
8085 				 * it's ire->ire_ipif is pointing to a virtual
8086 				 * network interface (vni) then
8087 				 * ip_newroute_get_dst_ll() will return the vni
8088 				 * interface as the dst_ill. Since the vni is
8089 				 * virtual i.e not associated with any physical
8090 				 * interface, it cannot be the dst_ill, hence
8091 				 * in such a case call ip_newroute_get_dst_ll()
8092 				 * with the stq_ill instead of the ire_ipif ILL.
8093 				 * The function returns a refheld ill.
8094 				 */
8095 				if ((ire->ire_type == IRE_CACHE) &&
8096 				    IS_VNI(ire->ire_ipif->ipif_ill))
8097 					dst_ill = ip_newroute_get_dst_ill(
8098 					    ire->ire_stq->q_ptr);
8099 				else
8100 					dst_ill = ip_newroute_get_dst_ill(
8101 					    ire->ire_ipif->ipif_ill);
8102 			}
8103 			if (dst_ill == NULL) {
8104 				if (ip_debug > 2) {
8105 					pr_addr_dbg("ip_newroute: "
8106 					    "no dst ill for dst"
8107 					    " %s\n", AF_INET, &dst);
8108 				}
8109 				goto icmp_err_ret;
8110 			}
8111 		} else {
8112 			dst_ill = ire->ire_ipif->ipif_ill;
8113 			/* for uniformity */
8114 			ill_refhold(dst_ill);
8115 			/*
8116 			 * We should have found a route matching ill as we
8117 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8118 			 * Rather than asserting, when there is a mismatch,
8119 			 * we just drop the packet.
8120 			 */
8121 			if (dst_ill != attach_ill) {
8122 				ip0dbg(("ip_newroute: Packet dropped as "
8123 				    "IPIF_NOFAILOVER ill is %s, "
8124 				    "ire->ire_ipif->ipif_ill is %s\n",
8125 				    attach_ill->ill_name,
8126 				    dst_ill->ill_name));
8127 				ill_refrele(attach_ill);
8128 				goto icmp_err_ret;
8129 			}
8130 		}
8131 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8132 		if (attach_ill != NULL) {
8133 			ill_refrele(attach_ill);
8134 			attach_ill = NULL;
8135 			do_attach_ill = B_TRUE;
8136 		}
8137 		ASSERT(dst_ill != NULL);
8138 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8139 
8140 		/*
8141 		 * Pick the best source address from dst_ill.
8142 		 *
8143 		 * 1) If it is part of a multipathing group, we would
8144 		 *    like to spread the inbound packets across different
8145 		 *    interfaces. ipif_select_source picks a random source
8146 		 *    across the different ills in the group.
8147 		 *
8148 		 * 2) If it is not part of a multipathing group, we try
8149 		 *    to pick the source address from the destination
8150 		 *    route. Clustering assumes that when we have multiple
8151 		 *    prefixes hosted on an interface, the prefix of the
8152 		 *    source address matches the prefix of the destination
8153 		 *    route. We do this only if the address is not
8154 		 *    DEPRECATED.
8155 		 *
8156 		 * 3) If the conn is in a different zone than the ire, we
8157 		 *    need to pick a source address from the right zone.
8158 		 *
8159 		 * NOTE : If we hit case (1) above, the prefix of the source
8160 		 *	  address picked may not match the prefix of the
8161 		 *	  destination routes prefix as ipif_select_source
8162 		 *	  does not look at "dst" while picking a source
8163 		 *	  address.
8164 		 *	  If we want the same behavior as (2), we will need
8165 		 *	  to change the behavior of ipif_select_source.
8166 		 */
8167 		ASSERT(src_ipif == NULL);
8168 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8169 			/*
8170 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8171 			 * Check that the ipif matching the requested source
8172 			 * address still exists.
8173 			 */
8174 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8175 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8176 		}
8177 
8178 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8179 
8180 		if (src_ipif == NULL &&
8181 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8182 			ire_marks |= IRE_MARK_USESRC_CHECK;
8183 			if ((dst_ill->ill_group != NULL) ||
8184 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8185 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8186 			    ire->ire_zoneid != ALL_ZONES) ||
8187 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8188 				/*
8189 				 * If the destination is reachable via a
8190 				 * given gateway, the selected source address
8191 				 * should be in the same subnet as the gateway.
8192 				 * Otherwise, the destination is not reachable.
8193 				 *
8194 				 * If there are no interfaces on the same subnet
8195 				 * as the destination, ipif_select_source gives
8196 				 * first non-deprecated interface which might be
8197 				 * on a different subnet than the gateway.
8198 				 * This is not desirable. Hence pass the dst_ire
8199 				 * source address to ipif_select_source.
8200 				 * It is sure that the destination is reachable
8201 				 * with the dst_ire source address subnet.
8202 				 * So passing dst_ire source address to
8203 				 * ipif_select_source will make sure that the
8204 				 * selected source will be on the same subnet
8205 				 * as dst_ire source address.
8206 				 */
8207 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8208 				src_ipif = ipif_select_source(dst_ill, saddr,
8209 				    zoneid);
8210 				if (src_ipif == NULL) {
8211 					if (ip_debug > 2) {
8212 						pr_addr_dbg("ip_newroute: "
8213 						    "no src for dst %s ",
8214 						    AF_INET, &dst);
8215 						printf("through interface %s\n",
8216 						    dst_ill->ill_name);
8217 					}
8218 					goto icmp_err_ret;
8219 				}
8220 			} else {
8221 				src_ipif = ire->ire_ipif;
8222 				ASSERT(src_ipif != NULL);
8223 				/* hold src_ipif for uniformity */
8224 				ipif_refhold(src_ipif);
8225 			}
8226 		}
8227 
8228 		/*
8229 		 * Assign a source address while we have the conn.
8230 		 * We can't have ip_wput_ire pick a source address when the
8231 		 * packet returns from arp since we need to look at
8232 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8233 		 * going through arp.
8234 		 *
8235 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8236 		 *	  it uses ip6i to store this information.
8237 		 */
8238 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8239 			ipha->ipha_src = src_ipif->ipif_src_addr;
8240 
8241 		if (ip_debug > 3) {
8242 			/* ip2dbg */
8243 			pr_addr_dbg("ip_newroute: first hop %s\n",
8244 			    AF_INET, &gw);
8245 		}
8246 		ip2dbg(("\tire type %s (%d)\n",
8247 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8248 
8249 		/*
8250 		 * The TTL of multirouted packets is bounded by the
8251 		 * ip_multirt_ttl ndd variable.
8252 		 */
8253 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8254 			/* Force TTL of multirouted packets */
8255 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8256 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8257 				ip2dbg(("ip_newroute: forcing multirt TTL "
8258 				    "to %d (was %d), dst 0x%08x\n",
8259 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8260 				    ntohl(sire->ire_addr)));
8261 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8262 			}
8263 		}
8264 		/*
8265 		 * At this point in ip_newroute(), ire is either the
8266 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8267 		 * destination or an IRE_INTERFACE type that should be used
8268 		 * to resolve an on-subnet destination or an on-subnet
8269 		 * next-hop gateway.
8270 		 *
8271 		 * In the IRE_CACHE case, we have the following :
8272 		 *
8273 		 * 1) src_ipif - used for getting a source address.
8274 		 *
8275 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8276 		 *    means packets using this IRE_CACHE will go out on
8277 		 *    dst_ill.
8278 		 *
8279 		 * 3) The IRE sire will point to the prefix that is the
8280 		 *    longest  matching route for the destination. These
8281 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8282 		 *
8283 		 *    The newly created IRE_CACHE entry for the off-subnet
8284 		 *    destination is tied to both the prefix route and the
8285 		 *    interface route used to resolve the next-hop gateway
8286 		 *    via the ire_phandle and ire_ihandle fields,
8287 		 *    respectively.
8288 		 *
8289 		 * In the IRE_INTERFACE case, we have the following :
8290 		 *
8291 		 * 1) src_ipif - used for getting a source address.
8292 		 *
8293 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8294 		 *    means packets using the IRE_CACHE that we will build
8295 		 *    here will go out on dst_ill.
8296 		 *
8297 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8298 		 *    to be created will only be tied to the IRE_INTERFACE
8299 		 *    that was derived from the ire_ihandle field.
8300 		 *
8301 		 *    If sire is non-NULL, it means the destination is
8302 		 *    off-link and we will first create the IRE_CACHE for the
8303 		 *    gateway. Next time through ip_newroute, we will create
8304 		 *    the IRE_CACHE for the final destination as described
8305 		 *    above.
8306 		 *
8307 		 * In both cases, after the current resolution has been
8308 		 * completed (or possibly initialised, in the IRE_INTERFACE
8309 		 * case), the loop may be re-entered to attempt the resolution
8310 		 * of another RTF_MULTIRT route.
8311 		 *
8312 		 * When an IRE_CACHE entry for the off-subnet destination is
8313 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8314 		 * for further processing in emission loops.
8315 		 */
8316 		save_ire = ire;
8317 		switch (ire->ire_type) {
8318 		case IRE_CACHE: {
8319 			ire_t	*ipif_ire;
8320 
8321 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8322 			if (gw == 0)
8323 				gw = ire->ire_gateway_addr;
8324 			/*
8325 			 * We need 3 ire's to create a new cache ire for an
8326 			 * off-link destination from the cache ire of the
8327 			 * gateway.
8328 			 *
8329 			 *	1. The prefix ire 'sire' (Note that this does
8330 			 *	   not apply to the conn_nexthop_set case)
8331 			 *	2. The cache ire of the gateway 'ire'
8332 			 *	3. The interface ire 'ipif_ire'
8333 			 *
8334 			 * We have (1) and (2). We lookup (3) below.
8335 			 *
8336 			 * If there is no interface route to the gateway,
8337 			 * it is a race condition, where we found the cache
8338 			 * but the interface route has been deleted.
8339 			 */
8340 			if (ip_nexthop) {
8341 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8342 			} else {
8343 				ipif_ire =
8344 				    ire_ihandle_lookup_offlink(ire, sire);
8345 			}
8346 			if (ipif_ire == NULL) {
8347 				ip1dbg(("ip_newroute: "
8348 				    "ire_ihandle_lookup_offlink failed\n"));
8349 				goto icmp_err_ret;
8350 			}
8351 
8352 			/*
8353 			 * Check cached gateway IRE for any security
8354 			 * attributes; if found, associate the gateway
8355 			 * credentials group to the destination IRE.
8356 			 */
8357 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8358 				mutex_enter(&attrp->igsa_lock);
8359 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8360 					GCGRP_REFHOLD(gcgrp);
8361 				mutex_exit(&attrp->igsa_lock);
8362 			}
8363 
8364 			/*
8365 			 * XXX For the source of the resolver mp,
8366 			 * we are using the same DL_UNITDATA_REQ
8367 			 * (from save_ire->ire_nce->nce_res_mp)
8368 			 * though the save_ire is not pointing at the same ill.
8369 			 * This is incorrect. We need to send it up to the
8370 			 * resolver to get the right res_mp. For ethernets
8371 			 * this may be okay (ill_type == DL_ETHER).
8372 			 */
8373 
8374 			ire = ire_create(
8375 			    (uchar_t *)&dst,		/* dest address */
8376 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8377 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8378 			    (uchar_t *)&gw,		/* gateway address */
8379 			    &save_ire->ire_max_frag,
8380 			    save_ire->ire_nce,		/* src nce */
8381 			    dst_ill->ill_rq,		/* recv-from queue */
8382 			    dst_ill->ill_wq,		/* send-to queue */
8383 			    IRE_CACHE,			/* IRE type */
8384 			    src_ipif,
8385 			    (sire != NULL) ?
8386 			    sire->ire_mask : 0, 	/* Parent mask */
8387 			    (sire != NULL) ?
8388 			    sire->ire_phandle : 0,	/* Parent handle */
8389 			    ipif_ire->ire_ihandle,	/* Interface handle */
8390 			    (sire != NULL) ? (sire->ire_flags &
8391 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8392 			    (sire != NULL) ?
8393 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8394 			    NULL,
8395 			    gcgrp,
8396 			    ipst);
8397 
8398 			if (ire == NULL) {
8399 				if (gcgrp != NULL) {
8400 					GCGRP_REFRELE(gcgrp);
8401 					gcgrp = NULL;
8402 				}
8403 				ire_refrele(ipif_ire);
8404 				ire_refrele(save_ire);
8405 				break;
8406 			}
8407 
8408 			/* reference now held by IRE */
8409 			gcgrp = NULL;
8410 
8411 			ire->ire_marks |= ire_marks;
8412 
8413 			/*
8414 			 * Prevent sire and ipif_ire from getting deleted.
8415 			 * The newly created ire is tied to both of them via
8416 			 * the phandle and ihandle respectively.
8417 			 */
8418 			if (sire != NULL) {
8419 				IRB_REFHOLD(sire->ire_bucket);
8420 				/* Has it been removed already ? */
8421 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8422 					IRB_REFRELE(sire->ire_bucket);
8423 					ire_refrele(ipif_ire);
8424 					ire_refrele(save_ire);
8425 					break;
8426 				}
8427 			}
8428 
8429 			IRB_REFHOLD(ipif_ire->ire_bucket);
8430 			/* Has it been removed already ? */
8431 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8432 				IRB_REFRELE(ipif_ire->ire_bucket);
8433 				if (sire != NULL)
8434 					IRB_REFRELE(sire->ire_bucket);
8435 				ire_refrele(ipif_ire);
8436 				ire_refrele(save_ire);
8437 				break;
8438 			}
8439 
8440 			xmit_mp = first_mp;
8441 			/*
8442 			 * In the case of multirouting, a copy
8443 			 * of the packet is done before its sending.
8444 			 * The copy is used to attempt another
8445 			 * route resolution, in a next loop.
8446 			 */
8447 			if (ire->ire_flags & RTF_MULTIRT) {
8448 				copy_mp = copymsg(first_mp);
8449 				if (copy_mp != NULL) {
8450 					xmit_mp = copy_mp;
8451 					MULTIRT_DEBUG_TAG(first_mp);
8452 				}
8453 			}
8454 			ire_add_then_send(q, ire, xmit_mp);
8455 			ire_refrele(save_ire);
8456 
8457 			/* Assert that sire is not deleted yet. */
8458 			if (sire != NULL) {
8459 				ASSERT(sire->ire_ptpn != NULL);
8460 				IRB_REFRELE(sire->ire_bucket);
8461 			}
8462 
8463 			/* Assert that ipif_ire is not deleted yet. */
8464 			ASSERT(ipif_ire->ire_ptpn != NULL);
8465 			IRB_REFRELE(ipif_ire->ire_bucket);
8466 			ire_refrele(ipif_ire);
8467 
8468 			/*
8469 			 * If copy_mp is not NULL, multirouting was
8470 			 * requested. We loop to initiate a next
8471 			 * route resolution attempt, starting from sire.
8472 			 */
8473 			if (copy_mp != NULL) {
8474 				/*
8475 				 * Search for the next unresolved
8476 				 * multirt route.
8477 				 */
8478 				copy_mp = NULL;
8479 				ipif_ire = NULL;
8480 				ire = NULL;
8481 				multirt_resolve_next = B_TRUE;
8482 				continue;
8483 			}
8484 			if (sire != NULL)
8485 				ire_refrele(sire);
8486 			ipif_refrele(src_ipif);
8487 			ill_refrele(dst_ill);
8488 			return;
8489 		}
8490 		case IRE_IF_NORESOLVER: {
8491 
8492 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8493 			    dst_ill->ill_resolver_mp == NULL) {
8494 				ip1dbg(("ip_newroute: dst_ill %p "
8495 				    "for IRE_IF_NORESOLVER ire %p has "
8496 				    "no ill_resolver_mp\n",
8497 				    (void *)dst_ill, (void *)ire));
8498 				break;
8499 			}
8500 
8501 			/*
8502 			 * TSol note: We are creating the ire cache for the
8503 			 * destination 'dst'. If 'dst' is offlink, going
8504 			 * through the first hop 'gw', the security attributes
8505 			 * of 'dst' must be set to point to the gateway
8506 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8507 			 * is possible that 'dst' is a potential gateway that is
8508 			 * referenced by some route that has some security
8509 			 * attributes. Thus in the former case, we need to do a
8510 			 * gcgrp_lookup of 'gw' while in the latter case we
8511 			 * need to do gcgrp_lookup of 'dst' itself.
8512 			 */
8513 			ga.ga_af = AF_INET;
8514 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8515 			    &ga.ga_addr);
8516 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8517 
8518 			ire = ire_create(
8519 			    (uchar_t *)&dst,		/* dest address */
8520 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8521 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8522 			    (uchar_t *)&gw,		/* gateway address */
8523 			    &save_ire->ire_max_frag,
8524 			    NULL,			/* no src nce */
8525 			    dst_ill->ill_rq,		/* recv-from queue */
8526 			    dst_ill->ill_wq,		/* send-to queue */
8527 			    IRE_CACHE,
8528 			    src_ipif,
8529 			    save_ire->ire_mask,		/* Parent mask */
8530 			    (sire != NULL) ?		/* Parent handle */
8531 			    sire->ire_phandle : 0,
8532 			    save_ire->ire_ihandle,	/* Interface handle */
8533 			    (sire != NULL) ? sire->ire_flags &
8534 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8535 			    &(save_ire->ire_uinfo),
8536 			    NULL,
8537 			    gcgrp,
8538 			    ipst);
8539 
8540 			if (ire == NULL) {
8541 				if (gcgrp != NULL) {
8542 					GCGRP_REFRELE(gcgrp);
8543 					gcgrp = NULL;
8544 				}
8545 				ire_refrele(save_ire);
8546 				break;
8547 			}
8548 
8549 			/* reference now held by IRE */
8550 			gcgrp = NULL;
8551 
8552 			ire->ire_marks |= ire_marks;
8553 
8554 			/* Prevent save_ire from getting deleted */
8555 			IRB_REFHOLD(save_ire->ire_bucket);
8556 			/* Has it been removed already ? */
8557 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8558 				IRB_REFRELE(save_ire->ire_bucket);
8559 				ire_refrele(save_ire);
8560 				break;
8561 			}
8562 
8563 			/*
8564 			 * In the case of multirouting, a copy
8565 			 * of the packet is made before it is sent.
8566 			 * The copy is used in the next
8567 			 * loop to attempt another resolution.
8568 			 */
8569 			xmit_mp = first_mp;
8570 			if ((sire != NULL) &&
8571 			    (sire->ire_flags & RTF_MULTIRT)) {
8572 				copy_mp = copymsg(first_mp);
8573 				if (copy_mp != NULL) {
8574 					xmit_mp = copy_mp;
8575 					MULTIRT_DEBUG_TAG(first_mp);
8576 				}
8577 			}
8578 			ire_add_then_send(q, ire, xmit_mp);
8579 
8580 			/* Assert that it is not deleted yet. */
8581 			ASSERT(save_ire->ire_ptpn != NULL);
8582 			IRB_REFRELE(save_ire->ire_bucket);
8583 			ire_refrele(save_ire);
8584 
8585 			if (copy_mp != NULL) {
8586 				/*
8587 				 * If we found a (no)resolver, we ignore any
8588 				 * trailing top priority IRE_CACHE in further
8589 				 * loops. This ensures that we do not omit any
8590 				 * (no)resolver.
8591 				 * This IRE_CACHE, if any, will be processed
8592 				 * by another thread entering ip_newroute().
8593 				 * IRE_CACHE entries, if any, will be processed
8594 				 * by another thread entering ip_newroute(),
8595 				 * (upon resolver response, for instance).
8596 				 * This aims to force parallel multirt
8597 				 * resolutions as soon as a packet must be sent.
8598 				 * In the best case, after the tx of only one
8599 				 * packet, all reachable routes are resolved.
8600 				 * Otherwise, the resolution of all RTF_MULTIRT
8601 				 * routes would require several emissions.
8602 				 */
8603 				multirt_flags &= ~MULTIRT_CACHEGW;
8604 
8605 				/*
8606 				 * Search for the next unresolved multirt
8607 				 * route.
8608 				 */
8609 				copy_mp = NULL;
8610 				save_ire = NULL;
8611 				ire = NULL;
8612 				multirt_resolve_next = B_TRUE;
8613 				continue;
8614 			}
8615 
8616 			/*
8617 			 * Don't need sire anymore
8618 			 */
8619 			if (sire != NULL)
8620 				ire_refrele(sire);
8621 
8622 			ipif_refrele(src_ipif);
8623 			ill_refrele(dst_ill);
8624 			return;
8625 		}
8626 		case IRE_IF_RESOLVER:
8627 			/*
8628 			 * We can't build an IRE_CACHE yet, but at least we
8629 			 * found a resolver that can help.
8630 			 */
8631 			res_mp = dst_ill->ill_resolver_mp;
8632 			if (!OK_RESOLVER_MP(res_mp))
8633 				break;
8634 
8635 			/*
8636 			 * To be at this point in the code with a non-zero gw
8637 			 * means that dst is reachable through a gateway that
8638 			 * we have never resolved.  By changing dst to the gw
8639 			 * addr we resolve the gateway first.
8640 			 * When ire_add_then_send() tries to put the IP dg
8641 			 * to dst, it will reenter ip_newroute() at which
8642 			 * time we will find the IRE_CACHE for the gw and
8643 			 * create another IRE_CACHE in case IRE_CACHE above.
8644 			 */
8645 			if (gw != INADDR_ANY) {
8646 				/*
8647 				 * The source ipif that was determined above was
8648 				 * relative to the destination address, not the
8649 				 * gateway's. If src_ipif was not taken out of
8650 				 * the IRE_IF_RESOLVER entry, we'll need to call
8651 				 * ipif_select_source() again.
8652 				 */
8653 				if (src_ipif != ire->ire_ipif) {
8654 					ipif_refrele(src_ipif);
8655 					src_ipif = ipif_select_source(dst_ill,
8656 					    gw, zoneid);
8657 					if (src_ipif == NULL) {
8658 						if (ip_debug > 2) {
8659 							pr_addr_dbg(
8660 							    "ip_newroute: no "
8661 							    "src for gw %s ",
8662 							    AF_INET, &gw);
8663 							printf("through "
8664 							    "interface %s\n",
8665 							    dst_ill->ill_name);
8666 						}
8667 						goto icmp_err_ret;
8668 					}
8669 				}
8670 				save_dst = dst;
8671 				dst = gw;
8672 				gw = INADDR_ANY;
8673 			}
8674 
8675 			/*
8676 			 * We obtain a partial IRE_CACHE which we will pass
8677 			 * along with the resolver query.  When the response
8678 			 * comes back it will be there ready for us to add.
8679 			 * The ire_max_frag is atomically set under the
8680 			 * irebucket lock in ire_add_v[46].
8681 			 */
8682 
8683 			ire = ire_create_mp(
8684 			    (uchar_t *)&dst,		/* dest address */
8685 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8686 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8687 			    (uchar_t *)&gw,		/* gateway address */
8688 			    NULL,			/* ire_max_frag */
8689 			    NULL,			/* no src nce */
8690 			    dst_ill->ill_rq,		/* recv-from queue */
8691 			    dst_ill->ill_wq,		/* send-to queue */
8692 			    IRE_CACHE,
8693 			    src_ipif,			/* Interface ipif */
8694 			    save_ire->ire_mask,		/* Parent mask */
8695 			    0,
8696 			    save_ire->ire_ihandle,	/* Interface handle */
8697 			    0,				/* flags if any */
8698 			    &(save_ire->ire_uinfo),
8699 			    NULL,
8700 			    NULL,
8701 			    ipst);
8702 
8703 			if (ire == NULL) {
8704 				ire_refrele(save_ire);
8705 				break;
8706 			}
8707 
8708 			if ((sire != NULL) &&
8709 			    (sire->ire_flags & RTF_MULTIRT)) {
8710 				copy_mp = copymsg(first_mp);
8711 				if (copy_mp != NULL)
8712 					MULTIRT_DEBUG_TAG(copy_mp);
8713 			}
8714 
8715 			ire->ire_marks |= ire_marks;
8716 
8717 			/*
8718 			 * Construct message chain for the resolver
8719 			 * of the form:
8720 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8721 			 * Packet could contain a IPSEC_OUT mp.
8722 			 *
8723 			 * NOTE : ire will be added later when the response
8724 			 * comes back from ARP. If the response does not
8725 			 * come back, ARP frees the packet. For this reason,
8726 			 * we can't REFHOLD the bucket of save_ire to prevent
8727 			 * deletions. We may not be able to REFRELE the bucket
8728 			 * if the response never comes back. Thus, before
8729 			 * adding the ire, ire_add_v4 will make sure that the
8730 			 * interface route does not get deleted. This is the
8731 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8732 			 * where we can always prevent deletions because of
8733 			 * the synchronous nature of adding IRES i.e
8734 			 * ire_add_then_send is called after creating the IRE.
8735 			 */
8736 			ASSERT(ire->ire_mp != NULL);
8737 			ire->ire_mp->b_cont = first_mp;
8738 			/* Have saved_mp handy, for cleanup if canput fails */
8739 			saved_mp = mp;
8740 			mp = copyb(res_mp);
8741 			if (mp == NULL) {
8742 				/* Prepare for cleanup */
8743 				mp = saved_mp; /* pkt */
8744 				ire_delete(ire); /* ire_mp */
8745 				ire = NULL;
8746 				ire_refrele(save_ire);
8747 				if (copy_mp != NULL) {
8748 					MULTIRT_DEBUG_UNTAG(copy_mp);
8749 					freemsg(copy_mp);
8750 					copy_mp = NULL;
8751 				}
8752 				break;
8753 			}
8754 			linkb(mp, ire->ire_mp);
8755 
8756 			/*
8757 			 * Fill in the source and dest addrs for the resolver.
8758 			 * NOTE: this depends on memory layouts imposed by
8759 			 * ill_init().
8760 			 */
8761 			areq = (areq_t *)mp->b_rptr;
8762 			addrp = (ipaddr_t *)((char *)areq +
8763 			    areq->areq_sender_addr_offset);
8764 			if (do_attach_ill) {
8765 				/*
8766 				 * This is bind to no failover case.
8767 				 * arp packet also must go out on attach_ill.
8768 				 */
8769 				ASSERT(ipha->ipha_src != NULL);
8770 				*addrp = ipha->ipha_src;
8771 			} else {
8772 				*addrp = save_ire->ire_src_addr;
8773 			}
8774 
8775 			ire_refrele(save_ire);
8776 			addrp = (ipaddr_t *)((char *)areq +
8777 			    areq->areq_target_addr_offset);
8778 			*addrp = dst;
8779 			/* Up to the resolver. */
8780 			if (canputnext(dst_ill->ill_rq) &&
8781 			    !(dst_ill->ill_arp_closing)) {
8782 				putnext(dst_ill->ill_rq, mp);
8783 				ire = NULL;
8784 				if (copy_mp != NULL) {
8785 					/*
8786 					 * If we found a resolver, we ignore
8787 					 * any trailing top priority IRE_CACHE
8788 					 * in the further loops. This ensures
8789 					 * that we do not omit any resolver.
8790 					 * IRE_CACHE entries, if any, will be
8791 					 * processed next time we enter
8792 					 * ip_newroute().
8793 					 */
8794 					multirt_flags &= ~MULTIRT_CACHEGW;
8795 					/*
8796 					 * Search for the next unresolved
8797 					 * multirt route.
8798 					 */
8799 					first_mp = copy_mp;
8800 					copy_mp = NULL;
8801 					/* Prepare the next resolution loop. */
8802 					mp = first_mp;
8803 					EXTRACT_PKT_MP(mp, first_mp,
8804 					    mctl_present);
8805 					if (mctl_present)
8806 						io = (ipsec_out_t *)
8807 						    first_mp->b_rptr;
8808 					ipha = (ipha_t *)mp->b_rptr;
8809 
8810 					ASSERT(sire != NULL);
8811 
8812 					dst = save_dst;
8813 					multirt_resolve_next = B_TRUE;
8814 					continue;
8815 				}
8816 
8817 				if (sire != NULL)
8818 					ire_refrele(sire);
8819 
8820 				/*
8821 				 * The response will come back in ip_wput
8822 				 * with db_type IRE_DB_TYPE.
8823 				 */
8824 				ipif_refrele(src_ipif);
8825 				ill_refrele(dst_ill);
8826 				return;
8827 			} else {
8828 				/* Prepare for cleanup */
8829 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8830 				    mp);
8831 				mp->b_cont = NULL;
8832 				freeb(mp); /* areq */
8833 				/*
8834 				 * this is an ire that is not added to the
8835 				 * cache. ire_freemblk will handle the release
8836 				 * of any resources associated with the ire.
8837 				 */
8838 				ire_delete(ire); /* ire_mp */
8839 				mp = saved_mp; /* pkt */
8840 				ire = NULL;
8841 				if (copy_mp != NULL) {
8842 					MULTIRT_DEBUG_UNTAG(copy_mp);
8843 					freemsg(copy_mp);
8844 					copy_mp = NULL;
8845 				}
8846 				break;
8847 			}
8848 		default:
8849 			break;
8850 		}
8851 	} while (multirt_resolve_next);
8852 
8853 	ip1dbg(("ip_newroute: dropped\n"));
8854 	/* Did this packet originate externally? */
8855 	if (mp->b_prev) {
8856 		mp->b_next = NULL;
8857 		mp->b_prev = NULL;
8858 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8859 	} else {
8860 		if (dst_ill != NULL) {
8861 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8862 		} else {
8863 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8864 		}
8865 	}
8866 	ASSERT(copy_mp == NULL);
8867 	MULTIRT_DEBUG_UNTAG(first_mp);
8868 	freemsg(first_mp);
8869 	if (ire != NULL)
8870 		ire_refrele(ire);
8871 	if (sire != NULL)
8872 		ire_refrele(sire);
8873 	if (src_ipif != NULL)
8874 		ipif_refrele(src_ipif);
8875 	if (dst_ill != NULL)
8876 		ill_refrele(dst_ill);
8877 	return;
8878 
8879 icmp_err_ret:
8880 	ip1dbg(("ip_newroute: no route\n"));
8881 	if (src_ipif != NULL)
8882 		ipif_refrele(src_ipif);
8883 	if (dst_ill != NULL)
8884 		ill_refrele(dst_ill);
8885 	if (sire != NULL)
8886 		ire_refrele(sire);
8887 	/* Did this packet originate externally? */
8888 	if (mp->b_prev) {
8889 		mp->b_next = NULL;
8890 		mp->b_prev = NULL;
8891 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8892 		q = WR(q);
8893 	} else {
8894 		/*
8895 		 * There is no outgoing ill, so just increment the
8896 		 * system MIB.
8897 		 */
8898 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8899 		/*
8900 		 * Since ip_wput() isn't close to finished, we fill
8901 		 * in enough of the header for credible error reporting.
8902 		 */
8903 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8904 			/* Failed */
8905 			MULTIRT_DEBUG_UNTAG(first_mp);
8906 			freemsg(first_mp);
8907 			if (ire != NULL)
8908 				ire_refrele(ire);
8909 			return;
8910 		}
8911 	}
8912 
8913 	/*
8914 	 * At this point we will have ire only if RTF_BLACKHOLE
8915 	 * or RTF_REJECT flags are set on the IRE. It will not
8916 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8917 	 */
8918 	if (ire != NULL) {
8919 		if (ire->ire_flags & RTF_BLACKHOLE) {
8920 			ire_refrele(ire);
8921 			MULTIRT_DEBUG_UNTAG(first_mp);
8922 			freemsg(first_mp);
8923 			return;
8924 		}
8925 		ire_refrele(ire);
8926 	}
8927 	if (ip_source_routed(ipha, ipst)) {
8928 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8929 		    zoneid, ipst);
8930 		return;
8931 	}
8932 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8933 }
8934 
8935 ip_opt_info_t zero_info;
8936 
8937 /*
8938  * IPv4 -
8939  * ip_newroute_ipif is called by ip_wput_multicast and
8940  * ip_rput_forward_multicast whenever we need to send
8941  * out a packet to a destination address for which we do not have specific
8942  * routing information. It is used when the packet will be sent out
8943  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8944  * socket option is set or icmp error message wants to go out on a particular
8945  * interface for a unicast packet.
8946  *
8947  * In most cases, the destination address is resolved thanks to the ipif
8948  * intrinsic resolver. However, there are some cases where the call to
8949  * ip_newroute_ipif must take into account the potential presence of
8950  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8951  * that uses the interface. This is specified through flags,
8952  * which can be a combination of:
8953  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8954  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8955  *   and flags. Additionally, the packet source address has to be set to
8956  *   the specified address. The caller is thus expected to set this flag
8957  *   if the packet has no specific source address yet.
8958  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8959  *   flag, the resulting ire will inherit the flag. All unresolved routes
8960  *   to the destination must be explored in the same call to
8961  *   ip_newroute_ipif().
8962  */
8963 static void
8964 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8965     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8966 {
8967 	areq_t	*areq;
8968 	ire_t	*ire = NULL;
8969 	mblk_t	*res_mp;
8970 	ipaddr_t *addrp;
8971 	mblk_t *first_mp;
8972 	ire_t	*save_ire = NULL;
8973 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8974 	ipif_t	*src_ipif = NULL;
8975 	ushort_t ire_marks = 0;
8976 	ill_t	*dst_ill = NULL;
8977 	boolean_t mctl_present;
8978 	ipsec_out_t *io;
8979 	ipha_t *ipha;
8980 	int	ihandle = 0;
8981 	mblk_t	*saved_mp;
8982 	ire_t   *fire = NULL;
8983 	mblk_t  *copy_mp = NULL;
8984 	boolean_t multirt_resolve_next;
8985 	boolean_t unspec_src;
8986 	ipaddr_t ipha_dst;
8987 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8988 
8989 	/*
8990 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8991 	 * here for uniformity
8992 	 */
8993 	ipif_refhold(ipif);
8994 
8995 	/*
8996 	 * This loop is run only once in most cases.
8997 	 * We loop to resolve further routes only when the destination
8998 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8999 	 */
9000 	do {
9001 		if (dst_ill != NULL) {
9002 			ill_refrele(dst_ill);
9003 			dst_ill = NULL;
9004 		}
9005 		if (src_ipif != NULL) {
9006 			ipif_refrele(src_ipif);
9007 			src_ipif = NULL;
9008 		}
9009 		multirt_resolve_next = B_FALSE;
9010 
9011 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9012 		    ipif->ipif_ill->ill_name));
9013 
9014 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9015 		if (mctl_present)
9016 			io = (ipsec_out_t *)first_mp->b_rptr;
9017 
9018 		ipha = (ipha_t *)mp->b_rptr;
9019 
9020 		/*
9021 		 * Save the packet destination address, we may need it after
9022 		 * the packet has been consumed.
9023 		 */
9024 		ipha_dst = ipha->ipha_dst;
9025 
9026 		/*
9027 		 * If the interface is a pt-pt interface we look for an
9028 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9029 		 * local_address and the pt-pt destination address. Otherwise
9030 		 * we just match the local address.
9031 		 * NOTE: dst could be different than ipha->ipha_dst in case
9032 		 * of sending igmp multicast packets over a point-to-point
9033 		 * connection.
9034 		 * Thus we must be careful enough to check ipha_dst to be a
9035 		 * multicast address, otherwise it will take xmit_if path for
9036 		 * multicast packets resulting into kernel stack overflow by
9037 		 * repeated calls to ip_newroute_ipif from ire_send().
9038 		 */
9039 		if (CLASSD(ipha_dst) &&
9040 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9041 			goto err_ret;
9042 		}
9043 
9044 		/*
9045 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9046 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9047 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9048 		 * propagate its flags to the new ire.
9049 		 */
9050 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9051 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9052 			ip2dbg(("ip_newroute_ipif: "
9053 			    "ipif_lookup_multi_ire("
9054 			    "ipif %p, dst %08x) = fire %p\n",
9055 			    (void *)ipif, ntohl(dst), (void *)fire));
9056 		}
9057 
9058 		if (mctl_present && io->ipsec_out_attach_if) {
9059 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9060 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9061 
9062 			/* Failure case frees things for us. */
9063 			if (attach_ill == NULL) {
9064 				ipif_refrele(ipif);
9065 				if (fire != NULL)
9066 					ire_refrele(fire);
9067 				return;
9068 			}
9069 
9070 			/*
9071 			 * Check if we need an ire that will not be
9072 			 * looked up by anybody else i.e. HIDDEN.
9073 			 */
9074 			if (ill_is_probeonly(attach_ill)) {
9075 				ire_marks = IRE_MARK_HIDDEN;
9076 			}
9077 			/*
9078 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9079 			 * case.
9080 			 */
9081 			dst_ill = ipif->ipif_ill;
9082 			/* attach_ill has been refheld by ip_grab_attach_ill */
9083 			ASSERT(dst_ill == attach_ill);
9084 		} else {
9085 			/*
9086 			 * If the interface belongs to an interface group,
9087 			 * make sure the next possible interface in the group
9088 			 * is used.  This encourages load spreading among
9089 			 * peers in an interface group.
9090 			 * Note: load spreading is disabled for RTF_MULTIRT
9091 			 * routes.
9092 			 */
9093 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9094 			    (fire->ire_flags & RTF_MULTIRT)) {
9095 				/*
9096 				 * Don't perform outbound load spreading
9097 				 * in the case of an RTF_MULTIRT issued route,
9098 				 * we actually typically want to replicate
9099 				 * outgoing packets through particular
9100 				 * interfaces.
9101 				 */
9102 				dst_ill = ipif->ipif_ill;
9103 				ill_refhold(dst_ill);
9104 			} else {
9105 				dst_ill = ip_newroute_get_dst_ill(
9106 				    ipif->ipif_ill);
9107 			}
9108 			if (dst_ill == NULL) {
9109 				if (ip_debug > 2) {
9110 					pr_addr_dbg("ip_newroute_ipif: "
9111 					    "no dst ill for dst %s\n",
9112 					    AF_INET, &dst);
9113 				}
9114 				goto err_ret;
9115 			}
9116 		}
9117 
9118 		/*
9119 		 * Pick a source address preferring non-deprecated ones.
9120 		 * Unlike ip_newroute, we don't do any source address
9121 		 * selection here since for multicast it really does not help
9122 		 * in inbound load spreading as in the unicast case.
9123 		 */
9124 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9125 		    (fire->ire_flags & RTF_SETSRC)) {
9126 			/*
9127 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9128 			 * on that interface. This ire has RTF_SETSRC flag, so
9129 			 * the source address of the packet must be changed.
9130 			 * Check that the ipif matching the requested source
9131 			 * address still exists.
9132 			 */
9133 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9134 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9135 		}
9136 
9137 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9138 
9139 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9140 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9141 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9142 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9143 		    (src_ipif == NULL) &&
9144 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9145 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9146 			if (src_ipif == NULL) {
9147 				if (ip_debug > 2) {
9148 					/* ip1dbg */
9149 					pr_addr_dbg("ip_newroute_ipif: "
9150 					    "no src for dst %s",
9151 					    AF_INET, &dst);
9152 				}
9153 				ip1dbg((" through interface %s\n",
9154 				    dst_ill->ill_name));
9155 				goto err_ret;
9156 			}
9157 			ipif_refrele(ipif);
9158 			ipif = src_ipif;
9159 			ipif_refhold(ipif);
9160 		}
9161 		if (src_ipif == NULL) {
9162 			src_ipif = ipif;
9163 			ipif_refhold(src_ipif);
9164 		}
9165 
9166 		/*
9167 		 * Assign a source address while we have the conn.
9168 		 * We can't have ip_wput_ire pick a source address when the
9169 		 * packet returns from arp since conn_unspec_src might be set
9170 		 * and we lose the conn when going through arp.
9171 		 */
9172 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9173 			ipha->ipha_src = src_ipif->ipif_src_addr;
9174 
9175 		/*
9176 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9177 		 * that the outgoing interface does not have an interface ire.
9178 		 */
9179 		if (CLASSD(ipha_dst) && (connp == NULL ||
9180 		    connp->conn_outgoing_ill == NULL) &&
9181 		    infop->ip_opt_ill_index == 0) {
9182 			/* ipif_to_ire returns an held ire */
9183 			ire = ipif_to_ire(ipif);
9184 			if (ire == NULL)
9185 				goto err_ret;
9186 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9187 				goto err_ret;
9188 			/*
9189 			 * ihandle is needed when the ire is added to
9190 			 * cache table.
9191 			 */
9192 			save_ire = ire;
9193 			ihandle = save_ire->ire_ihandle;
9194 
9195 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9196 			    "flags %04x\n",
9197 			    (void *)ire, (void *)ipif, flags));
9198 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9199 			    (fire->ire_flags & RTF_MULTIRT)) {
9200 				/*
9201 				 * As requested by flags, an IRE_OFFSUBNET was
9202 				 * looked up on that interface. This ire has
9203 				 * RTF_MULTIRT flag, so the resolution loop will
9204 				 * be re-entered to resolve additional routes on
9205 				 * other interfaces. For that purpose, a copy of
9206 				 * the packet is performed at this point.
9207 				 */
9208 				fire->ire_last_used_time = lbolt;
9209 				copy_mp = copymsg(first_mp);
9210 				if (copy_mp) {
9211 					MULTIRT_DEBUG_TAG(copy_mp);
9212 				}
9213 			}
9214 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9215 			    (fire->ire_flags & RTF_SETSRC)) {
9216 				/*
9217 				 * As requested by flags, an IRE_OFFSUBET was
9218 				 * looked up on that interface. This ire has
9219 				 * RTF_SETSRC flag, so the source address of the
9220 				 * packet must be changed.
9221 				 */
9222 				ipha->ipha_src = fire->ire_src_addr;
9223 			}
9224 		} else {
9225 			ASSERT((connp == NULL) ||
9226 			    (connp->conn_outgoing_ill != NULL) ||
9227 			    (connp->conn_dontroute) ||
9228 			    infop->ip_opt_ill_index != 0);
9229 			/*
9230 			 * The only ways we can come here are:
9231 			 * 1) IP_BOUND_IF socket option is set
9232 			 * 2) SO_DONTROUTE socket option is set
9233 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9234 			 * In all cases, the new ire will not be added
9235 			 * into cache table.
9236 			 */
9237 			ire_marks |= IRE_MARK_NOADD;
9238 		}
9239 
9240 		switch (ipif->ipif_net_type) {
9241 		case IRE_IF_NORESOLVER: {
9242 			/* We have what we need to build an IRE_CACHE. */
9243 
9244 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9245 			    (dst_ill->ill_resolver_mp == NULL)) {
9246 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9247 				    "for IRE_IF_NORESOLVER ire %p has "
9248 				    "no ill_resolver_mp\n",
9249 				    (void *)dst_ill, (void *)ire));
9250 				break;
9251 			}
9252 
9253 			/*
9254 			 * The new ire inherits the IRE_OFFSUBNET flags
9255 			 * and source address, if this was requested.
9256 			 */
9257 			ire = ire_create(
9258 			    (uchar_t *)&dst,		/* dest address */
9259 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9260 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9261 			    NULL,			/* gateway address */
9262 			    &ipif->ipif_mtu,
9263 			    NULL,			/* no src nce */
9264 			    dst_ill->ill_rq,		/* recv-from queue */
9265 			    dst_ill->ill_wq,		/* send-to queue */
9266 			    IRE_CACHE,
9267 			    src_ipif,
9268 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9269 			    (fire != NULL) ?		/* Parent handle */
9270 			    fire->ire_phandle : 0,
9271 			    ihandle,			/* Interface handle */
9272 			    (fire != NULL) ?
9273 			    (fire->ire_flags &
9274 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9275 			    (save_ire == NULL ? &ire_uinfo_null :
9276 			    &save_ire->ire_uinfo),
9277 			    NULL,
9278 			    NULL,
9279 			    ipst);
9280 
9281 			if (ire == NULL) {
9282 				if (save_ire != NULL)
9283 					ire_refrele(save_ire);
9284 				break;
9285 			}
9286 
9287 			ire->ire_marks |= ire_marks;
9288 
9289 			/*
9290 			 * If IRE_MARK_NOADD is set then we need to convert
9291 			 * the max_fragp to a useable value now. This is
9292 			 * normally done in ire_add_v[46]. We also need to
9293 			 * associate the ire with an nce (normally would be
9294 			 * done in ip_wput_nondata()).
9295 			 *
9296 			 * Note that IRE_MARK_NOADD packets created here
9297 			 * do not have a non-null ire_mp pointer. The null
9298 			 * value of ire_bucket indicates that they were
9299 			 * never added.
9300 			 */
9301 			if (ire->ire_marks & IRE_MARK_NOADD) {
9302 				uint_t  max_frag;
9303 
9304 				max_frag = *ire->ire_max_fragp;
9305 				ire->ire_max_fragp = NULL;
9306 				ire->ire_max_frag = max_frag;
9307 
9308 				if ((ire->ire_nce = ndp_lookup_v4(
9309 				    ire_to_ill(ire),
9310 				    (ire->ire_gateway_addr != INADDR_ANY ?
9311 				    &ire->ire_gateway_addr : &ire->ire_addr),
9312 				    B_FALSE)) == NULL) {
9313 					if (save_ire != NULL)
9314 						ire_refrele(save_ire);
9315 					break;
9316 				}
9317 				ASSERT(ire->ire_nce->nce_state ==
9318 				    ND_REACHABLE);
9319 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9320 			}
9321 
9322 			/* Prevent save_ire from getting deleted */
9323 			if (save_ire != NULL) {
9324 				IRB_REFHOLD(save_ire->ire_bucket);
9325 				/* Has it been removed already ? */
9326 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9327 					IRB_REFRELE(save_ire->ire_bucket);
9328 					ire_refrele(save_ire);
9329 					break;
9330 				}
9331 			}
9332 
9333 			ire_add_then_send(q, ire, first_mp);
9334 
9335 			/* Assert that save_ire is not deleted yet. */
9336 			if (save_ire != NULL) {
9337 				ASSERT(save_ire->ire_ptpn != NULL);
9338 				IRB_REFRELE(save_ire->ire_bucket);
9339 				ire_refrele(save_ire);
9340 				save_ire = NULL;
9341 			}
9342 			if (fire != NULL) {
9343 				ire_refrele(fire);
9344 				fire = NULL;
9345 			}
9346 
9347 			/*
9348 			 * the resolution loop is re-entered if this
9349 			 * was requested through flags and if we
9350 			 * actually are in a multirouting case.
9351 			 */
9352 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9353 				boolean_t need_resolve =
9354 				    ire_multirt_need_resolve(ipha_dst,
9355 				    MBLK_GETLABEL(copy_mp), ipst);
9356 				if (!need_resolve) {
9357 					MULTIRT_DEBUG_UNTAG(copy_mp);
9358 					freemsg(copy_mp);
9359 					copy_mp = NULL;
9360 				} else {
9361 					/*
9362 					 * ipif_lookup_group() calls
9363 					 * ire_lookup_multi() that uses
9364 					 * ire_ftable_lookup() to find
9365 					 * an IRE_INTERFACE for the group.
9366 					 * In the multirt case,
9367 					 * ire_lookup_multi() then invokes
9368 					 * ire_multirt_lookup() to find
9369 					 * the next resolvable ire.
9370 					 * As a result, we obtain an new
9371 					 * interface, derived from the
9372 					 * next ire.
9373 					 */
9374 					ipif_refrele(ipif);
9375 					ipif = ipif_lookup_group(ipha_dst,
9376 					    zoneid, ipst);
9377 					ip2dbg(("ip_newroute_ipif: "
9378 					    "multirt dst %08x, ipif %p\n",
9379 					    htonl(dst), (void *)ipif));
9380 					if (ipif != NULL) {
9381 						mp = copy_mp;
9382 						copy_mp = NULL;
9383 						multirt_resolve_next = B_TRUE;
9384 						continue;
9385 					} else {
9386 						freemsg(copy_mp);
9387 					}
9388 				}
9389 			}
9390 			if (ipif != NULL)
9391 				ipif_refrele(ipif);
9392 			ill_refrele(dst_ill);
9393 			ipif_refrele(src_ipif);
9394 			return;
9395 		}
9396 		case IRE_IF_RESOLVER:
9397 			/*
9398 			 * We can't build an IRE_CACHE yet, but at least
9399 			 * we found a resolver that can help.
9400 			 */
9401 			res_mp = dst_ill->ill_resolver_mp;
9402 			if (!OK_RESOLVER_MP(res_mp))
9403 				break;
9404 
9405 			/*
9406 			 * We obtain a partial IRE_CACHE which we will pass
9407 			 * along with the resolver query.  When the response
9408 			 * comes back it will be there ready for us to add.
9409 			 * The new ire inherits the IRE_OFFSUBNET flags
9410 			 * and source address, if this was requested.
9411 			 * The ire_max_frag is atomically set under the
9412 			 * irebucket lock in ire_add_v[46]. Only in the
9413 			 * case of IRE_MARK_NOADD, we set it here itself.
9414 			 */
9415 			ire = ire_create_mp(
9416 			    (uchar_t *)&dst,		/* dest address */
9417 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9418 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9419 			    NULL,			/* gateway address */
9420 			    (ire_marks & IRE_MARK_NOADD) ?
9421 			    ipif->ipif_mtu : 0,		/* max_frag */
9422 			    NULL,			/* no src nce */
9423 			    dst_ill->ill_rq,		/* recv-from queue */
9424 			    dst_ill->ill_wq,		/* send-to queue */
9425 			    IRE_CACHE,
9426 			    src_ipif,
9427 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9428 			    (fire != NULL) ?		/* Parent handle */
9429 			    fire->ire_phandle : 0,
9430 			    ihandle,			/* Interface handle */
9431 			    (fire != NULL) ?		/* flags if any */
9432 			    (fire->ire_flags &
9433 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9434 			    (save_ire == NULL ? &ire_uinfo_null :
9435 			    &save_ire->ire_uinfo),
9436 			    NULL,
9437 			    NULL,
9438 			    ipst);
9439 
9440 			if (save_ire != NULL) {
9441 				ire_refrele(save_ire);
9442 				save_ire = NULL;
9443 			}
9444 			if (ire == NULL)
9445 				break;
9446 
9447 			ire->ire_marks |= ire_marks;
9448 			/*
9449 			 * Construct message chain for the resolver of the
9450 			 * form:
9451 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9452 			 *
9453 			 * NOTE : ire will be added later when the response
9454 			 * comes back from ARP. If the response does not
9455 			 * come back, ARP frees the packet. For this reason,
9456 			 * we can't REFHOLD the bucket of save_ire to prevent
9457 			 * deletions. We may not be able to REFRELE the
9458 			 * bucket if the response never comes back.
9459 			 * Thus, before adding the ire, ire_add_v4 will make
9460 			 * sure that the interface route does not get deleted.
9461 			 * This is the only case unlike ip_newroute_v6,
9462 			 * ip_newroute_ipif_v6 where we can always prevent
9463 			 * deletions because ire_add_then_send is called after
9464 			 * creating the IRE.
9465 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9466 			 * does not add this IRE into the IRE CACHE.
9467 			 */
9468 			ASSERT(ire->ire_mp != NULL);
9469 			ire->ire_mp->b_cont = first_mp;
9470 			/* Have saved_mp handy, for cleanup if canput fails */
9471 			saved_mp = mp;
9472 			mp = copyb(res_mp);
9473 			if (mp == NULL) {
9474 				/* Prepare for cleanup */
9475 				mp = saved_mp; /* pkt */
9476 				ire_delete(ire); /* ire_mp */
9477 				ire = NULL;
9478 				if (copy_mp != NULL) {
9479 					MULTIRT_DEBUG_UNTAG(copy_mp);
9480 					freemsg(copy_mp);
9481 					copy_mp = NULL;
9482 				}
9483 				break;
9484 			}
9485 			linkb(mp, ire->ire_mp);
9486 
9487 			/*
9488 			 * Fill in the source and dest addrs for the resolver.
9489 			 * NOTE: this depends on memory layouts imposed by
9490 			 * ill_init().
9491 			 */
9492 			areq = (areq_t *)mp->b_rptr;
9493 			addrp = (ipaddr_t *)((char *)areq +
9494 			    areq->areq_sender_addr_offset);
9495 			*addrp = ire->ire_src_addr;
9496 			addrp = (ipaddr_t *)((char *)areq +
9497 			    areq->areq_target_addr_offset);
9498 			*addrp = dst;
9499 			/* Up to the resolver. */
9500 			if (canputnext(dst_ill->ill_rq) &&
9501 			    !(dst_ill->ill_arp_closing)) {
9502 				putnext(dst_ill->ill_rq, mp);
9503 				/*
9504 				 * The response will come back in ip_wput
9505 				 * with db_type IRE_DB_TYPE.
9506 				 */
9507 			} else {
9508 				mp->b_cont = NULL;
9509 				freeb(mp); /* areq */
9510 				ire_delete(ire); /* ire_mp */
9511 				saved_mp->b_next = NULL;
9512 				saved_mp->b_prev = NULL;
9513 				freemsg(first_mp); /* pkt */
9514 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9515 			}
9516 
9517 			if (fire != NULL) {
9518 				ire_refrele(fire);
9519 				fire = NULL;
9520 			}
9521 
9522 
9523 			/*
9524 			 * The resolution loop is re-entered if this was
9525 			 * requested through flags and we actually are
9526 			 * in a multirouting case.
9527 			 */
9528 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9529 				boolean_t need_resolve =
9530 				    ire_multirt_need_resolve(ipha_dst,
9531 				    MBLK_GETLABEL(copy_mp), ipst);
9532 				if (!need_resolve) {
9533 					MULTIRT_DEBUG_UNTAG(copy_mp);
9534 					freemsg(copy_mp);
9535 					copy_mp = NULL;
9536 				} else {
9537 					/*
9538 					 * ipif_lookup_group() calls
9539 					 * ire_lookup_multi() that uses
9540 					 * ire_ftable_lookup() to find
9541 					 * an IRE_INTERFACE for the group.
9542 					 * In the multirt case,
9543 					 * ire_lookup_multi() then invokes
9544 					 * ire_multirt_lookup() to find
9545 					 * the next resolvable ire.
9546 					 * As a result, we obtain an new
9547 					 * interface, derived from the
9548 					 * next ire.
9549 					 */
9550 					ipif_refrele(ipif);
9551 					ipif = ipif_lookup_group(ipha_dst,
9552 					    zoneid, ipst);
9553 					if (ipif != NULL) {
9554 						mp = copy_mp;
9555 						copy_mp = NULL;
9556 						multirt_resolve_next = B_TRUE;
9557 						continue;
9558 					} else {
9559 						freemsg(copy_mp);
9560 					}
9561 				}
9562 			}
9563 			if (ipif != NULL)
9564 				ipif_refrele(ipif);
9565 			ill_refrele(dst_ill);
9566 			ipif_refrele(src_ipif);
9567 			return;
9568 		default:
9569 			break;
9570 		}
9571 	} while (multirt_resolve_next);
9572 
9573 err_ret:
9574 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9575 	if (fire != NULL)
9576 		ire_refrele(fire);
9577 	ipif_refrele(ipif);
9578 	/* Did this packet originate externally? */
9579 	if (dst_ill != NULL)
9580 		ill_refrele(dst_ill);
9581 	if (src_ipif != NULL)
9582 		ipif_refrele(src_ipif);
9583 	if (mp->b_prev || mp->b_next) {
9584 		mp->b_next = NULL;
9585 		mp->b_prev = NULL;
9586 	} else {
9587 		/*
9588 		 * Since ip_wput() isn't close to finished, we fill
9589 		 * in enough of the header for credible error reporting.
9590 		 */
9591 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9592 			/* Failed */
9593 			freemsg(first_mp);
9594 			if (ire != NULL)
9595 				ire_refrele(ire);
9596 			return;
9597 		}
9598 	}
9599 	/*
9600 	 * At this point we will have ire only if RTF_BLACKHOLE
9601 	 * or RTF_REJECT flags are set on the IRE. It will not
9602 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9603 	 */
9604 	if (ire != NULL) {
9605 		if (ire->ire_flags & RTF_BLACKHOLE) {
9606 			ire_refrele(ire);
9607 			freemsg(first_mp);
9608 			return;
9609 		}
9610 		ire_refrele(ire);
9611 	}
9612 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9613 }
9614 
9615 /* Name/Value Table Lookup Routine */
9616 char *
9617 ip_nv_lookup(nv_t *nv, int value)
9618 {
9619 	if (!nv)
9620 		return (NULL);
9621 	for (; nv->nv_name; nv++) {
9622 		if (nv->nv_value == value)
9623 			return (nv->nv_name);
9624 	}
9625 	return ("unknown");
9626 }
9627 
9628 /*
9629  * This is a module open, i.e. this is a control stream for access
9630  * to a DLPI device.  We allocate an ill_t as the instance data in
9631  * this case.
9632  */
9633 int
9634 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9635 {
9636 	ill_t	*ill;
9637 	int	err;
9638 	zoneid_t zoneid;
9639 	netstack_t *ns;
9640 	ip_stack_t *ipst;
9641 
9642 	/*
9643 	 * Prevent unprivileged processes from pushing IP so that
9644 	 * they can't send raw IP.
9645 	 */
9646 	if (secpolicy_net_rawaccess(credp) != 0)
9647 		return (EPERM);
9648 
9649 	ns = netstack_find_by_cred(credp);
9650 	ASSERT(ns != NULL);
9651 	ipst = ns->netstack_ip;
9652 	ASSERT(ipst != NULL);
9653 
9654 	/*
9655 	 * For exclusive stacks we set the zoneid to zero
9656 	 * to make IP operate as if in the global zone.
9657 	 */
9658 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9659 		zoneid = GLOBAL_ZONEID;
9660 	else
9661 		zoneid = crgetzoneid(credp);
9662 
9663 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9664 	q->q_ptr = WR(q)->q_ptr = ill;
9665 	ill->ill_ipst = ipst;
9666 	ill->ill_zoneid = zoneid;
9667 
9668 	/*
9669 	 * ill_init initializes the ill fields and then sends down
9670 	 * down a DL_INFO_REQ after calling qprocson.
9671 	 */
9672 	err = ill_init(q, ill);
9673 	if (err != 0) {
9674 		mi_free(ill);
9675 		netstack_rele(ipst->ips_netstack);
9676 		q->q_ptr = NULL;
9677 		WR(q)->q_ptr = NULL;
9678 		return (err);
9679 	}
9680 
9681 	/* ill_init initializes the ipsq marking this thread as writer */
9682 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9683 	/* Wait for the DL_INFO_ACK */
9684 	mutex_enter(&ill->ill_lock);
9685 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9686 		/*
9687 		 * Return value of 0 indicates a pending signal.
9688 		 */
9689 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9690 		if (err == 0) {
9691 			mutex_exit(&ill->ill_lock);
9692 			(void) ip_close(q, 0);
9693 			return (EINTR);
9694 		}
9695 	}
9696 	mutex_exit(&ill->ill_lock);
9697 
9698 	/*
9699 	 * ip_rput_other could have set an error  in ill_error on
9700 	 * receipt of M_ERROR.
9701 	 */
9702 
9703 	err = ill->ill_error;
9704 	if (err != 0) {
9705 		(void) ip_close(q, 0);
9706 		return (err);
9707 	}
9708 
9709 	ill->ill_credp = credp;
9710 	crhold(credp);
9711 
9712 	mutex_enter(&ipst->ips_ip_mi_lock);
9713 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9714 	    credp);
9715 	mutex_exit(&ipst->ips_ip_mi_lock);
9716 	if (err) {
9717 		(void) ip_close(q, 0);
9718 		return (err);
9719 	}
9720 	return (0);
9721 }
9722 
9723 /* For /dev/ip aka AF_INET open */
9724 int
9725 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9726 {
9727 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9728 }
9729 
9730 /* For /dev/ip6 aka AF_INET6 open */
9731 int
9732 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9733 {
9734 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9735 }
9736 
9737 /* IP open routine. */
9738 int
9739 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9740     boolean_t isv6)
9741 {
9742 	conn_t 		*connp;
9743 	major_t		maj;
9744 	zoneid_t	zoneid;
9745 	netstack_t	*ns;
9746 	ip_stack_t	*ipst;
9747 
9748 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9749 
9750 	/* Allow reopen. */
9751 	if (q->q_ptr != NULL)
9752 		return (0);
9753 
9754 	if (sflag & MODOPEN) {
9755 		/* This is a module open */
9756 		return (ip_modopen(q, devp, flag, sflag, credp));
9757 	}
9758 
9759 	ns = netstack_find_by_cred(credp);
9760 	ASSERT(ns != NULL);
9761 	ipst = ns->netstack_ip;
9762 	ASSERT(ipst != NULL);
9763 
9764 	/*
9765 	 * For exclusive stacks we set the zoneid to zero
9766 	 * to make IP operate as if in the global zone.
9767 	 */
9768 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9769 		zoneid = GLOBAL_ZONEID;
9770 	else
9771 		zoneid = crgetzoneid(credp);
9772 
9773 	/*
9774 	 * We are opening as a device. This is an IP client stream, and we
9775 	 * allocate an conn_t as the instance data.
9776 	 */
9777 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9778 
9779 	/*
9780 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9781 	 * done by netstack_find_by_cred()
9782 	 */
9783 	netstack_rele(ipst->ips_netstack);
9784 
9785 	connp->conn_zoneid = zoneid;
9786 
9787 	connp->conn_upq = q;
9788 	q->q_ptr = WR(q)->q_ptr = connp;
9789 
9790 	if (flag & SO_SOCKSTR)
9791 		connp->conn_flags |= IPCL_SOCKET;
9792 
9793 	/* Minor tells us which /dev entry was opened */
9794 	if (isv6) {
9795 		connp->conn_flags |= IPCL_ISV6;
9796 		connp->conn_af_isv6 = B_TRUE;
9797 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9798 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9799 	} else {
9800 		connp->conn_af_isv6 = B_FALSE;
9801 		connp->conn_pkt_isv6 = B_FALSE;
9802 	}
9803 
9804 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9805 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9806 		connp->conn_minor_arena = ip_minor_arena_la;
9807 	} else {
9808 		/*
9809 		 * Either minor numbers in the large arena were exhausted
9810 		 * or a non socket application is doing the open.
9811 		 * Try to allocate from the small arena.
9812 		 */
9813 		if ((connp->conn_dev =
9814 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9815 			/* CONN_DEC_REF takes care of netstack_rele() */
9816 			q->q_ptr = WR(q)->q_ptr = NULL;
9817 			CONN_DEC_REF(connp);
9818 			return (EBUSY);
9819 		}
9820 		connp->conn_minor_arena = ip_minor_arena_sa;
9821 	}
9822 
9823 	maj = getemajor(*devp);
9824 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9825 
9826 	/*
9827 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9828 	 */
9829 	connp->conn_cred = credp;
9830 
9831 	/*
9832 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9833 	 */
9834 	connp->conn_recv = ip_conn_input;
9835 
9836 	crhold(connp->conn_cred);
9837 
9838 	/*
9839 	 * If the caller has the process-wide flag set, then default to MAC
9840 	 * exempt mode.  This allows read-down to unlabeled hosts.
9841 	 */
9842 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9843 		connp->conn_mac_exempt = B_TRUE;
9844 
9845 	connp->conn_rq = q;
9846 	connp->conn_wq = WR(q);
9847 
9848 	/* Non-zero default values */
9849 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9850 
9851 	/*
9852 	 * Make the conn globally visible to walkers
9853 	 */
9854 	ASSERT(connp->conn_ref == 1);
9855 	mutex_enter(&connp->conn_lock);
9856 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9857 	mutex_exit(&connp->conn_lock);
9858 
9859 	qprocson(q);
9860 
9861 	return (0);
9862 }
9863 
9864 /*
9865  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9866  * Note that there is no race since either ip_output function works - it
9867  * is just an optimization to enter the best ip_output routine directly.
9868  */
9869 void
9870 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9871     ip_stack_t *ipst)
9872 {
9873 	if (isv6)  {
9874 		if (bump_mib) {
9875 			BUMP_MIB(&ipst->ips_ip6_mib,
9876 			    ipIfStatsOutSwitchIPVersion);
9877 		}
9878 		connp->conn_send = ip_output_v6;
9879 		connp->conn_pkt_isv6 = B_TRUE;
9880 	} else {
9881 		if (bump_mib) {
9882 			BUMP_MIB(&ipst->ips_ip_mib,
9883 			    ipIfStatsOutSwitchIPVersion);
9884 		}
9885 		connp->conn_send = ip_output;
9886 		connp->conn_pkt_isv6 = B_FALSE;
9887 	}
9888 
9889 }
9890 
9891 /*
9892  * See if IPsec needs loading because of the options in mp.
9893  */
9894 static boolean_t
9895 ipsec_opt_present(mblk_t *mp)
9896 {
9897 	uint8_t *optcp, *next_optcp, *opt_endcp;
9898 	struct opthdr *opt;
9899 	struct T_opthdr *topt;
9900 	int opthdr_len;
9901 	t_uscalar_t optname, optlevel;
9902 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9903 	ipsec_req_t *ipsr;
9904 
9905 	/*
9906 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9907 	 * return TRUE.
9908 	 */
9909 
9910 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9911 	opt_endcp = optcp + tor->OPT_length;
9912 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9913 		opthdr_len = sizeof (struct T_opthdr);
9914 	} else {		/* O_OPTMGMT_REQ */
9915 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9916 		opthdr_len = sizeof (struct opthdr);
9917 	}
9918 	for (; optcp < opt_endcp; optcp = next_optcp) {
9919 		if (optcp + opthdr_len > opt_endcp)
9920 			return (B_FALSE);	/* Not enough option header. */
9921 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9922 			topt = (struct T_opthdr *)optcp;
9923 			optlevel = topt->level;
9924 			optname = topt->name;
9925 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9926 		} else {
9927 			opt = (struct opthdr *)optcp;
9928 			optlevel = opt->level;
9929 			optname = opt->name;
9930 			next_optcp = optcp + opthdr_len +
9931 			    _TPI_ALIGN_OPT(opt->len);
9932 		}
9933 		if ((next_optcp < optcp) || /* wraparound pointer space */
9934 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9935 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9936 			return (B_FALSE); /* bad option buffer */
9937 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9938 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9939 			/*
9940 			 * Check to see if it's an all-bypass or all-zeroes
9941 			 * IPsec request.  Don't bother loading IPsec if
9942 			 * the socket doesn't want to use it.  (A good example
9943 			 * is a bypass request.)
9944 			 *
9945 			 * Basically, if any of the non-NEVER bits are set,
9946 			 * load IPsec.
9947 			 */
9948 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9949 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9950 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9951 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9952 			    != 0)
9953 				return (B_TRUE);
9954 		}
9955 	}
9956 	return (B_FALSE);
9957 }
9958 
9959 /*
9960  * If conn is is waiting for ipsec to finish loading, kick it.
9961  */
9962 /* ARGSUSED */
9963 static void
9964 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9965 {
9966 	t_scalar_t	optreq_prim;
9967 	mblk_t		*mp;
9968 	cred_t		*cr;
9969 	int		err = 0;
9970 
9971 	/*
9972 	 * This function is called, after ipsec loading is complete.
9973 	 * Since IP checks exclusively and atomically (i.e it prevents
9974 	 * ipsec load from completing until ip_optcom_req completes)
9975 	 * whether ipsec load is complete, there cannot be a race with IP
9976 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9977 	 */
9978 	mutex_enter(&connp->conn_lock);
9979 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9980 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9981 		mp = connp->conn_ipsec_opt_mp;
9982 		connp->conn_ipsec_opt_mp = NULL;
9983 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9984 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9985 		mutex_exit(&connp->conn_lock);
9986 
9987 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9988 
9989 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9990 		if (optreq_prim == T_OPTMGMT_REQ) {
9991 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9992 			    &ip_opt_obj, B_FALSE);
9993 		} else {
9994 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9995 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9996 			    &ip_opt_obj, B_FALSE);
9997 		}
9998 		if (err != EINPROGRESS)
9999 			CONN_OPER_PENDING_DONE(connp);
10000 		return;
10001 	}
10002 	mutex_exit(&connp->conn_lock);
10003 }
10004 
10005 /*
10006  * Called from the ipsec_loader thread, outside any perimeter, to tell
10007  * ip qenable any of the queues waiting for the ipsec loader to
10008  * complete.
10009  */
10010 void
10011 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10012 {
10013 	netstack_t *ns = ipss->ipsec_netstack;
10014 
10015 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10016 }
10017 
10018 /*
10019  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10020  * determines the grp on which it has to become exclusive, queues the mp
10021  * and sq draining restarts the optmgmt
10022  */
10023 static boolean_t
10024 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10025 {
10026 	conn_t *connp = Q_TO_CONN(q);
10027 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10028 
10029 	/*
10030 	 * Take IPsec requests and treat them special.
10031 	 */
10032 	if (ipsec_opt_present(mp)) {
10033 		/* First check if IPsec is loaded. */
10034 		mutex_enter(&ipss->ipsec_loader_lock);
10035 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10036 			mutex_exit(&ipss->ipsec_loader_lock);
10037 			return (B_FALSE);
10038 		}
10039 		mutex_enter(&connp->conn_lock);
10040 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10041 
10042 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10043 		connp->conn_ipsec_opt_mp = mp;
10044 		mutex_exit(&connp->conn_lock);
10045 		mutex_exit(&ipss->ipsec_loader_lock);
10046 
10047 		ipsec_loader_loadnow(ipss);
10048 		return (B_TRUE);
10049 	}
10050 	return (B_FALSE);
10051 }
10052 
10053 /*
10054  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10055  * all of them are copied to the conn_t. If the req is "zero", the policy is
10056  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10057  * fields.
10058  * We keep only the latest setting of the policy and thus policy setting
10059  * is not incremental/cumulative.
10060  *
10061  * Requests to set policies with multiple alternative actions will
10062  * go through a different API.
10063  */
10064 int
10065 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10066 {
10067 	uint_t ah_req = 0;
10068 	uint_t esp_req = 0;
10069 	uint_t se_req = 0;
10070 	ipsec_selkey_t sel;
10071 	ipsec_act_t *actp = NULL;
10072 	uint_t nact;
10073 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10074 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10075 	ipsec_policy_root_t *pr;
10076 	ipsec_policy_head_t *ph;
10077 	int fam;
10078 	boolean_t is_pol_reset;
10079 	int error = 0;
10080 	netstack_t	*ns = connp->conn_netstack;
10081 	ip_stack_t	*ipst = ns->netstack_ip;
10082 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10083 
10084 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10085 
10086 	/*
10087 	 * The IP_SEC_OPT option does not allow variable length parameters,
10088 	 * hence a request cannot be NULL.
10089 	 */
10090 	if (req == NULL)
10091 		return (EINVAL);
10092 
10093 	ah_req = req->ipsr_ah_req;
10094 	esp_req = req->ipsr_esp_req;
10095 	se_req = req->ipsr_self_encap_req;
10096 
10097 	/*
10098 	 * Are we dealing with a request to reset the policy (i.e.
10099 	 * zero requests).
10100 	 */
10101 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10102 	    (esp_req & REQ_MASK) == 0 &&
10103 	    (se_req & REQ_MASK) == 0);
10104 
10105 	if (!is_pol_reset) {
10106 		/*
10107 		 * If we couldn't load IPsec, fail with "protocol
10108 		 * not supported".
10109 		 * IPsec may not have been loaded for a request with zero
10110 		 * policies, so we don't fail in this case.
10111 		 */
10112 		mutex_enter(&ipss->ipsec_loader_lock);
10113 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10114 			mutex_exit(&ipss->ipsec_loader_lock);
10115 			return (EPROTONOSUPPORT);
10116 		}
10117 		mutex_exit(&ipss->ipsec_loader_lock);
10118 
10119 		/*
10120 		 * Test for valid requests. Invalid algorithms
10121 		 * need to be tested by IPsec code because new
10122 		 * algorithms can be added dynamically.
10123 		 */
10124 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10125 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10126 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10127 			return (EINVAL);
10128 		}
10129 
10130 		/*
10131 		 * Only privileged users can issue these
10132 		 * requests.
10133 		 */
10134 		if (((ah_req & IPSEC_PREF_NEVER) ||
10135 		    (esp_req & IPSEC_PREF_NEVER) ||
10136 		    (se_req & IPSEC_PREF_NEVER)) &&
10137 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10138 			return (EPERM);
10139 		}
10140 
10141 		/*
10142 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10143 		 * are mutually exclusive.
10144 		 */
10145 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10146 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10147 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10148 			/* Both of them are set */
10149 			return (EINVAL);
10150 		}
10151 	}
10152 
10153 	mutex_enter(&connp->conn_lock);
10154 
10155 	/*
10156 	 * If we have already cached policies in ip_bind_connected*(), don't
10157 	 * let them change now. We cache policies for connections
10158 	 * whose src,dst [addr, port] is known.
10159 	 */
10160 	if (connp->conn_policy_cached) {
10161 		mutex_exit(&connp->conn_lock);
10162 		return (EINVAL);
10163 	}
10164 
10165 	/*
10166 	 * We have a zero policies, reset the connection policy if already
10167 	 * set. This will cause the connection to inherit the
10168 	 * global policy, if any.
10169 	 */
10170 	if (is_pol_reset) {
10171 		if (connp->conn_policy != NULL) {
10172 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10173 			connp->conn_policy = NULL;
10174 		}
10175 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10176 		connp->conn_in_enforce_policy = B_FALSE;
10177 		connp->conn_out_enforce_policy = B_FALSE;
10178 		mutex_exit(&connp->conn_lock);
10179 		return (0);
10180 	}
10181 
10182 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10183 	    ipst->ips_netstack);
10184 	if (ph == NULL)
10185 		goto enomem;
10186 
10187 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10188 	if (actp == NULL)
10189 		goto enomem;
10190 
10191 	/*
10192 	 * Always allocate IPv4 policy entries, since they can also
10193 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10194 	 */
10195 	bzero(&sel, sizeof (sel));
10196 	sel.ipsl_valid = IPSL_IPV4;
10197 
10198 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10199 	    ipst->ips_netstack);
10200 	if (pin4 == NULL)
10201 		goto enomem;
10202 
10203 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10204 	    ipst->ips_netstack);
10205 	if (pout4 == NULL)
10206 		goto enomem;
10207 
10208 	if (connp->conn_af_isv6) {
10209 		/*
10210 		 * We're looking at a v6 socket, also allocate the
10211 		 * v6-specific entries...
10212 		 */
10213 		sel.ipsl_valid = IPSL_IPV6;
10214 		pin6 = ipsec_policy_create(&sel, actp, nact,
10215 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10216 		if (pin6 == NULL)
10217 			goto enomem;
10218 
10219 		pout6 = ipsec_policy_create(&sel, actp, nact,
10220 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10221 		if (pout6 == NULL)
10222 			goto enomem;
10223 
10224 		/*
10225 		 * .. and file them away in the right place.
10226 		 */
10227 		fam = IPSEC_AF_V6;
10228 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10229 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10230 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10231 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10232 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10233 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10234 	}
10235 
10236 	ipsec_actvec_free(actp, nact);
10237 
10238 	/*
10239 	 * File the v4 policies.
10240 	 */
10241 	fam = IPSEC_AF_V4;
10242 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10243 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10244 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10245 
10246 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10247 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10248 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10249 
10250 	/*
10251 	 * If the requests need security, set enforce_policy.
10252 	 * If the requests are IPSEC_PREF_NEVER, one should
10253 	 * still set conn_out_enforce_policy so that an ipsec_out
10254 	 * gets attached in ip_wput. This is needed so that
10255 	 * for connections that we don't cache policy in ip_bind,
10256 	 * if global policy matches in ip_wput_attach_policy, we
10257 	 * don't wrongly inherit global policy. Similarly, we need
10258 	 * to set conn_in_enforce_policy also so that we don't verify
10259 	 * policy wrongly.
10260 	 */
10261 	if ((ah_req & REQ_MASK) != 0 ||
10262 	    (esp_req & REQ_MASK) != 0 ||
10263 	    (se_req & REQ_MASK) != 0) {
10264 		connp->conn_in_enforce_policy = B_TRUE;
10265 		connp->conn_out_enforce_policy = B_TRUE;
10266 		connp->conn_flags |= IPCL_CHECK_POLICY;
10267 	}
10268 
10269 	mutex_exit(&connp->conn_lock);
10270 	return (error);
10271 #undef REQ_MASK
10272 
10273 	/*
10274 	 * Common memory-allocation-failure exit path.
10275 	 */
10276 enomem:
10277 	mutex_exit(&connp->conn_lock);
10278 	if (actp != NULL)
10279 		ipsec_actvec_free(actp, nact);
10280 	if (pin4 != NULL)
10281 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10282 	if (pout4 != NULL)
10283 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10284 	if (pin6 != NULL)
10285 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10286 	if (pout6 != NULL)
10287 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10288 	return (ENOMEM);
10289 }
10290 
10291 /*
10292  * Only for options that pass in an IP addr. Currently only V4 options
10293  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10294  * So this function assumes level is IPPROTO_IP
10295  */
10296 int
10297 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10298     mblk_t *first_mp)
10299 {
10300 	ipif_t *ipif = NULL;
10301 	int error;
10302 	ill_t *ill;
10303 	int zoneid;
10304 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10305 
10306 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10307 
10308 	if (addr != INADDR_ANY || checkonly) {
10309 		ASSERT(connp != NULL);
10310 		zoneid = IPCL_ZONEID(connp);
10311 		if (option == IP_NEXTHOP) {
10312 			ipif = ipif_lookup_onlink_addr(addr,
10313 			    connp->conn_zoneid, ipst);
10314 		} else {
10315 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10316 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10317 			    &error, ipst);
10318 		}
10319 		if (ipif == NULL) {
10320 			if (error == EINPROGRESS)
10321 				return (error);
10322 			else if ((option == IP_MULTICAST_IF) ||
10323 			    (option == IP_NEXTHOP))
10324 				return (EHOSTUNREACH);
10325 			else
10326 				return (EINVAL);
10327 		} else if (checkonly) {
10328 			if (option == IP_MULTICAST_IF) {
10329 				ill = ipif->ipif_ill;
10330 				/* not supported by the virtual network iface */
10331 				if (IS_VNI(ill)) {
10332 					ipif_refrele(ipif);
10333 					return (EINVAL);
10334 				}
10335 			}
10336 			ipif_refrele(ipif);
10337 			return (0);
10338 		}
10339 		ill = ipif->ipif_ill;
10340 		mutex_enter(&connp->conn_lock);
10341 		mutex_enter(&ill->ill_lock);
10342 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10343 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10344 			mutex_exit(&ill->ill_lock);
10345 			mutex_exit(&connp->conn_lock);
10346 			ipif_refrele(ipif);
10347 			return (option == IP_MULTICAST_IF ?
10348 			    EHOSTUNREACH : EINVAL);
10349 		}
10350 	} else {
10351 		mutex_enter(&connp->conn_lock);
10352 	}
10353 
10354 	/* None of the options below are supported on the VNI */
10355 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10356 		mutex_exit(&ill->ill_lock);
10357 		mutex_exit(&connp->conn_lock);
10358 		ipif_refrele(ipif);
10359 		return (EINVAL);
10360 	}
10361 
10362 	switch (option) {
10363 	case IP_DONTFAILOVER_IF:
10364 		/*
10365 		 * This option is used by in.mpathd to ensure
10366 		 * that IPMP probe packets only go out on the
10367 		 * test interfaces. in.mpathd sets this option
10368 		 * on the non-failover interfaces.
10369 		 * For backward compatibility, this option
10370 		 * implicitly sets IP_MULTICAST_IF, as used
10371 		 * be done in bind(), so that ip_wput gets
10372 		 * this ipif to send mcast packets.
10373 		 */
10374 		if (ipif != NULL) {
10375 			ASSERT(addr != INADDR_ANY);
10376 			connp->conn_nofailover_ill = ipif->ipif_ill;
10377 			connp->conn_multicast_ipif = ipif;
10378 		} else {
10379 			ASSERT(addr == INADDR_ANY);
10380 			connp->conn_nofailover_ill = NULL;
10381 			connp->conn_multicast_ipif = NULL;
10382 		}
10383 		break;
10384 
10385 	case IP_MULTICAST_IF:
10386 		connp->conn_multicast_ipif = ipif;
10387 		break;
10388 	case IP_NEXTHOP:
10389 		connp->conn_nexthop_v4 = addr;
10390 		connp->conn_nexthop_set = B_TRUE;
10391 		break;
10392 	}
10393 
10394 	if (ipif != NULL) {
10395 		mutex_exit(&ill->ill_lock);
10396 		mutex_exit(&connp->conn_lock);
10397 		ipif_refrele(ipif);
10398 		return (0);
10399 	}
10400 	mutex_exit(&connp->conn_lock);
10401 	/* We succeded in cleared the option */
10402 	return (0);
10403 }
10404 
10405 /*
10406  * For options that pass in an ifindex specifying the ill. V6 options always
10407  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10408  */
10409 int
10410 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10411     int level, int option, mblk_t *first_mp)
10412 {
10413 	ill_t *ill = NULL;
10414 	int error = 0;
10415 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10416 
10417 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10418 	if (ifindex != 0) {
10419 		ASSERT(connp != NULL);
10420 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10421 		    first_mp, ip_restart_optmgmt, &error, ipst);
10422 		if (ill != NULL) {
10423 			if (checkonly) {
10424 				/* not supported by the virtual network iface */
10425 				if (IS_VNI(ill)) {
10426 					ill_refrele(ill);
10427 					return (EINVAL);
10428 				}
10429 				ill_refrele(ill);
10430 				return (0);
10431 			}
10432 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10433 			    0, NULL)) {
10434 				ill_refrele(ill);
10435 				ill = NULL;
10436 				mutex_enter(&connp->conn_lock);
10437 				goto setit;
10438 			}
10439 			mutex_enter(&connp->conn_lock);
10440 			mutex_enter(&ill->ill_lock);
10441 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10442 				mutex_exit(&ill->ill_lock);
10443 				mutex_exit(&connp->conn_lock);
10444 				ill_refrele(ill);
10445 				ill = NULL;
10446 				mutex_enter(&connp->conn_lock);
10447 			}
10448 			goto setit;
10449 		} else if (error == EINPROGRESS) {
10450 			return (error);
10451 		} else {
10452 			error = 0;
10453 		}
10454 	}
10455 	mutex_enter(&connp->conn_lock);
10456 setit:
10457 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10458 
10459 	/*
10460 	 * The options below assume that the ILL (if any) transmits and/or
10461 	 * receives traffic. Neither of which is true for the virtual network
10462 	 * interface, so fail setting these on a VNI.
10463 	 */
10464 	if (IS_VNI(ill)) {
10465 		ASSERT(ill != NULL);
10466 		mutex_exit(&ill->ill_lock);
10467 		mutex_exit(&connp->conn_lock);
10468 		ill_refrele(ill);
10469 		return (EINVAL);
10470 	}
10471 
10472 	if (level == IPPROTO_IP) {
10473 		switch (option) {
10474 		case IP_BOUND_IF:
10475 			connp->conn_incoming_ill = ill;
10476 			connp->conn_outgoing_ill = ill;
10477 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10478 			    0 : ifindex;
10479 			break;
10480 
10481 		case IP_MULTICAST_IF:
10482 			/*
10483 			 * This option is an internal special. The socket
10484 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10485 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10486 			 * specifies an ifindex and we try first on V6 ill's.
10487 			 * If we don't find one, we they try using on v4 ill's
10488 			 * intenally and we come here.
10489 			 */
10490 			if (!checkonly && ill != NULL) {
10491 				ipif_t	*ipif;
10492 				ipif = ill->ill_ipif;
10493 
10494 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10495 					mutex_exit(&ill->ill_lock);
10496 					mutex_exit(&connp->conn_lock);
10497 					ill_refrele(ill);
10498 					ill = NULL;
10499 					mutex_enter(&connp->conn_lock);
10500 				} else {
10501 					connp->conn_multicast_ipif = ipif;
10502 				}
10503 			}
10504 			break;
10505 
10506 		case IP_DHCPINIT_IF:
10507 			if (connp->conn_dhcpinit_ill != NULL) {
10508 				/*
10509 				 * We've locked the conn so conn_cleanup_ill()
10510 				 * cannot clear conn_dhcpinit_ill -- so it's
10511 				 * safe to access the ill.
10512 				 */
10513 				ill_t *oill = connp->conn_dhcpinit_ill;
10514 
10515 				ASSERT(oill->ill_dhcpinit != 0);
10516 				atomic_dec_32(&oill->ill_dhcpinit);
10517 				connp->conn_dhcpinit_ill = NULL;
10518 			}
10519 
10520 			if (ill != NULL) {
10521 				connp->conn_dhcpinit_ill = ill;
10522 				atomic_inc_32(&ill->ill_dhcpinit);
10523 			}
10524 			break;
10525 		}
10526 	} else {
10527 		switch (option) {
10528 		case IPV6_BOUND_IF:
10529 			connp->conn_incoming_ill = ill;
10530 			connp->conn_outgoing_ill = ill;
10531 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10532 			    0 : ifindex;
10533 			break;
10534 
10535 		case IPV6_BOUND_PIF:
10536 			/*
10537 			 * Limit all transmit to this ill.
10538 			 * Unlike IPV6_BOUND_IF, using this option
10539 			 * prevents load spreading and failover from
10540 			 * happening when the interface is part of the
10541 			 * group. That's why we don't need to remember
10542 			 * the ifindex in orig_bound_ifindex as in
10543 			 * IPV6_BOUND_IF.
10544 			 */
10545 			connp->conn_outgoing_pill = ill;
10546 			break;
10547 
10548 		case IPV6_DONTFAILOVER_IF:
10549 			/*
10550 			 * This option is used by in.mpathd to ensure
10551 			 * that IPMP probe packets only go out on the
10552 			 * test interfaces. in.mpathd sets this option
10553 			 * on the non-failover interfaces.
10554 			 */
10555 			connp->conn_nofailover_ill = ill;
10556 			/*
10557 			 * For backward compatibility, this option
10558 			 * implicitly sets ip_multicast_ill as used in
10559 			 * IPV6_MULTICAST_IF so that ip_wput gets
10560 			 * this ill to send mcast packets.
10561 			 */
10562 			connp->conn_multicast_ill = ill;
10563 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10564 			    0 : ifindex;
10565 			break;
10566 
10567 		case IPV6_MULTICAST_IF:
10568 			/*
10569 			 * Set conn_multicast_ill to be the IPv6 ill.
10570 			 * Set conn_multicast_ipif to be an IPv4 ipif
10571 			 * for ifindex to make IPv4 mapped addresses
10572 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10573 			 * Even if no IPv6 ill exists for the ifindex
10574 			 * we need to check for an IPv4 ifindex in order
10575 			 * for this to work with mapped addresses. In that
10576 			 * case only set conn_multicast_ipif.
10577 			 */
10578 			if (!checkonly) {
10579 				if (ifindex == 0) {
10580 					connp->conn_multicast_ill = NULL;
10581 					connp->conn_orig_multicast_ifindex = 0;
10582 					connp->conn_multicast_ipif = NULL;
10583 				} else if (ill != NULL) {
10584 					connp->conn_multicast_ill = ill;
10585 					connp->conn_orig_multicast_ifindex =
10586 					    ifindex;
10587 				}
10588 			}
10589 			break;
10590 		}
10591 	}
10592 
10593 	if (ill != NULL) {
10594 		mutex_exit(&ill->ill_lock);
10595 		mutex_exit(&connp->conn_lock);
10596 		ill_refrele(ill);
10597 		return (0);
10598 	}
10599 	mutex_exit(&connp->conn_lock);
10600 	/*
10601 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10602 	 * locate the ill and could not set the option (ifindex != 0)
10603 	 */
10604 	return (ifindex == 0 ? 0 : EINVAL);
10605 }
10606 
10607 /* This routine sets socket options. */
10608 /* ARGSUSED */
10609 int
10610 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10611     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10612     void *dummy, cred_t *cr, mblk_t *first_mp)
10613 {
10614 	int		*i1 = (int *)invalp;
10615 	conn_t		*connp = Q_TO_CONN(q);
10616 	int		error = 0;
10617 	boolean_t	checkonly;
10618 	ire_t		*ire;
10619 	boolean_t	found;
10620 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10621 
10622 	switch (optset_context) {
10623 
10624 	case SETFN_OPTCOM_CHECKONLY:
10625 		checkonly = B_TRUE;
10626 		/*
10627 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10628 		 * inlen != 0 implies value supplied and
10629 		 * 	we have to "pretend" to set it.
10630 		 * inlen == 0 implies that there is no
10631 		 * 	value part in T_CHECK request and just validation
10632 		 * done elsewhere should be enough, we just return here.
10633 		 */
10634 		if (inlen == 0) {
10635 			*outlenp = 0;
10636 			return (0);
10637 		}
10638 		break;
10639 	case SETFN_OPTCOM_NEGOTIATE:
10640 	case SETFN_UD_NEGOTIATE:
10641 	case SETFN_CONN_NEGOTIATE:
10642 		checkonly = B_FALSE;
10643 		break;
10644 	default:
10645 		/*
10646 		 * We should never get here
10647 		 */
10648 		*outlenp = 0;
10649 		return (EINVAL);
10650 	}
10651 
10652 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10653 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10654 
10655 	/*
10656 	 * For fixed length options, no sanity check
10657 	 * of passed in length is done. It is assumed *_optcom_req()
10658 	 * routines do the right thing.
10659 	 */
10660 
10661 	switch (level) {
10662 	case SOL_SOCKET:
10663 		/*
10664 		 * conn_lock protects the bitfields, and is used to
10665 		 * set the fields atomically.
10666 		 */
10667 		switch (name) {
10668 		case SO_BROADCAST:
10669 			if (!checkonly) {
10670 				/* TODO: use value someplace? */
10671 				mutex_enter(&connp->conn_lock);
10672 				connp->conn_broadcast = *i1 ? 1 : 0;
10673 				mutex_exit(&connp->conn_lock);
10674 			}
10675 			break;	/* goto sizeof (int) option return */
10676 		case SO_USELOOPBACK:
10677 			if (!checkonly) {
10678 				/* TODO: use value someplace? */
10679 				mutex_enter(&connp->conn_lock);
10680 				connp->conn_loopback = *i1 ? 1 : 0;
10681 				mutex_exit(&connp->conn_lock);
10682 			}
10683 			break;	/* goto sizeof (int) option return */
10684 		case SO_DONTROUTE:
10685 			if (!checkonly) {
10686 				mutex_enter(&connp->conn_lock);
10687 				connp->conn_dontroute = *i1 ? 1 : 0;
10688 				mutex_exit(&connp->conn_lock);
10689 			}
10690 			break;	/* goto sizeof (int) option return */
10691 		case SO_REUSEADDR:
10692 			if (!checkonly) {
10693 				mutex_enter(&connp->conn_lock);
10694 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10695 				mutex_exit(&connp->conn_lock);
10696 			}
10697 			break;	/* goto sizeof (int) option return */
10698 		case SO_PROTOTYPE:
10699 			if (!checkonly) {
10700 				mutex_enter(&connp->conn_lock);
10701 				connp->conn_proto = *i1;
10702 				mutex_exit(&connp->conn_lock);
10703 			}
10704 			break;	/* goto sizeof (int) option return */
10705 		case SO_ALLZONES:
10706 			if (!checkonly) {
10707 				mutex_enter(&connp->conn_lock);
10708 				if (IPCL_IS_BOUND(connp)) {
10709 					mutex_exit(&connp->conn_lock);
10710 					return (EINVAL);
10711 				}
10712 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10713 				mutex_exit(&connp->conn_lock);
10714 			}
10715 			break;	/* goto sizeof (int) option return */
10716 		case SO_ANON_MLP:
10717 			if (!checkonly) {
10718 				mutex_enter(&connp->conn_lock);
10719 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10720 				mutex_exit(&connp->conn_lock);
10721 			}
10722 			break;	/* goto sizeof (int) option return */
10723 		case SO_MAC_EXEMPT:
10724 			if (secpolicy_net_mac_aware(cr) != 0 ||
10725 			    IPCL_IS_BOUND(connp))
10726 				return (EACCES);
10727 			if (!checkonly) {
10728 				mutex_enter(&connp->conn_lock);
10729 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10730 				mutex_exit(&connp->conn_lock);
10731 			}
10732 			break;	/* goto sizeof (int) option return */
10733 		default:
10734 			/*
10735 			 * "soft" error (negative)
10736 			 * option not handled at this level
10737 			 * Note: Do not modify *outlenp
10738 			 */
10739 			return (-EINVAL);
10740 		}
10741 		break;
10742 	case IPPROTO_IP:
10743 		switch (name) {
10744 		case IP_NEXTHOP:
10745 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10746 				return (EPERM);
10747 			/* FALLTHRU */
10748 		case IP_MULTICAST_IF:
10749 		case IP_DONTFAILOVER_IF: {
10750 			ipaddr_t addr = *i1;
10751 
10752 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10753 			    first_mp);
10754 			if (error != 0)
10755 				return (error);
10756 			break;	/* goto sizeof (int) option return */
10757 		}
10758 
10759 		case IP_MULTICAST_TTL:
10760 			/* Recorded in transport above IP */
10761 			*outvalp = *invalp;
10762 			*outlenp = sizeof (uchar_t);
10763 			return (0);
10764 		case IP_MULTICAST_LOOP:
10765 			if (!checkonly) {
10766 				mutex_enter(&connp->conn_lock);
10767 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10768 				mutex_exit(&connp->conn_lock);
10769 			}
10770 			*outvalp = *invalp;
10771 			*outlenp = sizeof (uchar_t);
10772 			return (0);
10773 		case IP_ADD_MEMBERSHIP:
10774 		case MCAST_JOIN_GROUP:
10775 		case IP_DROP_MEMBERSHIP:
10776 		case MCAST_LEAVE_GROUP: {
10777 			struct ip_mreq *mreqp;
10778 			struct group_req *greqp;
10779 			ire_t *ire;
10780 			boolean_t done = B_FALSE;
10781 			ipaddr_t group, ifaddr;
10782 			struct sockaddr_in *sin;
10783 			uint32_t *ifindexp;
10784 			boolean_t mcast_opt = B_TRUE;
10785 			mcast_record_t fmode;
10786 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10787 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10788 
10789 			switch (name) {
10790 			case IP_ADD_MEMBERSHIP:
10791 				mcast_opt = B_FALSE;
10792 				/* FALLTHRU */
10793 			case MCAST_JOIN_GROUP:
10794 				fmode = MODE_IS_EXCLUDE;
10795 				optfn = ip_opt_add_group;
10796 				break;
10797 
10798 			case IP_DROP_MEMBERSHIP:
10799 				mcast_opt = B_FALSE;
10800 				/* FALLTHRU */
10801 			case MCAST_LEAVE_GROUP:
10802 				fmode = MODE_IS_INCLUDE;
10803 				optfn = ip_opt_delete_group;
10804 				break;
10805 			}
10806 
10807 			if (mcast_opt) {
10808 				greqp = (struct group_req *)i1;
10809 				sin = (struct sockaddr_in *)&greqp->gr_group;
10810 				if (sin->sin_family != AF_INET) {
10811 					*outlenp = 0;
10812 					return (ENOPROTOOPT);
10813 				}
10814 				group = (ipaddr_t)sin->sin_addr.s_addr;
10815 				ifaddr = INADDR_ANY;
10816 				ifindexp = &greqp->gr_interface;
10817 			} else {
10818 				mreqp = (struct ip_mreq *)i1;
10819 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10820 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10821 				ifindexp = NULL;
10822 			}
10823 
10824 			/*
10825 			 * In the multirouting case, we need to replicate
10826 			 * the request on all interfaces that will take part
10827 			 * in replication.  We do so because multirouting is
10828 			 * reflective, thus we will probably receive multi-
10829 			 * casts on those interfaces.
10830 			 * The ip_multirt_apply_membership() succeeds if the
10831 			 * operation succeeds on at least one interface.
10832 			 */
10833 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10834 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10835 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10836 			if (ire != NULL) {
10837 				if (ire->ire_flags & RTF_MULTIRT) {
10838 					error = ip_multirt_apply_membership(
10839 					    optfn, ire, connp, checkonly, group,
10840 					    fmode, INADDR_ANY, first_mp);
10841 					done = B_TRUE;
10842 				}
10843 				ire_refrele(ire);
10844 			}
10845 			if (!done) {
10846 				error = optfn(connp, checkonly, group, ifaddr,
10847 				    ifindexp, fmode, INADDR_ANY, first_mp);
10848 			}
10849 			if (error) {
10850 				/*
10851 				 * EINPROGRESS is a soft error, needs retry
10852 				 * so don't make *outlenp zero.
10853 				 */
10854 				if (error != EINPROGRESS)
10855 					*outlenp = 0;
10856 				return (error);
10857 			}
10858 			/* OK return - copy input buffer into output buffer */
10859 			if (invalp != outvalp) {
10860 				/* don't trust bcopy for identical src/dst */
10861 				bcopy(invalp, outvalp, inlen);
10862 			}
10863 			*outlenp = inlen;
10864 			return (0);
10865 		}
10866 		case IP_BLOCK_SOURCE:
10867 		case IP_UNBLOCK_SOURCE:
10868 		case IP_ADD_SOURCE_MEMBERSHIP:
10869 		case IP_DROP_SOURCE_MEMBERSHIP:
10870 		case MCAST_BLOCK_SOURCE:
10871 		case MCAST_UNBLOCK_SOURCE:
10872 		case MCAST_JOIN_SOURCE_GROUP:
10873 		case MCAST_LEAVE_SOURCE_GROUP: {
10874 			struct ip_mreq_source *imreqp;
10875 			struct group_source_req *gsreqp;
10876 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10877 			uint32_t ifindex = 0;
10878 			mcast_record_t fmode;
10879 			struct sockaddr_in *sin;
10880 			ire_t *ire;
10881 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10882 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10883 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10884 
10885 			switch (name) {
10886 			case IP_BLOCK_SOURCE:
10887 				mcast_opt = B_FALSE;
10888 				/* FALLTHRU */
10889 			case MCAST_BLOCK_SOURCE:
10890 				fmode = MODE_IS_EXCLUDE;
10891 				optfn = ip_opt_add_group;
10892 				break;
10893 
10894 			case IP_UNBLOCK_SOURCE:
10895 				mcast_opt = B_FALSE;
10896 				/* FALLTHRU */
10897 			case MCAST_UNBLOCK_SOURCE:
10898 				fmode = MODE_IS_EXCLUDE;
10899 				optfn = ip_opt_delete_group;
10900 				break;
10901 
10902 			case IP_ADD_SOURCE_MEMBERSHIP:
10903 				mcast_opt = B_FALSE;
10904 				/* FALLTHRU */
10905 			case MCAST_JOIN_SOURCE_GROUP:
10906 				fmode = MODE_IS_INCLUDE;
10907 				optfn = ip_opt_add_group;
10908 				break;
10909 
10910 			case IP_DROP_SOURCE_MEMBERSHIP:
10911 				mcast_opt = B_FALSE;
10912 				/* FALLTHRU */
10913 			case MCAST_LEAVE_SOURCE_GROUP:
10914 				fmode = MODE_IS_INCLUDE;
10915 				optfn = ip_opt_delete_group;
10916 				break;
10917 			}
10918 
10919 			if (mcast_opt) {
10920 				gsreqp = (struct group_source_req *)i1;
10921 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10922 					*outlenp = 0;
10923 					return (ENOPROTOOPT);
10924 				}
10925 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10926 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10927 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10928 				src = (ipaddr_t)sin->sin_addr.s_addr;
10929 				ifindex = gsreqp->gsr_interface;
10930 			} else {
10931 				imreqp = (struct ip_mreq_source *)i1;
10932 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10933 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10934 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10935 			}
10936 
10937 			/*
10938 			 * In the multirouting case, we need to replicate
10939 			 * the request as noted in the mcast cases above.
10940 			 */
10941 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10942 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10943 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10944 			if (ire != NULL) {
10945 				if (ire->ire_flags & RTF_MULTIRT) {
10946 					error = ip_multirt_apply_membership(
10947 					    optfn, ire, connp, checkonly, grp,
10948 					    fmode, src, first_mp);
10949 					done = B_TRUE;
10950 				}
10951 				ire_refrele(ire);
10952 			}
10953 			if (!done) {
10954 				error = optfn(connp, checkonly, grp, ifaddr,
10955 				    &ifindex, fmode, src, first_mp);
10956 			}
10957 			if (error != 0) {
10958 				/*
10959 				 * EINPROGRESS is a soft error, needs retry
10960 				 * so don't make *outlenp zero.
10961 				 */
10962 				if (error != EINPROGRESS)
10963 					*outlenp = 0;
10964 				return (error);
10965 			}
10966 			/* OK return - copy input buffer into output buffer */
10967 			if (invalp != outvalp) {
10968 				bcopy(invalp, outvalp, inlen);
10969 			}
10970 			*outlenp = inlen;
10971 			return (0);
10972 		}
10973 		case IP_SEC_OPT:
10974 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10975 			if (error != 0) {
10976 				*outlenp = 0;
10977 				return (error);
10978 			}
10979 			break;
10980 		case IP_HDRINCL:
10981 		case IP_OPTIONS:
10982 		case T_IP_OPTIONS:
10983 		case IP_TOS:
10984 		case T_IP_TOS:
10985 		case IP_TTL:
10986 		case IP_RECVDSTADDR:
10987 		case IP_RECVOPTS:
10988 			/* OK return - copy input buffer into output buffer */
10989 			if (invalp != outvalp) {
10990 				/* don't trust bcopy for identical src/dst */
10991 				bcopy(invalp, outvalp, inlen);
10992 			}
10993 			*outlenp = inlen;
10994 			return (0);
10995 		case IP_RECVIF:
10996 			/* Retrieve the inbound interface index */
10997 			if (!checkonly) {
10998 				mutex_enter(&connp->conn_lock);
10999 				connp->conn_recvif = *i1 ? 1 : 0;
11000 				mutex_exit(&connp->conn_lock);
11001 			}
11002 			break;	/* goto sizeof (int) option return */
11003 		case IP_RECVPKTINFO:
11004 			if (!checkonly) {
11005 				mutex_enter(&connp->conn_lock);
11006 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11007 				mutex_exit(&connp->conn_lock);
11008 			}
11009 			break;	/* goto sizeof (int) option return */
11010 		case IP_RECVSLLA:
11011 			/* Retrieve the source link layer address */
11012 			if (!checkonly) {
11013 				mutex_enter(&connp->conn_lock);
11014 				connp->conn_recvslla = *i1 ? 1 : 0;
11015 				mutex_exit(&connp->conn_lock);
11016 			}
11017 			break;	/* goto sizeof (int) option return */
11018 		case MRT_INIT:
11019 		case MRT_DONE:
11020 		case MRT_ADD_VIF:
11021 		case MRT_DEL_VIF:
11022 		case MRT_ADD_MFC:
11023 		case MRT_DEL_MFC:
11024 		case MRT_ASSERT:
11025 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11026 				*outlenp = 0;
11027 				return (error);
11028 			}
11029 			error = ip_mrouter_set((int)name, q, checkonly,
11030 			    (uchar_t *)invalp, inlen, first_mp);
11031 			if (error) {
11032 				*outlenp = 0;
11033 				return (error);
11034 			}
11035 			/* OK return - copy input buffer into output buffer */
11036 			if (invalp != outvalp) {
11037 				/* don't trust bcopy for identical src/dst */
11038 				bcopy(invalp, outvalp, inlen);
11039 			}
11040 			*outlenp = inlen;
11041 			return (0);
11042 		case IP_BOUND_IF:
11043 		case IP_DHCPINIT_IF:
11044 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11045 			    level, name, first_mp);
11046 			if (error != 0)
11047 				return (error);
11048 			break; 		/* goto sizeof (int) option return */
11049 
11050 		case IP_UNSPEC_SRC:
11051 			/* Allow sending with a zero source address */
11052 			if (!checkonly) {
11053 				mutex_enter(&connp->conn_lock);
11054 				connp->conn_unspec_src = *i1 ? 1 : 0;
11055 				mutex_exit(&connp->conn_lock);
11056 			}
11057 			break;	/* goto sizeof (int) option return */
11058 		default:
11059 			/*
11060 			 * "soft" error (negative)
11061 			 * option not handled at this level
11062 			 * Note: Do not modify *outlenp
11063 			 */
11064 			return (-EINVAL);
11065 		}
11066 		break;
11067 	case IPPROTO_IPV6:
11068 		switch (name) {
11069 		case IPV6_BOUND_IF:
11070 		case IPV6_BOUND_PIF:
11071 		case IPV6_DONTFAILOVER_IF:
11072 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11073 			    level, name, first_mp);
11074 			if (error != 0)
11075 				return (error);
11076 			break; 		/* goto sizeof (int) option return */
11077 
11078 		case IPV6_MULTICAST_IF:
11079 			/*
11080 			 * The only possible errors are EINPROGRESS and
11081 			 * EINVAL. EINPROGRESS will be restarted and is not
11082 			 * a hard error. We call this option on both V4 and V6
11083 			 * If both return EINVAL, then this call returns
11084 			 * EINVAL. If at least one of them succeeds we
11085 			 * return success.
11086 			 */
11087 			found = B_FALSE;
11088 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11089 			    level, name, first_mp);
11090 			if (error == EINPROGRESS)
11091 				return (error);
11092 			if (error == 0)
11093 				found = B_TRUE;
11094 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11095 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11096 			if (error == 0)
11097 				found = B_TRUE;
11098 			if (!found)
11099 				return (error);
11100 			break; 		/* goto sizeof (int) option return */
11101 
11102 		case IPV6_MULTICAST_HOPS:
11103 			/* Recorded in transport above IP */
11104 			break;	/* goto sizeof (int) option return */
11105 		case IPV6_MULTICAST_LOOP:
11106 			if (!checkonly) {
11107 				mutex_enter(&connp->conn_lock);
11108 				connp->conn_multicast_loop = *i1;
11109 				mutex_exit(&connp->conn_lock);
11110 			}
11111 			break;	/* goto sizeof (int) option return */
11112 		case IPV6_JOIN_GROUP:
11113 		case MCAST_JOIN_GROUP:
11114 		case IPV6_LEAVE_GROUP:
11115 		case MCAST_LEAVE_GROUP: {
11116 			struct ipv6_mreq *ip_mreqp;
11117 			struct group_req *greqp;
11118 			ire_t *ire;
11119 			boolean_t done = B_FALSE;
11120 			in6_addr_t groupv6;
11121 			uint32_t ifindex;
11122 			boolean_t mcast_opt = B_TRUE;
11123 			mcast_record_t fmode;
11124 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11125 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11126 
11127 			switch (name) {
11128 			case IPV6_JOIN_GROUP:
11129 				mcast_opt = B_FALSE;
11130 				/* FALLTHRU */
11131 			case MCAST_JOIN_GROUP:
11132 				fmode = MODE_IS_EXCLUDE;
11133 				optfn = ip_opt_add_group_v6;
11134 				break;
11135 
11136 			case IPV6_LEAVE_GROUP:
11137 				mcast_opt = B_FALSE;
11138 				/* FALLTHRU */
11139 			case MCAST_LEAVE_GROUP:
11140 				fmode = MODE_IS_INCLUDE;
11141 				optfn = ip_opt_delete_group_v6;
11142 				break;
11143 			}
11144 
11145 			if (mcast_opt) {
11146 				struct sockaddr_in *sin;
11147 				struct sockaddr_in6 *sin6;
11148 				greqp = (struct group_req *)i1;
11149 				if (greqp->gr_group.ss_family == AF_INET) {
11150 					sin = (struct sockaddr_in *)
11151 					    &(greqp->gr_group);
11152 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11153 					    &groupv6);
11154 				} else {
11155 					sin6 = (struct sockaddr_in6 *)
11156 					    &(greqp->gr_group);
11157 					groupv6 = sin6->sin6_addr;
11158 				}
11159 				ifindex = greqp->gr_interface;
11160 			} else {
11161 				ip_mreqp = (struct ipv6_mreq *)i1;
11162 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11163 				ifindex = ip_mreqp->ipv6mr_interface;
11164 			}
11165 			/*
11166 			 * In the multirouting case, we need to replicate
11167 			 * the request on all interfaces that will take part
11168 			 * in replication.  We do so because multirouting is
11169 			 * reflective, thus we will probably receive multi-
11170 			 * casts on those interfaces.
11171 			 * The ip_multirt_apply_membership_v6() succeeds if
11172 			 * the operation succeeds on at least one interface.
11173 			 */
11174 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11175 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11176 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11177 			if (ire != NULL) {
11178 				if (ire->ire_flags & RTF_MULTIRT) {
11179 					error = ip_multirt_apply_membership_v6(
11180 					    optfn, ire, connp, checkonly,
11181 					    &groupv6, fmode, &ipv6_all_zeros,
11182 					    first_mp);
11183 					done = B_TRUE;
11184 				}
11185 				ire_refrele(ire);
11186 			}
11187 			if (!done) {
11188 				error = optfn(connp, checkonly, &groupv6,
11189 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11190 			}
11191 			if (error) {
11192 				/*
11193 				 * EINPROGRESS is a soft error, needs retry
11194 				 * so don't make *outlenp zero.
11195 				 */
11196 				if (error != EINPROGRESS)
11197 					*outlenp = 0;
11198 				return (error);
11199 			}
11200 			/* OK return - copy input buffer into output buffer */
11201 			if (invalp != outvalp) {
11202 				/* don't trust bcopy for identical src/dst */
11203 				bcopy(invalp, outvalp, inlen);
11204 			}
11205 			*outlenp = inlen;
11206 			return (0);
11207 		}
11208 		case MCAST_BLOCK_SOURCE:
11209 		case MCAST_UNBLOCK_SOURCE:
11210 		case MCAST_JOIN_SOURCE_GROUP:
11211 		case MCAST_LEAVE_SOURCE_GROUP: {
11212 			struct group_source_req *gsreqp;
11213 			in6_addr_t v6grp, v6src;
11214 			uint32_t ifindex;
11215 			mcast_record_t fmode;
11216 			ire_t *ire;
11217 			boolean_t done = B_FALSE;
11218 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11219 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11220 
11221 			switch (name) {
11222 			case MCAST_BLOCK_SOURCE:
11223 				fmode = MODE_IS_EXCLUDE;
11224 				optfn = ip_opt_add_group_v6;
11225 				break;
11226 			case MCAST_UNBLOCK_SOURCE:
11227 				fmode = MODE_IS_EXCLUDE;
11228 				optfn = ip_opt_delete_group_v6;
11229 				break;
11230 			case MCAST_JOIN_SOURCE_GROUP:
11231 				fmode = MODE_IS_INCLUDE;
11232 				optfn = ip_opt_add_group_v6;
11233 				break;
11234 			case MCAST_LEAVE_SOURCE_GROUP:
11235 				fmode = MODE_IS_INCLUDE;
11236 				optfn = ip_opt_delete_group_v6;
11237 				break;
11238 			}
11239 
11240 			gsreqp = (struct group_source_req *)i1;
11241 			ifindex = gsreqp->gsr_interface;
11242 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11243 				struct sockaddr_in *s;
11244 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11245 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11246 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11247 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11248 			} else {
11249 				struct sockaddr_in6 *s6;
11250 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11251 				v6grp = s6->sin6_addr;
11252 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11253 				v6src = s6->sin6_addr;
11254 			}
11255 
11256 			/*
11257 			 * In the multirouting case, we need to replicate
11258 			 * the request as noted in the mcast cases above.
11259 			 */
11260 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11261 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11262 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11263 			if (ire != NULL) {
11264 				if (ire->ire_flags & RTF_MULTIRT) {
11265 					error = ip_multirt_apply_membership_v6(
11266 					    optfn, ire, connp, checkonly,
11267 					    &v6grp, fmode, &v6src, first_mp);
11268 					done = B_TRUE;
11269 				}
11270 				ire_refrele(ire);
11271 			}
11272 			if (!done) {
11273 				error = optfn(connp, checkonly, &v6grp,
11274 				    ifindex, fmode, &v6src, first_mp);
11275 			}
11276 			if (error != 0) {
11277 				/*
11278 				 * EINPROGRESS is a soft error, needs retry
11279 				 * so don't make *outlenp zero.
11280 				 */
11281 				if (error != EINPROGRESS)
11282 					*outlenp = 0;
11283 				return (error);
11284 			}
11285 			/* OK return - copy input buffer into output buffer */
11286 			if (invalp != outvalp) {
11287 				bcopy(invalp, outvalp, inlen);
11288 			}
11289 			*outlenp = inlen;
11290 			return (0);
11291 		}
11292 		case IPV6_UNICAST_HOPS:
11293 			/* Recorded in transport above IP */
11294 			break;	/* goto sizeof (int) option return */
11295 		case IPV6_UNSPEC_SRC:
11296 			/* Allow sending with a zero source address */
11297 			if (!checkonly) {
11298 				mutex_enter(&connp->conn_lock);
11299 				connp->conn_unspec_src = *i1 ? 1 : 0;
11300 				mutex_exit(&connp->conn_lock);
11301 			}
11302 			break;	/* goto sizeof (int) option return */
11303 		case IPV6_RECVPKTINFO:
11304 			if (!checkonly) {
11305 				mutex_enter(&connp->conn_lock);
11306 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11307 				mutex_exit(&connp->conn_lock);
11308 			}
11309 			break;	/* goto sizeof (int) option return */
11310 		case IPV6_RECVTCLASS:
11311 			if (!checkonly) {
11312 				if (*i1 < 0 || *i1 > 1) {
11313 					return (EINVAL);
11314 				}
11315 				mutex_enter(&connp->conn_lock);
11316 				connp->conn_ipv6_recvtclass = *i1;
11317 				mutex_exit(&connp->conn_lock);
11318 			}
11319 			break;
11320 		case IPV6_RECVPATHMTU:
11321 			if (!checkonly) {
11322 				if (*i1 < 0 || *i1 > 1) {
11323 					return (EINVAL);
11324 				}
11325 				mutex_enter(&connp->conn_lock);
11326 				connp->conn_ipv6_recvpathmtu = *i1;
11327 				mutex_exit(&connp->conn_lock);
11328 			}
11329 			break;
11330 		case IPV6_RECVHOPLIMIT:
11331 			if (!checkonly) {
11332 				mutex_enter(&connp->conn_lock);
11333 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11334 				mutex_exit(&connp->conn_lock);
11335 			}
11336 			break;	/* goto sizeof (int) option return */
11337 		case IPV6_RECVHOPOPTS:
11338 			if (!checkonly) {
11339 				mutex_enter(&connp->conn_lock);
11340 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11341 				mutex_exit(&connp->conn_lock);
11342 			}
11343 			break;	/* goto sizeof (int) option return */
11344 		case IPV6_RECVDSTOPTS:
11345 			if (!checkonly) {
11346 				mutex_enter(&connp->conn_lock);
11347 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11348 				mutex_exit(&connp->conn_lock);
11349 			}
11350 			break;	/* goto sizeof (int) option return */
11351 		case IPV6_RECVRTHDR:
11352 			if (!checkonly) {
11353 				mutex_enter(&connp->conn_lock);
11354 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11355 				mutex_exit(&connp->conn_lock);
11356 			}
11357 			break;	/* goto sizeof (int) option return */
11358 		case IPV6_RECVRTHDRDSTOPTS:
11359 			if (!checkonly) {
11360 				mutex_enter(&connp->conn_lock);
11361 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11362 				mutex_exit(&connp->conn_lock);
11363 			}
11364 			break;	/* goto sizeof (int) option return */
11365 		case IPV6_PKTINFO:
11366 			if (inlen == 0)
11367 				return (-EINVAL);	/* clearing option */
11368 			error = ip6_set_pktinfo(cr, connp,
11369 			    (struct in6_pktinfo *)invalp, first_mp);
11370 			if (error != 0)
11371 				*outlenp = 0;
11372 			else
11373 				*outlenp = inlen;
11374 			return (error);
11375 		case IPV6_NEXTHOP: {
11376 			struct sockaddr_in6 *sin6;
11377 
11378 			/* Verify that the nexthop is reachable */
11379 			if (inlen == 0)
11380 				return (-EINVAL);	/* clearing option */
11381 
11382 			sin6 = (struct sockaddr_in6 *)invalp;
11383 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11384 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11385 			    NULL, MATCH_IRE_DEFAULT, ipst);
11386 
11387 			if (ire == NULL) {
11388 				*outlenp = 0;
11389 				return (EHOSTUNREACH);
11390 			}
11391 			ire_refrele(ire);
11392 			return (-EINVAL);
11393 		}
11394 		case IPV6_SEC_OPT:
11395 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11396 			if (error != 0) {
11397 				*outlenp = 0;
11398 				return (error);
11399 			}
11400 			break;
11401 		case IPV6_SRC_PREFERENCES: {
11402 			/*
11403 			 * This is implemented strictly in the ip module
11404 			 * (here and in tcp_opt_*() to accomodate tcp
11405 			 * sockets).  Modules above ip pass this option
11406 			 * down here since ip is the only one that needs to
11407 			 * be aware of source address preferences.
11408 			 *
11409 			 * This socket option only affects connected
11410 			 * sockets that haven't already bound to a specific
11411 			 * IPv6 address.  In other words, sockets that
11412 			 * don't call bind() with an address other than the
11413 			 * unspecified address and that call connect().
11414 			 * ip_bind_connected_v6() passes these preferences
11415 			 * to the ipif_select_source_v6() function.
11416 			 */
11417 			if (inlen != sizeof (uint32_t))
11418 				return (EINVAL);
11419 			error = ip6_set_src_preferences(connp,
11420 			    *(uint32_t *)invalp);
11421 			if (error != 0) {
11422 				*outlenp = 0;
11423 				return (error);
11424 			} else {
11425 				*outlenp = sizeof (uint32_t);
11426 			}
11427 			break;
11428 		}
11429 		case IPV6_V6ONLY:
11430 			if (*i1 < 0 || *i1 > 1) {
11431 				return (EINVAL);
11432 			}
11433 			mutex_enter(&connp->conn_lock);
11434 			connp->conn_ipv6_v6only = *i1;
11435 			mutex_exit(&connp->conn_lock);
11436 			break;
11437 		default:
11438 			return (-EINVAL);
11439 		}
11440 		break;
11441 	default:
11442 		/*
11443 		 * "soft" error (negative)
11444 		 * option not handled at this level
11445 		 * Note: Do not modify *outlenp
11446 		 */
11447 		return (-EINVAL);
11448 	}
11449 	/*
11450 	 * Common case of return from an option that is sizeof (int)
11451 	 */
11452 	*(int *)outvalp = *i1;
11453 	*outlenp = sizeof (int);
11454 	return (0);
11455 }
11456 
11457 /*
11458  * This routine gets default values of certain options whose default
11459  * values are maintained by protocol specific code
11460  */
11461 /* ARGSUSED */
11462 int
11463 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11464 {
11465 	int *i1 = (int *)ptr;
11466 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11467 
11468 	switch (level) {
11469 	case IPPROTO_IP:
11470 		switch (name) {
11471 		case IP_MULTICAST_TTL:
11472 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11473 			return (sizeof (uchar_t));
11474 		case IP_MULTICAST_LOOP:
11475 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11476 			return (sizeof (uchar_t));
11477 		default:
11478 			return (-1);
11479 		}
11480 	case IPPROTO_IPV6:
11481 		switch (name) {
11482 		case IPV6_UNICAST_HOPS:
11483 			*i1 = ipst->ips_ipv6_def_hops;
11484 			return (sizeof (int));
11485 		case IPV6_MULTICAST_HOPS:
11486 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11487 			return (sizeof (int));
11488 		case IPV6_MULTICAST_LOOP:
11489 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11490 			return (sizeof (int));
11491 		case IPV6_V6ONLY:
11492 			*i1 = 1;
11493 			return (sizeof (int));
11494 		default:
11495 			return (-1);
11496 		}
11497 	default:
11498 		return (-1);
11499 	}
11500 	/* NOTREACHED */
11501 }
11502 
11503 /*
11504  * Given a destination address and a pointer to where to put the information
11505  * this routine fills in the mtuinfo.
11506  */
11507 int
11508 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11509     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11510 {
11511 	ire_t *ire;
11512 	ip_stack_t	*ipst = ns->netstack_ip;
11513 
11514 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11515 		return (-1);
11516 
11517 	bzero(mtuinfo, sizeof (*mtuinfo));
11518 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11519 	mtuinfo->ip6m_addr.sin6_port = port;
11520 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11521 
11522 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11523 	if (ire != NULL) {
11524 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11525 		ire_refrele(ire);
11526 	} else {
11527 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11528 	}
11529 	return (sizeof (struct ip6_mtuinfo));
11530 }
11531 
11532 /*
11533  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11534  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11535  * isn't.  This doesn't matter as the error checking is done properly for the
11536  * other MRT options coming in through ip_opt_set.
11537  */
11538 int
11539 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11540 {
11541 	conn_t		*connp = Q_TO_CONN(q);
11542 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11543 
11544 	switch (level) {
11545 	case IPPROTO_IP:
11546 		switch (name) {
11547 		case MRT_VERSION:
11548 		case MRT_ASSERT:
11549 			(void) ip_mrouter_get(name, q, ptr);
11550 			return (sizeof (int));
11551 		case IP_SEC_OPT:
11552 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11553 		case IP_NEXTHOP:
11554 			if (connp->conn_nexthop_set) {
11555 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11556 				return (sizeof (ipaddr_t));
11557 			} else
11558 				return (0);
11559 		case IP_RECVPKTINFO:
11560 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11561 			return (sizeof (int));
11562 		default:
11563 			break;
11564 		}
11565 		break;
11566 	case IPPROTO_IPV6:
11567 		switch (name) {
11568 		case IPV6_SEC_OPT:
11569 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11570 		case IPV6_SRC_PREFERENCES: {
11571 			return (ip6_get_src_preferences(connp,
11572 			    (uint32_t *)ptr));
11573 		}
11574 		case IPV6_V6ONLY:
11575 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11576 			return (sizeof (int));
11577 		case IPV6_PATHMTU:
11578 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11579 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11580 		default:
11581 			break;
11582 		}
11583 		break;
11584 	default:
11585 		break;
11586 	}
11587 	return (-1);
11588 }
11589 
11590 /* Named Dispatch routine to get a current value out of our parameter table. */
11591 /* ARGSUSED */
11592 static int
11593 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11594 {
11595 	ipparam_t *ippa = (ipparam_t *)cp;
11596 
11597 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11598 	return (0);
11599 }
11600 
11601 /* ARGSUSED */
11602 static int
11603 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11604 {
11605 
11606 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11607 	return (0);
11608 }
11609 
11610 /*
11611  * Set ip{,6}_forwarding values.  This means walking through all of the
11612  * ill's and toggling their forwarding values.
11613  */
11614 /* ARGSUSED */
11615 static int
11616 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11617 {
11618 	long new_value;
11619 	int *forwarding_value = (int *)cp;
11620 	ill_t *ill;
11621 	boolean_t isv6;
11622 	ill_walk_context_t ctx;
11623 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11624 
11625 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11626 
11627 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11628 	    new_value < 0 || new_value > 1) {
11629 		return (EINVAL);
11630 	}
11631 
11632 	*forwarding_value = new_value;
11633 
11634 	/*
11635 	 * Regardless of the current value of ip_forwarding, set all per-ill
11636 	 * values of ip_forwarding to the value being set.
11637 	 *
11638 	 * Bring all the ill's up to date with the new global value.
11639 	 */
11640 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11641 
11642 	if (isv6)
11643 		ill = ILL_START_WALK_V6(&ctx, ipst);
11644 	else
11645 		ill = ILL_START_WALK_V4(&ctx, ipst);
11646 
11647 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11648 		(void) ill_forward_set(ill, new_value != 0);
11649 
11650 	rw_exit(&ipst->ips_ill_g_lock);
11651 	return (0);
11652 }
11653 
11654 /*
11655  * Walk through the param array specified registering each element with the
11656  * Named Dispatch handler. This is called only during init. So it is ok
11657  * not to acquire any locks
11658  */
11659 static boolean_t
11660 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11661     ipndp_t *ipnd, size_t ipnd_cnt)
11662 {
11663 	for (; ippa_cnt-- > 0; ippa++) {
11664 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11665 			if (!nd_load(ndp, ippa->ip_param_name,
11666 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11667 				nd_free(ndp);
11668 				return (B_FALSE);
11669 			}
11670 		}
11671 	}
11672 
11673 	for (; ipnd_cnt-- > 0; ipnd++) {
11674 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11675 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11676 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11677 			    ipnd->ip_ndp_data)) {
11678 				nd_free(ndp);
11679 				return (B_FALSE);
11680 			}
11681 		}
11682 	}
11683 
11684 	return (B_TRUE);
11685 }
11686 
11687 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11688 /* ARGSUSED */
11689 static int
11690 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11691 {
11692 	long		new_value;
11693 	ipparam_t	*ippa = (ipparam_t *)cp;
11694 
11695 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11696 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11697 		return (EINVAL);
11698 	}
11699 	ippa->ip_param_value = new_value;
11700 	return (0);
11701 }
11702 
11703 /*
11704  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11705  * When an ipf is passed here for the first time, if
11706  * we already have in-order fragments on the queue, we convert from the fast-
11707  * path reassembly scheme to the hard-case scheme.  From then on, additional
11708  * fragments are reassembled here.  We keep track of the start and end offsets
11709  * of each piece, and the number of holes in the chain.  When the hole count
11710  * goes to zero, we are done!
11711  *
11712  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11713  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11714  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11715  * after the call to ip_reassemble().
11716  */
11717 int
11718 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11719     size_t msg_len)
11720 {
11721 	uint_t	end;
11722 	mblk_t	*next_mp;
11723 	mblk_t	*mp1;
11724 	uint_t	offset;
11725 	boolean_t incr_dups = B_TRUE;
11726 	boolean_t offset_zero_seen = B_FALSE;
11727 	boolean_t pkt_boundary_checked = B_FALSE;
11728 
11729 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11730 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11731 
11732 	/* Add in byte count */
11733 	ipf->ipf_count += msg_len;
11734 	if (ipf->ipf_end) {
11735 		/*
11736 		 * We were part way through in-order reassembly, but now there
11737 		 * is a hole.  We walk through messages already queued, and
11738 		 * mark them for hard case reassembly.  We know that up till
11739 		 * now they were in order starting from offset zero.
11740 		 */
11741 		offset = 0;
11742 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11743 			IP_REASS_SET_START(mp1, offset);
11744 			if (offset == 0) {
11745 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11746 				offset = -ipf->ipf_nf_hdr_len;
11747 			}
11748 			offset += mp1->b_wptr - mp1->b_rptr;
11749 			IP_REASS_SET_END(mp1, offset);
11750 		}
11751 		/* One hole at the end. */
11752 		ipf->ipf_hole_cnt = 1;
11753 		/* Brand it as a hard case, forever. */
11754 		ipf->ipf_end = 0;
11755 	}
11756 	/* Walk through all the new pieces. */
11757 	do {
11758 		end = start + (mp->b_wptr - mp->b_rptr);
11759 		/*
11760 		 * If start is 0, decrease 'end' only for the first mblk of
11761 		 * the fragment. Otherwise 'end' can get wrong value in the
11762 		 * second pass of the loop if first mblk is exactly the
11763 		 * size of ipf_nf_hdr_len.
11764 		 */
11765 		if (start == 0 && !offset_zero_seen) {
11766 			/* First segment */
11767 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11768 			end -= ipf->ipf_nf_hdr_len;
11769 			offset_zero_seen = B_TRUE;
11770 		}
11771 		next_mp = mp->b_cont;
11772 		/*
11773 		 * We are checking to see if there is any interesing data
11774 		 * to process.  If there isn't and the mblk isn't the
11775 		 * one which carries the unfragmentable header then we
11776 		 * drop it.  It's possible to have just the unfragmentable
11777 		 * header come through without any data.  That needs to be
11778 		 * saved.
11779 		 *
11780 		 * If the assert at the top of this function holds then the
11781 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11782 		 * is infrequently traveled enough that the test is left in
11783 		 * to protect against future code changes which break that
11784 		 * invariant.
11785 		 */
11786 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11787 			/* Empty.  Blast it. */
11788 			IP_REASS_SET_START(mp, 0);
11789 			IP_REASS_SET_END(mp, 0);
11790 			/*
11791 			 * If the ipf points to the mblk we are about to free,
11792 			 * update ipf to point to the next mblk (or NULL
11793 			 * if none).
11794 			 */
11795 			if (ipf->ipf_mp->b_cont == mp)
11796 				ipf->ipf_mp->b_cont = next_mp;
11797 			freeb(mp);
11798 			continue;
11799 		}
11800 		mp->b_cont = NULL;
11801 		IP_REASS_SET_START(mp, start);
11802 		IP_REASS_SET_END(mp, end);
11803 		if (!ipf->ipf_tail_mp) {
11804 			ipf->ipf_tail_mp = mp;
11805 			ipf->ipf_mp->b_cont = mp;
11806 			if (start == 0 || !more) {
11807 				ipf->ipf_hole_cnt = 1;
11808 				/*
11809 				 * if the first fragment comes in more than one
11810 				 * mblk, this loop will be executed for each
11811 				 * mblk. Need to adjust hole count so exiting
11812 				 * this routine will leave hole count at 1.
11813 				 */
11814 				if (next_mp)
11815 					ipf->ipf_hole_cnt++;
11816 			} else
11817 				ipf->ipf_hole_cnt = 2;
11818 			continue;
11819 		} else if (ipf->ipf_last_frag_seen && !more &&
11820 		    !pkt_boundary_checked) {
11821 			/*
11822 			 * We check datagram boundary only if this fragment
11823 			 * claims to be the last fragment and we have seen a
11824 			 * last fragment in the past too. We do this only
11825 			 * once for a given fragment.
11826 			 *
11827 			 * start cannot be 0 here as fragments with start=0
11828 			 * and MF=0 gets handled as a complete packet. These
11829 			 * fragments should not reach here.
11830 			 */
11831 
11832 			if (start + msgdsize(mp) !=
11833 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11834 				/*
11835 				 * We have two fragments both of which claim
11836 				 * to be the last fragment but gives conflicting
11837 				 * information about the whole datagram size.
11838 				 * Something fishy is going on. Drop the
11839 				 * fragment and free up the reassembly list.
11840 				 */
11841 				return (IP_REASS_FAILED);
11842 			}
11843 
11844 			/*
11845 			 * We shouldn't come to this code block again for this
11846 			 * particular fragment.
11847 			 */
11848 			pkt_boundary_checked = B_TRUE;
11849 		}
11850 
11851 		/* New stuff at or beyond tail? */
11852 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11853 		if (start >= offset) {
11854 			if (ipf->ipf_last_frag_seen) {
11855 				/* current fragment is beyond last fragment */
11856 				return (IP_REASS_FAILED);
11857 			}
11858 			/* Link it on end. */
11859 			ipf->ipf_tail_mp->b_cont = mp;
11860 			ipf->ipf_tail_mp = mp;
11861 			if (more) {
11862 				if (start != offset)
11863 					ipf->ipf_hole_cnt++;
11864 			} else if (start == offset && next_mp == NULL)
11865 					ipf->ipf_hole_cnt--;
11866 			continue;
11867 		}
11868 		mp1 = ipf->ipf_mp->b_cont;
11869 		offset = IP_REASS_START(mp1);
11870 		/* New stuff at the front? */
11871 		if (start < offset) {
11872 			if (start == 0) {
11873 				if (end >= offset) {
11874 					/* Nailed the hole at the begining. */
11875 					ipf->ipf_hole_cnt--;
11876 				}
11877 			} else if (end < offset) {
11878 				/*
11879 				 * A hole, stuff, and a hole where there used
11880 				 * to be just a hole.
11881 				 */
11882 				ipf->ipf_hole_cnt++;
11883 			}
11884 			mp->b_cont = mp1;
11885 			/* Check for overlap. */
11886 			while (end > offset) {
11887 				if (end < IP_REASS_END(mp1)) {
11888 					mp->b_wptr -= end - offset;
11889 					IP_REASS_SET_END(mp, offset);
11890 					BUMP_MIB(ill->ill_ip_mib,
11891 					    ipIfStatsReasmPartDups);
11892 					break;
11893 				}
11894 				/* Did we cover another hole? */
11895 				if ((mp1->b_cont &&
11896 				    IP_REASS_END(mp1) !=
11897 				    IP_REASS_START(mp1->b_cont) &&
11898 				    end >= IP_REASS_START(mp1->b_cont)) ||
11899 				    (!ipf->ipf_last_frag_seen && !more)) {
11900 					ipf->ipf_hole_cnt--;
11901 				}
11902 				/* Clip out mp1. */
11903 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11904 					/*
11905 					 * After clipping out mp1, this guy
11906 					 * is now hanging off the end.
11907 					 */
11908 					ipf->ipf_tail_mp = mp;
11909 				}
11910 				IP_REASS_SET_START(mp1, 0);
11911 				IP_REASS_SET_END(mp1, 0);
11912 				/* Subtract byte count */
11913 				ipf->ipf_count -= mp1->b_datap->db_lim -
11914 				    mp1->b_datap->db_base;
11915 				freeb(mp1);
11916 				BUMP_MIB(ill->ill_ip_mib,
11917 				    ipIfStatsReasmPartDups);
11918 				mp1 = mp->b_cont;
11919 				if (!mp1)
11920 					break;
11921 				offset = IP_REASS_START(mp1);
11922 			}
11923 			ipf->ipf_mp->b_cont = mp;
11924 			continue;
11925 		}
11926 		/*
11927 		 * The new piece starts somewhere between the start of the head
11928 		 * and before the end of the tail.
11929 		 */
11930 		for (; mp1; mp1 = mp1->b_cont) {
11931 			offset = IP_REASS_END(mp1);
11932 			if (start < offset) {
11933 				if (end <= offset) {
11934 					/* Nothing new. */
11935 					IP_REASS_SET_START(mp, 0);
11936 					IP_REASS_SET_END(mp, 0);
11937 					/* Subtract byte count */
11938 					ipf->ipf_count -= mp->b_datap->db_lim -
11939 					    mp->b_datap->db_base;
11940 					if (incr_dups) {
11941 						ipf->ipf_num_dups++;
11942 						incr_dups = B_FALSE;
11943 					}
11944 					freeb(mp);
11945 					BUMP_MIB(ill->ill_ip_mib,
11946 					    ipIfStatsReasmDuplicates);
11947 					break;
11948 				}
11949 				/*
11950 				 * Trim redundant stuff off beginning of new
11951 				 * piece.
11952 				 */
11953 				IP_REASS_SET_START(mp, offset);
11954 				mp->b_rptr += offset - start;
11955 				BUMP_MIB(ill->ill_ip_mib,
11956 				    ipIfStatsReasmPartDups);
11957 				start = offset;
11958 				if (!mp1->b_cont) {
11959 					/*
11960 					 * After trimming, this guy is now
11961 					 * hanging off the end.
11962 					 */
11963 					mp1->b_cont = mp;
11964 					ipf->ipf_tail_mp = mp;
11965 					if (!more) {
11966 						ipf->ipf_hole_cnt--;
11967 					}
11968 					break;
11969 				}
11970 			}
11971 			if (start >= IP_REASS_START(mp1->b_cont))
11972 				continue;
11973 			/* Fill a hole */
11974 			if (start > offset)
11975 				ipf->ipf_hole_cnt++;
11976 			mp->b_cont = mp1->b_cont;
11977 			mp1->b_cont = mp;
11978 			mp1 = mp->b_cont;
11979 			offset = IP_REASS_START(mp1);
11980 			if (end >= offset) {
11981 				ipf->ipf_hole_cnt--;
11982 				/* Check for overlap. */
11983 				while (end > offset) {
11984 					if (end < IP_REASS_END(mp1)) {
11985 						mp->b_wptr -= end - offset;
11986 						IP_REASS_SET_END(mp, offset);
11987 						/*
11988 						 * TODO we might bump
11989 						 * this up twice if there is
11990 						 * overlap at both ends.
11991 						 */
11992 						BUMP_MIB(ill->ill_ip_mib,
11993 						    ipIfStatsReasmPartDups);
11994 						break;
11995 					}
11996 					/* Did we cover another hole? */
11997 					if ((mp1->b_cont &&
11998 					    IP_REASS_END(mp1)
11999 					    != IP_REASS_START(mp1->b_cont) &&
12000 					    end >=
12001 					    IP_REASS_START(mp1->b_cont)) ||
12002 					    (!ipf->ipf_last_frag_seen &&
12003 					    !more)) {
12004 						ipf->ipf_hole_cnt--;
12005 					}
12006 					/* Clip out mp1. */
12007 					if ((mp->b_cont = mp1->b_cont) ==
12008 					    NULL) {
12009 						/*
12010 						 * After clipping out mp1,
12011 						 * this guy is now hanging
12012 						 * off the end.
12013 						 */
12014 						ipf->ipf_tail_mp = mp;
12015 					}
12016 					IP_REASS_SET_START(mp1, 0);
12017 					IP_REASS_SET_END(mp1, 0);
12018 					/* Subtract byte count */
12019 					ipf->ipf_count -=
12020 					    mp1->b_datap->db_lim -
12021 					    mp1->b_datap->db_base;
12022 					freeb(mp1);
12023 					BUMP_MIB(ill->ill_ip_mib,
12024 					    ipIfStatsReasmPartDups);
12025 					mp1 = mp->b_cont;
12026 					if (!mp1)
12027 						break;
12028 					offset = IP_REASS_START(mp1);
12029 				}
12030 			}
12031 			break;
12032 		}
12033 	} while (start = end, mp = next_mp);
12034 
12035 	/* Fragment just processed could be the last one. Remember this fact */
12036 	if (!more)
12037 		ipf->ipf_last_frag_seen = B_TRUE;
12038 
12039 	/* Still got holes? */
12040 	if (ipf->ipf_hole_cnt)
12041 		return (IP_REASS_PARTIAL);
12042 	/* Clean up overloaded fields to avoid upstream disasters. */
12043 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12044 		IP_REASS_SET_START(mp1, 0);
12045 		IP_REASS_SET_END(mp1, 0);
12046 	}
12047 	return (IP_REASS_COMPLETE);
12048 }
12049 
12050 /*
12051  * ipsec processing for the fast path, used for input UDP Packets
12052  * Returns true if ready for passup to UDP.
12053  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12054  * was an ESP-in-UDP packet, etc.).
12055  */
12056 static boolean_t
12057 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12058     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12059 {
12060 	uint32_t	ill_index;
12061 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12062 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12063 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12064 	udp_t		*udp = connp->conn_udp;
12065 
12066 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12067 	/* The ill_index of the incoming ILL */
12068 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12069 
12070 	/* pass packet up to the transport */
12071 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12072 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12073 		    NULL, mctl_present);
12074 		if (*first_mpp == NULL) {
12075 			return (B_FALSE);
12076 		}
12077 	}
12078 
12079 	/* Initiate IPPF processing for fastpath UDP */
12080 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12081 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12082 		if (*mpp == NULL) {
12083 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12084 			    "deferred/dropped during IPPF processing\n"));
12085 			return (B_FALSE);
12086 		}
12087 	}
12088 	/*
12089 	 * Remove 0-spi if it's 0, or move everything behind
12090 	 * the UDP header over it and forward to ESP via
12091 	 * ip_proto_input().
12092 	 */
12093 	if (udp->udp_nat_t_endpoint) {
12094 		if (mctl_present) {
12095 			/* mctl_present *shouldn't* happen. */
12096 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12097 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12098 			    &ipss->ipsec_dropper);
12099 			*first_mpp = NULL;
12100 			return (B_FALSE);
12101 		}
12102 
12103 		/* "ill" is "recv_ill" in actuality. */
12104 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12105 			return (B_FALSE);
12106 
12107 		/* Else continue like a normal UDP packet. */
12108 	}
12109 
12110 	/*
12111 	 * We make the checks as below since we are in the fast path
12112 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12113 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12114 	 */
12115 	if (connp->conn_recvif || connp->conn_recvslla ||
12116 	    connp->conn_ip_recvpktinfo) {
12117 		if (connp->conn_recvif) {
12118 			in_flags = IPF_RECVIF;
12119 		}
12120 		/*
12121 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12122 		 * so the flag passed to ip_add_info is based on IP version
12123 		 * of connp.
12124 		 */
12125 		if (connp->conn_ip_recvpktinfo) {
12126 			if (connp->conn_af_isv6) {
12127 				/*
12128 				 * V6 only needs index
12129 				 */
12130 				in_flags |= IPF_RECVIF;
12131 			} else {
12132 				/*
12133 				 * V4 needs index + matching address.
12134 				 */
12135 				in_flags |= IPF_RECVADDR;
12136 			}
12137 		}
12138 		if (connp->conn_recvslla) {
12139 			in_flags |= IPF_RECVSLLA;
12140 		}
12141 		/*
12142 		 * since in_flags are being set ill will be
12143 		 * referenced in ip_add_info, so it better not
12144 		 * be NULL.
12145 		 */
12146 		/*
12147 		 * the actual data will be contained in b_cont
12148 		 * upon successful return of the following call.
12149 		 * If the call fails then the original mblk is
12150 		 * returned.
12151 		 */
12152 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12153 		    ipst);
12154 	}
12155 
12156 	return (B_TRUE);
12157 }
12158 
12159 /*
12160  * Fragmentation reassembly.  Each ILL has a hash table for
12161  * queuing packets undergoing reassembly for all IPIFs
12162  * associated with the ILL.  The hash is based on the packet
12163  * IP ident field.  The ILL frag hash table was allocated
12164  * as a timer block at the time the ILL was created.  Whenever
12165  * there is anything on the reassembly queue, the timer will
12166  * be running.  Returns B_TRUE if successful else B_FALSE;
12167  * frees mp on failure.
12168  */
12169 static boolean_t
12170 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12171     uint32_t *cksum_val, uint16_t *cksum_flags)
12172 {
12173 	uint32_t	frag_offset_flags;
12174 	ill_t		*ill = (ill_t *)q->q_ptr;
12175 	mblk_t		*mp = *mpp;
12176 	mblk_t		*t_mp;
12177 	ipaddr_t	dst;
12178 	uint8_t		proto = ipha->ipha_protocol;
12179 	uint32_t	sum_val;
12180 	uint16_t	sum_flags;
12181 	ipf_t		*ipf;
12182 	ipf_t		**ipfp;
12183 	ipfb_t		*ipfb;
12184 	uint16_t	ident;
12185 	uint32_t	offset;
12186 	ipaddr_t	src;
12187 	uint_t		hdr_length;
12188 	uint32_t	end;
12189 	mblk_t		*mp1;
12190 	mblk_t		*tail_mp;
12191 	size_t		count;
12192 	size_t		msg_len;
12193 	uint8_t		ecn_info = 0;
12194 	uint32_t	packet_size;
12195 	boolean_t	pruned = B_FALSE;
12196 	ip_stack_t *ipst = ill->ill_ipst;
12197 
12198 	if (cksum_val != NULL)
12199 		*cksum_val = 0;
12200 	if (cksum_flags != NULL)
12201 		*cksum_flags = 0;
12202 
12203 	/*
12204 	 * Drop the fragmented as early as possible, if
12205 	 * we don't have resource(s) to re-assemble.
12206 	 */
12207 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12208 		freemsg(mp);
12209 		return (B_FALSE);
12210 	}
12211 
12212 	/* Check for fragmentation offset; return if there's none */
12213 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12214 	    (IPH_MF | IPH_OFFSET)) == 0)
12215 		return (B_TRUE);
12216 
12217 	/*
12218 	 * We utilize hardware computed checksum info only for UDP since
12219 	 * IP fragmentation is a normal occurence for the protocol.  In
12220 	 * addition, checksum offload support for IP fragments carrying
12221 	 * UDP payload is commonly implemented across network adapters.
12222 	 */
12223 	ASSERT(ill != NULL);
12224 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12225 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12226 		mblk_t *mp1 = mp->b_cont;
12227 		int32_t len;
12228 
12229 		/* Record checksum information from the packet */
12230 		sum_val = (uint32_t)DB_CKSUM16(mp);
12231 		sum_flags = DB_CKSUMFLAGS(mp);
12232 
12233 		/* IP payload offset from beginning of mblk */
12234 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12235 
12236 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12237 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12238 		    offset >= DB_CKSUMSTART(mp) &&
12239 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12240 			uint32_t adj;
12241 			/*
12242 			 * Partial checksum has been calculated by hardware
12243 			 * and attached to the packet; in addition, any
12244 			 * prepended extraneous data is even byte aligned.
12245 			 * If any such data exists, we adjust the checksum;
12246 			 * this would also handle any postpended data.
12247 			 */
12248 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12249 			    mp, mp1, len, adj);
12250 
12251 			/* One's complement subtract extraneous checksum */
12252 			if (adj >= sum_val)
12253 				sum_val = ~(adj - sum_val) & 0xFFFF;
12254 			else
12255 				sum_val -= adj;
12256 		}
12257 	} else {
12258 		sum_val = 0;
12259 		sum_flags = 0;
12260 	}
12261 
12262 	/* Clear hardware checksumming flag */
12263 	DB_CKSUMFLAGS(mp) = 0;
12264 
12265 	ident = ipha->ipha_ident;
12266 	offset = (frag_offset_flags << 3) & 0xFFFF;
12267 	src = ipha->ipha_src;
12268 	dst = ipha->ipha_dst;
12269 	hdr_length = IPH_HDR_LENGTH(ipha);
12270 	end = ntohs(ipha->ipha_length) - hdr_length;
12271 
12272 	/* If end == 0 then we have a packet with no data, so just free it */
12273 	if (end == 0) {
12274 		freemsg(mp);
12275 		return (B_FALSE);
12276 	}
12277 
12278 	/* Record the ECN field info. */
12279 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12280 	if (offset != 0) {
12281 		/*
12282 		 * If this isn't the first piece, strip the header, and
12283 		 * add the offset to the end value.
12284 		 */
12285 		mp->b_rptr += hdr_length;
12286 		end += offset;
12287 	}
12288 
12289 	msg_len = MBLKSIZE(mp);
12290 	tail_mp = mp;
12291 	while (tail_mp->b_cont != NULL) {
12292 		tail_mp = tail_mp->b_cont;
12293 		msg_len += MBLKSIZE(tail_mp);
12294 	}
12295 
12296 	/* If the reassembly list for this ILL will get too big, prune it */
12297 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12298 	    ipst->ips_ip_reass_queue_bytes) {
12299 		ill_frag_prune(ill,
12300 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12301 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12302 		pruned = B_TRUE;
12303 	}
12304 
12305 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12306 	mutex_enter(&ipfb->ipfb_lock);
12307 
12308 	ipfp = &ipfb->ipfb_ipf;
12309 	/* Try to find an existing fragment queue for this packet. */
12310 	for (;;) {
12311 		ipf = ipfp[0];
12312 		if (ipf != NULL) {
12313 			/*
12314 			 * It has to match on ident and src/dst address.
12315 			 */
12316 			if (ipf->ipf_ident == ident &&
12317 			    ipf->ipf_src == src &&
12318 			    ipf->ipf_dst == dst &&
12319 			    ipf->ipf_protocol == proto) {
12320 				/*
12321 				 * If we have received too many
12322 				 * duplicate fragments for this packet
12323 				 * free it.
12324 				 */
12325 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12326 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12327 					freemsg(mp);
12328 					mutex_exit(&ipfb->ipfb_lock);
12329 					return (B_FALSE);
12330 				}
12331 				/* Found it. */
12332 				break;
12333 			}
12334 			ipfp = &ipf->ipf_hash_next;
12335 			continue;
12336 		}
12337 
12338 		/*
12339 		 * If we pruned the list, do we want to store this new
12340 		 * fragment?. We apply an optimization here based on the
12341 		 * fact that most fragments will be received in order.
12342 		 * So if the offset of this incoming fragment is zero,
12343 		 * it is the first fragment of a new packet. We will
12344 		 * keep it.  Otherwise drop the fragment, as we have
12345 		 * probably pruned the packet already (since the
12346 		 * packet cannot be found).
12347 		 */
12348 		if (pruned && offset != 0) {
12349 			mutex_exit(&ipfb->ipfb_lock);
12350 			freemsg(mp);
12351 			return (B_FALSE);
12352 		}
12353 
12354 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12355 			/*
12356 			 * Too many fragmented packets in this hash
12357 			 * bucket. Free the oldest.
12358 			 */
12359 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12360 		}
12361 
12362 		/* New guy.  Allocate a frag message. */
12363 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12364 		if (mp1 == NULL) {
12365 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12366 			freemsg(mp);
12367 reass_done:
12368 			mutex_exit(&ipfb->ipfb_lock);
12369 			return (B_FALSE);
12370 		}
12371 
12372 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12373 		mp1->b_cont = mp;
12374 
12375 		/* Initialize the fragment header. */
12376 		ipf = (ipf_t *)mp1->b_rptr;
12377 		ipf->ipf_mp = mp1;
12378 		ipf->ipf_ptphn = ipfp;
12379 		ipfp[0] = ipf;
12380 		ipf->ipf_hash_next = NULL;
12381 		ipf->ipf_ident = ident;
12382 		ipf->ipf_protocol = proto;
12383 		ipf->ipf_src = src;
12384 		ipf->ipf_dst = dst;
12385 		ipf->ipf_nf_hdr_len = 0;
12386 		/* Record reassembly start time. */
12387 		ipf->ipf_timestamp = gethrestime_sec();
12388 		/* Record ipf generation and account for frag header */
12389 		ipf->ipf_gen = ill->ill_ipf_gen++;
12390 		ipf->ipf_count = MBLKSIZE(mp1);
12391 		ipf->ipf_last_frag_seen = B_FALSE;
12392 		ipf->ipf_ecn = ecn_info;
12393 		ipf->ipf_num_dups = 0;
12394 		ipfb->ipfb_frag_pkts++;
12395 		ipf->ipf_checksum = 0;
12396 		ipf->ipf_checksum_flags = 0;
12397 
12398 		/* Store checksum value in fragment header */
12399 		if (sum_flags != 0) {
12400 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12401 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12402 			ipf->ipf_checksum = sum_val;
12403 			ipf->ipf_checksum_flags = sum_flags;
12404 		}
12405 
12406 		/*
12407 		 * We handle reassembly two ways.  In the easy case,
12408 		 * where all the fragments show up in order, we do
12409 		 * minimal bookkeeping, and just clip new pieces on
12410 		 * the end.  If we ever see a hole, then we go off
12411 		 * to ip_reassemble which has to mark the pieces and
12412 		 * keep track of the number of holes, etc.  Obviously,
12413 		 * the point of having both mechanisms is so we can
12414 		 * handle the easy case as efficiently as possible.
12415 		 */
12416 		if (offset == 0) {
12417 			/* Easy case, in-order reassembly so far. */
12418 			ipf->ipf_count += msg_len;
12419 			ipf->ipf_tail_mp = tail_mp;
12420 			/*
12421 			 * Keep track of next expected offset in
12422 			 * ipf_end.
12423 			 */
12424 			ipf->ipf_end = end;
12425 			ipf->ipf_nf_hdr_len = hdr_length;
12426 		} else {
12427 			/* Hard case, hole at the beginning. */
12428 			ipf->ipf_tail_mp = NULL;
12429 			/*
12430 			 * ipf_end == 0 means that we have given up
12431 			 * on easy reassembly.
12432 			 */
12433 			ipf->ipf_end = 0;
12434 
12435 			/* Forget checksum offload from now on */
12436 			ipf->ipf_checksum_flags = 0;
12437 
12438 			/*
12439 			 * ipf_hole_cnt is set by ip_reassemble.
12440 			 * ipf_count is updated by ip_reassemble.
12441 			 * No need to check for return value here
12442 			 * as we don't expect reassembly to complete
12443 			 * or fail for the first fragment itself.
12444 			 */
12445 			(void) ip_reassemble(mp, ipf,
12446 			    (frag_offset_flags & IPH_OFFSET) << 3,
12447 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12448 		}
12449 		/* Update per ipfb and ill byte counts */
12450 		ipfb->ipfb_count += ipf->ipf_count;
12451 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12452 		ill->ill_frag_count += ipf->ipf_count;
12453 		/* If the frag timer wasn't already going, start it. */
12454 		mutex_enter(&ill->ill_lock);
12455 		ill_frag_timer_start(ill);
12456 		mutex_exit(&ill->ill_lock);
12457 		goto reass_done;
12458 	}
12459 
12460 	/*
12461 	 * If the packet's flag has changed (it could be coming up
12462 	 * from an interface different than the previous, therefore
12463 	 * possibly different checksum capability), then forget about
12464 	 * any stored checksum states.  Otherwise add the value to
12465 	 * the existing one stored in the fragment header.
12466 	 */
12467 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12468 		sum_val += ipf->ipf_checksum;
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 	} else if (ipf->ipf_checksum_flags != 0) {
12473 		/* Forget checksum offload from now on */
12474 		ipf->ipf_checksum_flags = 0;
12475 	}
12476 
12477 	/*
12478 	 * We have a new piece of a datagram which is already being
12479 	 * reassembled.  Update the ECN info if all IP fragments
12480 	 * are ECN capable.  If there is one which is not, clear
12481 	 * all the info.  If there is at least one which has CE
12482 	 * code point, IP needs to report that up to transport.
12483 	 */
12484 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12485 		if (ecn_info == IPH_ECN_CE)
12486 			ipf->ipf_ecn = IPH_ECN_CE;
12487 	} else {
12488 		ipf->ipf_ecn = IPH_ECN_NECT;
12489 	}
12490 	if (offset && ipf->ipf_end == offset) {
12491 		/* The new fragment fits at the end */
12492 		ipf->ipf_tail_mp->b_cont = mp;
12493 		/* Update the byte count */
12494 		ipf->ipf_count += msg_len;
12495 		/* Update per ipfb and ill byte counts */
12496 		ipfb->ipfb_count += msg_len;
12497 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12498 		ill->ill_frag_count += msg_len;
12499 		if (frag_offset_flags & IPH_MF) {
12500 			/* More to come. */
12501 			ipf->ipf_end = end;
12502 			ipf->ipf_tail_mp = tail_mp;
12503 			goto reass_done;
12504 		}
12505 	} else {
12506 		/* Go do the hard cases. */
12507 		int ret;
12508 
12509 		if (offset == 0)
12510 			ipf->ipf_nf_hdr_len = hdr_length;
12511 
12512 		/* Save current byte count */
12513 		count = ipf->ipf_count;
12514 		ret = ip_reassemble(mp, ipf,
12515 		    (frag_offset_flags & IPH_OFFSET) << 3,
12516 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12517 		/* Count of bytes added and subtracted (freeb()ed) */
12518 		count = ipf->ipf_count - count;
12519 		if (count) {
12520 			/* Update per ipfb and ill byte counts */
12521 			ipfb->ipfb_count += count;
12522 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12523 			ill->ill_frag_count += count;
12524 		}
12525 		if (ret == IP_REASS_PARTIAL) {
12526 			goto reass_done;
12527 		} else if (ret == IP_REASS_FAILED) {
12528 			/* Reassembly failed. Free up all resources */
12529 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12530 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12531 				IP_REASS_SET_START(t_mp, 0);
12532 				IP_REASS_SET_END(t_mp, 0);
12533 			}
12534 			freemsg(mp);
12535 			goto reass_done;
12536 		}
12537 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12538 	}
12539 	/*
12540 	 * We have completed reassembly.  Unhook the frag header from
12541 	 * the reassembly list.
12542 	 *
12543 	 * Before we free the frag header, record the ECN info
12544 	 * to report back to the transport.
12545 	 */
12546 	ecn_info = ipf->ipf_ecn;
12547 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12548 	ipfp = ipf->ipf_ptphn;
12549 
12550 	/* We need to supply these to caller */
12551 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12552 		sum_val = ipf->ipf_checksum;
12553 	else
12554 		sum_val = 0;
12555 
12556 	mp1 = ipf->ipf_mp;
12557 	count = ipf->ipf_count;
12558 	ipf = ipf->ipf_hash_next;
12559 	if (ipf != NULL)
12560 		ipf->ipf_ptphn = ipfp;
12561 	ipfp[0] = ipf;
12562 	ill->ill_frag_count -= count;
12563 	ASSERT(ipfb->ipfb_count >= count);
12564 	ipfb->ipfb_count -= count;
12565 	ipfb->ipfb_frag_pkts--;
12566 	mutex_exit(&ipfb->ipfb_lock);
12567 	/* Ditch the frag header. */
12568 	mp = mp1->b_cont;
12569 
12570 	freeb(mp1);
12571 
12572 	/* Restore original IP length in header. */
12573 	packet_size = (uint32_t)msgdsize(mp);
12574 	if (packet_size > IP_MAXPACKET) {
12575 		freemsg(mp);
12576 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12577 		return (B_FALSE);
12578 	}
12579 
12580 	if (DB_REF(mp) > 1) {
12581 		mblk_t *mp2 = copymsg(mp);
12582 
12583 		freemsg(mp);
12584 		if (mp2 == NULL) {
12585 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12586 			return (B_FALSE);
12587 		}
12588 		mp = mp2;
12589 	}
12590 	ipha = (ipha_t *)mp->b_rptr;
12591 
12592 	ipha->ipha_length = htons((uint16_t)packet_size);
12593 	/* We're now complete, zip the frag state */
12594 	ipha->ipha_fragment_offset_and_flags = 0;
12595 	/* Record the ECN info. */
12596 	ipha->ipha_type_of_service &= 0xFC;
12597 	ipha->ipha_type_of_service |= ecn_info;
12598 	*mpp = mp;
12599 
12600 	/* Reassembly is successful; return checksum information if needed */
12601 	if (cksum_val != NULL)
12602 		*cksum_val = sum_val;
12603 	if (cksum_flags != NULL)
12604 		*cksum_flags = sum_flags;
12605 
12606 	return (B_TRUE);
12607 }
12608 
12609 /*
12610  * Perform ip header check sum update local options.
12611  * return B_TRUE if all is well, else return B_FALSE and release
12612  * the mp. caller is responsible for decrementing ire ref cnt.
12613  */
12614 static boolean_t
12615 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12616     ip_stack_t *ipst)
12617 {
12618 	mblk_t		*first_mp;
12619 	boolean_t	mctl_present;
12620 	uint16_t	sum;
12621 
12622 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12623 	/*
12624 	 * Don't do the checksum if it has gone through AH/ESP
12625 	 * processing.
12626 	 */
12627 	if (!mctl_present) {
12628 		sum = ip_csum_hdr(ipha);
12629 		if (sum != 0) {
12630 			if (ill != NULL) {
12631 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12632 			} else {
12633 				BUMP_MIB(&ipst->ips_ip_mib,
12634 				    ipIfStatsInCksumErrs);
12635 			}
12636 			freemsg(first_mp);
12637 			return (B_FALSE);
12638 		}
12639 	}
12640 
12641 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12642 		if (mctl_present)
12643 			freeb(first_mp);
12644 		return (B_FALSE);
12645 	}
12646 
12647 	return (B_TRUE);
12648 }
12649 
12650 /*
12651  * All udp packet are delivered to the local host via this routine.
12652  */
12653 void
12654 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12655     ill_t *recv_ill)
12656 {
12657 	uint32_t	sum;
12658 	uint32_t	u1;
12659 	boolean_t	mctl_present;
12660 	conn_t		*connp;
12661 	mblk_t		*first_mp;
12662 	uint16_t	*up;
12663 	ill_t		*ill = (ill_t *)q->q_ptr;
12664 	uint16_t	reass_hck_flags = 0;
12665 	ip_stack_t	*ipst;
12666 
12667 	ASSERT(recv_ill != NULL);
12668 	ipst = recv_ill->ill_ipst;
12669 
12670 #define	rptr    ((uchar_t *)ipha)
12671 
12672 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12673 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12674 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12675 	ASSERT(ill != NULL);
12676 
12677 	/*
12678 	 * FAST PATH for udp packets
12679 	 */
12680 
12681 	/* u1 is # words of IP options */
12682 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12683 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12684 
12685 	/* IP options present */
12686 	if (u1 != 0)
12687 		goto ipoptions;
12688 
12689 	/* Check the IP header checksum.  */
12690 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12691 		/* Clear the IP header h/w cksum flag */
12692 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12693 	} else if (!mctl_present) {
12694 		/*
12695 		 * Don't verify header checksum if this packet is coming
12696 		 * back from AH/ESP as we already did it.
12697 		 */
12698 #define	uph	((uint16_t *)ipha)
12699 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12700 		    uph[6] + uph[7] + uph[8] + uph[9];
12701 #undef	uph
12702 		/* finish doing IP checksum */
12703 		sum = (sum & 0xFFFF) + (sum >> 16);
12704 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12705 		if (sum != 0 && sum != 0xFFFF) {
12706 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12707 			freemsg(first_mp);
12708 			return;
12709 		}
12710 	}
12711 
12712 	/*
12713 	 * Count for SNMP of inbound packets for ire.
12714 	 * if mctl is present this might be a secure packet and
12715 	 * has already been counted for in ip_proto_input().
12716 	 */
12717 	if (!mctl_present) {
12718 		UPDATE_IB_PKT_COUNT(ire);
12719 		ire->ire_last_used_time = lbolt;
12720 	}
12721 
12722 	/* packet part of fragmented IP packet? */
12723 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12724 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12725 		goto fragmented;
12726 	}
12727 
12728 	/* u1 = IP header length (20 bytes) */
12729 	u1 = IP_SIMPLE_HDR_LENGTH;
12730 
12731 	/* packet does not contain complete IP & UDP headers */
12732 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12733 		goto udppullup;
12734 
12735 	/* up points to UDP header */
12736 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12737 #define	iphs    ((uint16_t *)ipha)
12738 
12739 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12740 	if (up[3] != 0) {
12741 		mblk_t *mp1 = mp->b_cont;
12742 		boolean_t cksum_err;
12743 		uint16_t hck_flags = 0;
12744 
12745 		/* Pseudo-header checksum */
12746 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12747 		    iphs[9] + up[2];
12748 
12749 		/*
12750 		 * Revert to software checksum calculation if the interface
12751 		 * isn't capable of checksum offload or if IPsec is present.
12752 		 */
12753 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12754 			hck_flags = DB_CKSUMFLAGS(mp);
12755 
12756 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12757 			IP_STAT(ipst, ip_in_sw_cksum);
12758 
12759 		IP_CKSUM_RECV(hck_flags, u1,
12760 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12761 		    (int32_t)((uchar_t *)up - rptr),
12762 		    mp, mp1, cksum_err);
12763 
12764 		if (cksum_err) {
12765 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12766 			if (hck_flags & HCK_FULLCKSUM)
12767 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12768 			else if (hck_flags & HCK_PARTIALCKSUM)
12769 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12770 			else
12771 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12772 
12773 			freemsg(first_mp);
12774 			return;
12775 		}
12776 	}
12777 
12778 	/* Non-fragmented broadcast or multicast packet? */
12779 	if (ire->ire_type == IRE_BROADCAST)
12780 		goto udpslowpath;
12781 
12782 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12783 	    ire->ire_zoneid, ipst)) != NULL) {
12784 		ASSERT(connp->conn_upq != NULL);
12785 		IP_STAT(ipst, ip_udp_fast_path);
12786 
12787 		if (CONN_UDP_FLOWCTLD(connp)) {
12788 			freemsg(mp);
12789 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12790 		} else {
12791 			if (!mctl_present) {
12792 				BUMP_MIB(ill->ill_ip_mib,
12793 				    ipIfStatsHCInDelivers);
12794 			}
12795 			/*
12796 			 * mp and first_mp can change.
12797 			 */
12798 			if (ip_udp_check(q, connp, recv_ill,
12799 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12800 				/* Send it upstream */
12801 				(connp->conn_recv)(connp, mp, NULL);
12802 			}
12803 		}
12804 		/*
12805 		 * freeb() cannot deal with null mblk being passed
12806 		 * in and first_mp can be set to null in the call
12807 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12808 		 */
12809 		if (mctl_present && first_mp != NULL) {
12810 			freeb(first_mp);
12811 		}
12812 		CONN_DEC_REF(connp);
12813 		return;
12814 	}
12815 
12816 	/*
12817 	 * if we got here we know the packet is not fragmented and
12818 	 * has no options. The classifier could not find a conn_t and
12819 	 * most likely its an icmp packet so send it through slow path.
12820 	 */
12821 
12822 	goto udpslowpath;
12823 
12824 ipoptions:
12825 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12826 		goto slow_done;
12827 	}
12828 
12829 	UPDATE_IB_PKT_COUNT(ire);
12830 	ire->ire_last_used_time = lbolt;
12831 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12832 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12833 fragmented:
12834 		/*
12835 		 * "sum" and "reass_hck_flags" are non-zero if the
12836 		 * reassembled packet has a valid hardware computed
12837 		 * checksum information associated with it.
12838 		 */
12839 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12840 			goto slow_done;
12841 		/*
12842 		 * Make sure that first_mp points back to mp as
12843 		 * the mp we came in with could have changed in
12844 		 * ip_rput_fragment().
12845 		 */
12846 		ASSERT(!mctl_present);
12847 		ipha = (ipha_t *)mp->b_rptr;
12848 		first_mp = mp;
12849 	}
12850 
12851 	/* Now we have a complete datagram, destined for this machine. */
12852 	u1 = IPH_HDR_LENGTH(ipha);
12853 	/* Pull up the UDP header, if necessary. */
12854 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12855 udppullup:
12856 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12857 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12858 			freemsg(first_mp);
12859 			goto slow_done;
12860 		}
12861 		ipha = (ipha_t *)mp->b_rptr;
12862 	}
12863 
12864 	/*
12865 	 * Validate the checksum for the reassembled packet; for the
12866 	 * pullup case we calculate the payload checksum in software.
12867 	 */
12868 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12869 	if (up[3] != 0) {
12870 		boolean_t cksum_err;
12871 
12872 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12873 			IP_STAT(ipst, ip_in_sw_cksum);
12874 
12875 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12876 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12877 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12878 		    iphs[9] + up[2], sum, cksum_err);
12879 
12880 		if (cksum_err) {
12881 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12882 
12883 			if (reass_hck_flags & HCK_FULLCKSUM)
12884 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12885 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12886 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12887 			else
12888 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12889 
12890 			freemsg(first_mp);
12891 			goto slow_done;
12892 		}
12893 	}
12894 udpslowpath:
12895 
12896 	/* Clear hardware checksum flag to be safe */
12897 	DB_CKSUMFLAGS(mp) = 0;
12898 
12899 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12900 	    (ire->ire_type == IRE_BROADCAST),
12901 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12902 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12903 
12904 slow_done:
12905 	IP_STAT(ipst, ip_udp_slow_path);
12906 	return;
12907 
12908 #undef  iphs
12909 #undef  rptr
12910 }
12911 
12912 /* ARGSUSED */
12913 static mblk_t *
12914 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12915     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12916     ill_rx_ring_t *ill_ring)
12917 {
12918 	conn_t		*connp;
12919 	uint32_t	sum;
12920 	uint32_t	u1;
12921 	uint16_t	*up;
12922 	int		offset;
12923 	ssize_t		len;
12924 	mblk_t		*mp1;
12925 	boolean_t	syn_present = B_FALSE;
12926 	tcph_t		*tcph;
12927 	uint_t		ip_hdr_len;
12928 	ill_t		*ill = (ill_t *)q->q_ptr;
12929 	zoneid_t	zoneid = ire->ire_zoneid;
12930 	boolean_t	cksum_err;
12931 	uint16_t	hck_flags = 0;
12932 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12933 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12934 
12935 #define	rptr	((uchar_t *)ipha)
12936 
12937 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12938 	ASSERT(ill != NULL);
12939 
12940 	/*
12941 	 * FAST PATH for tcp packets
12942 	 */
12943 
12944 	/* u1 is # words of IP options */
12945 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12946 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12947 
12948 	/* IP options present */
12949 	if (u1) {
12950 		goto ipoptions;
12951 	} else if (!mctl_present) {
12952 		/* Check the IP header checksum.  */
12953 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12954 			/* Clear the IP header h/w cksum flag */
12955 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12956 		} else if (!mctl_present) {
12957 			/*
12958 			 * Don't verify header checksum if this packet
12959 			 * is coming back from AH/ESP as we already did it.
12960 			 */
12961 #define	uph	((uint16_t *)ipha)
12962 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12963 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12964 #undef	uph
12965 			/* finish doing IP checksum */
12966 			sum = (sum & 0xFFFF) + (sum >> 16);
12967 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12968 			if (sum != 0 && sum != 0xFFFF) {
12969 				BUMP_MIB(ill->ill_ip_mib,
12970 				    ipIfStatsInCksumErrs);
12971 				goto error;
12972 			}
12973 		}
12974 	}
12975 
12976 	if (!mctl_present) {
12977 		UPDATE_IB_PKT_COUNT(ire);
12978 		ire->ire_last_used_time = lbolt;
12979 	}
12980 
12981 	/* packet part of fragmented IP packet? */
12982 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12983 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12984 		goto fragmented;
12985 	}
12986 
12987 	/* u1 = IP header length (20 bytes) */
12988 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12989 
12990 	/* does packet contain IP+TCP headers? */
12991 	len = mp->b_wptr - rptr;
12992 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12993 		IP_STAT(ipst, ip_tcppullup);
12994 		goto tcppullup;
12995 	}
12996 
12997 	/* TCP options present? */
12998 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12999 
13000 	/*
13001 	 * If options need to be pulled up, then goto tcpoptions.
13002 	 * otherwise we are still in the fast path
13003 	 */
13004 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13005 		IP_STAT(ipst, ip_tcpoptions);
13006 		goto tcpoptions;
13007 	}
13008 
13009 	/* multiple mblks of tcp data? */
13010 	if ((mp1 = mp->b_cont) != NULL) {
13011 		/* more then two? */
13012 		if (mp1->b_cont != NULL) {
13013 			IP_STAT(ipst, ip_multipkttcp);
13014 			goto multipkttcp;
13015 		}
13016 		len += mp1->b_wptr - mp1->b_rptr;
13017 	}
13018 
13019 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13020 
13021 	/* part of pseudo checksum */
13022 
13023 	/* TCP datagram length */
13024 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13025 
13026 #define	iphs    ((uint16_t *)ipha)
13027 
13028 #ifdef	_BIG_ENDIAN
13029 	u1 += IPPROTO_TCP;
13030 #else
13031 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13032 #endif
13033 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13034 
13035 	/*
13036 	 * Revert to software checksum calculation if the interface
13037 	 * isn't capable of checksum offload or if IPsec is present.
13038 	 */
13039 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13040 		hck_flags = DB_CKSUMFLAGS(mp);
13041 
13042 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13043 		IP_STAT(ipst, ip_in_sw_cksum);
13044 
13045 	IP_CKSUM_RECV(hck_flags, u1,
13046 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13047 	    (int32_t)((uchar_t *)up - rptr),
13048 	    mp, mp1, cksum_err);
13049 
13050 	if (cksum_err) {
13051 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13052 
13053 		if (hck_flags & HCK_FULLCKSUM)
13054 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13055 		else if (hck_flags & HCK_PARTIALCKSUM)
13056 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13057 		else
13058 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13059 
13060 		goto error;
13061 	}
13062 
13063 try_again:
13064 
13065 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13066 	    zoneid, ipst)) == NULL) {
13067 		/* Send the TH_RST */
13068 		goto no_conn;
13069 	}
13070 
13071 	/*
13072 	 * TCP FAST PATH for AF_INET socket.
13073 	 *
13074 	 * TCP fast path to avoid extra work. An AF_INET socket type
13075 	 * does not have facility to receive extra information via
13076 	 * ip_process or ip_add_info. Also, when the connection was
13077 	 * established, we made a check if this connection is impacted
13078 	 * by any global IPsec policy or per connection policy (a
13079 	 * policy that comes in effect later will not apply to this
13080 	 * connection). Since all this can be determined at the
13081 	 * connection establishment time, a quick check of flags
13082 	 * can avoid extra work.
13083 	 */
13084 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13085 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13086 		ASSERT(first_mp == mp);
13087 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13088 		SET_SQUEUE(mp, tcp_rput_data, connp);
13089 		return (mp);
13090 	}
13091 
13092 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13093 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13094 		if (IPCL_IS_TCP(connp)) {
13095 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13096 			DB_CKSUMSTART(mp) =
13097 			    (intptr_t)ip_squeue_get(ill_ring);
13098 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13099 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13100 				BUMP_MIB(ill->ill_ip_mib,
13101 				    ipIfStatsHCInDelivers);
13102 				SET_SQUEUE(mp, connp->conn_recv, connp);
13103 				return (mp);
13104 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13105 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13106 				BUMP_MIB(ill->ill_ip_mib,
13107 				    ipIfStatsHCInDelivers);
13108 				ip_squeue_enter_unbound++;
13109 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13110 				    connp);
13111 				return (mp);
13112 			}
13113 			syn_present = B_TRUE;
13114 		}
13115 
13116 	}
13117 
13118 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13119 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13120 
13121 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13122 		/* No need to send this packet to TCP */
13123 		if ((flags & TH_RST) || (flags & TH_URG)) {
13124 			CONN_DEC_REF(connp);
13125 			freemsg(first_mp);
13126 			return (NULL);
13127 		}
13128 		if (flags & TH_ACK) {
13129 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13130 			    ipst->ips_netstack->netstack_tcp, connp);
13131 			CONN_DEC_REF(connp);
13132 			return (NULL);
13133 		}
13134 
13135 		CONN_DEC_REF(connp);
13136 		freemsg(first_mp);
13137 		return (NULL);
13138 	}
13139 
13140 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13141 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13142 		    ipha, NULL, mctl_present);
13143 		if (first_mp == NULL) {
13144 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13145 			CONN_DEC_REF(connp);
13146 			return (NULL);
13147 		}
13148 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13149 			ASSERT(syn_present);
13150 			if (mctl_present) {
13151 				ASSERT(first_mp != mp);
13152 				first_mp->b_datap->db_struioflag |=
13153 				    STRUIO_POLICY;
13154 			} else {
13155 				ASSERT(first_mp == mp);
13156 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13157 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13158 			}
13159 		} else {
13160 			/*
13161 			 * Discard first_mp early since we're dealing with a
13162 			 * fully-connected conn_t and tcp doesn't do policy in
13163 			 * this case.
13164 			 */
13165 			if (mctl_present) {
13166 				freeb(first_mp);
13167 				mctl_present = B_FALSE;
13168 			}
13169 			first_mp = mp;
13170 		}
13171 	}
13172 
13173 	/* Initiate IPPF processing for fastpath */
13174 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13175 		uint32_t	ill_index;
13176 
13177 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13178 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13179 		if (mp == NULL) {
13180 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13181 			    "deferred/dropped during IPPF processing\n"));
13182 			CONN_DEC_REF(connp);
13183 			if (mctl_present)
13184 				freeb(first_mp);
13185 			return (NULL);
13186 		} else if (mctl_present) {
13187 			/*
13188 			 * ip_process might return a new mp.
13189 			 */
13190 			ASSERT(first_mp != mp);
13191 			first_mp->b_cont = mp;
13192 		} else {
13193 			first_mp = mp;
13194 		}
13195 
13196 	}
13197 
13198 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13199 		/*
13200 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13201 		 * make sure IPF_RECVIF is passed to ip_add_info.
13202 		 */
13203 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13204 		    IPCL_ZONEID(connp), ipst);
13205 		if (mp == NULL) {
13206 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13207 			CONN_DEC_REF(connp);
13208 			if (mctl_present)
13209 				freeb(first_mp);
13210 			return (NULL);
13211 		} else if (mctl_present) {
13212 			/*
13213 			 * ip_add_info might return a new mp.
13214 			 */
13215 			ASSERT(first_mp != mp);
13216 			first_mp->b_cont = mp;
13217 		} else {
13218 			first_mp = mp;
13219 		}
13220 	}
13221 
13222 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13223 	if (IPCL_IS_TCP(connp)) {
13224 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13225 		return (first_mp);
13226 	} else {
13227 		/* SOCK_RAW, IPPROTO_TCP case */
13228 		(connp->conn_recv)(connp, first_mp, NULL);
13229 		CONN_DEC_REF(connp);
13230 		return (NULL);
13231 	}
13232 
13233 no_conn:
13234 	/* Initiate IPPf processing, if needed. */
13235 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13236 		uint32_t ill_index;
13237 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13238 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13239 		if (first_mp == NULL) {
13240 			return (NULL);
13241 		}
13242 	}
13243 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13244 
13245 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13246 	    ipst->ips_netstack->netstack_tcp, NULL);
13247 	return (NULL);
13248 ipoptions:
13249 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13250 		goto slow_done;
13251 	}
13252 
13253 	UPDATE_IB_PKT_COUNT(ire);
13254 	ire->ire_last_used_time = lbolt;
13255 
13256 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13257 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13258 fragmented:
13259 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13260 			if (mctl_present)
13261 				freeb(first_mp);
13262 			goto slow_done;
13263 		}
13264 		/*
13265 		 * Make sure that first_mp points back to mp as
13266 		 * the mp we came in with could have changed in
13267 		 * ip_rput_fragment().
13268 		 */
13269 		ASSERT(!mctl_present);
13270 		ipha = (ipha_t *)mp->b_rptr;
13271 		first_mp = mp;
13272 	}
13273 
13274 	/* Now we have a complete datagram, destined for this machine. */
13275 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13276 
13277 	len = mp->b_wptr - mp->b_rptr;
13278 	/* Pull up a minimal TCP header, if necessary. */
13279 	if (len < (u1 + 20)) {
13280 tcppullup:
13281 		if (!pullupmsg(mp, u1 + 20)) {
13282 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13283 			goto error;
13284 		}
13285 		ipha = (ipha_t *)mp->b_rptr;
13286 		len = mp->b_wptr - mp->b_rptr;
13287 	}
13288 
13289 	/*
13290 	 * Extract the offset field from the TCP header.  As usual, we
13291 	 * try to help the compiler more than the reader.
13292 	 */
13293 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13294 	if (offset != 5) {
13295 tcpoptions:
13296 		if (offset < 5) {
13297 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13298 			goto error;
13299 		}
13300 		/*
13301 		 * There must be TCP options.
13302 		 * Make sure we can grab them.
13303 		 */
13304 		offset <<= 2;
13305 		offset += u1;
13306 		if (len < offset) {
13307 			if (!pullupmsg(mp, offset)) {
13308 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13309 				goto error;
13310 			}
13311 			ipha = (ipha_t *)mp->b_rptr;
13312 			len = mp->b_wptr - rptr;
13313 		}
13314 	}
13315 
13316 	/* Get the total packet length in len, including headers. */
13317 	if (mp->b_cont) {
13318 multipkttcp:
13319 		len = msgdsize(mp);
13320 	}
13321 
13322 	/*
13323 	 * Check the TCP checksum by pulling together the pseudo-
13324 	 * header checksum, and passing it to ip_csum to be added in
13325 	 * with the TCP datagram.
13326 	 *
13327 	 * Since we are not using the hwcksum if available we must
13328 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13329 	 * If either of these fails along the way the mblk is freed.
13330 	 * If this logic ever changes and mblk is reused to say send
13331 	 * ICMP's back, then this flag may need to be cleared in
13332 	 * other places as well.
13333 	 */
13334 	DB_CKSUMFLAGS(mp) = 0;
13335 
13336 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13337 
13338 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13339 #ifdef	_BIG_ENDIAN
13340 	u1 += IPPROTO_TCP;
13341 #else
13342 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13343 #endif
13344 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13345 	/*
13346 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13347 	 */
13348 	IP_STAT(ipst, ip_in_sw_cksum);
13349 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13350 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13351 		goto error;
13352 	}
13353 
13354 	IP_STAT(ipst, ip_tcp_slow_path);
13355 	goto try_again;
13356 #undef  iphs
13357 #undef  rptr
13358 
13359 error:
13360 	freemsg(first_mp);
13361 slow_done:
13362 	return (NULL);
13363 }
13364 
13365 /* ARGSUSED */
13366 static void
13367 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13368     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13369 {
13370 	conn_t		*connp;
13371 	uint32_t	sum;
13372 	uint32_t	u1;
13373 	ssize_t		len;
13374 	sctp_hdr_t	*sctph;
13375 	zoneid_t	zoneid = ire->ire_zoneid;
13376 	uint32_t	pktsum;
13377 	uint32_t	calcsum;
13378 	uint32_t	ports;
13379 	in6_addr_t	map_src, map_dst;
13380 	ill_t		*ill = (ill_t *)q->q_ptr;
13381 	ip_stack_t	*ipst;
13382 	sctp_stack_t	*sctps;
13383 	boolean_t	sctp_csum_err = B_FALSE;
13384 
13385 	ASSERT(recv_ill != NULL);
13386 	ipst = recv_ill->ill_ipst;
13387 	sctps = ipst->ips_netstack->netstack_sctp;
13388 
13389 #define	rptr	((uchar_t *)ipha)
13390 
13391 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13392 	ASSERT(ill != NULL);
13393 
13394 	/* u1 is # words of IP options */
13395 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13396 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13397 
13398 	/* IP options present */
13399 	if (u1 > 0) {
13400 		goto ipoptions;
13401 	} else {
13402 		/* Check the IP header checksum.  */
13403 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13404 		    !mctl_present) {
13405 #define	uph	((uint16_t *)ipha)
13406 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13407 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13408 #undef	uph
13409 			/* finish doing IP checksum */
13410 			sum = (sum & 0xFFFF) + (sum >> 16);
13411 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13412 			/*
13413 			 * Don't verify header checksum if this packet
13414 			 * is coming back from AH/ESP as we already did it.
13415 			 */
13416 			if (sum != 0 && sum != 0xFFFF) {
13417 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13418 				goto error;
13419 			}
13420 		}
13421 		/*
13422 		 * Since there is no SCTP h/w cksum support yet, just
13423 		 * clear the flag.
13424 		 */
13425 		DB_CKSUMFLAGS(mp) = 0;
13426 	}
13427 
13428 	/*
13429 	 * Don't verify header checksum if this packet is coming
13430 	 * back from AH/ESP as we already did it.
13431 	 */
13432 	if (!mctl_present) {
13433 		UPDATE_IB_PKT_COUNT(ire);
13434 		ire->ire_last_used_time = lbolt;
13435 	}
13436 
13437 	/* packet part of fragmented IP packet? */
13438 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13439 	if (u1 & (IPH_MF | IPH_OFFSET))
13440 		goto fragmented;
13441 
13442 	/* u1 = IP header length (20 bytes) */
13443 	u1 = IP_SIMPLE_HDR_LENGTH;
13444 
13445 find_sctp_client:
13446 	/* Pullup if we don't have the sctp common header. */
13447 	len = MBLKL(mp);
13448 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13449 		if (mp->b_cont == NULL ||
13450 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13451 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13452 			goto error;
13453 		}
13454 		ipha = (ipha_t *)mp->b_rptr;
13455 		len = MBLKL(mp);
13456 	}
13457 
13458 	sctph = (sctp_hdr_t *)(rptr + u1);
13459 #ifdef	DEBUG
13460 	if (!skip_sctp_cksum) {
13461 #endif
13462 		pktsum = sctph->sh_chksum;
13463 		sctph->sh_chksum = 0;
13464 		calcsum = sctp_cksum(mp, u1);
13465 		sctph->sh_chksum = pktsum;
13466 		if (calcsum != pktsum)
13467 			sctp_csum_err = B_TRUE;
13468 #ifdef	DEBUG	/* skip_sctp_cksum */
13469 	}
13470 #endif
13471 	/* get the ports */
13472 	ports = *(uint32_t *)&sctph->sh_sport;
13473 
13474 	IRE_REFRELE(ire);
13475 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13476 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13477 	if (sctp_csum_err) {
13478 		/*
13479 		 * No potential sctp checksum errors go to the Sun
13480 		 * sctp stack however they might be Adler-32 summed
13481 		 * packets a userland stack bound to a raw IP socket
13482 		 * could reasonably use. Note though that Adler-32 is
13483 		 * a long deprecated algorithm and customer sctp
13484 		 * networks should eventually migrate to CRC-32 at
13485 		 * which time this facility should be removed.
13486 		 */
13487 		flags |= IP_FF_SCTP_CSUM_ERR;
13488 		goto no_conn;
13489 	}
13490 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13491 	    sctps)) == NULL) {
13492 		/* Check for raw socket or OOTB handling */
13493 		goto no_conn;
13494 	}
13495 
13496 	/* Found a client; up it goes */
13497 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13498 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13499 	return;
13500 
13501 no_conn:
13502 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13503 	    ports, mctl_present, flags, B_TRUE, zoneid);
13504 	return;
13505 
13506 ipoptions:
13507 	DB_CKSUMFLAGS(mp) = 0;
13508 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13509 		goto slow_done;
13510 
13511 	UPDATE_IB_PKT_COUNT(ire);
13512 	ire->ire_last_used_time = lbolt;
13513 
13514 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13515 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13516 fragmented:
13517 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13518 			goto slow_done;
13519 		/*
13520 		 * Make sure that first_mp points back to mp as
13521 		 * the mp we came in with could have changed in
13522 		 * ip_rput_fragment().
13523 		 */
13524 		ASSERT(!mctl_present);
13525 		ipha = (ipha_t *)mp->b_rptr;
13526 		first_mp = mp;
13527 	}
13528 
13529 	/* Now we have a complete datagram, destined for this machine. */
13530 	u1 = IPH_HDR_LENGTH(ipha);
13531 	goto find_sctp_client;
13532 #undef  iphs
13533 #undef  rptr
13534 
13535 error:
13536 	freemsg(first_mp);
13537 slow_done:
13538 	IRE_REFRELE(ire);
13539 }
13540 
13541 #define	VER_BITS	0xF0
13542 #define	VERSION_6	0x60
13543 
13544 static boolean_t
13545 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13546     ipaddr_t *dstp, ip_stack_t *ipst)
13547 {
13548 	uint_t	opt_len;
13549 	ipha_t *ipha;
13550 	ssize_t len;
13551 	uint_t	pkt_len;
13552 
13553 	ASSERT(ill != NULL);
13554 	IP_STAT(ipst, ip_ipoptions);
13555 	ipha = *iphapp;
13556 
13557 #define	rptr    ((uchar_t *)ipha)
13558 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13559 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13560 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13561 		freemsg(mp);
13562 		return (B_FALSE);
13563 	}
13564 
13565 	/* multiple mblk or too short */
13566 	pkt_len = ntohs(ipha->ipha_length);
13567 
13568 	/* Get the number of words of IP options in the IP header. */
13569 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13570 	if (opt_len) {
13571 		/* IP Options present!  Validate and process. */
13572 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13573 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13574 			goto done;
13575 		}
13576 		/*
13577 		 * Recompute complete header length and make sure we
13578 		 * have access to all of it.
13579 		 */
13580 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13581 		if (len > (mp->b_wptr - rptr)) {
13582 			if (len > pkt_len) {
13583 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13584 				goto done;
13585 			}
13586 			if (!pullupmsg(mp, len)) {
13587 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13588 				goto done;
13589 			}
13590 			ipha = (ipha_t *)mp->b_rptr;
13591 		}
13592 		/*
13593 		 * Go off to ip_rput_options which returns the next hop
13594 		 * destination address, which may have been affected
13595 		 * by source routing.
13596 		 */
13597 		IP_STAT(ipst, ip_opt);
13598 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13599 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13600 			return (B_FALSE);
13601 		}
13602 	}
13603 	*iphapp = ipha;
13604 	return (B_TRUE);
13605 done:
13606 	/* clear b_prev - used by ip_mroute_decap */
13607 	mp->b_prev = NULL;
13608 	freemsg(mp);
13609 	return (B_FALSE);
13610 #undef  rptr
13611 }
13612 
13613 /*
13614  * Deal with the fact that there is no ire for the destination.
13615  */
13616 static ire_t *
13617 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13618 {
13619 	ipha_t	*ipha;
13620 	ill_t	*ill;
13621 	ire_t	*ire;
13622 	boolean_t	check_multirt = B_FALSE;
13623 	ip_stack_t *ipst;
13624 
13625 	ipha = (ipha_t *)mp->b_rptr;
13626 	ill = (ill_t *)q->q_ptr;
13627 
13628 	ASSERT(ill != NULL);
13629 	ipst = ill->ill_ipst;
13630 
13631 	/*
13632 	 * No IRE for this destination, so it can't be for us.
13633 	 * Unless we are forwarding, drop the packet.
13634 	 * We have to let source routed packets through
13635 	 * since we don't yet know if they are 'ping -l'
13636 	 * packets i.e. if they will go out over the
13637 	 * same interface as they came in on.
13638 	 */
13639 	if (ll_multicast) {
13640 		freemsg(mp);
13641 		return (NULL);
13642 	}
13643 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13644 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13645 		freemsg(mp);
13646 		return (NULL);
13647 	}
13648 
13649 	/*
13650 	 * Mark this packet as having originated externally.
13651 	 *
13652 	 * For non-forwarding code path, ire_send later double
13653 	 * checks this interface to see if it is still exists
13654 	 * post-ARP resolution.
13655 	 *
13656 	 * Also, IPQOS uses this to differentiate between
13657 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13658 	 * QOS packet processing in ip_wput_attach_llhdr().
13659 	 * The QoS module can mark the b_band for a fastpath message
13660 	 * or the dl_priority field in a unitdata_req header for
13661 	 * CoS marking. This info can only be found in
13662 	 * ip_wput_attach_llhdr().
13663 	 */
13664 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13665 	/*
13666 	 * Clear the indication that this may have a hardware checksum
13667 	 * as we are not using it
13668 	 */
13669 	DB_CKSUMFLAGS(mp) = 0;
13670 
13671 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13672 	    MBLK_GETLABEL(mp), ipst);
13673 
13674 	if (ire == NULL && check_multirt) {
13675 		/* Let ip_newroute handle CGTP  */
13676 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13677 		return (NULL);
13678 	}
13679 
13680 	if (ire != NULL)
13681 		return (ire);
13682 
13683 	mp->b_prev = mp->b_next = 0;
13684 	/* send icmp unreachable */
13685 	q = WR(q);
13686 	/* Sent by forwarding path, and router is global zone */
13687 	if (ip_source_routed(ipha, ipst)) {
13688 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13689 		    GLOBAL_ZONEID, ipst);
13690 	} else {
13691 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13692 		    ipst);
13693 	}
13694 
13695 	return (NULL);
13696 
13697 }
13698 
13699 /*
13700  * check ip header length and align it.
13701  */
13702 static boolean_t
13703 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13704 {
13705 	ssize_t len;
13706 	ill_t *ill;
13707 	ipha_t	*ipha;
13708 
13709 	len = MBLKL(mp);
13710 
13711 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13712 		ill = (ill_t *)q->q_ptr;
13713 
13714 		if (!OK_32PTR(mp->b_rptr))
13715 			IP_STAT(ipst, ip_notaligned1);
13716 		else
13717 			IP_STAT(ipst, ip_notaligned2);
13718 		/* Guard against bogus device drivers */
13719 		if (len < 0) {
13720 			/* clear b_prev - used by ip_mroute_decap */
13721 			mp->b_prev = NULL;
13722 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13723 			freemsg(mp);
13724 			return (B_FALSE);
13725 		}
13726 
13727 		if (ip_rput_pullups++ == 0) {
13728 			ipha = (ipha_t *)mp->b_rptr;
13729 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13730 			    "ip_check_and_align_header: %s forced us to "
13731 			    " pullup pkt, hdr len %ld, hdr addr %p",
13732 			    ill->ill_name, len, ipha);
13733 		}
13734 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13735 			/* clear b_prev - used by ip_mroute_decap */
13736 			mp->b_prev = NULL;
13737 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13738 			freemsg(mp);
13739 			return (B_FALSE);
13740 		}
13741 	}
13742 	return (B_TRUE);
13743 }
13744 
13745 ire_t *
13746 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13747 {
13748 	ire_t		*new_ire;
13749 	ill_t		*ire_ill;
13750 	uint_t		ifindex;
13751 	ip_stack_t	*ipst = ill->ill_ipst;
13752 	boolean_t	strict_check = B_FALSE;
13753 
13754 	/*
13755 	 * This packet came in on an interface other than the one associated
13756 	 * with the first ire we found for the destination address. We do
13757 	 * another ire lookup here, using the ingress ill, to see if the
13758 	 * interface is in an interface group.
13759 	 * As long as the ills belong to the same group, we don't consider
13760 	 * them to be arriving on the wrong interface. Thus, if the switch
13761 	 * is doing inbound load spreading, we won't drop packets when the
13762 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13763 	 * for 'usesrc groups' where the destination address may belong to
13764 	 * another interface to allow multipathing to happen.
13765 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13766 	 * where the local address may not be unique. In this case we were
13767 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13768 	 * actually returned. The new lookup, which is more specific, should
13769 	 * only find the IRE_LOCAL associated with the ingress ill if one
13770 	 * exists.
13771 	 */
13772 
13773 	if (ire->ire_ipversion == IPV4_VERSION) {
13774 		if (ipst->ips_ip_strict_dst_multihoming)
13775 			strict_check = B_TRUE;
13776 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13777 		    ill->ill_ipif, ALL_ZONES, NULL,
13778 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13779 	} else {
13780 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13781 		if (ipst->ips_ipv6_strict_dst_multihoming)
13782 			strict_check = B_TRUE;
13783 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13784 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13785 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13786 	}
13787 	/*
13788 	 * If the same ire that was returned in ip_input() is found then this
13789 	 * is an indication that interface groups are in use. The packet
13790 	 * arrived on a different ill in the group than the one associated with
13791 	 * the destination address.  If a different ire was found then the same
13792 	 * IP address must be hosted on multiple ills. This is possible with
13793 	 * unnumbered point2point interfaces. We switch to use this new ire in
13794 	 * order to have accurate interface statistics.
13795 	 */
13796 	if (new_ire != NULL) {
13797 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13798 			ire_refrele(ire);
13799 			ire = new_ire;
13800 		} else {
13801 			ire_refrele(new_ire);
13802 		}
13803 		return (ire);
13804 	} else if ((ire->ire_rfq == NULL) &&
13805 	    (ire->ire_ipversion == IPV4_VERSION)) {
13806 		/*
13807 		 * The best match could have been the original ire which
13808 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13809 		 * the strict multihoming checks are irrelevant as we consider
13810 		 * local addresses hosted on lo0 to be interface agnostic. We
13811 		 * only expect a null ire_rfq on IREs which are associated with
13812 		 * lo0 hence we can return now.
13813 		 */
13814 		return (ire);
13815 	}
13816 
13817 	/*
13818 	 * Chase pointers once and store locally.
13819 	 */
13820 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13821 	    (ill_t *)(ire->ire_rfq->q_ptr);
13822 	ifindex = ill->ill_usesrc_ifindex;
13823 
13824 	/*
13825 	 * Check if it's a legal address on the 'usesrc' interface.
13826 	 */
13827 	if ((ifindex != 0) && (ire_ill != NULL) &&
13828 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13829 		return (ire);
13830 	}
13831 
13832 	/*
13833 	 * If the ip*_strict_dst_multihoming switch is on then we can
13834 	 * only accept this packet if the interface is marked as routing.
13835 	 */
13836 	if (!(strict_check))
13837 		return (ire);
13838 
13839 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13840 	    ILLF_ROUTER) != 0) {
13841 		return (ire);
13842 	}
13843 
13844 	ire_refrele(ire);
13845 	return (NULL);
13846 }
13847 
13848 ire_t *
13849 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13850 {
13851 	ipha_t	*ipha;
13852 	ire_t	*src_ire;
13853 	ill_t	*stq_ill;
13854 	uint_t	hlen;
13855 	uint_t	pkt_len;
13856 	uint32_t sum;
13857 	queue_t	*dev_q;
13858 	ip_stack_t *ipst = ill->ill_ipst;
13859 	mblk_t *fpmp;
13860 
13861 	ipha = (ipha_t *)mp->b_rptr;
13862 
13863 	/*
13864 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13865 	 * The loopback address check for both src and dst has already
13866 	 * been checked in ip_input
13867 	 */
13868 
13869 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13870 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13871 		goto drop;
13872 	}
13873 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13874 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13875 
13876 	if (src_ire != NULL) {
13877 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13878 		ire_refrele(src_ire);
13879 		goto drop;
13880 	}
13881 
13882 
13883 	/* No ire cache of nexthop. So first create one  */
13884 	if (ire == NULL) {
13885 		boolean_t check_multirt;
13886 
13887 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13888 		/*
13889 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13890 		 * is not set. So upon return from ire_forward
13891 		 * check_multirt should remain as false.
13892 		 */
13893 		if (ire == NULL) {
13894 			/* An attempt was made to forward the packet */
13895 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13896 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13897 			mp->b_prev = mp->b_next = 0;
13898 			/* send icmp unreachable */
13899 			/* Sent by forwarding path, and router is global zone */
13900 			if (ip_source_routed(ipha, ipst)) {
13901 				icmp_unreachable(ill->ill_wq, mp,
13902 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13903 				    ipst);
13904 			} else {
13905 				icmp_unreachable(ill->ill_wq, mp,
13906 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13907 				    ipst);
13908 			}
13909 			return (ire);
13910 		}
13911 	}
13912 
13913 	/*
13914 	 * Forwarding fastpath exception case:
13915 	 * If either of the follwoing case is true, we take
13916 	 * the slowpath
13917 	 *	o forwarding is not enabled
13918 	 *	o incoming and outgoing interface are the same, or the same
13919 	 *	  IPMP group
13920 	 *	o corresponding ire is in incomplete state
13921 	 *	o packet needs fragmentation
13922 	 *	o ARP cache is not resolved
13923 	 *
13924 	 * The codeflow from here on is thus:
13925 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13926 	 */
13927 	pkt_len = ntohs(ipha->ipha_length);
13928 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13929 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13930 	    !(ill->ill_flags & ILLF_ROUTER) ||
13931 	    (ill == stq_ill) ||
13932 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13933 	    (ire->ire_nce == NULL) ||
13934 	    (pkt_len > ire->ire_max_frag) ||
13935 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13936 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13937 	    ipha->ipha_ttl <= 1) {
13938 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13939 		    ipha, ill, B_FALSE);
13940 		return (ire);
13941 	}
13942 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13943 
13944 	DTRACE_PROBE4(ip4__forwarding__start,
13945 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13946 
13947 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13948 	    ipst->ips_ipv4firewall_forwarding,
13949 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13950 
13951 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13952 
13953 	if (mp == NULL)
13954 		goto drop;
13955 
13956 	mp->b_datap->db_struioun.cksum.flags = 0;
13957 	/* Adjust the checksum to reflect the ttl decrement. */
13958 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13959 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13960 	ipha->ipha_ttl--;
13961 
13962 	/*
13963 	 * Write the link layer header.  We can do this safely here,
13964 	 * because we have already tested to make sure that the IP
13965 	 * policy is not set, and that we have a fast path destination
13966 	 * header.
13967 	 */
13968 	mp->b_rptr -= hlen;
13969 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13970 
13971 	UPDATE_IB_PKT_COUNT(ire);
13972 	ire->ire_last_used_time = lbolt;
13973 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13974 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13975 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13976 
13977 	dev_q = ire->ire_stq->q_next;
13978 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
13979 	    !canputnext(ire->ire_stq)) {
13980 		goto indiscard;
13981 	}
13982 	if (ILL_DLS_CAPABLE(stq_ill)) {
13983 		/*
13984 		 * Send the packet directly to DLD, where it
13985 		 * may be queued depending on the availability
13986 		 * of transmit resources at the media layer.
13987 		 */
13988 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
13989 	} else {
13990 		DTRACE_PROBE4(ip4__physical__out__start,
13991 		    ill_t *, NULL, ill_t *, stq_ill,
13992 		    ipha_t *, ipha, mblk_t *, mp);
13993 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
13994 		    ipst->ips_ipv4firewall_physical_out,
13995 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13996 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13997 		if (mp == NULL)
13998 			goto drop;
13999 		putnext(ire->ire_stq, mp);
14000 	}
14001 	return (ire);
14002 
14003 indiscard:
14004 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14005 drop:
14006 	if (mp != NULL)
14007 		freemsg(mp);
14008 	return (ire);
14009 
14010 }
14011 
14012 /*
14013  * This function is called in the forwarding slowpath, when
14014  * either the ire lacks the link-layer address, or the packet needs
14015  * further processing(eg. fragmentation), before transmission.
14016  */
14017 
14018 static void
14019 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14020     ill_t *ill, boolean_t ll_multicast)
14021 {
14022 	ill_group_t	*ill_group;
14023 	ill_group_t	*ire_group;
14024 	queue_t		*dev_q;
14025 	ire_t		*src_ire;
14026 	ip_stack_t	*ipst = ill->ill_ipst;
14027 
14028 	ASSERT(ire->ire_stq != NULL);
14029 
14030 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14031 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14032 
14033 	if (ll_multicast != 0) {
14034 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14035 		goto drop_pkt;
14036 	}
14037 
14038 	/*
14039 	 * check if ipha_src is a broadcast address. Note that this
14040 	 * check is redundant when we get here from ip_fast_forward()
14041 	 * which has already done this check. However, since we can
14042 	 * also get here from ip_rput_process_broadcast() or, for
14043 	 * for the slow path through ip_fast_forward(), we perform
14044 	 * the check again for code-reusability
14045 	 */
14046 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14047 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14048 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14049 		if (src_ire != NULL)
14050 			ire_refrele(src_ire);
14051 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14052 		ip2dbg(("ip_rput_process_forward: Received packet with"
14053 		    " bad src/dst address on %s\n", ill->ill_name));
14054 		goto drop_pkt;
14055 	}
14056 
14057 	ill_group = ill->ill_group;
14058 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14059 	/*
14060 	 * Check if we want to forward this one at this time.
14061 	 * We allow source routed packets on a host provided that
14062 	 * they go out the same interface or same interface group
14063 	 * as they came in on.
14064 	 *
14065 	 * XXX To be quicker, we may wish to not chase pointers to
14066 	 * get the ILLF_ROUTER flag and instead store the
14067 	 * forwarding policy in the ire.  An unfortunate
14068 	 * side-effect of that would be requiring an ire flush
14069 	 * whenever the ILLF_ROUTER flag changes.
14070 	 */
14071 	if (((ill->ill_flags &
14072 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14073 	    ILLF_ROUTER) == 0) &&
14074 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14075 	    (ill_group != NULL && ill_group == ire_group)))) {
14076 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14077 		if (ip_source_routed(ipha, ipst)) {
14078 			q = WR(q);
14079 			/*
14080 			 * Clear the indication that this may have
14081 			 * hardware checksum as we are not using it.
14082 			 */
14083 			DB_CKSUMFLAGS(mp) = 0;
14084 			/* Sent by forwarding path, and router is global zone */
14085 			icmp_unreachable(q, mp,
14086 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14087 			return;
14088 		}
14089 		goto drop_pkt;
14090 	}
14091 
14092 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14093 
14094 	/* Packet is being forwarded. Turning off hwcksum flag. */
14095 	DB_CKSUMFLAGS(mp) = 0;
14096 	if (ipst->ips_ip_g_send_redirects) {
14097 		/*
14098 		 * Check whether the incoming interface and outgoing
14099 		 * interface is part of the same group. If so,
14100 		 * send redirects.
14101 		 *
14102 		 * Check the source address to see if it originated
14103 		 * on the same logical subnet it is going back out on.
14104 		 * If so, we should be able to send it a redirect.
14105 		 * Avoid sending a redirect if the destination
14106 		 * is directly connected (i.e., ipha_dst is the same
14107 		 * as ire_gateway_addr or the ire_addr of the
14108 		 * nexthop IRE_CACHE ), or if the packet was source
14109 		 * routed out this interface.
14110 		 */
14111 		ipaddr_t src, nhop;
14112 		mblk_t	*mp1;
14113 		ire_t	*nhop_ire = NULL;
14114 
14115 		/*
14116 		 * Check whether ire_rfq and q are from the same ill
14117 		 * or if they are not same, they at least belong
14118 		 * to the same group. If so, send redirects.
14119 		 */
14120 		if ((ire->ire_rfq == q ||
14121 		    (ill_group != NULL && ill_group == ire_group)) &&
14122 		    !ip_source_routed(ipha, ipst)) {
14123 
14124 			nhop = (ire->ire_gateway_addr != 0 ?
14125 			    ire->ire_gateway_addr : ire->ire_addr);
14126 
14127 			if (ipha->ipha_dst == nhop) {
14128 				/*
14129 				 * We avoid sending a redirect if the
14130 				 * destination is directly connected
14131 				 * because it is possible that multiple
14132 				 * IP subnets may have been configured on
14133 				 * the link, and the source may not
14134 				 * be on the same subnet as ip destination,
14135 				 * even though they are on the same
14136 				 * physical link.
14137 				 */
14138 				goto sendit;
14139 			}
14140 
14141 			src = ipha->ipha_src;
14142 
14143 			/*
14144 			 * We look up the interface ire for the nexthop,
14145 			 * to see if ipha_src is in the same subnet
14146 			 * as the nexthop.
14147 			 *
14148 			 * Note that, if, in the future, IRE_CACHE entries
14149 			 * are obsoleted,  this lookup will not be needed,
14150 			 * as the ire passed to this function will be the
14151 			 * same as the nhop_ire computed below.
14152 			 */
14153 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14154 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14155 			    0, NULL, MATCH_IRE_TYPE, ipst);
14156 
14157 			if (nhop_ire != NULL) {
14158 				if ((src & nhop_ire->ire_mask) ==
14159 				    (nhop & nhop_ire->ire_mask)) {
14160 					/*
14161 					 * The source is directly connected.
14162 					 * Just copy the ip header (which is
14163 					 * in the first mblk)
14164 					 */
14165 					mp1 = copyb(mp);
14166 					if (mp1 != NULL) {
14167 						icmp_send_redirect(WR(q), mp1,
14168 						    nhop, ipst);
14169 					}
14170 				}
14171 				ire_refrele(nhop_ire);
14172 			}
14173 		}
14174 	}
14175 sendit:
14176 	dev_q = ire->ire_stq->q_next;
14177 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14178 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14179 		freemsg(mp);
14180 		return;
14181 	}
14182 
14183 	ip_rput_forward(ire, ipha, mp, ill);
14184 	return;
14185 
14186 drop_pkt:
14187 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14188 	freemsg(mp);
14189 }
14190 
14191 ire_t *
14192 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14193     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14194 {
14195 	queue_t		*q;
14196 	uint16_t	hcksumflags;
14197 	ip_stack_t	*ipst = ill->ill_ipst;
14198 
14199 	q = *qp;
14200 
14201 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14202 
14203 	/*
14204 	 * Clear the indication that this may have hardware
14205 	 * checksum as we are not using it for forwarding.
14206 	 */
14207 	hcksumflags = DB_CKSUMFLAGS(mp);
14208 	DB_CKSUMFLAGS(mp) = 0;
14209 
14210 	/*
14211 	 * Directed broadcast forwarding: if the packet came in over a
14212 	 * different interface then it is routed out over we can forward it.
14213 	 */
14214 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14215 		ire_refrele(ire);
14216 		freemsg(mp);
14217 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14218 		return (NULL);
14219 	}
14220 	/*
14221 	 * For multicast we have set dst to be INADDR_BROADCAST
14222 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14223 	 * only for broadcast packets.
14224 	 */
14225 	if (!CLASSD(ipha->ipha_dst)) {
14226 		ire_t *new_ire;
14227 		ipif_t *ipif;
14228 		/*
14229 		 * For ill groups, as the switch duplicates broadcasts
14230 		 * across all the ports, we need to filter out and
14231 		 * send up only one copy. There is one copy for every
14232 		 * broadcast address on each ill. Thus, we look for a
14233 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14234 		 * later to see whether this ill is eligible to receive
14235 		 * them or not. ill_nominate_bcast_rcv() nominates only
14236 		 * one set of IREs for receiving.
14237 		 */
14238 
14239 		ipif = ipif_get_next_ipif(NULL, ill);
14240 		if (ipif == NULL) {
14241 			ire_refrele(ire);
14242 			freemsg(mp);
14243 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14244 			return (NULL);
14245 		}
14246 		new_ire = ire_ctable_lookup(dst, 0, 0,
14247 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14248 		ipif_refrele(ipif);
14249 
14250 		if (new_ire != NULL) {
14251 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14252 				ire_refrele(ire);
14253 				ire_refrele(new_ire);
14254 				freemsg(mp);
14255 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14256 				return (NULL);
14257 			}
14258 			/*
14259 			 * In the special case of multirouted broadcast
14260 			 * packets, we unconditionally need to "gateway"
14261 			 * them to the appropriate interface here.
14262 			 * In the normal case, this cannot happen, because
14263 			 * there is no broadcast IRE tagged with the
14264 			 * RTF_MULTIRT flag.
14265 			 */
14266 			if (new_ire->ire_flags & RTF_MULTIRT) {
14267 				ire_refrele(new_ire);
14268 				if (ire->ire_rfq != NULL) {
14269 					q = ire->ire_rfq;
14270 					*qp = q;
14271 				}
14272 			} else {
14273 				ire_refrele(ire);
14274 				ire = new_ire;
14275 			}
14276 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14277 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14278 				/*
14279 				 * Free the message if
14280 				 * ip_g_forward_directed_bcast is turned
14281 				 * off for non-local broadcast.
14282 				 */
14283 				ire_refrele(ire);
14284 				freemsg(mp);
14285 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14286 				return (NULL);
14287 			}
14288 		} else {
14289 			/*
14290 			 * This CGTP packet successfully passed the
14291 			 * CGTP filter, but the related CGTP
14292 			 * broadcast IRE has not been found,
14293 			 * meaning that the redundant ipif is
14294 			 * probably down. However, if we discarded
14295 			 * this packet, its duplicate would be
14296 			 * filtered out by the CGTP filter so none
14297 			 * of them would get through. So we keep
14298 			 * going with this one.
14299 			 */
14300 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14301 			if (ire->ire_rfq != NULL) {
14302 				q = ire->ire_rfq;
14303 				*qp = q;
14304 			}
14305 		}
14306 	}
14307 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14308 		/*
14309 		 * Verify that there are not more then one
14310 		 * IRE_BROADCAST with this broadcast address which
14311 		 * has ire_stq set.
14312 		 * TODO: simplify, loop over all IRE's
14313 		 */
14314 		ire_t	*ire1;
14315 		int	num_stq = 0;
14316 		mblk_t	*mp1;
14317 
14318 		/* Find the first one with ire_stq set */
14319 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14320 		for (ire1 = ire; ire1 &&
14321 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14322 		    ire1 = ire1->ire_next)
14323 			;
14324 		if (ire1) {
14325 			ire_refrele(ire);
14326 			ire = ire1;
14327 			IRE_REFHOLD(ire);
14328 		}
14329 
14330 		/* Check if there are additional ones with stq set */
14331 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14332 			if (ire->ire_addr != ire1->ire_addr)
14333 				break;
14334 			if (ire1->ire_stq) {
14335 				num_stq++;
14336 				break;
14337 			}
14338 		}
14339 		rw_exit(&ire->ire_bucket->irb_lock);
14340 		if (num_stq == 1 && ire->ire_stq != NULL) {
14341 			ip1dbg(("ip_rput_process_broadcast: directed "
14342 			    "broadcast to 0x%x\n",
14343 			    ntohl(ire->ire_addr)));
14344 			mp1 = copymsg(mp);
14345 			if (mp1) {
14346 				switch (ipha->ipha_protocol) {
14347 				case IPPROTO_UDP:
14348 					ip_udp_input(q, mp1, ipha, ire, ill);
14349 					break;
14350 				default:
14351 					ip_proto_input(q, mp1, ipha, ire, ill,
14352 					    B_FALSE);
14353 					break;
14354 				}
14355 			}
14356 			/*
14357 			 * Adjust ttl to 2 (1+1 - the forward engine
14358 			 * will decrement it by one.
14359 			 */
14360 			if (ip_csum_hdr(ipha)) {
14361 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14362 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14363 				freemsg(mp);
14364 				ire_refrele(ire);
14365 				return (NULL);
14366 			}
14367 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14368 			ipha->ipha_hdr_checksum = 0;
14369 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14370 			ip_rput_process_forward(q, mp, ire, ipha,
14371 			    ill, ll_multicast);
14372 			ire_refrele(ire);
14373 			return (NULL);
14374 		}
14375 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14376 		    ntohl(ire->ire_addr)));
14377 	}
14378 
14379 
14380 	/* Restore any hardware checksum flags */
14381 	DB_CKSUMFLAGS(mp) = hcksumflags;
14382 	return (ire);
14383 }
14384 
14385 /* ARGSUSED */
14386 static boolean_t
14387 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14388     int *ll_multicast, ipaddr_t *dstp)
14389 {
14390 	ip_stack_t	*ipst = ill->ill_ipst;
14391 
14392 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14393 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14394 	    ntohs(ipha->ipha_length));
14395 
14396 	/*
14397 	 * Forward packets only if we have joined the allmulti
14398 	 * group on this interface.
14399 	 */
14400 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14401 		int retval;
14402 
14403 		/*
14404 		 * Clear the indication that this may have hardware
14405 		 * checksum as we are not using it.
14406 		 */
14407 		DB_CKSUMFLAGS(mp) = 0;
14408 		retval = ip_mforward(ill, ipha, mp);
14409 		/* ip_mforward updates mib variables if needed */
14410 		/* clear b_prev - used by ip_mroute_decap */
14411 		mp->b_prev = NULL;
14412 
14413 		switch (retval) {
14414 		case 0:
14415 			/*
14416 			 * pkt is okay and arrived on phyint.
14417 			 *
14418 			 * If we are running as a multicast router
14419 			 * we need to see all IGMP and/or PIM packets.
14420 			 */
14421 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14422 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14423 				goto done;
14424 			}
14425 			break;
14426 		case -1:
14427 			/* pkt is mal-formed, toss it */
14428 			goto drop_pkt;
14429 		case 1:
14430 			/* pkt is okay and arrived on a tunnel */
14431 			/*
14432 			 * If we are running a multicast router
14433 			 *  we need to see all igmp packets.
14434 			 */
14435 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14436 				*dstp = INADDR_BROADCAST;
14437 				*ll_multicast = 1;
14438 				return (B_FALSE);
14439 			}
14440 
14441 			goto drop_pkt;
14442 		}
14443 	}
14444 
14445 	ILM_WALKER_HOLD(ill);
14446 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14447 		/*
14448 		 * This might just be caused by the fact that
14449 		 * multiple IP Multicast addresses map to the same
14450 		 * link layer multicast - no need to increment counter!
14451 		 */
14452 		ILM_WALKER_RELE(ill);
14453 		freemsg(mp);
14454 		return (B_TRUE);
14455 	}
14456 	ILM_WALKER_RELE(ill);
14457 done:
14458 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14459 	/*
14460 	 * This assumes the we deliver to all streams for multicast
14461 	 * and broadcast packets.
14462 	 */
14463 	*dstp = INADDR_BROADCAST;
14464 	*ll_multicast = 1;
14465 	return (B_FALSE);
14466 drop_pkt:
14467 	ip2dbg(("ip_rput: drop pkt\n"));
14468 	freemsg(mp);
14469 	return (B_TRUE);
14470 }
14471 
14472 /*
14473  * This function is used to both return an indication of whether or not
14474  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14475  * and in doing so, determine whether or not it is broadcast vs multicast.
14476  * For it to be a broadcast packet, we must have the appropriate mblk_t
14477  * hanging off the ill_t.  If this is either not present or doesn't match
14478  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14479  * to be multicast.  Thus NICs that have no broadcast address (or no
14480  * capability for one, such as point to point links) cannot return as
14481  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14482  * the return values simplifies the current use of the return value of this
14483  * function, which is to pass through the multicast/broadcast characteristic
14484  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14485  * changing the return value to some other symbol demands the appropriate
14486  * "translation" when hpe_flags is set prior to calling hook_run() for
14487  * packet events.
14488  */
14489 int
14490 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14491 {
14492 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14493 	mblk_t *bmp;
14494 
14495 	if (ind->dl_group_address) {
14496 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14497 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14498 		    MBLKL(mb) &&
14499 		    (bmp = ill->ill_bcast_mp) != NULL) {
14500 			dl_unitdata_req_t *dlur;
14501 			uint8_t *bphys_addr;
14502 
14503 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14504 			if (ill->ill_sap_length < 0)
14505 				bphys_addr = (uchar_t *)dlur +
14506 				    dlur->dl_dest_addr_offset;
14507 			else
14508 				bphys_addr = (uchar_t *)dlur +
14509 				    dlur->dl_dest_addr_offset +
14510 				    ill->ill_sap_length;
14511 
14512 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14513 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14514 				return (HPE_BROADCAST);
14515 			}
14516 			return (HPE_MULTICAST);
14517 		}
14518 		return (HPE_MULTICAST);
14519 	}
14520 	return (0);
14521 }
14522 
14523 static boolean_t
14524 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14525     int *ll_multicast, mblk_t **mpp)
14526 {
14527 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14528 	boolean_t must_copy = B_FALSE;
14529 	struct iocblk   *iocp;
14530 	ipha_t		*ipha;
14531 	ip_stack_t	*ipst = ill->ill_ipst;
14532 
14533 #define	rptr    ((uchar_t *)ipha)
14534 
14535 	first_mp = *first_mpp;
14536 	mp = *mpp;
14537 
14538 	ASSERT(first_mp == mp);
14539 
14540 	/*
14541 	 * if db_ref > 1 then copymsg and free original. Packet may be
14542 	 * changed and do not want other entity who has a reference to this
14543 	 * message to trip over the changes. This is a blind change because
14544 	 * trying to catch all places that might change packet is too
14545 	 * difficult (since it may be a module above this one)
14546 	 *
14547 	 * This corresponds to the non-fast path case. We walk down the full
14548 	 * chain in this case, and check the db_ref count of all the dblks,
14549 	 * and do a copymsg if required. It is possible that the db_ref counts
14550 	 * of the data blocks in the mblk chain can be different.
14551 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14552 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14553 	 * 'snoop' is running.
14554 	 */
14555 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14556 		if (mp1->b_datap->db_ref > 1) {
14557 			must_copy = B_TRUE;
14558 			break;
14559 		}
14560 	}
14561 
14562 	if (must_copy) {
14563 		mp1 = copymsg(mp);
14564 		if (mp1 == NULL) {
14565 			for (mp1 = mp; mp1 != NULL;
14566 			    mp1 = mp1->b_cont) {
14567 				mp1->b_next = NULL;
14568 				mp1->b_prev = NULL;
14569 			}
14570 			freemsg(mp);
14571 			if (ill != NULL) {
14572 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14573 			} else {
14574 				BUMP_MIB(&ipst->ips_ip_mib,
14575 				    ipIfStatsInDiscards);
14576 			}
14577 			return (B_TRUE);
14578 		}
14579 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14580 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14581 			/* Copy b_prev - used by ip_mroute_decap */
14582 			to_mp->b_prev = from_mp->b_prev;
14583 			from_mp->b_prev = NULL;
14584 		}
14585 		*first_mpp = first_mp = mp1;
14586 		freemsg(mp);
14587 		mp = mp1;
14588 		*mpp = mp1;
14589 	}
14590 
14591 	ipha = (ipha_t *)mp->b_rptr;
14592 
14593 	/*
14594 	 * previous code has a case for M_DATA.
14595 	 * We want to check how that happens.
14596 	 */
14597 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14598 	switch (first_mp->b_datap->db_type) {
14599 	case M_PROTO:
14600 	case M_PCPROTO:
14601 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14602 		    DL_UNITDATA_IND) {
14603 			/* Go handle anything other than data elsewhere. */
14604 			ip_rput_dlpi(q, mp);
14605 			return (B_TRUE);
14606 		}
14607 
14608 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14609 		/* Ditch the DLPI header. */
14610 		mp1 = mp->b_cont;
14611 		ASSERT(first_mp == mp);
14612 		*first_mpp = mp1;
14613 		freeb(mp);
14614 		*mpp = mp1;
14615 		return (B_FALSE);
14616 	case M_IOCACK:
14617 		ip1dbg(("got iocack "));
14618 		iocp = (struct iocblk *)mp->b_rptr;
14619 		switch (iocp->ioc_cmd) {
14620 		case DL_IOC_HDR_INFO:
14621 			ill = (ill_t *)q->q_ptr;
14622 			ill_fastpath_ack(ill, mp);
14623 			return (B_TRUE);
14624 		case SIOCSTUNPARAM:
14625 		case OSIOCSTUNPARAM:
14626 			/* Go through qwriter_ip */
14627 			break;
14628 		case SIOCGTUNPARAM:
14629 		case OSIOCGTUNPARAM:
14630 			ip_rput_other(NULL, q, mp, NULL);
14631 			return (B_TRUE);
14632 		default:
14633 			putnext(q, mp);
14634 			return (B_TRUE);
14635 		}
14636 		/* FALLTHRU */
14637 	case M_ERROR:
14638 	case M_HANGUP:
14639 		/*
14640 		 * Since this is on the ill stream we unconditionally
14641 		 * bump up the refcount
14642 		 */
14643 		ill_refhold(ill);
14644 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14645 		return (B_TRUE);
14646 	case M_CTL:
14647 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14648 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14649 		    IPHADA_M_CTL)) {
14650 			/*
14651 			 * It's an IPsec accelerated packet.
14652 			 * Make sure that the ill from which we received the
14653 			 * packet has enabled IPsec hardware acceleration.
14654 			 */
14655 			if (!(ill->ill_capabilities &
14656 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14657 				/* IPsec kstats: bean counter */
14658 				freemsg(mp);
14659 				return (B_TRUE);
14660 			}
14661 
14662 			/*
14663 			 * Make mp point to the mblk following the M_CTL,
14664 			 * then process according to type of mp.
14665 			 * After this processing, first_mp will point to
14666 			 * the data-attributes and mp to the pkt following
14667 			 * the M_CTL.
14668 			 */
14669 			mp = first_mp->b_cont;
14670 			if (mp == NULL) {
14671 				freemsg(first_mp);
14672 				return (B_TRUE);
14673 			}
14674 			/*
14675 			 * A Hardware Accelerated packet can only be M_DATA
14676 			 * ESP or AH packet.
14677 			 */
14678 			if (mp->b_datap->db_type != M_DATA) {
14679 				/* non-M_DATA IPsec accelerated packet */
14680 				IPSECHW_DEBUG(IPSECHW_PKT,
14681 				    ("non-M_DATA IPsec accelerated pkt\n"));
14682 				freemsg(first_mp);
14683 				return (B_TRUE);
14684 			}
14685 			ipha = (ipha_t *)mp->b_rptr;
14686 			if (ipha->ipha_protocol != IPPROTO_AH &&
14687 			    ipha->ipha_protocol != IPPROTO_ESP) {
14688 				IPSECHW_DEBUG(IPSECHW_PKT,
14689 				    ("non-M_DATA IPsec accelerated pkt\n"));
14690 				freemsg(first_mp);
14691 				return (B_TRUE);
14692 			}
14693 			*mpp = mp;
14694 			return (B_FALSE);
14695 		}
14696 		putnext(q, mp);
14697 		return (B_TRUE);
14698 	case M_IOCNAK:
14699 		ip1dbg(("got iocnak "));
14700 		iocp = (struct iocblk *)mp->b_rptr;
14701 		switch (iocp->ioc_cmd) {
14702 		case SIOCSTUNPARAM:
14703 		case OSIOCSTUNPARAM:
14704 			/*
14705 			 * Since this is on the ill stream we unconditionally
14706 			 * bump up the refcount
14707 			 */
14708 			ill_refhold(ill);
14709 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14710 			return (B_TRUE);
14711 		case DL_IOC_HDR_INFO:
14712 		case SIOCGTUNPARAM:
14713 		case OSIOCGTUNPARAM:
14714 			ip_rput_other(NULL, q, mp, NULL);
14715 			return (B_TRUE);
14716 		default:
14717 			break;
14718 		}
14719 		/* FALLTHRU */
14720 	default:
14721 		putnext(q, mp);
14722 		return (B_TRUE);
14723 	}
14724 }
14725 
14726 /* Read side put procedure.  Packets coming from the wire arrive here. */
14727 void
14728 ip_rput(queue_t *q, mblk_t *mp)
14729 {
14730 	ill_t	*ill;
14731 	union DL_primitives *dl;
14732 
14733 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14734 
14735 	ill = (ill_t *)q->q_ptr;
14736 
14737 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14738 		/*
14739 		 * If things are opening or closing, only accept high-priority
14740 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14741 		 * created; on close, things hanging off the ill may have been
14742 		 * freed already.)
14743 		 */
14744 		dl = (union DL_primitives *)mp->b_rptr;
14745 		if (DB_TYPE(mp) != M_PCPROTO ||
14746 		    dl->dl_primitive == DL_UNITDATA_IND) {
14747 			/*
14748 			 * SIOC[GS]TUNPARAM ioctls can come here.
14749 			 */
14750 			inet_freemsg(mp);
14751 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14752 			    "ip_rput_end: q %p (%S)", q, "uninit");
14753 			return;
14754 		}
14755 	}
14756 
14757 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14758 	    "ip_rput_end: q %p (%S)", q, "end");
14759 
14760 	ip_input(ill, NULL, mp, NULL);
14761 }
14762 
14763 static mblk_t *
14764 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14765 {
14766 	mblk_t *mp1;
14767 	boolean_t adjusted = B_FALSE;
14768 	ip_stack_t *ipst = ill->ill_ipst;
14769 
14770 	IP_STAT(ipst, ip_db_ref);
14771 	/*
14772 	 * The IP_RECVSLLA option depends on having the
14773 	 * link layer header. First check that:
14774 	 * a> the underlying device is of type ether,
14775 	 * since this option is currently supported only
14776 	 * over ethernet.
14777 	 * b> there is enough room to copy over the link
14778 	 * layer header.
14779 	 *
14780 	 * Once the checks are done, adjust rptr so that
14781 	 * the link layer header will be copied via
14782 	 * copymsg. Note that, IFT_ETHER may be returned
14783 	 * by some non-ethernet drivers but in this case
14784 	 * the second check will fail.
14785 	 */
14786 	if (ill->ill_type == IFT_ETHER &&
14787 	    (mp->b_rptr - mp->b_datap->db_base) >=
14788 	    sizeof (struct ether_header)) {
14789 		mp->b_rptr -= sizeof (struct ether_header);
14790 		adjusted = B_TRUE;
14791 	}
14792 	mp1 = copymsg(mp);
14793 
14794 	if (mp1 == NULL) {
14795 		mp->b_next = NULL;
14796 		/* clear b_prev - used by ip_mroute_decap */
14797 		mp->b_prev = NULL;
14798 		freemsg(mp);
14799 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14800 		return (NULL);
14801 	}
14802 
14803 	if (adjusted) {
14804 		/*
14805 		 * Copy is done. Restore the pointer in
14806 		 * the _new_ mblk
14807 		 */
14808 		mp1->b_rptr += sizeof (struct ether_header);
14809 	}
14810 
14811 	/* Copy b_prev - used by ip_mroute_decap */
14812 	mp1->b_prev = mp->b_prev;
14813 	mp->b_prev = NULL;
14814 
14815 	/* preserve the hardware checksum flags and data, if present */
14816 	if (DB_CKSUMFLAGS(mp) != 0) {
14817 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14818 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14819 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14820 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14821 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14822 	}
14823 
14824 	freemsg(mp);
14825 	return (mp1);
14826 }
14827 
14828 /*
14829  * Direct read side procedure capable of dealing with chains. GLDv3 based
14830  * drivers call this function directly with mblk chains while STREAMS
14831  * read side procedure ip_rput() calls this for single packet with ip_ring
14832  * set to NULL to process one packet at a time.
14833  *
14834  * The ill will always be valid if this function is called directly from
14835  * the driver.
14836  *
14837  * If ip_input() is called from GLDv3:
14838  *
14839  *   - This must be a non-VLAN IP stream.
14840  *   - 'mp' is either an untagged or a special priority-tagged packet.
14841  *   - Any VLAN tag that was in the MAC header has been stripped.
14842  *
14843  * If the IP header in packet is not 32-bit aligned, every message in the
14844  * chain will be aligned before further operations. This is required on SPARC
14845  * platform.
14846  */
14847 /* ARGSUSED */
14848 void
14849 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14850     struct mac_header_info_s *mhip)
14851 {
14852 	ipaddr_t		dst = NULL;
14853 	ipaddr_t		prev_dst;
14854 	ire_t			*ire = NULL;
14855 	ipha_t			*ipha;
14856 	uint_t			pkt_len;
14857 	ssize_t			len;
14858 	uint_t			opt_len;
14859 	int			ll_multicast;
14860 	int			cgtp_flt_pkt;
14861 	queue_t			*q = ill->ill_rq;
14862 	squeue_t		*curr_sqp = NULL;
14863 	mblk_t 			*head = NULL;
14864 	mblk_t			*tail = NULL;
14865 	mblk_t			*first_mp;
14866 	mblk_t 			*mp;
14867 	mblk_t			*dmp;
14868 	int			cnt = 0;
14869 	ip_stack_t		*ipst = ill->ill_ipst;
14870 
14871 	ASSERT(mp_chain != NULL);
14872 	ASSERT(ill != NULL);
14873 
14874 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14875 
14876 #define	rptr	((uchar_t *)ipha)
14877 
14878 	while (mp_chain != NULL) {
14879 		first_mp = mp = mp_chain;
14880 		mp_chain = mp_chain->b_next;
14881 		mp->b_next = NULL;
14882 		ll_multicast = 0;
14883 
14884 		/*
14885 		 * We do ire caching from one iteration to
14886 		 * another. In the event the packet chain contains
14887 		 * all packets from the same dst, this caching saves
14888 		 * an ire_cache_lookup for each of the succeeding
14889 		 * packets in a packet chain.
14890 		 */
14891 		prev_dst = dst;
14892 
14893 		/*
14894 		 * if db_ref > 1 then copymsg and free original. Packet
14895 		 * may be changed and we do not want the other entity
14896 		 * who has a reference to this message to trip over the
14897 		 * changes. This is a blind change because trying to
14898 		 * catch all places that might change the packet is too
14899 		 * difficult.
14900 		 *
14901 		 * This corresponds to the fast path case, where we have
14902 		 * a chain of M_DATA mblks.  We check the db_ref count
14903 		 * of only the 1st data block in the mblk chain. There
14904 		 * doesn't seem to be a reason why a device driver would
14905 		 * send up data with varying db_ref counts in the mblk
14906 		 * chain. In any case the Fast path is a private
14907 		 * interface, and our drivers don't do such a thing.
14908 		 * Given the above assumption, there is no need to walk
14909 		 * down the entire mblk chain (which could have a
14910 		 * potential performance problem)
14911 		 */
14912 
14913 		if (DB_REF(mp) > 1) {
14914 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14915 				continue;
14916 		}
14917 
14918 		/*
14919 		 * Check and align the IP header.
14920 		 */
14921 		first_mp = mp;
14922 		if (DB_TYPE(mp) == M_DATA) {
14923 			dmp = mp;
14924 		} else if (DB_TYPE(mp) == M_PROTO &&
14925 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14926 			dmp = mp->b_cont;
14927 		} else {
14928 			dmp = NULL;
14929 		}
14930 		if (dmp != NULL) {
14931 			/*
14932 			 * IP header ptr not aligned?
14933 			 * OR IP header not complete in first mblk
14934 			 */
14935 			if (!OK_32PTR(dmp->b_rptr) ||
14936 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14937 				if (!ip_check_and_align_header(q, dmp, ipst))
14938 					continue;
14939 			}
14940 		}
14941 
14942 		/*
14943 		 * ip_input fast path
14944 		 */
14945 
14946 		/* mblk type is not M_DATA */
14947 		if (DB_TYPE(mp) != M_DATA) {
14948 			if (ip_rput_process_notdata(q, &first_mp, ill,
14949 			    &ll_multicast, &mp))
14950 				continue;
14951 
14952 			/*
14953 			 * The only way we can get here is if we had a
14954 			 * packet that was either a DL_UNITDATA_IND or
14955 			 * an M_CTL for an IPsec accelerated packet.
14956 			 *
14957 			 * In either case, the first_mp will point to
14958 			 * the leading M_PROTO or M_CTL.
14959 			 */
14960 			ASSERT(first_mp != NULL);
14961 		} else if (mhip != NULL) {
14962 			/*
14963 			 * ll_multicast is set here so that it is ready
14964 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14965 			 * manipulates ll_multicast in the same fashion when
14966 			 * called from ip_rput_process_notdata.
14967 			 */
14968 			switch (mhip->mhi_dsttype) {
14969 			case MAC_ADDRTYPE_MULTICAST :
14970 				ll_multicast = HPE_MULTICAST;
14971 				break;
14972 			case MAC_ADDRTYPE_BROADCAST :
14973 				ll_multicast = HPE_BROADCAST;
14974 				break;
14975 			default :
14976 				break;
14977 			}
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, ll_multicast, 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, dl_primstr(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, dl_primstr(prim),
15382 	    dl_errstr(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 		    dl_primstr(dlea->dl_error_primitive),
15404 		    dlea->dl_error_primitive,
15405 		    dl_errstr(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 		    dl_primstr((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 		    dl_primstr(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 		    dl_primstr((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, 0, 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, 0, 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, 0, 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, 0, 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, 0, 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, 0, 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, 0, 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, 0, 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, 0, 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, 0, 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, 0, 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, NULL,
26274 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, 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